Merge branch 'master' into addBlendFunc_Sprite

This commit is contained in:
Huabing.Xu
2016-02-29 11:37:16 +08:00
177 changed files with 9182 additions and 6093 deletions
+14
View File
@@ -0,0 +1,14 @@
> Makes sure these boxes are checked before submitting your PR - thank you!
>
- [ ] Check that your javascript is following our [style guide](https://github.com/cocos-creator/fireball/blob/dev/.github/CONTRIBUTING.md) and end files with a newline
- [ ] Document new code with comments in source code based on [API Docs](https://github.com/cocos-creator/fireball#api-docs)
- [ ] If your pull request has gone "stale", you should **rebase** your work on top of the latest version of the upstream branch.
- [ ] If your commit history is full of small, unimportant commits (such as "fix pep8" or "update tests"), **squash** your commits down to a few, or one, discreet changesets before submitting a pull request.
Re: cocos-creator/fireball#
Changes proposed in this pull request:
-
-
@cocos-creator/engine-admins
+4 -4
View File
@@ -192,8 +192,8 @@ cc.formatStr = function(){
};
require('../cocos2d/core/utils');
require('../cocos2d/core/platform/CCLoader');
require('../cocos2d/core/platform/CCSys');
require('../cocos2d/core/load-pipeline/CCLoader');
require('../cocos2d/core/CCGame');
@@ -276,7 +276,7 @@ function _load(config) {
} else {
// Load cocos modules
var ccModulesPath = cc.path.join(engineDir, "moduleConfig.json");
loader.loadJson(ccModulesPath, function (err, modulesJson) {
loader.load(ccModulesPath, function (err, modulesJson) {
if (err) throw new Error(err);
var modules = config["modules"] || [];
var moduleMap = modulesJson["module"];
@@ -287,8 +287,8 @@ function _load(config) {
var arr = _getJsListOfModule(moduleMap, modules[i], engineDir);
if (arr) jsList = jsList.concat(arr);
}
cc.loader.loadJsWithImg(jsList, function (err) {
if (err) throw err;
loader.load(jsList, function (err) {
if (err) throw new Error(JSON.stringify(err));
_afterEngineLoaded(config);
});
});
+44 -28
View File
@@ -326,11 +326,13 @@ cc._formatString = function (arg) {
return arg;
};
var Enum = require('./cocos2d/core/value-types/CCEnum');
/**
* Enum for debug modes.
* @enum DebugMode
*/
cc.DebugMode = cc.Enum({
cc.DebugMode = Enum({
/**
* @property {number} NONE - The debug mode none.
*/
@@ -371,6 +373,9 @@ cc.DebugMode = cc.Enum({
* @param {DebugMode} mode
*/
cc._initDebugSetting = function (mode) {
// reset
cc.log = cc.warn = cc.error = cc._throw = cc.assert = function () {};
if(mode === cc.DebugMode.NONE)
return;
@@ -414,12 +419,15 @@ cc._initDebugSetting = function (mode) {
* @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 (console.error.bind) {
if (CC_EDITOR) {
cc.error = Editor.error;
}
else if (console.error.bind) {
// use bind to avoid pollute call stacks
cc.error = console.error.bind(console);
}
else {
cc.error = function(){
cc.error = function () {
return console.error.apply(console, arguments);
};
}
@@ -430,7 +438,7 @@ cc._initDebugSetting = function (mode) {
throw new Error(msg);
}
};
if(mode !== cc.DebugMode.ERROR)
if (mode !== cc.DebugMode.ERROR) {
/**
* Outputs a warning message to the Cocos Creator Console (editor) or Web Console (runtime).
* - In Cocos Creator, warning is yellow.
@@ -439,37 +447,45 @@ cc._initDebugSetting = function (mode) {
* @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 (console.warn.bind) {
if (CC_EDITOR) {
cc.warn = Editor.warn;
}
else if (console.warn.bind) {
// use bind to avoid pollute call stacks
cc.warn = console.warn.bind(console);
}
else {
cc.warn = function() {
cc.warn = function () {
return console.warn.apply(console, arguments);
};
}
if(mode === cc.DebugMode.INFO) {
/**
* Outputs a message to the Cocos Creator Console (editor) or Web Console (runtime).
* @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.
*/
cc.log = function () {
return console.log.apply(console, arguments);
};
/**
* Outputs an informational message to the Cocos Creator Console (editor) or Web Console (runtime).
* - In Cocos Creator, info is blue.
* - In Firefox and Chrome, a small "i" icon is displayed next to these items in the Web Console's log.
* @method info
* @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.
*/
cc.info = function () {
(console.info || console.log).apply(console, arguments);
};
}
}
if (CC_EDITOR) {
cc.log = Editor.log;
cc.info = Editor.info;
}
else if (mode === cc.DebugMode.INFO) {
/**
* Outputs a message to the Cocos Creator Console (editor) or Web Console (runtime).
* @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.
*/
cc.log = function () {
return console.log.apply(console, arguments);
};
/**
* Outputs an informational message to the Cocos Creator Console (editor) or Web Console (runtime).
* - In Cocos Creator, info is blue.
* - In Firefox and Chrome, a small "i" icon is displayed next to these items in the Web Console's log.
* @method info
* @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.
*/
cc.info = function () {
(console.info || console.log).apply(console, arguments);
};
}
}
cc._throw = function (error) {
cc.error(error.stack || error);
-167
View File
@@ -1,167 +0,0 @@
var NodeWrapper = require('./node');
var ProgressTimerWrapper = cc.Class({
name: 'cc.ProgressTimerWrapper',
extends: NodeWrapper,
ctor: function () {
this._midPoint = [0.5, 0.5];
this._barChangeRate = [1, 1];
},
properties: {
_type: {
default: cc.ProgressTimer.Type.RADIAL,
type: cc.ProgressTimer.Type
},
type: {
get: function () {
return this.targetN.getType();
},
set: function (value) {
if (!isNaN(value)) {
this.targetN.setType(value);
}
else {
cc.error('The new type must not be NaN');
}
},
type: cc.ProgressTimer.Type
},
_percentage: {
default: 50,
},
percentage: {
get: function() {
return this.targetN.getPercentage();
},
set: function (value) {
if (!isNaN(value)) {
this.targetN.setPercentage(value);
}
else {
cc.error('The new percentage must not be NaN');
}
},
},
_midPoint: {
default: []
},
midPoint: {
get: function () {
var pt = this.targetN.getMidpoint();
return new cc.Vec2(pt.x, pt.y);
},
set: function (value) {
if ( value instanceof cc.Vec2 ) {
this.targetN.setMidpoint(cc.p(value.x, value.y));
}
else {
cc.error('The new midPoint must be cc.Vec2');
}
}
},
_barChangeRate: {
default: []
},
barChangeRate: {
get: function () {
var pt = this.targetN.getBarChangeRate();
return new cc.Vec2(pt.x, pt.y);
},
set: function (value) {
if ( value instanceof cc.Vec2 ) {
this.targetN.setBarChangeRate(cc.p(value.x, value.y));
}
else {
cc.error('The new barChangeRate must be cc.Vec2');
}
}
},
_reverseDirection : {
default: false,
},
reverseDirection: {
get: function () {
return this.targetN.isReverseDirection();
},
set: function (value) {
if (typeof value === 'boolean') {
this.targetN.setReverseProgress(value);
}
else {
cc.error('The new reverseDirection must be Boolean');
}
}
},
_texture: {
default: '',
url: cc.Texture2D
},
texture: {
get: function () {
var tex = this.targetN.getSprite().texture;
return (tex && tex.url) || '';
},
set: function (value) {
this.targetN.getSprite().texture = value;
},
url: cc.Texture2D
}
},
onBeforeSerialize: function () {
NodeWrapper.prototype.onBeforeSerialize.call(this);
this._type = this.type;
this._percentage = this.percentage;
this._midPoint = [this.midPoint.x, this.midPoint.y];
this._barChangeRate = [this.barChangeRate.x, this.barChangeRate.y];
this._reverseDirection = this.reverseDirection;
this._texture = this.texture;
},
createNode: function (node) {
node = node || new cc.ProgressTimer(new _ccsg.Sprite());
var sp = node.getSprite();
if (this._texture) {
sp.texture = this._texture;
if (cc.sys.isNative) {
// jsb Texture will not save url, so we save manually.
sp.texture.url = this._texture;
}
}
node.setType(this._type);
node.setPercentage(this._percentage);
if (this._midPoint) {
node.setMidpoint(cc.p(this._midPoint[0], this._midPoint[1]));
}
if (this._barChangeRate) {
node.setBarChangeRate(cc.p(this._barChangeRate[0], this._barChangeRate[1]));
}
node.setReverseProgress(this._reverseDirection);
NodeWrapper.prototype.createNode.call(this, node);
return node;
}
});
cc.ProgressTimerWrapper = module.exports = ProgressTimerWrapper;
+1 -1
View File
@@ -41,7 +41,7 @@ var TiledMapWrapper = cc.Class({
childrenN: {
get: function () {
var children = this.targetN.children.filter( function (child) {
return !(child instanceof cc.TMXLayer);
return !(child instanceof _ccsg.TMXLayer);
});
return children;
},
-214
View File
@@ -1,214 +0,0 @@
var Utils = require('../utils');
var WidgetWrapper = require('./widget');
var TextFieldWrapper = cc.Class({
name: 'cc.TextFieldWrapper',
extends: WidgetWrapper,
properties: {
text: {
get: function () {
return this.targetN.string;
},
set: function (value) {
if (typeof value === 'string') {
this.targetN.string = value;
this.setDirtyFlag();
}
else {
cc.error('The new text must be String');
}
}
},
placeHolder: {
get: function () {
return this.targetN.placeHolder;
},
set: function (value) {
if (typeof value === 'string') {
this.targetN.placeHolder = value;
this.setDirtyFlag();
}
else {
cc.error('The new placeHolder must be String');
}
}
},
fontSize: {
get: function () {
return this.targetN.fontSize;
},
set: function (value) {
if ( !isNaN(value) ) {
this.targetN.fontSize = value;
this.setDirtyFlag();
}
else {
cc.error('The new fontSize must not be NaN');
}
}
},
font: {
default: null,
type: cc.TTFFont,
notify: function () {
if ( !this.targetN ) return;
var value = this.font;
if (!value || value instanceof cc.TTFFont) {
Utils.setFontToNode(value, this.targetN);
this.setDirtyFlag();
}
else {
cc.error('The new font must be cc.TTFFont');
}
}
},
fontFamily: {
get: function () {
return this.targetN.fontName;
},
set: function (value) {
if (typeof value === 'string') {
this.targetN.fontName = value;
this.setDirtyFlag();
}
else {
cc.error('The new fontFamily must be String');
}
}
},
maxLengthEnabled: {
get: function () {
return this.targetN.maxLengthEnabled;
},
set: function (value) {
if (typeof value === 'boolean') {
this.targetN.maxLengthEnabled = value;
this.setDirtyFlag();
}
else {
cc.error('The new maxLengthEnabled must be boolean');
}
}
},
maxLength: {
get: function () {
return this.targetN.maxLength;
},
set: function (value) {
if (typeof value === 'number') {
this.targetN.maxLength = value;
this.setDirtyFlag();
}
else {
cc.error('The new maxLength must be String');
}
}
},
passwordEnabled: {
get: function () {
return this.targetN.passwordEnabled;
},
set: function (value) {
if (typeof value === 'boolean') {
var targetN = this.targetN;
targetN.passwordEnabled = value;
this.text = this.text;
}
else {
cc.error('The new passwordEnabled must be boolean');
}
}
},
_text: {
default: ''
},
_placeHolder: {
default: 'Input Something'
},
_fontSize: {
default: 16
},
_fontFamily: {
default: null
},
_maxLengthEnabled: {
default: false
},
_maxLength: {
default: 0
},
_passwordEnabled: {
default: false
}
},
onSizeChanged: function () {
WidgetWrapper.prototype.onSizeChanged.call(this);
this.setDirtyFlag();
},
setDirtyFlag: function () {
cc.renderer.childrenOrderDirty = true;
},
onBeforeSerialize: function () {
WidgetWrapper.prototype.onBeforeSerialize.call(this);
this._text = this.text;
this._placeHolder = this.placeHolder;
this._fontSize = this.fontSize;
this._fontFamily = this.fontFamily;
this._maxLengthEnabled = this.maxLengthEnabled;
this._passwordEnabled = this.passwordEnabled;
if (this.maxLengthEnabled) this._maxLength = this.maxLength;
},
createNode: function (node) {
node = node || new ccui.TextField();
node.ignoreContentAdaptWithSize(false);
WidgetWrapper.prototype.createNode.call(this, node);
node.passwordEnabled = this._passwordEnabled;
node.string = this._text;
node.placeHolder = this._placeHolder;
node.fontSize = this._fontSize;
node.fontFamily = this._fontFamily;
node.maxLengthEnabled = this._maxLengthEnabled;
if (this._maxLengthEnabled) node.maxLength = this._maxLength;
Utils.setFontToNode(this.font, node);
return node;
}
});
cc.TextFieldWrapper = module.exports = TextFieldWrapper;
+1 -1
View File
@@ -3,7 +3,7 @@ module.exports = {
setFontToNode: function(fontAsset, node) {
if (fontAsset) {
var config = {type:'font', name: fontAsset.fontFamily, srcs:[fontAsset.url]};
cc.loader.load(config, function (err, results) {
cc.loader.load(config, function (err, result) {
if (err) throw err;
node.fontName = config.name;
+1 -4
View File
@@ -518,9 +518,6 @@ cc.Follow = cc.Action.extend({
tempPosX = this._halfScreenSize.x - tempPosX;
tempPosY = this._halfScreenSize.y - tempPosY;
//TODO Temporary treatment - The dirtyFlag symbol error
this.target._renderCmd._dirtyFlag = 0;
if (this._boundarySet) {
// whole map fits inside a single screen, no need to modify the position - unless map boundaries are increased
if (this._boundaryFullyCovered)
@@ -533,7 +530,7 @@ cc.Follow = cc.Action.extend({
},
isDone:function () {
return ( !this._followedNode.running );
return ( !this._followedNode.isRunning() );
},
stop:function () {
+2 -2
View File
@@ -251,7 +251,7 @@ cc.FlipX = cc.ActionInstant.extend({
},
update:function (dt) {
this.target.flippedX = this._flippedX;
this.target.scaleX = Math.abs(this.target.scaleX) * (this._flippedX ? 1 : -1);
},
reverse:function () {
@@ -309,7 +309,7 @@ cc.FlipY = cc.ActionInstant.extend({
},
update:function (dt) {
this.target.flippedY = this._flippedY;
this.target.scaleY = Math.abs(this.target.scaleY) * (this._flippedX ? 1 : -1);
},
reverse:function () {
+6 -5
View File
@@ -1998,17 +1998,17 @@ cc.Blink = cc.ActionInterval.extend({
if (this.target && !this.isDone()) {
var slice = 1.0 / this._times;
var m = dt % slice;
this.target.visible = (m > (slice / 2));
this.target.opacity = (m > (slice / 2)) ? 255 : 0;
}
},
startWithTarget:function (target) {
cc.ActionInterval.prototype.startWithTarget.call(this, target);
this._originalState = target.visible;
this._originalState = target.opacity;
},
stop:function () {
this.target.visible = this._originalState;
this.target.opacity = this._originalState;
cc.ActionInterval.prototype.stop.call(this);
},
@@ -2496,8 +2496,9 @@ cc.reverseTime = function (action) {
};
cc.ReverseTime.create = cc.reverseTime;
/* Animates a sprite given the name of an Animation
/**
* This API is deprecated, will be replaced by new API from {{#crossLink "Animation"}}cc.Animation{{/crossLink}}
* Animates a sprite given the name of an Animation
* @class Animate
* @extends ActionInterval
* @param {SpriteFrameAnimation} animation
+3 -5
View File
@@ -95,11 +95,9 @@ p.onResume = function () {
}
};
if (CC_DEV) {
p.reloadClip = function (state) {
initClipData(this.target, state);
};
}
p._reloadClip = function (state) {
initClipData(this.target, state);
};
// 这个方法应该是 SampledAnimCurve 才能用
function createBatchedProperty (propPath, firstDotIndex, mainValue, animValue) {
+5 -1
View File
@@ -17,6 +17,7 @@ var AnimationClip = cc.Class({
/**
* Duration of this animation
* @property duration
* @type {Number}
*/
duration: {
@@ -25,6 +26,7 @@ var AnimationClip = cc.Class({
/**
* FrameRate of this animation
* @property sample
* @type {Number}
*/
sample: {
@@ -33,6 +35,7 @@ var AnimationClip = cc.Class({
/**
* Speed of this animation
* @property speed
* @type {Number}
*/
speed: {
@@ -41,7 +44,8 @@ var AnimationClip = cc.Class({
/**
* WrapMode of this animation
* @type {cc.WrapMode}
* @property wrapMode
* @type {WrapMode}
*/
wrapMode: {
default: cc.WrapMode.Normal
+1
View File
@@ -205,6 +205,7 @@ DynamicAnimCurve.Bezier = function (controlPoints) {
* 所以 SampledAnimCurve 中查找 frame index 的速度会非常快
*
* @class SampledAnimCurve
* @private
* @constructor
* @extends DynamicAnimCurve
*/
+44 -322
View File
@@ -24,147 +24,44 @@
THE SOFTWARE.
****************************************************************************/
/**
* Audio support in the browser
*
* MULTI_CHANNEL : Multiple audio while playing - If it doesn't, you can only play background music
* WEB_AUDIO : Support for WebAudio - Support W3C WebAudio standards, all of the audio can be played
* AUTOPLAY : Supports auto-play audio - if Don‘t support it, On a touch detecting background music canvas, and then replay
* REPLAY_AFTER_TOUCH : The first music will fail, must be replay after touchstart
* USE_EMPTIED_EVENT : Whether to use the emptied event to replace load callback
* DELAY_CREATE_CTX : delay created the context object - only webAudio
* NEED_MANUAL_LOOP : WebAudio loop attribute failure, need to manually perform loop
*
* May be modifications for a few browser version
*/
(function(){
var DEBUG = false;
var sys = cc.sys;
var version = sys.browserVersion;
// check if browser supports Web Audio
// check Web Audio's context
var supportWebAudio = !!(window.AudioContext || window.webkitAudioContext || window.mozAudioContext);
var supportTable = {
"common" : {MULTI_CHANNEL: true , WEB_AUDIO: supportWebAudio , AUTOPLAY: true }
};
supportTable[sys.BROWSER_TYPE_IE] = {MULTI_CHANNEL: true , WEB_AUDIO: supportWebAudio , AUTOPLAY: true, USE_EMPTIED_EVENT: true};
// ANDROID //
supportTable[sys.BROWSER_TYPE_ANDROID] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false};
supportTable[sys.BROWSER_TYPE_CHROME] = {MULTI_CHANNEL: true , WEB_AUDIO: true , AUTOPLAY: false};
supportTable[sys.BROWSER_TYPE_FIREFOX] = {MULTI_CHANNEL: true , WEB_AUDIO: true , AUTOPLAY: true , DELAY_CREATE_CTX: true};
supportTable[sys.BROWSER_TYPE_UC] = {MULTI_CHANNEL: true , WEB_AUDIO: false, AUTOPLAY: false};
supportTable[sys.BROWSER_TYPE_QQ] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: true };
supportTable[sys.BROWSER_TYPE_OUPENG] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true };
supportTable[sys.BROWSER_TYPE_WECHAT] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true };
supportTable[sys.BROWSER_TYPE_360] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: true };
supportTable[sys.BROWSER_TYPE_MIUI] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: true };
supportTable[sys.BROWSER_TYPE_LIEBAO] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true };
supportTable[sys.BROWSER_TYPE_SOUGOU] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true };
//"Baidu" browser can automatically play
//But because it may be play failed, so need to replay and auto
supportTable[sys.BROWSER_TYPE_BAIDU] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true };
supportTable[sys.BROWSER_TYPE_BAIDU_APP]= {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true };
// APPLE //
supportTable[sys.BROWSER_TYPE_SAFARI] = {MULTI_CHANNEL: true , WEB_AUDIO: true , AUTOPLAY: false, webAudioCallback: function(realUrl){
document.createElement("audio").src = realUrl;
}};
if(cc.sys.isMobile){
if(cc.sys.os !== cc.sys.OS_IOS)
window.__audioSupport = supportTable[sys.browserType] || supportTable["common"];
else
window.__audioSupport = supportTable[sys.BROWSER_TYPE_SAFARI];
}else{
switch(sys.browserType){
case sys.BROWSER_TYPE_IE:
window.__audioSupport = supportTable[sys.BROWSER_TYPE_IE];
break;
case sys.BROWSER_TYPE_FIREFOX:
window.__audioSupport = supportTable[sys.BROWSER_TYPE_FIREFOX];
break;
default:
window.__audioSupport = supportTable["common"];
}
}
///////////////////////////
// Browser compatibility//
///////////////////////////
if(version){
switch(sys.browserType){
case sys.BROWSER_TYPE_CHROME:
version = parseInt(version);
if(version < 30){
window.__audioSupport = {MULTI_CHANNEL: false , WEB_AUDIO: true , AUTOPLAY: false};
}else if(version === 42){
window.__audioSupport.NEED_MANUAL_LOOP = true;
}
break;
case sys.BROWSER_TYPE_MIUI:
if(cc.sys.isMobile){
version = version.match(/\d+/g);
if(version[0] < 2 || (version[0] === 2 && version[1] === 0 && version[2] <= 1)){
window.__audioSupport.AUTOPLAY = false;
}
}
break;
}
}
if(DEBUG){
setTimeout(function(){
cc.log("browse type: " + sys.browserType);
cc.log("browse version: " + version);
cc.log("MULTI_CHANNEL: " + window.__audioSupport.MULTI_CHANNEL);
cc.log("WEB_AUDIO: " + window.__audioSupport.WEB_AUDIO);
cc.log("AUTOPLAY: " + window.__audioSupport.AUTOPLAY);
}, 0);
}
})();
var JS = require('../core/platform/js');
/**
* Encapsulate DOM and webAudio
*/
cc.Audio = cc._Class.extend({
cc.Audio = function (context, volume, url) {
//TODO Maybe loader shift in will be better
volume: 1,
loop: false,
src: null,
_touch: false,
this.volume = 1;
this.loop = false;
this._touch = false;
_playing: false,
_AUDIO_TYPE: "AUDIO",
_pause: false,
this._playing = false;
this._AUDIO_TYPE = "AUDIO";
this._pause = false;
//Web Audio
_buffer: null,
_currentSource: null,
_startTime: null,
_currentTime: null,
_context: null,
_volume: null,
this._buffer = null;
this._currentSource = null;
this._startTime = null;
this._currentTime = null;
this._context = null;
this._volume = null;
_ignoreEnded: false,
_manualLoop: false,
this._ignoreEnded = false;
this._manualLoop = false;
//DOM Audio
_element: null,
this._element = null;
ctor: function(context, volume, url){
context && (this._context = context);
volume && (this._volume = volume);
if(context && volume){
this._AUDIO_TYPE = "WEBAUDIO";
}
this.src = url;
},
context && (this._context = context);
volume && (this._volume = volume);
if (context && volume) {
this._AUDIO_TYPE = "WEBAUDIO";
}
this.src = url;
};
JS.mixin(cc.Audio.prototype, {
_setBufferCallback: null,
setBuffer: function(buffer){
if(!buffer) return;
@@ -440,190 +337,6 @@ cc.Audio = cc._Class.extend({
SWB = polyfill.MULTI_CHANNEL,
SWC = polyfill.AUTOPLAY;
var support = [];
(function(){
var audio = document.createElement("audio");
if(audio.canPlayType) {
var ogg = audio.canPlayType('audio/ogg; codecs="vorbis"');
if (ogg && ogg !== "") support.push(".ogg");
var mp3 = audio.canPlayType("audio/mpeg");
if (mp3 && mp3 !== "") support.push(".mp3");
var wav = audio.canPlayType('audio/wav; codecs="1"');
if (wav && wav !== "") support.push(".wav");
var mp4 = audio.canPlayType("audio/mp4");
if (mp4 && mp4 !== "") support.push(".mp4");
var m4a = audio.canPlayType("audio/x-m4a");
if (m4a && m4a !== "") support.push(".m4a");
}
})();
try{
if(SWA){
var context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
if(polyfill.DELAY_CREATE_CTX)
setTimeout(function(){ context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); }, 0);
}
}catch(error){
SWA = false;
cc.log("browser don't support web audio");
}
var loader = {
cache: {},
load: function(realUrl, url, res, cb){
if(support.length === 0)
return cb("can not support audio!");
var i;
if(cc.loader.audioPath)
realUrl = cc.path.join(cc.loader.audioPath, realUrl);
var extname = cc.path.extname(realUrl);
var typeList = [extname];
for(i=0; i<support.length; i++){
if(extname !== support[i]){
typeList.push(support[i]);
}
}
var audio;
if(loader.cache[url])
return cb(null, loader.cache[url]);
if(SWA){
try{
var volume = context["createGain"]();
volume["gain"].value = 1;
volume["connect"](context["destination"]);
audio = new cc.Audio(context, volume, realUrl);
if(polyfill.NEED_MANUAL_LOOP)
audio._manualLoop = true;
}catch(err){
SWA = false;
cc.log("browser don't support web audio");
audio = new cc.Audio(null, null, realUrl);
}
}else{
audio = new cc.Audio(null, null, realUrl);
}
this.loadAudioFromExtList(realUrl, typeList, audio, cb);
loader.cache[url] = audio;
},
loadAudioFromExtList: function(realUrl, typeList, audio, cb){
if(typeList.length === 0){
var ERRSTR = "can not found the resource of audio! Last match url is : ";
ERRSTR += realUrl.replace(/\.(.*)?$/, "(");
support.forEach(function(ext){
ERRSTR += ext + "|";
});
ERRSTR = ERRSTR.replace(/\|$/, ")");
return cb({status:520, errorMessage:ERRSTR}, null);
}
realUrl = cc.path.changeExtname(realUrl, typeList.splice(0, 1));
if(SWA){//Buffer
if(polyfill.webAudioCallback)
polyfill.webAudioCallback(realUrl);
var request = new XMLHttpRequest();
request.open("GET", realUrl, true);
request.responseType = "arraybuffer";
// Our asynchronous callback
request.onload = function () {
context["decodeAudioData"](request.response, function(buffer){
//success
audio.setBuffer(buffer);
cb(null, audio);
}, function(){
//error
loader.loadAudioFromExtList(realUrl, typeList, audio, cb);
});
};
request.onerror = function(){
cb({status:520, errorMessage:ERRSTR}, null);
};
request.send();
}else{//DOM
var element = document.createElement("audio");
var cbCheck = false;
var termination = false;
var timer = setTimeout(function(){
if(element.readyState === 0){
emptied();
}else{
termination = true;
element.pause();
document.body.removeChild(element);
cb("audio load timeout : " + realUrl, audio);
}
}, 10000);
var success = function(){
if(!cbCheck){
//element.pause();
try { element.currentTime = 0;
element.volume = 1; } catch (e) {}
document.body.removeChild(element);
audio.setElement(element);
element.removeEventListener("canplaythrough", success, false);
element.removeEventListener("error", failure, false);
element.removeEventListener("emptied", emptied, false);
!termination && cb(null, audio);
cbCheck = true;
clearTimeout(timer);
}
};
var failure = function(){
if(!cbCheck) return;
//element.pause();
document.body.removeChild(element);
element.removeEventListener("canplaythrough", success, false);
element.removeEventListener("error", failure, false);
element.removeEventListener("emptied", emptied, false);
!termination && loader.loadAudioFromExtList(realUrl, typeList, audio, cb);
cbCheck = true;
clearTimeout(timer);
};
var emptied = function(){
termination = true;
success();
cb(null, audio);
};
element.addEventListener("canplaythrough", success, false);
element.addEventListener("error", failure, false);
if(polyfill.USE_EMPTIED_EVENT)
element.addEventListener("emptied", emptied, false);
element.src = realUrl;
document.body.appendChild(element);
element.volume = 0;
//some browsers cannot pause(qq 6.1)
//element.play();
}
}
};
cc.loader.register(["mp3", "ogg", "wav", "mp4", "m4a"], loader);
/**
* cc.audioEngine is the singleton object, it provide simple audio APIs.
* @class audioEngine
@@ -656,10 +369,17 @@ cc.Audio = cc._Class.extend({
if(bgMusic && bgMusic.src !== url && bgMusic.getPlaying()){
bgMusic.stop();
}
var audio = loader.cache[url];
var audio = cc.loader.getRes(url);
if(!audio){
cc.loader.load(url);
audio = loader.cache[url];
var self = this;
cc.loader.load(url, function (error, audio) {
if (!error) {
audio.play(0, loop);
audio.setVolume(self._musicVolume);
self._currMusic = audio;
}
});
return;
}
audio.play(0, loop);
audio.setVolume(this._musicVolume);
@@ -806,14 +526,13 @@ cc.Audio = cc._Class.extend({
effectList = this._audioPool[url] = [];
}
var i;
for(i=0; i<effectList.length; i++){
for(var i=0; i<effectList.length; i++){
if(!effectList[i].getPlaying()){
break;
}
}
var audio;
if(effectList[i]){
audio = effectList[i];
audio.setVolume(this._effectVolume);
@@ -821,10 +540,14 @@ cc.Audio = cc._Class.extend({
}else if(!SWA && i > this._maxAudioInstance){
cc.log("Error: %s greater than %d", url, this._maxAudioInstance);
}else{
var audio = loader.cache[url];
audio = cc.loader.getRes(url);
if(!audio){
cc.loader.load(url);
audio = loader.cache[url];
var item = cc.loader.getItems().map[url];
audio = item ? item.content : null;
if (!audio) {
return;
}
}
audio = audio.cloneNode();
audio.setVolume(this._effectVolume);
@@ -983,7 +706,6 @@ cc.Audio = cc._Class.extend({
var pool = this._audioPool[url];
if(pool) pool.length = 0;
delete this._audioPool[url];
delete loader.cache[url];
},
/**
@@ -1051,4 +773,4 @@ cc.Audio = cc._Class.extend({
}, 150);
}
})(window.__audioSupport);
})(cc.sys.__audioSupport);
+5 -4
View File
@@ -27,6 +27,7 @@
/**
* @class HashElement
* @extends cc._Class
* @private
* @example
* var element = new cc.HashElement();
*/
@@ -91,8 +92,8 @@ cc.ActionManager = cc._Class.extend(/** @lends cc.ActionManager# */{
* If the target is not present, a new instance of this target will be created either paused or not, and the action will be added to the newly created target.
* When the target is paused, the queued actions won't be 'ticked'.
* @method addAction
* @param {cc.Action} action
* @param {cc.Node} target
* @param {Action} action
* @param {Node} target
* @param {Boolean} paused
*/
addAction:function (action, target, paused) {
@@ -155,7 +156,7 @@ cc.ActionManager = cc._Class.extend(/** @lends cc.ActionManager# */{
},
/** Removes an action given an action reference.
* @method removeAction
* @param {cc.Action} action
* @param {Action} action
*/
removeAction:function (action) {
// explicit null handling
@@ -205,7 +206,7 @@ cc.ActionManager = cc._Class.extend(/** @lends cc.ActionManager# */{
* @method getActionByTag
* @param {Number} tag
* @param {object} target
* @return {cc.Action|Null} return the Action with the given tag on success
* @return {Action|Null} return the Action with the given tag on success
*/
getActionByTag:function (tag, target) {
if(tag === cc.ACTION_TAG_INVALID)
+11 -46
View File
@@ -617,43 +617,6 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
}
},
// load raw assets
_loadRawAssets: function (assetObjects, done) {
var urls = assetObjects.map(function (asset) {
return asset.url;
});
//var info = 'preload ' + urls;
//console.time(info);
// currently cocos jsb 3.3 not support preload too much assets
// so we divide assets to 30 a group
var index = 0;
var count = 30;
var total = urls.length;
function preload () {
if (index + count > total) {
// the last time
count = total - index;
}
var assets = urls.slice(index, count);
index += count;
if (index < total) {
cc.loader.load(assets, preload);
}
else {
//console.timeEnd(info);
done();
}
}
preload();
},
/**
* Loads the scene by its uuid.
* @method _loadSceneByUuid
@@ -664,7 +627,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
*/
_loadSceneByUuid: function (uuid, onLaunched, onUnloaded) {
//cc.AssetLibrary.unloadAsset(uuid); // force reload
var handle = cc.AssetLibrary.loadAsset(uuid, function (error, sceneAsset) {
cc.AssetLibrary.loadAsset(uuid, function (error, sceneAsset) {
var self = cc.director;
var scene;
if (error) {
@@ -684,10 +647,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
scene = sceneAsset;
}
if (scene instanceof cc.Scene) {
self._loadRawAssets(handle.assetsNeedPostLoad,
function () {
self.runScene(scene, onUnloaded);
});
self.runScene(scene, onUnloaded);
}
else {
error = 'The asset ' + uuid + ' is not a scene';
@@ -699,7 +659,7 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
if (onLaunched) {
onLaunched(error, scene);
}
}, { recordAssets: true });
});
},
/**
@@ -889,8 +849,10 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
},
/**
* Returns current running Scene. Director can only run one Scene at the time.
* Returns current render Scene, normally you will never need to use this API.
* In most case, you probably want to use `getScene` instead.
* @method getRunningScene
* @private
* @return {Scene}
*/
getRunningScene: function () {
@@ -898,7 +860,10 @@ cc.Director = Class.extend(/** @lends cc.Director# */{
},
/**
* Returns current running Scene. Director can only run one Scene at the time.
* Returns current logic Scene.
* @example
* // This will help you to get the Canvas node in scene
* cc.director.getScene().getChildByName('Canvas');
* @method getScene
* @return {Scene}
*/
@@ -1101,7 +1066,7 @@ cc.Director.EVENT_BEFORE_SCENE_LAUNCH = "director_before_scene_launch";
/**
* @event EVENT_AFTER_SCENE_LAUNCH
* @param {cc.Scene} newScene
* @param {Scene} newScene
*/
cc.Director.EVENT_AFTER_SCENE_LAUNCH = "director_after_scene_launch";
+1 -1
View File
@@ -31,7 +31,7 @@ cc.PI2 = Math.PI * 2;
/**
* Canvas of DrawingPrimitive implement version use for canvasMode
* @class
* @class DrawingPrimitiveCanvas
* @extends cc._Class
* @param {CanvasRenderingContext2D} renderContext
*/
+1 -1
View File
@@ -450,7 +450,7 @@ cc.DrawingPrimitiveWebGL = cc._Class.extend(/** @lends cc.DrawingPrimitiveWebGL#
* @param {Number} pointSize
*/
setPointSize:function (pointSize) {
this._pointSize = pointSize * cc.contentScaleFactor();
this._pointSize = pointSize;
},
/**
+47 -15
View File
@@ -2,7 +2,7 @@ var EventTarget = require('./event/event-target');
/**
* An object to boot the game.
* @class game
* @class Game
*/
var game = /** @lends cc.game# */{
@@ -78,7 +78,31 @@ var game = /** @lends cc.game# */{
canvas: null,
/**
* Config of game
* The current game configuration, including:
* 1. debugMode
* "debugMode" possible values :
* 0 - No message will be printed.
* 1 - cc.error, cc.assert, cc.warn, cc.log will print in console.
* 2 - cc.error, cc.assert, cc.warn will print in console.
* 3 - cc.error, cc.assert will print in console.
* 4 - cc.error, cc.assert, cc.warn, cc.log will print on canvas, available only on web.
* 5 - cc.error, cc.assert, cc.warn will print on canvas, available only on web.
* 6 - cc.error, cc.assert will print on canvas, available only on web.
* 2. showFPS
* Left bottom corner fps information will show when "showFPS" equals true, otherwise it will be hide.
* 3. frameRate
* "frameRate" set the wanted frame rate for your game, but the real fps depends on your game implementation and the running environment.
* 4. id
* "gameCanvas" sets the id of your canvas element on the web page, it's useful only on web.
* 5. renderMode
* "renderMode" sets the renderer type, only useful on web :
* 0 - Automatically chosen by engine
* 1 - Forced to use canvas renderer
* 2 - Forced to use WebGL renderer, but this will be ignored on mobile browsers
* 6. scenes
* "scenes" include available scenes in the current bundle.
*
* Please DO NOT modify this object directly, it won't have any effect.
* @property config
* @type {Object}
*/
@@ -201,18 +225,17 @@ var game = /** @lends cc.game# */{
this._initRenderer(config[CONFIG_KEY.width], config[CONFIG_KEY.height]);
/**
* @type {cc.EGLView}
* @name cc.view
* @memberof cc
* cc.view is the shared view object.
*/
cc.view = cc.EGLView._getInstance();
/**
* @module cc
*/
/**
* cc.view is the shared view object.
* @property view
* @type View
*/
cc.view = cc.EGLView._getInstance();
/**
* @property director
* @type Director
@@ -223,7 +246,7 @@ var game = /** @lends cc.game# */{
/**
* cc.winSize is the alias object for the size of the current game window.
* @property winSize
* @type cc.Size
* @type Size
*/
cc.winSize = cc.director.getWinSize();
@@ -236,9 +259,9 @@ var game = /** @lends cc.game# */{
// Load game scripts
var jsList = config[CONFIG_KEY.jsList];
if (jsList) {
cc.loader.loadJsWithImg(jsList, function (err) {
if (err) throw new Error(err);
if (jsList && jsList.length > 0) {
cc.loader.load(jsList, function (err) {
if (err) throw new Error(JSON.stringify(err));
self._prepared = true;
if (cb) cb();
});
@@ -257,7 +280,8 @@ var game = /** @lends cc.game# */{
},
/**
* @class game
* cc.game is the singleton object for game related functions.
* @class Game
*/
/**
@@ -616,4 +640,12 @@ var game = /** @lends cc.game# */{
EventTarget.call(game);
cc.js.addon(game, EventTarget.prototype);
/**
* @module cc
*/
/**
* @property game
* @type Game
*/
cc.game = module.exports = game;
+86 -48
View File
@@ -34,7 +34,7 @@ var DontDestroy = Flags.DontDestroy;
/**
* The event type supported by Node
* @class Node.EventType
* @enum Node.EventType
* @static
* @namespace Node
*/
@@ -43,7 +43,7 @@ var EventType = cc.Enum({
* The event type for touch start event, you can use its value directly: 'touchstart'
* @property TOUCH_START
* @type {String}
* @readonly
* @static
*/
TOUCH_START: 'touchstart',
/**
@@ -51,21 +51,21 @@ var EventType = cc.Enum({
* @property TOUCH_MOVE
* @type {String}
* @value 1
* @readonly
* @static
*/
TOUCH_MOVE: 'touchmove',
/**
* The event type for touch end event, you can use its value directly: 'touchend'
* @property TOUCH_END
* @type {String}
* @readonly
* @static
*/
TOUCH_END: 'touchend',
/**
* The event type for touch end event, you can use its value directly: 'touchcancel'
* @property TOUCH_CANCEL
* @type {String}
* @readonly
* @static
*/
TOUCH_CANCEL: 'touchcancel',
@@ -73,42 +73,42 @@ var EventType = cc.Enum({
* The event type for mouse down events, you can use its value directly: 'mousedown'
* @property MOUSE_DOWN
* @type {String}
* @readonly
* @static
*/
MOUSE_DOWN: 'mousedown',
/**
* The event type for mouse move events, you can use its value directly: 'mousemove'
* @property MOUSE_MOVE
* @type {String}
* @readonly
* @static
*/
MOUSE_MOVE: 'mousemove',
/**
* The event type for mouse enter target events, you can use its value directly: 'mouseenter'
* @property MOUSE_ENTER
* @type {String}
* @readonly
* @static
*/
MOUSE_ENTER: 'mouseenter',
/**
* The event type for mouse leave target events, you can use its value directly: 'mouseleave'
* @property MOUSE_LEAVE
* @type {String}
* @readonly
* @static
*/
MOUSE_LEAVE: 'mouseleave',
/**
* The event type for mouse up events, you can use its value directly: 'mouseup'
* @property MOUSE_UP
* @type {String}
* @readonly
* @static
*/
MOUSE_UP: 'mouseup',
/**
* The event type for mouse wheel events, you can use its value directly: 'mousewheel'
* @property MOUSE_WHEEL
* @type {String}
* @readonly
* @static
*/
MOUSE_WHEEL: 'mousewheel',
});
@@ -128,6 +128,8 @@ var _mouseEvents = [
EventType.MOUSE_WHEEL,
];
var currentHovered = null;
var _touchStartHandler = function (touch, event) {
var pos = touch.getLocation();
var node = this.owner;
@@ -179,6 +181,13 @@ var _mouseMoveHandler = function (event) {
if (node._hitTest(pos, this)) {
event.stopPropagation();
if (!this._previousIn) {
// Fix issue when hover node switched, previous hovered node won't get MOUSE_LEAVE notification
if (currentHovered) {
event.type = EventType.MOUSE_LEAVE;
currentHovered.owner.dispatchEvent(event);
currentHovered._previousIn = false;
}
currentHovered = this;
event.type = EventType.MOUSE_ENTER;
node.dispatchEvent(event);
this._previousIn = true;
@@ -190,6 +199,7 @@ var _mouseMoveHandler = function (event) {
event.type = EventType.MOUSE_LEAVE;
node.dispatchEvent(event);
this._previousIn = false;
currentHovered = null;
}
};
var _mouseUpHandler = function (event) {
@@ -233,7 +243,8 @@ var _searchMaskParent = function (node) {
/**
* Class of all entities in Fireball scenes.
* Class of all entities in Cocos Creator scenes.
* For events supported by Node, please refer to {{#crossLink "Node.EventType"}}{{/crossLink}}
*
* @class Node
* @extends _BaseNode
@@ -551,11 +562,11 @@ var Node = cc.Class({
}
}
// check conflict
if (CC_EDITOR && !_Scene.DetectConflict.beforeAddComponent(this, constructor)) {
return null;
}
//// check conflict
//
//if (CC_EDITOR && !_Scene.DetectConflict.beforeAddComponent(this, constructor)) {
// return null;
//}
//
@@ -635,8 +646,8 @@ var Node = cc.Class({
/**
* @method _getDependComponent
* @param {cc.Component} depended
* @return {cc.Component}
* @param {Component} depended
* @return {Component}
* @private
*/
_getDependComponent: CC_EDITOR && function (depended) {
@@ -697,9 +708,11 @@ var Node = cc.Class({
var originCount = this._components.length;
for (var c = 0; c < originCount; ++c) {
var component = this._components[c];
if (! (component instanceof cc.Component) && CC_EDITOR) {
cc.error('Sorry, the component of entity "%s" which with an index of %s is corrupted! It has been removed.\nSee DevTools for details.', this.name, c);
console.log('Corrupted component value:', component);
if ( !(component instanceof cc.Component) ) {
if (CC_EDITOR) {
cc.error('Sorry, the component of "%s" which with an index of %s is corrupted! It has been removed.', this.name, c);
console.log('Corrupted component value:', component);
}
if (component) {
this._removeComponent(component);
}
@@ -765,17 +778,20 @@ var Node = cc.Class({
if (myPrefabInfo) {
if (newPrefabRoot) {
// change prefab
Editor.PrefabUtils.linkPrefab(newPrefabRoot._prefab.asset, newPrefabRoot, this);
_Scene.PrefabUtils.linkPrefab(newPrefabRoot._prefab.asset, newPrefabRoot, this);
}
else if (myPrefabInfo.root !== this) {
// detach from prefab
Editor.PrefabUtils.unlinkPrefab(this);
_Scene.PrefabUtils.unlinkPrefab(this);
}
}
else if (newPrefabRoot) {
// attach to prefab
Editor.PrefabUtils.linkPrefab(newPrefabRoot._prefab.asset, newPrefabRoot, this);
_Scene.PrefabUtils.linkPrefab(newPrefabRoot._prefab.asset, newPrefabRoot, this);
}
// conflict detection
_Scene.DetectConflict.afterAddChild(this);
}
},
@@ -812,7 +828,7 @@ var Node = cc.Class({
// update components if also in scene graph
for (var c = 0; c < this._components.length; ++c) {
var comp = this._components[c];
if (comp instanceof cc._ComponentInSG && comp.isValid && comp._sgNode) {
if (comp instanceof cc._SGComponent && comp.isValid && comp._sgNode) {
comp._sgNode.setColor(this._color);
if ( !this._cascadeOpacityEnabled ) {
comp._sgNode.setOpacity(this._opacity);
@@ -826,7 +842,7 @@ var Node = cc.Class({
var opacity = this._cascadeOpacityEnabled ? 255 : this._opacity;
for (var c = 0; c < this._components.length; ++c) {
var comp = this._components[c];
if (comp instanceof cc._ComponentInSG && comp.isValid && comp._sgNode) {
if (comp instanceof cc._SGComponent && comp.isValid && comp._sgNode) {
comp._sgNode.setOpacity(opacity);
}
}
@@ -836,9 +852,9 @@ var Node = cc.Class({
// update components if also in scene graph
for (var c = 0; c < this._components.length; ++c) {
var comp = this._components[c];
if (comp instanceof cc._ComponentInSG && comp.isValid && comp._sgNode) {
if (comp instanceof cc._SGComponent && comp.isValid && comp._sgNode) {
comp._sgNode.setAnchorPoint(this._anchorPoint);
comp._sgNode.ignoreAnchorPointForPosition(this._ignoreAnchorPointForPosition);
comp._sgNode.ignoreAnchorPointForPosition(this.__ignoreAnchor);
}
}
},
@@ -846,7 +862,7 @@ var Node = cc.Class({
_onOpacityModifyRGBChanged: function () {
for (var c = 0; c < this._components.length; ++c) {
var comp = this._components[c];
if (comp instanceof cc._ComponentInSG && comp.isValid && comp._sgNode) {
if (comp instanceof cc._SGComponent && comp.isValid && comp._sgNode) {
comp._sgNode.setOpacityModifyRGB(this._opacityModifyRGB);
}
}
@@ -966,7 +982,7 @@ var Node = cc.Class({
apy = this._anchorPoint.y,
w = this.width,
h = this.height;
var rect = cc.rect(-apx * w, -apy * h, w, h);
var rect = cc.rect(0, 0, w, h);
var trans = this.getNodeToWorldTransform();
cc._rectApplyAffineTransformIn(rect, trans);
var left = point.x - rect.x,
@@ -1018,8 +1034,8 @@ var Node = cc.Class({
* The node becomes the action's target. Refer to cc.Action's getTarget()
* Calling runAction while the node is not active won't have any effect
* @method runAction
* @param {cc.Action} action
* @return {cc.Action} An Action pointer
* @param {Action} action
* @return {Action} An Action pointer
*/
runAction: function (action) {
if (!this.active)
@@ -1028,6 +1044,7 @@ var Node = cc.Class({
if (cc.sys.isNative) {
this._retainAction(action);
this._sgNode._owner = this;
}
cc.director.getActionManager().addAction(action, this, false);
return action;
@@ -1044,7 +1061,7 @@ var Node = cc.Class({
/**
* Stops and removes an action from the running action list.
* @method stopAction
* @param {cc.Action} action An action object to be removed.
* @param {Action} action An action object to be removed.
*/
stopAction: function (action) {
cc.director.getActionManager().removeAction(action);
@@ -1068,7 +1085,7 @@ var Node = cc.Class({
* @method getActionByTag
* @see cc.Action#getTag and cc.Action#setTag
* @param {Number} tag
* @return {cc.Action} The action object with the given tag.
* @return {Action} The action object with the given tag.
*/
getActionByTag: function (tag) {
if (tag === cc.ACTION_TAG_INVALID) {
@@ -1135,45 +1152,66 @@ if (cc.sys.isNative) {
/**
* @event position-changed
* @param {cc.Event} event
* @param {cc.Vec2} event.detail - old position
* @param {Event} event
* @param {Vec2} event.detail - old position
*/
/**
* @event rotation-changed
* @param {cc.Event} event
* @param {Event} event
* @param {Number} event.detail - old rotation x
*/
/**
* @event scale-changed
* @param {cc.Event} event
* @param {cc.Vec2} event.detail - old scale
* @param {Event} event
* @param {Vec2} event.detail - old scale
*/
/**
* @event size-changed
* @param {cc.Event} event
* @param {cc.Size} event.detail - old size
* @param {Event} event
* @param {Size} event.detail - old size
*/
/**
* @event anchor-changed
* @param {cc.Event} event
* @param {cc.Vec2} event.detail - old anchor
* @param {Event} event
* @param {Vec2} event.detail - old anchor
*/
/**
* @event color-changed
* @param {cc.Event} event
* @param {cc.Color} event.detail - old color
* @param {Event} event
* @param {Color} event.detail - old color
*/
/**
* @event opacity-changed
* @param {cc.Event} event
* @param {Event} event
* @param {Number} event.detail - old opacity
*/
/**
* @event child-added
* @param {Event} event
* @param {Node} event.detail - child
*/
/**
* @event child-removed
* @param {Event} event
* @param {Node} event.detail - child
*/
/**
* @event child-reorder
* @param {Event} event
*/
/**
* Note: This event is only emitted from the top most node whose active value did changed,
* not including its child nodes.
* @event active-in-hierarchy-changed
* @param {cc.Event} event
* @param {Event} event
*/
/**
*
* @event touchstart
*
*/
Node.EventType = EventType;
cc.Node = module.exports = Node;
+16 -16
View File
@@ -39,10 +39,10 @@ cc.PRIORITY_NON_SYSTEM = cc.PRIORITY_SYSTEM + 1;
/**
* A list double-linked list used for "updates with priority"
* @class ListEntry
* @param {cc.ListEntry} prev
* @param {cc.ListEntry} next
* @param {ListEntry} prev
* @param {ListEntry} next
* @param {function} callback
* @param {cc._Class} target not retained (retained by hashUpdateEntry)
* @param {Object} target not retained (retained by hashUpdateEntry)
* @param {Number} priority
* @param {Boolean} paused
* @param {Boolean} markedForDeletion selector will no longer be called and entry will be removed at end of the next tick
@@ -64,8 +64,8 @@ cc.ListEntry.prototype.trigger = function (dt) {
* A update entry list
* @class HashUpdateEntry
* @param {Array} list Which list does it belong to ?
* @param {cc.ListEntry} entry entry in the list
* @param {cc._Class} target hash key (retained)
* @param {ListEntry} entry entry in the list
* @param {Object} target hash key (retained)
* @param {function} callback
* @param {Array} hh
*/
@@ -82,9 +82,9 @@ cc.HashUpdateEntry = function (list, entry, target, callback, hh) {
* Hash Element used for "selectors with interval"
* @class HashTimerEntry
* @param {Array} timers
* @param {cc._Class} target hash key (retained)
* @param {Object} target hash key (retained)
* @param {Number} timerIndex
* @param {cc.Timer} currentTimer
* @param {Timer} currentTimer
* @param {Boolean} currentTimerSalvaged
* @param {Boolean} paused
* @param {Array} hh
@@ -524,7 +524,7 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{
* </p>
* @method scheduleCallbackForTarget
* @deprecated since v3.4 please use .schedule
* @param {_Class} target
* @param {Object} target
* @param {function} callback_fn
* @param {Number} interval
* @param {Number} repeat
@@ -541,7 +541,7 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{
* The schedule
* @method schedule
* @param {Function} callback
* @param {_Class} target
* @param {Object} target
* @param {Number} interval
* @param {Number} repeat
* @param {Number} delay
@@ -918,7 +918,7 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{
* If the target is not present, nothing happens.
* </p>
* @method pauseTarget
* @param {_Class} target
* @param {Object} target
*/
pauseTarget:function (target) {
@@ -944,7 +944,7 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{
* The 'target' will be unpaused, so all schedule selectors/update will be 'ticked' again.<br/>
* If the target is not present, nothing happens.
* @method resumeTarget
* @param {_Class} target
* @param {Object} target
*/
resumeTarget:function (target) {
@@ -970,7 +970,7 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{
/**
* Returns whether or not the target is paused
* @method isTargetPaused
* @param {_Class} target
* @param {Object} target
* @return {Boolean}
*/
isTargetPaused:function (target) {
@@ -998,7 +998,7 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{
* </p>
* @method scheduleUpdateForTarget
* @deprecated since v3.4 please use .scheduleUpdate
* @param {_Class} target
* @param {Object} target
* @param {Number} priority
* @param {Boolean} paused
* @example {@link utils/api/engine/docs/cocos2d/core/CCScheduler/scheduleUpdateForTarget.js}
@@ -1015,7 +1015,7 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{
* </p>
* @method unscheduleCallbackForTarget
* @deprecated since v3.4 please use .unschedule
* @param {_Class} target
* @param {Object} target
* @param {Function} callback - callback[Function] or key[String]
* @example {@link utils/api/engine/docs/cocos2d/core/CCScheduler/unscheduleCallbackForTarget.js}
*/
@@ -1027,7 +1027,7 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{
/**
* Unschedules the update callback function for a given target
* @method unscheduleUpdateForTarget
* @param {_Class} target
* @param {Object} target
* @deprecated since v3.4 please use .unschedule
* @example {@link utils/api/engine/docs/cocos2d/core/CCScheduler/unscheduleUpdateForTarget.js}
*/
@@ -1040,7 +1040,7 @@ cc.Scheduler = cc._Class.extend(/** @lends cc.Scheduler# */{
* Unschedules all function callbacks for a given target. This also includes the "update" callback function.
* @method unscheduleAllCallbacksForTarget
* @deprecated since v3.4 please use .unscheduleAll
* @param {_Class} target
* @param {Object} target
*/
unscheduleAllCallbacksForTarget: function(target){
//cc.log("unscheduleAllCallbacksForTarget is deprecated. Please use unscheduleAll.");
+1 -1
View File
@@ -33,7 +33,7 @@ var Prefab = cc.Class({
var node = cc.instantiate(this.data);
if (CC_DEV) {
Editor.PrefabUtils.linkPrefab(this, node);
_Scene.PrefabUtils.linkPrefab(this, node);
}
return node;
-45
View File
@@ -1,45 +0,0 @@
/**
* Class for tiled map asset handling.
* @class TiledMapAsset
* @extends RawAsset
* @constructor
*/
var TiledMapAsset = cc.Class({
name: 'cc.TiledMapAsset',
extends: cc.RawAsset,
statics: {
createNodeByInfo: function (info, callback) {
if (CC_EDITOR) {
var Url = require('fire-url');
cc.TiledMapWrapper.preloadTmx( info.url , function (err, textures) {
if (err) {
callback(err);
return;
}
var node;
try {
node = new cc.TMXTiledMap(info.url);
node._file = info.url;
}
catch(e) {
return callback(e);
}
var wrapper = cc.getWrapper(node);
wrapper.name = Url.basenameNoExt(info.url);
wrapper._textures = textures;
return callback(null, node);
}.bind(this) );
}
}
}
});
cc.TiledMapAsset = TiledMapAsset;
module.exports = TiledMapAsset;
-1
View File
@@ -37,4 +37,3 @@ require('../textures/CCTexture2D');
require('./CCTTFFont');
require('./CCSpriteAnimation');
require('./CCSpriteAtlas');
require('./CCTiledMapAsset');
+1 -1
View File
@@ -88,7 +88,7 @@ cc.s_globalOrderOfArrival = 1;
* -# The node will be moved according to the camera values (camera) <br/>
* -# The grid will render the captured screen <br/></P>
*
* @class
* @class _ccsg.Node
* @extends cc._Class
*
* @property {Number} x - x axis position of node
+11 -3
View File
@@ -81,6 +81,10 @@ var Animation = cc.Class({
this._defaultClip = value;
if (!value) {
return;
}
var clips = this._clips;
for (var i = 0, l = clips.length; i < l; i++) {
@@ -302,6 +306,10 @@ var Animation = cc.Class({
state = this._nameToState[name];
}
if (state && !state.curveLoaded) {
this._animator._reloadClip(state);
}
return state || null;
},
@@ -415,7 +423,7 @@ var Animation = cc.Class({
state = new cc.AnimationState(clip);
if (CC_EDITOR) {
this._animator.reloadClip(state);
this._animator._reloadClip(state);
}
this._nameToState[state.name] = state;
@@ -428,7 +436,7 @@ var Animation = cc.Class({
state = new cc.AnimationState(this._defaultClip);
if (CC_EDITOR) {
this._animator.reloadClip(state);
this._animator._reloadClip(state);
}
this._nameToState[state.name] = state;
@@ -468,7 +476,7 @@ var Animation = cc.Class({
}
oldState._clip = clip;
this._animator.reloadClip(oldState);
this._animator._reloadClip(oldState);
}
});
+1 -1
View File
@@ -156,7 +156,7 @@ var AudioSource = cc.Class({
},
set: function (value) {
this._loop = value;
if (typeof this.audio === 'object') this.audio.loop = this._loop;
if (this.audio) this.audio.loop = this._loop;
},
animatable: false,
tooltip: 'i18n.COMPONENT.audio.loop'
+1 -17
View File
@@ -290,22 +290,6 @@ var Button = cc.Class({
this.node.on(cc.Node.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this);
},
_handleClickEvent: function () {
var events = this.clickEvents;
for (var i = 0, l = events.length; i < l; i++) {
var event = events[i];
var target = event.target;
if (!target) continue;
var comp = target.getComponent(event.component);
if (!comp) continue;
var handler = comp[event.handler];
if (!handler) continue;
handler.call(comp)
}
},
_cancelButtonClick: function(){
this._pressed = false;
},
@@ -341,7 +325,7 @@ var Button = cc.Class({
_onTouchEnded: function () {
if (this._pressed) {
this._handleClickEvent();
cc.Component.EventHandler.emitEvents(this.clickEvents);
}
this._pressed = false;
this._updateState();
+50 -19
View File
@@ -155,7 +155,7 @@ var _callLateUpdate = CC_EDITOR ? function (event) {
// Yes, the id might have a conflict problem once every 365 days
// if the game runs at 60 FPS and each frame 4760273 counts of new HashObject's id are requested.
var CompId = 0;
var IdPrefix = CC_DEV && ('Comp' + Editor.NonUuidMark);
var IdPrefix = CC_DEV && ('Comp' + Editor.UuidUtils.NonUuidMark);
var getNewId = CC_DEV && function () {
return IdPrefix + (++CompId);
};
@@ -175,8 +175,8 @@ var Component = cc.Class({
extends: cc.Object,
ctor: function () {
if (CC_EDITOR) {
Editor._AssetsWatcher.initComponent(this);
if (CC_EDITOR && !CC_TEST && window._Scene) {
_Scene.AssetsWatcher.initComponent(this);
}
// dont reset _id when destroyed
@@ -247,8 +247,8 @@ var Component = cc.Class({
get: function () {},
set: function (value) {
if (this.__scriptUuid !== value) {
if (value && Editor.isUuid(value._uuid)) {
var classId = Editor.compressUuid(value._uuid);
if (value && Editor.UuidUtils.isUuid(value._uuid)) {
var classId = Editor.UuidUtils.compressUuid(value._uuid);
var NewComp = cc.js._getClassById(classId);
if (cc.isChildClassOf(NewComp, cc.Component)) {
cc.warn('Sorry, replacing component script is not yet implemented.');
@@ -330,16 +330,6 @@ var Component = cc.Class({
__eventTargets: {
default: [],
serializable: false
},
/**
* Only for editor to calculate bounding box
*/
localSize: {
get: function () {
return cc.size(0, 0);
},
visible: false
}
},
@@ -405,7 +395,7 @@ var Component = cc.Class({
*/
onLostFocusInEditor: null,
//
// PUBLIC
/**
* Adds a component class to the entity. You can also add component to entity by passing in the name of the
@@ -500,7 +490,44 @@ var Component = cc.Class({
// return Timer.hasTimeoutKey(key);
//},
// OVERRIDES
// VIRTUAL
/**
* If the component's bounding box is different from the node's, you can implement this method to supply
* a custom axis aligned bounding box (AABB), so the editor's scene view can perform hit test properly.
*
* @method _getLocalBounds
* @param {Rect} out_rect - the Rect to receive the bounding box
*/
_getLocalBounds: null,
/**
* onRestore is called after the user clicks the Reset item in the Inspector's context menu or performs
* an undo operation on this component.
*
* If the component contains the "internal state", short for "temporary member variables which not included
* in its CCClass properties", then you may need to implement this function.
*
* The editor will call the getset accessors of your component to record/restore the component's state
* for undo/redo operation. However, in extreme cases, it may not works well. Then you should implement
* this function to manually synchronize your component's "internal states" with its public properties.
* Once you implement this function, all the getset accessors of your component will not be called when
* the user performs an undo/redo operation. Which means that only the properties with default value
* will be recorded or restored by editor.
*
* Similarly, the editor may failed to reset your component correctly in extreme cases. Then if you need
* to support the reset menu, you should manually synchronize your component's "internal states" with its
* properties in this function. Once you implement this function, all the getset accessors of your component
* will not be called during reset operation. Which means that only the properties with default value
* will be reset by editor.
*
* This function is only called in editor mode.
*
* @method onRestore
*/
onRestore: null,
// OVERRIDE
destroy: function () {
if (CC_EDITOR) {
@@ -537,7 +564,9 @@ var Component = cc.Class({
callOnLostFocusInTryCatch(this);
}
}
Editor._AssetsWatcher.start(this);
if ( !CC_TEST ) {
_Scene.AssetsWatcher.start(this);
}
}
if (this._enabled) {
@@ -577,7 +606,9 @@ var Component = cc.Class({
// onDestroy
if (CC_EDITOR) {
Editor._AssetsWatcher.stop(this);
if ( !CC_TEST ) {
_Scene.AssetsWatcher.stop(this);
}
if (cc.engine._isPlaying || this.constructor._executeInEditMode) {
if (this.onDestroy) {
callOnDestroyInTryCatch(this);
@@ -35,5 +35,40 @@ cc.Component.EventHandler = cc.Class({
handler: {
default: '',
}
},
statics: {
/**
* Emit events with params
* @method emitEvents
* @param {Array} events
* @param {*} params
*/
emitEvents: function(events, params) {
for (var i = 0, l = events.length; i < l; i++) {
var event = events[i];
if (! event instanceof cc.Component.EventHandler) continue;
event.emit(params);
}
}
},
/**
* Emit event with params
* @method emit
* @param {*} params
*/
emit: function(params) {
var target = this.target;
if (!cc.isValid(target)) return;
var comp = target.getComponent(this.component);
if (!cc.isValid(comp)) return;
var handler = comp[this.handler];
if (typeof(handler) !== 'function') return;
handler.call(comp, params);
}
});
-102
View File
@@ -1,102 +0,0 @@
var SceneGraphHelper = require('../utils/scene-graph-helper');
/**
* Component in scene graph.
* This is the base class for components which will attach a node to the cocos2d scene graph.
*
* You should override:
* - _createSgNode
*
* @class _ComponentInSG
* @extends Component
* @private
*/
var ComponentInSG = cc.Class({
extends: require('./CCComponent'),
editor: CC_EDITOR && {
executeInEditMode: true,
disallowMultiple: true
},
ctor: function () {
/**
* Reference to the instance of _ccsg.Node
* If it is possible to return null from your overloaded _createSgNode,
* then you should always check for null before using this property.
*
* @property {_ccsg.Node} _sgNode
* @private
*/
this._sgNode = this._createSgNode();
// retain immediately
// will be released in SceneGraphHelper.removeSgNode
this._sgNode.retain();
},
onLoad: function () {
var sgNode = this._sgNode;
this._initSgNode();
this._appendSgNode(sgNode);
if ( !this.node._sizeProvider ) {
this.node._sizeProvider = sgNode;
}
},
onEnable: function () {
if (this._sgNode) {
this._sgNode.visible = true;
}
},
onDisable: function () {
if (this._sgNode) {
this._sgNode.visible = false;
}
},
onDestroy: function () {
if ( this.node._sizeProvider === this._sgNode ) {
this.node._sizeProvider = null;
}
this._removeSgNode();
},
/**
* Create and returns your new scene graph node (SGNode) to append to scene graph.
* You should call the setContentSize of the SGNode if its size should be the same with the node's.
*
* @method _createSgNode
* @return {_ccsg.Node}
* @private
*/
_createSgNode: null,
/**
* @method _initSgNode
* @private
*/
_initSgNode: null,
_removeSgNode: SceneGraphHelper.removeSgNode,
_appendSgNode: function (sgNode) {
var node = this.node;
sgNode.setColor(node._color);
if ( !node._cascadeOpacityEnabled ) {
sgNode.setOpacity(node._opacity);
}
sgNode.setAnchorPoint(node._anchorPoint);
sgNode.ignoreAnchorPointForPosition(node._ignoreAnchorPointForPosition);
sgNode.setOpacityModifyRGB(node._opacityModifyRGB);
// set z order to -1 to make sure component will rendered before all of its entity's children.
sgNode.setLocalZOrder(-1);
var sgParent = node._sgNode;
sgParent.addChild(sgNode);
}
});
cc._ComponentInSG = module.exports = ComponentInSG;
+82 -46
View File
@@ -31,11 +31,11 @@ var InputFlag = _ccsg.EditBox.InputFlag;
/**
* cc.EditBox is a component for inputing text, you can use it to gather small amounts of text from users.
* @class EditBox
* @extends _ComponentInSG
* @extends _RendererUnderSG
*/
var EditBox = cc.Class({
name: 'cc.EditBox',
extends: cc._ComponentInSG,
extends: cc._RendererUnderSG,
editor: CC_EDITOR && {
menu: 'i18n:MAIN_MENU.component.ui/EditBox',
@@ -44,14 +44,19 @@ var EditBox = cc.Class({
},
properties: {
_useOriginalSize: true,
_string: '',
/**
* Input string of EditBox.
* @property {String} string
*/
string: {
default: '',
notify: function() {
this._sgNode.string = this.string;
tooltip: 'i18n:COMPONENT.editbox.string',
get: function () {
return this._sgNode.string;
},
set: function(value) {
this._sgNode.string = this._string = value;
}
},
@@ -60,13 +65,20 @@ var EditBox = cc.Class({
* @property {cc.SpriteFrame} backGroundImage
*/
backgroundImage: {
tooltip: 'i18n:COMPONENT.editbox.backgroundImage',
default: null,
type: cc.SpriteFrame,
notify: function() {
var sgNode = this._sgNode;
var backgroundSprite = sgNode.getBackgroundSprite();
backgroundSprite.setSpriteFrame(this.backgroundImage);
backgroundSprite.setContentSize(sgNode.getContentSize());
if(this.backgroundImage) {
var sprite = this._createBackgroundSprite();
sprite.setSpriteFrame(this.backgroundImage);
sprite.setContentSize(sgNode.getContentSize());
}
else {
backgroundSprite.removeFromParent();
}
}
},
@@ -78,6 +90,8 @@ var EditBox = cc.Class({
*/
returnType: {
default: KeyboardReturnType.DEFAULT,
tooltip: 'i18n:COMPONENT.editbox.returnType',
displayName: 'KeyboardReturnType',
type: KeyboardReturnType,
notify: function() {
this._sgNode.returnType = this.returnType;
@@ -90,13 +104,13 @@ var EditBox = cc.Class({
* @default InputFlag.INITIAL_CAPS_ALL_CHARACTERS
*/
inputFlag: {
tooltip: 'i18n:COMPONENT.editbox.input_flag',
default: InputFlag.INITIAL_CAPS_ALL_CHARACTERS,
type: InputFlag,
notify: function() {
this._sgNode.inputFlag = this.inputFlag;
}
},
/**
* Set the input mode of the edit box.
* If you pass ANY, it will create a multiline EditBox.
@@ -104,6 +118,7 @@ var EditBox = cc.Class({
* @default InputMode.ANY
*/
inputMode: {
tooltip: 'i18n:COMPONENT.editbox.input_mode',
default: InputMode.ANY,
type: InputMode,
notify: function() {
@@ -116,17 +131,31 @@ var EditBox = cc.Class({
* @property {Number} fontSize
*/
fontSize: {
tooltip: 'i18n:COMPONENT.editbox.font_size',
default: 20,
notify: function() {
this._sgNode.fontSize = this.fontSize;
}
},
/**
* Change the lineHeight of displayed text.
* @property {Number} lineHeight
*/
lineHeight: {
tooltip: 'i18n:COMPONENT.editbox.line_height',
default: 40,
notify: function() {
this._sgNode.setLineHeight(this.lineHeight);
}
},
/**
* Font color of the input text.
* @property {cc.Color} fontColor
*/
fontColor: {
tooltip: 'i18n:COMPONENT.editbox.font_color',
default: cc.Color.WHITE,
notify: function() {
this._sgNode.fontColor = this.fontColor;
@@ -134,35 +163,38 @@ var EditBox = cc.Class({
},
/**
* The display text of placeHolder.
* @property {String} placeHolder
* The display text of placeholder.
* @property {String} placeholder
*/
placeHolder: {
placeholder: {
tooltip: 'i18n:COMPONENT.editbox.placeholder',
default: 'Enter text here...',
notify: function() {
this._sgNode.placeHolder = this.placeHolder;
this._sgNode.placeholder = this.placeholder;
}
},
/**
* The font size of placeHolder.
* @property {Number} placeHolderFontSize
* The font size of placeholder.
* @property {Number} placeholderFontSize
*/
placeHolderFontSize: {
placeholderFontSize: {
tooltip: 'i18n:COMPONENT.editbox.placeholder_font_size',
default: 20,
notify: function() {
this._sgNode.placeHolderFontSize = this.placeHolderFontSize;
this._sgNode.placeholderFontSize = this.placeholderFontSize;
}
},
/**
* The font color of placeHolder.
* @property {cc.Color} placeHolderFontColor
* The font color of placeholder.
* @property {cc.Color} placeholderFontColor
*/
placeHolderFontColor: {
placeholderFontColor: {
tooltip: 'i18n:COMPONENT.editbox.placeholder_font_color',
default: cc.Color.GRAY,
notify: function() {
this._sgNode.placeHolderFontColor = this.placeHolderFontColor;
this._sgNode.placeholderFontColor = this.placeholderFontColor;
}
},
@@ -171,6 +203,7 @@ var EditBox = cc.Class({
* @property {Number} maxLength
*/
maxLength: {
tooltip: 'i18n:COMPONENT.editbox.max_length',
default: 20,
notify: function() {
this._sgNode.maxLength = this.maxLength;
@@ -197,7 +230,7 @@ var EditBox = cc.Class({
/**
* The event handler to be called when EditBox edit ends.
* @property {cc.Component.EventHandler} editingDidEnd
* @property {cc.Component.EventHandler} editingDidEnded
*/
editingDidEnded: {
default: [],
@@ -213,59 +246,62 @@ var EditBox = cc.Class({
},
_createSgNode: function() {
return new _ccsg.EditBox(cc.size(300, 100));
return new _ccsg.EditBox(cc.size(160, 40));
},
_createBackgroundSprite: function() {
var sgNode = this._sgNode;
var bgSprite = new cc.Scale9Sprite(this.backgroundImage);
sgNode.initWithSizeAndBackgroundSprite(cc.size(160, 40), bgSprite);
return bgSprite;
},
_initSgNode: function() {
var sgNode = this._sgNode;
var bgSprite = new cc.Scale9Sprite(this.backgroundImage);
sgNode.initWithSizeAndBackgroundSprite(this.node.getContentSize(), bgSprite);
sgNode.setContentSize(this.node.getContentSize());
this._createBackgroundSprite();
sgNode.inputMode = this.inputMode;
sgNode.maxLength = this.maxLength;
sgNode.string = this.string;
sgNode.string = this._string;
sgNode.fontSize = this.fontSize;
sgNode.fontColor = this.fontColor;
sgNode.placeHolder = this.placeHolder;
sgNode.placeHolderFontSize = this.placeHolderFontSize;
sgNode.placeHolderFontColor = this.placeHolderFontColor;
sgNode.placeholder = this.placeholder;
sgNode.placeholderFontSize = this.placeholderFontSize;
sgNode.placeholderFontColor = this.placeholderFontColor;
sgNode.inputFlag = this.inputFlag;
sgNode.returnType = this.returnType;
sgNode.setLineHeight(this.lineHeight);
if (!this._useOriginalSize) {
sgNode.setContentSize(this.node.getContentSize());
}
sgNode.setDelegate(this);
},
_handleComponentEvent: function(events, text) {
for (var i = 0, l = events.length; i < l; i++) {
var event = events[i];
var target = event.target;
if (!cc.isValid(target)) continue;
_resized: function () {
this._useOriginalSize = false;
},
var comp = target.getComponent(event.component);
if (!cc.isValid(comp)) continue;
onLoad: function () {
this._super();
var handler = comp[event.handler];
if (!handler) continue;
handler.call(comp, text);
}
this.node.on('size-changed', this._resized, this);
},
editBoxEditingDidBegan: function() {
var events = this.editingDidBegin;
this._handleComponentEvent(events);
cc.Component.EventHandler.emitEvents(this.editingDidBegan);
},
editBoxEditingDidEnded: function() {
var events = this.editingDidEnd;
this._handleComponentEvent(events);
cc.Component.EventHandler.emitEvents(this.editingDidEnded);
},
editBoxTextChanged: function(editBox, text) {
var events = this.textChanged;
this._handleComponentEvent(events, text);
cc.Component.EventHandler.emitEvents(this.textChanged, text);
},
});
+60 -27
View File
@@ -29,11 +29,11 @@ var LabelType = _ccsg.Label.Type;
/**
*
* @class Label
* @extends _ComponentInSG
* @extends _RendererUnderSG
*/
var Label = cc.Class({
name: 'cc.Label',
extends: cc._ComponentInSG,
extends: cc._RendererUnderSG,
editor: CC_EDITOR && {
menu: 'i18n:MAIN_MENU.component.renderers/Label'
@@ -50,8 +50,10 @@ var Label = cc.Class({
multiline: true,
tooltip: 'i18n:COMPONENT.label.string',
notify: function () {
this._sgNode.setString(this.string);
this._updateNodeSize();
if (this._sgNode) {
this._sgNode.setString(this.string);
this._updateNodeSize();
}
}
},
@@ -64,7 +66,9 @@ var Label = cc.Class({
type: HorizontalAlign,
tooltip: 'i18n:COMPONENT.label.horizontal_align',
notify: function () {
this._sgNode.setHorizontalAlign( this.horizontalAlign );
if (this._sgNode) {
this._sgNode.setHorizontalAlign( this.horizontalAlign );
}
},
animatable: false
},
@@ -78,7 +82,9 @@ var Label = cc.Class({
type: VerticalAlign,
tooltip: 'i18n:COMPONENT.label.vertical_align',
notify: function () {
this._sgNode.setVerticalAlign( this.verticalAlign );
if (this._sgNode) {
this._sgNode.setVerticalAlign( this.verticalAlign );
}
},
animatable: false
},
@@ -90,13 +96,17 @@ var Label = cc.Class({
*/
fontSize: {
get: function(){
this._fontSize = this._sgNode.getFontSize();
if (this._sgNode) {
this._fontSize = this._sgNode.getFontSize();
}
return this._fontSize;
},
set: function(value){
this._fontSize = value;
this._sgNode.setFontSize(value);
this._updateNodeSize();
if (this._sgNode) {
this._sgNode.setFontSize(value);
this._updateNodeSize();
}
},
tooltip: 'i18n:COMPONENT.label.font_size',
},
@@ -105,14 +115,18 @@ var Label = cc.Class({
lineHeight: {
get: function(){
this._lineHeight = this._sgNode.getLineHeight();
if (this._sgNode) {
this._lineHeight = this._sgNode.getLineHeight();
}
return this._lineHeight;
},
set: function(value){
this._lineHeight = value;
this._sgNode.setLineHeight(value);
this._updateNodeSize();
if (this._sgNode) {
this._sgNode.setLineHeight(value);
this._updateNodeSize();
}
},
tooltip: 'i18n:COMPONENT.label.line_height',
},
@@ -125,8 +139,10 @@ var Label = cc.Class({
type: Overflow,
tooltip: 'i18n:COMPONENT.label.overflow',
notify: function () {
this._sgNode.setOverflow(this.overflow);
this._updateNodeSize();
if (this._sgNode) {
this._sgNode.setOverflow(this.overflow);
this._updateNodeSize();
}
},
animatable: false
},
@@ -138,12 +154,16 @@ var Label = cc.Class({
*/
enableWrapText: {
get: function(){
this._enableWrapText = this._sgNode.isWrapTextEnabled();
if (this._sgNode) {
this._enableWrapText = this._sgNode.isWrapTextEnabled();
}
return this._enableWrapText;
},
set: function(value){
this._enableWrapText = value;
this._sgNode.enableWrapText(value);
if (this._sgNode) {
this._sgNode.enableWrapText(value);
}
},
animatable: false,
tooltip: 'i18n:COMPONENT.label.wrap',
@@ -151,14 +171,16 @@ var Label = cc.Class({
/**
* The font URL of label.
* @property {URL} file
* @property {string} file
*/
file: {
default: "Arial",
url: cc.Font,
tooltip: 'i18n:COMPONENT.label.file',
notify: function () {
this._sgNode.setFontFileOrFamily(this.file);
if (this._sgNode) {
this._sgNode.setFontFileOrFamily(this.file);
}
},
animatable: false
},
@@ -171,14 +193,18 @@ var Label = cc.Class({
*/
useSystemFont: {
get: function(){
this._isSystemFontUsed = this._sgNode.isSystemFontUsed();
if (this._sgNode) {
this._isSystemFontUsed = this._sgNode.isSystemFontUsed();
}
return this._isSystemFontUsed;
},
set: function(value){
this._isSystemFontUsed = value;
if (value) {
this.file = "";
this._sgNode.setSystemFontUsed(value);
if (this._sgNode) {
this._sgNode.setSystemFontUsed(value);
}
}
},
@@ -242,10 +268,12 @@ var Label = cc.Class({
},
_createSgNode: function () {
return new _ccsg.Label();
return null;
},
_initSgNode: function () {
this._sgNode = new _ccsg.Label(this.string, this.file);
this._sgNode.retain();
var sgNode = this._sgNode;
// TODO
@@ -260,7 +288,9 @@ var Label = cc.Class({
sgNode.setString(this.string);
sgNode.setFontFileOrFamily(this.file);
if(!this._useOriginalSize){
sgNode.setContentSize(this.node.getContentSize());
if(this.overflow !== Overflow.NONE) {
sgNode.setContentSize(this.node.getContentSize());
}
}
sgNode.setColor(this.node.color);
},
@@ -271,11 +301,14 @@ var Label = cc.Class({
// update node size (this will also invoke the size-changed event)
_updateNodeSize: function () {
if (this.overflow === Overflow.NONE) {
this.node.setContentSize(this._sgNode.getContentSize());
}
if ( !this.node._sizeProvider ) {
this.node._sizeProvider = this._sgNode;
var initialized = this._sgNode && this._sgNode.parent;
if (initialized) {
if (this.overflow === Overflow.NONE) {
this.node.setContentSize(this._sgNode.getContentSize());
}
if ( !this.node._sizeProvider ) {
this.node._sizeProvider = this._sgNode;
}
}
}
});
+20 -1
View File
@@ -143,6 +143,12 @@ var Layout = cc.Class({
default: Type.NONE,
type: Type,
notify: function() {
if (this.layoutType !== Type.NONE && this._resize === ResizeType.CONTAINER && CC_EDITOR && !cc.engine.isPlaying) {
var reLayouted = _Scene.DetectConflict.checkConflict_Layout(this);
if (reLayouted) {
return;
}
}
this._doLayoutDirty();
},
animatable: false,
@@ -168,8 +174,14 @@ var Layout = cc.Class({
return;
}
this._doLayoutDirty();
this._resize = value;
if (this.layoutType !== Type.NONE && value === ResizeType.CONTAINER && CC_EDITOR && !cc.engine.isPlaying) {
var reLayouted = _Scene.DetectConflict.checkConflict_Layout(this);
if (reLayouted) {
return;
}
}
this._doLayoutDirty();
},
animatable: false
},
@@ -197,6 +209,12 @@ var Layout = cc.Class({
default: AxisDirection.HORIZONTAL,
type: AxisDirection,
notify: function() {
if (this._resize === ResizeType.CONTAINER && CC_EDITOR && !cc.engine.isPlaying) {
var reLayouted = _Scene.DetectConflict.checkConflict_Layout(this);
if (reLayouted) {
return;
}
}
this._doLayoutDirty();
},
animatable: false
@@ -285,6 +303,7 @@ var Layout = cc.Class({
this.node.on('anchor-changed', this._doLayoutDirty, this);
this.node.on('child-added', this._childrenAddOrDeleted, this);
this.node.on('child-removed', this._childrenAddOrDeleted, this);
this.node.on('child-reorder', this._doLayoutDirty, this);
this._updateChildrenEventListener();
},
+42 -52
View File
@@ -23,86 +23,76 @@
****************************************************************************/
/**
*
* @class Mask
* @extends Component
* @extends _RendererInSG
*/
var Mask = cc.Class({
name: 'cc.Mask',
extends: cc.Component,
extends: cc._RendererInSG,
editor: CC_EDITOR && {
menu: 'i18n:MAIN_MENU.component.ui/Mask',
executeInEditMode: true
},
properties: {
_clippingNode: {
default: null,
serializable: false,
},
_clippingStencil: {
default: null,
serializable: false,
},
},
onLoad: function () {
_createSgNode: function () {
this._clippingStencil = new cc.DrawNode();
this._clippingNode = new cc.ClippingNode(this._clippingStencil);
if (cc.sys.isNative) {
this._clippingStencil.retain();
this._clippingNode.retain();
}
this._clippingStencil.retain();
return new cc.ClippingNode(this._clippingStencil);
},
onDestroy: function () {
if (cc.sys.isNative) {
this._clippingStencil && this._clippingStencil.release();
this._clippingNode && this._clippingNode.release();
}
_initSgNode: function () {
var clippingNode = this._sgNode;
clippingNode.setContentSize(this.node.getContentSize(true));
},
_refreshStencil: function () {
var contentSize = this.node._contentSize;
var anchorPoint = this.node._anchorPoint;
var x = contentSize.width * anchorPoint.x;
var y = contentSize.height * anchorPoint.y;
this._clippingStencil.clear();
var rectangle = [cc.v2(-x, -y), cc.v2(contentSize.width - x, -y),
cc.v2(contentSize.width - x, contentSize.height - y),
cc.v2(-x, contentSize.height - y)];
this._clippingStencil.drawPoly(rectangle, cc.color(255, 255, 255, 0), 0, cc.color(255, 255, 255, 0));
},
//onLoad: function () {
// this._super();
// // ignore node size
// if (this.node._sizeProvider === this._sgNode) {
// this.node._sizeProvider = null;
// }
//},
onEnable: function () {
var oldNode = this.node._sgNode;
this._refreshStencil();
this.node._replaceSgNode(this._clippingNode);
this.node.on('size-changed', this._onContentSizeChanged, this);
this.node.on('anchor-changed', this._onAnchorChanged, this);
this._super();
this.node.on('size-changed', this._refreshStencil, this);
this.node.on('anchor-changed', this._refreshStencil, this);
},
onDisable: function () {
var oldNode = this.node._sgNode;
var newNode = new _ccsg.Node();
this.node._replaceSgNode(newNode);
this.node.off('size-changed', this._onContentSizeChanged, this);
this.node.off('anchor-changed', this._onAnchorChanged, this);
this._super();
this.node.off('size-changed', this._refreshStencil, this);
this.node.off('anchor-changed', this._refreshStencil, this);
},
onDestroy: function () {
this._super();
this._clippingStencil.release();
},
_onContentSizeChanged: function () {
if (this._clippingStencil) {
this._refreshStencil();
}
},
_onAnchorChanged: function () {
if (this._clippingStencil) {
this._refreshStencil();
}
_refreshStencil: function () {
var contentSize = this.node.getContentSize();
var anchorPoint = this.node.getAnchorPoint();
var width = contentSize.width;
var height = contentSize.height;
var x = - width * anchorPoint.x;
var y = - height * anchorPoint.y;
var rectangle = [ cc.v2(x, y),
cc.v2(x + width, y),
cc.v2(x + width, y + height),
cc.v2(x, y + height) ];
var color = cc.color(255, 255, 255, 0);
this._clippingStencil.clear();
this._clippingStencil.drawPoly(rectangle, color, 0, color);
}
});
cc.Mask = module.exports = Mask;
+38 -8
View File
@@ -36,7 +36,11 @@ var Mode = cc.Enum({
/**
* @property {Number} VERTICAL
*/
VERTICAL: 1
VERTICAL: 1,
/**
* @property {Number} FILLED
*/
FILLED: 2,
});
/**
@@ -55,6 +59,7 @@ var ProgressBar = cc.Class({
_initBarSprite: function() {
if (this.barSprite) {
var entity = this.barSprite.node;
if (!entity) return;
var nodeSize = this.node.getContentSize();
var nodeAnchor = this.node.getAnchorPoint();
@@ -65,12 +70,20 @@ var ProgressBar = cc.Class({
this.node.setContentSize(entitySize);
}
if (this.barSprite.fillType === cc.Sprite.FillType.RADIAL) {
this.mode = Mode.FILLED;
}
var barSpriteSize = entity.getContentSize();
if (this.mode === Mode.HORIZONTAL) {
this.totalLength = barSpriteSize.width;
} else {
}
else if(this.mode === Mode.VERTICAL) {
this.totalLength = barSpriteSize.height;
}
else {
this.totalLength = this.barSprite.fillRange;
}
if(entity.parent === this.node){
var x = - nodeSize.width * nodeAnchor.x;
@@ -83,6 +96,9 @@ var ProgressBar = cc.Class({
_updateBarStatus: function() {
if (this.barSprite) {
var entity = this.barSprite.node;
if (!entity) return;
var entityAnchorPoint = entity.getAnchorPoint();
var entitySize = entity.getContentSize();
var entityPosition = entity.getPosition();
@@ -110,17 +126,27 @@ var ProgressBar = cc.Class({
finalContentSize = cc.size(entitySize.width, actualLenth);
totalWidth = entitySize.width;
totalHeight = this.totalLength;
break;
case Mode.FILLED:
if (this.reverse) {
actualLenth = actualLenth * -1;
}
this.barSprite.fillRange = actualLenth;
break;
}
var anchorOffsetX = anchorPoint.x - entityAnchorPoint.x;
var anchorOffsetY = anchorPoint.y - entityAnchorPoint.y;
if (this.barSprite.type !== cc.Sprite.Type.FILLED) {
var finalPosition = cc.p(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY);
var anchorOffsetX = anchorPoint.x - entityAnchorPoint.x;
var anchorOffsetY = anchorPoint.y - entityAnchorPoint.y;
var finalPosition = cc.p(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY);
entity.setPosition(cc.pAdd(entityPosition, finalPosition));
entity.setPosition(cc.pAdd(entityPosition, finalPosition));
entity.setAnchorPoint(anchorPoint);
entity.setContentSize(finalContentSize);
}
entity.setAnchorPoint(anchorPoint);
entity.setContentSize(finalContentSize);
}
},
@@ -151,11 +177,15 @@ var ProgressBar = cc.Class({
notify: function() {
if (this.barSprite) {
var entity = this.barSprite.node;
if (!entity) return;
var entitySize = entity.getContentSize();
if (this.mode === Mode.HORIZONTAL) {
this.totalLength = entitySize.width;
} else if (this.mode === Mode.VERTICAL) {
this.totalLength = entitySize.height;
} else if (this.mode === Mode.FILLED) {
this.totalLength = this.barSprite.fillRange;
}
}
},
+120
View File
@@ -0,0 +1,120 @@
/****************************************************************************
Copyright (c) 2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/**
* Rendering component in scene graph.
* Maintains a node which will be the scene graph of component's Node.
*
* @class _RendererInSG
* @extends _SGComponent
* @private
*/
var RendererInSG = cc.Class({
extends: require('./CCSGComponent'),
ctor: function () {
/**
* The Reference to the instance of _ccsg.Node used when this component enabled
* @property {_ccsg.Node} _sgNode
* @private
*/
this._sgNode = this._createSgNode();
if (this._sgNode) {
// retain immediately
// will be released in onDestroy
this._sgNode.retain();
}
else {
cc.error('Not support for asynchronous creating node in SG');
}
// The replacement node used when this component disabled
this._plainNode = new _ccsg.Node();
},
onEnable: function () {
this._replaceSgNode(this._sgNode);
this.node._ignoreAnchor = true;
},
onDisable: function () {
this._replaceSgNode(this._plainNode);
this.node._ignoreAnchor = false;
},
onDestroy: function () {
this._super();
var released = this.node._sgNode;
if (this._sgNode !== released) {
this._sgNode.release();
}
else {
this._plainNode.release();
}
},
_replaceSgNode: function (sgNode) {
if ( !(sgNode instanceof _ccsg.Node) && CC_EDITOR) {
throw new Error("Invalid sgNode. It must be an instance of _ccsg.Node");
}
var node = this.node;
var replaced = node._sgNode;
if (replaced === sgNode && CC_EDITOR) {
cc.warn('The same sgNode');
return;
}
// rebuild scene graph
// replace children
var children = replaced.getChildren().slice();
replaced.removeAllChildren();
if (sgNode.getChildrenCount() > 0) {
if (CC_EDITOR) {
cc.warn('The replacement sgNode should not contain any child.');
}
sgNode.removeAllChildren();
}
for (var i = 0, len = children.length; i < len; ++i) {
sgNode.addChild(children[i]);
}
// replace parent
var parentNode = replaced.getParent();
parentNode.removeChild(replaced);
parentNode.addChild(sgNode);
sgNode.arrivalOrder = replaced.arrivalOrder;
if (cc.renderer) {
cc.renderer.childrenOrderDirty = parentNode._reorderChildDirty = true;
}
// apply node's property
node._sgNode = sgNode;
node._updateSgNode();
},
});
cc._RendererInSG = module.exports = RendererInSG;
@@ -0,0 +1,96 @@
/****************************************************************************
Copyright (c) 2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
/**
* The base rendering component which will attach a leaf node to the cocos2d scene graph.
*
* @class _RendererUnderSG
* @extends _SGComponent
* @private
*/
var RendererUnderSG = cc.Class({
extends: require('./CCSGComponent'),
ctor: function () {
/**
* Reference to the instance of _ccsg.Node
* If it is possible to return null from your overloaded _createSgNode,
* then you should always check for null before using this property and reimplement onLoad.
*
* @property {_ccsg.Node} _sgNode
* @private
*/
this._sgNode = this._createSgNode();
if (this._sgNode) {
// retain immediately
// will be released in onDestroy
this._sgNode.retain();
}
},
// You should reimplement this function if your _sgNode maybe null.
onLoad: function () {
this._super();
this._appendSgNode(this._sgNode);
},
onEnable: function () {
if (this._sgNode) {
this._sgNode.setVisible(true);
}
},
onDisable: function () {
if (this._sgNode) {
this._sgNode.setVisible(false);
}
},
_appendSgNode: function (sgNode) {
if ( !sgNode ) {
return;
}
if ( !this.enabled ) {
sgNode.setVisible(false);
}
var node = this.node;
sgNode.setColor(node._color);
if ( !node._cascadeOpacityEnabled ) {
sgNode.setOpacity(node._opacity);
}
sgNode.setAnchorPoint(node._anchorPoint);
sgNode.ignoreAnchorPointForPosition(node.__ignoreAnchor);
sgNode.setOpacityModifyRGB(node._opacityModifyRGB);
// set z order to -1 to make sure component will rendered before all of its entity's children.
sgNode.setLocalZOrder(-1);
var sgParent = node._sgNode;
sgParent.addChild(sgNode);
}
});
cc._RendererUnderSG = module.exports = RendererUnderSG;
+90
View File
@@ -0,0 +1,90 @@
/****************************************************************************
Copyright (c) 2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
var SceneGraphHelper = require('../utils/scene-graph-helper');
/**
* The base class for all rendering component in scene graph.
*
* You should override:
* - _createSgNode
* - _initSgNode
*
* @class _SGComponent
* @extends Component
* @private
*/
var SGComponent = cc.Class({
extends: require('./CCComponent'),
editor: CC_EDITOR && {
executeInEditMode: true,
disallowMultiple: true
},
properties: {
_sgNode: {
default: null,
serializable: false
}
},
onLoad: function () {
this._initSgNode();
var sgNode = this._sgNode;
if ( !this.node._sizeProvider ) {
this.node._sizeProvider = sgNode;
}
},
onDestroy: function () {
if ( this.node._sizeProvider === this._sgNode ) {
this.node._sizeProvider = null;
}
this._removeSgNode();
},
/**
* Create and returns your new scene graph node (SGNode) to add to scene graph.
* You should call the setContentSize of the SGNode if its size should be the same with the node's.
*
* @method _createSgNode
* @return {_ccsg.Node}
* @private
*/
_createSgNode: null,
/**
* @method _initSgNode
* @private
*/
_initSgNode: null,
/**
* @method _removeSgNode
* @private
*/
_removeSgNode: SceneGraphHelper.removeSgNode,
});
cc._SGComponent = module.exports = SGComponent;
+8 -4
View File
@@ -159,8 +159,10 @@ var ScrollView = cc.Class({
type: cc.Scrollbar,
tooltip: 'i18n:COMPONENT.scrollview.horizontal_bar',
notify: function() {
this.horizontalScrollBar.setTargetScrollView(this);
this._updateScrollBar(0);
if (this.horizontalScrollBar) {
this.horizontalScrollBar.setTargetScrollView(this);
this._updateScrollBar(0);
}
},
animatable: false
},
@@ -174,8 +176,10 @@ var ScrollView = cc.Class({
type: cc.Scrollbar,
tooltip: 'i18n:COMPONENT.scrollview.vertical_bar',
notify: function() {
this.verticalScrollBar.setTargetScrollView(this);
this._updateScrollBar(0);
if (this.verticalScrollBar) {
this.verticalScrollBar.setTargetScrollView(this);
this._updateScrollBar(0);
}
},
animatable: false
}
+21 -23
View File
@@ -61,11 +61,11 @@ var SizeMode = cc.Enum({
/**
* Renders a sprite in the scene.
* @class Sprite
* @extends _ComponentInSG
* @extends _RendererUnderSG
*/
var Sprite = cc.Class({
name: 'cc.Sprite',
extends: require('./CCComponentInSG'),
extends: require('./CCRendererUnderSG'),
editor: CC_EDITOR && {
menu: 'i18n:MAIN_MENU.component.renderers/Sprite',
@@ -96,7 +96,7 @@ var Sprite = cc.Class({
* @type {SpriteAtlas}
*/
_atlas: {
default: '',
default: null,
type: cc.SpriteAtlas,
tooltip: 'i18n:COMPONENT.sprite.atlas',
editorOnly: true,
@@ -174,7 +174,7 @@ var Sprite = cc.Class({
return this._fillStart;
},
set: function(value) {
this._fillStart = value;
this._fillStart = cc.clampf(value, -1, 1);
this._sgNode && this._sgNode.setFillStart(value);
},
},
@@ -184,7 +184,7 @@ var Sprite = cc.Class({
return this._fillRange;
},
set: function(value) {
this._fillRange = value;
this._fillRange = cc.clampf(value, -1, 1);
this._sgNode && this._sgNode.setFillRange(value);
},
},
@@ -264,20 +264,15 @@ var Sprite = cc.Class({
},
animatable: false,
type: SizeMode
},
/**
* Only for editor to calculate bounding box.
*/
localSize: {
get: function () {
var sgNode = this._sgNode;
return cc.size(sgNode.width, sgNode.height);
},
visible: false,
override: true
}
},
statics: {
FillType: FillType,
Type: SpriteType,
SizeMode: SizeMode,
},
/**
* Sets whether the sprite is visible or not.
* @method setVisible
@@ -445,6 +440,14 @@ var Sprite = cc.Class({
this.node.on('size-changed', this._resized, this);
},
onEnable: function () {
if (this._sgNode) {
if (this._spriteFrame && this._spriteFrame.textureLoaded()) {
this._sgNode.setVisible(true);
}
}
},
onDestroy: function () {
this._super();
this.node.off('size-changed', this._resized, this);
@@ -505,7 +508,7 @@ var Sprite = cc.Class({
sgNode.setSpriteFrame(self._spriteFrame);
self._applyCapInset();
self._applySpriteSize();
if (this.enabledInHierarchy && !sgNode.isVisible()) {
if (self.enabledInHierarchy && !sgNode.isVisible()) {
sgNode.setVisible(true);
}
},
@@ -540,13 +543,8 @@ var Sprite = cc.Class({
_initSgNode: function () {
var sgNode = this._sgNode;
if (!this.enabledInHierarchy) {
sgNode.setVisible(false);
}
this._validateSizeMode();
this._applySpriteFrame(null);
// should keep the size of the sg node the same as entity,
+9 -1
View File
@@ -392,6 +392,10 @@ var Widget = cc.Class({
if (this.isStretchWidth) {
// become stretch
this._originalWidth = this.node.width;
// test check conflict
if (CC_EDITOR && !cc.engine.isPlaying) {
_Scene.DetectConflict.checkConflict_Widget(this);
}
}
}
else {
@@ -399,10 +403,14 @@ var Widget = cc.Class({
if (this.isStretchHeight) {
// become stretch
this._originalHeight = this.node.height;
// test check conflict
if (CC_EDITOR && !cc.engine.isPlaying) {
_Scene.DetectConflict.checkConflict_Widget(this);
}
}
}
if (CC_EDITOR && !cc.engine._isPlaying) {
if (CC_EDITOR && !cc.engine._isPlaying && this.node._parent) {
// adjust the offsets to keep the size and position unchanged after alignment chagned
var type;
if (flag & TOP) {
+4 -2
View File
@@ -1,6 +1,8 @@
require('./CCComponent');
require('./CCComponentInSG');
require('./CCComponentEventHandler')
require('./CCRendererInSG');
require('./CCRendererUnderSG');
require('./CCComponentEventHandler');
require('./missing-script');
module.exports = [
require('./CCSprite'),
+79
View File
@@ -0,0 +1,79 @@
var JS = cc.js;
/*
* 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', extends: cc.Component,
properties: {
//_scriptUuid: {
// get: function () {
// var id = this._$erialized.__type__;
// if (Editor.UuidUtils.isUuid(id)) {
// return Editor.UuidUtils.decompressUuid(id);
// }
// return '';
// },
// set: function (value) {
// if ( !sandbox.compiled ) {
// cc.error('Scripts not yet compiled, please fix script errors and compile first.');
// return;
// }
// if (value && Editor.UuidUtils.isUuid(value._uuid)) {
// var classId = Editor.UuidUtils.compressUuid(value);
// if (cc.js._getClassById(classId)) {
// this._$erialized.__type__ = classId;
// Editor.sendToWindows('reload:window-scripts', sandbox.compiled);
// }
// else {
// cc.error('Can not find a component in the script which uuid is "%s".', value);
// }
// }
// else {
// cc.error('invalid script');
// }
// }
//},
error: {
default: '',
multiline: true,
readonly: true,
serializable: false,
displayName: '(Error)'
},
// the serialized data for original script object
_$erialized: {
default: null,
visible: false,
editorOnly: true
}
},
ctor: CC_EDITOR && function () {
this.error = _Scene.Sandbox.compiled ?
Editor.T('COMPONENT.missing_scirpt.error_compiled') :
Editor.T('COMPONENT.missing_scirpt.error_not_compiled')
},
statics: {
/*
* @param {string} id
* @return {function} constructor
*/
safeFindClass: function (id) {
var cls = JS._getClassById(id);
if (cls) {
return cls;
}
if (id) {
return MissingScript;
}
return null;
}
},
onLoad: function () {
cc.warn('The referenced script on "%s" is missing!', this.name);
}
});
cc._MissingScript = module.exports = MissingScript;
+493 -252
View File
@@ -26,6 +26,13 @@
THE SOFTWARE.
****************************************************************************/
var capitalize = function(string) {
return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
};
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
/**
* Enum for keyboard return types
* @readonly
@@ -162,14 +169,14 @@ cc.EditBoxDelegate = cc._Class.extend({
* This method is called when an edit box gains focus after keyboard is shown.
* @param {cc.EditBox} sender
*/
editBoxEditingDidBegin: function (sender) {
editBoxEditingDidBegan: function (sender) {
},
/**
* This method is called when an edit box loses focus after keyboard is hidden.
* @param {cc.EditBox} sender
*/
editBoxEditingDidEnd: function (sender) {
editBoxEditingDidEnded: function (sender) {
},
/**
@@ -188,6 +195,415 @@ cc.EditBoxDelegate = cc._Class.extend({
}
});
var EditBoxImpl = function(editBox) {
this._domInputSprite = null;
this._spriteDOM = null;
this._edTxt = null;
this._edFontSize = 14;
this._edFontName = 'Arial';
this._editBox = editBox;
this._textLabel = null;
this._placeholderLabel = null;
};
EditBoxImpl.prototype = {
constructor: EditBoxImpl,
createNativeControl: function(size) {
var tmpDOMSprite = this._domInputSprite = new _ccsg.Sprite();
tmpDOMSprite.draw = function () {}; //redefine draw function
this._editBox.addChild(tmpDOMSprite);
this._spriteDOM = tmpDOMSprite;
this._createDomTextArea();
cc.DOM.convert(tmpDOMSprite);
this._addDomInputControl();
this._domInputSprite.dom.showTooltipDiv = false;
this._domInputSprite.dom.style.width = (size.width - 6) + 'px';
this._domInputSprite.dom.style.height = (size.height - 6) + 'px';
tmpDOMSprite.canvas.remove();
this._domInputSprite.x = 3;
this._domInputSprite.y = 3;
this._createLabels();
},
_createLabels: function () {
var editBoxSize = this._editBox.getContentSize();
this._textLabel = new _ccsg.Label();
this._textLabel.setVisible(false);
this._textLabel.setAnchorPoint(cc.p(0, 1));
this._editBox.addChild(this._textLabel, 100);
this._placeholderLabel = new _ccsg.Label();
this._placeholderLabel.setAnchorPoint(cc.p(0, 1));
this._placeholderLabel.setColor(cc.Color.GRAY);
this._editBox.addChild(this._placeholderLabel, 100);
this._updateLabelPosition(editBoxSize);
},
_updateLabelPosition: function (editBoxSize) {
var textLabelSize = this._textLabel.getContentSize();
var placeholderLabelSize = this._placeholderLabel.getContentSize();
this._placeholderLabel.setLineHeight(editBoxSize.height);
if (this._editBox._editBoxInputMode === InputMode.ANY){
this._textLabel.setPosition(cc.p(0, editBoxSize.height));
this._placeholderLabel.setPosition(cc.p(0, editBoxSize.height));
this._placeholderLabel.setVerticalAlign(cc.VerticalTextAlignment.TOP);
this._textLabel.setVerticalAlign(cc.VerticalTextAlignment.TOP);
}
else {
this._textLabel.setPosition(cc.p(0, (editBoxSize.height + textLabelSize.height) / 2));
this._placeholderLabel.setPosition(cc.p(0, (editBoxSize.height + placeholderLabelSize.height) / 2));
this._placeholderLabel.setVerticalAlign(cc.VerticalTextAlignment.CENTER);
this._textLabel.setVerticalAlign(cc.VerticalTextAlignment.CENTER);
}
},
setLineHeight: function (lineHeight) {
this._textLabel.setLineHeight(lineHeight);
},
_hiddenLabels: function () {
this._textLabel.setVisible(false);
this._placeholderLabel.setVisible(false);
},
_updateLabelString: function() {
this._textLabel.setVisible(true);
this._textLabel.setString(this._editBox._text);
var inputFlag = this._editBox._editBoxInputFlag;
if (this._edTxt.type === 'password') {
var passwordString = '';
var len = this._editBox._text.length;
for (var i = 0; i < len; ++i) {
passwordString += '\u25CF';
}
this._textLabel.setString(passwordString);
}
else if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) {
this._textLabel.setString(this._editBox._text.toUpperCase());
}
else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) {
this._textLabel.setString(capitalize(this._editBox._text));
}
else if (inputFlag === InputFlag.INITIAL_CAPS_SENTENCE) {
this._textLabel.setString(capitalizeFirstLetter(this._editBox._text));
}
},
_showLabels: function () {
this._hiddenLabels();
if (this._edTxt.value === '') {
this._placeholderLabel.setVisible(true);
this._placeholderLabel.setString(this._editBox._placeholderText);
}
else {
this._updateLabelString();
}
},
registerClickEvent: function() {
var self = this;
var div = self._edTxt.parentNode;
div.style.pointerEvents = 'none';
div.addEventListener('click', function() {
if (self._edTxt.style.display === 'none') {
self._edTxt.style.display = '';
self._edTxt.focus();
self._hiddenLabels();
}
});
},
show: function() {
var div = this._edTxt.parentNode;
div.style.pointerEvents = '';
window.setTimeout(function() {
div.click();
}, 10);
},
hidden: function() {
this._edTxt.style.display = 'none';
var div = this._edTxt.parentNode;
div.style.pointerEvents = 'none';
this._showLabels();
},
_setFont: function (fontStyle) {
var res = cc.LabelTTF._fontStyleRE.exec(fontStyle);
var textFontName = res[2];
var textFontSize = parseInt(res[1]);
if (res) {
this.setFont(textFontName, textFontSize);
}
},
setFont: function (fontName, fontSize) {
this._edFontName = fontName || this._edFontName;
this._edFontSize = fontSize || this._edFontSize;
this._updateDOMFontStyle();
},
setFontName: function (fontName) {
this._edFontName = fontName || this._edFontName;
this._updateDOMFontStyle();
},
setFontSize: function (fontSize) {
this._edFontSize = fontSize || this._edFontSize;
this._updateDOMFontStyle();
},
setFontColor: function (color) {
if (this._edTxt.value !== this._editBox._placeholderText) {
this._edTxt.style.color = cc.colorToHex(color);
}
this._textLabel.setColor(color);
},
setPlaceHolder: function (text) {
this._placeholderLabel.setString(text);
},
setMaxLength: function (maxLength) {
this._edTxt.maxLength = maxLength;
},
_updateDOMPlaceholderFontStyle: function () {
this._placeholderLabel.setFontFileOrFamily(this._editBox._placeholderFontName);
this._placeholderLabel.setFontSize(this._editBox._placeholderFontSize);
},
setPlaceholderFontColor: function (color) {
this._placeholderLabel.setColor(color);
},
setInputFlag: function (inputFlag) {
if ((this._edTxt.value !== this._placeholderText) && (inputFlag === InputFlag.PASSWORD))
this._edTxt.type = 'password';
else
this._edTxt.type = 'text';
this._edTxt.style.textTransform = 'none';
if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) {
this._edTxt.style.textTransform = 'uppercase';
}
else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) {
this._edTxt.style.textTransform = 'capitalize';
}
this._updateLabelString();
},
setInputMode : function (inputMode) {
if (inputMode === InputMode.ANY) {
this._removeDomInputControl();
this._createDomTextArea();
this._addDomInputControl();
}
else if(this._editBox._editBoxInputMode === InputMode.ANY) {
this._removeDomInputControl();
this._createDomInput();
this._addDomInputControl();
}
},
/**
* Set the text entered in the edit box.
* @param {string} text The given text.
*/
setString: function (text) {
if (text !== null) {
this._edTxt.value = text;
if (text === '') {
this._edTxt.type = 'text';
this._placeholderLabel.setString(this._editBox._placeholderText);
this._placeholderLabel.setColor(this._editBox._placeholderColor);
this._placeholderLabel.setVisible(true);
this._textLabel.setVisible(false);
}
else {
this._edTxt.style.color = cc.colorToHex(this._editBox._textColor);
this._textLabel.setColor(this._editBox._textColor);
this._placeholderLabel.setVisible(false);
if (this._editBox._editBoxInputFlag === InputFlag.PASSWORD) {
this._edTxt.type = 'password';
}
else {
this._edTxt.type = 'text';
}
this._updateLabelString();
}
}
},
_updateDOMFontStyle: function() {
if (this._edTxt.value !== '') {
this._edTxt.style.fontFamily = this._edFontName;
this._edTxt.style.fontSize = this._edFontSize + 'px';
if (this._editBox._editBoxInputFlag === InputFlag.PASSWORD)
this._edTxt.type = 'password';
else
this._edTxt.type = 'text';
}
this._textLabel.setFontSize(this._edFontSize);
this._textLabel.setFontFileOrFamily(this._edFontName);
},
setSize: function(newWidth, newHeight) {
this._spriteDOM.dom.style.width = (newWidth - 6) + 'px';
this._spriteDOM.dom.style.height = (newHeight - 6) + 'px';
this._updateLabelPosition(cc.size(newWidth, newHeight));
},
_createDomInput: function () {
var selfPointer = this;
var tmpEdTxt = this._edTxt = document.createElement('input');
tmpEdTxt.type = 'text';
tmpEdTxt.style.fontSize = this._edFontSize + 'px';
tmpEdTxt.style.color = '#000000';
tmpEdTxt.style.border = 0;
tmpEdTxt.style.background = 'transparent';
//tmpEdTxt.style.paddingLeft = '2px';
tmpEdTxt.style.width = '100%';
tmpEdTxt.style.height = '100%';
tmpEdTxt.style.active = 0;
tmpEdTxt.style.outline = 'medium';
tmpEdTxt.style.padding = '0';
tmpEdTxt.style.textTransform = 'uppercase';
tmpEdTxt.style.display = 'none';
var onCanvasClick = function() { tmpEdTxt.blur();};
tmpEdTxt.addEventListener('input', function () {
var editBox = selfPointer._editBox;
if (editBox._delegate && editBox._delegate.editBoxTextChanged)
editBox._delegate.editBoxTextChanged(editBox, this.value);
});
tmpEdTxt.addEventListener('keypress', function (e) {
var editBox = selfPointer._editBox;
if (e.keyCode === cc.KEY.enter) {
e.stopPropagation();
e.preventDefault();
if(this.value === '') {
this.style.fontSize = editBox._placeholderFontSize + 'px';
this.style.color = cc.colorToHex(editBox._placeholderColor);
}
editBox._text = this.value;
selfPointer.hidden();
if (editBox._delegate && editBox._delegate.editBoxReturn)
editBox._delegate.editBoxReturn(editBox);
cc._canvas.focus();
}
});
tmpEdTxt.addEventListener('focus', function () {
var editBox = selfPointer._editBox;
this.style.fontSize = selfPointer._edFontSize + 'px';
this.style.color = cc.colorToHex(editBox._textColor);
if (editBox._editBoxInputFlag === InputFlag.PASSWORD)
selfPointer._edTxt.type = 'password';
else
selfPointer._edTxt.type = 'text';
if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan)
editBox._delegate.editBoxEditingDidBegan(editBox);
cc._canvas.addEventListener('click', onCanvasClick);
});
tmpEdTxt.addEventListener('blur', function () {
var editBox = selfPointer._editBox;
editBox._text = this.value;
if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded)
editBox._delegate.editBoxEditingDidEnded(editBox);
cc._canvas.removeEventListener('click', onCanvasClick);
if (this.value === '') {
this.style.fontSize = editBox._placeholderFontSize + 'px';
this.style.color = cc.colorToHex(editBox._placeholderColor);
}
selfPointer.hidden();
});
return tmpEdTxt;
},
_createDomTextArea: function () {
var selfPointer = this;
var tmpEdTxt = this._edTxt = document.createElement('textarea');
tmpEdTxt.type = 'text';
tmpEdTxt.style.fontSize = this._edFontSize + 'px';
tmpEdTxt.style.color = '#000000';
tmpEdTxt.style.border = 0;
tmpEdTxt.style.background = 'transparent';
//tmpEdTxt.style.paddingLeft = '2px';
tmpEdTxt.style.width = '100%';
tmpEdTxt.style.height = '100%';
tmpEdTxt.style.active = 0;
tmpEdTxt.style.outline = 'medium';
tmpEdTxt.style.padding = '0';
tmpEdTxt.style.resize = 'none';
tmpEdTxt.style.textTransform = 'uppercase';
tmpEdTxt.style.overflow_y = 'scroll';
tmpEdTxt.style.display = 'none';
var onCanvasClick = function() { tmpEdTxt.blur();};
tmpEdTxt.addEventListener('input', function () {
var editBox = selfPointer._editBox;
if (editBox._delegate && editBox._delegate.editBoxTextChanged)
editBox._delegate.editBoxTextChanged(editBox, this.value);
});
tmpEdTxt.addEventListener('focus', function () {
var editBox = selfPointer._editBox;
this.style.fontSize = selfPointer._edFontSize + 'px';
this.style.color = cc.colorToHex(editBox._textColor);
if (editBox._delegate && editBox._delegate.editBoxEditingDidBegan)
editBox._delegate.editBoxEditingDidBegan(editBox);
cc._canvas.addEventListener('click', onCanvasClick);
});
tmpEdTxt.addEventListener('blur', function () {
var editBox = selfPointer._editBox;
editBox._text = this.value;
if (editBox._delegate && editBox._delegate.editBoxEditingDidEnded)
editBox._delegate.editBoxEditingDidEnded(editBox);
if (this.value === '') {
this.style.fontSize = editBox._placeholderFontSize + 'px';
this.style.color = cc.colorToHex(editBox._placeholderColor);
}
selfPointer.hidden();
cc._canvas.removeEventListener('click', onCanvasClick);
});
return tmpEdTxt;
},
_removeDomInputControl: function() {
this._domInputSprite.dom.removeChild(this._edTxt);
},
_addDomInputControl: function () {
this._domInputSprite.dom.appendChild(this._edTxt);
},
};
/**
* <p>cc.EditBox is a brief Class for edit box.<br/>
* You can use this widget to gather small amounts of text from the user.</p>
@@ -213,143 +629,27 @@ cc.EditBoxDelegate = cc._Class.extend({
*
*/
_ccsg.EditBox = _ccsg.Node.extend({
_domInputSprite: null,
_backgroundSprite: null,
_spriteDOM: null,
_delegate: null,
_editBoxInputMode: InputMode.ANY,
_editBoxInputFlag: InputFlag.SENSITIVE,
_keyboardReturnType: KeyboardReturnType.DEFAULT,
_maxLength: 50,
_nativeControl: null,
_text: '',
_placeholderText: '',
_textColor: null,
_placeholderColor: null,
_maxLength: 50,
_adjustHeight: 18,
_edTxt: null,
_edFontSize: 14,
_edFontName: 'Arial',
_placeholderText: '',
_placeholderFontName: '',
_placeholderFontSize: 14,
_placeholderColor: null,
_adjustHeight: 18,
_tooltip: false,
_className: 'EditBox',
_createDomInput: function () {
var selfPointer = this;
var tmpEdTxt = this._edTxt = document.createElement('input');
tmpEdTxt.type = 'text';
tmpEdTxt.style.fontSize = this._edFontSize + 'px';
tmpEdTxt.style.color = '#000000';
tmpEdTxt.style.border = 0;
tmpEdTxt.style.background = 'transparent';
//tmpEdTxt.style.paddingLeft = '2px';
tmpEdTxt.style.width = '100%';
tmpEdTxt.style.height = '100%';
tmpEdTxt.style.active = 0;
tmpEdTxt.style.outline = 'medium';
tmpEdTxt.style.padding = '0';
tmpEdTxt.style.textTransform = 'uppercase';
var onCanvasClick = function() { tmpEdTxt.blur();};
// TODO the event listener will be remove when EditBox removes from parent.
tmpEdTxt.addEventListener('input', function () {
if (selfPointer._delegate && selfPointer._delegate.editBoxTextChanged)
selfPointer._delegate.editBoxTextChanged(selfPointer, this.value);
});
tmpEdTxt.addEventListener('keypress', function (e) {
if (e.keyCode === cc.KEY.enter) {
e.stopPropagation();
e.preventDefault();
if (selfPointer._delegate && selfPointer._delegate.editBoxReturn)
selfPointer._delegate.editBoxReturn(selfPointer);
cc._canvas.focus();
}
});
tmpEdTxt.addEventListener('focus', function () {
if (this.value === selfPointer._placeholderText) {
this.value = '';
this.style.fontSize = selfPointer._edFontSize + 'px';
this.style.color = cc.colorToHex(selfPointer._textColor);
if (selfPointer._editBoxInputFlag === InputFlag.PASSWORD)
selfPointer._edTxt.type = 'password';
else
selfPointer._edTxt.type = 'text';
}
if (selfPointer._delegate && selfPointer._delegate.editBoxEditingDidBegin)
selfPointer._delegate.editBoxEditingDidBegin(selfPointer);
cc._canvas.addEventListener('click', onCanvasClick);
});
tmpEdTxt.addEventListener('blur', function () {
if (this.value === '') {
this.value = selfPointer._placeholderText;
this.style.fontSize = selfPointer._placeholderFontSize + 'px';
this.style.color = cc.colorToHex(selfPointer._placeholderColor);
selfPointer._edTxt.type = 'text';
}
if (selfPointer._delegate && selfPointer._delegate.editBoxEditingDidEnd)
selfPointer._delegate.editBoxEditingDidEnd(selfPointer);
cc._canvas.removeEventListener('click', onCanvasClick);
});
return tmpEdTxt;
},
_createDomTextArea: function () {
var selfPointer = this;
var tmpEdTxt = this._edTxt = document.createElement('textarea');
tmpEdTxt.type = 'text';
tmpEdTxt.style.fontSize = this._edFontSize + 'px';
tmpEdTxt.style.color = '#000000';
tmpEdTxt.style.border = 0;
tmpEdTxt.style.background = 'transparent';
//tmpEdTxt.style.paddingLeft = '2px';
tmpEdTxt.style.width = '100%';
tmpEdTxt.style.height = '100%';
tmpEdTxt.style.active = 0;
tmpEdTxt.style.outline = 'medium';
tmpEdTxt.style.padding = '0';
tmpEdTxt.style.textTransform = 'uppercase';
var onCanvasClick = function() { tmpEdTxt.blur();};
// TODO the event listener will be remove when EditBox removes from parent.
tmpEdTxt.addEventListener('input', function () {
if (selfPointer._delegate && selfPointer._delegate.editBoxTextChanged)
selfPointer._delegate.editBoxTextChanged(selfPointer, this.value);
});
tmpEdTxt.addEventListener('focus', function () {
if (this.value === selfPointer._placeholderText) {
this.value = '';
this.style.fontSize = selfPointer._edFontSize + 'px';
this.style.color = cc.colorToHex(selfPointer._textColor);
}
if (selfPointer._delegate && selfPointer._delegate.editBoxEditingDidBegin)
selfPointer._delegate.editBoxEditingDidBegin(selfPointer);
cc._canvas.addEventListener('click', onCanvasClick);
});
tmpEdTxt.addEventListener('blur', function () {
if (this.value === '') {
this.value = selfPointer._placeholderText;
this.style.fontSize = selfPointer._placeholderFontSize + 'px';
this.style.color = cc.colorToHex(selfPointer._placeholderColor);
}
if (selfPointer._delegate && selfPointer._delegate.editBoxEditingDidEnd)
selfPointer._delegate.editBoxEditingDidEnd(selfPointer);
cc._canvas.removeEventListener('click', onCanvasClick);
});
return tmpEdTxt;
},
_removeDomInputControl: function() {
this._domInputSprite.dom.removeChild(this._edTxt);
},
/**
* constructor of cc.EditBox
* @param {cc.Size} size
@@ -357,10 +657,6 @@ _ccsg.EditBox = _ccsg.Node.extend({
* @param {cc.Scale9Sprite} press9SpriteBg
* @param {cc.Scale9Sprite} disabled9SpriteBg
*/
_addDomInputControl: function () {
this._domInputSprite.dom.appendChild(this._edTxt);
},
ctor: function (size, normal9SpriteBg, press9SpriteBg, disabled9SpriteBg) {
_ccsg.Node.prototype.ctor.call(this);
@@ -368,29 +664,47 @@ _ccsg.EditBox = _ccsg.Node.extend({
this._placeholderColor = cc.Color.GRAY;
_ccsg.Node.prototype.setContentSize.call(this, size);
var tmpDOMSprite = this._domInputSprite = new _ccsg.Sprite();
tmpDOMSprite.draw = function () {}; //redefine draw function
this.addChild(tmpDOMSprite);
this._spriteDOM = tmpDOMSprite;
this._createDomTextArea();
cc.DOM.convert(tmpDOMSprite);
this._addDomInputControl();
var editBoxImpl = this._nativeControl = new EditBoxImpl(this);
editBoxImpl.createNativeControl(size);
//because cc.DOM.convert will replace editbox's setContentSize method.
//here is a hack to provide a better version of setContentSize.
this._oldSetContentSize = this.setContentSize;
this.setContentSize = this._updateEditBoxSize;
this._domInputSprite.dom.showTooltipDiv = false;
this._domInputSprite.dom.style.width = (size.width - 6) + 'px';
this._domInputSprite.dom.style.height = (size.height - 6) + 'px';
tmpDOMSprite.canvas.remove();
this.initWithSizeAndBackgroundSprite(size, normal9SpriteBg);
this._registerTouchEvent();
this.scheduleOnce(function () {
editBoxImpl.registerClickEvent();
}, 0.01);
},
_registerTouchEvent: function() {
var touchListener = cc.EventListener.create({
event: cc.EventListener.TOUCH_ONE_BY_ONE,
swallowTouches: true,
onTouchBegan: this._onTouchBegan.bind(this),
onTouchEnded: this._onTouchEnded.bind(this),
});
cc.eventManager.addListener(touchListener, this);
},
_onTouchBegan: function (touch, event) {
var touchPoint = touch.getLocation();
var bb = cc.rect(0,0, this._contentSize.width, this._contentSize.height);
var hitted = cc.rectContainsPoint(bb, this.convertToNodeSpace(touchPoint));
if(hitted) {
return true;
}
else {
this._nativeControl.hidden();
return false;
}
},
_onTouchEnded: function (touch, event) {
this._nativeControl.show();
},
_updateBackgroundSpriteSizeAndPosition: function (width, height) {
@@ -407,11 +721,11 @@ _ccsg.EditBox = _ccsg.Node.extend({
var newHeight = size.height || height;
this._updateBackgroundSpriteSizeAndPosition(newWidth, newHeight);
this._nativeControl.setSize(newWidth, newHeight);
},
this._spriteDOM.dom.style.width = (newWidth - 6) + 'px';
this._spriteDOM.dom.style.height = (newHeight - 6) + 'px';
this.setFontSize(height * 2 / 3);
setLineHeight: function (lineHeight) {
this._nativeControl.setLineHeight(lineHeight);
},
/**
@@ -420,18 +734,11 @@ _ccsg.EditBox = _ccsg.Node.extend({
* @param {Number} fontSize The font size.
*/
setFont: function (fontName, fontSize) {
this._edFontSize = fontSize;
this._edFontName = fontName;
this._setFontToEditBox();
this._nativeControl.setFont(fontName, fontSize);
},
_setFont: function (fontStyle) {
var res = cc.LabelTTF._fontStyleRE.exec(fontStyle);
if (res) {
this._edFontSize = parseInt(res[1]);
this._edFontName = res[2];
this._setFontToEditBox();
}
this._nativeControl._setFont(fontStyle);
},
getBackgroundSprite: function() {
@@ -443,8 +750,7 @@ _ccsg.EditBox = _ccsg.Node.extend({
* @param {String} fontName
*/
setFontName: function (fontName) {
this._edFontName = fontName;
this._setFontToEditBox();
this._nativeControl.setFontName(fontName);
},
/**
@@ -452,19 +758,7 @@ _ccsg.EditBox = _ccsg.Node.extend({
* @param {Number} fontSize
*/
setFontSize: function (fontSize) {
this._edFontSize = fontSize;
this._setFontToEditBox();
},
_setFontToEditBox: function () {
if (this._edTxt.value !== this._placeholderText) {
this._edTxt.style.fontFamily = this._edFontName;
this._edTxt.style.fontSize = this._edFontSize + 'px';
if (this._editBoxInputFlag === InputFlag.PASSWORD)
this._edTxt.type = 'password';
else
this._edTxt.type = 'text';
}
this._nativeControl.setFontSize(fontSize);
},
/**
@@ -477,28 +771,12 @@ _ccsg.EditBox = _ccsg.Node.extend({
this.setString(text);
},
/**
* Set the text entered in the edit box.
* @param {string} text The given text.
*/
setString: function (text) {
if (text !== null) {
if (text === '') {
this._edTxt.value = this._placeholderText;
this._edTxt.style.color = cc.colorToHex(this._placeholderColor);
this._edTxt.type = 'text';
} else {
if (text.length >= this._maxLength) {
text = text.slice(0, this._maxLength);
}
this._edTxt.value = text;
this._edTxt.style.color = cc.colorToHex(this._textColor);
if (this._editBoxInputFlag === InputFlag.PASSWORD)
this._edTxt.type = 'password';
else
this._edTxt.type = 'text';
}
if (text.length >= this._maxLength) {
text = text.slice(0, this._maxLength);
}
this._text = text;
this._nativeControl.setString(text);
},
/**
@@ -507,9 +785,7 @@ _ccsg.EditBox = _ccsg.Node.extend({
*/
setFontColor: function (color) {
this._textColor = color;
if (this._edTxt.value !== this._placeholderText) {
this._edTxt.style.color = cc.colorToHex(color);
}
this._nativeControl.setFontColor(color);
},
/**
@@ -522,7 +798,7 @@ _ccsg.EditBox = _ccsg.Node.extend({
setMaxLength: function (maxLength) {
if (!isNaN(maxLength) && maxLength > 0) {
this._maxLength = maxLength;
this._edTxt.maxLength = maxLength;
this._nativeControl.setMaxLength(maxLength);
}
},
@@ -540,13 +816,9 @@ _ccsg.EditBox = _ccsg.Node.extend({
*/
setPlaceHolder: function (text) {
if (text !== null) {
var oldPlaceholderText = this._placeholderText;
//Note: the following calling order matters
this._nativeControl.setPlaceHolder(text);
this._placeholderText = text;
if (this._edTxt.value === oldPlaceholderText) {
this._edTxt.value = text;
this._edTxt.style.color = cc.colorToHex(this._placeholderColor);
this._setPlaceholderFontToEditText();
}
}
},
@@ -558,14 +830,15 @@ _ccsg.EditBox = _ccsg.Node.extend({
setPlaceholderFont: function (fontName, fontSize) {
this._placeholderFontName = fontName;
this._placeholderFontSize = fontSize;
this._setPlaceholderFontToEditText();
this._nativeControl._updateDOMPlaceholderFontStyle();
},
_setPlaceholderFont: function (fontStyle) {
var res = cc.LabelTTF._fontStyleRE.exec(fontStyle);
if (res) {
this._placeholderFontName = res[2];
this._placeholderFontSize = parseInt(res[1]);
this._setPlaceholderFontToEditText();
this._nativeControl._updateDOMPlaceholderFontStyle();
}
},
@@ -575,7 +848,7 @@ _ccsg.EditBox = _ccsg.Node.extend({
*/
setPlaceholderFontName: function (fontName) {
this._placeholderFontName = fontName;
this._setPlaceholderFontToEditText();
this._nativeControl._updateDOMPlaceholderFontStyle();
},
/**
@@ -584,15 +857,7 @@ _ccsg.EditBox = _ccsg.Node.extend({
*/
setPlaceholderFontSize: function (fontSize) {
this._placeholderFontSize = fontSize;
this._setPlaceholderFontToEditText();
},
_setPlaceholderFontToEditText: function () {
if (this._edTxt.value === this._placeholderText) {
this._edTxt.style.fontFamily = this._placeholderFontName;
this._edTxt.style.fontSize = this._placeholderFontSize + 'px';
this._edTxt.type = 'text';
}
this._nativeControl._updateDOMPlaceholderFontStyle();
},
/**
@@ -601,9 +866,7 @@ _ccsg.EditBox = _ccsg.Node.extend({
*/
setPlaceholderFontColor: function (color) {
this._placeholderColor = color;
if (this._edTxt.value === this._placeholderText) {
this._edTxt.style.color = cc.colorToHex(color);
}
this._nativeControl.setPlaceholderFontColor(color);
},
/**
@@ -613,20 +876,7 @@ _ccsg.EditBox = _ccsg.Node.extend({
*/
setInputFlag: function (inputFlag) {
this._editBoxInputFlag = inputFlag;
if ((this._edTxt.value !== this._placeholderText) && (inputFlag === InputFlag.PASSWORD))
this._edTxt.type = 'password';
else
this._edTxt.type = 'text';
if (inputFlag === InputFlag.SENSITIVE || inputFlag === InputFlag.PASSWORD) {
this._edTxt.style.textTransform = 'none';
}
else if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) {
this._edTxt.style.textTransform = 'uppercase';
}
else if (inputFlag === InputFlag.INITIAL_CAPS_SENTENCE || inputFlag === InputFlag.INITIAL_CAPS_WORD) {
this._edTxt.style.textTransform = 'capitalize';
}
this._nativeControl.setInputFlag(inputFlag);
},
/**
@@ -636,7 +886,7 @@ _ccsg.EditBox = _ccsg.Node.extend({
*/
getText: function () {
cc.log('Please use the getString');
return this._edTxt.value;
return this.getString();
},
/**
@@ -644,9 +894,7 @@ _ccsg.EditBox = _ccsg.Node.extend({
* @return {string}
*/
getString: function () {
if(this._edTxt.value === this._placeholderText)
return '';
return this._edTxt.value;
return this._text;
},
/**
@@ -655,16 +903,17 @@ _ccsg.EditBox = _ccsg.Node.extend({
* @param {cc.Color | cc.Scale9Sprite} normal9SpriteBg
*/
initWithSizeAndBackgroundSprite: function (size, normal9SpriteBg) {
if(this._backgroundSprite) {
this._backgroundSprite.removeFromParent();
}
this._backgroundSprite = normal9SpriteBg;
if(this._backgroundSprite) {
if(this._backgroundSprite && !this._backgroundSprite.parent) {
this.addChild(this._backgroundSprite);
this._updateBackgroundSpriteSizeAndPosition(size.width, size.height);
}
this._domInputSprite.x = 3;
this._domInputSprite.y = 3;
this.x = 0;
this.y = 0;
@@ -698,19 +947,11 @@ _ccsg.EditBox = _ccsg.Node.extend({
var oldText = this.getString();
if (inputMode === InputMode.ANY) {
this._removeDomInputControl();
this._createDomTextArea();
this._addDomInputControl();
}
else if(this._editBoxInputMode === InputMode.ANY) {
this._removeDomInputControl();
this._createDomInput();
this._addDomInputControl();
}
this._nativeControl.setInputMode(inputMode);
this.setString(oldText);
this._editBoxInputMode = inputMode;
this._nativeControl._updateLabelPosition(this.getContentSize());
},
/**
@@ -774,19 +1015,19 @@ _p.maxLength;
cc.defineGetterSetter(_p, 'maxLength', _p.getMaxLength, _p.setMaxLength);
/** @expose */
_p.placeHolder;
cc.defineGetterSetter(_p, 'placeHolder', _p.getPlaceHolder, _p.setPlaceHolder);
cc.defineGetterSetter(_p, 'placeholder', _p.getPlaceHolder, _p.setPlaceHolder);
/** @expose */
_p.placeHolderFont;
cc.defineGetterSetter(_p, 'placeHolderFont', null, _p._setPlaceholderFont);
cc.defineGetterSetter(_p, 'placeholderFont', null, _p._setPlaceholderFont);
/** @expose */
_p.placeHolderFontName;
cc.defineGetterSetter(_p, 'placeHolderFontName', null, _p.setPlaceholderFontName);
cc.defineGetterSetter(_p, 'placeholderFontName', null, _p.setPlaceholderFontName);
/** @expose */
_p.placeHolderFontSize;
cc.defineGetterSetter(_p, 'placeHolderFontSize', null, _p.setPlaceholderFontSize);
cc.defineGetterSetter(_p, 'placeholderFontSize', null, _p.setPlaceholderFontSize);
/** @expose */
_p.placeHolderFontColor;
cc.defineGetterSetter(_p, 'placeHolderFontColor', null, _p.setPlaceholderFontColor);
cc.defineGetterSetter(_p, 'placeholderFontColor', null, _p.setPlaceholderFontColor);
/** @expose */
_p.inputFlag;
cc.defineGetterSetter(_p, 'inputFlag', null, _p.setInputFlag);
+2 -1
View File
@@ -324,6 +324,7 @@ cc.DOM.methods = /** @lends cc.DOM# */{
* @param {Boolean} x
*/
setVisible:function (x) {
_ccsg.Node.prototype.setVisible.call(this, x);
this._visible = x;
this.setNodeDirty();
if (this.dom)
@@ -602,7 +603,7 @@ cc.DOM.forSprite = function (x) {
cc.DOM.placeHolder = function (x) {
//creating a placeholder dom to simulate other ccNode in the hierachy
x.dom = cc.$new('div');
x.placeholder = true;
// x.placeholder = true;
x.dom.style.position = 'absolute';
x.dom.style.bottom = 0;
//x.dom.style.display='block';
@@ -141,7 +141,7 @@ cc.EventListener = cc._Class.extend(/** @lends cc.EventListener# */{
/**
* Sets scene graph priority for this listener
* @param {_ccsg.Node|cc.Node} node
* @param {_ccsg.Node|Node} node
* @private
*/
_setSceneGraphPriority: function (node) {
+110 -1
View File
@@ -145,6 +145,15 @@ JS.mixin(EventMouse.prototype, {
this._prevY = y;
},
/**
* Returns the previous touch location.
* @method getPreviousLocation
* @return {Vec2}
*/
getPreviousLocation:function () {
return {x: this._prevX, y: this._prevY};
},
/**
* Returns the delta distance from the previous location to current location.
* @method getDelta
@@ -305,7 +314,7 @@ EventMouse.BUTTON_8 = 7;
* @param {Array} [touchArr=[]] - The array of the touches
* @param {Boolean} [bubbles=false] - A boolean indicating whether the event bubbles up through the tree or not
*/
EventTouch = function (touchArr, bubbles) {
var EventTouch = function (touchArr, bubbles) {
cc.Event.call(this, cc.Event.TOUCH, bubbles);
this._eventCode = 0;
this._touches = touchArr || [];
@@ -338,6 +347,106 @@ JS.mixin(EventTouch.prototype, {
_setTouches: function (touches) {
this._touches = touches;
},
/**
* Sets touch location.
* @method setLocation
* @param {Number} x
* @param {Number} y
*/
setLocation: function (x, y) {
this.touch && this.touch.setTouchInfo(this.touch.getID(), x, y);
},
/**
* Returns touch location.
* @method getLocation
* @return {Vec2} location
*/
getLocation: function () {
return this.touch ? this.touch.getLocation() : cc.v2();
},
/**
* Returns the current touch location in screen coordinates.
* @method getLocationInView
* @return {Vec2}
*/
getLocationInView: function() {
return this.touch ? this.touch.getLocationInView() : cc.v2();
},
/**
* Returns the previous touch location.
* @method getPreviousLocation
* @return {Vec2}
*/
getPreviousLocation:function () {
return this.touch ? this.touch.getPreviousLocation() : cc.v2();
},
/**
* Returns the start touch location.
* @method getStartLocation
* @returns {Vec2}
*/
getStartLocation: function() {
return this.touch ? this.touch.getStartLocation() : cc.v2();
},
/**
* Returns the id of cc.Touch.
* @method getID
* @return {Number}
*/
getID:function () {
return this.touch ? this.getID() : null;
},
/**
* Returns the delta distance from the previous location to current location.
* @method getDelta
* @return {Vec2}
*/
getDelta: function () {
return this.touch ? this.touch.getDelta() : cc.v2();
},
/**
* Returns the X axis delta distance from the previous location to current location.
* @method getDeltaX
* @return {Number}
*/
getDeltaX: function () {
return this.touch ? this.touch.getDelta().x : 0;
},
/**
* Returns the Y axis delta distance from the previous location to current location.
* @method getDeltaY
* @return {Number}
*/
getDeltaY: function () {
return this.touch ? this.touch.getDelta().y : 0;
},
/**
* Returns location X axis data.
* @method getLocationX
* @returns {Number}
*/
getLocationX: function () {
return this.touch ? this.touch.getLocationX() : 0;
},
/**
* Returns location Y axis data.
* @method getLocationY
* @returns {Number}
*/
getLocationY: function () {
return this.touch ? this.touch.getLocationY() : 0;
}
});
+3 -14
View File
@@ -108,7 +108,7 @@ cc.Touch = cc._Class.extend(/** @lends cc.Touch# */{
* @return {Vec2}
*/
getLocationInView: function() {
return {x: this._point.x, y: this._point.y};
return {x: this._point.x, y: cc.view._designResolutionSize.height - this._point.y};
},
/**
@@ -117,7 +117,7 @@ cc.Touch = cc._Class.extend(/** @lends cc.Touch# */{
* @return {Vec2}
*/
getPreviousLocationInView: function(){
return {x: this._prevPoint.x, y: this._prevPoint.y};
return {x: this._prevPoint.x, y: cc.view._designResolutionSize.height - this._prevPoint.y};
},
/**
@@ -126,7 +126,7 @@ cc.Touch = cc._Class.extend(/** @lends cc.Touch# */{
* @return {Vec2}
*/
getStartLocationInView: function(){
return {x: this._startPoint.x, y: this._startPoint.y};
return {x: this._startPoint.x, y: cc.view._designResolutionSize.height - this._startPoint.y};
},
/**
@@ -138,17 +138,6 @@ cc.Touch = cc._Class.extend(/** @lends cc.Touch# */{
return this._id;
},
/**
* Returns the id of cc.Touch.
* @method getId
* @return {Number}
* @deprecated since v3.0, please use getID() instead
*/
getId:function () {
cc.log("getId is deprecated. Please use getID instead.")
return this._id;
},
/**
* Sets information to touch.
* @method setTouchInfo
+2 -2
View File
@@ -46,9 +46,9 @@ cc.Event = function(type, bubbles) {
this.type = type;
/**
* A reference to the target to which the event was originally dispatched.
* Indicate whether the event bubbles up through the tree or not.
* @property bubbles
* @type {Object}
* @type {Boolean}
*/
this.bubbles = bubbles || false;
+8 -13
View File
@@ -328,7 +328,7 @@ _ccsg.Label = _ccsg.Node.extend({
this._resetBMFont();
//specify font family name directly
if (extName === null) {
if (!extName) {
this._fontHandle = fontHandle;
this._labelType = _ccsg.Label.Type.SystemFont;
this._notifyLabelSkinDirty();
@@ -336,8 +336,6 @@ _ccsg.Label = _ccsg.Node.extend({
this.emit('load');
return;
}
//add resource path
fontHandle = cc.path.join(cc.loader.resPath, fontHandle);
this._isUseSystemFont = false;
if (extName === ".ttf") {
@@ -685,8 +683,7 @@ cc.BMFontHelper = {
var longestLine = 0;
var letterRight = 0;
var contentScaleFactor = cc.contentScaleFactor();
var lineSpacing = this._lineSpacing * contentScaleFactor;
var lineSpacing = this._lineSpacing;
var highestY = 0;
var lowestY = 0;
var letterDef = null;
@@ -728,7 +725,7 @@ cc.BMFontHelper = {
continue;
}
var letterX = (nextLetterX + letterDef._offsetX * this._bmfontScale) / contentScaleFactor;
var letterX = nextLetterX + letterDef._offsetX * this._bmfontScale;
if (this._isWrapText
&& this._maxLineWidth > 0
@@ -746,7 +743,7 @@ cc.BMFontHelper = {
letterPosition.x = letterX;
}
letterPosition.y = (nextTokenY - letterDef._offsetY * this._bmfontScale) / contentScaleFactor;
letterPosition.y = nextTokenY - letterDef._offsetY * this._bmfontScale;
this._recordLetterInfo(letterPosition, character, letterIndex, lineIndex);
if (letterIndex + 1 < this._horizontalKernings.length && letterIndex < textLen - 1) {
@@ -788,7 +785,7 @@ cc.BMFontHelper = {
this._linesWidth.push(letterRight);
this._numberOfLines = lineIndex + 1;
this._textDesiredHeight = (this._numberOfLines * this._lineHeight * this._bmfontScale) / contentScaleFactor;
this._textDesiredHeight = this._numberOfLines * this._lineHeight * this._bmfontScale;
if (this._numberOfLines > 1) {
this._textDesiredHeight += (this._numberOfLines - 1) * this._lineSpacing;
}
@@ -1001,7 +998,7 @@ cc.BMFontHelper = {
_updateBMFontScale: function() {
if (this._labelType === _ccsg.Label.Type.BMFont) {
var originalFontSize = this._fontAtlas._fontSize;
this._bmfontScale = this._fontSize * cc.contentScaleFactor() / originalFontSize;
this._bmfontScale = this._fontSize / originalFontSize;
} else {
this._bmfontScale = 1;
}
@@ -1047,8 +1044,6 @@ cc.BMFontHelper = {
var letterDefinition = new cc.FontLetterDefinition();
var tempRect = locFontDict[fontDef].rect;
cc.rectPointsToPixels(tempRect);
letterDefinition._offsetX = locFontDict[fontDef].xOffset;
letterDefinition._offsetY = locFontDict[fontDef].yOffset;
@@ -1098,12 +1093,12 @@ cc.BMFontHelper = {
this._resetBMFont();
var texture;
cc.loader.load(this._fontHandle, function(err, results) {
cc.loader.load(this._fontHandle, function(err, config) {
if (err) {
cc.log("_ccsg.Label._initBMFontWithString(): Impossible to create font. Please check file");
}
self._config = results[0];
self._config = config;
self._createFontChars();
texture = cc.textureCache.addImage(self._config.atlasName);
var locIsLoaded = texture.isLoaded();
@@ -180,6 +180,12 @@
node._labelSkinDirty = true;
};
proto._syncDisplayColor = function (parentColor) {
_ccsg.Node.RenderCmd.prototype._syncDisplayColor.call(this, parentColor);
var node = this._node;
node._labelSkinDirty = true;
};
proto._calculateLabelFont = function(canvasSize) {
var node = this._node;
var paragraphedStrings = node._string.split('\n');
-103
View File
@@ -1,103 +0,0 @@
cc._fntLoader = {
INFO_EXP: /info [^\n]*(\n|$)/gi,
COMMON_EXP: /common [^\n]*(\n|$)/gi,
PAGE_EXP: /page [^\n]*(\n|$)/gi,
CHAR_EXP: /char [^\n]*(\n|$)/gi,
KERNING_EXP: /kerning [^\n]*(\n|$)/gi,
ITEM_EXP: /\w+=[^ \r\n]+/gi,
INT_EXP: /^[\-]?\d+$/,
_parseStrToObj: function (str) {
var arr = str.match(this.ITEM_EXP);
var obj = {};
if (arr) {
for (var i = 0, li = arr.length; i < li; i++) {
var tempStr = arr[i];
var index = tempStr.indexOf("=");
var key = tempStr.substring(0, index);
var value = tempStr.substring(index + 1);
if (value.match(this.INT_EXP)) value = parseInt(value);
else if (value[0] === '"') value = value.substring(1, value.length - 1);
obj[key] = value;
}
}
return obj;
},
/**
* Parse Fnt string.
* @param fntStr
* @param url
* @returns {{}}
*/
parseFnt: function (fntStr, url) {
var self = this, fnt = {};
//padding
var infoObj = self._parseStrToObj(fntStr.match(self.INFO_EXP)[0]);
var paddingArr = infoObj["padding"].split(",");
var padding = {
left: parseInt(paddingArr[0]),
top: parseInt(paddingArr[1]),
right: parseInt(paddingArr[2]),
bottom: parseInt(paddingArr[3])
};
//common
var commonObj = self._parseStrToObj(fntStr.match(self.COMMON_EXP)[0]);
fnt.commonHeight = commonObj["lineHeight"];
//font size
fnt.fontSize = infoObj["size"];
if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
var texSize = cc.configuration.getMaxTextureSize();
if (commonObj["scaleW"] > texSize.width || commonObj["scaleH"] > texSize.height)
cc.log("cc.LabelBMFont._parseCommonArguments(): page can't be larger than supported");
}
if (commonObj["pages"] !== 1) cc.log("cc.LabelBMFont._parseCommonArguments(): only supports 1 page");
//page
var pageObj = self._parseStrToObj(fntStr.match(self.PAGE_EXP)[0]);
if (pageObj["id"] !== 0) cc.log("cc.LabelBMFont._parseImageFileName() : file could not be found");
fnt.atlasName = cc.path.changeBasename(url, pageObj["file"]);
//char
var charLines = fntStr.match(self.CHAR_EXP);
var fontDefDictionary = fnt.fontDefDictionary = {};
for (var i = 0, li = charLines.length; i < li; i++) {
var charObj = self._parseStrToObj(charLines[i]);
var charId = charObj["id"];
fontDefDictionary[charId] = {
rect: {x: charObj["x"], y: charObj["y"], width: charObj["width"], height: charObj["height"]},
xOffset: charObj["xoffset"],
yOffset: charObj["yoffset"],
xAdvance: charObj["xadvance"]
};
}
//kerning
var kerningDict = fnt.kerningDict = {};
var kerningLines = fntStr.match(self.KERNING_EXP);
if (kerningLines) {
for (var i = 0, li = kerningLines.length; i < li; i++) {
var kerningObj = self._parseStrToObj(kerningLines[i]);
kerningDict[(kerningObj["first"] << 16) | (kerningObj["second"] & 0xffff)] = kerningObj["amount"];
}
}
return fnt;
},
/**
* load the fnt
* @param realUrl
* @param url
* @param res
* @param cb
*/
load: function (realUrl, url, res, cb) {
var self = this;
cc.loader.loadTxt(realUrl, function (err, txt) {
if (err) return cb(err);
cb(null, self.parseFnt(txt, url));
});
}
};
cc.loader.register(["fnt"], cc._fntLoader);
+8 -15
View File
@@ -272,7 +272,7 @@ cc.LabelTTF = _ccsg.Sprite.extend(/** @lends cc.LabelTTF# */{
* @return {cc.FontDefinition}
*/
getTextDefinition: function () {
return this._prepareTextDefinition(false);
return this._prepareTextDefinition();
},
/**
@@ -535,18 +535,12 @@ cc.LabelTTF = _ccsg.Sprite.extend(/** @lends cc.LabelTTF# */{
this._renderCmd.setDirtyFlag(flags.colorDirty|flags.opacityDirty|flags.textDirty);
},
_prepareTextDefinition: function (adjustForResolution) {
_prepareTextDefinition: function () {
var texDef = new cc.FontDefinition();
if (adjustForResolution) {
texDef.fontSize = this._fontSize;
texDef.boundingWidth = cc.contentScaleFactor() * this._dimensions.width;
texDef.boundingHeight = cc.contentScaleFactor() * this._dimensions.height;
} else {
texDef.fontSize = this._fontSize;
texDef.boundingWidth = this._dimensions.width;
texDef.boundingHeight = this._dimensions.height;
}
texDef.fontSize = this._fontSize;
texDef.boundingWidth = this._dimensions.width;
texDef.boundingHeight = this._dimensions.height;
texDef.fontName = this._fontName;
texDef.textAlign = this._hAlignment;
@@ -567,8 +561,8 @@ cc.LabelTTF = _ccsg.Sprite.extend(/** @lends cc.LabelTTF# */{
texDef.shadowBlur = this._shadowBlur;
texDef.shadowOpacity = this._shadowOpacity;
texDef.shadowOffsetX = (adjustForResolution ? cc.contentScaleFactor() : 1) * this._shadowOffset.x;
texDef.shadowOffsetY = (adjustForResolution ? cc.contentScaleFactor() : 1) * this._shadowOffset.y;
texDef.shadowOffsetX = this._shadowOffset.x;
texDef.shadowOffsetY = this._shadowOffset.y;
} else
texDef._shadowEnabled = false;
@@ -735,8 +729,7 @@ cc.LabelTTF = _ccsg.Sprite.extend(/** @lends cc.LabelTTF# */{
},
setTextureRect: function (rect, rotated, untrimmedSize) {
//set needConvert to false
_ccsg.Sprite.prototype.setTextureRect.call(this, rect, rotated, untrimmedSize, false);
_ccsg.Sprite.prototype.setTextureRect.call(this, rect, rotated, untrimmedSize);
},
/**
+245
View File
@@ -0,0 +1,245 @@
/****************************************************************************
Copyright (c) 2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
var JS = require('../platform/js');
var Pipeline = require('./pipeline');
var Downloader = require('./downloader');
var Loader = require('./loader');
var downloader = new Downloader();
var loader = new Loader();
/**
* Loader for resource loading process. It's a singleton object.
* @class loader
* @static
*/
cc.loader = new Pipeline([
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.
* You can add your own download function with addDownloadHandlers
* @property downloader
* @type {Object}
*/
downloader: downloader,
/**
* The downloader in cc.loader's pipeline, it's by default the second pipe.
* It's used to parse downloaded content with several handlers: JSON, image, plist, fnt, uuid.
* You can add your own download function with addLoadHandlers
* @property loader
* @type {Object}
*/
loader: loader,
/**
* Get XMLHttpRequest.
* @returns {XMLHttpRequest}
*/
getXMLHttpRequest: Pipeline.getXMLHttpRequest,
/**
* Add custom supported types handler or modify existing type handler for download process.
* @example
* cc.loader.addDownloadHandlers({
* // This will match all url with `.scene` extension or all url with `scene` type
* 'scene' : function (url, callback) {}
* });
* @method addDownloadHandlers
* @param {Object} extMap Custom supported types with corresponded handler
*/
addDownloadHandlers: function (extMap) {
downloader.addHandlers(extMap);
},
/**
* Add custom supported types handler or modify existing type handler for load process.
* @example
* cc.loader.addLoadHandlers({
* // This will match all url with `.scene` extension or all url with `scene` type
* 'scene' : function (url, callback) {}
* });
* @method addLoadHandlers
* @param {Object} extMap Custom supported types with corresponded handler
*/
addLoadHandlers: function (extMap) {
loader.addHandlers(extMap);
},
/**
* Load resources with a progression callback and a complete callback.
* The progression callback is the same as Pipeline's {{#crossLink "Pipeline/onProgress:method"}}onProgress{{/crossLink}}
* The complete callback is almost the same as Pipeline's {{#crossLink "Pipeline/onComplete:method"}}onComplete{{/crossLink}}
* The only difference is when user pass a single url as resources, the complete callback will set its result directly as the second parameter.
*
* @example
* cc.loader.load('a.png', function (err, tex) {
* cc.log('Result should be a texture: ' + (tex instanceof cc.Texture2D));
* });
*
*
* cc.loader.load(['a.png', 'b.json'], function (errors, results) {
* if (errors) {
* for (var i = 0; i < errors.length; i++) {
* cc.log('Error url [' + errors[i] + ']: ' + results.getError(errors[i]));
* }
* }
* var aTex = results.getContent('a.png');
* var bJsonObj = results.getContent('b.json');
* });
*
* @method load
* @param {String|Array} resources - Url list in an array
* @param {[Function]} progressCallback - Callback invoked when progression change
* @param {Function} completeCallback - Callback invoked when all resources loaded
*/
load: function(resources, progressCallback, completeCallback) {
if (completeCallback === undefined) {
completeCallback = progressCallback;
progressCallback = null;
}
var singleRes = false;
if (!(resources instanceof Array)) {
resources = resources ? [resources] : [];
singleRes = true;
}
// Return directly if no resources
if (resources.length === 0) {
completeCallback && completeCallback.call(this, null, this._items);
}
// Resolve callback
var error = null;
var checker = {};
var totalCount = 0;
var completedCount = 0;
var self = this;
function loadedCheck (item) {
checker[item.src] = item;
if (item.error) {
error = error || [];
error.push(item.src);
}
completedCount++;
progressCallback && progressCallback.call(self, completedCount, totalCount, item);
for (var url in checker) {
// Not done yet
if (!checker[url]) {
return;
}
}
// All url completed
if (completeCallback) {
if (singleRes) {
completeCallback.call(self, item.error, item.content);
}
else {
completeCallback.call(self, error, self._items);
}
}
}
// Add loaded listeners
for (var i = 0; i < resources.length; ++i) {
var url = resources[i].src || resources[i];
if (typeof url !== 'string')
continue;
var item = this._items.map[url];
if ( !item || (item && !item.complete) ) {
this._items.add(url, loadedCheck);
checker[url] = null;
totalCount++;
}
else if (item && item.complete) {
checker[url] = item;
totalCount++;
completedCount++;
}
}
// No new resources, complete directly
if (totalCount === completedCount) {
if (singleRes) {
var src = resources[0].src || resources[0];
var result = this._items.map[src];
completeCallback.call(this, result.error, result.content);
}
else {
completeCallback.call(this, null, this._items);
}
}
else {
this.flowIn(resources);
}
},
/**
* Get resource data by url.
*
* @method getRes
* @param {String} url
* @returns {*}
*/
getRes: function (url) {
var item = this._items.map[url];
if (item && item.complete) {
return item.content;
}
else {
return null;
}
},
/**
* Release the cache of resource by url.
*
* @method release
* @param {String} url
*/
release: function (url) {
this.removeItem(url);
},
/**
* Resource cache of all resources.
*
* @method releaseAll
*/
releaseAll: function () {
this.clear();
}
});
module.exports = cc.loader;
@@ -0,0 +1,177 @@
/****************************************************************************
Copyright (c) 2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
var Path = require('../utils/CCPath');
var Sys = require('../platform/CCSys');
var Pipeline = require('./pipeline');
require('../../audio/CCAudio');
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);
}
url = Path.changeExtname(url, typeList.splice(0, 1));
if (__audioSupport.WEB_AUDIO) {//Buffer
if (__audioSupport.webAudioCallback) {
__audioSupport.webAudioCallback(url);
}
var request = Pipeline.getXMLHttpRequest();
request.open('GET', url, true);
request.responseType = 'arraybuffer';
request.onload = function () {
context['decodeAudioData'](request.response, function (buffer) {
//success
audio.setBuffer(buffer);
cb(null, audio);
}, function() {
//error
loadAudioFromExtList(url, typeList, audio, cb);
});
};
request.onerror = function () {
cb({status: 520, errorMessage: ERRSTR}, null);
};
request.send();
} else {//DOM
var element = document.createElement('audio');
var cbCheck = false;
var termination = false;
var timer = setTimeout(function () {
if (element.readyState === 0) {
emptied();
} else {
termination = true;
element.pause();
document.body.removeChild(element);
cb('Audio load timeout : ' + url, audio);
}
}, 8000);
var success = function () {
if (!cbCheck) {
//element.pause();
try {
element.currentTime = 0;
element.volume = 1;
} catch (e) {}
document.body.removeChild(element);
audio.setElement(element);
element.removeEventListener('canplaythrough', success, false);
element.removeEventListener('error', failure, false);
element.removeEventListener('emptied', emptied, false);
!termination && cb(null, audio);
cbCheck = true;
clearTimeout(timer);
}
};
var failure = function(){
if (!cbCheck) return;
//element.pause();
document.body.removeChild(element);
element.removeEventListener('canplaythrough', success, false);
element.removeEventListener('error', failure, false);
element.removeEventListener('emptied', emptied, false);
!termination && loadAudioFromExtList(url, typeList, audio, cb);
cbCheck = true;
clearTimeout(timer);
};
var emptied = function(){
termination = true;
success();
cb(null, audio);
};
element.addEventListener('canplaythrough', success, false);
element.addEventListener('error', failure, false);
if(__audioSupport.USE_EMPTIED_EVENT)
element.addEventListener('emptied', emptied, false);
element.src = url;
document.body.appendChild(element);
element.volume = 0;
//some browsers cannot pause(qq 6.1)
//element.play();
}
}
function downloadAudio (item, callback) {
if (formatSupport.length === 0) {
return callback( new Error('Audio Downloader: audio not supported on this browser!') );
}
var url = item.src,
extname = Path.extname(url),
typeList = [extname],
i, audio;
// Generate all types
for (i = 0; i < formatSupport.length; i++) {
if (extname !== formatSupport[i]) {
typeList.push(formatSupport[i]);
}
}
if (__audioSupport.WEB_AUDIO) {
try {
var volume = context['createGain']();
volume['gain'].value = 1;
volume['connect'](context['destination']);
audio = new cc.Audio(context, volume, url);
if (__audioSupport.NEED_MANUAL_LOOP) {
audio._manualLoop = true;
}
} catch(err) {
__audioSupport.WEB_AUDIO = false;
cc.warn('The current browser don\'t support web audio');
audio = new cc.Audio(null, null, url);
}
} else {
audio = new cc.Audio(null, null, url);
}
// hack for audio to be found before loaded
item.content = audio;
loadAudioFromExtList(url, typeList, audio, callback);
}
module.exports = downloadAudio;
@@ -0,0 +1,117 @@
/****************************************************************************
Copyright (c) 2015-2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the 'Software'), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
function _str2Uint8Array (strData) {
if (!strData)
return null;
var arrData = new Uint8Array(strData.length);
for (var i = 0; i < strData.length; i++) {
arrData[i] = strData.charCodeAt(i) & 0xff;
}
return arrData;
}
var navigator = window.navigator;
var _IEFilter = (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent));
//Compatibility with IE9
window.Uint8Array = window.Uint8Array || window.Array;
if (_IEFilter) {
var IEBinaryToArray_ByteStr_Script =
'<!-- IEBinaryToArray_ByteStr -->\r\n' +
//'<script type='text/vbscript'>\r\n' +
'Function IEBinaryToArray_ByteStr(Binary)\r\n' +
' IEBinaryToArray_ByteStr = CStr(Binary)\r\n' +
'End Function\r\n' +
'Function IEBinaryToArray_ByteStr_Last(Binary)\r\n' +
' Dim lastIndex\r\n' +
' lastIndex = LenB(Binary)\r\n' +
' if lastIndex mod 2 Then\r\n' +
' IEBinaryToArray_ByteStr_Last = Chr( AscB( MidB( Binary, lastIndex, 1 ) ) )\r\n' +
' Else\r\n' +
' IEBinaryToArray_ByteStr_Last = ' + '""' + '\r\n' +
' End If\r\n' +
'End Function\r\n';// +
//'</script>\r\n';
// inject VBScript
//document.write(IEBinaryToArray_ByteStr_Script);
var myVBScript = document.createElement('script');
myVBScript.type = 'text/vbscript';
myVBScript.textContent = IEBinaryToArray_ByteStr_Script;
document.body.appendChild(myVBScript);
// helper to convert from responseBody to a 'responseText' like thing
var _convertResponseBodyToText = function(binary) {
var byteMapping = {};
for (var i = 0; i < 256; i++) {
for (var j = 0; j < 256; j++) {
byteMapping[ String.fromCharCode(i + j * 256) ] =
String.fromCharCode(i) + String.fromCharCode(j);
}
}
var rawBytes = IEBinaryToArray_ByteStr(binary);
var lastChr = IEBinaryToArray_ByteStr_Last(binary);
return rawBytes.replace(/[\s\S]/g,
function (match) {
return byteMapping[match];
}) + lastChr;
};
}
function downloadBinary (url, callback) {
var self = this;
var xhr = this.getXMLHttpRequest(),
errInfo = 'Load ' + url + ' failed!';
xhr.open('GET', url, true);
if (_IEFilter) {
// IE-specific logic here
xhr.setRequestHeader('Accept-Charset', 'x-user-defined');
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && (xhr.status === 200 || (CC_TEST && xhr.status === 0))) {
var fileContents = _convertResponseBodyToText(xhr['responseBody']);
callback(null, self._str2Uint8Array(fileContents));
}
else {
callback(errInfo);
}
};
} else {
if (xhr.overrideMimeType) xhr.overrideMimeType('text\/plain; charset=x-user-defined');
xhr.onload = function () {
if (xhr.readyState === 4 && (xhr.status === 200 || (CC_TEST && xhr.status === 0))) {
callback(null, self._str2Uint8Array(xhr.responseText));
}
else {
callback(errInfo);
}
};
}
xhr.send(null);
};
module.exports = downloadBinary;
+403
View File
@@ -0,0 +1,403 @@
/****************************************************************************
Copyright (c) 2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
var JS = require('../platform/js');
var Path = require('../utils/CCPath');
var Pipeline = require('./pipeline');
var downloadAudio;
if (!CC_EDITOR || !Editor.isCoreLevel) {
downloadAudio = require('./audio-downloader');
}
else {
downloadAudio = null;
}
// var downloadBinary = require('binary-downloader');
var _noCacheRex = /\?/;
function urlAppendTimestamp (url) {
if (cc.game.config['noCache'] && typeof url === 'string') {
if(_noCacheRex.test(url))
url += '&_t=' + (new Date() - 0);
else
url += '?_t=' + (new Date() - 0);
}
return url;
}
function downloadScript (item, callback, isAsync) {
var url = item.src,
d = document,
s = document.createElement('script');
s.async = isAsync;
s.src = urlAppendTimestamp(url);
function loadHandler () {
s.parentNode.removeChild(s);
s.removeEventListener('load', loadHandler, false);
s.removeEventListener('error', errorHandler, false);
callback(null, url);
}
function errorHandler() {
s.parentNode.removeChild(s);
s.removeEventListener('load', loadHandler, false);
s.removeEventListener('error', errorHandler, false);
callback(new Error('Load ' + url + ' failed!'), url);
}
s.addEventListener('load', loadHandler, false);
s.addEventListener('error', errorHandler, false);
d.body.appendChild(s);
}
function downloadText (item, callback) {
var url = item.src,
xhr = Pipeline.getXMLHttpRequest(),
errInfo = 'Load ' + url + ' failed!',
navigator = window.navigator;
url = urlAppendTimestamp(url);
xhr.open('GET', url, true);
if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
// IE-specific logic here
xhr.setRequestHeader('Accept-Charset', 'utf-8');
xhr.onreadystatechange = function () {
if(xhr.readyState === 4) {
if (xhr.status === 200 || xhr.status === 0) {
callback(null, xhr.responseText);
}
else {
callback({status:xhr.status, errorMessage:errInfo});
}
}
};
} else {
if (xhr.overrideMimeType) xhr.overrideMimeType('text\/plain; charset=utf-8');
xhr.onload = function () {
if(xhr.readyState === 4) {
if (xhr.status === 200 || xhr.status === 0) {
callback(null, xhr.responseText);
}
else {
callback({status:xhr.status, errorMessage:errInfo});
}
}
};
xhr.onerror = function(){
callback({status:xhr.status, errorMessage:errInfo});
};
}
xhr.send(null);
}
function downloadTextSync (item) {
var url = item.src;
var xhr = Pipeline.getXMLHttpRequest();
xhr.open('GET', url, false);
if (/msie/i.test(window.navigator.userAgent) && !/opera/i.test(window.navigator.userAgent)) {
// IE-specific logic here
xhr.setRequestHeader('Accept-Charset', 'utf-8');
} else {
if (xhr.overrideMimeType) xhr.overrideMimeType('text\/plain; charset=utf-8');
}
xhr.send(null);
if (xhr.readyState !== 4 || !(xhr.status === 200 || xhr.status === 0)) {
return null;
}
return xhr.responseText;
}
function downloadImage (item, callback, isCrossOrigin) {
if (isCrossOrigin === undefined) {
isCrossOrigin = true;
}
var url = urlAppendTimestamp(item.src);
var img = new Image();
if (isCrossOrigin && window.location.origin !== 'file://') {
img.crossOrigin = 'Anonymous';
}
if (img.complete && img.naturalWidth > 0) {
callback(null, img);
}
else {
function loadCallback () {
img.removeEventListener('load', loadCallback);
img.removeEventListener('error', errorCallback);
if (callback) {
callback(null, img);
}
}
function errorCallback () {
img.removeEventListener('load', loadCallback);
img.removeEventListener('error', errorCallback);
if (img.crossOrigin && img.crossOrigin.toLowerCase() === 'anonymous') {
downloadImage(url, callback, false);
}
else {
callback('Load image (' + url + ') failed');
}
}
img.addEventListener('load', loadCallback);
img.addEventListener('error', errorCallback);
}
img.src = url;
}
var FONT_TYPE = {
'.eot' : 'embedded-opentype',
'.ttf' : 'truetype',
'.ttc' : 'truetype',
'.woff' : 'woff',
'.svg' : 'svg'
};
function _loadFont (name, srcs, type){
var doc = document,
path = cc.path,
fontStyle = document.createElement('style');
fontStyle.type = 'text/css';
doc.body.appendChild(fontStyle);
var fontStr = '';
if (isNaN(name - 0)) {
fontStr += '@font-face { font-family:' + name + '; src:';
}
else {
fontStr += '@font-face { font-family:\'' + name + '\'; src:';
}
if (srcs instanceof Array) {
for (var i = 0, li = srcs.length; i < li; i++) {
var src = srcs[i];
type = path.extname(src).toLowerCase();
fontStr += 'url(\'' + srcs[i] + '\') format(\'' + FONT_TYPE[type] + '\')';
fontStr += (i === li - 1) ? ';' : ',';
}
} else {
type = type.toLowerCase();
fontStr += 'url(\'' + srcs + '\') format(\'' + FONT_TYPE[type] + '\');';
}
fontStyle.textContent += fontStr + '}';
//<div style="font-family: PressStart;">.</div>
var preloadDiv = document.createElement('div');
var _divStyle = preloadDiv.style;
_divStyle.fontFamily = name;
preloadDiv.innerHTML = '.';
_divStyle.position = 'absolute';
_divStyle.left = '-100px';
_divStyle.top = '-100px';
doc.body.appendChild(preloadDiv);
}
function downloadFont (item, callback) {
var url = item.src,
type = item.type,
name = item.name,
srcs = item.srcs;
if (name && srcs) {
if (srcs.indexOf(url) === -1) {
srcs.push(url);
}
_loadFont(name, srcs);
} else {
type = cc.path.extname(url);
name = cc.path.basename(url, type);
_loadFont(name, url, type);
}
if (document.fonts) {
document.fonts.load('1em ' + name).then(function () {
callback(null, null);
}, function(err){
callback(err);
});
} else {
callback(null, null);
}
}
function downloadUuid (item, callback) {
var uuid = item.src;
var self = this;
cc.AssetLibrary.queryAssetInfo(uuid, function (error, url, isRawAsset) {
if (error) {
callback(error);
}
else {
item.url = url;
item.isRawAsset = isRawAsset;
if (isRawAsset) {
var ext = Path.extname(url).toLowerCase();
if (!ext) {
callback(new Error('Download Uuid: can not find type of raw asset[' + uuid + ']: ' + url));
return;
}
ext = ext.substr(1);
// Dispatch to other raw type downloader
var downloadFunc = self.extMap[ext] || self.extMap['default'];
item.type = ext;
downloadFunc({src: url}, callback);
}
else {
self.extMap['json']({src: url}, callback);
}
}
});
}
var defaultMap = {
// JS
'js' : downloadScript,
// Images
'png' : downloadImage,
'jpg' : downloadImage,
'bmp' : downloadImage,
'jpeg' : downloadImage,
'gif' : downloadImage,
'ico' : downloadImage,
'tiff' : downloadImage,
'webp' : downloadImage,
'image' : downloadImage,
// Audio
'mp3' : downloadAudio,
'ogg' : downloadAudio,
'wav' : downloadAudio,
'mp4' : downloadAudio,
'm4a' : downloadAudio,
// Txt
'txt' : downloadText,
'xml' : downloadText,
'vsh' : downloadText,
'fsh' : downloadText,
'atlas' : downloadText,
'tmx' : downloadText,
'tsx' : downloadText,
'json' : downloadText,
'ExportJson' : downloadText,
'plist' : downloadText,
'fnt' : downloadText,
// Font
'font' : downloadFont,
'eot' : downloadFont,
'ttf' : downloadFont,
'woff' : downloadFont,
'svg' : downloadFont,
'ttc' : downloadFont,
// Deserializer
'uuid' : downloadUuid,
'prefab' : downloadUuid,
'fire' : downloadUuid,
'scene' : downloadUuid,
'default' : downloadText
};
var ID = 'Downloader';
/**
* The downloader pipe, it can download several types of files:
* 1. Text
* 2. Image
* 3. Script
* 4. Audio
* All unknown type will be downloaded as plain text.
* You can pass custom supported types in the constructor.
* @class Downloader
*/
/**
* Constructor of Downloader, you can pass custom supported types.
* @example
* var downloader = new Downloader({
* // This will match all url with `.scene` extension or all url with `scene` type
* 'scene' : function (url, callback) {}
* });
*
* @method Downloader
* @param {Object} extMap Custom supported types with corresponded handler
*/
var Downloader = function (extMap) {
this.id = ID;
this.async = true;
this.pipeline = null;
this.maxConcurrent = 2;
this._curConcurrent = 0;
this._loadQueue = [];
this.extMap = JS.mixin(extMap, defaultMap);
};
Downloader.ID = ID;
JS.mixin(Downloader.prototype, {
/**
* Add custom supported types handler or modify existing type handler.
* @method addHandlers
* @param {Object} extMap Custom supported types with corresponded handler
*/
addHandlers: function (extMap) {
this.extMap = JS.mixin(this.extMap, extMap);
},
handle: function (item, callback) {
var self = this;
var downloadFunc = this.extMap[item.type] || this.extMap['default'];
if (this._curConcurrent < this.maxConcurrent) {
if (cc.sys.isMobile) {
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);
}
}
callback && callback(err, result);
});
}
else {
this._loadQueue.push({
item: item,
callback: callback
});
}
}
});
Pipeline.Downloader = module.exports = Downloader;
+7
View File
@@ -0,0 +1,7 @@
require('./downloader');
require('./loader');
require('./loading-items');
require('./pipeline');
require('./CCLoader');
+245
View File
@@ -0,0 +1,245 @@
/****************************************************************************
Copyright (c) 2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
var JS = require('../platform/js');
var Pipeline = require('./pipeline');
var Texture2D = require('../textures/CCTexture2D');
var loadUuid = require('./uuid-loader');
function loadNothing (item, callback) {
callback(null, null);
}
function loadJSON (item, callback) {
if (typeof item.content !== 'string') {
callback( new Error('JSON Loader: Input item doesn\'t contain string content') );
}
try {
var result = JSON.parse(item.content);
callback(null, result);
}
catch (e) {
callback( new Error('JSON Loader: Parse json [' + item.src + '] failed : ' + e) );
}
}
function loadImage (item, callback) {
if (!(item.content instanceof Image)) {
callback( new Error('Image Loader: Input item doesn\'t contain Image content') );
}
var url = item.url || item.src;
var tex = cc.textureCache.getTextureForKey(url) || new Texture2D();
tex.url = url;
tex.initWithElement(item.content);
tex.handleLoadedTexture();
cc.textureCache.cacheImage(url, tex);
callback(null, tex);
}
function loadPlist (item, callback) {
if (typeof item.content !== 'string') {
callback( new Error('Plist Loader: Input item doesn\'t contain string content') );
}
var result = cc.plistParser.parse(item.content);
if (result) {
callback(null, result);
}
else {
callback( new Error('Plist Loader: Parse [' + item.src + '] failed') );
}
}
var fntRE = {
INFO_EXP: /info [^\n]*(\n|$)/gi,
COMMON_EXP: /common [^\n]*(\n|$)/gi,
PAGE_EXP: /page [^\n]*(\n|$)/gi,
CHAR_EXP: /char [^\n]*(\n|$)/gi,
KERNING_EXP: /kerning [^\n]*(\n|$)/gi,
ITEM_EXP: /\w+=[^ \r\n]+/gi,
INT_EXP: /^[\-]?\d+$/,
};
function _parseFntStrToObj (str) {
var arr = str.match(fntRE.ITEM_EXP);
var obj = {};
if (arr) {
for (var i = 0, li = arr.length; i < li; i++) {
var tempStr = arr[i];
var index = tempStr.indexOf('=');
var key = tempStr.substring(0, index);
var value = tempStr.substring(index + 1);
if (value.match(fntRE.INT_EXP)) value = parseInt(value);
else if (value[0] === '"') value = value.substring(1, value.length - 1);
obj[key] = value;
}
}
return obj;
}
function loadFnt (item, callback) {
var fntStr = item.content;
var url = item.src;
var fnt = {}, i, li;
//padding
var infoObj = _parseFntStrToObj(fntStr.match(fntRE.INFO_EXP)[0]);
var paddingArr = infoObj['padding'].split(',');
var padding = {
left: parseInt(paddingArr[0]),
top: parseInt(paddingArr[1]),
right: parseInt(paddingArr[2]),
bottom: parseInt(paddingArr[3])
};
//common
var commonObj = _parseFntStrToObj(fntStr.match(fntRE.COMMON_EXP)[0]);
fnt.commonHeight = commonObj['lineHeight'];
//font size
fnt.fontSize = infoObj['size'];
if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
var texSize = cc.configuration.getMaxTextureSize();
if (commonObj['scaleW'] > texSize.width || commonObj['scaleH'] > texSize.height) {
cc.log('cc.LabelBMFont._parseCommonArguments(): page can\'t be larger than supported');
}
}
if (commonObj['pages'] !== 1) {
cc.log('cc.LabelBMFont._parseCommonArguments(): only supports 1 page');
}
//page
var pageObj = _parseFntStrToObj(fntStr.match(fntRE.PAGE_EXP)[0]);
if (pageObj['id'] !== 0) {
cc.log('cc.LabelBMFont._parseImageFileName() : file could not be found');
}
fnt.atlasName = cc.path.changeBasename(url, pageObj['file']);
//char
var charLines = fntStr.match(fntRE.CHAR_EXP);
var fontDefDictionary = fnt.fontDefDictionary = {};
for (i = 0, li = charLines.length; i < li; i++) {
var charObj = _parseFntStrToObj(charLines[i]);
var charId = charObj['id'];
fontDefDictionary[charId] = {
rect: {x: charObj['x'], y: charObj['y'], width: charObj['width'], height: charObj['height']},
xOffset: charObj['xoffset'],
yOffset: charObj['yoffset'],
xAdvance: charObj['xadvance']
};
}
//kerning
var kerningDict = fnt.kerningDict = {};
var kerningLines = fntStr.match(fntRE.KERNING_EXP);
if (kerningLines) {
for (i = 0, li = kerningLines.length; i < li; i++) {
var kerningObj = _parseFntStrToObj(kerningLines[i]);
kerningDict[(kerningObj['first'] << 16) | (kerningObj['second'] & 0xffff)] = kerningObj['amount'];
}
}
callback(null, fnt);
}
var defaultMap = {
// Images
'png' : loadImage,
'jpg' : loadImage,
'bmp' : loadImage,
'jpeg' : loadImage,
'gif' : loadImage,
'ico' : loadImage,
'tiff' : loadImage,
'webp' : loadImage,
'image' : loadImage,
'json' : loadJSON,
'ExportJson' : loadJSON,
'plist' : loadPlist,
'fnt' : loadFnt,
'uuid' : loadUuid,
'prefab' : loadUuid,
'fire' : loadUuid,
'scene' : loadUuid,
'default' : loadNothing
};
var ID = 'Loader';
/**
* The loader pipe, it can load several types of files:
* 1. Images
* 2. JSON
* 3. Plist
* 4. Audio
* 5. Font
* 6. Cocos Creator scene
* It will not interfere with items of unknown type.
* You can pass custom supported types in the constructor.
* @class Loader
*/
/**
* Constructor of Loader, you can pass custom supported types.
* @example
* var loader = new Loader({
* // This will match all url with `.scene` extension or all url with `scene` type
* 'scene' : function (url, callback) {}
* });
*
* @method Loader
* @param {Object} extMap Custom supported types with corresponded handler
*/
var Loader = function (extMap) {
this.id = ID;
this.async = true;
this.pipeline = null;
this.extMap = JS.mixin(extMap, defaultMap);
};
Loader.ID = ID;
JS.mixin(Loader.prototype, {
/**
* Add custom supported types handler or modify existing type handler.
* @method addHandlers
* @param {Object} extMap Custom supported types with corresponded handler
*/
addHandlers: function (extMap) {
this.extMap = JS.mixin(this.extMap, extMap);
},
handle: function (item, callback) {
var loadFunc = this.extMap[item.type] || this.extMap['default'];
loadFunc.call(this, item, function (err, result) {
if (err) {
callback && callback(err);
}
else {
callback && callback(null, result);
}
});
}
});
Pipeline.Loader = module.exports = Loader;
+148
View File
@@ -0,0 +1,148 @@
/****************************************************************************
Copyright (c) 2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
var CallbacksInvoker = require('../platform/callbacks-invoker');
var JS = require('../platform/js');
/**
* LoadingItems is the manager of items in pipeline.
* It hold a map of items, each entry in the map is a url to object key value pair.
* Each item always contains the following property:
* - src: The url
* - type: The type, it's the extension name of the url by default, could be specified manually too
* - error: The error happened in pipeline will be stored in this property
* - content: The content processed by the pipeline, the final result will also be stored in this property
* - complete: The flag indicate whether the item is completed by the pipeline
* - states: An object stores the states of each pipe the item go through, the state can be: Pipeline.ItemState.WORKING | Pipeline.ItemState.ERROR | Pipeline.ItemState.COMPLETE
*
* Item can hold other custom properties
*
* @class LoadingItems
*/
var LoadingItems = function () {
CallbacksInvoker.call(this);
/**
* The map of all items
* @property map
* @type {Object}
*/
this.map = {};
/**
* The map of completed items
* @property completed
* @type {Object}
*/
this.completed = {};
/**
* Total count of all items
* @property totalCount
* @type {Number}
*/
this.totalCount = 0;
/**
* Total count of completed items
* @property completedCount
* @type {Number}
*/
this.completedCount = 0;
};
JS.mixin(LoadingItems.prototype, CallbacksInvoker.prototype, {
append: function (items) {
var list = [];
for (var i = 0; i < items.length; ++i) {
var item = items[i];
var url = item.src;
// No duplicated url
if (!this.map[url]) {
this.map[item.src] = item;
list.push(item);
}
}
this.totalCount += list.length;
return list;
},
/**
* Check whether all items are completed
* @return {Boolean}
*/
isCompleted: function () {
return this.completedCount >= this.totalCount;
},
/**
* Check whether an item is completed
* @return {Boolean}
*/
isItemCompleted: function (url) {
return !!this.completed[url];
},
/**
* Check whether an item exists
* @return {Boolean}
*/
exists: function (url) {
return !!this.map[url];
},
getContent: function (url) {
var item = this.map[url];
return item ? item.content : null;
},
getError: function (url) {
var item = this.map[url];
return item ? item.error : null;
},
/**
* Remove an item, can only remove completed item, ongoing item can not be removed
* @param {String} url
*/
remove: function (url) {
if (this.completed[url]) {
delete this.completed[url];
delete this.map[url];
this.completedCount--;
this.totalCount--;
}
},
complete: function (url) {
if (this.map[url] && !this.completed[url]) {
var item = this.map[url];
item.complete = true;
this.completed[url] = item;
this.completedCount++;
}
}
});
module.exports = LoadingItems;
+504
View File
@@ -0,0 +1,504 @@
/****************************************************************************
Copyright (c) 2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
var JS = require('../platform/js');
var Path = require('../utils/CCPath');
var LoadingItems = require('./loading-items');
var ItemState = {
WORKING: 1,
COMPLETE: 2,
ERROR: 3
};
function asyncFlow (item) {
var pipeId = this.id;
var itemState = item.states[pipeId];
var next = this.next;
if (item.error || itemState === ItemState.WORKING || itemState === ItemState.ERROR) {
return;
}
else if (itemState === ItemState.COMPLETE) {
if (next) {
next.async ? asyncFlow.call(next, item) : syncFlow.call(next, item);
}
else {
this.pipeline.flowOut(item);
}
}
else {
item.states[pipeId] = ItemState.WORKING;
var pipe = this;
this.handle(item, function (err, result) {
if (err) {
item.error = err;
item.states[pipeId] = ItemState.ERROR;
pipe.pipeline.flowOut(item);
}
else {
// Result can be null, then it means no result for this pipe
if (result) {
item.content = result;
}
item.states[pipeId] = ItemState.COMPLETE;
if (next) {
next.async ? asyncFlow.call(next, item) : syncFlow.call(next, item);
}
else {
pipe.pipeline.flowOut(item);
}
}
});
}
}
function syncFlow (item) {
var pipeId = this.id;
var itemState = item.states[pipeId];
var next = this.next;
if (item.error || itemState === ItemState.WORKING || itemState === ItemState.ERROR) {
return;
}
else if (itemState === ItemState.COMPLETE) {
if (next) {
next.async ? asyncFlow.call(next, item) : syncFlow.call(next, item);
}
else {
this.pipeline.flowOut(item);
}
}
else {
item.states[pipeId] = ItemState.WORKING;
var result = this.handle(item);
if (result instanceof Error) {
item.error = result;
item.states[pipeId] = ItemState.ERROR;
this.pipeline.flowOut(item);
}
else {
// Result can be null, then it means no result for this pipe
if (result) {
item.content = result;
}
item.states[pipeId] = ItemState.COMPLETE;
if (next) {
next.async ? asyncFlow.call(next, item) : syncFlow.call(next, item);
}
else {
this.pipeline.flowOut(item);
}
}
}
}
function isUrlValid (url) {
var realUrl = url.src || url;
return (typeof realUrl === 'string');
}
function createItem (url) {
var result;
if (typeof url === 'object' && url.src) {
if (!url.type) {
url.type = Path.extname(url.src).toLowerCase().substr(1);
}
result = {
error: null,
content: null,
complete: false,
states: {}
};
JS.mixin(result, url);
}
else if (typeof url === 'string') {
result = {
src: url,
type: Path.extname(url).toLowerCase().substr(1),
error: null,
content: null,
complete: false,
states: {}
};
}
if (result.skips) {
for (var i = 0, l = result.skips.length; i < l; i++) {
var skip = result.skips[i];
result.states[skip] = ItemState.COMPLETE;
}
}
return result;
}
function getXMLHttpRequest () {
return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject('MSXML2.XMLHTTP');
}
/**
* A pipeline describes a sequence of manipulations, each manipulation is called a pipe.
* It's designed for loading process, so items should be urls, and the url will be the identity of each item during the process.
* A list of items can flow in the pipeline and it will output the results of all pipes.
* They flow in the pipeline like water in tubes, they go through pipe by pipe separately.
* Finally all items will flow out the pipeline and the process is finished.
*
* @class Pipeline
*/
/**
* Constructor, pass an array of pipes to construct a new Pipeline, the pipes will be chained in the given order.
* A pipe is an object which must contain an `id` in string and a `handle` function, the id must be unique in the pipeline.
* It can also include `async` property to identify whether it's an asynchronous process.
* @example
* var pipeline = new Pipeline([
* {
* id: 'Downloader',
* handle: function (item, callback) {},
* async: true
* },
* {id: 'Parser', handle: function (item) {}, async: false}
* ]);
*
* @method Pipeline
* @param {Array} pipes
*/
var Pipeline = function (pipes) {
this._pipes = pipes;
this._items = new LoadingItems();
this._errorUrls = [];
this._flowing = false;
for (var i = 0; i < pipes.length; ++i) {
var pipe = pipes[i];
// Must have handle and id, handle for flow, id for state flag
if (!pipe.handle || !pipe.id) {
continue;
}
pipe.pipeline = this;
pipe.next = i < pipes.length - 1 ? pipes[i+1] : null;
}
};
Pipeline.ItemState = new cc.Enum(ItemState);
Pipeline.getXMLHttpRequest = getXMLHttpRequest;
JS.mixin(Pipeline.prototype, {
/**
* Insert a new pipe at the given index of the pipeline.
* A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline.
*
* @method insertPipe
* @param {Object} pipe The pipe to be inserted
* @param {Number} index The index to insert
*/
insertPipe: function (pipe, index) {
// Must have handle and id, handle for flow, id for state flag
if (!pipe.handle || !pipe.id) {
return;
}
pipe.pipeline = this;
if (index < this._pipes.length) {
pipe.next = this._pipes[index];
this._pipes.splice(index, 0, pipe);
}
else {
pipe.next = null;
this._pipes.push(pipe);
}
},
/**
* Add a new pipe at the end of the pipeline.
* A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline.
*
* @method appendPipe
* @param {Object} pipe The pipe to be appended
*/
appendPipe: function (pipe) {
// Must have handle and id, handle for flow, id for state flag
if (!pipe.handle || !pipe.id) {
return;
}
pipe.pipeline = this;
pipe.next = null;
this._pipes.push(pipe);
},
/**
* Let new items flow into the pipeline.
* Each item can be a simple url string or an object,
* if it's an object, it must contain `src` property.
* You can specify its type by `type` property, by default, the type is the extension name in `src`.
* By adding a `skips` property including pipe ids, you can skip these pipe.
* The object can contain any supplementary property as you want.
* @example
* pipeline.flowIn([
* 'res/Background.png',
* {
* src: 'res/scene.json',
* type: 'scene',
* name: 'scene',
* skips: ['Downloader']
* }
* ]);
*
* @method flowIn
* @param {Array} urlList
* @return {Array} Items accepted by the pipeline
*/
flowIn: function (urlList) {
var items = [], i, url, item;
for (i = 0; i < urlList.length; ++i) {
url = urlList[i];
if (isUrlValid(url)) {
item = createItem(url);
items.push(item);
}
else {
throw new Error('Pipeline flowIn: Invalid url: ' + (url.src || url));
}
}
var acceptedItems = this._items.append(items);
// Manually complete
if (this._pipes.length === 0 || acceptedItems.length === 0) {
this.complete();
return acceptedItems;
}
if (!this._flowing) {
this._flowing = true;
}
// Flow in after appended to loading items
var pipe = this._pipes[0];
if (pipe) {
for (i = 0; i < acceptedItems.length; i++) {
pipe.async ? asyncFlow.call(pipe, acceptedItems[i]) : syncFlow.call(pipe, acceptedItems[i]);
}
}
return acceptedItems;
},
/**
* Let new items flow into the pipeline and give a callback when the list of items are all completed.
* This is for loading dependencies for an existing item in flow, usually used in a pipe logic.
* For example, we have a loader for scene configuration file in JSON, the scene will only be fully loaded
* after all its dependencies are loaded, then you will need to use function to flow in all dependencies
* found in the configuration file, and finish the loader pipe only after all dependencies are loaded (in the callback).
*
* @method flowInDeps
* @param {Array} urlList
* @param {Function} callback
* @return {Array} Items accepted by the pipeline
*/
flowInDeps: function (urlList, callback) {
var checker = {};
var count = 0;
function loadedCheck (item) {
checker[item.src] = item;
for (var url in checker) {
// Not done yet
if (!checker[url]) {
return;
}
}
// All url completed
callback && callback.call(this, checker);
}
// Add loaded listeners
for (var i = 0; i < urlList.length; ++i) {
var url = urlList[i].src || urlList[i];
if (typeof url !== 'string')
continue;
var item = this._items.map[url];
if ( !item ) {
this._items.add(url, loadedCheck);
checker[url] = null;
count++;
}
else {
checker[url] = item;
}
}
// No new resources, complete directly
if (count === 0) {
callback && callback.call(this, checker);
}
return this.flowIn(urlList);
},
complete: function () {
// All completed
if (this._items.isCompleted()) {
this._flowing = false;
if (this.onComplete) {
var error = this._errorUrls.length === 0 ? null : this._errorUrls;
this.onComplete(error, this._items);
this._errorUrls = [];
}
}
},
flowOut: function (item) {
var url = item.src;
var items = this._items;
var exists = items.map[url];
// Not exist or already completed
if (!exists || exists.complete) {
return;
}
// Register or unregister errors
var errorListId = this._errorUrls.indexOf(url);
if (item.error && errorListId === -1) {
this._errorUrls.push(url);
}
else if (!item.error && errorListId !== -1) {
this._errorUrls.splice(errorListId, 1);
}
items.complete(item.src);
this.onProgress && this.onProgress(items.completedCount, items.totalCount, item);
this.complete();
items.invoke(url, item);
},
/**
* Copy the item states from one source item to all destination items.
* It's quite useful when a pipe generate new items from one source item,
* then you should flowIn these generated items into pipeline,
* but you probably want them to skip all pipes the source item already go through,
* you can achieve it with this API.
*
* For example, an unzip pipe will generate more items, but you won't want them to pass unzip or download pipe again.
* @method copyItemStates
* @param {Object} srcItem The source item
* @param {Array|Object} dstItems A single destination item or an array of destination items
*/
copyItemStates: function (srcItem, dstItems) {
if (!(dstItems instanceof Array)) {
dstItems.states = srcItem.states;
return;
}
for (var i = 0; i < dstItems.length; ++i) {
dstItems[i].states = srcItem.states;
}
},
/**
* Returns whether the pipeline is flowing (contains item) currently.
* @method isFlowing
* @return {Boolean}
*/
isFlowing: function () {
return this._flowing;
},
/**
* Returns all items in pipeline.
* @method getItems
* @return {LoadingItems}
*/
getItems: function () {
return this._items;
},
/**
* Removes an item in pipeline, no matter it's in progress or completed.
* @method removeItem
* @return {Boolean} succeed or not
*/
removeItem: function (url) {
var item = this._items.map[url];
if (item) {
if (!item.complete) {
item.error = new Error('Canceled manually');
this.flowOut(item);
}
this._items.remove(url);
}
else {
return false;
}
},
/**
* Clear the current pipeline, this function will clean up the items.
* @method clear
*/
clear: function () {
if (this._flowing) {
var items = this._items.map;
for (var url in items) {
var item = items[url];
if (!item.complete) {
item.error = new Error('Canceled manually');
this.flowOut(item);
}
}
}
this._items = new LoadingItems();
this._errorUrls = [];
this._flowing = false;
},
/**
* This is a callback which will be invoked while an item flow out the pipeline, you should overwrite this function.
* @example
* pipeline.onProgress = function (completedCount, totalCount, item) {
* var progress = (100 * completedCount / totalCount).toFixed(2);
* cc.log(progress + '%');
* }
* @method onProgress
* @param {Number} completedCount The number of the items that are already completed.
* @param {Number} totalCount The total number of the items.
* @param {Object} item The latest item which flow out the pipeline.
*/
onProgress: function (completedCount, totalCount, item) {},
/**
* This is a callback which will be invoked while all items flow out the pipeline, you should overwirte this function.
* @example
* pipeline.onComplete = function (error, items) {
* if (error)
* cc.log('Completed with ' + error.length + ' errors');
* else
* cc.log('Completed ' + items.totalCount + ' items');
* }
* @method onComplete
* @param {Array} error All errored urls will be stored in this array, if no error happened, then it will be null
* @param {LoadingItems} items All items.
*/
onComplete: function (error, items) {}
});
cc.Pipeline = module.exports = Pipeline;
+147
View File
@@ -0,0 +1,147 @@
/****************************************************************************
Copyright (c) 2016 Chukong Technologies Inc.
http://www.cocos2d-x.org
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
var JS = require('../platform/js');
require('../platform/deserialize');
// temp deserialize info
var _tdInfo = new cc.deserialize.Details();
var SCENE_ID = 'cc.Scene';
function loadUuid (item, callback) {
var json,
uuid = item.src,
url = item.url;
if (typeof item.content === 'string') {
try {
json = JSON.parse(item.content);
}
catch (e) {
callback( new Error('Uuid Loader: Parse asset [' + item.src + '] failed : ' + e) );
return;
}
}
else if (typeof item.content === 'object') {
json = item.content;
}
else {
callback( new Error('JSON Loader: Input item doesn\'t contain string content') );
return;
}
var isScene = json && (
(json[0] && json[0].__type__ === SCENE_ID) ||
(json[1] && json[1].__type__ === SCENE_ID)
);
var classFinder = isScene ? cc._MissingScript.safeFindClass : function (id) {
var cls = JS._getClassById(id);
if (cls) {
return cls;
}
cc.warn('Can not get class "%s"', id);
return Object;
};
var tdInfo = cc.sys.isNative ? new cc.deserialize.Details() : (item.deserializeInfo || _tdInfo);
var asset = cc.deserialize(json, tdInfo, {
classFinder: classFinder,
target: item.existingAsset
});
var dependsSrcs = JS.array.copy(tdInfo.uuidList);
var ownerList = JS.array.copy(tdInfo.uuidObjList);
var propList = JS.array.copy(tdInfo.uuidPropList);
var depends = new Array(dependsSrcs.length);
// load depends assets
for (var i = 0; i < dependsSrcs.length; i++) {
var dependSrc = dependsSrcs[i];
depends[i] = {
src: dependSrc,
type: 'uuid',
uuid: dependSrc
};
}
// load raw
if (tdInfo.rawProp) {
dependsSrcs.push(url);
ownerList.push(asset);
propList.push(tdInfo.rawProp);
depends.push(url);
}
var pipeline = this.pipeline;
if (depends.length > 0) {
pipeline.flowInDeps(depends, function (items) {
var item;
for (var src in items) {
item = items[src];
if (item.uuid && item.content) {
item.content._uuid = item.uuid;
}
}
for (var i = 0; i < dependsSrcs.length; i++) {
var dependSrc = dependsSrcs[i];
var obj = ownerList[i];
var dependProp = propList[i];
item = items[dependSrc];
if (item) {
if (item.complete) {
var value = item.isRawAsset ? (item.url || item.src) : item.content;
obj[dependProp] = value;
}
else {
var loadCallback = function (item) {
var value = item.isRawAsset ? (item.url || item.src) : item.content;
this.obj[this.prop] = value;
};
var target = {
obj: obj,
prop: dependProp
};
// Hack to get a better behavior
var list = pipeline.getItems()._callbackTable[dependSrc];
if (list) {
list.unshift(loadCallback, target);
}
else {
pipeline.getItems().add(dependSrc, loadCallback, target);
}
}
}
}
callback(null, asset);
});
}
else {
callback(null, asset);
}
asset._uuid = uuid;
// tdInfo 是用来重用的临时对象,每次使用后都要重设,这样才对 GC 友好。
tdInfo.reset();
}
module.exports = loadUuid;
+66 -308
View File
@@ -1,8 +1,6 @@
var JS = require('./js');
var Asset = require('../assets/CCAsset');
var Asset = require('../assets/CCAsset');
var callInNextTick = require('./utils').callInNextTick;
var LoadManager = require('./load-manager');
var CallbacksInvoker = require('./callbacks-invoker');
var Loader = require('../load-pipeline/CCLoader');
/**
* The asset library which managing loading/unloading assets in project.
@@ -17,64 +15,9 @@ var _libraryBase = '';
var _rawAssetsBase = ''; // The base dir for raw assets in runtime
var _uuidToRawAssets;
// variables
// the loading uuid's callbacks
var _uuidToCallbacks = new CallbacksInvoker();
// temp deserialize info
var _tdInfo = new cc.deserialize.Details();
var _cc_loader_loadJson = cc.loader.loadJson.bind(cc.loader);
// create a loading context which reserves all relevant parameters
function LoadingHandle (readMainCache, writeMainCache, recordAssets, deserializeInfo) {
//this.readMainCache = readMainCache;
//this.writeMainCache = writeMainCache;
// FORCE ignore global cache in fireball lite
this.readMainCache = false;
this.writeMainCache = false;
// 缓存同一个任务中已经加载好的资源
var needIndieCache = !(this.readMainCache && this.writeMainCache);
this.taskIndieCache = needIndieCache ? {} : null;
// 保存正在等待依赖项加载完毕的资源,防止循环依赖
// (其它缓存包含的是已经加载完毕的资源,如果已经缓存会立即结束并回调,而这个缓存存的是还在加载中的资源,不会影响加载也不会触发回调)
this.pendingCache = {};
// 需要让场景 preload 的 asset(所有包含 raw file 后缀名的 asset 并且不含 rawType 属性的 asset)
this.assetsNeedPostLoad = recordAssets ? [] : null;
// 可以提供一个反序列化句柄,用来在执行反序列化任务时,做一些特殊处理
this.deserializeInfo = deserializeInfo;
function isScene (asset) {
return asset && (asset.constructor === cc.SceneAsset || asset instanceof cc.Scene);
}
LoadingHandle.prototype.readCache = function (uuid) {
if (this.readMainCache && this.writeMainCache) {
return AssetLibrary._uuidToAsset[uuid];
}
else {
if (this.readMainCache) {
// writeMainCache == false
return AssetLibrary._uuidToAsset[uuid] || this.taskIndieCache[uuid];
}
else {
return this.taskIndieCache[uuid];
}
}
};
LoadingHandle.prototype.writeCache = function (uuid, asset, hasRawType) {
if (this.writeMainCache) {
AssetLibrary._uuidToAsset[uuid] = asset;
}
if (this.taskIndieCache) {
this.taskIndieCache[uuid] = asset;
}
if (this.assetsNeedPostLoad && asset._rawFiles && !hasRawType) {
this.assetsNeedPostLoad.push(asset);
}
};
// publics
@@ -93,25 +36,27 @@ var AssetLibrary = {
* @param {Boolean} options.readMainCache - Default is true. If false, the asset and all its depends assets will reload and create new instances from library.
* @param {Boolean} options.writeMainCache - Default is true. If true, the result will cache to AssetLibrary, and MUST be unload by user manually.
* @param {Asset} options.existingAsset - load to existing asset, this argument is only available in editor
* @param {Boolean} options.recordAssets - Default is false. If true, tracking statistics associated with the assets which needs to preload(All the assets contains "urls" but dont have "_rawFiles")
* @param {deserialize.Details} options.deserializeInfo - specified a DeserializeInfo object if you want,
* this parameter is only available in editor.
* @private
*/
loadAsset: function (uuid, callback, options) {
var readMainCache = typeof (options && options.readMainCache) !== 'undefined' ? readMainCache : true;
var writeMainCache = typeof (options && options.writeMainCache) !== 'undefined' ? writeMainCache : true;
// var readMainCache = typeof (options && options.readMainCache) !== 'undefined' ? readMainCache : true;
// var writeMainCache = typeof (options && options.writeMainCache) !== 'undefined' ? writeMainCache : true;
var handle = new LoadingHandle(readMainCache,
writeMainCache,
options && options.recordAssets,
options && options.deserializeInfo);
this._loadAssetByUuid(uuid, callback, handle, options && options.existingAsset);
return handle;
var item = {
src: uuid,
type: 'uuid'
};
if (options && options.deserializeInfo) {
item.deserializeInfo = options.deserializeInfo;
}
if (options && options.existingAsset) {
item.existingAsset = options.existingAsset;
}
this._loadAssetByUuid(item, callback);
},
_LoadingHandle: LoadingHandle,
getImportedDir: function (uuid) {
return _libraryBase + uuid.slice(0, 2)/* + cc.path.sep + uuid*/;
},
@@ -120,7 +65,7 @@ var AssetLibrary = {
if (CC_EDITOR) {
Editor.sendRequestToCore( 'scene:query-asset-info-by-uuid', uuid, function (info) {
if (info) {
Editor.onRawAssetUsed(info.url, uuid);
Editor.UuidCache.cache(info.url, uuid);
var ctor = Editor.assets[info.type];
if (ctor) {
var isRawAsset = !cc.isChildClassOf(ctor, Asset);
@@ -176,7 +121,7 @@ var AssetLibrary = {
// parse uuid out of url
parseUuidInEditor: function (url) {
if (CC_EDITOR) {
var uuid = "";
var uuid = '';
var isImported = url.startsWith(_libraryBase);
if (isImported) {
var dir = cc.path.dirname(url);
@@ -208,264 +153,77 @@ var AssetLibrary = {
* 4. 递归加载Asset及其引用到的其它Asset
*
* @method _loadAssetByUuid
* @param {String} uuid
* @param {Object} item - loading item including uuid, type and extra infos
* @param {loadCallback} callback - the callback to receive the asset, can be null
* @param {LoadingHandle} handle - the loading context which reserves all relevant parameters
* @param {Asset} [existingAsset] - load to existing asset, this argument is only available in editor
* @private
*/
_loadAssetByUuid: function (uuid, callback, handle, existingAsset) {
_loadAssetByUuid: function (item, callback) {
var uuid = item.src;
var thisTick = true;
if (typeof uuid !== 'string') {
return callInNextTick(callback, new Error('[AssetLibrary] uuid must be string'), null);
}
// step 1
if ( !existingAsset ) {
var asset = handle.readCache(uuid);
if (asset) {
return callInNextTick(callback, null, asset);
Loader.load(item, function (error, asset) {
if (error || !asset) {
error = new Error('[AssetLibrary] loading JSON or dependencies failed : ' + JSON.stringify(error));
}
}
// step 2
// 如果必须重新加载,则不能合并到到 _uuidToCallbacks,否则现有的加载成功后会同时触发回调,
// 导致提前返回的之前的资源。
var canShareLoadingTask = handle.readMainCache && !existingAsset;
if ( canShareLoadingTask && !_uuidToCallbacks.add(uuid, callback) ) {
// already loading
return;
}
// 防止循环加载
var loading = handle.pendingCache[uuid];
if (loading) {
// already loading
return callInNextTick(callback, null, loading);
}
//if (CC_EDITOR && !_libraryBase) {
// callInNextTick(callback, new Error('Cannot load ' + uuid + ' in editor because AssetLibrary not yet initialized!'), null);
// return;
//}
function onload (error, json, url) {
function onDeserializedWithDepends (err, asset, hasRawType) {
if (asset) {
asset._uuid = uuid;
handle.writeCache(uuid, asset, hasRawType);
}
if ( canShareLoadingTask ) {
_uuidToCallbacks.invokeAndRemove(uuid, err, asset);
}
else if (callback) {
callback(err, asset);
}
}
if (json) {
AssetLibrary._deserializeWithDepends(json, url, uuid, onDeserializedWithDepends, handle, existingAsset);
if (thisTick) {
callInNextTick(function () {
if (isScene(asset) || CC_EDITOR) {
Loader.removeItem(uuid);
}
callback(error, asset);
});
}
else {
onDeserializedWithDepends(error, null);
}
}
if (CC_EDITOR && !CC_TEST) {
this._queryAssetInfoInEditor(uuid, function (err, url, isRawAsset) {
if (err) {
callback(err);
if (isScene(asset) || CC_EDITOR) {
Loader.removeItem(uuid);
}
else {
var shouldLoadByEngine = !isRawAsset;
if (!shouldLoadByEngine) {
return callback(new Error('Should not load raw file in AssetLibrary, uuid: ' + uuid));
}
LoadManager.loadByLoader(_cc_loader_loadJson, url, function (error, json) {
onload(error, json, url);
});
}
});
}
else {
var info = this._getAssetInfoInRuntime(uuid);
if (info.raw) {
return callback(new Error('Should not load raw file in AssetLibrary, uuid: ' + uuid));
callback(error, asset);
}
LoadManager.loadByLoader(_cc_loader_loadJson, info.url, function (error, json) {
onload(error, json, info.url);
});
}
});
thisTick = false;
},
/**
* @method loadJson
* @param {String|Object} json
* @param {String} json
* @param {loadCallback} callback
* @param {Boolean} [dontCache=false] - If false, the result will cache to AssetLibrary, and MUST be unload by user manually.
* @param {Boolean} [recordAssets=false] - 是否统计新加载的需要让场景 preload 的 asset(所有包含 raw file 后缀名的 asset 并且不含 rawType 属性的 asset)
* @return {LoadingHandle}
* @private
*/
loadJson: function (json, callback, dontCache, recordAssets) {
var handle = new LoadingHandle(!dontCache, !dontCache, recordAssets);
loadJson: function (json, callback) {
var randomUuid = '' + ((new Date()).getTime() + Math.random());
var thisTick = true;
this._deserializeWithDepends(json, '', '', function (p1, p2) {
var item = {
src: randomUuid,
type: 'uuid',
content: json,
skips: [ Loader.downloader.id ]
};
Loader.load(item, function (error, asset) {
if (error) {
error = new Error('[AssetLibrary] loading JSON or dependencies failed : ' + JSON.stringify(error));
}
if (thisTick) {
callInNextTick(callback, p1, p2);
callInNextTick(function () {
if (isScene(asset) || CC_EDITOR) {
Loader.removeItem(randomUuid);
}
asset._uuid = '';
callback(error, asset);
});
}
else {
callback(p1, p2);
if (isScene(asset) || CC_EDITOR) {
Loader.removeItem(randomUuid);
}
asset._uuid = '';
callback(error, asset);
}
}, handle);
});
thisTick = false;
return handle;
},
_loadDepends: function (asset, _tdInfo, url, handle, callback) {
// load depends
var pendingCount = _tdInfo.uuidList.length;
// load raw
var rawProp = _tdInfo.rawProp; // _tdInfo不能用在回调里!
if (rawProp) {
// load depends raw objects
var attrs = cc.Class.attr(asset.constructor, _tdInfo.rawProp);
var rawType = attrs.rawType;
++pendingCount;
LoadManager.load(url, rawType, asset._rawext, function onRawObjLoaded (error, raw) {
if (error) {
cc.error('[AssetLibrary] Failed to load %s of %s. %s', rawType, url, error);
}
asset[rawProp] = raw;
--pendingCount;
if (pendingCount === 0) {
callback();
callback = null;
}
});
}
if (pendingCount === 0) {
if (callback) {
callback();
}
return;
}
/*
如果依赖的所有资源都要重新下载,批量操作时将会导致同时执行多次重复下载。优化方法是增加一全局事件队列,
队列保存每个任务的注册,启动,结束事件,任务从注册到启动要延迟几帧,每个任务都存有父任务。
这样通过队列的事件序列就能做到合并批量任务。
如果依赖的资源不重新下载也行,但要判断是否刚好在下载过程中,如果是的话必须等待下载完成才能结束本资源的加载,
否则外部获取到的依赖资源就会是旧的。
*/
// load depends assets
for (var i = 0; i < _tdInfo.uuidList.length; i++) {
var dependsUuid = _tdInfo.uuidList[i];
(function (dependsUuid, obj, prop) {
AssetLibrary.queryAssetInfo(dependsUuid, function (err, dependsUrl, isRawAsset) {
if (err) {
cc.error('[AssetLibrary] Failed to load "%s", %s', dependsUuid, err);
--pendingCount;
if (callback && pendingCount === 0) {
callback();
callback = null;
}
obj[prop] = obj[prop]; // ensures forEach worked
return;
}
else if (isRawAsset) {
cc.loader.load(dependsUrl, function (err, assets) {
if (err) {
cc.error('[AssetLibrary] Failed to load "%s"', dependsUrl);
obj[prop] = '';
}
else {
obj[prop] = dependsUrl;
}
--pendingCount;
if (callback && pendingCount === 0) {
callback();
callback = null;
}
});
return;
}
var onDependsAssetLoaded = function (error, dependsAsset, hasRawType) {
if (CC_EDITOR && error) {
if (Editor.AssetDB && Editor.AssetDB.isValidUuid(dependsUuid)) {
cc.error('[AssetLibrary] Failed to load "%s", %s', dependsUuid, error);
}
}
//else {
// dependsAsset._uuid = dependsUuid;
//}
// update reference
obj[prop] = dependsAsset;
//
--pendingCount;
if (callback && pendingCount === 0) {
callback();
callback = null;
}
};
AssetLibrary._loadAssetByUuid(dependsUuid, onDependsAssetLoaded, handle);
});
})( dependsUuid, _tdInfo.uuidObjList[i], _tdInfo.uuidPropList[i] );
}
// AssetLibrary._loadAssetByUuid 的回调有可能在当帧也可能延后执行,所以这里要判断 callback 来防止多次调用
if (callback && pendingCount === 0) {
callback();
callback = null;
}
},
/**
* @method _deserializeWithDepends
* @param {String|Object} json
* @param {String} url
* @param {String} uuid
* @param {loadCallback} callback
* @param {Object} handle - the loading context which reserves all relevant parameters
* @param {Asset} [existingAsset] - existing asset to reload
* @private
*/
_deserializeWithDepends: function (json, url, uuid, callback, handle, existingAsset) {
// deserialize asset
//var isScene = typeof Scene !== 'undefined' && json && json[0] && json[0].__type__ === JS._getClassId(Scene);
//var classFinder = isScene ? cc._MissingScript.safeFindClass : function (id) {
var classFinder = function (id) {
var cls = JS._getClassById(id);
if (cls) {
return cls;
}
cc.warn('Can not get class "%s"', id);
return Object;
};
var tdInfo = cc.sys.isNative ? new cc.deserialize.Details() : (handle.deserializeInfo || _tdInfo);
var asset = cc.deserialize(json, tdInfo, {
classFinder: classFinder,
target: existingAsset
});
var hasRawType = !!tdInfo.rawProp;
if (uuid) {
handle.pendingCache[uuid] = asset;
}
this._loadDepends(asset, tdInfo, url, handle, function () {
if (uuid) {
delete handle.pendingCache[uuid];
}
callback(null, asset, hasRawType);
});
// tdInfo 是用来重用的临时对象,每次使用后都要重设,这样才对 GC 友好。
tdInfo.reset();
},
/**
@@ -524,7 +282,7 @@ var AssetLibrary = {
mountPaths = {
assets: _rawAssetsBase + 'assets',
internal: _rawAssetsBase + 'internal',
}
};
}
cc.url._init(mountPaths);
}
+26 -30
View File
@@ -417,7 +417,7 @@ function define (className, baseClasses, mixins, constructor, options) {
JS._setClassId(uuid, cls);
if (CC_EDITOR) {
cc.Component._addMenuItem(cls, 'i18n:MAIN_MENU.component.scripts/' + className, -1);
cls.prototype.__scriptUuid = Editor.decompressUuid(uuid);
cls.prototype.__scriptUuid = Editor.UuidUtils.decompressUuid(uuid);
}
}
frame.beh = cls;
@@ -583,35 +583,26 @@ function _boundSuperCall (func, funcName, base) {
var superFunc = null;
var pd = JS.getPropertyDescriptor(base.prototype, funcName);
if (pd) {
if (pd.value) {
if (typeof pd.value === 'function') {
superFunc = pd.value;
superFunc = pd.value;
// 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;
};
}
}
else if (pd.get) {
var got = pd.get();
if (typeof got === 'function') {
superFunc = got;
}
}
}
if (superFunc) {
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;
};
}
}
return null;
}
@@ -674,7 +665,6 @@ function declareProperties (cls, className, properties, baseClass, mixins) {
*
* @method Class
* @param {Object} options
* TODO: add properties of options
* @return {Function} - the created class
*
* @example
@@ -782,7 +772,13 @@ function CCClass (options) {
}
var func = options[funcName];
if (typeof func === 'function' || func === null) {
cls.prototype[funcName] = func;
// use defineProperty to redefine some super method defined as getter
Object.defineProperty(cls.prototype, funcName, {
value: func,
enumerable: true,
configurable: true,
writable: true,
});
}
else if (CC_DEV) {
var correct = TYPO_TO_CORRECT[funcName];
+7 -1
View File
@@ -31,7 +31,13 @@
* @type {String}
* @name cc.ENGINE_VERSION
*/
window['CocosEngine'] = cc.ENGINE_VERSION = 'Cocos Creator v0.8.0';
var engineVersion;
if (CC_EDITOR) {
engineVersion = 'Cocos Creator v' + Editor.remote.versions.CocosCreator;
} else {
engineVersion = 'Cocos Creator';
}
window['CocosEngine'] = cc.ENGINE_VERSION = engineVersion;
/**
* <p>
+5 -10
View File
@@ -114,9 +114,9 @@ switch(cc.__BrowserGetter.adaptationType){
* the standard way to use it is by calling:<br/>
* - cc.view.methodName(); <br/>
*
* @class view
* @class View
*/
cc.EGLView = cc._Class.extend(/** @lends cc.view# */{
cc.EGLView = cc._Class.extend({
_delegate: null,
// Size of parent node that contains cc.container and cc.game.canvas
_frameSize: null,
@@ -344,14 +344,6 @@ cc.EGLView = cc._Class.extend(/** @lends cc.view# */{
}
},
// RenderTexture hacker
_setScaleXYForRenderTexture: function () {
//hack for RenderTexture on canvas mode when adapting multiple resolution resources
var scaleFactor = cc.contentScaleFactor();
this._scaleX = scaleFactor;
this._scaleY = scaleFactor;
},
// Other helper functions
_resetScale: function () {
this._scaleX = this._originalScaleX;
@@ -887,10 +879,13 @@ cc.EGLView = cc._Class.extend(/** @lends cc.view# */{
selTouch = touches[i];
selPoint = selTouch._point;
selPrePoint = selTouch._prevPoint;
selStartPoint = selTouch._startPoint;
selTouch._setPoint((selPoint.x - locViewPortRect.x) / locScaleX,
(selPoint.y - locViewPortRect.y) / locScaleY);
selTouch._setPrevPoint((selPrePoint.x - locViewPortRect.x) / locScaleX,
(selPrePoint.y - locViewPortRect.y) / locScaleY);
selStartPoint.x = (selStartPoint.x - locViewPortRect.x) / locScaleX;
selStartPoint.y = (selStartPoint.y - locViewPortRect.y) / locScaleY;
}
}
});
-595
View File
@@ -1,595 +0,0 @@
var _noCacheRex = /\?/;
function urlAppendTimestamp (url) {
if (cc.game.config['noCache'] && typeof url === 'string') {
if(_noCacheRex.test(url))
url += '&_t=' + (new Date() - 0);
else
url += '?_t=' + (new Date() - 0);
}
return url;
}
/**
* Loader for resource loading process. It's a singleton object.
* @class loader
* @static
*/
cc.loader = cc.loader || (function () {
var _jsCache = {}, //cache for js
_register = {}, //register of loaders
_langPathCache = {}, //cache for lang path
_aliases = {}, //aliases for res url
_urlRegExp = new RegExp(
"^" +
// protocol identifier
"(?:(?:https?|ftp)://)" +
// user:pass authentication
"(?:\\S+(?::\\S*)?@)?" +
"(?:" +
// IP address dotted notation octets
// excludes loopback network 0.0.0.0
// excludes reserved space >= 224.0.0.0
// excludes network & broacast addresses
// (first & last IP address of each class)
"(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])" +
"(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}" +
"(?:\\.(?:[1-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))" +
"|" +
// host name
"(?:(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)" +
// domain name
"(?:\\.(?:[a-z\\u00a1-\\uffff0-9]-*)*[a-z\\u00a1-\\uffff0-9]+)*" +
// TLD identifier
"(?:\\.(?:[a-z\\u00a1-\\uffff]{2,}))" +
"|" +
"(?:localhost)" +
")" +
// port number
"(?::\\d{2,5})?" +
// resource path
"(?:/\\S*)?" +
"$", "i"
);
return /** @lends cc.loader# */{
resPath: "",//root path of resource
audioPath: "",//root path of audio
cache: {},//cache for data loaded
/**
* Get XMLHttpRequest.
* @returns {XMLHttpRequest}
*/
getXMLHttpRequest: function () {
return window.XMLHttpRequest ? new window.XMLHttpRequest() : new ActiveXObject("MSXML2.XMLHTTP");
},
//@MODE_BEGIN DEV
_getArgs4Js: function (args) {
var a0 = args[0], a1 = args[1], a2 = args[2], results = ["", null, null];
if (args.length === 1) {
results[1] = a0 instanceof Array ? a0 : [a0];
} else if (args.length === 2) {
if (typeof a1 === "function") {
results[1] = a0 instanceof Array ? a0 : [a0];
results[2] = a1;
} else {
results[0] = a0 || "";
results[1] = a1 instanceof Array ? a1 : [a1];
}
} else if (args.length === 3) {
results[0] = a0 || "";
results[1] = a1 instanceof Array ? a1 : [a1];
results[2] = a2;
} else throw new Error("arguments error to load js!");
return results;
},
/**
* Load js files.
* If the third parameter doesn't exist, then the baseDir turns to be "".
*
* @method loadJs
* @param {String} [baseDir] - The pre path for jsList or the list of js path.
* @param {Array} jsList - List of js path.
* @param {Function} [cb] - Callback function
* @returns {*}
*/
loadJs: function (baseDir, jsList, cb) {
var self = this,
args = self._getArgs4Js(arguments);
var preDir = args[0], list = args[1], callback = args[2];
if (navigator.userAgent.indexOf("Trident/5") > -1) {
self._loadJs4Dependency(preDir, list, 0, callback);
} else {
cc.async.map(list, function (item, index, cb1) {
var jsPath = cc.path.join(preDir, item);
if (_jsCache[jsPath]) return cb1(null);
self._createScript(jsPath, false, cb1);
}, callback);
}
},
/**
* Load js width loading image.
*
* @method loadJsWithImg
* @param {String} [baseDir]
* @param {Array} jsList
* @param {Function} [cb]
*/
loadJsWithImg: function (baseDir, jsList, cb) {
var self = this, jsLoadingImg = self._loadJsImg(),
args = self._getArgs4Js(arguments);
this.loadJs(args[0], args[1], function (err) {
if (err) throw new Error(err);
jsLoadingImg.parentNode.removeChild(jsLoadingImg);//remove loading gif
if (args[2]) args[2]();
});
},
_createScript: function (jsPath, isAsync, cb) {
var d = document, self = this, s = document.createElement('script');
s.async = isAsync;
_jsCache[jsPath] = true;
s.src = urlAppendTimestamp(jsPath);
s.addEventListener('load', function () {
s.parentNode.removeChild(s);
s.removeEventListener('load', arguments.callee, false);
cb();
}, false);
s.addEventListener('error', function () {
s.parentNode.removeChild(s);
cb("Load " + jsPath + " failed!");
}, false);
d.body.appendChild(s);
},
_loadJs4Dependency: function (baseDir, jsList, index, cb) {
if (index >= jsList.length) {
if (cb) cb();
return;
}
var self = this;
self._createScript(cc.path.join(baseDir, jsList[index]), false, function (err) {
if (err) return cb(err);
self._loadJs4Dependency(baseDir, jsList, index + 1, cb);
});
},
_loadJsImg: function () {
var d = document, jsLoadingImg = d.getElementById("cocos2d_loadJsImg");
if (!jsLoadingImg) {
jsLoadingImg = document.createElement('img');
if (cc._loadingImage)
jsLoadingImg.src = cc._loadingImage;
var canvasNode = d.getElementById(cc.game.config["id"]);
canvasNode.style.backgroundColor = "transparent";
canvasNode.parentNode.appendChild(jsLoadingImg);
var canvasStyle = getComputedStyle ? getComputedStyle(canvasNode) : canvasNode.currentStyle;
if (!canvasStyle)
canvasStyle = {width: canvasNode.width, height: canvasNode.height};
jsLoadingImg.style.left = canvasNode.offsetLeft + (parseFloat(canvasStyle.width) - jsLoadingImg.width) / 2 + "px";
jsLoadingImg.style.top = canvasNode.offsetTop + (parseFloat(canvasStyle.height) - jsLoadingImg.height) / 2 + "px";
jsLoadingImg.style.position = "absolute";
}
return jsLoadingImg;
},
//@MODE_END DEV
/**
* Load a single resource as txt.
*
* @method loadTxt
* @param {String} url
* @param {Function} [cb] - arguments are : err, txt
*/
loadTxt: function (url, cb) {
var xhr = this.getXMLHttpRequest(),
errInfo = "load " + url + " failed!";
url = urlAppendTimestamp(url);
xhr.open("GET", url, true);
if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
// IE-specific logic here
xhr.setRequestHeader("Accept-Charset", "utf-8");
xhr.onreadystatechange = function () {
if(xhr.readyState === 4)
(xhr.status === 200 || xhr.status === 0) ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null);
};
} else {
if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8");
xhr.onload = function () {
if(xhr.readyState === 4) {
(xhr.status === 200 || xhr.status === 0) ? cb(null, xhr.responseText) : cb({status:xhr.status, errorMessage:errInfo}, null);
}
};
xhr.onerror = function(){
cb({status:xhr.status, errorMessage:errInfo}, null);
};
}
xhr.send(null);
},
_loadTxtSync: function (url) {
var xhr = this.getXMLHttpRequest();
xhr.open("GET", url, false);
if (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent)) {
// IE-specific logic here
xhr.setRequestHeader("Accept-Charset", "utf-8");
} else {
if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=utf-8");
}
xhr.send(null);
if (!xhr.readyState === 4 || !(xhr.status === 200 || xhr.status === 0)) {
return null;
}
return xhr.responseText;
},
loadCsb: function(url, cb){
var xhr = new XMLHttpRequest(),
errInfo = "load " + url + " failed!";
url = urlAppendTimestamp(url);
xhr.open("GET", url, true);
xhr.responseType = "arraybuffer";
xhr.onload = function () {
var arrayBuffer = xhr.response; // Note: not oReq.responseText
if (arrayBuffer) {
window.msg = arrayBuffer;
}
if(xhr.readyState === 4)
xhr.status === 200 ? cb(null, xhr.response) : cb({status:xhr.status, errorMessage:errInfo}, null);
};
xhr.onerror = function(){
cb({status:xhr.status, errorMessage:errInfo}, null);
};
xhr.send(null);
},
/**
* Load a single resource as json.
*
* @method loadJson
* @param {String} url
* @param {Function} [cb] - arguments are : err, json
*/
loadJson: function (url, cb) {
this.loadTxt(url, function (err, txt) {
if (err) {
cb(err);
}
else {
try {
var result = JSON.parse(txt);
}
catch (e) {
throw new Error("parse json [" + url + "] failed : " + e);
return;
}
cb(null, result);
}
});
},
_checkIsImageURL: function (url) {
var ext = /(\.png)|(\.jpg)|(\.bmp)|(\.jpeg)|(\.gif)/.exec(url);
return (ext != null);
},
/**
* Load a single image.
*
* @method loadImg
* @param {String} url
* @param {Object} [option]
* @param {Function} callback
* @returns {Image}
*/
loadImg: function (url, option, callback) {
var opt = {
isCrossOrigin: true
};
if (callback !== undefined)
opt.isCrossOrigin = option.isCrossOrigin === null ? opt.isCrossOrigin : option.isCrossOrigin;
else if (option !== undefined)
callback = option;
url = urlAppendTimestamp(url);
var isNew = false;
var img = this.getRes(url);
if (!img) {
img = new Image();
isNew = true;
if (opt.isCrossOrigin && location.origin !== "file://")
img.crossOrigin = "Anonymous";
}
if (!isNew && img.complete && img.naturalWidth > 0) {
callback && callback(null, img);
}
else {
function loadCallback () {
img.removeEventListener('load', loadCallback);
img.removeEventListener('error', errorCallback);
if (callback)
callback(null, img);
}
var self = this;
function errorCallback () {
img.removeEventListener('load', loadCallback);
img.removeEventListener('error', errorCallback);
if (img.crossOrigin && img.crossOrigin.toLowerCase() === "anonymous") {
opt.isCrossOrigin = false;
self.release(url);
cc.loader.loadImg(url, opt, callback);
}
else {
typeof callback === "function" && callback("load image failed");
}
}
img.addEventListener("load", loadCallback);
img.addEventListener("error", errorCallback);
}
if (isNew) {
img.src = url;
}
return img;
},
/**
* Iterator function to load res.
*
* @method _loadResIterator
* @param {Object} item
* @param {Number} index
* @param {Function} [cb]
* @returns {*}
* @private
*/
_loadResIterator: function (item, index, cb) {
var self = this, url = null;
var type = item.type;
if (type) {
type = "." + type.toLowerCase();
url = item.src ? item.src : item.name + type;
} else {
url = item;
type = cc.path.extname(url);
}
var obj = self.getRes(url);
if (obj)
return cb(null, obj);
var loader = null;
if (type) {
loader = _register[type.toLowerCase()];
}
if (!loader) {
cc.error("loader for [" + type + "] not exists!");
return cb();
}
var realUrl = url;
if (!_urlRegExp.test(url))
{
var basePath = loader.getBasePath ? loader.getBasePath() : self.resPath;
realUrl = self.getUrl(basePath, url);
}
loader.load(realUrl, url, item, function (err, data) {
if (err) {
cc.log(err);
self.cache[url] = null;
delete self.cache[url];
cb({status:520, errorMessage:err}, null);
} else {
self.cache[url] = data;
cb(null, data);
}
});
},
/**
* Get url with basePath.
*
* @method getUrl
* @param {String} basePath
* @param {String} [url]
* @returns {*}
*/
getUrl: function (basePath, url) {
var self = this, path = cc.path;
if (basePath !== undefined && url === undefined) {
url = basePath;
var type = path.extname(url);
type = type ? type.toLowerCase() : "";
var loader = _register[type];
if (!loader)
basePath = self.resPath;
else
basePath = loader.getBasePath ? loader.getBasePath() : self.resPath;
}
url = cc.path.join(basePath || "", url);
if (url.match(/[\/(\\\\)]lang[\/(\\\\)]/i)) {
if (_langPathCache[url])
return _langPathCache[url];
var extname = path.extname(url) || "";
url = _langPathCache[url] = url.substring(0, url.length - extname.length) + "_" + cc.sys.language + extname;
}
return url;
},
/**
* Load resources then call the callback.
*
* @method load
* @param {String} resources
* @param {Function} [option] - callback or trigger
* @param {Function|Object} [loadCallback]
* @return {AsyncPool}
*/
load: function(resources, option, loadCallback){
'use strict';
var self = this;
var len = arguments.length;
if(len === 0)
throw new Error("arguments error!");
if(len === 3){
if(typeof option === "function"){
if(typeof loadCallback === "function")
option = {trigger : option, cb : loadCallback };
else
option = { cb : option, cbTarget : loadCallback};
}
}else if(len === 2){
if(typeof option === "function")
option = {cb : option};
}else if(len === 1){
option = {};
}
if(!(resources instanceof Array))
resources = [resources];
var asyncPool = new cc.AsyncPool(
resources, 0,
function (value, index, AsyncPoolCallback, aPool) {
self._loadResIterator(value, index, function (err, res) {
if (option.trigger)
option.trigger.call(option.triggerTarget, res, aPool.size, aPool.finishedSize); //call trigger
AsyncPoolCallback(err, res);
});
},
option.cb, option.cbTarget);
asyncPool.flow();
return asyncPool;
},
_handleAliases: function (fileNames, cb) {
var self = this;
var resList = [];
for (var key in fileNames) {
var value = fileNames[key];
_aliases[key] = value;
resList.push(value);
}
this.load(resList, cb);
},
/**
* <p>
* Loads alias map from the contents of a filename. <br/>
* <br/>
* @note The plist file name should follow the format below: <br/>
* <?xml version="1.0" encoding="UTF-8"?> <br/>
* <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <br/>
* <plist version="1.0"> <br/>
* <dict> <br/>
* <key>filenames</key> <br/>
* <dict> <br/>
* <key>sounds/click.wav</key> <br/>
* <string>sounds/click.caf</string> <br/>
* <key>sounds/endgame.wav</key> <br/>
* <string>sounds/endgame.caf</string> <br/>
* <key>sounds/gem-0.wav</key> <br/>
* <string>sounds/gem-0.caf</string> <br/>
* </dict> <br/>
* <key>metadata</key> <br/>
* <dict> <br/>
* <key>version</key> <br/>
* <integer>1</integer> <br/>
* </dict> <br/>
* </dict> <br/>
* </plist> <br/>
* </p>
*
* @method loadAliases
* @param {String} url - The plist file name.
* @param {Function} [callback]
*/
loadAliases: function (url, callback) {
var self = this, dict = self.getRes(url);
if (!dict) {
self.load(url, function (err, results) {
self._handleAliases(results[0]["filenames"], callback);
});
} else
self._handleAliases(dict["filenames"], callback);
},
/**
* Register a resource loader into loader.
*
* @method register
* @param {String} extNames
* @param {Function} loader
*/
register: function (extNames, loader) {
if (!extNames || !loader) return;
var self = this;
if (typeof extNames === "string")
return _register[extNames.trim().toLowerCase()] = loader;
for (var i = 0, li = extNames.length; i < li; i++) {
_register["." + extNames[i].trim().toLowerCase()] = loader;
}
},
/**
* Get resource data by url.
*
* @method getRes
* @param {String} url
* @returns {*}
*/
getRes: function (url) {
return this.cache[url] || this.cache[_aliases[url]];
},
/**
* Get aliase by url.
*
* @method getAliase
* @param {String} url
* @returns {*}
*/
getAliase: function (url) {
return _aliases[url];
},
/**
* Release the cache of resource by url.
*
* @method release
* @param {String} url
*/
release: function (url) {
var cache = this.cache;
delete cache[url];
delete cache[_aliases[url]];
delete _aliases[url];
},
/**
* Resource cache of all resources.
*
* @method releaseAll
*/
releaseAll: function () {
var locCache = this.cache;
for (var key in locCache)
delete locCache[key];
for (var key in _aliases)
delete _aliases[key];
}
};
})();
-156
View File
@@ -1,156 +0,0 @@
/****************************************************************************
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.
****************************************************************************/
cc._txtLoader = {
load : function(realUrl, url, res, cb){
cc.loader.loadTxt(realUrl, cb);
}
};
cc.loader.register(["txt", "xml", "vsh", "fsh", "atlas"], cc._txtLoader);
cc._jsonLoader = {
load : function(realUrl, url, res, cb){
cc.loader.loadJson(realUrl, cb);
}
};
cc.loader.register(["json", "ExportJson"], cc._jsonLoader);
cc._jsLoader = {
load : function(realUrl, url, res, cb){
cc.loader.loadJs(realUrl, cb);
}
};
cc.loader.register(["js"], cc._jsLoader);
cc._imgLoader = {
load : function(realUrl, url, res, cb){
cc.loader.cache[url] = cc.loader.loadImg(realUrl, function(err, img){
if(err)
return cb(err);
cc.textureCache.handleLoadedTexture(url);
cb(null, img);
});
}
};
cc.loader.register(["png", "jpg", "bmp","jpeg","gif", "ico", "tiff", "webp"], cc._imgLoader);
cc._serverImgLoader = {
load : function(realUrl, url, res, cb){
cc.loader.cache[url] = cc.loader.loadImg(res.src, function(err, img){
if(err)
return cb(err);
cc.textureCache.handleLoadedTexture(url);
cb(null, img);
});
}
};
cc.loader.register(["serverImg"], cc._serverImgLoader);
cc._plistLoader = {
load : function(realUrl, url, res, cb){
cc.loader.loadTxt(realUrl, function(err, txt){
if(err)
return cb(err);
cb(null, cc.plistParser.parse(txt));
});
}
};
cc.loader.register(["plist"], cc._plistLoader);
cc._fontLoader = {
TYPE : {
".eot" : "embedded-opentype",
".ttf" : "truetype",
".ttc" : "truetype",
".woff" : "woff",
".svg" : "svg"
},
_loadFont : function(name, srcs, type){
var doc = document, path = cc.path, TYPE = this.TYPE, fontStyle = document.createElement("style");
fontStyle.type = "text/css";
doc.body.appendChild(fontStyle);
var fontStr = "";
if(isNaN(name - 0))
fontStr += "@font-face { font-family:" + name + "; src:";
else
fontStr += "@font-face { font-family:'" + name + "'; src:";
if(srcs instanceof Array){
for(var i = 0, li = srcs.length; i < li; i++){
var src = srcs[i];
type = path.extname(src).toLowerCase();
fontStr += "url('" + srcs[i] + "') format('" + TYPE[type] + "')";
fontStr += (i === li - 1) ? ";" : ",";
}
}else{
type = type.toLowerCase();
fontStr += "url('" + srcs + "') format('" + TYPE[type] + "');";
}
fontStyle.textContent += fontStr + "}";
//<div style="font-family: PressStart;">.</div>
var preloadDiv = document.createElement("div");
var _divStyle = preloadDiv.style;
_divStyle.fontFamily = name;
preloadDiv.innerHTML = ".";
_divStyle.position = "absolute";
_divStyle.left = "-100px";
_divStyle.top = "-100px";
doc.body.appendChild(preloadDiv);
},
load : function(realUrl, url, res, cb){
var self = this;
var type = res.type, name = res.name, srcs = res.srcs;
if(cc.js.isString(res)){
type = cc.path.extname(res);
name = cc.path.basename(res, type);
self._loadFont(name, res, type);
}else{
self._loadFont(name, srcs);
}
if(document.fonts){
document.fonts.load("1em " + name).then(function(){
cb(null, true);
}, function(err){
cb(err);
});
}else{
cb(null, true);
}
}
};
cc.loader.register(["font", "eot", "ttf", "woff", "svg", "ttc"], cc._fontLoader);
cc._binaryLoader = {
load : function(realUrl, url, res, cb){
cc.loader.loadBinary(realUrl, cb);
}
};
cc._csbLoader = {
load: function(realUrl, url, res, cb){
cc.loader.loadCsb(realUrl, cb);
}
};
cc.loader.register(["csb"], cc._csbLoader);
+1 -99
View File
@@ -97,7 +97,7 @@ cc.swap = function (x, y, ref) {
* @param {Number} b number B
* @param {Number} r ratio between 0 and 1
* @method lerp
* @example {@link utils/api/engine/docs/cocos2d/core/platform/CCMacro/.js}
* @example {@link utils/api/engine/docs/cocos2d/core/platform/CCMacro/lerp.js}
*/
cc.lerp = function (a, b, r) {
return a + (b - a) * r;
@@ -234,104 +234,6 @@ cc.incrementGLDraws = function (addNumber) {
*/
cc.FLT_EPSILON = 0.0000001192092896;
/**
* <p>
* On Mac it returns 1;<br/>
* On iPhone it returns 2 if RetinaDisplay is On. Otherwise it returns 1
* </p>
* @return {Number}
* @method contentScaleFactor
*/
cc.contentScaleFactor = cc.IS_RETINA_DISPLAY_SUPPORTED ? function () {
return cc.director.getContentScaleFactor();
} : function () {
return 1;
};
/**
* Converts a Point in points to pixels
* @param {Vec2} points
* @return {Vec2}
* @method pointPointsToPixels
*/
cc.pointPointsToPixels = function (points) {
var scale = cc.contentScaleFactor();
return cc.p(points.x * scale, points.y * scale);
};
/**
* Converts a Point in pixels to points
* @param {Rect} pixels
* @return {Vec2}
* @method pointPixelsToPoints
*/
cc.pointPixelsToPoints = function (pixels) {
var scale = cc.contentScaleFactor();
return cc.p(pixels.x / scale, pixels.y / scale);
};
cc._pointPixelsToPointsOut = function(pixels, outPoint){
var scale = cc.contentScaleFactor();
outPoint.x = pixels.x / scale;
outPoint.y = pixels.y / scale;
};
/**
* Converts a Size in points to pixels
* @param {Size} sizeInPoints
* @return {Size}
* @method sizePointsToPixels
*/
cc.sizePointsToPixels = function (sizeInPoints) {
var scale = cc.contentScaleFactor();
return cc.size(sizeInPoints.width * scale, sizeInPoints.height * scale);
};
/**
* Converts a size in pixels to points
* @param {Size} sizeInPixels
* @return {Size}
* @method sizePixelsToPoints
*/
cc.sizePixelsToPoints = function (sizeInPixels) {
var scale = cc.contentScaleFactor();
return cc.size(sizeInPixels.width / scale, sizeInPixels.height / scale);
};
cc._sizePixelsToPointsOut = function (sizeInPixels, outSize) {
var scale = cc.contentScaleFactor();
outSize.width = sizeInPixels.width / scale;
outSize.height = sizeInPixels.height / scale;
};
/**
* Converts a rect in pixels to points
* @param {Rect} pixel
* @return {Rect}
* @method rectPixelsToPoints
*/
cc.rectPixelsToPoints = cc.IS_RETINA_DISPLAY_SUPPORTED ? function (pixel) {
var scale = cc.contentScaleFactor();
return cc.rect(pixel.x / scale, pixel.y / scale,
pixel.width / scale, pixel.height / scale);
} : function (p) {
return cc.rect(p);
};
/**
* Converts a rect in points to pixels
* @param {Rect} point
* @return {Rect}
* @method rectPointsToPixels
*/
cc.rectPointsToPixels = cc.IS_RETINA_DISPLAY_SUPPORTED ? function (point) {
var scale = cc.contentScaleFactor();
return cc.rect(point.x * scale, point.y * scale,
point.width * scale, point.height * scale);
} : function (p) {
return cc.rect(p);
};
//some gl constant variable
/**
* @property {Number} ONE
+161 -1
View File
@@ -450,6 +450,7 @@ if (typeof Editor !== 'undefined' && Editor.isCoreLevel) {
width: 0,
height: 0
};
sys.__audioSupport = {};
}
else {
// browser or runtime
@@ -581,6 +582,7 @@ else {
//Whether or not the Canvas BlendModes are supported.
sys._supportCanvasNewBlendModes = (function(){
var data1, data2;
var canvas = _tmpCanvas1;
canvas.width = 1;
canvas.height = 1;
@@ -597,7 +599,27 @@ else {
context2.fillRect(0,0,1,1);
context.drawImage(canvas2, 0, 0, 1, 1);
return context.getImageData(0,0,1,1).data[0] === 0;
data1 = context.getImageData(0,0,1,1).data[0];
canvas = _tmpCanvas1;
canvas.width = 1;
canvas.height = 1;
var context = canvas.getContext('2d');
context.fillStyle = '#fff';
context.fillRect(0,0,1,1);
context.globalCompositeOperation = 'destination-atop';
canvas2 = _tmpCanvas2;
canvas2.width = 1;
canvas2.height = 1;
var context2 = canvas2.getContext('2d');
context2.fillStyle = '#000';
context2.fillRect(0,0,1,1);
context.drawImage(canvas2, 0, 0, 1, 1);
data2 = context.getImageData(0,0,1,1).data[0];
return (data1 === 0) && (data2 === 0);
})();
// Adjust mobile css settings
@@ -677,6 +699,144 @@ else {
delete _tmpCanvas1;
delete _tmpCanvas2;
var __audioSupport;
/**
* Audio support in the browser
*
* MULTI_CHANNEL : Multiple audio while playing - If it doesn't, you can only play background music
* WEB_AUDIO : Support for WebAudio - Support W3C WebAudio standards, all of the audio can be played
* AUTOPLAY : Supports auto-play audio - if Don‘t support it, On a touch detecting background music canvas, and then replay
* REPLAY_AFTER_TOUCH : The first music will fail, must be replay after touchstart
* USE_EMPTIED_EVENT : Whether to use the emptied event to replace load callback
* DELAY_CREATE_CTX : delay created the context object - only webAudio
* NEED_MANUAL_LOOP : WebAudio loop attribute failure, need to manually perform loop
*
* May be modifications for a few browser version
*/
(function(){
var DEBUG = false;
var version = sys.browserVersion;
// check if browser supports Web Audio
// check Web Audio's context
var supportWebAudio = !!(window.AudioContext || window.webkitAudioContext || window.mozAudioContext);
var supportTable = {
'common' : {MULTI_CHANNEL: true , WEB_AUDIO: supportWebAudio , AUTOPLAY: true }
};
supportTable[sys.BROWSER_TYPE_IE] = {MULTI_CHANNEL: true , WEB_AUDIO: supportWebAudio , AUTOPLAY: true, USE_EMPTIED_EVENT: true};
// ANDROID //
supportTable[sys.BROWSER_TYPE_ANDROID] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false};
supportTable[sys.BROWSER_TYPE_CHROME] = {MULTI_CHANNEL: true , WEB_AUDIO: true , AUTOPLAY: false};
supportTable[sys.BROWSER_TYPE_FIREFOX] = {MULTI_CHANNEL: true , WEB_AUDIO: true , AUTOPLAY: true , DELAY_CREATE_CTX: true};
supportTable[sys.BROWSER_TYPE_UC] = {MULTI_CHANNEL: true , WEB_AUDIO: false, AUTOPLAY: false};
supportTable[sys.BROWSER_TYPE_QQ] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: true };
supportTable[sys.BROWSER_TYPE_OUPENG] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true };
supportTable[sys.BROWSER_TYPE_WECHAT] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true };
supportTable[sys.BROWSER_TYPE_360] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: true };
supportTable[sys.BROWSER_TYPE_MIUI] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: true };
supportTable[sys.BROWSER_TYPE_LIEBAO] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true };
supportTable[sys.BROWSER_TYPE_SOUGOU] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true };
//'Baidu' browser can automatically play
//But because it may be play failed, so need to replay and auto
supportTable[sys.BROWSER_TYPE_BAIDU] = {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true };
supportTable[sys.BROWSER_TYPE_BAIDU_APP]= {MULTI_CHANNEL: false, WEB_AUDIO: false, AUTOPLAY: false, REPLAY_AFTER_TOUCH: true , USE_EMPTIED_EVENT: true };
// APPLE //
supportTable[sys.BROWSER_TYPE_SAFARI] = {MULTI_CHANNEL: true , WEB_AUDIO: true , AUTOPLAY: false, webAudioCallback: function(realUrl){
document.createElement('audio').src = realUrl;
}};
if(sys.isMobile){
if(sys.os !== sys.OS_IOS)
__audioSupport = supportTable[sys.browserType] || supportTable['common'];
else
__audioSupport = supportTable[sys.BROWSER_TYPE_SAFARI];
}else{
switch(sys.browserType){
case sys.BROWSER_TYPE_IE:
__audioSupport = supportTable[sys.BROWSER_TYPE_IE];
break;
case sys.BROWSER_TYPE_FIREFOX:
__audioSupport = supportTable[sys.BROWSER_TYPE_FIREFOX];
break;
default:
__audioSupport = supportTable['common'];
}
}
///////////////////////////
// Browser compatibility//
///////////////////////////
if(version){
switch(sys.browserType){
case sys.BROWSER_TYPE_CHROME:
version = parseInt(version);
if(version < 30){
__audioSupport = {MULTI_CHANNEL: false , WEB_AUDIO: true , AUTOPLAY: false};
}else if(version === 42){
__audioSupport.NEED_MANUAL_LOOP = true;
}
break;
case sys.BROWSER_TYPE_MIUI:
if(sys.isMobile){
version = version.match(/\d+/g);
if(version[0] < 2 || (version[0] === 2 && version[1] === 0 && version[2] <= 1)){
__audioSupport.AUTOPLAY = false;
}
}
break;
}
}
if(DEBUG){
setTimeout(function(){
cc.log('browse type: ' + sys.browserType);
cc.log('browse version: ' + version);
cc.log('MULTI_CHANNEL: ' + __audioSupport.MULTI_CHANNEL);
cc.log('WEB_AUDIO: ' + __audioSupport.WEB_AUDIO);
cc.log('AUTOPLAY: ' + __audioSupport.AUTOPLAY);
}, 0);
}
})();
try {
if (__audioSupport.WEB_AUDIO) {
__audioSupport.context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)();
if(__audioSupport.DELAY_CREATE_CTX) {
setTimeout(function(){ __audioSupport.context = new (window.AudioContext || window.webkitAudioContext || window.mozAudioContext)(); }, 0);
}
}
} catch(error) {
__audioSupport.WEB_AUDIO = false;
cc.log("browser don't support web audio");
}
var formatSupport = [];
(function(){
var audio = document.createElement('audio');
if(audio.canPlayType) {
var ogg = audio.canPlayType('audio/ogg; codecs="vorbis"');
if (ogg) formatSupport.push('.ogg');
var mp3 = audio.canPlayType('audio/mpeg');
if (mp3) formatSupport.push('.mp3');
var wav = audio.canPlayType('audio/wav; codecs="1"');
if (wav) formatSupport.push('.wav');
var mp4 = audio.canPlayType('audio/mp4');
if (mp4) formatSupport.push('.mp4');
var m4a = audio.canPlayType('audio/x-m4a');
if (m4a) formatSupport.push('.m4a');
}
})();
__audioSupport.format = formatSupport;
sys.__audioSupport = __audioSupport;
}
/**
+16 -16
View File
@@ -27,23 +27,23 @@
var JS = require('./js');
var isPlainEmptyObj = require('./utils').isPlainEmptyObj_DEV;
/**
* @class Class
*/
// /**
// * @class Class
// */
/**
* Tag the class with any meta attributes, then return all current attributes assigned to it.
* This function holds only the attributes, not their implementations.
*
* @method attr
* @param {Function|Object} constructor - the class or instance. If instance, the attribute will be dynamic and only available for the specified instance.
* @param {String} propertyName - the name of property or function, used to retrieve the attributes
* @param {Object} [attributes] - the attribute table to mark, new attributes will merged with existed attributes. Attribute whose key starts with '_' will be ignored.
* @return {Object|Undefined} return all attributes associated with the property. if none undefined will be returned
* @static
* @private
* @example {@link utils/api/engine/docs/cocos2d/core/platform/attribute/attr.js}
*/
// *
// * Tag the class with any meta attributes, then return all current attributes assigned to it.
// * This function holds only the attributes, not their implementations.
// *
// * @method attr
// * @param {Function|Object} constructor - the class or instance. If instance, the attribute will be dynamic and only available for the specified instance.
// * @param {String} propertyName - the name of property or function, used to retrieve the attributes
// * @param {Object} [attributes] - the attribute table to mark, new attributes will merged with existed attributes. Attribute whose key starts with '_' will be ignored.
// * @return {Object|Undefined} return all attributes associated with the property. if none undefined will be returned
// * @static
// * @private
// * @example {@link utils/api/engine/docs/cocos2d/core/platform/attribute/attr.js}
function attr (constructor, propertyName, attributes) {
var key = '_attr$' + propertyName;
var instance, attrs, name;
+32 -31
View File
@@ -22,13 +22,7 @@ CallbacksHandler.prototype.add = function (key, callback, target) {
var list = this._callbackTable[key];
if (typeof list !== 'undefined') {
if (typeof callback === 'function') {
if (list !== null) {
list.push(callback);
}
else {
list = [callback];
this._callbackTable[key] = list;
}
list.push(callback);
// Just append the target after callback
if (typeof target === 'object') {
list.push(target);
@@ -38,7 +32,7 @@ CallbacksHandler.prototype.add = function (key, callback, target) {
}
else {
// new key
list = (typeof callback === 'function') ? [callback] : null;
list = (typeof callback === 'function') ? [callback] : [];
// Just append the target after callback
if (list && typeof target === 'object') {
list.push(target);
@@ -90,6 +84,11 @@ CallbacksHandler.prototype.has = function (key, callback, target) {
* @param {String|Object} key - The event key to be removed or the target to be removed
*/
CallbacksHandler.prototype.removeAll = function (key) {
// Delay removing
if (this._invoking) {
this._toRemoveAll = key;
return;
}
if (typeof key === 'object') {
var target = key, list, index, callback;
// loop for all event types
@@ -120,6 +119,12 @@ CallbacksHandler.prototype.removeAll = function (key) {
CallbacksHandler.prototype.remove = function (key, callback, target) {
var list = this._callbackTable[key], index, callbackTarget;
if (list) {
// Delay removing
if (this._invoking === key) {
this._toRemove.push([callback, target]);
return true;
}
index = list.indexOf(callback);
while (index !== -1) {
callbackTarget = list[index+1];
@@ -148,6 +153,9 @@ CallbacksHandler.prototype.remove = function (key, callback, target) {
*/
var CallbacksInvoker = function () {
CallbacksHandler.call(this);
this._invoking = null;
this._toRemove = [];
this._toRemoveAll = null;
};
JS.extend(CallbacksInvoker, CallbacksHandler);
@@ -165,11 +173,12 @@ if (CC_TEST) {
* @param {any} [p5]
*/
CallbacksInvoker.prototype.invoke = function (key, p1, p2, p3, p4, p5) {
var list = this._callbackTable[key];
this._toRemove.length = 0;
this._invoking = key;
var list = this._callbackTable[key], i;
if (list) {
var endIndex = list.length - 1;
var lastItem = list[endIndex];
for (var i = 0; i <= endIndex;) {
for (i = 0; i <= endIndex;) {
var callingFunc = list[i];
var target = list[i + 1];
var hasTarget = target && typeof target === 'object';
@@ -183,29 +192,21 @@ CallbacksInvoker.prototype.invoke = function (key, p1, p2, p3, p4, p5) {
increment = 1;
}
// TODO: check in remove
// check last one to see if any one removed
if (list[endIndex] !== lastItem && i + increment <= endIndex) { // 如果变短
if (list[endIndex - 1] === lastItem) {
// 只支持删一个
endIndex -= 1;
}
else if (list[endIndex - 2] === lastItem) {
// 只支持删一个 + target
endIndex -= 2;
}
else {
// 只允许在一个回调里面移除一个回调
return cc.error('Can remove only a callback at a time.');
}
if (list[i] !== callingFunc) { // 如果删了前面的回调,索引不加
continue;
}
}
i += increment;
}
}
this._invoking = null;
// Delay removing
for (i = 0; i < this._toRemove.length; ++i) {
var toRemove = this._toRemove[i];
this.remove(key, toRemove[0], toRemove[1]);
}
this._toRemove.length = 0;
if (this._toRemoveAll) {
this.removeAll(this._toRemoveAll);
this._toRemoveAll = null;
}
};
/**
+8 -2
View File
@@ -404,9 +404,15 @@ var _Deserializer = (function () {
// Type Object (including CCClass)
klass = self._classFinder(serialized.__type__);
var type = serialized.__type__;
klass = self._classFinder(type);
if (!klass) {
cc.error('[cc.deserialize] unknown type: ' + serialized.__type__);
if (CC_EDITOR && Editor.UuidUtils.isUuid(type)) {
type = Editor.UuidUtils.decompressUuid(type);
cc.warn('Can not find script "%s"', type);
return null;
}
cc.warn('Can not find class "%s"', type);
return null;
}
-2
View File
@@ -34,10 +34,8 @@ require('./instantiate');
require('./prefab-info');
require('./requiring-frame');
require('./CCSys');
require('./CCLoader');
require('./CCMacro');
if (cc.sys.isBrowser || cc.sys.isNative) {
require('./load-manager');
require('./CCAssetLibrary');
}
-204
View File
@@ -1,204 +0,0 @@
var CallbacksInvoker = require('./callbacks-invoker');
function getBuiltinRawTypes () {
return {
image: {
loader: cc.loader.loadImg.bind(cc.loader),
defaultExtname: '.host'
},
json: {
loader: cc.loader.loadJson.bind(cc.loader),
defaultExtname: '.json'
},
text: {
loader: cc.loader.loadTxt.bind(cc.loader),
defaultExtname: '.txt'
}
};
}
var urlToCallbacks = new CallbacksInvoker();
// list of elements to load, the element type is {
// url: url,
// loader: loader,
// callback: callback,
// }
var loadQueue = [];
var loadNext = function () {
if (LoadManager._curConcurrent >= LoadManager.maxConcurrent) {
cc.error('too many concurrent requests');
return;
}
var nextOne = loadQueue.pop();
if (nextOne) {
doLoad(nextOne.loader, nextOne.url, nextOne.callback);
}
};
function doLoad (loader, url, callback) {
LoadManager._curConcurrent += 1;
loader(url, function doLoadCB (error, asset) {
callback(error, asset);
LoadManager._curConcurrent = Math.max(0, LoadManager._curConcurrent - 1);
loadNext();
});
}
/**
* The manager scheduling resources loading
* - It will:
* - select registered loader
* - merge same url request
* - limit the max concurrent request
* - It will NOT:
* - cache what has being loaded
* - load depends of resource
* @class LoadManager
* @static
*/
var LoadManager = {
/**
* Max allowed concurrent request count
* @property {Number} maxConcurrent
* @default 2
*/
maxConcurrent: 2,
/**
* Current concurrent request count
* @property {Number} _curConcurrent
* @readOnly
*/
_curConcurrent: 0,
/**
* NOTE: Request the same url with different loader is disallowed
* @method loadByLoader
* @param {Function} loader
* @param {String} url
* @param {Function} callback
* @param {String} callback.param error - null or the error info
* @param {any} callback.param data - the loaded data
* @private
*/
loadByLoader: function (loader, url, callback) {
if (urlToCallbacks.add(url, callback)) {
var callbackBundle = urlToCallbacks.bindKey(url, true);
if (this._curConcurrent < this.maxConcurrent) {
doLoad(loader, url, callbackBundle);
}
else {
loadQueue.push({
url: url,
loader: loader,
callback: callbackBundle
});
}
}
},
/**
* @method load
* @param {String} url
* @param {String} rawType
* @param {String} [rawExtname]
* @param {Function} callback
* @param {String} callback.param error - null or the error info
* @param {any} callback.param data - the loaded data
* @private
*/
load: function (url, rawType, rawExtname, callback) {
if (typeof rawExtname === 'function') {
callback = rawExtname;
}
var typeInfo = this._rawTypes[rawType];
if (typeInfo) {
var extname = rawExtname ? ('.' + rawExtname) : typeInfo.defaultExtname;
if (extname) {
var rawUrl = url + extname;
this.loadByLoader(typeInfo.loader, rawUrl, callback);
}
else {
callback(new Error('Undefined extname for the raw ' + rawType + ' file of ' + url), null);
}
}
else {
callback(new Error('Unknown raw type "' + rawType + '" of ' + url), null);
}
},
_rawTypes: getBuiltinRawTypes(),
/**
* @method registerRawTypes
* @param {String} rawType
* @param {Function} loader
* @param {String} defaultExtname
*/
registerRawTypes: function (rawType, loader, defaultExtname) {
if (CC_DEV) {
if (!rawType) {
cc.error('[AssetLibrary.registerRawTypes] rawType must be non-nil');
return;
}
if (typeof rawType !== 'string') {
cc.error('[AssetLibrary.registerRawTypes] rawType must be string');
return;
}
if (!loader) {
cc.error('[AssetLibrary.registerRawTypes] loader must be non-nil');
return;
}
if (typeof loader !== 'function') {
cc.error('[AssetLibrary.registerRawTypes] loader must be function');
return;
}
}
if (this._rawTypes[rawType]) {
cc.error('rawType "%s" has already defined', rawType);
return;
}
if (defaultExtname && defaultExtname[0] !== '.') {
defaultExtname = '.' + defaultExtname;
}
this._rawTypes[rawType] = {
loader: loader,
defaultExtname: defaultExtname
};
},
reset: function () {
if (CC_EDITOR) {
var audio = this._rawTypes.audio;
this._rawTypes = getBuiltinRawTypes();
this._rawTypes.audio = audio;
}
},
isLoading: function (url, alsoCheckRaw) {
if (CC_EDITOR) {
if (this._curConcurrent === 0) {
return false;
}
if (urlToCallbacks.has(url)) {
return true;
}
if (alsoCheckRaw) {
for (var u in urlToCallbacks._callbackTable) {
if (u.indexOf(url) === 0) {
return true;
}
}
}
return false;
}
}
};
// TODO - merge with cc.loader
cc._LoadManager = LoadManager;
module.exports = LoadManager;
+8 -5
View File
@@ -77,10 +77,13 @@ if (CC_DEV) {
if (CC_TEST) {
// editor mocks using in unit tests
if (typeof Editor === 'undefined') {
Editor = {};
Editor = {
UuidUtils: {
NonUuidMark: '.',
uuid: function () {
return '' + ((new Date()).getTime() + Math.random());
}
}
};
}
Editor.uuid = function () {
return '' + ((new Date()).getTime() + Math.random());
};
Editor.NonUuidMark = '.';
}
+9 -9
View File
@@ -56,11 +56,12 @@ cc.LoaderScene = _ccsg.Scene.extend({
var fontSize = 24, lblHeight = -logoHeight / 2 + 100;
if(cc._loaderImage){
//loading logo
cc.loader.loadImg(cc._loaderImage, {isCrossOrigin : false }, function(err, img){
logoWidth = img.width;
logoHeight = img.height;
self._initStage(img, cc.visibleRect.center);
});
var img = new Image();
img.src = cc._loaderImage;
logoWidth = img.width;
logoHeight = img.height;
self._initStage(img, cc.visibleRect.center);
fontSize = 14;
lblHeight = -logoHeight / 2 - 10;
}
@@ -78,7 +79,6 @@ cc.LoaderScene = _ccsg.Scene.extend({
texture2d.initWithElement(img);
texture2d.handleLoadedTexture();
var logo = self._logo = new _ccsg.Sprite(texture2d);
logo.setScale(cc.contentScaleFactor());
logo.x = centerPos.x;
logo.y = centerPos.y;
self._bgLayer.addChild(logo, 10);
@@ -124,13 +124,13 @@ cc.LoaderScene = _ccsg.Scene.extend({
self.unschedule(self._startLoading);
var res = self.resources;
cc.loader.load(res,
function (result, count, loadedCount) {
function (loadedCount, count) {
var percent = (loadedCount / count * 100) | 0;
percent = Math.min(percent, 100);
self._label.setString("Loading... " + percent + "%");
}, function () {
}, function (error, items) {
if (self.cb)
self.cb.call(self.target);
self.cb.call(self.target, error, items);
});
},
+37 -6
View File
@@ -25,15 +25,15 @@
****************************************************************************/
/**
* <p>
* This API is deprecated, will be replaced by new API from {{#crossLink "Animation"}}cc.Animation{{/crossLink}}
* cc.AnimationFrame
* A frame of the animation. It contains information like:
* - sprite frame name
* - # of delay units.
* - offset
* </p>
* @class
* @class AnimationFrame
* @extends cc._Class
* @deprecated
* @param spriteFrame
* @param delayUnits
* @param userInfo
@@ -52,6 +52,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{
/**
* Create a new animation frame and copy all contents into it
* @method clone
* @returns {AnimationFrame}
*/
clone: function(){
@@ -62,6 +63,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{
/**
* Create a new animation frame and copy all contents into it
* @method copyWithZone
* @returns {AnimationFrame}
*/
copyWithZone:function (pZone) {
@@ -70,6 +72,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{
/**
* Create a new animation frame and copy all contents into it
* @method copy
* @returns {AnimationFrame}
*/
copy:function (pZone) {
@@ -80,6 +83,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{
/**
* initializes the animation frame with a spriteframe, number of delay units and a notification user info
* @method initWithSpriteFrame
* @param {cc.SpriteFrame} spriteFrame
* @param {Number} delayUnits
* @param {object} userInfo
@@ -94,6 +98,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{
/**
* Returns sprite frame to be used
* @method getSpriteFrame
* @return {cc.SpriteFrame}
*/
getSpriteFrame:function () {
@@ -102,6 +107,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{
/**
* Sets sprite frame to be used
* @method setSpriteFrame
* @param {cc.SpriteFrame} spriteFrame
*/
setSpriteFrame:function (spriteFrame) {
@@ -110,6 +116,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{
/**
* Returns how many units of time the frame takes getter
* @method getDelayUnits
* @return {Number}
*/
getDelayUnits:function () {
@@ -118,6 +125,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{
/**
* Sets how many units of time the frame takes setter
* @method setDelayUnits
* @param delayUnits
*/
setDelayUnits:function (delayUnits) {
@@ -126,6 +134,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{
/**
* Returns the user custom information
* @method getUserInfo
* @return {object}
*/
getUserInfo:function () {
@@ -134,6 +143,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{
/**
* Sets the user custom information
* @method setUserInfo
* @param {object} userInfo
*/
setUserInfo:function (userInfo) {
@@ -143,6 +153,7 @@ cc.AnimationFrame = cc._Class.extend(/** @lends cc.AnimationFrame# */{
/**
* Creates an animation frame.
* @method create
* @deprecated since v3.0, please use the new construction instead
* @param {cc.SpriteFrame} spriteFrame
* @param {Number} delayUnits
@@ -154,6 +165,7 @@ cc.AnimationFrame.create = function(spriteFrame,delayUnits,userInfo){
};
/**
* This API is deprecated, will be replaced by new API from {{#crossLink "Animation"}}cc.Animation{{/crossLink}}
* <p>
* A cc.SpriteFrameAnimation object is used to perform animations on the _ccsg.Sprite objects.<br/>
* <br/>
@@ -223,6 +235,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Returns the array of animation frames
* @method getFrames
* @return {Array}
*/
getFrames:function () {
@@ -231,6 +244,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Sets array of animation frames
* @method setFrames
* @param {Array} frames
*/
setFrames:function (frames) {
@@ -239,6 +253,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Adds a frame to a cc.SpriteFrameAnimation, the frame will be added with one "delay unit".
* @method addSpriteFrame
* @param {cc.SpriteFrame} frame
*/
addSpriteFrame:function (frame) {
@@ -252,6 +267,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Adds a frame with an image filename. Internally it will create a cc.SpriteFrame and it will add it. The frame will be added with one "delay unit".
* @method addSpriteFrameWithFile
* @param {String} fileName
*/
addSpriteFrameWithFile:function (fileName) {
@@ -265,6 +281,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Adds a frame with a texture and a rect. Internally it will create a cc.SpriteFrame and it will add it. The frame will be added with one "delay unit".
* @method addSpriteFrameWithTexture
* @param {cc.Texture2D} texture
* @param {cc.Rect} rect
*/
@@ -275,6 +292,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Initializes a cc.SpriteFrameAnimation with cc.AnimationFrame, do not call this method yourself, please pass parameters to constructor to initialize.
* @method initWithAnimationFrames
* @param {Array} arrayOfAnimationFrames
* @param {Number} delayPerUnit
* @param {Number} [loops=1]
@@ -299,6 +317,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Clone the current animation
* @method clone
* @return {cc.SpriteFrameAnimation}
*/
clone: function(){
@@ -310,6 +329,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Clone the current animation
* @method copyWithZone
* @return {cc.SpriteFrameAnimation}
*/
copyWithZone:function (pZone) {
@@ -328,6 +348,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Clone the current animation
* @method copy
* @param pZone
* @returns {cc.SpriteFrameAnimation}
*/
@@ -337,6 +358,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Returns how many times the animation is going to loop. 0 means animation is not animated. 1, animation is executed one time, ...
* @method getLoops
* @return {Number}
*/
getLoops:function () {
@@ -345,6 +367,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Sets how many times the animation is going to loop. 0 means animation is not animated. 1, animation is executed one time, ...
* @method setLoops
* @param {Number} value
*/
setLoops:function (value) {
@@ -353,6 +376,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Sets whether or not it shall restore the original frame when the animation finishes
* @method setRestoreOriginalFrame
* @param {Boolean} restOrigFrame
*/
setRestoreOriginalFrame:function (restOrigFrame) {
@@ -361,6 +385,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Returns whether or not it shall restore the original frame when the animation finishes
* @method getRestoreOriginalFrame
* @return {Boolean}
*/
getRestoreOriginalFrame:function () {
@@ -369,6 +394,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Returns duration in seconds of the whole animation. It is the result of totalDelayUnits * delayPerUnit
* @method getDuration
* @return {Number}
*/
getDuration:function () {
@@ -377,6 +403,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Returns delay in seconds of the "delay unit"
* @method getDelayPerUnit
* @return {Number}
*/
getDelayPerUnit:function () {
@@ -385,6 +412,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Sets delay in seconds of the "delay unit"
* @method setDelayPerUnit
* @param {Number} delayPerUnit
*/
setDelayPerUnit:function (delayPerUnit) {
@@ -393,6 +421,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Returns total delay units of the cc.SpriteFrameAnimation.
* @method getTotalDelayUnits
* @return {Number}
*/
getTotalDelayUnits:function () {
@@ -401,6 +430,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Initializes a cc.SpriteFrameAnimation with frames and a delay between frames, do not call this method yourself, please pass parameters to constructor to initialize.
* @method initWithSpriteFrames
* @param {Array} frames
* @param {Number} delay
* @param {Number} [loops=1]
@@ -434,7 +464,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
* The retain function can increase a reference count for the native object to avoid it being released,<br/>
* you need to manually invoke release function when you think this object is no longer needed, otherwise, there will be memory learks.<br/>
* retain and release function call should be paired in developer's game code.</p>
* @function
* @function retain
* @see cc.SpriteFrameAnimation#release
*/
retain:function () {
@@ -449,7 +479,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
* The retain function can increase a reference count for the native object to avoid it being released,<br/>
* you need to manually invoke release function when you think this object is no longer needed, otherwise, there will be memory learks.<br/>
* retain and release function call should be paired in developer's game code.</p>
* @function
* @function release
* @see cc.SpriteFrameAnimation#retain
*/
release:function () {
@@ -458,6 +488,7 @@ cc.SpriteFrameAnimation = cc._Class.extend({
/**
* Creates an animation.
* @method create
* @deprecated since v3.0, please use new construction instead
* @see cc.SpriteFrameAnimation
* @param {Array} frames
@@ -471,7 +502,7 @@ cc.SpriteFrameAnimation.create = function (frames, delay, loops) {
/**
* @deprecated since v3.0, please use new construction instead
* @method createWithAnimationFrames
* @see cc.SpriteFrameAnimation
* @type {Function}
*/
cc.SpriteFrameAnimation.createWithAnimationFrames = cc.SpriteFrameAnimation.create;
+5 -6
View File
@@ -758,15 +758,14 @@ _ccsg.Sprite = _ccsg.Node.extend({
* @param {cc.Rect} rect a rect of texture
* @param {Boolean} [rotated] Whether or not the texture is rotated
* @param {cc.Size} [untrimmedSize] The original pixels size of the texture
* @param {Boolean} [needConvert] contentScaleFactor switch
*/
setTextureRect: function (rect, rotated, untrimmedSize, needConvert) {
setTextureRect: function (rect, rotated, untrimmedSize) {
var _t = this;
_t._rectRotated = rotated || false;
_t.setContentSize(untrimmedSize || rect);
_t.setVertexRect(rect);
_t._renderCmd._setTextureCoords(rect, needConvert);
_t._renderCmd._setTextureCoords(rect);
var relativeOffsetX = _t._unflippedOffsetPositionFromCenter.x, relativeOffsetY = _t._unflippedOffsetPositionFromCenter.y;
if (_t._flippedX)
@@ -897,10 +896,10 @@ _ccsg.Sprite = _ccsg.Node.extend({
*/
getSpriteFrame: function () {
return new cc.SpriteFrame(this._texture,
cc.rectPointsToPixels(this._rect),
this._rect,
this._rectRotated,
cc.pointPointsToPixels(this._unflippedOffsetPositionFromCenter),
cc.sizePointsToPixels(this._contentSize));
this._unflippedOffsetPositionFromCenter,
this._contentSize);
},
/**
@@ -277,15 +277,12 @@
node.emit("load");
};
proto._setTextureCoords = function (rect, needConvert) {
if (needConvert === undefined)
needConvert = true;
var locTextureRect = this._textureCoord,
scaleFactor = needConvert ? cc.contentScaleFactor() : 1;
locTextureRect.renderX = locTextureRect.x = 0 | (rect.x * scaleFactor);
locTextureRect.renderY = locTextureRect.y = 0 | (rect.y * scaleFactor);
locTextureRect.width = 0 | (rect.width * scaleFactor);
locTextureRect.height = 0 | (rect.height * scaleFactor);
proto._setTextureCoords = function (rect) {
var locTextureRect = this._textureCoord;
locTextureRect.renderX = locTextureRect.x = 0 | rect.x;
locTextureRect.renderY = locTextureRect.y = 0 | rect.y;
locTextureRect.width = 0 | rect.width;
locTextureRect.height = 0 | rect.height;
locTextureRect.validRect = !(locTextureRect.width === 0 || locTextureRect.height === 0 || locTextureRect.x < 0 || locTextureRect.y < 0);
};
@@ -143,11 +143,7 @@
node.emit("load");
};
proto._setTextureCoords = function (rect, needConvert) {
if (needConvert === undefined)
needConvert = true;
if (needConvert)
rect = cc.rectPointsToPixels(rect);
proto._setTextureCoords = function (rect) {
var node = this._node;
var tex = node._batchNode ? node.textureAtlas.texture : node._texture;
+26 -13
View File
@@ -125,7 +125,7 @@ var simpleQuadGenerator = {
var atlasWidth = spriteFrame._texture.getPixelWidth();
var atlasHeight = spriteFrame._texture.getPixelHeight();
var textureRect = cc.rectPointsToPixels(spriteFrame.getRect());
var textureRect = spriteFrame.getRect();
//uv computation should take spritesheet into account.
var u0, u3;
@@ -255,7 +255,7 @@ var scale9QuadGenerator = {
bottomHeight = insetBottom;
centerHeight = rect.height - topHeight - bottomHeight;
var textureRect = cc.rectPointsToPixels(spriteFrame.getRect());
var textureRect = spriteFrame.getRect();
//uv computation should take spritesheet into account.
var u0, u1, u2, u3;
@@ -346,7 +346,7 @@ var tiledQuadGenerator = {
var atlasWidth = spriteFrame._texture.getPixelWidth();
var atlasHeight = spriteFrame._texture.getPixelHeight();
var textureRect = cc.rectPointsToPixels(spriteFrame.getRect());
var textureRect = spriteFrame.getRect();
//uv computation should take spritesheet into account.
var u0, u3;
@@ -425,7 +425,7 @@ var fillQuadGeneratorBar = {
var progressStart, progressEnd;
switch (fillType) {
case cc.Scale9Sprite.FillType.Horizontal:
case cc.Scale9Sprite.FillType.HORIZONTAL:
progressStart = vertices[0].x + (vertices[1].x - vertices[0].x) * fillStart;
progressEnd = vertices[0].x + (vertices[1].x - vertices[0].x) * fillEnd;
@@ -447,7 +447,7 @@ var fillQuadGeneratorBar = {
quad._tr.texCoords.u = quadUV[2].u + (quadUV[3].u - quadUV[2].u) * fillEnd;
quad._tr.texCoords.v = quadUV[2].v + (quadUV[3].v - quadUV[2].v) * fillEnd;
break;
case cc.Scale9Sprite.FillType.Vertical:
case cc.Scale9Sprite.FillType.VERTICAL:
progressStart = vertices[0].y + (vertices[1].y - vertices[0].y) * fillStart;
progressEnd = vertices[0].y + (vertices[1].y - vertices[0].y) * fillEnd;
@@ -494,7 +494,7 @@ var fillQuadGeneratorBar = {
var atlasWidth = spriteFrame._texture.getPixelWidth();
var atlasHeight = spriteFrame._texture.getPixelHeight();
var textureRect = cc.rectPointsToPixels(spriteFrame.getRect());
var textureRect = spriteFrame.getRect();
//uv computation should take spritesheet into account.
var u0, u3;
@@ -764,7 +764,7 @@ var fillQuadGeneratorRadial = {
var yleft = center.y + tanAngle * (left - center.x);
if(yleft > bottom && yleft < top) {
intersectPoints[0] = intersectPoints[4];
intersectPoints[5] = null;
intersectPoints[4] = null;
intersectPoints[0].x = left;
intersectPoints[0].y = yleft;
}
@@ -843,7 +843,7 @@ var fillQuadGeneratorRadial = {
var atlasWidth = spriteFrame._texture.getPixelWidth();
var atlasHeight = spriteFrame._texture.getPixelHeight();
var textureRect = cc.rectPointsToPixels(spriteFrame.getRect());
var textureRect = spriteFrame.getRect();
//uv computation should take spritesheet into account.
var u0, u3;
@@ -1221,11 +1221,24 @@ cc.Scale9Sprite = _ccsg.Node.extend({
} else if (this._renderingType === cc.Scale9Sprite.RenderingType.TILED) {
this._quads = tiledQuadGenerator._rebuildQuads_base(this._spriteFrame, this.getContentSize(), color);
} else if (this._renderingType === cc.Scale9Sprite.RenderingType.FILLED) {
var fillstart = this._fillStart;
var fillRange = this._fillRange;
if(fillRange < 0) {
fillstart += fillRange;
fillRange = -fillRange;
}
if(this._fillType !== cc.Scale9Sprite.FillType.RADIAL) {
this._quads = fillQuadGeneratorBar._rebuildQuads_base(this._spriteFrame, this.getContentSize(), color, this._fillType, this._fillStart,this._fillRange);
fillRange = fillstart + fillRange;
fillstart = fillstart > 1.0 ? 1.0 : fillstart;
fillstart = fillstart < 0.0 ? 0.0 : fillstart;
fillRange = fillRange > 1.0 ? 1.0 : fillRange;
fillRange = fillRange < 0.0 ? 0.0 : fillRange;
fillRange = fillRange - fillstart;
this._quads = fillQuadGeneratorBar._rebuildQuads_base(this._spriteFrame, this.getContentSize(), color, this._fillType, fillstart,fillRange);
} else {
this._isTriangle = true;
var fillResult = fillQuadGeneratorRadial._rebuildQuads_base(this._spriteFrame, this.getContentSize(), color,this._fillCenter,this._fillStart,this._fillRange);
var fillResult = fillQuadGeneratorRadial._rebuildQuads_base(this._spriteFrame, this.getContentSize(), color,this._fillCenter,fillstart,fillRange);
this._quads = fillResult.quad;
this._rawQuad = fillResult.rawQuad;
}
@@ -1315,8 +1328,8 @@ cc.Scale9Sprite.RenderingType = cc.Enum({
});
cc.Scale9Sprite.FillType = cc.Enum({
Horizontal: 0,
Vertical: 1,
HORIZONTAL: 0,
VERTICAL: 1,
//todo implement this
RADIAL:2,
});
});
+18 -116
View File
@@ -90,15 +90,12 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{
// the location of the sprite on rendering texture
this._rect = null;
this._rectInPixels = null;
// for trimming
this._offset = null;
this._offsetInPixels = null;
// for trimming
this._originalSize = null;
this._originalSizeInPixels = null;
this._rotated = false;
@@ -170,34 +167,6 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{
this.once("load", callback, target);
},
/**
* Gets the rect of the frame in the texture.
* @method getRectInPixels
* @return {Rect}
*/
getRectInPixels: function () {
return cc.rect(this._rectInPixels);
},
/**
* Sets the rect of the frame in the texture.
* @method setRectInPixels
* @param {Rect} rectInPixels
*/
setRectInPixels: function (rectInPixels) {
if (!this._rectInPixels) {
this._rectInPixels = cc.rect(rectInPixels);
} else {
var rect = this._rectInPixels;
rect.x = rectInPixels.x;
rect.y = rectInPixels.y;
rect.width = rectInPixels.width;
rect.height = rectInPixels.height;
}
this._rect = cc.rectPixelsToPoints(rectInPixels);
},
/**
* Returns whether the sprite frame is rotated in the texture.
* @method isRotated
@@ -231,66 +200,7 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{
* @param {Rect} rect
*/
setRect: function (rect) {
if (!this._rect) {
this._rect = cc.rect(rect);
} else {
var locRect = this._rect;
locRect.x = rect.x;
locRect.y = rect.y;
locRect.width = rect.width;
locRect.height = rect.height;
}
this._rectInPixels = cc.rectPointsToPixels(rect);
},
/**
* Returns the offset of the sprite frame in the texture in pixel.
* @method getOffsetInPixels
* @return {Vec2}
*/
getOffsetInPixels: function () {
return cc.v2(this._offsetInPixels);
},
/**
* Sets the offset of the sprite frame in the texture in pixel.
* @method setOffsetInPixels
* @param {Vec2} offsetInPixels
*/
setOffsetInPixels: function (offsetInPixels) {
if (!this._offsetInPixels) {
this._offsetInPixels = cc.v2(offsetInPixels);
} else {
this._offsetInPixels.x = offsetInPixels.x;
this._offsetInPixels.y = offsetInPixels.y;
}
this._offset = cc.pointPixelsToPoints(offsetInPixels);
},
/**
* Returns the original size of the trimmed image.
* @method getOriginalSizeInPixels
* @return {Size}
*/
getOriginalSizeInPixels: function () {
return cc.size(this._originalSizeInPixels);
},
/**
* Sets the original size of the trimmed image.
* @method setOriginalSizeInPixels
* @param {Size} sizeInPixels
*/
setOriginalSizeInPixels: function (sizeInPixels) {
if (!this._originalSizeInPixels) {
this._originalSizeInPixels = cc.size(sizeInPixels);
} else {
this._originalSizeInPixels.width = sizeInPixels.width;
this._originalSizeInPixels.height = sizeInPixels.height;
}
this._originalSize = cc.sizePixelsToPoints(sizeInPixels);
this._rect = rect;
},
/**
@@ -314,8 +224,6 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{
this._originalSize.width = size.width;
this._originalSize.height = size.height;
}
this._originalSizeInPixels = cc.sizePointsToPixels(size);
},
/**
@@ -388,13 +296,7 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{
* @param {Vec2} offsets
*/
setOffset: function (offsets) {
if (!this._offset) {
this._offset = cc.v2(offsets);
} else {
this._offset.x = offsets.x;
this._offset.y = offsets.y;
}
this._offsetInPixels = cc.pointPointsToPixels(offsets);
this._offset = cc.v2(offsets);
},
/**
@@ -403,14 +305,14 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{
* @return {SpriteFrame}
*/
clone: function () {
return new cc.SpriteFrame(this._textureFilename, this._rectInPixels, this._rotated, this._offsetInPixels, this._originalSizeInPixels);
return new cc.SpriteFrame(this._texture || this._textureFilename, this._rect, this._rotated, this._offset, this._originalSize);
},
/**
* Initializes SpriteFrame with Texture, rect, rotated, offset and originalSize in pixels.<br/>
* Please pass parameters to the constructor to initialize the sprite, do not call this function yourself.
* @method initWithTexture
* @param {String|cc.Texture2D} texture
* @param {String|Texture2D} texture
* @param {Rect} rect - if parameters' length equal 2, rect in points, else rect in pixels
* @param {Boolean} [rotated=false]
* @param {Vec2} [offset=cc.v2(0,0)]
@@ -424,21 +326,21 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{
setTexture: function (textureOrTextureFile, rect, rotated, offset, originalSize) {
if (rect) {
this.setRectInPixels(rect);
this.setRect(rect);
} else {
this._rect = this._rectInPixels = null;
this._rect = null;
}
if (offset) {
this.setOffsetInPixels(offset);
this.setOffset(offset);
} else {
this._offset = this._offsetInPixels = null;
this._offset = null;
}
if (originalSize) {
this.setOriginalSizeInPixels(originalSize);
this.setOriginalSize(originalSize);
} else {
this._originalSize = this._originalSizeInPixels = null;
this._originalSize = null;
}
this._rotated = rotated || false;
@@ -463,7 +365,7 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{
},
_checkRect: function (texture) {
var rect = this._rectInPixels;
var rect = this._rect;
var maxX = rect.x, maxY = rect.y;
if (this._rotated) {
maxX += rect.height;
@@ -494,7 +396,7 @@ cc.SpriteFrame = cc.Class(/** @lends cc.SpriteFrame# */{
uuid = url._uuid;
}
else {
uuid = Editor.urlToUuid(url);
uuid = Editor.UuidCache.urlToUuid(url);
}
}
var capInsets = undefined;
@@ -560,7 +462,7 @@ proto.copyWithZone = proto.clone;
/**
* Copy the sprite frame
* @method copy
* @returns {cc.SpriteFrame}
* @returns {SpriteFrame}
*/
proto.copy = proto.clone;
@@ -571,12 +473,12 @@ proto.copy = proto.clone;
* </p>
* since v3.0, please use new constructor {{#crossLink "SpriteFrame/SpriteFrame:method"}}SpriteFrame(){{/crossLink}} instead.
* @method create
* @param {String|cc.Texture2D} filename
* @param {cc.Rect} rect if parameters' length equal 2, rect in points, else rect in pixels
* @param {String|Texture2D} filename
* @param {Rect} rect if parameters' length equal 2, rect in points, else rect in pixels
* @param {Boolean} rotated
* @param {cc.Vec2} offset
* @param {cc.Size} originalSize
* @return {cc.SpriteFrame}
* @param {Vec2} offset
* @param {Size} originalSize
* @return {SpriteFrame}
*/
cc.SpriteFrame.create = function (filename, rect, rotated, offset, originalSize) {
return new cc.SpriteFrame(filename, rect, rotated, offset, originalSize);
+1 -1
View File
@@ -185,7 +185,7 @@ cc.spriteFrameCache = /** @lends cc.spriteFrameCache# */{
var locTexture = spriteFrame.getTexture();
if (locTexture.isLoaded()) {
var tempElement = spriteFrame.getTexture().getHtmlElementObj();
tempElement = _ccsg.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, spriteFrame.getRectInPixels());
tempElement = _ccsg.Sprite.CanvasRenderCmd._cutRotateImageToCanvas(tempElement, spriteFrame.getRect());
var tempTexture = new cc.Texture2D();
tempTexture.initWithElement(tempElement);
tempTexture.handleLoadedTexture();
+2 -2
View File
@@ -34,7 +34,7 @@
/**
* convert an affine transform object to a kmMat4 object
* @method CGAffineToGL
* @param {cc.AffineTransform} trans
* @param {AffineTransform} trans
* @param {cc.kmMat4} mat
*/
cc.CGAffineToGL = function (trans, mat) {
@@ -56,7 +56,7 @@ cc.CGAffineToGL = function (trans, mat) {
* Convert a kmMat4 object to an affine transform object
* @method GLToCGAffine
* @param {cc.kmMat4} mat
* @param {cc.AffineTransform} trans
* @param {AffineTransform} trans
*/
cc.GLToCGAffine = function (mat, trans) {
trans.a = mat[0];
+44 -58
View File
@@ -194,15 +194,14 @@ var Texture2D = cc.Class(/** @lends cc.Texture2D# */{
* @returns {Size}
*/
getContentSize: function () {
var locScaleFactor = cc.contentScaleFactor();
return cc.size(this._contentSize.width / locScaleFactor, this._contentSize.height / locScaleFactor);
return cc.size(this._contentSize.width, this._contentSize.height);
},
_getWidth: function () {
return this._contentSize.width / cc.contentScaleFactor();
return this._contentSize.width;
},
_getHeight: function () {
return this._contentSize.height / cc.contentScaleFactor();
return this._contentSize.height;
},
/**
@@ -705,22 +704,25 @@ game.once(game.EVENT_RENDERER_INITED, function () {
canvas.width = rect.width;
canvas.height = rect.height;
var context = canvas.getContext("2d");
context.globalCompositeOperation = "source-over";
context.fillStyle = "rgb(" + (r|0) + "," + (g|0) + "," + (b|0) + ")";
context.fillRect(0, 0, rect.width, rect.height);
context.globalCompositeOperation = "multiply";
context.drawImage(
textureImage,
rect.x, rect.y, rect.width, rect.height,
0, 0, rect.width, rect.height
);
context.globalCompositeOperation = "destination-atop";
context.drawImage(
textureImage,
rect.x, rect.y, rect.width, rect.height,
0, 0, rect.width, rect.height
);
if(rect.width && rect.height) {
var context = canvas.getContext("2d");
context.globalCompositeOperation = "source-over";
context.fillStyle = "rgb(" + (r|0) + "," + (g|0) + "," + (b|0) + ")";
context.fillRect(0, 0, rect.width, rect.height);
context.globalCompositeOperation = "multiply";
context.drawImage(
textureImage,
rect.x, rect.y, rect.width, rect.height,
0, 0, rect.width, rect.height
);
context.globalCompositeOperation = "destination-atop";
context.drawImage(
textureImage,
rect.x, rect.y, rect.width, rect.height,
0, 0, rect.width, rect.height
);
}
if(onlyCanvas)
return canvas;
var newTexture = new Texture2D();
@@ -733,53 +735,37 @@ game.once(game.EVENT_RENDERER_INITED, function () {
onlyCanvas = true;
else
canvas = document.createElement("canvas");
var textureImage = this._htmlElementObj;
if(!rect)
rect = cc.rect(0, 0, textureImage.width, textureImage.height);
var x, y, w, h;
x = rect.x; y = rect.y; w = rect.width; h = rect.height;
if(!w || !h)
return;
canvas.width = w;
canvas.height = h;
var context = canvas.getContext("2d");
var tintedImgCache = cc.textureCache.getTextureColors(this);
context.globalCompositeOperation = 'lighter';
context.drawImage(
tintedImgCache[3],
x, y, w, h,
0, 0, w, h
);
if (r > 0) {
context.globalAlpha = r / 255;
canvas.width = rect.width;
canvas.height = rect.height;
if(rect.width && rect.height) {
var context = canvas.getContext("2d");
context.drawImage(
tintedImgCache[0],
x, y, w, h,
0, 0, w, h
);
}
if (g > 0) {
context.globalAlpha = g / 255;
context.drawImage(
tintedImgCache[1],
x, y, w, h,
0, 0, w, h
);
}
if (b > 0) {
context.globalAlpha = b / 255;
context.drawImage(
tintedImgCache[2],
x, y, w, h,
0, 0, w, h
textureImage,
rect.x, rect.y, rect.width, rect.height,
0, 0, rect.width, rect.height
);
var imageData = context.getImageData(0,0,canvas.width, canvas.height);
var data = imageData.data;
r = r/255;
g = g/255;
b = b/255;
for (var i = 0; i < data.length; i += 4) {
data[i] = data[i] * r;
data[i + 1] = data[i+1] * g;
data[i + 2] = data[i+2] * b;
}
context.putImageData(imageData, 0, 0);
}
if(onlyCanvas)
return canvas;
var newTexture = new Texture2D();
newTexture.initWithElement(canvas);
newTexture.handleLoadedTexture();
+11 -11
View File
@@ -83,7 +83,7 @@ var textureCache = /** @lends cc.textureCache# */{
* @example {@link utils/api/engine/docs/cocos2d/core/textures/getTextureForKey.js}
*/
getTextureForKey: function(textureKeyName){
return this._textures[textureKeyName] || this._textures[cc.loader.getAliase(textureKeyName)];
return this._textures[textureKeyName];
},
/**
@@ -301,7 +301,7 @@ game.once(game.EVENT_RENDERER_INITED, function () {
var locTexs = this._textures;
//remove judge
var tex = locTexs[url] || locTexs[cc.loader.getAliase(url)];
var tex = locTexs[url];
if (tex) {
if(tex.isLoaded()) {
cb && cb.call(target, tex);
@@ -318,11 +318,11 @@ game.once(game.EVENT_RENDERER_INITED, function () {
tex = locTexs[url] = new Texture2D();
tex.url = url;
cc.loader.loadImg(url, function (err, img) {
if (err)
return cb && cb.call(target, err);
cc.loader.load(url, function (err, texture) {
if (err) {
return cb && cb.call(target, err || new Error('Unknown error'));
}
tex.initWithElement(img);
textureCache.handleLoadedTexture(url);
cb && cb.call(target, tex);
@@ -359,7 +359,7 @@ game.once(game.EVENT_RENDERER_INITED, function () {
if (!cc.game._rendererInitialized) {
locTexs = this._loadedTexturesBefore;
}
var tex = locTexs[url] || locTexs[cc.loader.getAliase(url)];
var tex = locTexs[url];
if (tex) {
if(tex.isLoaded()) {
cb && cb.call(target, tex);
@@ -376,11 +376,11 @@ game.once(game.EVENT_RENDERER_INITED, function () {
tex = locTexs[url] = new Texture2D();
tex.url = url;
cc.loader.loadImg(url, function (err, img) {
if (err)
return cb && cb.call(target, err);
cc.loader.load(url, function (err, texture) {
if (err) {
return cb && cb.call(target, err || new Error('Unknown error'));
}
tex.initWithElement(img);
textureCache.handleLoadedTexture(url);
cb && cb.call(target, tex);
-159
View File
@@ -1,159 +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.
****************************************************************************/
require('../platform/CCLoader');
/**
* @module cc
* @class loader
*/
/**
* Load binary data by url.
* @method loadBinary
* @param {String} url
* @param {Function} [cb]
*/
cc.loader.loadBinary = function (url, cb) {
var self = this;
var xhr = this.getXMLHttpRequest(),
errInfo = "load " + url + " failed!";
xhr.open("GET", url, true);
if (cc.loader.loadBinary._IEFilter) {
// IE-specific logic here
xhr.setRequestHeader("Accept-Charset", "x-user-defined");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && (xhr.status === 200 || (CC_TEST && xhr.status === 0))) {
var fileContents = cc._convertResponseBodyToText(xhr["responseBody"]);
cb(null, self._str2Uint8Array(fileContents));
} else cb(errInfo);
};
} else {
if (xhr.overrideMimeType) xhr.overrideMimeType("text\/plain; charset=x-user-defined");
xhr.onload = function () {
xhr.readyState === 4 && (xhr.status === 200 || (CC_TEST && xhr.status === 0)) ? cb(null, self._str2Uint8Array(xhr.responseText)) : cb(errInfo);
};
}
xhr.send(null);
};
cc.loader.loadBinary._IEFilter = (/msie/i.test(navigator.userAgent) && !/opera/i.test(navigator.userAgent) && window.IEBinaryToArray_ByteStr && window.IEBinaryToArray_ByteStr_Last);
cc.loader._str2Uint8Array = function (strData) {
if (!strData)
return null;
var arrData = new Uint8Array(strData.length);
for (var i = 0; i < strData.length; i++) {
arrData[i] = strData.charCodeAt(i) & 0xff;
}
return arrData;
};
/**
* Load binary data by url synchronously.
* @method loadBinarySync
* @param {String} url
* @return {Uint8Array}
*/
cc.loader.loadBinarySync = function (url) {
var self = this;
var req = this.getXMLHttpRequest();
var errInfo = "load " + url + " failed!";
req.open('GET', url, false);
var arrayInfo = null;
if (cc.loader.loadBinary._IEFilter) {
req.setRequestHeader("Accept-Charset", "x-user-defined");
req.send(null);
if (req.status !== 200) {
cc.log(errInfo);
return null;
}
var fileContents = cc._convertResponseBodyToText(req["responseBody"]);
if (fileContents) {
arrayInfo = self._str2Uint8Array(fileContents);
}
} else {
if (req.overrideMimeType)
req.overrideMimeType('text\/plain; charset=x-user-defined');
req.send(null);
if (req.status !== 200) {
cc.log(errInfo);
return null;
}
arrayInfo = this._str2Uint8Array(req.responseText);
}
return arrayInfo;
};
//Compatibility with IE9
window.Uint8Array = window.Uint8Array || window.Array;
if (cc.loader.loadBinary._IEFilter) {
var IEBinaryToArray_ByteStr_Script =
"<!-- IEBinaryToArray_ByteStr -->\r\n" +
//"<script type='text/vbscript'>\r\n" +
"Function IEBinaryToArray_ByteStr(Binary)\r\n" +
" IEBinaryToArray_ByteStr = CStr(Binary)\r\n" +
"End Function\r\n" +
"Function IEBinaryToArray_ByteStr_Last(Binary)\r\n" +
" Dim lastIndex\r\n" +
" lastIndex = LenB(Binary)\r\n" +
" if lastIndex mod 2 Then\r\n" +
" IEBinaryToArray_ByteStr_Last = Chr( AscB( MidB( Binary, lastIndex, 1 ) ) )\r\n" +
" Else\r\n" +
" IEBinaryToArray_ByteStr_Last = " + '""' + "\r\n" +
" End If\r\n" +
"End Function\r\n";// +
//"</script>\r\n";
// inject VBScript
//document.write(IEBinaryToArray_ByteStr_Script);
var myVBScript = document.createElement('script');
myVBScript.type = "text/vbscript";
myVBScript.textContent = IEBinaryToArray_ByteStr_Script;
document.body.appendChild(myVBScript);
// helper to convert from responseBody to a "responseText" like thing
cc._convertResponseBodyToText = function (binary) {
var byteMapping = {};
for (var i = 0; i < 256; i++) {
for (var j = 0; j < 256; j++) {
byteMapping[ String.fromCharCode(i + j * 256) ] =
String.fromCharCode(i) + String.fromCharCode(j);
}
}
var rawBytes = IEBinaryToArray_ByteStr(binary);
var lastChr = IEBinaryToArray_ByteStr_Last(binary);
return rawBytes.replace(/[\s\S]/g,
function (match) {
return byteMapping[match];
}) + lastChr;
};
}
+11 -7
View File
@@ -1,11 +1,13 @@
require('../platform/CCSys');
var EXTNAME_RE = /(\.[^\.\/\?\\]*)(\?.*)?$/;
var NORMALIZE_RE = /[^\.\/]+\/\.\.\//;
/**
* @class path
* @static
*/
cc.path = /** @lends cc.path# */{
normalizeRE: /[^\.\/]+\/\.\.\//,
/**
* Join strings to be a path.
* @method join
@@ -22,15 +24,15 @@ cc.path = /** @lends cc.path# */{
},
/**
* Get the ext name of a path.
* Get the ext name of a path including '.', like '.png'.
* @method extname
* @example {@link utils/api/engine/docs/cocos2d/core/utils/CCPath/extname.js}
* @param {String} pathStr
* @returns {*}
*/
extname: function (pathStr) {
var temp = /(\.[^\.\/\?\\]*)(\?.*)?$/.exec(pathStr);
return temp ? temp[1] : null;
var temp = EXTNAME_RE.exec(pathStr);
return temp ? temp[1] : '';
},
/**
@@ -128,7 +130,7 @@ cc.path = /** @lends cc.path# */{
//removing all ../
do {
oldUrl = url;
url = url.replace(this.normalizeRE, "");
url = url.replace(NORMALIZE_RE, "");
} while(oldUrl.length !== url.length);
return url;
},
@@ -159,4 +161,6 @@ cc.path = /** @lends cc.path# */{
}
return path;
}
};
};
module.exports = cc.path;
+107 -83
View File
@@ -48,6 +48,7 @@ var COLOR_CHANGED = 'color-changed';
var OPACITY_CHANGED = 'opacity-changed';
var CHILD_ADDED = 'child-added';
var CHILD_REMOVED = 'child-removed';
var CHILD_REORDER = 'child-reorder';
var ERR_INVALID_NUMBER = CC_EDITOR && 'The %s is invalid';
@@ -89,7 +90,6 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
_skewY: 0,
_localZOrder: 0,
_globalZOrder: 0,
_ignoreAnchorPointForPosition: false,
_tag: cc.NODE_TAG_INVALID,
_opacityModifyRGB: false,
@@ -123,6 +123,11 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
if (this._parent === value) {
return;
}
if (CC_EDITOR && !cc.engine.isPlaying) {
if (_Scene.DetectConflict.beforeAddChild(this)) {
return;
}
}
var node = this._sgNode;
if (node.parent) {
node.parent.removeChild(node, false);
@@ -144,12 +149,8 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
return cc.error('Internal error, should not remove unknown node from parent.');
}
oldParent._children.splice(removeAt, 1);
oldParent.emit(CHILD_REMOVED, removeAt);
oldParent.emit(CHILD_REMOVED, this);
this._onHierarchyChanged(oldParent);
if (CC_EDITOR) {
_Scene.DetectConflict.afterAddChild(this);
}
}
}
else if (value) {
@@ -177,7 +178,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
*/
uuid: {
get: function () {
return this._id || (this._id = window.Editor ? Editor.uuid() : '');
return this._id || (this._id = window.Editor ? Editor.UuidUtils.uuid() : '');
}
},
@@ -507,16 +508,17 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
/**
* Indicate whether ignore the anchor point property for positioning.
* @property ignoreAnchor
* @property _ignoreAnchor
* @type {Boolean}
* @private
*/
ignoreAnchor: {
_ignoreAnchor: {
get: function () {
return this._ignoreAnchorPointForPosition;
return this.__ignoreAnchor;
},
set: function (value) {
if (this._ignoreAnchorPointForPosition !== value) {
this._ignoreAnchorPointForPosition = value;
if (this.__ignoreAnchor !== value) {
this.__ignoreAnchor = value;
this._sgNode.ignoreAnchor = value;
this._onAnchorChanged();
this.emit(ANCHOR_CHANGED, this._anchorPoint);
@@ -640,6 +642,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
// _ccsg.Node
this._sizeProvider = null;
this.__ignoreAnchor = false;
},
_onPreDestroy: function () {
@@ -928,7 +931,11 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
* @return {Rect} The calculated bounding box of the node
*/
getBoundingBox: function () {
var rect = cc.rect(0, 0, this._contentSize.width, this._contentSize.height);
var size = this.getContentSize();
var rect = cc.rect( - this._anchorPoint.x * size.width,
- this._anchorPoint.y * size.height,
size.width,
size.height );
return cc._rectApplyAffineTransformIn(rect, this.getNodeToParentTransform());
},
@@ -1136,8 +1143,6 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
child.cleanup();
child.parent = null;
cc.js.array.remove(this._children, child);
this.emit(CHILD_REMOVED, child);
},
setNodeDirty: function(){
@@ -1161,7 +1166,19 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
* @return {AffineTransform}
*/
getNodeToWorldTransform: function () {
return this._sgNode.getNodeToWorldTransform();
var computedSize = this._sgNode.getContentSize();
var expectedSize = this.getContentSize();
var mat = this._sgNode.getNodeToWorldTransform();
var anchorPointIgnored = (computedSize.width === 0 && computedSize.height === 0 &&
(expectedSize.width !== 0 || expectedSize.height !== 0));
if (anchorPointIgnored || this._sgNode.isIgnoreAnchorPointForPosition()) {
// compute anchor, see https://github.com/cocos-creator/engine/pull/391
var tx = - expectedSize.width * this._anchorPoint.x;
var ty = - expectedSize.height * this._anchorPoint.y;
var offset = cc.affineTransformMake(1, 0, 0, 1, tx, ty);
mat = cc.affineTransformConcatIn(offset, mat);
}
return mat;
},
/**
@@ -1203,7 +1220,13 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
* @return {Vec2}
*/
convertToNodeSpaceAR: function (worldPoint) {
return this._sgNode.convertToNodeSpaceAR(worldPoint);
if (this._sgNode.isIgnoreAnchorPointForPosition()) {
// see https://github.com/cocos-creator/engine/pull/391
return cc.v2(this._sgNode.convertToNodeSpace(worldPoint));
}
else {
return this._sgNode.convertToNodeSpaceAR(worldPoint);
}
},
/**
@@ -1214,7 +1237,13 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
* @return {Vec2}
*/
convertToWorldSpaceAR: function (nodePoint) {
return cc.v2(this._sgNode.convertToWorldSpaceAR(nodePoint));
if (this._sgNode.isIgnoreAnchorPointForPosition()) {
// see https://github.com/cocos-creator/engine/pull/391
return cc.v2(this._sgNode.convertToWorldSpace(nodePoint));
}
else {
return cc.v2(this._sgNode.convertToWorldSpaceAR(nodePoint));
}
},
// _convertToWindowSpace: function (nodePoint) {
@@ -1252,12 +1281,42 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
},
/**
* Returns a "world" axis aligned bounding box of the node.
* Returns a "world" axis aligned bounding box of the node.<br/>
* The bounding box contains self and active children's world bounding box.
* @method getBoundingBoxToWorld
* @return {Rect}
*/
getBoundingBoxToWorld: function () {
return this._sgNode.getBoundingBoxToWorld();
var trans;
if (this.parent) {
trans = this.parent.getNodeToWorldTransform();
}
return this._getBoundingBoxTo(trans);
},
_getBoundingBoxTo: function (parentTransform) {
var size = this.getContentSize();
var width = size.width;
var height = size.height;
var rect = cc.rect(0, 0, width, height);
var trans = (parentTransform === undefined) ? this.getNodeToParentTransform() : cc.affineTransformConcat(this.getNodeToParentTransform(), parentTransform);
cc._rectApplyAffineTransformIn(rect, trans);
//query child's BoundingBox
if (!this._children)
return rect;
var locChildren = this._children;
for (var i = 0; i < locChildren.length; i++) {
var child = locChildren[i];
if (child && child.active) {
var childRect = child._getBoundingBoxTo(trans);
if (childRect)
rect = cc.rectUnion(rect, childRect);
}
}
return rect;
},
/**
@@ -1270,9 +1329,9 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
return this._sgNode.getDisplayedOpacity();
},
/**
/*
* Update displayed opacity
* @method
* @method _updateDisplayedOpacity
* @param {Number} parentOpacity
*/
_updateDisplayedOpacity: function (parentOpacity) {
@@ -1360,6 +1419,7 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
if (cc.renderer) {
cc.renderer.childrenOrderDirty = this._parent._sgNode._reorderChildDirty = true;
}
this._parent.emit(CHILD_REORDER);
}
},
@@ -1382,25 +1442,40 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
return false;
},
// The deserializer for sgNode which will be called before components onLoad
_onBatchCreated: function () {
_updateDummySgNode: function () {
var sgNode = this._sgNode;
sgNode.setOpacity(this._opacity);
sgNode.setCascadeOpacityEnabled(this._cascadeOpacityEnabled);
sgNode.setPosition(this._position);
sgNode.setRotationX(this._rotationX);
sgNode.setRotationY(this._rotationY);
sgNode.setScale(this._scaleX, this._scaleY);
sgNode.setPosition(this._position);
sgNode.setSkewX(this._skewX);
sgNode.setSkewY(this._skewY);
sgNode.ignoreAnchorPointForPosition(this.__ignoreAnchor);
sgNode.setLocalZOrder(this._localZOrder);
sgNode.setGlobalZOrder(this._globalZOrder);
sgNode.ignoreAnchorPointForPosition(this._ignoreAnchorPointForPosition);
sgNode.setTag(this._tag);
sgNode.setOpacity(this._opacity);
sgNode.setOpacityModifyRGB(this._opacityModifyRGB);
sgNode.setCascadeOpacityEnabled(this._cascadeOpacityEnabled);
sgNode.setTag(this._tag);
},
_updateSgNode: function () {
this._updateDummySgNode();
var sgNode = this._sgNode;
sgNode.setAnchorPoint(this._anchorPoint);
sgNode.setVisible(this._active);
sgNode.setColor(this._color);
},
// The deserializer for sgNode which will be called before components onLoad
_onBatchCreated: function () {
this._updateDummySgNode();
if (this._parent) {
this._parent._sgNode.addChild(sgNode);
this._parent._sgNode.addChild(this._sgNode);
}
var children = this._children;
@@ -1410,56 +1485,6 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
},
_removeSgNode: SceneGraphHelper.removeSgNode,
_replaceSgNode: function(sgNode) {
if(sgNode instanceof _ccsg.Node) {
var oldSgNode = this._sgNode;
//apply property
sgNode.setPosition(this._position);
sgNode.setRotationX(this._rotationX);
sgNode.setRotationY(this._rotationY);
sgNode.setScale(this._scaleX, this._scaleY);
sgNode.setSkewX(this._skewX);
sgNode.setSkewY(this._skewY);
sgNode.setLocalZOrder(this._localZOrder);
sgNode.setGlobalZOrder(this._globalZOrder);
sgNode.setOpacity(this._opacity);
sgNode.setCascadeOpacityEnabled(this._cascadeOpacityEnabled);
sgNode.ignoreAnchorPointForPosition(this._ignoreAnchorPointForPosition);
sgNode.setTag(this._tag);
sgNode.setColor(this._color);
sgNode.setOpacityModifyRGB(this._opacityModifyRGB);
//rebuild scenegraph
var children = oldSgNode.getChildren().slice(0);
oldSgNode.removeAllChildren();
for(var index = 0; index < children.length; ++index) {
sgNode.addChild(children[index]);
}
var parentNode = oldSgNode.getParent();
parentNode.removeChild(oldSgNode);
// insert node
parentNode.addChild(sgNode);
sgNode.arrivalOrder = oldSgNode.arrivalOrder;
if (cc.renderer) {
cc.renderer.childrenOrderDirty = this._parent._sgNode._reorderChildDirty = true;
}
this._sgNode = sgNode;
if (cc.sys.isNative) {
oldSgNode.release();
sgNode.retain();
}
} else {
throw new Error("Invalid sgNode. It must an instance of _ccsg.Node");
}
},
});
@@ -1475,7 +1500,6 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
y: ['getPositionY', 'setPositionY'],
zIndex: ['getLocalZOrder', 'setLocalZOrder'],
//running: ['isRunning'],
ignoreAnchor: ['isIgnoreAnchorPointForPosition', 'ignoreAnchorPointForPosition'],
opacityModifyRGB: ['isOpacityModifyRGB'],
cascadeOpacity: ['isCascadeOpacityEnabled', 'setCascadeOpacityEnabled'],
cascadeColor: ['isCascadeColorEnabled', 'setCascadeColorEnabled'],
@@ -1524,13 +1548,13 @@ var BaseNode = cc.Class(/** @lends cc.Node# */{
*/
/**
* <p>Sets the x axis position of the node in cocos2d coordinates.</p>
* <p>Returns the x axis position of the node in cocos2d coordinates.</p>
* @method getPositionX
* @param {Number} x - The new position in x axis
*/
/**
* <p>Returns the x axis position of the node in cocos2d coordinates.</p>
* <p>Sets the x axis position of the node in cocos2d coordinates.</p>
* @method setPositionX
* @return {Number}
*/
@@ -260,9 +260,9 @@ cc.affineTransformConcat = function (t1, t2) {
* The results are reflected in the first matrix.<br/>
* t' = t1 * t2
* @method affineTransformConcatIn
* @param {cc.AffineTransform} t1 - The first transform object.
* @param {cc.AffineTransform} t2 - The transform object to concatenate.
* @return {cc.AffineTransform} The result of concatenation.
* @param {AffineTransform} t1 - The first transform object.
* @param {AffineTransform} t2 - The transform object to concatenate.
* @return {AffineTransform} The result of concatenation.
*/
cc.affineTransformConcatIn = function (t1, t2) {
var a = t1.a, b = t1.b, c = t1.c, d = t1.d, tx = t1.tx, ty = t1.ty;
+5 -5
View File
@@ -6,17 +6,17 @@ var Color = (function () {
/**
* Representation of RGBA colors.
*
* Each color component is a floating point value with a range from 0 to 1.
* Each color component is a floating point value with a range from 0 to 255.
*
* You can also use the convenience method <% crosslink cc.Color cc.Color %> to create a new Color.
*
* @class Color
* @extends ValueType
* @constructor
* @param {Number} [r=0] - red component of the color.
* @param {Number} [g=0] - green component of the color.
* @param {Number} [b=0] - blue component of the color.
* @param {Number} [a=255] - alpha component of the color.
* @param {Number} [r=0] - red component of the color, default value is 0.
* @param {Number} [g=0] - green component of the color, defualt value is 0.
* @param {Number} [b=0] - blue component of the color, default value is 0.
* @param {Number} [a=255] - alpha component of the color, default value is 255.
*/
function Color( r, g, b, a ) {
if (typeof r === 'object') {
+3 -3
View File
@@ -467,7 +467,7 @@ cc.v2 = function v2 (x, y) {
* @method p
* @param {Number|Object} [x=0] a Number or a size object
* @param {Number} [y=0]
* @return {cc.Vec2}
* @return {Vec2}
* @example
* var point1 = cc.p();
* var point2 = cc.p(100, 100);
@@ -482,8 +482,8 @@ cc.p = cc.v2;
/**
* Check whether a point's value equals to another
* @method pointEqualToPoint
* @param {cc.Vec2} point1
* @param {cc.Vec2} point2
* @param {Vec2} point1
* @param {Vec2} point2
* @return {Boolean}
*/
cc.pointEqualToPoint = function (point1, point2) {
+50 -30
View File
@@ -133,7 +133,8 @@ if (CC_DEV) {
js.obsoletes(cc, 'cc', {
'Point': 'Vec2',
'EScene': 'Scene',
'ENode': 'Node'
'ENode': 'Node',
'_ComponentInSG': '_RendererUnderSG'
});
/**
@@ -203,9 +204,7 @@ if (CC_DEV) {
return cc.js.array.copy;
});
Object.defineProperty(cc._ComponentInSG.prototype, 'visible', {
Object.defineProperty(cc._SGComponent.prototype, 'visible', {
get: function () {
cc.warn('The "visible" property of %s is deprecated, use "enabled" instead please.', cc.js.getClassName(this));
return this.enabled;
@@ -265,7 +264,7 @@ if (CC_DEV) {
function provideClearError (owner, obj) {
var className = cc.js.getClassName(owner);
var Info = 'Sorry,' + className + '.%s is removed, please use %s instead.';
var Info = 'Sorry, ' + className + '.%s is removed, please use %s instead.';
for (var prop in obj) {
function define (prop, getset) {
function accessor (newProp) {
@@ -298,26 +297,6 @@ if (CC_DEV) {
}
}
function shouldNotUseNodeProp (component) {
var compName = cc.js.getClassName(component);
var Info = 'Sorry, ' + compName + '.%s is removed, please use cc.Node.%s instead.';
var compProto = component.prototype;
for (var prop in cc.Node.prototype) {
(function (prop) {
if (!(prop in compProto) && prop[0] !== '_') {
js.getset(compProto, prop,
function () {
cc.error(Info, prop, prop);
},
function () {
cc.error(Info, prop, prop);
}
);
}
})(prop);
}
}
// cc.Node
markAsRemoved(cc.Node, [
@@ -384,7 +363,10 @@ if (CC_DEV) {
'userData',
'userObject',
'_cascadeColorEnabled',
'cascadeColor'
'cascadeColor',
'ignoreAnchor',
'isIgnoreAnchorPointForPosition',
'ignoreAnchorPointForPosition'
]);
provideClearError(cc.Node.prototype, {
arrivalOrder: 'getSiblingIndex, setSiblingIndex',
@@ -407,8 +389,31 @@ if (CC_DEV) {
removeAllComponents: 'removeComponent',
getNodeToParentAffineTransform: 'getNodeToParentTransform',
});
// RENDERERS
// cc.SpriteRenderer
function shouldNotUseNodeProp (component) {
var compProto = component.prototype;
for (var prop in cc.Node.prototype) {
(function (prop) {
if (!(prop in compProto) && prop[0] !== '_') {
Object.defineProperty(compProto, prop, {
get: function () {
var compName = cc.js.getClassName(this); // 允许继承
var Info = 'Sorry, ' + compName + '.%s is undefined, please use cc.Node.%s instead.';
cc.error(Info, prop, prop);
},
enumerable: false,
configurable: true, // 允许继承
});
}
})(prop);
}
}
shouldNotUseNodeProp(cc._SGComponent);
// cc.Sprite
markAsRemoved(cc.Sprite, [
'textureLoaded',
@@ -433,14 +438,12 @@ if (CC_DEV) {
createWithSpriteFrame: 'node.addComponent',
});
provideClearError(cc.Sprite.prototype, {
ignoreAnchorPointForPosition: 'instance.ignoreAnchor',
getPreferredSize: 'node.getContentSize',
setPreferredSize: 'node.setContentSize',
updateWithSprite: 'spriteFrame',
getSpriteFrame: 'spriteFrame',
setSpriteFrame: 'spriteFrame',
});
shouldNotUseNodeProp(cc.Sprite);
// Particle
markAsRemoved(cc.ParticleSystem, [
@@ -490,7 +493,6 @@ if (CC_DEV) {
'*etTotalParticles': 'totalParticles',
'*etTexture': 'texture',
});
shouldNotUseNodeProp(cc.ParticleSystem);
js.obsoletes(cc.ParticleSystem, 'cc.ParticleSystem', {
Type: 'PositionType',
Mode: 'EmitterMode'
@@ -540,4 +542,22 @@ if (CC_DEV) {
'setFlippedY',
'isFlippedY'
]);
// SPINE
if (typeof sp !== 'undefined') {
deprecateEnum(sp, 'sp.ANIMATION_EVENT_TYPE', 'sp.AnimationEventType');
js.obsolete(sp, 'SkeletonAnimation', 'Skeleton');
provideClearError(sp.Skeleton, {
create: 'node.addComponent',
});
provideClearError(sp.Skeleton.prototype, {
'*etDebugSlotsEnabled': 'debugSlots',
'*etDebugBonesEnabled': 'debugBones',
'setDebugSolots': 'debugSlots',
'setDebugBones': 'debugBones',
'*etTimeScale': 'timeScale',
});
}
}
+2 -3
View File
@@ -124,9 +124,8 @@ cc.LabelAtlas = cc.AtlasNode.extend(/** @lends cc.LabelAtlas# */{
}
textureFilename = cc.path.changeBasename(charMapFile, dict["textureFilename"]);
var locScaleFactor = cc.contentScaleFactor();
width = parseInt(dict["itemWidth"], 10) / locScaleFactor;
height = parseInt(dict["itemHeight"], 10) / locScaleFactor;
width = parseInt(dict["itemWidth"], 10);
height = parseInt(dict["itemHeight"], 10);
startChar = String.fromCharCode(parseInt(dict["firstChar"], 10));
} else {
textureFilename = charMapFile;
@@ -42,7 +42,7 @@
var locString = node._string || "";
var n = locString.length;
var texture = this._textureToRender;
var locItemWidth = node._itemWidth , locItemHeight = node._itemHeight; //needn't multiply cc.contentScaleFactor(), because sprite's draw will do this
var locItemWidth = node._itemWidth , locItemHeight = node._itemHeight;
for (var i = 0, cr = -1; i < n; i++) {
var a = locString.charCodeAt(i) - node._mapStartChar.charCodeAt(0);
+10 -14
View File
@@ -62,12 +62,8 @@
var texture = locTextureAtlas.texture;
var textureWide = texture.getPixelWidth();
var textureHigh = texture.getPixelHeight();
var itemWidthInPixels = node._itemWidth;
var itemHeightInPixels = node._itemHeight;
if (!node._ignoreContentScaleFactor) {
itemWidthInPixels = node._itemWidth * cc.contentScaleFactor();
itemHeightInPixels = node._itemHeight * cc.contentScaleFactor();
}
var itemWidth = node._itemWidth;
var itemHeight = node._itemHeight;
if (n > locTextureAtlas.getCapacity())
cc.log("cc.LabelAtlas._updateAtlasValues(): Invalid String length");
var quads = locTextureAtlas.quads;
@@ -88,15 +84,15 @@
var left, right, top, bottom;
if (cc.FIX_ARTIFACTS_BY_STRECHING_TEXEL) {
// Issue #938. Don't use texStepX & texStepY
left = (2 * row * itemWidthInPixels + 1) / (2 * textureWide);
right = left + (itemWidthInPixels * 2 - 2) / (2 * textureWide);
top = (2 * col * itemHeightInPixels + 1) / (2 * textureHigh);
bottom = top + (itemHeightInPixels * 2 - 2) / (2 * textureHigh);
left = (2 * row * itemWidth + 1) / (2 * textureWide);
right = left + (itemWidth * 2 - 2) / (2 * textureWide);
top = (2 * col * itemHeight + 1) / (2 * textureHigh);
bottom = top + (itemHeight * 2 - 2) / (2 * textureHigh);
} else {
left = row * itemWidthInPixels / textureWide;
right = left + itemWidthInPixels / textureWide;
top = col * itemHeightInPixels / textureHigh;
bottom = top + itemHeightInPixels / textureHigh;
left = row * itemWidth / textureWide;
right = left + itemWidth / textureWide;
top = col * itemHeight / textureHigh;
bottom = top + itemHeight / textureHigh;
}
var quad = quads[i];
var locQuadTL = quad.tl, locQuadTR = quad.tr, locQuadBL = quad.bl, locQuadBR = quad.br;
+3 -108
View File
@@ -345,7 +345,6 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
}
var rect = cc.rect(fontDef.rect.x, fontDef.rect.y, fontDef.rect.width, fontDef.rect.height);
rect = cc.rectPixelsToPoints(rect);
rect.x += self._imageOffset.x;
rect.y += self._imageOffset.y;
@@ -366,8 +365,8 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
var yOffset = locCfg.commonHeight - fontDef.yOffset;
var fontPos = cc.p(nextFontPositionX + fontDef.xOffset + fontDef.rect.width * 0.5 + kerningAmount,
nextFontPositionY + yOffset - rect.height * 0.5 * cc.contentScaleFactor());
fontChar.setPosition(cc.pointPixelsToPoints(fontPos));
nextFontPositionY + yOffset - rect.height * 0.5);
fontChar.setPosition(fontPos);
// update kerning
nextFontPositionX += fontDef.xAdvance + kerningAmount;
@@ -384,7 +383,7 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
else
tmpSize.width = longestLine;
tmpSize.height = totalHeight;
self.setContentSize(cc.sizePixelsToPoints(tmpSize));
self.setContentSize(tmpSize);
},
/**
@@ -867,107 +866,3 @@ cc.LabelBMFont = cc.SpriteBatchNode.extend(/** @lends cc.LabelBMFont# */{
cc.LabelBMFont.create = function (str, fntFile, width, alignment, imageOffset) {
return new cc.LabelBMFont(str, fntFile, width, alignment, imageOffset);
};
cc._fntLoader = {
INFO_EXP: /info [^\n]*(\n|$)/gi,
COMMON_EXP: /common [^\n]*(\n|$)/gi,
PAGE_EXP: /page [^\n]*(\n|$)/gi,
CHAR_EXP: /char [^\n]*(\n|$)/gi,
KERNING_EXP: /kerning [^\n]*(\n|$)/gi,
ITEM_EXP: /\w+=[^ \r\n]+/gi,
INT_EXP: /^[\-]?\d+$/,
_parseStrToObj: function (str) {
var arr = str.match(this.ITEM_EXP);
var obj = {};
if (arr) {
for (var i = 0, li = arr.length; i < li; i++) {
var tempStr = arr[i];
var index = tempStr.indexOf("=");
var key = tempStr.substring(0, index);
var value = tempStr.substring(index + 1);
if (value.match(this.INT_EXP)) value = parseInt(value);
else if (value[0] === '"') value = value.substring(1, value.length - 1);
obj[key] = value;
}
}
return obj;
},
/**
* Parse Fnt string.
* @param fntStr
* @param url
* @returns {{}}
*/
parseFnt: function (fntStr, url) {
var self = this, fnt = {};
//padding
var infoObj = self._parseStrToObj(fntStr.match(self.INFO_EXP)[0]);
var paddingArr = infoObj["padding"].split(",");
var padding = {
left: parseInt(paddingArr[0]),
top: parseInt(paddingArr[1]),
right: parseInt(paddingArr[2]),
bottom: parseInt(paddingArr[3])
};
//common
var commonObj = self._parseStrToObj(fntStr.match(self.COMMON_EXP)[0]);
fnt.commonHeight = commonObj["lineHeight"];
//font size
fnt.fontSize = infoObj["size"];
if (cc._renderType === cc.game.RENDER_TYPE_WEBGL) {
var texSize = cc.configuration.getMaxTextureSize();
if (commonObj["scaleW"] > texSize.width || commonObj["scaleH"] > texSize.height)
cc.log("cc.LabelBMFont._parseCommonArguments(): page can't be larger than supported");
}
if (commonObj["pages"] !== 1) cc.log("cc.LabelBMFont._parseCommonArguments(): only supports 1 page");
//page
var pageObj = self._parseStrToObj(fntStr.match(self.PAGE_EXP)[0]);
if (pageObj["id"] !== 0) cc.log("cc.LabelBMFont._parseImageFileName() : file could not be found");
fnt.atlasName = cc.path.changeBasename(url, pageObj["file"]);
//char
var charLines = fntStr.match(self.CHAR_EXP);
var fontDefDictionary = fnt.fontDefDictionary = {};
for (var i = 0, li = charLines.length; i < li; i++) {
var charObj = self._parseStrToObj(charLines[i]);
var charId = charObj["id"];
fontDefDictionary[charId] = {
rect: {x: charObj["x"], y: charObj["y"], width: charObj["width"], height: charObj["height"]},
xOffset: charObj["xoffset"],
yOffset: charObj["yoffset"],
xAdvance: charObj["xadvance"]
};
}
//kerning
var kerningDict = fnt.kerningDict = {};
var kerningLines = fntStr.match(self.KERNING_EXP);
if (kerningLines) {
for (var i = 0, li = kerningLines.length; i < li; i++) {
var kerningObj = self._parseStrToObj(kerningLines[i]);
kerningDict[(kerningObj["first"] << 16) | (kerningObj["second"] & 0xffff)] = kerningObj["amount"];
}
}
return fnt;
},
/**
* load the fnt
* @param realUrl
* @param url
* @param res
* @param cb
*/
load: function (realUrl, url, res, cb) {
var self = this;
cc.loader.loadTxt(realUrl, function (err, txt) {
if (err) return cb(err);
cb(null, self.parseFnt(txt, url));
});
}
};
cc.loader.register(["fnt"], cc._fntLoader);
+70 -59
View File
@@ -64,6 +64,10 @@ var PositionType = cc.Enum({
GROUPED: 2
});
/**
* @class ParticleSystem
*/
var properties = {
/**
@@ -133,10 +137,10 @@ var properties = {
this._file = value;
if (value) {
this._applyFile();
cc.engine.repaintInEditMode();
//if (CC_EDITOR) {
// self.preview = self.preview;
//}
if (CC_EDITOR) {
cc.engine.repaintInEditMode();
//self.preview = self.preview;
}
}
else {
this.custom = true;
@@ -219,9 +223,6 @@ var properties = {
}
};
/**
* @class ParticleSystem
*/
var CustomProps = (function () {
var DefaultValues = {
/**
@@ -479,48 +480,51 @@ properties.positionType.type = PositionType;
properties.emitterMode.type = EmitterMode;
/**
* <p>
* Particle System base class. <br/>
* Attributes of a Particle System:<br/>
* - emmision rate of the particles<br/>
* - Gravity Mode (Mode A): <br/>
* - gravity <br/>
* - direction <br/>
* - speed +- variance <br/>
* - tangential acceleration +- variance<br/>
* - radial acceleration +- variance<br/>
* - Radius Mode (Mode B): <br/>
* - startRadius +- variance <br/>
* - endRadius +- variance <br/>
* - rotate +- variance <br/>
* - Properties common to all modes: <br/>
* - life +- life variance <br/>
* - start spin +- variance <br/>
* - end spin +- variance <br/>
* - start size +- variance <br/>
* - end size +- variance <br/>
* - start color +- variance <br/>
* - end color +- variance <br/>
* - life +- variance <br/>
* - blending function <br/>
* - texture <br/>
* <br/>
* cocos2d also supports particles generated by Particle Designer (http://particledesigner.71squared.com/).<br/>
* 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d, <br/>
* cocos2d uses a another approach, but the results are almost identical.<br/>
* cocos2d supports all the variables used by Particle Designer plus a bit more: <br/>
* - spinning particles (supported when using ParticleSystem) <br/>
* - tangential acceleration (Gravity mode) <br/>
* - radial acceleration (Gravity mode) <br/>
* - radius direction (Radius mode) (Particle Designer supports outwards to inwards direction only) <br/>
* It is possible to customize any of the above mentioned properties in runtime. Example: <br/>
* </p>
* Particle System base class. <br/>
* Attributes of a Particle System:<br/>
* - emmision rate of the particles<br/>
* - Gravity Mode (Mode A): <br/>
* - gravity <br/>
* - direction <br/>
* - speed +- variance <br/>
* - tangential acceleration +- variance<br/>
* - radial acceleration +- variance<br/>
* - Radius Mode (Mode B): <br/>
* - startRadius +- variance <br/>
* - endRadius +- variance <br/>
* - rotate +- variance <br/>
* - Properties common to all modes: <br/>
* - life +- life variance <br/>
* - start spin +- variance <br/>
* - end spin +- variance <br/>
* - start size +- variance <br/>
* - end size +- variance <br/>
* - start color +- variance <br/>
* - end color +- variance <br/>
* - life +- variance <br/>
* - blending function <br/>
* - texture <br/>
* <br/>
* cocos2d also supports particles generated by Particle Designer (http://particledesigner.71squared.com/).<br/>
* 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d, <br/>
* cocos2d uses a another approach, but the results are almost identical.<br/>
* cocos2d supports all the variables used by Particle Designer plus a bit more: <br/>
* - spinning particles (supported when using ParticleSystem) <br/>
* - tangential acceleration (Gravity mode) <br/>
* - radial acceleration (Gravity mode) <br/>
* - radius direction (Radius mode) (Particle Designer supports outwards to inwards direction only) <br/>
* It is possible to customize any of the above mentioned properties in runtime. Example: <br/>
*
* @example
* emitter.radialAccel = 15;
* emitter.startSpin = 0;
*
* @class ParticleSystem
* @extends cc._ComponentInSG
* @extends cc._RendererUnderSG
*/
var ParticleSystem = cc.Class({
name: 'cc.ParticleSystem',
extends: cc._ComponentInSG,
extends: cc._RendererUnderSG,
editor: CC_EDITOR && {
menu: 'i18n:MAIN_MENU.component.renderers/ParticleSystem',
inspector: 'app://editor/page/inspector/particle-system/index.html',
@@ -569,6 +573,7 @@ var ParticleSystem = cc.Class({
},
// LIFE-CYCLE METHODS
onLoad: function () {
this._super();
// auto play
@@ -579,12 +584,7 @@ var ParticleSystem = cc.Class({
this._applyAutoRemove();
}
},
//onEnable: function () {
// this._super();
//},
//onDisable: function () {
// this._super();
//},
onDestroy: function () {
if (this._autoRemoveOnFinish) {
this.autoRemoveOnFinish = false; // already removed
@@ -723,26 +723,37 @@ var ParticleSystem = cc.Class({
var file = this._file;
if (file) {
var self = this;
cc.loader.load(file, function (err, results) {
if (err) throw err;
cc.loader.load(file, function (err, content) {
if (err || !content) {
throw err || new Error('Unkown error');
}
sgNode.particleCount = 0;
var active = sgNode.isActive();
sgNode.initWithFile(file);
// To avoid it export custom particle data textureImageData too large,
// so use the texutreUuid instead of textureImageData
if (content.textureUuid) {
cc.AssetLibrary.queryAssetInfo(content.textureUuid, function (err, url, raw) {
self.texture = url;
});
}
// For custom data export
if (content.emissionRate) {
self.emissionRate = content.emissionRate;
}
// recover sgNode properties
sgNode.setPosition(0, 0);
if (!active) {
sgNode.stopSystem();
}
var sourcePos = sgNode.getPosition();
if (CC_EDITOR && (sourcePos.x !== 0 || sourcePos.y !== 0)) {
cc.log('Discard sourcePosition: %s from "%s", you can set position in the node directly.', sourcePos, cc.path.basename(file));
}
sgNode.setPosition(0, 0);
if (!CC_EDITOR || cc.engine.isPlaying) {
self._applyAutoRemove();
}

Some files were not shown because too many files have changed in this diff Show More