mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-20 23:52:40 +08:00
Merge branch 'master' of github.com:cocos-creator/engine into issue3120
# Conflicts: # cocos2d/tilemap/CCSGTMXObjectGroup.js
This commit is contained in:
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"extends": "eslint:recommended",
|
||||
"rules": {
|
||||
"comma-dangle": 0,
|
||||
"no-console": 0,
|
||||
"no-constant-condition": 0,
|
||||
"semi": 1
|
||||
},
|
||||
"env": {
|
||||
"browser": true,
|
||||
"node": true,
|
||||
"es6": true,
|
||||
"mocha": true
|
||||
},
|
||||
"plugins": [
|
||||
],
|
||||
"globals": {
|
||||
"cc": false,
|
||||
"CC_EDITOR": false,
|
||||
"CC_DEV": false,
|
||||
"CC_JSB": false,
|
||||
"_ccsg": false
|
||||
}
|
||||
}
|
||||
@@ -58,7 +58,7 @@ _p = null;
|
||||
* @name cc.ENGINE_VERSION
|
||||
*/
|
||||
var engineVersion;
|
||||
engineVersion = '1.2.0-beta.1';
|
||||
engineVersion = '1.3.0-beta.2';
|
||||
window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion;
|
||||
|
||||
/**
|
||||
@@ -87,8 +87,6 @@ cc._canvas = null;
|
||||
cc.container = null;
|
||||
cc._gameDiv = null;
|
||||
|
||||
cc.isEditor = typeof Editor !== 'undefined';
|
||||
|
||||
require('./cocos2d/core/utils');
|
||||
require('./cocos2d/core/platform/CCSys');
|
||||
|
||||
@@ -154,20 +152,18 @@ function _getJsListOfModule(moduleMap, moduleName, dir) {
|
||||
return jsList;
|
||||
}
|
||||
|
||||
function _afterEngineLoaded(config) {
|
||||
cc._initDebugSetting(config[cc.game.CONFIG_KEY.debugMode]);
|
||||
function _afterEngineLoaded() {
|
||||
cc._engineLoaded = true;
|
||||
cc.log(cc.ENGINE_VERSION);
|
||||
console.log(cc.ENGINE_VERSION);
|
||||
if (_engineLoadedCallback) _engineLoadedCallback();
|
||||
}
|
||||
|
||||
function _load(config) {
|
||||
var self = this;
|
||||
var CONFIG_KEY = cc.game.CONFIG_KEY, engineDir = config[CONFIG_KEY.engineDir], loader = cc.loader;
|
||||
|
||||
if (cc._Class) {
|
||||
// Single file loaded
|
||||
_afterEngineLoaded(config);
|
||||
_afterEngineLoaded();
|
||||
} else {
|
||||
// Load cocos modules
|
||||
var ccModulesPath = cc.path.join(engineDir, "moduleConfig.json");
|
||||
@@ -184,7 +180,7 @@ function _load(config) {
|
||||
}
|
||||
loader.load(jsList, function (err) {
|
||||
if (err) throw new Error(JSON.stringify(err));
|
||||
_afterEngineLoaded(config);
|
||||
_afterEngineLoaded();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
+14
-8
@@ -333,7 +333,7 @@ cc.DebugMode = Enum({
|
||||
/**
|
||||
* !#en The debug mode none.
|
||||
* !#zh 禁止模式,禁止显示任何日志信息。
|
||||
* @property NONE.
|
||||
* @property NONE
|
||||
* @type {Number}
|
||||
* @static
|
||||
*/
|
||||
@@ -451,8 +451,8 @@ cc._initDebugSetting = function (mode) {
|
||||
* - 在 Chrome 中,错误信息有红色的图标以及红色的消息文本。<br/>
|
||||
*
|
||||
* @method error
|
||||
* @param {Any} obj - A JavaScript string containing zero or more substitution strings.
|
||||
* @param {Any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output.
|
||||
* @param {any} obj - A JavaScript string containing zero or more substitution strings.
|
||||
* @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output.
|
||||
*/
|
||||
if (CC_EDITOR) {
|
||||
cc.error = Editor.error;
|
||||
@@ -484,8 +484,8 @@ cc._initDebugSetting = function (mode) {
|
||||
* - 在 Cocos Creator 中,警告信息显示是黄色的。<br/>
|
||||
* - 在 Chrome 中,警告信息有着黄色的图标以及黄色的消息文本。<br/>
|
||||
* @method warn
|
||||
* @param {Any} obj - A JavaScript string containing zero or more substitution strings.
|
||||
* @param {Any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output.
|
||||
* @param {any} obj - A JavaScript string containing zero or more substitution strings.
|
||||
* @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output.
|
||||
*/
|
||||
if (CC_EDITOR) {
|
||||
cc.warn = Editor.warn;
|
||||
@@ -509,8 +509,8 @@ cc._initDebugSetting = function (mode) {
|
||||
* !#en Outputs a message to the Cocos Creator Console (editor) or Web Console (runtime).
|
||||
* !#zh 输出一条消息到 Cocos Creator 编辑器的 Console 或运行时 Web 端的 Console 中。
|
||||
* @method log
|
||||
* @param {Any} obj - A JavaScript string containing zero or more substitution strings.
|
||||
* @param {Any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output.
|
||||
* @param {any} obj - A JavaScript string containing zero or more substitution strings.
|
||||
* @param {any} ...subst - JavaScript objects with which to replace substitution strings within msg. This gives you additional control over the format of the output.
|
||||
*/
|
||||
if (CC_JSB) {
|
||||
cc.log = jsbLog;
|
||||
@@ -543,7 +543,13 @@ cc._initDebugSetting = function (mode) {
|
||||
}
|
||||
}
|
||||
cc._throw = CC_EDITOR ? Editor.error : function (error) {
|
||||
cc.error(error.stack || error);
|
||||
var stack = error.stack;
|
||||
if (stack) {
|
||||
cc.error(CC_JSB ? (error + '\n' + stack) : stack);
|
||||
}
|
||||
else {
|
||||
cc.error(error);
|
||||
}
|
||||
};
|
||||
};
|
||||
//+++++++++++++++++++++++++something about log end+++++++++++++++++++++++++++++
|
||||
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
|
||||
2youyou2
|
||||
dabingnn
|
||||
jareguo
|
||||
knoxHuang
|
||||
nantas
|
||||
natural-law
|
||||
pandamicro
|
||||
VisualSJ
|
||||
zilongshanren
|
||||
@@ -69,36 +69,6 @@ cc.cardinalSplineAt = function (p0, p1, p2, p3, tension, t) {
|
||||
return cc.p(x, y);
|
||||
};
|
||||
|
||||
/*
|
||||
* returns a new copy of the array reversed.
|
||||
* @method reverseControlPoints
|
||||
* @param {Array} controlPoints
|
||||
* @return {Array}
|
||||
*/
|
||||
cc.reverseControlPoints = function (controlPoints) {
|
||||
var newArray = [];
|
||||
for (var i = controlPoints.length - 1; i >= 0; i--) {
|
||||
newArray.push(cc.p(controlPoints[i].x, controlPoints[i].y));
|
||||
}
|
||||
return newArray;
|
||||
};
|
||||
|
||||
|
||||
/*
|
||||
* returns a new clone of the controlPoints
|
||||
* @method cloneControlPoints
|
||||
* @param {Array} controlPoints
|
||||
* @returns {Array}
|
||||
*/
|
||||
cc.cloneControlPoints = function (controlPoints) {
|
||||
var newArray = [];
|
||||
for (var i = 0; i < controlPoints.length; i++)
|
||||
newArray.push(cc.p(controlPoints[i].x, controlPoints[i].y));
|
||||
return newArray;
|
||||
};
|
||||
|
||||
cc.copyControlPoints = cc.cloneControlPoints;
|
||||
|
||||
/*
|
||||
* returns a point from the array
|
||||
* @method getControlPointAt
|
||||
@@ -111,20 +81,20 @@ cc.getControlPointAt = function (controlPoints, pos) {
|
||||
return controlPoints[p];
|
||||
};
|
||||
|
||||
/*
|
||||
* reverse the current control point array inline, without generating a new one <br />
|
||||
* @method reverseControlPointsInline
|
||||
* @param {Array} controlPoints
|
||||
*/
|
||||
cc.reverseControlPointsInline = function (controlPoints) {
|
||||
var len = controlPoints.length;
|
||||
var mid = 0 | (len / 2);
|
||||
for (var i = 0; i < mid; ++i) {
|
||||
var temp = controlPoints[i];
|
||||
controlPoints[i] = controlPoints[len - i - 1];
|
||||
controlPoints[len - i - 1] = temp;
|
||||
function reverseControlPoints (controlPoints) {
|
||||
var newArray = [];
|
||||
for (var i = controlPoints.length - 1; i >= 0; i--) {
|
||||
newArray.push(cc.p(controlPoints[i].x, controlPoints[i].y));
|
||||
}
|
||||
};
|
||||
return newArray;
|
||||
}
|
||||
|
||||
function cloneControlPoints (controlPoints) {
|
||||
var newArray = [];
|
||||
for (var i = 0; i < controlPoints.length; i++)
|
||||
newArray.push(cc.p(controlPoints[i].x, controlPoints[i].y));
|
||||
return newArray;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
@@ -157,15 +127,6 @@ cc.CardinalSplineTo = cc.ActionInterval.extend({
|
||||
tension !== undefined && this.initWithDuration(duration, points, tension);
|
||||
},
|
||||
|
||||
/*
|
||||
* initializes the action with a duration and an array of points
|
||||
* @method initWithDuration
|
||||
* @param {Number} duration
|
||||
* @param {Array} points array of control points
|
||||
* @param {Number} tension
|
||||
*
|
||||
* @return {Boolean}
|
||||
*/
|
||||
initWithDuration:function (duration, points, tension) {
|
||||
if(!points || points.length === 0)
|
||||
throw new Error("Invalid configuration. It must at least have one control point");
|
||||
@@ -180,7 +141,7 @@ cc.CardinalSplineTo = cc.ActionInterval.extend({
|
||||
|
||||
clone:function () {
|
||||
var action = new cc.CardinalSplineTo();
|
||||
action.initWithDuration(this._duration, cc.copyControlPoints(this._points), this._tension);
|
||||
action.initWithDuration(this._duration, cloneControlPoints(this._points), this._tension);
|
||||
return action;
|
||||
},
|
||||
|
||||
@@ -234,7 +195,7 @@ cc.CardinalSplineTo = cc.ActionInterval.extend({
|
||||
},
|
||||
|
||||
reverse:function () {
|
||||
var reversePoints = cc.reverseControlPoints(this._points);
|
||||
var reversePoints = reverseControlPoints(this._points);
|
||||
return cc.cardinalSplineTo(this._duration, reversePoints, this._tension);
|
||||
},
|
||||
|
||||
@@ -257,7 +218,7 @@ cc.CardinalSplineTo = cc.ActionInterval.extend({
|
||||
return this._points;
|
||||
},
|
||||
|
||||
/*
|
||||
/**
|
||||
* Points setter
|
||||
* @method setPoints
|
||||
* @param {Array} points
|
||||
@@ -329,7 +290,7 @@ cc.CardinalSplineBy = cc.CardinalSplineTo.extend({
|
||||
}
|
||||
|
||||
// convert to "diffs" to "reverse absolute"
|
||||
var reverseArray = cc.reverseControlPoints(copyConfig);
|
||||
var reverseArray = reverseControlPoints(copyConfig);
|
||||
|
||||
// 1st element (which should be 0,0) should be here too
|
||||
p = reverseArray[ reverseArray.length - 1 ];
|
||||
@@ -351,7 +312,7 @@ cc.CardinalSplineBy = cc.CardinalSplineTo.extend({
|
||||
return cc.cardinalSplineBy(this._duration, reverseArray, this._tension);
|
||||
},
|
||||
|
||||
/*
|
||||
/**
|
||||
* update position of target
|
||||
* @method updatePosition
|
||||
* @param {Vec2} newPos
|
||||
@@ -365,14 +326,9 @@ cc.CardinalSplineBy = cc.CardinalSplineTo.extend({
|
||||
this.target.setPosition(posX, posY);
|
||||
},
|
||||
|
||||
/*
|
||||
* returns a new clone of the action
|
||||
* @method clone
|
||||
* @returns {CardinalSplineBy}
|
||||
*/
|
||||
clone:function () {
|
||||
var a = new cc.CardinalSplineBy();
|
||||
a.initWithDuration(this._duration, cc.copyControlPoints(this._points), this._tension);
|
||||
a.initWithDuration(this._duration, cloneControlPoints(this._points), this._tension);
|
||||
return a;
|
||||
}
|
||||
});
|
||||
@@ -412,19 +368,13 @@ cc.CatmullRomTo = cc.CardinalSplineTo.extend({
|
||||
points && this.initWithDuration(dt, points);
|
||||
},
|
||||
|
||||
/*
|
||||
* Initializes the action with a duration and an array of points
|
||||
* @method initWithDuration
|
||||
* @param {Number} dt
|
||||
* @param {Array} points
|
||||
*/
|
||||
initWithDuration:function (dt, points) {
|
||||
return cc.CardinalSplineTo.prototype.initWithDuration.call(this, dt, points, 0.5);
|
||||
},
|
||||
|
||||
clone:function () {
|
||||
var action = new cc.CatmullRomTo();
|
||||
action.initWithDuration(this._duration, cc.copyControlPoints(this._points));
|
||||
action.initWithDuration(this._duration, cloneControlPoints(this._points));
|
||||
return action;
|
||||
}
|
||||
});
|
||||
@@ -466,20 +416,13 @@ cc.CatmullRomBy = cc.CardinalSplineBy.extend({
|
||||
points && this.initWithDuration(dt, points);
|
||||
},
|
||||
|
||||
/*
|
||||
* initializes the action with a duration and an array of points
|
||||
*
|
||||
* @method initWithDuration
|
||||
* @param {Number} dt
|
||||
* @param {Array} points
|
||||
*/
|
||||
initWithDuration:function (dt, points) {
|
||||
return cc.CardinalSplineTo.prototype.initWithDuration.call(this, dt, points, 0.5);
|
||||
},
|
||||
|
||||
clone:function () {
|
||||
var action = new cc.CatmullRomBy();
|
||||
action.initWithDuration(this._duration, cc.copyControlPoints(this._points));
|
||||
action.initWithDuration(this._duration, cloneControlPoints(this._points));
|
||||
return action;
|
||||
}
|
||||
});
|
||||
|
||||
@@ -75,7 +75,11 @@ cc.ActionInstant = cc.FiniteTimeAction.extend({
|
||||
cc.Show = cc.ActionInstant.extend({
|
||||
|
||||
update:function (dt) {
|
||||
this.target.visible = true;
|
||||
var _renderComps = this.target.getComponentsInChildren(cc._SGComponent);
|
||||
for (var i = 0; i < _renderComps.length; ++i) {
|
||||
var render = _renderComps[i];
|
||||
render.enabled = true;
|
||||
}
|
||||
},
|
||||
|
||||
reverse:function () {
|
||||
@@ -108,7 +112,11 @@ cc.show = function () {
|
||||
cc.Hide = cc.ActionInstant.extend({
|
||||
|
||||
update:function (dt) {
|
||||
this.target.visible = false;
|
||||
var _renderComps = this.target.getComponentsInChildren(cc._SGComponent);
|
||||
for (var i = 0; i < _renderComps.length; ++i) {
|
||||
var render = _renderComps[i];
|
||||
render.enabled = false;
|
||||
}
|
||||
},
|
||||
|
||||
reverse:function () {
|
||||
@@ -141,7 +149,11 @@ cc.hide = function () {
|
||||
cc.ToggleVisibility = cc.ActionInstant.extend({
|
||||
|
||||
update:function (dt) {
|
||||
this.target.visible = !this.target.visible;
|
||||
var _renderComps = this.target.getComponentsInChildren(cc._SGComponent);
|
||||
for (var i = 0; i < _renderComps.length; ++i) {
|
||||
var render = _renderComps[i];
|
||||
render.enabled = !render.enabled;
|
||||
}
|
||||
},
|
||||
|
||||
reverse:function () {
|
||||
|
||||
@@ -705,8 +705,8 @@ cc.RepeatForever = cc.ActionInterval.extend({
|
||||
});
|
||||
|
||||
/**
|
||||
* !#en Create a acton which repeat forever
|
||||
* !#zh 永远地重复一个动作,有限次数内重复一个动作请使用 repeat 动作。
|
||||
* !#en Create a acton which repeat forever, as it runs forever, it can't be added into cc.sequence and cc.spawn.
|
||||
* !#zh 永远地重复一个动作,有限次数内重复一个动作请使用 repeat 动作,由于这个动作不会停止,所以不能被添加到 cc.sequence 或 cc.spawn 中。
|
||||
* @method repeatForever
|
||||
* @param {FiniteTimeAction} action
|
||||
* @return {ActionInterval}
|
||||
|
||||
@@ -1,166 +0,0 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2008-2010 Ricardo Quesada
|
||||
Copyright (c) 2011-2012 cocos2d-x.org
|
||||
Copyright (c) 2013-2014 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
/**
|
||||
*
|
||||
* @class ActionTweenDelegate
|
||||
* @extends _Class
|
||||
*/
|
||||
cc.ActionTweenDelegate = cc._Class.extend(/** @lends cc.ActionTweenDelegate */{
|
||||
|
||||
/**
|
||||
* Update Tween Action.
|
||||
* @param value
|
||||
* @param key
|
||||
*/
|
||||
updateTweenAction:function(value, key){}
|
||||
});
|
||||
|
||||
/**
|
||||
* cc.ActionTween
|
||||
* cc.ActionTween is an action that lets you update any property of an object.
|
||||
*
|
||||
* @class
|
||||
* @extends ActionInterval
|
||||
* @example
|
||||
* //For example, if you want to modify the "width" property of a target from 200 to 300 in 2 seconds, then:
|
||||
* var modifyWidth = cc.actionTween(2,"width",200,300)
|
||||
* target.runAction(modifyWidth);
|
||||
*
|
||||
* //Another example: cc.ScaleTo action could be rewriten using cc.PropertyAction:
|
||||
* // scaleA and scaleB are equivalents
|
||||
* var scaleA = cc.scaleTo(2,3);
|
||||
* var scaleB = cc.actionTween(2,"scale",1,3);
|
||||
* @param {Number} duration
|
||||
* @param {String} key
|
||||
* @param {Number} from
|
||||
* @param {Number} to
|
||||
*/
|
||||
cc.ActionTween = cc.ActionInterval.extend(/** @lends cc.ActionTween */{
|
||||
key:"",
|
||||
from:0,
|
||||
to:0,
|
||||
delta:0,
|
||||
|
||||
/**
|
||||
* Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function. <br />
|
||||
* Creates an initializes the action with the property name (key), and the from and to parameters.
|
||||
* @param {Number} duration
|
||||
* @param {String} key
|
||||
* @param {Number} from
|
||||
* @param {Number} to
|
||||
*/
|
||||
ctor:function(duration, key, from, to){
|
||||
cc.ActionInterval.prototype.ctor.call(this);
|
||||
this.key = "";
|
||||
|
||||
to !== undefined && this.initWithDuration(duration, key, from, to);
|
||||
},
|
||||
|
||||
/**
|
||||
* initializes the action with the property name (key), and the from and to parameters.
|
||||
* @param {Number} duration
|
||||
* @param {String} key
|
||||
* @param {Number} from
|
||||
* @param {Number} to
|
||||
* @return {Boolean}
|
||||
*/
|
||||
initWithDuration:function (duration, key, from, to) {
|
||||
if (cc.ActionInterval.prototype.initWithDuration.call(this, duration)) {
|
||||
this.key = key;
|
||||
this.to = to;
|
||||
this.from = from;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
/**
|
||||
* Start this tween with target.
|
||||
* @param {ActionTweenDelegate} target
|
||||
*/
|
||||
startWithTarget:function (target) {
|
||||
if(!target || !target.updateTweenAction)
|
||||
throw new Error("cc.ActionTween.startWithTarget(): target must be non-null, and target must implement updateTweenAction function");
|
||||
cc.ActionInterval.prototype.startWithTarget.call(this, target);
|
||||
this.delta = this.to - this.from;
|
||||
},
|
||||
|
||||
/**
|
||||
* Called once per frame. Time is the number of seconds of a frame interval.
|
||||
*
|
||||
* @param {Number} dt
|
||||
*/
|
||||
update:function (dt) {
|
||||
this.target.updateTweenAction(this.to - this.delta * (1 - dt), this.key);
|
||||
},
|
||||
|
||||
/**
|
||||
* returns a reversed action.
|
||||
* @return {ActionTween}
|
||||
*/
|
||||
reverse:function () {
|
||||
return new cc.ActionTween(this.duration, this.key, this.to, this.from);
|
||||
},
|
||||
|
||||
/**
|
||||
* to copy object with deep copy.
|
||||
* returns a clone of action.
|
||||
*
|
||||
* @return {ActionTween}
|
||||
*/
|
||||
clone:function(){
|
||||
var action = new cc.ActionTween();
|
||||
action.initWithDuration(this._duration, this.key, this.from, this.to);
|
||||
return action;
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* Creates an initializes the action with the property name (key), and the from and to parameters.
|
||||
* @method
|
||||
* @param {Number} duration
|
||||
* @param {String} key
|
||||
* @param {Number} from
|
||||
* @param {Number} to
|
||||
* @return {ActionTween}
|
||||
*/
|
||||
cc.actionTween = function (duration, key, from, to) {
|
||||
return new cc.ActionTween(duration, key, from, to);
|
||||
};
|
||||
|
||||
/**
|
||||
* Please use cc.actionTween instead.
|
||||
* Creates an initializes the action with the property name (key), and the from and to parameters.
|
||||
* @static
|
||||
* @deprecated since v3.0 <br /> Please use cc.actionTween instead.
|
||||
* @param {Number} duration
|
||||
* @param {String} key
|
||||
* @param {Number} from
|
||||
* @param {Number} to
|
||||
* @return {ActionTween}
|
||||
*/
|
||||
cc.ActionTween.create = cc.actionTween;
|
||||
@@ -1,4 +1,5 @@
|
||||
require('./CCAction.js');
|
||||
require('./CCActionInterval.js');
|
||||
require('./CCActionInstant.js');
|
||||
require('./CCActionEase.js');
|
||||
require('./CCActionEase.js');
|
||||
require('./CCActionCatmullRom.js');
|
||||
@@ -37,8 +37,25 @@ p.playState = function (state, startTime) {
|
||||
this.play();
|
||||
};
|
||||
|
||||
p.addAnimation = function (anim) {
|
||||
Animator.prototype.addAnimation.call(this, anim);
|
||||
|
||||
var listeners = this.animation._listeners;
|
||||
for (var i = 0, l = listeners.length; i < l; i++) {
|
||||
var listener = listeners[i];
|
||||
anim.on(listener[0], listener[1], listener[2], listener[3]);
|
||||
}
|
||||
};
|
||||
|
||||
p.removeAnimation = function (anim) {
|
||||
var listeners = this.animation._listeners;
|
||||
for (var i = 0, l = listeners.length; i < l; i++) {
|
||||
var listener = listeners[i];
|
||||
anim.off(listener[0], listener[1], listener[2], listener[3]);
|
||||
}
|
||||
|
||||
Animator.prototype.removeAnimation.call(this, anim);
|
||||
|
||||
anim.animator = null;
|
||||
};
|
||||
|
||||
|
||||
@@ -86,7 +86,7 @@ var AnimationClip = cc.Class({
|
||||
* !#en Crate clip with a set of sprite frames
|
||||
* !#zh 使用一组序列帧图片来创建动画剪辑
|
||||
* @method createWithSpriteFrames
|
||||
* @param {[cc.SpriteFrame]} spriteFrames
|
||||
* @param {[SpriteFrame]} spriteFrames
|
||||
* @param {Number} sample
|
||||
* @return {AnimationClip}
|
||||
* @example
|
||||
|
||||
@@ -68,9 +68,13 @@ JS.getset(state, 'curveLoaded',
|
||||
state.onPlay = function () {
|
||||
// replay
|
||||
this.setTime(0);
|
||||
|
||||
AnimationNode.prototype.onPlay.call(this);
|
||||
};
|
||||
|
||||
state.onStop = function () {
|
||||
AnimationNode.prototype.onStop.call(this);
|
||||
|
||||
if (this.animator) {
|
||||
this.animator.removeAnimation(this);
|
||||
}
|
||||
|
||||
@@ -79,7 +79,6 @@ cc.WrapMode = WrapMode;
|
||||
* @class AnimationNodeBase
|
||||
* @constructor
|
||||
* @extends Playable
|
||||
* @private
|
||||
*/
|
||||
var AnimationNodeBase = function () {
|
||||
Playable.call(this);
|
||||
@@ -94,7 +93,7 @@ JS.extend(AnimationNodeBase, Playable);
|
||||
AnimationNodeBase.prototype.update = function (deltaTime) {};
|
||||
|
||||
|
||||
/*
|
||||
/**
|
||||
* !#en The collection and instance of playing animations.
|
||||
* !#zh 动画曲线的集合,根据当前时间计算出每条曲线的状态。
|
||||
* @class AnimationNode
|
||||
@@ -167,8 +166,12 @@ function AnimationNode (animator, curves, timingInput) {
|
||||
this.speed = 1;
|
||||
|
||||
/**
|
||||
* !#en Wrapping mode of the playing animation.
|
||||
* !#zh 动画循环方式。
|
||||
* !#en
|
||||
* Wrapping mode of the playing animation.
|
||||
* Notice : dynamic change wrapMode will reset time and repeatCount property
|
||||
* !#zh
|
||||
* 动画循环方式。
|
||||
* 需要注意的是,动态修改 wrapMode 时,会重置 time 以及 repeatCount
|
||||
*
|
||||
* @property wrapMode
|
||||
* @type {WrapMode}
|
||||
@@ -262,10 +265,32 @@ JS.mixin(AnimationNode.prototype, {
|
||||
}
|
||||
|
||||
// sample
|
||||
var info = this.sample();
|
||||
|
||||
if (this.sample()) {
|
||||
if (!this._lastWrappedInfo) {
|
||||
this._lastWrappedInfo = info;
|
||||
}
|
||||
|
||||
var anotherIteration = (info.iterations | 0) > (this._lastWrappedInfo.iterations | 0);
|
||||
if (this.repeatCount > 1 && anotherIteration) {
|
||||
if ((this.wrapMode & WrapModeMask.Reverse) === WrapModeMask.Reverse) {
|
||||
if (this._lastWrappedInfo.direction < 0) {
|
||||
this.emit('lastframe', this);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (this._lastWrappedInfo.direction > 0) {
|
||||
this.emit('lastframe', this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (info.stopped) {
|
||||
this.emit('finished', this);
|
||||
this.stop();
|
||||
}
|
||||
|
||||
this._lastWrappedInfo = info;
|
||||
},
|
||||
|
||||
_needRevers: function (currentIterations) {
|
||||
@@ -337,7 +362,7 @@ JS.mixin(AnimationNode.prototype, {
|
||||
direction: direction,
|
||||
stopped: stopped,
|
||||
iterations: currentIterations
|
||||
}
|
||||
};
|
||||
},
|
||||
|
||||
sample: function () {
|
||||
@@ -352,10 +377,49 @@ JS.mixin(AnimationNode.prototype, {
|
||||
curve.sample(info.time, info.ratio, this);
|
||||
}
|
||||
|
||||
return info.stopped;
|
||||
return info;
|
||||
},
|
||||
|
||||
onStop: function () {
|
||||
this.emit('stop', this);
|
||||
},
|
||||
|
||||
onPlay: function () {
|
||||
this.emit('play', this);
|
||||
},
|
||||
|
||||
onPause: function () {
|
||||
this.emit('pause', this);
|
||||
},
|
||||
|
||||
onResume: function () {
|
||||
this.emit('resume', this);
|
||||
}
|
||||
});
|
||||
|
||||
cc.defineGetterSetter(AnimationNode.prototype, 'wrapMode',
|
||||
function () {
|
||||
return this._wrapMode;
|
||||
},
|
||||
function (value) {
|
||||
this._wrapMode = value;
|
||||
|
||||
if (CC_EDITOR) return;
|
||||
|
||||
// dynamic change wrapMode will need reset time to 0
|
||||
this.time = 0;
|
||||
|
||||
if (value & WrapModeMask.Loop) {
|
||||
this.repeatCount = Infinity;
|
||||
}
|
||||
else {
|
||||
this.repeatCount = 1;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
cc.js.mixin(AnimationNode.prototype, cc.EventTarget.prototype);
|
||||
|
||||
cc.AnimationNode = AnimationNode;
|
||||
|
||||
module.exports = {
|
||||
|
||||
+296
-651
@@ -24,42 +24,208 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
var JS = require('../core/platform/js');
|
||||
|
||||
/**
|
||||
* Encapsulate DOM and webAudio
|
||||
*/
|
||||
cc.Audio = function (url) {
|
||||
this.src = url;
|
||||
this._element = null;
|
||||
this._AUDIO_TYPE = 'AUDIO';
|
||||
};
|
||||
|
||||
cc.Audio.touchPlayList = [
|
||||
var touchBinded = false;
|
||||
var touchPlayList = [
|
||||
//{ offset: 0, audio: audio }
|
||||
];
|
||||
|
||||
cc.Audio.bindTouch = false;
|
||||
cc.Audio.touchStart = function () {
|
||||
var list = cc.Audio.touchPlayList;
|
||||
var item = null;
|
||||
while (item = list.pop()) {
|
||||
item.audio.loop = !!item.loop;
|
||||
item.audio.play(item.offset);
|
||||
}
|
||||
var Audio = function (src) {
|
||||
this.src = src;
|
||||
this._audioType = Audio.Type.UNKNOWN;
|
||||
this._element = null;
|
||||
|
||||
this._eventList = {};
|
||||
this._state = Audio.State.ERROR;
|
||||
this._loaded = false;
|
||||
};
|
||||
|
||||
cc.Audio.WebAudio = function (buffer) {
|
||||
this.buffer = buffer;
|
||||
this.context = cc.sys.__audioSupport.context;
|
||||
Audio.Type = {
|
||||
DOM: 'AUDIO',
|
||||
WEBAUDIO: 'WEBAUDIO',
|
||||
NATIVE: 'NATIVE',
|
||||
UNKNOWN: 'UNKNOWN'
|
||||
};
|
||||
|
||||
var volume = this.context['createGain']();
|
||||
volume['gain'].value = 1;
|
||||
volume['connect'](this.context['destination']);
|
||||
this._volume = volume;
|
||||
Audio.State = {
|
||||
ERROR : -1,
|
||||
INITIALZING: 0,
|
||||
PLAYING: 1,
|
||||
PAUSED: 2
|
||||
};
|
||||
|
||||
(function (proto) {
|
||||
|
||||
proto.preload = function () {
|
||||
var src = this.src,
|
||||
audio = this;
|
||||
var item = cc.loader.getItem(src);
|
||||
|
||||
// If the resource does not exist
|
||||
if (!item) {
|
||||
return cc.loader.load(src, function (error) {
|
||||
if (!error) {
|
||||
var item = cc.loader.getItem(src);
|
||||
audio.mount(item.element || item.buffer);
|
||||
audio.emit('load');
|
||||
}
|
||||
});
|
||||
}
|
||||
audio.mount(item.element || item.buffer);
|
||||
audio.emit('load');
|
||||
};
|
||||
|
||||
proto.on = function (event, callback) {
|
||||
var list = this._eventList[event];
|
||||
if (!list) {
|
||||
list = this._eventList[event] = [];
|
||||
}
|
||||
list.push(callback);
|
||||
};
|
||||
proto.once = function (event, callback) {
|
||||
var onceCallback = function (elem) {
|
||||
callback.call(this, elem);
|
||||
this.off(event, onceCallback);
|
||||
};
|
||||
this.on(event, onceCallback);
|
||||
};
|
||||
proto.emit = function (event) {
|
||||
var list = this._eventList[event];
|
||||
if (!list) return;
|
||||
for (var i=0; i<list.length; i++) {
|
||||
list[i].call(this, this);
|
||||
}
|
||||
};
|
||||
proto.off = function (event, callback) {
|
||||
var list = this._eventList[event];
|
||||
if (!list) return false;
|
||||
if (!callback) {
|
||||
this._eventList[event] = [];
|
||||
return true;
|
||||
}
|
||||
|
||||
for (var i=0; i<list.length; i++) {
|
||||
if (list[i] === callback) {
|
||||
list.splice(i, 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
proto.mount = function (elem) {
|
||||
if (elem instanceof HTMLElement) {
|
||||
this._element = document.createElement('audio');
|
||||
this._element.src = elem.src;
|
||||
this._audioType = Audio.Type.DOM;
|
||||
elem.addEventListener('ended', function () {
|
||||
this.emit('ended', this);
|
||||
}, this);
|
||||
} else {
|
||||
this._element = new WebAudioElement(elem);
|
||||
this._audioType = Audio.Type.WEBAUDIO;
|
||||
elem.onended = function () {
|
||||
this.emit('ended', this);
|
||||
};
|
||||
}
|
||||
this._state = Audio.State.INITIALZING;
|
||||
this._loaded = true;
|
||||
};
|
||||
|
||||
proto.play = function () {
|
||||
if (!this._element) return;
|
||||
this._element.play();
|
||||
this.emit('play');
|
||||
this._state = Audio.State.PLAYING;
|
||||
|
||||
if (this._audioType = Audio.Type.DOM && this._element.paused) {
|
||||
this.stop();
|
||||
touchPlayList.push({ offset: 0, audio: this._element });
|
||||
}
|
||||
|
||||
if (touchBinded) return;
|
||||
touchBinded = true;
|
||||
|
||||
// Listen to the touchstart body event and play the audio when necessary.
|
||||
cc.game.canvas.addEventListener('touchstart', function () {
|
||||
var item;
|
||||
while (item = touchPlayList.pop()) {
|
||||
item.audio.play(item.offset);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
proto.pause = function () {
|
||||
if (!this._element) return;
|
||||
this._element.pause();
|
||||
this.emit('pause');
|
||||
this._state = Audio.State.PAUSED;
|
||||
};
|
||||
|
||||
proto.resume = function () {
|
||||
if (!this._element || this._element.currentTime === 0) return;
|
||||
this._element.play();
|
||||
this.emit('play');
|
||||
this._state = Audio.State.PLAYING;
|
||||
};
|
||||
|
||||
proto.stop = function () {
|
||||
if (!this._element) return;
|
||||
this._element.pause();
|
||||
try {
|
||||
this._element.currentTime = 0;
|
||||
} catch (error) {}
|
||||
this.emit('pause');
|
||||
this._state = Audio.State.PAUSED;
|
||||
};
|
||||
|
||||
proto.setLoop = function (loop) {
|
||||
if (!this._element) return;
|
||||
this._element.loop = loop;
|
||||
};
|
||||
proto.getLoop = function () {
|
||||
return this._element && this._element.loop;
|
||||
};
|
||||
|
||||
proto.setVolume = function (num) {
|
||||
if (!this._element) return;
|
||||
this._element.volume = num;
|
||||
};
|
||||
proto.getVolume = function () {
|
||||
return this._element ? this._element.volume : 1;
|
||||
};
|
||||
|
||||
proto.setCurrentTime = function (num) {
|
||||
if (!this._element) return;
|
||||
this._element.currentTime = num;
|
||||
};
|
||||
proto.getCurrentTime = function () {
|
||||
return this._element ? this._element.currentTime : 0;
|
||||
};
|
||||
|
||||
proto.getDuration = function () {
|
||||
return this._element ? this._element.duration : 0;
|
||||
};
|
||||
|
||||
proto.getState = function () {
|
||||
var elem = this._element;
|
||||
if (Audio.State.PLAYING === this._state && elem.paused) {
|
||||
this._state = Audio.State.PAUSED;
|
||||
}
|
||||
return this._state;
|
||||
};
|
||||
|
||||
// setFinishCallback
|
||||
|
||||
})(Audio.prototype);
|
||||
|
||||
// Encapsulated WebAudio interface
|
||||
var WebAudioElement = function (buffer) {
|
||||
this._context = cc.sys.__audioSupport.context;
|
||||
this._buffer = buffer;
|
||||
this._volume = this._context['createGain']();
|
||||
this._volume['gain'].value = 1;
|
||||
this._volume['connect'](this._context['destination']);
|
||||
this._loop = false;
|
||||
|
||||
// The time stamp on the audio time axis when the recording begins to play.
|
||||
this._startTime = -1;
|
||||
// Record the currently playing 'Source'
|
||||
@@ -70,10 +236,82 @@ cc.Audio.WebAudio = function (buffer) {
|
||||
this._currextTimer = null;
|
||||
};
|
||||
|
||||
cc.Audio.WebAudio.prototype = {
|
||||
constructor: cc.Audio.WebAudio,
|
||||
(function (proto) {
|
||||
proto.play = function (offset) {
|
||||
// If repeat play, you need to stop before an audio
|
||||
if (this._currentSource && !this.paused) {
|
||||
this._currentSource.stop(0);
|
||||
this.playedLength = 0;
|
||||
}
|
||||
|
||||
get paused () {
|
||||
var audio = this._context["createBufferSource"]();
|
||||
audio.buffer = this._buffer;
|
||||
audio["connect"](this._volume);
|
||||
audio.loop = this._loop;
|
||||
|
||||
this._startTime = this._context.currentTime;
|
||||
offset = offset || this.playedLength;
|
||||
if (offset) {
|
||||
this._startTime -= offset;
|
||||
}
|
||||
var duration = this._buffer.duration;
|
||||
|
||||
var startTime = offset;
|
||||
var endTime;
|
||||
if (this._loop) {
|
||||
if (audio.start)
|
||||
audio.start(0, startTime);
|
||||
else if (audio["notoGrainOn"])
|
||||
audio["noteGrainOn"](0, startTime);
|
||||
else
|
||||
audio["noteOn"](0, startTime);
|
||||
} else {
|
||||
endTime = duration - offset;
|
||||
if (audio.start)
|
||||
audio.start(0, startTime, endTime);
|
||||
else if (audio["notoGrainOn"])
|
||||
audio["noteGrainOn"](0, startTime, endTime);
|
||||
else
|
||||
audio["noteOn"](0, startTime, endTime);
|
||||
}
|
||||
|
||||
this._currentSource = audio;
|
||||
|
||||
audio.onended = function () {
|
||||
if (this.onended) {
|
||||
this.onended(this);
|
||||
}
|
||||
}.bind(this);
|
||||
|
||||
// If the current audio context time stamp is 0
|
||||
// There may be a need to touch events before you can actually start playing audio
|
||||
if (this._context.currentTime === 0) {
|
||||
var self = this;
|
||||
clearTimeout(this._currextTimer);
|
||||
this._currextTimer = setTimeout(function () {
|
||||
if (self._context.currentTime === 0) {
|
||||
touchPlayList.push({
|
||||
offset: offset,
|
||||
audio: self
|
||||
});
|
||||
}
|
||||
}, 10);
|
||||
}
|
||||
};
|
||||
|
||||
proto.pause = function () {
|
||||
// Record the time the current has been played
|
||||
this.playedLength = this._context.currentTime - this._startTime;
|
||||
// If more than the duration of the audio, Need to take the remainder
|
||||
this.playedLength %= this._buffer.duration;
|
||||
var audio = this._currentSource;
|
||||
this._currentSource = null;
|
||||
this._startTime = -1;
|
||||
if (audio)
|
||||
audio.stop(0);
|
||||
};
|
||||
|
||||
proto.__defineGetter__('paused', function () {
|
||||
// If the current audio is a loop, paused is false
|
||||
if (this._currentSource && this._currentSource.loop)
|
||||
return false;
|
||||
@@ -83,634 +321,41 @@ cc.Audio.WebAudio.prototype = {
|
||||
return true;
|
||||
|
||||
// Current time - Start playing time > Audio duration
|
||||
return this.context.currentTime - this._startTime > this.buffer.duration;
|
||||
},
|
||||
return this._context.currentTime - this._startTime > this._buffer.duration;
|
||||
});
|
||||
|
||||
get loop () { return this._loop; },
|
||||
set loop (bool) { return this._loop = bool; },
|
||||
proto.__defineGetter__('loop', function () { return this._loop; });
|
||||
proto.__defineSetter__('loop', function (bool) {
|
||||
if (this._currentSource)
|
||||
this._currentSource.loop = bool;
|
||||
|
||||
get volume () { return this._volume['gain'].value; },
|
||||
set volume (num) { return this._volume['gain'].value = num; },
|
||||
return this._loop = bool;
|
||||
});
|
||||
|
||||
get currentTime () { return this.playedLength; },
|
||||
set currentTime (num) { return this.playedLength = num; },
|
||||
proto.__defineGetter__('volume', function () { return this._volume['gain'].value; });
|
||||
proto.__defineSetter__('volume', function (num) { return this._volume['gain'].value = num; });
|
||||
|
||||
play: function (offset) {
|
||||
|
||||
// If repeat play, you need to stop before an audio
|
||||
if (this._currentSource && !this.paused) {
|
||||
this._currentSource.stop(0);
|
||||
this.playedLength = 0;
|
||||
proto.__defineGetter__('currentTime', function () {
|
||||
if (this.paused) {
|
||||
return this.playedLength;
|
||||
}
|
||||
|
||||
var audio = this.context["createBufferSource"]();
|
||||
audio.buffer = this.buffer;
|
||||
audio["connect"](this._volume);
|
||||
audio.loop = this._loop;
|
||||
|
||||
this._startTime = this.context.currentTime;
|
||||
offset = offset || this.playedLength;
|
||||
|
||||
var duration = this.buffer.duration;
|
||||
if (!this._loop) {
|
||||
if (audio.start)
|
||||
audio.start(0, offset, duration - offset);
|
||||
else if (audio["notoGrainOn"])
|
||||
audio["noteGrainOn"](0, offset, duration - offset);
|
||||
else
|
||||
audio["noteOn"](0, offset, duration - offset);
|
||||
} else {
|
||||
if (audio.start)
|
||||
audio.start(0);
|
||||
else if (audio["notoGrainOn"])
|
||||
audio["noteGrainOn"](0);
|
||||
else
|
||||
audio["noteOn"](0);
|
||||
}
|
||||
|
||||
this._currentSource = audio;
|
||||
|
||||
// If the current audio context time stamp is 0
|
||||
// There may be a need to touch events before you can actually start playing audio
|
||||
if (this.context.currentTime === 0) {
|
||||
var self = this;
|
||||
clearTimeout(this._currextTimer);
|
||||
this._currextTimer = setTimeout(function () {
|
||||
if (self.context.currentTime === 0) {
|
||||
cc.Audio.touchPlayList.push({
|
||||
offset: offset,
|
||||
audio: self
|
||||
});
|
||||
}
|
||||
}, 10);
|
||||
}
|
||||
},
|
||||
pause: function () {
|
||||
// Record the time the current has been played
|
||||
this.playedLength = this.context.currentTime - this._startTime;
|
||||
this.playedLength = this._context.currentTime - this._startTime;
|
||||
// If more than the duration of the audio, Need to take the remainder
|
||||
this.playedLength %= this.buffer.duration;
|
||||
var audio = this._currentSource;
|
||||
this._currentSource = null;
|
||||
this._startTime = -1;
|
||||
if (audio)
|
||||
audio.stop(0);
|
||||
}
|
||||
};
|
||||
|
||||
JS.mixin(cc.Audio.prototype, {
|
||||
setBuffer: function (buffer) {
|
||||
this._AUDIO_TYPE = "WEBAUDIO";
|
||||
this._element = new cc.Audio.WebAudio(buffer);
|
||||
},
|
||||
|
||||
setElement: function (element) {
|
||||
this._AUDIO_TYPE = "AUDIO";
|
||||
this._element = element;
|
||||
|
||||
// Prevent partial browser from playing after the end does not reset the paused tag
|
||||
element.addEventListener('ended', function () {
|
||||
if (!element.loop) {
|
||||
element.paused = true;
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
play: function (offset, loop) {
|
||||
if (!this._element) return;
|
||||
this._element.loop = loop;
|
||||
this._element.play();
|
||||
|
||||
if (this._AUDIO_TYPE === 'AUDIO' && this._element.paused) {
|
||||
this.stop();
|
||||
cc.Audio.touchPlayList.push({ loop: loop, offset: offset, audio: this._element });
|
||||
}
|
||||
|
||||
if (cc.Audio.bindTouch === false) {
|
||||
cc.Audio.bindTouch = true;
|
||||
// Listen to the touchstart body event and play the audio when necessary.
|
||||
cc.game.canvas.addEventListener('touchstart', cc.Audio.touchStart);
|
||||
}
|
||||
},
|
||||
|
||||
getPlaying: function () {
|
||||
if (!this._element) return true;
|
||||
return !this._element.paused;
|
||||
},
|
||||
|
||||
stop: function () {
|
||||
if (!this._element) return;
|
||||
this._element.pause();
|
||||
try{
|
||||
this._element.currentTime = 0;
|
||||
} catch (err) {}
|
||||
},
|
||||
|
||||
pause: function () {
|
||||
if (!this._element) return;
|
||||
this._element.pause();
|
||||
},
|
||||
|
||||
resume: function () {
|
||||
if (!this._element) return;
|
||||
this._element.play();
|
||||
},
|
||||
|
||||
setVolume: function (volume) {
|
||||
if (!this._element) return;
|
||||
this._element.volume = volume;
|
||||
},
|
||||
|
||||
getVolume: function () {
|
||||
if (!this._element) return;
|
||||
return this._element.volume;
|
||||
},
|
||||
|
||||
cloneNode: function () {
|
||||
var audio = new cc.Audio(this.src);
|
||||
if (this._AUDIO_TYPE === "AUDIO") {
|
||||
var elem = document.createElement("audio");
|
||||
var sources = elem.getElementsByTagName('source');
|
||||
for (var i=0; i<sources.length; i++) {
|
||||
elem.appendChild(sources[i]);
|
||||
}
|
||||
elem.src = this.src;
|
||||
audio.setElement(elem);
|
||||
this.playedLength %= this._buffer.duration;
|
||||
return this.playedLength;
|
||||
});
|
||||
proto.__defineSetter__('currentTime', function (num) {
|
||||
if (!this.paused) {
|
||||
this.pause();
|
||||
this.playedLength = num;
|
||||
this.play();
|
||||
} else {
|
||||
audio.setBuffer(this._element.buffer);
|
||||
this.playedLength = num;
|
||||
}
|
||||
return audio;
|
||||
}
|
||||
});
|
||||
return num;
|
||||
});
|
||||
|
||||
(function(polyfill){
|
||||
})(WebAudioElement.prototype);
|
||||
|
||||
var SWA = polyfill.WEB_AUDIO, SWB = polyfill.ONLY_ONE;
|
||||
|
||||
/**
|
||||
* !#en cc.audioEngine is the singleton object, it provide simple audio APIs.
|
||||
* !#zn
|
||||
* cc.audioengine是单例对象。<br/>
|
||||
* 主要用来播放背景音乐和音效,背景音乐同一时间只能播放一个,而音效则可以同时播放多个。<br/>
|
||||
* 注意:<br/>
|
||||
* 在 Android 系统浏览器上,不同浏览器,不同版本的效果不尽相同。<br/>
|
||||
* 比如说:大多数浏览器都需要用户物理交互才可以开始播放音效,有一些不支持 WebAudio,<br/>
|
||||
* 有一些不支持多音轨播放。总之如果对音乐依赖比较强,请做尽可能多的测试。
|
||||
* @class audioEngine
|
||||
* @static
|
||||
*/
|
||||
cc.audioEngine = {
|
||||
_currMusic: null,
|
||||
_musicVolume: 1,
|
||||
|
||||
features: polyfill,
|
||||
|
||||
/**
|
||||
* !#en Play music.
|
||||
* !#zh
|
||||
* 播放指定音乐,并可以设置是否循环播放。<br/>
|
||||
* 注意:音乐播放接口不支持多音轨,同一时间只能播放一个音乐。
|
||||
* @method playMusic
|
||||
* @param {String} url - The path of the music file without filename extension.
|
||||
* @param {Boolean} loop - Whether the music loop or not.
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.playMusic(path, false);
|
||||
*/
|
||||
playMusic: function(url, loop){
|
||||
var bgMusic = this._currMusic;
|
||||
if (bgMusic && bgMusic.getPlaying()) {
|
||||
bgMusic.stop();
|
||||
}
|
||||
var item = cc.loader.getItem(url);
|
||||
var audio = item && item.audio ? item.audio : null;
|
||||
if (!audio) {
|
||||
var self = this;
|
||||
cc.loader.load(url, function (error) {
|
||||
if (!error) {
|
||||
var item = cc.loader.getItem(url);
|
||||
var audio = item && item.audio ? item.audio : null;
|
||||
audio.play(0, loop || false);
|
||||
audio.setVolume(self._musicVolume);
|
||||
self._currMusic = audio;
|
||||
}
|
||||
});
|
||||
item = cc.loader.getItem(url);
|
||||
return item && item.audio ? item.audio : null;
|
||||
}
|
||||
audio.play(0, loop);
|
||||
audio.setVolume(this._musicVolume);
|
||||
|
||||
this._currMusic = audio;
|
||||
return audio;
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Stop playing music.
|
||||
* !#zh 停止当前音乐。
|
||||
* @method stopMusic
|
||||
* @param {Boolean} [releaseData] - If release the music data or not.As default value is false.
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.stopMusic();
|
||||
*/
|
||||
stopMusic: function(releaseData){
|
||||
var audio = this._currMusic;
|
||||
if (audio) {
|
||||
audio.stop();
|
||||
if (releaseData)
|
||||
cc.loader.release(audio.src);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Pause playing music.
|
||||
* !#zh 暂停正在播放音乐。
|
||||
* @method pauseMusic
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.pauseMusic();
|
||||
*/
|
||||
pauseMusic: function(){
|
||||
var audio = this._currMusic;
|
||||
if (audio)
|
||||
audio.pause();
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Resume playing music.
|
||||
* !#zh 恢复音乐播放。
|
||||
* @method resumeMusic
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.resumeMusic();
|
||||
*/
|
||||
resumeMusic: function(){
|
||||
var audio = this._currMusic;
|
||||
if (audio)
|
||||
audio.resume();
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Rewind playing music.
|
||||
* !#zh 从头开始重新播放当前音乐。
|
||||
* @method rewindMusic
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.rewindMusic();
|
||||
*/
|
||||
rewindMusic: function(){
|
||||
var audio = this._currMusic;
|
||||
if (audio) {
|
||||
audio.stop();
|
||||
audio.play();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en The volume of the music max value is 1.0,the min value is 0.0 .
|
||||
* !#zh 获取音量(0.0 ~ 1.0)。
|
||||
* @method getMusicVolume
|
||||
* @return {Number}
|
||||
* @example
|
||||
* //example
|
||||
* var volume = cc.audioEngine.getMusicVolume();
|
||||
*/
|
||||
getMusicVolume: function(){
|
||||
return this._musicVolume;
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Set the volume of music.
|
||||
* !#zh 设置音量(0.0 ~ 1.0)。
|
||||
* @method setMusicVolume
|
||||
* @param {Number} volume Volume must be in 0.0~1.0 .
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.setMusicVolume(0.5);
|
||||
*/
|
||||
setMusicVolume: function(volume){
|
||||
volume = volume - 0;
|
||||
if (isNaN(volume)) volume = 1;
|
||||
if (volume > 1) volume = 1;
|
||||
if (volume < 0) volume = 0;
|
||||
|
||||
this._musicVolume = volume;
|
||||
var audio = this._currMusic;
|
||||
if (audio) {
|
||||
audio.setVolume(volume);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Whether the music is playing.
|
||||
* !#zh 音乐是否正在播放。
|
||||
* @method isMusicPlaying
|
||||
* @return {Boolean} If is playing return true,or return false.
|
||||
* @example
|
||||
* //example
|
||||
* if (cc.audioEngine.isMusicPlaying()) {
|
||||
* cc.log("music is playing");
|
||||
* }
|
||||
* else {
|
||||
* cc.log("music is not playing");
|
||||
* }
|
||||
*/
|
||||
isMusicPlaying: function(){
|
||||
var audio = this._currMusic;
|
||||
if (audio) {
|
||||
return audio.getPlaying();
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
},
|
||||
|
||||
_audioPool: {},
|
||||
_maxAudioInstance: 10,
|
||||
_effectVolume: 1,
|
||||
/**
|
||||
* !#en Play sound effect.
|
||||
* !#zh
|
||||
* 播放指定音效,并可以设置是否循环播放。<br/>
|
||||
* 注意:在部分不支持多音轨的浏览器上,这个接口会失效,请使用 playMusic
|
||||
* @method playEffect
|
||||
* @param {String} url The path of the sound effect with filename extension.
|
||||
* @param {Boolean} loop Whether to loop the effect playing, default value is false
|
||||
* @param {Boolean} volume
|
||||
* @return {Number|null} the audio id
|
||||
* @example
|
||||
* //example
|
||||
* var soundId = cc.audioEngine.playEffect(path);
|
||||
*/
|
||||
playEffect: function(url, loop, volume){
|
||||
volume = volume === undefined ? this._effectVolume : volume;
|
||||
|
||||
// 如果只能够播放一个音频,则优先保证背景音乐
|
||||
if (SWB && this._currMusic && this._currMusic.getPlaying()) {
|
||||
cc.log('Browser is only allowed to play one audio');
|
||||
return null;
|
||||
}
|
||||
|
||||
var effectList = this._audioPool[url];
|
||||
if (!effectList) {
|
||||
effectList = this._audioPool[url] = [];
|
||||
}
|
||||
|
||||
var i;
|
||||
for(i = 0; i < effectList.length; i++){
|
||||
if (!effectList[i].getPlaying()) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!SWA && i > this._maxAudioInstance) {
|
||||
var first = effectList.shift();
|
||||
first.stop();
|
||||
effectList.push(first);
|
||||
i = effectList.length - 1;
|
||||
// cc.log("Error: %s greater than %d", url, this._maxAudioInstance);
|
||||
}
|
||||
|
||||
var audio;
|
||||
if (effectList[i]) {
|
||||
audio = effectList[i];
|
||||
audio.setVolume(volume);
|
||||
audio.play(0, loop || false);
|
||||
return audio;
|
||||
}
|
||||
|
||||
var item = cc.loader.getItem(url);
|
||||
audio = item && item.audio ? item.audio : null;
|
||||
if (SWA && audio && audio._AUDIO_TYPE != "WEBAUDIO") {
|
||||
//delete cc.loader.getRes(url);
|
||||
cc.loader.release(url);
|
||||
audio = null;
|
||||
}
|
||||
|
||||
if (!audio) {
|
||||
// Force using webaudio for effects
|
||||
cc.Audio.useWebAudio = true;
|
||||
audio = new cc.Audio(url);
|
||||
cc.loader.load(url, function (error, url) {
|
||||
if (error) return;
|
||||
var item = cc.loader.getItem(url);
|
||||
var loadAudio = item && item.audio ? item.audio : null;
|
||||
|
||||
if (loadAudio._AUDIO_TYPE === 'WEBAUDIO')
|
||||
audio.setBuffer(loadAudio._element.buffer);
|
||||
else
|
||||
audio.setElement(loadAudio._element);
|
||||
|
||||
audio.setVolume(volume);
|
||||
audio.play(0, loop || false);
|
||||
effectList.push(audio);
|
||||
});
|
||||
cc.Audio.useWebAudio = false;
|
||||
return audio;
|
||||
}
|
||||
|
||||
audio = audio.cloneNode();
|
||||
audio.setVolume(volume);
|
||||
audio.play(0, loop || false);
|
||||
effectList.push(audio);
|
||||
|
||||
return audio;
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Set the volume of sound effects.
|
||||
* !#zh 设置音效音量(0.0 ~ 1.0)。
|
||||
* @method setEffectsVolume
|
||||
* @param {Number} volume Volume must be in 0.0~1.0 .
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.setEffectsVolume(0.5);
|
||||
*/
|
||||
setEffectsVolume: function(volume){
|
||||
volume = volume - 0;
|
||||
if(isNaN(volume)) volume = 1;
|
||||
if(volume > 1) volume = 1;
|
||||
if(volume < 0) volume = 0;
|
||||
|
||||
this._effectVolume = volume;
|
||||
var audioPool = this._audioPool;
|
||||
for(var p in audioPool){
|
||||
var audioList = audioPool[p];
|
||||
if(Array.isArray(audioList))
|
||||
for(var i=0; i<audioList.length; i++){
|
||||
audioList[i].setVolume(volume);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en The volume of the effects max value is 1.0,the min value is 0.0 .
|
||||
* !#zh 获取音效音量(0.0 ~ 1.0)。
|
||||
* @method getEffectsVolume
|
||||
* @return {Number}
|
||||
* @example
|
||||
* //example
|
||||
* var effectVolume = cc.audioEngine.getEffectsVolume();
|
||||
*/
|
||||
getEffectsVolume: function(){
|
||||
return this._effectVolume;
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Pause playing sound effect.
|
||||
* !#zh 暂停指定的音效。
|
||||
* @method pauseEffect
|
||||
* @param {Number} audio - The return value of function playEffect.
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.pauseEffect(audioID);
|
||||
*/
|
||||
pauseEffect: function(audio){
|
||||
if(audio){
|
||||
audio.pause();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Pause all playing sound effect.
|
||||
* !#zh 暂停现在正在播放的所有音效。
|
||||
* @method pauseAllEffects
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.pauseAllEffects();
|
||||
*/
|
||||
pauseAllEffects: function(){
|
||||
var ap = this._audioPool;
|
||||
for(var p in ap){
|
||||
var list = ap[p];
|
||||
for(var i=0; i<ap[p].length; i++){
|
||||
if(list[i].getPlaying()){
|
||||
list[i].pause();
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Resume playing sound effect.
|
||||
* !#zh 恢复播放指定的音效。
|
||||
* @method resumeEffect
|
||||
* @param {Number} audioID - The return value of function playEffect.
|
||||
* @audioID
|
||||
* //example
|
||||
* cc.audioEngine.resumeEffect(audioID);
|
||||
*/
|
||||
resumeEffect: function(audio){
|
||||
if(audio)
|
||||
audio.resume();
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Resume all playing sound effect.
|
||||
* !#zh 恢复播放所有之前暂停的所有音效。
|
||||
* @method resumeAllEffects
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.resumeAllEffects();
|
||||
*/
|
||||
resumeAllEffects: function(){
|
||||
var ap = this._audioPool;
|
||||
for(var p in ap){
|
||||
var list = ap[p];
|
||||
for(var i=0; i<ap[p].length; i++){
|
||||
list[i].resume();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Stop playing sound effect.
|
||||
* !#zh 停止播放指定音效。
|
||||
* @method stopEffect
|
||||
* @param {Number} audioID - The return value of function playEffect.
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.stopEffect(audioID);
|
||||
*/
|
||||
stopEffect: function(audio){
|
||||
if(audio)
|
||||
audio.stop();
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Stop all playing sound effects.
|
||||
* !#zh 停止正在播放的所有音效。
|
||||
* @method stopAllEffects
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.stopAllEffects();
|
||||
*/
|
||||
stopAllEffects: function(){
|
||||
var ap = this._audioPool;
|
||||
for(var p in ap){
|
||||
var list = ap[p];
|
||||
for(var i=0; i<ap[p].length; i++){
|
||||
list[i].stop();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Unload the preloaded effect from internal buffer.
|
||||
* !#zh 卸载预加载的音效。
|
||||
* @method unloadEffect
|
||||
* @param {String} url
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.unloadEffect(EFFECT_FILE);
|
||||
*/
|
||||
unloadEffect: function(url){
|
||||
if(!url){
|
||||
return;
|
||||
}
|
||||
|
||||
cc.loader.release(url);
|
||||
var pool = this._audioPool[url];
|
||||
if(pool) pool.length = 0;
|
||||
delete this._audioPool[url];
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en End music and effects.
|
||||
* !#zh 停止所有音乐和音效的播放。
|
||||
* @method end
|
||||
*/
|
||||
end: function(){
|
||||
this.stopMusic();
|
||||
this.stopAllEffects();
|
||||
},
|
||||
|
||||
_pauseCache: [],
|
||||
_pausePlaying: function(){
|
||||
var bgMusic = this._currMusic;
|
||||
if(bgMusic && bgMusic.getPlaying()){
|
||||
bgMusic.pause();
|
||||
this._pauseCache.push(bgMusic);
|
||||
}
|
||||
var ap = this._audioPool;
|
||||
for(var p in ap){
|
||||
var list = ap[p];
|
||||
for(var i=0; i<ap[p].length; i++){
|
||||
if(list[i].getPlaying()){
|
||||
list[i].pause();
|
||||
this._pauseCache.push(list[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
_resumePlaying: function(){
|
||||
var list = this._pauseCache;
|
||||
for(var i=0; i<list.length; i++){
|
||||
list[i].resume();
|
||||
}
|
||||
list.length = 0;
|
||||
}
|
||||
};
|
||||
|
||||
})(cc.sys.__audioSupport);
|
||||
module.exports = cc.Audio = Audio;
|
||||
@@ -0,0 +1,456 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2008-2010 Ricardo Quesada
|
||||
Copyright (c) 2011-2012 cocos2d-x.org
|
||||
Copyright (c) 2013-2014 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos2d-x.org
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
var Audio = require('./CCAudio');
|
||||
|
||||
var instanceId = 0;
|
||||
var id2audio = {};
|
||||
var url2id = {};
|
||||
|
||||
var getAudioFromPath = function (path) {
|
||||
var id = instanceId++;
|
||||
var list = url2id[path];
|
||||
if (!list) {
|
||||
list = url2id[path] = [];
|
||||
}
|
||||
var audio;
|
||||
if (audioEngine._maxAudioInstance > list.length) {
|
||||
audio = new Audio(path);
|
||||
id2audio[id] = audio;
|
||||
} else {
|
||||
var oldId = list.shift();
|
||||
audio = id2audio[id] = id2audio[oldId];
|
||||
delete id2audio[oldId];
|
||||
}
|
||||
audio.instanceId = id;
|
||||
list.push(id);
|
||||
|
||||
return audio;
|
||||
};
|
||||
|
||||
var getAudioFromId = function (id) {
|
||||
return id2audio[id];
|
||||
};
|
||||
|
||||
var audioEngine = {
|
||||
|
||||
AudioState: Audio.State,
|
||||
|
||||
_maxWebAudioSize: 307200, // 300kb * 1024
|
||||
_maxAudioInstance: 24,
|
||||
|
||||
_id2audio: id2audio,
|
||||
|
||||
/**
|
||||
* !#en Play audio.
|
||||
* !#zh 播放音频
|
||||
* @method play
|
||||
* @param {String} filePath - The path of the audio file without filename extension.
|
||||
* @param {Boolean} loop - Whether the music loop or not.
|
||||
* @param {Number} volume - Volume size.
|
||||
* @return {Number} audioId
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.(path, false, 0.5);
|
||||
*/
|
||||
play: function (filePath, loop, volume/*, profile*/) {
|
||||
var audio = getAudioFromPath(filePath);
|
||||
var callback = function () {
|
||||
audio.setLoop(loop || false);
|
||||
audio.setVolume(volume || 1);
|
||||
audio.play();
|
||||
};
|
||||
audio.on('load', callback);
|
||||
audio.preload();
|
||||
|
||||
return audio.instanceId;
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Set audio loop.
|
||||
* !#zh 设置音频是否循环。
|
||||
* @method setLoop
|
||||
* @param {Number} audioID - audio id.
|
||||
* @param {Boolean} loop - Whether cycle.
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.setLoop(id, true);
|
||||
*/
|
||||
setLoop: function (audioID, loop) {
|
||||
var audio = getAudioFromId(audioID);
|
||||
if (!audio || !audio.setLoop)
|
||||
return;
|
||||
audio.setLoop(loop);
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Get audio cycle state.
|
||||
* !#zh 获取音频的循环状态。
|
||||
* @method isLoop
|
||||
* @param {Number} audioID - audio id.
|
||||
* @return {Boolean} Whether cycle.
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.isLoop(id);
|
||||
*/
|
||||
isLoop: function (audioID) {
|
||||
var audio = getAudioFromId(audioID);
|
||||
if (!audio || !audio.isLoop)
|
||||
return false;
|
||||
return audio.isLoop();
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Set the volume of audio.
|
||||
* !#zh 设置音量(0.0 ~ 1.0)。
|
||||
* @method setVolume
|
||||
* @param {Number} audioID audio id.
|
||||
* @param {Number} volume Volume must be in 0.0~1.0 .
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.setVolume(0.5);
|
||||
*/
|
||||
setVolume: function (audioID, volume) {
|
||||
var audio = getAudioFromId(audioID);
|
||||
if (!audio || !audio.setVolume)
|
||||
return;
|
||||
audio.setVolume(volume);
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en The volume of the music max value is 1.0,the min value is 0.0 .
|
||||
* !#zh 获取音量(0.0 ~ 1.0)。
|
||||
* @method getVolume
|
||||
* @param {Number} audioID audio id.
|
||||
* @return {Boolean}
|
||||
* @example
|
||||
* //example
|
||||
* var volume = cc.audioEngine.getVolume(id);
|
||||
*/
|
||||
getVolume: function (audioID) {
|
||||
var audio = getAudioFromId(audioID);
|
||||
if (!audio || !audio.getVolume)
|
||||
return 1;
|
||||
return audio.getVolume();
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Set current time
|
||||
* !#zh 设置当前的音频时间。
|
||||
* @method setCurrentTime
|
||||
* @param {Number} audioID audio id.
|
||||
* @param {Number} sec current time.
|
||||
* @return {Boolean}
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.setCurrentTime(id, 2);
|
||||
*/
|
||||
setCurrentTime: function (audioID, sec) {
|
||||
var audio = getAudioFromId(audioID);
|
||||
if (!audio || !audio.setCurrentTime)
|
||||
return false;
|
||||
audio.setCurrentTime(sec);
|
||||
return true;
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Get current time
|
||||
* !#zh 获取当前的音频播放时间。
|
||||
* @method getCurrentTime
|
||||
* @param {Number} audioID audio id.
|
||||
* @return {Number} audio current time.
|
||||
* @example
|
||||
* //example
|
||||
* var time = cc.audioEngine.getCurrentTime(id);
|
||||
*/
|
||||
getCurrentTime: function (audioID) {
|
||||
var audio = getAudioFromId(audioID);
|
||||
if (!audio || !audio.getCurrentTime)
|
||||
return 0;
|
||||
return audio.getCurrentTime();
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Get audio duration
|
||||
* !#zh 获取音频总时长。
|
||||
* @method getDuration
|
||||
* @param {Number} audioID audio id.
|
||||
* @return {Number} audio duration.
|
||||
* @example
|
||||
* //example
|
||||
* var time = cc.audioEngine.getDuration(id);
|
||||
*/
|
||||
getDuration: function (audioID) {
|
||||
var audio = getAudioFromId(audioID);
|
||||
if (!audio || !audio.getDuration)
|
||||
return 0;
|
||||
return audio.getDuration();
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Get audio state
|
||||
* !#zh 获取音频状态。
|
||||
* @method getState
|
||||
* @param {Number} audioID audio id.
|
||||
* @return {cc.audioEngine.AudioState} audio duration.
|
||||
* @example
|
||||
* //example
|
||||
* var state = cc.audioEngine.getState(id);
|
||||
*/
|
||||
getState: function (audioID) {
|
||||
var audio = getAudioFromId(audioID);
|
||||
if (!audio || !audio.getState)
|
||||
return 0;
|
||||
return audio.getState();
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Get audio state
|
||||
* !#zh 获取音频状态。
|
||||
* @method getState
|
||||
* @param {Number} audioID audio id.
|
||||
* @param {Function} callback loaded callback.
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.setFinishCallback(id, function () {});
|
||||
*/
|
||||
setFinishCallback: function (audioID, callback) {
|
||||
var audio = getAudioFromId(audioID);
|
||||
if (!audio)
|
||||
return;
|
||||
|
||||
audio.off('ended');
|
||||
audio.on('ended', callback);
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Pause playing audio.
|
||||
* !#zh 暂停正在播放音频。
|
||||
* @method pause
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.pause(id);
|
||||
*/
|
||||
pause: function (audioID) {
|
||||
var audio = getAudioFromId(audioID);
|
||||
if (!audio || !audio.pause)
|
||||
return false;
|
||||
audio.pause();
|
||||
return true;
|
||||
},
|
||||
_pauseIDCache: [],
|
||||
|
||||
/**
|
||||
* !#en Pause all playing audio
|
||||
* !#zh 暂停现在正在播放的所有音频。
|
||||
* @method pauseAll
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.pauseAll();
|
||||
*/
|
||||
pauseAll: function () {
|
||||
for (var id in id2audio) {
|
||||
var audio = id2audio[id];
|
||||
var state = audio.getState();
|
||||
if (state === Audio.State.PLAYING) {
|
||||
this._pauseIDCache.push(id);
|
||||
audio.pause();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Resume playing audio.
|
||||
* !#zh 恢复播放指定的音频。
|
||||
* @method resume
|
||||
* @param {Number} audioID - The return value of function play.
|
||||
* //example
|
||||
* cc.audioEngine.resume(audioID);
|
||||
*/
|
||||
resume: function (audioID) {
|
||||
var audio = getAudioFromId(audioID);
|
||||
if (!audio || !audio.resume)
|
||||
return false;
|
||||
if (audio.getCurrentTime() === 0) {
|
||||
audio.play();
|
||||
} else {
|
||||
audio.resume();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Resume all playing audio.
|
||||
* !#zh 恢复播放所有之前暂停的所有音频。
|
||||
* @method resumeAll
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.resumeAll();
|
||||
*/
|
||||
resumeAll: function () {
|
||||
while (this._pauseIDCache.length > 0) {
|
||||
var id = this._pauseIDCache.pop();
|
||||
var audio = getAudioFromId(id);
|
||||
if (audio && audio.resume)
|
||||
audio.resume();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Stop playing audio.
|
||||
* !#zh 停止播放指定音频。
|
||||
* @method stop
|
||||
* @param {Number} audioID - The return value of function play.
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.stop(audioID);
|
||||
*/
|
||||
stop: function (audioID) {
|
||||
var audio = getAudioFromId(audioID);
|
||||
if (!audio || !audio.stop)
|
||||
return false;
|
||||
audio.stop();
|
||||
return true;
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Stop all playing audio.
|
||||
* !#zh 停止正在播放的所有音频。
|
||||
* @method stopAll
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.stopAll();
|
||||
*/
|
||||
stopAll: function () {
|
||||
for (var id in id2audio) {
|
||||
var audio = id2audio[id];
|
||||
if (audio && audio.stop) {
|
||||
audio.stop();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Set up an audio can generate a few examples.
|
||||
* !#zh 设置一个音频可以设置几个实例
|
||||
* @method setMaxAudioInstance
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.setMaxAudioInstance(20);
|
||||
*/
|
||||
setMaxAudioInstance: function (num) {
|
||||
return this._maxAudioInstance = num;
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Getting audio can produce several examples.
|
||||
* !#zh 获取一个音频可以设置几个实例
|
||||
* @method getMaxAudioInstance
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.getMaxAudioInstance();
|
||||
*/
|
||||
getMaxAudioInstance: function () {
|
||||
return this._maxAudioInstance;
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Unload the preloaded audio from internal buffer.
|
||||
* !#zh 卸载预加载的音频。
|
||||
* @method uncache
|
||||
* @param {String} filePath
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.uncache(filePath);
|
||||
*/
|
||||
uncache: function (filePath) {
|
||||
var list = url2id[filePath];
|
||||
if (!list) return;
|
||||
while (list.length > 0) {
|
||||
var id = list.pop();
|
||||
var audio = id2audio[id];
|
||||
if (audio) {
|
||||
audio.stop();
|
||||
delete id2audio[id];
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Unload all audio from internal buffer.
|
||||
* !#zh 卸载所有音频。
|
||||
* @method uncacheAll
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.uncacheAll();
|
||||
*/
|
||||
uncacheAll: function () {
|
||||
this.stopAll();
|
||||
id2audio = {};
|
||||
url2id = {};
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Gets an audio profile by name.
|
||||
*
|
||||
* @param profileName A name of audio profile.
|
||||
* @return The audio profile.
|
||||
*/
|
||||
getProfile: function (profileName) {},
|
||||
|
||||
/**
|
||||
* !#en Preload audio file.
|
||||
* !#zh 预加载一个音频
|
||||
* @param filePath The file path of an audio.
|
||||
* @param callback The callback of an audio.
|
||||
* @method preload
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.preload(path);
|
||||
*/
|
||||
preload: function (filePath, callback) {
|
||||
cc.loader.load(filePath, function (error) {
|
||||
if (!error) {
|
||||
callback();
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Set a size, the unit is KB,Over this size is directly resolved into DOM nodes
|
||||
* !#zh 设置一个以kb为单位的尺寸,大于这个尺寸的音频在加载的时候会强制使用 dom 方式加载
|
||||
* @param kb The file path of an audio.
|
||||
* @method setMaxWebAudioSize
|
||||
* @example
|
||||
* //example
|
||||
* cc.audioEngine.setMaxWebAudioSize(300);
|
||||
*/
|
||||
// Because webAudio takes up too much memory,So allow users to manually choose
|
||||
setMaxWebAudioSize: function (kb) {
|
||||
this._maxWebAudioSize = kb * 1024;
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = cc.audioEngine = audioEngine;
|
||||
+36
-20
@@ -26,6 +26,7 @@
|
||||
|
||||
var EventTarget = require('./event/event-target');
|
||||
var Class = require('./platform/_CCClass');
|
||||
var AutoReleaseUtils = require('./load-pipeline/auto-release-utils');
|
||||
|
||||
cc.g_NumberOfDraws = 0;
|
||||
|
||||
@@ -268,7 +269,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
|
||||
renderer.clearRenderCommands();
|
||||
cc.renderer.assignedZ = 0;
|
||||
this._runningScene._renderCmd._curLevel = 0; //level start from 0;
|
||||
this._runningScene.visit();
|
||||
this._runningScene._renderCmd.visit();
|
||||
renderer.resetFlag();
|
||||
}
|
||||
else if (renderer.transformDirty()) {
|
||||
@@ -296,16 +297,6 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
|
||||
this._afterVisitScene();
|
||||
},
|
||||
|
||||
render: function (deltaTime) {
|
||||
cc.g_NumberOfDraws = 0;
|
||||
cc.renderer.clear();
|
||||
|
||||
cc.renderer.rendering(cc._renderContext);
|
||||
this._totalFrames++;
|
||||
|
||||
this.emit(cc.Director.EVENT_AFTER_DRAW);
|
||||
},
|
||||
|
||||
_beforeVisitScene: null,
|
||||
_afterVisitScene: null,
|
||||
|
||||
@@ -399,8 +390,12 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
|
||||
getZEye: null,
|
||||
|
||||
/**
|
||||
* !#en Pause the director's ticker.
|
||||
* !#zh 暂停正在运行的场景,该暂停只会停止 Scheduler,但是不会停止渲染和 UI 响应。
|
||||
* !#en Pause the director's ticker, only involve the game logic execution.
|
||||
* It won't pause the rendering process nor the event manager.
|
||||
* If you want to pause the entier game including rendering, audio and event,
|
||||
* please use {{#crossLink "Game.pause"}}cc.game.pause{{/crossLink}}
|
||||
* !#zh 暂停正在运行的场景,该暂停只会停止游戏逻辑执行,但是不会停止渲染和 UI 响应。
|
||||
* 如果想要更彻底得暂停游戏,包含渲染,音频和事件,请使用 {{#crossLink "Game.pause"}}cc.game.pause{{/crossLink}}。
|
||||
* @method pause
|
||||
*/
|
||||
pause: function () {
|
||||
@@ -546,8 +541,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
|
||||
var persistNodes = game._persistRootNodes;
|
||||
|
||||
if (scene instanceof cc.Scene) {
|
||||
// ensure scene initialized
|
||||
scene._load();
|
||||
scene._load(); // ensure scene initialized
|
||||
}
|
||||
|
||||
// detach persist nodes
|
||||
@@ -558,8 +552,13 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
|
||||
game._ignoreRemovePersistNode = null;
|
||||
}
|
||||
|
||||
// unload scene
|
||||
var oldScene = this._scene;
|
||||
|
||||
// auto release assets
|
||||
var autoReleaseAssets = oldScene && oldScene.autoReleaseAssets && oldScene.dependAssets;
|
||||
AutoReleaseUtils.autoRelease(cc.loader, autoReleaseAssets, scene.dependAssets);
|
||||
|
||||
// unload scene
|
||||
if (cc.isValid(oldScene)) {
|
||||
oldScene.destroy();
|
||||
}
|
||||
@@ -828,8 +827,8 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Resume director after pause, if the current scene is not paused, nothing will happen.
|
||||
* !#zh 恢复暂停场景,恢复 Scheduler,如果当前场景没有暂停将没任何事情发生。
|
||||
* !#en Resume game logic execution after pause, if the current scene is not paused, nothing will happen.
|
||||
* !#zh 恢复暂停场景的游戏逻辑,如果当前场景没有暂停将没任何事情发生。
|
||||
* @method resume
|
||||
*/
|
||||
resume: function () {
|
||||
@@ -1389,7 +1388,16 @@ cc.DisplayLinkDirector = cc.Director.extend(/** @lends cc.Director# */{
|
||||
}
|
||||
|
||||
this.visit();
|
||||
this.render();
|
||||
|
||||
// Render
|
||||
cc.g_NumberOfDraws = 0;
|
||||
cc.renderer.clear();
|
||||
|
||||
cc.renderer.rendering(cc._renderContext);
|
||||
this._totalFrames++;
|
||||
|
||||
this.emit(cc.Director.EVENT_AFTER_DRAW);
|
||||
|
||||
} : function () {
|
||||
if (this._purgeDirectorInNextLoop) {
|
||||
this._purgeDirectorInNextLoop = false;
|
||||
@@ -1421,7 +1429,15 @@ cc.DisplayLinkDirector = cc.Director.extend(/** @lends cc.Director# */{
|
||||
}
|
||||
|
||||
this.visit(this._deltaTime);
|
||||
this.render(this._deltaTime);
|
||||
|
||||
// Render
|
||||
cc.g_NumberOfDraws = 0;
|
||||
cc.renderer.clear();
|
||||
|
||||
cc.renderer.rendering(cc._renderContext);
|
||||
this._totalFrames++;
|
||||
|
||||
this.emit(cc.Director.EVENT_AFTER_DRAW);
|
||||
|
||||
this._calculateMPF();
|
||||
}
|
||||
|
||||
+29
-15
@@ -29,17 +29,19 @@ if (!(CC_EDITOR && Editor.isMainProcess)) {
|
||||
View = require('./platform/CCView');
|
||||
}
|
||||
|
||||
var audioEngine = cc.audioEngine = require('../audio/CCAudioEngine');
|
||||
|
||||
/**
|
||||
* !#en An object to boot the game.
|
||||
* !#zh 包含游戏主体信息并负责驱动游戏的游戏对象。
|
||||
* @class Game
|
||||
*/
|
||||
var game = /** @lends cc.game# */{
|
||||
var game = {
|
||||
|
||||
/**
|
||||
* Event triggered when game hide to background.
|
||||
* Please note that this event is not 100% guaranteed to be fired.
|
||||
* @constant
|
||||
* @property EVENT_HIDE
|
||||
* @type {String}
|
||||
* @example
|
||||
* cc.game.on(cc.game.EVENT_HIDE, function () {
|
||||
@@ -52,21 +54,21 @@ var game = /** @lends cc.game# */{
|
||||
/**
|
||||
* Event triggered when game back to foreground
|
||||
* Please note that this event is not 100% guaranteed to be fired.
|
||||
* @constant
|
||||
* @property EVENT_SHOW
|
||||
* @type {String}
|
||||
*/
|
||||
EVENT_SHOW: "game_on_show",
|
||||
|
||||
/**
|
||||
* Event triggered after game inited, at this point all engine objects and game scripts are loaded
|
||||
* @constant
|
||||
* @property EVENT_GAME_INITED
|
||||
* @type {String}
|
||||
*/
|
||||
EVENT_GAME_INITED: "game_inited",
|
||||
|
||||
/**
|
||||
* Event triggered after renderer inited, at this point you will be able to use the render context
|
||||
* @constant
|
||||
* @property EVENT_RENDERER_INITED
|
||||
* @type {String}
|
||||
*/
|
||||
EVENT_RENDERER_INITED: "renderer_inited",
|
||||
@@ -80,7 +82,7 @@ var game = /** @lends cc.game# */{
|
||||
|
||||
/**
|
||||
* Key of config
|
||||
* @constant
|
||||
* @property CONFIG_KEY
|
||||
* @type {Object}
|
||||
*/
|
||||
CONFIG_KEY: {
|
||||
@@ -241,15 +243,19 @@ var game = /** @lends cc.game# */{
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Pause the game,pause main loop.
|
||||
* !#zh 暂停游戏,暂停的是整个主循环。
|
||||
* !#en Pause the game main loop. This will pause:
|
||||
* game logic execution, rendering process, event manager, background music and all audio effects.
|
||||
* This is different with cc.director.pause which only pause the game logic execution.
|
||||
* !#zh 暂停游戏主循环。包含:游戏逻辑,渲染,事件处理,背景音乐和所有音效。这点和只暂停游戏逻辑的 cc.director.pause 不同。
|
||||
* @method pause
|
||||
*/
|
||||
pause: function () {
|
||||
if (this._paused) return;
|
||||
this._paused = true;
|
||||
// Pause audio engine
|
||||
cc.audioEngine && cc.audioEngine._pausePlaying();
|
||||
if (audioEngine) {
|
||||
audioEngine.pauseAll();
|
||||
}
|
||||
// Pause main loop
|
||||
if (this._intervalId)
|
||||
window.cancelAnimationFrame(this._intervalId);
|
||||
@@ -257,15 +263,18 @@ var game = /** @lends cc.game# */{
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Resume the game from pause.
|
||||
* !#zh 继续游戏,继续的是整个主循环。
|
||||
* !#en Resume the game from pause. This will resume:
|
||||
* game logic execution, rendering process, event manager, background music and all audio effects.
|
||||
* !#zh 恢复游戏主循环。包含:游戏逻辑,渲染,事件处理,背景音乐和所有音效。
|
||||
* @method resume
|
||||
*/
|
||||
resume: function () {
|
||||
if (!this._paused) return;
|
||||
this._paused = false;
|
||||
// Resume audio engine
|
||||
cc.audioEngine && cc.audioEngine._resumePlaying();
|
||||
if (audioEngine) {
|
||||
audioEngine.resumeAll();
|
||||
}
|
||||
// Resume main loop
|
||||
this._runMainLoop();
|
||||
},
|
||||
@@ -288,13 +297,15 @@ var game = /** @lends cc.game# */{
|
||||
restart: function () {
|
||||
cc.director.popToSceneStackLevel(0);
|
||||
// Clean up audio
|
||||
cc.audioEngine && cc.audioEngine.end();
|
||||
audioEngine && audioEngine.end();
|
||||
|
||||
game.onStart();
|
||||
},
|
||||
|
||||
/**
|
||||
* End game, it will close the game window
|
||||
* !#en End game, it will close the game window
|
||||
* !#zh 退出游戏
|
||||
* @method end
|
||||
*/
|
||||
end: function () {
|
||||
close();
|
||||
@@ -613,11 +624,13 @@ var game = /** @lends cc.game# */{
|
||||
modules && (config[CONFIG_KEY.modules] = modules);
|
||||
|
||||
// Scene parser
|
||||
this._sceneInfos = this._sceneInfos.concat(config[CONFIG_KEY.scenes]);
|
||||
this._sceneInfos = config[CONFIG_KEY.scenes] || [];
|
||||
|
||||
// Collide Map and Group List
|
||||
this.collisionMatrix = config.collisionMatrix || [];
|
||||
this.groupList = config.groupList || [];
|
||||
|
||||
cc._initDebugSetting(config[CONFIG_KEY.debugMode]);
|
||||
|
||||
this.config = config;
|
||||
},
|
||||
@@ -686,6 +699,7 @@ var game = /** @lends cc.game# */{
|
||||
} else {
|
||||
cc._renderType = game.RENDER_TYPE_CANVAS;
|
||||
cc.renderer = cc.rendererCanvas;
|
||||
cc.renderer.init();
|
||||
this._renderContext = cc._renderContext = new cc.CanvasContextWrapper(localCanvas.getContext("2d"));
|
||||
cc._drawingUtil = cc.DrawingPrimitiveCanvas ? new cc.DrawingPrimitiveCanvas(this._renderContext) : null;
|
||||
}
|
||||
|
||||
+95
-22
@@ -25,6 +25,7 @@
|
||||
'use strict';
|
||||
|
||||
var EventTarget = require('./event/event-target');
|
||||
var PrefabHelper = require('./utils/prefab-helper');
|
||||
|
||||
var JS = cc.js;
|
||||
var Flags = cc.Object.Flags;
|
||||
@@ -140,7 +141,7 @@ var _mouseEvents = [
|
||||
EventType.MOUSE_WHEEL,
|
||||
];
|
||||
|
||||
var currentHovered = null;
|
||||
var _currentHovered = null;
|
||||
|
||||
var _touchStartHandler = function (touch, event) {
|
||||
var pos = touch.getLocation();
|
||||
@@ -194,12 +195,12 @@ var _mouseMoveHandler = function (event) {
|
||||
event.stopPropagation();
|
||||
if (!this._previousIn) {
|
||||
// Fix issue when hover node switched, previous hovered node won't get MOUSE_LEAVE notification
|
||||
if (currentHovered) {
|
||||
if (_currentHovered) {
|
||||
event.type = EventType.MOUSE_LEAVE;
|
||||
currentHovered.owner.dispatchEvent(event);
|
||||
currentHovered._previousIn = false;
|
||||
_currentHovered.dispatchEvent(event);
|
||||
_currentHovered._mouseListener._previousIn = false;
|
||||
}
|
||||
currentHovered = this;
|
||||
_currentHovered = this.owner;
|
||||
event.type = EventType.MOUSE_ENTER;
|
||||
node.dispatchEvent(event);
|
||||
this._previousIn = true;
|
||||
@@ -211,7 +212,7 @@ var _mouseMoveHandler = function (event) {
|
||||
event.type = EventType.MOUSE_LEAVE;
|
||||
node.dispatchEvent(event);
|
||||
this._previousIn = false;
|
||||
currentHovered = null;
|
||||
_currentHovered = null;
|
||||
}
|
||||
};
|
||||
var _mouseUpHandler = function (event) {
|
||||
@@ -394,10 +395,7 @@ var Node = cc.Class({
|
||||
* @type {PrefabInfo}
|
||||
* @private
|
||||
*/
|
||||
_prefab: {
|
||||
default: null,
|
||||
editorOnly: true
|
||||
},
|
||||
_prefab: null,
|
||||
|
||||
/**
|
||||
* If true, the node is an persist node which won't be destroyed during scene transition.
|
||||
@@ -524,16 +522,25 @@ var Node = cc.Class({
|
||||
}
|
||||
|
||||
// Actions
|
||||
this.stopAllActions();
|
||||
cc.director.getActionManager().removeAllActionsFromTarget(this);
|
||||
this._releaseAllActions();
|
||||
|
||||
// Remove Node.currentHovered
|
||||
if (_currentHovered === this) {
|
||||
_currentHovered = null;
|
||||
}
|
||||
|
||||
// Remove all listeners
|
||||
if (CC_JSB && this._touchListener) {
|
||||
this._touchListener.release();
|
||||
this._touchListener.owner = null;
|
||||
this._touchListener.mask = null;
|
||||
this._touchListener = null;
|
||||
}
|
||||
if (CC_JSB && this._mouseListener) {
|
||||
this._mouseListener.release();
|
||||
this._mouseListener.owner = null;
|
||||
this._mouseListener.mask = null;
|
||||
this._mouseListener = null;
|
||||
}
|
||||
cc.eventManager.removeListeners(this);
|
||||
@@ -566,6 +573,7 @@ var Node = cc.Class({
|
||||
}
|
||||
else if (CC_JSB) {
|
||||
this._sgNode.release();
|
||||
this._sgNode._entity = null;
|
||||
this._sgNode = null;
|
||||
}
|
||||
},
|
||||
@@ -633,8 +641,8 @@ var Node = cc.Class({
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Returns all components of supplied type in any of its children.
|
||||
* !#zh 递归查找所有子节点中指定类型的组件。
|
||||
* !#en Returns all components of supplied type in self or any of its children.
|
||||
* !#zh 递归查找自身或所有子节点中指定类型的组件
|
||||
* @method getComponentsInChildren
|
||||
* @param {Function|String} typeOrClassName
|
||||
* @return {Component[]}
|
||||
@@ -645,6 +653,7 @@ var Node = cc.Class({
|
||||
getComponentsInChildren: function (typeOrClassName) {
|
||||
var constructor = getConstructor(typeOrClassName), components = [];
|
||||
if (constructor) {
|
||||
findComponents(this, constructor, components);
|
||||
findChildComponents(this._children, constructor, components);
|
||||
}
|
||||
return components;
|
||||
@@ -780,13 +789,14 @@ var Node = cc.Class({
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (ctor._requireComponent) {
|
||||
var ReqComp = ctor._requireComponent;
|
||||
if (ReqComp && !this.getComponent(ReqComp)) {
|
||||
if (index === this._components.length) {
|
||||
// If comp should be last component, increase the index because required component added
|
||||
++index;
|
||||
}
|
||||
var depend = this.addComponent(ctor._requireComponent);
|
||||
if (!depend) {
|
||||
var depended = this.addComponent(ReqComp);
|
||||
if (!depended) {
|
||||
// depend conflicts
|
||||
return null;
|
||||
}
|
||||
@@ -888,6 +898,33 @@ var Node = cc.Class({
|
||||
}
|
||||
},
|
||||
|
||||
/*
|
||||
* The initializer for Node which will be called before all components onLoad
|
||||
*/
|
||||
_onBatchCreated: function () {
|
||||
var prefabInfo = this._prefab;
|
||||
if (prefabInfo && prefabInfo.sync && !prefabInfo._synced) {
|
||||
PrefabHelper.syncWithPrefab(this);
|
||||
}
|
||||
|
||||
this._updateDummySgNode();
|
||||
|
||||
if (this._parent) {
|
||||
this._parent._sgNode.addChild(this._sgNode);
|
||||
}
|
||||
|
||||
if ( !this._activeInHierarchy ) {
|
||||
// deactivate ActionManager and EventManager by default
|
||||
cc.director.getActionManager().pauseTarget(this);
|
||||
cc.eventManager.pauseTarget(this);
|
||||
}
|
||||
|
||||
var children = this._children;
|
||||
for (var i = 0, len = children.length; i < len; i++) {
|
||||
children[i]._onBatchCreated();
|
||||
}
|
||||
},
|
||||
|
||||
_activeRecursively: function (newActive) {
|
||||
var cancelActivation = false;
|
||||
if (this._objFlags & Activating) {
|
||||
@@ -958,6 +995,12 @@ var Node = cc.Class({
|
||||
// activate
|
||||
cc.director.getActionManager().resumeTarget(this);
|
||||
cc.eventManager.resumeTarget(this);
|
||||
if (this._touchListener) {
|
||||
this._touchListener.mask = _searchMaskParent(this);
|
||||
}
|
||||
if (this._mouseListener) {
|
||||
this._mouseListener.mask = _searchMaskParent(this);
|
||||
}
|
||||
}
|
||||
else {
|
||||
// deactivate
|
||||
@@ -1046,10 +1089,20 @@ var Node = cc.Class({
|
||||
var clone = cc.instantiate._clone(this, this);
|
||||
clone._parent = null;
|
||||
|
||||
// init
|
||||
if (CC_EDITOR && cc.engine._isPlaying) {
|
||||
var thisPrefabInfo = this._prefab;
|
||||
var syncing = thisPrefabInfo && this === thisPrefabInfo.root && thisPrefabInfo.sync;
|
||||
if (syncing) {
|
||||
// copy non-serialized property
|
||||
clone._prefab._synced = thisPrefabInfo._synced;
|
||||
//if (thisPrefabInfo._synced) {
|
||||
// return clone;
|
||||
//}
|
||||
}
|
||||
else if (CC_EDITOR && cc.engine._isPlaying) {
|
||||
this._name += ' (Clone)';
|
||||
}
|
||||
|
||||
// init
|
||||
clone._onBatchCreated();
|
||||
|
||||
return clone;
|
||||
@@ -1086,6 +1139,7 @@ var Node = cc.Class({
|
||||
* node.on(cc.Node.EventType.TOUCH_CANCEL, callback, this.node);
|
||||
*/
|
||||
on: function (type, callback, target, useCapture) {
|
||||
var newAdded = false;
|
||||
if (_touchEvents.indexOf(type) !== -1) {
|
||||
if (!this._touchListener) {
|
||||
this._touchListener = cc.EventListener.create({
|
||||
@@ -1101,6 +1155,7 @@ var Node = cc.Class({
|
||||
this._touchListener.retain();
|
||||
}
|
||||
cc.eventManager.addListener(this._touchListener, this);
|
||||
newAdded = true;
|
||||
}
|
||||
}
|
||||
else if (_mouseEvents.indexOf(type) !== -1) {
|
||||
@@ -1119,8 +1174,17 @@ var Node = cc.Class({
|
||||
this._mouseListener.retain();
|
||||
}
|
||||
cc.eventManager.addListener(this._mouseListener, this);
|
||||
newAdded = true;
|
||||
}
|
||||
}
|
||||
if (newAdded && !this._activeInHierarchy) {
|
||||
cc.director.getScheduler().schedule(function() {
|
||||
if (!this._activeInHierarchy) {
|
||||
cc.eventManager.pauseTarget(this);
|
||||
}
|
||||
}, this, 0, 0, 0, false);
|
||||
}
|
||||
|
||||
this._EventTargetOn(type, callback, target, useCapture);
|
||||
},
|
||||
|
||||
@@ -1188,6 +1252,10 @@ var Node = cc.Class({
|
||||
}
|
||||
}
|
||||
|
||||
if (_currentHovered === this) {
|
||||
_currentHovered = null;
|
||||
}
|
||||
|
||||
cc.eventManager.removeListener(this._mouseListener);
|
||||
this._mouseListener = null;
|
||||
}
|
||||
@@ -1211,7 +1279,7 @@ var Node = cc.Class({
|
||||
// find mask parent, should hit test it
|
||||
if (parent === mask.node) {
|
||||
var comp = parent.getComponent(cc.Mask);
|
||||
return (comp && comp.enabledInHierarchy) ? parent._hitTest(point) : true;
|
||||
return (comp && comp.enabledInHierarchy) ? comp._hitTest(point) : true;
|
||||
}
|
||||
// mask parent no longer exists
|
||||
else {
|
||||
@@ -1258,17 +1326,22 @@ var Node = cc.Class({
|
||||
/**
|
||||
* !#en
|
||||
* Executes an action, and returns the action that is executed.<br/>
|
||||
* The node becomes the action's target. Refer to cc.Action's getTarget()<br/>
|
||||
* Calling runAction while the node is not active won't have any effect.
|
||||
* The node becomes the action's target. Refer to cc.Action's getTarget() <br/>
|
||||
* Calling runAction while the node is not active won't have any effect. <br/>
|
||||
* Note:You shouldn't modify the action after runAction, that won't take any effect.<br/>
|
||||
* if you want to modify, when you define action plus.
|
||||
* !#zh
|
||||
* 执行并返回该执行的动作。该节点将会变成动作的目标。<br/>
|
||||
* 调用 runAction 时,节点自身处于不激活状态将不会有任何效果。
|
||||
* 调用 runAction 时,节点自身处于不激活状态将不会有任何效果。<br/>
|
||||
* 注意:你不应该修改 runAction 后的动作,将无法发挥作用,如果想进行修改,请在定义 action 时加入。
|
||||
* @method runAction
|
||||
* @param {Action} action
|
||||
* @return {Action} An Action pointer
|
||||
* @example
|
||||
* var action = cc.scaleTo(0.2, 1, 0.6);
|
||||
* node.runAction(action);
|
||||
* node.runAction(action).repeatForever(); // fail
|
||||
* node.runAction(action.repeatForever()); // right
|
||||
*/
|
||||
runAction: function (action) {
|
||||
if (!this.active)
|
||||
|
||||
+26
-47
@@ -38,15 +38,17 @@ cc.Scene = cc.Class({
|
||||
name: 'cc.Scene',
|
||||
extends: require('./utils/base-node'),
|
||||
|
||||
//properties: {
|
||||
// /**
|
||||
// * !#en Indicates the raw assets of this scene can be load after scene launched.
|
||||
// * !#zh 指示该场景依赖的资源可否在场景切换后再延迟加载。
|
||||
// * @property {Boolean} _asyncLoadAssets
|
||||
// * @default false
|
||||
// */
|
||||
// _asyncLoadAssets: false
|
||||
//},
|
||||
properties: {
|
||||
|
||||
/**
|
||||
* !#en Indicates whether all (directly or indirectly) static referenced assets of this scene are releasable by default after scene unloading.
|
||||
* !#zh 指示该场景中直接或间接静态引用到的所有资源是否默认在场景切换后自动释放。
|
||||
* @property {Boolean} autoReleaseAssets
|
||||
* @default false
|
||||
*/
|
||||
autoReleaseAssets: undefined,
|
||||
|
||||
},
|
||||
|
||||
ctor: function () {
|
||||
var sgNode = this._sgNode = new _ccsg.Scene();
|
||||
@@ -59,6 +61,9 @@ cc.Scene = cc.Class({
|
||||
|
||||
this._activeInHierarchy = false;
|
||||
this._inited = !cc.game._isCloning;
|
||||
|
||||
// cache all depend assets for auto release
|
||||
this.dependAssets = null;
|
||||
},
|
||||
|
||||
destroy: function () {
|
||||
@@ -82,7 +87,18 @@ cc.Scene = cc.Class({
|
||||
|
||||
_load: function () {
|
||||
if ( ! this._inited) {
|
||||
this._onBatchCreated();
|
||||
|
||||
this._updateDummySgNode();
|
||||
|
||||
// deactivate ActionManager and EventManager by default
|
||||
cc.director.getActionManager().pauseTarget(this);
|
||||
cc.eventManager.pauseTarget(this);
|
||||
|
||||
var children = this._children;
|
||||
for (var i = 0, len = children.length; i < len; i++) {
|
||||
children[i]._onBatchCreated();
|
||||
}
|
||||
|
||||
this._inited = true;
|
||||
}
|
||||
},
|
||||
@@ -112,40 +128,3 @@ cc.Scene = cc.Class({
|
||||
});
|
||||
|
||||
module.exports = cc.Scene;
|
||||
|
||||
if (CC_DEV) {
|
||||
var ERR = '"%s" is not defined in the Scene, it is only defined in child nodes.';
|
||||
Object.defineProperties(cc.Scene.prototype, {
|
||||
active: {
|
||||
get: function () {
|
||||
cc.error(ERR, 'active');
|
||||
return true;
|
||||
},
|
||||
set: function () {
|
||||
cc.error(ERR, 'active');
|
||||
}
|
||||
},
|
||||
activeInHierarchy: {
|
||||
get: function () {
|
||||
cc.error(ERR, 'activeInHierarchy');
|
||||
return true;
|
||||
},
|
||||
},
|
||||
getComponent: {
|
||||
get: function () {
|
||||
cc.error(ERR, 'getComponent');
|
||||
return function () {
|
||||
return null;
|
||||
};
|
||||
}
|
||||
},
|
||||
addComponent: {
|
||||
get: function () {
|
||||
cc.error(ERR, 'addComponent');
|
||||
return function () {
|
||||
return null;
|
||||
};
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -55,10 +55,16 @@ var Prefab = cc.Class({
|
||||
},
|
||||
|
||||
_instantiate: function () {
|
||||
//if (this.data._prefab) {
|
||||
// prefab asset is always synced
|
||||
this.data._prefab._synced = true;
|
||||
//}
|
||||
|
||||
// instantiate
|
||||
var node = cc.instantiate(this.data);
|
||||
|
||||
if (CC_EDITOR || CC_TEST) {
|
||||
// This operation is not necessary, but some old prefab asset may not contain complete data.
|
||||
_Scene.PrefabUtils.linkPrefab(this, node);
|
||||
}
|
||||
|
||||
|
||||
@@ -35,14 +35,27 @@ var Scene = cc.Class({
|
||||
extends: cc.Asset,
|
||||
|
||||
properties: {
|
||||
|
||||
/**
|
||||
* @property {cc.Scene} scene
|
||||
* @default null
|
||||
*/
|
||||
scene: null,
|
||||
|
||||
/**
|
||||
* !#en Indicates the raw assets of this scene can be load after scene launched.
|
||||
* !#zh 指示该场景依赖的资源可否在场景切换后再延迟加载。
|
||||
* @property {Boolean} asyncLoadAssets
|
||||
* @default undefined
|
||||
* @default false
|
||||
*/
|
||||
asyncLoadAssets: undefined
|
||||
asyncLoadAssets: undefined,
|
||||
|
||||
//// backup prefab assets in editor
|
||||
//// {string} assetUuid: {cc.Node} rootInPrefab
|
||||
//_prefabDatas: {
|
||||
// default: null,
|
||||
// editorOnly: true
|
||||
//}
|
||||
},
|
||||
});
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ var SpriteAtlas = cc.Class({
|
||||
* Returns the sprite frame correspond to the given key in sprite atlas.
|
||||
* @method getSpriteFrame
|
||||
* @param {String} key
|
||||
* @returns {cc.SpriteFrame}
|
||||
* @returns {SpriteFrame}
|
||||
*/
|
||||
getSpriteFrame: function (key) {
|
||||
return this._spriteFrames[key];
|
||||
@@ -68,7 +68,7 @@ var SpriteAtlas = cc.Class({
|
||||
/**
|
||||
* Returns the sprite frames in sprite atlas.
|
||||
* @method getSpriteFrames
|
||||
* @returns {[cc.SpriteFrame]}
|
||||
* @returns {[SpriteFrame]}
|
||||
*/
|
||||
getSpriteFrames: function () {
|
||||
var frames = [];
|
||||
|
||||
@@ -48,7 +48,7 @@ cc._tmp.PrototypeCCNode = function () {
|
||||
cc.defineGetterSetter(_p, "parent", _p.getParent, _p.setParent);
|
||||
cc.defineGetterSetter(_p, "visible", _p.isVisible, _p.setVisible);
|
||||
cc.defineGetterSetter(_p, "running", _p.isRunning);
|
||||
cc.defineGetterSetter(_p, "ignoreAnchor", _p.isIgnoreAnchorPointForPosition, _p.ignoreAnchorPointForPosition);
|
||||
cc.defineGetterSetter(_p, "ignoreAnchor", _p.isIgnoreAnchorPointForPosition, _p.setIgnoreAnchorPointForPosition);
|
||||
cc.defineGetterSetter(_p, "actionManager", _p.getActionManager, _p.setActionManager);
|
||||
cc.defineGetterSetter(_p, "scheduler", _p.getScheduler, _p.setScheduler);
|
||||
//cc.defineGetterSetter(_p, "boundingBox", _p.getBoundingBox);
|
||||
|
||||
@@ -286,7 +286,7 @@ cc.js.addon(_p, EventTarget.prototype);
|
||||
/**
|
||||
* Creates a cc.AtlasNode with an Atlas file the width and height of each item and the quantity of items to render
|
||||
* @deprecated since v3.0, please use new construction instead
|
||||
* @function
|
||||
* @method create
|
||||
* @static
|
||||
* @param {String} tile
|
||||
* @param {Number} tileWidth
|
||||
|
||||
@@ -161,7 +161,7 @@ _ccsg.Node = cc.Class({
|
||||
this._running = false;
|
||||
this._reorderChildDirty = false;
|
||||
this._shaderProgram = null;
|
||||
this.arrivalOrder = 0;
|
||||
this._arrivalOrder = 0;
|
||||
|
||||
this._additionalTransformDirty = false;
|
||||
this._isTransitionFinished = false;
|
||||
@@ -867,7 +867,8 @@ _ccsg.Node = cc.Class({
|
||||
*/
|
||||
setParent: function (parent) {
|
||||
this._parent = parent;
|
||||
this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty);
|
||||
var dirtyFlags = _ccsg.Node._dirtyFlags;
|
||||
this._renderCmd.setDirtyFlag(dirtyFlags.transformDirty | dirtyFlags.opacityDirty);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -891,7 +892,7 @@ _ccsg.Node = cc.Class({
|
||||
* @function
|
||||
* @param {Boolean} newValue true if anchor point will be ignored when you position this node
|
||||
*/
|
||||
ignoreAnchorPointForPosition: function (newValue) {
|
||||
setIgnoreAnchorPointForPosition: function (newValue) {
|
||||
if (newValue !== this._ignoreAnchorPointForPosition) {
|
||||
this._ignoreAnchorPointForPosition = newValue;
|
||||
this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.transformDirty);
|
||||
@@ -957,28 +958,18 @@ _ccsg.Node = cc.Class({
|
||||
return this._name;
|
||||
},
|
||||
|
||||
/**
|
||||
* Returns the arrival order, indicates which children should be added previously.
|
||||
* @function
|
||||
* @return {Number} The arrival order.
|
||||
*/
|
||||
getOrderOfArrival: function () {
|
||||
return this.arrivalOrder;
|
||||
},
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sets the arrival order when this node has a same ZOrder with other children. <br/>
|
||||
* Update the arrival order. <br/>
|
||||
* <br/>
|
||||
* A node which called addChild subsequently will take a larger arrival order, <br/>
|
||||
* If two children have the same Z order, the child with larger arrival order will be drawn later.
|
||||
* </p>
|
||||
* @function
|
||||
* @warning This method is used internally for zOrder sorting, don't change this manually
|
||||
* @param {Number} Var The arrival order.
|
||||
* @warning This method is used internally for zOrder sorting, don't call this method manually
|
||||
*/
|
||||
setOrderOfArrival: function (Var) {
|
||||
this.arrivalOrder = Var;
|
||||
updateOrderOfArrival: function () {
|
||||
this._arrivalOrder = ++cc.s_globalOrderOfArrival;
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -1153,7 +1144,7 @@ _ccsg.Node = cc.Class({
|
||||
child.setName(name);
|
||||
|
||||
child.setParent(this);
|
||||
child.setOrderOfArrival(cc.s_globalOrderOfArrival++);
|
||||
child.updateOrderOfArrival();
|
||||
|
||||
if( this._running ){
|
||||
child.onEnter();
|
||||
@@ -1318,8 +1309,7 @@ _ccsg.Node = cc.Class({
|
||||
reorderChild: function (child, zOrder) {
|
||||
cc.assert(child, cc._LogInfos.Node.reorderChild);
|
||||
cc.renderer.childrenOrderDirty = this._reorderChildDirty = true;
|
||||
child.arrivalOrder = cc.s_globalOrderOfArrival;
|
||||
cc.s_globalOrderOfArrival++;
|
||||
child.updateOrderOfArrival();
|
||||
child._setLocalZOrder(zOrder);
|
||||
this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.orderDirty);
|
||||
},
|
||||
@@ -1346,7 +1336,7 @@ _ccsg.Node = cc.Class({
|
||||
while(j >= 0){
|
||||
if(tmp._localZOrder < _children[j]._localZOrder){
|
||||
_children[j+1] = _children[j];
|
||||
}else if(tmp._localZOrder === _children[j]._localZOrder && tmp.arrivalOrder < _children[j].arrivalOrder){
|
||||
}else if(tmp._localZOrder === _children[j]._localZOrder && tmp._arrivalOrder < _children[j]._arrivalOrder){
|
||||
_children[j+1] = _children[j];
|
||||
}else{
|
||||
break;
|
||||
|
||||
@@ -208,10 +208,10 @@ _ccsg.Node.RenderCmd.prototype = {
|
||||
skx = 99999999;
|
||||
if (sky === Infinity)
|
||||
sky = 99999999;
|
||||
t.a = a + b * sky;
|
||||
t.b = b + a * sky;
|
||||
t.c = c + d * skx;
|
||||
t.d = d + c * skx;
|
||||
t.a = a + c * sky;
|
||||
t.b = b + d * sky;
|
||||
t.c = c + a * skx;
|
||||
t.d = d + b * skx;
|
||||
}
|
||||
|
||||
if (appX || appY) {
|
||||
@@ -448,16 +448,22 @@ _ccsg.Node.RenderCmd.prototype = {
|
||||
var locFlag = this._dirtyFlag;
|
||||
var colorDirty = locFlag & dirtyFlags.colorDirty,
|
||||
opacityDirty = locFlag & dirtyFlags.opacityDirty;
|
||||
if(colorDirty)
|
||||
|
||||
if (locFlag & dirtyFlags.contentDirty) {
|
||||
this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty);
|
||||
this._dirtyFlag &= ~dirtyFlags.contentDirty;
|
||||
}
|
||||
|
||||
if (colorDirty)
|
||||
this._updateDisplayColor();
|
||||
|
||||
if(opacityDirty)
|
||||
if (opacityDirty)
|
||||
this._updateDisplayOpacity();
|
||||
|
||||
if(colorDirty || opacityDirty)
|
||||
if (colorDirty || opacityDirty)
|
||||
this._updateColor();
|
||||
|
||||
if(locFlag & dirtyFlags.transformDirty){
|
||||
if (locFlag & dirtyFlags.transformDirty) {
|
||||
//update the transform
|
||||
this.transform(this.getParentRenderCmd(), true);
|
||||
this._dirtyFlag &= ~dirtyFlags.transformDirty;
|
||||
@@ -481,7 +487,7 @@ _ccsg.Node.RenderCmd.prototype = {
|
||||
//update the opacity
|
||||
this._syncDisplayOpacity();
|
||||
|
||||
if(colorDirty)
|
||||
if (colorDirty || opacityDirty)
|
||||
this._updateColor();
|
||||
|
||||
if (transformDirty)
|
||||
|
||||
@@ -91,8 +91,9 @@ function alignToParent (node, widget) {
|
||||
else {
|
||||
width = node.width * scaleX;
|
||||
if (widget.isAlignHorizontalCenter) {
|
||||
var parentCenter = (0.5 - parentAnchor.x) * parentWidth; // no offset
|
||||
x = parentCenter + (anchorX - 0.5) * width;
|
||||
var localHorizontalCenter = widget._isAbsHorizontalCenter ? widget._horizontalCenter : widget._horizontalCenter * parentWidth;
|
||||
var parentCenter = (0.5 - parentAnchor.x) * parentWidth;
|
||||
x = parentCenter + (anchorX - 0.5) * width + localHorizontalCenter;
|
||||
}
|
||||
else if (widget.isAlignLeft) {
|
||||
x = localLeft + anchorX * width;
|
||||
@@ -137,8 +138,9 @@ function alignToParent (node, widget) {
|
||||
else {
|
||||
height = node.height * scaleY;
|
||||
if (widget.isAlignVerticalCenter) {
|
||||
var parentMiddle = (0.5 - parentAnchor.y) * parentHeight; // no offset
|
||||
y = parentMiddle + (anchorY - 0.5) * height;
|
||||
var localVerticalCenter = widget._isAbsVerticalCenter ? widget._verticalCenter : widget._verticalCenter * parentHeight;
|
||||
var parentMiddle = (0.5 - parentAnchor.y) * parentHeight;
|
||||
y = parentMiddle + (anchorY - 0.5) * height + localVerticalCenter;
|
||||
}
|
||||
else if (widget.isAlignBottom) {
|
||||
y = localBottom + anchorY * height;
|
||||
@@ -156,7 +158,7 @@ function visitNode (node) {
|
||||
var widget = node._widget;
|
||||
if (widget) {
|
||||
alignToParent(node, widget);
|
||||
if ((!CC_EDITOR || _Scene.AnimUtils.curAnimState) && widget.isAlignOnce) {
|
||||
if ((!CC_EDITOR || animationState.animatedSinceLastFrame) && widget.isAlignOnce) {
|
||||
widget.enabled = false;
|
||||
}
|
||||
else {
|
||||
@@ -172,7 +174,34 @@ function visitNode (node) {
|
||||
}
|
||||
}
|
||||
|
||||
if (CC_EDITOR) {
|
||||
var animationState = {
|
||||
previewing: false,
|
||||
time: 0,
|
||||
animatedSinceLastFrame: false,
|
||||
};
|
||||
}
|
||||
|
||||
function refreshScene () {
|
||||
// check animation editor
|
||||
if (CC_EDITOR && window._Scene && _Scene.AnimUtils) {
|
||||
var nowPreviewing = !!_Scene.AnimUtils.curAnimState;
|
||||
if (nowPreviewing !== animationState.previewing) {
|
||||
animationState.previewing = nowPreviewing;
|
||||
if (nowPreviewing) {
|
||||
animationState.animatedSinceLastFrame = true;
|
||||
animationState.time = _Scene.AnimUtils.curAnimState.time;
|
||||
}
|
||||
else {
|
||||
animationState.animatedSinceLastFrame = false;
|
||||
}
|
||||
}
|
||||
else if (nowPreviewing && animationState.time !== _Scene.AnimUtils.curAnimState.time) {
|
||||
animationState.animatedSinceLastFrame = true;
|
||||
animationState.time = _Scene.AnimUtils.curAnimState.time;
|
||||
}
|
||||
}
|
||||
|
||||
var scene = cc.director.getScene();
|
||||
if (scene) {
|
||||
widgetManager.isAligning = true;
|
||||
@@ -180,14 +209,15 @@ function refreshScene () {
|
||||
widgetManager._nodesWithWidget.length = 0;
|
||||
visitNode(scene);
|
||||
widgetManager._nodesOrderDirty = false;
|
||||
} else {
|
||||
}
|
||||
else {
|
||||
var i, node, nodes = widgetManager._nodesWithWidget, len = nodes.length;
|
||||
if (CC_EDITOR && _Scene.AnimUtils.curAnimState) {
|
||||
// always check isAlignOnce because animation mode maybe changed
|
||||
if (CC_EDITOR && window._Scene && _Scene.AnimUtils && _Scene.AnimUtils.curAnimState) {
|
||||
var editingNode = _Scene.AnimUtils.curRootNode;
|
||||
for (i = len - 1; i >= 0; i--) {
|
||||
node = nodes[i];
|
||||
var widget = node._widget;
|
||||
if (widget.isAlignOnce) {
|
||||
if (widget.isAlignOnce && animationState.animatedSinceLastFrame && node.isChildOf(editingNode)) {
|
||||
// widget contains in _nodesWithWidget should aligned at least once
|
||||
widget.enabled = false;
|
||||
}
|
||||
@@ -206,6 +236,10 @@ function refreshScene () {
|
||||
widgetManager.isAligning = false;
|
||||
}
|
||||
|
||||
// check animation editor
|
||||
if (CC_EDITOR) {
|
||||
animationState.animatedSinceLastFrame = false;
|
||||
}
|
||||
}
|
||||
|
||||
var adjustWidgetToAllowMovingInEditor = CC_EDITOR && function (event) {
|
||||
@@ -237,14 +271,10 @@ var adjustWidgetToAllowMovingInEditor = CC_EDITOR && function (event) {
|
||||
this.right -= (this.isAbsoluteRight ? delta.x : deltaInPercent.x);
|
||||
}
|
||||
if (this.isAlignHorizontalCenter) {
|
||||
if (oldPos.x !== newPos.x) {
|
||||
this.isAlignHorizontalCenter = false;
|
||||
}
|
||||
this.horizontalCenter += (this.isAbsoluteHorizontalCenter ? delta.x : deltaInPercent.x);
|
||||
}
|
||||
if (this.isAlignVerticalCenter) {
|
||||
if (oldPos.y !== newPos.y) {
|
||||
this.isAlignVerticalCenter = false;
|
||||
}
|
||||
this.verticalCenter += (this.isAbsoluteVerticalCenter ? delta.y : deltaInPercent.y);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -280,14 +310,10 @@ var adjustWidgetToAllowResizingInEditor = CC_EDITOR && function (event) {
|
||||
this.right -= (this.isAbsoluteRight ? delta.x : deltaInPercent.x) * (1 - anchor.x);
|
||||
}
|
||||
if (this.isAlignHorizontalCenter) {
|
||||
if (delta.x !== 0 && anchor.x !== 0.5) {
|
||||
this.isAlignHorizontalCenter = false;
|
||||
}
|
||||
this.horizontalCenter -= (this.isAbsoluteHorizontalCenter ? delta.x : deltaInPercent.x);
|
||||
}
|
||||
if (this.isAlignVerticalCenter) {
|
||||
if (delta.y !== 0 && anchor.y !== 0.5) {
|
||||
this.isAlignVerticalCenter = false;
|
||||
}
|
||||
this.verticalCenter -= (this.isAbsoluteVerticalCenter ? delta.y : deltaInPercent.y);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -400,7 +400,7 @@ cc.js.getset(CollisionManager.prototype, 'enabledDebugDraw',
|
||||
}
|
||||
else if (!value && this._enabledDebugDraw) {
|
||||
this._debugDrawer.clear();
|
||||
cc.director.getScene()._sgNode.removeChild(this._debugDrawer);
|
||||
this._debugDrawer.removeFromParent(false);
|
||||
cc.director.off(cc.Director.EVENT_AFTER_SCENE_LAUNCH, this.onSceneLaunched, this);
|
||||
}
|
||||
|
||||
|
||||
@@ -36,7 +36,25 @@ function equalClips (clip1, clip2) {
|
||||
|
||||
/**
|
||||
* !#en The animation component is used to play back animations.
|
||||
*
|
||||
* Animation provide several events to register:
|
||||
* - play : Emit when egine playing animation
|
||||
* - stop : Emit when stop playing animation
|
||||
* - pause : Emit when pause animation
|
||||
* - resume : Emit when resume animation
|
||||
* - lastframe : If animation repeat coutn is larger than 1, emit when animation play to the last frame
|
||||
* - finished : Emit when finish playing animation
|
||||
*
|
||||
* !#zh Animation 组件用于播放动画。你能指定动画剪辑到动画组件并从脚本控制播放。
|
||||
*
|
||||
* Animation 提供了一系列可注册的事件:
|
||||
* - play : 开始播放时
|
||||
* - stop : 停止播放时
|
||||
* - pause : 暂停播放时
|
||||
* - resume : 恢复播放时
|
||||
* - lastframe : 假如动画循环次数大于 1,当动画播放到最后一帧时
|
||||
* - finished : 动画播放完成时
|
||||
*
|
||||
* @class Animation
|
||||
* @extends CCComponent
|
||||
*/
|
||||
@@ -58,6 +76,8 @@ var Animation = cc.Class({
|
||||
this._didInit = false;
|
||||
|
||||
this._currentClip = null;
|
||||
|
||||
this._listeners = [];
|
||||
},
|
||||
|
||||
properties: {
|
||||
@@ -146,19 +166,16 @@ var Animation = cc.Class({
|
||||
}
|
||||
},
|
||||
|
||||
__preload: function () {
|
||||
if (CC_EDITOR) return;
|
||||
onEnable: function () {
|
||||
if (!CC_EDITOR && this.playOnLoad && this._defaultClip) {
|
||||
this.playOnLoad = false;
|
||||
|
||||
this._init();
|
||||
|
||||
if (this.playOnLoad && this._defaultClip) {
|
||||
var state = this.getAnimationState(this._defaultClip.name);
|
||||
this._animator.playState(state);
|
||||
}
|
||||
},
|
||||
|
||||
onEnable: function () {
|
||||
this.resume();
|
||||
else {
|
||||
this.resume();
|
||||
}
|
||||
},
|
||||
|
||||
onDisable: function () {
|
||||
@@ -471,6 +488,98 @@ var Animation = cc.Class({
|
||||
this._animator.sample();
|
||||
},
|
||||
|
||||
|
||||
/**
|
||||
* !#en
|
||||
* Register animation event callback.
|
||||
* The event argumetns will provide the AnimationState which emit the event.
|
||||
* When play an animation, will auto register the event callback to the AnimationState, and unregister the event callback from the AnimationState when animation stopped.
|
||||
* !#zh
|
||||
* 注册动画事件回调。
|
||||
* 回调的事件里将会附上发送事件的 AnimationState。
|
||||
* 当播放一个动画时,会自动将事件注册到对应的 AnimationState 上,停止播放时会将事件从这个 AnimationState 上取消注册。
|
||||
* @method on
|
||||
* @param {String} type - A string representing the event type to listen for.
|
||||
* @param {Function} callback - The callback that will be invoked when the event is dispatched.
|
||||
* The callback is ignored if it is a duplicate (the callbacks are unique).
|
||||
* @param {Event} callback.param event
|
||||
* @param {Object} target - The target to invoke the callback, can be null
|
||||
* @param {Boolean} useCapture - When set to true, the capture argument prevents callback
|
||||
* from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE.
|
||||
* When false, callback will NOT be invoked when event's eventPhase attribute value is CAPTURING_PHASE.
|
||||
* Either way, callback will be invoked when event's eventPhase attribute value is AT_TARGET.
|
||||
*
|
||||
* @example
|
||||
* onPlay: function (event) {
|
||||
* var state = event.detail; // state instanceof cc.AnimationState
|
||||
* var type = event.type; // type === 'play';
|
||||
* }
|
||||
*
|
||||
* // register event to all animation
|
||||
* animation.on('', 'play', this.onPlay, this);
|
||||
*/
|
||||
on: function (type, callback, target, useCapture) {
|
||||
this._init();
|
||||
var listeners = this._listeners;
|
||||
|
||||
for (var i = 0, l = listeners.length; i < l; i++) {
|
||||
var listener = listeners[i];
|
||||
if (listener[0] === type &&
|
||||
listener[1] === callback &&
|
||||
listener[2] === target &&
|
||||
listener[3] === useCapture) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
var anims = this._animator.playingAnims;
|
||||
for (var j = 0, jj = anims.length; j < jj; j++) {
|
||||
anims[j].on(type, callback, target, useCapture);
|
||||
}
|
||||
|
||||
listeners.push([type, callback, target, useCapture]);
|
||||
},
|
||||
|
||||
|
||||
/**
|
||||
* !#en
|
||||
* Unregister animation event callback.
|
||||
* !#zh
|
||||
* 取消注册动画事件回调。
|
||||
* @method off
|
||||
* @param {String} type - A string representing the event type being removed.
|
||||
* @param {Function} callback - The callback to remove.
|
||||
* @param {Object} target - The target to invoke the callback, if it's not given, only callback without target will be removed
|
||||
* @param {Boolean} useCapture - Specifies whether the callback being removed was registered as a capturing callback or not.
|
||||
* If not specified, useCapture defaults to false. If a callback was registered twice,
|
||||
* one with capture and one without, each must be removed separately. Removal of a capturing callback
|
||||
* does not affect a non-capturing version of the same listener, and vice versa.
|
||||
*
|
||||
* @example
|
||||
* // unregister event to all animation
|
||||
* animation.off('', 'play', this.onPlay, this);
|
||||
*/
|
||||
off: function (type, callback, target, useCapture) {
|
||||
this._init();
|
||||
var listeners = this._listeners;
|
||||
|
||||
for (var i = listeners.length - 1; i >= 0; i--) {
|
||||
var listener = listeners[i];
|
||||
if (listener[0] === type &&
|
||||
listener[1] === callback &&
|
||||
listener[2] === target &&
|
||||
listener[3] === useCapture) {
|
||||
|
||||
var anims = this._animator.playingAnims;
|
||||
for (var j = 0, jj = anims.length; j < jj; j++) {
|
||||
anims[j].off(type, callback, target, useCapture);
|
||||
}
|
||||
|
||||
listeners.splice(i, 1);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
// Internal Methods
|
||||
///////////////////////////////////////////////////////////////////////////////
|
||||
@@ -520,5 +629,4 @@ var Animation = cc.Class({
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
cc.Animation = module.exports = Animation;
|
||||
|
||||
@@ -30,9 +30,6 @@
|
||||
* @extends Component
|
||||
*/
|
||||
|
||||
// todo jsb 中无法针对单独的音效对象进行设置(如音量大小等)
|
||||
|
||||
var audioEngine = cc.audioEngine;
|
||||
|
||||
var AudioSource = cc.Class({
|
||||
name: 'cc.AudioSource',
|
||||
@@ -44,7 +41,7 @@ var AudioSource = cc.Class({
|
||||
},
|
||||
|
||||
ctor: function () {
|
||||
this.audio = null;
|
||||
this.audio = new cc.Audio();
|
||||
},
|
||||
|
||||
properties: {
|
||||
@@ -70,7 +67,9 @@ var AudioSource = cc.Class({
|
||||
*/
|
||||
isPlaying: {
|
||||
get: function () {
|
||||
return (!cc.sys.isNative && this.audio && this.audio.getPlaying());
|
||||
if (!this.audio) return false;
|
||||
var state = this.audio.getState();
|
||||
return state === cc.Audio.State.PLAYING;
|
||||
},
|
||||
visible: false
|
||||
},
|
||||
@@ -88,6 +87,10 @@ var AudioSource = cc.Class({
|
||||
},
|
||||
set: function (value) {
|
||||
this._clip = value;
|
||||
this.audio.src = this._clip;
|
||||
if (this.audio.preload) {
|
||||
this.audio.preload();
|
||||
}
|
||||
},
|
||||
url: cc.AudioClip,
|
||||
tooltip: 'i18n:COMPONENT.audio.clip',
|
||||
@@ -107,14 +110,10 @@ var AudioSource = cc.Class({
|
||||
},
|
||||
set: function (value) {
|
||||
this._volume = value;
|
||||
if (this.audio) {
|
||||
if (cc.sys.isNative) {
|
||||
cc.audioEngine.setEffectsVolume(value);
|
||||
}
|
||||
else {
|
||||
this.audio.setVolume(value);
|
||||
}
|
||||
if (this.audio && !this._mute) {
|
||||
this.audio.setVolume(value);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
tooltip: 'i18n:COMPONENT.audio.volume'
|
||||
},
|
||||
@@ -133,20 +132,9 @@ var AudioSource = cc.Class({
|
||||
set: function (value) {
|
||||
this._mute = value;
|
||||
if (this.audio) {
|
||||
if (this._mute) {
|
||||
if (CC_JSB) {
|
||||
cc.audioEngine.setEffectsVolume(0);
|
||||
} else {
|
||||
this.audio.setVolume(0);
|
||||
}
|
||||
} else {
|
||||
if (CC_JSB) {
|
||||
cc.audioEngine.setEffectsVolume(this._volume);
|
||||
} else {
|
||||
this.audio.setVolume(this._volume);
|
||||
}
|
||||
}
|
||||
this.audio.setVolume(value ? 0 : this._volume);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
animatable: false,
|
||||
tooltip: 'i18n:COMPONENT.audio.mute',
|
||||
@@ -165,7 +153,10 @@ var AudioSource = cc.Class({
|
||||
},
|
||||
set: function (value) {
|
||||
this._loop = value;
|
||||
if (this.audio) this.audio.loop = this._loop;
|
||||
if (this.audio) {
|
||||
this.audio.setLoop(value);
|
||||
}
|
||||
return value;
|
||||
},
|
||||
animatable: false,
|
||||
tooltip: 'i18n:COMPONENT.audio.loop'
|
||||
@@ -197,6 +188,7 @@ var AudioSource = cc.Class({
|
||||
|
||||
onDestroy: function () {
|
||||
this.stop();
|
||||
audioEngine.uncache(this._clip);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -205,14 +197,17 @@ var AudioSource = cc.Class({
|
||||
* @method play
|
||||
*/
|
||||
play: function () {
|
||||
if ( this._clip ) {
|
||||
var volume = this._mute ? 0 : this._volume;
|
||||
this.audio = audioEngine.playEffect(this._clip, this._loop, volume);
|
||||
if ( !this._clip ) return;
|
||||
|
||||
if (CC_JSB) {
|
||||
cc.audioEngine.setEffectsVolume(volume);
|
||||
}
|
||||
}
|
||||
var volume = this._mute ? 0 : this._volume;
|
||||
var audio = this.audio;
|
||||
audio.src = this._clip;
|
||||
audio.setLoop(this._loop);
|
||||
audio.setVolume(volume);
|
||||
audio.once('load', function () {
|
||||
audio.play();
|
||||
});
|
||||
audio.preload();
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -221,7 +216,9 @@ var AudioSource = cc.Class({
|
||||
* @method stop
|
||||
*/
|
||||
stop: function () {
|
||||
if ( this.audio ) cc.audioEngine.stopEffect(this.audio);
|
||||
if (this.audio) {
|
||||
this.audio.stop();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -230,7 +227,9 @@ var AudioSource = cc.Class({
|
||||
* @method pause
|
||||
*/
|
||||
pause: function () {
|
||||
if ( this.audio ) cc.audioEngine.pauseEffect(this.audio);
|
||||
if (this.audio) {
|
||||
this.audio.pause();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -239,7 +238,9 @@ var AudioSource = cc.Class({
|
||||
* @method resume
|
||||
*/
|
||||
resume: function () {
|
||||
if ( this.audio ) cc.audioEngine.resumeEffect(this.audio);
|
||||
if (this.audio) {
|
||||
this.audio.resume();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -248,11 +249,10 @@ var AudioSource = cc.Class({
|
||||
* @method rewind
|
||||
*/
|
||||
rewind: function(){
|
||||
if ( this.audio ) {
|
||||
this.stop();
|
||||
this.play();
|
||||
if (this.audio) {
|
||||
this.audio.setCurrentTime(0);
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
|
||||
@@ -47,7 +47,13 @@ var Transition = cc.Enum({
|
||||
* !#zh 精灵过渡
|
||||
* @property {Number} SPRITE
|
||||
*/
|
||||
SPRITE: 2
|
||||
SPRITE: 2,
|
||||
/**
|
||||
* !#en The scale type
|
||||
* !#zh 缩放过渡
|
||||
* @property {Number} SCALE
|
||||
*/
|
||||
SCALE: 3
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -103,6 +109,15 @@ var Button = cc.Class({
|
||||
|
||||
ctor: function () {
|
||||
this._resetState();
|
||||
|
||||
this._fromColor = null;
|
||||
this._toColor = null;
|
||||
this._time = 0;
|
||||
this._transitionFinished = true;
|
||||
this._fromScale = 1.0;
|
||||
this._toScale = 1.0;
|
||||
this._originalScale = 1.0;
|
||||
|
||||
this._sprite = null;
|
||||
|
||||
if(CC_EDITOR) {
|
||||
@@ -114,10 +129,6 @@ var Button = cc.Class({
|
||||
this._pressed = false;
|
||||
this._hovered = false;
|
||||
|
||||
this._fromColor = null;
|
||||
this._toColor = null;
|
||||
this._time = 0;
|
||||
this._transitionFinished = true;
|
||||
},
|
||||
|
||||
editor: CC_EDITOR && {
|
||||
@@ -157,6 +168,28 @@ var Button = cc.Class({
|
||||
animatable: false
|
||||
},
|
||||
|
||||
_resizeToTarget: {
|
||||
animatable: false,
|
||||
set: function (value) {
|
||||
if(value) {
|
||||
this._resizeNodeToTargetNode();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en When this flag is true, Button target sprite will turn gray when interactable is false.
|
||||
* !#zh 如果这个标记为 true,当 button 的 interactable 属性为 false 的时候,会使用内置 shader 让 button 的 target 节点的 sprite 组件变灰
|
||||
* @property {Boolean} enableAutoGrayEffect
|
||||
*/
|
||||
enableAutoGrayEffect: {
|
||||
default: true,
|
||||
tooltip: 'i18n:COMPONENT.button.auto_gray_effect',
|
||||
notify: function () {
|
||||
this._updateDisabledState();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Transition type
|
||||
* !#zh 按钮状态改变时过渡方式。
|
||||
@@ -216,15 +249,15 @@ var Button = cc.Class({
|
||||
disabledColor: {
|
||||
default: cc.color(124, 124, 124),
|
||||
displayName: 'Disabled',
|
||||
tooltip: 'i18n:COMPONENT.button.diabled_color',
|
||||
tooltip: 'i18n:COMPONENT.button.disabled_color',
|
||||
notify: function () {
|
||||
this._updateState();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Color transition duration
|
||||
* !#zh 颜色过渡时所需时间
|
||||
* !#en Color and Scale transition duration
|
||||
* !#zh 颜色过渡和缩放过渡时所需时间
|
||||
* @property {Number} duration
|
||||
*/
|
||||
duration: {
|
||||
@@ -233,6 +266,17 @@ var Button = cc.Class({
|
||||
tooltip: 'i18n:COMPONENT.button.duration',
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en When user press the button, the button will zoom to a scale.
|
||||
* The final scale of the button equals (button original scale * zoomScale)
|
||||
* !#zh 当用户点击按钮后,按钮会缩放到一个值,这个值等于 Button 原始 scale * zoomScale
|
||||
* @property {Number} zoomScale
|
||||
*/
|
||||
zoomScale: {
|
||||
default: 0.1,
|
||||
tooltip: 'i18n:COMPONENT.button.zoom_scale'
|
||||
},
|
||||
|
||||
// sprite transition
|
||||
/**
|
||||
* !#en Normal state sprite
|
||||
@@ -297,10 +341,10 @@ var Button = cc.Class({
|
||||
* If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite
|
||||
* !#zh
|
||||
* 需要过渡的目标。
|
||||
* 当前按钮状态改变有:
|
||||
* 当前按钮状态改变规则:
|
||||
* -如果 Transition type 选择 Button.Transition.NONE,按钮不做任何过渡。
|
||||
* -如果 Transition type 选择 Button.Transition.COLOR,按钮会对目标颜色进行颜色之间的过渡。
|
||||
* -如果 Transition type 选择 Button.Transition.NONE,按钮会对目标 Sprite 进行 Sprite 之间的过渡。
|
||||
* -如果 Transition type 选择 Button.Transition.Sprite,按钮会对目标 Sprite 进行 Sprite 之间的过渡。
|
||||
* @property {Node} target
|
||||
*/
|
||||
target: {
|
||||
@@ -360,23 +404,33 @@ var Button = cc.Class({
|
||||
}
|
||||
},
|
||||
|
||||
start: function () {
|
||||
onLoad: function () {
|
||||
this._applyTarget();
|
||||
this._updateState();
|
||||
},
|
||||
|
||||
update: function (dt) {
|
||||
var target = this.target;
|
||||
if (!this.transition === Transition.COLOR || !target || this._transitionFinished) return;
|
||||
if (this.transition !== Transition.COLOR || this.transition !== Transition.SCALE
|
||||
|| !target || this._transitionFinished) return;
|
||||
|
||||
this.time += dt;
|
||||
var ratio = this.time / this.duration;
|
||||
if (ratio > 1) {
|
||||
var ratio = 1.0;
|
||||
if(this.duration > 0) {
|
||||
ratio = this.time / this.duration;
|
||||
}
|
||||
|
||||
if (ratio >= 1) {
|
||||
ratio = 1;
|
||||
this._transitionFinished = true;
|
||||
}
|
||||
|
||||
target.color = this._fromColor.lerp(this._toColor, ratio);
|
||||
if(this.transition === Transition.COLOR) {
|
||||
target.color = this._fromColor.lerp(this._toColor, ratio);
|
||||
} else if (this.transition === Transition.SCALE) {
|
||||
target.scale = cc.lerp(this._fromScale, this._toScale, ratio);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
_registerEvent: function () {
|
||||
@@ -393,6 +447,7 @@ var Button = cc.Class({
|
||||
var target = this.target;
|
||||
if (target) {
|
||||
this._sprite = target.getComponent(cc.Sprite);
|
||||
this._originalScale = target.scale;
|
||||
}
|
||||
else {
|
||||
this._sprite = null;
|
||||
@@ -404,7 +459,11 @@ var Button = cc.Class({
|
||||
if (!this.interactable || !this.enabledInHierarchy) return;
|
||||
|
||||
this._pressed = true;
|
||||
this._updateState();
|
||||
if(this.transition === Transition.SCALE) {
|
||||
this._zoomUp();
|
||||
} else {
|
||||
this._updateState();
|
||||
}
|
||||
event.stopPropagation();
|
||||
},
|
||||
|
||||
@@ -414,16 +473,24 @@ var Button = cc.Class({
|
||||
// so we have to do hit test when touch moving
|
||||
var touch = event.touch;
|
||||
var hit = this.node._hitTest(touch.getLocation());
|
||||
var state;
|
||||
if (hit) {
|
||||
state = 'pressed';
|
||||
} else {
|
||||
state = 'normal';
|
||||
}
|
||||
var color = this[state + 'Color'];
|
||||
var sprite = this[state + 'Sprite'];
|
||||
|
||||
this._applyTransition(color, sprite);
|
||||
if(this.transition === Transition.SCALE && this.target) {
|
||||
if(hit) {
|
||||
this.target.scale = this._originalScale * this.zoomScale;
|
||||
} else {
|
||||
this.target.scale = this._originalScale;
|
||||
}
|
||||
} else {
|
||||
var state;
|
||||
if (hit) {
|
||||
state = 'pressed';
|
||||
} else {
|
||||
state = 'normal';
|
||||
}
|
||||
var color = this[state + 'Color'];
|
||||
var sprite = this[state + 'Sprite'];
|
||||
this._applyTransition(color, sprite);
|
||||
}
|
||||
event.stopPropagation();
|
||||
},
|
||||
|
||||
@@ -434,19 +501,38 @@ var Button = cc.Class({
|
||||
cc.Component.EventHandler.emitEvents(this.clickEvents, event);
|
||||
}
|
||||
this._pressed = false;
|
||||
this._updateState();
|
||||
if(this.transition === Transition.SCALE) {
|
||||
this._zoomBack();
|
||||
} else {
|
||||
this._updateState();
|
||||
}
|
||||
event.stopPropagation();
|
||||
},
|
||||
|
||||
_zoomUp: function () {
|
||||
this._fromScale = this._originalScale;
|
||||
this._toScale = this._originalScale * this.zoomScale;
|
||||
this.time = 0;
|
||||
this._transitionFinished = false;
|
||||
},
|
||||
|
||||
_zoomBack: function () {
|
||||
this._fromScale = this._originalScale * this.zoomScale;
|
||||
this._toScale = this._originalScale;
|
||||
this.time = 0;
|
||||
this._transitionFinished = false;
|
||||
},
|
||||
|
||||
_onTouchCancel: function () {
|
||||
if (!this.interactable || !this.enabledInHierarchy) return;
|
||||
|
||||
this._pressed = false;
|
||||
|
||||
this._updateState();
|
||||
},
|
||||
|
||||
_onMouseMoveIn: function () {
|
||||
if (this._pressed || !this.interactable || !this.enabledInHierarchy) return;
|
||||
if (!this.hoverSprite || this._pressed || !this.interactable || !this.enabledInHierarchy) return;
|
||||
|
||||
if (!this._hovered) {
|
||||
this._hovered = true;
|
||||
@@ -480,6 +566,7 @@ var Button = cc.Class({
|
||||
var sprite = this[state + 'Sprite'];
|
||||
|
||||
this._applyTransition(color, sprite);
|
||||
this._updateDisabledState();
|
||||
},
|
||||
|
||||
onDisable: function() {
|
||||
@@ -520,6 +607,25 @@ var Button = cc.Class({
|
||||
}
|
||||
},
|
||||
|
||||
_resizeNodeToTargetNode: CC_EDITOR && function () {
|
||||
if(this.target) {
|
||||
this.node.setContentSize(this.target.getContentSize());
|
||||
}
|
||||
},
|
||||
|
||||
_updateDisabledState: function () {
|
||||
if(this._sprite) {
|
||||
this._sprite._sgNode.setState(0);
|
||||
}
|
||||
if(this.enableAutoGrayEffect) {
|
||||
if(! (this.transition === Transition.SPRITE && this.disabledSprite)) {
|
||||
if(this._sprite && !this.interactable) {
|
||||
this._sprite._sgNode.setState(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
cc.Button = module.exports = Button;
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
|
||||
require('../platform/CCObject');
|
||||
require('../CCNode');
|
||||
var IdGenerater = require('../platform/id-generater');
|
||||
var idGenerater = new (require('../platform/id-generater'))('Comp');
|
||||
var Misc = require('../utils/misc');
|
||||
|
||||
var Flags = cc.Object.Flags;
|
||||
@@ -52,6 +52,48 @@ var callOnFocusInTryCatch = CC_EDITOR && eval(ExecInTryCatchTmpl.replace(/_FUNC_
|
||||
var callOnLostFocusInTryCatch = CC_EDITOR && eval(ExecInTryCatchTmpl.replace(/_FUNC_/g, 'onLostFocusInEditor'));
|
||||
|
||||
function callOnEnable (self, enable) {
|
||||
|
||||
if (!CC_EDITOR || (cc.engine.isPlaying || self.constructor._executeInEditMode) ) {
|
||||
var enableCalled = self._objFlags & IsOnEnableCalled;
|
||||
if (enable) {
|
||||
if (!enableCalled) {
|
||||
if (self.onEnable) {
|
||||
if (CC_EDITOR) {
|
||||
callOnEnableInTryCatch(self);
|
||||
}
|
||||
else {
|
||||
self.onEnable();
|
||||
}
|
||||
}
|
||||
|
||||
var deactivatedDuringOnEnable = !self.node._activeInHierarchy;
|
||||
if (deactivatedDuringOnEnable) {
|
||||
return;
|
||||
}
|
||||
|
||||
cc.director.getScheduler().resumeTarget(self);
|
||||
_registerEvent(self, true);
|
||||
|
||||
self._objFlags |= IsOnEnableCalled;
|
||||
}
|
||||
}
|
||||
else if (enableCalled) {
|
||||
if (self.onDisable) {
|
||||
if (CC_EDITOR) {
|
||||
callOnDisableInTryCatch(self);
|
||||
}
|
||||
else {
|
||||
self.onDisable();
|
||||
}
|
||||
}
|
||||
|
||||
cc.director.getScheduler().pauseTarget(self);
|
||||
_registerEvent(self, false);
|
||||
|
||||
self._objFlags &= ~IsOnEnableCalled;
|
||||
}
|
||||
}
|
||||
|
||||
if (CC_EDITOR) {
|
||||
if (enable) {
|
||||
if ( !(self._objFlags & IsEditorOnEnableCalled) ) {
|
||||
@@ -65,47 +107,6 @@ function callOnEnable (self, enable) {
|
||||
self._objFlags &= ~IsEditorOnEnableCalled;
|
||||
}
|
||||
}
|
||||
if ( !(cc.engine.isPlaying || self.constructor._executeInEditMode) ) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
var enableCalled = self._objFlags & IsOnEnableCalled;
|
||||
if (enable) {
|
||||
if (!enableCalled) {
|
||||
if (self.onEnable) {
|
||||
if (CC_EDITOR) {
|
||||
callOnEnableInTryCatch(self);
|
||||
}
|
||||
else {
|
||||
self.onEnable();
|
||||
}
|
||||
}
|
||||
|
||||
var deactivatedDuringOnEnable = !self.node._activeInHierarchy;
|
||||
if (deactivatedDuringOnEnable) {
|
||||
return;
|
||||
}
|
||||
|
||||
cc.director.getScheduler().resumeTarget(self);
|
||||
_registerEvent(self, true);
|
||||
|
||||
self._objFlags |= IsOnEnableCalled;
|
||||
}
|
||||
}
|
||||
else if (enableCalled) {
|
||||
if (self.onDisable) {
|
||||
if (CC_EDITOR) {
|
||||
callOnDisableInTryCatch(self);
|
||||
}
|
||||
else {
|
||||
self.onDisable();
|
||||
}
|
||||
}
|
||||
|
||||
cc.director.getScheduler().pauseTarget(self);
|
||||
_registerEvent(self, false);
|
||||
|
||||
self._objFlags &= ~IsOnEnableCalled;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -216,8 +217,6 @@ function _callPreloadOnComponent (component) {
|
||||
}
|
||||
}
|
||||
|
||||
var idGenerater = new IdGenerater('Comp');
|
||||
|
||||
/**
|
||||
* !#en
|
||||
* Base class for everything attached to Node(Entity).<br/>
|
||||
@@ -237,11 +236,13 @@ var Component = cc.Class({
|
||||
name: 'cc.Component',
|
||||
extends: cc.Object,
|
||||
|
||||
ctor: function () {
|
||||
if (CC_EDITOR && !CC_TEST && window._Scene) {
|
||||
ctor: CC_EDITOR ? function () {
|
||||
if (window._Scene && _Scene.AssetsWatcher) {
|
||||
_Scene.AssetsWatcher.initComponent(this);
|
||||
}
|
||||
|
||||
// Support for Scheduler
|
||||
this.__instanceId = cc.ClassManager.getNewInstanceId();
|
||||
} : function () {
|
||||
// Support for Scheduler
|
||||
this.__instanceId = cc.ClassManager.getNewInstanceId();
|
||||
},
|
||||
@@ -374,7 +375,7 @@ var Component = cc.Class({
|
||||
*/
|
||||
enabledInHierarchy: {
|
||||
get: function () {
|
||||
return this._objFlags & IsOnEnableCalled;
|
||||
return (this._objFlags & IsOnEnableCalled) > 0;
|
||||
},
|
||||
visible: false
|
||||
},
|
||||
@@ -550,8 +551,8 @@ var Component = cc.Class({
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Returns the components of supplied type in any of its children using depth first search.
|
||||
* !#zh 递归查找所有子节点中指定类型的组件。
|
||||
* !#en Returns the components of supplied type in self or any of its children using depth first search.
|
||||
* !#zh 递归查找自身或所有子节点中指定类型的组件
|
||||
*
|
||||
* @method getComponentsInChildren
|
||||
* @param {Function|String} typeOrClassName
|
||||
|
||||
@@ -80,6 +80,7 @@ cc.Component.EventHandler = cc.Class({
|
||||
/**
|
||||
* @method emitEvents
|
||||
* @param {Component.EventHandler[]} events
|
||||
* @param {any} ...params
|
||||
* @statics
|
||||
*/
|
||||
emitEvents: function(events) {
|
||||
@@ -88,7 +89,7 @@ cc.Component.EventHandler = cc.Class({
|
||||
var event = events[i];
|
||||
if (! event instanceof cc.Component.EventHandler) continue;
|
||||
|
||||
event.emit(Array.prototype.slice.call(arguments,1));
|
||||
event.emit(Array.prototype.slice.call(arguments, 1));
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -114,7 +114,6 @@ var Overflow = _ccsg.Label.Overflow;
|
||||
* !#zh 系统字体
|
||||
* @property {Number} SystemFont
|
||||
*/
|
||||
var LabelType = _ccsg.Label.Type;
|
||||
|
||||
|
||||
// Returns a function, that, as long as it continues to be invoked, will not
|
||||
@@ -134,7 +133,7 @@ function debounce(func, wait, immediate) {
|
||||
timeout = setTimeout(later, wait);
|
||||
if (callNow) func.apply(context, args);
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
|
||||
@@ -23,6 +23,8 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
var Base = cc._RendererInSG;
|
||||
|
||||
/**
|
||||
* @class Mask
|
||||
* @extends _RendererInSG
|
||||
@@ -51,7 +53,7 @@ var MaskType = cc.Enum({
|
||||
|
||||
var Mask = cc.Class({
|
||||
name: 'cc.Mask',
|
||||
extends: cc._RendererInSG,
|
||||
extends: Base,
|
||||
|
||||
editor: CC_EDITOR && {
|
||||
menu: 'i18n:MAIN_MENU.component.renderers/Mask',
|
||||
@@ -120,6 +122,40 @@ var Mask = cc.Class({
|
||||
|
||||
_initSgNode: function () {},
|
||||
|
||||
_hitTest: function (point) {
|
||||
var size = this.node.getContentSize(),
|
||||
w = size.width,
|
||||
h = size.height,
|
||||
trans = this.node.getNodeToWorldTransform();
|
||||
|
||||
if (this._type === MaskType.RECT) {
|
||||
var rect = cc.rect(0, 0, w, h);
|
||||
cc._rectApplyAffineTransformIn(rect, trans);
|
||||
var left = point.x - rect.x,
|
||||
right = rect.x + rect.width - point.x,
|
||||
bottom = point.y - rect.y,
|
||||
top = rect.y + rect.height - point.y;
|
||||
if (left >= 0 && right >= 0 && top >= 0 && bottom >= 0) {
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
else {
|
||||
var a = w/2, b = h/2;
|
||||
var cx = trans.a * a + trans.c * b + trans.tx;
|
||||
var cy = trans.b * a + trans.d * b + trans.ty;
|
||||
var px = point.x - cx, py = point.y - cy;
|
||||
if (px * px / (a * a) + py * py / (b * b) < 1) {
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
onEnable: function () {
|
||||
this._refreshStencil();
|
||||
this._super();
|
||||
@@ -133,12 +169,6 @@ var Mask = cc.Class({
|
||||
this.node.off('anchor-changed', this._refreshStencil, this);
|
||||
},
|
||||
|
||||
onDestroy: CC_JSB && function () {
|
||||
this._super();
|
||||
this._clippingStencil.release();
|
||||
this._clippingStencil = null;
|
||||
},
|
||||
|
||||
_calculateCircle: function(center, radius, segements) {
|
||||
var polies =[];
|
||||
var anglePerStep = Math.PI * 2 / segements;
|
||||
@@ -174,4 +204,14 @@ var Mask = cc.Class({
|
||||
}
|
||||
});
|
||||
|
||||
if (CC_JSB) {
|
||||
// override onDestroy
|
||||
Mask.prototype.__superOnDestroy = Base.prototype.onDestroy;
|
||||
Mask.prototype.onDestroy = function () {
|
||||
this.__superOnDestroy();
|
||||
this._clippingStencil.release();
|
||||
this._clippingStencil = null;
|
||||
};
|
||||
}
|
||||
|
||||
cc.Mask = module.exports = Mask;
|
||||
|
||||
@@ -244,6 +244,7 @@ var ProgressBar = cc.Class({
|
||||
default: 1,
|
||||
type: 'Float',
|
||||
range: [0, 1, 0.1],
|
||||
slide: true,
|
||||
tooltip: 'i18n:COMPONENT.progress.progress',
|
||||
notify: function() {
|
||||
this._updateBarStatus();
|
||||
|
||||
@@ -33,6 +33,7 @@
|
||||
*/
|
||||
var RendererInSG = cc.Class({
|
||||
extends: require('./CCSGComponent'),
|
||||
name: 'cc._RendererInSG',
|
||||
|
||||
ctor: function () {
|
||||
/**
|
||||
@@ -83,6 +84,7 @@ var RendererInSG = cc.Class({
|
||||
var releasedByNode = this.node._sgNode;
|
||||
if (this._plainNode !== releasedByNode) {
|
||||
this._plainNode.release();
|
||||
this._plainNode = null;
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -94,6 +96,7 @@ var RendererInSG = cc.Class({
|
||||
|
||||
var node = this.node;
|
||||
var replaced = node._sgNode;
|
||||
replaced._entity = null;
|
||||
|
||||
if (CC_EDITOR && replaced === sgNode) {
|
||||
cc.warn('The same sgNode');
|
||||
@@ -120,15 +123,16 @@ var RendererInSG = cc.Class({
|
||||
if (parentNode) {
|
||||
parentNode.removeChild(replaced);
|
||||
parentNode.addChild(sgNode);
|
||||
sgNode.arrivalOrder = replaced.arrivalOrder;
|
||||
if ( !CC_JSB ) {
|
||||
sgNode._arrivalOrder = replaced._arrivalOrder;
|
||||
cc.renderer.childrenOrderDirty = parentNode._reorderChildDirty = true;
|
||||
}
|
||||
}
|
||||
// replaced.release();
|
||||
|
||||
// apply node's property
|
||||
|
||||
node._sgNode = sgNode;
|
||||
node._sgNode._entity = node;
|
||||
node._updateSgNode();
|
||||
},
|
||||
});
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
*/
|
||||
var RendererUnderSG = cc.Class({
|
||||
extends: require('./CCSGComponent'),
|
||||
name: 'cc._RendererUnderSG',
|
||||
|
||||
ctor: function () {
|
||||
/**
|
||||
@@ -92,7 +93,7 @@ var RendererUnderSG = cc.Class({
|
||||
}
|
||||
|
||||
sgNode.setAnchorPoint(node._anchorPoint);
|
||||
sgNode.ignoreAnchorPointForPosition(node.__ignoreAnchor);
|
||||
sgNode.setIgnoreAnchorPointForPosition(node.__ignoreAnchor);
|
||||
|
||||
sgNode.setOpacityModifyRGB(node._opacityModifyRGB);
|
||||
|
||||
|
||||
@@ -0,0 +1,652 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated engine source code (the "Software"), a limited,
|
||||
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
|
||||
to use Cocos Creator solely to develop games on your target platforms. You shall
|
||||
not use Cocos Creator software for developing other software or tools that's
|
||||
used for developing games. You are not granted to publish, distribute,
|
||||
sublicense, and/or sell copies of Cocos Creator.
|
||||
|
||||
The software or tools in this License Agreement are licensed, not sold.
|
||||
Chukong Aipu reserves all rights not expressly granted to you.
|
||||
|
||||
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 HorizontalAlign = cc.TextAlignment;
|
||||
var VerticalAlign = cc.VerticalTextAlignment;
|
||||
|
||||
var label_wrapinspection = true;
|
||||
var label_wordRex = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+|\S)/;
|
||||
var label_symbolRex = /^[!,.:;}\]%\?>、‘“》?。,!]/;
|
||||
var label_lastWordRex = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+|\S)$/;
|
||||
var label_lastEnglish = /[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]+$/;
|
||||
var label_firsrEnglish = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôû]/;
|
||||
|
||||
// Returns a function, that, as long as it continues to be invoked, will not
|
||||
// be triggered. The function will be called after it stops being called for
|
||||
// N milliseconds. If `immediate` is passed, trigger the function on the
|
||||
// leading edge, instead of the trailing.
|
||||
function debounce(func, wait, immediate) {
|
||||
var timeout;
|
||||
return function() {
|
||||
var context = this, args = arguments;
|
||||
var later = function() {
|
||||
timeout = null;
|
||||
if (!immediate) func.apply(context, args);
|
||||
};
|
||||
var callNow = immediate && !timeout;
|
||||
clearTimeout(timeout);
|
||||
timeout = setTimeout(later, wait);
|
||||
if (callNow) func.apply(context, args);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* !#en The RichText Component.
|
||||
* !#zh 富文本组件
|
||||
* @class RichText
|
||||
* @extends Component
|
||||
*/
|
||||
var RichText = cc.Class({
|
||||
name: 'cc.RichText',
|
||||
extends: cc._RendererUnderSG,
|
||||
|
||||
ctor: function() {
|
||||
this._textArray = null;
|
||||
|
||||
this._resetState();
|
||||
|
||||
if(CC_EDITOR) {
|
||||
this._updateRichTextStatus = debounce(this._updateRichText, 200);
|
||||
} else {
|
||||
this._updateRichTextStatus = this._updateRichText;
|
||||
}
|
||||
},
|
||||
|
||||
editor: CC_EDITOR && {
|
||||
menu: 'i18n:MAIN_MENU.component.renderers/RichText',
|
||||
help: 'i18n:COMPONENT.help_url.richtext',
|
||||
},
|
||||
|
||||
|
||||
properties: {
|
||||
/**
|
||||
* !#en Content string of RichText.
|
||||
* !#zh 富文本显示的文本内容。
|
||||
* @property {String} string
|
||||
*/
|
||||
string: {
|
||||
default: '<color=#00ff00>Rich</c><color=#0fffff>Text</color>',
|
||||
multiline: true,
|
||||
tooltip: 'i18n:COMPONENT.richtext.string',
|
||||
notify: function () {
|
||||
this._updateRichTextStatus();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Horizontal Alignment of each line in RichText.
|
||||
* !#zh 文本内容的水平对齐方式。
|
||||
* @property {RichText.HorizontalAlign} horizontalAlign
|
||||
*/
|
||||
horizontalAlign: {
|
||||
default: HorizontalAlign.LEFT,
|
||||
type: HorizontalAlign,
|
||||
tooltip: 'i18n:COMPONENT.richtext.horizontal_align',
|
||||
animatable: false,
|
||||
notify: function () {
|
||||
this._layoutDirty = true;
|
||||
this._updateRichTextStatus();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Font size of RichText.
|
||||
* !#zh 富文本字体大小。
|
||||
* @property {Number} fontSize
|
||||
*/
|
||||
fontSize: {
|
||||
default: 40,
|
||||
tooltip: 'i18n:COMPONENT.richtext.font_size',
|
||||
notify: function () {
|
||||
this._layoutDirty = true;
|
||||
this._updateRichTextStatus();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en The maximize width of the RichText
|
||||
* !#zh 富文本的最大宽度
|
||||
* @property {Number} maxWidth
|
||||
*/
|
||||
maxWidth: {
|
||||
default: 0,
|
||||
tooltip: 'i18n:COMPONENT.richtext.max_width',
|
||||
notify: function () {
|
||||
this._layoutDirty = true;
|
||||
this._updateRichTextStatus();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Line Height of RichText.
|
||||
* !#zh 富文本行高。
|
||||
* @property {Number} lineHeight
|
||||
*/
|
||||
lineHeight: {
|
||||
default: 40,
|
||||
tooltip: 'i18n:COMPONENT.richtext.line_height',
|
||||
notify: function () {
|
||||
this._layoutDirty = true;
|
||||
this._updateRichTextStatus();
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
statics: {
|
||||
HorizontalAlign: HorizontalAlign,
|
||||
VerticalAlign: VerticalAlign
|
||||
},
|
||||
|
||||
__preload: function () {
|
||||
this._super();
|
||||
|
||||
if (!CC_EDITOR) {
|
||||
this._registerEvents();
|
||||
}
|
||||
},
|
||||
|
||||
_createSgNode: function () {
|
||||
var sgNode = new _ccsg.Node();
|
||||
|
||||
sgNode.setCascadeOpacityEnabled(true);
|
||||
|
||||
var self = this;
|
||||
sgNode.setColor = function () {
|
||||
self._updateLabelSegmentTextAttributes();
|
||||
};
|
||||
|
||||
sgNode._setContentSize = sgNode.setContentSize;
|
||||
sgNode.setContentSize = function () {};
|
||||
return sgNode;
|
||||
},
|
||||
|
||||
_updateLabelSegmentTextAttributes: function() {
|
||||
this._labelSegments.forEach(function(item) {
|
||||
this._applyTextAttribute(item);
|
||||
}.bind(this));
|
||||
},
|
||||
|
||||
_initSgNode: function () {
|
||||
this._updateRichText();
|
||||
},
|
||||
|
||||
_measureText: function (string, styleIndex) {
|
||||
var label = new _ccsg.Label(string);
|
||||
label._styleIndex = styleIndex;
|
||||
this._applyTextAttribute(label);
|
||||
var labelSize = label.getContentSize();
|
||||
return labelSize.width;
|
||||
},
|
||||
|
||||
|
||||
_onTouchEnded: function (event) {
|
||||
if(!this.enabledInHierarchy) return;
|
||||
|
||||
var components = this.node.getComponents(cc.Component);
|
||||
|
||||
for (var i = 0; i < this._labelSegments.length; ++i ) {
|
||||
var labelSegment = this._labelSegments[i];
|
||||
var clickHandler = labelSegment._clickHandler;
|
||||
if (clickHandler && this._containsTouchLocation(labelSegment, event.touch.getLocation())) {
|
||||
components.forEach(function(component) {
|
||||
if(component.enabledInHierarchy && component[clickHandler]) {
|
||||
component[clickHandler](event);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
_containsTouchLocation:function (label, point) {
|
||||
var myRect = label.getBoundingBoxToWorld();
|
||||
|
||||
return cc.rectContainsPoint(myRect, point);
|
||||
},
|
||||
|
||||
_registerEvents: function () {
|
||||
this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
|
||||
},
|
||||
|
||||
_fragmentText: function (stringToken, allWidth, styleIndex) {
|
||||
//check the first character
|
||||
var wrappedWords = [];
|
||||
//fast return if strArr is empty
|
||||
if(stringToken.length === 0 || this.maxWidth < 0) {
|
||||
wrappedWords.push('');
|
||||
return wrappedWords;
|
||||
}
|
||||
|
||||
var text = stringToken;
|
||||
while (allWidth > this.maxWidth && text.length > 1) {
|
||||
|
||||
var fuzzyLen = text.length * ( this.maxWidth / allWidth ) | 0;
|
||||
var tmpText = text.substr(fuzzyLen);
|
||||
var width = allWidth - this._measureText(tmpText, styleIndex);
|
||||
var sLine = tmpText;
|
||||
var pushNum = 0;
|
||||
|
||||
var checkWhile = 0;
|
||||
var checkCount = 10;
|
||||
|
||||
//Exceeded the size
|
||||
while (width > this.maxWidth && checkWhile++ < checkCount) {
|
||||
fuzzyLen *= this.maxWidth / width;
|
||||
fuzzyLen = fuzzyLen | 0;
|
||||
tmpText = text.substr(fuzzyLen);
|
||||
width = allWidth - this._measureText(tmpText, styleIndex);
|
||||
}
|
||||
|
||||
checkWhile = 0;
|
||||
|
||||
//Find the truncation point
|
||||
while (width < this.maxWidth && checkWhile++ < checkCount) {
|
||||
if (tmpText) {
|
||||
var exec = label_wordRex.exec(tmpText);
|
||||
pushNum = exec ? exec[0].length : 1;
|
||||
sLine = tmpText;
|
||||
}
|
||||
|
||||
fuzzyLen = fuzzyLen + pushNum;
|
||||
tmpText = text.substr(fuzzyLen);
|
||||
width = allWidth - this._measureText(tmpText, styleIndex);
|
||||
}
|
||||
|
||||
fuzzyLen -= pushNum;
|
||||
if (fuzzyLen === 0) {
|
||||
fuzzyLen = 1;
|
||||
sLine = sLine.substr(1);
|
||||
}
|
||||
|
||||
var sText = text.substr(0, fuzzyLen), result;
|
||||
|
||||
//symbol in the first
|
||||
if (label_wrapinspection) {
|
||||
if (label_symbolRex.test(sLine || tmpText)) {
|
||||
result = label_lastWordRex.exec(sText);
|
||||
fuzzyLen -= result ? result[0].length : 0;
|
||||
if (fuzzyLen === 0) fuzzyLen = 1;
|
||||
|
||||
sLine = text.substr(fuzzyLen);
|
||||
sText = text.substr(0, fuzzyLen);
|
||||
}
|
||||
}
|
||||
|
||||
//To judge whether a English words are truncated
|
||||
if (label_firsrEnglish.test(sLine)) {
|
||||
result = label_lastEnglish.exec(sText);
|
||||
if (result && sText !== result[0]) {
|
||||
fuzzyLen -= result[0].length;
|
||||
sLine = text.substr(fuzzyLen);
|
||||
sText = text.substr(0, fuzzyLen);
|
||||
}
|
||||
}
|
||||
if (sText.trim().length > 0) {
|
||||
wrappedWords.push(sText);
|
||||
}
|
||||
text = sLine || tmpText;
|
||||
allWidth = this._measureText(text, styleIndex);
|
||||
}
|
||||
if (text.length > 0) {
|
||||
wrappedWords.push(text);
|
||||
}
|
||||
|
||||
return wrappedWords;
|
||||
},
|
||||
|
||||
_resetState: function () {
|
||||
var sgNode = this._sgNode;
|
||||
if(sgNode) {
|
||||
sgNode.removeAllChildren();
|
||||
}
|
||||
|
||||
this._labelSegments = [];
|
||||
this._linesWidth = [];
|
||||
this._lineOffsetX = 0;
|
||||
this._lineCount = 1;
|
||||
this._labelWidth = 0;
|
||||
this._labelHeight = 0;
|
||||
this._layoutDirty = true;
|
||||
},
|
||||
|
||||
_addLabelSegment: function(stringToken, styleIndex) {
|
||||
var labelSegment = new _ccsg.Label(stringToken);
|
||||
labelSegment._styleIndex = styleIndex;
|
||||
labelSegment._lineCount = this._lineCount;
|
||||
|
||||
this._applyTextAttribute(labelSegment);
|
||||
|
||||
labelSegment.setAnchorPoint(cc.p(0, 0));
|
||||
this._sgNode.addChild(labelSegment);
|
||||
this._labelSegments.push(labelSegment);
|
||||
|
||||
if(CC_JSB) {
|
||||
labelSegment.setOverflow(1);
|
||||
var size = labelSegment.getContentSize();
|
||||
labelSegment.setContentSize(size.width, this.lineHeight);
|
||||
}
|
||||
|
||||
return labelSegment;
|
||||
},
|
||||
|
||||
_updateRichTextWithMaxWidth: function (labelString, labelWidth, styleIndex) {
|
||||
var fragmentWidth = labelWidth;
|
||||
var labelSegment;
|
||||
|
||||
if (this._lineOffsetX > 0 && fragmentWidth + this._lineOffsetX > this.maxWidth) {
|
||||
//concat previous line
|
||||
var checkStartIndex = 0;
|
||||
while (this._lineOffsetX <= this.maxWidth) {
|
||||
var checkEndIndex = this._getFirstWordLen(labelString, checkStartIndex, labelString.length);
|
||||
var checkString = labelString.substr(checkStartIndex, checkEndIndex);
|
||||
var checkStringWidth = this._measureText(checkString, styleIndex);
|
||||
|
||||
if(this._lineOffsetX + checkStringWidth <= this.maxWidth) {
|
||||
this._lineOffsetX += checkStringWidth;
|
||||
checkStartIndex += checkEndIndex;
|
||||
} else {
|
||||
|
||||
if(checkStartIndex > 0) {
|
||||
var remainingString = labelString.substr(0, checkStartIndex);
|
||||
|
||||
this._addLabelSegment(remainingString, styleIndex);
|
||||
|
||||
labelString = labelString.substr(checkStartIndex, labelString.length);
|
||||
fragmentWidth = this._measureText(labelString, styleIndex);
|
||||
}
|
||||
this._updateLineInfo();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if(fragmentWidth > this.maxWidth) {
|
||||
var fragments = this._fragmentText(labelString, fragmentWidth, styleIndex);
|
||||
for(var k = 0; k < fragments.length; ++k) {
|
||||
var splitString = fragments[k];
|
||||
|
||||
labelSegment = this._addLabelSegment(splitString, styleIndex);
|
||||
|
||||
var labelSize = labelSegment.getContentSize();
|
||||
|
||||
this._lineOffsetX += labelSize.width;
|
||||
|
||||
if(fragments.length > 1 && k < fragments.length - 1) {
|
||||
this._updateLineInfo();
|
||||
}
|
||||
}
|
||||
} else {
|
||||
this._lineOffsetX += fragmentWidth;
|
||||
|
||||
this._addLabelSegment(labelString, styleIndex);
|
||||
}
|
||||
|
||||
},
|
||||
|
||||
_isLastComponentCR: function(stringToken) {
|
||||
return stringToken.length -1 === stringToken.lastIndexOf("\n");
|
||||
},
|
||||
|
||||
_updateLineInfo: function () {
|
||||
this._linesWidth.push(this._lineOffsetX);
|
||||
this._lineOffsetX = 0;
|
||||
this._lineCount++;
|
||||
},
|
||||
|
||||
_needsUpdateTextLayout: function (newTextArray) {
|
||||
if(this._layoutDirty || !this._textArray || !newTextArray) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if(this._textArray.length !== newTextArray.length) {
|
||||
return true;
|
||||
}
|
||||
|
||||
for(var i = 0; i < this._textArray.length; ++i) {
|
||||
var oldItem = this._textArray[i];
|
||||
var newItem = newTextArray[i];
|
||||
if(oldItem.text != newItem.text) {
|
||||
return true;
|
||||
} else {
|
||||
if (oldItem.style) {
|
||||
if (newItem.style) {
|
||||
if(oldItem.style.size != newItem.style.size) {
|
||||
return true;
|
||||
}
|
||||
} else {
|
||||
if(oldItem.style.size) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (newItem.style) {
|
||||
if(newItem.style.size) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
},
|
||||
|
||||
_updateRichText: function () {
|
||||
var newTextArray = cc.htmlTextParser.parse(this.string);
|
||||
if(!this._needsUpdateTextLayout(newTextArray)) {
|
||||
this._textArray = newTextArray;
|
||||
this._updateLabelSegmentTextAttributes();
|
||||
return;
|
||||
}
|
||||
|
||||
this._textArray = newTextArray;
|
||||
var sgNode = this._sgNode;
|
||||
this._resetState();
|
||||
|
||||
var lastEmptyLine = false;
|
||||
var label;
|
||||
var labelSize;
|
||||
|
||||
for (var i = 0; i < this._textArray.length; ++i) {
|
||||
var richTextElement = this._textArray[i];
|
||||
var text = richTextElement.text;
|
||||
//handle <br/> <img /> tag
|
||||
if(text === "") {
|
||||
if(richTextElement.style && richTextElement.style.newline) {
|
||||
this._updateLineInfo();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
var multilineTexts = text.split("\n");
|
||||
|
||||
for (var j = 0; j < multilineTexts.length; ++j) {
|
||||
var labelString = multilineTexts[j];
|
||||
if(labelString === "") {
|
||||
//for continues \n
|
||||
if(this._isLastComponentCR(text) && j == multilineTexts.length - 1) {
|
||||
continue;
|
||||
}
|
||||
this._updateLineInfo();
|
||||
lastEmptyLine = true;
|
||||
continue;
|
||||
}
|
||||
lastEmptyLine = false;
|
||||
|
||||
if(this.maxWidth > 0) {
|
||||
var labelWidth = this._measureText(labelString, i);
|
||||
this._updateRichTextWithMaxWidth(labelString, labelWidth, i);
|
||||
|
||||
if(multilineTexts.length > 1 && j < multilineTexts.length - 1) {
|
||||
this._updateLineInfo();
|
||||
}
|
||||
} else {
|
||||
label = this._addLabelSegment(labelString, i);
|
||||
labelSize = label.getContentSize();
|
||||
|
||||
this._lineOffsetX += labelSize.width;
|
||||
if(this._lineOffsetX > this._labelWidth) {
|
||||
this._labelWidth = this._lineOffsetX;
|
||||
}
|
||||
|
||||
if(multilineTexts.length > 1 && j < multilineTexts.length - 1) {
|
||||
this._updateLineInfo();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if(!lastEmptyLine) {
|
||||
this._linesWidth.push(this._lineOffsetX);
|
||||
}
|
||||
|
||||
if(this.maxWidth > 0) {
|
||||
this._labelWidth = this.maxWidth;
|
||||
}
|
||||
this._labelHeight =this._lineCount * this.lineHeight;
|
||||
|
||||
sgNode._setContentSize(cc.size(this._labelWidth, this._labelHeight));
|
||||
|
||||
this._updateRichTextPosition();
|
||||
this._layoutDirty = false;
|
||||
},
|
||||
|
||||
_isCJK_unicode: function(ch) {
|
||||
var __CHINESE_REG = /^[\u4E00-\u9FFF\u3400-\u4DFF]+$/;
|
||||
var __JAPANESE_REG = /[\u3000-\u303F]|[\u3040-\u309F]|[\u30A0-\u30FF]|[\uFF00-\uFFEF]|[\u4E00-\u9FAF]|[\u2605-\u2606]|[\u2190-\u2195]|\u203B/g;
|
||||
var __KOREAN_REG = /^[\u1100-\u11FF]|[\u3130-\u318F]|[\uA960-\uA97F]|[\uAC00-\uD7AF]|[\uD7B0-\uD7FF]+$/;
|
||||
return __CHINESE_REG.test(ch) || __JAPANESE_REG.test(ch) || __KOREAN_REG.test(ch);
|
||||
},
|
||||
|
||||
//Checking whether the character is a whitespace
|
||||
_isspace_unicode: function(ch) {
|
||||
ch = ch.charCodeAt(0);
|
||||
return ((ch >= 9 && ch <= 13) || ch === 32 || ch === 133 || ch === 160 || ch === 5760 || (ch >= 8192 && ch <= 8202) || ch === 8232 || ch === 8233 || ch === 8239 || ch === 8287 || ch === 12288);
|
||||
},
|
||||
|
||||
_getFirstWordLen: function(text, startIndex, textLen) {
|
||||
var character = text.charAt(startIndex);
|
||||
if (this._isCJK_unicode(character) || this._isspace_unicode(character)) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
var len = 1;
|
||||
for (var index = startIndex + 1; index < textLen; ++index) {
|
||||
character = text.charAt(index);
|
||||
if (this._isspace_unicode(character) || this._isCJK_unicode(character)) {
|
||||
break;
|
||||
}
|
||||
len++;
|
||||
}
|
||||
|
||||
return len;
|
||||
},
|
||||
|
||||
_updateRichTextPosition: function () {
|
||||
|
||||
var nextTokenX = 0;
|
||||
var nextLineIndex = 1;
|
||||
var totalLineCount = this._lineCount;
|
||||
for(var i = 0; i < this._labelSegments.length; ++i) {
|
||||
var label = this._labelSegments[i];
|
||||
var lineCount = label._lineCount;
|
||||
if (lineCount > nextLineIndex) {
|
||||
nextTokenX = 0;
|
||||
nextLineIndex = lineCount;
|
||||
}
|
||||
var lineOffsetX = 0;
|
||||
switch (this.horizontalAlign) {
|
||||
case cc.TextAlignment.LEFT:
|
||||
lineOffsetX = 0;
|
||||
break;
|
||||
case cc.TextAlignment.CENTER:
|
||||
lineOffsetX = (this._labelWidth - this._linesWidth[lineCount - 1]) / 2;
|
||||
break;
|
||||
case cc.TextAlignment.RIGHT:
|
||||
lineOffsetX = this._labelWidth - this._linesWidth[lineCount - 1];
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
label.setPositionX(nextTokenX + lineOffsetX);
|
||||
|
||||
var labelSize = label.getContentSize();
|
||||
|
||||
var positionY = (totalLineCount - lineCount) * this.lineHeight;
|
||||
|
||||
label.setPositionY(positionY);
|
||||
|
||||
if (lineCount === nextLineIndex) {
|
||||
nextTokenX += labelSize.width;
|
||||
}
|
||||
|
||||
}
|
||||
},
|
||||
|
||||
_applyTextAttribute: function (label) {
|
||||
var index = label._styleIndex;
|
||||
label.setLineHeight(this.lineHeight);
|
||||
label.setVerticalAlign(VerticalAlign.CENTER);
|
||||
label.enableBold(false);
|
||||
label.enableItalics(false);
|
||||
label.enableUnderline(false);
|
||||
|
||||
var textStyle = null;
|
||||
if(this._textArray[index]) {
|
||||
textStyle = this._textArray[index].style;
|
||||
}
|
||||
if(textStyle && textStyle.color) {
|
||||
var colorValue = textStyle.color.toUpperCase();
|
||||
if(cc.Color[colorValue]) {
|
||||
label.setColor(cc.Color[colorValue]);
|
||||
} else {
|
||||
label.setColor(cc.hexToColor(textStyle.color));
|
||||
}
|
||||
} else {
|
||||
label.setColor(this.node.color);
|
||||
}
|
||||
|
||||
if(textStyle && textStyle.bold) {
|
||||
label.enableBold(true);
|
||||
}
|
||||
|
||||
if(textStyle && textStyle.italic) {
|
||||
label.enableItalics(true);
|
||||
}
|
||||
|
||||
if(textStyle && textStyle.underline) {
|
||||
label.enableUnderline(true);
|
||||
}
|
||||
|
||||
if(textStyle && textStyle.size) {
|
||||
label.setFontSize(textStyle.size);
|
||||
} else {
|
||||
label.setFontSize(this.fontSize);
|
||||
}
|
||||
|
||||
if(textStyle && textStyle.event) {
|
||||
if(textStyle.event.click) {
|
||||
label._clickHandler = textStyle.event.click;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
cc.RichText = module.exports = RichText;
|
||||
@@ -38,6 +38,7 @@ var SceneGraphHelper = require('../utils/scene-graph-helper');
|
||||
*/
|
||||
var SGComponent = cc.Class({
|
||||
extends: require('./CCComponent'),
|
||||
name: 'cc._SGComponent',
|
||||
|
||||
editor: CC_EDITOR && {
|
||||
executeInEditMode: true,
|
||||
|
||||
@@ -333,7 +333,7 @@ var Scrollbar = cc.Class({
|
||||
},
|
||||
|
||||
show: function() {
|
||||
this._autoHideRemainingTime = 0;
|
||||
this._autoHideRemainingTime = this.autoHideTime;
|
||||
this._setOpacity(this._opacity);
|
||||
},
|
||||
|
||||
|
||||
@@ -103,7 +103,13 @@ var EventType = cc.Enum({
|
||||
* !#zh 滚动视图滚动滚动结束的时候发出的事件
|
||||
* @property {Number} AUTOSCROLL_ENDED
|
||||
*/
|
||||
AUTOSCROLL_ENDED : 9
|
||||
AUTOSCROLL_ENDED : 9,
|
||||
/**
|
||||
* !#en The event emmitted when user release the touch
|
||||
* !#zh 当用户松手的时候会发出一个事件
|
||||
* @property {Number} TOUCH_UP
|
||||
*/
|
||||
TOUCH_UP : 10
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -123,7 +129,7 @@ var ScrollView = cc.Class({
|
||||
editor: CC_EDITOR && {
|
||||
menu: 'i18n:MAIN_MENU.component.ui/ScrollView',
|
||||
help: 'i18n:COMPONENT.help_url.scrollview',
|
||||
executeInEditMode: true,
|
||||
executeInEditMode: false,
|
||||
},
|
||||
|
||||
ctor: function() {
|
||||
@@ -160,7 +166,7 @@ var ScrollView = cc.Class({
|
||||
* @property {Node} content
|
||||
*/
|
||||
content: {
|
||||
default: null,
|
||||
default: undefined,
|
||||
type: cc.Node,
|
||||
tooltip: 'i18n:COMPONENT.scrollview.content',
|
||||
},
|
||||
@@ -240,7 +246,7 @@ var ScrollView = cc.Class({
|
||||
* @property {Scrollbar} horizontalScrollBar
|
||||
*/
|
||||
horizontalScrollBar: {
|
||||
default: null,
|
||||
default: undefined,
|
||||
type: cc.Scrollbar,
|
||||
tooltip: 'i18n:COMPONENT.scrollview.horizontal_bar',
|
||||
notify: function() {
|
||||
@@ -258,7 +264,7 @@ var ScrollView = cc.Class({
|
||||
* @property {Scrollbar} verticalScrollBar
|
||||
*/
|
||||
verticalScrollBar: {
|
||||
default: null,
|
||||
default: undefined,
|
||||
type: cc.Scrollbar,
|
||||
tooltip: 'i18n:COMPONENT.scrollview.vertical_bar',
|
||||
notify: function() {
|
||||
@@ -278,6 +284,18 @@ var ScrollView = cc.Class({
|
||||
scrollEvents: {
|
||||
default: [],
|
||||
type: cc.Component.EventHandler
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en If cancelInnerEvents is set to true, the scroll behavior will cancel touch events on inner content nodes of the scroll view
|
||||
* It's set to true by default.
|
||||
* !#zh 如果这个属性被设置为 true,那么滚动行为会取消 ScrollView 的子节点上注册的触摸事件,默认被设置为 true。
|
||||
* 注意,子节点上的 touchstart 事件仍然会触发,触点移动距离非常短的情况下 touchmove 和 touchend 也不会受影响。
|
||||
* @property {Boolean} cancelInnerEvents
|
||||
*/
|
||||
cancelInnerEvents: {
|
||||
default: true,
|
||||
animatable: false,
|
||||
}
|
||||
},
|
||||
|
||||
@@ -686,10 +704,12 @@ var ScrollView = cc.Class({
|
||||
},
|
||||
|
||||
_onMouseWheel: function(event) {
|
||||
if (!this.enabledInHierarchy) return;
|
||||
|
||||
var deltaMove = cc.p(0, 0);
|
||||
var wheelPrecision = 1.0 / 40;
|
||||
var wheelPrecision = -0.1;
|
||||
if(CC_JSB) {
|
||||
wheelPrecision = 7;
|
||||
wheelPrecision = -7;
|
||||
}
|
||||
if(this.vertical) {
|
||||
deltaMove = cc.p(0, event.getScrollY() * wheelPrecision);
|
||||
@@ -762,6 +782,48 @@ var ScrollView = cc.Class({
|
||||
return moveDelta;
|
||||
},
|
||||
|
||||
_moveContentToTopLeft: function (scrollViewSize) {
|
||||
var contentSize = this.content.getContentSize();
|
||||
|
||||
var bottomDeta = this._getContentBottomBoundary() - this._bottomBoundary;
|
||||
bottomDeta = -bottomDeta;
|
||||
var moveDelta = cc.p(0, 0);
|
||||
var totalScrollDelta = 0;
|
||||
|
||||
var leftDeta = this._getContentLeftBoundary() - this._leftBoundary;
|
||||
leftDeta = -leftDeta;
|
||||
|
||||
if (contentSize.height < scrollViewSize.height) {
|
||||
totalScrollDelta = contentSize.height - scrollViewSize.height;
|
||||
moveDelta.y = bottomDeta - totalScrollDelta;
|
||||
|
||||
if (this.verticalScrollBar) {
|
||||
this.verticalScrollBar.hide();
|
||||
}
|
||||
} else {
|
||||
if (this.verticalScrollBar) {
|
||||
this.verticalScrollBar.show();
|
||||
}
|
||||
}
|
||||
|
||||
if (contentSize.width < scrollViewSize.width) {
|
||||
totalScrollDelta = contentSize.width - scrollViewSize.width;
|
||||
moveDelta.x = leftDeta;
|
||||
|
||||
if (this.horizontalScrollBar) {
|
||||
this.horizontalScrollBar.hide();
|
||||
}
|
||||
|
||||
} else {
|
||||
if (this.horizontalScrollBar) {
|
||||
this.horizontalScrollBar.show();
|
||||
}
|
||||
}
|
||||
|
||||
this._moveContent(moveDelta);
|
||||
this._adjustContentOutOfBoundary();
|
||||
},
|
||||
|
||||
_calculateBoundary: function() {
|
||||
if (this.content) {
|
||||
//refresh content size
|
||||
@@ -779,44 +841,9 @@ var ScrollView = cc.Class({
|
||||
this._rightBoundary = topRightPosition.x;
|
||||
this._topBoundary = topRightPosition.y;
|
||||
|
||||
var contentSize = this.content.getContentSize();
|
||||
|
||||
var bottomDeta = this._getContentBottomBoundary() - this._bottomBoundary;
|
||||
bottomDeta = -bottomDeta;
|
||||
var moveDelta = cc.p(0, 0);
|
||||
var totalScrollDelta = 0;
|
||||
|
||||
var leftDeta = this._getContentLeftBoundary() - this._leftBoundary;
|
||||
leftDeta = -leftDeta;
|
||||
|
||||
if (contentSize.height < scrollViewSize.height) {
|
||||
totalScrollDelta = contentSize.height - scrollViewSize.height;
|
||||
moveDelta.y = bottomDeta - totalScrollDelta;
|
||||
|
||||
if (this.verticalScrollBar) {
|
||||
this.verticalScrollBar.hide();
|
||||
}
|
||||
} else {
|
||||
if (this.verticalScrollBar) {
|
||||
this.verticalScrollBar.show();
|
||||
}
|
||||
if(!CC_EDITOR) {
|
||||
this._moveContentToTopLeft(scrollViewSize);
|
||||
}
|
||||
|
||||
if (contentSize.width < scrollViewSize.width) {
|
||||
totalScrollDelta = contentSize.width - scrollViewSize.width;
|
||||
moveDelta.x = leftDeta;
|
||||
|
||||
if (this.horizontalScrollBar) {
|
||||
this.horizontalScrollBar.hide();
|
||||
}
|
||||
|
||||
} else {
|
||||
if (this.horizontalScrollBar) {
|
||||
this.horizontalScrollBar.show();
|
||||
}
|
||||
}
|
||||
|
||||
this._moveContent(moveDelta);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -828,6 +855,8 @@ var ScrollView = cc.Class({
|
||||
|
||||
// touch event handler
|
||||
_onTouchBegan: function(event) {
|
||||
if (!this.enabledInHierarchy) return;
|
||||
|
||||
var touch = event.touch;
|
||||
if (this.content) {
|
||||
this._handlePressLogic(touch);
|
||||
@@ -836,36 +865,54 @@ var ScrollView = cc.Class({
|
||||
},
|
||||
|
||||
_onTouchMoved: function(event) {
|
||||
if (!this.enabledInHierarchy) return;
|
||||
|
||||
var touch = event.touch;
|
||||
if (this.content) {
|
||||
this._handleMoveLogic(touch);
|
||||
}
|
||||
var deltaMove = touch.getDelta();
|
||||
// Do not prevent touch events in inner nodes
|
||||
if (!this.cancelInnerEvents) {
|
||||
return;
|
||||
}
|
||||
|
||||
var deltaMove = cc.pSub(touch.getLocation(), touch.getStartLocation());
|
||||
//FIXME: touch move delta should be calculated by DPI.
|
||||
if (cc.pLength(deltaMove) > 7) {
|
||||
this._touchMoved = true;
|
||||
var buttonComponent = event.target.getComponent(cc.Button);
|
||||
if (buttonComponent) {
|
||||
buttonComponent._onTouchCancel();
|
||||
if (!this._touchMoved && event.target !== this.node) {
|
||||
// Simulate touch cancel for target node
|
||||
var cancelEvent = new cc.Event.EventTouch(event.getTouches(), event.bubbles);
|
||||
cancelEvent.type = cc.Node.EventType.TOUCH_CANCEL;
|
||||
cancelEvent.touch = event.touch;
|
||||
cancelEvent.simulate = true;
|
||||
event.target.dispatchEvent(cancelEvent);
|
||||
this._touchMoved = true;
|
||||
}
|
||||
event.stopPropagation();
|
||||
}
|
||||
// TODO: detect move distance, if distance greater than a seuil, then stop propagation.
|
||||
event.stopPropagation();
|
||||
},
|
||||
|
||||
_onTouchEnded: function(event) {
|
||||
if (!this.enabledInHierarchy) return;
|
||||
|
||||
var touch = event.touch;
|
||||
if (this.content) {
|
||||
this._handleReleaseLogic(touch);
|
||||
}
|
||||
this._dispatchEvent(EventType.TOUCH_UP);
|
||||
if (this._touchMoved) {
|
||||
event.stopPropagation();
|
||||
}
|
||||
},
|
||||
_onTouchCancelled: function(event) {
|
||||
var touch = event.touch;
|
||||
if(this.content){
|
||||
this._handleReleaseLogic(touch);
|
||||
if (!this.enabledInHierarchy) return;
|
||||
|
||||
// Filte touch cancel event send from self
|
||||
if (!event.simulate) {
|
||||
var touch = event.touch;
|
||||
if(this.content){
|
||||
this._handleReleaseLogic(touch);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1093,7 +1140,6 @@ var ScrollView = cc.Class({
|
||||
_startAttenuatingAutoScroll: function(deltaMove, initialVelocity) {
|
||||
var time = this._calculateAutoScrollTimeByInitalSpeed(cc.pLength(initialVelocity));
|
||||
|
||||
var originalMoveLength = cc.pLength(deltaMove);
|
||||
|
||||
var targetDelta = cc.pNormalize(deltaMove);
|
||||
var contentSize = this.content.getContentSize();
|
||||
@@ -1107,10 +1153,23 @@ var ScrollView = cc.Class({
|
||||
|
||||
targetDelta = cc.p(targetDelta.x * totalMoveWidth * (1 - this.brake) * attenuatedFactorX, targetDelta.y * totalMoveHeight * attenuatedFactorY * (1 - this.brake));
|
||||
|
||||
targetDelta = cc.pAdd(deltaMove, targetDelta);
|
||||
var originalMoveLength = cc.pLength(deltaMove);
|
||||
var factor = cc.pLength(targetDelta) / originalMoveLength;
|
||||
targetDelta = cc.pAdd(targetDelta, deltaMove);
|
||||
|
||||
time = time * factor;
|
||||
if(this.brake > 0 && factor > 7) {
|
||||
factor = Math.sqrt(factor);
|
||||
targetDelta = cc.pAdd(cc.pMult(deltaMove, factor), deltaMove);
|
||||
}
|
||||
|
||||
if(this.brake > 0 && factor > 3) {
|
||||
factor = 3;
|
||||
time = time * factor;
|
||||
}
|
||||
|
||||
if(this.brake === 0 && factor > 1) {
|
||||
time = time * factor;
|
||||
}
|
||||
|
||||
this._startAutoScroll(targetDelta, time, true);
|
||||
},
|
||||
@@ -1159,7 +1218,8 @@ var ScrollView = cc.Class({
|
||||
return cc.pAdd(a, b);
|
||||
}, totalMovement);
|
||||
|
||||
return cc.p(totalMovement.x / totalTime, totalMovement.y / totalTime);
|
||||
return cc.p(totalMovement.x * (1 - this.brake) / totalTime,
|
||||
totalMovement.y * (1 - this.brake) / totalTime);
|
||||
},
|
||||
|
||||
_flattenVectorByDirection: function(vector) {
|
||||
@@ -1282,8 +1342,25 @@ var ScrollView = cc.Class({
|
||||
}
|
||||
},
|
||||
|
||||
_adjustContentOutOfBoundary: function () {
|
||||
this._outOfBoundaryAmountDirty = true;
|
||||
if(this._isOutOfBoundary()) {
|
||||
var outOfBoundary = this._getHowMuchOutOfBoundary(cc.p(0, 0));
|
||||
var newPosition = cc.pAdd(this.getContentPosition(), outOfBoundary);
|
||||
if(this.content) {
|
||||
this.content.setPosition(newPosition);
|
||||
this._updateScrollBar(0);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
start: function() {
|
||||
this._calculateBoundary();
|
||||
//Because widget component will adjust content position and scrollview position is correct after visit
|
||||
//So this event could make sure the content is on the correct position after loading.
|
||||
if(this.content) {
|
||||
cc.director.once(cc.Director.EVENT_AFTER_VISIT, this._adjustContentOutOfBoundary, this);
|
||||
}
|
||||
},
|
||||
|
||||
onDestroy: function() {
|
||||
@@ -1303,11 +1380,25 @@ var ScrollView = cc.Class({
|
||||
}
|
||||
},
|
||||
|
||||
onDisable: function() {
|
||||
_showScrollbar: function () {
|
||||
if (this.horizontalScrollBar) {
|
||||
this.horizontalScrollBar.show();
|
||||
}
|
||||
|
||||
if (this.verticalScrollBar) {
|
||||
this.verticalScrollBar.show();
|
||||
}
|
||||
},
|
||||
|
||||
onDisable: function () {
|
||||
this._hideScrollbar();
|
||||
this.stopAutoScroll();
|
||||
},
|
||||
|
||||
onEnable: function () {
|
||||
this._showScrollbar();
|
||||
},
|
||||
|
||||
update: function(dt) {
|
||||
if (this._autoScrolling) {
|
||||
this._processAutoScrolling(dt);
|
||||
|
||||
@@ -23,6 +23,8 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
var Base = require('./CCRendererUnderSG');
|
||||
|
||||
/**
|
||||
* !#en Enum for sprite type.
|
||||
* !#zh Sprite 类型
|
||||
@@ -113,7 +115,7 @@ var SizeMode = cc.Enum({
|
||||
*/
|
||||
var Sprite = cc.Class({
|
||||
name: 'cc.Sprite',
|
||||
extends: require('./CCRendererUnderSG'),
|
||||
extends: Base,
|
||||
|
||||
editor: CC_EDITOR && {
|
||||
menu: 'i18n:MAIN_MENU.component.renderers/Sprite',
|
||||
@@ -161,10 +163,17 @@ var Sprite = cc.Class({
|
||||
return this._spriteFrame;
|
||||
},
|
||||
set: function (value, force) {
|
||||
if (this._spriteFrame === value) {
|
||||
return;
|
||||
}
|
||||
var lastSprite = this._spriteFrame;
|
||||
if (CC_EDITOR) {
|
||||
if (!force && ((lastSprite && lastSprite._uuid) === (value && value._uuid))) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (lastSprite === value) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
this._spriteFrame = value;
|
||||
this._applySpriteFrame(lastSprite);
|
||||
if (CC_EDITOR) {
|
||||
@@ -379,15 +388,6 @@ var Sprite = cc.Class({
|
||||
SizeMode: SizeMode,
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Sets whether the sprite is visible or not.
|
||||
* !#zh 设置精灵是否可见
|
||||
* @method setVisible
|
||||
* @param {Boolean} visible
|
||||
* @override
|
||||
* @example
|
||||
* sprite.setVisible(false);
|
||||
*/
|
||||
setVisible: function (visible) {
|
||||
this.enabled = visible;
|
||||
},
|
||||
@@ -492,11 +492,6 @@ var Sprite = cc.Class({
|
||||
return this._sgNode.getInsetBottom();
|
||||
},
|
||||
|
||||
__preload: CC_EDITOR && function () {
|
||||
this._super();
|
||||
this.node.on('size-changed', this._resized, this);
|
||||
},
|
||||
|
||||
onEnable: function () {
|
||||
if (this._sgNode) {
|
||||
if (this._spriteFrame && this._spriteFrame.textureLoaded()) {
|
||||
@@ -505,11 +500,6 @@ var Sprite = cc.Class({
|
||||
}
|
||||
},
|
||||
|
||||
onDestroy: CC_EDITOR && function () {
|
||||
this._super();
|
||||
this.node.off('size-changed', this._resized, this);
|
||||
},
|
||||
|
||||
_applyAtlas: CC_EDITOR && function (spriteFrame) {
|
||||
// Set atlas
|
||||
if (spriteFrame && spriteFrame._atlasUuid) {
|
||||
@@ -632,6 +622,21 @@ var Sprite = cc.Class({
|
||||
},
|
||||
});
|
||||
|
||||
if (CC_EDITOR) {
|
||||
// override __preload
|
||||
Sprite.prototype.__superPreload = Base.prototype.__preload;
|
||||
Sprite.prototype.__preload = function () {
|
||||
this.__superPreload();
|
||||
this.node.on('size-changed', this._resized, this);
|
||||
};
|
||||
// override onDestroy
|
||||
Sprite.prototype.__superOnDestroy = Base.prototype.onDestroy;
|
||||
Sprite.prototype.onDestroy = function () {
|
||||
this.__superOnDestroy();
|
||||
this.node.off('size-changed', this._resized, this);
|
||||
};
|
||||
}
|
||||
|
||||
var misc = require('../utils/misc');
|
||||
var SameNameGetSets = ['atlas', 'capInsets', 'insetLeft', 'insetTop', 'insetRight', 'insetBottom'];
|
||||
var DiffNameGetSets = {
|
||||
|
||||
@@ -21,6 +21,31 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
/**
|
||||
* !#en Video event type
|
||||
* !#zh 视频事件类型
|
||||
* @enum VideoPlayer.EventType
|
||||
*/
|
||||
/**
|
||||
* !#en play
|
||||
* !#zh 播放
|
||||
* @property {Number} PLAYING
|
||||
*/
|
||||
/**
|
||||
* !#en pause
|
||||
* !#zh 暂停
|
||||
* @property {Number} PAUSED
|
||||
*/
|
||||
/**
|
||||
* !#en stop
|
||||
* !#zh 停止
|
||||
* @property {Number} STOPPED
|
||||
*/
|
||||
/**
|
||||
* !#en play end
|
||||
* !#zh 播放结束
|
||||
* @property {Number} COMPLETED
|
||||
*/
|
||||
var EventType = _ccsg.VideoPlayer.EventType;
|
||||
|
||||
|
||||
@@ -106,7 +131,7 @@ var VideoPlayer = cc.Class({
|
||||
/**
|
||||
* !#en The local video full path.
|
||||
* !#zh 本地视频的 URL
|
||||
* @property {String} video
|
||||
* @property {String} clip
|
||||
*/
|
||||
clip: {
|
||||
tooltip: 'i18n:COMPONENT.videoplayer.video',
|
||||
@@ -122,21 +147,24 @@ var VideoPlayer = cc.Class({
|
||||
url: cc.RawAsset
|
||||
},
|
||||
|
||||
_time: 0,
|
||||
/**
|
||||
* !#en The current time when video start to play.
|
||||
* !#zh 从当前时间点开始播放视频
|
||||
* @property {Float} currentTime
|
||||
* !#en The current playback time of the now playing item in seconds, you could also change the start playback time.
|
||||
* !#zh 指定视频从什么时间点开始播放,单位是秒,也可以用来获取当前视频播放的时间进度。
|
||||
* @property {Number} currentTime
|
||||
*/
|
||||
currentTime: {
|
||||
tooltip: 'i18n:COMPONENT.videoplayer.currentTime',
|
||||
type: cc.Float,
|
||||
set: function ( time ) {
|
||||
this._time = time;
|
||||
this._sgNode.seekTo(time);
|
||||
if(this._sgNode) {
|
||||
this._sgNode.seekTo(time);
|
||||
}
|
||||
},
|
||||
get: function () {
|
||||
return this._time;
|
||||
if(this._sgNode) {
|
||||
return this._sgNode.currentTime();
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -185,7 +213,6 @@ var VideoPlayer = cc.Class({
|
||||
},
|
||||
|
||||
onLoad: function() {
|
||||
|
||||
if(CC_JSB) {
|
||||
if (cc.sys.os === cc.sys.OS_OSX || cc.sys.os === cc.sys.OS_WINDOWS) {
|
||||
this.enabled = false;
|
||||
@@ -293,6 +320,28 @@ var VideoPlayer = cc.Class({
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Gets the duration of the video
|
||||
* !#zh 获取视频文件的播放总时长
|
||||
*/
|
||||
getDuration: function() {
|
||||
if(this._sgNode) {
|
||||
return this._sgNode.duration();
|
||||
}
|
||||
return -1;
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Determine whether video is playing or not.
|
||||
* !#zh 判断当前视频是否处于播放状态
|
||||
*/
|
||||
isPlaying: function() {
|
||||
if(this._sgNode) {
|
||||
return this._sgNode.isPlaying();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
cc.VideoPlayer = module.exports = VideoPlayer;
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
/*global _ccsg */
|
||||
|
||||
/****************************************************************************
|
||||
Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
http://www.cocos.com
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated engine source code (the "Software"), a limited,
|
||||
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
|
||||
to use Cocos Creator solely to develop games on your target platforms. You shall
|
||||
not use Cocos Creator software for developing other software or tools that's
|
||||
used for developing games. You are not granted to publish, distribute,
|
||||
sublicense, and/or sell copies of Cocos Creator.
|
||||
The software or tools in this License Agreement are licensed, not sold.
|
||||
Chukong Aipu reserves all rights not expressly granted to you.
|
||||
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.
|
||||
****************************************************************************/
|
||||
|
||||
/**
|
||||
* !#en WebView event type
|
||||
* !#zh 网页视图事件类型
|
||||
* @enum WebView.EventType
|
||||
*/
|
||||
var EventType = _ccsg.WebView.EventType;
|
||||
|
||||
|
||||
/**
|
||||
* !#en Web page Load completed.
|
||||
* !#zh 网页加载完成
|
||||
* @property {String} LOADED
|
||||
*/
|
||||
|
||||
/**
|
||||
* !#en Web page is loading.
|
||||
* !#zh 网页加载中
|
||||
* @property {String} LOADING
|
||||
*/
|
||||
|
||||
/**
|
||||
* !#en Web page error occurs when loading.
|
||||
* !#zh 网页加载出错
|
||||
* @property {String} ERROR
|
||||
*/
|
||||
|
||||
/**
|
||||
* !#en cc.WebView is a component for display web pages in the game
|
||||
* !#zh WebView 组件,用于在游戏中显示网页
|
||||
* @class WebView
|
||||
* @extends _RendererUnderSG
|
||||
*/
|
||||
var WebView = cc.Class({
|
||||
name: 'cc.WebView',
|
||||
extends: cc._RendererUnderSG,
|
||||
|
||||
editor: CC_EDITOR && {
|
||||
menu: 'i18n:MAIN_MENU.component.ui/WebView'
|
||||
},
|
||||
|
||||
properties: {
|
||||
_useOriginalSize: true,
|
||||
|
||||
_url: '',
|
||||
/**
|
||||
* !#en A given URL to be loaded by the WebView, it should have a http or https prefix.
|
||||
* !#zh 指定 WebView 加载的网址,它应该是一个 http 或者 https 开头的字符串
|
||||
* @property {String} url
|
||||
*/
|
||||
url: {
|
||||
type: String,
|
||||
tooltip: 'i18n:COMPONENT.webview.url',
|
||||
get: function () {
|
||||
return this._url;
|
||||
},
|
||||
set: function (url) {
|
||||
this._url = url;
|
||||
var sgNode = this._sgNode;
|
||||
if (sgNode) {
|
||||
sgNode.loadURL(url);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en The webview's event callback , it will be triggered when certain webview event occurs.
|
||||
* !#zh WebView 的回调事件,当网页加载过程中,加载完成后或者加载出错时都会回调此函数
|
||||
* @property {cc.Component.EventHandler[]} webviewLoadedEvents
|
||||
*/
|
||||
webviewEvents: {
|
||||
default: [],
|
||||
type: cc.Component.EventHandler,
|
||||
},
|
||||
},
|
||||
|
||||
statics: {
|
||||
EventType: EventType,
|
||||
},
|
||||
|
||||
onLoad: CC_JSB && function() {
|
||||
if (cc.sys.os === cc.sys.OS_OSX || cc.sys.os === cc.sys.OS_WINDOWS) {
|
||||
this.enabled = false;
|
||||
}
|
||||
},
|
||||
|
||||
_createSgNode: function () {
|
||||
if(CC_JSB) {
|
||||
if (cc.sys.os === cc.sys.OS_OSX || cc.sys.os === cc.sys.OS_WINDOWS) {
|
||||
console.log('WebView is not supported on Mac and Windows!');
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return new _ccsg.WebView();
|
||||
},
|
||||
|
||||
_initSgNode: function () {
|
||||
var sgNode = this._sgNode;
|
||||
if (!sgNode) return;
|
||||
|
||||
if(!CC_JSB) {
|
||||
sgNode.createDomElementIfNeeded();
|
||||
}
|
||||
sgNode.setEventListener(EventType.LOADED , this._onWebViewLoaded.bind(this));
|
||||
sgNode.setEventListener(EventType.LOADING , this._onWebViewLoading.bind(this));
|
||||
sgNode.setEventListener(EventType.ERROR , this._onWebViewLoadError.bind(this));
|
||||
|
||||
sgNode.loadURL(this._url);
|
||||
|
||||
if (CC_EDITOR && this._useOriginalSize) {
|
||||
this.node.setContentSize(sgNode.getContentSize());
|
||||
this._useOriginalSize = false;
|
||||
} else {
|
||||
sgNode.setContentSize(this.node.getContentSize());
|
||||
}
|
||||
},
|
||||
|
||||
_onWebViewLoaded: function () {
|
||||
cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.LOADED);
|
||||
},
|
||||
|
||||
_onWebViewLoading: function () {
|
||||
cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.LOADING);
|
||||
return true;
|
||||
},
|
||||
|
||||
_onWebViewLoadError: function () {
|
||||
cc.Component.EventHandler.emitEvents(this.webviewEvents, this, EventType.ERROR);
|
||||
}
|
||||
|
||||
});
|
||||
|
||||
cc.WebView = module.exports = WebView;
|
||||
@@ -38,8 +38,10 @@ var LEFT_RIGHT = LEFT | RIGHT;
|
||||
* !#en
|
||||
* Stores and manipulate the anchoring based on its parent.
|
||||
* Widget are used for GUI but can also be used for other things.
|
||||
* Widget will adjust current node's position and size automatically, but the results after adjustment can not be obtained until the next frame.
|
||||
* !#zh
|
||||
* Widget 组件,用于设置和适配其相对于父节点的边距,Widget 通常被用于 UI 界面,也可以用于其他地方。
|
||||
* Widget 会自动调整当前节点的坐标和宽高,不过目前调整后的结果要到下一帧才能在脚本里获取到。
|
||||
* @class Widget
|
||||
* @extends Component
|
||||
*/
|
||||
@@ -301,8 +303,80 @@ var Widget = cc.Class({
|
||||
tooltip: 'i18n:COMPONENT.widget.right',
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en
|
||||
* Horizontal aligns the midpoint offset value,
|
||||
* the value can be negative, Only available in 'isAlignHorizontalCenter' open.
|
||||
* !#zh 水平居中的偏移值,可填写负值,只有在 isAlignHorizontalCenter 开启时才有作用。
|
||||
* @property horizontalCenter
|
||||
* @type {Number}
|
||||
* @default 0
|
||||
*/
|
||||
horizontalCenter: {
|
||||
get: function () {
|
||||
return this._horizontalCenter;
|
||||
},
|
||||
set: function (value) {
|
||||
this._horizontalCenter = value;
|
||||
},
|
||||
tooltip: 'i18n:COMPONENT.widget.horizontal_center',
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en
|
||||
* Vertical aligns the midpoint offset value,
|
||||
* the value can be negative, Only available in 'isAlignVerticalCenter' open.
|
||||
* !#zh 垂直居中的偏移值,可填写负值,只有在 isAlignVerticalCenter 开启时才有作用。
|
||||
* @property verticalCenter
|
||||
* @type {Number}
|
||||
* @default 0
|
||||
*/
|
||||
verticalCenter: {
|
||||
get: function () {
|
||||
return this._verticalCenter;
|
||||
},
|
||||
set: function (value) {
|
||||
this._verticalCenter = value;
|
||||
},
|
||||
tooltip: 'i18n:COMPONENT.widget.vertical_center',
|
||||
},
|
||||
|
||||
// PARCENTAGE OR ABSOLUTE
|
||||
|
||||
/**
|
||||
* !#en If true, horizontalCenter is pixel margin, otherwise is percentage (0 - 1) margin.
|
||||
* !#zh 如果为 true,"horizontalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。
|
||||
* @property isAbsoluteHorizontalCenter
|
||||
* @type {Boolean}
|
||||
* @default true
|
||||
*/
|
||||
isAbsoluteHorizontalCenter: {
|
||||
get: function () {
|
||||
return this._isAbsHorizontalCenter;
|
||||
},
|
||||
set: function (value) {
|
||||
this._isAbsHorizontalCenter = value;
|
||||
},
|
||||
animatable: false
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en If true, verticalCenter is pixel margin, otherwise is percentage (0 - 1) margin.
|
||||
* !#zh 如果为 true,"verticalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。
|
||||
* @property isAbsoluteVerticalCenter
|
||||
* @type {Boolean}
|
||||
* @default true
|
||||
*/
|
||||
isAbsoluteVerticalCenter: {
|
||||
get: function () {
|
||||
return this._isAbsVerticalCenter;
|
||||
},
|
||||
set: function (value) {
|
||||
this._isAbsVerticalCenter = value;
|
||||
},
|
||||
animatable: false
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en
|
||||
* If true, top is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's height.
|
||||
@@ -411,10 +485,14 @@ var Widget = cc.Class({
|
||||
_right: 0,
|
||||
_top: 0,
|
||||
_bottom: 0,
|
||||
_verticalCenter: 0,
|
||||
_horizontalCenter: 0,
|
||||
_isAbsLeft: true,
|
||||
_isAbsRight: true,
|
||||
_isAbsTop: true,
|
||||
_isAbsBottom: true,
|
||||
_isAbsHorizontalCenter: true,
|
||||
_isAbsVerticalCenter: true,
|
||||
|
||||
// original size before align
|
||||
_originalWidth: 0,
|
||||
|
||||
@@ -44,6 +44,8 @@ module.exports = [
|
||||
require('./CCLayout'),
|
||||
require('./CCEditBox'),
|
||||
require('./CCVideoPlayer'),
|
||||
require('./CCWebView'),
|
||||
require('./CCSpriteDistortion'),
|
||||
require('./CCLabelOutline'),
|
||||
require('./CCRichText'),
|
||||
];
|
||||
|
||||
@@ -25,10 +25,23 @@
|
||||
|
||||
var JS = cc.js;
|
||||
|
||||
/*
|
||||
* A temp fallback to contain the original serialized data which can not be loaded.
|
||||
*/
|
||||
var MissingClass = cc.Class({
|
||||
name: 'cc.MissingClass',
|
||||
properties: {
|
||||
// the serialized data for original object
|
||||
_$erialized: {
|
||||
default: null,
|
||||
visible: false,
|
||||
editorOnly: true
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
/*
|
||||
* A temp fallback to contain the original component which can not be loaded.
|
||||
* Actually, this class will be used whenever a class failed to deserialize,
|
||||
* regardless of whether it is child class of component.
|
||||
*/
|
||||
var MissingScript = cc.Class({
|
||||
name: 'cc.MissingScript',
|
||||
@@ -84,19 +97,25 @@ var MissingScript = cc.Class({
|
||||
* @param {string} id
|
||||
* @return {function} constructor
|
||||
*/
|
||||
safeFindClass: function (id) {
|
||||
safeFindClass: function (id, data) {
|
||||
var cls = JS._getClassById(id);
|
||||
if (cls) {
|
||||
return cls;
|
||||
}
|
||||
if (id) {
|
||||
return MissingScript;
|
||||
cc.deserialize.reportMissingClass(id);
|
||||
if (data.node && (CC_EDITOR && Editor.UuidUtils.isUuid(id))) {
|
||||
return MissingScript;
|
||||
}
|
||||
else {
|
||||
return MissingClass;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
},
|
||||
onLoad: function () {
|
||||
cc.warn('The referenced component script on node "%s" is missing!', this.node.name);
|
||||
cc.warn('Script attached to "%s" is missing or invalid.', this.node.name);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -26,6 +26,31 @@
|
||||
THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
|
||||
// https://segmentfault.com/q/1010000002914610
|
||||
var SCROLLY = 40;
|
||||
var TIMER_NAME = 400;
|
||||
var LEFT_PADDING = 2;
|
||||
|
||||
function scrollWindowUp(editBox) {
|
||||
if (cc.sys.os === cc.sys.OS_IOS && cc.sys.osMainVersion === 9) {
|
||||
var worldPos = editBox.convertToWorldSpace(cc.p(0,0));
|
||||
var windowHeight = cc.visibleRect.height;
|
||||
var windowWidth = cc.visibleRect.width;
|
||||
var factor = 0.5;
|
||||
if(windowWidth > windowHeight) {
|
||||
factor = 0.7;
|
||||
}
|
||||
setTimeout(function() {
|
||||
if(window.scrollY < SCROLLY && worldPos.y < windowHeight * factor) {
|
||||
var scrollOffset = windowHeight * factor - worldPos.y - window.scrollY;
|
||||
if (scrollOffset < 35) scrollOffset = 35;
|
||||
if (scrollOffset > 320) scrollOffset = 320;
|
||||
window.scrollTo(0, scrollOffset);
|
||||
}
|
||||
}, TIMER_NAME);
|
||||
}
|
||||
}
|
||||
|
||||
var capitalize = function(string) {
|
||||
return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
|
||||
};
|
||||
@@ -223,7 +248,7 @@ _ccsg.EditBox = _ccsg.Node.extend({
|
||||
this._placeholderColor = cc.Color.GRAY;
|
||||
|
||||
this.initWithSizeAndBackgroundSprite(size, normal9SpriteBg);
|
||||
this._renderCmd.createNativeControl();
|
||||
this._renderCmd._createLabels();
|
||||
},
|
||||
|
||||
_createRenderCmd: function () {
|
||||
@@ -255,9 +280,9 @@ _ccsg.EditBox = _ccsg.Node.extend({
|
||||
},
|
||||
|
||||
cleanup: function () {
|
||||
this._super();
|
||||
|
||||
this._renderCmd._removeDomInputControl();
|
||||
this.stopAllActions();
|
||||
this.unscheduleAllCallbacks();
|
||||
},
|
||||
|
||||
_onTouchBegan: function (touch) {
|
||||
@@ -492,7 +517,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType;
|
||||
scaleX /= dpr;
|
||||
scaleY /= dpr;
|
||||
|
||||
var container = cc.container;
|
||||
var container = cc.game.container;
|
||||
var a = t.a * scaleX, b = t.b, c = t.c, d = t.d * scaleY;
|
||||
|
||||
var offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft);
|
||||
@@ -519,12 +544,22 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType;
|
||||
var editBox = this._edTxt;
|
||||
if (node.visible) {
|
||||
editBox.style.visibility = 'visible';
|
||||
cc.game.container.appendChild(editBox);
|
||||
} else {
|
||||
editBox.style.visibility = 'hidden';
|
||||
var hasChild = false;
|
||||
if('contains' in cc.game.container) {
|
||||
hasChild = cc.game.container.contains(editBox);
|
||||
}else {
|
||||
hasChild = cc.game.container.compareDocumentPosition(editBox) % 16;
|
||||
}
|
||||
if(hasChild)
|
||||
cc.game.container.removeChild(editBox);
|
||||
}
|
||||
};
|
||||
|
||||
proto._createDomInput = function () {
|
||||
this._removeDomInputControl();
|
||||
var thisPointer = this;
|
||||
var tmpEdTxt = this._edTxt = document.createElement('input');
|
||||
tmpEdTxt.type = 'text';
|
||||
@@ -541,15 +576,23 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType;
|
||||
tmpEdTxt.style.display = 'none';
|
||||
tmpEdTxt.style.position = "absolute";
|
||||
tmpEdTxt.style.bottom = "0px";
|
||||
tmpEdTxt.style.left = "0px";
|
||||
tmpEdTxt.style.left = LEFT_PADDING + "px";
|
||||
tmpEdTxt.style.className = "cocosEditBox";
|
||||
|
||||
tmpEdTxt.addEventListener('input', function () {
|
||||
var editBox = thisPointer._editBox;
|
||||
|
||||
|
||||
if (this.value.length > this.maxLength) {
|
||||
this.value = this.value.slice(0, this.maxLength);
|
||||
}
|
||||
|
||||
if (editBox._delegate && editBox._delegate.editBoxTextChanged) {
|
||||
editBox._text = this.value;
|
||||
thisPointer._updateEditBoxContentStyle();
|
||||
editBox._delegate.editBoxTextChanged(editBox, editBox._text);
|
||||
if (editBox._text.toLowerCase() !== this.value.toLowerCase()) {
|
||||
editBox._text = this.value;
|
||||
thisPointer._updateEditBoxContentStyle();
|
||||
editBox._delegate.editBoxTextChanged(editBox, editBox._text);
|
||||
}
|
||||
}
|
||||
});
|
||||
tmpEdTxt.addEventListener('keypress', function (e) {
|
||||
@@ -562,6 +605,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType;
|
||||
this.style.fontSize = editBox._placeholderFontSize + 'px';
|
||||
this.style.color = cc.colorToHex(editBox._placeholderColor);
|
||||
}
|
||||
|
||||
editBox._text = this.value;
|
||||
thisPointer._updateEditBoxContentStyle();
|
||||
thisPointer.hidden();
|
||||
@@ -571,10 +615,20 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType;
|
||||
cc._canvas.focus();
|
||||
}
|
||||
});
|
||||
|
||||
tmpEdTxt.addEventListener('focus', function () {
|
||||
var editBox = thisPointer._editBox;
|
||||
this.style.fontSize = thisPointer._edFontSize + 'px';
|
||||
this.style.color = cc.colorToHex(editBox._textColor);
|
||||
if(cc.view.isAutoFullScreenEnabled()) {
|
||||
thisPointer.__fullscreen = true;
|
||||
cc.view.enableAutoFullScreen(false);
|
||||
cc.screen.exitFullScreen();
|
||||
} else {
|
||||
thisPointer.__fullscreen = false;
|
||||
}
|
||||
|
||||
scrollWindowUp(editBox);
|
||||
|
||||
if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan) {
|
||||
editBox._delegate.editBoxEditingDidBegan(editBox);
|
||||
@@ -584,7 +638,10 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType;
|
||||
var editBox = thisPointer._editBox;
|
||||
editBox._text = this.value;
|
||||
thisPointer._updateEditBoxContentStyle();
|
||||
|
||||
if(thisPointer.__fullscreen) {
|
||||
cc.view.enableAutoFullScreen(true);
|
||||
}
|
||||
window.scrollY = 0;
|
||||
if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded) {
|
||||
editBox._delegate.editBoxEditingDidEnded(editBox);
|
||||
}
|
||||
@@ -599,6 +656,7 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType;
|
||||
};
|
||||
|
||||
proto._createDomTextArea = function () {
|
||||
this._removeDomInputControl();
|
||||
var thisPointer = this;
|
||||
var tmpEdTxt = this._edTxt = document.createElement('textarea');
|
||||
tmpEdTxt.type = 'text';
|
||||
@@ -617,15 +675,21 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType;
|
||||
tmpEdTxt.style.display = 'none';
|
||||
tmpEdTxt.style.position = "absolute";
|
||||
tmpEdTxt.style.bottom = "0px";
|
||||
tmpEdTxt.style.left = "0px";
|
||||
tmpEdTxt.style.left = LEFT_PADDING + "px";
|
||||
tmpEdTxt.style.className = "cocosEditBox";
|
||||
|
||||
tmpEdTxt.addEventListener('input', function () {
|
||||
if (this.value.length > this.maxLength) {
|
||||
this.value = this.value.slice(0, this.maxLength);
|
||||
}
|
||||
|
||||
var editBox = thisPointer._editBox;
|
||||
if (editBox._delegate && editBox._delegate.editBoxTextChanged) {
|
||||
editBox._text = this.value;
|
||||
thisPointer._updateEditBoxContentStyle();
|
||||
editBox._delegate.editBoxTextChanged(editBox, editBox._text);
|
||||
if(editBox._text.toLowerCase() !== this.value.toLowerCase()) {
|
||||
editBox._text = this.value;
|
||||
thisPointer._updateEditBoxContentStyle();
|
||||
editBox._delegate.editBoxTextChanged(editBox, editBox._text);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -634,6 +698,15 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType;
|
||||
|
||||
this.style.fontSize = thisPointer._edFontSize + 'px';
|
||||
this.style.color = cc.colorToHex(editBox._textColor);
|
||||
if(cc.view.isAutoFullScreenEnabled()) {
|
||||
thisPointer.__fullscreen = true;
|
||||
cc.view.enableAutoFullScreen(false);
|
||||
cc.screen.exitFullScreen();
|
||||
} else {
|
||||
thisPointer.__fullscreen = false;
|
||||
}
|
||||
|
||||
scrollWindowUp(editBox);
|
||||
|
||||
if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan) {
|
||||
editBox._delegate.editBoxEditingDidBegan(editBox);
|
||||
@@ -655,6 +728,10 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType;
|
||||
var editBox = thisPointer._editBox;
|
||||
editBox._text = this.value;
|
||||
thisPointer._updateEditBoxContentStyle();
|
||||
window.scrollY = 0;
|
||||
if(thisPointer.__fullscreen) {
|
||||
cc.view.enableAutoFullScreen(true);
|
||||
}
|
||||
|
||||
if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded) {
|
||||
editBox._delegate.editBoxEditingDidEnded(editBox);
|
||||
@@ -688,21 +765,22 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType;
|
||||
};
|
||||
|
||||
proto._updateLabelPosition = function (editBoxSize) {
|
||||
this._textLabel.setContentSize(editBoxSize);
|
||||
var labelContentSize = cc.size(editBoxSize.width - LEFT_PADDING, editBoxSize.height);
|
||||
this._textLabel.setContentSize(labelContentSize);
|
||||
this._placeholderLabel.setLineHeight(editBoxSize.height);
|
||||
var placeholderLabelSize = this._placeholderLabel.getContentSize();
|
||||
|
||||
if (this._editBox._editBoxInputMode === InputMode.ANY){
|
||||
this._textLabel.setPosition(0, editBoxSize.height);
|
||||
this._placeholderLabel.setPosition(0, editBoxSize.height);
|
||||
this._textLabel.setPosition(LEFT_PADDING, editBoxSize.height);
|
||||
this._placeholderLabel.setPosition(LEFT_PADDING, editBoxSize.height);
|
||||
this._placeholderLabel.setVerticalAlign(cc.VerticalTextAlignment.TOP);
|
||||
this._textLabel.setVerticalAlign(cc.VerticalTextAlignment.TOP);
|
||||
this._textLabel.enableWrapText(true);
|
||||
}
|
||||
else {
|
||||
this._textLabel.enableWrapText(false);
|
||||
this._textLabel.setPosition(0, editBoxSize.height);
|
||||
this._placeholderLabel.setPosition(0, (editBoxSize.height + placeholderLabelSize.height) / 2);
|
||||
this._textLabel.setPosition(LEFT_PADDING, editBoxSize.height);
|
||||
this._placeholderLabel.setPosition(LEFT_PADDING, (editBoxSize.height + placeholderLabelSize.height) / 2);
|
||||
this._placeholderLabel.setVerticalAlign(cc.VerticalTextAlignment.CENTER);
|
||||
this._textLabel.setVerticalAlign(cc.VerticalTextAlignment.CENTER);
|
||||
}
|
||||
@@ -929,24 +1007,23 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType;
|
||||
proto.createNativeControl = function() {
|
||||
this._createDomTextArea();
|
||||
this._addDomInputControl();
|
||||
this._createLabels();
|
||||
};
|
||||
|
||||
proto._addDomInputControl = function () {
|
||||
cc.container.appendChild(this._edTxt);
|
||||
cc.game.container.appendChild(this._edTxt);
|
||||
};
|
||||
|
||||
proto._removeDomInputControl = function () {
|
||||
var editBox = this._edTxt;
|
||||
if(editBox){
|
||||
var hasChild = false;
|
||||
if('contains' in cc.container) {
|
||||
hasChild = cc.container.contains(editBox);
|
||||
if('contains' in cc.game.container) {
|
||||
hasChild = cc.game.container.contains(editBox);
|
||||
}else {
|
||||
hasChild = cc.container.compareDocumentPosition(editBox) % 16;
|
||||
hasChild = cc.game.container.compareDocumentPosition(editBox) % 16;
|
||||
}
|
||||
if(hasChild)
|
||||
cc.container.removeChild(editBox);
|
||||
cc.game.container.removeChild(editBox);
|
||||
}
|
||||
this._edTxt = null;
|
||||
};
|
||||
@@ -955,7 +1032,6 @@ _ccsg.EditBox.KeyboardReturnType = KeyboardReturnType;
|
||||
this._editBox = node;
|
||||
|
||||
//it's a dom node, may be assigned with Input or TextArea.
|
||||
this._edTxt = null;
|
||||
this._edFontSize = 14;
|
||||
this._edFontName = 'Arial';
|
||||
this._textLabel = null;
|
||||
|
||||
@@ -44,7 +44,7 @@
|
||||
* @param {Number} type
|
||||
* @param {Number} listenerID
|
||||
* @param {Number} callback
|
||||
* @return {EventListner}
|
||||
* @return {EventListener}
|
||||
*/
|
||||
cc.EventListener = cc._Class.extend(/** @lends cc.EventListener# */{
|
||||
_onEvent: null, // Event callback function
|
||||
|
||||
@@ -536,7 +536,7 @@ EventTouch.CANCELED = 3;
|
||||
* @param {Object} acc - The acceleration
|
||||
* @param {Boolean} bubbles - A boolean indicating whether the event bubbles up through the tree or not
|
||||
*/
|
||||
EventAcceleration = function (acc, bubbles) {
|
||||
var EventAcceleration = function (acc, bubbles) {
|
||||
cc.Event.call(this, Event.ACCELERATION, bubbles);
|
||||
this._acc = acc;
|
||||
};
|
||||
@@ -552,7 +552,7 @@ JS.extend(EventAcceleration, cc.Event);
|
||||
* @param {Boolean} isPressed - A boolean indicating whether the key have been pressed
|
||||
* @param {Boolean} bubbles - A boolean indicating whether the event bubbles up through the tree or not
|
||||
*/
|
||||
EventKeyboard = function (keyCode, isPressed, bubbles) {
|
||||
var EventKeyboard = function (keyCode, isPressed, bubbles) {
|
||||
cc.Event.call(this, Event.KEYBOARD, bubbles);
|
||||
this._keyCode = keyCode;
|
||||
this._isPressed = isPressed;
|
||||
|
||||
@@ -163,6 +163,7 @@ cc.Touch = cc._Class.extend(/** @lends cc.Touch# */{
|
||||
this._id = id;
|
||||
if(!this._startPointCaptured){
|
||||
this._startPoint = cc.p(this._point);
|
||||
cc.view._convertPointWithScale(this._startPoint);
|
||||
this._startPointCaptured = true;
|
||||
}
|
||||
},
|
||||
|
||||
@@ -56,7 +56,15 @@ var _doDispatchEvent = function (owner, event) {
|
||||
// Event.AT_TARGET
|
||||
// checks if destroyed in capturing callbacks
|
||||
if (owner._isTargetActive(event.type)) {
|
||||
_doSendEvent(owner, event);
|
||||
// Event.AT_TARGET
|
||||
event.eventPhase = 2;
|
||||
event.currentTarget = owner;
|
||||
if (owner._capturingListeners) {
|
||||
owner._capturingListeners.invoke(event);
|
||||
}
|
||||
if (!event._propagationImmediateStopped && owner._bubblingListeners) {
|
||||
owner._bubblingListeners.invoke(event);
|
||||
}
|
||||
}
|
||||
|
||||
if (!event._propagationStopped && event.bubbles) {
|
||||
@@ -81,22 +89,6 @@ var _doDispatchEvent = function (owner, event) {
|
||||
cachedArray.length = 0;
|
||||
};
|
||||
|
||||
|
||||
var _doSendEvent = function (owner, event) {
|
||||
// Event.AT_TARGET
|
||||
event.eventPhase = 2;
|
||||
event.currentTarget = owner;
|
||||
if (owner._capturingListeners) {
|
||||
owner._capturingListeners.invoke(event);
|
||||
if (event._propagationImmediateStopped) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (owner._bubblingListeners) {
|
||||
owner._bubblingListeners.invoke(event);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* !#en
|
||||
* EventTarget is an object to which an event is dispatched when something has occurred.
|
||||
@@ -337,7 +329,16 @@ JS.mixin(EventTarget.prototype, {
|
||||
|
||||
var event = new cc.Event.EventCustom(message);
|
||||
event.detail = detail;
|
||||
_doSendEvent(this, event);
|
||||
|
||||
// Event.AT_TARGET
|
||||
event.eventPhase = 2;
|
||||
event.target = event.currentTarget = this;
|
||||
if (caplisteners) {
|
||||
this._capturingListeners.invoke(event);
|
||||
}
|
||||
if (bublisteners && !event._propagationImmediateStopped) {
|
||||
this._bubblingListeners.invoke(event);
|
||||
}
|
||||
},
|
||||
|
||||
/*
|
||||
|
||||
@@ -53,7 +53,7 @@ cc.Event = function(type, bubbles) {
|
||||
* @property bubbles
|
||||
* @type {Boolean}
|
||||
*/
|
||||
this.bubbles = bubbles || false;
|
||||
this.bubbles = !!bubbles;
|
||||
|
||||
/**
|
||||
* !#en A reference to the target to which the event was originally dispatched.
|
||||
|
||||
@@ -27,16 +27,7 @@ var Js = cc.js;
|
||||
var LineCap = require('./types').LineCap;
|
||||
var LineJoin = require('./types').LineJoin;
|
||||
|
||||
var PI = 3.14159265358979323846264338327;
|
||||
|
||||
var min = Math.min;
|
||||
var max = Math.max;
|
||||
var cos = Math.cos;
|
||||
var sin = Math.sin;
|
||||
var abs = Math.abs;
|
||||
var sign = Math.sign;
|
||||
|
||||
var KAPPA90 = 0.5522847493;
|
||||
var Helper = require('./helper');
|
||||
|
||||
var CanvasRenderCmd = function (renderable) {
|
||||
_ccsg.Node.CanvasRenderCmd.call(this, renderable);
|
||||
@@ -47,12 +38,19 @@ var CanvasRenderCmd = function (renderable) {
|
||||
var _p = CanvasRenderCmd.prototype = Object.create(_ccsg.Node.CanvasRenderCmd.prototype);
|
||||
_p.constructor = CanvasRenderCmd;
|
||||
|
||||
_p._updateCurrentRegions = function() {
|
||||
var temp = this._currentRegion;
|
||||
this._currentRegion = this._oldRegion;
|
||||
this._oldRegion = temp;
|
||||
this._currentRegion.setTo(0,0, cc.visibleRect.width, cc.visibleRect.height);
|
||||
};
|
||||
|
||||
_p.rendering = function (ctx, scaleX, scaleY) {
|
||||
var wrapper = ctx || cc._renderContext, context = wrapper.getContext();
|
||||
wrapper.setTransform(this._worldTransform, scaleX, scaleY);
|
||||
|
||||
context.save();
|
||||
context.scale(scaleX, -scaleY);
|
||||
context.scale(1, -1);
|
||||
|
||||
var endPath = true;
|
||||
var cmds = this.cmds;
|
||||
@@ -63,7 +61,8 @@ _p.rendering = function (ctx, scaleX, scaleY) {
|
||||
if (ctxCmd === 'clear') {
|
||||
cmds.splice(0, i+1);
|
||||
i = 0;
|
||||
return;
|
||||
l = cmds.length;
|
||||
continue;
|
||||
}
|
||||
else if (ctxCmd === 'moveTo' && endPath) {
|
||||
context.beginPath();
|
||||
@@ -87,12 +86,12 @@ _p.rendering = function (ctx, scaleX, scaleY) {
|
||||
// draw api
|
||||
Js.mixin(_p, {
|
||||
setStrokeColor: function (v) {
|
||||
var fillStyle = "rgba(" + (0 | v.r) + "," + (0 | v.g) + "," + (0 | v.b) + "," + v.a / 255 + ")";
|
||||
var fillStyle = 'rgba(' + (0 | v.r) + ',' + (0 | v.g) + ',' + (0 | v.b) + ',' + v.a / 255 + ')';
|
||||
this.cmds.push(['strokeStyle', fillStyle]);
|
||||
},
|
||||
|
||||
setFillColor: function (v) {
|
||||
var fillStyle = "rgba(" + (0 | v.r) + "," + (0 | v.g) + "," + (0 | v.b) + "," + v.a / 255 + ")";
|
||||
var fillStyle = 'rgba(' + (0 | v.r) + ',' + (0 | v.g) + ',' + (0 | v.b) + ',' + v.a / 255 + ')';
|
||||
this.cmds.push(['fillStyle', fillStyle]);
|
||||
},
|
||||
|
||||
@@ -150,69 +149,16 @@ Js.mixin(_p, {
|
||||
},
|
||||
|
||||
//
|
||||
arc: function (cx, cy, r, a0, a1, counterclockwise) {
|
||||
// this.cmds.push(['arc', arguments]);
|
||||
var a = 0, da = 0, hda = 0, kappa = 0;
|
||||
var dx = 0, dy = 0, x = 0, y = 0, tanx = 0, tany = 0;
|
||||
var px = 0, py = 0, ptanx = 0, ptany = 0;
|
||||
var i, ndivs;
|
||||
|
||||
// Clamp angles
|
||||
da = a1 - a0;
|
||||
if (!counterclockwise) {
|
||||
if (abs(da) >= PI * 2) {
|
||||
da = PI * 2;
|
||||
} else {
|
||||
while (da < 0) da += PI * 2;
|
||||
}
|
||||
} else {
|
||||
if (abs(da) >= PI * 2) {
|
||||
da = -PI * 2;
|
||||
} else {
|
||||
while (da > 0) da -= PI * 2;
|
||||
}
|
||||
}
|
||||
|
||||
// Split arc into max 90 degree segments.
|
||||
ndivs = max(1, min(abs(da) / (PI * 0.5) + 0.5, 5)) | 0;
|
||||
hda = da / ndivs / 2.0;
|
||||
kappa = abs(4.0 / 3.0 * (1 - cos(hda)) / sin(hda));
|
||||
|
||||
if (counterclockwise) kappa = -kappa;
|
||||
|
||||
for (i = 0; i <= ndivs; i++) {
|
||||
a = a0 + da * (i / ndivs);
|
||||
dx = cos(a);
|
||||
dy = sin(a);
|
||||
x = cx + dx * r;
|
||||
y = cy + dy * r;
|
||||
tanx = -dy * r * kappa;
|
||||
tany = dx * r * kappa;
|
||||
|
||||
if (i === 0) {
|
||||
this.moveTo(x, y);
|
||||
} else {
|
||||
this.bezierCurveTo(px + ptanx, py + ptany, x - tanx, y - tany, x, y);
|
||||
}
|
||||
px = x;
|
||||
py = y;
|
||||
ptanx = tanx;
|
||||
ptany = tany;
|
||||
}
|
||||
arc: function (cx, cy, r, startAngle, endAngle, counterclockwise) {
|
||||
Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise);
|
||||
},
|
||||
|
||||
ellipse: function (cx, cy, rx, ry) {
|
||||
this.moveTo(cx - rx, cy);
|
||||
this.bezierCurveTo(cx - rx, cy + ry * KAPPA90, cx - rx * KAPPA90, cy + ry, cx, cy + ry);
|
||||
this.bezierCurveTo(cx + rx * KAPPA90, cy + ry, cx + rx, cy + ry * KAPPA90, cx + rx, cy);
|
||||
this.bezierCurveTo(cx + rx, cy - ry * KAPPA90, cx + rx * KAPPA90, cy - ry, cx, cy - ry);
|
||||
this.bezierCurveTo(cx - rx * KAPPA90, cy - ry, cx - rx, cy - ry * KAPPA90, cx - rx, cy);
|
||||
this.close();
|
||||
Helper.ellipse(this, cx, cy, rx, ry);
|
||||
},
|
||||
|
||||
circle: function (cx, cy, r) {
|
||||
this.ellipse(cx, cy, r, r);
|
||||
this.close();
|
||||
Helper.ellipse(this, cx, cy, r, r);
|
||||
},
|
||||
|
||||
rect: function (x, y, w, h) {
|
||||
@@ -224,28 +170,12 @@ Js.mixin(_p, {
|
||||
},
|
||||
|
||||
roundRect: function (x, y, w, h, r) {
|
||||
if (r < 0.1) {
|
||||
this.rect(x, y, w, h);
|
||||
return;
|
||||
} else {
|
||||
var rx = min(r, abs(w) * 0.5) * sign(w),
|
||||
ry = min(r, abs(h) * 0.5) * sign(h);
|
||||
|
||||
this.moveTo(x, y + ry);
|
||||
this.lineTo(x, y + h - ry);
|
||||
this.bezierCurveTo(x, y + h - ry * (1 - KAPPA90), x + rx * (1 - KAPPA90), y + h, x + rx, y + h);
|
||||
this.lineTo(x + w - rx, y + h);
|
||||
this.bezierCurveTo(x + w - rx * (1 - KAPPA90), y + h, x + w, y + h - ry * (1 - KAPPA90), x + w, y + h - ry);
|
||||
this.lineTo(x + w, y + ry);
|
||||
this.bezierCurveTo(x + w, y + ry * (1 - KAPPA90), x + w - rx * (1 - KAPPA90), y, x + w - rx, y);
|
||||
this.lineTo(x + rx, y);
|
||||
this.bezierCurveTo(x + rx * (1 - KAPPA90), y, x, y + ry * (1 - KAPPA90), x, y + ry);
|
||||
this.close();
|
||||
}
|
||||
Helper.roundRect(this, x, y, w, h, r);
|
||||
},
|
||||
|
||||
fillRect: function (x, y, w, h) {
|
||||
this.cmds.push(['fillRect', arguments]);
|
||||
this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
|
||||
},
|
||||
|
||||
close: function () {
|
||||
@@ -254,14 +184,17 @@ Js.mixin(_p, {
|
||||
|
||||
stroke: function () {
|
||||
this.cmds.push(['stroke', arguments]);
|
||||
this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
|
||||
},
|
||||
|
||||
fill: function () {
|
||||
this.cmds.push(['fill', arguments]);
|
||||
this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
|
||||
},
|
||||
|
||||
clear: function () {
|
||||
this.cmds.push(['clear']);
|
||||
this.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -30,18 +30,18 @@ var LineJoin = require('./types').LineJoin;
|
||||
|
||||
var Earcut = require('./earcut');
|
||||
|
||||
var Helper = require('./helper');
|
||||
|
||||
var Vec2 = cc.Vec2;
|
||||
var Js = cc.js;
|
||||
|
||||
// Math
|
||||
var PI = 3.14159265358979323846264338327;
|
||||
var PI_2 = PI*2;
|
||||
var INIT_VERTS_SIZE = 32;
|
||||
var KAPPA90 = 0.5522847493;
|
||||
|
||||
var VERTS_FLOAT_LENGTH = 2;
|
||||
var VERTS_BYTE_LENGTH = 8;
|
||||
|
||||
var PI = Math.PI;
|
||||
var min = Math.min;
|
||||
var max = Math.max;
|
||||
var ceil = Math.ceil;
|
||||
@@ -50,7 +50,6 @@ var cos = Math.cos;
|
||||
var sin = Math.sin;
|
||||
var atan2 = Math.atan2;
|
||||
var abs = Math.abs;
|
||||
var sign = Math.sign;
|
||||
|
||||
function clamp (v, min, max) {
|
||||
if (v < min) {
|
||||
@@ -206,86 +205,17 @@ Js.mixin(_p, {
|
||||
},
|
||||
|
||||
//
|
||||
arc: function (cx, cy, r, a0, a1, counterclockwise) {
|
||||
var a = 0, da = 0, hda = 0, kappa = 0;
|
||||
var dx = 0, dy = 0, x = 0, y = 0, tanx = 0, tany = 0;
|
||||
var px = 0, py = 0, ptanx = 0, ptany = 0;
|
||||
var i, ndivs;
|
||||
|
||||
// Clamp angles
|
||||
da = a1 - a0;
|
||||
if (!counterclockwise) {
|
||||
if (abs(da) >= PI * 2) {
|
||||
da = PI * 2;
|
||||
} else {
|
||||
while (da < 0) da += PI * 2;
|
||||
}
|
||||
} else {
|
||||
if (abs(da) >= PI * 2) {
|
||||
da = -PI * 2;
|
||||
} else {
|
||||
while (da > 0) da -= PI * 2;
|
||||
}
|
||||
}
|
||||
|
||||
// Split arc into max 90 degree segments.
|
||||
ndivs = max(1, min(abs(da) / (PI * 0.5) + 0.5, 5)) | 0;
|
||||
hda = da / ndivs / 2.0;
|
||||
kappa = abs(4.0 / 3.0 * (1 - cos(hda)) / sin(hda));
|
||||
|
||||
if (counterclockwise) kappa = -kappa;
|
||||
|
||||
for (i = 0; i <= ndivs; i++) {
|
||||
a = a0 + da * (i / ndivs);
|
||||
dx = cos(a);
|
||||
dy = sin(a);
|
||||
x = cx + dx * r;
|
||||
y = cy + dy * r;
|
||||
tanx = -dy * r * kappa;
|
||||
tany = dx * r * kappa;
|
||||
|
||||
if (i === 0) {
|
||||
this.moveTo(x, y);
|
||||
} else {
|
||||
this.bezierCurveTo(px + ptanx, py + ptany, x - tanx, y - tany, x, y);
|
||||
}
|
||||
px = x;
|
||||
py = y;
|
||||
ptanx = tanx;
|
||||
ptany = tany;
|
||||
}
|
||||
|
||||
// this.close();
|
||||
// this._curPath.complex = false;
|
||||
arc: function (cx, cy, r, startAngle, endAngle, counterclockwise) {
|
||||
Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise);
|
||||
},
|
||||
|
||||
ellipse: function (cx, cy, rx, ry) {
|
||||
this.moveTo(cx - rx, cy);
|
||||
this.bezierCurveTo(cx - rx, cy + ry * KAPPA90, cx - rx * KAPPA90, cy + ry, cx, cy + ry);
|
||||
this.bezierCurveTo(cx + rx * KAPPA90, cy + ry, cx + rx, cy + ry * KAPPA90, cx + rx, cy);
|
||||
this.bezierCurveTo(cx + rx, cy - ry * KAPPA90, cx + rx * KAPPA90, cy - ry, cx, cy - ry);
|
||||
this.bezierCurveTo(cx - rx * KAPPA90, cy - ry, cx - rx, cy - ry * KAPPA90, cx - rx, cy);
|
||||
|
||||
this.close();
|
||||
Helper.ellipse(this, cx, cy, rx, ry);
|
||||
this._curPath.complex = false;
|
||||
},
|
||||
|
||||
circle: function (cx, cy, r) {
|
||||
// this.ellipse(cx, cy, r, r);
|
||||
var divs = this._curveDivs(r, PI_2, this._tessTol);
|
||||
var step = PI_2 / divs;
|
||||
|
||||
this.moveTo(cx, cy + r);
|
||||
|
||||
for (var i = 1; i < divs; i++) {
|
||||
var angle = step * i;
|
||||
var x = r * sin(angle);
|
||||
var y = r * cos(angle);
|
||||
|
||||
this.lineTo(cx + x, cy + y);
|
||||
}
|
||||
|
||||
this.close();
|
||||
Helper.ellipse(this, cx, cy, r, r);
|
||||
this._curPath.complex = false;
|
||||
},
|
||||
|
||||
@@ -299,25 +229,8 @@ Js.mixin(_p, {
|
||||
},
|
||||
|
||||
roundRect: function (x, y, w, h, r) {
|
||||
if (r < 0.1) {
|
||||
this.rect(x, y, w, h);
|
||||
return;
|
||||
} else {
|
||||
var rx = min(r, abs(w) * 0.5) * sign(w),
|
||||
ry = min(r, abs(h) * 0.5) * sign(h);
|
||||
|
||||
this.moveTo(x, y + ry);
|
||||
this.lineTo(x, y + h - ry);
|
||||
this.bezierCurveTo(x, y + h - ry * (1 - KAPPA90), x + rx * (1 - KAPPA90), y + h, x + rx, y + h);
|
||||
this.lineTo(x + w - rx, y + h);
|
||||
this.bezierCurveTo(x + w - rx * (1 - KAPPA90), y + h, x + w, y + h - ry * (1 - KAPPA90), x + w, y + h - ry);
|
||||
this.lineTo(x + w, y + ry);
|
||||
this.bezierCurveTo(x + w, y + ry * (1 - KAPPA90), x + w - rx * (1 - KAPPA90), y, x + w - rx, y);
|
||||
this.lineTo(x + rx, y);
|
||||
this.bezierCurveTo(x + rx * (1 - KAPPA90), y, x, y + ry * (1 - KAPPA90), x, y + ry);
|
||||
this.close();
|
||||
this._curPath.complex = false;
|
||||
}
|
||||
Helper.roundRect(this, x, y, w, h, r);
|
||||
this._curPath.complex = false;
|
||||
},
|
||||
|
||||
fillRect: function (x, y, w, h) {
|
||||
|
||||
@@ -26,6 +26,7 @@
|
||||
var LineCap = require('./types').LineCap;
|
||||
var LineJoin = require('./types').LineJoin;
|
||||
|
||||
|
||||
/**
|
||||
* @class Graphics
|
||||
* @extends _RendererUnderSG
|
||||
@@ -157,6 +158,15 @@ var Graphics = cc.Class({
|
||||
},
|
||||
|
||||
_createSgNode: function () {
|
||||
if (CC_JSB && !_ccsg.GraphicsNode) {
|
||||
var sgNode = new _ccsg.Node();
|
||||
var func = function () {};
|
||||
['moveTo', 'lineTo', 'bezierCurveTo', 'quadraticCurveTo', 'arc', 'ellipse', 'circle', 'rect', 'roundRect', 'fillRect', 'clear', 'close', 'stroke', 'fill'].forEach(function (funcName) {
|
||||
sgNode[funcName] = func;
|
||||
});
|
||||
return sgNode;
|
||||
}
|
||||
|
||||
return new _ccsg.GraphicsNode();
|
||||
},
|
||||
|
||||
@@ -168,6 +178,8 @@ var Graphics = cc.Class({
|
||||
sgNode.strokeColor = this._strokeColor;
|
||||
sgNode.fillColor = this._fillColor;
|
||||
sgNode.miterLimit = this._miterLimit;
|
||||
|
||||
sgNode.setContentSize(this.node.getContentSize(true));
|
||||
},
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
|
||||
var PI = Math.PI;
|
||||
var min = Math.min;
|
||||
var max = Math.max;
|
||||
var cos = Math.cos;
|
||||
var sin = Math.sin;
|
||||
var abs = Math.abs;
|
||||
var sign = Math.sign;
|
||||
|
||||
var KAPPA90 = 0.5522847493;
|
||||
|
||||
function arc (ctx, cx, cy, r, startAngle, endAngle, counterclockwise) {
|
||||
counterclockwise = counterclockwise || false;
|
||||
|
||||
var a = 0, da = 0, hda = 0, kappa = 0;
|
||||
var dx = 0, dy = 0, x = 0, y = 0, tanx = 0, tany = 0;
|
||||
var px = 0, py = 0, ptanx = 0, ptany = 0;
|
||||
var i, ndivs;
|
||||
|
||||
// Clamp angles
|
||||
da = endAngle - startAngle;
|
||||
if (counterclockwise) {
|
||||
if (abs(da) >= PI * 2) {
|
||||
da = PI * 2;
|
||||
} else {
|
||||
while (da < 0) da += PI * 2;
|
||||
}
|
||||
} else {
|
||||
if (abs(da) >= PI * 2) {
|
||||
da = -PI * 2;
|
||||
} else {
|
||||
while (da > 0) da -= PI * 2;
|
||||
}
|
||||
}
|
||||
|
||||
// Split arc into max 90 degree segments.
|
||||
ndivs = max(1, min(abs(da) / (PI * 0.5) + 0.5, 5)) | 0;
|
||||
hda = da / ndivs / 2.0;
|
||||
kappa = abs(4.0 / 3.0 * (1 - cos(hda)) / sin(hda));
|
||||
|
||||
if (!counterclockwise) kappa = -kappa;
|
||||
|
||||
for (i = 0; i <= ndivs; i++) {
|
||||
a = startAngle + da * (i / ndivs);
|
||||
dx = cos(a);
|
||||
dy = sin(a);
|
||||
x = cx + dx * r;
|
||||
y = cy + dy * r;
|
||||
tanx = -dy * r * kappa;
|
||||
tany = dx * r * kappa;
|
||||
|
||||
if (i === 0) {
|
||||
ctx.moveTo(x, y);
|
||||
} else {
|
||||
ctx.bezierCurveTo(px + ptanx, py + ptany, x - tanx, y - tany, x, y);
|
||||
}
|
||||
px = x;
|
||||
py = y;
|
||||
ptanx = tanx;
|
||||
ptany = tany;
|
||||
}
|
||||
}
|
||||
|
||||
function ellipse (ctx, cx, cy, rx, ry) {
|
||||
ctx.moveTo(cx - rx, cy);
|
||||
ctx.bezierCurveTo(cx - rx, cy + ry * KAPPA90, cx - rx * KAPPA90, cy + ry, cx, cy + ry);
|
||||
ctx.bezierCurveTo(cx + rx * KAPPA90, cy + ry, cx + rx, cy + ry * KAPPA90, cx + rx, cy);
|
||||
ctx.bezierCurveTo(cx + rx, cy - ry * KAPPA90, cx + rx * KAPPA90, cy - ry, cx, cy - ry);
|
||||
ctx.bezierCurveTo(cx - rx * KAPPA90, cy - ry, cx - rx, cy - ry * KAPPA90, cx - rx, cy);
|
||||
ctx.close();
|
||||
}
|
||||
|
||||
function roundRect (ctx, x, y, w, h, r) {
|
||||
if (r < 0.1) {
|
||||
ctx.rect(x, y, w, h);
|
||||
return;
|
||||
} else {
|
||||
var rx = min(r, abs(w) * 0.5) * sign(w),
|
||||
ry = min(r, abs(h) * 0.5) * sign(h);
|
||||
|
||||
ctx.moveTo(x, y + ry);
|
||||
ctx.lineTo(x, y + h - ry);
|
||||
ctx.bezierCurveTo(x, y + h - ry * (1 - KAPPA90), x + rx * (1 - KAPPA90), y + h, x + rx, y + h);
|
||||
ctx.lineTo(x + w - rx, y + h);
|
||||
ctx.bezierCurveTo(x + w - rx * (1 - KAPPA90), y + h, x + w, y + h - ry * (1 - KAPPA90), x + w, y + h - ry);
|
||||
ctx.lineTo(x + w, y + ry);
|
||||
ctx.bezierCurveTo(x + w, y + ry * (1 - KAPPA90), x + w - rx * (1 - KAPPA90), y, x + w - rx, y);
|
||||
ctx.lineTo(x + rx, y);
|
||||
ctx.bezierCurveTo(x + rx * (1 - KAPPA90), y, x, y + ry * (1 - KAPPA90), x, y + ry);
|
||||
ctx.close();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
module.exports = {
|
||||
arc: arc,
|
||||
ellipse: ellipse,
|
||||
roundRect: roundRect,
|
||||
};
|
||||
@@ -33,7 +33,9 @@ else {
|
||||
GraphicsNode = _ccsg.GraphicsNode = cc.GraphicsNode;
|
||||
}
|
||||
|
||||
var misc = require('../utils/misc');
|
||||
misc.propertyDefine(GraphicsNode, ['lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'deviceRatio', 'strokeColor', 'fillColor'], {});
|
||||
if (GraphicsNode) {
|
||||
var misc = require('../utils/misc');
|
||||
misc.propertyDefine(GraphicsNode, ['lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'deviceRatio', 'strokeColor', 'fillColor'], {});
|
||||
}
|
||||
|
||||
require('./graphics');
|
||||
|
||||
@@ -34,6 +34,7 @@ if (!CC_EDITOR || !Editor.isMainProcess) {
|
||||
require('./CCNode');
|
||||
require('./CCScene');
|
||||
|
||||
require('./label/CCHtmlTextParser.js');
|
||||
require('./components');
|
||||
require('./graphics');
|
||||
require('./collider');
|
||||
|
||||
@@ -0,0 +1,236 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos.com
|
||||
|
||||
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 eventRegx = /^(click)(\s)*=/;
|
||||
/**
|
||||
* A utils class for parsing HTML texts. The parsed results will be an object array.
|
||||
*/
|
||||
cc.HtmlTextParser = function() {
|
||||
this._parsedObject = {};
|
||||
this._specialSymbolArray = [];
|
||||
this._specialSymbolArray.push([/</g, '<']);
|
||||
this._specialSymbolArray.push([/>/g, '>']);
|
||||
this._specialSymbolArray.push([/&/g, '&']);
|
||||
this._specialSymbolArray.push([/"/g, '"']);
|
||||
this._specialSymbolArray.push([/'/g, '\'']);
|
||||
};
|
||||
|
||||
cc.HtmlTextParser.prototype = {
|
||||
constructor: cc.HtmlTextParser,
|
||||
parse: function(htmlString) {
|
||||
this._resultObjectArray = [];
|
||||
this._stack = [];
|
||||
|
||||
var startIndex = 0;
|
||||
var length = htmlString.length;
|
||||
while (startIndex < length) {
|
||||
var tagBeginIndex = htmlString.indexOf('<', startIndex);
|
||||
if (tagBeginIndex < 0) {
|
||||
this._stack.pop();
|
||||
this._processResult(htmlString.substring(startIndex));
|
||||
startIndex = length;
|
||||
} else {
|
||||
this._processResult(htmlString.substring(startIndex, tagBeginIndex));
|
||||
|
||||
var tagEndIndex = htmlString.indexOf('>', startIndex);
|
||||
if (tagEndIndex === -1) {
|
||||
// cc.error('The HTML tag is invalid!');
|
||||
tagEndIndex = tagBeginIndex;
|
||||
} else if (htmlString.charAt(tagBeginIndex + 1) === '\/'){
|
||||
this._stack.pop();
|
||||
} else {
|
||||
this._addToStack(htmlString.substring(tagBeginIndex + 1, tagEndIndex));
|
||||
}
|
||||
startIndex = tagEndIndex + 1;
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return this._resultObjectArray;
|
||||
},
|
||||
|
||||
_attributeToObject: function (attribute) {
|
||||
attribute = attribute.trim();
|
||||
|
||||
var obj = {};
|
||||
var header = attribute.match(/^(color|size)(\s)*=/);
|
||||
var tagName;
|
||||
var nextSpace;
|
||||
var eventObj;
|
||||
if (header) {
|
||||
tagName = header[0];
|
||||
attribute = attribute.substring(tagName.length).trim();
|
||||
if(attribute === "") return obj;
|
||||
|
||||
//parse color
|
||||
nextSpace = attribute.indexOf(' ');
|
||||
switch(tagName[0]){
|
||||
case 'c':
|
||||
if (nextSpace > -1) {
|
||||
obj.color = attribute.substring(0, nextSpace).trim();
|
||||
} else {
|
||||
obj.color = attribute;
|
||||
}
|
||||
break;
|
||||
case 's':
|
||||
obj.size = parseInt(attribute);
|
||||
break;
|
||||
}
|
||||
|
||||
//tag has event arguments
|
||||
if(nextSpace > -1) {
|
||||
var eventHanlderString = attribute.substring(nextSpace+1).trim();
|
||||
eventObj = this._processEventHandler(eventHanlderString);
|
||||
obj.event = eventObj;
|
||||
}
|
||||
}
|
||||
header = attribute.match(/^(br(\s)*\/)/);
|
||||
if(header && header[0].length > 0) {
|
||||
tagName = header[0].trim();
|
||||
if(tagName.startsWith("br") && tagName[tagName.length-1] === "/") {
|
||||
obj.isNewLine = true;
|
||||
this._resultObjectArray.push({text: "", style: {newline: true}});
|
||||
}
|
||||
}
|
||||
|
||||
header = attribute.match(/^(on|u|b|i)(\s)*/);
|
||||
if(header && header[0].length > 0) {
|
||||
tagName = header[0];
|
||||
attribute = attribute.substring(tagName.length).trim();
|
||||
switch(tagName[0]){
|
||||
case 'u':
|
||||
obj.underline = true;
|
||||
break;
|
||||
case 'i':
|
||||
obj.italic = true;
|
||||
break;
|
||||
case 'b':
|
||||
obj.bold = true;
|
||||
break;
|
||||
}
|
||||
if(attribute === "") {
|
||||
return obj;
|
||||
}
|
||||
eventObj = this._processEventHandler(attribute);
|
||||
obj.event = eventObj;
|
||||
}
|
||||
|
||||
|
||||
return obj;
|
||||
},
|
||||
|
||||
_processEventHandler: function (eventString) {
|
||||
var index = 0;
|
||||
var obj = {};
|
||||
var eventNames = eventString.match(eventRegx);
|
||||
var isValidTag = false;
|
||||
while(eventNames) {
|
||||
var eventName = eventNames[0];
|
||||
var eventValue = "";
|
||||
isValidTag = false;
|
||||
eventString = eventString.substring(eventName.length).trim();
|
||||
if(eventString.charAt(0) === "\"") {
|
||||
index = eventString.indexOf("\"", 1);
|
||||
if (index > -1) {
|
||||
eventValue = eventString.substring(1, index).trim();
|
||||
isValidTag = true;
|
||||
}
|
||||
index++;
|
||||
} else if(eventString.charAt(0) === "\'") {
|
||||
index = eventString.indexOf('\'', 1);
|
||||
if(index > -1) {
|
||||
eventValue = eventString.substring(1, index).trim();
|
||||
isValidTag = true;
|
||||
}
|
||||
index++;
|
||||
} else {
|
||||
//skip the invalid attribute value
|
||||
var match = eventString.match(/(\S)+/);
|
||||
if(match) {
|
||||
eventValue = match[0];
|
||||
} else {
|
||||
eventValue = "";
|
||||
}
|
||||
index = eventValue.length;
|
||||
}
|
||||
|
||||
if(isValidTag) {
|
||||
eventName = eventName.substring(0, eventName.length-1).trim();
|
||||
obj[eventName] = eventValue;
|
||||
}
|
||||
|
||||
eventString = eventString.substring(index).trim();
|
||||
eventNames = eventString.match(eventRegx);
|
||||
}
|
||||
|
||||
return obj;
|
||||
},
|
||||
|
||||
_addToStack: function(attribute) {
|
||||
var obj = this._attributeToObject(attribute);
|
||||
|
||||
if (this._stack.length === 0){
|
||||
this._stack.push(obj);
|
||||
} else {
|
||||
if(obj.isNewLine) {
|
||||
return;
|
||||
}
|
||||
//for nested tags
|
||||
var previousTagObj = this._stack[this._stack.length - 1];
|
||||
for (var key in previousTagObj) {
|
||||
if (!(obj[key])) {
|
||||
obj[key] = previousTagObj[key];
|
||||
}
|
||||
}
|
||||
this._stack.push(obj);
|
||||
}
|
||||
},
|
||||
|
||||
_processResult: function(value) {
|
||||
if (value === "") {
|
||||
return;
|
||||
}
|
||||
|
||||
value = this._escapeSpecialSymbol(value);
|
||||
if (this._stack.length > 0) {
|
||||
this._resultObjectArray.push({text: value, style: this._stack[this._stack.length - 1]});
|
||||
} else {
|
||||
this._resultObjectArray.push({text: value});
|
||||
}
|
||||
},
|
||||
|
||||
_escapeSpecialSymbol: function(str) {
|
||||
for(var i = 0; i < this._specialSymbolArray.length; ++i) {
|
||||
var key = this._specialSymbolArray[i][0];
|
||||
var value = this._specialSymbolArray[i][1];
|
||||
|
||||
str = str.replace(key, value);
|
||||
}
|
||||
return str;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
cc.htmlTextParser = new cc.HtmlTextParser();
|
||||
@@ -131,6 +131,10 @@ _ccsg.Label = _ccsg.Node.extend({
|
||||
_className: "Label",
|
||||
//used for left and right margin
|
||||
_margin : 0,
|
||||
//bold,italic, underline
|
||||
_isBold: false,
|
||||
_isItalic: false,
|
||||
_isUnderline: false,
|
||||
|
||||
//fontHandle it is a system font name, ttf file path or bmfont file path.
|
||||
ctor: function(string, fontHandle, textureUrl) {
|
||||
@@ -234,6 +238,21 @@ _ccsg.Label = _ccsg.Node.extend({
|
||||
this._notifyLabelSkinDirty();
|
||||
},
|
||||
|
||||
enableItalics: function (enabled) {
|
||||
this._isItalic = enabled;
|
||||
this._notifyLabelSkinDirty();
|
||||
},
|
||||
|
||||
enableBold: function (enabled) {
|
||||
this._isBold = enabled;
|
||||
this._notifyLabelSkinDirty();
|
||||
},
|
||||
|
||||
enableUnderline: function (enabled) {
|
||||
this._isUnderline = enabled;
|
||||
this._notifyLabelSkinDirty();
|
||||
},
|
||||
|
||||
isWrapTextEnabled: function() {
|
||||
return this._isWrapText;
|
||||
},
|
||||
@@ -358,6 +377,8 @@ _ccsg.Label = _ccsg.Node.extend({
|
||||
if (!extName) {
|
||||
this._fontHandle = fontHandle;
|
||||
this._labelType = _ccsg.Label.Type.SystemFont;
|
||||
this._blendFunc = cc.BlendFunc._alphaPremultiplied();
|
||||
this._renderCmd._needDraw = true;
|
||||
this._notifyLabelSkinDirty();
|
||||
this.emit('load');
|
||||
return;
|
||||
@@ -365,15 +386,36 @@ _ccsg.Label = _ccsg.Node.extend({
|
||||
|
||||
if (extName === ".ttf") {
|
||||
this._labelType = _ccsg.Label.Type.TTF;
|
||||
this._blendFunc = cc.BlendFunc._alphaPremultiplied();
|
||||
this._renderCmd._needDraw = true;
|
||||
this._fontHandle = this._loadTTFFont(fontHandle);
|
||||
} else if (extName === ".fnt") {
|
||||
//todo add bmfont here
|
||||
this._labelType = _ccsg.Label.Type.BMFont;
|
||||
this._blendFunc = cc.BlendFunc._alphaNonPremultiplied();
|
||||
this._renderCmd._needDraw = false;
|
||||
this._initBMFontWithString(this._string, fontHandle, textureUrl);
|
||||
}
|
||||
this._notifyLabelSkinDirty();
|
||||
},
|
||||
|
||||
cleanup: function () {
|
||||
this._super();
|
||||
|
||||
//remove the created DIV and style due to loading @font-face
|
||||
if(this._fontFaceStyle) {
|
||||
if(document.body.contains(this._fontFaceStyle)) {
|
||||
document.body.removeChild(this._fontFaceStyle);
|
||||
}
|
||||
}
|
||||
|
||||
if(this._preloadDiv) {
|
||||
if(document.body.contains(this._preloadDiv)) {
|
||||
document.body.removeChild(this._preloadDiv);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
_loadTTFFont: function(fontHandle) {
|
||||
var ttfIndex = fontHandle.lastIndexOf(".ttf");
|
||||
if (ttfIndex === -1) return fontHandle;
|
||||
@@ -395,6 +437,7 @@ _ccsg.Label = _ccsg.Node.extend({
|
||||
fontStyle = document.createElement("style");
|
||||
fontStyle.type = "text/css";
|
||||
doc.body.appendChild(fontStyle);
|
||||
this._fontFaceStyle = fontStyle;
|
||||
|
||||
var fontStr = "";
|
||||
if (isNaN(fontFamilyName - 0))
|
||||
@@ -415,10 +458,15 @@ _ccsg.Label = _ccsg.Node.extend({
|
||||
_divStyle.left = "-100px";
|
||||
_divStyle.top = "-100px";
|
||||
doc.body.appendChild(preloadDiv);
|
||||
self.scheduleOnce(function () {
|
||||
self._notifyLabelSkinDirty();
|
||||
self.emit("load");
|
||||
}, 2);
|
||||
this._preloadDiv = preloadDiv;
|
||||
fontStyle.onload = function() {
|
||||
fontStyle.onload = null;
|
||||
self.scheduleOnce(function() {
|
||||
self._notifyLabelSkinDirty();
|
||||
self.emit("load");
|
||||
},0.1);
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
return fontFamilyName;
|
||||
@@ -484,7 +532,7 @@ _ccsg.Label = _ccsg.Node.extend({
|
||||
if (CC_EDITOR) {
|
||||
this._updateLabel();
|
||||
} else {
|
||||
this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.textDirty);
|
||||
this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.textDirty|_ccsg.Node._dirtyFlags.contentDirty);
|
||||
}
|
||||
},
|
||||
_createRenderCmd: function() {
|
||||
@@ -1114,7 +1162,7 @@ cc.BMFontHelper = {
|
||||
}
|
||||
},
|
||||
|
||||
_computeHorizontalKerningForText: function(text) {
|
||||
_computeHorizontalKerningForText: function() {
|
||||
var stringLen = this.getStringLength();
|
||||
var locKerningDict = this._config.kerningDict;
|
||||
|
||||
@@ -1149,7 +1197,7 @@ cc.BMFontHelper = {
|
||||
var locIsLoaded = texture.isLoaded();
|
||||
self._textureLoaded = locIsLoaded;
|
||||
if (!locIsLoaded) {
|
||||
texture.once("load", function(event) {
|
||||
texture.once("load", function() {
|
||||
var self = this;
|
||||
|
||||
if (!self._spriteBatchNode) {
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
/*global dirtyFlags */
|
||||
|
||||
/****************************************************************************
|
||||
Copyright (c) 2008-2010 Ricardo Quesada
|
||||
Copyright (c) 2011-2012 cocos2d-x.org
|
||||
@@ -39,6 +41,11 @@
|
||||
if (opacityDirty)
|
||||
this._updateDisplayOpacity();
|
||||
|
||||
if(locFlag & dirtyFlags.contentDirty) {
|
||||
this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty);
|
||||
this._dirtyFlag &= ~dirtyFlags.contentDirty;
|
||||
}
|
||||
|
||||
if (colorDirty || opacityDirty || (locFlag & flags.textDirty)) {
|
||||
this._notifyRegionStatus && this._notifyRegionStatus(_ccsg.Node.CanvasRenderCmd.RegionStatus.Dirty);
|
||||
this._rebuildLabelSkin();
|
||||
@@ -112,10 +119,11 @@
|
||||
maxWidth -= 2 * this._getMargin();
|
||||
var wrappedWords = [];
|
||||
//fast return if strArr is empty
|
||||
if(strArr.length === 0) {
|
||||
if(strArr.length === 0 || maxWidth < 0) {
|
||||
wrappedWords.push('');
|
||||
return wrappedWords;
|
||||
}
|
||||
|
||||
var text = strArr;
|
||||
var allWidth = ctx.measureText(text).width;
|
||||
while (allWidth > maxWidth && text.length > 1) {
|
||||
@@ -195,14 +203,29 @@
|
||||
return wrappedWords;
|
||||
};
|
||||
|
||||
proto._constructFontDesc = function () {
|
||||
var node = this._node;
|
||||
var fontDesc = node._fontSize.toString() + 'px ';
|
||||
var fontFamily = node._fontHandle.length === 0 ? 'serif' : node._fontHandle;
|
||||
fontDesc = fontDesc + fontFamily;
|
||||
if(node._isBold) {
|
||||
fontDesc = "bold " + fontDesc;
|
||||
}
|
||||
|
||||
if(node._isItalic) {
|
||||
fontDesc = "italic " + fontDesc;
|
||||
}
|
||||
|
||||
return fontDesc;
|
||||
};
|
||||
|
||||
|
||||
proto._calculateLabelFont = function() {
|
||||
var node = this._node;
|
||||
var paragraphedStrings = node._string.split('\n');
|
||||
|
||||
var fontDesc = this._drawFontsize.toString() + 'px ';
|
||||
var fontFamily = node._fontHandle.length === 0 ? 'serif' : node._fontHandle;
|
||||
fontDesc = fontDesc + fontFamily;
|
||||
node._fontSize = node._drawFontsize;
|
||||
var fontDesc = this._constructFontDesc();
|
||||
this._labelContext.font = fontDesc;
|
||||
|
||||
var paragraphLength = this._calculateParagraphLength(paragraphedStrings, this._labelContext);
|
||||
@@ -217,6 +240,11 @@
|
||||
|
||||
var canvasWidthNoMargin = this._canvasSize.width - 2 * this._getMargin();
|
||||
var canvasHeightNoMargin = this._canvasSize.height - 2 * this._getMargin();
|
||||
if(canvasWidthNoMargin < 0 || canvasHeightNoMargin < 0) {
|
||||
fontDesc = this._constructFontDesc();
|
||||
this._labelContext.font = fontDesc;
|
||||
return fontDesc;
|
||||
}
|
||||
totalHeight = canvasHeightNoMargin + 1;
|
||||
maxLength = canvasWidthNoMargin + 1;
|
||||
var actualFontSize = this._drawFontsize + 1;
|
||||
@@ -236,7 +264,7 @@
|
||||
break;
|
||||
}
|
||||
node._fontSize = actualFontSize;
|
||||
fontDesc = actualFontSize.toString() + 'px ' + fontFamily;
|
||||
fontDesc = this._constructFontDesc();
|
||||
this._labelContext.font = fontDesc;
|
||||
|
||||
this._splitedStrings = [];
|
||||
@@ -246,7 +274,6 @@
|
||||
textFragment = this._fragmentText(paragraphedStrings[i],
|
||||
canvasWidthNoMargin,
|
||||
this._labelContext);
|
||||
var isBiggerSize = false;
|
||||
while(j < textFragment.length) {
|
||||
var measureWidth = this._labelContext.measureText(textFragment[j]).width;
|
||||
maxLength = measureWidth;
|
||||
@@ -278,7 +305,8 @@
|
||||
var scaleY = this._canvasSize.height / totalHeight;
|
||||
|
||||
node._fontSize = (this._drawFontsize * Math.min(1, scaleX, scaleY)) | 0;
|
||||
fontDesc = node._fontSize.toString() + 'px ' + fontFamily;
|
||||
fontDesc = this._constructFontDesc();
|
||||
this._labelContext.font = fontDesc;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -435,9 +463,28 @@
|
||||
|
||||
};
|
||||
|
||||
// proto._updateColor = function() {
|
||||
// this._rebuildLabelSkin();
|
||||
// };
|
||||
|
||||
proto._calculateUnderlineStartPosition = function () {
|
||||
var node = this._node;
|
||||
var lineHeight = this._getLineHeight();
|
||||
var lineCount = this._splitedStrings.length;
|
||||
var labelX;
|
||||
var firstLinelabelY;
|
||||
|
||||
labelX = 0 + this._getMargin();
|
||||
|
||||
if (cc.VerticalTextAlignment.TOP === node._vAlign) {
|
||||
firstLinelabelY = node._fontSize;
|
||||
}
|
||||
else if (cc.VerticalTextAlignment.CENTER === node._vAlign) {
|
||||
firstLinelabelY = this._canvasSize.height / 2 - lineHeight * (lineCount - 1) / 2 + node._fontSize / 2;
|
||||
}
|
||||
else {
|
||||
firstLinelabelY = this._canvasSize.height - lineHeight * (lineCount - 1);
|
||||
}
|
||||
|
||||
return cc.p(labelX, firstLinelabelY);
|
||||
};
|
||||
|
||||
proto._updateTexture = function() {
|
||||
this._labelContext.clearRect(0, 0, this._labelCanvas.width, this._labelCanvas.height);
|
||||
@@ -450,6 +497,7 @@
|
||||
this._labelContext.lineJoin = 'round';
|
||||
var color = this._displayedColor;
|
||||
this._labelContext.fillStyle = 'rgb(' + color.r + ',' + color.g + ',' + color.b + ')';
|
||||
var underlineStartPosition;
|
||||
|
||||
//do real rendering
|
||||
for (var i = 0; i < this._splitedStrings.length; ++i) {
|
||||
@@ -463,10 +511,21 @@
|
||||
startPosition.x, startPosition.y + i * lineHeight);
|
||||
}
|
||||
this._labelContext.fillText(this._splitedStrings[i], startPosition.x, startPosition.y + i * lineHeight);
|
||||
if(this._node._isUnderline) {
|
||||
underlineStartPosition = this._calculateUnderlineStartPosition();
|
||||
this._labelContext.save();
|
||||
this._labelContext.beginPath();
|
||||
this._labelContext.lineWidth = this._node._fontSize / 8;
|
||||
this._labelContext.strokeStyle = 'rgb(' + color.r + ',' + color.g + ',' + color.b + ')';
|
||||
this._labelContext.moveTo(underlineStartPosition.x, underlineStartPosition.y + i * lineHeight - 1);
|
||||
this._labelContext.lineTo(underlineStartPosition.x + this._labelCanvas.width, underlineStartPosition.y + i * lineHeight - 1);
|
||||
this._labelContext.stroke();
|
||||
this._labelContext.restore();
|
||||
}
|
||||
}
|
||||
|
||||
this._texture._textureLoaded = false;
|
||||
this._texture.handleLoadedTexture();
|
||||
this._texture.handleLoadedTexture(true);
|
||||
};
|
||||
|
||||
proto._rebuildLabelSkin = function () {
|
||||
|
||||
@@ -69,7 +69,8 @@ proto._updateDisplayOpacity = function (parentOpacity) {
|
||||
proto.transform = function (parentCmd, recursive) {
|
||||
this.originTransform(parentCmd, recursive);
|
||||
|
||||
var lx = 0, rx = this._labelCanvas.width,
|
||||
var node = this._node,
|
||||
lx = 0, rx = this._labelCanvas.width,
|
||||
by = 0, ty = this._labelCanvas.height,
|
||||
wt = this._worldTransform;
|
||||
|
||||
@@ -83,6 +84,12 @@ proto.transform = function (parentCmd, recursive) {
|
||||
vert[3].x = rx * wt.a + by * wt.c + wt.tx; // br
|
||||
vert[3].y = rx * wt.b + by * wt.d + wt.ty;
|
||||
|
||||
if (!node._string || (node._labelType !== _ccsg.Label.Type.TTF &&
|
||||
node._labelType !== _ccsg.Label.Type.SystemFont)) {
|
||||
// No culling for bmfont
|
||||
return;
|
||||
}
|
||||
|
||||
var rect = cc.visibleRect,
|
||||
vl = rect.left.x, vr = rect.right.x, vt = rect.top.y, vb = rect.bottom.y;
|
||||
if (((vert[0].x-vl) & (vert[1].x-vl) & (vert[2].x-vl) & (vert[3].x-vl)) >> 31 || // All outside left
|
||||
@@ -104,17 +111,11 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset) {
|
||||
return 0;
|
||||
|
||||
// Fill in vertex data with quad information (4 vertices for sprite)
|
||||
// Use 255 because color has been set when baking label
|
||||
// premultiplied alpha is used for labelTTF and system font
|
||||
var opacity = this._displayedOpacity;
|
||||
var r = this._displayedColor.r,
|
||||
g = this._displayedColor.g,
|
||||
b = this._displayedColor.b;
|
||||
if (node._opacityModifyRGB) {
|
||||
var a = opacity / 255;
|
||||
r *= a;
|
||||
g *= a;
|
||||
b *= a;
|
||||
}
|
||||
this._color[0] = ((opacity<<24) | (b<<16) | (g<<8) | r);
|
||||
this._color[0] = ((opacity<<24) | (opacity<<16) | (opacity<<8) | opacity);
|
||||
|
||||
var z = node._vertexZ;
|
||||
|
||||
var vertices = this._vertices;
|
||||
|
||||
@@ -29,9 +29,8 @@ var Downloader = require('./downloader');
|
||||
var Loader = require('./loader');
|
||||
var AssetTable = require('./asset-table');
|
||||
var callInNextTick = require('../platform/utils').callInNextTick;
|
||||
var AutoReleaseUtils = require('./auto-release-utils');
|
||||
|
||||
var downloader = new Downloader();
|
||||
var loader = new Loader();
|
||||
var resources = new AssetTable();
|
||||
|
||||
/**
|
||||
@@ -40,13 +39,15 @@ var resources = new AssetTable();
|
||||
* @extends Pipeline
|
||||
* @static
|
||||
*/
|
||||
cc.loader = new Pipeline([
|
||||
downloader,
|
||||
loader
|
||||
]);
|
||||
function CCLoader () {
|
||||
var downloader = new Downloader();
|
||||
var loader = new Loader();
|
||||
|
||||
Pipeline.call(this, [
|
||||
downloader,
|
||||
loader
|
||||
]);
|
||||
|
||||
JS.mixin(cc.loader, {
|
||||
/**
|
||||
* The downloader in cc.loader's pipeline, it's by default the first pipe.
|
||||
* It's used to download files with several handlers: pure text, image, script, audio, font, uuid.
|
||||
@@ -54,7 +55,7 @@ JS.mixin(cc.loader, {
|
||||
* @property downloader
|
||||
* @type {Object}
|
||||
*/
|
||||
downloader: downloader,
|
||||
this.downloader = downloader;
|
||||
|
||||
/**
|
||||
* The downloader in cc.loader's pipeline, it's by default the second pipe.
|
||||
@@ -63,7 +64,13 @@ JS.mixin(cc.loader, {
|
||||
* @property loader
|
||||
* @type {Object}
|
||||
*/
|
||||
loader: loader,
|
||||
this.loader = loader;
|
||||
|
||||
// assets to release automatically
|
||||
this._autoReleaseSetting = {};
|
||||
}
|
||||
JS.extend(CCLoader, Pipeline);
|
||||
JS.mixin(CCLoader.prototype, {
|
||||
|
||||
/**
|
||||
* Get XMLHttpRequest.
|
||||
@@ -82,7 +89,7 @@ JS.mixin(cc.loader, {
|
||||
* @param {Object} extMap Custom supported types with corresponded handler
|
||||
*/
|
||||
addDownloadHandlers: function (extMap) {
|
||||
downloader.addHandlers(extMap);
|
||||
this.downloader.addHandlers(extMap);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -96,7 +103,7 @@ JS.mixin(cc.loader, {
|
||||
* @param {Object} extMap Custom supported types with corresponded handler
|
||||
*/
|
||||
addLoadHandlers: function (extMap) {
|
||||
loader.addHandlers(extMap);
|
||||
this.loader.addHandlers(extMap);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -281,7 +288,7 @@ JS.mixin(cc.loader, {
|
||||
* cc.log('Result should be a prefab: ' + (prefab instanceof cc.Prefab));
|
||||
* });
|
||||
*
|
||||
* // load the sprite frame (project/assets/resources/imgs/cocos.png/cocos) from resources folder
|
||||
* // load the sprite frame of (project/assets/resources/imgs/cocos.png) from resources folder
|
||||
* cc.loader.loadRes('imgs/cocos', cc.SpriteFrame, function (err, spriteFrame) {
|
||||
* if (err) {
|
||||
* cc.error(err.message || err);
|
||||
@@ -295,7 +302,8 @@ JS.mixin(cc.loader, {
|
||||
completeCallback = type;
|
||||
type = null;
|
||||
}
|
||||
var uuid = this._getResUuid(url, type);
|
||||
var self = this;
|
||||
var uuid = self._getResUuid(url, type);
|
||||
if (uuid) {
|
||||
this.load(
|
||||
{
|
||||
@@ -303,7 +311,15 @@ JS.mixin(cc.loader, {
|
||||
type: 'uuid',
|
||||
uuid: uuid
|
||||
},
|
||||
completeCallback
|
||||
function (err, asset) {
|
||||
if (asset) {
|
||||
// should not release these assets, even if they are static referenced in the scene.
|
||||
self.setAutoReleaseRecursively(asset, false);
|
||||
}
|
||||
if (completeCallback) {
|
||||
completeCallback(err, asset);
|
||||
}
|
||||
}
|
||||
);
|
||||
}
|
||||
else {
|
||||
@@ -315,7 +331,9 @@ JS.mixin(cc.loader, {
|
||||
else {
|
||||
info = 'Resources url "' + url + '" does not exist.';
|
||||
}
|
||||
completeCallback(new Error(info), null);
|
||||
if (completeCallback) {
|
||||
completeCallback(new Error(info), null);
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
@@ -335,7 +353,7 @@ JS.mixin(cc.loader, {
|
||||
*
|
||||
* @example
|
||||
*
|
||||
* // load the texture (resources/imgs/cocos.png) and sprite frame (resources/imgs/cocos.png/cocos)
|
||||
* // load the texture (resources/imgs/cocos.png) and the corresponding sprite frame
|
||||
* cc.loader.loadResAll('imgs/cocos', function (err, assets) {
|
||||
* if (err) {
|
||||
* cc.error(err);
|
||||
@@ -360,6 +378,7 @@ JS.mixin(cc.loader, {
|
||||
completeCallback = type;
|
||||
type = null;
|
||||
}
|
||||
var self = this;
|
||||
var uuids = resources.getUuidArray(url, type);
|
||||
var remain = uuids.length;
|
||||
if (remain > 0) {
|
||||
@@ -371,18 +390,25 @@ JS.mixin(cc.loader, {
|
||||
}
|
||||
if (err) {
|
||||
aborted = true;
|
||||
completeCallback(err, null);
|
||||
if (completeCallback) {
|
||||
completeCallback(err, null);
|
||||
}
|
||||
return;
|
||||
}
|
||||
results.push(res);
|
||||
--remain;
|
||||
if (remain === 0) {
|
||||
completeCallback(null, results);
|
||||
for (var i = 0; i < results.length; i++) {
|
||||
self.setAutoReleaseRecursively(results[i], false);
|
||||
}
|
||||
if (completeCallback) {
|
||||
completeCallback(null, results);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (var i = 0, len = remain; i < len; ++i) {
|
||||
var uuid = uuids[i];
|
||||
this.load(
|
||||
self.load(
|
||||
{
|
||||
id: uuid,
|
||||
type: 'uuid',
|
||||
@@ -394,7 +420,9 @@ JS.mixin(cc.loader, {
|
||||
}
|
||||
else {
|
||||
callInNextTick(function () {
|
||||
completeCallback(null, []);
|
||||
if (completeCallback) {
|
||||
completeCallback(null, []);
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
@@ -429,7 +457,7 @@ JS.mixin(cc.loader, {
|
||||
/**
|
||||
* Returns an item in pipeline.
|
||||
* @method getItem
|
||||
* @return {LoadingItem}
|
||||
* @return {Object}
|
||||
*/
|
||||
getItem: function (url) {
|
||||
var item = this._items.map[url];
|
||||
@@ -489,9 +517,131 @@ JS.mixin(cc.loader, {
|
||||
*/
|
||||
releaseAll: function () {
|
||||
this.clear();
|
||||
}
|
||||
},
|
||||
|
||||
// AUTO RELEASE
|
||||
|
||||
_baseRemoveItem: Pipeline.prototype.removeItem,
|
||||
|
||||
// override
|
||||
removeItem: function (key) {
|
||||
var removed = this._baseRemoveItem(key);
|
||||
delete this._autoReleaseSetting[key];
|
||||
return removed;
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en
|
||||
* Indicates whether to release the asset when loading a new scene.<br>
|
||||
* By default, when loading a new scene, all assets in the previous scene will be released or preserved
|
||||
* according to whether the previous scene checked the "Auto Release Assets" option.
|
||||
* On the other hand, assets dynamically loaded by using `cc.loader.loadRes` or `cc.loader.loadResAll`
|
||||
* will not be affected by that option, remain not released by default.<br>
|
||||
* Use this API to change the default behavior on a single asset, to force preserve or release specified asset when scene switching.<br>
|
||||
* <br>
|
||||
* See: {{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}}, {{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}}
|
||||
* !#zh
|
||||
* 设置当场景切换时是否自动释放资源。<br>
|
||||
* 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。
|
||||
* 而使用 `cc.loader.loadRes` 或 `cc.loader.loadResAll` 动态加载的资源,则不受场景设置的影响,默认不自动释放。<br>
|
||||
* 使用这个 API 可以在单个资源上改变这个默认行为,强制在切换场景时保留或者释放指定资源。<br>
|
||||
* <br>
|
||||
* 参考:{{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}},{{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}}
|
||||
*
|
||||
* @example
|
||||
* // auto release the texture event if "Auto Release Assets" disabled in current scene
|
||||
* cc.loader.setAutoRelease(texture2d, true);
|
||||
* // don't release the texture even if "Auto Release Assets" enabled in current scene
|
||||
* cc.loader.setAutoRelease(texture2d, false);
|
||||
* // first parameter can be url
|
||||
* cc.loader.setAutoRelease(audioUrl, false);
|
||||
*
|
||||
* @method setAutoRelease
|
||||
* @param {Asset|String} assetOrUrl - asset object or the raw asset's url
|
||||
* @param {Boolean} autoRelease - indicates whether should release automatically
|
||||
*/
|
||||
setAutoRelease: function (assetOrUrl, autoRelease) {
|
||||
var key = AutoReleaseUtils.getKey(this, assetOrUrl);
|
||||
if (key) {
|
||||
this._autoReleaseSetting[key] = !!autoRelease;
|
||||
}
|
||||
else if (CC_DEV) {
|
||||
cc.warn('No need to release non-cached asset.');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en
|
||||
* Indicates whether to release the asset and its referenced other assets when loading a new scene.<br>
|
||||
* By default, when loading a new scene, all assets in the previous scene will be released or preserved
|
||||
* according to whether the previous scene checked the "Auto Release Assets" option.
|
||||
* On the other hand, assets dynamically loaded by using `cc.loader.loadRes` or `cc.loader.loadResAll`
|
||||
* will not be affected by that option, remain not released by default.<br>
|
||||
* Use this API to change the default behavior on the specified asset and its recursively referenced assets, to force preserve or release specified asset when scene switching.<br>
|
||||
* <br>
|
||||
* See: {{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}}, {{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}}
|
||||
* !#zh
|
||||
* 设置当场景切换时是否自动释放资源及资源引用的其它资源。<br>
|
||||
* 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。
|
||||
* 而使用 `cc.loader.loadRes` 或 `cc.loader.loadResAll` 动态加载的资源,则不受场景设置的影响,默认不自动释放。<br>
|
||||
* 使用这个 API 可以在指定资源及资源递归引用到的所有资源上改变这个默认行为,强制在切换场景时保留或者释放指定资源。<br>
|
||||
* <br>
|
||||
* 参考:{{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}},{{#crossLink "loader/isAutoRelease:method"}}cc.loader.isAutoRelease{{/crossLink}}
|
||||
*
|
||||
* @example
|
||||
* // auto release the SpriteFrame and its Texture event if "Auto Release Assets" disabled in current scene
|
||||
* cc.loader.setAutoReleaseRecursively(spriteFrame, true);
|
||||
* // don't release the SpriteFrame and its Texture even if "Auto Release Assets" enabled in current scene
|
||||
* cc.loader.setAutoReleaseRecursively(spriteFrame, false);
|
||||
* // don't release the Prefab and all the referenced assets
|
||||
* cc.loader.setAutoReleaseRecursively(prefab, false);
|
||||
*
|
||||
* @method setAutoReleaseRecursively
|
||||
* @param {Asset|String} assetOrUrl - asset object or the raw asset's url
|
||||
* @param {Boolean} autoRelease - indicates whether should release automatically
|
||||
*/
|
||||
setAutoReleaseRecursively: function (assetOrUrl, autoRelease) {
|
||||
autoRelease = !!autoRelease;
|
||||
var key = AutoReleaseUtils.getKey(this, assetOrUrl);
|
||||
if (key) {
|
||||
this._autoReleaseSetting[key] = autoRelease;
|
||||
|
||||
var depends = AutoReleaseUtils.getDependsRecursively(key);
|
||||
for (var i = 0; i < depends.length; i++) {
|
||||
var depend = depends[i];
|
||||
this._autoReleaseSetting[depend] = autoRelease;
|
||||
}
|
||||
}
|
||||
else if (CC_DEV) {
|
||||
cc.warn('No need to release non-cached asset.');
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en
|
||||
* Returns whether the asset is configured as auto released, despite how "Auto Release Assets" property is set on scene asset.<br>
|
||||
* <br>
|
||||
* See: {{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}}, {{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}}
|
||||
*
|
||||
* !#zh
|
||||
* 返回指定的资源是否有被设置为自动释放,不论场景的“Auto Release Assets”如何设置。<br>
|
||||
* <br>
|
||||
* 参考:{{#crossLink "loader/setAutoRelease:method"}}cc.loader.setAutoRelease{{/crossLink}},{{#crossLink "loader/setAutoReleaseRecursively:method"}}cc.loader.setAutoReleaseRecursively{{/crossLink}}
|
||||
* @method isAutoRelease
|
||||
* @param {Asset|String} assetOrUrl - asset object or the raw asset's url
|
||||
* @returns {Boolean}
|
||||
*/
|
||||
isAutoRelease: function (assetOrUrl) {
|
||||
var key = AutoReleaseUtils.getKey(this, assetOrUrl);
|
||||
if (key) {
|
||||
return !!this._autoReleaseSetting[key];
|
||||
}
|
||||
return false;
|
||||
},
|
||||
});
|
||||
|
||||
cc.loader = new CCLoader();
|
||||
|
||||
if (CC_EDITOR) {
|
||||
cc.loader.refreshUrl = function (uuid, oldUrl, newUrl) {
|
||||
this._items.refreshItemUrl(uuid, oldUrl, newUrl);
|
||||
|
||||
@@ -26,63 +26,36 @@
|
||||
var Path = require('../utils/CCPath');
|
||||
var Sys = require('../platform/CCSys');
|
||||
var Pipeline = require('./pipeline');
|
||||
require('../../audio/CCAudio');
|
||||
var audioEngine = require('../../audio/CCAudioEngine');
|
||||
|
||||
var __audioSupport = Sys.__audioSupport;
|
||||
var formatSupport = __audioSupport.format;
|
||||
var context = __audioSupport.context;
|
||||
|
||||
function loadAudioFromExtList (url, typeList, audio, cb){
|
||||
if(typeList.length === 0){
|
||||
var ERRSTR = 'can not found the resource of audio! Last match url is : ';
|
||||
ERRSTR += url.replace(/\.(.*)?$/, '(');
|
||||
formatSupport.forEach(function(ext){
|
||||
ERRSTR += ext + '|';
|
||||
});
|
||||
ERRSTR = ERRSTR.replace(/\|$/, ')');
|
||||
return cb({status: 520, errorMessage: ERRSTR}, null);
|
||||
}
|
||||
|
||||
if (__audioSupport.WEB_AUDIO && cc.Audio.useWebAudio) {
|
||||
loadWebAudio(url, typeList, audio, cb);
|
||||
} else {
|
||||
loadDomAudio(url, typeList, audio, cb);
|
||||
}
|
||||
}
|
||||
|
||||
function loadDomAudio (url, typeList, audio, cb) {
|
||||
var num = __audioSupport.ONE_SOURCE ? 1 : typeList.length;
|
||||
|
||||
// 加载统一使用dom
|
||||
function loadDomAudio (item, callback) {
|
||||
var dom = document.createElement('audio');
|
||||
for (var i=0; i<num; i++) {
|
||||
var source = document.createElement('source');
|
||||
source.src = cc.path.changeExtname(url, typeList[i]);
|
||||
dom.appendChild(source);
|
||||
}
|
||||
|
||||
audio.setElement(dom);
|
||||
|
||||
var timer = setTimeout(function(){
|
||||
if (dom.readyState === 0) {
|
||||
failure();
|
||||
} else {
|
||||
success();
|
||||
}
|
||||
}, 8000);
|
||||
|
||||
var success = function () {
|
||||
dom.src = item.url;
|
||||
var clearEvent = function () {
|
||||
clearTimeout(timer);
|
||||
dom.removeEventListener("canplaythrough", success, false);
|
||||
dom.removeEventListener("error", failure, false);
|
||||
dom.removeEventListener("emptied", success, false);
|
||||
if (__audioSupport.USE_LOADER_EVENT)
|
||||
if(__audioSupport.USE_LOADER_EVENT)
|
||||
dom.removeEventListener(__audioSupport.USE_LOADER_EVENT, success, false);
|
||||
clearTimeout(timer);
|
||||
cb(null, url);
|
||||
};
|
||||
var timer = setTimeout(function () {
|
||||
if (dom.readyState === 0)
|
||||
failure();
|
||||
else
|
||||
success();
|
||||
}, 8000);
|
||||
var success = function () {
|
||||
clearEvent();
|
||||
item.element = dom;
|
||||
callback(null, item.url);
|
||||
};
|
||||
var failure = function () {
|
||||
cc.log('load audio failure - ' + url);
|
||||
success();
|
||||
clearEvent();
|
||||
cc.log('load audio failure - ' + item.url);
|
||||
};
|
||||
dom.addEventListener("canplaythrough", success, false);
|
||||
dom.addEventListener("error", failure, false);
|
||||
@@ -90,27 +63,27 @@ function loadDomAudio (url, typeList, audio, cb) {
|
||||
dom.addEventListener(__audioSupport.USE_LOADER_EVENT, success, false);
|
||||
}
|
||||
|
||||
function loadWebAudio (url, typeList, audio, cb) {
|
||||
function loadWebAudio (item, callback) {
|
||||
if (!context) return;
|
||||
|
||||
var request = Pipeline.getXMLHttpRequest();
|
||||
request.open("GET", url, true);
|
||||
request.open("GET", item.url, true);
|
||||
request.responseType = "arraybuffer";
|
||||
|
||||
// Our asynchronous callback
|
||||
request.onload = function () {
|
||||
context["decodeAudioData"](request.response, function(buffer){
|
||||
//success
|
||||
audio.setBuffer(buffer);
|
||||
cb(null, url);
|
||||
item.buffer = buffer;
|
||||
callback(null, item.url);
|
||||
}, function(){
|
||||
//error
|
||||
cb('decode error - ' + url, url);
|
||||
callback('decode error - ' + item.url, null);
|
||||
});
|
||||
};
|
||||
|
||||
request.onerror = function(){
|
||||
cb('request error - ' + url, url);
|
||||
callback('request error - ' + item.url, null);
|
||||
};
|
||||
|
||||
request.send();
|
||||
@@ -121,25 +94,30 @@ function downloadAudio (item, callback) {
|
||||
return callback( new Error('Audio Downloader: audio not supported on this browser!') );
|
||||
}
|
||||
|
||||
var url = item.url,
|
||||
extname = Path.extname(url),
|
||||
typeList = [extname],
|
||||
i, audio;
|
||||
item.content = item.url;
|
||||
|
||||
// Generate all types
|
||||
for (i = 0; i < formatSupport.length; i++) {
|
||||
if (extname !== formatSupport[i]) {
|
||||
typeList.push(formatSupport[i]);
|
||||
}
|
||||
if (!__audioSupport.WEB_AUDIO) {
|
||||
// If WebAudio is not supported, load using DOM mode
|
||||
return loadDomAudio(item, callback);
|
||||
}
|
||||
|
||||
audio = new cc.Audio(url);
|
||||
|
||||
// hack for audio to be found before loaded
|
||||
item.content = url;
|
||||
item.audio = audio;
|
||||
loadAudioFromExtList(url, typeList, audio, callback);
|
||||
// Get a header
|
||||
// check audio size
|
||||
var request = Pipeline.getXMLHttpRequest();
|
||||
request.open("HEAD", item.url, true);
|
||||
// Our asynchronous callback
|
||||
request.onload = function () {
|
||||
var bit = this.getResponseHeader('Content-Length');
|
||||
if (bit > audioEngine._maxWebAudioSize) {
|
||||
return loadDomAudio(item, callback);
|
||||
}
|
||||
return loadWebAudio(item, callback);
|
||||
};
|
||||
request.onerror = function () {
|
||||
var ERRSTR = 'can not found the resource of audio! Last match url is : ' + item.url;
|
||||
return callback({status: 520, errorMessage: ERRSTR}, null);
|
||||
};
|
||||
request.send();
|
||||
}
|
||||
|
||||
|
||||
module.exports = downloadAudio;
|
||||
@@ -0,0 +1,93 @@
|
||||
|
||||
function parseDepends (key, parsed) {
|
||||
var item = cc.loader.getItem(key);
|
||||
if (item) {
|
||||
var depends = item.dependKeys;
|
||||
if (depends) {
|
||||
for (var i = 0; i < depends.length; i++) {
|
||||
var depend = depends[i];
|
||||
if ( !parsed[depend] ) {
|
||||
parsed[depend] = true;
|
||||
parseDepends(depend, parsed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function release (loader, key, nextSceneAssets) {
|
||||
if (!nextSceneAssets || nextSceneAssets.indexOf(key) === -1) {
|
||||
var item = loader.getItem(key);
|
||||
if (item) {
|
||||
var removed = loader.removeItem(key);
|
||||
//console.log('auto release: ' + key);
|
||||
// TODO: Audio
|
||||
var asset = item.content;
|
||||
if (asset instanceof cc.Texture2D) {
|
||||
cc.textureCache.removeTextureForKey(item.url);
|
||||
}
|
||||
else if (CC_JSB && asset instanceof cc.SpriteFrame && removed) {
|
||||
// for the "Temporary solution" in deserialize.js
|
||||
asset.release();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
|
||||
// get asset url or uuid
|
||||
getKey: function (loader, assetOrUrl) {
|
||||
if (assetOrUrl) {
|
||||
if (typeof assetOrUrl === 'string') {
|
||||
return assetOrUrl;
|
||||
}
|
||||
else if (assetOrUrl instanceof cc.Asset) {
|
||||
return assetOrUrl._uuid;
|
||||
}
|
||||
else if (assetOrUrl instanceof cc.Texture2D) {
|
||||
return assetOrUrl.url;
|
||||
}
|
||||
else if (!CC_JSB && assetOrUrl instanceof cc.Audio) {
|
||||
return assetOrUrl.src;
|
||||
}
|
||||
else if (CC_DEV) {
|
||||
cc.warn('unknown asset type');
|
||||
}
|
||||
}
|
||||
return '';
|
||||
},
|
||||
|
||||
// do auto release
|
||||
autoRelease: function (loader, oldSceneAssets, nextSceneAssets) {
|
||||
var releaseSettings = loader._autoReleaseSetting;
|
||||
var i, key;
|
||||
|
||||
// remove ununsed scene assets
|
||||
if (oldSceneAssets) {
|
||||
for (i = 0; i < oldSceneAssets.length; i++) {
|
||||
key = oldSceneAssets[i];
|
||||
if (releaseSettings[key] !== false) {
|
||||
release(loader, key, nextSceneAssets);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// remove auto release assets
|
||||
var keys = Object.keys(releaseSettings);
|
||||
// releasing asset will change _autoReleaseSetting, so don't use enumerator
|
||||
for (i = 0; i < keys.length; i++) {
|
||||
key = keys[i];
|
||||
if (releaseSettings[key] === true) {
|
||||
release(loader, key, nextSceneAssets);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
// get dependencies not including self
|
||||
getDependsRecursively: function (key) {
|
||||
var depends = {};
|
||||
parseDepends(key, depends);
|
||||
return Object.keys(depends);
|
||||
}
|
||||
};
|
||||
@@ -310,7 +310,7 @@ var Downloader = function (extMap) {
|
||||
this.id = ID;
|
||||
this.async = true;
|
||||
this.pipeline = null;
|
||||
this.maxConcurrent = 2;
|
||||
this.maxConcurrent = cc.sys.isMobile ? 2 : 512;
|
||||
this._curConcurrent = 0;
|
||||
this._loadQueue = [];
|
||||
|
||||
@@ -331,21 +331,16 @@ JS.mixin(Downloader.prototype, {
|
||||
var self = this;
|
||||
var downloadFunc = this.extMap[item.type] || this.extMap['default'];
|
||||
if (this._curConcurrent < this.maxConcurrent) {
|
||||
if (cc.sys.isMobile) {
|
||||
this._curConcurrent++;
|
||||
}
|
||||
this._curConcurrent++;
|
||||
downloadFunc.call(this, item, function (err, result) {
|
||||
if (cc.sys.isMobile) {
|
||||
// Concurrent logic
|
||||
self._curConcurrent = Math.max(0, self._curConcurrent - 1);
|
||||
|
||||
while (self._curConcurrent < self.maxConcurrent) {
|
||||
var nextOne = self._loadQueue.shift();
|
||||
if (!nextOne) {
|
||||
break;
|
||||
}
|
||||
self.handle(nextOne.item, nextOne.callback);
|
||||
// Concurrent logic
|
||||
self._curConcurrent = Math.max(0, self._curConcurrent - 1);
|
||||
while (self._curConcurrent < self.maxConcurrent) {
|
||||
var nextOne = self._loadQueue.shift();
|
||||
if (!nextOne) {
|
||||
break;
|
||||
}
|
||||
self.handle(nextOne.item, nextOne.callback);
|
||||
}
|
||||
|
||||
callback && callback(err, result);
|
||||
|
||||
@@ -509,6 +509,7 @@ JS.mixin(Pipeline.prototype, {
|
||||
this.flowOut(item);
|
||||
}
|
||||
this._items.removeItem(url);
|
||||
return true;
|
||||
}
|
||||
else {
|
||||
return false;
|
||||
|
||||
@@ -97,6 +97,9 @@ function loadDepends (pipeline, item, asset, tdInfo, deferredLoadRawAssetsInRunt
|
||||
return callback(null, asset);
|
||||
}
|
||||
|
||||
// cache dependencies for auto release
|
||||
var dependKeys = item.dependKeys = [];
|
||||
|
||||
pipeline.flowInDeps(depends, function (items) {
|
||||
var item;
|
||||
for (var src in items) {
|
||||
@@ -114,12 +117,14 @@ function loadDepends (pipeline, item, asset, tdInfo, deferredLoadRawAssetsInRunt
|
||||
if (item.complete) {
|
||||
var value = item.isRawAsset ? item.url : item.content;
|
||||
dependObj[dependProp] = value;
|
||||
dependKeys.push(item.isRawAsset ? item.url : dependSrc);
|
||||
}
|
||||
else {
|
||||
// item was removed from cache, but ready in pipeline actually
|
||||
var loadCallback = function (item) {
|
||||
var value = item.isRawAsset ? item.url : item.content;
|
||||
this.obj[this.prop] = value;
|
||||
dependKeys.push(item.isRawAsset ? item.url : item.uuid);
|
||||
};
|
||||
var target = {
|
||||
obj: dependObj,
|
||||
@@ -159,9 +164,9 @@ function canDeferredLoad (asset, item, isScene) {
|
||||
else if (isScene) {
|
||||
if (asset instanceof cc.SceneAsset) {
|
||||
res = asset.asyncLoadAssets;
|
||||
if (res) {
|
||||
cc.log('deferred load raw assets for ' + item.id);
|
||||
}
|
||||
//if (res) {
|
||||
// cc.log('deferred load raw assets for ' + item.id);
|
||||
//}
|
||||
}
|
||||
//else if (asset instanceof cc.Scene) {
|
||||
// deferredLoadRawAssetsInRuntime = asset._asyncLoadAssets;
|
||||
@@ -210,7 +215,8 @@ function loadUuid (item, callback) {
|
||||
});
|
||||
}
|
||||
catch (e) {
|
||||
callback( new Error('Uuid Loader: Deserialize asset [' + item.id + '] failed : ' + e.stack) );
|
||||
var err = CC_JSB ? (e + '\n' + e.stack) : e.stack;
|
||||
callback( new Error('Uuid Loader: Deserialize asset [' + item.id + '] failed : ' + err) );
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ var Asset = require('../assets/CCAsset');
|
||||
var callInNextTick = require('./utils').callInNextTick;
|
||||
var Loader = require('../load-pipeline/CCLoader');
|
||||
var PackDownloader = require('../load-pipeline/pack-downloader');
|
||||
var AutoReleaseUtils = require('../load-pipeline/auto-release-utils');
|
||||
|
||||
/**
|
||||
* The asset library which managing loading/unloading assets in project.
|
||||
@@ -67,6 +68,9 @@ var AssetLibrary = {
|
||||
* @private
|
||||
*/
|
||||
loadAsset: function (uuid, callback, options) {
|
||||
if (typeof uuid !== 'string') {
|
||||
return callInNextTick(callback, new Error('[AssetLibrary] uuid must be string'), null);
|
||||
}
|
||||
// var readMainCache = typeof (options && options.readMainCache) !== 'undefined' ? readMainCache : true;
|
||||
// var writeMainCache = typeof (options && options.writeMainCache) !== 'undefined' ? writeMainCache : true;
|
||||
var item = {
|
||||
@@ -79,7 +83,22 @@ var AssetLibrary = {
|
||||
if (options && options.existingAsset) {
|
||||
item.existingAsset = options.existingAsset;
|
||||
}
|
||||
this._loadAssetByUuid(item, callback);
|
||||
Loader.load(item, function (error, asset) {
|
||||
if (error || !asset) {
|
||||
error = new Error('[AssetLibrary] loading JSON or dependencies failed: ' + error.message);
|
||||
}
|
||||
else {
|
||||
if (asset.constructor === cc.SceneAsset) {
|
||||
asset.scene.dependAssets = AutoReleaseUtils.getDependsRecursively(uuid);
|
||||
}
|
||||
if (CC_EDITOR || isScene(asset)) {
|
||||
Loader.removeItem(uuid);
|
||||
}
|
||||
}
|
||||
if (callback) {
|
||||
callback(error, asset);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
getImportedDir: function (uuid) {
|
||||
@@ -170,36 +189,6 @@ var AssetLibrary = {
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#zh uuid加载流程:
|
||||
* 1. 查找_uuidToAsset,如果已经加载过,直接返回
|
||||
* 2. 查找_uuidToCallbacks,如果已经在加载,则注册回调,直接返回
|
||||
* 3. 如果没有url,则将uuid直接作为路径
|
||||
* 4. 递归加载Asset及其引用到的其它Asset
|
||||
*
|
||||
* @method _loadAssetByUuid
|
||||
* @param {Object} item - loading item including uuid, type and extra infos
|
||||
* @param {loadCallback} callback - the callback to receive the asset, can be null
|
||||
* @private
|
||||
*/
|
||||
_loadAssetByUuid: function (item, callback) {
|
||||
var uuid = item.id;
|
||||
if (typeof uuid !== 'string') {
|
||||
return callInNextTick(callback, new Error('[AssetLibrary] uuid must be string'), null);
|
||||
}
|
||||
Loader.load(item, function (error, asset) {
|
||||
if (error || !asset) {
|
||||
error = new Error('[AssetLibrary] loading JSON or dependencies failed: ' + error.message);
|
||||
}
|
||||
else if (CC_EDITOR || isScene(asset)) {
|
||||
Loader.removeItem(uuid);
|
||||
}
|
||||
if (callback) {
|
||||
callback(error, asset);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* @method loadJson
|
||||
* @param {String} json
|
||||
@@ -219,8 +208,13 @@ var AssetLibrary = {
|
||||
if (error) {
|
||||
error = new Error('[AssetLibrary] loading JSON or dependencies failed: ' + error.message);
|
||||
}
|
||||
else if (CC_EDITOR || isScene(asset)) {
|
||||
Loader.removeItem(randomUuid);
|
||||
else {
|
||||
if (asset.constructor === cc.SceneAsset) {
|
||||
asset.scene.dependAssets = AutoReleaseUtils.getDependsRecursively(randomUuid);
|
||||
}
|
||||
if (CC_EDITOR || isScene(asset)) {
|
||||
Loader.removeItem(randomUuid);
|
||||
}
|
||||
}
|
||||
asset._uuid = '';
|
||||
if (callback) {
|
||||
|
||||
@@ -338,9 +338,14 @@ cc.isChildClassOf = function (subclass, superclass) {
|
||||
return true;
|
||||
}
|
||||
for (;;) {
|
||||
var proto = subclass.prototype; // binded function do not have prototype
|
||||
var dunderProto = proto && Object.getPrototypeOf(proto);
|
||||
subclass = dunderProto && dunderProto.constructor;
|
||||
if (CC_JSB && subclass.$super) {
|
||||
subclass = subclass.$super;
|
||||
}
|
||||
else {
|
||||
var proto = subclass.prototype; // binded function do not have prototype
|
||||
var dunderProto = proto && Object.getPrototypeOf(proto);
|
||||
subclass = dunderProto && dunderProto.constructor;
|
||||
}
|
||||
if (!subclass) {
|
||||
return false;
|
||||
}
|
||||
@@ -356,8 +361,13 @@ cc.isChildClassOf = function (subclass, superclass) {
|
||||
function getInheritanceChain (klass) {
|
||||
var chain = [];
|
||||
for (;;) {
|
||||
var dunderProto = Object.getPrototypeOf(klass.prototype);
|
||||
klass = dunderProto && dunderProto.constructor;
|
||||
if (CC_JSB && klass.$super) {
|
||||
klass = klass.$super;
|
||||
}
|
||||
else {
|
||||
var dunderProto = Object.getPrototypeOf(klass.prototype);
|
||||
klass = dunderProto && dunderProto.constructor;
|
||||
}
|
||||
if (!klass) {
|
||||
break;
|
||||
}
|
||||
@@ -416,7 +426,7 @@ function define (className, baseClasses, mixins, constructor, options) {
|
||||
var frame = cc._RFpeek();
|
||||
if (frame) {
|
||||
if (CC_DEV && constructor) {
|
||||
cc.warn('cc.Class: Should not define constructor for cc.Component.');
|
||||
cc.warn('Should not define constructor for cc.Component %s.', className);
|
||||
}
|
||||
if (frame.beh) {
|
||||
cc.error('Each script can have at most one Component.');
|
||||
@@ -425,7 +435,7 @@ function define (className, baseClasses, mixins, constructor, options) {
|
||||
var uuid = frame.uuid;
|
||||
if (uuid) {
|
||||
if (CC_EDITOR && className) {
|
||||
cc.warn('Should not specify class name for Component which defines in project.');
|
||||
cc.warn('Should not specify class name %s for Component which defines in project.', className);
|
||||
}
|
||||
}
|
||||
//else {
|
||||
@@ -448,21 +458,21 @@ function define (className, baseClasses, mixins, constructor, options) {
|
||||
return doDefine(className, baseClasses, mixins, constructor, options);
|
||||
}
|
||||
|
||||
function _checkCtor (ctor) {
|
||||
function _checkCtor (ctor, className) {
|
||||
if (CC_DEV) {
|
||||
if (CCClass._isCCClass(ctor)) {
|
||||
cc.error("Constructor can not be another CCClass");
|
||||
cc.error('ctor of "%s" can not be another CCClass', className);
|
||||
return;
|
||||
}
|
||||
if (typeof ctor !== 'function') {
|
||||
cc.error("Constructor of CCClass must be function type");
|
||||
cc.error('ctor of "%s" must be function type', className);
|
||||
return;
|
||||
}
|
||||
if (ctor.length > 0) {
|
||||
// fireball-x/dev#138: To make a unified CCClass serialization process,
|
||||
// we don't allow parameters for constructor when creating instances of CCClass.
|
||||
// For advance user, construct arguments can still get from 'arguments'.
|
||||
cc.warn("Can not instantiate CCClass with arguments.");
|
||||
cc.warn('Can not instantiate CCClass "%s" with arguments.', className);
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -520,7 +530,7 @@ function _createCtor (ctor, baseClass, mixins, className, options) {
|
||||
var superCallBounded = options && baseClass && boundSuperCalls(baseClass, options);
|
||||
|
||||
if (ctor && CC_DEV) {
|
||||
_checkCtor(ctor);
|
||||
_checkCtor(ctor, className);
|
||||
}
|
||||
// get base user constructors
|
||||
var ctors = [];
|
||||
@@ -604,21 +614,21 @@ function _boundSuperCall (func, funcName, base) {
|
||||
var pd = JS.getPropertyDescriptor(base.prototype, funcName);
|
||||
if (pd) {
|
||||
superFunc = pd.value;
|
||||
// ignore pd.get, assume that function defined by getter is just for warnings
|
||||
// ignore pd.get, assume that function defined by getter is just for warnings
|
||||
if (typeof superFunc === 'function') {
|
||||
var hasSuperCall = SuperCallReg.test(func);
|
||||
if (hasSuperCall) {
|
||||
return function () {
|
||||
var tmp = this._super;
|
||||
|
||||
|
||||
// Add a new ._super() method that is the same method but on the super-Class
|
||||
this._super = superFunc;
|
||||
|
||||
|
||||
var ret = func.apply(this, arguments);
|
||||
|
||||
|
||||
// The method only need to be bound temporarily, so we remove it when we're done executing
|
||||
this._super = tmp;
|
||||
|
||||
|
||||
return ret;
|
||||
};
|
||||
}
|
||||
@@ -679,72 +689,6 @@ function declareProperties (cls, className, properties, baseClass, mixins) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @class _ComponentAttributes
|
||||
* @constructor
|
||||
*/
|
||||
/**
|
||||
* Automatically add required component as a dependency.
|
||||
*
|
||||
* @property requireComponent
|
||||
* @type {Component}
|
||||
* @default null
|
||||
*/
|
||||
/**
|
||||
* If specified to a type, prevents Component of the same type (or subtype) to be added more than once to a Node.
|
||||
*
|
||||
* @property disallowMultiple
|
||||
* @type {Component}
|
||||
* @default null
|
||||
*/
|
||||
/**
|
||||
* The menu path to register a component to the editors "Component" menu. Eg. "Rendering/Camera".
|
||||
*
|
||||
* @property menu
|
||||
* @type {String}
|
||||
* @default ""
|
||||
*/
|
||||
/**
|
||||
* Makes a component execute in edit mode.
|
||||
* By default, all components are only executed in play mode,
|
||||
* which means they will not have their callback functions executed while the Editor is in edit mode.
|
||||
*
|
||||
* @property executeInEditMode
|
||||
* @type {Boolean}
|
||||
* @default false
|
||||
*/
|
||||
/**
|
||||
* This property is only available if executeInEditMode is true.
|
||||
* If specified, the editor's scene view will keep updating this node in 60 fps when it is selected,
|
||||
* otherwise, it will update only if necessary.
|
||||
*
|
||||
* @property playOnFocus
|
||||
* @type {Boolean}
|
||||
* @default false
|
||||
*/
|
||||
/**
|
||||
* Specifying the url of the custom html to draw the component in inspector.
|
||||
*
|
||||
* @property inspector
|
||||
* @type {String}
|
||||
* @default ""
|
||||
*/
|
||||
/**
|
||||
* Specifying the url of the icon to display in inspector.
|
||||
*
|
||||
* @property icon
|
||||
* @type {String}
|
||||
* @default ""
|
||||
*/
|
||||
|
||||
/**
|
||||
* The custom documentation URL
|
||||
*
|
||||
* @property help
|
||||
* @type {String}
|
||||
* @default ""
|
||||
*/
|
||||
|
||||
/**
|
||||
* @module cc
|
||||
*/
|
||||
@@ -752,9 +696,9 @@ function declareProperties (cls, className, properties, baseClass, mixins) {
|
||||
/**
|
||||
* !#en Defines a CCClass using the given specification, please see [Class](/en/scripting/class/) for details.
|
||||
* !#zh 定义一个 CCClass,传入参数必须是一个包含类型参数的字面量对象,具体用法请查阅[类型定义](/zh/scripting/class/)。
|
||||
*
|
||||
*
|
||||
* @method Class
|
||||
*
|
||||
*
|
||||
* @param {Object} [options]
|
||||
* @param {String} [options.name] - The class name used for serialization.
|
||||
* @param {Function} [options.extends] - The base class.
|
||||
@@ -762,9 +706,17 @@ function declareProperties (cls, className, properties, baseClass, mixins) {
|
||||
* @param {Object} [options.properties] - The property definitions.
|
||||
* @param {Object} [options.statics] - The static members.
|
||||
* @param {Function[]} [options.mixins]
|
||||
*
|
||||
* @param {Object} [options.editor] - attributes for Component, see {{#crossLink "_ComponentAttributes"}}ComponentAttributes{{/crossLink}}.
|
||||
*
|
||||
*
|
||||
* @param {Object} [options.editor] - attributes for Component listed below.
|
||||
* @param {Component} [options.editor.requireComponent] - Automatically add required component as a dependency.
|
||||
* @param {Component} [options.editor.disallowMultiple] - If specified to a type, prevents Component of the same type (or subtype) to be added more than once to a Node.
|
||||
* @param {String} [options.editor.menu] - The menu path to register a component to the editors "Component" menu. Eg. "Rendering/Camera".
|
||||
* @param {Boolean} [options.editor.executeInEditMode] - Makes a component execute in edit mode. By default, all components are only executed in play mode, which means they will not have their callback functions executed while the Editor is in edit mode.
|
||||
* @param {Boolean} [options.editor.playOnFocus] - This property is only available if executeInEditMode is true. If specified, the editor's scene view will keep updating this node in 60 fps when it is selected, otherwise, it will update only if necessary.
|
||||
* @param {String} [options.editor.inspector] - Specifying the url of the custom html to draw the component in inspector.
|
||||
* @param {String} [options.editor.icon] - Specifying the url of the icon to display in inspector.
|
||||
* @param {String} [options.editor.help] - The custom documentation UR
|
||||
*
|
||||
* @param {Function} [options.update] - lifecycle method for Component, see {{#crossLink "Component/update:method"}}{{/crossLink}}
|
||||
* @param {Function} [options.lateUpdate] - lifecycle method for Component, see {{#crossLink "Component/lateUpdate:method"}}{{/crossLink}}
|
||||
* @param {Function} [options.onLoad] - lifecycle method for Component, see {{#crossLink "Component/onLoad:method"}}{{/crossLink}}
|
||||
@@ -776,9 +728,9 @@ function declareProperties (cls, className, properties, baseClass, mixins) {
|
||||
* @param {Function} [options.onLostFocusInEditor] - lifecycle method for Component, see {{#crossLink "Component/onLostFocusInEditor:method"}}{{/crossLink}}
|
||||
* @param {Function} [options.onRestore] - for Component only, see {{#crossLink "Component/onRestore:method"}}{{/crossLink}}
|
||||
* @param {Function} [options._getLocalBounds] - for Component only, see {{#crossLink "Component/_getLocalBounds:method"}}{{/crossLink}}
|
||||
*
|
||||
*
|
||||
* @return {Function} - the created class
|
||||
*
|
||||
*
|
||||
* @example
|
||||
// define base class
|
||||
var Node = cc.Class();
|
||||
@@ -896,6 +848,15 @@ function CCClass (options) {
|
||||
});
|
||||
}
|
||||
else if (CC_DEV) {
|
||||
if (func === false && base && base.prototype) {
|
||||
// check override
|
||||
var overrided = base.prototype[funcName];
|
||||
if (typeof overrided === 'function') {
|
||||
var baseFuc = JS.getClassName(base) + '.' + funcName;
|
||||
var subFuc = name + '.' + funcName;
|
||||
cc.warn('"%s" overrided "%s" but "%s" is defined as "false" so the super method will not be called. You can set "%s" to null to disable this warning.', subFuc, baseFuc, subFuc, subFuc);
|
||||
}
|
||||
}
|
||||
var correct = TYPO_TO_CORRECT[funcName];
|
||||
if (correct) {
|
||||
cc.warn('Unknown type of %s.%s, maybe you want is "%s".', name, funcName, correct);
|
||||
@@ -1042,10 +1003,10 @@ function parseAttributes (attrs, className, propName) {
|
||||
}
|
||||
|
||||
function parseSimpleAttr (attrName, expectType, attrCreater) {
|
||||
var val = attrs[attrName];
|
||||
if (val) {
|
||||
if (attrName in attrs) {
|
||||
var val = attrs[attrName];
|
||||
if (typeof val === expectType) {
|
||||
if (typeof attrCreater === 'undefined') {
|
||||
if ( !attrCreater ) {
|
||||
var attr = {};
|
||||
attr[attrName] = val;
|
||||
result.push(attr);
|
||||
@@ -1055,7 +1016,7 @@ function parseAttributes (attrs, className, propName) {
|
||||
}
|
||||
}
|
||||
else if (CC_DEV) {
|
||||
cc.error('The %s of %s.%s must be type %s', attrName, className, propName, expectType);
|
||||
cc.error(ERR_Type, attrName, className, propName, expectType);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1068,6 +1029,7 @@ function parseAttributes (attrs, className, propName) {
|
||||
parseSimpleAttr('multiline', 'boolean', {multiline: true});
|
||||
parseSimpleAttr('readonly', 'boolean', {readonly: true});
|
||||
parseSimpleAttr('tooltip', 'string');
|
||||
parseSimpleAttr('slide', 'boolean');
|
||||
}
|
||||
|
||||
if (attrs.url) {
|
||||
@@ -1105,16 +1067,19 @@ function parseAttributes (attrs, className, propName) {
|
||||
if (range) {
|
||||
if (Array.isArray(range)) {
|
||||
if (range.length >= 2) {
|
||||
result.push(Attr.Range(range[0], range[1]));
|
||||
result.push({ min: range[0], max: range[1], step: range[2] });
|
||||
}
|
||||
else if (CC_DEV) {
|
||||
cc.error('The length of range array must be 2');
|
||||
cc.error('The length of range array must be equal or greater than 2');
|
||||
}
|
||||
}
|
||||
else if (CC_DEV) {
|
||||
cc.error(ERR_Type, '"range"', className + '.' + propName, 'array');
|
||||
cc.error(ERR_Type, 'range', className, propName, 'array');
|
||||
}
|
||||
}
|
||||
parseSimpleAttr('min', 'number');
|
||||
parseSimpleAttr('max', 'number');
|
||||
parseSimpleAttr('step', 'number');
|
||||
|
||||
return result;
|
||||
}
|
||||
@@ -1131,5 +1096,5 @@ module.exports = {
|
||||
};
|
||||
|
||||
if (CC_EDITOR) {
|
||||
module.exports.getDefault = getDefault;
|
||||
module.exports.getDefault = getDefault;
|
||||
}
|
||||
|
||||
@@ -245,14 +245,14 @@ var deferredDestroyTimer = null;
|
||||
/**
|
||||
* !#en
|
||||
* Destroy this Object, and release all its own references to other objects.<br/>
|
||||
* Actual object destruction will delayed until before rendering.
|
||||
* <br/>
|
||||
* After destroy, this CCObject is not usable any more.<br/>
|
||||
* You can use cc.isValid(obj) (or obj.isValid if obj is non-nil) to check whether the object is destroyed before
|
||||
* accessing it.
|
||||
* After destroy, this CCObject is not usable any more.
|
||||
* You can use cc.isValid(obj) to check whether the object is destroyed before accessing it.
|
||||
* !#zh
|
||||
* 销毁该对象,并释放所有它对其它对象的引用。<br/>
|
||||
* 销毁后,CCObject 不再可用。<br/>
|
||||
* 您可以在访问对象之前使用 cc.isValid(obj)(或 obj.isValid 如果 obj 不为 null)来检查对象是否已被销毁。
|
||||
* 销毁后,CCObject 不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。
|
||||
* 实际销毁操作会延迟到当前帧渲染前执行。
|
||||
* @method destroy
|
||||
* @return {Boolean} whether it is the first time the destroy being called
|
||||
* @example
|
||||
|
||||
@@ -80,7 +80,7 @@ cc.screen = /** @lends cc.screen# */{
|
||||
*/
|
||||
init: function () {
|
||||
this._fn = {};
|
||||
var i, val, map = this._fnMap, valL;
|
||||
var i, l, val, map = this._fnMap, valL;
|
||||
for (i = 0, l = map.length; i < l; i++) {
|
||||
val = map[i];
|
||||
if (val && val[1] in document) {
|
||||
|
||||
@@ -232,7 +232,7 @@ sys.MACOS = 2;
|
||||
*/
|
||||
sys.ANDROID = 3;
|
||||
/**
|
||||
* @property {Number} IOS
|
||||
* @property {Number} IPHONE
|
||||
* @readOnly
|
||||
* @default 4
|
||||
*/
|
||||
@@ -459,7 +459,7 @@ sys.isNative = false;
|
||||
*/
|
||||
sys.isBrowser = typeof window === 'object' && typeof document === 'object';
|
||||
|
||||
if (typeof Editor !== 'undefined' && Editor.isMainProcess) {
|
||||
if (CC_EDITOR && Editor.isMainProcess) {
|
||||
sys.isMobile = false;
|
||||
sys.platform = sys.EDITOR_CORE;
|
||||
sys.language = sys.LANGUAGE_UNKNOWN;
|
||||
@@ -481,7 +481,7 @@ else {
|
||||
var win = window, nav = win.navigator, doc = document, docEle = doc.documentElement;
|
||||
var ua = nav.userAgent.toLowerCase();
|
||||
|
||||
if (cc.isEditor) {
|
||||
if (CC_EDITOR) {
|
||||
sys.isMobile = false;
|
||||
sys.platform = sys.EDITOR_PAGE;
|
||||
}
|
||||
@@ -705,10 +705,17 @@ else {
|
||||
var tmpCanvas = document.createElement("CANVAS");
|
||||
try{
|
||||
var context = cc.create3DContext(tmpCanvas, {'stencil': true});
|
||||
if(context) {
|
||||
if (context && context.getShaderPrecisionFormat) {
|
||||
_supportWebGL = true;
|
||||
}
|
||||
|
||||
if (_supportWebGL && sys.os === sys.OS_IOS) {
|
||||
// Not activating WebGL in iOS UIWebView because it may crash when entering background
|
||||
if (!window.indexedDB) {
|
||||
_supportWebGL = false;
|
||||
}
|
||||
}
|
||||
|
||||
if (_supportWebGL && sys.os === sys.OS_ANDROID) {
|
||||
var browserVer = parseFloat(sys.browserVersion);
|
||||
switch (sys.browserType) {
|
||||
|
||||
@@ -127,6 +127,8 @@ var View = cc._Class.extend({
|
||||
// Custom callback for resize event
|
||||
_resizeCallback: null,
|
||||
|
||||
_orientationChanging: true,
|
||||
|
||||
_scaleX: 1,
|
||||
_originalScaleX: 1,
|
||||
_scaleY: 1,
|
||||
@@ -149,12 +151,13 @@ var View = cc._Class.extend({
|
||||
__resizeWithBrowserSize: false,
|
||||
_isAdjustViewPort: true,
|
||||
_targetDensityDPI: null,
|
||||
_antiAliasEnabled: true,
|
||||
|
||||
/**
|
||||
* Constructor of View
|
||||
*/
|
||||
ctor: function () {
|
||||
var _t = this, d = document, _strategyer = cc.ContainerStrategy, _strategy = cc.ContentStrategy;
|
||||
var _t = this, _strategyer = cc.ContainerStrategy, _strategy = cc.ContentStrategy;
|
||||
|
||||
__BrowserGetter.init(this);
|
||||
|
||||
@@ -171,7 +174,6 @@ var View = cc._Class.extend({
|
||||
|
||||
var sys = cc.sys;
|
||||
_t.enableRetina(sys.os === sys.OS_IOS || sys.os === sys.OS_OSX);
|
||||
_t.enableAutoFullScreen(sys.isMobile && sys.browserType !== sys.BROWSER_TYPE_BAIDU);
|
||||
cc.visibleRect && cc.visibleRect.init(_t._visibleRect);
|
||||
|
||||
// Setup system default resolution policies
|
||||
@@ -182,6 +184,7 @@ var View = cc._Class.extend({
|
||||
_t._rpFixedWidth = new cc.ResolutionPolicy(_strategyer.EQUAL_TO_FRAME, _strategy.FIXED_WIDTH);
|
||||
|
||||
_t._targetDensityDPI = cc.macro.DENSITYDPI_HIGH;
|
||||
_t.enableAntiAlias(true);
|
||||
},
|
||||
|
||||
// Resize helper functions
|
||||
@@ -211,6 +214,11 @@ var View = cc._Class.extend({
|
||||
}
|
||||
},
|
||||
|
||||
_orientationChange: function () {
|
||||
this._orientationChanging = true;
|
||||
this._resizeEvent();
|
||||
},
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Sets view's target-densitydpi for android mobile browser. it can be set to: <br/>
|
||||
@@ -250,14 +258,14 @@ var View = cc._Class.extend({
|
||||
if (!this.__resizeWithBrowserSize) {
|
||||
this.__resizeWithBrowserSize = true;
|
||||
window.addEventListener('resize', this._resizeEvent);
|
||||
window.addEventListener('orientationchange', this._resizeEvent);
|
||||
window.addEventListener('orientationchange', this._orientationChange);
|
||||
}
|
||||
} else {
|
||||
//disable
|
||||
if (this.__resizeWithBrowserSize) {
|
||||
this.__resizeWithBrowserSize = false;
|
||||
window.removeEventListener('resize', this._resizeEvent);
|
||||
window.removeEventListener('orientationchange', this._resizeEvent);
|
||||
window.removeEventListener('orientationchange', this._orientationChange);
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -298,7 +306,7 @@ var View = cc._Class.extend({
|
||||
var h = __BrowserGetter.availHeight(cc.game.frame);
|
||||
var isLandscape = w >= h;
|
||||
|
||||
if (CC_EDITOR || !cc.sys.isMobile ||
|
||||
if (CC_EDITOR || !this._orientationChanging || !cc.sys.isMobile ||
|
||||
(isLandscape && this._orientation & cc.macro.ORIENTATION_LANDSCAPE) ||
|
||||
(!isLandscape && this._orientation & cc.macro.ORIENTATION_PORTRAIT)) {
|
||||
locFrameSize.width = w;
|
||||
@@ -316,6 +324,7 @@ var View = cc._Class.extend({
|
||||
cc.container.style.transformOrigin = '0px 0px 0px';
|
||||
this._isRotated = true;
|
||||
}
|
||||
this._orientationChanging = false;
|
||||
},
|
||||
|
||||
// hack
|
||||
@@ -416,6 +425,55 @@ var View = cc._Class.extend({
|
||||
return this._retinaEnabled;
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Whether to Enable on anti-alias
|
||||
* !#zh 控制抗锯齿是否开启
|
||||
* @method enableAntiAlias
|
||||
* @param {Boolean} enabled - Enable or not anti-alias
|
||||
*/
|
||||
enableAntiAlias: function (enabled) {
|
||||
if (this._antiAliasEnabled === enabled) {
|
||||
return;
|
||||
}
|
||||
this._antiAliasEnabled = enabled;
|
||||
if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
|
||||
var map = cc.loader._items.map;
|
||||
for (var key in map) {
|
||||
var item = map[key];
|
||||
var tex = item && item.content instanceof cc.Texture2D ? item.content : null;
|
||||
if (tex) {
|
||||
if (enabled) {
|
||||
tex.setAntiAliasTexParameters();
|
||||
}
|
||||
else {
|
||||
tex.setAliasTexParameters();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else if(cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
|
||||
var ctx = cc._canvas.getContext('2d');
|
||||
ctx.imageSmoothingEnabled = enabled;
|
||||
ctx.mozImageSmoothingEnabled = enabled;
|
||||
// refresh canvas
|
||||
var dirtyRegion = cc.rendererCanvas._dirtyRegion;
|
||||
if (dirtyRegion) {
|
||||
var oldRegion = new cc.Region();
|
||||
oldRegion.setTo(0, 0, cc.visibleRect.width, cc.visibleRect.height);
|
||||
dirtyRegion.addRegion(oldRegion);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Returns whether the current enable on anti-alias
|
||||
* !#zh 返回当前是否抗锯齿
|
||||
* @method isAntiAliasEnabled
|
||||
* @return {Boolean}
|
||||
*/
|
||||
isAntiAliasEnabled: function () {
|
||||
return this._antiAliasEnabled;
|
||||
},
|
||||
/**
|
||||
* If enabled, the application will try automatically to enter full screen mode on mobile devices<br/>
|
||||
* You can pass true as parameter to enable it and disable it by passing false.<br/>
|
||||
@@ -704,6 +762,9 @@ var View = cc._Class.extend({
|
||||
// reset director's member variables to fit visible rect
|
||||
director.setGLDefaultValues();
|
||||
}
|
||||
else if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
|
||||
cc.renderer._allNeedDraw = true;
|
||||
}
|
||||
|
||||
this._originalScaleX = this._scaleX;
|
||||
this._originalScaleY = this._scaleY;
|
||||
@@ -875,32 +936,30 @@ var View = cc._Class.extend({
|
||||
return this._isRotated ? {x: this._viewPortRect.width - y, y: x} : {x: x, y: y};
|
||||
},
|
||||
|
||||
_convertMouseToLocationInView: function(point, relatedPos) {
|
||||
var locViewPortRect = this._viewPortRect, _t = this;
|
||||
point.x = ((_t._devicePixelRatio * (point.x - relatedPos.left)) - locViewPortRect.x) / _t._scaleX;
|
||||
point.y = (_t._devicePixelRatio * (relatedPos.top + relatedPos.height - point.y) - locViewPortRect.y) / _t._scaleY;
|
||||
_convertMouseToLocationInView: function (point, relatedPos) {
|
||||
var viewport = this._viewPortRect, _t = this;
|
||||
point.x = ((_t._devicePixelRatio * (point.x - relatedPos.left)) - viewport.x) / _t._scaleX;
|
||||
point.y = (_t._devicePixelRatio * (relatedPos.top + relatedPos.height - point.y) - viewport.y) / _t._scaleY;
|
||||
},
|
||||
|
||||
_convertTouchesWithScale: function(touches){
|
||||
var locViewPortRect = this._viewPortRect, locScaleX = this._scaleX, locScaleY = this._scaleY,
|
||||
selTouch, selPoint, selPrePoint, selStartPoint;
|
||||
for( var i = 0; i < touches.length; i ++){
|
||||
_convertPointWithScale: function (point) {
|
||||
var viewport = this._viewPortRect;
|
||||
point.x = (point.x - viewport.x) / this._scaleX;
|
||||
point.y = (point.y - viewport.y) / this._scaleY;
|
||||
},
|
||||
|
||||
_convertTouchesWithScale: function (touches) {
|
||||
var viewport = this._viewPortRect, scaleX = this._scaleX, scaleY = this._scaleY,
|
||||
selTouch, selPoint, selPrePoint;
|
||||
for( var i = 0; i < touches.length; i++){
|
||||
selTouch = touches[i];
|
||||
hasStartPoint = selTouch._startPointCaptured;
|
||||
selPoint = selTouch._point;
|
||||
selPrePoint = selTouch._prevPoint;
|
||||
|
||||
selPoint.x = (selPoint.x - locViewPortRect.x) / locScaleX;
|
||||
selPoint.y = (selPoint.y - locViewPortRect.y) / locScaleY;
|
||||
selPrePoint.x = (selPrePoint.x - locViewPortRect.x) / locScaleX;
|
||||
selPrePoint.y = (selPrePoint.y - locViewPortRect.y) / locScaleY;
|
||||
|
||||
if (!hasStartPoint) {
|
||||
selStartPoint = selTouch._startPoint;
|
||||
selStartPoint.x = selPoint.x;
|
||||
selStartPoint.y = selPoint.y;
|
||||
selTouch._startPointCaptured = true;
|
||||
}
|
||||
selPoint.x = (selPoint.x - viewport.x) / scaleX;
|
||||
selPoint.y = (selPoint.y - viewport.y) / scaleY;
|
||||
selPrePoint.x = (selPrePoint.x - viewport.x) / scaleX;
|
||||
selPrePoint.y = (selPrePoint.y - viewport.y) / scaleY;
|
||||
}
|
||||
}
|
||||
});
|
||||
@@ -1058,7 +1117,15 @@ cc.ContentStrategy = cc._Class.extend(/** @lends cc.ContentStrategy# */{
|
||||
*/
|
||||
var EqualToFrame = cc.ContainerStrategy.extend({
|
||||
apply: function (view) {
|
||||
var frameH = view._frameSize.height, containerStyle = cc.container.style;
|
||||
this._setupContainer(view, view._frameSize.width, view._frameSize.height);
|
||||
// Setup container's margin and padding
|
||||
if (view._isRotated) {
|
||||
containerStyle.marginLeft = frameH + 'px';
|
||||
}
|
||||
else {
|
||||
containerStyle.margin = '0px';
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -351,10 +351,6 @@ function RawType (typename) {
|
||||
};
|
||||
}
|
||||
|
||||
function Range (min, max) {
|
||||
return { min: min, max: max };
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
attr: attr,
|
||||
getClassAttrs: getClassAttrs,
|
||||
@@ -366,5 +362,4 @@ module.exports = {
|
||||
ObjectType: ObjectType,
|
||||
RawType: RawType,
|
||||
ScriptUuid: {}, // the value will be represented as a uuid string
|
||||
Range: Range
|
||||
};
|
||||
|
||||
@@ -27,9 +27,6 @@ var JS = require('./js');
|
||||
var CCObject = require('./CCObject');
|
||||
var Attr = require('./attribute');
|
||||
|
||||
var EDITOR = CC_DEV;
|
||||
var ENABLE_TARGET = EDITOR;
|
||||
|
||||
// HELPERS
|
||||
|
||||
/**
|
||||
@@ -67,22 +64,18 @@ var Details = function () {
|
||||
*/
|
||||
this.rawProp = '';
|
||||
|
||||
if (EDITOR) {
|
||||
if (CC_DEV) {
|
||||
/**
|
||||
* 用户可以指定一个在反序列化结束时会被触发的回调,该回调会传回反序列化时统计到的所有解析过的字段。
|
||||
* 用户可以指定一个在反序列化过程中会被触发的回调,该回调会在反序列化之前调用,并且传回反序列化时解析到的字段。
|
||||
* NOTE:
|
||||
* - only available in editor
|
||||
* - 会被传回的字段仅限于非 Asset 类型,并且如果字段值为 null 或 undefined,则可能不会被传回。
|
||||
* - 该回调在 DeserializeInfo 第一次调用 reset 时就会被清空。
|
||||
* @callback visitorInEditor
|
||||
* @param {Object[]} objs
|
||||
* @param {String[]} propNames
|
||||
* @param {Object} _Deserializer
|
||||
* @callback visit
|
||||
* @param {Object} obj
|
||||
* @param {String} propName
|
||||
* @private
|
||||
*/
|
||||
this.visitorInEditor = null;
|
||||
|
||||
this.visitObjList = [];
|
||||
this.visitPropList = [];
|
||||
this.visit = null;
|
||||
}
|
||||
};
|
||||
/**
|
||||
@@ -95,17 +88,15 @@ Details.prototype.reset = function () {
|
||||
this.rawProp = '';
|
||||
//this.rawObjList.length = 0;
|
||||
//this.rawPropList.length = 0;
|
||||
|
||||
if (EDITOR) {
|
||||
this.visitorInEditor = null;
|
||||
this.visitObjList.length = 0;
|
||||
this.visitPropList.length = 0;
|
||||
}
|
||||
};
|
||||
if (EDITOR) {
|
||||
Details.prototype.visitLater = function (obj, propName) {
|
||||
this.visitObjList.push(obj);
|
||||
this.visitPropList.push(propName);
|
||||
if (CC_DEV) {
|
||||
Details.prototype.assignAssetsBy = function (getter) {
|
||||
for (var i = 0, len = this.uuidList.length; i < len; i++) {
|
||||
var uuid = this.uuidList[i];
|
||||
var obj = this.uuidObjList[i];
|
||||
var prop = this.uuidPropList[i];
|
||||
obj[prop] = getter(uuid);
|
||||
}
|
||||
};
|
||||
}
|
||||
/**
|
||||
@@ -122,28 +113,6 @@ Details.prototype.getUuidOf = function (obj, propName) {
|
||||
}
|
||||
return "";
|
||||
};
|
||||
/**
|
||||
* @method assignAssetsBy
|
||||
* @param {Function} getter
|
||||
* @return {Boolean} success
|
||||
*/
|
||||
Details.prototype.assignAssetsBy = function (getter) {
|
||||
var success = true;
|
||||
for (var i = 0, len = this.uuidList.length; i < len; i++) {
|
||||
var uuid = this.uuidList[i];
|
||||
var asset = getter(uuid);
|
||||
if (asset) {
|
||||
var obj = this.uuidObjList[i];
|
||||
var prop = this.uuidPropList[i];
|
||||
obj[prop] = asset;
|
||||
}
|
||||
else {
|
||||
cc.error('Failed to assign asset: ' + uuid);
|
||||
success = false;
|
||||
}
|
||||
}
|
||||
return success;
|
||||
};
|
||||
/**
|
||||
* @method push
|
||||
* @param {Object} obj
|
||||
@@ -159,13 +128,11 @@ Details.prototype.push = function (obj, propName, uuid) {
|
||||
// IMPLEMENT OF DESERIALIZATION
|
||||
|
||||
var _Deserializer = (function () {
|
||||
///**
|
||||
// * @param {Boolean} isEditor - if false, "editorOnly" properties will be discarded
|
||||
// */
|
||||
function _Deserializer(jsonObj, result, target, classFinder, customEnv) {
|
||||
function _Deserializer(jsonObj, result, target, classFinder, customEnv, ignoreEditorOnly) {
|
||||
this._classFinder = classFinder;
|
||||
if (ENABLE_TARGET) {
|
||||
if (CC_DEV) {
|
||||
this._target = target;
|
||||
this._ignoreEditorOnly = ignoreEditorOnly;
|
||||
}
|
||||
this._idList = [];
|
||||
this._idObjList = [];
|
||||
@@ -181,7 +148,7 @@ var _Deserializer = (function () {
|
||||
for (var i = 0; i < refCount; i++) {
|
||||
if (jsonArray[i]) {
|
||||
var mainTarget;
|
||||
if (ENABLE_TARGET) {
|
||||
if (CC_DEV) {
|
||||
mainTarget = (i === 0 && target);
|
||||
}
|
||||
this.deserializedList[i] = _deserializeObject(this, jsonArray[i], mainTarget);
|
||||
@@ -209,14 +176,9 @@ var _Deserializer = (function () {
|
||||
|
||||
// dereference
|
||||
_dereference(this);
|
||||
|
||||
// call visitor after all properties initialized
|
||||
if (EDITOR) {
|
||||
this._callVisitorInEditor();
|
||||
}
|
||||
}
|
||||
|
||||
var _dereference = function (self) {
|
||||
function _dereference (self) {
|
||||
// 这里不采用遍历反序列化结果的方式,因为反序列化的结果如果引用到复杂的外部库,很容易堆栈溢出。
|
||||
var deserializedList = self.deserializedList;
|
||||
var idPropList = self._idPropList;
|
||||
@@ -227,18 +189,9 @@ var _Deserializer = (function () {
|
||||
var id = idList[i];
|
||||
idObjList[i][propName] = deserializedList[id];
|
||||
}
|
||||
};
|
||||
|
||||
if (EDITOR) {
|
||||
_Deserializer.prototype._callVisitorInEditor = function () {
|
||||
var result = this.result;
|
||||
if (result.visitorInEditor) {
|
||||
result.visitorInEditor(result.visitObjList, result.visitPropList, this);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
// 和 _deserializeObject 不同的地方在于会判断 id 和 uuid
|
||||
// 和 _deserializeObject 不同的地方在于会判断 id 和 uuid
|
||||
_Deserializer.prototype._deserializeObjField = function (obj, jsonObj, propName, target) {
|
||||
var id = jsonObj.__id__;
|
||||
if (typeof id === 'undefined') {
|
||||
@@ -258,14 +211,14 @@ var _Deserializer = (function () {
|
||||
this.result.uuidPropList.push(propName);
|
||||
}
|
||||
else {
|
||||
if (ENABLE_TARGET) {
|
||||
if (CC_DEV) {
|
||||
obj[propName] = _deserializeObject(this, jsonObj, target && target[propName]);
|
||||
}
|
||||
else {
|
||||
obj[propName] = _deserializeObject(this, jsonObj);
|
||||
}
|
||||
if (this.result.visitorInEditor && EDITOR) {
|
||||
this.result.visitLater(obj, propName);
|
||||
if (CC_DEV && this.result.visit) {
|
||||
this.result.visit(obj, propName);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -279,8 +232,8 @@ var _Deserializer = (function () {
|
||||
this._idObjList.push(obj);
|
||||
this._idPropList.push(propName);
|
||||
}
|
||||
if (this.result.visitorInEditor && EDITOR) {
|
||||
this.result.visitLater(obj, propName);
|
||||
if (CC_DEV && this.result.visit) {
|
||||
this.result.visit(obj, propName);
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -292,14 +245,14 @@ var _Deserializer = (function () {
|
||||
if (typeof prop !== 'object') {
|
||||
if (propName !== '__type__'/* && k != '__id__'*/) {
|
||||
instance[propName] = prop;
|
||||
if (self.result.visitorInEditor && EDITOR) {
|
||||
self.result.visitLater(instance, propName);
|
||||
if (CC_DEV && self.result.visit) {
|
||||
self.result.visit(instance, propName);
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (prop) {
|
||||
if (ENABLE_TARGET) {
|
||||
if (CC_DEV) {
|
||||
self._deserializeObjField(instance, prop, propName, self._target && instance);
|
||||
}
|
||||
else {
|
||||
@@ -328,7 +281,7 @@ var _Deserializer = (function () {
|
||||
}
|
||||
else {
|
||||
if (prop) {
|
||||
if (ENABLE_TARGET) {
|
||||
if (CC_DEV) {
|
||||
self._deserializeObjField(instance, prop, propName, self._target && instance);
|
||||
}
|
||||
else {
|
||||
@@ -344,22 +297,25 @@ var _Deserializer = (function () {
|
||||
//--self.stackCounter;
|
||||
}
|
||||
|
||||
var RAW_TYPE = Attr.DELIMETER + 'rawType';
|
||||
var EDITOR_ONLY = Attr.DELIMETER + 'editorOnly';
|
||||
var SERIALIZABLE = Attr.DELIMETER + 'serializable';
|
||||
|
||||
function _deserializeFireClass(self, obj, serialized, klass, target) {
|
||||
var DELIMETER = Attr.DELIMETER;
|
||||
var props = klass.__props__;
|
||||
var attrs = Attr.getClassAttrs(klass);
|
||||
for (var p = 0; p < props.length; p++) {
|
||||
var propName = props[p];
|
||||
// assume all prop in __props__ must have attr
|
||||
var rawType = attrs[propName + DELIMETER + 'rawType'];
|
||||
var rawType = attrs[propName + RAW_TYPE];
|
||||
if (!rawType) {
|
||||
if (!EDITOR && attrs[propName + DELIMETER + 'editorOnly']) {
|
||||
if (((CC_EDITOR && self._ignoreEditorOnly) || (!CC_EDITOR && CC_DEV && !CC_TEST))
|
||||
&& attrs[propName + EDITOR_ONLY]) {
|
||||
var mayUsedInPersistRoot = (obj instanceof cc.Node && propName === '_id');
|
||||
if ( !mayUsedInPersistRoot ) {
|
||||
continue; // skip editor only if not editor
|
||||
continue; // skip editor only if in preview
|
||||
}
|
||||
}
|
||||
if (attrs[propName + DELIMETER + 'serializable'] === false) {
|
||||
if (attrs[propName + SERIALIZABLE] === false) {
|
||||
continue; // skip nonSerialized
|
||||
}
|
||||
var prop = serialized[propName];
|
||||
@@ -371,7 +327,7 @@ var _Deserializer = (function () {
|
||||
}
|
||||
else {
|
||||
if (prop) {
|
||||
if (ENABLE_TARGET) {
|
||||
if (CC_DEV) {
|
||||
self._deserializeObjField(obj, prop, propName, target && obj);
|
||||
}
|
||||
else {
|
||||
@@ -404,8 +360,8 @@ var _Deserializer = (function () {
|
||||
// * @param {Object} serialized - The obj to deserialize, must be non-nil
|
||||
// * @param {Object} [target=null]
|
||||
// */
|
||||
var _deserializeObject = function (self, serialized, target) {
|
||||
var propName, prop;
|
||||
function _deserializeObject (self, serialized, target) {
|
||||
var prop;
|
||||
var obj = null; // the obj to return
|
||||
var klass = null;
|
||||
if (serialized.__type__) {
|
||||
@@ -413,18 +369,16 @@ var _Deserializer = (function () {
|
||||
// Type Object (including CCClass)
|
||||
|
||||
var type = serialized.__type__;
|
||||
klass = self._classFinder(type);
|
||||
klass = self._classFinder(type, serialized);
|
||||
if (!klass) {
|
||||
if (CC_EDITOR && Editor.UuidUtils.isUuid(type)) {
|
||||
type = Editor.UuidUtils.decompressUuid(type);
|
||||
cc.warn('Can not find script "%s"', type);
|
||||
return null;
|
||||
var noLog = self._classFinder === JS._getClassById;
|
||||
if (noLog) {
|
||||
cc.deserialize.reportMissingClass(type);
|
||||
}
|
||||
cc.warn('Can not find class "%s"', type);
|
||||
return null;
|
||||
}
|
||||
|
||||
if (ENABLE_TARGET && target) {
|
||||
if (CC_DEV && target) {
|
||||
// use target
|
||||
if ( !(target instanceof klass) ) {
|
||||
cc.warn('Type of target to deserialize not matched with data: target is %s, data is %s',
|
||||
@@ -456,14 +410,14 @@ var _Deserializer = (function () {
|
||||
|
||||
// embedded primitive javascript object
|
||||
|
||||
obj = (ENABLE_TARGET && target) || {};
|
||||
obj = (CC_DEV && target) || {};
|
||||
_deserializePrimitiveObject(self, obj, serialized);
|
||||
}
|
||||
else {
|
||||
|
||||
// Array
|
||||
|
||||
if (ENABLE_TARGET && target) {
|
||||
if (CC_DEV && target) {
|
||||
target.length = serialized.length;
|
||||
obj = target;
|
||||
}
|
||||
@@ -474,7 +428,7 @@ var _Deserializer = (function () {
|
||||
for (var i = 0; i < serialized.length; i++) {
|
||||
prop = serialized[i];
|
||||
if (typeof prop === 'object' && prop) {
|
||||
if (ENABLE_TARGET) {
|
||||
if (CC_DEV) {
|
||||
self._deserializeObjField(obj, prop, '' + i, target && obj);
|
||||
}
|
||||
else {
|
||||
@@ -483,21 +437,18 @@ var _Deserializer = (function () {
|
||||
}
|
||||
else {
|
||||
obj[i] = prop;
|
||||
|
||||
if (self.result.visitorInEditor && EDITOR) {
|
||||
self.result.visitLater(obj, '' + i);
|
||||
if (CC_DEV && self.result.visit) {
|
||||
self.result.visit(obj, '' + i);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return obj;
|
||||
};
|
||||
}
|
||||
|
||||
return _Deserializer;
|
||||
})();
|
||||
|
||||
// FACADE
|
||||
|
||||
/**
|
||||
* @module cc
|
||||
*/
|
||||
@@ -516,11 +467,13 @@ var _Deserializer = (function () {
|
||||
* @return {object} the main data(asset)
|
||||
*/
|
||||
cc.deserialize = function (data, result, options) {
|
||||
var classFinder = (options && options.classFinder) || JS._getClassById;
|
||||
options = options || {};
|
||||
var classFinder = options.classFinder || JS._getClassById;
|
||||
// 启用 createAssetRefs 后,如果有 url 属性则会被统一强制设置为 { uuid: 'xxx' },必须后面再特殊处理
|
||||
var createAssetRefs = (options && options.createAssetRefs) || cc.sys.platform === cc.sys.EDITOR_CORE;
|
||||
var target = ENABLE_TARGET && (options && options.target);
|
||||
var customEnv = (options && options.customEnv);
|
||||
var createAssetRefs = options.createAssetRefs || cc.sys.platform === cc.sys.EDITOR_CORE;
|
||||
var target = CC_DEV && options.target;
|
||||
var customEnv = options.customEnv;
|
||||
var ignoreEditorOnly = options.ignoreEditorOnly;
|
||||
|
||||
if (CC_EDITOR && Buffer.isBuffer(data)) {
|
||||
data = data.toString();
|
||||
@@ -536,7 +489,7 @@ cc.deserialize = function (data, result, options) {
|
||||
result = new Details();
|
||||
}
|
||||
cc.game._isCloning = true;
|
||||
var deserializer = new _Deserializer(data, result, target, classFinder, customEnv);
|
||||
var deserializer = new _Deserializer(data, result, target, classFinder, customEnv, ignoreEditorOnly);
|
||||
cc.game._isCloning = false;
|
||||
|
||||
if (createAssetRefs) {
|
||||
@@ -552,3 +505,12 @@ cc.deserialize = function (data, result, options) {
|
||||
};
|
||||
|
||||
cc.deserialize.Details = Details;
|
||||
cc.deserialize.reportMissingClass = function (id) {
|
||||
if (CC_EDITOR && Editor.UuidUtils.isUuid(id)) {
|
||||
id = Editor.UuidUtils.decompressUuid(id);
|
||||
cc.warn('Can not find script "%s"', id);
|
||||
}
|
||||
else {
|
||||
cc.warn('Can not find class "%s"', id);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -30,7 +30,6 @@ require('./callbacks-invoker');
|
||||
require('./url');
|
||||
require('./deserialize');
|
||||
require('./instantiate');
|
||||
require('./prefab-info');
|
||||
require('./requiring-frame');
|
||||
require('./CCSys');
|
||||
require('./CCMacro');
|
||||
|
||||
@@ -46,15 +46,21 @@ var _isDomNode = require('./utils').isDomNode;
|
||||
*/
|
||||
function instantiate (original) {
|
||||
if (typeof original !== 'object' || Array.isArray(original)) {
|
||||
cc.error('The thing you want to instantiate must be an object');
|
||||
if (CC_DEV) {
|
||||
cc.error('The thing you want to instantiate must be an object');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (!original) {
|
||||
cc.error('The thing you want to instantiate is nil');
|
||||
if (CC_DEV) {
|
||||
cc.error('The thing you want to instantiate is nil');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
if (original instanceof CCObject && !original.isValid) {
|
||||
cc.error('The thing you want to instantiate is destroyed');
|
||||
if (CC_DEV) {
|
||||
cc.error('The thing you want to instantiate is destroyed');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -69,7 +75,9 @@ function instantiate (original) {
|
||||
}
|
||||
else if (original instanceof cc.Asset) {
|
||||
// 不允许用通用方案实例化资源
|
||||
cc.error('The instantiate method for given asset do not implemented');
|
||||
if (CC_DEV) {
|
||||
cc.error('The instantiate method for given asset do not implemented');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -103,12 +111,21 @@ function doInstantiate (obj, parent) {
|
||||
cc.error('Can not instantiate array');
|
||||
return null;
|
||||
}
|
||||
if (_isDomNode && _isDomNode(obj)) {
|
||||
if (!CC_JSB && _isDomNode && _isDomNode(obj)) {
|
||||
cc.error('Can not instantiate DOM element');
|
||||
return null;
|
||||
}
|
||||
|
||||
var clone = enumerateObject(obj, parent);
|
||||
var clone;
|
||||
if (obj._iN$t) {
|
||||
clone = obj._iN$t;
|
||||
}
|
||||
else {
|
||||
// User can specify an existing object by assigning the "_iN$t" property
|
||||
var klass = obj.constructor;
|
||||
clone = new klass();
|
||||
}
|
||||
enumerateObject(obj, clone, parent);
|
||||
|
||||
for (var i = 0, len = objsToClearTmpVar.length; i < len; ++i) {
|
||||
objsToClearTmpVar[i]._iN$t = null;
|
||||
@@ -118,14 +135,10 @@ function doInstantiate (obj, parent) {
|
||||
return clone;
|
||||
}
|
||||
|
||||
///**
|
||||
// * @param {Object} obj - The object to instantiate, typeof must be 'object' and should not be an array.
|
||||
// * @return {Object} - the instantiated instance
|
||||
// */
|
||||
var enumerateObject = function (obj, parent) {
|
||||
// @param {Object} obj - The object to instantiate, typeof must be 'object' and should not be an array.
|
||||
function enumerateObject (obj, clone, parent) {
|
||||
var value, type, key;
|
||||
var klass = obj.constructor;
|
||||
var clone = new klass();
|
||||
obj._iN$t = clone;
|
||||
objsToClearTmpVar.push(obj);
|
||||
if (cc.Class._isCCClass(klass)) {
|
||||
@@ -175,8 +188,7 @@ var enumerateObject = function (obj, parent) {
|
||||
if (obj instanceof CCObject) {
|
||||
clone._objFlags &= PersistentMask;
|
||||
}
|
||||
return clone;
|
||||
};
|
||||
}
|
||||
|
||||
///**
|
||||
// * @return {Object} - the original non-nil object, typeof must be 'object'
|
||||
@@ -248,7 +260,9 @@ function instantiateObj (obj, parent, ownerObj, ownerKey) {
|
||||
// unknown type
|
||||
return obj;
|
||||
}
|
||||
return enumerateObject(obj, parent);
|
||||
clone = new ctor();
|
||||
enumerateObject(obj, clone, parent);
|
||||
return clone;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -24,12 +24,17 @@
|
||||
****************************************************************************/
|
||||
|
||||
module.exports = {
|
||||
isDomNode: typeof window === 'object' && function (obj) {
|
||||
return (
|
||||
typeof Node === "object" ? obj instanceof Node :
|
||||
obj && typeof obj === "object" && typeof obj.nodeType === "number" && typeof obj.nodeName === "string"
|
||||
);
|
||||
},
|
||||
isDomNode: typeof window === 'object' && (typeof Node === 'function' ?
|
||||
function (obj) {
|
||||
return obj instanceof Node;
|
||||
} :
|
||||
function (obj) {
|
||||
return obj &&
|
||||
typeof obj === 'object' &&
|
||||
typeof obj.nodeType === 'number' &&
|
||||
typeof obj.nodeName === 'string';
|
||||
}
|
||||
),
|
||||
|
||||
callInNextTick: CC_EDITOR ?
|
||||
function (callback, p1, p2) {
|
||||
|
||||
@@ -44,6 +44,11 @@ cc.rendererCanvas = {
|
||||
|
||||
//max dirty Region count, default is 10
|
||||
_dirtyRegionCountThreshold: 10,
|
||||
init: function() {
|
||||
if(cc.sys.browserType === cc.sys.BROWSER_TYPE_IE || cc.sys.browserType === cc.sys.BROWSER_TYPE_UC) {
|
||||
this.enableDirtyRegion(false);
|
||||
}
|
||||
},
|
||||
|
||||
getRenderCmd: function (renderableObject) {
|
||||
//TODO Add renderCmd pool here
|
||||
@@ -390,14 +395,7 @@ cc.rendererCanvas = {
|
||||
};
|
||||
|
||||
proto.setFillStyle = function(fillStyle){
|
||||
if (this._saveCount > 0) {
|
||||
this._context.fillStyle = fillStyle;
|
||||
} else {
|
||||
if (this._currentFillStyle !== fillStyle) {
|
||||
this._currentFillStyle = fillStyle;
|
||||
this._context.fillStyle = fillStyle;
|
||||
}
|
||||
}
|
||||
this._context.fillStyle = fillStyle;
|
||||
};
|
||||
|
||||
proto.setStrokeStyle = function(strokeStyle){
|
||||
|
||||
@@ -38,6 +38,7 @@ var _batchedInfo = {
|
||||
shader: null
|
||||
},
|
||||
|
||||
_batchBroken = false,
|
||||
_indexBuffer = null,
|
||||
_vertexBuffer = null,
|
||||
// Total vertex size
|
||||
@@ -302,6 +303,10 @@ cc.rendererWebGL = {
|
||||
_batchingSize += increment;
|
||||
},
|
||||
|
||||
_breakBatch: function () {
|
||||
_batchBroken = true;
|
||||
},
|
||||
|
||||
_uploadBufferData: function (cmd) {
|
||||
if (_batchingSize >= _maxVertexSize) {
|
||||
this._batchRendering();
|
||||
@@ -313,7 +318,8 @@ cc.rendererWebGL = {
|
||||
var blendSrc = cmd._node._blendFunc.src;
|
||||
var blendDst = cmd._node._blendFunc.dst;
|
||||
var shader = cmd._shaderProgram;
|
||||
if (_batchedInfo.texture !== texture ||
|
||||
if (_batchBroken ||
|
||||
_batchedInfo.texture !== texture ||
|
||||
_batchedInfo.blendSrc !== blendSrc ||
|
||||
_batchedInfo.blendDst !== blendDst ||
|
||||
_batchedInfo.shader !== shader) {
|
||||
@@ -324,6 +330,7 @@ cc.rendererWebGL = {
|
||||
_batchedInfo.blendSrc = blendSrc;
|
||||
_batchedInfo.blendDst = blendDst;
|
||||
_batchedInfo.shader = shader;
|
||||
_batchBroken = false;
|
||||
}
|
||||
|
||||
// Upload vertex data
|
||||
|
||||
@@ -400,12 +400,12 @@ _ccsg.Sprite = _ccsg.Node.extend({
|
||||
* @param {Boolean} relative
|
||||
* @override
|
||||
*/
|
||||
ignoreAnchorPointForPosition:function (relative) {
|
||||
setIgnoreAnchorPointForPosition:function (relative) {
|
||||
if(this._batchNode){
|
||||
cc.log(cc._LogInfos.Sprite.ignoreAnchorPointForPosition);
|
||||
cc.log(cc._LogInfos.Sprite.setIgnoreAnchorPointForPosition);
|
||||
return;
|
||||
}
|
||||
_ccsg.Node.prototype.ignoreAnchorPointForPosition.call(this, relative);
|
||||
_ccsg.Node.prototype.setIgnoreAnchorPointForPosition.call(this, relative);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -975,7 +975,7 @@ Object.defineProperty(spritePro, 'visible', {
|
||||
|
||||
Object.defineProperty(spritePro, 'ignoreAnchor', {
|
||||
get: _ccsg.Node.prototype.isIgnoreAnchorPointForPosition,
|
||||
set: spritePro.ignoreAnchorPointForPosition
|
||||
set: spritePro.setIgnoreAnchorPointForPosition
|
||||
});
|
||||
|
||||
Object.defineProperty(spritePro, 'opacityModifyRGB', {
|
||||
|
||||
@@ -84,13 +84,6 @@ var FIX_ARTIFACTS_BY_STRECHING_TEXEL = cc.macro.FIX_ARTIFACTS_BY_STRECHING_TEXEL
|
||||
var simpleQuadGenerator = {
|
||||
_rebuildQuads_base: function (sprite, spriteFrame, contentSize, isTrimmedContentSize) {
|
||||
//build vertices
|
||||
this._calculateVertices(sprite, spriteFrame, contentSize, isTrimmedContentSize);
|
||||
//build uvs
|
||||
this._calculateUVs(sprite, spriteFrame);
|
||||
sprite._vertCount = 4;
|
||||
},
|
||||
|
||||
_calculateVertices: function (sprite, spriteFrame, contentSize, isTrimmedContentSize) {
|
||||
var vertices = sprite._vertices,
|
||||
wt = sprite._renderCmd._worldTransform,
|
||||
l, b, r, t;
|
||||
@@ -100,9 +93,9 @@ var simpleQuadGenerator = {
|
||||
r = contentSize.width;
|
||||
t = contentSize.height;
|
||||
} else {
|
||||
var originalSize = spriteFrame.getOriginalSize();
|
||||
var originalSize = spriteFrame._originalSize;
|
||||
var rect = spriteFrame._rect;
|
||||
var offset = spriteFrame.getOffset();
|
||||
var offset = spriteFrame._offset;
|
||||
var scaleX = contentSize.width / originalSize.width;
|
||||
var scaleY = contentSize.height / originalSize.height;
|
||||
var trimmLeft = offset.x + (originalSize.width - rect.width) / 2;
|
||||
@@ -147,12 +140,19 @@ var simpleQuadGenerator = {
|
||||
cornerId[1] = 2;
|
||||
cornerId[2] = 4;
|
||||
cornerId[3] = 6;
|
||||
|
||||
//build uvs
|
||||
if (sprite._uvsDirty) {
|
||||
this._calculateUVs(sprite, spriteFrame);
|
||||
}
|
||||
|
||||
sprite._vertCount = 4;
|
||||
},
|
||||
|
||||
_calculateUVs: function (sprite, spriteFrame) {
|
||||
var uvs = sprite._uvs;
|
||||
var atlasWidth = spriteFrame._texture.getPixelWidth();
|
||||
var atlasHeight = spriteFrame._texture.getPixelHeight();
|
||||
var atlasWidth = spriteFrame._texture._pixelWidth;
|
||||
var atlasHeight = spriteFrame._texture._pixelHeight;
|
||||
var textureRect = spriteFrame._rect;
|
||||
|
||||
if (uvs.length < 8) {
|
||||
@@ -189,24 +189,19 @@ var simpleQuadGenerator = {
|
||||
};
|
||||
|
||||
var scale9QuadGenerator = {
|
||||
x: new Array(4),
|
||||
y: new Array(4),
|
||||
_rebuildQuads_base: function (sprite, spriteFrame, contentSize, insetLeft, insetRight, insetTop, insetBottom) {
|
||||
//build vertices
|
||||
this._calculateVertices(sprite, spriteFrame, contentSize, insetLeft, insetRight, insetTop, insetBottom);
|
||||
//build uvs
|
||||
this._calculateUVs(sprite, spriteFrame, insetLeft, insetRight, insetTop, insetBottom);
|
||||
},
|
||||
|
||||
_calculateVertices: function (sprite, spriteFrame, contentSize, insetLeft, insetRight, insetTop, insetBottom) {
|
||||
var vertices = sprite._vertices;
|
||||
var wt = sprite._renderCmd._worldTransform;
|
||||
var leftWidth, centerWidth, rightWidth;
|
||||
var topHeight, centerHeight, bottomHeight;
|
||||
|
||||
var rect = spriteFrame._rect;
|
||||
|
||||
leftWidth = insetLeft;
|
||||
rightWidth = insetRight;
|
||||
centerWidth = rect.width - leftWidth - rightWidth;
|
||||
|
||||
topHeight = insetTop;
|
||||
bottomHeight = insetBottom;
|
||||
centerHeight = rect.height - topHeight - bottomHeight;
|
||||
@@ -220,8 +215,8 @@ var scale9QuadGenerator = {
|
||||
yScale = yScale > 1 ? 1 : yScale;
|
||||
sizableWidth = sizableWidth < 0 ? 0 : sizableWidth;
|
||||
sizableHeight = sizableHeight < 0 ? 0 : sizableHeight;
|
||||
var x = new Array(4);
|
||||
var y = new Array(4);
|
||||
var x = this.x;
|
||||
var y = this.y;
|
||||
x[0] = 0;
|
||||
x[1] = leftWidth * xScale;
|
||||
x[2] = x[1] + sizableWidth;
|
||||
@@ -260,25 +255,30 @@ var scale9QuadGenerator = {
|
||||
cornerId[1] = 6;
|
||||
cornerId[2] = 24;
|
||||
cornerId[3] = 30;
|
||||
|
||||
//build uvs
|
||||
if (sprite._uvsDirty) {
|
||||
this._calculateUVs(sprite, spriteFrame, insetLeft, insetRight, insetTop, insetBottom);
|
||||
}
|
||||
},
|
||||
|
||||
_calculateUVs: function (sprite, spriteFrame, insetLeft, insetRight, insetTop, insetBottom) {
|
||||
var uvs = sprite._uvs;
|
||||
var rect = spriteFrame._rect;
|
||||
var atlasWidth = spriteFrame._texture.getPixelWidth();
|
||||
var atlasHeight = spriteFrame._texture.getPixelHeight();
|
||||
var atlasWidth = spriteFrame._texture._pixelWidth;
|
||||
var atlasHeight = spriteFrame._texture._pixelHeight;
|
||||
|
||||
//caculate texture coordinate
|
||||
var leftWidth, centerWidth, rightWidth;
|
||||
var topHeight, centerHeight, bottomHeight;
|
||||
var textureRect = spriteFrame._rect;
|
||||
|
||||
leftWidth = insetLeft;
|
||||
rightWidth = insetRight;
|
||||
centerWidth = rect.width - leftWidth - rightWidth;
|
||||
|
||||
topHeight = insetTop;
|
||||
bottomHeight = insetBottom;
|
||||
centerHeight = rect.height - topHeight - bottomHeight;
|
||||
var textureRect = spriteFrame._rect;
|
||||
|
||||
if (uvs.length < 32) {
|
||||
dataPool.put(uvs);
|
||||
@@ -287,20 +287,20 @@ var scale9QuadGenerator = {
|
||||
}
|
||||
|
||||
//uv computation should take spritesheet into account.
|
||||
var u = new Array(4);
|
||||
var v = new Array(4);
|
||||
var offset = 0, row, col;
|
||||
var u = this.x;
|
||||
var v = this.y;
|
||||
var texelCorrect = FIX_ARTIFACTS_BY_STRECHING_TEXEL ? 0.5 : 0;
|
||||
var offset = 0, row, col;
|
||||
|
||||
if (spriteFrame._rotated) {
|
||||
u[0] = (textureRect.x + texelCorrect) / atlasWidth;
|
||||
u[1] = (bottomHeight + textureRect.x - texelCorrect) / atlasWidth;
|
||||
u[2] = (bottomHeight + centerHeight + textureRect.x - texelCorrect) / atlasWidth;
|
||||
u[1] = (bottomHeight + textureRect.x) / atlasWidth;
|
||||
u[2] = (bottomHeight + centerHeight + textureRect.x) / atlasWidth;
|
||||
u[3] = (textureRect.x + textureRect.height - texelCorrect) / atlasWidth;
|
||||
|
||||
v[3] = (textureRect.y + texelCorrect) / atlasHeight;
|
||||
v[2] = (leftWidth + textureRect.y - texelCorrect) / atlasHeight;
|
||||
v[1] = (leftWidth + centerWidth + textureRect.y - texelCorrect) / atlasHeight;
|
||||
v[2] = (leftWidth + textureRect.y) / atlasHeight;
|
||||
v[1] = (leftWidth + centerWidth + textureRect.y) / atlasHeight;
|
||||
v[0] = (textureRect.y + textureRect.width - texelCorrect) / atlasHeight;
|
||||
|
||||
for (row = 0; row < 4; row++) {
|
||||
@@ -313,13 +313,13 @@ var scale9QuadGenerator = {
|
||||
}
|
||||
else {
|
||||
u[0] = (textureRect.x + texelCorrect) / atlasWidth;
|
||||
u[1] = (leftWidth + textureRect.x - texelCorrect) / atlasWidth;
|
||||
u[2] = (leftWidth + centerWidth + textureRect.x - texelCorrect) / atlasWidth;
|
||||
u[1] = (leftWidth + textureRect.x) / atlasWidth;
|
||||
u[2] = (leftWidth + centerWidth + textureRect.x) / atlasWidth;
|
||||
u[3] = (textureRect.x + textureRect.width - texelCorrect) / atlasWidth;
|
||||
|
||||
v[3] = (textureRect.y + texelCorrect) / atlasHeight;
|
||||
v[2] = (topHeight + textureRect.y - texelCorrect) / atlasHeight;
|
||||
v[1] = (topHeight + centerHeight + textureRect.y - texelCorrect) / atlasHeight;
|
||||
v[2] = (topHeight + textureRect.y) / atlasHeight;
|
||||
v[1] = (topHeight + centerHeight + textureRect.y) / atlasHeight;
|
||||
v[0] = (textureRect.y + textureRect.height - texelCorrect) / atlasHeight;
|
||||
|
||||
for (row = 0; row < 4; row++) {
|
||||
@@ -339,8 +339,8 @@ var tiledQuadGenerator = {
|
||||
wt = sprite._renderCmd._worldTransform,
|
||||
uvs = sprite._uvs;
|
||||
//build uvs
|
||||
var atlasWidth = spriteFrame._texture.getPixelWidth();
|
||||
var atlasHeight = spriteFrame._texture.getPixelHeight();
|
||||
var atlasWidth = spriteFrame._texture._pixelWidth;
|
||||
var atlasHeight = spriteFrame._texture._pixelHeight;
|
||||
var textureRect = spriteFrame._rect;
|
||||
|
||||
//uv computation should take spritesheet into account.
|
||||
@@ -437,9 +437,9 @@ var tiledQuadGenerator = {
|
||||
}
|
||||
|
||||
cornerId[0] = 0;
|
||||
cornerId[1] = 2;
|
||||
cornerId[2] = 4;
|
||||
cornerId[3] = 6;
|
||||
cornerId[1] = col * 8 + 2;
|
||||
cornerId[2] = dataLength - col * 8 + 4;
|
||||
cornerId[3] = dataLength - 2;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -454,8 +454,8 @@ var fillQuadGeneratorBar = {
|
||||
var l = 0, b = 0,
|
||||
r = contentSize.width, t = contentSize.height;
|
||||
//build uvs
|
||||
var atlasWidth = spriteFrame._texture.getPixelWidth();
|
||||
var atlasHeight = spriteFrame._texture.getPixelHeight();
|
||||
var atlasWidth = spriteFrame._texture._pixelWidth;
|
||||
var atlasHeight = spriteFrame._texture._pixelHeight;
|
||||
var textureRect = spriteFrame._rect;
|
||||
//uv computation should take spritesheet into account.
|
||||
var ul, vb, ur, vt;
|
||||
@@ -484,28 +484,6 @@ var fillQuadGeneratorBar = {
|
||||
sprite._uvs = uvs;
|
||||
}
|
||||
|
||||
//build quads
|
||||
if (webgl) {
|
||||
vertices[0] = l * wt.a + b * wt.c + wt.tx;
|
||||
vertices[1] = l * wt.b + b * wt.d + wt.ty;
|
||||
vertices[2] = r * wt.a + b * wt.c + wt.tx;
|
||||
vertices[3] = r * wt.b + b * wt.d + wt.ty;
|
||||
vertices[4] = l * wt.a + t * wt.c + wt.tx;
|
||||
vertices[5] = l * wt.b + t * wt.d + wt.ty;
|
||||
vertices[6] = r * wt.a + t * wt.c + wt.tx;
|
||||
vertices[7] = r * wt.b + t * wt.d + wt.ty;
|
||||
}
|
||||
else {
|
||||
vertices[0] = l;
|
||||
vertices[1] = b;
|
||||
vertices[2] = r;
|
||||
vertices[3] = b;
|
||||
vertices[4] = l;
|
||||
vertices[5] = t;
|
||||
vertices[6] = r;
|
||||
vertices[7] = t;
|
||||
}
|
||||
|
||||
var quadUV = new Array(8);
|
||||
if (!spriteFrame._rotated) {
|
||||
quadUV[0] = quadUV[4] = ul;
|
||||
@@ -532,14 +510,12 @@ var fillQuadGeneratorBar = {
|
||||
// tr : 6, 7
|
||||
var progressStart, progressEnd;
|
||||
switch (fillType) {
|
||||
case cc.Scale9Sprite.FillType.HORIZONTAL:
|
||||
progressStart = vertices[0] + (vertices[2] - vertices[0]) * fillStart;
|
||||
progressEnd = vertices[0] + (vertices[2] - vertices[0]) * fillEnd;
|
||||
case FillType.HORIZONTAL:
|
||||
progressStart = l + (r - l) * fillStart;
|
||||
progressEnd = l + (r - l) * fillEnd;
|
||||
|
||||
vertices[0] = progressStart;
|
||||
vertices[2] = progressEnd;
|
||||
vertices[4] = progressStart;
|
||||
vertices[6] = progressEnd;
|
||||
l = progressStart;
|
||||
r = progressEnd;
|
||||
|
||||
uvs[0] = quadUV[0] + (quadUV[2] - quadUV[0]) * fillStart;
|
||||
uvs[1] = quadUV[1];
|
||||
@@ -550,14 +526,12 @@ var fillQuadGeneratorBar = {
|
||||
uvs[6] = quadUV[4] + (quadUV[6] - quadUV[4]) * fillEnd;
|
||||
uvs[7] = quadUV[7];
|
||||
break;
|
||||
case cc.Scale9Sprite.FillType.VERTICAL:
|
||||
progressStart = vertices[1] + (vertices[5] - vertices[1]) * fillStart;
|
||||
progressEnd = vertices[1] + (vertices[5] - vertices[1]) * fillEnd;
|
||||
case FillType.VERTICAL:
|
||||
progressStart = b + (t - b) * fillStart;
|
||||
progressEnd = b + (t - b) * fillEnd;
|
||||
|
||||
vertices[1] = progressStart;
|
||||
vertices[3] = progressStart;
|
||||
vertices[5] = progressEnd;
|
||||
vertices[7] = progressEnd;
|
||||
b = progressStart;
|
||||
t = progressEnd;
|
||||
|
||||
uvs[0] = quadUV[0];
|
||||
uvs[1] = quadUV[1] + (quadUV[5] - quadUV[1]) * fillStart;
|
||||
@@ -572,6 +546,28 @@ var fillQuadGeneratorBar = {
|
||||
cc.error('Unrecognized fill type in bar fill');
|
||||
break;
|
||||
}
|
||||
|
||||
//build vertices
|
||||
if (webgl) {
|
||||
vertices[0] = l * wt.a + b * wt.c + wt.tx;
|
||||
vertices[1] = l * wt.b + b * wt.d + wt.ty;
|
||||
vertices[2] = r * wt.a + b * wt.c + wt.tx;
|
||||
vertices[3] = r * wt.b + b * wt.d + wt.ty;
|
||||
vertices[4] = l * wt.a + t * wt.c + wt.tx;
|
||||
vertices[5] = l * wt.b + t * wt.d + wt.ty;
|
||||
vertices[6] = r * wt.a + t * wt.c + wt.tx;
|
||||
vertices[7] = r * wt.b + t * wt.d + wt.ty;
|
||||
} else{
|
||||
vertices[0] = l;
|
||||
vertices[1] = b;
|
||||
vertices[2] = r;
|
||||
vertices[3] = b;
|
||||
vertices[4] = l;
|
||||
vertices[5] = t;
|
||||
vertices[6] = r;
|
||||
vertices[7] = t;
|
||||
}
|
||||
|
||||
sprite._vertCount = 4;
|
||||
|
||||
cornerId[0] = 0;
|
||||
@@ -603,8 +599,7 @@ var fillQuadGeneratorRadial = {
|
||||
while (fillStart < 0.0) fillStart += 1.0;
|
||||
var cx = fillCenter.x * contentSize.width,
|
||||
cy = fillCenter.y * contentSize.height;
|
||||
var center = cc.v2( webgl ? cx * wt.a + cy * wt.c + wt.tx : cx,
|
||||
webgl ? cx * wt.b + cy * wt.d + wt.ty : cy);
|
||||
var center = cc.v2( cx, cy);
|
||||
|
||||
fillStart *= Math.PI * 2;
|
||||
fillRange *= Math.PI * 2;
|
||||
@@ -681,12 +676,12 @@ var fillQuadGeneratorRadial = {
|
||||
if (vertices.length < dataLength) {
|
||||
dataPool.put(vertices);
|
||||
vertices = dataPool.get(dataLength) || new Float32Array(dataLength);
|
||||
sprite._vertices = vertices;
|
||||
this.outVerts = sprite._vertices = vertices;
|
||||
}
|
||||
if (uvs.length < dataLength) {
|
||||
dataPool.put(uvs);
|
||||
uvs = dataPool.get(dataLength) || new Float32Array(dataLength);
|
||||
sprite._uvs = uvs;
|
||||
this.outUvs = sprite._uvs = uvs;
|
||||
}
|
||||
|
||||
var offset = 0, count = 0;
|
||||
@@ -697,7 +692,7 @@ var fillQuadGeneratorRadial = {
|
||||
}
|
||||
//all in
|
||||
if(fillRange >= Math.PI * 2) {
|
||||
this._generateTriangle(offset, center, this._vertPos[triangle[0]], this._vertPos[triangle[1]]);
|
||||
this._generateTriangle(wt, offset, center, this._vertPos[triangle[0]], this._vertPos[triangle[1]]);
|
||||
offset += 6;
|
||||
count += 3;
|
||||
continue;
|
||||
@@ -715,10 +710,10 @@ var fillQuadGeneratorRadial = {
|
||||
} else if (startAngle >= fillStart) {
|
||||
if(endAngle >= fillEnd) {
|
||||
//startAngle to fillEnd
|
||||
this._generateTriangle(offset, center, this._vertPos[triangle[0]], this._intersectPoint_2[triangleIndex]);
|
||||
this._generateTriangle(wt, offset, center, this._vertPos[triangle[0]], this._intersectPoint_2[triangleIndex]);
|
||||
} else {
|
||||
//startAngle to endAngle
|
||||
this._generateTriangle(offset, center, this._vertPos[triangle[0]], this._vertPos[triangle[1]]);
|
||||
this._generateTriangle(wt, offset, center, this._vertPos[triangle[0]], this._vertPos[triangle[1]]);
|
||||
}
|
||||
offset += 6;
|
||||
count += 3;
|
||||
@@ -728,12 +723,12 @@ var fillQuadGeneratorRadial = {
|
||||
//all out
|
||||
} else if(endAngle <= fillEnd) {
|
||||
//fillStart to endAngle
|
||||
this._generateTriangle(offset, center, this._intersectPoint_1[triangleIndex], this._vertPos[triangle[1]]);
|
||||
this._generateTriangle(wt, offset, center, this._intersectPoint_1[triangleIndex], this._vertPos[triangle[1]]);
|
||||
offset += 6;
|
||||
count += 3;
|
||||
} else {
|
||||
//fillStart to fillEnd
|
||||
this._generateTriangle(offset, center, this._intersectPoint_1[triangleIndex], this._intersectPoint_2[triangleIndex]);
|
||||
this._generateTriangle(wt, offset, center, this._intersectPoint_1[triangleIndex], this._intersectPoint_2[triangleIndex]);
|
||||
offset += 6;
|
||||
count += 3;
|
||||
}
|
||||
@@ -751,7 +746,7 @@ var fillQuadGeneratorRadial = {
|
||||
cornerId[3] = 6;
|
||||
},
|
||||
|
||||
_generateTriangle: function(offset, vert0, vert1, vert2) {
|
||||
_generateTriangle: function(wt, offset, vert0, vert1, vert2) {
|
||||
var rawVerts = this.rawVerts;
|
||||
var rawUvs = this.rawUvs;
|
||||
var vertices = this.outVerts;
|
||||
@@ -763,12 +758,22 @@ var fillQuadGeneratorRadial = {
|
||||
// tl: 0, 1
|
||||
// bl: 2, 3
|
||||
// tr: 4, 5
|
||||
vertices[offset] = vert0.x;
|
||||
vertices[offset+1] = vert0.y;
|
||||
vertices[offset+2] = vert1.x;
|
||||
vertices[offset+3] = vert1.y;
|
||||
vertices[offset+4] = vert2.x;
|
||||
vertices[offset+5] = vert2.y;
|
||||
if(webgl) {
|
||||
vertices[offset] = vert0.x * wt.a + vert0.y * wt.c + wt.tx;
|
||||
vertices[offset+1] = vert0.x * wt.b + vert0.y * wt.d + wt.ty;
|
||||
vertices[offset+2] = vert1.x * wt.a + vert1.y * wt.c + wt.tx;
|
||||
vertices[offset+3] = vert1.x * wt.b + vert1.y * wt.d + wt.ty;
|
||||
vertices[offset+4] = vert2.x * wt.a + vert2.y * wt.c + wt.tx;
|
||||
vertices[offset+5] = vert2.x * wt.b + vert2.y * wt.d + wt.ty;
|
||||
|
||||
} else {
|
||||
vertices[offset] = vert0.x;
|
||||
vertices[offset+1] = vert0.y;
|
||||
vertices[offset+2] = vert1.x;
|
||||
vertices[offset+3] = vert1.y;
|
||||
vertices[offset+4] = vert2.x;
|
||||
vertices[offset+5] = vert2.y;
|
||||
}
|
||||
|
||||
progressX = (vert0.x - v0x) / (v1x - v0x);
|
||||
progressY = (vert0.y - v0y) / (v1y - v0y);
|
||||
@@ -879,23 +884,15 @@ var fillQuadGeneratorRadial = {
|
||||
x3 = contentSize.width;
|
||||
y3 = contentSize.height;
|
||||
|
||||
if (webgl) {
|
||||
this._vertices[0].x = x0 * wt.a + y0 * wt.c + wt.tx;
|
||||
this._vertices[0].y = x0 * wt.b + y0 * wt.d + wt.ty;
|
||||
this._vertices[1].x = x3 * wt.a + y3 * wt.c + wt.tx;
|
||||
this._vertices[1].y = x3 * wt.b + y3 * wt.d + wt.ty;
|
||||
}
|
||||
else {
|
||||
this._vertices[0].x = x0;
|
||||
this._vertices[0].y = y0;
|
||||
this._vertices[1].x = x3;
|
||||
this._vertices[1].y = y3;
|
||||
}
|
||||
this._vertices[0].x = x0;
|
||||
this._vertices[0].y = y0;
|
||||
this._vertices[1].x = x3;
|
||||
this._vertices[1].y = y3;
|
||||
},
|
||||
|
||||
_calculateUVs : function (spriteFrame) {
|
||||
var atlasWidth = spriteFrame._texture.getPixelWidth();
|
||||
var atlasHeight = spriteFrame._texture.getPixelHeight();
|
||||
var atlasWidth = spriteFrame._texture._pixelWidth;
|
||||
var atlasHeight = spriteFrame._texture._pixelHeight;
|
||||
var textureRect = spriteFrame._rect;
|
||||
|
||||
//uv computation should take spritesheet into account.
|
||||
@@ -946,6 +943,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({
|
||||
_uvs: null,
|
||||
_vertCount: 0,
|
||||
_quadsDirty: true,
|
||||
_uvsDirty: true,
|
||||
_isTriangle: false,
|
||||
_isTrimmedContentSize: true,
|
||||
//fill type
|
||||
@@ -1045,6 +1043,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({
|
||||
if (spriteFrame) {
|
||||
this._spriteFrame = spriteFrame;
|
||||
this._quadsDirty = true;
|
||||
this._uvsDirty = true;
|
||||
this._renderCmd._needDraw = false;
|
||||
var self = this;
|
||||
var onResourceDataLoaded = function () {
|
||||
@@ -1076,6 +1075,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({
|
||||
this._blendFunc.src = blendFunc || cc.macro.BLEND_SRC;
|
||||
this._blendFunc.dst = dst || cc.macro.BLEND_DST;
|
||||
}
|
||||
this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -1106,6 +1106,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({
|
||||
if (this._isTrimmedContentSize !== isTrimmed) {
|
||||
this._isTrimmedContentSize = isTrimmed;
|
||||
this._quadsDirty = true;
|
||||
this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1120,6 +1121,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({
|
||||
setState: function (state) {
|
||||
this._brightState = state;
|
||||
this._renderCmd.setState(state);
|
||||
this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -1138,6 +1140,8 @@ cc.Scale9Sprite = _ccsg.Node.extend({
|
||||
if (this._renderingType === type) return;
|
||||
this._renderingType = type;
|
||||
this._quadsDirty = true;
|
||||
this._uvsDirty = true;
|
||||
this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
|
||||
},
|
||||
/**
|
||||
* get the rendering type, could be simple or slice
|
||||
@@ -1153,6 +1157,8 @@ cc.Scale9Sprite = _ccsg.Node.extend({
|
||||
setInsetLeft: function (insetLeft) {
|
||||
this._insetLeft = insetLeft;
|
||||
this._quadsDirty = true;
|
||||
this._uvsDirty = true;
|
||||
this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
|
||||
},
|
||||
/**
|
||||
* get the left border of 9 slice sprite, the result is specified before trimmed.
|
||||
@@ -1168,6 +1174,8 @@ cc.Scale9Sprite = _ccsg.Node.extend({
|
||||
setInsetTop: function (insetTop) {
|
||||
this._insetTop = insetTop;
|
||||
this._quadsDirty = true;
|
||||
this._uvsDirty = true;
|
||||
this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -1185,6 +1193,8 @@ cc.Scale9Sprite = _ccsg.Node.extend({
|
||||
setInsetRight: function (insetRight) {
|
||||
this._insetRight = insetRight;
|
||||
this._quadsDirty = true;
|
||||
this._uvsDirty = true;
|
||||
this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -1202,6 +1212,8 @@ cc.Scale9Sprite = _ccsg.Node.extend({
|
||||
setInsetBottom: function (insetBottom) {
|
||||
this._insetBottom = insetBottom;
|
||||
this._quadsDirty = true;
|
||||
this._uvsDirty = true;
|
||||
this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
|
||||
},
|
||||
/**
|
||||
* get the bottom border of 9 slice sprite, the result is specified before trimmed.
|
||||
@@ -1215,8 +1227,9 @@ cc.Scale9Sprite = _ccsg.Node.extend({
|
||||
if(this._fillType === value)
|
||||
return;
|
||||
this._fillType = value;
|
||||
if(this._renderingType === cc.Scale9Sprite.RenderingType.FILLED) {
|
||||
if(this._renderingType === RenderingType.FILLED) {
|
||||
this._quadsDirty = true;
|
||||
this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1226,8 +1239,9 @@ cc.Scale9Sprite = _ccsg.Node.extend({
|
||||
|
||||
setFillCenter: function(value, y) {
|
||||
this._fillCenter = cc.v2(value,y);
|
||||
if(this._renderingType === cc.Scale9Sprite.RenderingType.FILLED && this._fillType === cc.Scale9Sprite.FillType.RADIAL) {
|
||||
if(this._renderingType === RenderingType.FILLED && this._fillType === FillType.RADIAL) {
|
||||
this._quadsDirty = true;
|
||||
this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1259,8 +1273,9 @@ cc.Scale9Sprite = _ccsg.Node.extend({
|
||||
if(this._fillStart === value)
|
||||
return;
|
||||
this._fillStart = value;
|
||||
if(this._renderingType === cc.Scale9Sprite.RenderingType.FILLED) {
|
||||
if(this._renderingType === RenderingType.FILLED) {
|
||||
this._quadsDirty = true;
|
||||
this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1272,8 +1287,9 @@ cc.Scale9Sprite = _ccsg.Node.extend({
|
||||
if(this._fillRange === value)
|
||||
return;
|
||||
this._fillRange = value;
|
||||
if(this._renderingType === cc.Scale9Sprite.RenderingType.FILLED ) {
|
||||
if(this._renderingType === RenderingType.FILLED ) {
|
||||
this._quadsDirty = true;
|
||||
this._renderCmd.setDirtyFlag(_ccsg.Node._dirtyFlags.contentDirty);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1287,24 +1303,24 @@ cc.Scale9Sprite = _ccsg.Node.extend({
|
||||
return;
|
||||
}
|
||||
this._isTriangle = false;
|
||||
var vert;
|
||||
if (this._renderingType === cc.Scale9Sprite.RenderingType.SIMPLE) {
|
||||
simpleQuadGenerator._rebuildQuads_base(this, this._spriteFrame, this.getContentSize(), this._isTrimmedContentSize);
|
||||
vert = this._vertices;
|
||||
} else if (this._renderingType === cc.Scale9Sprite.RenderingType.SLICED) {
|
||||
scale9QuadGenerator._rebuildQuads_base(this, this._spriteFrame, this.getContentSize(), this._insetLeft, this._insetRight, this._insetTop, this._insetBottom);
|
||||
vert = this._vertices;
|
||||
} else if (this._renderingType === cc.Scale9Sprite.RenderingType.TILED) {
|
||||
tiledQuadGenerator._rebuildQuads_base(this, this._spriteFrame, this.getContentSize());
|
||||
vert = this._vertices;
|
||||
} else if (this._renderingType === cc.Scale9Sprite.RenderingType.FILLED) {
|
||||
switch (this._renderingType) {
|
||||
case RenderingType.SIMPLE:
|
||||
simpleQuadGenerator._rebuildQuads_base(this, this._spriteFrame, this._contentSize, this._isTrimmedContentSize);
|
||||
break;
|
||||
case RenderingType.SLICED:
|
||||
scale9QuadGenerator._rebuildQuads_base(this, this._spriteFrame, this._contentSize, this._insetLeft, this._insetRight, this._insetTop, this._insetBottom);
|
||||
break;
|
||||
case RenderingType.TILED:
|
||||
tiledQuadGenerator._rebuildQuads_base(this, this._spriteFrame, this._contentSize);
|
||||
break;
|
||||
case RenderingType.FILLED:
|
||||
var fillstart = this._fillStart;
|
||||
var fillRange = this._fillRange;
|
||||
if(fillRange < 0) {
|
||||
fillstart += fillRange;
|
||||
fillRange = -fillRange;
|
||||
}
|
||||
if (this._fillType !== cc.Scale9Sprite.FillType.RADIAL) {
|
||||
if (this._fillType !== FillType.RADIAL) {
|
||||
fillRange = fillstart + fillRange;
|
||||
fillstart = fillstart > 1.0 ? 1.0 : fillstart;
|
||||
fillstart = fillstart < 0.0 ? 0.0 : fillstart;
|
||||
@@ -1312,20 +1328,19 @@ cc.Scale9Sprite = _ccsg.Node.extend({
|
||||
fillRange = fillRange > 1.0 ? 1.0 : fillRange;
|
||||
fillRange = fillRange < 0.0 ? 0.0 : fillRange;
|
||||
fillRange = fillRange - fillstart;
|
||||
fillQuadGeneratorBar._rebuildQuads_base(this, this._spriteFrame, this.getContentSize(), this._fillType, fillstart, fillRange);
|
||||
vert = this._vertices;
|
||||
fillQuadGeneratorBar._rebuildQuads_base(this, this._spriteFrame, this._contentSize, this._fillType, fillstart, fillRange);
|
||||
} else {
|
||||
this._isTriangle = true;
|
||||
if (!this._rawVerts) {
|
||||
this._rawVerts = dataPool.get(8) || new Float32Array(8);
|
||||
this._rawUvs = dataPool.get(8) || new Float32Array(8);
|
||||
}
|
||||
fillQuadGeneratorRadial._rebuildQuads_base(this, this._spriteFrame, this.getContentSize(), this._fillCenter,fillstart, fillRange);
|
||||
vert = this._rawVerts;
|
||||
fillQuadGeneratorRadial._rebuildQuads_base(this, this._spriteFrame, this._contentSize, this._fillCenter,fillstart, fillRange);
|
||||
}
|
||||
} else {
|
||||
this._quads = [];
|
||||
break;
|
||||
default:
|
||||
this._quadsDirty = false;
|
||||
this._uvsDirty = false;
|
||||
this._renderCmd._needDraw = false;
|
||||
cc.error('Can not generate quad');
|
||||
return;
|
||||
@@ -1333,12 +1348,13 @@ cc.Scale9Sprite = _ccsg.Node.extend({
|
||||
|
||||
// Culling
|
||||
if (webgl) {
|
||||
var x0 = cornerId[0], x1 = cornerId[1], x2 = cornerId[2], x3 = cornerId[3],
|
||||
y0 = cornerId[0]+1, y1 = cornerId[1]+1, y2 = cornerId[2]+1, y3 = cornerId[3]+1;
|
||||
if (((vert[x0]-vl.x) & (vert[x1]-vl.x) & (vert[x2]-vl.x) & (vert[x3]-vl.x)) >> 31 || // All outside left
|
||||
((vr.x-vert[x0]) & (vr.x-vert[x1]) & (vr.x-vert[x2]) & (vr.x-vert[x3])) >> 31 || // All outside right
|
||||
((vert[y0]-vb.y) & (vert[y1]-vb.y) & (vert[y2]-vb.y) & (vert[y3]-vb.y)) >> 31 || // All outside bottom
|
||||
((vt.y-vert[y0]) & (vt.y-vert[y1]) & (vt.y-vert[y2]) & (vt.y-vert[y3])) >> 31) // All outside top
|
||||
var vert = this._isTriangle ? this._rawVerts : this._vertices,
|
||||
x0 = vert[cornerId[0]], x1 = vert[cornerId[1]], x2 = vert[cornerId[2]], x3 = vert[cornerId[3]],
|
||||
y0 = vert[cornerId[0]+1], y1 = vert[cornerId[1]+1], y2 = vert[cornerId[2]+1], y3 = vert[cornerId[3]+1];
|
||||
if (((x0-vl.x) & (x1-vl.x) & (x2-vl.x) & (x3-vl.x)) >> 31 || // All outside left
|
||||
((vr.x-x0) & (vr.x-x1) & (vr.x-x2) & (vr.x-x3)) >> 31 || // All outside right
|
||||
((y0-vb.y) & (y1-vb.y) & (y2-vb.y) & (y3-vb.y)) >> 31 || // All outside bottom
|
||||
((vt.y-y0) & (vt.y-y1) & (vt.y-y2) & (vt.y-y3)) >> 31) // All outside top
|
||||
{
|
||||
this._renderCmd._needDraw = false;
|
||||
}
|
||||
@@ -1358,6 +1374,7 @@ cc.Scale9Sprite = _ccsg.Node.extend({
|
||||
}
|
||||
|
||||
this._quadsDirty = false;
|
||||
this._uvsDirty = false;
|
||||
},
|
||||
_createRenderCmd: function () {
|
||||
if (cc._renderType === cc.game.RENDER_TYPE_CANVAS)
|
||||
@@ -1382,7 +1399,7 @@ cc.Scale9Sprite.state = {NORMAL: 0, GRAY: 1, DISTORTION: 2};
|
||||
* Enum for sprite type
|
||||
* @enum SpriteType
|
||||
*/
|
||||
cc.Scale9Sprite.RenderingType = cc.Enum({
|
||||
var RenderingType = cc.Scale9Sprite.RenderingType = cc.Enum({
|
||||
/**
|
||||
* @property {Number} SIMPLE
|
||||
*/
|
||||
@@ -1401,7 +1418,7 @@ cc.Scale9Sprite.RenderingType = cc.Enum({
|
||||
FILLED: 3
|
||||
});
|
||||
|
||||
cc.Scale9Sprite.FillType = cc.Enum({
|
||||
var FillType = cc.Scale9Sprite.FillType = cc.Enum({
|
||||
HORIZONTAL: 0,
|
||||
VERTICAL: 1,
|
||||
RADIAL:2,
|
||||
|
||||
@@ -83,8 +83,8 @@ proto.rendering = function (ctx, scaleX, scaleY) {
|
||||
}
|
||||
var sx,sy,sw,sh;
|
||||
var x, y, w,h;
|
||||
var textureWidth = this._textureToRender.getPixelWidth();
|
||||
var textureHeight = this._textureToRender.getPixelHeight();
|
||||
var textureWidth = this._textureToRender._pixelWidth;
|
||||
var textureHeight = this._textureToRender._pixelHeight;
|
||||
var image = this._textureToRender._htmlElementObj;
|
||||
var vertices = node._vertices;
|
||||
var uvs = node._uvs;
|
||||
|
||||
@@ -39,8 +39,9 @@ cc.Scale9Sprite.WebGLRenderCmd = function (renderable) {
|
||||
this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_SPRITE_POSITION_TEXTURECOLOR);
|
||||
};
|
||||
|
||||
var proto = cc.Scale9Sprite.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype);
|
||||
proto.constructor = cc.Scale9Sprite.WebGLRenderCmd;
|
||||
var Scale9Sprite = cc.Scale9Sprite;
|
||||
var proto = Scale9Sprite.WebGLRenderCmd.prototype = Object.create(_ccsg.Node.WebGLRenderCmd.prototype);
|
||||
proto.constructor = Scale9Sprite.WebGLRenderCmd;
|
||||
|
||||
proto._uploadSliced = function (vertices, uvs, color, z, f32buffer, ui32buffer, offset) {
|
||||
var off;
|
||||
@@ -84,21 +85,6 @@ proto._uploadSliced = function (vertices, uvs, color, z, f32buffer, ui32buffer,
|
||||
return 36;
|
||||
};
|
||||
|
||||
proto._uploadVertices = function (vertices, uvs, color, z, f32buffer, ui32buffer, offset) {
|
||||
// src: bl, br, tl, tr
|
||||
var count = this._node._vertCount;
|
||||
for (var i = 0, srcOff = 0; i < count; i++, srcOff += 2) {
|
||||
f32buffer[offset] = vertices[srcOff];
|
||||
f32buffer[offset + 1] = vertices[srcOff+1];
|
||||
f32buffer[offset + 2] = z;
|
||||
ui32buffer[offset + 3] = color[0];
|
||||
f32buffer[offset + 4] = uvs[srcOff];
|
||||
f32buffer[offset + 5] = uvs[srcOff+1];
|
||||
offset += 6;
|
||||
}
|
||||
return count;
|
||||
};
|
||||
|
||||
proto.transform = function (parentCmd, recursive) {
|
||||
this.originTransform(parentCmd, recursive);
|
||||
this._node._rebuildQuads();
|
||||
@@ -106,7 +92,7 @@ proto.transform = function (parentCmd, recursive) {
|
||||
|
||||
proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){
|
||||
var node = this._node;
|
||||
if (!node._spriteFrame || !node._spriteFrame.textureLoaded() || this._displayedOpacity === 0) {
|
||||
if (this._displayedOpacity === 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -115,16 +101,16 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){
|
||||
node._rebuildQuads();
|
||||
}
|
||||
|
||||
// this._shaderProgram.use();
|
||||
if (this._shaderProgram === cc.Scale9Sprite.WebGLRenderCmd._distortionProgram && this._node._distortionOffset) {
|
||||
if (node._distortionOffset && this._shaderProgram === Scale9Sprite.WebGLRenderCmd._distortionProgram) {
|
||||
this._shaderProgram.setUniformLocationWith2f(
|
||||
cc.Scale9Sprite.WebGLRenderCmd._distortionOffset,
|
||||
this._node._distortionOffset.x, this._node._distortionOffset.y
|
||||
Scale9Sprite.WebGLRenderCmd._distortionOffset,
|
||||
node._distortionOffset.x, node._distortionOffset.y
|
||||
);
|
||||
this._shaderProgram.setUniformLocationWith2f(
|
||||
cc.Scale9Sprite.WebGLRenderCmd._distortionTiling,
|
||||
this._node._distortionTiling.x, this._node._distortionTiling.y
|
||||
Scale9Sprite.WebGLRenderCmd._distortionTiling,
|
||||
node._distortionTiling.x, node._distortionTiling.y
|
||||
);
|
||||
cc.renderer._breakBatch();
|
||||
}
|
||||
|
||||
// Color & z
|
||||
@@ -144,20 +130,30 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){
|
||||
// Upload data
|
||||
var vertices = node._vertices;
|
||||
var uvs = node._uvs;
|
||||
var types = cc.Scale9Sprite.RenderingType;
|
||||
var types = Scale9Sprite.RenderingType;
|
||||
var offset = vertexDataOffset;
|
||||
var len = 0;
|
||||
switch (node._renderingType) {
|
||||
case types.SIMPLE:
|
||||
case types.TILED:
|
||||
case types.FILLED:
|
||||
len = this._uploadVertices(vertices, uvs, this._color, z, f32buffer, ui32buffer, offset);
|
||||
// Inline for performance
|
||||
len = this._node._vertCount;
|
||||
for (var i = 0, srcOff = 0; i < len; i++, srcOff += 2) {
|
||||
f32buffer[offset] = vertices[srcOff];
|
||||
f32buffer[offset + 1] = vertices[srcOff+1];
|
||||
f32buffer[offset + 2] = z;
|
||||
ui32buffer[offset + 3] = this._color[0];
|
||||
f32buffer[offset + 4] = uvs[srcOff];
|
||||
f32buffer[offset + 5] = uvs[srcOff+1];
|
||||
offset += 6;
|
||||
}
|
||||
break;
|
||||
case types.SLICED:
|
||||
len = this._uploadSliced(vertices, uvs, this._color, z, f32buffer, ui32buffer, offset);
|
||||
break;
|
||||
}
|
||||
if (node._renderingType === types.FILLED && node._fillType === cc.Scale9Sprite.FillType.RADIAL) {
|
||||
if (node._renderingType === types.FILLED && node._fillType === Scale9Sprite.FillType.RADIAL) {
|
||||
this.vertexType = cc.renderer.VertexType.TRIANGLE;
|
||||
}
|
||||
else {
|
||||
@@ -167,18 +163,18 @@ proto.uploadData = function (f32buffer, ui32buffer, vertexDataOffset){
|
||||
};
|
||||
|
||||
proto.setState = function (state) {
|
||||
if (state === cc.Scale9Sprite.state.NORMAL) {
|
||||
if (state === Scale9Sprite.state.NORMAL) {
|
||||
this._shaderProgram = cc.shaderCache.programForKey(cc.macro.SHADER_SPRITE_POSITION_TEXTURECOLOR);
|
||||
} else if (state === cc.Scale9Sprite.state.GRAY) {
|
||||
} else if (state === Scale9Sprite.state.GRAY) {
|
||||
this._shaderProgram = cc.Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram();
|
||||
} else if (state === cc.Scale9Sprite.state.DISTORTION) {
|
||||
} else if (state === Scale9Sprite.state.DISTORTION) {
|
||||
this._shaderProgram = cc.Scale9Sprite.WebGLRenderCmd._getDistortionProgram();
|
||||
}
|
||||
};
|
||||
|
||||
cc.Scale9Sprite.WebGLRenderCmd._grayShaderProgram = null;
|
||||
cc.Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram = function(){
|
||||
var grayShader = cc.Scale9Sprite.WebGLRenderCmd._grayShaderProgram;
|
||||
Scale9Sprite.WebGLRenderCmd._grayShaderProgram = null;
|
||||
Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram = function(){
|
||||
var grayShader = Scale9Sprite.WebGLRenderCmd._grayShaderProgram;
|
||||
if (grayShader)
|
||||
return grayShader;
|
||||
|
||||
@@ -190,11 +186,11 @@ cc.Scale9Sprite.WebGLRenderCmd._getGrayShaderProgram = function(){
|
||||
grayShader.link();
|
||||
grayShader.updateUniforms();
|
||||
|
||||
cc.Scale9Sprite.WebGLRenderCmd._grayShaderProgram = grayShader;
|
||||
Scale9Sprite.WebGLRenderCmd._grayShaderProgram = grayShader;
|
||||
return grayShader;
|
||||
};
|
||||
|
||||
cc.Scale9Sprite.WebGLRenderCmd._grayShaderFragment =
|
||||
Scale9Sprite.WebGLRenderCmd._grayShaderFragment =
|
||||
"precision lowp float;\n"
|
||||
+ "varying vec4 v_fragmentColor; \n"
|
||||
+ "varying vec2 v_texCoord; \n"
|
||||
@@ -205,9 +201,9 @@ cc.Scale9Sprite.WebGLRenderCmd._grayShaderFragment =
|
||||
+" gl_FragColor.w = c.w ; \n"
|
||||
+ "}";
|
||||
|
||||
cc.Scale9Sprite.WebGLRenderCmd._distortionProgram = null;
|
||||
cc.Scale9Sprite.WebGLRenderCmd._getDistortionProgram = function(){
|
||||
var shader = cc.Scale9Sprite.WebGLRenderCmd._distortionProgram;
|
||||
Scale9Sprite.WebGLRenderCmd._distortionProgram = null;
|
||||
Scale9Sprite.WebGLRenderCmd._getDistortionProgram = function(){
|
||||
var shader = Scale9Sprite.WebGLRenderCmd._distortionProgram;
|
||||
if(shader)
|
||||
return shader;
|
||||
|
||||
@@ -219,9 +215,9 @@ cc.Scale9Sprite.WebGLRenderCmd._getDistortionProgram = function(){
|
||||
shader.link();
|
||||
shader.updateUniforms();
|
||||
|
||||
cc.Scale9Sprite.WebGLRenderCmd._distortionProgram = shader;
|
||||
cc.Scale9Sprite.WebGLRenderCmd._distortionOffset = shader.getUniformLocationForName('u_offset');
|
||||
cc.Scale9Sprite.WebGLRenderCmd._distortionTiling = shader.getUniformLocationForName('u_offset_tiling');
|
||||
Scale9Sprite.WebGLRenderCmd._distortionProgram = shader;
|
||||
Scale9Sprite.WebGLRenderCmd._distortionOffset = shader.getUniformLocationForName('u_offset');
|
||||
Scale9Sprite.WebGLRenderCmd._distortionTiling = shader.getUniformLocationForName('u_offset_tiling');
|
||||
return shader;
|
||||
};
|
||||
|
||||
|
||||
@@ -292,20 +292,23 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{
|
||||
this._texture = texture;
|
||||
function textureLoadedCallback () {
|
||||
self._textureLoaded = true;
|
||||
var w = texture.width, h = texture.height;
|
||||
|
||||
if (self._rotated && cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
|
||||
var tempElement = texture.getHtmlElementObj();
|
||||
tempElement = _ccsg.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, self.getRect());
|
||||
var tempTexture = new cc.Texture2D();
|
||||
tempTexture.initWithElement(tempElement);
|
||||
tempTexture.handleLoadedTexture();
|
||||
// _refreshTexture will be recalled in setTexture
|
||||
self.setTexture(tempTexture);
|
||||
return;
|
||||
self._texture = tempTexture;
|
||||
self._rotated = false;
|
||||
w = self._texture.width;
|
||||
h = self._texture.height;
|
||||
self.setRect(cc.rect(0, 0, w, h));
|
||||
}
|
||||
var w = texture.width, h = texture.height;
|
||||
|
||||
if (self._rect) {
|
||||
self._checkRect(texture);
|
||||
self._checkRect(self._texture);
|
||||
}
|
||||
else {
|
||||
self.setRect(cc.rect(0, 0, w, h));
|
||||
|
||||
@@ -85,6 +85,8 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{
|
||||
this._textureLoaded = false;
|
||||
this._htmlElementObj = null;
|
||||
this._contentSize = cc.size(0, 0);
|
||||
this._pixelWidth = 0;
|
||||
this._pixelHeight = 0;
|
||||
|
||||
if (cc._renderType === game.RENDER_TYPE_CANVAS) {
|
||||
this._pattern = "";
|
||||
@@ -94,10 +96,7 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{
|
||||
this._isGray = false;
|
||||
}
|
||||
else if (cc._renderType === game.RENDER_TYPE_WEBGL) {
|
||||
this._hasPremultipliedAlpha = false;
|
||||
this._pixelFormat = Texture2D.defaultPixelFormat;
|
||||
this._pixelsWide = 0;
|
||||
this._pixelsHigh = 0;
|
||||
this._hasPremultipliedAlpha = false;
|
||||
this._hasMipmaps = false;
|
||||
|
||||
@@ -111,7 +110,7 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{
|
||||
* @return {Number}
|
||||
*/
|
||||
getPixelWidth: function () {
|
||||
return this._contentSize.width;
|
||||
return this._pixelWidth;
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -120,7 +119,7 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{
|
||||
* @return {Number}
|
||||
*/
|
||||
getPixelHeight: function () {
|
||||
return this._contentSize.height;
|
||||
return this._pixelHeight;
|
||||
},
|
||||
|
||||
/**
|
||||
@@ -162,8 +161,8 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{
|
||||
if (!element)
|
||||
return;
|
||||
this._htmlElementObj = element;
|
||||
this._contentSize.width = element.width;
|
||||
this._contentSize.height = element.height;
|
||||
this._pixelWidth = this._contentSize.width = element.width;
|
||||
this._pixelHeight = this._contentSize.height = element.height;
|
||||
this._textureLoaded = true;
|
||||
},
|
||||
|
||||
@@ -229,10 +228,20 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{
|
||||
return;
|
||||
|
||||
var locElement = self._htmlElementObj;
|
||||
self._contentSize.width = locElement.width;
|
||||
self._contentSize.height = locElement.height;
|
||||
self._pixelWidth = self._contentSize.width = locElement.width;
|
||||
self._pixelHeight = self._contentSize.height = locElement.height;
|
||||
self._textureLoaded = true;
|
||||
|
||||
// anti-alias
|
||||
if(cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
|
||||
if (cc.view._antiAliasEnabled) {
|
||||
self.setAntiAliasTexParameters();
|
||||
}
|
||||
else {
|
||||
self.setAliasTexParameters();
|
||||
}
|
||||
}
|
||||
|
||||
//dispatch load event to listener.
|
||||
self.emit("load");
|
||||
},
|
||||
@@ -716,13 +725,6 @@ game.once(game.EVENT_RENDERER_INITED, function () {
|
||||
|
||||
} else if (cc._renderType === game.RENDER_TYPE_WEBGL) {
|
||||
JS.mixin(Texture2D.prototype, {
|
||||
getPixelWidth: function () {
|
||||
return this._pixelsWide;
|
||||
},
|
||||
|
||||
getPixelHeight: function () {
|
||||
return this._pixelsHigh;
|
||||
},
|
||||
|
||||
initWithData: function (data, pixelFormat, pixelsWide, pixelsHigh, contentSize) {
|
||||
var self = this, tex2d = Texture2D;
|
||||
@@ -784,8 +786,8 @@ game.once(game.EVENT_RENDERER_INITED, function () {
|
||||
|
||||
self._contentSize.width = contentSize.width;
|
||||
self._contentSize.height = contentSize.height;
|
||||
self._pixelsWide = pixelsWide;
|
||||
self._pixelsHigh = pixelsHigh;
|
||||
self._pixelWidth = pixelsWide;
|
||||
self._pixelHeight = pixelsHigh;
|
||||
self._pixelFormat = pixelFormat;
|
||||
|
||||
self._hasPremultipliedAlpha = false;
|
||||
@@ -863,14 +865,21 @@ game.once(game.EVENT_RENDERER_INITED, function () {
|
||||
var pixelsWide = self._htmlElementObj.width;
|
||||
var pixelsHigh = self._htmlElementObj.height;
|
||||
|
||||
self._pixelsWide = self._contentSize.width = pixelsWide;
|
||||
self._pixelsHigh = self._contentSize.height = pixelsHigh;
|
||||
self._pixelWidth = self._contentSize.width = pixelsWide;
|
||||
self._pixelHeight = self._contentSize.height = pixelsHigh;
|
||||
self._pixelFormat = Texture2D.PIXEL_FORMAT_RGBA8888;
|
||||
|
||||
self._hasPremultipliedAlpha = premultiplied;
|
||||
self._hasMipmaps = false;
|
||||
self._textureLoaded = true;
|
||||
|
||||
if (cc.view._antiAliasEnabled) {
|
||||
self.setAntiAliasTexParameters();
|
||||
}
|
||||
else {
|
||||
self.setAliasTexParameters();
|
||||
}
|
||||
|
||||
//dispatch load event to listener.
|
||||
self.emit("load");
|
||||
},
|
||||
@@ -882,7 +891,7 @@ game.once(game.EVENT_RENDERER_INITED, function () {
|
||||
if(magFilter !== undefined)
|
||||
texParams = {minFilter: texParams, magFilter: magFilter, wrapS: wrapS, wrapT: wrapT};
|
||||
|
||||
cc.assert((_t._pixelsWide === misc.NextPOT(_t._pixelsWide) && _t._pixelsHigh === misc.NextPOT(_t._pixelsHigh)) ||
|
||||
cc.assert((_t._pixelWidth === misc.NextPOT(_t._pixelWidth) && _t._pixelHeight === misc.NextPOT(_t._pixelHeight)) ||
|
||||
(texParams.wrapS === gl.CLAMP_TO_EDGE && texParams.wrapT === gl.CLAMP_TO_EDGE),
|
||||
"WebGLRenderingContext.CLAMP_TO_EDGE should be used in NPOT textures");
|
||||
|
||||
@@ -917,7 +926,7 @@ game.once(game.EVENT_RENDERER_INITED, function () {
|
||||
|
||||
generateMipmap: function () {
|
||||
var _t = this;
|
||||
cc.assert(_t._pixelsWide === misc.NextPOT(_t._pixelsWide) && _t._pixelsHigh === misc.NextPOT(_t._pixelsHigh), "Mimpap texture only works in POT textures");
|
||||
cc.assert(_t._pixelWidth === misc.NextPOT(_t._pixelWidth) && _t._pixelHeight === misc.NextPOT(_t._pixelHeight), "Mimpap texture only works in POT textures");
|
||||
|
||||
cc.gl.bindTexture2D(_t);
|
||||
cc._renderContext.generateMipmap(cc._renderContext.TEXTURE_2D);
|
||||
|
||||
@@ -85,7 +85,7 @@ var textureCache = /** @lends cc.textureCache# */{
|
||||
return this._textures[textureKeyName];
|
||||
},
|
||||
|
||||
/**
|
||||
/*
|
||||
* @method getKeyByTexture
|
||||
* @param {Image} texture
|
||||
* @return {String|Null}
|
||||
@@ -125,6 +125,21 @@ var textureCache = /** @lends cc.textureCache# */{
|
||||
return this._textureColorsCache[key];
|
||||
},
|
||||
|
||||
/**
|
||||
* #en get all textures
|
||||
* #zh 获取所有贴图
|
||||
* @method getAllTextures
|
||||
* @return {Texture2D[]}
|
||||
*/
|
||||
getAllTextures: function () {
|
||||
var texs = [];
|
||||
for (var key in this._textures) {
|
||||
var item = this._textures[key];
|
||||
texs.push(item);
|
||||
}
|
||||
return texs;
|
||||
},
|
||||
|
||||
/**
|
||||
* <p>Purges the dictionary of loaded textures. <br />
|
||||
* Call this method if you receive the "Memory Warning" <br />
|
||||
|
||||
@@ -688,8 +688,8 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
|
||||
},
|
||||
|
||||
/**
|
||||
* !#en Indicate whether node's opacity value affect its child nodes, default value is false.
|
||||
* !#zh 节点的不透明度值是否影响其子节点,默认值为 false。
|
||||
* !#en Indicate whether node's opacity value affect its child nodes, default value is true.
|
||||
* !#zh 节点的不透明度值是否影响其子节点,默认值为 true。
|
||||
* @property cascadeOpacity
|
||||
* @type {Boolean}
|
||||
* @example
|
||||
@@ -755,10 +755,10 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
|
||||
var sgNode = this._sgNode = new _ccsg.Node();
|
||||
if (CC_JSB) {
|
||||
sgNode.retain();
|
||||
var entity = this;
|
||||
sgNode._entity = this;
|
||||
sgNode.onEnter = function () {
|
||||
_ccsg.Node.prototype.onEnter.call(this);
|
||||
if (!entity._active) {
|
||||
if (this._entity && !this._entity._active) {
|
||||
cc.director.getActionManager().pauseTarget(this);
|
||||
cc.eventManager.pauseTarget(this);
|
||||
}
|
||||
@@ -797,6 +797,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
|
||||
_onPreDestroy: function () {
|
||||
if (CC_JSB) {
|
||||
this._sgNode.release();
|
||||
this._sgNode._entity = null;
|
||||
this._sgNode = null;
|
||||
}
|
||||
cc.eventManager.removeListeners(this);
|
||||
@@ -843,7 +844,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
/*
|
||||
* !#en
|
||||
* Defines the oder in which the nodes are renderer.
|
||||
* Nodes that have a Global Z Order lower, are renderer first.
|
||||
@@ -880,7 +881,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
|
||||
this._sgNode.setGlobalZOrder(globalZOrder);
|
||||
},
|
||||
|
||||
/**
|
||||
/*
|
||||
* !#en Return the Node's Global Z Order.
|
||||
* !#zh 获取节点的全局 Z 顺序。
|
||||
* @method getGlobalZOrder
|
||||
@@ -1609,7 +1610,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
|
||||
* treating the returned/received node point as anchor relative.
|
||||
* !#zh
|
||||
* 将一个点转换到世界空间坐标系。结果以 Vec2 为单位。<br/>
|
||||
* 返回值将基于节点坐标。
|
||||
* 返回值将基于世界坐标。
|
||||
* @method convertToWorldSpaceAR
|
||||
* @param {Vec2} nodePoint
|
||||
* @return {Vec2}
|
||||
@@ -1885,7 +1886,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
|
||||
sibling.setLocalZOrder(zOrder);
|
||||
}
|
||||
else {
|
||||
sibling.arrivalOrder = i;
|
||||
sibling._arrivalOrder = i;
|
||||
cc.eventManager._setDirtyForNode(siblings[i]);
|
||||
}
|
||||
}
|
||||
@@ -1942,7 +1943,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
|
||||
if (child._localZOrder < _children[j]._localZOrder) {
|
||||
_children[j+1] = _children[j];
|
||||
} else if (child._localZOrder === _children[j]._localZOrder &&
|
||||
child._sgNode.arrivalOrder < _children[j]._sgNode.arrivalOrder) {
|
||||
child._sgNode._arrivalOrder < _children[j]._sgNode._arrivalOrder) {
|
||||
_children[j+1] = _children[j];
|
||||
} else {
|
||||
break;
|
||||
@@ -1971,14 +1972,18 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
|
||||
sgNode.setScale(self._scaleX, self._scaleY);
|
||||
sgNode.setSkewX(self._skewX);
|
||||
sgNode.setSkewY(self._skewY);
|
||||
sgNode.ignoreAnchorPointForPosition(self.__ignoreAnchor);
|
||||
sgNode.setIgnoreAnchorPointForPosition(self.__ignoreAnchor);
|
||||
|
||||
var arrivalOrder = sgNode.arrivalOrder;
|
||||
var arrivalOrder = sgNode._arrivalOrder;
|
||||
sgNode.setLocalZOrder(self._localZOrder);
|
||||
sgNode.arrivalOrder = arrivalOrder; // revert arrivalOrder changed in setLocalZOrder
|
||||
sgNode._arrivalOrder = arrivalOrder; // revert arrivalOrder changed in setLocalZOrder
|
||||
|
||||
sgNode.setGlobalZOrder(self._globalZOrder);
|
||||
|
||||
if (CC_JSB) {
|
||||
// fix tintTo and tintBy action for jsb displays err for fireball/issues/4137
|
||||
sgNode.setColor(this._color);
|
||||
}
|
||||
sgNode.setOpacity(self._opacity);
|
||||
sgNode.setOpacityModifyRGB(self._opacityModifyRGB);
|
||||
sgNode.setCascadeOpacityEnabled(self._cascadeOpacityEnabled);
|
||||
@@ -2003,29 +2008,6 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
|
||||
}
|
||||
},
|
||||
|
||||
/*
|
||||
* The deserializer for sgNode which will be called before components onLoad
|
||||
* @param {Boolean} [skipChildrenInEditor=false]
|
||||
*/
|
||||
_onBatchCreated: function () {
|
||||
this._updateDummySgNode();
|
||||
|
||||
if (this._parent) {
|
||||
this._parent._sgNode.addChild(this._sgNode);
|
||||
}
|
||||
|
||||
if ( !this._activeInHierarchy ) {
|
||||
// deactivate ActionManager and EventManager by default
|
||||
cc.director.getActionManager().pauseTarget(this);
|
||||
cc.eventManager.pauseTarget(this);
|
||||
}
|
||||
|
||||
var children = this._children;
|
||||
for (var i = 0, len = children.length; i < len; i++) {
|
||||
children[i]._onBatchCreated();
|
||||
}
|
||||
},
|
||||
|
||||
onRestore: CC_EDITOR && function () {
|
||||
this._updateDummySgNode();
|
||||
|
||||
@@ -2055,6 +2037,13 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
|
||||
}
|
||||
}
|
||||
|
||||
// check activity state
|
||||
var shouldActiveInHierarchy = (this._parent && this._parent._activeInHierarchy && this._active);
|
||||
if (shouldActiveInHierarchy !== this._activeInHierarchy) {
|
||||
this._onActivatedInHierarchy(shouldActiveInHierarchy);
|
||||
this.emit('active-in-hierarchy-changed', this);
|
||||
}
|
||||
|
||||
if (this._activeInHierarchy) {
|
||||
cc.director.getActionManager().resumeTarget(this);
|
||||
cc.eventManager.resumeTarget(this);
|
||||
|
||||
@@ -43,11 +43,21 @@ cc.find = module.exports = function (path, referenceNode) {
|
||||
if (!referenceNode) {
|
||||
var scene = cc.director.getScene();
|
||||
if (!scene) {
|
||||
cc.warn('Can not get current scene.');
|
||||
if (CC_DEV) {
|
||||
cc.warn('Can not get current scene.');
|
||||
}
|
||||
return null;
|
||||
}
|
||||
else if (CC_DEV && !scene.isValid) {
|
||||
cc.warn('Scene is destroyed');
|
||||
return null;
|
||||
}
|
||||
referenceNode = scene;
|
||||
}
|
||||
else if (CC_DEV && !referenceNode.isValid) {
|
||||
cc.warn('reference node is destroyed');
|
||||
return null;
|
||||
}
|
||||
|
||||
var match = referenceNode;
|
||||
var startIndex = (path[0] !== '/') ? 0 : 1; // skip first '/'
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
|
||||
http://www.cocos.com
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated engine source code (the "Software"), a limited,
|
||||
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
|
||||
to use Cocos Creator solely to develop games on your target platforms. You shall
|
||||
not use Cocos Creator software for developing other software or tools that's
|
||||
used for developing games. You are not granted to publish, distribute,
|
||||
sublicense, and/or sell copies of Cocos Creator.
|
||||
|
||||
The software or tools in this License Agreement are licensed, not sold.
|
||||
Chukong Aipu reserves all rights not expressly granted to you.
|
||||
|
||||
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.
|
||||
****************************************************************************/
|
||||
|
||||
// 保存编辑器下用到的 prefab 相关信息
|
||||
cc._PrefabInfo = cc.Class({
|
||||
name: 'cc.PrefabInfo',
|
||||
properties: {
|
||||
//// the serialized version
|
||||
//VER: {
|
||||
// default: 1
|
||||
//},
|
||||
|
||||
// the most top node of this prefab in the scene
|
||||
root: null,
|
||||
|
||||
// 所属的 prefab 资源对象 (cc.Prefab)
|
||||
// (这个属性在场景中是会保存的,但是不会保存在 prefab 里面,因为创建 prefab 时还不知道自己的 uuid 是多少。)
|
||||
asset: null,
|
||||
|
||||
// 用来标识别该节点在 prefab 资源中的位置,因此这个 ID 只需要保证在 Assets 里不重复就行
|
||||
fileId: '',
|
||||
|
||||
// Indicates whether this node should always synchronize with the prefab asset, only available in the root node
|
||||
sync: false,
|
||||
|
||||
// Indicates whether this node is synchronized, only available in the root node
|
||||
_synced: {
|
||||
default: false,
|
||||
serializable: false
|
||||
},
|
||||
}
|
||||
});
|
||||
|
||||
// prefab helper function
|
||||
module.exports = {
|
||||
// update node to make it sync with prefab
|
||||
syncWithPrefab: function (node) {
|
||||
|
||||
// save preserved props to avoid overwritten by prefabRoot
|
||||
var _objFlags = node._objFlags;
|
||||
var _parent = node._parent;
|
||||
var _id = node._id;
|
||||
var _prefab = node._prefab;
|
||||
var _name = node._name;
|
||||
var _active = node._active;
|
||||
var _position = node._position;
|
||||
var _rotationX = node._rotationX;
|
||||
var _rotationY = node._rotationY;
|
||||
var _localZOrder = node._localZOrder;
|
||||
var _globalZOrder = node._globalZOrder;
|
||||
|
||||
// non-reentrant
|
||||
_prefab._synced = true;
|
||||
|
||||
var prefabRoot = _prefab.asset.data;
|
||||
|
||||
// prefab asset is always synced
|
||||
prefabRoot._prefab._synced = true;
|
||||
|
||||
// use node as the instantiated prefabRoot to make references to prefabRoot in prefab redirect to node
|
||||
prefabRoot._iN$t = node;
|
||||
|
||||
// instantiate prefab and apply to node
|
||||
cc.game._isCloning = true;
|
||||
cc.instantiate._clone(prefabRoot, prefabRoot);
|
||||
cc.game._isCloning = false;
|
||||
|
||||
// restore preserved props
|
||||
node._objFlags = _objFlags;
|
||||
node._parent = _parent;
|
||||
node._id = _id;
|
||||
node._prefab = _prefab;
|
||||
node._name = _name;
|
||||
node._active = _active;
|
||||
node._position = _position;
|
||||
node._rotationX = _rotationX;
|
||||
node._rotationY = _rotationY;
|
||||
node._localZOrder = _localZOrder;
|
||||
node._globalZOrder = _globalZOrder;
|
||||
}
|
||||
};
|
||||
@@ -34,6 +34,9 @@ var SceneGraphUtils = {
|
||||
parent.removeChild(node);
|
||||
}
|
||||
node.release();
|
||||
if (this._sgNode._entity) {
|
||||
this._sgNode._entity = null;
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
@@ -154,40 +154,45 @@ cc.affineTransformIdentity = function () {
|
||||
* @param {AffineTransform} anAffineTransform
|
||||
* @return {Rect}
|
||||
*/
|
||||
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);
|
||||
cc.rectApplyAffineTransform = function (rect, t) {
|
||||
var ol = rect.x;
|
||||
var ob = rect.y;
|
||||
var or = ol + rect.width;
|
||||
var ot = ob + rect.height;
|
||||
var lbx = t.a * ol + t.c * ob + t.tx;
|
||||
var lby = t.b * ol + t.d * ob + t.ty;
|
||||
var rbx = t.a * or + t.c * ob + t.tx;
|
||||
var rby = t.b * or + t.d * ob + t.ty;
|
||||
var ltx = t.a * ol + t.c * ot + t.tx;
|
||||
var lty = t.b * ol + t.d * ot + t.ty;
|
||||
var rtx = t.a * or + t.c * ot + t.tx;
|
||||
var rty = t.b * or + t.d * ot + t.ty;
|
||||
|
||||
var minX = Math.min(lbx, rbx, ltx, rtx);
|
||||
var maxX = Math.max(lbx, rbx, ltx, rtx);
|
||||
var minY = Math.min(lby, rby, lty, rty);
|
||||
var maxY = Math.max(lby, rby, lty, rty);
|
||||
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);
|
||||
cc._rectApplyAffineTransformIn = function(rect, t){
|
||||
var ol = rect.x;
|
||||
var ob = rect.y;
|
||||
var or = ol + rect.width;
|
||||
var ot = ob + rect.height;
|
||||
var lbx = t.a * ol + t.c * ob + t.tx;
|
||||
var lby = t.b * ol + t.d * ob + t.ty;
|
||||
var rbx = t.a * or + t.c * ob + t.tx;
|
||||
var rby = t.b * or + t.d * ob + t.ty;
|
||||
var ltx = t.a * ol + t.c * ot + t.tx;
|
||||
var lty = t.b * ol + t.d * ot + t.ty;
|
||||
var rtx = t.a * or + t.c * ot + t.tx;
|
||||
var rty = t.b * or + t.d * ot + t.ty;
|
||||
|
||||
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);
|
||||
var minX = Math.min(lbx, rbx, ltx, rtx);
|
||||
var maxX = Math.max(lbx, rbx, ltx, rtx);
|
||||
var minY = Math.min(lby, rby, lty, rty);
|
||||
var maxY = Math.max(lby, rby, lty, rty);
|
||||
|
||||
rect.x = minX;
|
||||
rect.y = minY;
|
||||
|
||||
@@ -35,7 +35,6 @@ _ccsg.VideoPlayer = _ccsg.Node.extend(/** @lends _ccsg.VideoPlayer# */{
|
||||
_ccsg.Node.prototype.ctor.call(this);
|
||||
// 播放结束等事件处理的队列
|
||||
this._EventList = {};
|
||||
this._renderCmd.createDom();
|
||||
},
|
||||
|
||||
_createRenderCmd: function(){
|
||||
@@ -74,6 +73,14 @@ _ccsg.VideoPlayer = _ccsg.Node.extend(/** @lends _ccsg.VideoPlayer# */{
|
||||
return this._renderCmd.isPlaying();
|
||||
},
|
||||
|
||||
duration: function () {
|
||||
return this._renderCmd.duration();
|
||||
},
|
||||
|
||||
currentTime: function() {
|
||||
return this._renderCmd.currentTime();
|
||||
},
|
||||
|
||||
createDomElementIfNeeded: function () {
|
||||
if (!this._renderCmd._video) {
|
||||
this._renderCmd.createDom();
|
||||
@@ -132,9 +139,9 @@ _ccsg.VideoPlayer = _ccsg.Node.extend(/** @lends _ccsg.VideoPlayer# */{
|
||||
},
|
||||
|
||||
cleanup: function () {
|
||||
this._super();
|
||||
|
||||
this._renderCmd.removeDom();
|
||||
this.stopAllActions();
|
||||
this.unscheduleAllCallbacks();
|
||||
},
|
||||
|
||||
onEnter: function () {
|
||||
@@ -183,15 +190,11 @@ cc.game.on(cc.game.EVENT_SHOW, function () {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* The VideoPlayer support list of events
|
||||
* @type {{PLAYING: string, PAUSED: string, STOPPED: string, COMPLETED: string}}
|
||||
*/
|
||||
_ccsg.VideoPlayer.EventType = {
|
||||
PLAYING: "play",
|
||||
PAUSED: "pause",
|
||||
STOPPED: "stop",
|
||||
COMPLETED: "complete"
|
||||
PLAYING: 0,
|
||||
PAUSED: 1,
|
||||
STOPPED: 2,
|
||||
COMPLETED: 3
|
||||
};
|
||||
|
||||
(function (video) {
|
||||
@@ -275,7 +278,7 @@ _ccsg.VideoPlayer.EventType = {
|
||||
scaleX /= dpr;
|
||||
scaleY /= dpr;
|
||||
|
||||
var container = cc.container;
|
||||
var container = cc.game.container;
|
||||
var a = t.a * scaleX, b = t.b, c = t.c, d = t.d * scaleY;
|
||||
|
||||
var offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft);
|
||||
@@ -388,9 +391,20 @@ _ccsg.VideoPlayer.EventType = {
|
||||
var video = this._video;
|
||||
if (node.visible) {
|
||||
video.style.visibility = 'visible';
|
||||
cc.game.container.appendChild(video);
|
||||
} else {
|
||||
video.style.visibility = 'hidden';
|
||||
video.pause();
|
||||
if(video){
|
||||
var hasChild = false;
|
||||
if('contains' in cc.game.container) {
|
||||
hasChild = cc.game.container.contains(video);
|
||||
}else {
|
||||
hasChild = cc.game.container.compareDocumentPosition(video) % 16;
|
||||
}
|
||||
if(hasChild)
|
||||
cc.game.container.removeChild(video);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
@@ -402,20 +416,20 @@ _ccsg.VideoPlayer.EventType = {
|
||||
video.className = "cocosVideo";
|
||||
video.setAttribute('preload', true);
|
||||
this._video = video;
|
||||
cc.container.appendChild(video);
|
||||
cc.game.container.appendChild(video);
|
||||
};
|
||||
|
||||
proto.removeDom = function () {
|
||||
var video = this._video;
|
||||
if(video){
|
||||
var hasChild = false;
|
||||
if('contains' in cc.container) {
|
||||
hasChild = cc.container.contains(video);
|
||||
if('contains' in cc.game.container) {
|
||||
hasChild = cc.game.container.contains(video);
|
||||
}else {
|
||||
hasChild = cc.container.compareDocumentPosition(video) % 16;
|
||||
hasChild = cc.game.container.compareDocumentPosition(video) % 16;
|
||||
}
|
||||
if(hasChild)
|
||||
cc.container.removeChild(video);
|
||||
cc.game.container.removeChild(video);
|
||||
}
|
||||
this._video = null;
|
||||
this._url = "";
|
||||
@@ -495,6 +509,7 @@ _ccsg.VideoPlayer.EventType = {
|
||||
};
|
||||
|
||||
proto.isPlaying = function () {
|
||||
var video = this._video;
|
||||
if(_ccsg.VideoPlayer._polyfill.autoplayAfterOperation && this._playing){
|
||||
setTimeout(function(){
|
||||
video.play();
|
||||
@@ -503,4 +518,18 @@ _ccsg.VideoPlayer.EventType = {
|
||||
return this._playing;
|
||||
};
|
||||
|
||||
proto.duration = function () {
|
||||
var video = this._video;
|
||||
if(!video) return -1;
|
||||
|
||||
return video.duration;
|
||||
};
|
||||
|
||||
proto.currentTime = function () {
|
||||
var video = this._video;
|
||||
if(!video) return -1;
|
||||
|
||||
return video.currentTime;
|
||||
};
|
||||
|
||||
})(_ccsg.VideoPlayer._polyfill);
|
||||
|
||||
@@ -0,0 +1,407 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2013-2016 Chukong Technologies Inc.
|
||||
http://www.cocos.com
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated engine source code (the "Software"), a limited,
|
||||
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
|
||||
to use Cocos Creator solely to develop games on your target platforms. You shall
|
||||
not use Cocos Creator software for developing other software or tools that's
|
||||
used for developing games. You are not granted to publish, distribute,
|
||||
sublicense, and/or sell copies of Cocos Creator.
|
||||
The software or tools in this License Agreement are licensed, not sold.
|
||||
Chukong Aipu reserves all rights not expressly granted to you.
|
||||
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.
|
||||
****************************************************************************/
|
||||
|
||||
_ccsg.WebView = _ccsg.Node.extend(/** @lends _ccsg.WebView# */{
|
||||
|
||||
ctor: function () {
|
||||
_ccsg.Node.prototype.ctor.call(this);
|
||||
this.setContentSize(cc.size(300, 200));
|
||||
this._EventList = {};
|
||||
},
|
||||
|
||||
createDomElementIfNeeded: function () {
|
||||
if (!this._renderCmd._div) {
|
||||
this._renderCmd.createNativeControl();
|
||||
}
|
||||
},
|
||||
|
||||
setJavascriptInterfaceScheme: function(scheme){},
|
||||
loadData: function(data, MIMEType, encoding, baseURL){},
|
||||
loadHTMLString: function(string, baseURL){},
|
||||
/**
|
||||
* Load an URL
|
||||
* @param {String} url
|
||||
*/
|
||||
loadURL: function(url){
|
||||
this._renderCmd.updateURL(url);
|
||||
this._dispatchEvent(_ccsg.WebView.EventType.LOADING);
|
||||
},
|
||||
|
||||
/**
|
||||
* Stop loading
|
||||
*/
|
||||
stopLoading: function(){
|
||||
cc.log("Web does not support loading");
|
||||
},
|
||||
|
||||
/**
|
||||
* Reload the WebView
|
||||
*/
|
||||
reload: function(){
|
||||
var iframe = this._renderCmd._iframe;
|
||||
if(iframe){
|
||||
var win = iframe.contentWindow;
|
||||
if(win && win.location)
|
||||
win.location.reload();
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Determine whether to go back
|
||||
*/
|
||||
canGoBack: function(){
|
||||
cc.log("Web does not support query history");
|
||||
return true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Determine whether to go forward
|
||||
*/
|
||||
canGoForward: function(){
|
||||
cc.log("Web does not support query history");
|
||||
return true;
|
||||
},
|
||||
|
||||
/**
|
||||
* go back
|
||||
*/
|
||||
goBack: function(){
|
||||
try{
|
||||
if(_ccsg.WebView._polyfill.closeHistory)
|
||||
return cc.log("The current browser does not support the GoBack");
|
||||
var iframe = this._renderCmd._iframe;
|
||||
if(iframe){
|
||||
var win = iframe.contentWindow;
|
||||
if(win && win.location)
|
||||
win.history.back.call(win);
|
||||
}
|
||||
}catch(err){
|
||||
cc.log(err);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* go forward
|
||||
*/
|
||||
goForward: function(){
|
||||
try{
|
||||
if(_ccsg.WebView._polyfill.closeHistory)
|
||||
return cc.log("The current browser does not support the GoForward");
|
||||
var iframe = this._renderCmd._iframe;
|
||||
if(iframe){
|
||||
var win = iframe.contentWindow;
|
||||
if(win && win.location)
|
||||
win.history.forward.call(win);
|
||||
}
|
||||
}catch(err){
|
||||
cc.log(err);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* In the webview execution within a period of js string
|
||||
* @param {String} str
|
||||
*/
|
||||
evaluateJS: function(str){
|
||||
var iframe = this._renderCmd._iframe;
|
||||
if(iframe){
|
||||
var win = iframe.contentWindow;
|
||||
try{
|
||||
win.eval(str);
|
||||
this._dispatchEvent(_ccsg.WebView.EventType.JS_EVALUATED);
|
||||
}catch(err){
|
||||
console.error(err);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Limited scale
|
||||
*/
|
||||
setScalesPageToFit: function(){
|
||||
cc.log("Web does not support zoom");
|
||||
},
|
||||
|
||||
/**
|
||||
* The binding event
|
||||
* @param {_ccsg.WebView.EventType} event
|
||||
* @param {Function} callback
|
||||
*/
|
||||
setEventListener: function(event, callback){
|
||||
this._EventList[event] = callback;
|
||||
},
|
||||
|
||||
/**
|
||||
* Delete events
|
||||
* @param {_ccsg.WebView.EventType} event
|
||||
*/
|
||||
removeEventListener: function(event){
|
||||
this._EventList[event] = null;
|
||||
},
|
||||
|
||||
_dispatchEvent: function(event) {
|
||||
var callback = this._EventList[event];
|
||||
if (callback)
|
||||
callback.call(this, this, this._renderCmd._iframe.src);
|
||||
},
|
||||
|
||||
_createRenderCmd: function(){
|
||||
return new _ccsg.WebView.RenderCmd(this);
|
||||
},
|
||||
|
||||
/**
|
||||
* Set the contentSize
|
||||
* @param {Number} width
|
||||
* @param {Number} height
|
||||
*/
|
||||
setContentSize: function(width, height){
|
||||
if (width.width !== undefined && width.height !== undefined) {
|
||||
height = width.height;
|
||||
width = width.width;
|
||||
}
|
||||
_ccsg.Node.prototype.setContentSize.call(this, width, height);
|
||||
this._renderCmd.updateSize(width, height);
|
||||
},
|
||||
|
||||
/**
|
||||
* remove node
|
||||
*/
|
||||
cleanup: function(){
|
||||
this._super();
|
||||
|
||||
this._renderCmd.removeDom();
|
||||
},
|
||||
|
||||
setVisible: function ( visible ) {
|
||||
_ccsg.Node.prototype.setVisible.call(this, visible);
|
||||
this._renderCmd.updateVisibility();
|
||||
}
|
||||
});
|
||||
|
||||
_ccsg.WebView.EventType = {
|
||||
LOADING: 0,
|
||||
LOADED: 1,
|
||||
ERROR: 2,
|
||||
JS_EVALUATED: 3
|
||||
};
|
||||
|
||||
(function(){
|
||||
|
||||
var polyfill = _ccsg.WebView._polyfill = {
|
||||
devicePixelRatio: false,
|
||||
enableDiv: false
|
||||
};
|
||||
|
||||
if(cc.sys.os === cc.sys.OS_IOS)
|
||||
polyfill.enableDiv = true;
|
||||
|
||||
if(cc.sys.isMobile){
|
||||
if(cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX){
|
||||
polyfill.enableBG = true;
|
||||
}
|
||||
}else{
|
||||
if(cc.sys.browserType === cc.sys.BROWSER_TYPE_IE){
|
||||
polyfill.closeHistory = true;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
})();
|
||||
|
||||
(function(polyfill){
|
||||
|
||||
var RenderCmd;
|
||||
if (cc._renderType === cc.game.RENDER_TYPE_CANVAS) {
|
||||
RenderCmd = _ccsg.Node.CanvasRenderCmd;
|
||||
} else {
|
||||
RenderCmd = _ccsg.Node.WebGLRenderCmd;
|
||||
}
|
||||
|
||||
_ccsg.WebView.RenderCmd = function(node){
|
||||
RenderCmd.call(this, node);
|
||||
|
||||
this._parent = null;
|
||||
this._div = null;
|
||||
this._iframe = null;
|
||||
this._listener = null;
|
||||
};
|
||||
|
||||
var proto = _ccsg.WebView.RenderCmd.prototype = Object.create(RenderCmd.prototype);
|
||||
proto.constructor = _ccsg.WebView.RenderCmd;
|
||||
|
||||
proto.transform = function (parentCmd, recursive) {
|
||||
this.originTransform(parentCmd, recursive);
|
||||
this.updateMatrix();
|
||||
};
|
||||
|
||||
proto.updateStatus = function(){
|
||||
polyfill.devicePixelRatio = cc.view.isRetinaEnabled();
|
||||
var flags = _ccsg.Node._dirtyFlags, locFlag = this._dirtyFlag;
|
||||
if(locFlag & flags.transformDirty){
|
||||
//update the transform
|
||||
this.transform(this.getParentRenderCmd(), true);
|
||||
this.updateMatrix();
|
||||
this._dirtyFlag = this._dirtyFlag & _ccsg.Node._dirtyFlags.transformDirty ^ this._dirtyFlag;
|
||||
}
|
||||
};
|
||||
|
||||
proto.initEvent = function () {
|
||||
var node = this._node;
|
||||
this._iframe.addEventListener("load", function(){
|
||||
node._dispatchEvent(_ccsg.WebView.EventType.LOADED);
|
||||
});
|
||||
this._iframe.addEventListener("error", function(){
|
||||
node._dispatchEvent(_ccsg.WebView.EventType.ERROR);
|
||||
});
|
||||
};
|
||||
|
||||
proto.resize = function(view){
|
||||
view = view || cc.view;
|
||||
var node = this._node,
|
||||
eventManager = cc.eventManager;
|
||||
if(node._parent && node._visible)
|
||||
this.updateMatrix();
|
||||
else{
|
||||
var list = eventManager._listenersMap[cc.game.EVENT_RESIZE].getFixedPriorityListeners();
|
||||
eventManager._removeListenerInVector(list, this._listener);
|
||||
this._listener = null;
|
||||
}
|
||||
};
|
||||
|
||||
proto.updateMatrix = function(){
|
||||
if (!this._div) return;
|
||||
|
||||
var node = this._node, scaleX = cc.view._scaleX, scaleY = cc.view._scaleY;
|
||||
var dpr = cc.view._devicePixelRatio;
|
||||
var t = this._worldTransform;
|
||||
|
||||
scaleX /= dpr;
|
||||
scaleY /= dpr;
|
||||
|
||||
var container = cc.game.container;
|
||||
var a = t.a * scaleX, b = t.b, c = t.c, d = t.d * scaleY;
|
||||
|
||||
var offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft);
|
||||
var offsetY = container && container.style.paddingBottom && parseInt(container.style.paddingBottom);
|
||||
var tx = t.tx * scaleX + offsetX, ty = t.ty * scaleY + offsetY;
|
||||
|
||||
var matrix = "matrix(" + a + "," + -b + "," + -c + "," + d + "," + tx + "," + -ty + ")";
|
||||
this._div.style['transform'] = matrix;
|
||||
this._div.style['-webkit-transform'] = matrix;
|
||||
this._div.style['transform-origin'] = '0px 100% 0px';
|
||||
this._div.style['-webkit-transform-origin'] = '0px 100% 0px';
|
||||
};
|
||||
|
||||
proto.initStyle = function(){
|
||||
if(!this._div) return;
|
||||
var div = this._div;
|
||||
div.style.position = "absolute";
|
||||
div.style.bottom = "0px";
|
||||
div.style.left = "0px";
|
||||
};
|
||||
|
||||
proto.updateURL = function(url){
|
||||
var iframe = this._iframe;
|
||||
iframe.src = url;
|
||||
var self = this;
|
||||
var cb = function(){
|
||||
self._loaded = true;
|
||||
self.updateVisibility();
|
||||
iframe.removeEventListener("load", cb);
|
||||
};
|
||||
iframe.addEventListener("load", cb);
|
||||
};
|
||||
|
||||
proto.updateSize = function(w, h){
|
||||
var div = this._div;
|
||||
if(div){
|
||||
div.style["width"] = w+"px";
|
||||
div.style["height"] = h+"px";
|
||||
}
|
||||
};
|
||||
|
||||
proto.createDom = function () {
|
||||
if(polyfill.enableDiv){
|
||||
this._div = document.createElement("div");
|
||||
this._div.style["-webkit-overflow"] = "auto";
|
||||
this._div.style["-webkit-overflow-scrolling"] = "touch";
|
||||
this._iframe = document.createElement("iframe");
|
||||
this._div.appendChild(this._iframe);
|
||||
}else{
|
||||
this._div = this._iframe = document.createElement("iframe");
|
||||
}
|
||||
|
||||
if(polyfill.enableBG)
|
||||
this._div.style["background"] = "#FFF";
|
||||
|
||||
this._div.style["background"] = "#FFF";
|
||||
var contentSize = this._node._contentSize;
|
||||
this._div.style.height = contentSize.height + "px";
|
||||
this._div.style.width = contentSize.width + "px";
|
||||
this._div.style.overflow = "scroll";
|
||||
this._div.style.border = "none";
|
||||
cc.game.container.appendChild(this._div);
|
||||
};
|
||||
|
||||
proto.createNativeControl = function () {
|
||||
this.createDom();
|
||||
this.initStyle();
|
||||
this.initEvent();
|
||||
};
|
||||
|
||||
proto.removeDom = function(){
|
||||
var div = this._div;
|
||||
if(div){
|
||||
var hasChild = false;
|
||||
if('contains' in cc.game.container) {
|
||||
hasChild = cc.game.container.contains(div);
|
||||
}else {
|
||||
hasChild = cc.game.container.compareDocumentPosition(div) % 16;
|
||||
}
|
||||
if(hasChild)
|
||||
cc.game.container.removeChild(div);
|
||||
}
|
||||
this._div = null;
|
||||
};
|
||||
|
||||
proto.updateVisibility = function () {
|
||||
var node = this._node;
|
||||
if (!this._div) return;
|
||||
var div = this._div;
|
||||
if (node.visible) {
|
||||
div.style.visibility = 'visible';
|
||||
cc.game.container.appendChild(div);
|
||||
} else {
|
||||
div.style.visibility = 'hidden';
|
||||
if(div){
|
||||
var hasChild = false;
|
||||
if('contains' in cc.game.container) {
|
||||
hasChild = cc.game.container.contains(div);
|
||||
}else {
|
||||
hasChild = cc.game.container.compareDocumentPosition(div) % 16;
|
||||
}
|
||||
if(hasChild)
|
||||
cc.game.container.removeChild(div);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
})(_ccsg.WebView._polyfill);
|
||||
+255
-34
@@ -1,11 +1,12 @@
|
||||
var js = cc.js;
|
||||
|
||||
// Label
|
||||
if (cc.Label) {
|
||||
js.obsolete(cc.Label.prototype, 'cc.Label.file', 'font', true);
|
||||
}
|
||||
if (CC_DEV && typeof eruda === 'undefined') {
|
||||
|
||||
if (CC_DEV) {
|
||||
var js = cc.js;
|
||||
|
||||
// Label
|
||||
if (cc.Label) {
|
||||
js.obsolete(cc.Label.prototype, 'cc.Label.file', 'font', true);
|
||||
}
|
||||
|
||||
var INFO = cc._LogInfos.deprecated;
|
||||
|
||||
@@ -210,6 +211,11 @@ if (CC_DEV) {
|
||||
return cc.js.array.copy;
|
||||
});
|
||||
|
||||
js.get(cc, 'PI', function () {
|
||||
cc.warn(INFO, 'cc.PI', 'Math.PI');
|
||||
return Math.PI;
|
||||
});
|
||||
|
||||
/**
|
||||
* Get the Tile set information for the layer.
|
||||
* @memberof cc.TiledLayer
|
||||
@@ -273,7 +279,9 @@ if (CC_DEV) {
|
||||
}
|
||||
// deprecateEnum(cc.ProgressTimer, 'cc.ProgressTimer.TYPE', 'cc.ProgressTimer.Type');
|
||||
deprecateEnum(cc.game, 'cc.game.DEBUG_MODE', 'cc.DebugMode');
|
||||
deprecateEnum(cc, 'cc', 'cc.Texture2D.WrapMode', false);
|
||||
if (!CC_JSB) {
|
||||
deprecateEnum(cc, 'cc', 'cc.Texture2D.WrapMode', false);
|
||||
}
|
||||
if (_ccsg.EditBox) {
|
||||
deprecateEnum(cc, 'cc.KEYBOARD_RETURNTYPE', '_ccsg.EditBox.KeyboardReturnType');
|
||||
deprecateEnum(cc, 'cc.EDITBOX_INPUT_MODE', '_ccsg.EditBox.InputMode');
|
||||
@@ -372,7 +380,6 @@ if (CC_DEV) {
|
||||
'onEnterTransitionDidFinish',
|
||||
'onExitTransitionDidStart',
|
||||
'onExit',
|
||||
'getNumberOfRunningActions',
|
||||
'scheduleUpdate',
|
||||
'scheduleUpdateWithPriority',
|
||||
'unscheduleUpdate',
|
||||
@@ -392,6 +399,8 @@ if (CC_DEV) {
|
||||
'transform',
|
||||
'getCamera',
|
||||
'grid',
|
||||
'getOrderOfArrival',
|
||||
'setOrderOfArrival',
|
||||
'getGrid',
|
||||
'setGrid',
|
||||
'getShaderProgram',
|
||||
@@ -422,8 +431,6 @@ if (CC_DEV) {
|
||||
_detachChild: 'removeChild',
|
||||
getZOrder: 'getLocalZOrder',
|
||||
setZOrder: 'setLocalZOrder',
|
||||
getOrderOfArrival: 'getSiblingIndex',
|
||||
setOrderOfArrival: 'setSiblingIndex',
|
||||
boundingBox: 'getBoundingBox',
|
||||
removeFromParentAndCleanup: 'removeFromParent',
|
||||
removeAllChildrenWithCleanup: 'removeAllChildren',
|
||||
@@ -434,7 +441,7 @@ if (CC_DEV) {
|
||||
removeAllComponents: 'removeComponent',
|
||||
getNodeToParentAffineTransform: 'getNodeToParentTransform',
|
||||
});
|
||||
|
||||
|
||||
// RENDERERS
|
||||
|
||||
function shouldNotUseNodeProp (component) {
|
||||
@@ -544,29 +551,33 @@ if (CC_DEV) {
|
||||
Mode: 'EmitterMode'
|
||||
});
|
||||
|
||||
// _ccsg.Node
|
||||
markAsRemoved(_ccsg.Node, [
|
||||
'_normalizedPositionDirty',
|
||||
'_normalizedPosition',
|
||||
'_usingNormalizedPosition',
|
||||
'grid',
|
||||
'userData',
|
||||
'userObject',
|
||||
'getNormalizedPosition',
|
||||
'setNormalizedPosition',
|
||||
'getCamera',
|
||||
'getUserData',
|
||||
'setUserData',
|
||||
'getUserObject',
|
||||
'setUserObject',
|
||||
'getComponent',
|
||||
'addComponent',
|
||||
'removeComponent',
|
||||
'removeAllComponents',
|
||||
'enumerateChildren',
|
||||
'setCameraMask',
|
||||
'getCameraMask'
|
||||
], '_ccsg.Node');
|
||||
if (!CC_JSB) {
|
||||
// _ccsg.Node
|
||||
markAsRemoved(_ccsg.Node, [
|
||||
'_normalizedPositionDirty',
|
||||
'_normalizedPosition',
|
||||
'_usingNormalizedPosition',
|
||||
'grid',
|
||||
'userData',
|
||||
'userObject',
|
||||
'getNormalizedPosition',
|
||||
'setNormalizedPosition',
|
||||
'getCamera',
|
||||
'getUserData',
|
||||
'setUserData',
|
||||
'getUserObject',
|
||||
'setUserObject',
|
||||
'getComponent',
|
||||
'addComponent',
|
||||
'removeComponent',
|
||||
'removeAllComponents',
|
||||
'enumerateChildren',
|
||||
'setCameraMask',
|
||||
'getCameraMask'
|
||||
], '_ccsg.Node');
|
||||
}
|
||||
|
||||
js.obsolete(_ccsg.Node.prototype, '_ccsg.Node.ignoreAnchorPointForPosition', 'setIgnoreAnchorPointForPosition');
|
||||
|
||||
js.obsoletes(cc.Scale9Sprite.prototype, 'cc.Scale9Sprite', {
|
||||
setPreferredSize: 'setContentSize',
|
||||
@@ -612,4 +623,214 @@ if (CC_DEV) {
|
||||
'*etTimeScale': 'timeScale',
|
||||
});
|
||||
}
|
||||
|
||||
// SCENE
|
||||
|
||||
var ERR = '"%s" is not defined in the Scene, it is only defined in normal nodes.';
|
||||
Object.defineProperties(cc.Scene.prototype, {
|
||||
active: {
|
||||
get: function () {
|
||||
cc.error(ERR, 'active');
|
||||
return true;
|
||||
},
|
||||
set: function () {
|
||||
cc.error(ERR, 'active');
|
||||
}
|
||||
},
|
||||
activeInHierarchy: {
|
||||
get: function () {
|
||||
cc.error(ERR, 'activeInHierarchy');
|
||||
return true;
|
||||
},
|
||||
},
|
||||
getComponent: {
|
||||
get: function () {
|
||||
cc.error(ERR, 'getComponent');
|
||||
return function () {
|
||||
return null;
|
||||
};
|
||||
}
|
||||
},
|
||||
addComponent: {
|
||||
get: function () {
|
||||
cc.error(ERR, 'addComponent');
|
||||
return function () {
|
||||
return null;
|
||||
};
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
(function (audioEngine) {
|
||||
if (typeof audioEngine === 'undefined') return;
|
||||
|
||||
(function (prop) {
|
||||
function error () {
|
||||
cc.error('Sorry, %s.%s is removed.', 'cc.audioEngine', prop);
|
||||
}
|
||||
js.getset(audioEngine, prop, error, error);
|
||||
})('willPlayMusic');
|
||||
|
||||
var musicId = -1;
|
||||
var musicVolume = 1;
|
||||
var effectsVolume = 1;
|
||||
var pauseIDCache = [];
|
||||
js.get(audioEngine, 'playMusic', function () {
|
||||
cc.warn(INFO, 'audioEngine.playMusic', 'audioEngine.play');
|
||||
return function (url, loop) {
|
||||
musicId = audioEngine.play(url, loop, musicVolume);
|
||||
return musicId;
|
||||
}
|
||||
});
|
||||
js.get(audioEngine, 'stopMusic', function () {
|
||||
cc.warn(INFO, 'audioEngine.stopMusic', 'audioEngine.stop');
|
||||
return function () {
|
||||
audioEngine.stop(musicId);
|
||||
return musicId;
|
||||
}
|
||||
});
|
||||
js.get(audioEngine, 'pauseMusic', function () {
|
||||
cc.warn(INFO, 'audioEngine.pauseMusic', 'audioEngine.pause');
|
||||
return function () {
|
||||
audioEngine.pause(musicId);
|
||||
return musicId;
|
||||
}
|
||||
});
|
||||
js.get(audioEngine, 'resumeMusic', function () {
|
||||
cc.warn(INFO, 'audioEngine.resumeMusic', 'audioEngine.resume');
|
||||
return function () {
|
||||
audioEngine.resume(musicId);
|
||||
return musicId;
|
||||
}
|
||||
});
|
||||
js.get(audioEngine, 'rewindMusic', function () {
|
||||
cc.warn(INFO, 'audioEngine.rewindMusic', 'audioEngine.setCurrentTime');
|
||||
return function () {
|
||||
audioEngine.setCurrentTime(musicId, 0);
|
||||
return musicId;
|
||||
}
|
||||
});
|
||||
js.get(audioEngine, 'getMusicVolume', function () {
|
||||
cc.warn(INFO, 'audioEngine.getMusicVolume', 'audioEngine.getVolume');
|
||||
return function () {
|
||||
return musicVolume;
|
||||
}
|
||||
});
|
||||
js.get(audioEngine, 'setMusicVolume', function () {
|
||||
cc.warn(INFO, 'audioEngine.setMusicVolume', 'audioEngine.setVolume');
|
||||
return function (volume) {
|
||||
musicVolume = volume;
|
||||
audioEngine.setVolume(musicId, musicVolume);
|
||||
return musicVolume;
|
||||
}
|
||||
});
|
||||
js.get(audioEngine, 'isMusicPlaying', function () {
|
||||
cc.warn(INFO, 'audioEngine.isMusicPlaying', 'audioEngine.getState');
|
||||
return function () {
|
||||
return audioEngine.getState(musicId) === audioEngine.AudioState.PLAYING;
|
||||
}
|
||||
});
|
||||
js.get(audioEngine, 'playEffect', function () {
|
||||
cc.warn(INFO, 'audioEngine.playEffect', 'audioEngine.play');
|
||||
|
||||
return function (url, loop, volume) {
|
||||
return audioEngine.play(url, loop, volume === undefined ? effectsVolume : volume);
|
||||
}
|
||||
});
|
||||
js.get(audioEngine, 'setEffectsVolume', function (volume) {
|
||||
cc.warn(INFO, 'audioEngine.setEffectsVolume', 'audioEngine.setVolume');
|
||||
return function (volume) {
|
||||
effectsVolume = volume;
|
||||
var id2audio = audioEngine._id2audio;
|
||||
for (var id in id2audio) {
|
||||
if (id === musicId) continue;
|
||||
audioEngine.setVolume(id, volume);
|
||||
}
|
||||
}
|
||||
});
|
||||
js.get(audioEngine, 'getEffectsVolume', function () {
|
||||
cc.warn(INFO, 'audioEngine.getEffectsVolume', 'audioEngine.getVolume');
|
||||
return function () {
|
||||
return effectsVolume;
|
||||
}
|
||||
});
|
||||
js.get(audioEngine, 'pauseEffect', function () {
|
||||
cc.warn(INFO, 'audioEngine.pauseEffect', 'audioEngine.pause');
|
||||
|
||||
return function (id) {
|
||||
return audioEngine.pause(id);
|
||||
}
|
||||
});
|
||||
js.get(audioEngine, 'pauseAllEffects', function () {
|
||||
cc.warn(INFO, 'audioEngine.pauseAllEffects', 'audioEngine.pauseAll');
|
||||
|
||||
return function () {
|
||||
var id2audio = audioEngine._id2audio;
|
||||
for (var id in id2audio) {
|
||||
if (id === musicId) continue;
|
||||
var audio = id2audio[id];
|
||||
var state = audio.getState();
|
||||
if (state === audioEngine.AudioState.PLAYING) {
|
||||
pauseIDCache.push(id);
|
||||
audio.pause();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
js.get(audioEngine, 'resumeEffect', function () {
|
||||
cc.warn(INFO, 'audioEngine.resumeEffect', 'audioEngine.resume');
|
||||
return function (id) {
|
||||
audioEngine.resume(id);
|
||||
}
|
||||
});
|
||||
js.get(audioEngine, 'resumeAllEffects', function () {
|
||||
cc.warn(INFO, 'audioEngine.resumeEffect', 'audioEngine.resume');
|
||||
return function () {
|
||||
var id2audio = audioEngine._id2audio;
|
||||
while (pauseIDCache.length > 0) {
|
||||
var id = pauseIDCache.pop();
|
||||
var audio = id2audio[id];
|
||||
if (audio && audio.resume)
|
||||
audio.resume();
|
||||
}
|
||||
}
|
||||
});
|
||||
js.get(audioEngine, 'stopEffect', function () {
|
||||
cc.warn(INFO, 'audioEngine.stopEffect', 'audioEngine.stop');
|
||||
return function (id) {
|
||||
return audioEngine.stop(id);
|
||||
}
|
||||
});
|
||||
js.get(audioEngine, 'stopAllEffects', function () {
|
||||
cc.warn(INFO, 'audioEngine.stopAllEffects', 'audioEngine.stopAll');
|
||||
return function () {
|
||||
var id2audio = audioEngine._id2audio;
|
||||
for (var id in id2audio) {
|
||||
if (id === musicId) continue;
|
||||
var audio = id2audio[id];
|
||||
var state = audio.getState();
|
||||
if (state === audioEngine.AudioState.PLAYING) {
|
||||
audio.stop();
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
js.get(audioEngine, 'unloadEffect', function () {
|
||||
cc.warn(INFO, 'audioEngine.unloadEffect', 'audioEngine.stop');
|
||||
return function (id) {
|
||||
return audioEngine.stop(id);
|
||||
}
|
||||
});
|
||||
|
||||
if (!CC_JSB) {
|
||||
js.get(audioEngine, 'end', function () {
|
||||
cc.warn(INFO, 'audioEngine.end', 'audioEngine.stopAll');
|
||||
return function () {
|
||||
return audioEngine.stopAll();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
})(cc.audioEngine);
|
||||
|
||||
}
|
||||
|
||||
@@ -48,6 +48,9 @@ if (ENABLE_GL_STATE_CACHE) {
|
||||
|
||||
var _currBuffers = {};
|
||||
|
||||
// IE 10 WebGLRenderingContext does not exist
|
||||
if (!window.WebGLRenderingContext) return;
|
||||
|
||||
WebGLRenderingContext.prototype.glBindBuffer = WebGLRenderingContext.prototype.bindBuffer;
|
||||
WebGLRenderingContext.prototype.bindBuffer = function (target, buffer) {
|
||||
if (_currBuffers[target] !== buffer) {
|
||||
|
||||
@@ -145,7 +145,8 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{
|
||||
maxGid = tileset.firstGid + count,
|
||||
grids = this._texGrids,
|
||||
grid = null,
|
||||
override = grids[gid] ? true : false;
|
||||
override = grids[gid] ? true : false,
|
||||
texelCorrect = cc.macro.FIX_ARTIFACTS_BY_STRECHING_TEXEL ? 0.5 : 0;
|
||||
|
||||
for (; gid < maxGid; ++gid) {
|
||||
// Avoid overlapping
|
||||
@@ -162,8 +163,12 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{
|
||||
t: 0, l: 0, r: 0, b: 0
|
||||
};
|
||||
tileset.rectForGID(gid, grid);
|
||||
grid.t = grid.y / imageH;
|
||||
grid.l = grid.x / imageW;
|
||||
grid.x += texelCorrect;
|
||||
grid.y += texelCorrect;
|
||||
grid.width -= texelCorrect*2;
|
||||
grid.height -= texelCorrect*2;
|
||||
grid.t = (grid.y) / imageH;
|
||||
grid.l = (grid.x) / imageW;
|
||||
grid.r = (grid.x + grid.width) / imageW;
|
||||
grid.b = (grid.y + grid.height) / imageH;
|
||||
grids[gid] = grid;
|
||||
@@ -321,7 +326,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{
|
||||
* Tile set information for the layer
|
||||
* @return {cc.TMXTilesetInfo}
|
||||
*/
|
||||
getTileset:function () {
|
||||
getTileSet:function () {
|
||||
return this.tileset;
|
||||
},
|
||||
|
||||
@@ -329,7 +334,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{
|
||||
* Tile set information for the layer
|
||||
* @param {cc.TMXTilesetInfo} Var
|
||||
*/
|
||||
setTileset:function (Var) {
|
||||
setTileSet:function (Var) {
|
||||
this.tileset = Var;
|
||||
},
|
||||
|
||||
@@ -434,7 +439,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{
|
||||
return tile;
|
||||
}
|
||||
|
||||
var z = Math.floor(pos.x) + Math.floor(pos.y) * this._layerSize.width;
|
||||
var z = Math.floor(x) + Math.floor(y) * this._layerSize.width;
|
||||
tile = this._spriteTiles[z];
|
||||
// tile not created yet. create it
|
||||
if (!tile) {
|
||||
@@ -477,7 +482,7 @@ _ccsg.TMXLayer = _ccsg.Node.extend(/** @lends _ccsg.TMXLayer# */{
|
||||
return null;
|
||||
}
|
||||
|
||||
var idx = Math.floor(pos.x) + Math.floor(pos.y) * this._layerSize.width;
|
||||
var idx = Math.floor(x) + Math.floor(y) * this._layerSize.width;
|
||||
// Bits on the far end of the 32-bit global tile ID are used for tile flags
|
||||
var tile = this.tiles[idx];
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user