diff --git a/cocos/2d/base-ui/CCWidgetManager.js b/cocos/2d/base-ui/CCWidgetManager.js
index 5bbf5785f8..99794d5376 100644
--- a/cocos/2d/base-ui/CCWidgetManager.js
+++ b/cocos/2d/base-ui/CCWidgetManager.js
@@ -24,14 +24,16 @@
THE SOFTWARE.
****************************************************************************/
-var Event = require('../CCNode').EventType;
+// var Event = require('../CCNode').EventType;
+import { Node } from '../../scene-graph/index'
-var TOP = 1 << 0;
-var MID = 1 << 1; // vertical center
-var BOT = 1 << 2;
-var LEFT = 1 << 3;
-var CENTER = 1 << 4; // horizontal center
-var RIGHT = 1 << 5;
+var Event = Node.EventType;
+var TOP = 1 << 0;
+var MID = 1 << 1; // vertical center
+var BOT = 1 << 2;
+var LEFT = 1 << 3;
+var CENTER = 1 << 4; // horizontal center
+var RIGHT = 1 << 5;
var HORIZONTAL = LEFT | CENTER | RIGHT;
var VERTICAL = TOP | MID | BOT;
@@ -42,7 +44,7 @@ var AlignMode = cc.Enum({
});
// returns a readonly size of the node
-function getReadonlyNodeSize (parent) {
+function getReadonlyNodeSize(parent) {
if (parent instanceof cc.Scene) {
return CC_EDITOR ? cc.engine.getDesignResolutionSize() : cc.visibleRect;
}
@@ -51,12 +53,12 @@ function getReadonlyNodeSize (parent) {
}
}
-function computeInverseTransForTarget (widgetNode, target, out_inverseTranslate, out_inverseScale) {
+function computeInverseTransForTarget(widgetNode, target, out_inverseTranslate, out_inverseScale) {
var scaleX = widgetNode._parent._scale.x;
var scaleY = widgetNode._parent._scale.y;
var translateX = 0;
var translateY = 0;
- for (var node = widgetNode._parent;;) {
+ for (var node = widgetNode._parent; ;) {
var pos = node._position;
translateX += pos.x;
translateY += pos.y;
@@ -89,7 +91,7 @@ var tInverseTranslate = cc.Vec2.ZERO;
var tInverseScale = cc.Vec2.ONE;
// align to borders by adjusting node's position and size (ignore rotation)
-function align (node, widget) {
+function align(node, widget) {
var hasTarget = widget._target;
var target;
var inverseTranslate, inverseScale;
@@ -225,7 +227,7 @@ function align (node, widget) {
node.setPosition(x, y);
}
-function visitNode (node) {
+function visitNode(node) {
var widget = node._widget;
if (widget) {
if (CC_DEV) {
@@ -263,7 +265,7 @@ if (CC_EDITOR) {
};
}
-function refreshScene () {
+function refreshScene() {
// check animation editor
if (CC_EDITOR && !Editor.isBuilder) {
var AnimUtils = Editor.require('scene://utils/animation');
@@ -433,19 +435,19 @@ var adjustWidgetToAllowResizingInEditor = CC_EDITOR && function (oldSize) {
var activeWidgets = [];
// updateAlignment from scene to node recursively
-function updateAlignment (node) {
+function updateAlignment(node) {
var parent = node._parent;
if (cc.Node.isNode(parent)) {
updateAlignment(parent);
}
var widget = node._widget ||
- node.getComponent(cc.Widget); // node._widget will be null when widget is disabled
+ node.getComponent(cc.Widget); // node._widget will be null when widget is disabled
if (widget) {
align(node, widget);
}
}
-var widgetManager = cc._widgetManager = module.exports = {
+let WidgetManager = cc._widgetManager = {
_AlignFlags: {
TOP: TOP,
MID: MID, // vertical center
@@ -489,13 +491,13 @@ var widgetManager = cc._widgetManager = module.exports = {
widget.node.off(Event.SIZE_CHANGED, adjustWidgetToAllowResizingInEditor, widget);
}
},
- onResized () {
+ onResized() {
var scene = cc.director.getScene();
if (scene) {
this.refreshWidgetOnResized(scene);
}
},
- refreshWidgetOnResized (node) {
+ refreshWidgetOnResized(node) {
var widget = cc.Node.isNode(node) && node.getComponent(cc.Widget);
if (widget) {
if (widget.alignMode === AlignMode.ON_WINDOW_RESIZE) {
@@ -513,6 +515,8 @@ var widgetManager = cc._widgetManager = module.exports = {
AlignMode: AlignMode,
};
+export default WidgetManager;
+
if (CC_EDITOR) {
module.exports._computeInverseTransForTarget = computeInverseTransForTarget;
module.exports._getReadonlyNodeSize = getReadonlyNodeSize;
diff --git a/cocos/2d/label/CCLabel.js b/cocos/2d/label/CCLabel.js
deleted file mode 100644
index 8102cab888..0000000000
--- a/cocos/2d/label/CCLabel.js
+++ /dev/null
@@ -1,620 +0,0 @@
-/****************************************************************************
- Copyright (c) 2013-2016 Chukong Technologies Inc.
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos.com
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
-
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-const macro = require('../platform/CCMacro');
-const RenderComponent = require('./CCRenderComponent');
-const renderEngine = require('../renderer/render-engine');
-const RenderFlow = require('../renderer/render-flow');
-const SpriteMaterial = renderEngine.SpriteMaterial;
-const ImageAsset = require('../../assets/image-asset');
-
-/**
- * !#en Enum for text alignment.
- * !#zh 文本横向对齐类型
- * @enum Label.HorizontalAlign
- */
-/**
- * !#en Alignment left for text.
- * !#zh 文本内容左对齐。
- * @property {Number} LEFT
- */
-/**
- * !#en Alignment center for text.
- * !#zh 文本内容居中对齐。
- * @property {Number} CENTER
- */
-/**
- * !#en Alignment right for text.
- * !#zh 文本内容右边对齐。
- * @property {Number} RIGHT
- */
-const HorizontalAlign = macro.TextAlignment;
-
-/**
- * !#en Enum for vertical text alignment.
- * !#zh 文本垂直对齐类型
- * @enum Label.VerticalAlign
- */
-/**
- * !#en Vertical alignment top for text.
- * !#zh 文本顶部对齐。
- * @property {Number} TOP
- */
-/**
- * !#en Vertical alignment center for text.
- * !#zh 文本居中对齐。
- * @property {Number} CENTER
- */
-/**
- * !#en Vertical alignment bottom for text.
- * !#zh 文本底部对齐。
- * @property {Number} BOTTOM
- */
-const VerticalAlign = macro.VerticalTextAlignment;
-
-/**
- * !#en Enum for Overflow.
- * !#zh Overflow 类型
- * @enum Label.Overflow
- */
-/**
- * !#en NONE.
- * !#zh 不做任何限制。
- * @property {Number} NONE
- */
-/**
- * !#en In CLAMP mode, when label content goes out of the bounding box, it will be clipped.
- * !#zh CLAMP 模式中,当文本内容超出边界框时,多余的会被截断。
- * @property {Number} CLAMP
- */
-/**
- * !#en In SHRINK mode, the font size will change dynamically to adapt the content size.
- * !#zh SHRINK 模式,字体大小会动态变化,以适应内容大小。
- * @property {Number} SHRINK
- */
-/**
- * !#en In RESIZE_HEIGHT mode, you can only change the width of label and the height is changed automatically.
- * !#zh 在 RESIZE_HEIGHT 模式下,只能更改文本的宽度,高度是自动改变的。
- * @property {Number} RESIZE_HEIGHT
- */
-const Overflow = cc.Enum({
- NONE: 0,
- CLAMP: 1,
- SHRINK: 2,
- RESIZE_HEIGHT: 3
-});
-
-/**
- * !#en Enum for font type.
- * !#zh Type 类型
- * @enum Label.Type
- */
-/**
- * !#en The TTF font type.
- * !#zh TTF字体
- * @property {Number} TTF
- */
-/**
- * !#en The bitmap font type.
- * !#zh 位图字体
- * @property {Number} BMFont
- */
-/**
- * !#en The system font type.
- * !#zh 系统字体
- * @property {Number} SystemFont
- */
-
-/**
- * !#en The Label Component.
- * !#zh 文字标签组件
- * @class Label
- * @extends Component
- */
-let Label = cc.Class({
- name: 'cc.Label',
- extends: RenderComponent,
-
- ctor () {
- if (CC_EDITOR) {
- this._userDefinedFont = null;
- }
-
- this._actualFontSize = 0;
- this._assemblerData = null;
-
- this._ttfTexture = null;
- },
-
- editor: CC_EDITOR && {
- menu: 'i18n:MAIN_MENU.component.renderers/Label',
- help: 'i18n:COMPONENT.help_url.label',
- inspector: 'packages://inspector/inspectors/comps/label.js',
- },
-
- properties: {
- _useOriginalSize: true,
-
- /**
- * !#en Content string of label.
- * !#zh 标签显示的文本内容。
- * @property {String} string
- */
- _string: {
- default: '',
- formerlySerializedAs: '_N$string',
- },
- string: {
- get () {
- return this._string;
- },
- set (value) {
- let oldValue = this._string;
- this._string = value.toString();
-
- if (this.string !== oldValue) {
- this._updateRenderData();
- }
-
- this._checkStringEmpty();
- },
- multiline: true,
- tooltip: CC_DEV && 'i18n:COMPONENT.label.string'
- },
-
- /**
- * !#en Horizontal Alignment of label.
- * !#zh 文本内容的水平对齐方式。
- * @property {Label.HorizontalAlign} horizontalAlign
- */
- horizontalAlign: {
- default: HorizontalAlign.LEFT,
- type: HorizontalAlign,
- tooltip: CC_DEV && 'i18n:COMPONENT.label.horizontal_align',
- notify (oldValue) {
- if (this.horizontalAlign === oldValue) return;
- this._updateRenderData();
- },
- animatable: false
- },
-
- /**
- * !#en Vertical Alignment of label.
- * !#zh 文本内容的垂直对齐方式。
- * @property {Label.VerticalAlign} verticalAlign
- */
- verticalAlign: {
- default: VerticalAlign.TOP,
- type: VerticalAlign,
- tooltip: CC_DEV && 'i18n:COMPONENT.label.vertical_align',
- notify (oldValue) {
- if (this.verticalAlign === oldValue) return;
- this._updateRenderData();
- },
- animatable: false
- },
-
-
- /**
- * !#en The actual rendering font size in shrink mode
- * !#zh SHRINK 模式下面文本实际渲染的字体大小
- * @property {Number} actualFontSize
- */
- actualFontSize: {
- displayName: 'Actual Font Size',
- animatable: false,
- readonly: true,
- get () {
- return this._actualFontSize;
- }
- },
-
- _fontSize: 40,
- /**
- * !#en Font size of label.
- * !#zh 文本字体大小。
- * @property {Number} fontSize
- */
- fontSize: {
- get () {
- return this._fontSize;
- },
- set (value) {
- if (this._fontSize === value) return;
-
- this._fontSize = value;
- this._updateRenderData();
- },
- tooltip: CC_DEV && 'i18n:COMPONENT.label.font_size',
- },
-
- /**
- * !#en Font family of label, only take effect when useSystemFont property is true.
- * !#zh 文本字体名称, 只在 useSystemFont 属性为 true 的时候生效。
- * @property {String} fontFamily
- */
- fontFamily: {
- default: "Arial",
- tooltip: CC_DEV && 'i18n:COMPONENT.label.font_family',
- notify (oldValue) {
- if (this.fontFamily === oldValue) return;
- this._updateRenderData();
- },
- animatable: false
- },
-
- _lineHeight: 40,
- /**
- * !#en Line Height of label.
- * !#zh 文本行高。
- * @property {Number} lineHeight
- */
- lineHeight: {
- get () {
- return this._lineHeight;
- },
- set (value) {
- if (this._lineHeight === value) return;
- this._lineHeight = value;
- this._updateRenderData();
- },
- tooltip: CC_DEV && 'i18n:COMPONENT.label.line_height',
- },
- /**
- * !#en Overflow of label.
- * !#zh 文字显示超出范围时的处理方式。
- * @property {Label.Overflow} overflow
- */
- overflow: {
- default: Overflow.NONE,
- type: Overflow,
- tooltip: CC_DEV && 'i18n:COMPONENT.label.overflow',
- notify (oldValue) {
- if (this.overflow === oldValue) return;
- this._updateRenderData();
- },
- animatable: false
- },
-
- _enableWrapText: true,
- /**
- * !#en Whether auto wrap label when string width is large than label width.
- * !#zh 是否自动换行。
- * @property {Boolean} enableWrapText
- */
- enableWrapText: {
- get () {
- return this._enableWrapText;
- },
- set (value) {
- if (this._enableWrapText === value) return;
-
- this._enableWrapText = value;
- this._updateRenderData();
- },
- animatable: false,
- tooltip: CC_DEV && 'i18n:COMPONENT.label.wrap',
- },
-
- // 这个保存了旧项目的 file 数据
- _N$file: null,
-
- /**
- * !#en The font of label.
- * !#zh 文本字体。
- * @property {Font} font
- */
- font: {
- get () {
- return this._N$file;
- },
- set (value) {
- if (this.font === value) return;
-
- //if delete the font, we should change isSystemFontUsed to true
- if (!value) {
- this._isSystemFontUsed = true;
- }
-
- if (CC_EDITOR && value) {
- this._userDefinedFont = value;
- }
-
- this._N$file = value;
- this._bmFontOriginalSize = -1;
- if (value && this._isSystemFontUsed)
- this._isSystemFontUsed = false;
-
- if ( typeof value === 'string' ) {
- cc.warnID(4000);
- }
-
- if (value instanceof cc.BitmapFont) {
- this._bmFontOriginalSize = value.fontSize;
- }
-
- if (this._renderData) {
- this.destroyRenderData(this._renderData);
- this._renderData = null;
- }
- this._fontAtlas = null;
- this._updateAssembler();
- this._activateMaterial(true);
- this._updateRenderData();
- },
- type: cc.Font,
- tooltip: CC_DEV && 'i18n:COMPONENT.label.font',
- animatable: false
- },
-
- _isSystemFontUsed: true,
-
- /**
- * !#en Whether use system font name or not.
- * !#zh 是否使用系统字体。
- * @property {Boolean} isSystemFontUsed
- */
- useSystemFont: {
- get () {
- return this._isSystemFontUsed;
- },
- set (value) {
- if (this._isSystemFontUsed === value) return;
-
- this.destroyRenderData(this._renderData);
- this._renderData = null;
-
- if (CC_EDITOR) {
- if (!value && this._isSystemFontUsed && this._userDefinedFont) {
- this.font = this._userDefinedFont;
- this.spacingX = this._spacingX;
- return;
- }
- }
-
- this._isSystemFontUsed = !!value;
- if (value) {
- this.font = null;
- this._updateAssembler();
- this._updateRenderData();
- this._checkStringEmpty();
- }
- else if (!this._userDefinedFont) {
- this.disableRender();
- }
-
- },
- animatable: false,
- tooltip: CC_DEV && 'i18n:COMPONENT.label.system_font',
- },
-
- _bmFontOriginalSize: {
- displayName: 'BMFont Original Size',
- default: -1,
- serializable: false,
- readonly: true,
- visible: true,
- animatable: false
- },
-
- _spacingX: 0,
- spacingX: {
- get () {
- return this._spacingX;
- },
- set (value) {
- this._spacingX = value;
- this._updateRenderData();
- }
- },
-
- _isBold: {
- default: false,
- serializable: false,
- },
- _isItalic: {
- default: false,
- serializable: false,
- },
- _isUnderline: {
- default: false,
- serializable: false,
- },
- },
-
- statics: {
- HorizontalAlign: HorizontalAlign,
- VerticalAlign: VerticalAlign,
- Overflow: Overflow,
- },
-
- onEnable () {
- this._super();
-
- // TODO: Hack for barbarians
- if (!this.font && !this._isSystemFontUsed) {
- this.useSystemFont = true;
- }
- // Reapply default font family if necessary
- if (this.useSystemFont && !this.fontFamily) {
- this.fontFamily = 'Arial';
- }
-
- // Keep track of Node size
- this.node.on(cc.Node.EventType.SIZE_CHANGED, this._updateRenderData, this);
- this.node.on(cc.Node.EventType.ANCHOR_CHANGED, this._updateRenderData, this);
-
- this._checkStringEmpty();
- this._updateAssembler();
- this._activateMaterial();
- },
-
- onDisable () {
- this._super();
- this.node.off(cc.Node.EventType.SIZE_CHANGED, this._updateRenderData, this);
- this.node.off(cc.Node.EventType.ANCHOR_CHANGED, this._updateRenderData, this);
- },
-
- onDestroy () {
- this._assembler._resetAssemblerData && this._assembler._resetAssemblerData(this._assemblerData);
- this._assemblerData = null;
- if (this._ttfTexture) {
- this._ttfTexture.destroy();
- this._ttfTexture = null;
- }
- this._super();
- },
-
- _canRender () {
- let result = this._super();
- let font = this.font;
- if (font instanceof cc.BitmapFont) {
- let spriteFrame = font.spriteFrame;
- // cannot be activated if texture not loaded yet
- if (!spriteFrame || !spriteFrame.textureLoaded()) {
- result = false;
- }
- }
- return result;
- },
-
- _checkStringEmpty () {
- this.markForRender(!!this.string);
- },
-
- _updateAssembler () {
- let assembler = Label._assembler.getAssembler(this);
-
- if (this._assembler !== assembler) {
- this._assembler = assembler;
- this._renderData = null;
- }
-
- if (!this._renderData) {
- this._renderData = this._assembler.createData(this);
- }
- },
-
- _activateMaterial (force) {
- let material = this._material;
- if (material && !force) {
- return;
- }
-
- let font = this.font;
- if (font instanceof cc.BitmapFont) {
- let spriteFrame = font.spriteFrame;
- // cannot be activated if texture not loaded yet
- if (!spriteFrame || !spriteFrame.textureLoaded()) {
- this.disableRender();
-
- if (spriteFrame) {
- spriteFrame.once('load', this._activateMaterial, this);
- spriteFrame.ensureLoadTexture();
- }
- return;
- }
-
- // TODO: old texture in material have been released by loader
- this._texture = spriteFrame._texture;
- }
- else {
- if (!this._ttfTexture) {
- this._ttfTexture = new cc.Texture2D();
- // TTF texture in web will blend with canvas or body background color
- if (!CC_JSB) {
- this._ttfTexture.setPremultiplyAlpha(true);
- }
- this._assemblerData = this._assembler._getAssemblerData();
- this._ttfTexture.image = new ImageAsset(this._assemblerData.canvas);
- }
- this._texture = this._ttfTexture;
- }
-
- // Canvas
- if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) {
- this._texture.url = this.uuid + '_texture';
- }
- // WebGL
- else {
- if (!material) {
- material = new SpriteMaterial();
- }
- // Setup blend function for premultiplied ttf label texture
- if (this._texture === this._ttfTexture) {
- this._srcBlendFactor = cc.macro.BlendFactor.ONE;
- }
- else {
- this._srcBlendFactor = cc.macro.BlendFactor.SRC_ALPHA;
- }
- material.texture = this._texture;
- this._updateMaterial(material);
- }
-
- this.markForUpdateRenderData(true);
- this.markForRender(true);
- },
-
- _updateColor () {
- let font = this.font;
- if (font instanceof cc.BitmapFont) {
- this._super();
- }
- else {
- this._updateRenderData();
- this.node._renderFlag &= ~RenderFlow.FLAG_COLOR;
- }
- },
-
- _updateRenderData (force) {
- let renderData = this._renderData;
- if (renderData) {
- renderData.vertDirty = true;
- renderData.uvDirty = true;
- this.markForUpdateRenderData(true);
- }
-
- if (CC_EDITOR || force) {
- this._updateAssembler();
- this._activateMaterial(force);
- this._assembler.updateRenderData(this);
- }
- },
-
- _enableBold (enabled) {
- this._isBold = !!enabled;
- },
-
- _enableItalics (enabled) {
- this._isItalic = !!enabled;
- },
-
- _enableUnderline (enabled) {
- this._isUnderline = !!enabled;
- },
- });
-
- cc.Label = module.exports = Label;
diff --git a/cocos/2d/label/CCLabelOutline.js b/cocos/2d/label/CCLabelOutline.js
index ae859c1545..dea564fe3c 100644
--- a/cocos/2d/label/CCLabelOutline.js
+++ b/cocos/2d/label/CCLabelOutline.js
@@ -37,63 +37,51 @@
* node.parent = this.node;
*/
-let LabelOutline = cc.Class({
- name: 'cc.LabelOutline',
- extends: require('./CCComponent'),
- editor: CC_EDITOR && {
- menu: 'i18n:MAIN_MENU.component.renderers/LabelOutline',
- executeInEditMode: true,
- requireComponent: cc.Label,
- },
+import Component from '../../components/component';
- properties: {
- _color: cc.color(255,255,255,255),
- _width: 1,
+export default class LabelOutline extends Component {
+ _color = cc.color(255, 255, 255, 255);
+ _width = 1;
- /**
- * !#en Change the outline color
- * !#zh 改变描边的颜色
- * @property color
- * @type {Color}
- * @example
- * outline.color = new cc.Color(0.5, 0.3, 0.7, 1.0);;
- */
- color: {
- get: function () {
- return this._color;
- },
- set: function (value) {
- this._color = cc.color(value);
- this._updateRenderData();
- }
- },
+ /**
+ * !#en Change the outline color
+ * !#zh 改变描边的颜色
+ * @property color
+ * @type {Color}
+ * @example
+ * outline.color = new cc.Color(0.5, 0.3, 0.7, 1.0);;
+ */
+ get color() {
+ return this._color;
+ }
+ set color(value) {
+ this._color = cc.color(value);
+ this._updateRenderData();
+ }
- /**
- * !#en Change the outline width
- * !#zh 改变描边的宽度
- * @property width
- * @type {Number}
- * @example
- * outline.width = 3;
- */
- width: {
- get: function () {
- return this._width;
- },
- set: function (value) {
- this._width = value;
- this._updateRenderData();
- }
- }
- },
+ /**
+ * !#en Change the outline width
+ * !#zh 改变描边的宽度
+ * @property width
+ * @type {Number}
+ * @example
+ * outline.width = 3;
+ */
+ get width() {
+ return this._width;
+ }
- _updateRenderData () {
+ set width(value) {
+ this._width = value;
+ this._updateRenderData();
+ }
+
+ _updateRenderData() {
let label = this.node.getComponent(cc.Label);
if (label) {
label._updateRenderData(true);
}
}
+}
-});
-
-cc.LabelOutline = module.exports = LabelOutline;
+cc.LabelOutline = LabelOutline;
diff --git a/cocos/2d/renderable/CCMask.js b/cocos/2d/renderable/CCMask.js
deleted file mode 100644
index 35f58a94f5..0000000000
--- a/cocos/2d/renderable/CCMask.js
+++ /dev/null
@@ -1,443 +0,0 @@
-/****************************************************************************
- Copyright (c) 2013-2016 Chukong Technologies Inc.
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos.com
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
-
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-const misc = require('../utils/misc');
-const renderEngine = require('../renderer/render-engine');
-const math = renderEngine.math;
-const StencilMaterial = renderEngine.StencilMaterial;
-const RenderComponent = require('./CCRenderComponent');
-const RenderFlow = require('../renderer/render-flow');
-const Graphics = require('../graphics/graphics');
-
-let _vec2_temp = cc.v2();
-let _mat4_temp = math.mat4.create();
-
-/**
- * !#en the type for mask.
- * !#zh 遮罩组件类型
- * @enum Mask.Type
- */
-let MaskType = cc.Enum({
- /**
- * !#en Rect mask.
- * !#zh 使用矩形作为遮罩
- * @property {Number} RECT
- */
- RECT: 0,
- /**
- * !#en Ellipse Mask.
- * !#zh 使用椭圆作为遮罩
- * @property {Number} ELLIPSE
- */
- ELLIPSE: 1,
- /**
- * !#en Image Stencil Mask.
- * !#zh 使用图像模版作为遮罩
- * @property {Number} IMAGE_STENCIL
- */
- IMAGE_STENCIL: 2,
-});
-
-const SEGEMENTS_MIN = 3;
-const SEGEMENTS_MAX = 10000;
-
-/**
- * !#en The Mask Component
- * !#zh 遮罩组件
- * @class Mask
- * @extends Component
- */
-let Mask = cc.Class({
- name: 'cc.Mask',
- extends: RenderComponent,
-
- editor: CC_EDITOR && {
- menu: 'i18n:MAIN_MENU.component.renderers/Mask',
- help: 'i18n:COMPONENT.help_url.mask',
- inspector: 'packages://inspector/inspectors/comps/mask.js'
- },
-
- properties: {
- _spriteFrame: {
- default: null,
- type: cc.SpriteFrame
- },
-
- /**
- * !#en The mask type.
- * !#zh 遮罩类型
- * @property type
- * @type {Mask.Type}
- * @example
- * mask.type = cc.Mask.Type.RECT;
- */
- _type: MaskType.RECT,
- type: {
- get: function () {
- return this._type;
- },
- set: function (value) {
- this._type = value;
- if (this._type !== MaskType.IMAGE_STENCIL) {
- this.spriteFrame = null;
- this.alphaThreshold = 0;
- this._updateGraphics();
- }
- if (this._renderData) {
- this.destroyRenderData(this._renderData);
- this._renderData = null;
- }
- this._activateMaterial();
- },
- type: MaskType,
- tooltip: CC_DEV && 'i18n:COMPONENT.mask.type',
- },
-
- /**
- * !#en The mask image
- * !#zh 遮罩所需要的贴图
- * @property spriteFrame
- * @type {SpriteFrame}
- * @default null
- * @example
- * mask.spriteFrame = newSpriteFrame;
- */
- spriteFrame: {
- type: cc.SpriteFrame,
- tooltip: CC_DEV && 'i18n:COMPONENT.mask.spriteFrame',
- get: function () {
- return this._spriteFrame;
- },
- set: function (value) {
- let lastSprite = this._spriteFrame;
- if (CC_EDITOR) {
- if ((lastSprite && lastSprite._uuid) === (value && value._uuid)) {
- return;
- }
- }
- else {
- if (lastSprite === value) {
- return;
- }
- }
- this._spriteFrame = value;
- this._applySpriteFrame(lastSprite);
- },
- },
-
- /**
- * !#en
- * The alpha threshold.(Not supported Canvas Mode)
- * The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold.
- * Should be a float between 0 and 1.
- * This default to 0 (so alpha test is disabled).
- * When it's set to 1, the stencil will discard all pixels, nothing will be shown,
- * In previous version, it act as if the alpha test is disabled, which is incorrect.
- * !#zh
- * Alpha 阈值(不支持 Canvas 模式)
- * 只有当模板的像素的 alpha 大于 alphaThreshold 时,才会绘制内容。
- * 该数值 0 ~ 1 之间的浮点数,默认值为 0(因此禁用 alpha 测试)
- * 当被设置为 1 时,会丢弃所有蒙版像素,所以不会显示任何内容,在之前的版本中,设置为 1 等同于 0,这种效果其实是不正确的
- * @property alphaThreshold
- * @type {Number}
- * @default 0
- */
- alphaThreshold: {
- default: 0,
- type: cc.Float,
- range: [0, 1, 0.1],
- slide: true,
- tooltip: CC_DEV && 'i18n:COMPONENT.mask.alphaThreshold',
- notify: function () {
- if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) {
- cc.warnID(4201);
- return;
- }
- if (this._material) {
- this._material.alphaThreshold = this.alphaThreshold;
- this._material.updateHash();
- }
- }
- },
-
- /**
- * !#en Reverse mask (Not supported Canvas Mode)
- * !#zh 反向遮罩(不支持 Canvas 模式)
- * @property inverted
- * @type {Boolean}
- * @default false
- */
- inverted: {
- default: false,
- type: cc.Boolean,
- tooltip: CC_DEV && 'i18n:COMPONENT.mask.inverted',
- notify: function () {
- if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) {
- cc.warnID(4202);
- return;
- }
- }
- },
-
- /**
- * TODO: remove segments, not supported by graphics
- * !#en The segements for ellipse mask.
- * !#zh 椭圆遮罩的曲线细分数
- * @property segements
- * @type {Number}
- * @default 64
- */
- _segments: 64,
- segements: {
- get: function () {
- return this._segments;
- },
- set: function (value) {
- this._segments = misc.clampf(value, SEGEMENTS_MIN, SEGEMENTS_MAX);
- },
- tooltip: CC_DEV && 'i18n:COMPONENT.mask.segements',
- },
-
- _resizeToTarget: {
- animatable: false,
- set: function (value) {
- if(value) {
- this._resizeNodeToTargetNode();
- }
- }
- }
- },
-
- statics: {
- Type: MaskType,
- },
-
- onLoad () {
- this._graphics = new Graphics();
- this._graphics.node = this.node;
- this._graphics.lineWidth = 0;
- this._graphics.strokeColor = cc.color(0, 0, 0, 0);
- },
-
- onRestore () {
- if (!this._graphics) {
- this._graphics = new Graphics();
- this._graphics.node = this.node;
- this._graphics.lineWidth = 0;
- }
- if (this._type !== MaskType.IMAGE_STENCIL) {
- this._updateGraphics();
- }
- },
-
- onEnable () {
- this._super();
- if (this._type === MaskType.IMAGE_STENCIL) {
- if (!this._spriteFrame || !this._spriteFrame.textureLoaded()) {
- // Do not render when sprite frame is not ready
- this.markForRender(false);
- if (this._spriteFrame) {
- this._spriteFrame.once('load', this._onTextureLoaded, this);
- this._spriteFrame.ensureLoadTexture();
- }
- }
- }
- else {
- this._updateGraphics();
- }
-
- this.node.on(cc.Node.EventType.POSITION_CHANGED, this._updateGraphics, this);
- this.node.on(cc.Node.EventType.ROTATION_CHANGED, this._updateGraphics, this);
- this.node.on(cc.Node.EventType.SCALE_CHANGED, this._updateGraphics, this);
- this.node.on(cc.Node.EventType.SIZE_CHANGED, this._updateGraphics, this);
- this.node.on(cc.Node.EventType.ANCHOR_CHANGED, this._updateGraphics, this);
-
- this.node._renderFlag |= RenderFlow.FLAG_POST_RENDER;
- this._activateMaterial();
- },
-
- onDisable () {
- this._super();
-
- this.node.off(cc.Node.EventType.POSITION_CHANGED, this._updateGraphics, this);
- this.node.off(cc.Node.EventType.ROTATION_CHANGED, this._updateGraphics, this);
- this.node.off(cc.Node.EventType.SCALE_CHANGED, this._updateGraphics, this);
- this.node.off(cc.Node.EventType.SIZE_CHANGED, this._updateGraphics, this);
- this.node.off(cc.Node.EventType.ANCHOR_CHANGED, this._updateGraphics, this);
-
- this.node._renderFlag &= ~RenderFlow.FLAG_POST_RENDER;
- },
-
- onDestroy () {
- this._super();
- this._graphics.destroy();
- },
-
- _resizeNodeToTargetNode: CC_EDITOR && function () {
- if(this.spriteFrame) {
- let rect = this.spriteFrame.getRect();
- this.node.setContentSize(rect.width, rect.height);
- }
- },
-
- _onTextureLoaded () {
- // Mark render data dirty
- if (this._renderData) {
- this._renderData.uvDirty = true;
- this._renderData.vertDirty = true;
- this.markForUpdateRenderData(true);
- }
- // Reactivate material
- if (this.enabledInHierarchy) {
- this._activateMaterial();
- }
- },
-
- _applySpriteFrame (oldFrame) {
- if (oldFrame && oldFrame.off) {
- oldFrame.off('load', this._onTextureLoaded, this);
- }
- let spriteFrame = this._spriteFrame;
- if (spriteFrame) {
- if (spriteFrame.textureLoaded()) {
- this._onTextureLoaded(null);
- }
- else {
- spriteFrame.once('load', this._onTextureLoaded, this);
- spriteFrame.ensureLoadTexture();
- }
- }
- },
-
- _activateMaterial () {
- // cannot be activated if texture not loaded yet
- if (this._type === MaskType.IMAGE_STENCIL && (!this.spriteFrame || !this.spriteFrame.textureLoaded())) {
- this.markForRender(false);
- return;
- }
-
- // WebGL
- if (cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) {
- // Init material
- if (!this._material) {
- this._material = new StencilMaterial();
- }
-
- // Reset material
- if (this._type === MaskType.IMAGE_STENCIL) {
- let texture = this.spriteFrame.getTexture();
- this._material.useModel = false;
- this._material.useTexture = true;
- this._material.useColor = true;
- this._material.texture = texture;
- this._material.alphaThreshold = this.alphaThreshold;
- }
- else {
- this._material.useModel = true;
- this._material.useTexture = false;
- this._material.useColor = false;
- }
- }
-
- this.markForRender(true);
- },
-
- _updateGraphics () {
- let node = this.node;
- let graphics = this._graphics;
- // Share render data with graphics content
- graphics.clear(false);
- let width = node._contentSize.width;
- let height = node._contentSize.height;
- let x = -width * node._anchorPoint.x;
- let y = -height * node._anchorPoint.y;
- if (this._type === MaskType.RECT) {
- graphics.rect(x, y, width, height);
- }
- else if (this._type === MaskType.ELLIPSE) {
- let cx = x + width / 2,
- cy = y + height / 2,
- rx = width / 2,
- ry = height / 2;
- graphics.ellipse(cx, cy, rx, ry);
- }
- if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) {
- graphics.stroke();
- }
- else {
- graphics.fill();
- }
- },
-
- _hitTest (cameraPt) {
- let node = this.node;
- let size = node.getContentSize(),
- w = size.width,
- h = size.height,
- testPt = _vec2_temp;
-
- node._updateWorldMatrix();
- math.mat4.invert(_mat4_temp, node._worldMatrix);
- math.vec2.transformMat4(testPt, cameraPt, _mat4_temp);
- testPt.x += node._anchorPoint.x * w;
- testPt.y += node._anchorPoint.y * h;
-
- if (this.type === MaskType.RECT || this.type === MaskType.IMAGE_STENCIL) {
- return testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h;
- }
- else if (this.type === MaskType.ELLIPSE) {
- let rx = w / 2, ry = h / 2;
- let px = testPt.x - 0.5 * w, py = testPt.y - 0.5 * h;
- return px * px / (rx * rx) + py * py / (ry * ry) < 1;
- }
- },
-
- markForUpdateRenderData (enable) {
- if (enable && this.enabledInHierarchy) {
- this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA;
- }
- else if (!enable) {
- this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA;
- }
- },
-
- markForRender (enable) {
- if (enable && this.enabledInHierarchy) {
- this.node._renderFlag |= (RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA |
- RenderFlow.FLAG_POST_RENDER);
- }
- else if (!enable) {
- this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_POST_RENDER);
- }
- },
-
- disableRender () {
- this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA |
- RenderFlow.FLAG_POST_RENDER);
- },
-});
-
-cc.Mask = module.exports = Mask;
diff --git a/cocos/2d/renderable/CCRenderComponent.js b/cocos/2d/renderable/CCRenderComponent.js
deleted file mode 100644
index 4ff2a9f050..0000000000
--- a/cocos/2d/renderable/CCRenderComponent.js
+++ /dev/null
@@ -1,224 +0,0 @@
-/****************************************************************************
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos.com
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
-
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-const Component = require('./CCComponent');
-const renderEngine = require('../renderer/render-engine');
-const RenderFlow = require('../renderer/render-flow');
-const BlendFactor = require('../platform/CCMacro').BlendFactor;
-const RenderData = renderEngine.RenderData;
-const gfx = renderEngine.gfx;
-
-/**
- * !#en
- * Base class for components which supports rendering features.
- * !#zh
- * 所有支持渲染的组件的基类
- *
- * @class RenderComponent
- * @extends Component
- */
-let RenderComponent = cc.Class({
- name: 'RenderComponent',
- extends: Component,
-
- editor: CC_EDITOR && {
- executeInEditMode: true,
- disallowMultiple: true
- },
-
- properties: {
- _srcBlendFactor: BlendFactor.SRC_ALPHA,
- _dstBlendFactor: BlendFactor.ONE_MINUS_SRC_ALPHA,
-
- /**
- * !#en specify the source Blend Factor, this will generate a custom material object, please pay attention to the memory cost.
- * !#zh 指定原图的混合模式,这会克隆一个新的材质对象,注意这带来的
- * @property srcBlendFactor
- * @type {macro.BlendFactor}
- * @example
- * sprite.srcBlendFactor = cc.macro.BlendFactor.ONE;
- */
- srcBlendFactor: {
- get: function() {
- return this._srcBlendFactor;
- },
- set: function(value) {
- if (this._srcBlendFactor === value) return;
- this._srcBlendFactor = value;
- this._updateBlendFunc(true);
- },
- animatable: false,
- type:BlendFactor,
- tooltip: CC_DEV && 'i18n:COMPONENT.sprite.src_blend_factor'
- },
-
- /**
- * !#en specify the destination Blend Factor.
- * !#zh 指定目标的混合模式
- * @property dstBlendFactor
- * @type {macro.BlendFactor}
- * @example
- * sprite.dstBlendFactor = cc.macro.BlendFactor.ONE;
- */
- dstBlendFactor: {
- get: function() {
- return this._dstBlendFactor;
- },
- set: function(value) {
- if (this._dstBlendFactor === value) return;
- this._dstBlendFactor = value;
- this._updateBlendFunc(true);
- },
- animatable: false,
- type: BlendFactor,
- tooltip: CC_DEV && 'i18n:COMPONENT.sprite.dst_blend_factor'
- },
- },
-
- ctor () {
- this._material = null;
- this._renderData = null;
- this.__allocedDatas = [];
- this._vertexFormat = null;
- this._toPostHandle = false;
- this._assembler = this.constructor._assembler;
- this._postAssembler = this.constructor._postAssembler;
- },
-
- onEnable () {
- if (this.node._renderComponent) {
- this.node._renderComponent.enabled = false;
- }
- this.node._renderComponent = this;
- this.node._renderFlag |= RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | RenderFlow.FLAG_COLOR;
- },
-
- onDisable () {
- this.node._renderComponent = null;
- this.disableRender();
- },
-
- onDestroy () {
- for (let i = 0, l = this.__allocedDatas.length; i < l; i++) {
- RenderData.free(this.__allocedDatas[i]);
- }
- this.__allocedDatas.length = 0;
- this._material = null;
- this._renderData = null;
- },
-
- _canRender () {
- return this._enabled;
- },
-
- markForUpdateRenderData (enable) {
- if (enable && this._canRender()) {
- this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA;
- }
- else if (!enable) {
- this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA;
- }
- },
-
- markForRender (enable) {
- if (enable && this._canRender()) {
- this.node._renderFlag |= RenderFlow.FLAG_RENDER;
- }
- else if (!enable) {
- this.node._renderFlag &= ~RenderFlow.FLAG_RENDER;
- }
- },
-
- markForCustomIARender (enable) {
- if (enable && this._canRender()) {
- this.node._renderFlag |= RenderFlow.FLAG_CUSTOM_IA_RENDER;
- }
- else if (!enable) {
- this.node._renderFlag &= ~RenderFlow.FLAG_CUSTOM_IA_RENDER;
- }
- },
-
- disableRender () {
- this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_CUSTOM_IA_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | RenderFlow.FLAG_COLOR);
- },
-
- requestRenderData () {
- let data = RenderData.alloc();
- this.__allocedDatas.push(data);
- return data;
- },
-
- destroyRenderData (data) {
- let index = this.__allocedDatas.indexOf(data);
- if (index !== -1) {
- this.__allocedDatas.splice(index, 1);
- RenderData.free(data);
- }
- },
-
- _updateColor () {
- let material = this._material;
- if (material) {
- material.color = this.node.color;
- material.updateHash();
-
- // reset flag when set color to material successfully
- this.node._renderFlag &= ~RenderFlow.FLAG_COLOR;
- }
- },
-
- getMaterial () {
- return this._material;
- },
-
- _updateMaterial (material) {
- this._material = material;
-
- this._updateBlendFunc();
- material.updateHash();
- },
-
- _updateBlendFunc: function (updateHash) {
- if (!this._material) {
- return;
- }
-
- var pass = this._material._mainTech.passes[0];
- pass.setBlend(
- gfx.BLEND_FUNC_ADD,
- this._srcBlendFactor, this._dstBlendFactor,
- gfx.BLEND_FUNC_ADD,
- this._srcBlendFactor, this._dstBlendFactor
- );
-
- if (updateHash) {
- this._material.updateHash();
- }
- },
-});
-RenderComponent._assembler = null;
-RenderComponent._postAssembler = null;
-
-cc.RenderComponent = module.exports = RenderComponent;
\ No newline at end of file
diff --git a/cocos/2d/renderable/CCSprite.js b/cocos/2d/renderable/CCSprite.js
deleted file mode 100644
index cd2de5ab18..0000000000
--- a/cocos/2d/renderable/CCSprite.js
+++ /dev/null
@@ -1,661 +0,0 @@
-/****************************************************************************
- Copyright (c) 2013-2016 Chukong Technologies Inc.
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos.com
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
-
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-const misc = require('../utils/misc');
-const NodeEvent = require('../CCNode').EventType;
-const RenderComponent = require('./CCRenderComponent');
-const RenderFlow = require('../renderer/render-flow');
-const renderEngine = require('../renderer/render-engine');
-const SpriteMaterial = renderEngine.SpriteMaterial;
-const GraySpriteMaterial = renderEngine.GraySpriteMaterial;
-
-/**
- * !#en Enum for sprite type.
- * !#zh Sprite 类型
- * @enum Sprite.Type
- */
-var SpriteType = cc.Enum({
- /**
- * !#en The simple type.
- * !#zh 普通类型
- * @property {Number} SIMPLE
- */
- SIMPLE: 0,
- /**
- * !#en The sliced type.
- * !#zh 切片(九宫格)类型
- * @property {Number} SLICED
- */
- SLICED: 1,
- /**
- * !#en The tiled type.
- * !#zh 平铺类型
- * @property {Number} TILED
- */
- TILED: 2,
- /**
- * !#en The filled type.
- * !#zh 填充类型
- * @property {Number} FILLED
- */
- FILLED: 3,
- /**
- * !#en The mesh type.
- * !#zh 以 Mesh 三角形组成的类型
- * @property {Number} MESH
- */
- MESH: 4
-});
-
-/**
- * !#en Enum for fill type.
- * !#zh 填充类型
- * @enum Sprite.FillType
- */
-var FillType = cc.Enum({
- /**
- * !#en The horizontal fill.
- * !#zh 水平方向填充
- * @property {Number} HORIZONTAL
- */
- HORIZONTAL: 0,
- /**
- * !#en The vertical fill.
- * !#zh 垂直方向填充
- * @property {Number} VERTICAL
- */
- VERTICAL: 1,
- /**
- * !#en The radial fill.
- * !#zh 径向填充
- * @property {Number} RADIAL
- */
- RADIAL:2,
-});
-
-/**
- * !#en Sprite Size can track trimmed size, raw size or none.
- * !#zh 精灵尺寸调整模式
- * @enum Sprite.SizeMode
- */
-var SizeMode = cc.Enum({
- /**
- * !#en Use the customized node size.
- * !#zh 使用节点预设的尺寸
- * @property {Number} CUSTOM
- */
- CUSTOM: 0,
- /**
- * !#en Match the trimmed size of the sprite frame automatically.
- * !#zh 自动适配为精灵裁剪后的尺寸
- * @property {Number} TRIMMED
- */
- TRIMMED: 1,
- /**
- * !#en Match the raw size of the sprite frame automatically.
- * !#zh 自动适配为精灵原图尺寸
- * @property {Number} RAW
- */
- RAW: 2
-});
-
-var State = cc.Enum({
- /**
- * !#en The normal state
- * !#zh 正常状态
- * @property {Number} NORMAL
- */
- NORMAL: 0,
- /**
- * !#en The gray state, all color will be modified to grayscale value.
- * !#zh 灰色状态,所有颜色会被转换成灰度值
- * @property {Number} GRAY
- */
- GRAY: 1
-});
-
-/**
- * !#en Renders a sprite in the scene.
- * !#zh 该组件用于在场景中渲染精灵。
- * @class Sprite
- * @extends Component
- * @example
- * // Create a new node and add sprite components.
- * var node = new cc.Node("New Sprite");
- * var sprite = node.addComponent(cc.Sprite);
- * node.parent = this.node;
- */
-var Sprite = cc.Class({
- name: 'cc.Sprite',
- extends: RenderComponent,
-
- ctor () {
- this._assembler = null;
- this._graySpriteMaterial = null;
- this._spriteMaterial = null;
- },
-
- editor: CC_EDITOR && {
- menu: 'i18n:MAIN_MENU.component.renderers/Sprite',
- help: 'i18n:COMPONENT.help_url.sprite',
- inspector: 'packages://inspector/inspectors/comps/sprite.js',
- },
-
- properties: {
- _spriteFrame: {
- default: null,
- type: cc.SpriteFrame
- },
- _type: SpriteType.SIMPLE,
- _sizeMode: SizeMode.TRIMMED,
- _fillType: 0,
- _fillCenter: cc.v2(0,0),
- _fillStart: 0,
- _fillRange: 0,
- _isTrimmedMode: true,
- _state: 0,
- _atlas: {
- default: null,
- type: cc.SpriteAtlas,
- tooltip: CC_DEV && 'i18n:COMPONENT.sprite.atlas',
- editorOnly: true,
- visible: true,
- animatable: false
- },
-
- /**
- * !#en The sprite frame of the sprite.
- * !#zh 精灵的精灵帧
- * @property spriteFrame
- * @type {SpriteFrame}
- * @example
- * sprite.spriteFrame = newSpriteFrame;
- */
- spriteFrame: {
- get: function () {
- return this._spriteFrame;
- },
- set: function (value, force) {
- var lastSprite = this._spriteFrame;
- if (CC_EDITOR) {
- if (!force && ((lastSprite && lastSprite._uuid) === (value && value._uuid))) {
- return;
- }
- }
- else {
- if (lastSprite === value) {
- return;
- }
- }
- this._spriteFrame = value;
- // render & update render data flag will be triggered while applying new sprite frame
- this.markForUpdateRenderData(false);
- this._applySpriteFrame(lastSprite);
- if (CC_EDITOR) {
- this.node.emit('spriteframe-changed', this);
- }
- },
- type: cc.SpriteFrame,
- },
-
- /**
- * !#en The sprite render type.
- * !#zh 精灵渲染类型
- * @property type
- * @type {Sprite.Type}
- * @example
- * sprite.type = cc.Sprite.Type.SIMPLE;
- */
- type: {
- get: function () {
- return this._type;
- },
- set: function (value) {
- if (this._type !== value) {
- this.destroyRenderData(this._renderData);
- this._renderData = null;
- this._type = value;
- this._updateAssembler();
- }
- },
- type: SpriteType,
- animatable: false,
- tooltip: CC_DEV && 'i18n:COMPONENT.sprite.type',
- },
-
- /**
- * !#en
- * The fill type, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”.
- * !#zh
- * 精灵填充类型,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。
- * @property fillType
- * @type {Sprite.FillType}
- * @example
- * sprite.fillType = cc.Sprite.FillType.HORIZONTAL;
- */
- fillType : {
- get: function () {
- return this._fillType;
- },
- set: function(value) {
- if (value !== this._fillType) {
- if (value === FillType.RADIAL || this._fillType === FillType.RADIAL) {
- this.destroyRenderData(this._renderData);
- this._renderData = null;
- }
- else if (this._renderData) {
- this.markForUpdateRenderData(true);
- }
- this._fillType = value;
- this._updateAssembler();
- }
- },
- type: FillType,
- tooltip: CC_DEV && 'i18n:COMPONENT.sprite.fill_type'
- },
-
- /**
- * !#en
- * The fill Center, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”.
- * !#zh
- * 填充中心点,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。
- * @property fillCenter
- * @type {Vec2}
- * @example
- * sprite.fillCenter = new cc.Vec2(0, 0);
- */
- fillCenter: {
- get: function() {
- return this._fillCenter;
- },
- set: function(value) {
- this._fillCenter.x = value.x;
- this._fillCenter.y = value.y;
- if (this._type === SpriteType.FILLED && this._renderData) {
- this.markForUpdateRenderData(true);
- }
- },
- tooltip: CC_DEV && 'i18n:COMPONENT.sprite.fill_center',
- },
-
- /**
- * !#en
- * The fill Start, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”.
- * !#zh
- * 填充起始点,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。
- * @property fillStart
- * @type {Number}
- * @example
- * // -1 To 1 between the numbers
- * sprite.fillStart = 0.5;
- */
- fillStart: {
- get: function() {
- return this._fillStart;
- },
- set: function(value) {
- this._fillStart = misc.clampf(value, -1, 1);
- if (this._type === SpriteType.FILLED && this._renderData) {
- this.markForUpdateRenderData(true);
- }
- },
- tooltip: CC_DEV && 'i18n:COMPONENT.sprite.fill_start'
- },
-
- /**
- * !#en
- * The fill Range, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”.
- * !#zh
- * 填充范围,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。
- * @property fillRange
- * @type {Number}
- * @example
- * // -1 To 1 between the numbers
- * sprite.fillRange = 1;
- */
- fillRange: {
- get: function() {
- return this._fillRange;
- },
- set: function(value) {
- this._fillRange = misc.clampf(value, -1, 1);
- if (this._type === SpriteType.FILLED && this._renderData) {
- this.markForUpdateRenderData(true);
- }
- },
- tooltip: CC_DEV && 'i18n:COMPONENT.sprite.fill_range'
- },
- /**
- * !#en specify the frame is trimmed or not.
- * !#zh 是否使用裁剪模式
- * @property trim
- * @type {Boolean}
- * @example
- * sprite.trim = true;
- */
- trim: {
- get: function () {
- return this._isTrimmedMode;
- },
- set: function (value) {
- if (this._isTrimmedMode !== value) {
- this._isTrimmedMode = value;
- if ((this._type === SpriteType.SIMPLE || this._type === SpriteType.MESH) &&
- this._renderData) {
- this.markForUpdateRenderData(true);
- }
- }
- },
- animatable: false,
- tooltip: CC_DEV && 'i18n:COMPONENT.sprite.trim'
- },
-
-
- /**
- * !#en specify the size tracing mode.
- * !#zh 精灵尺寸调整模式
- * @property sizeMode
- * @type {Sprite.SizeMode}
- * @example
- * sprite.sizeMode = cc.Sprite.SizeMode.CUSTOM;
- */
- sizeMode: {
- get: function () {
- return this._sizeMode;
- },
- set: function (value) {
- this._sizeMode = value;
- if (value !== SizeMode.CUSTOM) {
- this._applySpriteSize();
- }
- },
- animatable: false,
- type: SizeMode,
- tooltip: CC_DEV && 'i18n:COMPONENT.sprite.size_mode'
- }
- },
-
- statics: {
- FillType: FillType,
- Type: SpriteType,
- SizeMode: SizeMode,
- State: State,
- },
-
- setVisible: function (visible) {
- this.enabled = visible;
- },
-
- /**
- * Change the state of sprite.
- * @method setState
- * @see `Sprite.State`
- * @param state {Sprite.State} NORMAL or GRAY State.
- */
- setState: function (state) {
- if (this._state === state) return;
- this._state = state;
- this._activateMaterial();
- },
-
- /**
- * Gets the current state.
- * @method getState
- * @see `Sprite.State`
- * @return {Sprite.State}
- */
- getState: function () {
- return this._state;
- },
-
- onEnable: function () {
- this._super();
-
- if (!this._spriteFrame || !this._spriteFrame.textureLoaded()) {
- // Do not render when sprite frame is not ready
- this.disableRender();
- if (this._spriteFrame) {
- this._spriteFrame.once('load', this._onTextureLoaded, this);
- this._spriteFrame.ensureLoadTexture();
- }
- }
-
- this._updateAssembler();
- this._activateMaterial();
-
- this.node.on(NodeEvent.SIZE_CHANGED, this._onNodeSizeDirty, this);
- this.node.on(NodeEvent.ANCHOR_CHANGED, this._onNodeSizeDirty, this);
- },
-
- onDisable: function () {
- this._super();
-
- this.node.off(NodeEvent.SIZE_CHANGED, this._onNodeSizeDirty, this);
- this.node.off(NodeEvent.ANCHOR_CHANGED, this._onNodeSizeDirty, this);
- },
-
- _onNodeSizeDirty () {
- if (!this._renderData) return;
- this.markForUpdateRenderData(true);
- },
-
- _updateAssembler: function () {
- let assembler = Sprite._assembler.getAssembler(this);
-
- if (this._assembler !== assembler) {
- this._assembler = assembler;
- this._renderData = null;
- }
-
- if (!this._renderData) {
- this._renderData = this._assembler.createData(this);
- this._renderData.material = this._material;
- this.markForUpdateRenderData(true);
- }
- },
-
- _activateMaterial: function () {
- let spriteFrame = this._spriteFrame;
-
- // WebGL
- if (cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) {
- // Get material
- let material;
- if (this._state === State.GRAY) {
- if (!this._graySpriteMaterial) {
- this._graySpriteMaterial = new GraySpriteMaterial();
- }
- material = this._graySpriteMaterial;
- }
- else {
- if (!this._spriteMaterial) {
- this._spriteMaterial = new SpriteMaterial();
- }
- material = this._spriteMaterial;
- }
- // Set texture
- if (spriteFrame && spriteFrame.textureLoaded()) {
- let texture = spriteFrame.getTexture();
- if (material.texture !== texture) {
- material.texture = texture;
- this._updateMaterial(material);
- }
- else if (material !== this._material) {
- this._updateMaterial(material);
- }
- if (this._renderData) {
- this._renderData.material = material;
- }
-
- this.node._renderFlag |= RenderFlow.FLAG_COLOR;
- this.markForUpdateRenderData(true);
- this.markForRender(true);
- }
- else {
- this.disableRender();
- }
- }
- else {
- this.markForUpdateRenderData(true);
- this.markForRender(true);
- }
- },
-
- _applyAtlas: CC_EDITOR && function (spriteFrame) {
- // Set atlas
- if (spriteFrame && spriteFrame._atlasUuid) {
- var self = this;
- cc.AssetLibrary.loadAsset(spriteFrame._atlasUuid, function (err, asset) {
- self._atlas = asset;
- });
- } else {
- this._atlas = null;
- }
- },
-
- _canRender () {
- if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) {
- if (!this._enabled) return false;
- }
- else {
- if (!this._enabled || !this._material) return false;
- }
-
- let spriteFrame = this._spriteFrame;
- if (!spriteFrame || !spriteFrame.textureLoaded()) {
- return false;
- }
- return true;
- },
-
- markForUpdateRenderData (enable) {
- if (enable && this._canRender()) {
- this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA;
-
- let renderData = this._renderData;
- if (renderData) {
- renderData.uvDirty = true;
- renderData.vertDirty = true;
- }
- }
- else if (!enable) {
- this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA;
- }
- },
-
- _applySpriteSize: function () {
- if (this._spriteFrame) {
- if (SizeMode.RAW === this._sizeMode) {
- var size = this._spriteFrame.getOriginalSize();
- this.node.setContentSize(size);
- } else if (SizeMode.TRIMMED === this._sizeMode) {
- var rect = this._spriteFrame.getRect();
- this.node.setContentSize(rect.width, rect.height);
- }
-
- this._activateMaterial();
- }
- },
-
- _onTextureLoaded: function () {
- if (!this.isValid) {
- return;
- }
-
- this._applySpriteSize();
- },
-
- _applySpriteFrame: function (oldFrame) {
- if (oldFrame && oldFrame.off) {
- oldFrame.off('load', this._onTextureLoaded, this);
- }
-
- var spriteFrame = this._spriteFrame;
- if (!spriteFrame || (this._material && this._material._texture) !== (spriteFrame && spriteFrame._texture)) {
- // disable render flow until texture is loaded
- this.markForRender(false);
- }
-
- if (spriteFrame) {
- if (!oldFrame || spriteFrame._texture !== oldFrame._texture) {
- if (spriteFrame.textureLoaded()) {
- this._onTextureLoaded(null);
- }
- else {
- spriteFrame.once('load', this._onTextureLoaded, this);
- spriteFrame.ensureLoadTexture();
- }
- }
- else {
- this._applySpriteSize();
- }
- }
-
- if (CC_EDITOR) {
- // Set atlas
- this._applyAtlas(spriteFrame);
- }
- },
-
- _resized: CC_EDITOR && function () {
- if (this._spriteFrame) {
- var actualSize = this.node.getContentSize();
- var expectedW = actualSize.width;
- var expectedH = actualSize.height;
- if (this._sizeMode === SizeMode.RAW) {
- var size = this._spriteFrame.getOriginalSize();
- expectedW = size.width;
- expectedH = size.height;
- } else if (this._sizeMode === SizeMode.TRIMMED) {
- var rect = this._spriteFrame.getRect();
- expectedW = rect.width;
- expectedH = rect.height;
-
- }
-
- if (expectedW !== actualSize.width || expectedH !== actualSize.height) {
- this._sizeMode = SizeMode.CUSTOM;
- }
- }
- },
-});
-
-if (CC_EDITOR) {
- // override __preload
- Sprite.prototype.__superPreload = cc.Component.prototype.__preload;
- Sprite.prototype.__preload = function () {
- if (this.__superPreload) this.__superPreload();
- this.node.on(NodeEvent.SIZE_CHANGED, this._resized, this);
- };
- // override onDestroy
- Sprite.prototype.__superOnDestroy = cc.Component.prototype.onDestroy;
- Sprite.prototype.onDestroy = function () {
- if (this.__superOnDestroy) this.__superOnDestroy();
- this.node.off(NodeEvent.SIZE_CHANGED, this._resized, this);
- };
-}
-
-cc.Sprite = module.exports = Sprite;
diff --git a/cocos/2d/renderer/utils/label/bmfont.js b/cocos/2d/renderer/utils/label/bmfont.js
index e05fad174d..7520f736bb 100644
--- a/cocos/2d/renderer/utils/label/bmfont.js
+++ b/cocos/2d/renderer/utils/label/bmfont.js
@@ -23,14 +23,19 @@
THE SOFTWARE.
****************************************************************************/
-const macro = require('../../../platform/CCMacro');
+// const macro = require('../../../platform/CCMacro');
+
+// const Label = require('../../../components/CCLabel');
+// const Overflow = Label.Overflow;
+
+// const textUtils = require('../../../utils/text-utils');
+import macro from '../../../../core/platform/CCMacro';
+import Label from '../../../../3d/ui/components/label-component';
+import textUtils from '../../../../core/utils/text-utils';
-const Label = require('../../../components/CCLabel');
const Overflow = Label.Overflow;
-const textUtils = require('../../../utils/text-utils');
-
-let FontLetterDefinition = function() {
+let FontLetterDefinition = function () {
this._u = 0;
this._v = 0;
this._width = 0;
@@ -42,16 +47,16 @@ let FontLetterDefinition = function() {
this._xAdvance = 0;
};
-cc.FontAtlas = function (fntConfig) {
- this._letterDefinitions = {};
-};
+class FontAtlas {
+ constructor(fntConfig) {
+ this._letterDefinitions = {};
+ }
-cc.FontAtlas.prototype = {
- constructor: cc.FontAtlas,
- addLetterDefinitions: function(letter, letterDefinition) {
+ addLetterDefinitions(letter, letterDefinition) {
this._letterDefinitions[letter] = letterDefinition;
- },
- cloneLetterDefinition: function() {
+ }
+
+ cloneLetterDefinition() {
let copyLetterDefinitions = {};
for (let key in this._letterDefinitions) {
let value = new FontLetterDefinition();
@@ -59,15 +64,17 @@ cc.FontAtlas.prototype = {
copyLetterDefinitions[key] = value;
}
return copyLetterDefinitions;
- },
- assignLetterDefinitions: function(letterDefinition) {
+ }
+
+ assignLetterDefinitions(letterDefinition) {
for (let key in this._letterDefinitions) {
let newValue = letterDefinition[key];
let oldValue = this._letterDefinitions[key];
cc.js.mixin(oldValue, newValue);
}
- },
- scaleFontLetterDefinition: function(scaleFactor) {
+ }
+
+ scaleFontLetterDefinition(scaleFactor) {
for (let fontDefinition in this._letterDefinitions) {
let letterDefinitions = this._letterDefinitions[fontDefinition];
letterDefinitions._width *= scaleFactor;
@@ -76,8 +83,9 @@ cc.FontAtlas.prototype = {
letterDefinitions._offsetY *= scaleFactor;
letterDefinitions._xAdvance *= scaleFactor;
}
- },
- getLetterDefinitionForChar: function(char) {
+ }
+
+ getLetterDefinitionForChar(char) {
let hasKey = this._letterDefinitions.hasOwnProperty(char.charCodeAt(0));
let letterDefinition;
if (hasKey) {
@@ -87,9 +95,11 @@ cc.FontAtlas.prototype = {
}
return letterDefinition;
}
-};
+}
-let LetterInfo = function() {
+cc.FontAtlas = FontAtlas;
+
+let LetterInfo = function () {
this._char = '';
this._valid = true;
this._positionX = 0;
@@ -110,12 +120,12 @@ let _labelDimensions = cc.size();
let _fontAtlas = null;
let _fntConfig = null;
let _numberOfLines = 0;
-let _textDesiredHeight = 0;
-let _letterOffsetY = 0;
-let _tailoredTopY = 0;
-let _tailoredBottomY = 0;
-let _bmfontScale = 1.0;
-let _lineBreakWithoutSpaces = false;
+let _textDesiredHeight = 0;
+let _letterOffsetY = 0;
+let _tailoredTopY = 0;
+let _tailoredBottomY = 0;
+let _bmfontScale = 1.0;
+let _lineBreakWithoutSpaces = false;
let _spriteFrame = null;
let _lineSpacing = 0;
let _string = '';
@@ -132,39 +142,39 @@ let _labelWidth = 0;
let _labelHeight = 0;
let _maxLineWidth = 0;
-module.exports = {
- updateRenderData (comp) {
+let bmfont = {
+ updateRenderData(comp) {
if (!comp._renderData.vertDirty) return;
if (_comp === comp) return;
_comp = comp;
-
+
this._updateProperties();
this._updateContent();
-
+
_comp._actualFontSize = _fontSize;
_comp.node.setContentSize(_contentSize);
_comp._renderData.vertDirty = _comp._renderData.uvDirty = false;
_comp = null;
-
+
this._resetProperties();
},
- _updateFontScale () {
+ _updateFontScale() {
_bmfontScale = _fontSize / _originFontSize;
},
- _updateProperties () {
+ _updateProperties() {
let fontAsset = _comp.font;
_spriteFrame = fontAsset.spriteFrame;
_fntConfig = fontAsset._fntConfig;
_fontAtlas = _comp._fontAtlas;
if (!_fontAtlas) {
- _fontAtlas = new cc.FontAtlas(_fntConfig);
-
+ _fontAtlas = new FontAtlas(_fntConfig);
+
let fontDict = _fntConfig.fontDefDictionary;
for (let fontDef in fontDict) {
@@ -199,7 +209,7 @@ module.exports = {
_spacingX = _comp.spacingX;
_overflow = _comp.overflow;
_lineHeight = _comp._lineHeight;
-
+
// should wrap text
if (_overflow === Overflow.NONE) {
_isWrapText = false;
@@ -214,19 +224,19 @@ module.exports = {
this._setupBMFontOverflowMetrics();
},
- _resetProperties () {
+ _resetProperties() {
_fontAtlas = null;
_fntConfig = null;
_spriteFrame = null;
},
- _updateContent () {
+ _updateContent() {
this._updateFontScale();
this._computeHorizontalKerningForText();
this._alignText();
},
- _computeHorizontalKerningForText () {
+ _computeHorizontalKerningForText() {
let string = _string;
let stringLen = string.length;
@@ -246,7 +256,7 @@ module.exports = {
}
},
- _multilineTextWrap: function(nextTokenFunc) {
+ _multilineTextWrap(nextTokenFunc) {
let textLen = _string.length;
let lineIndex = 0;
@@ -384,11 +394,11 @@ module.exports = {
return true;
},
- _getFirstCharLen: function() {
+ _getFirstCharLen() {
return 1;
},
- _getFirstWordLen: function(text, startIndex, textLen) {
+ _getFirstWordLen(text, startIndex, textLen) {
let character = text.charAt(startIndex);
if (textUtils.isUnicodeCJK(character)
|| character === "\n"
@@ -412,9 +422,9 @@ module.exports = {
}
letterX = nextLetterX + letterDef._offsetX * _bmfontScale;
- if(letterX + letterDef._width * _bmfontScale > _maxLineWidth
- && !textUtils.isUnicodeSpace(character)
- && _maxLineWidth > 0) {
+ if (letterX + letterDef._width * _bmfontScale > _maxLineWidth
+ && !textUtils.isUnicodeSpace(character)
+ && _maxLineWidth > 0) {
return len;
}
nextLetterX += letterDef._xAdvance * _bmfontScale + _spacingX;
@@ -429,15 +439,15 @@ module.exports = {
return len;
},
- _multilineTextWrapByWord: function() {
+ _multilineTextWrapByWord() {
return this._multilineTextWrap(this._getFirstWordLen);
},
- _multilineTextWrapByChar: function() {
+ _multilineTextWrapByChar() {
return this._multilineTextWrap(this._getFirstCharLen);
},
- _recordPlaceholderInfo: function(letterIndex, char) {
+ _recordPlaceholderInfo(letterIndex, char) {
if (letterIndex >= _lettersInfo.length) {
let tmpInfo = new LetterInfo();
_lettersInfo.push(tmpInfo);
@@ -447,7 +457,7 @@ module.exports = {
_lettersInfo[letterIndex]._valid = false;
},
- _recordLetterInfo: function(letterDefinitions, letterPosition, character, letterIndex, lineIndex) {
+ _recordLetterInfo(letterDefinitions, letterPosition, character, letterIndex, lineIndex) {
if (letterIndex >= _lettersInfo.length) {
let tmpInfo = new LetterInfo();
_lettersInfo.push(tmpInfo);
@@ -461,7 +471,7 @@ module.exports = {
_lettersInfo[letterIndex]._positionY = letterPosition.y;
},
- _alignText: function() {
+ _alignText() {
_textDesiredHeight = 0;
_linesWidth.length = 0;
@@ -487,7 +497,7 @@ module.exports = {
}
},
- _scaleFontSizeDown (fontSize) {
+ _scaleFontSizeDown(fontSize) {
let shouldUpdateContent = true;
if (!fontSize) {
fontSize = 0.1;
@@ -500,11 +510,11 @@ module.exports = {
}
},
- _shrinkLabelToContentSize (lambda) {
+ _shrinkLabelToContentSize(lambda) {
let fontSize = _fontSize;
let originalLineHeight = _lineHeight;
let fontAtlas = _fontAtlas;
-
+
let i = 0;
let tempLetterDefinition = fontAtlas.cloneLetterDefinition();
let flag = true;
@@ -540,7 +550,7 @@ module.exports = {
}
},
- _isVerticalClamp () {
+ _isVerticalClamp() {
if (_textDesiredHeight > _contentSize.height) {
return true;
} else {
@@ -548,7 +558,7 @@ module.exports = {
}
},
- _isHorizontalClamp () {
+ _isHorizontalClamp() {
let letterDefinitions = _fontAtlas._letterDefinitions;
let letterClamp = false;
for (let ctr = 0, l = _string.length; ctr < l; ++ctr) {
@@ -560,11 +570,11 @@ module.exports = {
let lineIndex = letterInfo._lineIndex;
if (_labelWidth > 0) {
if (!_isWrapText) {
- if(px > _contentSize.width){
+ if (px > _contentSize.width) {
letterClamp = true;
break;
}
- }else{
+ } else {
let wordWidth = _linesWidth[lineIndex];
if (wordWidth > _contentSize.width && (px > _contentSize.width || px < 0)) {
letterClamp = true;
@@ -578,20 +588,20 @@ module.exports = {
return letterClamp;
},
- _isHorizontalClamped (px, lineIndex) {
+ _isHorizontalClamped(px, lineIndex) {
let wordWidth = _linesWidth[lineIndex];
let letterOverClamp = (px > _contentSize.width || px < 0);
- if(!_isWrapText){
+ if (!_isWrapText) {
return letterOverClamp;
- }else{
+ } else {
return (wordWidth > _contentSize.width && letterOverClamp);
}
},
- _updateQuads () {
+ _updateQuads() {
let letterDefinitions = _fontAtlas._letterDefinitions;
-
+
let texture = _spriteFrame._texture;
let node = _comp.node;
@@ -601,7 +611,7 @@ module.exports = {
let contentSize = _contentSize,
appx = node._anchorPoint.x * contentSize.width,
appy = node._anchorPoint.y * contentSize.height;
-
+
let ret = true;
for (let ctr = 0, l = _string.length; ctr < l; ++ctr) {
let letterInfo = _lettersInfo[ctr];
@@ -655,7 +665,7 @@ module.exports = {
let trimmedLeft = offset.x + (originalSize.width - rect.width) / 2;
let trimmedTop = offset.y - (originalSize.height - rect.height) / 2;
- if(!isRotated) {
+ if (!isRotated) {
_tmpRect.x += (rect.x - trimmedLeft);
_tmpRect.y += (rect.y + trimmedTop);
} else {
@@ -675,12 +685,12 @@ module.exports = {
return ret;
},
- appendQuad (renderData, texture, rect, rotated, x, y, scale) {
+ appendQuad(renderData, texture, rect, rotated, x, y, scale) {
},
- _computeAlignmentOffset: function() {
+ _computeAlignmentOffset() {
_linesOffsetX.length = 0;
-
+
switch (_hAlign) {
case macro.TextAlignment.LEFT:
for (let i = 0; i < _numberOfLines; ++i) {
@@ -716,7 +726,7 @@ module.exports = {
}
},
- _setupBMFontOverflowMetrics () {
+ _setupBMFontOverflowMetrics() {
let newWidth = _contentSize.width,
newHeight = _contentSize.height;
@@ -736,3 +746,5 @@ module.exports = {
_maxLineWidth = newWidth;
}
};
+
+export default bmfont;
diff --git a/cocos/2d/renderer/utils/label/ttf.js b/cocos/2d/renderer/utils/label/ttf.js
index 1c4e9b5611..787a04525e 100644
--- a/cocos/2d/renderer/utils/label/ttf.js
+++ b/cocos/2d/renderer/utils/label/ttf.js
@@ -23,14 +23,19 @@
THE SOFTWARE.
****************************************************************************/
-const macro = require('../../../platform/CCMacro');
-const textUtils = require('../../../utils/text-utils');
+// const macro = require('../../../platform/CCMacro');
+// const textUtils = require('../../../utils/text-utils');
-const Component = require('../../../components/CCComponent');
-const Label = require('../../../components/CCLabel');
-const LabelOutline = require('../../../components/CCLabelOutline');
-const Overflow = Label.Overflow;
+// const Component = require('../../../components/component');
+// const Label = require('../../../components/CCLabel');
+// const LabelOutline = require('../../../components/CCLabelOutline');
+import macro from '../../../../core/platform/CCMacro';
+import * as textUtils from '../../../../core/utils/text-utils';
+import Component from '../../../../components/component';
+import LabelComponent from '../../../../3d/ui/components/label-component';
+import LabelOutline from '../../../../2d/label/CCLabelOutline';
+const Overflow = LabelComponent.Overflow;
const WHITE = cc.Color.WHITE;
const OUTLINE_SUPPORTED = cc.js.isChildClassOf(LabelOutline, Component);
@@ -67,7 +72,7 @@ let _sharedLabelData;
//
let _canvasPool = {
pool: [],
- get () {
+ get() {
let data = this.pool.pop();
if (!data) {
@@ -81,7 +86,7 @@ let _canvasPool = {
return data;
},
- put (canvas) {
+ put(canvas) {
if (this.pool.length >= 32) {
return;
}
@@ -90,32 +95,31 @@ let _canvasPool = {
};
-module.exports = {
-
- _getAssemblerData () {
- if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) {
- _sharedLabelData = _canvasPool.get();
- }
- else {
- if (!_sharedLabelData) {
- let labelCanvas = document.createElement("canvas");
- _sharedLabelData = {
- canvas: labelCanvas,
- context: labelCanvas.getContext("2d")
- };
- }
- }
- _sharedLabelData.canvas.width = _sharedLabelData.canvas.height = 1;
- return _sharedLabelData;
+export default {
+ _getAssemblerData() {
+ // if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) {
+ // _sharedLabelData = _canvasPool.get();
+ // }
+ // else {
+ // if (!_sharedLabelData) {
+ let labelCanvas = document.createElement("canvas");
+ let sharedLabelData = {
+ canvas: labelCanvas,
+ context: labelCanvas.getContext("2d")
+ };
+ // }
+ // }
+ sharedLabelData.canvas.width = sharedLabelData.canvas.height = 1;
+ return sharedLabelData;
},
- _resetAssemblerData (assemblerData) {
+ _resetAssemblerData(assemblerData) {
if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS && assemblerData) {
_canvasPool.put(assemblerData);
}
},
- updateRenderData (comp) {
+ updateRenderData(comp) {
if (!comp._renderData.vertDirty) return;
this._updateFontFamly(comp);
@@ -138,10 +142,10 @@ module.exports = {
_texture = null;
},
- _updateVerts () {
+ _updateVerts() {
},
- _updateFontFamly (comp) {
+ _updateFontFamly(comp) {
if (!comp.useSystemFont) {
if (comp.font) {
if (comp.font._nativeAsset) {
@@ -163,12 +167,12 @@ module.exports = {
}
},
- _updateProperties (comp) {
+ _updateProperties(comp) {
let assemblerData = comp._assemblerData;
_context = assemblerData.context;
_canvas = assemblerData.canvas;
_texture = comp._texture;
-
+
_string = comp.string.toString();
_fontSize = comp._fontSize;
_drawFontsize = _fontSize;
@@ -178,7 +182,7 @@ module.exports = {
_lineHeight = comp._lineHeight;
_hAlign = comp.horizontalAlign;
_vAlign = comp.verticalAlign;
- _color = comp.node.color;
+ _color = comp._color;
_isBold = comp._isBold;
_isItalic = comp._isItalic;
_isUnderline = comp._isUnderline;
@@ -208,7 +212,7 @@ module.exports = {
}
},
- _calculateFillTextStartPosition () {
+ _calculateFillTextStartPosition() {
let lineHeight = this._getLineHeight();
let lineCount = _splitedStrings.length;
let labelX;
@@ -237,7 +241,7 @@ module.exports = {
return cc.v2(labelX, firstLinelabelY);
},
- _updateTexture () {
+ _updateTexture() {
_context.clearRect(0, 0, _canvas.width, _canvas.height);
_context.font = _fontDesc;
@@ -271,10 +275,11 @@ module.exports = {
}
}
- _texture.handleLoadedTexture();
+ // _texture.handleLoadedTexture();
+ _texture.mipmaps = [_texture.image];
},
- _calculateUnderlineStartPosition () {
+ _calculateUnderlineStartPosition() {
let lineHeight = this._getLineHeight();
let lineCount = _splitedStrings.length;
let labelX;
@@ -295,7 +300,7 @@ module.exports = {
return cc.v2(labelX, firstLinelabelY);
},
- _updateLabelDimensions () {
+ _updateLabelDimensions() {
let paragraphedStrings = _string.split('\n');
if (_overflow === Overflow.RESIZE_HEIGHT) {
@@ -323,7 +328,7 @@ module.exports = {
_canvas.height = _canvasSize.height;
},
- _calculateTextBaseline () {
+ _calculateTextBaseline() {
let node = this._node;
let hAlign;
let vAlign;
@@ -351,7 +356,7 @@ module.exports = {
_context.textBaseline = vAlign;
},
- _calculateSplitedStrings () {
+ _calculateSplitedStrings() {
let paragraphedStrings = _string.split('\n');
if (_isWrapText) {
@@ -360,9 +365,9 @@ module.exports = {
for (let i = 0; i < paragraphedStrings.length; ++i) {
let allWidth = textUtils.safeMeasureText(_context, paragraphedStrings[i]);
let textFragment = textUtils.fragmentText(paragraphedStrings[i],
- allWidth,
- canvasWidthNoMargin,
- this._measureText(_context));
+ allWidth,
+ canvasWidthNoMargin,
+ this._measureText(_context));
_splitedStrings = _splitedStrings.concat(textFragment);
}
}
@@ -372,7 +377,7 @@ module.exports = {
},
- _getFontDesc () {
+ _getFontDesc() {
let fontDesc = _fontSize.toString() + 'px ';
fontDesc = fontDesc + _fontFamily;
if (_isBold) {
@@ -382,7 +387,7 @@ module.exports = {
return fontDesc;
},
- _getLineHeight () {
+ _getLineHeight() {
let nodeSpacingY = _lineHeight;
if (nodeSpacingY === 0) {
nodeSpacingY = _fontSize;
@@ -393,7 +398,7 @@ module.exports = {
return nodeSpacingY | 0;
},
- _calculateParagraphLength (paragraphedStrings, ctx) {
+ _calculateParagraphLength(paragraphedStrings, ctx) {
let paragraphLength = [];
for (let i = 0; i < paragraphedStrings.length; ++i) {
@@ -404,20 +409,20 @@ module.exports = {
return paragraphLength;
},
- _measureText (ctx) {
+ _measureText(ctx) {
return function (string) {
return textUtils.safeMeasureText(ctx, string);
};
},
- _calculateLabelFont () {
+ _calculateLabelFont() {
_fontDesc = this._getFontDesc();
_context.font = _fontDesc;
if (_overflow === Overflow.SHRINK) {
let paragraphedStrings = _string.split('\n');
let paragraphLength = this._calculateParagraphLength(paragraphedStrings, _context);
-
+
_splitedStrings = paragraphedStrings;
let i = 0;
let totalHeight = 0;
@@ -459,9 +464,9 @@ module.exports = {
let j = 0;
let allWidth = textUtils.safeMeasureText(_context, paragraphedStrings[i]);
textFragment = textUtils.fragmentText(paragraphedStrings[i],
- allWidth,
- canvasWidthNoMargin,
- this._measureText(_context));
+ allWidth,
+ canvasWidthNoMargin,
+ this._measureText(_context));
while (j < textFragment.length) {
let measureWidth = textUtils.safeMeasureText(_context, textFragment[j]);
maxLength = measureWidth;
diff --git a/cocos/2d/renderer/webgl/assemblers/sprite/radial-filled.js b/cocos/2d/renderer/webgl/assemblers/sprite/radial-filled.js
deleted file mode 100644
index 3dca7ed1ef..0000000000
--- a/cocos/2d/renderer/webgl/assemblers/sprite/radial-filled.js
+++ /dev/null
@@ -1,364 +0,0 @@
-/****************************************************************************
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos.com
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
-
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
-
-const PI_2 = Math.PI * 2;
-
-module.exports = {
- useModel: false,
-
- _vertPos: [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)],
- _vertices: [0, 0, 0, 0],
- _uvs: [0, 0, 0, 0, 0, 0, 0, 0],
- _intersectPoint_1: [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)],
- _intersectPoint_2: [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)],
- _center: cc.v2(0, 0),
- _triangles: [],
-
- createData (sprite) {
- return sprite.requestRenderData();
- },
-
- updateRenderData (sprite) {
- let frame = sprite.spriteFrame;
-
- // TODO: Material API design and export from editor could affect the material activation process
- // need to update the logic here
- if (frame) {
- if (!frame._original && dynamicAtlasManager) {
- dynamicAtlasManager.insertSpriteFrame(frame);
- }
- if (sprite._material._texture !== frame._texture) {
- sprite._activateMaterial();
- }
- }
-
- let renderData = sprite._renderData;
- if (renderData && frame) {
- if (renderData.vertDirty || renderData.uvDirty) {
- let data = renderData._data;
-
- let fillStart = sprite._fillStart;
- let fillRange = sprite._fillRange;
- if (fillRange < 0) {
- fillStart += fillRange;
- fillRange = -fillRange;
- }
-
- //do round fill start [0,1), include 0, exclude 1
- while (fillStart >= 1.0) fillStart -= 1.0;
- while (fillStart < 0.0) fillStart += 1.0;
-
- fillStart *= PI_2;
- fillRange *= PI_2;
- let fillEnd = fillStart + fillRange;
-
- //build vertices
- this._calculateVertices(sprite);
- //build uvs
- this._calculateUVs(frame);
-
- let center = this._center;
-
- let vertPos = this._vertPos,
- vertices = this._vertices;
-
- let triangles = this._triangles;
-
- this._calcInsectedPoints(vertices[0], vertices[2], vertices[1], vertices[3], center, fillStart, this._intersectPoint_1);
- this._calcInsectedPoints(vertices[0], vertices[2], vertices[1], vertices[3], center, fillStart + fillRange, this._intersectPoint_2);
-
- let offset = 0;
- for (let triangleIndex = 0; triangleIndex < 4; ++triangleIndex) {
- let triangle = triangles[triangleIndex];
- if (!triangle) {
- continue;
- }
- //all in
- if (fillRange >= PI_2) {
- renderData.dataLength = offset + 3;
- this._generateTriangle(data, offset, center, vertPos[triangle[0]], vertPos[triangle[1]]);
- offset += 3;
- continue;
- }
- //test against
- let startAngle = this._getVertAngle(center, vertPos[triangle[0]]);
- let endAngle = this._getVertAngle(center, vertPos[triangle[1]]);
- if(endAngle < startAngle) endAngle += PI_2;
- startAngle -= PI_2;
- endAngle -= PI_2;
- //testing
- for(let testIndex = 0; testIndex < 3; ++testIndex) {
- if(startAngle >= fillEnd) {
- //all out
- } else if (startAngle >= fillStart) {
- renderData.dataLength = offset + 3;
- if(endAngle >= fillEnd) {
- //startAngle to fillEnd
- this._generateTriangle(data, offset, center, vertPos[triangle[0]], this._intersectPoint_2[triangleIndex]);
- } else {
- //startAngle to endAngle
- this._generateTriangle(data, offset, center, vertPos[triangle[0]], vertPos[triangle[1]]);
- }
- offset += 3;
- } else {
- //startAngle < fillStart
- if(endAngle <= fillStart) {
- //all out
- } else if(endAngle <= fillEnd) {
- renderData.dataLength = offset + 3;
- //fillStart to endAngle
- this._generateTriangle(data, offset, center, this._intersectPoint_1[triangleIndex], vertPos[triangle[1]]);
- offset += 3;
- } else {
- renderData.dataLength = offset + 3;
- //fillStart to fillEnd
- this._generateTriangle(data, offset, center, this._intersectPoint_1[triangleIndex], this._intersectPoint_2[triangleIndex]);
- offset += 3;
- }
- }
- //add 2 * PI
- startAngle += PI_2;
- endAngle += PI_2;
- }
- }
-
- renderData.indiceCount = renderData.vertexCount = offset;
- renderData.vertDirty = renderData.uvDirty = false;
- }
- }
- },
-
- _getVertAngle: function(start, end) {
- let placementX, placementY;
- placementX = end.x - start.x;
- placementY = end.y - start.y;
-
- if(placementX === 0 && placementY === 0) {
- return undefined;
- } else if(placementX === 0) {
- if(placementY > 0) {
- return Math.PI * 0.5;
- } else {
- return Math.PI * 1.5;
- }
- } else {
- let angle = Math.atan(placementY / placementX);
- if(placementX < 0) {
- angle += Math.PI;
- }
-
- return angle;
- }
- },
-
- _generateTriangle: function(data, offset, vert0, vert1, vert2) {
- let vertices = this._vertices;
- let v0x = vertices[0];
- let v0y = vertices[1];
- let v1x = vertices[2];
- let v1y = vertices[3];
-
- data[offset].x = vert0.x;
- data[offset].y = vert0.y;
- data[offset+1].x = vert1.x;
- data[offset+1].y = vert1.y;
- data[offset+2].x = vert2.x;
- data[offset+2].y = vert2.y;
-
- let progressX, progressY;
- progressX = (vert0.x - v0x) / (v1x - v0x);
- progressY = (vert0.y - v0y) / (v1y - v0y);
- this._generateUV(progressX, progressY, data, offset);
-
- progressX = (vert1.x - v0x) / (v1x - v0x);
- progressY = (vert1.y - v0y) / (v1y - v0y);
- this._generateUV(progressX, progressY, data, offset + 1);
-
- progressX = (vert2.x - v0x) / (v1x - v0x);
- progressY = (vert2.y - v0y) / (v1y - v0y);
- this._generateUV(progressX, progressY, data, offset + 2);
- },
-
- _generateUV : function(progressX, progressY, data, offset) {
- let uvs = this._uvs;
- let px1 = uvs[0] + (uvs[2] - uvs[0]) * progressX;
- let px2 = uvs[4] + (uvs[6] - uvs[4]) * progressX;
- let py1 = uvs[1] + (uvs[3] - uvs[1]) * progressX;
- let py2 = uvs[5] + (uvs[7] - uvs[5]) * progressX;
- let uv = data[offset];
- uv.u = px1 + (px2 - px1) * progressY;
- uv.v = py1 + (py2 - py1) * progressY;
- },
-
- _calcInsectedPoints: function(left, right, bottom, top, center, angle, intersectPoints) {
- //left bottom, right, top
- let sinAngle = Math.sin(angle);
- let cosAngle = Math.cos(angle);
- let tanAngle,cotAngle;
- if(Math.cos(angle) !== 0) {
- tanAngle = sinAngle / cosAngle;
- //calculate right and left
- if((left - center.x) * cosAngle > 0) {
- let yleft = center.y + tanAngle * (left - center.x);
- intersectPoints[0].x = left;
- intersectPoints[0].y = yleft;
- }
- if((right - center.x) * cosAngle > 0) {
- let yright = center.y + tanAngle * (right - center.x);
-
- intersectPoints[2].x = right;
- intersectPoints[2].y = yright;
- }
-
- }
-
- if(Math.sin(angle) !== 0) {
- cotAngle = cosAngle / sinAngle;
- //calculate top and bottom
- if((top - center.y) * sinAngle > 0) {
- let xtop = center.x + cotAngle * (top-center.y);
- intersectPoints[3].x = xtop;
- intersectPoints[3].y = top;
- }
- if((bottom - center.y) * sinAngle > 0) {
- let xbottom = center.x + cotAngle * (bottom-center.y);
- intersectPoints[1].x = xbottom;
- intersectPoints[1].y = bottom;
- }
-
- }
- },
-
- _calculateVertices : function (sprite) {
- let node = sprite.node,
- width = node.width, height = node.height,
- appx = node.anchorX * width, appy = node.anchorY * height;
-
- let l = -appx, b = -appy,
- r = width-appx, t = height-appy;
-
- let vertices = this._vertices;
- vertices[0] = l;
- vertices[1] = b;
- vertices[2] = r;
- vertices[3] = t;
-
- let center = this._center,
- fillCenter = sprite._fillCenter,
- cx = center.x = Math.min(Math.max(0, fillCenter.x), 1) * (r-l) + l,
- cy = center.y = Math.min(Math.max(0, fillCenter.y), 1) * (t-b) + b;
-
- let vertPos = this._vertPos;
- vertPos[0].x = vertPos[3].x = l;
- vertPos[1].x = vertPos[2].x = r;
- vertPos[0].y = vertPos[1].y = b;
- vertPos[2].y = vertPos[3].y = t;
-
- let triangles = this._triangles;
- triangles.length = 0;
- if(cx !== vertices[0]) {
- triangles[0] = [3, 0];
- }
- if(cx !== vertices[2]) {
- triangles[2] = [1, 2];
- }
- if(cy !== vertices[1]) {
- triangles[1] = [0, 1];
- }
- if(cy !== vertices[3]) {
- triangles[3] = [2, 3];
- }
- },
-
- _calculateUVs : function (spriteFrame) {
- let atlasWidth = spriteFrame._texture.width;
- let atlasHeight = spriteFrame._texture.height;
- let textureRect = spriteFrame._rect;
-
- let u0, u1, v0, v1;
- let uvs = this._uvs;
-
- if (spriteFrame._rotated) {
- u0 = (textureRect.x) / atlasWidth;
- u1 = (textureRect.x + textureRect.height) / atlasWidth;
-
- v0 = (textureRect.y) / atlasHeight;
- v1 = (textureRect.y + textureRect.width) / atlasHeight;
-
- uvs[0] = uvs[2] = u0;
- uvs[4] = uvs[6] = u1;
- uvs[3] = uvs[7] = v1;
- uvs[1] = uvs[5] = v0;
- }
- else {
- u0 = (textureRect.x) / atlasWidth;
- u1 = (textureRect.x + textureRect.width) / atlasWidth;
-
- v0 = (textureRect.y) / atlasHeight;
- v1 = (textureRect.y + textureRect.height) / atlasHeight;
-
- uvs[0] = uvs[4] = u0;
- uvs[2] = uvs[6] = u1;
- uvs[1] = uvs[3] = v1;
- uvs[5] = uvs[7] = v0;
- }
- },
-
- fillBuffers (sprite, renderer) {
- let renderData = sprite._renderData,
- data = renderData._data,
- node = sprite.node;
-
- let matrix = node._worldMatrix,
- a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05,
- tx = matrix.m12, ty = matrix.m13;
-
- // buffer
- let buffer = renderer._meshBuffer,
- vertexOffset = buffer.byteOffset >> 2,
- vbuf = buffer._vData;
-
- let ibuf = buffer._iData,
- indiceOffset = buffer.indiceOffset,
- vertexId = buffer.vertexOffset;
-
- buffer.request(renderData.vertexCount, renderData.indiceCount);
-
- let count = data.length;
- for (let i = 0; i < count; i++) {
- let vert = data[i];
- vbuf[vertexOffset ++] = vert.x * a + vert.y * c + tx;
- vbuf[vertexOffset ++] = vert.x * b + vert.y * d + ty;
- vbuf[vertexOffset ++] = vert.u;
- vbuf[vertexOffset ++] = vert.v;
- }
-
- for (let i = 0; i < count; i++) {
- ibuf[indiceOffset+i] = vertexId+i;
- }
- },
-};
diff --git a/cocos/2d/renderer/webgl/assemblers/sprite/simple.js b/cocos/2d/renderer/webgl/assemblers/sprite/simple.js
deleted file mode 100644
index d684b2c021..0000000000
--- a/cocos/2d/renderer/webgl/assemblers/sprite/simple.js
+++ /dev/null
@@ -1,150 +0,0 @@
-/****************************************************************************
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos.com
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
-
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
-
-module.exports = {
- useModel: false,
-
- updateRenderData (sprite) {
- let frame = sprite._spriteFrame;
-
- // TODO: Material API design and export from editor could affect the material activation process
- // need to update the logic here
- if (frame) {
- if (!frame._original && dynamicAtlasManager) {
- dynamicAtlasManager.insertSpriteFrame(frame);
- }
- if (sprite._material._texture !== frame._texture) {
- sprite._activateMaterial();
- }
- }
-
- let renderData = sprite._renderData;
- if (renderData && frame) {
- if (renderData.vertDirty) {
- this.updateVerts(sprite);
- }
- }
- },
-
- fillBuffers (sprite, renderer) {
- let data = sprite._renderData._data,
- node = sprite.node,
- matrix = node._worldMatrix,
- a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05,
- tx = matrix.m12, ty = matrix.m13;
-
- let buffer = renderer._quadBuffer,
- vertexOffset = buffer.byteOffset >> 2;
-
- buffer.request(4, 6);
-
- // buffer data may be realloc, need get reference after request.
- let vbuf = buffer._vData;
-
- // get uv from sprite frame directly
- let uv = sprite._spriteFrame.uv;
- vbuf[vertexOffset+2] = uv[0];
- vbuf[vertexOffset+3] = uv[1];
- vbuf[vertexOffset+6] = uv[2];
- vbuf[vertexOffset+7] = uv[3];
- vbuf[vertexOffset+10] = uv[4];
- vbuf[vertexOffset+11] = uv[5];
- vbuf[vertexOffset+14] = uv[6];
- vbuf[vertexOffset+15] = uv[7];
-
- let data0 = data[0], data3 = data[3],
- vl = data0.x, vr = data3.x,
- vb = data0.y, vt = data3.y;
-
- let al = a * vl, ar = a * vr,
- bl = b * vl, br = b * vr,
- cb = c * vb, ct = c * vt,
- db = d * vb, dt = d * vt;
-
- // left bottom
- vbuf[vertexOffset] = al + cb + tx;
- vbuf[vertexOffset+1] = bl + db + ty;
- // right bottom
- vbuf[vertexOffset+4] = ar + cb + tx;
- vbuf[vertexOffset+5] = br + db + ty;
- // left top
- vbuf[vertexOffset+8] = al + ct + tx;
- vbuf[vertexOffset+9] = bl + dt + ty;
- // right top
- vbuf[vertexOffset+12] = ar + ct + tx;
- vbuf[vertexOffset+13] = br + dt + ty;
- },
-
- createData (sprite) {
- let renderData = sprite.requestRenderData();
- renderData.dataLength = 4;
- renderData.vertexCount = 4;
- renderData.indiceCount = 6;
- return renderData;
- },
-
- updateVerts (sprite) {
- let renderData = sprite._renderData,
- node = sprite.node,
- data = renderData._data,
- cw = node.width, ch = node.height,
- appx = node.anchorX * cw, appy = node.anchorY * ch,
- l, b, r, t;
- if (sprite.trim) {
- l = -appx;
- b = -appy;
- r = cw - appx;
- t = ch - appy;
- }
- else {
- let frame = sprite.spriteFrame,
- ow = frame._originalSize.width, oh = frame._originalSize.height,
- rw = frame._rect.width, rh = frame._rect.height,
- offset = frame._offset,
- scaleX = cw / ow, scaleY = ch / oh;
- let trimLeft = offset.x + (ow - rw) / 2;
- let trimRight = offset.x - (ow - rw) / 2;
- let trimBottom = offset.y + (oh - rh) / 2;
- let trimTop = offset.y - (oh - rh) / 2;
- l = trimLeft * scaleX - appx;
- b = trimBottom * scaleY - appy;
- r = cw + trimRight * scaleX - appx;
- t = ch + trimTop * scaleY - appy;
- }
-
- data[0].x = l;
- data[0].y = b;
- // data[1].x = r;
- // data[1].y = b;
- // data[2].x = l;
- // data[2].y = t;
- data[3].x = r;
- data[3].y = t;
-
- renderData.vertDirty = false;
- }
-};
diff --git a/cocos/2d/renderer/webgl/assemblers/sprite/tiled.js b/cocos/2d/renderer/webgl/assemblers/sprite/tiled.js
deleted file mode 100644
index 9e60ca17d4..0000000000
--- a/cocos/2d/renderer/webgl/assemblers/sprite/tiled.js
+++ /dev/null
@@ -1,190 +0,0 @@
-/****************************************************************************
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos.com
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
-
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
-
-module.exports = {
- useModel: false,
-
- createData (sprite) {
- return sprite.requestRenderData();
- },
-
- updateRenderData (sprite) {
- let frame = sprite.spriteFrame;
-
- // TODO: Material API design and export from editor could affect the material activation process
- // need to update the logic here
- if (frame) {
- if (!frame._original && dynamicAtlasManager) {
- dynamicAtlasManager.insertSpriteFrame(frame);
- }
- if (sprite._material._texture !== frame._texture) {
- sprite._activateMaterial();
- }
- }
-
- let renderData = sprite._renderData;
- if (!frame || !renderData ||
- !(renderData.uvDirty || renderData.vertDirty))
- return;
-
- let texture = frame._texture;
- let texw = texture.width,
- texh = texture.height,
- rect = frame._rect;
-
- let node = sprite.node,
- contentWidth = Math.abs(node.width),
- contentHeight = Math.abs(node.height),
- appx = node.anchorX * contentWidth,
- appy = node.anchorY * contentHeight;
-
- let rectWidth = rect.width,
- rectHeight = rect.height,
- hRepeat = contentWidth / rectWidth,
- vRepeat = contentHeight / rectHeight,
- row = Math.ceil(vRepeat),
- col = Math.ceil(hRepeat);
-
- let data = renderData._data;
- renderData.dataLength = Math.max(8, row+1, col+1);
-
- for (let i = 0; i <= col; ++i) {
- data[i].x = Math.min(rectWidth * i, contentWidth) - appx;
- }
- for (let i = 0; i <= row; ++i) {
- data[i].y = Math.min(rectHeight * i, contentHeight) - appy;
- }
-
- // update data property
- renderData.vertexCount = row * col * 4;
- renderData.indiceCount = row * col * 6;
- renderData.uvDirty = false;
- renderData.vertDirty = false;
- },
-
- fillBuffers (sprite, renderer) {
- let node = sprite.node,
- renderData = sprite._renderData,
- data = renderData._data;
-
- // buffer
- let buffer = renderer._meshBuffer,
- vertexOffset = buffer.byteOffset >> 2;
-
- let indiceOffset = buffer.indiceOffset,
- vertexId = buffer.vertexOffset;
-
- buffer.request(renderData.vertexCount, renderData.indiceCount);
-
- // buffer data may be realloc, need get reference after request.
- let vbuf = buffer._vData,
- ibuf = buffer._iData;
-
- let rotated = sprite.spriteFrame._rotated;
- let uv = sprite.spriteFrame.uv;
- let rect = sprite.spriteFrame._rect;
- let contentWidth = Math.abs(node.width);
- let contentHeight = Math.abs(node.height);
- let hRepeat = contentWidth / rect.width;
- let vRepeat = contentHeight / rect.height;
- let row = Math.ceil(vRepeat),
- col = Math.ceil(hRepeat);
-
- let matrix = node._worldMatrix;
- let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05,
- tx = matrix.m12, ty = matrix.m13;
-
- let x, x1, y, y1, coefu, coefv;
- for (let yindex = 0, ylength = row; yindex < ylength; ++yindex) {
- y = data[yindex].y;
- y1 = data[yindex+1].y;
- coefv = Math.min(1, vRepeat - yindex);
- for (let xindex = 0, xlength = col; xindex < xlength; ++xindex) {
- coefu = Math.min(1, hRepeat - xindex);
- x = data[xindex].x;
- x1 = data[xindex+1].x;
-
- // Vertex
- // lb
- vbuf[vertexOffset] = x * a + y * c + tx;
- vbuf[vertexOffset+1] = x * b + y * d + ty;
- // rb
- vbuf[vertexOffset+4] = x1 * a + y * c + tx;
- vbuf[vertexOffset+5] = x1 * b + y * d + ty;
- // lt
- vbuf[vertexOffset+8] = x * a + y1 * c + tx;
- vbuf[vertexOffset+9] = x * b + y1 * d + ty;
- // rt
- vbuf[vertexOffset+12] = x1 * a + y1 * c + tx;
- vbuf[vertexOffset+13] = x1 * b + y1 * d + ty;
-
- // UV
- if (rotated) {
- // lb
- vbuf[vertexOffset+2] = uv[0];
- vbuf[vertexOffset+3] = uv[1];
- // rb
- vbuf[vertexOffset+6] = uv[0];
- vbuf[vertexOffset+7] = uv[1] + (uv[7] - uv[1]) * coefu;
- // lt
- vbuf[vertexOffset+10] = uv[0] + (uv[6] - uv[0]) * coefv;
- vbuf[vertexOffset+11] = uv[1];
- // rt
- vbuf[vertexOffset+14] = vbuf[vertexOffset+10];
- vbuf[vertexOffset+15] = vbuf[vertexOffset+7];
- }
- else {
- // lb
- vbuf[vertexOffset+2] = uv[0];
- vbuf[vertexOffset+3] = uv[1];
- // rb
- vbuf[vertexOffset+6] = uv[0] + (uv[6] - uv[0]) * coefu;
- vbuf[vertexOffset+7] = uv[1];
- // lt
- vbuf[vertexOffset+10] = uv[0];
- vbuf[vertexOffset+11] = uv[1] + (uv[7] - uv[1]) * coefv;
- // rt
- vbuf[vertexOffset+14] = vbuf[vertexOffset+6];
- vbuf[vertexOffset+15] = vbuf[vertexOffset+11];
- }
- vertexOffset += 16;
- }
- }
-
- // update indices
- let length = renderData.indiceCount;
- for (let i = 0; i < length; i+=6) {
- ibuf[indiceOffset++] = vertexId;
- ibuf[indiceOffset++] = vertexId+1;
- ibuf[indiceOffset++] = vertexId+2;
- ibuf[indiceOffset++] = vertexId+1;
- ibuf[indiceOffset++] = vertexId+3;
- ibuf[indiceOffset++] = vertexId+2;
- vertexId += 4;
- }
- },
-};
\ No newline at end of file
diff --git a/cocos/2d/ui/CCButton.js b/cocos/2d/ui/CCButton.js
deleted file mode 100644
index 0c3163fc45..0000000000
--- a/cocos/2d/ui/CCButton.js
+++ /dev/null
@@ -1,687 +0,0 @@
-/****************************************************************************
- Copyright (c) 2013-2016 Chukong Technologies Inc.
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos.com
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
-
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-const Component = require('./CCComponent');
-const misc = require('../utils/misc');
-
-/**
- * !#en Enum for transition type.
- * !#zh 过渡类型
- * @enum Button.Transition
- */
-let Transition = cc.Enum({
- /**
- * !#en The none type.
- * !#zh 不做任何过渡
- * @property {Number} NONE
- */
- NONE: 0,
-
- /**
- * !#en The color type.
- * !#zh 颜色过渡
- * @property {Number} COLOR
- */
- COLOR: 1,
-
- /**
- * !#en The sprite type.
- * !#zh 精灵过渡
- * @property {Number} SPRITE
- */
- SPRITE: 2,
- /**
- * !#en The scale type
- * !#zh 缩放过渡
- * @property {Number} SCALE
- */
- SCALE: 3
-});
-
-/**
- * !#en
- * Button has 4 Transition types
- * When Button state changed:
- * If Transition type is Button.Transition.NONE, Button will do nothing
- * If Transition type is Button.Transition.COLOR, Button will change target's color
- * If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite
- * If Transition type is Button.Transition.SCALE, Button will change target node's scale
- *
- * Button will trigger 5 events:
- * Button.EVENT_TOUCH_DOWN
- * Button.EVENT_TOUCH_UP
- * Button.EVENT_HOVER_IN
- * Button.EVENT_HOVER_MOVE
- * Button.EVENT_HOVER_OUT
- *
- * !#zh
- * 按钮组件。可以被按下,或者点击。
- *
- * 按钮可以通过修改 Transition 来设置按钮状态过渡的方式:
- * -Button.Transition.NONE // 不做任何过渡
- * -Button.Transition.COLOR // 进行颜色之间过渡
- * -Button.Transition.SPRITE // 进行精灵之间过渡
- * -Button.Transition.SCALE // 进行缩放过渡
- *
- * 按钮可以绑定事件(但是必须要在按钮的 Node 上才能绑定事件):
- * // 以下事件可以在全平台上都触发
- * -cc.Node.EventType.TOUCH_START // 按下时事件
- * -cc.Node.EventType.TOUCH_Move // 按住移动后事件
- * -cc.Node.EventType.TOUCH_END // 按下后松开后事件
- * -cc.Node.EventType.TOUCH_CANCEL // 按下取消事件
- * // 以下事件只在 PC 平台上触发
- * -cc.Node.EventType.MOUSE_DOWN // 鼠标按下时事件
- * -cc.Node.EventType.MOUSE_MOVE // 鼠标按住移动后事件
- * -cc.Node.EventType.MOUSE_ENTER // 鼠标进入目标事件
- * -cc.Node.EventType.MOUSE_LEAVE // 鼠标离开目标事件
- * -cc.Node.EventType.MOUSE_UP // 鼠标松开事件
- * -cc.Node.EventType.MOUSE_WHEEL // 鼠标滚轮事件
- *
- * @class Button
- * @extends Component
- * @example
- *
- * // Add an event to the button.
- * button.node.on(cc.Node.EventType.TOUCH_START, function (event) {
- * cc.log("This is a callback after the trigger event");
- * });
-
- * // You could also add a click event
- * //Note: In this way, you can't get the touch event info, so use it wisely.
- * button.node.on('click', function (button) {
- * //The event is a custom event, you could get the Button component via first argument
- * })
- *
- */
-let Button = cc.Class({
- name: 'cc.Button',
- extends: Component,
-
- ctor () {
- this._pressed = false;
- this._hovered = false;
- this._fromColor = null;
- this._toColor = null;
- this._time = 0;
- this._transitionFinished = true;
- this._fromScale = 1.0;
- this._toScale = 1.0;
- this._originalScale = 1.0;
-
- this._sprite = null;
-
- if (CC_EDITOR) {
- this._previousNormalSprite = null;
- }
- },
-
- editor: CC_EDITOR && {
- menu: 'i18n:MAIN_MENU.component.ui/Button',
- help: 'i18n:COMPONENT.help_url.button',
- inspector: 'packages://inspector/inspectors/comps/button.js',
- executeInEditMode: true
- },
-
- properties: {
- /**
- * !#en
- * Whether the Button is disabled.
- * If true, the Button will trigger event and do transition.
- * !#zh
- * 按钮事件是否被响应,如果为 false,则按钮将被禁用。
- * @property {Boolean} interactable
- * @default true
- */
- interactable: {
- default: true,
- tooltip: CC_DEV && 'i18n:COMPONENT.button.interactable',
- notify (oldValue) {
- if (CC_EDITOR) {
- if (oldValue) {
- this._previousNormalSprite = this.normalSprite;
- } else {
- this.normalSprite = this._previousNormalSprite;
- }
- }
- this._updateState();
-
- if (!this.interactable) {
- this._resetState();
- }
- },
- animatable: false
- },
-
- _resizeToTarget: {
- animatable: false,
- set (value) {
- if (value) {
- this._resizeNodeToTargetNode();
- }
- }
- },
-
- /**
- * !#en When this flag is true, Button target sprite will turn gray when interactable is false.
- * !#zh 如果这个标记为 true,当 button 的 interactable 属性为 false 的时候,会使用内置 shader 让 button 的 target 节点的 sprite 组件变灰
- * @property {Boolean} enableAutoGrayEffect
- */
- enableAutoGrayEffect: {
- default: false,
- tooltip: CC_DEV && 'i18n:COMPONENT.button.auto_gray_effect',
- notify () {
- this._updateDisabledState();
- }
- },
-
- /**
- * !#en Transition type
- * !#zh 按钮状态改变时过渡方式。
- * @property {Button.Transition} transition
- * @default Button.Transition.Node
- */
- transition: {
- default: Transition.NONE,
- tooltip: CC_DEV && 'i18n:COMPONENT.button.transition',
- type: Transition,
- animatable: false
- },
-
- // color transition
-
- /**
- * !#en Normal state color.
- * !#zh 普通状态下按钮所显示的颜色。
- * @property {Color} normalColor
- */
- normalColor: {
- default: cc.color(214, 214, 214),
- displayName: 'Normal',
- tooltip: CC_DEV && 'i18n:COMPONENT.button.normal_color',
- notify () {
- this._updateState();
- }
- },
-
- /**
- * !#en Pressed state color
- * !#zh 按下状态时按钮所显示的颜色。
- * @property {Color} pressedColor
- */
- pressedColor: {
- default: cc.color(211, 211, 211),
- displayName: 'Pressed',
- tooltip: CC_DEV && 'i18n:COMPONENT.button.pressed_color',
- },
-
- /**
- * !#en Hover state color
- * !#zh 悬停状态下按钮所显示的颜色。
- * @property {Color} hoverColor
- */
- hoverColor: {
- default: cc.Color.WHITE,
- displayName: 'Hover',
- tooltip: CC_DEV && 'i18n:COMPONENT.button.hover_color',
- },
-
- /**
- * !#en Disabled state color
- * !#zh 禁用状态下按钮所显示的颜色。
- * @property {Color} disabledColor
- */
- disabledColor: {
- default: cc.color(124, 124, 124),
- displayName: 'Disabled',
- tooltip: CC_DEV && 'i18n:COMPONENT.button.disabled_color',
- notify () {
- this._updateState();
- }
- },
-
- /**
- * !#en Color and Scale transition duration
- * !#zh 颜色过渡和缩放过渡时所需时间
- * @property {Number} duration
- */
- duration: {
- default: 0.1,
- range: [0, 10],
- tooltip: CC_DEV && 'i18n:COMPONENT.button.duration',
- },
-
- /**
- * !#en When user press the button, the button will zoom to a scale.
- * The final scale of the button equals (button original scale * zoomScale)
- * !#zh 当用户点击按钮后,按钮会缩放到一个值,这个值等于 Button 原始 scale * zoomScale
- * @property {Number} zoomScale
- */
- zoomScale: {
- default: 1.2,
- tooltip: CC_DEV && 'i18n:COMPONENT.button.zoom_scale'
- },
-
- // sprite transition
- /**
- * !#en Normal state sprite
- * !#zh 普通状态下按钮所显示的 Sprite 。
- * @property {SpriteFrame} normalSprite
- */
- normalSprite: {
- default: null,
- type: cc.SpriteFrame,
- displayName: 'Normal',
- tooltip: CC_DEV && 'i18n:COMPONENT.button.normal_sprite',
- notify () {
- this._updateState();
- }
- },
-
- /**
- * !#en Pressed state sprite
- * !#zh 按下状态时按钮所显示的 Sprite 。
- * @property {SpriteFrame} pressedSprite
- */
- pressedSprite: {
- default: null,
- type: cc.SpriteFrame,
- displayName: 'Pressed',
- tooltip: CC_DEV && 'i18n:COMPONENT.button.pressed_sprite',
- formerlySerializedAs: 'pressedSprite',
- notify () {
- this._updateState();
- }
- },
-
- /**
- * !#en Hover state sprite
- * !#zh 悬停状态下按钮所显示的 Sprite 。
- * @property {SpriteFrame} hoverSprite
- */
- hoverSprite: {
- default: null,
- type: cc.SpriteFrame,
- displayName: 'Hover',
- tooltip: CC_DEV && 'i18n:COMPONENT.button.hover_sprite',
- formerlySerializedAs: 'hoverSprite',
- notify () {
- this._updateState();
- }
- },
-
- /**
- * !#en Disabled state sprite
- * !#zh 禁用状态下按钮所显示的 Sprite 。
- * @property {SpriteFrame} disabledSprite
- */
- disabledSprite: {
- default: null,
- type: cc.SpriteFrame,
- displayName: 'Disabled',
- tooltip: CC_DEV && 'i18n:COMPONENT.button.disabled_sprite',
- notify () {
- this._updateState();
- }
- },
-
- /**
- * !#en
- * Transition target.
- * When Button state changed:
- * If Transition type is Button.Transition.NONE, Button will do nothing
- * If Transition type is Button.Transition.COLOR, Button will change target's color
- * If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite
- * !#zh
- * 需要过渡的目标。
- * 当前按钮状态改变规则:
- * -如果 Transition type 选择 Button.Transition.NONE,按钮不做任何过渡。
- * -如果 Transition type 选择 Button.Transition.COLOR,按钮会对目标颜色进行颜色之间的过渡。
- * -如果 Transition type 选择 Button.Transition.Sprite,按钮会对目标 Sprite 进行 Sprite 之间的过渡。
- * @property {Node} target
- */
- target: {
- default: null,
- type: cc.Node,
- tooltip: CC_DEV && "i18n:COMPONENT.button.target",
- notify () {
- this._applyTarget();
- }
- },
-
- /**
- * !#en If Button is clicked, it will trigger event's handler
- * !#zh 按钮的点击事件列表。
- * @property {Component.EventHandler[]} clickEvents
- */
- clickEvents: {
- default: [],
- type: cc.Component.EventHandler,
- tooltip: CC_DEV && 'i18n:COMPONENT.button.click_events',
- }
- },
-
- statics: {
- Transition: Transition,
- },
-
- __preload () {
- if (!this.target) {
- this.target = this.node;
- }
- this._applyTarget();
- this._updateState();
- },
-
- _resetState () {
- this._pressed = false;
- this._hovered = false;
- // // Restore button status
- let target = this.target;
- let transition = this.transition;
- if (transition === Transition.COLOR && this.interactable) {
- target.color = this.normalColor;
- } else if (transition === Transition.SCALE) {
- target.scale = this._originalScale;
- }
- this._transitionFinished = true;
- },
-
- onEnable () {
- // check sprite frames
- if (this.normalSprite) {
- this.normalSprite.ensureLoadTexture();
- }
- if (this.hoverSprite) {
- this.hoverSprite.ensureLoadTexture();
- }
- if (this.pressedSprite) {
- this.pressedSprite.ensureLoadTexture();
- }
- if (this.disabledSprite) {
- this.disabledSprite.ensureLoadTexture();
- }
- //
- if (!CC_EDITOR) {
- this._registerEvent();
- } else {
- this.node.on('spriteframe-changed', function (comp) {
- if (this.transition === Transition.SPRITE) {
- this.normalSprite = comp.spriteFrame;
- }
- }.bind(this));
- }
- },
-
- onDisable () {
- this._resetState();
-
- if (!CC_EDITOR) {
- this.node.off(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this);
- this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMove, this);
- this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
- this.node.off(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancel, this);
-
- this.node.off(cc.Node.EventType.MOUSE_ENTER, this._onMouseMoveIn, this);
- this.node.off(cc.Node.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this);
- } else {
- this.node.off('spriteframe-changed');
- }
- },
-
- update (dt) {
- let target = this.target;
- if (this._transitionFinished) return;
- if (this.transition !== Transition.COLOR && this.transition !== Transition.SCALE) return;
-
- this.time += dt;
- let ratio = 1.0;
- if (this.duration > 0) {
- ratio = this.time / this.duration;
- }
-
- if (ratio >= 1) {
- ratio = 1;
- this._transitionFinished = true;
- }
-
- if (this.transition === Transition.COLOR) {
- target.color = this._fromColor.lerp(this._toColor, ratio);
- } else if (this.transition === Transition.SCALE) {
- target.scale = misc.lerp(this._fromScale, this._toScale, ratio);
- }
-
- },
-
- _registerEvent () {
- this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this);
- this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMove, this);
- this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
- this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancel, this);
-
- this.node.on(cc.Node.EventType.MOUSE_ENTER, this._onMouseMoveIn, this);
- this.node.on(cc.Node.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this);
- },
-
- _getTargetSprite (target) {
- let sprite = null;
- if (target) {
- sprite = target.getComponent(cc.Sprite);
- }
- return sprite;
- },
-
- _applyTarget () {
- this._sprite = this._getTargetSprite(this.target);
- if (this.target) {
- this._originalScale = this.target.scale;
- }
- },
-
- // touch event handler
- _onTouchBegan (event) {
- if (!this.interactable || !this.enabledInHierarchy) return;
-
- this._pressed = true;
- this._updateState();
- event.stopPropagation();
- },
-
- _onTouchMove (event) {
- if (!this.interactable || !this.enabledInHierarchy || !this._pressed) return;
- // mobile phone will not emit _onMouseMoveOut,
- // so we have to do hit test when touch moving
- let touch = event.touch;
- let hit = this.node._hitTest(touch.getLocation());
-
- if (this.transition === Transition.SCALE && this.target) {
- if (hit) {
- this._fromScale = this._originalScale;
- this._toScale = this._originalScale * this.zoomScale;
- this._transitionFinished = false;
- } else {
- this.time = 0;
- this._transitionFinished = true;
- this.target.scale = this._originalScale;
- }
- } else {
- let state;
- if (hit) {
- state = 'pressed';
- } else {
- state = 'normal';
- }
- this._applyTransition(state);
- }
- event.stopPropagation();
- },
-
- _onTouchEnded (event) {
- if (!this.interactable || !this.enabledInHierarchy) return;
-
- if (this._pressed) {
- cc.Component.EventHandler.emitEvents(this.clickEvents, event);
- this.node.emit('click', this);
- }
- this._pressed = false;
- this._updateState();
- event.stopPropagation();
- },
-
- _onTouchCancel () {
- if (!this.interactable || !this.enabledInHierarchy) return;
-
- this._pressed = false;
- this._updateState();
- },
-
- _onMouseMoveIn () {
- if (this._pressed || !this.interactable || !this.enabledInHierarchy) return;
- if (this.transition === Transition.SPRITE && !this.hoverSprite) return;
-
- if (!this._hovered) {
- this._hovered = true;
- this._updateState();
- }
- },
-
- _onMouseMoveOut () {
- if (this._hovered) {
- this._hovered = false;
- this._updateState();
- }
- },
-
- // state handler
- _updateState () {
- let state = this._getButtonState();
- this._applyTransition(state);
- this._updateDisabledState();
- },
-
- _getButtonState () {
- let state;
- if (!this.interactable) {
- state = 'disabled';
- }
- else if (this._pressed) {
- state = 'pressed';
- }
- else if (this._hovered) {
- state = 'hover';
- }
- else {
- state = 'normal';
- }
- return state;
- },
-
- _updateColorTransition (state) {
- let color = this[state + 'Color'];
- let target = this.target;
-
- if (CC_EDITOR) {
- target.color = color;
- }
- else {
- this._fromColor = target.color.clone();
- this._toColor = color;
- this.time = 0;
- this._transitionFinished = false;
- }
- },
-
- _updateSpriteTransition (state) {
- let sprite = this[state + 'Sprite'];
- if (this._sprite && sprite) {
- this._sprite.spriteFrame = sprite;
- }
- },
-
- _updateScaleTransition (state) {
- if (state === 'pressed') {
- this._zoomUp();
- } else {
- this._zoomBack();
- }
- },
-
- _zoomUp () {
- this._fromScale = this._originalScale;
- this._toScale = this._originalScale * this.zoomScale;
- this.time = 0;
- this._transitionFinished = false;
- },
-
- _zoomBack () {
- this._fromScale = this.target.scale;
- this._toScale = this._originalScale;
- this.time = 0;
- this._transitionFinished = false;
- },
-
- _applyTransition (state) {
- let transition = this.transition;
- if (transition === Transition.COLOR) {
- this._updateColorTransition(state);
- } else if (transition === Transition.SPRITE) {
- this._updateSpriteTransition(state);
- } else if (transition === Transition.SCALE) {
- this._updateScaleTransition(state);
- }
- },
-
- _resizeNodeToTargetNode: CC_EDITOR && function () {
- if (this.target) {
- this.node.setContentSize(this.target.getContentSize());
- }
- },
-
- _updateDisabledState () {
- if (this._sprite) {
- if (this.enableAutoGrayEffect) {
- if (!(this.transition === Transition.SPRITE && this.disabledSprite)) {
- if (!this.interactable) {
- this._sprite.setState(cc.Sprite.State.GRAY);
- return;
- }
- }
- }
- this._sprite.setState(cc.Sprite.State.NORMAL);
- }
- }
-});
-
-cc.Button = module.exports = Button;
-
-/**
- * !#en
- * Note: This event is emitted from the node to which the component belongs.
- * !#zh
- * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
- * @event click
- * @param {Event.EventCustom} event
- * @param {Button} button - The Button component.
- */
diff --git a/cocos/2d/ui/CCScrollBar.js b/cocos/2d/ui/CCScrollBar.js
index 070f28dbd3..abbf584406 100644
--- a/cocos/2d/ui/CCScrollBar.js
+++ b/cocos/2d/ui/CCScrollBar.js
@@ -24,8 +24,9 @@
THE SOFTWARE.
****************************************************************************/
-const misc = require('../utils/misc');
-const Component = require('./CCComponent');
+import Component from '../../components/CCComponent';
+import misc from '../../core/utils/misc';
+import { ccclass, menu, executionOrder, executeInEditMode, property } from '../../core/data/class-decorator';
var GETTINGSHORTERFACTOR = 20;
@@ -52,117 +53,137 @@ var Direction = cc.Enum({
* @class Scrollbar
* @extends Component
*/
-var Scrollbar = cc.Class({
- name: 'cc.Scrollbar',
- extends: require('./CCComponent'),
+@ccclass('cc.ScrollBarComponent')
+@executionOrder(100)
+@menu('UI/ScrollBar')
+// @executeInEditMode
+export default class ScrollBarComponent extends Component {
+ @property
+ _scrollView = null;
+ _touching = false;
+ _autoHideRemainingTime = 0;
+ @property
+ _handle = null;
+ @property
+ _direction = Direction.HORIZONTAL;
+ @property
+ _enableAutoHide = false;
+ @property
+ _autoHideTime = 1.0;
+ /**
+ * !#en The "handle" part of the scrollbar.
+ * !#zh 作为当前滚动区域位置显示的滑块 Sprite。
+ * @property {Sprite} handle
+ */
+ @property({
+ type: cc.Node
+ })
+ get handle() {
+ return this._handle;
+ }
- editor: CC_EDITOR && {
- menu: 'i18n:MAIN_MENU.component.ui/ScrollBar',
- help: 'i18n:COMPONENT.help_url.scrollbar',
- },
-
- properties: {
- _scrollView: null,
- _touching: false,
- _autoHideRemainingTime: {
- default: 0,
- serializable: false
- },
- _opacity: 255,
-
- /**
- * !#en The "handle" part of the scrollbar.
- * !#zh 作为当前滚动区域位置显示的滑块 Sprite。
- * @property {Sprite} handle
- */
- handle: {
- default: null,
- type: cc.Sprite,
- tooltip: CC_DEV && 'i18n:COMPONENT.scrollbar.handle',
- notify: function() {
- this._onScroll(cc.v2(0, 0));
- },
- animatable: false
- },
-
- /**
- * !#en The direction of scrollbar.
- * !#zh ScrollBar 的滚动方向。
- * @property {Scrollbar.Direction} direction
- */
- direction: {
- default: Direction.HORIZONTAL,
- type: Direction,
- tooltip: CC_DEV && 'i18n:COMPONENT.scrollbar.direction',
- notify: function() {
- this._onScroll(cc.v2(0, 0));
- },
- animatable: false
- },
-
- /**
- * !#en Whether enable auto hide or not.
- * !#zh 是否在没有滚动动作时自动隐藏 ScrollBar。
- * @property {Boolean} enableAutoHide
- */
- enableAutoHide: {
- default: true,
- animatable: false,
- tooltip: CC_DEV && 'i18n:COMPONENT.scrollbar.auto_hide',
- },
-
- /**
- * !#en
- * The time to hide scrollbar when scroll finished.
- * Note: This value is only useful when enableAutoHide is true.
- * !#zh
- * 没有滚动动作后经过多久会自动隐藏。
- * 注意:只要当 “enableAutoHide” 为 true 时,才有效。
- * @property {Number} autoHideTime
- */
- autoHideTime: {
- default: 1.0,
- animatable: false,
- tooltip: CC_DEV && 'i18n:COMPONENT.scrollbar.auto_hide_time',
+ set handle(value) {
+ value = value.getComponent(cc.RenderComponent);
+ if (this._handle === value) {
+ return
}
- },
+ this._handle = value;
+ this._onScroll(cc.v2(0, 0));
+ }
+ /**
+ * !#en The direction of scrollbar.
+ * !#zh ScrollBar 的滚动方向。
+ * @property {Scrollbar.Direction} direction
+ */
+ @property({
+ type: Direction
+ })
+ get direction() {
+ return this._direction;
+ }
- statics: {
- Direction: Direction
- },
+ set direction(value) {
+ if (this._direction === value) {
+ return;
+ }
- setTargetScrollView: function(scrollView) {
+ this._direction = value;
+ this._onScroll(cc.v2(0, 0));
+ }
+
+ /**
+ * !#en Whether enable auto hide or not.
+ * !#zh 是否在没有滚动动作时自动隐藏 ScrollBar。
+ * @property {Boolean} enableAutoHide
+ */
+ get enableAutoHide() {
+ return this._enableAutoHide;
+ }
+
+ set enableAutoHide(value) {
+ if (this._enableAutoHide === value) {
+ return;
+ }
+
+ this._enableAutoHide = value;
+ }
+
+ /**
+ * !#en
+ * The time to hide scrollbar when scroll finished.
+ * Note: This value is only useful when enableAutoHide is true.
+ * !#zh
+ * 没有滚动动作后经过多久会自动隐藏。
+ * 注意:只要当 “enableAutoHide” 为 true 时,才有效。
+ * @property {Number} autoHideTime
+ */
+ @property
+ get autoHideTime() {
+ return this._autoHideTime;
+ }
+
+ set autoHideTime(value) {
+ if (this._autoHideTime === value) {
+ return;
+ }
+
+ this._autoHideTime = value;
+ }
+
+ static Direction = Direction;
+
+ setTargetScrollView(scrollView) {
this._scrollView = scrollView;
- },
+ }
- _convertToScrollViewSpace: function(content) {
+ _convertToScrollViewSpace(content) {
var worldSpacePos = content.convertToWorldSpace(cc.v2(0, 0));
var scrollViewSpacePos = this._scrollView.node.convertToNodeSpace(worldSpacePos);
return scrollViewSpacePos;
- },
+ }
- _setOpacity: function(opacity) {
- if (this.handle) {
- this.node.opacity = opacity;
- this.handle.node.opacity = opacity;
- }
- },
+ // _setOpacity(opacity) {
+ // if (this._handle) {
+ // this.node.opacity = opacity;
+ // this._handle.node.opacity = opacity;
+ // }
+ // }
- _onScroll: function(outOfBoundary) {
+ _onScroll(outOfBoundary) {
if (this._scrollView) {
var content = this._scrollView.content;
- if(content){
+ if (content) {
var contentSize = content.getContentSize();
var scrollViewSize = this._scrollView.node.getContentSize();
var handleNodeSize = this.node.getContentSize();
- if(this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
+ if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
return;
}
- if (this.enableAutoHide) {
- this._autoHideRemainingTime = this.autoHideTime;
+ if (this._enableAutoHide) {
+ this._autoHideRemainingTime = this._autoHideTime;
this._setOpacity(this._opacity);
}
@@ -172,14 +193,14 @@ var Scrollbar = cc.Class({
var contentPosition = 0;
var handleNodeMeasure = 0;
- if (this.direction === Direction.HORIZONTAL) {
+ if (this._direction === Direction.HORIZONTAL) {
contentMeasure = contentSize.width;
scrollViewMeasure = scrollViewSize.width;
handleNodeMeasure = handleNodeSize.width;
outOfBoundaryValue = outOfBoundary.x;
contentPosition = -this._convertToScrollViewSpace(content).x;
- } else if (this.direction === Direction.VERTICAL) {
+ } else if (this._direction === Direction.VERTICAL) {
contentMeasure = contentSize.height;
scrollViewMeasure = scrollViewSize.height;
handleNodeMeasure = handleNodeSize.height;
@@ -195,85 +216,85 @@ var Scrollbar = cc.Class({
this._updateHanlderPosition(position);
}
}
- },
+ }
- _updateHanlderPosition: function(position) {
- if (this.handle) {
+ _updateHanlderPosition(position) {
+ if (this._handle) {
var oldPosition = this._fixupHandlerPosition();
- this.handle.node.setPosition(position.x + oldPosition.x, position.y + oldPosition.y);
+ this._handle.node.setPosition(position.x + oldPosition.x, position.y + oldPosition.y);
}
- },
+ }
- _fixupHandlerPosition: function() {
+ _fixupHandlerPosition() {
var barSize = this.node.getContentSize();
var barAnchor = this.node.getAnchorPoint();
- var handleSize = this.handle.node.getContentSize();
+ var handleSize = this._handle.node.getContentSize();
- var handleParent = this.handle.node.parent;
+ var handleParent = this._handle.node.parent;
var leftBottomWorldPosition = this.node.convertToWorldSpaceAR(cc.v2(-barSize.width * barAnchor.x, -barSize.height * barAnchor.y));
var fixupPosition = handleParent.convertToNodeSpaceAR(leftBottomWorldPosition);
- if (this.direction === Direction.HORIZONTAL) {
+ if (this._direction === Direction.HORIZONTAL) {
fixupPosition = cc.v2(fixupPosition.x, fixupPosition.y + (barSize.height - handleSize.height) / 2);
- } else if (this.direction === Direction.VERTICAL) {
+ } else if (this._direction === Direction.VERTICAL) {
fixupPosition = cc.v2(fixupPosition.x + (barSize.width - handleSize.width) / 2, fixupPosition.y);
}
- this.handle.node.setPosition(fixupPosition);
+ this._handle.node.setPosition(fixupPosition);
return fixupPosition;
- },
+ }
- _onTouchBegan: function() {
- if (!this.enableAutoHide) {
+ _onTouchBegan() {
+ if (!this._enableAutoHide) {
return;
}
this._touching = true;
- },
+ }
- _conditionalDisableScrollBar: function (contentSize, scrollViewSize) {
- if(contentSize.width <= scrollViewSize.width
- && this.direction === Direction.HORIZONTAL){
+ _conditionalDisableScrollBar(contentSize, scrollViewSize) {
+ if (contentSize.width <= scrollViewSize.width
+ && this._direction === Direction.HORIZONTAL) {
return true;
}
- if(contentSize.height <= scrollViewSize.height
- && this.direction === Direction.VERTICAL){
+ if (contentSize.height <= scrollViewSize.height
+ && this._direction === Direction.VERTICAL) {
return true;
}
return false;
- },
+ }
- _onTouchEnded: function() {
- if (!this.enableAutoHide) {
+ _onTouchEnded() {
+ if (!this._enableAutoHide) {
return;
}
this._touching = false;
- if (this.autoHideTime <= 0) {
+ if (this._autoHideTime <= 0) {
return;
}
if (this._scrollView) {
var content = this._scrollView.content;
- if(content){
+ if (content) {
var contentSize = content.getContentSize();
var scrollViewSize = this._scrollView.node.getContentSize();
- if(this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
+ if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
return;
}
}
}
- this._autoHideRemainingTime = this.autoHideTime;
- },
+ this._autoHideRemainingTime = this._autoHideTime;
+ }
- _calculateLength: function(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundary) {
+ _calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundary) {
var denominatorValue = contentMeasure;
if (outOfBoundary) {
denominatorValue += (outOfBoundary > 0 ? outOfBoundary : -outOfBoundary) * GETTINGSHORTERFACTOR;
@@ -281,9 +302,9 @@ var Scrollbar = cc.Class({
var lengthRation = scrollViewMeasure / denominatorValue;
return handleNodeMeasure * lengthRation;
- },
+ }
- _calculatePosition: function(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundary, actualLenth) {
+ _calculatePosition(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundary, actualLenth) {
var denominatorValue = contentMeasure - scrollViewMeasure;
if (outOfBoundary) {
denominatorValue += Math.abs(outOfBoundary);
@@ -296,28 +317,28 @@ var Scrollbar = cc.Class({
}
var position = (handleNodeMeasure - actualLenth) * positionRatio;
- if (this.direction === Direction.VERTICAL) {
+ if (this._direction === Direction.VERTICAL) {
return cc.v2(0, position);
} else {
return cc.v2(position, 0);
}
- },
+ }
- _updateLength: function(length) {
- if (this.handle) {
- var handleNode = this.handle.node;
+ _updateLength(length) {
+ if (this._handle) {
+ var handleNode = this._handle.node;
var handleNodeSize = handleNode.getContentSize();
handleNode.setAnchorPoint(cc.v2(0, 0));
- if (this.direction === Direction.HORIZONTAL) {
+ if (this._direction === Direction.HORIZONTAL) {
handleNode.setContentSize(length, handleNodeSize.height);
} else {
handleNode.setContentSize(handleNodeSize.width, length);
}
}
- },
+ }
- _processAutoHide: function(deltaTime) {
- if (!this.enableAutoHide || this._autoHideRemainingTime <= 0) {
+ _processAutoHide(deltaTime) {
+ if (!this._enableAutoHide || this._autoHideRemainingTime <= 0) {
return;
} else if (this._touching) {
return;
@@ -325,33 +346,30 @@ var Scrollbar = cc.Class({
this._autoHideRemainingTime -= deltaTime;
- if (this._autoHideRemainingTime <= this.autoHideTime) {
+ if (this._autoHideRemainingTime <= this._autoHideTime) {
this._autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime);
- var opacity = this._opacity * (this._autoHideRemainingTime / this.autoHideTime);
+ var opacity = this._opacity * (this._autoHideRemainingTime / this._autoHideTime);
this._setOpacity(opacity);
}
- },
+ }
- start: function() {
- if (this.enableAutoHide) {
+ start() {
+ if (this._enableAutoHide) {
this._setOpacity(0);
}
- },
+ }
- hide: function() {
+ hide() {
this._autoHideRemainingTime = 0;
this._setOpacity(0);
- },
+ }
- show: function() {
- this._autoHideRemainingTime = this.autoHideTime;
+ show() {
+ this._autoHideRemainingTime = this._autoHideTime;
this._setOpacity(this._opacity);
- },
+ }
- update: function(dt) {
+ update(dt) {
this._processAutoHide(dt);
}
-});
-
-
-cc.Scrollbar = module.exports = Scrollbar;
+}
diff --git a/cocos/2d/ui/CCSlider.js b/cocos/2d/ui/CCSlider.js
deleted file mode 100644
index 11e0b270a0..0000000000
--- a/cocos/2d/ui/CCSlider.js
+++ /dev/null
@@ -1,240 +0,0 @@
-/****************************************************************************
- Copyright (c) 2013-2016 Chukong Technologies Inc.
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos.com
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
-
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-const misc = require('../utils/misc');
-const Component = require('./CCComponent');
-
-/**
- * !#en The Slider Direction
- * !#zh 滑动器方向
- * @enum Slider.Direction
- */
-var Direction = cc.Enum({
- /**
- * !#en The horizontal direction.
- * !#zh 水平方向
- * @property {Number} Horizontal
- */
- Horizontal: 0,
- /**
- * !#en The vertical direction.
- * !#zh 垂直方向
- * @property {Number} Vertical
- */
- Vertical: 1
-});
-
-/**
- * !#en The Slider Control
- * !#zh 滑动器组件
- * @class Slider
- * @extends Component
- */
-var Slider = cc.Class({
- name: 'cc.Slider',
- extends: Component,
-
- editor: CC_EDITOR && {
- menu: 'i18n:MAIN_MENU.component.ui/Slider',
- help: 'i18n:COMPONENT.help_url.slider'
- },
-
- ctor: function () {
- this._offset = cc.v2();
- this._touchHandle = false;
- this._dragging = false;
- },
-
- properties: {
- /**
- * !#en The "handle" part of the slider
- * !#zh 滑动器滑块按钮部件
- * @property {Button} handle
- */
- handle: {
- default: null,
- type: cc.Button,
- tooltip: CC_DEV && 'i18n:COMPONENT.slider.handle',
- notify: function() {
- if (CC_EDITOR && this.handle) {
- this._updateHandlePosition();
- }
- }
- },
-
- /**
- * !#en The slider direction
- * !#zh 滑动器方向
- * @property {Slider.Direction} direction
- */
- direction: {
- default: Direction.Horizontal,
- type: Direction,
- tooltip: CC_DEV && 'i18n:COMPONENT.slider.direction'
- },
-
- /**
- * !#en The current progress of the slider. The valid value is between 0-1
- * !#zh 当前进度值,该数值的区间是 0-1 之间
- * @property {Number} progress
- */
- progress: {
- default: 0.5,
- type: cc.Float,
- range: [0, 1, 0.1],
- slide: true,
- tooltip: CC_DEV && 'i18n:COMPONENT.slider.progress',
- notify: function() {
- this._updateHandlePosition();
- }
- },
-
- /**
- * !#en The slider events callback
- * !#zh 滑动器组件事件回调函数
- * @property {Component.EventHandler[]} slideEvents
- */
- slideEvents: {
- default: [],
- type: cc.Component.EventHandler,
- tooltip: CC_DEV && 'i18n:COMPONENT.slider.slideEvents'
- }
- },
-
- statics: {
- Direction: Direction
- },
-
- __preload: function () {
- this._updateHandlePosition();
- },
-
- // 注册事件
- onEnable: function () {
- this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this);
- this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this);
- this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
- this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this);
- if (this.handle && this.handle.isValid) {
- this.handle.node.on(cc.Node.EventType.TOUCH_START, this._onHandleDragStart, this);
- this.handle.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this);
- this.handle.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
- }
- },
-
- onDisable: function() {
- this.node.off(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this);
- this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this);
- this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
- this.node.off(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this);
- if (this.handle && this.handle.isValid) {
- this.handle.node.off(cc.Node.EventType.TOUCH_START, this._onHandleDragStart, this);
- this.handle.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this);
- this.handle.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
- }
- },
-
- _onHandleDragStart: function (event) {
- this._dragging = true;
- this._touchHandle = true;
- this._offset = this.handle.node.convertToNodeSpaceAR(event.touch.getLocation());
- event.stopPropagation();
- },
-
- _onTouchBegan: function (event) {
- if (!this.handle) { return; }
- this._dragging = true;
- if (!this._touchHandle) {
- this._handleSliderLogic(event.touch);
- }
- event.stopPropagation();
- },
-
- _onTouchMoved: function (event) {
- if (!this._dragging) { return; }
- this._handleSliderLogic(event.touch);
- event.stopPropagation();
- },
-
- _onTouchEnded: function (event) {
- this._dragging = false;
- this._touchHandle = false;
- this._offset = cc.v2();
- event.stopPropagation();
- },
-
- _onTouchCancelled: function (event) {
- this._dragging = false;
- event.stopPropagation();
- },
-
- _handleSliderLogic: function (touch) {
- this._updateProgress(touch);
- this._emitSlideEvent();
- },
-
- _emitSlideEvent: function () {
- cc.Component.EventHandler.emitEvents(this.slideEvents, this);
- this.node.emit('slide', this);
- },
-
- _updateProgress: function (touch) {
- if (!this.handle) { return; }
- var localTouchPos = this.node.convertToNodeSpaceAR(touch.getLocation());
- if (this.direction === Direction.Horizontal) {
- this.progress = misc.clamp01(0.5 + (localTouchPos.x - this._offset.x) / this.node.width);
- }
- else {
- this.progress = misc.clamp01(0.5 + (localTouchPos.y - this._offset.y) / this.node.height);
- }
- },
-
- _updateHandlePosition: function () {
- if (!this.handle) { return; }
- var handlelocalPos;
- if (this.direction === Direction.Horizontal) {
- handlelocalPos = cc.v2(-this.node.width * this.node.anchorX + this.progress * this.node.width, 0);
- }
- else {
- handlelocalPos = cc.v2(0, -this.node.height * this.node.anchorY + this.progress * this.node.height);
- }
- var worldSpacePos = this.node.convertToWorldSpaceAR(handlelocalPos);
- this.handle.node.position = this.handle.node.parent.convertToNodeSpaceAR(worldSpacePos);
- }
-
-});
-
-cc.Slider = module.exports = Slider;
-
-/**
- * !#en
- * Note: This event is emitted from the node to which the component belongs.
- * !#zh
- * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
- * @event slide
- * @param {Event.EventCustom} event
- * @param {Slider} slider - The slider component.
- */
diff --git a/cocos/2d/ui/CCToggle.js b/cocos/2d/ui/CCToggle.js
deleted file mode 100644
index 5f546d8e89..0000000000
--- a/cocos/2d/ui/CCToggle.js
+++ /dev/null
@@ -1,243 +0,0 @@
-/****************************************************************************
- Copyright (c) 2013-2016 Chukong Technologies Inc.
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos.com
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
-
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-/**
- * !#en The toggle component is a CheckBox, when it used together with a ToggleGroup, it
- * could be treated as a RadioButton.
- * !#zh Toggle 是一个 CheckBox,当它和 ToggleGroup 一起使用的时候,可以变成 RadioButton。
- * @class Toggle
- * @extends Button
- */
-var Toggle = cc.Class({
- name: 'cc.Toggle',
- extends: require('./CCButton'),
- editor: CC_EDITOR && {
- menu: 'i18n:MAIN_MENU.component.ui/Toggle',
- help: 'i18n:COMPONENT.help_url.toggle',
- inspector: 'packages://inspector/inspectors/comps/toggle.js',
- },
-
- properties: {
- /**
- * !#en When this value is true, the check mark component will be enabled, otherwise
- * the check mark component will be disabled.
- * !#zh 如果这个设置为 true,则 check mark 组件会处于 enabled 状态,否则处于 disabled 状态。
- * @property {Boolean} isChecked
- */
- isChecked: {
- default: true,
- tooltip: CC_DEV && 'i18n:COMPONENT.toggle.isChecked',
- notify: function () {
- this._updateCheckMark();
- }
- },
-
- /**
- * !#en The toggle group which the toggle belongs to, when it is null, the toggle is a CheckBox.
- * Otherwise, the toggle is a RadioButton.
- * !#zh Toggle 所属的 ToggleGroup,这个属性是可选的。如果这个属性为 null,则 Toggle 是一个 CheckBox,
- * 否则,Toggle 是一个 RadioButton。
- * @property {ToggleGroup} toggleGroup
- */
- toggleGroup: {
- default: null,
- tooltip: CC_DEV && 'i18n:COMPONENT.toggle.toggleGroup',
- type: require('./CCToggleGroup')
- },
-
- /**
- * !#en The image used for the checkmark.
- * !#zh Toggle 处于选中状态时显示的图片
- * @property {Sprite} checkMark
- */
- checkMark: {
- default: null,
- type: cc.Sprite,
- tooltip: CC_DEV && 'i18n:COMPONENT.toggle.checkMark'
- },
-
- /**
- * !#en If Toggle is clicked, it will trigger event's handler
- * !#zh Toggle 按钮的点击事件列表。
- * @property {Component.EventHandler[]} checkEvents
- */
- checkEvents: {
- default: [],
- type: cc.Component.EventHandler
- },
-
- _resizeToTarget: {
- animatable: false,
- set: function (value) {
- if (value) {
- this._resizeNodeToTargetNode();
- }
- }
- },
-
- },
-
- onEnable: function () {
- this._super();
- if (!CC_EDITOR) {
- this._registerToggleEvent();
- }
- if (this.toggleGroup && this.toggleGroup.enabled) {
- this.toggleGroup.addToggle(this);
- }
- },
-
- onDisable: function () {
- this._super();
- if (!CC_EDITOR) {
- this._unregisterToggleEvent();
- }
- if (this.toggleGroup && this.toggleGroup.enabled) {
- this.toggleGroup.removeToggle(this);
- }
- },
-
- _updateCheckMark: function () {
- if (this.checkMark) {
- this.checkMark.node.active = !!this.isChecked;
- }
- },
-
- _updateDisabledState: function () {
- this._super();
-
- if (this.checkMark) {
- this.checkMark.setState(0);
- }
- if (this.enableAutoGrayEffect) {
- if (this.checkMark && !this.interactable) {
- this.checkMark.setState(1);
- }
- }
- },
-
- _registerToggleEvent: function () {
- this.node.on('click', this.toggle, this);
- },
-
- _unregisterToggleEvent: function () {
- this.node.off('click', this.toggle, this);
- },
-
- toggle: function (event) {
- var group = this.toggleGroup || this._toggleContainer;
-
- if (group && group.enabled && this.isChecked) {
- if (!group.allowSwitchOff) {
- return;
- }
- }
-
- this.isChecked = !this.isChecked;
-
- this._updateCheckMark();
-
- if (group && group.enabled) {
- group.updateToggles(this);
- }
-
- this._emitToggleEvents(event);
- },
-
- _emitToggleEvents: function () {
- this.node.emit('toggle', this);
- if (this.checkEvents) {
- cc.Component.EventHandler.emitEvents(this.checkEvents, this);
- }
- },
-
- /**
- * !#en Make the toggle button checked.
- * !#zh 使 toggle 按钮处于选中状态
- * @method check
- */
- check: function () {
- var group = this.toggleGroup || this._toggleContainer;
-
- if (group && group.enabled && this.isChecked) {
- if (!group.allowSwitchOff) {
- return;
- }
- }
-
- this.isChecked = true;
-
- if (group && group.enabled) {
- group.updateToggles(this);
- }
-
- this._emitToggleEvents();
- },
-
- /**
- * !#en Make the toggle button unchecked.
- * !#zh 使 toggle 按钮处于未选中状态
- * @method uncheck
- */
- uncheck: function () {
- var group = this.toggleGroup || this._toggleContainer;
-
- if (group && group.enabled && this.isChecked) {
- if (!group.allowSwitchOff) {
- return;
- }
- }
-
- this.isChecked = false;
-
- this._emitToggleEvents();
- }
-});
-
-cc.Toggle = module.exports = Toggle;
-
-
-var js = require('../platform/js');
-
-js.get(Toggle.prototype, '_toggleContainer',
- function () {
- var parent = this.node.parent;
- if (cc.Node.isNode(parent)) {
- return parent.getComponent(cc.ToggleContainer);
- }
- return null;
- }
-);
-
-/**
- * !#en
- * Note: This event is emitted from the node to which the component belongs.
- * !#zh
- * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
- * @event toggle
- * @param {Event.EventCustom} event
- * @param {Toggle} toggle - The Toggle component.
- */
diff --git a/cocos/2d/ui/CCWidget.js b/cocos/2d/ui/CCWidget.js
deleted file mode 100644
index be95904646..0000000000
--- a/cocos/2d/ui/CCWidget.js
+++ /dev/null
@@ -1,685 +0,0 @@
-/****************************************************************************
- Copyright (c) 2013-2016 Chukong Technologies Inc.
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos.com
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
-
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-var WidgetManager = require('../base-ui/CCWidgetManager');
-
-/**
- * !#en Enum for Widget's alignment mode, indicating when the widget should refresh.
- * !#zh Widget 的对齐模式,表示 Widget 应该何时刷新。
- * @enum Widget.AlignMode
- */
-/**
- * !#en
- * Only align once when the Widget is enabled for the first time.
- * This will allow the script or animation to continue controlling the current node.
- * It will only be aligned once before the end of frame when onEnable is called,
- * then immediately disables the Widget.
- * !#zh
- * 仅在 Widget 第一次激活时对齐一次,便于脚本或动画继续控制当前节点。
- * 开启后会在 onEnable 时所在的那一帧结束前对齐一次,然后立刻禁用该 Widget。
- * @property {Number} ONCE
- */
-/**
- * !#en Align first from the beginning as ONCE, and then realign it every time the window is resized.
- * !#zh 一开始会像 ONCE 一样对齐一次,之后每当窗口大小改变时还会重新对齐。
- * @property {Number} ON_WINDOW_RESIZE
- */
-/**
- * !#en Keep aligning all the way.
- * !#zh 始终保持对齐。
- * @property {Number} ALWAYS
- */
-var AlignMode = WidgetManager.AlignMode;
-
-var AlignFlags = WidgetManager._AlignFlags;
-var TOP = AlignFlags.TOP;
-var MID = AlignFlags.MID;
-var BOT = AlignFlags.BOT;
-var LEFT = AlignFlags.LEFT;
-var CENTER = AlignFlags.CENTER;
-var RIGHT = AlignFlags.RIGHT;
-var TOP_BOT = TOP | BOT;
-var LEFT_RIGHT = LEFT | RIGHT;
-
-/**
- * !#en
- * Stores and manipulate the anchoring based on its parent.
- * Widget are used for GUI but can also be used for other things.
- * Widget will adjust current node's position and size automatically, but the results after adjustment can not be obtained until the next frame unless you call {{#crossLink "Widget/updateAlignment:method"}}{{/crossLink}} manually.
- * !#zh
- * Widget 组件,用于设置和适配其相对于父节点的边距,Widget 通常被用于 UI 界面,也可以用于其他地方。
- * Widget 会自动调整当前节点的坐标和宽高,不过目前调整后的结果要到下一帧才能在脚本里获取到,除非你先手动调用 {{#crossLink "Widget/updateAlignment:method"}}{{/crossLink}}。
- *
- * @class Widget
- * @extends Component
- */
-var Widget = cc.Class({
- name: 'cc.Widget', extends: require('./CCComponent'),
-
- editor: CC_EDITOR && {
- menu: 'i18n:MAIN_MENU.component.ui/Widget',
- help: 'i18n:COMPONENT.help_url.widget',
- inspector: 'packages://inspector/inspectors/comps/ccwidget.js',
- executeInEditMode: true,
- disallowMultiple: true,
- },
-
- properties: {
-
- /**
- * !#en Specifies an alignment target that can only be one of the parent nodes of the current node.
- * The default value is null, and when null, indicates the current parent.
- * !#zh 指定一个对齐目标,只能是当前节点的其中一个父节点,默认为空,为空时表示当前父节点。
- * @property {Node} target
- * @default null
- */
- target: {
- get: function () {
- return this._target;
- },
- set: function (value) {
- this._target = value;
- if (CC_EDITOR && !cc.engine._isPlaying && this.node._parent) {
- // adjust the offsets to keep the size and position unchanged after target chagned
- WidgetManager.updateOffsetsToStayPut(this);
- }
- },
- type: cc.Node,
- tooltip: CC_DEV && 'i18n:COMPONENT.widget.target',
- },
-
- // ENABLE ALIGN ?
-
- /**
- * !#en Whether to align the top.
- * !#zh 是否对齐上边。
- * @property isAlignTop
- * @type {Boolean}
- * @default false
- */
- isAlignTop: {
- get: function () {
- return (this._alignFlags & TOP) > 0;
- },
- set: function (value) {
- this._setAlign(TOP, value);
- },
- animatable: false,
- tooltip: CC_DEV && 'i18n:COMPONENT.widget.align_top',
- },
-
- /**
- * !#en
- * Vertically aligns the midpoint, This will open the other vertical alignment options cancel.
- * !#zh
- * 是否垂直方向对齐中点,开启此项会将垂直方向其他对齐选项取消。
- * @property isAlignVerticalCenter
- * @type {Boolean}
- * @default false
- */
- isAlignVerticalCenter: {
- get: function () {
- return (this._alignFlags & MID) > 0;
- },
- set: function (value) {
- if (value) {
- this.isAlignTop = false;
- this.isAlignBottom = false;
- this._alignFlags |= MID;
- }
- else {
- this._alignFlags &= ~MID;
- }
- },
- animatable: false,
- tooltip: CC_DEV && 'i18n:COMPONENT.widget.align_v_center',
- },
-
- /**
- * !#en Whether to align the bottom.
- * !#zh 是否对齐下边。
- * @property isAlignBottom
- * @type {Boolean}
- * @default false
- */
- isAlignBottom: {
- get: function () {
- return (this._alignFlags & BOT) > 0;
- },
- set: function (value) {
- this._setAlign(BOT, value);
- },
- animatable: false,
- tooltip: CC_DEV && 'i18n:COMPONENT.widget.align_bottom',
- },
-
- /**
- * !#en Whether to align the left.
- * !#zh 是否对齐左边
- * @property isAlignLeft
- * @type {Boolean}
- * @default false
- */
- isAlignLeft: {
- get: function () {
- return (this._alignFlags & LEFT) > 0;
- },
- set: function (value) {
- this._setAlign(LEFT, value);
- },
- animatable: false,
- tooltip: CC_DEV && 'i18n:COMPONENT.widget.align_left',
- },
-
- /**
- * !#en
- * Horizontal aligns the midpoint. This will open the other horizontal alignment options canceled.
- * !#zh
- * 是否水平方向对齐中点,开启此选项会将水平方向其他对齐选项取消。
- * @property isAlignHorizontalCenter
- * @type {Boolean}
- * @default false
- */
- isAlignHorizontalCenter: {
- get: function () {
- return (this._alignFlags & CENTER) > 0;
- },
- set: function (value) {
- if (value) {
- this.isAlignLeft = false;
- this.isAlignRight = false;
- this._alignFlags |= CENTER;
- }
- else {
- this._alignFlags &= ~CENTER;
- }
- },
- animatable: false,
- tooltip: CC_DEV && 'i18n:COMPONENT.widget.align_h_center',
- },
-
- /**
- * !#en Whether to align the right.
- * !#zh 是否对齐右边。
- * @property isAlignRight
- * @type {Boolean}
- * @default false
- */
- isAlignRight: {
- get: function () {
- return (this._alignFlags & RIGHT) > 0;
- },
- set: function (value) {
- this._setAlign(RIGHT, value);
- },
- animatable: false,
- tooltip: CC_DEV && 'i18n:COMPONENT.widget.align_right',
- },
-
- /**
- * !#en
- * Whether the stretched horizontally, when enable the left and right alignment will be stretched horizontally,
- * the width setting is invalid (read only).
- * !#zh
- * 当前是否水平拉伸。当同时启用左右对齐时,节点将会被水平拉伸,此时节点的宽度只读。
- * @property isStretchWidth
- * @type {Boolean}
- * @default false
- * @readOnly
- */
- isStretchWidth: {
- get: function () {
- return (this._alignFlags & LEFT_RIGHT) === LEFT_RIGHT;
- },
- visible: false
- },
- /**
- * !#en
- * Whether the stretched vertically, when enable the left and right alignment will be stretched vertically,
- * then height setting is invalid (read only)
- * !#zh
- * 当前是否垂直拉伸。当同时启用上下对齐时,节点将会被垂直拉伸,此时节点的高度只读。
- * @property isStretchHeight
- * @type {Boolean}
- * @default false
- * @readOnly
- */
- isStretchHeight: {
- get: function () {
- return (this._alignFlags & TOP_BOT) === TOP_BOT;
- },
- visible: false
- },
-
- // ALIGN MARGINS
-
- /**
- * !#en
- * The margins between the top of this node and the top of parent node,
- * the value can be negative, Only available in 'isAlignTop' open.
- * !#zh
- * 本节点顶边和父节点顶边的距离,可填写负值,只有在 isAlignTop 开启时才有作用。
- * @property top
- * @type {Number}
- * @default 0
- */
- top: {
- get: function () {
- return this._top;
- },
- set: function (value) {
- this._top = value;
- },
- tooltip: CC_DEV && 'i18n:COMPONENT.widget.top',
- },
-
- /**
- * !#en
- * The margins between the bottom of this node and the bottom of parent node,
- * the value can be negative, Only available in 'isAlignBottom' open.
- * !#zh
- * 本节点底边和父节点底边的距离,可填写负值,只有在 isAlignBottom 开启时才有作用。
- * @property bottom
- * @type {Number}
- * @default 0
- */
- bottom: {
- get: function () {
- return this._bottom;
- },
- set: function (value) {
- this._bottom = value;
- },
- tooltip: CC_DEV && 'i18n:COMPONENT.widget.bottom',
- },
-
- /**
- * !#en
- * The margins between the left of this node and the left of parent node,
- * the value can be negative, Only available in 'isAlignLeft' open.
- * !#zh
- * 本节点左边和父节点左边的距离,可填写负值,只有在 isAlignLeft 开启时才有作用。
- * @property left
- * @type {Number}
- * @default 0
- */
- left: {
- get: function () {
- return this._left;
- },
- set: function (value) {
- this._left = value;
- },
- tooltip: CC_DEV && 'i18n:COMPONENT.widget.left',
- },
-
- /**
- * !#en
- * The margins between the right of this node and the right of parent node,
- * the value can be negative, Only available in 'isAlignRight' open.
- * !#zh
- * 本节点右边和父节点右边的距离,可填写负值,只有在 isAlignRight 开启时才有作用。
- * @property right
- * @type {Number}
- * @default 0
- */
- right: {
- get: function () {
- return this._right;
- },
- set: function (value) {
- this._right = value;
- },
- tooltip: CC_DEV && 'i18n:COMPONENT.widget.right',
- },
-
- /**
- * !#en
- * Horizontal aligns the midpoint offset value,
- * the value can be negative, Only available in 'isAlignHorizontalCenter' open.
- * !#zh 水平居中的偏移值,可填写负值,只有在 isAlignHorizontalCenter 开启时才有作用。
- * @property horizontalCenter
- * @type {Number}
- * @default 0
- */
- horizontalCenter: {
- get: function () {
- return this._horizontalCenter;
- },
- set: function (value) {
- this._horizontalCenter = value;
- },
- tooltip: CC_DEV && 'i18n:COMPONENT.widget.horizontal_center',
- },
-
- /**
- * !#en
- * Vertical aligns the midpoint offset value,
- * the value can be negative, Only available in 'isAlignVerticalCenter' open.
- * !#zh 垂直居中的偏移值,可填写负值,只有在 isAlignVerticalCenter 开启时才有作用。
- * @property verticalCenter
- * @type {Number}
- * @default 0
- */
- verticalCenter: {
- get: function () {
- return this._verticalCenter;
- },
- set: function (value) {
- this._verticalCenter = value;
- },
- tooltip: CC_DEV && 'i18n:COMPONENT.widget.vertical_center',
- },
-
- // PARCENTAGE OR ABSOLUTE
-
- /**
- * !#en If true, horizontalCenter is pixel margin, otherwise is percentage (0 - 1) margin.
- * !#zh 如果为 true,"horizontalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。
- * @property isAbsoluteHorizontalCenter
- * @type {Boolean}
- * @default true
- */
- isAbsoluteHorizontalCenter: {
- get: function () {
- return this._isAbsHorizontalCenter;
- },
- set: function (value) {
- this._isAbsHorizontalCenter = value;
- },
- animatable: false
- },
-
- /**
- * !#en If true, verticalCenter is pixel margin, otherwise is percentage (0 - 1) margin.
- * !#zh 如果为 true,"verticalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。
- * @property isAbsoluteVerticalCenter
- * @type {Boolean}
- * @default true
- */
- isAbsoluteVerticalCenter: {
- get: function () {
- return this._isAbsVerticalCenter;
- },
- set: function (value) {
- this._isAbsVerticalCenter = value;
- },
- animatable: false
- },
-
- /**
- * !#en
- * If true, top is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's height.
- * !#zh
- * 如果为 true,"top" 将会以像素作为边距,否则将会以相对父物体高度的百分比(0 到 1)作为边距。
- * @property isAbsoluteTop
- * @type {Boolean}
- * @default true
- */
- isAbsoluteTop: {
- get: function () {
- return this._isAbsTop;
- },
- set: function (value) {
- this._isAbsTop = value;
- },
- animatable: false
- },
-
- /**
- * !#en
- * If true, bottom is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's height.
- * !#zh
- * 如果为 true,"bottom" 将会以像素作为边距,否则将会以相对父物体高度的百分比(0 到 1)作为边距。
- * @property isAbsoluteBottom
- * @type {Boolean}
- * @default true
- */
- isAbsoluteBottom: {
- get: function () {
- return this._isAbsBottom;
- },
- set: function (value) {
- this._isAbsBottom = value;
- },
- animatable: false
- },
-
- /**
- * !#en
- * If true, left is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's width.
- * !#zh
- * 如果为 true,"left" 将会以像素作为边距,否则将会以相对父物体宽度的百分比(0 到 1)作为边距。
- * @property isAbsoluteLeft
- * @type {Boolean}
- * @default true
- */
- isAbsoluteLeft: {
- get: function () {
- return this._isAbsLeft;
- },
- set: function (value) {
- this._isAbsLeft = value;
- },
- animatable: false
- },
-
- /**
- * !#en
- * If true, right is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's width.
- * !#zh
- * 如果为 true,"right" 将会以像素作为边距,否则将会以相对父物体宽度的百分比(0 到 1)作为边距。
- * @property isAbsoluteRight
- * @type {Boolean}
- * @default true
- */
- isAbsoluteRight: {
- get: function () {
- return this._isAbsRight;
- },
- set: function (value) {
- this._isAbsRight = value;
- },
- animatable: false
- },
-
- /**
- * !#en Specifies the alignment mode of the Widget, which determines when the widget should refresh.
- * !#zh 指定 Widget 的对齐模式,用于决定 Widget 应该何时刷新。
- * @property {Widget.AlignMode} alignMode
- * @example
- * widget.alignMode = cc.Widget.AlignMode.ON_WINDOW_RESIZE;
- */
- alignMode: {
- default: AlignMode.ON_WINDOW_RESIZE,
- type: AlignMode,
- tooltip: CC_DEV && 'i18n:COMPONENT.widget.align_mode',
- },
-
- //
-
- _wasAlignOnce: {
- default: undefined,
- formerlySerializedAs: 'isAlignOnce',
- },
-
- _target: null,
-
- /**
- * !#zh: 对齐开关,由 AlignFlags 组成
- *
- * @property _alignFlags
- * @type {Number}
- * @default 0
- * @private
- */
- _alignFlags: 0,
-
- _left: 0,
- _right: 0,
- _top: 0,
- _bottom: 0,
- _verticalCenter: 0,
- _horizontalCenter: 0,
- _isAbsLeft: true,
- _isAbsRight: true,
- _isAbsTop: true,
- _isAbsBottom: true,
- _isAbsHorizontalCenter: true,
- _isAbsVerticalCenter: true,
-
- // original size before align
- _originalWidth: 0,
- _originalHeight: 0
- },
-
- statics: {
- AlignMode: AlignMode,
- },
-
- onLoad: function () {
- if (this._wasAlignOnce !== undefined) {
- // migrate for old version
- this.alignMode = this._wasAlignOnce ? AlignMode.ONCE : AlignMode.ALWAYS;
- this._wasAlignOnce = undefined;
- }
- },
-
- onEnable: function () {
- WidgetManager.add(this);
- },
-
- onDisable: function () {
- WidgetManager.remove(this);
- },
-
- _setAlign: function (flag, isAlign) {
- var current = (this._alignFlags & flag) > 0;
- if (isAlign == current) {
- return;
- }
- var isHorizontal = (flag & LEFT_RIGHT) > 0;
- if (isAlign) {
- this._alignFlags |= flag;
-
- if (isHorizontal) {
- this.isAlignHorizontalCenter = false;
- 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 {
- this.isAlignVerticalCenter = false;
- 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 && this.node._parent) {
- // adjust the offsets to keep the size and position unchanged after alignment chagned
- WidgetManager.updateOffsetsToStayPut(this, flag);
- }
- }
- else {
- if (isHorizontal) {
- if (this.isStretchWidth) {
- // will cancel stretch
- this.node.width = this._originalWidth;
- }
- }
- else {
- if (this.isStretchHeight) {
- // will cancel stretch
- this.node.height = this._originalHeight;
- }
- }
-
- this._alignFlags &= ~flag;
- }
- },
-
- /**
- * !#en
- * Immediately perform the widget alignment. You need to manually call this method only if
- * you need to get the latest results after the alignment before the end of current frame.
- * !#zh
- * 立刻执行 widget 对齐操作。这个接口一般不需要手工调用。
- * 只有当你需要在当前帧结束前获得 widget 对齐后的最新结果时才需要手动调用这个方法。
- *
- * @method updateAlignment
- *
- * @example
- * widget.top = 10; // change top margin
- * cc.log(widget.node.y); // not yet changed
- * widget.updateAlignment();
- * cc.log(widget.node.y); // changed
- */
- updateAlignment: function () {
- WidgetManager.updateAlignment(this.node);
- },
-});
-
-/**
- * !#en
- * When turned on, it will only be aligned once at the end of the onEnable frame,
- * then immediately disables the current component.
- * This will allow the script or animation to continue controlling the current node.
- * Note: It will still be aligned at the frame when onEnable is called.
- * !#zh
- * 开启后仅会在 onEnable 的当帧结束时对齐一次,然后立刻禁用当前组件。
- * 这样便于脚本或动画继续控制当前节点。
- * 注意:onEnable 时所在的那一帧仍然会进行对齐。
- * @property {Boolean} isAlignOnce
- * @default false
- * @deprecated
- */
-Object.defineProperty(Widget.prototype, 'isAlignOnce', {
- get () {
- if (CC_DEBUG) {
- cc.warn('`widget.isAlignOnce` is deprecated, use `widget.alignMode === cc.Widget.AlignMode.ONCE` instead please.');
- }
- return this.alignMode === AlignMode.ONCE;
- },
- set (value) {
- if (CC_DEBUG) {
- cc.warn('`widget.isAlignOnce` is deprecated, use `widget.alignMode = cc.Widget.AlignMode.*` instead please.');
- }
- this.alignMode = value ? AlignMode.ONCE : AlignMode.ALWAYS;
- }
-});
-
-
-cc.Widget = module.exports = Widget;
diff --git a/cocos/2d/ui/editbox/CCEditBox.js b/cocos/2d/ui/editbox/CCEditBox.js
deleted file mode 100644
index b6b5be0ffd..0000000000
--- a/cocos/2d/ui/editbox/CCEditBox.js
+++ /dev/null
@@ -1,729 +0,0 @@
-/****************************************************************************
- Copyright (c) 2013-2016 Chukong Technologies Inc.
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos.com
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
-
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-const macro = require('../../platform/CCMacro');
-const EditBoxImpl = require('../editbox/CCEditBoxImpl');
-const Label = require('../CCLabel');
-const Types = require('./types');
-const InputMode = Types.InputMode;
-const InputFlag = Types.InputFlag;
-const KeyboardReturnType = Types.KeyboardReturnType;
-
-const LEFT_PADDING = 2;
-
-function capitalize (string) {
- return string.replace(/(?:^|\s)\S/g, function(a) { return a.toUpperCase(); });
-}
-
-function capitalizeFirstLetter (string) {
- return string.charAt(0).toUpperCase() + string.slice(1);
-}
-
-
-/**
- * !#en cc.EditBox is a component for inputing text, you can use it to gather small amounts of text from users.
- * !#zh EditBox 组件,用于获取用户的输入文本。
- * @class EditBox
- * @extends Component
- */
-let EditBox = cc.Class({
- name: 'cc.EditBox',
- extends: cc.Component,
-
- editor: CC_EDITOR && {
- menu: 'i18n:MAIN_MENU.component.ui/EditBox',
- inspector: 'packages://inspector/inspectors/comps/cceditbox.js',
- help: 'i18n:COMPONENT.help_url.editbox',
- executeInEditMode: true,
- },
-
- properties: {
- _useOriginalSize: true,
- _string: '',
- /**
- * !#en Input string of EditBox.
- * !#zh 输入框的初始输入内容,如果为空则会显示占位符的文本。
- * @property {String} string
- */
- string: {
- tooltip: CC_DEV && 'i18n:COMPONENT.editbox.string',
- get () {
- return this._string;
- },
- set(value) {
- if (this.maxLength >= 0 && value.length >= this.maxLength) {
- value = value.slice(0, this.maxLength);
- }
-
- this._string = value;
- if (this._impl) {
- this._updateString(value);
- }
- }
- },
-
- /**
- * !#en The background image of EditBox.
- * !#zh 输入框的背景图片
- * @property {SpriteFrame} backgroundImage
- */
- backgroundImage: {
- tooltip: CC_DEV && 'i18n:COMPONENT.editbox.backgroundImage',
- default: null,
- type: cc.SpriteFrame,
- notify () {
- this._createBackgroundSprite();
- }
- },
-
- /**
- * !#en
- * The return key type of EditBox.
- * Note: it is meaningless for web platforms and desktop platforms.
- * !#zh
- * 指定移动设备上面回车按钮的样式。
- * 注意:这个选项对 web 平台与 desktop 平台无效。
- * @property {EditBox.KeyboardReturnType} returnType
- * @default KeyboardReturnType.DEFAULT
- */
- returnType: {
- default: KeyboardReturnType.DEFAULT,
- tooltip: CC_DEV && 'i18n:COMPONENT.editbox.returnType',
- displayName: 'KeyboardReturnType',
- type: KeyboardReturnType,
- notify () {
- if (this._impl) {
- this._impl.returnType = this.returnType;
- }
- }
- },
-
- /**
- * !#en Set the input flags that are to be applied to the EditBox.
- * !#zh 指定输入标志位,可以指定输入方式为密码或者单词首字母大写。
- * @property {EditBox.InputFlag} inputFlag
- * @default InputFlag.DEFAULT
- */
- inputFlag: {
- tooltip: CC_DEV && 'i18n:COMPONENT.editbox.input_flag',
- default: InputFlag.DEFAULT,
- type: InputFlag,
- notify () {
- if (this._impl) {
- this._impl.setInputFlag(this.inputFlag);
- this._updateString(this._string);
- }
- }
- },
- /**
- * !#en
- * Set the input mode of the edit box.
- * If you pass ANY, it will create a multiline EditBox.
- * !#zh
- * 指定输入模式: ANY表示多行输入,其它都是单行输入,移动平台上还可以指定键盘样式。
- * @property {EditBox.InputMode} inputMode
- * @default InputMode.ANY
- */
- inputMode: {
- tooltip: CC_DEV && 'i18n:COMPONENT.editbox.input_mode',
- default: InputMode.ANY,
- type: InputMode,
- notify () {
- if (this._impl) {
- this._impl.setInputMode(this.inputMode);
- }
- }
- },
-
- /**
- * !#en Font size of the input text.
- * !#zh 输入框文本的字体大小
- * @property {Number} fontSize
- */
- fontSize: {
- tooltip: CC_DEV && 'i18n:COMPONENT.editbox.font_size',
- default: 20,
- notify () {
- if (this._textLabel) {
- this._textLabel.fontSize = this.fontSize;
- }
- if (this._impl) {
- this._impl.setFontSize(this.fontSize);
- }
- }
- },
-
- /**
- * !#en Change the lineHeight of displayed text.
- * !#zh 输入框文本的行高。
- * @property {Number} lineHeight
- */
- lineHeight: {
- tooltip: CC_DEV && 'i18n:COMPONENT.editbox.line_height',
- default: 40,
- notify () {
- if (this._textLabel) {
- this._textLabel.lineHeight = this.lineHeight;
- }
- }
- },
-
- /**
- * !#en Font color of the input text.
- * !#zh 输入框文本的颜色。
- * @property {Color} fontColor
- */
- fontColor: {
- tooltip: CC_DEV && 'i18n:COMPONENT.editbox.font_color',
- default: cc.Color.WHITE,
- notify () {
- if (this._textLabel) {
- this._textLabel.node.opacity = this.fontColor.a;
- this._textLabel.node.color = this.fontColor;
- }
- if (this._impl) {
- this._impl.setFontColor(this.fontColor);
- }
- }
- },
-
- /**
- * !#en The display text of placeholder.
- * !#zh 输入框占位符的文本内容。
- * @property {String} placeholder
- */
- placeholder: {
- tooltip: CC_DEV && 'i18n:COMPONENT.editbox.placeholder',
- default: 'Enter text here...',
- notify () {
- if (this._placeholderLabel) {
- this._placeholderLabel.string = this.placeholder;
- }
- if (this._impl) {
- this._impl.setPlaceholderText(this.placeholder);
- }
- }
- },
-
- /**
- * !#en The font size of placeholder.
- * !#zh 输入框占位符的字体大小。
- * @property {Number} placeholderFontSize
- */
- placeholderFontSize: {
- tooltip: CC_DEV && 'i18n:COMPONENT.editbox.placeholder_font_size',
- default: 20,
- notify () {
- if (this._placeholderLabel) {
- this._placeholderLabel.fontSize = this.placeholderFontSize;
- }
- }
- },
-
- /**
- * !#en The font color of placeholder.
- * !#zh 输入框占位符的字体颜色。
- * @property {Color} placeholderFontColor
- */
- placeholderFontColor: {
- tooltip: CC_DEV && 'i18n:COMPONENT.editbox.placeholder_font_color',
- default: cc.Color.GRAY,
- notify () {
- if (this._placeholderLabel) {
- this._placeholderLabel.node.color = this.placeholderFontColor;
- this._placeholderLabel.node.opacity = this.placeholderFontColor.a;
- }
- }
- },
-
- /**
- * !#en The maximize input length of EditBox.
- * - If pass a value less than 0, it won't limit the input number of characters.
- * - If pass 0, it doesn't allow input any characters.
- * !#zh 输入框最大允许输入的字符个数。
- * - 如果值为小于 0 的值,则不会限制输入字符个数。
- * - 如果值为 0,则不允许用户进行任何输入。
- * @property {Number} maxLength
- */
- maxLength: {
- tooltip: CC_DEV && 'i18n:COMPONENT.editbox.max_length',
- default: 20,
- notify () {
- if (this._impl) {
- this._impl.setMaxLength(this.maxLength);
- }
- }
- },
-
- /**
- * !#en The input is always visible and be on top of the game view (only useful on Web).
- * !zh 输入框总是可见,并且永远在游戏视图的上面(这个属性只有在 Web 上面修改有意义)
- * Note: only available on Web at the moment.
- * @property {Boolean} stayOnTop
- */
- stayOnTop: {
- tooltip: CC_DEV && 'i18n:COMPONENT.editbox.stay_on_top',
- default: false,
- notify () {
- if (this._impl) {
- this._updateStayOnTop();
- }
- }
- },
-
- _tabIndex: 0,
-
- /**
- * !#en Set the tabIndex of the DOM input element (only useful on Web).
- * !#zh 修改 DOM 输入元素的 tabIndex(这个属性只有在 Web 上面修改有意义)。
- * @property {Number} tabIndex
- */
- tabIndex: {
- tooltip: CC_DEV && 'i18n:COMPONENT.editbox.tab_index',
- get () {
- return this._tabIndex;
- },
- set (value) {
- this._tabIndex = value;
- if (this._impl) {
- this._impl.setTabIndex(value);
- }
- }
- },
-
- /**
- * !#en The event handler to be called when EditBox began to edit text.
- * !#zh 开始编辑文本输入框触发的事件回调。
- * @property {Component.EventHandler[]} editingDidBegan
- */
- editingDidBegan: {
- default: [],
- type: cc.Component.EventHandler,
- },
-
- /**
- * !#en The event handler to be called when EditBox text changes.
- * !#zh 编辑文本输入框时触发的事件回调。
- * @property {Component.EventHandler[]} textChanged
- */
- textChanged: {
- default: [],
- type: cc.Component.EventHandler,
- },
-
- /**
- * !#en The event handler to be called when EditBox edit ends.
- * !#zh 结束编辑文本输入框时触发的事件回调。
- * @property {Component.EventHandler[]} editingDidEnded
- */
- editingDidEnded: {
- default: [],
- type: cc.Component.EventHandler,
- },
-
- /**
- * !#en The event handler to be called when return key is pressed. Windows is not supported.
- * !#zh 当用户按下回车按键时的事件回调,目前不支持 windows 平台
- * @property {Component.EventHandler[]} editingReturn
- */
- editingReturn: {
- default: [],
- type: cc.Component.EventHandler
- }
-
- },
-
- statics: {
- _EditBoxImpl: EditBoxImpl,
- KeyboardReturnType: KeyboardReturnType,
- InputFlag: InputFlag,
- InputMode: InputMode
- },
-
- _init () {
- this._createBackgroundSprite();
- this._createLabels();
- this.node.on(cc.Node.EventType.SIZE_CHANGED, this._resizeChildNodes, this);
-
- let impl = this._impl = new EditBoxImpl();
-
- impl.setDelegate(this);
- impl.setNode(this.node);
- impl.setInputMode(this.inputMode);
- impl.setMaxLength(this.maxLength);
- impl.setInputFlag(this.inputFlag);
- impl.setReturnType(this.returnType);
- impl.setTabIndex(this.tabIndex);
- impl.setFontColor(this.fontColor);
- impl.setFontSize(this.fontSize);
- impl.setPlaceholderText(this.placeholder);
-
- this._updateStayOnTop();
- this._updateString(this.string);
- this._syncSize();
- },
-
- _updateStayOnTop () {
- if (this.stayOnTop) {
- this._hideLabels();
- }
- else {
- this._showLabels();
- }
- this._impl.stayOnTop(this.stayOnTop);
- },
-
- _syncSize () {
- let size = this.node.getContentSize();
-
- this._background.node.setAnchorPoint(this.node.getAnchorPoint());
- this._background.node.setContentSize(size);
-
- this._updateLabelPosition(size);
- this._impl.setSize(size.width, size.height);
- },
-
- _updateLabelPosition (size) {
- let node = this.node;
- let offx = -node.anchorX * node.width;
- let offy = -node.anchorY * node.height;
-
- let placeholderLabel = this._placeholderLabel;
- let textLabel = this._textLabel;
-
- textLabel.node.setContentSize(size.width - LEFT_PADDING, size.height);
- placeholderLabel.node.setContentSize(size.width - LEFT_PADDING, size.height);
- placeholderLabel.lineHeight = size.height;
-
- placeholderLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height);
- textLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height);
-
- if (this.inputMode === InputMode.ANY){
- placeholderLabel.verticalAlign = macro.VerticalTextAlignment.TOP;
- placeholderLabel.enableWrapText = true;
- textLabel.verticalAlign = macro.VerticalTextAlignment.TOP;
- textLabel.enableWrapText = true;
- }
- else {
- placeholderLabel.verticalAlign = macro.VerticalTextAlignment.CENTER;
- placeholderLabel.enableWrapText = false;
- textLabel.verticalAlign = macro.VerticalTextAlignment.CENTER;
- textLabel.enableWrapText = false;
- }
- },
-
- _createBackgroundSprite () {
- let background = this._background;
- if (!background) {
- let node = this.node.getChildByName('BACKGROUND_SPRITE');
- if (!node) {
- node = new cc.Node('BACKGROUND_SPRITE');
- }
-
- background = node.getComponent(cc.Sprite);
- if (!background) {
- background = node.addComponent(cc.Sprite);
- }
- background.type = cc.Sprite.Type.SLICED;
-
- node.parent = this.node;
- this._background = background;
- }
- background.spriteFrame = this.backgroundImage;
- },
-
- _createLabels () {
- if (!this._textLabel) {
- let node = this.node.getChildByName('TEXT_LABEL');
- if (!node) {
- node = new cc.Node('TEXT_LABEL');
- }
- node.color = this.fontColor;
- node.parent = this.node;
- node.setAnchorPoint(0, 1);
-
- let textLabel = node.getComponent(Label);
- if (!textLabel) {
- textLabel = node.addComponent(Label);
- }
- textLabel.overflow = Label.Overflow.CLAMP;
- textLabel.fontSize = this.fontSize;
- textLabel.lineHeight = this.lineHeight;
- this._textLabel = textLabel;
- }
-
- if (!this._placeholderLabel) {
- let node = this.node.getChildByName('PLACEHOLDER_LABEL');
- if (!node) {
- node = new cc.Node('PLACEHOLDER_LABEL');
- }
- node.color = this.placeholderFontColor;
- node.parent = this.node;
- node.setAnchorPoint(0, 1);
-
- let placeholderLabel = node.getComponent(Label);
- if (!placeholderLabel) {
- placeholderLabel = node.addComponent(Label);
- }
- placeholderLabel.overflow = Label.Overflow.CLAMP;
- placeholderLabel.fontSize = this.placeholderFontSize;
- placeholderLabel.string = this.placeholder;
- this._placeholderLabel = placeholderLabel;
- }
- },
-
- _resizeChildNodes () {
- let textLabelNode = this._textLabel.node,
- placeholderLabelNode = this._placeholderLabel.node,
- backgroundNode = this._background.node;
-
- textLabelNode.x = -this.node.width/2;
- textLabelNode.y = this.node.height/2;
- textLabelNode.width = this.node.width;
- textLabelNode.height = this.node.height;
-
- placeholderLabelNode.x = -this.node.width/2;
- placeholderLabelNode.y = this.node.height/2;
- placeholderLabelNode.width = this.node.width;
- placeholderLabelNode.height = this.node.height;
-
- backgroundNode.width = this.node.width;
- backgroundNode.height = this.node.height;
- },
-
- _showLabels () {
- let displayText = this._textLabel.string;
- this._textLabel.node.active = displayText !== '';
- this._placeholderLabel.node.active = displayText === '';
- },
-
- _hideLabels () {
- this._textLabel.node.active = false;
- this._placeholderLabel.node.active = false;
- },
-
- _updateString (text) {
- let textLabel = this._textLabel;
- // Not inited yet
- if (!textLabel) {
- return;
- }
-
- let displayText = text;
- if (displayText) {
- displayText = this._updateLabelStringStyle(displayText);
- }
-
- textLabel.string = displayText;
- this._impl.setString(text);
- if (!this._impl._editing && !this.stayOnTop) {
- this._showLabels();
- }
- },
-
- _updateLabelStringStyle (text, ignorePassword) {
- let inputFlag = this.inputFlag;
- if (!ignorePassword && inputFlag === InputFlag.PASSWORD) {
- let passwordString = '';
- let len = text.length;
- for (let i = 0; i < len; ++i) {
- passwordString += '\u25CF';
- }
- text = passwordString;
- }
- else if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) {
- text = text.toUpperCase();
- }
- else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) {
- text = capitalize(text);
- }
- else if (inputFlag === InputFlag.INITIAL_CAPS_SENTENCE) {
- text = capitalizeFirstLetter(text);
- }
-
- return text;
- },
-
- editBoxEditingDidBegan () {
- this._hideLabels();
- cc.Component.EventHandler.emitEvents(this.editingDidBegan, this);
- this.node.emit('editing-did-began', this);
- },
-
- editBoxEditingDidEnded () {
- if (!this.stayOnTop) {
- this._showLabels();
- }
- cc.Component.EventHandler.emitEvents(this.editingDidEnded, this);
- this.node.emit('editing-did-ended', this);
- },
-
- editBoxTextChanged (text) {
- text = this._updateLabelStringStyle(text, true);
- this.string = text;
- cc.Component.EventHandler.emitEvents(this.textChanged, text, this);
- this.node.emit('text-changed', this);
- },
-
- editBoxEditingReturn() {
- cc.Component.EventHandler.emitEvents(this.editingReturn, this);
- this.node.emit('editing-return', this);
- },
-
- onDestroy () {
- this._impl.clear();
- },
-
- onEnable () {
- this._impl && this._impl.onEnable();
- },
-
- onDisable () {
- this._impl && this._impl.onDisable();
- },
-
- __preload () {
- if (!CC_EDITOR) {
- this._registerEvent();
- }
- this._init();
- },
-
- _registerEvent () {
- this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this);
- this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
- },
-
- _onTouchBegan (event) {
- if (this._impl) {
- this._impl._onTouchBegan(event.touch);
- }
- event.stopPropagation();
- },
-
- _onTouchCancel (event) {
- if (this._impl) {
- this._impl._onTouchCancel();
- }
- event.stopPropagation();
- },
-
- _onTouchEnded (event) {
- if (this._impl) {
- this._impl._onTouchEnded();
- }
- event.stopPropagation();
- },
-
- /**
- * !#en Let the EditBox get focus
- * !#zh 让当前 EditBox 获得焦点
- * @method setFocus
- */
- setFocus () {
- if(this._impl) {
- this._impl.setFocus();
- }
- },
-
- /**
- * !#en Determine whether EditBox is getting focus or not.
- * !#zh 判断 EditBox 是否获得了焦点
- * Note: only available on Web at the moment.
- * @method isFocused
- */
- isFocused () {
- let isFocused = false;
- if (this._impl) {
- isFocused = this._impl.isFocused();
- }
- return isFocused;
- },
-
- update () {
- if (this._impl) {
- this._impl.update();
- }
- }
-
-});
-
-cc.EditBox = module.exports = EditBox;
-
-/**
- * !#en
- * Note: This event is emitted from the node to which the component belongs.
- * !#zh
- * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
- * @event editing-did-began
- * @param {Event.EventCustom} event
- * @param {EditBox} editbox - The EditBox component.
- */
-
-/**
- * !#en
- * Note: This event is emitted from the node to which the component belongs.
- * !#zh
- * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
- * @event editing-did-ended
- * @param {Event.EventCustom} event
- * @param {EditBox} editbox - The EditBox component.
- */
-
-/**
- * !#en
- * Note: This event is emitted from the node to which the component belongs.
- * !#zh
- * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
- * @event text-changed
- * @param {Event.EventCustom} event
- * @param {EditBox} editbox - The EditBox component.
- */
-
-/**
- * !#en
- * Note: This event is emitted from the node to which the component belongs.
- * !#zh
- * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
- * @event editing-return
- * @param {Event.EventCustom} event
- * @param {EditBox} editbox - The EditBox component.
- */
-
-/**
- * !#en if you don't need the EditBox and it isn't in any running Scene, you should
- * call the destroy method on this component or the associated node explicitly.
- * Otherwise, the created DOM element won't be removed from web page.
- * !#zh
- * 如果你不再使用 EditBox,并且组件未添加到场景中,那么你必须手动对组件或所在节点调用 destroy。
- * 这样才能移除网页上的 DOM 节点,避免 Web 平台内存泄露。
- * @example
- * editbox.node.parent = null; // or editbox.node.removeFromParent(false);
- * // when you don't need editbox anymore
- * editbox.node.destroy();
- * @method destroy
- * @return {Boolean} whether it is the first time the destroy being called
- */
diff --git a/cocos/3d/assets/font.js b/cocos/3d/assets/font.js
index 292ee84ecd..3d0891759b 100644
--- a/cocos/3d/assets/font.js
+++ b/cocos/3d/assets/font.js
@@ -29,9 +29,9 @@ import { Asset } from "../../assets/asset";
@ccclass('cc.Font')
export default class Font extends Asset {
- /** Font size.
- * @type {number}
- */
+ /** Font size.
+ * @type {number}
+ */
_size = 32;
/** Font type.
diff --git a/cocos/3d/builtin/init.js b/cocos/3d/builtin/init.js
index f131953a21..304ccf62ee 100644
--- a/cocos/3d/builtin/init.js
+++ b/cocos/3d/builtin/init.js
@@ -4,38 +4,39 @@ import ImageAsset from '../../assets/image-asset';
import { Material } from '../assets/material';
import { EffectAsset } from '../assets/effect-asset';
import effects from './effects';
+import { SpriteFrame} from '../../assets/CCSpriteFrame';
let builtinResMgr = {
// this should be called after renderer initialized
- initBuiltinRes: function(device) {
+ initBuiltinRes: function (device) {
builtinResMgr.device = device;
- // let canvas = document.createElement('canvas');
- // let context = canvas.getContext('2d');
+ let canvas = document.createElement('canvas');
+ let context = canvas.getContext('2d');
- // // ============================
- // // builtin textures
- // // ============================
+ // ============================
+ // builtin textures
+ // ============================
- // // default texture canvas fill
- // canvas.width = canvas.height = 128;
- // context.fillStyle = '#ddd';
- // context.fillRect(0, 0, 128, 128);
- // context.fillStyle = '#555';
- // context.fillRect(0, 0, 64, 64);
- // context.fillStyle = '#555';
- // context.fillRect(64, 64, 64, 64);
+ // default texture canvas fill
+ canvas.width = canvas.height = 128;
+ context.fillStyle = '#ddd';
+ context.fillRect(0, 0, 128, 128);
+ context.fillStyle = '#555';
+ context.fillRect(0, 0, 64, 64);
+ context.fillStyle = '#555';
+ context.fillRect(64, 64, 64, 64);
- // const canvasImage = new ImageAsset(canvas);
+ const canvasImage = new ImageAsset(canvas);
- // // default-texture
- // let defaultTexture = new Texture2D();
- // defaultTexture.setMipFilter(Texture2D.Filter.LINEAR);
- // defaultTexture.setFilters(Texture2D.Filter.LINEAR, Texture2D.Filter.LINEAR);
- // defaultTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT);
- // defaultTexture._uuid = 'default-texture';
- // defaultTexture.image = canvasImage;
+ // default-texture
+ let defaultTexture = new Texture2D();
+ defaultTexture.setMipFilter(Texture2D.Filter.LINEAR);
+ defaultTexture.setFilters(Texture2D.Filter.LINEAR, Texture2D.Filter.LINEAR);
+ defaultTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT);
+ defaultTexture._uuid = 'default-texture';
+ defaultTexture.image = canvasImage;
- // // default-texture-cube
+ // default-texture-cube
// let defaultTextureCube = new TextureCube();
// defaultTextureCube._uuid = 'default-texture-cube';
// defaultTextureCube.image = {
@@ -47,29 +48,38 @@ let builtinResMgr = {
// bottom: canvasImage,
// };
- // // black texture canvas fill
- // canvas.width = canvas.height = 2;
- // context.fillStyle = '#000';
- // context.fillRect(0, 0, 2, 2);
+ // black texture canvas fill
+ canvas.width = canvas.height = 2;
+ context.fillStyle = '#000';
+ context.fillRect(0, 0, 2, 2);
- // // black-texture
- // let blackTexture = new Texture2D();
- // blackTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST);
- // blackTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT);
- // blackTexture._uuid = 'black-texture';
- // defaultTexture.image = canvasImage;
+ // black-texture
+ let blackTexture = new Texture2D();
+ blackTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST);
+ blackTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT);
+ blackTexture._uuid = 'black-texture';
+ defaultTexture.image = canvasImage;
- // // white texture canvas fill
- // canvas.width = canvas.height = 2;
- // context.fillStyle = '#fff';
- // context.fillRect(0, 0, 2, 2);
+ // white texture canvas fill
+ canvas.width = canvas.height = 2;
+ context.fillStyle = '#fff';
+ context.fillRect(0, 0, 2, 2);
- // // white-texture
- // let whiteTexture = new Texture2D();
- // blackTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST);
- // blackTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT);
- // whiteTexture._uuid = 'white-texture';
- // defaultTexture.image = canvasImage;
+ // white-texture
+ let whiteTexture = new Texture2D();
+ blackTexture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST);
+ blackTexture.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT);
+ whiteTexture._uuid = 'white-texture';
+ defaultTexture.image = canvasImage;
+
+ let spriteFrame = new SpriteFrame();
+ spriteFrame.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST);
+ spriteFrame.setWrapMode(Texture2D.WrapMode.REPEAT, Texture2D.WrapMode.REPEAT);
+ spriteFrame._uuid = 'default-spriteframe';
+ spriteFrame.image = canvasImage;
+ if (spriteFrame.onLoaded) {
+ spriteFrame.onLoaded();
+ }
// essential builtin effects
let efxs = effects.map(e => {
@@ -81,15 +91,22 @@ let builtinResMgr = {
let defaultMtl = new Material();
defaultMtl._uuid = 'default-material';
defaultMtl.setDefines({ USE_COLOR: true });
- defaultMtl.effectAsset = efxs[0];
+ defaultMtl.effectName = 'builtin-effect-unlit';
defaultMtl.setProperty('color', cc.color('#FF00FF'));
+ // sprite material
+ let spriteMtl = new Material();
+ spriteMtl._uuid = 'sprite-material';
+ spriteMtl.effectName = 'builtin-effect-sprite';
+ defaultMtl.setProperty('mainTexture', defaultTexture);
+
let builtins = {
- // [defaultTexture._uuid]: defaultTexture,
- // [defaultTextureCube._uuid]: defaultTextureCube,
- // [blackTexture._uuid]: blackTexture,
- // [whiteTexture._uuid]: whiteTexture,
- [defaultMtl._uuid]: defaultMtl
+ [defaultTexture._uuid]: defaultTexture,
+ // [defaultTextureCube._uuid]: defaultTextureCub
+ [blackTexture._uuid]: blackTexture,
+ [whiteTexture._uuid]: whiteTexture,
+ [spriteMtl._uuid]: spriteMtl,
+ [spriteFrame._uuid]:spriteFrame
};
return Object.assign(builtinResMgr, builtins);
},
diff --git a/cocos/3d/index.js b/cocos/3d/index.js
index 32a86b567a..c3998ccf3c 100644
--- a/cocos/3d/index.js
+++ b/cocos/3d/index.js
@@ -30,6 +30,7 @@ export * from './memop';
import * as utils from './misc/utils';
import * as primitives from './primitive';
import * as geometry from './geom-utils';
+import './ui';
export {
utils,
@@ -39,4 +40,4 @@ export {
cc.geometry = geometry;
cc.primitives = primitives;
-cc.utils = utils;
\ No newline at end of file
+cc.utils = utils;
diff --git a/cocos/2d/renderer/webgl/assemblers/assembler.js b/cocos/3d/ui/assembler/assembler.js
similarity index 100%
rename from cocos/2d/renderer/webgl/assemblers/assembler.js
rename to cocos/3d/ui/assembler/assembler.js
diff --git a/cocos/2d/renderer/webgl/assemblers/index.js b/cocos/3d/ui/assembler/index.js
similarity index 89%
rename from cocos/2d/renderer/webgl/assemblers/index.js
rename to cocos/3d/ui/assembler/index.js
index 65a9b28071..27e68b6314 100644
--- a/cocos/2d/renderer/webgl/assemblers/index.js
+++ b/cocos/3d/ui/assembler/index.js
@@ -23,8 +23,9 @@
THE SOFTWARE.
****************************************************************************/
-require('./sprite');
-require('./mask-assembler');
-require('./graphics');
-require('./label');
-require('./motion-streak');
+// require('./sprite');
+import './sprite/index';
+// require('./mask-assembler');
+// require('./graphics');
+// import './label/index';
+// require('./motion-streak');
diff --git a/cocos/2d/renderer/webgl/assemblers/label/bmfont.js b/cocos/3d/ui/assembler/label/bmfont.js
similarity index 55%
rename from cocos/2d/renderer/webgl/assemblers/label/bmfont.js
rename to cocos/3d/ui/assembler/label/bmfont.js
index c4b985ee3c..c19f3ad835 100644
--- a/cocos/2d/renderer/webgl/assemblers/label/bmfont.js
+++ b/cocos/3d/ui/assembler/label/bmfont.js
@@ -23,45 +23,23 @@
THE SOFTWARE.
****************************************************************************/
-const js = require('../../../../platform/js');
-const bmfontUtls = require('../../../utils/label/bmfont');
+import * as js from '../../../../core/utils/js';
+import bmfontUtls from '../../../../2d/renderer/utils/label/bmfont';
+import { fillMeshVertices3D } from '../utils';
-module.exports = js.addon({
- createData (comp) {
+let bmfont = {
+ createData(comp) {
return comp.requestRenderData();
},
- fillBuffers (comp, renderer) {
- let node = comp.node,
- renderData = comp._renderData,
- data = renderData._data,
- color = node.color._val;
-
- let matrix = node._worldMatrix,
- a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05,
- tx = matrix.m12, ty = matrix.m13;
-
- let buffer = renderer._quadBuffer,
- vertexOffset = buffer.byteOffset >> 2;
-
- let vertexCount = renderData.vertexCount;
- buffer.request(vertexCount, renderData.indiceCount);
-
- // buffer data may be realloc, need get reference after request.
- let vbuf = buffer._vData;
-
- for (let i = 0; i < vertexCount; i++) {
- let vert = data[i];
- vbuf[vertexOffset++] = vert.x * a + vert.y * c + tx;
- vbuf[vertexOffset++] = vert.x * b + vert.y * d + ty;
- vbuf[vertexOffset++] = vert.u;
- vbuf[vertexOffset++] = vert.v;
- }
+ fillBuffers(comp, renderer) {
+ let node = comp.node;
+ fillMeshVertices3D(node, renderer._meshBuffer3D, comp._renderData, node._color._val);
},
- appendQuad (renderData, texture, rect, rotated, x, y, scale) {
+ appendQuad(renderData, texture, rect, rotated, x, y, scale) {
let dataOffset = renderData.dataLength;
-
+
renderData.dataLength += 4;
renderData.vertexCount = renderData.dataLength;
renderData.indiceCount = renderData.dataLength / 2 * 3;
@@ -82,12 +60,12 @@ module.exports = js.addon({
data[dataOffset].u = l;
data[dataOffset].v = b;
- data[dataOffset+1].u = r;
- data[dataOffset+1].v = b;
- data[dataOffset+2].u = l;
- data[dataOffset+2].v = t;
- data[dataOffset+3].u = r;
- data[dataOffset+3].v = t;
+ data[dataOffset + 1].u = r;
+ data[dataOffset + 1].v = b;
+ data[dataOffset + 2].u = l;
+ data[dataOffset + 2].v = t;
+ data[dataOffset + 3].u = r;
+ data[dataOffset + 3].v = t;
} else {
l = (rect.x) / texw;
r = (rect.x + rectHeight) / texw;
@@ -96,21 +74,25 @@ module.exports = js.addon({
data[dataOffset].u = l;
data[dataOffset].v = t;
- data[dataOffset+1].u = l;
- data[dataOffset+1].v = b;
- data[dataOffset+2].u = r;
- data[dataOffset+2].v = t;
- data[dataOffset+3].u = r;
- data[dataOffset+3].v = b;
+ data[dataOffset + 1].u = l;
+ data[dataOffset + 1].v = b;
+ data[dataOffset + 2].u = r;
+ data[dataOffset + 2].v = t;
+ data[dataOffset + 3].u = r;
+ data[dataOffset + 3].v = b;
}
data[dataOffset].x = x;
data[dataOffset].y = y - rectHeight * scale;
- data[dataOffset+1].x = x + rectWidth * scale;
- data[dataOffset+1].y = y - rectHeight * scale;
- data[dataOffset+2].x = x;
- data[dataOffset+2].y = y;
- data[dataOffset+3].x = x + rectWidth * scale;
- data[dataOffset+3].y = y;
+ data[dataOffset + 1].x = x + rectWidth * scale;
+ data[dataOffset + 1].y = y - rectHeight * scale;
+ data[dataOffset + 2].x = x;
+ data[dataOffset + 2].y = y;
+ data[dataOffset + 3].x = x + rectWidth * scale;
+ data[dataOffset + 3].y = y;
},
-}, bmfontUtls);
+};
+
+js.addon(bmfont, bmfontUtls);
+
+export default bmfont;
diff --git a/cocos/2d/renderer/webgl/assemblers/label/index.js b/cocos/3d/ui/assembler/label/index.js
similarity index 77%
rename from cocos/2d/renderer/webgl/assemblers/label/index.js
rename to cocos/3d/ui/assembler/label/index.js
index fe44c9af4d..a1c6a6ae35 100644
--- a/cocos/2d/renderer/webgl/assemblers/label/index.js
+++ b/cocos/3d/ui/assembler/label/index.js
@@ -23,14 +23,17 @@
THE SOFTWARE.
****************************************************************************/
-const Label = require('../../../../components/CCLabel');
-const ttfAssembler = require('./ttf');
-const bmfontAssembler = require('./bmfont');
+// const Label = require('../../../../components/CCLabel');
+// const ttfAssembler = require('./ttf');
+// const bmfontAssembler = require('./bmfont');
+import { LabelComponent} from '../../components/label-component';
+import ttfAssembler from './ttf';
+import bmfontAssembler from './bmfont';
-var labelAssembler = {
- getAssembler (comp) {
+export default labelAssembler = {
+ getAssembler(comp) {
let assembler = ttfAssembler;
-
+
if (comp.font instanceof cc.BitmapFont) {
assembler = bmfontAssembler;
}
@@ -39,11 +42,9 @@ var labelAssembler = {
},
// Skip invalid labels (without own _assembler)
- updateRenderData (label) {
- return label.__allocedDatas;
- }
+ // updateRenderData(label) {
+ // return label.__allocedDatas;
+ // }
};
-Label._assembler = labelAssembler;
-
-module.exports = labelAssembler;
\ No newline at end of file
+LabelComponent._assembler = labelAssembler;
diff --git a/cocos/2d/renderer/webgl/assemblers/label/ttf.js b/cocos/3d/ui/assembler/label/ttf.js
similarity index 69%
rename from cocos/2d/renderer/webgl/assemblers/label/ttf.js
rename to cocos/3d/ui/assembler/label/ttf.js
index 0d980acdc1..f9287de57b 100644
--- a/cocos/2d/renderer/webgl/assemblers/label/ttf.js
+++ b/cocos/3d/ui/assembler/label/ttf.js
@@ -23,11 +23,14 @@
THE SOFTWARE.
****************************************************************************/
-const js = require('../../../../platform/js');
-const ttfUtls = require('../../../utils/label/ttf');
+import * as js from '../../../../core/utils/js';
+import ttfUtls from '../../../../2d/renderer/utils/label/ttf';
+import { fillMeshVertices3D } from '../utils';
-module.exports = js.addon({
- createData (comp) {
+const WHITE = cc.color(255, 255, 255, 255);
+
+let ttf = {
+ createData(comp) {
let renderData = comp.requestRenderData();
renderData.dataLength = 4;
@@ -46,32 +49,11 @@ module.exports = js.addon({
return renderData;
},
- fillBuffers (comp, renderer) {
- let data = comp._renderData._data,
- node = comp.node,
- matrix = node._worldMatrix,
- a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05,
- tx = matrix.m12, ty = matrix.m13;
-
- let buffer = renderer._quadBuffer,
- vertexOffset = buffer.byteOffset >> 2;
-
- buffer.request(4, 6);
-
- // buffer data may be realloc, need get reference after request.
- let vbuf = buffer._vData;
-
- // vertex
- for (let i = 0; i < 4; i++) {
- let vert = data[i];
- vbuf[vertexOffset++] = vert.x * a + vert.y * c + tx;
- vbuf[vertexOffset++] = vert.x * b + vert.y * d + ty;
- vbuf[vertexOffset++] = vert.u;
- vbuf[vertexOffset++] = vert.v;
- }
+ fillBuffers(comp, /*renderer*/buffer) {
+ fillMeshVertices3D(comp.node, /*renderer._quadBuffer3D*/buffer, comp._renderData, WHITE._val);
},
- _updateVerts (comp) {
+ _updateVerts(comp) {
let renderData = comp._renderData;
let node = comp.node,
@@ -90,4 +72,9 @@ module.exports = js.addon({
data[3].x = width - appx;
data[3].y = height - appy;
}
-}, ttfUtls);
+}
+
+js.addon(ttf, ttfUtls);
+
+export default ttf;
+
diff --git a/cocos/2d/renderer/webgl/assemblers/mask-assembler.js b/cocos/3d/ui/assembler/mask-assembler.js
similarity index 100%
rename from cocos/2d/renderer/webgl/assemblers/mask-assembler.js
rename to cocos/3d/ui/assembler/mask-assembler.js
diff --git a/cocos/2d/renderer/webgl/assemblers/sprite/bar-filled.js b/cocos/3d/ui/assembler/sprite/bar-filled.js
similarity index 54%
rename from cocos/2d/renderer/webgl/assemblers/sprite/bar-filled.js
rename to cocos/3d/ui/assembler/sprite/bar-filled.js
index 474fe24380..3d08df2fc9 100644
--- a/cocos/2d/renderer/webgl/assemblers/sprite/bar-filled.js
+++ b/cocos/3d/ui/assembler/sprite/bar-filled.js
@@ -1,7 +1,7 @@
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
- http://www.cocos.com
+ https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
@@ -22,27 +22,29 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
+//@ts-check
+import { SpriteComponent} from '../../components/sprite-component';
+const FillType = SpriteComponent.FillType;
-const Sprite = require('../../../../components/CCSprite');
-const FillType = Sprite.FillType;
+// const dynamicAtlasManager = require('../../../../utils/dynamic-atlas/manager');
+import { fillVerticesWithoutCalc3D } from '../utils';
+import { vec3 } from '../../../../core/vmath/index';
-const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
-
-module.exports = {
+let barFilled = {
useModel: false,
- updateRenderData (sprite) {
+ updateRenderData(sprite) {
let frame = sprite.spriteFrame;
-
+
// TODO: Material API design and export from editor could affect the material activation process
// need to update the logic here
- if (frame) {
- if (!frame._original && dynamicAtlasManager) {
- dynamicAtlasManager.insertSpriteFrame(frame);
- }
- if (sprite._material._texture !== frame._texture) {
- sprite._activateMaterial();
- }
- }
+ // if (frame) {
+ // if (!frame._original && dynamicAtlasManager) {
+ // dynamicAtlasManager.insertSpriteFrame(frame);
+ // }
+ // if (sprite._material._texture !== frame._texture) {
+ // sprite._activateMaterial();
+ // }
+ // }
let renderData = sprite._renderData;
if (renderData && frame) {
@@ -70,7 +72,7 @@ module.exports = {
fillRange = fillRange < 0.0 ? 0.0 : fillRange;
fillRange = fillRange - fillStart;
fillRange = fillRange < 0 ? 0 : fillRange;
-
+
let fillEnd = fillStart + fillRange;
fillEnd = fillEnd > 1 ? 1 : fillEnd;
@@ -79,19 +81,19 @@ module.exports = {
}
if (vertDirty) {
this.updateVerts(sprite, fillStart, fillEnd);
- this.updateWorldVerts(sprite);
+ // this.updateWorldVerts(sprite);
}
}
},
- updateUVs (sprite, fillStart, fillEnd) {
+ updateUVs(sprite, fillStart, fillEnd) {
let spriteFrame = sprite._spriteFrame,
renderData = sprite._renderData,
data = renderData._data;
//build uvs
- let atlasWidth = spriteFrame._texture.width;
- let atlasHeight = spriteFrame._texture.height;
+ let atlasWidth = spriteFrame.width;
+ let atlasHeight = spriteFrame.height;
let textureRect = spriteFrame._rect;
//uv computation should take spritesheet into account.
let ul, vb, ur, vt;
@@ -113,32 +115,50 @@ module.exports = {
ur = (textureRect.x + textureRect.width) / atlasWidth;
vt = (textureRect.y) / atlasHeight;
- quadUV0 = quadUV4 = ul;
- quadUV2 = quadUV6 = ur;
- quadUV1 = quadUV3 = vb;
- quadUV5 = quadUV7 = vt;
+ // quadUV0 = quadUV4 = ul;
+ // quadUV2 = quadUV6 = ur;
+ // quadUV1 = quadUV3 = vb;
+ // quadUV5 = quadUV7 = vt;
}
switch (sprite._fillType) {
case FillType.HORIZONTAL:
- data[0].u = quadUV0 + (quadUV2 - quadUV0) * fillStart;
- data[0].v = quadUV1;
- data[1].u = quadUV0 + (quadUV2 - quadUV0) * fillEnd;
- data[1].v = quadUV3;
- data[2].u = quadUV4 + (quadUV6 - quadUV4) * fillStart;
- data[2].v = quadUV5;
- data[3].u = quadUV4 + (quadUV6 - quadUV4) * fillEnd;
- data[3].v = quadUV7;
+ data[0].u = ul + (ur - ul) * fillStart;
+ data[0].v = vb;
+ data[1].u = ul + (ur - ul) * fillEnd;
+ data[1].v = vb;
+ data[2].u = ul + (ur - ul) * fillStart;
+ data[2].v = vt;
+ data[3].u = ul + (ur - ul) * fillEnd;
+ data[3].v = vt;
+
+ // data[0].u = quadUV0 + (quadUV2 - quadUV0) * fillStart;
+ // data[0].v = quadUV1 + (quadUV3 - quadUV1) * fillStart;
+ // data[1].u = quadUV0 + (quadUV2 - quadUV0) * fillEnd;
+ // data[1].v = quadUV1 + (quadUV3 - quadUV1) * fillEnd;
+ // data[2].u = quadUV4 + (quadUV6 - quadUV4) * fillStart;
+ // data[2].v = quadUV5 + (quadUV7 - quadUV5) * fillStart;
+ // data[3].u = quadUV4 + (quadUV6 - quadUV4) * fillEnd;
+ // data[3].v = quadUV5 + (quadUV7 - quadUV5) * fillEnd;
break;
case FillType.VERTICAL:
- data[0].u = quadUV0;
- data[0].v = quadUV1 + (quadUV5 - quadUV1) * fillStart;
- data[1].u = quadUV2;
- data[1].v = quadUV3 + (quadUV7 - quadUV3) * fillStart;
- data[2].u = quadUV4;
- data[2].v = quadUV1 + (quadUV5 - quadUV1) * fillEnd;
- data[3].u = quadUV6;
- data[3].v = quadUV3 + (quadUV7 - quadUV3) * fillEnd;
+ data[0].u = ul
+ data[0].v = vb + (vt - vb) * fillStart;
+ data[1].u = ur;
+ data[1].v = vb + (vt - vb) * fillStart;
+ data[2].u = ul;
+ data[2].v = vb + (vt - vb) * fillEnd;
+ data[3].u = ur;
+ data[3].v = vb + (vt - vb) * fillEnd;
+
+ // data[0].u = quadUV0 + (quadUV4 - quadUV0) * fillStart;
+ // data[0].v = quadUV1 + (quadUV5 - quadUV1) * fillStart;
+ // data[1].u = quadUV2 + (quadUV6 - quadUV2) * fillStart;
+ // data[1].v = quadUV3 + (quadUV7 - quadUV3) * fillStart;
+ // data[2].u = quadUV0 + (quadUV4 - quadUV0) * fillEnd;
+ // data[2].v = quadUV1 + (quadUV5 - quadUV1) * fillEnd;
+ // data[3].u = quadUV2 + (quadUV6 - quadUV2) * fillEnd;
+ // data[3].v = quadUV3 + (quadUV7 - quadUV3) * fillEnd;
break;
default:
cc.errorID(2626);
@@ -148,7 +168,7 @@ module.exports = {
renderData.uvDirty = false;
},
- updateVerts (sprite, fillStart, fillEnd) {
+ updateVerts(sprite, fillStart, fillEnd) {
let renderData = sprite._renderData,
data = renderData._data,
node = sprite.node,
@@ -156,7 +176,7 @@ module.exports = {
appx = node.anchorX * width, appy = node.anchorY * height;
let l = -appx, b = -appy,
- r = width-appx, t = height-appy;
+ r = width - appx, t = height - appy;
let progressStart, progressEnd;
switch (sprite._fillType) {
@@ -179,70 +199,68 @@ module.exports = {
break;
}
- data[4].x = l;
- data[4].y = b;
- data[5].x = r;
- data[5].y = b;
- data[6].x = l;
- data[6].y = t;
- data[7].x = r;
- data[7].y = t;
+ data[0].x = l;
+ data[0].y = b;
+ data[1].x = r;
+ data[1].y = b;
+ data[2].x = l;
+ data[2].y = t;
+ data[3].x = r;
+ data[3].y = t;
renderData.vertDirty = false;
},
- createData (sprite) {
+ createData(sprite) {
let renderData = sprite.requestRenderData();
// 0-4 for world verts
// 5-8 for local verts
- renderData.dataLength = 8;
+ renderData.dataLength = 4;
renderData.vertexCount = 4;
renderData.indiceCount = 6;
+
+ let data = renderData._data;
+ for (let i = 0; i < data.length; i++) {
+ data[i].z = 0;
+ }
return renderData;
},
- updateWorldVerts (sprite) {
- let node = sprite.node,
- data = sprite._renderData._data;
-
- let matrix = node._worldMatrix,
- a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05,
- tx = matrix.m12, ty = matrix.m13;
-
- for (let i = 0; i < 4; i++) {
- let local = data[i+4];
- let world = data[i];
- world.x = local.x * a + local.y * c + tx;
- world.y = local.x * b + local.y * d + ty;
- }
- },
+ // updateWorldVerts(sprite) {
+ // let node = sprite.node,
+ // data = sprite._renderData._data;
- fillBuffers (sprite, renderer) {
- if (renderer.worldMatDirty) {
- this.updateWorldVerts(sprite);
- }
+ // node._updateWorldMatrix();
+ // let matrix = node._worldMatrix;
+ // for (let i = 0; i < 4; i++) {
+ // let local = data[i + 4];
+ // let world = data[i];
+ // vec3.transformMat4(world, local, matrix);
+ // }
+ // },
- let data = sprite._renderData._data,
- node = sprite.node,
- matrix = node._worldMatrix,
- a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05,
- tx = matrix.m12, ty = matrix.m13;
-
- let buffer = renderer._quadBuffer,
- vertexOffset = buffer.byteOffset >> 2;
+ fillBuffers(sprite, /*renderer*/buffer) {
+ // if (renderer.worldMatDirty) {
+ // this.updateWorldVerts(sprite);
+ // }
- buffer.request(4, 6);
+ // buffer
+ let /*buffer = renderer._meshBuffer3D,*/
+ indiceOffset = buffer.indiceOffset,
+ vertexId = buffer.vertexOffset;
+
+ let node = sprite.node;
+ fillVerticesWithoutCalc3D(node, buffer, sprite._renderData, sprite._color._val);
// buffer data may be realloc, need get reference after request.
- let vbuf = buffer._vData;
-
- // vertex
- for (let i = 0; i < 4; i++) {
- let vert = data[i];
- vbuf[vertexOffset++] = vert.x;
- vbuf[vertexOffset++] = vert.y;
- vbuf[vertexOffset++] = vert.u;
- vbuf[vertexOffset++] = vert.v;
- }
+ let ibuf = buffer._iData;
+ ibuf[indiceOffset++] = vertexId;
+ ibuf[indiceOffset++] = vertexId + 1;
+ ibuf[indiceOffset++] = vertexId + 2;
+ ibuf[indiceOffset++] = vertexId + 1;
+ ibuf[indiceOffset++] = vertexId + 3;
+ ibuf[indiceOffset++] = vertexId + 2;
}
};
+
+export default barFilled;
diff --git a/cocos/2d/renderer/webgl/assemblers/sprite/index.js b/cocos/3d/ui/assembler/sprite/index.js
similarity index 55%
rename from cocos/2d/renderer/webgl/assemblers/sprite/index.js
rename to cocos/3d/ui/assembler/sprite/index.js
index c59947b09c..00ce2ab056 100644
--- a/cocos/2d/renderer/webgl/assemblers/sprite/index.js
+++ b/cocos/3d/ui/assembler/sprite/index.js
@@ -23,53 +23,56 @@
THE SOFTWARE.
****************************************************************************/
-const Sprite = require('../../../../components/CCSprite');
+// const Sprite = require('../../../../components/CCSprite');
+import { SpriteComponent} from '../../components/sprite-component';
-const SpriteType = Sprite.Type;
-const FillType = Sprite.FillType;
+const SpriteType = SpriteComponent.Type;
+const FillType = SpriteComponent.FillType;
-const simpleRenderUtil = require('./simple');
-const slicedRenderUtil = require('./sliced');
-const tiledRenderUtil = require('./tiled');
-const radialFilledRenderUtil = require('./radial-filled');
-const barFilledRenderUtil = require('./bar-filled');
-const meshRenderUtil = require('./mesh');
+import simpleRenderUtil from './simple';
+import slicedRenderUtil from './sliced';
+import tiledRenderUtil from './tiled';
+import radialFilledRenderUtil from './radial-filled';
+import barFilledRenderUtil from './bar-filled';
+import meshRenderUtil from './mesh';
// Inline all type switch to avoid jit deoptimization during inlined function change
-let spriteAssembler = {
- getAssembler (sprite) {
+const spriteAssembler = {
+ getAssembler(sprite) {
let util = simpleRenderUtil;
-
- switch (sprite.type) {
- case SpriteType.SLICED:
- util = slicedRenderUtil;
- break;
- case SpriteType.TILED:
- util = tiledRenderUtil;
- break;
- case SpriteType.FILLED:
- if (sprite._fillType === FillType.RADIAL) {
- util = radialFilledRenderUtil;
- }
- else {
- util = barFilledRenderUtil;
- }
- break;
- case SpriteType.MESH:
- util = meshRenderUtil;
- break;
- }
+
+ // switch (sprite.type) {
+ // case SpriteType.SLICED:
+ // util = slicedRenderUtil;
+ // break;
+ // // case SpriteType.TILED:
+ // // util = tiledRenderUtil;
+ // // break;
+ // case SpriteType.FILLED:
+ // // if (sprite._fillType === FillType.RADIAL) {
+ // // util = radialFilledRenderUtil;
+ // // }
+ // // else {
+ // util = barFilledRenderUtil;
+ // // }
+ // break;
+ // // case SpriteType.MESH:
+ // // util = meshRenderUtil;
+ // // break;
+ // }
return util;
},
// Skip invalid sprites (without own _assembler)
- updateRenderData (sprite) {
+ updateRenderData(sprite) {
return sprite.__allocedDatas;
}
};
-Sprite._assembler = spriteAssembler;
+export {
+ spriteAssembler
+}
-module.exports = spriteAssembler;
+SpriteComponent._assembler = spriteAssembler;
diff --git a/cocos/2d/renderer/webgl/assemblers/sprite/mesh.js b/cocos/3d/ui/assembler/sprite/mesh.js
similarity index 72%
rename from cocos/2d/renderer/webgl/assemblers/sprite/mesh.js
rename to cocos/3d/ui/assembler/sprite/mesh.js
index e8f024b84b..8ad6bae97f 100644
--- a/cocos/2d/renderer/webgl/assemblers/sprite/mesh.js
+++ b/cocos/3d/ui/assembler/sprite/mesh.js
@@ -23,28 +23,28 @@
THE SOFTWARE.
****************************************************************************/
-const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
+// const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
- module.exports = {
+let mesh = {
useModel: false,
- createData (sprite) {
+ createData(sprite) {
return sprite.requestRenderData();
},
- updateRenderData (sprite) {
+ updateRenderData(sprite) {
let frame = sprite.spriteFrame;
-
+
// TODO: Material API design and export from editor could affect the material activation process
// need to update the logic here
- if (frame) {
- if (!frame._original && dynamicAtlasManager) {
- dynamicAtlasManager.insertSpriteFrame(frame);
- }
- if (sprite._material._texture !== frame._texture) {
- sprite._activateMaterial();
- }
- }
+ // if (frame) {
+ // if (!frame._original && dynamicAtlasManager) {
+ // dynamicAtlasManager.insertSpriteFrame(frame);
+ // }
+ // if (sprite._material._texture !== frame._texture) {
+ // sprite._activateMaterial();
+ // }
+ // }
let renderData = sprite._renderData;
if (renderData && frame) {
@@ -53,7 +53,7 @@ const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
if (renderData.vertexCount !== vertices.x.length) {
renderData.vertexCount = vertices.x.length;
renderData.indiceCount = vertices.triangles.length;
-
+
// 1 for world vertices, 2 for local vertices
renderData.dataLength = renderData.vertexCount * 2;
@@ -72,12 +72,7 @@ const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
}
},
- updateUVs (sprite) {
- let material = sprite.getMaterial();
- let texture = material.effect.getProperty('texture');
- let texw = texture._width,
- texh = texture._height;
-
+ updateUVs(sprite) {
let vertices = sprite.spriteFrame.vertices,
u = vertices.nu,
v = vertices.nv;
@@ -93,7 +88,7 @@ const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
renderData.uvDirty = false;
},
- updateVerts (sprite) {
+ updateVerts(sprite) {
let node = sprite.node,
contentWidth = Math.abs(node.width),
contentHeight = Math.abs(node.height),
@@ -112,87 +107,72 @@ const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
offsetY = frame._offset.y,
trimX = offsetX + (originalWidth - rectWidth) / 2,
trimY = offsetY + (originalHeight - rectHeight) / 2;
-
- let scaleX = contentWidth / (sprite.trim ? rectWidth : originalWidth),
+
+ let scaleX = contentWidth / (sprite.trim ? rectWidth : originalWidth),
scaleY = contentHeight / (sprite.trim ? rectHeight : originalHeight);
let renderData = sprite._renderData;
let data = renderData._data;
-
+
if (!sprite.trim) {
for (let i = 0, l = x.length; i < l; i++) {
- let vertice = data[i+l];
+ let vertice = data[i + l];
vertice.x = (x[i]) * scaleX - appx;
vertice.y = (originalHeight - y[i]) * scaleY - appy;
}
}
else {
for (let i = 0, l = x.length; i < l; i++) {
- let vertice = data[i+l];
+ let vertice = data[i + l];
vertice.x = (x[i] - trimX) * scaleX - appx;
vertice.y = (originalHeight - y[i] - trimY) * scaleY - appy;
}
}
-
+
renderData.vertDirty = false;
},
- updateWorldVerts (sprite) {
+ updateWorldVerts(sprite) {
let node = sprite.node,
renderData = sprite._renderData,
data = renderData._data;
+
+ node._updateWorldMatrix();
let matrix = node._worldMatrix;
- let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05,
- tx = matrix.m12, ty = matrix.m13;
-
for (let i = 0, l = renderData.vertexCount; i < l; i++) {
- let local = data[i+l];
+ let local = data[i + l];
let world = data[i];
- world.x = local.x * a + local.y * c + tx;
- world.y = local.x * b + local.y * d + ty;
+ vec3.set(vec3_temp, local.x, local.y, 0);
+ vec3.transformMat4(world, vec3_temp, matrix);
}
},
- fillBuffers (sprite, renderer) {
- let node = sprite.node,
- renderData = sprite._renderData,
- data = renderData._data;
-
+ fillBuffers(sprite, /*renderer*/buffer) {
let vertices = sprite.spriteFrame.vertices;
if (!vertices) {
return;
}
-
+
// update world verts
- if (renderer.worldMatDirty) {
- this.updateWorldVerts(sprite);
- }
+ // if (renderer.worldMatDirty) {
+ this.updateWorldVerts(sprite);
+ // }
// buffer
- let buffer = renderer._meshBuffer,
- vertexOffset = buffer.byteOffset >> 2;
-
- let indiceOffset = buffer.indiceOffset,
+ let /*buffer = renderer._meshBuffer3D,*/
+ indiceOffset = buffer.indiceOffset,
vertexId = buffer.vertexOffset;
- buffer.request(renderData.vertexCount, renderData.indiceCount);
+ let node = sprite.node;
+ fillVerticesWithoutCalc3D(node, buffer, sprite._renderData, sprite._color._val);
// buffer data may be realloc, need get reference after request.
- let vbuf = buffer._vData,
- ibuf = buffer._iData;
-
- for (let i = 0, l = renderData.vertexCount; i < l; i++) {
- let vertice = data[i];
- vbuf[vertexOffset++] = vertice.x;
- vbuf[vertexOffset++] = vertice.y;
- vbuf[vertexOffset++] = vertice.u;
- vbuf[vertexOffset++] = vertice.v;
- }
-
+ let ibuf = buffer._iData;
let triangles = vertices.triangles;
-
for (let i = 0, l = triangles.length; i < l; i++) {
ibuf[indiceOffset++] = vertexId + triangles[i];
}
},
-};
\ No newline at end of file
+};
+
+export default mesh;
diff --git a/cocos/3d/ui/assembler/sprite/radial-filled.js b/cocos/3d/ui/assembler/sprite/radial-filled.js
new file mode 100644
index 0000000000..51cc742161
--- /dev/null
+++ b/cocos/3d/ui/assembler/sprite/radial-filled.js
@@ -0,0 +1,341 @@
+/****************************************************************************
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ https://www.cocos.com/
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated engine source code (the "Software"), a limited,
+ worldwide, royalty-free, non-assignable, revocable and non-exclusive license
+ to use Cocos Creator solely to develop games on your target platforms. You shall
+ not use Cocos Creator software for developing other software or tools that's
+ used for developing games. You are not granted to publish, distribute,
+ sublicense, and/or sell copies of Cocos Creator.
+
+ The software or tools in this License Agreement are licensed, not sold.
+ Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+// const dynamicAtlasManager = require('../../../../utils/dynamic-atlas/manager');
+import { fillVertices3D } from '../utils';
+
+const PI_2 = Math.PI * 2;
+
+let _vertPos = [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)];
+let _vertices = [0, 0, 0, 0];
+let _uvs = [0, 0, 0, 0, 0, 0, 0, 0];
+let _intersectPoint_1 = [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)];
+let _intersectPoint_2 = [cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0), cc.v2(0, 0)];
+let _center = cc.v2(0, 0);
+let _triangles = [];
+
+function _calcInsectedPoints(left, right, bottom, top, center, angle, intersectPoints) {
+ //left bottom, right, top
+ let sinAngle = Math.sin(angle);
+ let cosAngle = Math.cos(angle);
+ let tanAngle, cotAngle;
+ if (cosAngle !== 0) {
+ tanAngle = sinAngle / cosAngle;
+ //calculate right and left
+ if ((left - center.x) * cosAngle > 0) {
+ let yleft = center.y + tanAngle * (left - center.x);
+ intersectPoints[0].x = left;
+ intersectPoints[0].y = yleft;
+ }
+ if ((right - center.x) * cosAngle > 0) {
+ let yright = center.y + tanAngle * (right - center.x);
+
+ intersectPoints[2].x = right;
+ intersectPoints[2].y = yright;
+ }
+
+ }
+
+ if (sinAngle !== 0) {
+ cotAngle = cosAngle / sinAngle;
+ //calculate top and bottom
+ if ((top - center.y) * sinAngle > 0) {
+ let xtop = center.x + cotAngle * (top - center.y);
+ intersectPoints[3].x = xtop;
+ intersectPoints[3].y = top;
+ }
+ if ((bottom - center.y) * sinAngle > 0) {
+ let xbottom = center.x + cotAngle * (bottom - center.y);
+ intersectPoints[1].x = xbottom;
+ intersectPoints[1].y = bottom;
+ }
+
+ }
+}
+
+function _calculateVertices(sprite) {
+ let node = sprite.node,
+ width = node.width, height = node.height,
+ appx = node.anchorX * width, appy = node.anchorY * height;
+
+ let l = -appx, b = -appy,
+ r = width - appx, t = height - appy;
+
+ let vertices = _vertices;
+ vertices[0] = l;
+ vertices[1] = b;
+ vertices[2] = r;
+ vertices[3] = t;
+
+ let fillCenter = sprite._fillCenter,
+ cx = _center.x = Math.min(Math.max(0, fillCenter.x), 1) * (r - l) + l,
+ cy = _center.y = Math.min(Math.max(0, fillCenter.y), 1) * (t - b) + b;
+
+ _vertPos[0].x = _vertPos[3].x = l;
+ _vertPos[1].x = _vertPos[2].x = r;
+ _vertPos[0].y = _vertPos[1].y = b;
+ _vertPos[2].y = _vertPos[3].y = t;
+
+ _triangles.length = 0;
+ if (cx !== vertices[0]) {
+ _triangles[0] = [3, 0];
+ }
+ if (cx !== vertices[2]) {
+ _triangles[2] = [1, 2];
+ }
+ if (cy !== vertices[1]) {
+ _triangles[1] = [0, 1];
+ }
+ if (cy !== vertices[3]) {
+ _triangles[3] = [2, 3];
+ }
+}
+
+function _calculateUVs(spriteFrame) {
+ let atlasWidth = spriteFrame.width;
+ let atlasHeight = spriteFrame.height;
+ let textureRect = spriteFrame._rect;
+
+ let u0, u1, v0, v1;
+ let uvs = _uvs;
+
+ if (spriteFrame._rotated) {
+ u0 = (textureRect.x) / atlasWidth;
+ u1 = (textureRect.x + textureRect.height) / atlasWidth;
+
+ v0 = (textureRect.y) / atlasHeight;
+ v1 = (textureRect.y + textureRect.width) / atlasHeight;
+
+ uvs[0] = uvs[2] = u0;
+ uvs[4] = uvs[6] = u1;
+ uvs[3] = uvs[7] = v1;
+ uvs[1] = uvs[5] = v0;
+ }
+ else {
+ u0 = (textureRect.x) / atlasWidth;
+ u1 = (textureRect.x + textureRect.width) / atlasWidth;
+
+ v0 = (textureRect.y) / atlasHeight;
+ v1 = (textureRect.y + textureRect.height) / atlasHeight;
+
+ uvs[0] = uvs[4] = u0;
+ uvs[2] = uvs[6] = u1;
+ uvs[1] = uvs[3] = v1;
+ uvs[5] = uvs[7] = v0;
+ }
+}
+
+function _getVertAngle(start, end) {
+ let placementX, placementY;
+ placementX = end.x - start.x;
+ placementY = end.y - start.y;
+
+ if (placementX === 0 && placementY === 0) {
+ return undefined;
+ } else if (placementX === 0) {
+ if (placementY > 0) {
+ return Math.PI * 0.5;
+ } else {
+ return Math.PI * 1.5;
+ }
+ } else {
+ let angle = Math.atan(placementY / placementX);
+ if (placementX < 0) {
+ angle += Math.PI;
+ }
+
+ return angle;
+ }
+}
+
+function _generateTriangle(data, offset, vert0, vert1, vert2) {
+ let vertices = _vertices;
+ let v0x = vertices[0];
+ let v0y = vertices[1];
+ let v1x = vertices[2];
+ let v1y = vertices[3];
+
+ data[offset].x = vert0.x;
+ data[offset].y = vert0.y;
+ data[offset + 1].x = vert1.x;
+ data[offset + 1].y = vert1.y;
+ data[offset + 2].x = vert2.x;
+ data[offset + 2].y = vert2.y;
+
+ let progressX, progressY;
+ progressX = (vert0.x - v0x) / (v1x - v0x);
+ progressY = (vert0.y - v0y) / (v1y - v0y);
+ _generateUV(progressX, progressY, data, offset);
+
+ progressX = (vert1.x - v0x) / (v1x - v0x);
+ progressY = (vert1.y - v0y) / (v1y - v0y);
+ _generateUV(progressX, progressY, data, offset + 1);
+
+ progressX = (vert2.x - v0x) / (v1x - v0x);
+ progressY = (vert2.y - v0y) / (v1y - v0y);
+ _generateUV(progressX, progressY, data, offset + 2);
+}
+
+function _generateUV(progressX, progressY, data, offset) {
+ let uvs = _uvs;
+ let px1 = uvs[0] + (uvs[2] - uvs[0]) * progressX;
+ let px2 = uvs[4] + (uvs[6] - uvs[4]) * progressX;
+ let py1 = uvs[1] + (uvs[3] - uvs[1]) * progressX;
+ let py2 = uvs[5] + (uvs[7] - uvs[5]) * progressX;
+ let uv = data[offset];
+ uv.u = px1 + (px2 - px1) * progressY;
+ uv.v = py1 + (py2 - py1) * progressY;
+}
+
+let radialFilled = {
+ useModel: false,
+
+ createData(sprite) {
+ return sprite.requestRenderData();
+ },
+
+ updateRenderData(sprite) {
+ let frame = sprite.spriteFrame;
+
+ // TODO: Material API design and export from editor could affect the material activation process
+ // need to update the logic here
+ // if (frame) {
+ // if (!frame._original && dynamicAtlasManager) {
+ // dynamicAtlasManager.insertSpriteFrame(frame);
+ // }
+ // if (sprite._material._texture !== frame._texture) {
+ // sprite._activateMaterial();
+ // }
+ // }
+
+ let renderData = sprite._renderData;
+ if (renderData && frame) {
+ if (renderData.vertDirty || renderData.uvDirty) {
+ let data = renderData._data;
+
+ let fillStart = sprite._fillStart;
+ let fillRange = sprite._fillRange;
+ if (fillRange < 0) {
+ fillStart += fillRange;
+ fillRange = -fillRange;
+ }
+
+ //do round fill start [0,1), include 0, exclude 1
+ while (fillStart >= 1.0) fillStart -= 1.0;
+ while (fillStart < 0.0) fillStart += 1.0;
+
+ fillStart *= PI_2;
+ fillRange *= PI_2;
+ let fillEnd = fillStart + fillRange;
+
+ //build vertices
+ _calculateVertices(sprite);
+ //build uvs
+ _calculateUVs(frame);
+
+ _calcInsectedPoints(_vertices[0], _vertices[2], _vertices[1], _vertices[3], _center, fillStart, _intersectPoint_1);
+ _calcInsectedPoints(_vertices[0], _vertices[2], _vertices[1], _vertices[3], _center, fillStart + fillRange, _intersectPoint_2);
+
+ let offset = 0;
+ for (let triangleIndex = 0; triangleIndex < 4; ++triangleIndex) {
+ let triangle = _triangles[triangleIndex];
+ if (!triangle) {
+ continue;
+ }
+ //all in
+ if (fillRange >= PI_2) {
+ renderData.dataLength = offset + 3;
+ _generateTriangle(data, offset, _center, _vertPos[triangle[0]], _vertPos[triangle[1]]);
+ offset += 3;
+ continue;
+ }
+ //test against
+ let startAngle = _getVertAngle(_center, _vertPos[triangle[0]]);
+ let endAngle = _getVertAngle(_center, _vertPos[triangle[1]]);
+ if (endAngle < startAngle) endAngle += PI_2;
+ startAngle -= PI_2;
+ endAngle -= PI_2;
+ //testing
+ for (let testIndex = 0; testIndex < 3; ++testIndex) {
+ if (startAngle >= fillEnd) {
+ //all out
+ } else if (startAngle >= fillStart) {
+ renderData.dataLength = offset + 3;
+ if (endAngle >= fillEnd) {
+ //startAngle to fillEnd
+ _generateTriangle(data, offset, _center, _vertPos[triangle[0]], _intersectPoint_2[triangleIndex]);
+ } else {
+ //startAngle to endAngle
+ _generateTriangle(data, offset, _center, _vertPos[triangle[0]], _vertPos[triangle[1]]);
+ }
+ offset += 3;
+ } else {
+ //startAngle < fillStart
+ if (endAngle <= fillStart) {
+ //all out
+ } else if (endAngle <= fillEnd) {
+ renderData.dataLength = offset + 3;
+ //fillStart to endAngle
+ _generateTriangle(data, offset, _center, _intersectPoint_1[triangleIndex], _vertPos[triangle[1]]);
+ offset += 3;
+ } else {
+ renderData.dataLength = offset + 3;
+ //fillStart to fillEnd
+ _generateTriangle(data, offset, _center, _intersectPoint_1[triangleIndex], _intersectPoint_2[triangleIndex]);
+ offset += 3;
+ }
+ }
+ //add 2 * PI
+ startAngle += PI_2;
+ endAngle += PI_2;
+ }
+ }
+
+ renderData.indiceCount = renderData.vertexCount = offset;
+ renderData.vertDirty = renderData.uvDirty = false;
+ }
+ }
+ },
+
+ fillBuffers(comp, /*renderer*/buffer) {
+ let node = comp.node,
+ color = comp._color._val,
+ /*buffer = renderer._meshBuffer3D,*/
+ renderData = comp._renderData;
+
+ let indiceOffset = buffer.indiceOffset,
+ vertexId = buffer.vertexOffset;
+ fillVertices3D(node, buffer, renderData, color);
+
+ // buffer data may be realloc, need get reference after request.
+ let ibuf = buffer._iData;
+ for (let i = 0; i < renderData.dataLength; i++) {
+ ibuf[indiceOffset + i] = vertexId + i;
+ }
+ },
+};
+
+
+export default radialFilled;
diff --git a/cocos/3d/ui/assembler/sprite/simple.js b/cocos/3d/ui/assembler/sprite/simple.js
new file mode 100644
index 0000000000..77b47a4347
--- /dev/null
+++ b/cocos/3d/ui/assembler/sprite/simple.js
@@ -0,0 +1,169 @@
+/****************************************************************************
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ https://www.cocos.com/
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated engine source code (the "Software"), a limited,
+ worldwide, royalty-free, non-assignable, revocable and non-exclusive license
+ to use Cocos Creator solely to develop games on your target platforms. You shall
+ not use Cocos Creator software for developing other software or tools that's
+ used for developing games. You are not granted to publish, distribute,
+ sublicense, and/or sell copies of Cocos Creator.
+
+ The software or tools in this License Agreement are licensed, not sold.
+ Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+import { vec3 } from '../../../../core/vmath/index';
+// const dynamicAtlasManager = require('../../../../utils/dynamic-atlas/manager');
+let matrix = cc.mat4();
+
+let simple = {
+ useModel: false,
+
+ createData(sprite) {
+ let renderData = sprite.requestRenderData();
+ renderData.dataLength = 4;
+ renderData.vertexCount = 4;
+ renderData.indiceCount = 6;
+ return renderData;
+ },
+
+ updateRenderData(sprite) {
+ let frame = sprite._spriteFrame;
+
+ // TODO: Material API design and export from editor could affect the material activation process
+ // need to update the logic here
+ // if (frame) {
+ // if (!frame._original && dynamicAtlasManager) {
+ // dynamicAtlasManager.insertSpriteFrame(frame);
+ // }
+ // if (sprite._material._texture !== frame._texture) {
+ // sprite._activateMaterial();
+ // }
+ // }
+
+ let renderData = sprite._renderData;
+ if (renderData && frame) {
+ if (renderData.vertDirty) {
+ this.updateVerts(sprite);
+ }
+ }
+ },
+
+ fillBuffers: (function () {
+ let vec3_temps = [];
+ for (let i = 0; i < 4; i++) {
+ vec3_temps.push(vec3.create());
+ }
+ return function (sprite, /*renderer*/buffer) {
+ let data = sprite._renderData._data,
+ node = sprite.node,
+ color = sprite._color;
+
+ node.getWorldMatrix(matrix);
+
+ let /*buffer = renderer._meshBuffer3D,*/
+ vertexOffset = buffer.byteOffset >> 2,
+ indiceOffset = buffer.indiceOffset,
+ vertexId = buffer.vertexOffset;
+
+ buffer.request(4, 6);
+
+ // buffer data may be realloc, need get reference after request.
+ let vbuf = buffer.vData,
+ uintbuf = buffer.uintVData,
+ ibuf = buffer.iData;
+
+ let data0 = data[0], data3 = data[3];
+ vec3.set(vec3_temps[0], data0.x, data0.y, 0);
+ vec3.set(vec3_temps[1], data3.x, data0.y, 0);
+ vec3.set(vec3_temps[2], data0.x, data3.y, 0);
+ vec3.set(vec3_temps[3], data3.x, data3.y, 0);
+
+ // get uv from sprite frame directly
+ let uv = sprite._spriteFrame.uv;
+ for (let i = 0; i < 4; i++) {
+ // vertex
+ let vertex = vec3_temps[i];
+ vec3.transformMat4(vertex, vertex, matrix);
+
+ vbuf[vertexOffset++] = vertex.x;
+ vbuf[vertexOffset++] = vertex.y;
+ vbuf[vertexOffset++] = vertex.z;
+
+ // uv
+ let uvOffset = i * 2;
+ vbuf[vertexOffset++] = uv[0 + uvOffset];
+ vbuf[vertexOffset++] = uv[1 + uvOffset];
+
+ // color
+ vbuf[vertexOffset++] = color.r;
+ vbuf[vertexOffset++] = color.g;
+ vbuf[vertexOffset++] = color.b;
+ vbuf[vertexOffset++] = color.a;
+ // uintbuf[vertexOffset++] = color;
+ }
+
+ // fill indice data
+ ibuf[indiceOffset++] = vertexId;
+ ibuf[indiceOffset++] = vertexId + 1;
+ ibuf[indiceOffset++] = vertexId + 2;
+ ibuf[indiceOffset++] = vertexId + 1;
+ ibuf[indiceOffset++] = vertexId + 3;
+ ibuf[indiceOffset++] = vertexId + 2;
+ };
+ })(),
+
+ updateVerts(sprite) {
+ let renderData = sprite._renderData,
+ node = sprite.node,
+ data = renderData._data,
+ cw = node.width, ch = node.height,
+ appx = node.anchorX * cw, appy = node.anchorY * ch,
+ l, b, r, t;
+ // if (sprite.trim) {
+ l = -appx;
+ b = -appy;
+ r = cw - appx;
+ t = ch - appy;
+ // }
+ // else {
+ // let frame = sprite.spriteFrame,
+ // ow = frame._originalSize.width, oh = frame._originalSize.height,
+ // rw = frame._rect.width, rh = frame._rect.height,
+ // offset = frame._offset,
+ // scaleX = cw / ow, scaleY = ch / oh;
+ // let trimLeft = offset.x + (ow - rw) / 2;
+ // let trimRight = offset.x - (ow - rw) / 2;
+ // let trimBottom = offset.y + (oh - rh) / 2;
+ // let trimTop = offset.y - (oh - rh) / 2;
+ // l = trimLeft * scaleX - appx;
+ // b = trimBottom * scaleY - appy;
+ // r = cw + trimRight * scaleX - appx;
+ // t = ch + trimTop * scaleY - appy;
+ // }
+
+ data[0].x = l;
+ data[0].y = b;
+ // data[1].x = r;
+ // data[1].y = b;
+ // data[2].x = l;
+ // data[2].y = t;
+ data[3].x = r;
+ data[3].y = t;
+
+ renderData.vertDirty = false;
+ }
+};
+
+export default simple;
diff --git a/cocos/2d/renderer/webgl/assemblers/sprite/sliced.js b/cocos/3d/ui/assembler/sprite/sliced.js
similarity index 61%
rename from cocos/2d/renderer/webgl/assemblers/sprite/sliced.js
rename to cocos/3d/ui/assembler/sprite/sliced.js
index 3279497dab..20149a52ae 100644
--- a/cocos/2d/renderer/webgl/assemblers/sprite/sliced.js
+++ b/cocos/3d/ui/assembler/sprite/sliced.js
@@ -23,59 +23,63 @@
THE SOFTWARE.
****************************************************************************/
-const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
+// const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
+import { vec3 } from '../../../../core/vmath/index';
-module.exports = {
+const vec3_temp = vec3.create();
+
+let sliced = {
useModel: false,
- createData (sprite) {
+ createData(sprite) {
let renderData = sprite.requestRenderData();
// 0-4 for local verts
// 5-20 for world verts
- renderData.dataLength = 20;
+ // renderData.dataLength = 20;
+ renderData.dataLength = 16;
renderData.vertexCount = 16;
renderData.indiceCount = 54;
return renderData;
},
- updateRenderData (sprite, batchData) {
+ updateRenderData(sprite, batchData) {
let frame = sprite.spriteFrame;
-
+
// TODO: Material API design and export from editor could affect the material activation process
// need to update the logic here
- if (frame) {
- if (!frame._original && dynamicAtlasManager) {
- dynamicAtlasManager.insertSpriteFrame(frame);
- }
- if (sprite._material._texture !== frame._texture) {
- sprite._activateMaterial();
- }
- }
+ // if (frame) {
+ // if (!frame._original && dynamicAtlasManager) {
+ // dynamicAtlasManager.insertSpriteFrame(frame);
+ // }
+ // if (sprite._material._texture !== frame._texture) {
+ // sprite._activateMaterial();
+ // }
+ // }
let renderData = sprite._renderData;
if (renderData && frame) {
let vertDirty = renderData.vertDirty;
if (vertDirty) {
this.updateVerts(sprite);
- this.updateWorldVerts(sprite);
+ // this.updateWorldVerts(sprite);
}
}
},
-
- updateVerts (sprite) {
+
+ updateVerts(sprite) {
let renderData = sprite._renderData,
data = renderData._data,
node = sprite.node,
width = node.width, height = node.height,
appx = node.anchorX * width, appy = node.anchorY * height;
-
+
let frame = sprite.spriteFrame;
let leftWidth = frame.insetLeft;
let rightWidth = frame.insetRight;
let topHeight = frame.insetTop;
let bottomHeight = frame.insetBottom;
-
+
let sizableWidth = width - leftWidth - rightWidth;
let sizableHeight = height - topHeight - bottomHeight;
let xScale = width / (leftWidth + rightWidth);
@@ -84,55 +88,78 @@ module.exports = {
yScale = (isNaN(yScale) || yScale > 1) ? 1 : yScale;
sizableWidth = sizableWidth < 0 ? 0 : sizableWidth;
sizableHeight = sizableHeight < 0 ? 0 : sizableHeight;
-
- data[0].x = -appx;
- data[0].y = -appy;
- data[1].x = leftWidth * xScale - appx;
- data[1].y = bottomHeight * yScale - appy;
- data[2].x = data[1].x + sizableWidth;
- data[2].y = data[1].y + sizableHeight;
- data[3].x = width - appx;
- data[3].y = height - appy;
+
+ let value = [
+ cc.v3(-appx, -appy, 0),
+ cc.v3(leftWidth * xScale - appx, bottomHeight * yScale - appy, 0),
+ cc.v3(leftWidth * xScale - appx + sizableWidth, bottomHeight * yScale - appy + sizableHeight, 0),
+ cc.v3(width - appx, height - appy, 0)
+ ];
+
+ for (let row = 0; row < 4; ++row) {
+ let rowD = value[row];
+ for (let col = 0; col < 4; ++col) {
+ let colD = value[col];
+ let world = data[row * 4 + col];
+ vec3.set(world, colD.x, rowD.y, 0);
+ // vec3.transformMat4(world, vec3_temp, matrix);
+ }
+ }
+
+ // data[0].x = -appx;
+ // data[0].y = -appy;
+ // data[1].x = leftWidth * xScale - appx;
+ // data[1].y = bottomHeight * yScale - appy;
+ // data[2].x = data[1].x + sizableWidth;
+ // data[2].y = data[1].y + sizableHeight;
+ // data[3].x = width - appx;
+ // data[3].y = height - appy;
renderData.vertDirty = false;
},
- fillBuffers (sprite, renderer) {
- if (renderer.worldMatDirty) {
- this.updateWorldVerts(sprite);
- }
+ fillBuffers(sprite, /*renderer*/buffer) {
+ // if (renderer.worldMatDirty) {
+ this.updateWorldVerts(sprite);
+ // }
let renderData = sprite._renderData,
+ node = sprite.node,
+ color = sprite._color._val,
data = renderData._data;
- let buffer = renderer._meshBuffer,
+ let /*buffer = is3DNode ? renderer._meshBuffer3D : renderer._meshBuffer,*/
vertexOffset = buffer.byteOffset >> 2,
- vertexCount = renderData.vertexCount;
-
- let indiceOffset = buffer.indiceOffset,
+ vertexCount = renderData.vertexCount,
+ indiceOffset = buffer.indiceOffset,
vertexId = buffer.vertexOffset;
let uvSliced = sprite.spriteFrame.uvSliced;
-
+
buffer.request(vertexCount, renderData.indiceCount);
// buffer data may be realloc, need get reference after request.
let vbuf = buffer._vData,
+ uintbuf = buffer._uintVData,
ibuf = buffer._iData;
- for (let i = 4; i < 20; ++i) {
+ // for (let i = 4; i < 20; ++i) {
+ for (let i = 0; i < 16; ++i) {
let vert = data[i];
- let uvs = uvSliced[i - 4];
+ // let uvs = uvSliced[i - 4];
+ let uvs = uvSliced[i];
vbuf[vertexOffset++] = vert.x;
vbuf[vertexOffset++] = vert.y;
+ vbuf[vertexOffset++] = vert.z;
vbuf[vertexOffset++] = uvs.u;
vbuf[vertexOffset++] = uvs.v;
+ uintbuf[vertexOffset++] = color;
}
for (let r = 0; r < 3; ++r) {
for (let c = 0; c < 3; ++c) {
- let start = vertexId + r*4 + c;
+ let start = vertexId + r * 4 + c;
ibuf[indiceOffset++] = start;
ibuf[indiceOffset++] = start + 1;
ibuf[indiceOffset++] = start + 4;
@@ -143,22 +170,23 @@ module.exports = {
}
},
- updateWorldVerts (sprite) {
+ updateWorldVerts(sprite) {
let node = sprite.node,
data = sprite._renderData._data;
-
- let matrix = node._worldMatrix,
- a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05,
- tx = matrix.m12, ty = matrix.m13;
-
+
+ // node._updateWorldMatrix();
+ // let matrix = node._worldMatrix;
for (let row = 0; row < 4; ++row) {
let rowD = data[row];
for (let col = 0; col < 4; ++col) {
let colD = data[col];
- let world = data[4 + row*4 + col];
- world.x = colD.x*a + rowD.y*c + tx;
- world.y = colD.x*b + rowD.y*d + ty;
+ let world = data[4 + row * 4 + col];
+
+ vec3.set(vec3_temp, colD.x, rowD.y, 0);
+ // vec3.transformMat4(world, vec3_temp, matrix);
}
}
},
};
+
+export default sliced;
diff --git a/cocos/3d/ui/assembler/sprite/tiled.js b/cocos/3d/ui/assembler/sprite/tiled.js
new file mode 100644
index 0000000000..0ab4c25a0f
--- /dev/null
+++ b/cocos/3d/ui/assembler/sprite/tiled.js
@@ -0,0 +1,222 @@
+/****************************************************************************
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos.com
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated engine source code (the "Software"), a limited,
+ worldwide, royalty-free, non-assignable, revocable and non-exclusive license
+ to use Cocos Creator solely to develop games on your target platforms. You shall
+ not use Cocos Creator software for developing other software or tools that's
+ used for developing games. You are not granted to publish, distribute,
+ sublicense, and/or sell copies of Cocos Creator.
+
+ The software or tools in this License Agreement are licensed, not sold.
+ Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+// const dynamicAtlasManager = require('../../../utils/dynamic-atlas/manager');
+import { vec3 } from '../../../../core/vmath/index';
+
+let tilled = {
+ useModel: false,
+
+ vertexOffset: 6,
+ uvOffset: 3,
+ colorOffset: 5,
+
+ createData(sprite) {
+ return sprite.requestRenderData();
+ },
+
+ updateRenderData(sprite) {
+ let frame = sprite.spriteFrame;
+
+ // TODO: Material API design and export from editor could affect the material activation process
+ // need to update the logic here
+ // if (frame) {
+ // if (!frame._original && dynamicAtlasManager) {
+ // dynamicAtlasManager.insertSpriteFrame(frame);
+ // }
+ // if (sprite._material._texture !== frame._texture) {
+ // sprite._activateMaterial();
+ // }
+ // }
+
+ let renderData = sprite._renderData;
+ if (!frame || !renderData ||
+ !(renderData.uvDirty || renderData.vertDirty))
+ return;
+
+ let node = sprite.node,
+ // contentWidth = Math.abs(node.width),
+ // contentHeight = Math.abs(node.height),
+ contentWidth = Math.abs(node.width),
+ contentHeight = Math.abs(node.height),
+ appx = node.anchorX * contentWidth,
+ appy = node.anchorY * contentHeight;
+ node._updateWorldMatrix();
+
+ let rect = frame._rect,
+ rectWidth = rect.width,
+ rectHeight = rect.height,
+ hRepeat = contentWidth / rectWidth,
+ vRepeat = contentHeight / rectHeight,
+ row = Math.ceil(vRepeat),
+ col = Math.ceil(hRepeat);
+
+ let data = renderData._data;
+ renderData.dataLength = Math.max(8, row + 1, col + 1);
+
+ for (let i = 0; i <= col; ++i) {
+ data[i].x = Math.min(rectWidth * i, contentWidth) - appx;
+ }
+ for (let i = 0; i <= row; ++i) {
+ data[i].y = Math.min(rectHeight * i, contentHeight) - appy;
+ }
+
+ // update data property
+ renderData.vertexCount = row * col * 4;
+ renderData.indiceCount = row * col * 6;
+ renderData.uvDirty = false;
+ renderData.vertDirty = false;
+ },
+
+ fillBuffers(sprite, /*renderer*/buffer) {
+ let node = sprite.node,
+ color = sprite._color._val,
+ renderData = sprite._renderData,
+ data = renderData._data;
+
+ // buffer
+ let /*buffer = is3DNode ? renderer._meshBuffer3D : renderer._meshBuffer,*/
+ vertexOffset = buffer.byteOffset >> 2,
+ indiceOffset = buffer.indiceOffset,
+ vertexId = buffer.vertexOffset;
+
+ buffer.request(renderData.vertexCount, renderData.indiceCount);
+
+ // buffer data may be realloc, need get reference after request.
+ let vbuf = buffer._vData,
+ uintbuf = buffer._uintVData,
+ ibuf = buffer._iData;
+
+ let rotated = sprite.spriteFrame._rotated;
+ let uv = sprite.spriteFrame.uv;
+ let rect = sprite.spriteFrame._rect;
+ let contentWidth = Math.abs(node.width);
+ let contentHeight = Math.abs(node.height);
+ let hRepeat = contentWidth / rect.width;
+ let vRepeat = contentHeight / rect.height;
+ let row = Math.ceil(vRepeat),
+ col = Math.ceil(hRepeat);
+
+ let matrix = node._worldMatrix;
+
+ this.fillVertices(vbuf, vertexOffset, matrix, row, col, data);
+
+ let offset = this.vertexOffset, uvOffset = this.uvOffset, colorOffset = this.colorOffset;
+ let offset1 = offset, offset2 = offset * 2, offset3 = offset * 3, offset4 = offset * 4;
+ let coefu, coefv;
+ for (let yindex = 0, ylength = row; yindex < ylength; ++yindex) {
+ coefv = Math.min(1, vRepeat - yindex);
+ for (let xindex = 0, xlength = col; xindex < xlength; ++xindex) {
+ coefu = Math.min(1, hRepeat - xindex);
+
+ let vertexOffsetU = vertexOffset + uvOffset;
+ let vertexOffsetV = vertexOffsetU + 1;
+ // UV
+ if (rotated) {
+ // lb
+ vbuf[vertexOffsetU] = uv[0];
+ vbuf[vertexOffsetV] = uv[1];
+ // rb
+ vbuf[vertexOffsetU + offset1] = uv[0];
+ vbuf[vertexOffsetV + offset1] = uv[1] + (uv[7] - uv[1]) * coefu;
+ // lt
+ vbuf[vertexOffsetU + offset2] = uv[0] + (uv[6] - uv[0]) * coefv;
+ vbuf[vertexOffsetV + offset2] = uv[1];
+ // rt
+ vbuf[vertexOffsetU + offset3] = vbuf[vertexOffsetU + offset2];
+ vbuf[vertexOffsetV + offset3] = vbuf[vertexOffsetV + offset1];
+ }
+ else {
+ // lb
+ vbuf[vertexOffsetU] = uv[0];
+ vbuf[vertexOffsetV] = uv[1];
+ // rb
+ vbuf[vertexOffsetU + offset1] = uv[0] + (uv[6] - uv[0]) * coefu;
+ vbuf[vertexOffsetV + offset1] = uv[1];
+ // lt
+ vbuf[vertexOffsetU + offset2] = uv[0];
+ vbuf[vertexOffsetV + offset2] = uv[1] + (uv[7] - uv[1]) * coefv;
+ // rt
+ vbuf[vertexOffsetU + offset3] = vbuf[vertexOffsetU + offset1];
+ vbuf[vertexOffsetV + offset3] = vbuf[vertexOffsetV + offset2];
+ }
+ // color
+ uintbuf[vertexOffset + colorOffset] = color;
+ uintbuf[vertexOffset + colorOffset + offset1] = color;
+ uintbuf[vertexOffset + colorOffset + offset2] = color;
+ uintbuf[vertexOffset + colorOffset + offset3] = color;
+ vertexOffset += offset4;
+ }
+ }
+
+ // update indices
+ let length = renderData.indiceCount;
+ for (let i = 0; i < length; i += 6) {
+ ibuf[indiceOffset++] = vertexId;
+ ibuf[indiceOffset++] = vertexId + 1;
+ ibuf[indiceOffset++] = vertexId + 2;
+ ibuf[indiceOffset++] = vertexId + 1;
+ ibuf[indiceOffset++] = vertexId + 3;
+ ibuf[indiceOffset++] = vertexId + 2;
+ vertexId += 4;
+ }
+ },
+
+ fillVertices: (function () {
+ let vec3_temps = [];
+ for (let i = 0; i < 4; i++) {
+ vec3_temps.push(vec3.create());
+ }
+ return function (vbuf, vertexOffset, matrix, row, col, data) {
+ let x, x1, y, y1;
+ for (let yindex = 0, ylength = row; yindex < ylength; ++yindex) {
+ y = data[yindex].y;
+ y1 = data[yindex + 1].y;
+ for (let xindex = 0, xlength = col; xindex < xlength; ++xindex) {
+ x = data[xindex].x;
+ x1 = data[xindex + 1].x;
+
+ vec3.set(vec3_temps[0], x, y, 0);
+ vec3.set(vec3_temps[1], x1, y, 0);
+ vec3.set(vec3_temps[2], x, y1, 0);
+ vec3.set(vec3_temps[3], x1, y1, 0);
+
+ for (let i = 0; i < 4; i++) {
+ let vec3_temp = vec3_temps[i];
+ vec3.transformMat4(vec3_temp, vec3_temp, matrix);
+ let offset = i * 6;
+ vbuf[vertexOffset + offset] = vec3_temp.x;
+ vbuf[vertexOffset + offset + 1] = vec3_temp.y;
+ vbuf[vertexOffset + offset + 2] = vec3_temp.z;
+ }
+
+ vertexOffset += 24;
+ }
+ }
+ };
+ })(),
+};
+
+export default tilled;
diff --git a/cocos/3d/ui/assembler/utils.js b/cocos/3d/ui/assembler/utils.js
new file mode 100644
index 0000000000..e69ffdae82
--- /dev/null
+++ b/cocos/3d/ui/assembler/utils.js
@@ -0,0 +1,193 @@
+
+import { vec3, mat4 } from '../../../core/vmath/index';
+
+let vec3_temp = vec3.create();
+let _worldMatrix = mat4.create();
+
+export function fillVertices(node, buffer, renderData, color) {
+ let data = renderData._data,
+ vertexOffset = buffer.byteOffset >> 2;
+
+ let vertexCount = renderData.vertexCount;
+ buffer.request(vertexCount, renderData.indiceCount);
+
+ // buffer data may be realloc, need get reference after request.
+ let vbuf = buffer._vData,
+ uintbuf = buffer._uintVData;
+
+ // let matrix = node._worldMatrix;
+ node.getWorldMatrix(_worldMatrix);
+ let matrix = _worldMatrix;
+ let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05,
+ tx = matrix.m12, ty = matrix.m13;
+ for (let i = 0; i < vertexCount; i++) {
+ let vert = data[i];
+ vbuf[vertexOffset++] = vert.x * a + vert.y * c + tx;
+ vbuf[vertexOffset++] = vert.x * b + vert.y * d + ty;
+ vbuf[vertexOffset++] = vert.u;
+ vbuf[vertexOffset++] = vert.v;
+ uintbuf[vertexOffset++] = color;
+ }
+}
+
+export function fillMeshVertices(node, buffer, renderData, color) {
+ let data = renderData._data,
+ vertexOffset = buffer.byteOffset >> 2;
+
+ let vertexCount = renderData.vertexCount,
+ indiceOffset = buffer.indiceOffset,
+ vertexId = buffer.vertexOffset;
+
+ buffer.request(vertexCount, renderData.indiceCount);
+
+ // buffer data may be realloc, need get reference after request.
+ let vbuf = buffer._vData,
+ uintbuf = buffer._uintVData,
+ ibuf = buffer._iData;
+
+ // let matrix = node._worldMatrix;
+ node.getWorldMatrix(_worldMatrix);
+ let matrix = _worldMatrix;
+ let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05,
+ tx = matrix.m12, ty = matrix.m13;
+ for (let i = 0; i < vertexCount; i++) {
+ let vert = data[i];
+ vbuf[vertexOffset++] = vert.x * a + vert.y * c + tx;
+ vbuf[vertexOffset++] = vert.x * b + vert.y * d + ty;
+ vbuf[vertexOffset++] = vert.u;
+ vbuf[vertexOffset++] = vert.v;
+ uintbuf[vertexOffset++] = color;
+ }
+
+ // fill indice data
+ for (let i = 0, count = vertexCount / 4; i < count; i++) {
+ let start = vertexId + i * 4;
+ ibuf[indiceOffset++] = start;
+ ibuf[indiceOffset++] = start + 1;
+ ibuf[indiceOffset++] = start + 2;
+ ibuf[indiceOffset++] = start + 1;
+ ibuf[indiceOffset++] = start + 3;
+ ibuf[indiceOffset++] = start + 2;
+ }
+}
+
+export function fillVertices3D(node, buffer, renderData, color) {
+ let data = renderData._data,
+ vertexOffset = buffer.byteOffset >> 2;
+
+ let vertexCount = renderData.vertexCount;
+ buffer.request(vertexCount, renderData.indiceCount);
+
+ // buffer data may be realloc, need get reference after request.
+ let vbuf = buffer._vData,
+ uintbuf = buffer._uintVData;
+
+ // let matrix = node._worldMatrix;
+ // node.getWorldMatrix(_worldMatrix);
+
+ for (let i = 0; i < vertexCount; i++) {
+ let vert = data[i];
+ vec3.set(vec3_temp, vert.x, vert.y, 0);
+ // vec3.transformMat4(vec3_temp, vec3_temp, _worldMatrix);
+ vbuf[vertexOffset++] = vec3_temp.x;
+ vbuf[vertexOffset++] = vec3_temp.y;
+ vbuf[vertexOffset++] = vec3_temp.z;
+ vbuf[vertexOffset++] = vert.u;
+ vbuf[vertexOffset++] = vert.v;
+ uintbuf[vertexOffset++] = color;
+ }
+}
+
+export function fillMeshVertices3D(node, buffer, renderData, color) {
+ let data = renderData._data,
+ vertexOffset = buffer.byteOffset >> 2;
+
+ let vertexCount = renderData.vertexCount,
+ indiceOffset = buffer.indiceOffset,
+ vertexId = buffer.vertexOffset;
+
+ buffer.request(vertexCount, renderData.indiceCount);
+
+ // buffer data may be realloc, need get reference after request.
+ let vbuf = buffer._vData,
+ uintbuf = buffer._uintVData,
+ ibuf = buffer._iData;
+
+ // let matrix = node._worldMatrix;
+ // node.getWorldMatrix(_worldMatrix);
+
+ for (let i = 0; i < vertexCount; i++) {
+ let vert = data[i];
+ vec3.set(vec3_temp, vert.x, vert.y, 0);
+ // vec3.transformMat4(vec3_temp, vec3_temp, _worldMatrix);
+ vbuf[vertexOffset++] = vec3_temp.x;
+ vbuf[vertexOffset++] = vec3_temp.y;
+ vbuf[vertexOffset++] = vec3_temp.z;
+ vbuf[vertexOffset++] = vert.u;
+ vbuf[vertexOffset++] = vert.v;
+ uintbuf[vertexOffset++] = color;
+ }
+
+ // fill indice data
+ for (let i = 0, count = vertexCount / 4; i < count; i++) {
+ let start = vertexId + i * 4;
+ ibuf[indiceOffset++] = start;
+ ibuf[indiceOffset++] = start + 1;
+ ibuf[indiceOffset++] = start + 2;
+ ibuf[indiceOffset++] = start + 1;
+ ibuf[indiceOffset++] = start + 3;
+ ibuf[indiceOffset++] = start + 2;
+ }
+}
+
+export function fillVerticesWithoutCalc(node, buffer, renderData, color) {
+ let data = renderData._data,
+ vertexOffset = buffer.byteOffset >> 2;
+
+ let vertexCount = renderData.vertexCount;
+ buffer.request(vertexCount, renderData.indiceCount);
+
+ // buffer data may be realloc, need get reference after request.
+ let vbuf = buffer._vData,
+ uintbuf = buffer._uintVData;
+
+ for (let i = 0; i < vertexCount; i++) {
+ let vert = data[i];
+ vbuf[vertexOffset++] = vert.x;
+ vbuf[vertexOffset++] = vert.y;
+ vbuf[vertexOffset++] = vert.u;
+ vbuf[vertexOffset++] = vert.v;
+ uintbuf[vertexOffset++] = color;
+ }
+}
+
+export function fillVerticesWithoutCalc3D(node, buffer, renderData, color) {
+ let data = renderData._data,
+ vertexOffset = buffer.byteOffset >> 2;
+
+ let vertexCount = renderData.vertexCount;
+ buffer.request(vertexCount, renderData.indiceCount);
+
+ // buffer data may be realloc, need get reference after request.
+ let vbuf = buffer._vData,
+ uintbuf = buffer._uintVData;
+
+ for (let i = 0; i < vertexCount; i++) {
+ let vert = data[i];
+ vbuf[vertexOffset++] = vert.x;
+ vbuf[vertexOffset++] = vert.y;
+ vbuf[vertexOffset++] = vert.z;
+ vbuf[vertexOffset++] = vert.u;
+ vbuf[vertexOffset++] = vert.v;
+ uintbuf[vertexOffset++] = color;
+ }
+}
+
+// module.exports = {
+// fillVertices: fillVertices,
+// fillMeshVertices: fillMeshVertices,
+// fillVertices3D: fillVertices3D,
+// fillMeshVertices3D: fillMeshVertices3D,
+// fillVerticesWithoutCalc: fillVerticesWithoutCalc,
+// fillVerticesWithoutCalc3D: fillVerticesWithoutCalc3D
+// };
diff --git a/cocos/2d/ui/CCLayout.js b/cocos/3d/ui/components/CCLayout.js
similarity index 100%
rename from cocos/2d/ui/CCLayout.js
rename to cocos/3d/ui/components/CCLayout.js
diff --git a/cocos/3d/ui/components/button-component.ts b/cocos/3d/ui/components/button-component.ts
new file mode 100644
index 0000000000..d9a5c2b319
--- /dev/null
+++ b/cocos/3d/ui/components/button-component.ts
@@ -0,0 +1,802 @@
+/****************************************************************************
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos.com
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated engine source code (the "Software"), a limited,
+ worldwide, royalty-free, non-assignable, revocable and non-exclusive license
+ to use Cocos Creator solely to develop games on your target platforms. You shall
+ not use Cocos Creator software for developing other software or tools that's
+ used for developing games. You are not granted to publish, distribute,
+ sublicense, and/or sell copies of Cocos Creator.
+
+ The software or tools in this License Agreement are licensed, not sold.
+ Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+// @ts-check
+import SpriteFrame from '../../../assets/CCSpriteFrame';
+import ComponentEventHandler from '../../../components/CCComponentEventHandler';
+import { Component} from '../../../components/component';
+import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator';
+import Event from '../../../core/event/event';
+import { lerp } from '../../../core/utils/misc';
+import { Color, Vec3 } from '../../../core/value-types/index';
+import * as math from '../../../core/vmath/index';
+import { Node } from '../../../scene-graph';
+import SpriteComponent from './sprite-component';
+
+/**
+ * !#en Enum for transition type.
+ * !#zh 过渡类型
+ * @enum Button.Transition
+ */
+const Transition = cc.Enum({
+ /**
+ * !#en The none type.
+ * !#zh 不做任何过渡
+ * @property {Number} NONE
+ */
+ NONE: 0,
+
+ /**
+ * !#en The color type.
+ * !#zh 颜色过渡
+ * @property {Number} COLOR
+ */
+ COLOR: 1,
+
+ /**
+ * !#en The sprite type.
+ * !#zh 精灵过渡
+ * @property {Number} SPRITE
+ */
+ SPRITE: 2,
+ /**
+ * !#en The scale type
+ * !#zh 缩放过渡
+ * @property {Number} SCALE
+ */
+ SCALE: 3,
+});
+
+/**
+ * !#en
+ * Button has 4 Transition types
+ * When Button state changed:
+ * If Transition type is Button.Transition.NONE, Button will do nothing
+ * If Transition type is Button.Transition.COLOR, Button will change target's color
+ * If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite
+ * If Transition type is Button.Transition.SCALE, Button will change target node's scale
+ *
+ * Button will trigger 5 events:
+ * Button.EVENT_TOUCH_DOWN
+ * Button.EVENT_TOUCH_UP
+ * Button.EVENT_HOVER_IN
+ * Button.EVENT_HOVER_MOVE
+ * Button.EVENT_HOVER_OUT
+ *
+ * !#zh
+ * 按钮组件。可以被按下,或者点击。
+ *
+ * 按钮可以通过修改 Transition 来设置按钮状态过渡的方式:
+ * -Button.Transition.NONE // 不做任何过渡
+ * -Button.Transition.COLOR // 进行颜色之间过渡
+ * -Button.Transition.SPRITE // 进行精灵之间过渡
+ * -Button.Transition.SCALE // 进行缩放过渡
+ *
+ * 按钮可以绑定事件(但是必须要在按钮的 Node 上才能绑定事件):
+ * // 以下事件可以在全平台上都触发
+ * -cc.NodeUI.EventType.TOUCH_START // 按下时事件
+ * -cc.NodeUI.EventType.TOUCH_Move // 按住移动后事件
+ * -cc.NodeUI.EventType.TOUCH_END // 按下后松开后事件
+ * -cc.NodeUI.EventType.TOUCH_CANCEL // 按下取消事件
+ * // 以下事件只在 PC 平台上触发
+ * -cc.NodeUI.EventType.MOUSE_DOWN // 鼠标按下时事件
+ * -cc.NodeUI.EventType.MOUSE_MOVE // 鼠标按住移动后事件
+ * -cc.NodeUI.EventType.MOUSE_ENTER // 鼠标进入目标事件
+ * -cc.NodeUI.EventType.MOUSE_LEAVE // 鼠标离开目标事件
+ * -cc.NodeUI.EventType.MOUSE_UP // 鼠标松开事件
+ * -cc.NodeUI.EventType.MOUSE_WHEEL // 鼠标滚轮事件
+ *
+ * @class Button
+ * @extends Component
+ * @example
+ *
+ * // Add an event to the button.
+ * button.node.on(cc.NodeUI.EventType.TOUCH_START, function (event) {
+ * cc.log("This is a callback after the trigger event");
+ * });
+ * // You could also add a click event
+ * //Note: In this way, you can't get the touch event info, so use it wisely.
+ * button.node.on('click', function (button) {
+ * //The event is a custom event, you could get the Button component via first argument
+ * })
+ *
+ */
+
+@ccclass('cc.ButtonComponent')
+@executionOrder(100)
+@menu('UI/Button')
+@executeInEditMode
+export default class ButtonComponent extends Component {
+
+ /**
+ * !#en
+ * Whether the Button is disabled.
+ * If true, the Button will trigger event and do transition.
+ * !#zh
+ * 按钮事件是否被响应,如果为 false,则按钮将被禁用。
+ * @property {Boolean} interactable
+ * @default true
+ */
+ @property
+ get interactable () {
+ return this._interactable;
+ }
+
+ set interactable (value: boolean) {
+ if (CC_EDITOR) {
+ if (value) {
+ this._previousNormalSprite = this.normalSprite;
+ } else {
+ this.normalSprite = this._previousNormalSprite;
+ }
+ }
+ this._interactable = !this._interactable;
+ this._updateState();
+
+ if (!this._interactable) {
+ this._resetState();
+ }
+ }
+
+ set _resizeToTarget (value: boolean) {
+ if (value) {
+ this._resizeNodeToTargetNode();
+ }
+ }
+
+ /**
+ * !#en When this flag is true, Button target sprite will turn gray when interactable is false.
+ * !#zh 如果这个标记为 true,当 button 的 interactable 属性为 false 的时候,会使用内置 shader 让 button 的 target 节点的 sprite 组件变灰
+ * @property {Boolean} enableAutoGrayEffect
+ */
+ // enableAutoGrayEffect: {
+ // default: false,
+ // tooltip: CC_DEV && 'i18n:COMPONENT.button.auto_gray_effect',
+ // notify() {
+ // this._updateDisabledState();
+ // }
+ // },
+
+ /**
+ * !#en Transition type
+ * !#zh 按钮状态改变时过渡方式。
+ * @property {Button.Transition} transition
+ * @default Button.Transition.Node
+ */
+ @property({
+ type: Transition,
+ })
+ get transition () {
+ return this._transition;
+ }
+
+ set transition (value: number) {
+ if (this._transition === value) {
+ return;
+ }
+
+ this._transition = value;
+ }
+
+ // color transition
+
+ /**
+ * !#en Normal state color.
+ * !#zh 普通状态下按钮所显示的颜色。
+ * @property {Color} normalColor
+ */
+ @property
+ get normalColor () {
+ return this._normalColor;
+ }
+
+ set normalColor (value: Color) {
+ if (this._normalColor === value) {
+ return;
+ }
+
+ this._normalColor = value;
+ this._updateState();
+ }
+
+ /**
+ * !#en Pressed state color
+ * !#zh 按下状态时按钮所显示的颜色。
+ * @property {Color} pressedColor
+ */
+ @property
+ get pressedColor () {
+ return this._pressColor;
+ }
+
+ set pressedColor (value: Color) {
+ if (this._pressColor === value) {
+ return;
+ }
+
+ this._pressColor = value;
+ }
+
+ /**
+ * !#en Hover state color
+ * !#zh 悬停状态下按钮所显示的颜色。
+ * @property {Color} hoverColor
+ */
+ @property
+ get hoverColor () {
+ return this._hoverColor;
+ }
+
+ set hoverColor (value: Color) {
+ if (this._hoverColor === value) {
+ return;
+ }
+
+ this._hoverColor = value;
+ }
+ /**
+ * !#en Disabled state color
+ * !#zh 禁用状态下按钮所显示的颜色。
+ * @property {Color} disabledColor
+ */
+ @property
+ get disabledColor () {
+ return this._disabledColor;
+ }
+
+ set disabledColor (value: Color) {
+ if (this._disabledColor === value) {
+ return;
+ }
+
+ this._disabledColor = value;
+ this._updateState();
+ }
+
+ /**
+ * !#en Color and Scale transition duration
+ * !#zh 颜色过渡和缩放过渡时所需时间
+ * @property {Number} duration
+ */
+ @property({
+ min: 0,
+ max: 10,
+ })
+ get duration () {
+ return this._duration;
+ }
+
+ set duration (value: number) {
+ if (this._duration === value) {
+ return;
+ }
+
+ this._duration = 0.1;
+ }
+
+ /**
+ * !#en When user press the button, the button will zoom to a scale.
+ * The final scale of the button equals (button original scale * zoomScale)
+ * !#zh 当用户点击按钮后,按钮会缩放到一个值,这个值等于 Button 原始 scale * zoomScale
+ * @property {Number} zoomScale
+ */
+ @property
+ get zoomScale () {
+ return this._zoomScale;
+ }
+
+ set zoomScale (value: number) {
+ if (this._zoomScale === value) {
+ return;
+ }
+
+ this._zoomScale = value;
+ }
+
+ // sprite transition
+ /**
+ * !#en Normal state sprite
+ * !#zh 普通状态下按钮所显示的 Sprite 。
+ * @property {SpriteFrame} normalSprite
+ */
+ @property({
+ type: SpriteFrame,
+ })
+ get normalSprite () {
+ return this._normalSprite;
+ }
+
+ set normalSprite (value: SpriteFrame) {
+ if (this._normalSprite === value) {
+ return;
+ }
+
+ this._normalSprite = value;
+ this._updateState();
+ }
+
+ /**
+ * !#en Pressed state sprite
+ * !#zh 按下状态时按钮所显示的 Sprite 。
+ * @property {SpriteFrame} pressedSprite
+ */
+ @property({
+ type: SpriteFrame,
+ })
+ get pressedSprite () {
+ return this._pressedSprite;
+ }
+
+ set pressedSprite (value: SpriteFrame) {
+ if (this._pressedSprite === value) {
+ return;
+ }
+
+ this._pressedSprite = value;
+ this._updateState();
+ }
+
+ /**
+ * !#en Hover state sprite
+ * !#zh 悬停状态下按钮所显示的 Sprite 。
+ * @property {SpriteFrame} hoverSprite
+ */
+ @property({
+ type: SpriteFrame,
+ })
+ get hoverSprite () {
+ return this._hoverSprite;
+ }
+
+ set hoverSprite (value: SpriteFrame) {
+ if (this._hoverSprite === value) {
+ return;
+ }
+
+ this._hoverSprite = value;
+ this._updateState();
+ }
+
+ /**
+ * !#en Disabled state sprite
+ * !#zh 禁用状态下按钮所显示的 Sprite 。
+ * @return {SpriteFrame}
+ */
+ @property({
+ type: SpriteFrame,
+ })
+ get disabledSprite () {
+ return this._disabledSprite;
+ }
+
+ set disabledSprite (value: SpriteFrame) {
+ if (this._disabledSprite === value) {
+ return;
+ }
+
+ this._disabledSprite = value;
+ this._updateState();
+ }
+
+ /**
+ * !#en
+ * Transition target.
+ * When Button state changed:
+ * If Transition type is Button.Transition.NONE, Button will do nothing
+ * If Transition type is Button.Transition.COLOR, Button will change target's color
+ * If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite
+ * !#zh
+ * 需要过渡的目标。
+ * 当前按钮状态改变规则:
+ * -如果 Transition type 选择 Button.Transition.NONE,按钮不做任何过渡。
+ * -如果 Transition type 选择 Button.Transition.COLOR,按钮会对目标颜色进行颜色之间的过渡。
+ * -如果 Transition type 选择 Button.Transition.Sprite,按钮会对目标 Sprite 进行 Sprite 之间的过渡。
+ * @property {Node} target
+ */
+ @property
+ get target () {
+ return this._target;
+ }
+
+ set target (value: Node) {
+ if (this._target === value) {
+ return;
+ }
+
+ this._target = value;
+ this._applyTarget();
+ }
+
+ /**
+ * !#en If Button is clicked, it will trigger event's handler
+ * !#zh 按钮的点击事件列表。
+ * @property {ComponentEventHandler[]} clickEvents
+ */
+ @property({
+ type: ComponentEventHandler,
+ })
+ get clickEvents () {
+ return this._clickEvents;
+ }
+
+ set clickEvents (value: ComponentEventHandler[]) {
+ this._clickEvents = value;
+ }
+
+ public static Transition = Transition;
+ @property
+ public _interactable: boolean = true;
+ @property
+ public _transition: number = Transition.NONE;
+ @property
+ public _normalColor: Color = cc.color(214, 214, 214);
+ @property
+ public _hoverColor: Color = cc.color(211, 211, 211);
+ @property
+ public _pressColor: Color = cc.Color.WHITE;
+ @property
+ public _disabledColor: Color = cc.color(124, 124, 124);
+ @property
+ public _normalSprite: SpriteFrame | null = null;
+ @property
+ public _hoverSprite: SpriteFrame | null = null;
+ @property
+ public _pressedSprite: SpriteFrame | null = null;
+ @property
+ public _disabledSprite = null;
+ @property
+ public _duration: number = 0.1;
+ @property
+ public _zoomScale: number = 1.2;
+ @property
+ public _target: Node = null;
+ @property
+ public _clickEvents: ComponentEventHandler[] = [];
+
+ public _pressed: boolean = false;
+ public _hovered: boolean = false;
+ public _fromColor: Color = cc.color();
+ public _toColor: Color = cc.color();
+ public _time: number = 0;
+ public _transitionFinished: boolean = true;
+ public _fromScale: Vec3 = cc.v3();
+ public _toScale: Vec3 = cc.v3();
+ public _originalScale: Vec3 = cc.v3();
+ public _sprite: SpriteComponent | null = null;
+ public _previousNormalSprite: SpriteFrame | null = null;
+
+ constructor () {
+ super();
+ if (CC_EDITOR) {
+ this._previousNormalSprite = null;
+ }
+ }
+
+ public __preload () {
+ if (!this.target) {
+ this.target = this.node;
+ }
+ this._applyTarget();
+ this._updateState();
+ }
+
+ public _resetState () {
+ this._pressed = false;
+ this._hovered = false;
+ // // Restore button status
+ const target = this.target;
+ const renderComp = this.target.getComponent(cc.RenderComponent);
+ const transition = this.transition;
+ if (transition === Transition.COLOR && this.interactable) {
+ renderComp.color = this.normalColor;
+ } else if (transition === Transition.SCALE) {
+ target.scale = this._originalScale;
+ }
+ this._transitionFinished = true;
+ }
+
+ public onEnable () {
+ // check sprite frames
+ if (this._normalSprite) {
+ this._normalSprite.ensureLoadTexture();
+ }
+ if (this._hoverSprite) {
+ this._hoverSprite.ensureLoadTexture();
+ }
+ if (this._pressedSprite) {
+ this._pressedSprite.ensureLoadTexture();
+ }
+ if (this._disabledSprite) {
+ this._disabledSprite.ensureLoadTexture();
+ }
+ //
+ if (!CC_EDITOR) {
+ this._registerEvent();
+ } else {
+ this.node.on('spriteframe-changed', function (comp) {
+ if (this._transition === Transition.SPRITE) {
+ this._normalSprite = comp.spriteFrame;
+ }
+ }.bind(this));
+ }
+ }
+
+ public onDisable () {
+ this._resetState();
+
+ if (!CC_EDITOR) {
+ this.node.off(cc.NodeUI.EventType.TOUCH_START, this._onTouchBegan, this);
+ this.node.off(cc.NodeUI.EventType.TOUCH_MOVE, this._onTouchMove, this);
+ this.node.off(cc.NodeUI.EventType.TOUCH_END, this._onTouchEnded, this);
+ this.node.off(cc.NodeUI.EventType.TOUCH_CANCEL, this._onTouchCancel, this);
+
+ this.node.off(cc.NodeUI.EventType.MOUSE_ENTER, this._onMouseMoveIn, this);
+ this.node.off(cc.NodeUI.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this);
+ } else {
+ this.node.off('spriteframe-changed');
+ }
+ }
+
+ public update (dt) {
+ const target = this._target;
+ if (this._transitionFinished) {
+ return;
+ }
+
+ if (this._transition !== Transition.COLOR && this._transition !== Transition.SCALE) {
+ return;
+ }
+
+ this._time += dt;
+ let ratio = 1.0;
+ if (this._duration > 0) {
+ ratio = this._time / this._duration;
+ }
+
+ if (ratio >= 1) {
+ ratio = 1;
+ this._transitionFinished = true;
+ }
+
+ const renderComp = target.getComponent(cc.RenderComponent);
+ if (this._transition === Transition.COLOR) {
+ renderComp.color = this._fromColor.lerp(this._toColor, ratio);
+ } else if (this.transition === Transition.SCALE) {
+ // target.scale = lerp(this._fromScale, this._toScale, ratio);
+ target.scaleX = lerp(this._fromScale.x, this._toScale.x, ratio);
+ target.scaleY = lerp(this._fromScale.y, this._toScale.y, ratio);
+ }
+ }
+
+ public _registerEvent () {
+ this.node.on(cc.NodeUI.EventType.TOUCH_START, this._onTouchBegan, this);
+ this.node.on(cc.NodeUI.EventType.TOUCH_MOVE, this._onTouchMove, this);
+ this.node.on(cc.NodeUI.EventType.TOUCH_END, this._onTouchEnded, this);
+ this.node.on(cc.NodeUI.EventType.TOUCH_CANCEL, this._onTouchCancel, this);
+
+ this.node.on(cc.NodeUI.EventType.MOUSE_ENTER, this._onMouseMoveIn, this);
+ this.node.on(cc.NodeUI.EventType.MOUSE_LEAVE, this._onMouseMoveOut, this);
+ }
+
+ public _getTargetSprite (target: Node | null) {
+ let sprite = null;
+ if (target) {
+ sprite = target.getComponent(cc.SpriteComponent);
+ }
+ return sprite;
+ }
+
+ public _applyTarget () {
+ this._sprite = this._getTargetSprite(this._target);
+ if (this._target) {
+ math.vec3.copy(this._originalScale, this.target._lscale);
+ }
+ }
+
+ // touch event handler
+ public _onTouchBegan (event: Event | null) {
+ if (!this._interactable || !this.enabledInHierarchy) { return; }
+
+ this._pressed = true;
+ this._updateState();
+ event.stopPropagation();
+ }
+
+ public _onTouchMove (event: Event | null) {
+ if (!this._interactable || !this.enabledInHierarchy || !this._pressed) { return; }
+ // mobile phone will not emit _onMouseMoveOut,
+ // so we have to do hit test when touch moving
+ const touch = event.touch;
+ const hit = this.node._hitTest(touch.getLocation());
+
+ if (this._transition === Transition.SCALE && this._target) {
+ if (hit) {
+ this._fromScale = this._originalScale;
+ math.vec3.scale(this._toScale, this._originalScale, this._zoomScale);
+ this._transitionFinished = false;
+ } else {
+ this._time = 0;
+ this._transitionFinished = true;
+ this._target.scaleX = this._originalScale.x;
+ this._target.scaleY = this._originalScale.y;
+ }
+ } else {
+ let state;
+ if (hit) {
+ state = 'pressed';
+ } else {
+ state = 'normal';
+ }
+ this._applyTransition(state);
+ }
+ event.stopPropagation();
+ }
+
+ public _onTouchEnded (event: Event | null) {
+ if (!this._interactable || !this.enabledInHierarchy) { return; }
+
+ if (this._pressed) {
+ ComponentEventHandler.emitEvents(this._clickEvents, event);
+ this.node.emit('click', this);
+ }
+ this._pressed = false;
+ this._updateState();
+ event.stopPropagation();
+ }
+
+ public _onTouchCancel () {
+ if (!this._interactable || !this.enabledInHierarchy) { return; }
+
+ this._pressed = false;
+ this._updateState();
+ }
+
+ public _onMouseMoveIn () {
+ if (this._pressed || !this.interactable || !this.enabledInHierarchy) { return; }
+ if (this._transition === Transition.SPRITE && !this._hoverSprite) { return; }
+
+ if (!this._hovered) {
+ this._hovered = true;
+ this._updateState();
+ }
+ }
+
+ public _onMouseMoveOut () {
+ if (this._hovered) {
+ this._hovered = false;
+ this._updateState();
+ }
+ }
+
+ // state handler
+ public _updateState () {
+ const state = this._getButtonState();
+ this._applyTransition(state);
+ // this._updateDisabledState();
+ }
+
+ public _getButtonState () {
+ let state;
+ if (!this._interactable) {
+ state = 'disabled';
+ } else if (this._pressed) {
+ state = 'pressed';
+ } else if (this._hovered) {
+ state = 'hover';
+ } else {
+ state = 'normal';
+ }
+ return state;
+ }
+
+ public _updateColorTransition (state: string) {
+ const color = this[state + 'Color'];
+ const target = this._target;
+
+ const renderComp = target.getComponent(cc.RenderComponent);
+ if (!renderComp) {
+ return;
+ }
+
+ if (CC_EDITOR) {
+ renderComp.color = color;
+ } else {
+ this._fromColor = renderComp.color.clone();
+ this._toColor = color;
+ this._time = 0;
+ this._transitionFinished = false;
+ }
+ }
+
+ public _updateSpriteTransition (state: string) {
+ const sprite = this[state + 'Sprite'];
+ if (this._sprite && sprite) {
+ this._sprite.spriteFrame = sprite;
+ }
+ }
+
+ public _updateScaleTransition (state: string) {
+ if (state === 'pressed') {
+ this._zoomUp();
+ } else {
+ this._zoomBack();
+ }
+ }
+
+ public _zoomUp () {
+ math.vec3.copy(this._fromScale, this._originalScale);
+ math.vec3.scale(this._toScale, this._originalScale, this._zoomScale);
+ this._time = 0;
+ this._transitionFinished = false;
+ }
+
+ public _zoomBack () {
+ math.vec3.copy(this._fromScale, this.target._lscale);
+ math.vec3.copy(this._toScale, this._originalScale);
+ this._time = 0;
+ this._transitionFinished = false;
+ }
+
+ public _applyTransition (state: string) {
+ const transition = this._transition;
+ if (transition === Transition.COLOR) {
+ this._updateColorTransition(state);
+ } else if (transition === Transition.SPRITE) {
+ this._updateSpriteTransition(state);
+ } else if (transition === Transition.SCALE) {
+ this._updateScaleTransition(state);
+ }
+ }
+
+ public _resizeNodeToTargetNode () {
+ if (CC_EDITOR && this._target) {
+ this.node.setContentSize(this.target.getContentSize());
+ }
+ }
+
+ // _updateDisabledState() {
+ // if (this._sprite) {
+ // if (this.enableAutoGrayEffect) {
+ // if (!(this._transition === Transition.SPRITE && this._disabledSprite)) {
+ // if (!this._interactable) {
+ // this._sprite.setState(cc.SpriteComponent.State.GRAY);
+ // return;
+ // }
+ // }
+ // }
+ // this._sprite.setState(cc.SpriteComponent.State.NORMAL);
+ // }
+ // }
+}
+
+/**
+ * !#en
+ * Note: This event is emitted from the node to which the component belongs.
+ * !#zh
+ * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
+ * @event click
+ * @param {Event.EventCustom} event
+ * @param {Button} button - The Button component.
+ */
diff --git a/cocos/3d/ui/components/canvas-component.ts b/cocos/3d/ui/components/canvas-component.ts
new file mode 100644
index 0000000000..50e0a6a7d4
--- /dev/null
+++ b/cocos/3d/ui/components/canvas-component.ts
@@ -0,0 +1,300 @@
+/****************************************************************************
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos.com
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated engine source code (the "Software"), a limited,
+ worldwide, royalty-free, non-assignable, revocable and non-exclusive license
+ to use Cocos Creator solely to develop games on your target platforms. You shall
+ not use Cocos Creator software for developing other software or tools that's
+ used for developing games. You are not granted to publish, distribute,
+ sublicense, and/or sell copies of Cocos Creator.
+
+ The software or tools in this License Agreement are licensed, not sold.
+ Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+import { CameraComponent } from '../../../3d/framework/camera-component';
+import { Component } from '../../../components/component';
+import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator';
+import Rect from '../../../core/value-types/rect';
+import Size from '../../../core/value-types/size';
+import { GFXClearFlag } from '../../../gfx/define';
+import { Camera } from '../../../renderer/scene/camera';
+
+/**
+ * !#zh: 作为 UI 根节点,为所有子节点提供视窗四边的位置信息以供对齐,另外提供屏幕适配策略接口,方便从编辑器设置。
+ * 注:由于本节点的尺寸会跟随屏幕拉伸,所以 anchorPoint 只支持 (0.5, 0.5),否则适配不同屏幕时坐标会有偏差。
+ *
+ * @class Canvas
+ * @extends Component
+ */
+@ccclass('cc.CanvasComponent')
+@executionOrder(100)
+@menu('UI/Canvas')
+@executeInEditMode
+// @disallowMultiple
+export class CanvasComponent extends Component {
+
+ @property({
+ type: Size,
+ })
+ get designResolution () {
+ return cc.size(this._designResolution);
+ }
+ set designResolution (value: Size) {
+ this._designResolution.width = value.width;
+ this._designResolution.height = value.height;
+ this.applySettings();
+ this.alignWithScreen();
+ }
+
+ /**
+ * !#en TODO
+ * !#zh: 是否优先将设计分辨率高度撑满视图高度。
+ * @property {Boolean} fitHeight
+ * @default false
+ */
+ @property()
+ get fitHeight () {
+ return this._fitHeight;
+ }
+ set fitHeight (value: boolean) {
+ if (this._fitHeight !== value) {
+ this._fitHeight = value;
+ this.applySettings();
+ this.alignWithScreen();
+ }
+ }
+
+ /**
+ * !#en TODO
+ * !#zh: 是否优先将设计分辨率宽度撑满视图宽度。
+ * @property {Boolean} fitWidth
+ * @default false
+ */
+ @property()
+ get fitWidth () {
+ return this._fitWidth;
+ }
+ set fitWidth (value: boolean) {
+ if (this._fitWidth !== value) {
+ this._fitWidth = value;
+ this.applySettings();
+ this.alignWithScreen();
+ }
+ }
+
+ /**
+ * !#en priority in render
+ * !#zh 显示优先级
+ */
+ @property
+ get priority () {
+ return this._priority;
+ }
+
+ set priority (value: number) {
+ this._priority = value;
+ }
+
+ get visibility () {
+ if (this._camere) {
+ return this._camere.view.visibility;
+ }
+
+ return -1;
+ }
+
+ get camera () {
+ return this._camere;
+ }
+
+ public static views = [];
+ /**
+ * !#en The desigin resolution for current scene.
+ * !#zh 当前场景设计分辨率。
+ * @property {Size} designResolution
+ * @default new cc.Size(960, 640)
+ */
+ @property
+ private _designResolution = cc.size(960, 640);
+ @property
+ private _fitWidth = false;
+ @property
+ private _fitHeight = true;
+ @property
+ private _priority = 0;
+
+ private _thisOnResized: Function | null = null;
+
+ private _camere: Camera | null = null;
+ private _cameraInfo: object | null = null;
+
+ // /**
+ // * !#en Current active canvas, the scene should only have one active canvas at the same time.
+ // * !#zh 当前激活的画布组件,场景同一时间只能有一个激活的画布。
+ // * @property {CanvasComponent} instance
+ // * @static
+ // */
+ // static instance = null;
+
+ constructor () {
+ super();
+ this._thisOnResized = this.alignWithScreen.bind(this);
+ }
+
+ // public onLoad () {}
+
+ public resetInEditor () {
+ // _Scene._applyCanvasPreferences(this);
+ }
+
+ public __preload () {
+ // if (CC_DEV) {
+ // var Flags = cc.Object.Flags;
+ // this._objFlags |= (Flags.IsPositionLocked | Flags.IsAnchorLocked | Flags.IsSizeLocked);
+ // }
+
+ // if (CanvasComponent.instance) {
+ // return cc.errorID(6700,
+ // this.node.name, CanvasComponent.instance.node.name);
+ // }
+ // CanvasComponent.instance = this;
+
+ // if (CC_EDITOR) {
+ // cc.engine.on('design-resolution-changed', this._thisOnResized);
+ // }
+ // else {
+ // TODO: Need to do editor initiative call
+ if (!CC_EDITOR) {
+ // if (cc.sys.isMobile) {
+ // window.addEventListener('resize', this._thisOnResized);
+ // }
+ // else {
+ // cc.view.on('canvas-resize', this._thisOnResized);
+ // }
+ cc.view.on('design-resolution-changed', this._thisOnResized);
+ }
+
+ this.applySettings();
+ this.alignWithScreen();
+ }
+
+ public onEnable () {
+ this._cameraInfo = {
+ name: 'ui',
+ clearFlags: GFXClearFlag.DEPTH | GFXClearFlag.STENCIL,
+ node: this.node,
+ stencil: 0,
+ projection: CameraComponent.ProjectionType.ORTHO,
+ orthoHeight: 10,
+ far: 4096,
+ near: 0.1,
+ rect: new Rect(0, 0, 1, 1),
+ color: cc.color(255, 255, 255, 255),
+ };
+ this._camere = this._getRenderScene().createCamera(this._cameraInfo);
+ cc.director.root.ui.addScreen(this);
+ }
+
+ public onDisable () {
+ if (this._camere) {
+ this._getRenderScene().destroyCamera(this._cameraInfo);
+ cc.director.root.ui.removeScreen(this);
+ }
+ }
+
+ public onDestroy () {
+ if (super.onDestroy) {
+ super.onDestroy();
+ }
+ // if (CC_EDITOR) {
+ // cc.engine.off('design-resolution-changed', this._thisOnResized);
+ // }
+ // else {
+ // if (cc.sys.isMobile) {
+ // window.removeEventListener('resize', this._thisOnResized);
+ // }
+ // else {
+ // cc.view.off('canvas-resize', this._thisOnResized);
+ // }
+ // }
+
+ cc.view.off('design-resolution-changed', this._thisOnResized);
+
+ // cc.director._uiSystem.removeScreen(this);
+
+ // if (CanvasComponent.instance === this) {
+ // CanvasComponent.instance = null;
+ // }
+ }
+
+ //
+
+ public alignWithScreen () {
+ if (this._camere) {
+ this._camere.resize(cc.game.canvas.width, cc.game.canvas.height);
+ this._camere.orthoHeight = cc.game.canvas.height / cc.view._scaleY / 2;
+ const viewport = this._camere.viewport;
+ viewport.x = viewport.y = 0;
+ viewport.width = cc.game.canvas.width;
+ viewport.height = cc.game.canvas.height;
+ }
+ // if (CC_EDITOR) {
+ // nodeSize = designSize = cc.engine.getDesignResolutionSize();
+ // this.node.setPosition(designSize.width * 0.5, designSize.height * 0.5, 1);
+ // }
+ // else {
+ const canvasSize = cc.visibleRect;
+ const nodeSize = canvasSize;
+ const designSize = cc.view.getDesignResolutionSize();
+ const clipTopRight = !this.fitHeight && !this.fitWidth;
+ let offsetX = 0;
+ let offsetY = 0;
+ if (clipTopRight) {
+ // offset the canvas to make it in the center of screen
+ offsetX = (designSize.width - canvasSize.width) * 0.5;
+ offsetY = (designSize.height - canvasSize.height) * 0.5;
+ }
+ this.node.setPosition(canvasSize.width * 0.5 + offsetX, canvasSize.height * 0.5 + offsetY, 1);
+ // }
+ // let canvasSize = nodeSize = cc.visibleRect;
+ // this.node.setPosition(canvasSize.width / 2, canvasSize.height / 2, 1);
+ this.node.width = nodeSize.width;
+ this.node.height = nodeSize.height;
+ }
+
+ public applySettings () {
+ const ResolutionPolicy = cc.ResolutionPolicy;
+ let policy;
+
+ if (this.fitHeight && this.fitWidth) {
+ policy = ResolutionPolicy.SHOW_ALL;
+ } else if (!this.fitHeight && !this.fitWidth) {
+ policy = ResolutionPolicy.NO_BORDER;
+ } else if (this.fitWidth) {
+ policy = ResolutionPolicy.FIXED_WIDTH;
+ } else { // fitHeight
+ policy = ResolutionPolicy.FIXED_HEIGHT;
+ }
+
+ const designRes = this._designResolution;
+ // if (CC_EDITOR) {
+ // cc.engine.setDesignResolutionSize(designRes.width, designRes.height);
+ // }
+ // else {
+ cc.view.setDesignResolutionSize(designRes.width, designRes.height, policy);
+ // }
+ }
+}
diff --git a/cocos/3d/ui/components/editbox/edit-box-component.ts b/cocos/3d/ui/components/editbox/edit-box-component.ts
new file mode 100644
index 0000000000..a5f31b283b
--- /dev/null
+++ b/cocos/3d/ui/components/editbox/edit-box-component.ts
@@ -0,0 +1,861 @@
+/****************************************************************************
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos.com
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated engine source code (the "Software"), a limited,
+ worldwide, royalty-free, non-assignable, revocable and non-exclusive license
+ to use Cocos Creator solely to develop games on your target platforms. You shall
+ not use Cocos Creator software for developing other software or tools that's
+ used for developing games. You are not granted to publish, distribute,
+ sublicense, and/or sell copies of Cocos Creator.
+
+ The software or tools in this License Agreement are licensed, not sold.
+ Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+import { ccclass, menu, executionOrder, executeInEditMode, property } from '../../../../core/data/class-decorator';
+import Component from '../../../../components/component';
+import Color from '../../../../core/value-types/color';
+import macro from '../../../../core/platform/CCMacro';
+import EditBoxImpl from './edit-box-impl';
+import LabelComponent from '../label-component';
+// import { InputMode, InputFlag, KeyboardReturnType } from './types';
+import * as Types from './types';
+import SpriteFrame from '../../../../assets/CCSpriteFrame';
+import ComponentEventHandler from '../../../../components/CCComponentEventHandler';
+import SpriteComponent from '../sprite-component';
+const InputMode = Types.InputMode;
+const InputFlag = Types.InputFlag;
+const KeyboardReturnType = Types.KeyboardReturnType;
+
+const LEFT_PADDING = 2;
+
+function capitalize(string) {
+ return string.replace(/(?:^|\s)\S/g, function (a) { return a.toUpperCase(); });
+}
+
+function capitalizeFirstLetter(string) {
+ return string.charAt(0).toUpperCase() + string.slice(1);
+}
+
+
+/**
+ * !#en cc.EditBox is a component for inputing text, you can use it to gather small amounts of text from users.
+ * !#zh EditBox 组件,用于获取用户的输入文本。
+ * @class EditBox
+ * @extends Component
+ */
+
+@ccclass('cc.EditBoxComponent')
+@executionOrder(100)
+@menu('UI/EditBox')
+@executeInEditMode
+export default class EditBoxComponent extends Component {
+ @property
+ _useOriginalSize: boolean = true;
+ @property
+ _string: string = '';
+ @property
+ _tabIndex: number = 0;
+ @property
+ _backgroundImage: SpriteFrame | null = null;
+ @property
+ _returnType: number = KeyboardReturnType.DEFAULT;
+ @property
+ _inputFlag: number = InputFlag.DEFAULT;
+ @property
+ _inputMode: number = InputMode.SINGLE_LINE;
+ @property
+ _fontSize: number = 20;
+ @property
+ _lineHeight: number = 40;
+ @property
+ _maxLength: number = 20;
+ @property
+ _fontColor: Color = Color.WHITE;
+ @property
+ _placeholder: string = 'Enter text here...';
+ @property
+ _placeholderFontSize: number = 20;
+ @property
+ _placeholderFontColor: Color = Color.GRAY;
+ @property
+ _stayOnTop: boolean = false;
+ @property
+ editingDidBegan: ComponentEventHandler[] = [];
+ @property
+ editingDidEnded: ComponentEventHandler[] = [];
+ @property
+ editingReturn: ComponentEventHandler[] = [];
+ @property
+ textChanged: ComponentEventHandler[] = [];
+
+ _impl: EditBoxImpl | null = null;
+ _textLabel: LabelComponent | null = null;
+ _placeholderLabel: LabelComponent | null = null;
+ _background: SpriteComponent | null = null;
+
+ /**
+ * !#en Input string of EditBox.
+ * !#zh 输入框的初始输入内容,如果为空则会显示占位符的文本。
+ * @property {String} string
+ */
+ @property
+ get string() {
+ return this._string;
+ }
+
+ set string(value: string) {
+ if (this._maxLength >= 0 && value.length >= this._maxLength) {
+ value = value.slice(0, this._maxLength);
+ }
+
+ this._string = value;
+ if (this._impl) {
+ this._updateString(value);
+ }
+ }
+
+ /**
+ * !#en The background image of EditBox.
+ * !#zh 输入框的背景图片
+ * @property {SpriteFrame} backgroundImage
+ */
+ @property({
+ type: SpriteFrame
+ })
+ get backgroundImage() {
+ return this._backgroundImage;
+ }
+
+ set backgroundImage(value: SpriteFrame | null) {
+ if (this._backgroundImage === value) {
+ return;
+ }
+
+ this._backgroundImage = value;
+ this._createBackgroundSprite();
+ }
+
+ /**
+ * !#en
+ * The return key type of EditBox.
+ * Note: it is meaningless for web platforms and desktop platforms.
+ * !#zh
+ * 指定移动设备上面回车按钮的样式。
+ * 注意:这个选项对 web 平台与 desktop 平台无效。
+ * @property {EditBox.KeyboardReturnType} returnType
+ * @default KeyboardReturnType.DEFAULT
+ */
+ @property({
+ type: KeyboardReturnType
+ })
+ get returnType() {
+ return this._returnType;
+ }
+
+ set returnType(value: number) {
+ this._returnType = value;
+ if (this._impl) {
+ this._impl.returnType = this._returnType;
+ }
+ }
+
+
+ /**
+ * !#en Set the input flags that are to be applied to the EditBox.
+ * !#zh 指定输入标志位,可以指定输入方式为密码或者单词首字母大写。
+ * @property {EditBox.InputFlag} inputFlag
+ * @default InputFlag.DEFAULT
+ */
+ @property({
+ type: InputFlag
+ })
+ get inputFlag() {
+ return this._inputFlag;
+ }
+
+ set inputFlag(value: number) {
+ this._inputFlag = value;
+ if (this._impl) {
+ this._impl.setInputFlag(this._inputFlag);
+ this._updateString(this._string);
+ }
+ }
+ /**
+ * !#en
+ * Set the input mode of the edit box.
+ * If you pass ANY, it will create a multiline EditBox.
+ * !#zh
+ * 指定输入模式: ANY表示多行输入,其它都是单行输入,移动平台上还可以指定键盘样式。
+ * @property {EditBox.InputMode} inputMode
+ * @default InputMode.ANY
+ */
+ @property({
+ type: InputMode
+ })
+ get inputMode() {
+ return this._inputMode;
+ }
+
+ set inputMode(value: number) {
+ this._inputMode = value;
+ if (this._impl) {
+ this._impl.setInputMode(this._inputMode);
+ }
+ }
+
+ /**
+ * !#en Font size of the input text.
+ * !#zh 输入框文本的字体大小
+ * @property {Number} fontSize
+ */
+ @property
+ get fontSize() {
+ return this._fontSize;
+ }
+
+ set fontSize(value: number) {
+ if (this._fontSize === value) {
+ return;
+ }
+
+ this._fontSize = value;
+ if (this._textLabel) {
+ this._textLabel.fontSize = this._fontSize;
+ }
+ if (this._impl) {
+ this._impl.setFontSize(this._fontSize);
+ }
+ }
+
+
+ /**
+ * !#en Change the lineHeight of displayed text.
+ * !#zh 输入框文本的行高。
+ * @property {Number} lineHeight
+ */
+ @property
+ get lineHeight() {
+ return this._lineHeight;
+ }
+
+ set lineHeight(value: number) {
+ if (this._lineHeight === value) {
+ return;
+ }
+
+ this._lineHeight = value;
+ if (this._textLabel) {
+ this._textLabel.lineHeight = this._lineHeight;
+ }
+ }
+
+
+ /**
+ * !#en Font color of the input text.
+ * !#zh 输入框文本的颜色。
+ * @property {Color} fontColor
+ */
+ @property({
+ type: Color
+ })
+ get fontColor() {
+ return this._fontColor;
+ }
+
+ set fontColor(value: Color) {
+ if (this._fontColor === value) {
+ return
+ }
+
+ this._fontColor = value;
+ if (this._textLabel) {
+ this._textLabel.node.opacity = this._fontColor.a;
+ this._textLabel.node.color = this._fontColor;
+ }
+ if (this._impl) {
+ this._impl.setFontColor(this._fontColor);
+ }
+ }
+
+ /**
+ * !#en The display text of placeholder.
+ * !#zh 输入框占位符的文本内容。
+ * @property {String} placeholder
+ */
+ @property
+ get placeholder() {
+ return this._placeholder;
+ }
+
+ set placeholder(value: string) {
+ if (this._placeholder === value) {
+ return;
+ }
+
+ this._placeholder = value;
+ if (this._placeholderLabel) {
+ this._placeholderLabel.string = this._placeholder;
+ }
+ if (this._impl) {
+ this._impl.setPlaceholderText(this._placeholder);
+ }
+ }
+
+ /**
+ * !#en The font size of placeholder.
+ * !#zh 输入框占位符的字体大小。
+ * @property {Number} placeholderFontSize
+ */
+ @property
+ get placeholderFontSize() {
+ return this._placeholderFontSize;
+ }
+
+ set placeholderFontSize(value: number) {
+ if (this._placeholderFontSize === value) {
+ return;
+ }
+
+ this._placeholderFontSize = value;
+ if (this._placeholderLabel) {
+ this._placeholderLabel.fontSize = this._placeholderFontSize;
+ }
+ }
+
+ /**
+ * !#en The font color of placeholder.
+ * !#zh 输入框占位符的字体颜色。
+ * @property {Color} placeholderFontColor
+ */
+ @property
+ get placeholderFontColor() {
+ return this._placeholderFontColor;
+ }
+
+ set placeholderFontColor(value: Color) {
+ if (this._placeholderFontColor === value) {
+ return;
+ }
+
+ this._placeholderFontColor = value;
+ if (this._placeholderLabel) {
+ this._placeholderLabel.node.color = this._placeholderFontColor;
+ this._placeholderLabel.node.opacity = this._placeholderFontColor.a;
+ }
+ }
+
+ /**
+ * !#en The maximize input length of EditBox.
+ * - If pass a value less than 0, it won't limit the input number of characters.
+ * - If pass 0, it doesn't allow input any characters.
+ * !#zh 输入框最大允许输入的字符个数。
+ * - 如果值为小于 0 的值,则不会限制输入字符个数。
+ * - 如果值为 0,则不允许用户进行任何输入。
+ * @property {Number} maxLength
+ */
+ @property
+ get maxLength() {
+ return this._maxLength;
+ }
+ set maxLength(value: number) {
+ if (this._maxLength === value) {
+ return
+ }
+
+ this._maxLength = value;
+ if (this._impl) {
+ this._impl.setMaxLength(this._maxLength);
+ }
+ }
+
+ /**
+ * !#en The input is always visible and be on top of the game view (only useful on Web).
+ * !zh 输入框总是可见,并且永远在游戏视图的上面(这个属性只有在 Web 上面修改有意义)
+ * Note: only available on Web at the moment.
+ * @property {Boolean} stayOnTop
+ */
+ @property
+ get stayOnTop() {
+ return this._stayOnTop;
+ }
+
+ set stayOnTop(value: boolean) {
+ this._stayOnTop = value;
+ if (this._impl) {
+ this._updateStayOnTop();
+ }
+ }
+
+ /**
+ * !#en Set the tabIndex of the DOM input element (only useful on Web).
+ * !#zh 修改 DOM 输入元素的 tabIndex(这个属性只有在 Web 上面修改有意义)。
+ * @property {Number} tabIndex
+ */
+ @property
+ get tabIndex() {
+ return this._tabIndex;
+ }
+
+ set tabIndex(value: number) {
+ this._tabIndex = value;
+ if (this._impl) {
+ this._impl.setTabIndex(value);
+ }
+ }
+
+ /**
+ * !#en The event handler to be called when EditBox began to edit text.
+ * !#zh 开始编辑文本输入框触发的事件回调。
+ * @property {Component.EventHandler[]} editingDidBegan
+ */
+ // @property({
+ // default: [],
+ // type: [ComponentEventHandler]
+ // })
+ // get editingDidBegan() {
+ // return this._editingDidBegan;
+ // }
+
+ // set editingDidBegan(value: ComponentEventHandler[]) {
+ // this._editingDidBegan = value;
+ // }
+
+ /**
+ * !#en The event handler to be called when EditBox text changes.
+ * !#zh 编辑文本输入框时触发的事件回调。
+ * @property {Component.EventHandler[]} textChanged
+ */
+ // @property({
+ // default: [],
+ // type: [ComponentEventHandler]
+ // })
+ // get textChanged() {
+ // return this._textChanged;
+ // }
+
+ // set textChanged(value: ComponentEventHandler[]) {
+ // this._textChanged = value;
+ // }
+
+ /**
+ * !#en The event handler to be called when EditBox edit ends.
+ * !#zh 结束编辑文本输入框时触发的事件回调。
+ * @property {Component.EventHandler[]} editingDidEnded
+ */
+ // @property({
+ // default: [],
+ // type: [ComponentEventHandler]
+ // })
+ // get editingDidEnded() {
+ // return this._editingDidEnded;
+ // }
+
+ // set editingDidEnded(value: ComponentEventHandler[]) {
+ // this._editingDidEnded = value;
+ // }
+
+ /**
+ * !#en The event handler to be called when return key is pressed. Windows is not supported.
+ * !#zh 当用户按下回车按键时的事件回调,目前不支持 windows 平台
+ * @property {Component.EventHandler[]} editingReturn
+ */
+ // @property({
+ // default: [],
+ // type: [ComponentEventHandler]
+ // })
+ // get editingReturn() {
+ // return this._editingReturn;
+ // }
+
+ // set editingReturn(value: ComponentEventHandler[]) {
+ // this._editingReturn = value;
+ // }
+
+ static _EditBoxImpl = EditBoxImpl;
+ static KeyboardReturnType = KeyboardReturnType;
+ static InputFlag = InputFlag;
+ static InputMode = InputMode;
+
+ onEnable() {
+ this._impl && this._impl.onEnable();
+ }
+
+ onDisable() {
+ this._impl && this._impl.onDisable();
+ }
+
+ onDestroy() {
+ this._impl.clear();
+ }
+
+ _init() {
+ this._createBackgroundSprite();
+ this._createLabels();
+ this.node.on(cc.NodeUI.EventType.SIZE_CHANGED, this._resizeChildNodes, this);
+
+ let impl = this._impl = new EditBoxImpl();
+
+ impl.setDelegate(this);
+ impl.setNode(this.node);
+ impl.setInputMode(this._inputMode);
+ impl.setMaxLength(this._maxLength);
+ impl.setInputFlag(this._inputFlag);
+ impl.setReturnType(this._returnType);
+ impl.setTabIndex(this._tabIndex);
+ impl.setFontColor(this._fontColor);
+ impl.setFontSize(this._fontSize);
+ impl.setPlaceholderText(this._placeholder);
+
+ this._updateStayOnTop();
+ this._updateString(this._string);
+ this._syncSize();
+ }
+
+ __preload() {
+ if (!CC_EDITOR) {
+ this._registerEvent();
+ }
+ this._init();
+ }
+
+ _registerEvent() {
+ this.node.on(cc.NodeUI.EventType.TOUCH_START, this._onTouchBegan, this);
+ this.node.on(cc.NodeUI.EventType.TOUCH_END, this._onTouchEnded, this);
+ }
+
+ _updateStayOnTop() {
+ if (this.stayOnTop) {
+ this._hideLabels();
+ }
+ else {
+ this._showLabels();
+ }
+ this._impl.stayOnTop(this.stayOnTop);
+ }
+
+ _syncSize() {
+ let size = this.node.getContentSize();
+
+ this._background.node.setAnchorPoint(this.node.getAnchorPoint());
+ this._background.node.setContentSize(size);
+
+ this._updateLabelPosition(size);
+ this._impl.setSize(size.width, size.height);
+ }
+
+ _updateLabelPosition(size) {
+ let node = this.node;
+ let offx = -node.anchorX * node.width;
+ let offy = -node.anchorY * node.height;
+
+ let placeholderLabel = this._placeholderLabel;
+ let textLabel = this._textLabel;
+
+ textLabel.node.setContentSize(size.width - LEFT_PADDING, size.height);
+ placeholderLabel.node.setContentSize(size.width - LEFT_PADDING, size.height);
+ placeholderLabel.lineHeight = size.height;
+
+ placeholderLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height);
+ textLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height);
+
+ if (this._inputMode === InputMode.ANY) {
+ placeholderLabel.verticalAlign = macro.VerticalTextAlignment.TOP;
+ placeholderLabel.enableWrapText = true;
+ textLabel.verticalAlign = macro.VerticalTextAlignment.TOP;
+ textLabel.enableWrapText = true;
+ }
+ else {
+ placeholderLabel.verticalAlign = macro.VerticalTextAlignment.CENTER;
+ placeholderLabel.enableWrapText = false;
+ textLabel.verticalAlign = macro.VerticalTextAlignment.CENTER;
+ textLabel.enableWrapText = false;
+ }
+ }
+
+ _createBackgroundSprite() {
+ if (!this._background) {
+ this._background = this.node.getComponent(cc.SpriteComponent);
+ if (!this._background) {
+ this._background = this.node.addComponent(cc.SpriteComponent);
+ }
+ this._background.type = cc.SpriteComponent.Type.SLICED;
+ }
+
+ this._background.spriteFrame = this._backgroundImage;
+ // let background = this._background;
+ // if (!background) {
+ // let node = this.node.getChildByName('BACKGROUND_SPRITE');
+ // if (!node) {
+ // node = new cc.NodeUI('BACKGROUND_SPRITE');
+ // }
+
+ // background = node.getComponent(cc.SpriteComponent);
+ // if (!background) {
+ // background = node.addComponent(cc.SpriteComponent);
+ // }
+ // background.type = cc.SpriteComponent.Type.SLICED;
+
+ // node.parent = this.node;
+ // this._background = background;
+ // }
+ // background.spriteFrame = this._backgroundImage;
+ }
+
+ _createLabels() {
+ if (!this._textLabel) {
+ let node = this.node.getChildByName('TEXT_LABEL');
+ if (!node) {
+ node = new cc.NodeUI('TEXT_LABEL');
+ }
+ node.color = this._fontColor;
+ node.parent = this.node;
+ node.setAnchorPoint(0, 1);
+
+ let textLabel = node.getComponent(LabelComponent);
+ if (!textLabel) {
+ textLabel = node.addComponent(LabelComponent);
+ }
+ textLabel.overflow = LabelComponent.Overflow.CLAMP;
+ textLabel.fontSize = this._fontSize;
+ textLabel.lineHeight = this.lineHeight;
+ this._textLabel = textLabel;
+ }
+
+ if (!this._placeholderLabel) {
+ let node = this.node.getChildByName('PLACEHOLDER_LABEL');
+ if (!node) {
+ node = new cc.NodeUI('PLACEHOLDER_LABEL');
+ }
+ node.color = this._placeholderFontColor;
+ node.parent = this.node;
+ node.setAnchorPoint(0, 1);
+
+ let placeholderLabel = node.getComponent(LabelComponent);
+ if (!placeholderLabel) {
+ placeholderLabel = node.addComponent(LabelComponent);
+ }
+ placeholderLabel.overflow = LabelComponent.Overflow.CLAMP;
+ placeholderLabel.fontSize = this._placeholderFontSize;
+ placeholderLabel.string = this._placeholder;
+ this._placeholderLabel = placeholderLabel;
+ }
+ }
+
+ _resizeChildNodes() {
+ let textLabelNode = this._textLabel.node,
+ placeholderLabelNode = this._placeholderLabel.node,
+ backgroundNode = this._background.node;
+
+ textLabelNode.x = -this.node.width / 2;
+ textLabelNode.y = this.node.height / 2;
+ textLabelNode.width = this.node.width;
+ textLabelNode.height = this.node.height;
+
+ placeholderLabelNode.x = -this.node.width / 2;
+ placeholderLabelNode.y = this.node.height / 2;
+ placeholderLabelNode.width = this.node.width;
+ placeholderLabelNode.height = this.node.height;
+
+ backgroundNode.width = this.node.width;
+ backgroundNode.height = this.node.height;
+ }
+
+ _showLabels() {
+ let displayText = this._textLabel.string;
+ this._textLabel.node.active = displayText !== '';
+ this._placeholderLabel.node.active = displayText === '';
+ }
+
+ _hideLabels() {
+ this._textLabel.node.active = false;
+ this._placeholderLabel.node.active = false;
+ }
+
+ _updateString(text) {
+ let textLabel = this._textLabel;
+ // Not inited yet
+ if (!textLabel) {
+ return;
+ }
+
+ let displayText = text;
+ if (displayText) {
+ displayText = this._updateLabelStringStyle(displayText);
+ }
+
+ textLabel.string = displayText;
+ this._impl.setString(text);
+ if (!this._impl._editing && !this.stayOnTop) {
+ this._showLabels();
+ }
+ }
+
+ _updateLabelStringStyle(text, ignorePassword) {
+ let inputFlag = this._inputFlag;
+ if (!ignorePassword && inputFlag === InputFlag.PASSWORD) {
+ let passwordString = '';
+ let len = text.length;
+ for (let i = 0; i < len; ++i) {
+ passwordString += '\u25CF';
+ }
+ text = passwordString;
+ }
+ else if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) {
+ text = text.toUpperCase();
+ }
+ else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) {
+ text = capitalize(text);
+ }
+ else if (inputFlag === InputFlag.INITIAL_CAPS_SENTENCE) {
+ text = capitalizeFirstLetter(text);
+ }
+
+ return text;
+ }
+
+ editBoxEditingDidBegan() {
+ this._hideLabels();
+ ComponentEventHandler.emitEvents(this.editingDidBegan, this);
+ this.node.emit('editing-did-began', this);
+ }
+
+ editBoxEditingDidEnded() {
+ if (!this.stayOnTop) {
+ this._showLabels();
+ }
+ ComponentEventHandler.emitEvents(this.editingDidEnded, this);
+ this.node.emit('editing-did-ended', this);
+ }
+
+ editBoxTextChanged(text) {
+ text = this._updateLabelStringStyle(text, true);
+ this.string = text;
+ ComponentEventHandler.emitEvents(this.textChanged, text, this);
+ this.node.emit('text-changed', this);
+ }
+
+ editBoxEditingReturn() {
+ ComponentEventHandler.emitEvents(this.editingReturn, this);
+ this.node.emit('editing-return', this);
+ }
+
+ _onTouchBegan(event) {
+ if (this._impl) {
+ this._impl._onTouchBegan(event.touch);
+ }
+ event.stopPropagation();
+ }
+
+ _onTouchCancel(event) {
+ if (this._impl) {
+ this._impl._onTouchCancel();
+ }
+ event.stopPropagation();
+ }
+
+ _onTouchEnded(event) {
+ if (this._impl) {
+ this._impl._onTouchEnded();
+ }
+ event.stopPropagation();
+ }
+
+ /**
+ * !#en Let the EditBox get focus
+ * !#zh 让当前 EditBox 获得焦点
+ * @method setFocus
+ */
+ setFocus() {
+ if (this._impl) {
+ this._impl.setFocus();
+ }
+ }
+
+ /**
+ * !#en Determine whether EditBox is getting focus or not.
+ * !#zh 判断 EditBox 是否获得了焦点
+ * Note: only available on Web at the moment.
+ * @method isFocused
+ */
+ isFocused() {
+ let isFocused = false;
+ if (this._impl) {
+ isFocused = this._impl.isFocused();
+ }
+ return isFocused;
+ }
+
+ update() {
+ if (this._impl) {
+ this._impl.update();
+ }
+ }
+}
+
+/**
+ * !#en
+ * Note: This event is emitted from the node to which the component belongs.
+ * !#zh
+ * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
+ * @event editing-did-began
+ * @param {Event.EventCustom} event
+ * @param {EditBox} editbox - The EditBox component.
+ */
+
+/**
+ * !#en
+ * Note: This event is emitted from the node to which the component belongs.
+ * !#zh
+ * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
+ * @event editing-did-ended
+ * @param {Event.EventCustom} event
+ * @param {EditBox} editbox - The EditBox component.
+ */
+
+/**
+ * !#en
+ * Note: This event is emitted from the node to which the component belongs.
+ * !#zh
+ * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
+ * @event text-changed
+ * @param {Event.EventCustom} event
+ * @param {EditBox} editbox - The EditBox component.
+ */
+
+/**
+ * !#en
+ * Note: This event is emitted from the node to which the component belongs.
+ * !#zh
+ * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
+ * @event editing-return
+ * @param {Event.EventCustom} event
+ * @param {EditBox} editbox - The EditBox component.
+ */
+
+/**
+ * !#en if you don't need the EditBox and it isn't in any running Scene, you should
+ * call the destroy method on this component or the associated node explicitly.
+ * Otherwise, the created DOM element won't be removed from web page.
+ * !#zh
+ * 如果你不再使用 EditBox,并且组件未添加到场景中,那么你必须手动对组件或所在节点调用 destroy。
+ * 这样才能移除网页上的 DOM 节点,避免 Web 平台内存泄露。
+ * @example
+ * editbox.node.parent = null; // or editbox.node.removeFromParent(false);
+ * // when you don't need editbox anymore
+ * editbox.node.destroy();
+ * @method destroy
+ * @return {Boolean} whether it is the first time the destroy being called
+ */
diff --git a/cocos/2d/ui/editbox/CCEditBoxImpl.js b/cocos/3d/ui/components/editbox/edit-box-impl.ts
similarity index 58%
rename from cocos/2d/ui/editbox/CCEditBoxImpl.js
rename to cocos/3d/ui/components/editbox/edit-box-impl.ts
index f198c565d7..91c128f001 100644
--- a/cocos/2d/ui/editbox/CCEditBoxImpl.js
+++ b/cocos/3d/ui/components/editbox/edit-box-impl.ts
@@ -26,9 +26,15 @@
THE SOFTWARE.
****************************************************************************/
-const utils = require('../../platform/utils');
-const macro = require('../../platform/CCMacro');
-const Types = require('./types');
+import { ccclass } from '../../../../core/data/class-decorator';
+import { contains } from '../../../../core/utils/misc';
+import macro from '../../../../core/platform/CCMacro';
+// import { InputMode, InputFlag, KeyboardReturnType } from './types';
+import * as Types from './types';
+import * as math from '../../../../core/vmath';
+import { Size, Color } from '../../../../core/value-types';
+import { Node } from '../../../../scene-graph';
+import EditBoxComponent from './edit-box-component';
const InputMode = Types.InputMode;
const InputFlag = Types.InputFlag;
const KeyboardReturnType = Types.KeyboardReturnType;
@@ -40,9 +46,8 @@ let DELAY_TIME = 400;
let FOCUS_DELAY_UC = 400;
let FOCUS_DELAY_FIREFOX = 0;
-let math = cc.vmath;
-let _matrix = math.mat4.create();
-let _matrix_temp = math.mat4.create();
+let _matrix = cc.mat4();
+let _matrix_temp = cc.mat4();
let _vec3 = cc.v3();
let _currentEditBoxImpl = null;
@@ -54,11 +59,11 @@ let polyfill = {
if (cc.sys.OS_ANDROID === cc.sys.os &&
(cc.sys.browserType === cc.sys.BROWSER_TYPE_SOUGOU ||
- cc.sys.browserType === cc.sys.BROWSER_TYPE_360)) {
+ cc.sys.browserType === cc.sys.BROWSER_TYPE_360)) {
polyfill.zoomInvalid = true;
}
-function getKeyboardReturnType (type) {
+function getKeyboardReturnType(type) {
switch (type) {
case KeyboardReturnType.DEFAULT:
case KeyboardReturnType.DONE:
@@ -75,55 +80,55 @@ function getKeyboardReturnType (type) {
return 'done';
}
-let EditBoxImpl = cc.Class({
- ctor () {
- this._delegate = null;
- this._inputMode = -1;
- this._inputFlag = -1;
- this._returnType = KeyboardReturnType.DEFAULT;
- this._maxLength = 50;
- this._text = '';
- this._placeholderText = '';
- this._alwaysOnTop = false;
- this._size = cc.size();
- this._node = null;
- this._editing = false;
-
- this.__eventListeners = {};
- this.__fullscreen = false;
- this.__autoResize = false;
- this.__rotateScreen = false;
- this.__orientationChanged = null;
- },
+@ccclass
+export default class EditBoxImpl {
+ _delegate: EditBoxComponent | null = null;
+ _inputMode: number = -1;
+ _inputFlag: number = -1;
+ _returnType: number = KeyboardReturnType.DEFAULT;
+ _maxLength: number = 50;
+ _text: string = '';
+ _placeholderText: string = '';
+ _alwaysOnTop: boolean = false;
+ _size: Size = cc.size();
+ _node: Node = null;
+ _editing: boolean = false;
+ __eventListeners: object = {};
+ __fullscreen: boolean = false;
+ __autoResize: boolean = false;
+ __rotateScreen: boolean = false;
+ __orientationChanged: Function | null = null;
+ _edTxt: HTMLElement | null = null;
+ _textColor: Color = Color.WHITE;
- onEnable () {
+ onEnable() {
if (!this._edTxt) {
return;
}
if (this._alwaysOnTop) {
this._edTxt.style.display = '';
- }
+ }
else {
this._edTxt.style.display = 'none';
}
- },
+ }
- onDisable () {
+ onDisable() {
if (!this._edTxt) {
return;
}
this._edTxt.style.display = 'none';
- },
+ }
- setTabIndex (index) {
+ setTabIndex(index) {
if (this._edTxt) {
this._edTxt.tabIndex = index;
}
- },
+ }
- setFocus () {
+ setFocus() {
this._beginEditing();
- },
+ }
isFocused() {
if (this._edTxt) {
@@ -131,23 +136,23 @@ let EditBoxImpl = cc.Class({
}
cc.warnID(4700);
return false;
- },
+ }
- stayOnTop (flag) {
- if(this._alwaysOnTop === flag || !this._edTxt) return;
+ stayOnTop(flag) {
+ if (this._alwaysOnTop === flag || !this._edTxt) return;
this._alwaysOnTop = flag;
-
+
if (flag) {
this._edTxt.style.display = '';
} else {
this._edTxt.style.display = 'none';
}
- },
+ }
- setMaxLength (maxLength) {
+ setMaxLength(maxLength) {
if (!isNaN(maxLength)) {
- if(maxLength < 0) {
+ if (maxLength < 0) {
//we can't set Number.MAX_VALUE to input's maxLength property
//so we use a magic number here, it should works at most use cases.
maxLength = 65535;
@@ -155,40 +160,40 @@ let EditBoxImpl = cc.Class({
this._maxLength = maxLength;
this._edTxt && (this._edTxt.maxLength = maxLength);
}
- },
+ }
- setString (text) {
+ setString(text) {
this._text = text;
this._edTxt && (this._edTxt.value = text);
- },
+ }
- getString () {
+ getString() {
return this._text;
- },
+ }
- setPlaceholderText (text) {
+ setPlaceholderText(text) {
this._placeholderText = text;
- },
+ }
- getPlaceholderText () {
+ getPlaceholderText() {
return this._placeholderText;
- },
+ }
- setDelegate (delegate) {
+ setDelegate(delegate) {
this._delegate = delegate;
- },
+ }
- setInputMode (inputMode) {
+ setInputMode(inputMode) {
if (this._inputMode === inputMode) return;
this._inputMode = inputMode;
this.createInput();
-
+
this._updateDomInputType();
this._updateSize(this._size.width, this._size.height);
- },
+ }
- setInputFlag (inputFlag) {
+ setInputFlag(inputFlag) {
if (this._inputFlag === inputFlag) return;
this._inputFlag = inputFlag;
@@ -207,55 +212,55 @@ let EditBoxImpl = cc.Class({
this._edTxt.style.textTransform = textTransform;
this._edTxt.value = this._text;
}
- },
+ }
- setReturnType (returnType) {
+ setReturnType(returnType) {
this._returnType = returnType;
this._updateDomInputType();
- },
+ }
- setFontSize (fontSize) {
+ setFontSize(fontSize) {
this._edFontSize = fontSize || this._edFontSize;
this._edTxt && (this._edTxt.style.fontSize = this._edFontSize + 'px');
- },
-
- setFontColor (color) {
+ }
+
+ setFontColor(color) {
this._textColor = color;
this._edTxt && (this._edTxt.style.color = color.toCSS('rgba'));
- },
-
- setSize (width, height) {
+ }
+
+ setSize(width, height) {
this._size.width = width;
this._size.height = height;
this._updateSize(width, height);
- },
+ }
- setNode (node) {
+ setNode(node) {
this._node = node;
- },
+ }
- update () {
+ update() {
// TODO: find better way to update matrix
// if (this._editing) {
- this._updateMatrix();
+ this._updateMatrix();
// }
- },
+ }
- clear () {
+ clear() {
this._node = null;
this.setDelegate(null);
this.removeDom();
- },
+ }
- _onTouchBegan (touch) {
-
- },
+ _onTouchBegan(touch) {
- _onTouchEnded () {
+ }
+
+ _onTouchEnded() {
this._beginEditing();
- },
+ }
- _beginEditing () {
+ _beginEditing() {
if (cc.sys.isMobile && !this._editing) {
// Pre adaptation
this._beginEditingOnMobile();
@@ -265,7 +270,7 @@ let EditBoxImpl = cc.Class({
this._edTxt.style.display = '';
let self = this;
- function startFocus () {
+ function startFocus() {
self._edTxt.focus();
}
@@ -279,11 +284,11 @@ let EditBoxImpl = cc.Class({
startFocus();
}
}
-
+
this._editing = true;
- },
-
- _endEditing () {
+ }
+
+ _endEditing() {
let self = this;
let hideDomInputAndShowLabel = function () {
if (!self._alwaysOnTop && self._edTxt) {
@@ -306,100 +311,115 @@ let EditBoxImpl = cc.Class({
}
}
this._editing = false;
- },
-
- _updateDomInputType () {
+ }
+
+ _updateDomInputType() {
let inputMode = this._inputMode;
let edTxt = this._edTxt;
if (!edTxt) return;
-
+
if (this._inputFlag === InputFlag.PASSWORD) {
edTxt.type = 'password';
return;
}
-
+
let type = edTxt.type;
if (inputMode === InputMode.EMAIL_ADDR) {
type = 'email';
- } else if(inputMode === InputMode.NUMERIC || inputMode === InputMode.DECIMAL) {
+ } else if (inputMode === InputMode.NUMERIC || inputMode === InputMode.DECIMAL) {
type = 'number';
- } else if(inputMode === InputMode.PHONE_NUMBER) {
+ } else if (inputMode === InputMode.PHONE_NUMBER) {
type = 'number';
edTxt.pattern = '[0-9]*';
- } else if(inputMode === InputMode.URL) {
+ } else if (inputMode === InputMode.URL) {
type = 'url';
} else {
type = 'text';
-
+
if (this._returnType === KeyboardReturnType.SEARCH) {
type = 'search';
}
}
-
+
edTxt.type = type;
- },
-
- _updateSize (newWidth, newHeight) {
+ }
+
+ _updateSize(newWidth, newHeight) {
let edTxt = this._edTxt;
if (!edTxt) return;
-
+
edTxt.style.width = newWidth + 'px';
edTxt.style.height = newHeight + 'px';
- },
+ }
- _updateMatrix () {
+ _updateMatrix() {
if (!this._edTxt) return;
-
- let node = this._node,
+
+ let node = this._node,
scaleX = cc.view._scaleX, scaleY = cc.view._scaleY,
viewport = cc.view._viewportRect,
dpr = cc.view._devicePixelRatio;
-
+
node.getWorldMatrix(_matrix);
let contentSize = node._contentSize;
_vec3.x = -node._anchorPoint.x * contentSize.width;
_vec3.y = -node._anchorPoint.y * contentSize.height;
-
+
math.mat4.translate(_matrix, _matrix, _vec3);
let camera;
// can't find camera in editor
- if (CC_EDITOR) {
- camera = cc.Camera.main;
+ // if (CC_EDITOR) {
+ // camera = cc.Camera.main;
+ // }
+ // else {
+ // camera = cc.Camera.findCamera(node);
+ // }
+ let renderComp = node.getComponent(cc.RenderComponent);
+ if (!renderComp) {
+ return false;
}
- else {
- camera = cc.Camera.findCamera(node);
+ let canvas = cc.CanvasComponent.findView(renderComp);
+ if (!canvas) {
+ return;
}
-
- camera.getWorldToCameraMatrix(_matrix_temp);
+
+ // camera.getWorldToCameraMatrix(_matrix_temp);
+ canvas.node.getWorldRT(_matrix_temp);
+ let m12 = _matrix_temp.m12;
+ let m13 = _matrix_temp.m13;
+ let center = cc.visibleRect.center;
+ _matrix_temp.m12 = center.x - (_matrix_temp.m00 * m12 + _matrix_temp.m04 * m13);
+ _matrix_temp.m13 = center.y - (_matrix_temp.m01 * m12 + _matrix_temp.m05 * m13);
+
math.mat4.mul(_matrix_temp, _matrix_temp, _matrix);
-
+
scaleX /= dpr;
scaleY /= dpr;
-
+
let container = cc.game.container;
let a = _matrix_temp.m00 * scaleX, b = _matrix.m01, c = _matrix.m04, d = _matrix_temp.m05 * scaleY;
-
+
let offsetX = container && container.style.paddingLeft && parseInt(container.style.paddingLeft);
offsetX += viewport.x / dpr;
let offsetY = container && container.style.paddingBottom && parseInt(container.style.paddingBottom);
offsetY += viewport.y / dpr;
let tx = _matrix_temp.m12 * scaleX + offsetX, ty = _matrix_temp.m13 * scaleY + offsetY;
-
+
if (polyfill.zoomInvalid) {
this._updateSize(this._size.width * a, this._size.height * d);
a = 1;
d = 1;
}
-
+
let matrix = "matrix(" + a + "," + -b + "," + -c + "," + d + "," + tx + "," + -ty + ")";
this._edTxt.style['transform'] = matrix;
this._edTxt.style['-webkit-transform'] = matrix;
this._edTxt.style['transform-origin'] = '0px 100% 0px';
this._edTxt.style['-webkit-transform-origin'] = '0px 100% 0px';
- },
+ }
- _adjustEditBoxPosition () {
+ _adjustEditBoxPosition() {
this._node.getWorldMatrix(_matrix);
let y = _matrix.m13;
let windowHeight = cc.visibleRect.height;
@@ -408,7 +428,7 @@ let EditBoxImpl = cc.Class({
if (windowWidth > windowHeight) {
factor = 0.7;
}
- setTimeout(function() {
+ setTimeout(function () {
if (window.scrollY < SCROLLY && y < windowHeight * factor) {
let scrollOffset = windowHeight * factor - y - window.scrollY;
if (scrollOffset < 35) scrollOffset = 35;
@@ -417,70 +437,155 @@ let EditBoxImpl = cc.Class({
}
}, DELAY_TIME);
}
-});
-let _p = EditBoxImpl.prototype;
-
-_p.createInput = function() {
- if (this._inputMode === InputMode.ANY) {
- this._createDomTextArea();
- }
- else {
- this._createDomInput();
- }
-};
-
-// Called before editbox focus to register cc.view status
-_p._beginEditingOnMobile = function () {
- let self = this;
- this.__orientationChanged = function () {
- self._adjustEditBoxPosition();
- };
- window.addEventListener('orientationchange', this.__orientationChanged);
-
- if (cc.view.isAutoFullScreenEnabled()) {
- this.__fullscreen = true;
- cc.view.enableAutoFullScreen(false);
- cc.screen.exitFullScreen();
- } else {
- this.__fullscreen = false;
- }
- this.__autoResize = cc.view._resizeWithBrowserSize;
- cc.view.resizeWithBrowserSize(false);
- _currentEditBoxImpl = this;
-};
-
-// Called after keyboard disappeared to readapte the game view
-_p._endEditingOnMobile = function () {
- if (this.__rotateScreen) {
- cc.game.container.style['-webkit-transform'] = 'rotate(90deg)';
- cc.game.container.style.transform = 'rotate(90deg)';
-
- let view = cc.view;
- let width = view._originalDesignResolutionSize.width;
- let height = view._originalDesignResolutionSize.height;
- if (width > 0) {
- view.setDesignResolutionSize(width, height, view._resolutionPolicy);
+ createInput() {
+ if (this._inputMode === InputMode.ANY) {
+ this._createDomTextArea();
+ }
+ else {
+ this._createDomInput();
}
- this.__rotateScreen = false;
}
- window.removeEventListener('orientationchange', this.__orientationChanged);
+ // Called before editbox focus to register cc.view status
+ _beginEditingOnMobile() {
+ let self = this;
+ this.__orientationChanged = function () {
+ self._adjustEditBoxPosition();
+ };
+ window.addEventListener('orientationchange', this.__orientationChanged);
- if(this.__fullscreen) {
- cc.view.enableAutoFullScreen(true);
+ if (cc.view.isAutoFullScreenEnabled()) {
+ this.__fullscreen = true;
+ cc.view.enableAutoFullScreen(false);
+ cc.screen.exitFullScreen();
+ } else {
+ this.__fullscreen = false;
+ }
+ this.__autoResize = cc.view._resizeWithBrowserSize;
+ cc.view.resizeWithBrowserSize(false);
+ _currentEditBoxImpl = this;
}
- // In case focus on editBox A from editBox B
- // A disable resizeWithBrowserSize
- // whilte B enable resizeWithBrowserSize
- // Only _currentEditBoxImpl can enable resizeWithBrowserSize
- if (this.__autoResize && _currentEditBoxImpl === this) {
- cc.view.resizeWithBrowserSize(true);
- }
-};
+ // Called after keyboard disappeared to readapte the game view
+ _endEditingOnMobile() {
+ if (this.__rotateScreen) {
+ cc.game.container.style['-webkit-transform'] = 'rotate(90deg)';
+ cc.game.container.style.transform = 'rotate(90deg)';
-function _inputValueHandle (input, editBoxImpl) {
+ let view = cc.view;
+ let width = view._originalDesignResolutionSize.width;
+ let height = view._originalDesignResolutionSize.height;
+ if (width > 0) {
+ view.setDesignResolutionSize(width, height, view._resolutionPolicy);
+ }
+ this.__rotateScreen = false;
+ }
+
+ window.removeEventListener('orientationchange', this.__orientationChanged);
+
+ if (this.__fullscreen) {
+ cc.view.enableAutoFullScreen(true);
+ }
+
+ // In case focus on editBox A from editBox B
+ // A disable resizeWithBrowserSize
+ // whilte B enable resizeWithBrowserSize
+ // Only _currentEditBoxImpl can enable resizeWithBrowserSize
+ if (this.__autoResize && _currentEditBoxImpl === this) {
+ cc.view.resizeWithBrowserSize(true);
+ }
+ }
+
+ _createDomInput() {
+ this.removeDom();
+
+ let 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.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';
+ tmpEdTxt.style.position = "absolute";
+ tmpEdTxt.style.bottom = "0px";
+ tmpEdTxt.style.left = LEFT_PADDING + "px";
+ tmpEdTxt.style['-moz-appearance'] = 'textfield';
+ tmpEdTxt.style.className = "cocosEditBox";
+ tmpEdTxt.style.fontFamily = 'Arial';
+
+ registerInputEventListener(tmpEdTxt, this);
+
+ return tmpEdTxt;
+ }
+
+ _createDomTextArea() {
+ this.removeDom();
+
+ let 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.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';
+ tmpEdTxt.style.position = "absolute";
+ tmpEdTxt.style.bottom = "0px";
+ tmpEdTxt.style.left = LEFT_PADDING + "px";
+ tmpEdTxt.style.className = "cocosEditBox";
+ tmpEdTxt.style.fontFamily = 'Arial';
+
+ registerInputEventListener(tmpEdTxt, this, true);
+
+ return tmpEdTxt;
+ }
+
+ _addDomToGameContainer() {
+ cc.game.container.appendChild(this._edTxt);
+ }
+
+ removeDom() {
+ let edTxt = this._edTxt;
+ if (edTxt) {
+ // Remove listeners
+ let cbs = this.__eventListeners;
+ edTxt.removeEventListener('compositionstart', cbs.compositionstart);
+ edTxt.removeEventListener('compositionend', cbs.compositionend);
+ edTxt.removeEventListener('input', cbs.input);
+ edTxt.removeEventListener('focus', cbs.focus);
+ edTxt.removeEventListener('keypress', cbs.keypress);
+ edTxt.removeEventListener('blur', cbs.blur);
+ cbs.compositionstart = null;
+ cbs.compositionend = null;
+ cbs.input = null;
+ cbs.focus = null;
+ cbs.keypress = null;
+ cbs.blur = null;
+
+ let hasChild = contains(cc.game.container, edTxt);
+ if (hasChild) {
+ cc.game.container.removeChild(edTxt);
+ }
+ }
+ this._edTxt = null;
+ }
+}
+
+function _inputValueHandle(input, editBoxImpl) {
if (input.value.length > editBoxImpl._maxLength) {
input.value = input.value.slice(0, editBoxImpl._maxLength);
}
@@ -492,7 +597,7 @@ function _inputValueHandle (input, editBoxImpl) {
}
}
-function registerInputEventListener (tmpEdTxt, editBoxImpl, isTextarea) {
+function registerInputEventListener(tmpEdTxt: HTMLElement, editBoxImpl: EditBoxImpl, isTextarea: boolean = false) {
let inputLock = false;
let cbs = editBoxImpl.__eventListeners;
cbs.compositionstart = function () {
@@ -557,92 +662,3 @@ function registerInputEventListener (tmpEdTxt, editBoxImpl, isTextarea) {
editBoxImpl._addDomToGameContainer();
}
-
-_p._createDomInput = function () {
- this.removeDom();
-
- let 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.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';
- tmpEdTxt.style.position = "absolute";
- tmpEdTxt.style.bottom = "0px";
- tmpEdTxt.style.left = LEFT_PADDING + "px";
- tmpEdTxt.style['-moz-appearance'] = 'textfield';
- tmpEdTxt.style.className = "cocosEditBox";
- tmpEdTxt.style.fontFamily = 'Arial';
-
- registerInputEventListener(tmpEdTxt, this);
-
- return tmpEdTxt;
-};
-
-_p._createDomTextArea = function () {
- this.removeDom();
-
- let 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.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';
- tmpEdTxt.style.position = "absolute";
- tmpEdTxt.style.bottom = "0px";
- tmpEdTxt.style.left = LEFT_PADDING + "px";
- tmpEdTxt.style.className = "cocosEditBox";
- tmpEdTxt.style.fontFamily = 'Arial';
-
- registerInputEventListener(tmpEdTxt, this, true);
-
- return tmpEdTxt;
-};
-
-_p._addDomToGameContainer = function () {
- cc.game.container.appendChild(this._edTxt);
-};
-
-_p.removeDom = function () {
- let edTxt = this._edTxt;
- if (edTxt) {
- // Remove listeners
- let cbs = this.__eventListeners;
- edTxt.removeEventListener('compositionstart', cbs.compositionstart);
- edTxt.removeEventListener('compositionend', cbs.compositionend);
- edTxt.removeEventListener('input', cbs.input);
- edTxt.removeEventListener('focus', cbs.focus);
- edTxt.removeEventListener('keypress', cbs.keypress);
- edTxt.removeEventListener('blur', cbs.blur);
- cbs.compositionstart = null;
- cbs.compositionend = null;
- cbs.input = null;
- cbs.focus = null;
- cbs.keypress = null;
- cbs.blur = null;
-
- let hasChild = utils.contains(cc.game.container, edTxt);
- if (hasChild) {
- cc.game.container.removeChild(edTxt);
- }
- }
- this._edTxt = null;
-};
-
-module.exports = EditBoxImpl;
diff --git a/cocos/2d/ui/editbox/types.js b/cocos/3d/ui/components/editbox/types.js
similarity index 98%
rename from cocos/2d/ui/editbox/types.js
rename to cocos/3d/ui/components/editbox/types.js
index ca1757d2e4..88b52a381b 100644
--- a/cocos/2d/ui/editbox/types.js
+++ b/cocos/3d/ui/components/editbox/types.js
@@ -180,8 +180,4 @@ let InputFlag = cc.Enum({
DEFAULT: 5
});
-module.exports = {
- KeyboardReturnType: KeyboardReturnType,
- InputMode: InputMode,
- InputFlag: InputFlag
-};
+export { KeyboardReturnType, InputMode, InputFlag }
diff --git a/cocos/3d/ui/components/label-component.ts b/cocos/3d/ui/components/label-component.ts
new file mode 100644
index 0000000000..e3667fee59
--- /dev/null
+++ b/cocos/3d/ui/components/label-component.ts
@@ -0,0 +1,703 @@
+/****************************************************************************
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos.com
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated engine source code (the "Software"), a limited,
+ worldwide, royalty-free, non-assignable, revocable and non-exclusive license
+ to use Cocos Creator solely to develop games on your target platforms. You shall
+ not use Cocos Creator software for developing other software or tools that's
+ used for developing games. You are not granted to publish, distribute,
+ sublicense, and/or sell copies of Cocos Creator.
+
+ The software or tools in this License Agreement are licensed, not sold.
+ Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+// @ts-check
+import macro from '../../../core/platform/CCMacro';
+import { RenderComponent } from './ui-render-component';
+import ImageAsset from '../../../assets/image-asset';
+// import { vec2, vec3, mat4, color4 } from '../../../core/vmath/index';
+import {
+ ccclass,
+ property,
+ menu,
+ executionOrder,
+ executeInEditMode,
+} from '../../../core/data/class-decorator';
+import Font from '../../../assets/CCFont';
+import Texture2D from '../../../assets/texture-2d';
+import { MeshBuffer } from '../mesh-buffer';
+import { Enum } from '../../../core/value-types';
+// import { value } from '../../../core/utils/js';
+
+/**
+ * !#en Enum for text alignment.
+ * !#zh 文本横向对齐类型
+ * @enum Label.HorizontalAlign
+ */
+/**
+ * !#en Alignment left for text.
+ * !#zh 文本内容左对齐。
+ * @property {Number} LEFT
+ */
+/**
+ * !#en Alignment center for text.
+ * !#zh 文本内容居中对齐。
+ * @property {Number} CENTER
+ */
+/**
+ * !#en Alignment right for text.
+ * !#zh 文本内容右边对齐。
+ * @property {Number} RIGHT
+ */
+const HorizontalAlign = macro.TextAlignment;
+
+/**
+ * !#en Enum for vertical text alignment.
+ * !#zh 文本垂直对齐类型
+ * @enum Label.VerticalAlign
+ */
+/**
+ * !#en Vertical alignment top for text.
+ * !#zh 文本顶部对齐。
+ * @property {Number} TOP
+ */
+/**
+ * !#en Vertical alignment center for text.
+ * !#zh 文本居中对齐。
+ * @property {Number} CENTER
+ */
+/**
+ * !#en Vertical alignment bottom for text.
+ * !#zh 文本底部对齐。
+ * @property {Number} BOTTOM
+ */
+const VerticalAlign = macro.VerticalTextAlignment;
+
+/**
+ * !#en Enum for Overflow.
+ * !#zh Overflow 类型
+ * @enum Label.Overflow
+ */
+/**
+ * !#en NONE.
+ * !#zh 不做任何限制。
+ * @property {Number} NONE
+ */
+/**
+ * !#en In CLAMP mode, when label content goes out of the bounding box, it will be clipped.
+ * !#zh CLAMP 模式中,当文本内容超出边界框时,多余的会被截断。
+ * @property {Number} CLAMP
+ */
+/**
+ * !#en In SHRINK mode, the font size will change dynamically to adapt the content size.
+ * !#zh SHRINK 模式,字体大小会动态变化,以适应内容大小。
+ * @property {Number} SHRINK
+ */
+/**
+ * !#en In RESIZE_HEIGHT mode, you can only change the width of label and the height is changed automatically.
+ * !#zh 在 RESIZE_HEIGHT 模式下,只能更改文本的宽度,高度是自动改变的。
+ * @property {Number} RESIZE_HEIGHT
+ */
+const Overflow = Enum({
+ NONE: 0,
+ CLAMP: 1,
+ SHRINK: 2,
+ RESIZE_HEIGHT: 3,
+});
+
+/**
+ * !#en Enum for font type.
+ * !#zh Type 类型
+ * @enum Label.Type
+ */
+/**
+ * !#en The TTF font type.
+ * !#zh TTF字体
+ * @property {Number} TTF
+ */
+/**
+ * !#en The bitmap font type.
+ * !#zh 位图字体
+ * @property {Number} BMFont
+ */
+/**
+ * !#en The system font type.
+ * !#zh 系统字体
+ * @property {Number} SystemFont
+ */
+
+/**
+ * !#en The Label Component.
+ * !#zh 文字标签组件
+ * @class Label
+ * @extends RenderComponent
+ */
+@ccclass('cc.LabelComponent')
+@executionOrder(100)
+@menu('UI/Label')
+@executeInEditMode
+export class LabelComponent extends RenderComponent {
+
+ /**
+ * !#en Content string of label.
+ * !#zh 标签显示的文本内容。
+ * @property {String} string
+ */
+ @property
+ get string () {
+ return this._string;
+ }
+ set string (value: string) {
+ value = value.toString();
+ if (this._string === value) {
+ return;
+ }
+
+ this._string = value;
+ this._updateRenderData();
+ this._checkStringEmpty();
+ }
+
+ /**
+ * !#en Horizontal Alignment of label.
+ * !#zh 文本内容的水平对齐方式。
+ * @property {Label.HorizontalAlign} horizontalAlign
+ */
+ @property({
+ type: HorizontalAlign,
+ })
+ get horizontalAlign () {
+ return this._horizontalAlign;
+ }
+
+ set horizontalAlign (value: number) {
+ if (this._horizontalAlign === value) {
+ return;
+ }
+
+ this._horizontalAlign = value;
+ this._updateRenderData();
+ }
+
+ /**
+ * !#en Vertical Alignment of label.
+ * !#zh 文本内容的垂直对齐方式。
+ * @property {Label.VerticalAlign} verticalAlign
+ */
+ @property({
+ type: VerticalAlign,
+ })
+ get verticalAlign () {
+ return this._verticalAlign;
+ }
+
+ set verticalAlign (value: number) {
+ if (this._verticalAlign === value) {
+ return;
+ }
+
+ this._verticalAlign = value;
+ this._updateRenderData();
+ }
+
+ /**
+ * !#en The actual rendering font size in shrink mode
+ * !#zh SHRINK 模式下面文本实际渲染的字体大小
+ * @property {Number} actualFontSize
+ */
+ @property
+ get actualFontSize () {
+ return this._actualFontSize;
+ }
+
+ /**
+ * !#en Font size of label.
+ * !#zh 文本字体大小。
+ * @property {Number} fontSize
+ */
+ @property
+ get fontSize () {
+ return this._fontSize;
+ }
+
+ set fontSize (value: number) {
+ if (this._fontSize === value) {
+ return;
+ }
+
+ this._fontSize = value;
+ this._updateRenderData();
+ }
+
+ /**
+ * !#en Font family of label, only take effect when useSystemFont property is true.
+ * !#zh 文本字体名称, 只在 useSystemFont 属性为 true 的时候生效。
+ * @property {String} fontFamily
+ */
+ get fontFamily () {
+ return this._fontFamily;
+ }
+
+ set fontFamily (value: string) {
+ if (this._fontFamily === value) {
+ return;
+ }
+
+ this._fontFamily = value;
+ this._updateRenderData();
+ }
+
+ /**
+ * !#en Line Height of label.
+ * !#zh 文本行高。
+ * @property {Number} lineHeight
+ */
+ @property
+ get lineHeight () {
+ return this._lineHeight;
+ }
+ set lineHeight (value: number) {
+ if (this._lineHeight === value) {
+ return;
+ }
+
+ this._lineHeight = value;
+ this._updateRenderData();
+ }
+
+ /**
+ * !#en Overflow of label.
+ * !#zh 文字显示超出范围时的处理方式。
+ * @property {Label.Overflow} overflow
+ */
+ @property
+ get overflow () {
+ return this._overflow;
+ }
+
+ set overflow (value: number) {
+ if (this._overflow === value) {
+ return;
+ }
+
+ this._overflow = value;
+ this._updateRenderData();
+ }
+
+ /**
+ * !#en Whether auto wrap label when string width is large than label width.
+ * !#zh 是否自动换行。
+ * @property {Boolean} enableWrapText
+ */
+ @property
+ get enableWrapText () {
+ return this._enableWrapText;
+ }
+ set enableWrapText (value: boolean) {
+ if (this._enableWrapText === value) {
+ return;
+ }
+
+ this._enableWrapText = value;
+ this._updateRenderData();
+ }
+
+ /**
+ * !#en The font of label.
+ * !#zh 文本字体。
+ * @property {Font} font
+ */
+ @property({
+ type: Font,
+ })
+ get font () {
+ // return this._N$file;
+ return this._font;
+ }
+
+ set font (value: Font | null) {
+ if (this._font === value) { return; }
+
+ // if delete the font, we should change isSystemFontUsed to true
+ this._isSystemFontUsed = !value;
+
+ if (CC_EDITOR && value) {
+ this._userDefinedFont = value;
+ }
+
+ // this._N$file = value;
+ this._font = value;
+ this._bmFontOriginalSize = -1;
+ // if (value && this._isSystemFontUsed)
+ // this._isSystemFontUsed = false;
+
+ if (typeof value === 'string') {
+ cc.warnID(4000);
+ }
+
+ if (value instanceof cc.BitmapFont) {
+ this._bmFontOriginalSize = value.fontSize;
+ }
+
+ if (this._renderData) {
+ this.destroyRenderData();
+ this._renderData = null;
+ }
+ // this._fontAtlas = null;
+ this._updateAssembler();
+ this._applyFontTexture(true);
+ this._updateRenderData();
+ }
+
+ /**
+ * !#en Whether use system font name or not.
+ * !#zh 是否使用系统字体。
+ * @property {Boolean} isSystemFontUsed
+ */
+ @property
+ get useSystemFont () {
+ return this._isSystemFontUsed;
+ }
+
+ set useSystemFont (value: boolean) {
+ if (this._isSystemFontUsed === value) {
+ return;
+ }
+
+ this.destroyRenderData();
+ this._renderData = null;
+
+ if (CC_EDITOR) {
+ if (!value && this._isSystemFontUsed && this._userDefinedFont) {
+ this.font = this._userDefinedFont;
+ this.spacingX = this._spacingX;
+ return;
+ }
+ }
+
+ this._isSystemFontUsed = !!value;
+ if (value) {
+ this.font = null;
+ this._updateAssembler();
+ this._updateRenderData();
+ this._checkStringEmpty();
+ }
+ // else if (!this._userDefinedFont) {
+ // this.disableRender();
+ // }
+
+ }
+
+ @property
+ get spacingX () {
+ return this._spacingX;
+ }
+
+ set spacingX (value: number) {
+ if (this._spacingX === value) {
+ return;
+ }
+
+ this._spacingX = value;
+ this._updateRenderData();
+ }
+
+ /**
+ * !#en Whether the font is bold or not.
+ * !#zh 字体是否加粗。
+ * @property {Boolean} isBold
+ */
+ get isBold () {
+ return this._isBold;
+ }
+
+ set isBold (value: boolean) {
+ if (this._isBold === value) {
+ return;
+ }
+
+ this._isBold = value;
+ }
+
+ /**
+ * !#en Whether the font is tilted or not.
+ * !#zh 字体是否倾斜。
+ * @property {Boolean} isBold
+ */
+ get isItalic () {
+ return this._isItalic;
+ }
+
+ set isItalic (value: boolean) {
+ if (this._isItalic === value) {
+ return;
+ }
+
+ this._isItalic = value;
+ }
+
+ /**
+ * !#en Whether the font is underlined.
+ * !#zh 字体是否加下划线。
+ * @property {Boolean} isBold
+ */
+ get isUnderline () {
+ return this._isUnderline;
+ }
+
+ set isUnderline (value: boolean) {
+ if (this._isUnderline === value) {
+ return;
+ }
+
+ this._isUnderline = value;
+ }
+
+ public static HorizontalAlign = HorizontalAlign;
+ public static VerticalAlign = VerticalAlign;
+ public static Overflow = Overflow;
+ @property
+ public _useOriginalSize: boolean = true;
+ @property
+ public _string: string = 'label';
+ @property
+ public _horizontalAlign: number = HorizontalAlign.LEFT;
+ @property
+ public _verticalAlign: number = VerticalAlign.TOP;
+ @property
+ public _actualFontSize: number = 0;
+ @property
+ public _fontSize: number = 40;
+ @property
+ public _fontFamily: string = 'Arial';
+ @property
+ public _lineHeight: number = 40;
+ @property
+ public _overflow: number = Overflow.NONE;
+ @property
+ public _enableWrapText: boolean = true;
+ // // 这个保存了旧项目的 file 数据
+ // _N$file = null;
+ @property
+ public _font: Font | null = null;
+ @property
+ public _isSystemFontUsed: boolean = true;
+ @property
+ public _bmFontOriginalSize: number = -1;
+ @property
+ public _spacingX: number = 0;
+ @property
+ public _isItalic: boolean = false;
+ @property
+ public _isBold: boolean = false;
+ @property
+ public _isUnderline: boolean = false;
+
+ // don't need serialize
+ private _texture: Texture2D | null = null;
+ private _ttfTexture: Texture2D | null = null;
+ private _userDefinedFont: Font | null = null;
+ private _assemblerData: object|null = null;
+ private _assembler: object|null = null;
+
+ constructor () {
+ super();
+ if (CC_EDITOR) {
+ this._userDefinedFont = null;
+ }
+
+ this._assemblerData = null;
+
+ this._ttfTexture = null;
+ }
+
+ public onEnable () {
+ // this._super();
+ super.onEnable();
+
+ // TODO: Hack for barbarians
+ if (!this._font && !this._isSystemFontUsed) {
+ this.useSystemFont = true;
+ }
+ // Reapply default font family if necessary
+ if (this._isSystemFontUsed && !this._fontFamily) {
+ this.fontFamily = 'Arial';
+ }
+
+ // Keep track of Node size
+ this.node.on(cc.Node.EventType.SIZE_CHANGED, this._updateRenderData, this);
+ this.node.on(cc.Node.EventType.ANCHOR_CHANGED, this._updateRenderData, this);
+
+ this._checkStringEmpty();
+ this._updateRenderData(true);
+ // this._updateAssembler();
+ // this._activateMaterial();
+ }
+
+ public onDisable () {
+ super.onDisable();
+ // this._super();
+ this.node.off(cc.Node.EventType.SIZE_CHANGED, this._updateRenderData, this);
+ this.node.off(cc.Node.EventType.ANCHOR_CHANGED, this._updateRenderData, this);
+ }
+
+ public onDestroy () {
+ if (this._assembler && this._assembler._resetAssemblerData){
+ this._assembler._resetAssemblerData(this._assemblerData);
+ }
+
+ this._assemblerData = null;
+ if (this._ttfTexture) {
+ this._ttfTexture.destroy();
+ this._ttfTexture = null;
+ }
+ // this._super();
+ }
+
+ public updateRenderData (buffer: MeshBuffer) {
+ if (!this._assembler) {
+ return;
+ }
+
+ this._assembler.updateRenderData(this);
+ this._assembler.fillBuffers(this, buffer);
+ }
+
+ public _canRender () {
+ // let result = this._super();
+ let result = this._enabled;
+ const font = this.font;
+ if (font instanceof cc.BitmapFont) {
+ const spriteFrame = font.spriteFrame;
+ // cannot be activated if texture not loaded yet
+ if (!spriteFrame || !spriteFrame.textureLoaded()) {
+ result = false;
+ }
+ }
+ return result;
+ }
+
+ public _checkStringEmpty () {
+ // this.markForRender(!!this.string);
+ }
+
+ public _updateAssembler () {
+ const assembler = LabelComponent._assembler.getAssembler(this);
+
+ if (this._assembler !== assembler) {
+ this.destroyRenderData();
+ this._assembler = assembler;
+ }
+
+ if (!this._renderData) {
+ this._renderData = this._assembler.createData(this);
+ this._renderData.material = this.material;
+ }
+ }
+
+ public _activateMaterial (force: boolean) {
+ let material = this.material;
+ if (material && !force) {
+ return;
+ }
+
+ if (!material) {
+ // material = new SpriteMaterial();
+ this.material = cc.BuiltinResMgr['sprite-material'];
+ material = this.material;
+ }
+ // Setup blend function for premultiplied ttf label texture
+ if (this._texture === this._ttfTexture) {
+ this._srcBlendFactor = cc.macro.BlendFactor.ONE;
+ } else {
+ this._srcBlendFactor = cc.macro.BlendFactor.SRC_ALPHA;
+ }
+ material.setProperty('mainTexture', this._texture);
+ // For batch rendering, do not use uniform color.
+ material.useColor = false;
+ // this._updateMaterial(material);
+ }
+
+ public _applyFontTexture (force: boolean) {
+ const font = this._font;
+ if (font instanceof cc.BitmapFont) {
+ const spriteFrame = font.spriteFrame;
+ const self = this;
+ const onBMFontTextureLoaded = function () {
+ // TODO: old texture in material have been released by loader
+ self._texture = spriteFrame;
+ self._activateMaterial(force);
+
+ if (force) {
+ self._assembler && self._assembler.updateRenderData(self);
+ }
+ };
+ // cannot be activated if texture not loaded yet
+ if (spriteFrame && spriteFrame.textureLoaded()) {
+ onBMFontTextureLoaded();
+ } else {
+ // this.disableRender();
+
+ if (spriteFrame) {
+ spriteFrame.once('load', onBMFontTextureLoaded, this);
+ spriteFrame.ensureLoadTexture();
+ }
+ }
+ } else {
+ if (!this._ttfTexture) {
+ this._ttfTexture = new cc.SpriteFrame();
+ this._ttfTexture.setFilters(cc.Texture2D.Filter.LINEAR, cc.Texture2D.Filter.LINEAR);
+ this._ttfTexture.setWrapMode(cc.Texture2D.WrapMode.CLAMP_TO_EDGE, cc.Texture2D.WrapMode.CLAMP_TO_EDGE);
+ // TTF texture in web will blend with canvas or body background color
+ if (!CC_JSB) {
+ // this._ttfTexture.setPremultiplyAlpha(true);
+ }
+ this._assemblerData = this._assembler._getAssemblerData();
+ this._ttfTexture.image = new ImageAsset(this._assemblerData.canvas);
+ // this._ttfTexture.initWithElement(this._assemblerData.canvas);
+ }
+ this._texture = this._ttfTexture;
+ this._activateMaterial(force);
+
+ if (force) {
+ this._assembler && this._assembler.updateRenderData(this);
+ }
+ }
+ }
+
+ public _updateColor () {
+ const font = this.font;
+ if (font instanceof cc.BitmapFont) {
+ // this._super();
+ } else {
+ this._updateRenderData(false);
+ // this.node._renderFlag &= ~RenderFlow.FLAG_COLOR;
+ }
+ }
+
+ public _updateRenderData (force: boolean = false) {
+ const renderData = this._renderData;
+ if (renderData) {
+ renderData.vertDirty = true;
+ renderData.uvDirty = true;
+ // this.markForUpdateRenderData(true);
+ }
+
+ if (force) {
+ this._updateAssembler();
+ this._applyFontTexture(force);
+ }
+ }
+}
diff --git a/cocos/3d/ui/components/mask-component.ts b/cocos/3d/ui/components/mask-component.ts
new file mode 100644
index 0000000000..606aa50a3a
--- /dev/null
+++ b/cocos/3d/ui/components/mask-component.ts
@@ -0,0 +1,420 @@
+/****************************************************************************
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos.com
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated engine source code (the "Software"), a limited,
+ worldwide, royalty-free, non-assignable, revocable and non-exclusive license
+ to use Cocos Creator solely to develop games on your target platforms. You shall
+ not use Cocos Creator software for developing other software or tools that's
+ used for developing games. You are not granted to publish, distribute,
+ sublicense, and/or sell copies of Cocos Creator.
+
+ The software or tools in this License Agreement are licensed, not sold.
+ Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+import {SpriteFrame} from '../../../assets/CCSpriteFrame';
+import { ccclass, executeInEditMode, executionOrder,
+ menu, property, requireComponent } from '../../../core/data/class-decorator';
+import { ccenum } from '../../../core/value-types/enum';
+import { clamp } from '../../../core/vmath';
+import { Node } from '../../../scene-graph/node';
+import { RenderComponent } from './ui-render-component';
+import { UITransformComponent } from './ui-transfrom-component';
+const renderEngine = require('../../../2d/renderer/render-engine');
+const math = renderEngine.math;
+const StencilMaterial = renderEngine.StencilMaterial;
+// const RenderFlow = require('../../../2d/renderer/render-flow');
+const Graphics = require('../../../2d/graphics/graphics');
+
+const _vec2_temp = cc.v2();
+const _mat4_temp = math.mat4.create();
+
+/**
+ * !#en the type for mask.
+ * !#zh 遮罩组件类型
+ */
+export enum MaskType {
+ /**
+ * !#en Rect mask.
+ * !#zh 使用矩形作为遮罩
+ */
+ RECT = 0,
+
+ /**
+ * !#en Ellipse Mask.
+ * !#zh 使用椭圆作为遮罩
+ */
+ ELLIPSE = 1,
+
+ /**
+ * !#en Image Stencil Mask.
+ * !#zh 使用图像模版作为遮罩
+ */
+ IMAGE_STENCIL = 2,
+}
+
+ccenum(MaskType);
+
+const SEGEMENTS_MIN = 3;
+const SEGEMENTS_MAX = 10000;
+
+/**
+ * !#en The Mask Component.
+ * !#zh 遮罩组件。
+ */
+@ccclass('cc.Mask')
+@executionOrder(100)
+@menu('UI/Mask')
+@requireComponent(UITransformComponent)
+@executeInEditMode
+export class MaskComponent extends RenderComponent {
+ public static Type = MaskType;
+
+ /**
+ * !#en The mask type.
+ * !#zh 遮罩类型。
+ */
+ public get type () {
+ return this._type;
+ }
+
+ public set type (value) {
+ this._type = value;
+ if (this._type !== MaskType.IMAGE_STENCIL) {
+ this.spriteFrame = null;
+ this.alphaThreshold = 0;
+ this._updateGraphics();
+ }
+ if (this._renderData) {
+ this.destroyRenderData();
+ this._renderData = null;
+ }
+ this._activateMaterial();
+ }
+
+ /**
+ * !#en The mask image
+ * !#zh 遮罩所需要的贴图
+ */
+ public get spriteFrame () {
+ return this._spriteFrame;
+ }
+
+ public set spriteFrame (value) {
+ const lastSprite = this._spriteFrame;
+ if (CC_EDITOR) {
+ if ((lastSprite && lastSprite._uuid) === (value && value._uuid)) {
+ return;
+ }
+ } else {
+ if (lastSprite === value) {
+ return;
+ }
+ }
+ this._spriteFrame = value;
+ this._applySpriteFrame(lastSprite);
+ }
+
+ /**
+ * !#en
+ * The alpha threshold.(Not supported in Canvas Mode)
+ * The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold.
+ * Should be a float between 0 and 1.
+ * This default to 0 (so alpha test is disabled).
+ * When it's set to 1, the stencil will discard all pixels, nothing will be shown,
+ * In previous version, it act as if the alpha test is disabled, which is incorrect.
+ * !#zh
+ * Alpha 阈值(不支持 Canvas 模式)
+ * 只有当模板的像素的 alpha 大于 alphaThreshold 时,才会绘制内容。
+ * 该数值 0 ~ 1 之间的浮点数,默认值为 0(因此禁用 alpha 测试)
+ * 当被设置为 1 时,会丢弃所有蒙版像素,所以不会显示任何内容,在之前的版本中,设置为 1 等同于 0,这种效果其实是不正确的
+ */
+ // @range: [0, 1, 0.1],
+ // slide: true,
+ @property({type: cc.Float})
+ public get alphaThreshold () {
+ return this._alphaThreshold;
+ }
+
+ public set alphaThreshold (value) {
+ this._alphaThreshold = value;
+ if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) {
+ cc.warnID(4201);
+ return;
+ }
+ if (this._material) {
+ this._material.alphaThreshold = this.alphaThreshold;
+ this._material.updateHash();
+ }
+ }
+
+ /**
+ * !#en Reverse mask(Not supported in Canvas Mode).
+ * !#zh 反向遮罩(不支持 Canvas 模式)。
+ */
+ @property({type: Boolean})
+ public get inverted () {
+ return this._inverted;
+ }
+
+ public set inverted (value) {
+ this._inverted = value;
+ if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) {
+ cc.warnID(4202);
+ return;
+ }
+ }
+
+ /**
+ * TODO: remove segments, not supported by graphics
+ * !#en The segements for ellipse mask.
+ * !#zh 椭圆遮罩的曲线细分数
+ */
+ public get segments () {
+ return this._segments;
+ }
+
+ public set segments (value) {
+ this._segments = clamp(value, SEGEMENTS_MIN, SEGEMENTS_MAX);
+ }
+
+ // _resizeToTarget: {
+ // animatable: false,
+ // set (value) {
+ // if (value) {
+ // this._resizeNodeToTargetNode();
+ // }
+ // },
+ // },
+
+ @property
+ private _spriteFrame: SpriteFrame | null = null;
+
+ @property
+ private _type = MaskType.RECT;
+
+ @property
+ private _alphaThreshold: number = 0;
+
+ @property
+ private _inverted: boolean = false;
+
+ @property
+ private _segments: number = 64;
+
+ private _graphics: Graphics | null = null;
+
+ private _material: StencilMaterial | null = null;
+
+ public onLoad () {
+ this._graphics = new Graphics();
+ this._graphics.node = this.node;
+ this._graphics.lineWidth = 0;
+ this._graphics.strokeColor = cc.color(0, 0, 0, 0);
+ }
+
+ public onRestore () {
+ if (!this._graphics) {
+ this._graphics = new Graphics();
+ this._graphics.node = this.node;
+ this._graphics.lineWidth = 0;
+ }
+ if (this._type !== MaskType.IMAGE_STENCIL) {
+ this._updateGraphics();
+ }
+ }
+
+ public onEnable () {
+ super.onEnable();
+ if (this._type === MaskType.IMAGE_STENCIL) {
+ if (!this._spriteFrame || !this._spriteFrame.textureLoaded()) {
+ // Do not render when sprite frame is not ready
+ this.markForRender(false);
+ if (this._spriteFrame) {
+ this._spriteFrame.once('load', this._onTextureLoaded, this);
+ this._spriteFrame.ensureLoadTexture();
+ }
+ }
+ } else {
+ this._updateGraphics();
+ }
+
+ this.node.on(Node.EventType.POSITION_CHANGED, this._updateGraphics, this);
+ this.node.on(Node.EventType.ROTATION_CHANGED, this._updateGraphics, this);
+ this.node.on(Node.EventType.SCALE_CHANGED, this._updateGraphics, this);
+ this.node.on(Node.EventType.SIZE_CHANGED, this._updateGraphics, this);
+ this.node.on(Node.EventType.ANCHOR_CHANGED, this._updateGraphics, this);
+
+ // this.node._renderFlag |= RenderFlow.FLAG_POST_RENDER;
+ this._activateMaterial();
+ }
+
+ public onDisable () {
+ super.onDisable();
+
+ this.node.off(Node.EventType.POSITION_CHANGED, this._updateGraphics, this);
+ this.node.off(Node.EventType.ROTATION_CHANGED, this._updateGraphics, this);
+ this.node.off(Node.EventType.SCALE_CHANGED, this._updateGraphics, this);
+ this.node.off(Node.EventType.SIZE_CHANGED, this._updateGraphics, this);
+ this.node.off(Node.EventType.ANCHOR_CHANGED, this._updateGraphics, this);
+
+ // this.node._renderFlag &= ~RenderFlow.FLAG_POST_RENDER;
+ }
+
+ public onDestroy () {
+ super.onDestroy();
+ this._graphics.destroy();
+ }
+
+ // _resizeNodeToTargetNode: CC_EDITOR && function () {
+ // if (this.spriteFrame) {
+ // const rect = this.spriteFrame.getRect();
+ // this.node.setContentSize(rect.width, rect.height);
+ // }
+ // }
+
+ public _onTextureLoaded () {
+ // Mark render data dirty
+ if (this._renderData) {
+ this._renderData.uvDirty = true;
+ this._renderData.vertDirty = true;
+ this.markForUpdateRenderData(true);
+ }
+ // Reactivate material
+ if (this.enabledInHierarchy) {
+ this._activateMaterial();
+ }
+ }
+
+ public _applySpriteFrame (oldFrame) {
+ if (oldFrame && oldFrame.off) {
+ oldFrame.off('load', this._onTextureLoaded, this);
+ }
+ const spriteFrame = this._spriteFrame;
+ if (spriteFrame) {
+ if (spriteFrame.textureLoaded()) {
+ this._onTextureLoaded();
+ } else {
+ spriteFrame.once('load', this._onTextureLoaded, this);
+ spriteFrame.ensureLoadTexture();
+ }
+ }
+ }
+
+ public _activateMaterial () {
+ // cannot be activated if texture not loaded yet
+ if (this._type === MaskType.IMAGE_STENCIL && (!this.spriteFrame || !this.spriteFrame.textureLoaded())) {
+ this.markForRender(false);
+ return;
+ }
+
+ // WebGL
+ if (cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) {
+ // Init material
+ if (!this._material) {
+ this._material = new StencilMaterial();
+ }
+
+ // Reset material
+ if (this._type === MaskType.IMAGE_STENCIL) {
+ const texture = this._spriteFrame;
+ this._material.useModel = false;
+ this._material.useTexture = true;
+ this._material.useColor = true;
+ this._material.texture = texture;
+ this._material.alphaThreshold = this.alphaThreshold;
+ } else {
+ this._material.useModel = true;
+ this._material.useTexture = false;
+ this._material.useColor = false;
+ }
+ }
+
+ this.markForRender(true);
+ }
+
+ public _updateGraphics () {
+ const node = this.node;
+ const graphics = this._graphics;
+ // Share render data with graphics content
+ graphics.clear(false);
+ const width = node._contentSize.width;
+ const height = node._contentSize.height;
+ const x = -width * node._anchorPoint.x;
+ const y = -height * node._anchorPoint.y;
+ if (this._type === MaskType.RECT) {
+ graphics.rect(x, y, width, height);
+ } else if (this._type === MaskType.ELLIPSE) {
+ const cx = x + width / 2;
+ const cy = y + height / 2;
+ const rx = width / 2;
+ const ry = height / 2;
+ graphics.ellipse(cx, cy, rx, ry);
+ }
+ if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) {
+ graphics.stroke();
+ } else {
+ graphics.fill();
+ }
+ }
+
+ public _hitTest (cameraPt) {
+ const node = this.node;
+ const size = node.getContentSize();
+ const w = size.width;
+ const h = size.height;
+ const testPt = _vec2_temp;
+
+ node._updateWorldMatrix();
+ math.mat4.invert(_mat4_temp, node._worldMatrix);
+ math.vec2.transformMat4(testPt, cameraPt, _mat4_temp);
+ testPt.x += node._anchorPoint.x * w;
+ testPt.y += node._anchorPoint.y * h;
+
+ if (this.type === MaskType.RECT || this.type === MaskType.IMAGE_STENCIL) {
+ return testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h;
+ } else if (this.type === MaskType.ELLIPSE) {
+ const rx = w / 2;
+ const ry = h / 2;
+ const px = testPt.x - 0.5 * w;
+ const py = testPt.y - 0.5 * h;
+ return px * px / (rx * rx) + py * py / (ry * ry) < 1;
+ }
+ }
+
+ public markForUpdateRenderData (enable) {
+ // if (enable && this.enabledInHierarchy) {
+ // this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA;
+ // } else if (!enable) {
+ // this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA;
+ // }
+ }
+
+ public markForRender (enable) {
+ // if (enable && this.enabledInHierarchy) {
+ // this.node._renderFlag |= (RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA |
+ // RenderFlow.FLAG_POST_RENDER);
+ // } else if (!enable) {
+ // this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_POST_RENDER);
+ // }
+ }
+
+ public disableRender () {
+ // this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA |
+ // RenderFlow.FLAG_POST_RENDER);
+ }
+}
+
+// tslint:disable-next-line
+cc['MaskComponent'] = MaskComponent;
diff --git a/cocos/2d/ui/CCProgressBar.js b/cocos/3d/ui/components/progress-bar-component.ts
similarity index 52%
rename from cocos/2d/ui/CCProgressBar.js
rename to cocos/3d/ui/components/progress-bar-component.ts
index a90d987d1a..d8a6bffb2d 100644
--- a/cocos/2d/ui/CCProgressBar.js
+++ b/cocos/3d/ui/components/progress-bar-component.ts
@@ -24,8 +24,11 @@
THE SOFTWARE.
****************************************************************************/
-const misc = require('../utils/misc');
-const Component = require('./CCComponent');
+import { Component} from '../../../components/component';
+import { clamp01 } from '../../../core/utils/misc';
+import { ccclass, menu, executionOrder, executeInEditMode, property } from '../../../core/data/class-decorator';
+import SpriteComponent from './sprite-component';
+
/**
* !#en Enum for ProgressBar mode
@@ -64,7 +67,7 @@ var Mode = cc.Enum({
* @extends Component
* @example
* // update progressBar
- * update: function (dt) {
+ * update(dt) {
* var progress = progressBar.progress;
* if (progress > 0) {
* progress += dt;
@@ -76,18 +79,139 @@ var Mode = cc.Enum({
* }
*
*/
-var ProgressBar = cc.Class({
- name: 'cc.ProgressBar',
- extends: Component,
+@ccclass('cc.ProgressBarComponent')
+@executionOrder(100)
+@menu('UI/ProgressBar')
+// @executeInEditMode
+export default class ProgressBarComponent extends Component {
+ @property
+ _barSprite: SpriteComponent | null = null;
+ @property
+ _mode: number = Mode.HORIZONTAL;
+ _N$totalLength: number = 1;
+ @property
+ _progress: number = 0.1;
+ @property
+ _reverse: boolean = false;
- editor: CC_EDITOR && {
- menu: 'i18n:MAIN_MENU.component.ui/ProgressBar',
- help: 'i18n:COMPONENT.help_url.progressbar',
- },
+ /**
+ * !#en The targeted Sprite which will be changed progressively.
+ * !#zh 用来显示进度条比例的 Sprite 对象。
+ * @property {Sprite} barSprite
+ */
+ @property({
+ type: SpriteComponent
+ })
+ get barSprite() {
+ return this._barSprite;
+ }
- _initBarSprite: function() {
- if (this.barSprite) {
- var entity = this.barSprite.node;
+ set barSprite(value: SpriteComponent) {
+ if (this._barSprite === value) {
+ return
+ }
+
+ this._barSprite = value;
+ this._initBarSprite();
+ }
+
+ /**
+ * !#en The progress mode, there are two modes supported now: horizontal and vertical.
+ * !#zh 进度条的模式
+ * @property {ProgressBar.Mode} mode
+ */
+ @property({
+ type: Mode
+ })
+ get mode() {
+ return this._mode;
+ }
+
+ set mode(value: number) {
+ if (this._mode === value) {
+ return;
+ }
+
+ this._mode = value;
+ 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;
+ }
+ }
+ }
+
+ /**
+ * !#en The total width or height of the bar sprite.
+ * !#zh 进度条实际的总长度
+ * @property {Number} totalLength - range[[0, Number.MAX_VALUE]]
+ */
+ @property
+ get totalLength() {
+ return this._N$totalLength;
+ }
+
+ set totalLength(value: number) {
+ if (this._mode === Mode.FILLED) {
+ value = clamp01(value);
+ }
+ this._N$totalLength = value;
+ this._updateBarStatus();
+ }
+
+ /**
+ * !#en The current progress of the bar sprite. The valid value is between 0-1.
+ * !#zh 当前进度值,该数值的区间是 0-1 之间。
+ * @property {Number} progress
+ */
+ @property
+ get progress() {
+ return this._progress;
+ }
+
+ set progress(value: number) {
+ if (this._progress === value) {
+ return
+ }
+
+ this._progress = value;
+ this._updateBarStatus();
+ }
+
+ /**
+ * !#en Whether reverse the progress direction of the bar sprite.
+ * !#zh 进度条是否进行反方向变化。
+ * @property {Boolean} reverse
+ */
+ @property
+ get reverse() {
+ return this._reverse;
+ }
+
+ set reverse(value: boolean) {
+ if (this._reverse === value) {
+ return;
+ }
+
+ this._reverse = value;
+ if (this._barSprite) {
+ this._barSprite.fillStart = 1 - this._barSprite.fillStart;
+ }
+ this._updateBarStatus();
+ }
+
+ static Mode = Mode;
+
+ _initBarSprite() {
+ if (this._barSprite) {
+ var entity = this._barSprite.node;
if (!entity) return;
var nodeSize = this.node.getContentSize();
@@ -95,36 +219,36 @@ var ProgressBar = cc.Class({
var entitySize = entity.getContentSize();
- if(entity.parent === this.node){
+ if (entity.parent === this.node) {
this.node.setContentSize(entitySize);
}
- if (this.barSprite.fillType === cc.Sprite.FillType.RADIAL) {
- this.mode = Mode.FILLED;
+ if (this._barSprite.fillType === cc.SpriteComponent.FillType.RADIAL) {
+ this._mode = Mode.FILLED;
}
var barSpriteSize = entity.getContentSize();
- if (this.mode === Mode.HORIZONTAL) {
+ if (this._mode === Mode.HORIZONTAL) {
this.totalLength = barSpriteSize.width;
}
- else if(this.mode === Mode.VERTICAL) {
+ else if (this._mode === Mode.VERTICAL) {
this.totalLength = barSpriteSize.height;
}
else {
- this.totalLength = this.barSprite.fillRange;
+ this.totalLength = this._barSprite.fillRange;
}
- if(entity.parent === this.node){
+ if (entity.parent === this.node) {
var x = - nodeSize.width * nodeAnchor.x;
var y = 0;
entity.setPosition(cc.v2(x, y));
}
}
- },
+ }
- _updateBarStatus: function() {
- if (this.barSprite) {
- var entity = this.barSprite.node;
+ _updateBarStatus() {
+ if (this._barSprite) {
+ var entity = this._barSprite.node;
if (!entity) return;
@@ -133,14 +257,14 @@ var ProgressBar = cc.Class({
var entityPosition = entity.getPosition();
var anchorPoint = cc.v2(0, 0.5);
- var progress = misc.clamp01(this.progress);
+ var progress = clamp01(this._progress);
var actualLenth = this.totalLength * progress;
var finalContentSize;
var totalWidth;
var totalHeight;
- switch (this.mode) {
+ switch (this._mode) {
case Mode.HORIZONTAL:
- if (this.reverse) {
+ if (this._reverse) {
anchorPoint = cc.v2(1, 0.5);
}
finalContentSize = cc.size(actualLenth, entitySize.height);
@@ -148,7 +272,7 @@ var ProgressBar = cc.Class({
totalHeight = entitySize.height;
break;
case Mode.VERTICAL:
- if (this.reverse) {
+ if (this._reverse) {
anchorPoint = cc.v2(0.5, 1);
} else {
anchorPoint = cc.v2(0.5, 0);
@@ -160,17 +284,17 @@ var ProgressBar = cc.Class({
}
//handling filled mode
- if (this.mode === Mode.FILLED) {
- if (this.barSprite.type !== cc.Sprite.Type.FILLED) {
+ if (this._mode === Mode.FILLED) {
+ if (this._barSprite.type !== cc.SpriteComponent.Type.FILLED) {
cc.warn('ProgressBar FILLED mode only works when barSprite\'s Type is FILLED!');
} else {
- if (this.reverse) {
+ if (this._reverse) {
actualLenth = actualLenth * -1;
}
- this.barSprite.fillRange = actualLenth;
+ this._barSprite.fillRange = actualLenth;
}
} else {
- if (this.barSprite.type !== cc.Sprite.Type.FILLED) {
+ if (this._barSprite.type !== cc.SpriteComponent.Type.FILLED) {
var anchorOffsetX = anchorPoint.x - entityAnchorPoint.x;
var anchorOffsetY = anchorPoint.y - entityAnchorPoint.y;
@@ -184,114 +308,7 @@ var ProgressBar = cc.Class({
cc.warn('ProgressBar non-FILLED mode only works when barSprite\'s Type is non-FILLED!');
}
}
-
-
-
}
- },
-
- properties: {
- /**
- * !#en The targeted Sprite which will be changed progressively.
- * !#zh 用来显示进度条比例的 Sprite 对象。
- * @property {Sprite} barSprite
- */
- barSprite: {
- default: null,
- type: cc.Sprite,
- tooltip: CC_DEV && 'i18n:COMPONENT.progress.bar_sprite',
- notify: function() {
- this._initBarSprite();
- },
- animatable: false
- },
-
- /**
- * !#en The progress mode, there are two modes supported now: horizontal and vertical.
- * !#zh 进度条的模式
- * @property {ProgressBar.Mode} mode
- */
- mode: {
- default: Mode.HORIZONTAL,
- type: Mode,
- tooltip: CC_DEV && 'i18n:COMPONENT.progress.mode',
- 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;
- }
- }
- },
- animatable: false
- },
-
- _N$totalLength: 1,
- /**
- * !#en The total width or height of the bar sprite.
- * !#zh 进度条实际的总长度
- * @property {Number} totalLength
- */
- totalLength: {
- range: [0, Number.MAX_VALUE],
- tooltip: CC_DEV && 'i18n:COMPONENT.progress.total_length',
- get: function () {
- return this._N$totalLength;
- },
- set: function(value) {
- if (this.mode === Mode.FILLED) {
- value = misc.clamp01(value);
- }
- this._N$totalLength = value;
- this._updateBarStatus();
- }
- },
-
- /**
- * !#en The current progress of the bar sprite. The valid value is between 0-1.
- * !#zh 当前进度值,该数值的区间是 0-1 之间。
- * @property {Number} progress
- */
- progress: {
- default: 1,
- type: 'Float',
- range: [0, 1, 0.1],
- slide: true,
- tooltip: CC_DEV && 'i18n:COMPONENT.progress.progress',
- notify: function() {
- this._updateBarStatus();
- }
- },
-
- /**
- * !#en Whether reverse the progress direction of the bar sprite.
- * !#zh 进度条是否进行反方向变化。
- * @property {Boolean} reverse
- */
- reverse: {
- default: false,
- tooltip: CC_DEV && 'i18n:COMPONENT.progress.reverse',
- notify: function() {
- if (this.barSprite) {
- this.barSprite.fillStart = 1 - this.barSprite.fillStart;
- }
- this._updateBarStatus();
- },
- animatable: false
- }
- },
-
- statics: {
- Mode: Mode
}
-});
+}
-
-cc.ProgressBar = module.exports = ProgressBar;
diff --git a/cocos/3d/ui/components/slider-component.ts b/cocos/3d/ui/components/slider-component.ts
new file mode 100644
index 0000000000..a981d1fb63
--- /dev/null
+++ b/cocos/3d/ui/components/slider-component.ts
@@ -0,0 +1,270 @@
+/****************************************************************************
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos.com
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated engine source code (the "Software"), a limited,
+ worldwide, royalty-free, non-assignable, revocable and non-exclusive license
+ to use Cocos Creator solely to develop games on your target platforms. You shall
+ not use Cocos Creator software for developing other software or tools that's
+ used for developing games. You are not granted to publish, distribute,
+ sublicense, and/or sell copies of Cocos Creator.
+
+ The software or tools in this License Agreement are licensed, not sold.
+ Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+import { Component} from '../../../components/component';
+import { clamp01 } from '../../../core/utils/misc';
+import { ccclass, menu, executionOrder, executeInEditMode, property } from '../../../core/data/class-decorator';
+import SpriteComponent from './sprite-component';
+import { Vec2 } from '../../../core/value-types/index';
+import ComponentEventHandler from '../../../components/CCComponentEventHandler';
+import Event from '../../../core/event/event';
+import { EventTouch } from '../../../core/platform/event-manager/CCEvent';
+/**
+ * !#en The Slider Direction
+ * !#zh 滑动器方向
+ * @enum Slider.Direction
+ */
+var Direction = cc.Enum({
+ /**
+ * !#en The horizontal direction.
+ * !#zh 水平方向
+ * @property {Number} Horizontal
+ */
+ Horizontal: 0,
+ /**
+ * !#en The vertical direction.
+ * !#zh 垂直方向
+ * @property {Number} Vertical
+ */
+ Vertical: 1
+});
+
+/**
+ * !#en The Slider Control
+ * !#zh 滑动器组件
+ * @class Slider
+ * @extends Component
+ */
+@ccclass('cc.SliderComponent')
+@executionOrder(100)
+@menu('UI/Slider')
+// @executeInEditMode
+export default class SliderComponent extends Component {
+ @property
+ _handle: SpriteComponent | null = null;
+ @property
+ _direction: number = Direction.Horizontal;
+ @property
+ _progress: number = 0.1;
+ @property
+ _slideEvents: ComponentEventHandler[] = [];
+
+ _offset: Vec2 = cc.v2();
+ _dragging = false;
+ _touchHandle = false;
+
+ /**
+ * !#en The "handle" part of the slider
+ * !#zh 滑动器滑块按钮部件
+ * @property {Button} handle
+ */
+ @property({
+ type: SpriteComponent
+ })
+ get handle() {
+ return this._handle;
+ }
+
+ set handle(value: SpriteComponent) {
+ if (this._handle === value) {
+ return;
+ }
+
+ this._handle = value;
+ if (CC_EDITOR && this._handle) {
+ this._updateHandlePosition();
+ }
+ }
+
+ /**
+ * !#en The slider direction
+ * !#zh 滑动器方向
+ * @property {Slider.Direction} direction
+ */
+ @property({
+ type: Direction
+ })
+ get direction() {
+ return this._direction;
+ }
+
+ set direction(value: number) {
+ if (this._direction === value) {
+ return;
+ }
+
+ this._direction = value;
+ }
+ /**
+ * !#en The current progress of the slider. The valid value is between 0-1
+ * !#zh 当前进度值,该数值的区间是 0-1 之间
+ * @property {Number} progress
+ */
+ @property
+ get progress() {
+ return this._progress;
+ }
+
+ set progress(value: number) {
+ if (this._progress === value) {
+ return;
+ }
+
+ this._progress = value;
+ this._updateHandlePosition();
+ }
+
+ /**
+ * !#en The slider events callback
+ * !#zh 滑动器组件事件回调函数
+ * @property {ComponentEventHandler[]} slideEvents
+ */
+ @property({
+ type: ComponentEventHandler
+ })
+ get slideEvents() {
+ return this._slideEvents;
+ }
+
+ set slideEvents(value: ComponentEventHandler[]) {
+ this._slideEvents = value;
+ }
+
+ static Direction = Direction;
+
+ __preload() {
+ this._updateHandlePosition();
+ }
+
+ // 注册事件
+ onEnable() {
+ this._updateHandlePosition();
+
+ this.node.on(cc.NodeUI.EventType.TOUCH_START, this._onTouchBegan, this);
+ this.node.on(cc.NodeUI.EventType.TOUCH_MOVE, this._onTouchMoved, this);
+ this.node.on(cc.NodeUI.EventType.TOUCH_END, this._onTouchEnded, this);
+ this.node.on(cc.NodeUI.EventType.TOUCH_CANCEL, this._onTouchCancelled, this);
+ if (this._handle && this._handle.isValid) {
+ this._handle.node.on(cc.NodeUI.EventType.TOUCH_START, this._onHandleDragStart, this);
+ this._handle.node.on(cc.NodeUI.EventType.TOUCH_MOVE, this._onTouchMoved, this);
+ this._handle.node.on(cc.NodeUI.EventType.TOUCH_END, this._onTouchEnded, this);
+ }
+ }
+
+ onDisable() {
+ this.node.off(cc.NodeUI.EventType.TOUCH_START, this._onTouchBegan, this);
+ this.node.off(cc.NodeUI.EventType.TOUCH_MOVE, this._onTouchMoved, this);
+ this.node.off(cc.NodeUI.EventType.TOUCH_END, this._onTouchEnded, this);
+ this.node.off(cc.NodeUI.EventType.TOUCH_CANCEL, this._onTouchCancelled, this);
+ if (this._handle && this._handle.isValid) {
+ this._handle.node.off(cc.NodeUI.EventType.TOUCH_START, this._onHandleDragStart, this);
+ this._handle.node.off(cc.NodeUI.EventType.TOUCH_MOVE, this._onTouchMoved, this);
+ this._handle.node.off(cc.NodeUI.EventType.TOUCH_END, this._onTouchEnded, this);
+ }
+ }
+
+ _onHandleDragStart(event: Event | null) {
+ this._dragging = true;
+ this._touchHandle = true;
+ this._offset = this._handle.node.convertToNodeSpaceAR(event.touch.getLocation());
+
+ event.stopPropagation();
+ }
+
+ _onTouchBegan(event: Event | null) {
+ if (!this._handle) { return; }
+ this._dragging = true;
+ if (!this._touchHandle) {
+ this._handleSliderLogic(event.touch);
+ }
+
+ event.stopPropagation();
+ }
+
+ _onTouchMoved(event: Event | null) {
+ if (!this._dragging) { return; }
+ this._handleSliderLogic(event.touch);
+ event.stopPropagation();
+ }
+
+ _onTouchEnded(event: Event | null) {
+ this._dragging = false;
+ this._touchHandle = false;
+ this._offset = cc.v2();
+ event.stopPropagation();
+ }
+
+ _onTouchCancelled(event: Event | null) {
+ this._dragging = false;
+ event.stopPropagation();
+ }
+
+ _handleSliderLogic(touch) {
+ this._updateProgress(touch);
+ this._emitSlideEvent();
+ }
+
+ _emitSlideEvent() {
+ cc.Component.EventHandler.emitEvents(this.slideEvents, this);
+ this.node.emit('slide', this);
+ }
+
+ _updateProgress(touch: EventTouch | null) {
+ if (!this._handle) { return; }
+ var localTouchPos = this.node.convertToNodeSpaceAR(touch.getLocation());
+ if (this.direction === Direction.Horizontal) {
+ this.progress = clamp01(0.5 + (localTouchPos.x - this._offset.x) / this.node.width);
+ }
+ else {
+ this.progress = clamp01(0.5 + (localTouchPos.y - this._offset.y) / this.node.height);
+ }
+ }
+
+ _updateHandlePosition() {
+ if (!this._handle) { return; }
+ var handlelocalPos;
+ if (this._direction === Direction.Horizontal) {
+ handlelocalPos = cc.v2(-this.node.width * this.node.anchorX + this.progress * this.node.width, 0);
+ }
+ else {
+ handlelocalPos = cc.v2(0, -this.node.height * this.node.anchorY + this.progress * this.node.height);
+ }
+ var worldSpacePos = this.node.convertToWorldSpaceAR(handlelocalPos);
+ this._handle.node.setPosition(this._handle.node.parent.convertToNodeSpaceAR(worldSpacePos));
+ }
+}
+
+// cc.Slider = module.exports = Slider;
+
+/**
+ * !#en
+ * Note: This event is emitted from the node to which the component belongs.
+ * !#zh
+ * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
+ * @event slide
+ * @param {Event.EventCustom} event
+ * @param {Slider} slider - The slider component.
+ */
diff --git a/cocos/3d/ui/components/sprite-component.ts b/cocos/3d/ui/components/sprite-component.ts
new file mode 100644
index 0000000000..b7c9975a7b
--- /dev/null
+++ b/cocos/3d/ui/components/sprite-component.ts
@@ -0,0 +1,617 @@
+/****************************************************************************
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos.com
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated engine source code (the "Software"), a limited,
+ worldwide, royalty-free, non-assignable, revocable and non-exclusive license
+ to use Cocos Creator solely to develop games on your target platforms. You shall
+ not use Cocos Creator software for developing other software or tools that's
+ used for developing games. You are not granted to publish, distribute,
+ sublicense, and/or sell copies of Cocos Creator.
+
+ The software or tools in this License Agreement are licensed, not sold.
+ Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+// @ts-check
+import atlas from '../../../assets/CCSpriteAtlas';
+import { SpriteFrame } from '../../../assets/CCSpriteFrame';
+import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator';
+import { clampf } from '../../../core/utils/misc';
+import { Vec2, Enum } from '../../../core/value-types';
+import { MeshBuffer } from '../mesh-buffer';
+import { RenderComponent } from './ui-render-component';
+import { Node } from '../../../scene-graph/node';
+const EventType = Node.EventType;
+
+/**
+ * !#en Enum for sprite type.
+ * !#zh Sprite 类型
+ * @enum Sprite.Type
+ */
+const SpriteType = Enum({
+ /**
+ * !#en The simple type.
+ * !#zh 普通类型
+ * @property {Number} SIMPLE
+ */
+ SIMPLE: 0,
+ /**
+ * !#en The sliced type.
+ * !#zh 切片(九宫格)类型
+ * @property {Number} SLICED
+ */
+ SLICED: 1,
+ // /**
+ // * !#en The tiled type.
+ // * !#zh 平铺类型
+ // * @property {Number} TILED
+ // */
+ // TILED: 2,
+ /**
+ * !#en The filled type.
+ * !#zh 填充类型
+ * @property {Number} FILLED
+ */
+ FILLED: 3,
+ // /**
+ // * !#en The mesh type.
+ // * !#zh 以 Mesh 三角形组成的类型
+ // * @property {Number} MESH
+ // */
+ // MESH: 4
+});
+
+/**
+ * !#en Enum for fill type.
+ * !#zh 填充类型
+ * @enum Sprite.FillType
+ */
+const FillType = cc.Enum({
+ /**
+ * !#en The horizontal fill.
+ * !#zh 水平方向填充
+ * @property {Number} HORIZONTAL
+ */
+ HORIZONTAL: 0,
+ /**
+ * !#en The vertical fill.
+ * !#zh 垂直方向填充
+ * @property {Number} VERTICAL
+ */
+ VERTICAL: 1,
+ // /**
+ // * !#en The radial fill.
+ // * !#zh 径向填充
+ // * @property {Number} RADIAL
+ // */
+ // RADIAL: 2,
+});
+
+/**
+ * !#en Sprite Size can track trimmed size, raw size or none.
+ * !#zh 精灵尺寸调整模式
+ * @enum Sprite.SizeMode
+ */
+// var SizeMode = cc.Enum({
+// /**
+// * !#en Use the customized node size.
+// * !#zh 使用节点预设的尺寸
+// * @property {Number} CUSTOM
+// */
+// CUSTOM: 0,
+// /**
+// * !#en Match the trimmed size of the sprite frame automatically.
+// * !#zh 自动适配为精灵裁剪后的尺寸
+// * @property {Number} TRIMMED
+// */
+// TRIMMED: 1,
+// /**
+// * !#en Match the raw size of the sprite frame automatically.
+// * !#zh 自动适配为精灵原图尺寸
+// * @property {Number} RAW
+// */
+// RAW: 2
+// });
+
+// var State = cc.Enum({
+// /**
+// * !#en The normal state
+// * !#zh 正常状态
+// * @property {Number} NORMAL
+// */
+// NORMAL: 0,
+// /**
+// * !#en The gray state, all color will be modified to grayscale value.
+// * !#zh 灰色状态,所有颜色会被转换成灰度值
+// * @property {Number} GRAY
+// */
+// GRAY: 1
+// });
+
+@ccclass('cc.SpriteComponent')
+@executionOrder(100)
+@menu('UI/Sprite')
+@executeInEditMode
+export class SpriteComponent extends RenderComponent {
+
+ /**
+ * !#en The sprite frame of the sprite.
+ * !#zh 精灵的精灵帧
+ * @return {SpriteFrame}
+ */
+ @property({
+ type: SpriteFrame,
+ })
+ get spriteFrame () {
+ return this._spriteFrame;
+ }
+
+ set spriteFrame (value: SpriteFrame | null) {
+ if (this._spriteFrame === value) {
+ return;
+ }
+
+ const lastSprite = this._spriteFrame;
+ this._spriteFrame = value;
+ // render & update render data flag will be triggered while applying new sprite frame
+ this.markForUpdateRenderData(false);
+ this._applySpriteFrame(lastSprite);
+ if (CC_EDITOR) {
+ // @ts-ignore
+ this.node.emit('spriteframe-changed', this);
+ }
+ }
+
+ /**
+ * !#en The sprite render type.
+ * !#zh 精灵渲染类型
+ * @property type
+ * @type {Sprite.Type}
+ * @example
+ * sprite.type = cc.Sprite.Type.SIMPLE;
+ */
+ @property({
+ type: SpriteType,
+ })
+ get type () {
+ return this._type;
+ }
+ set type (value: number) {
+ if (this._type !== value) {
+ this._type = value;
+ this._updateAssembler();
+ }
+ }
+
+ /**
+ * !#en
+ * The fill type, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”.
+ * !#zh
+ * 精灵填充类型,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。
+ * @property fillType
+ * @type {Sprite.FillType}
+ * @example
+ * sprite.fillType = SpriteComponent.FillType.HORIZONTAL;
+ */
+ @property({
+ type: FillType,
+ })
+ get fillType () {
+ return this._fillType;
+ }
+ set fillType (value: number) {
+ if (value !== this._fillType) {
+ if (value === FillType.RADIAL || this._fillType === FillType.RADIAL) {
+ // this.destroyRenderData(/*this._renderData*/);
+ this._renderData = null;
+ } else if (this._renderData) {
+ this.markForUpdateRenderData(true);
+ }
+ this._fillType = value;
+ this._updateAssembler();
+ }
+ }
+
+ /**
+ * !#en
+ * The fill Center, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”.
+ * !#zh
+ * 填充中心点,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。
+ * @property fillCenter
+ * @type {Vec2}
+ * @example
+ * sprite.fillCenter = new cc.v2(0, 0);
+ */
+ @property
+ get fillCenter () {
+ return this._fillCenter;
+ }
+ set fillCenter (value: Vec2) {
+ this._fillCenter.x = value.x;
+ this._fillCenter.y = value.y;
+ if (this._type === SpriteType.FILLED && this._renderData) {
+ this.markForUpdateRenderData(true);
+ }
+ }
+
+ /**
+ * !#en
+ * The fill Start, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”.
+ * !#zh
+ * 填充起始点,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。
+ * @property fillStart
+ * @type {Number}
+ * @example
+ * // -1 To 1 between the numbers
+ * sprite.fillStart = 0.5;
+ */
+ @property
+ get fillStart () {
+ return this._fillStart;
+ }
+
+ set fillStart (value: number) {
+ this._fillStart = clampf(value, -1, 1);
+ if (this._type === SpriteType.FILLED && this._renderData) {
+ this.markForUpdateRenderData(true);
+ }
+ }
+
+ /**
+ * !#en
+ * The fill Range, This will only have any effect if the "type" is set to “cc.Sprite.Type.FILLED”.
+ * !#zh
+ * 填充范围,仅渲染类型设置为 cc.Sprite.Type.FILLED 时有效。
+ * @property fillRange
+ * @type {Number}
+ * @example
+ * // -1 To 1 between the numbers
+ * sprite.fillRange = 1;
+ */
+ @property
+ get fillRange () {
+ return this._fillRange;
+ }
+ set fillRange (value: number) {
+ // ??? -1 ~ 1
+ // this._fillRange = cc.misc.clampf(value, -1, 1);
+ this._fillRange = clampf(value, 0, 1);
+ if (this._type === SpriteType.FILLED && this._renderData) {
+ this.markForUpdateRenderData(true);
+ }
+ }
+ /**
+ * !#en specify the frame is trimmed or not.
+ * !#zh 是否使用裁剪模式
+ * @property trim
+ * @type {Boolean}
+ * @example
+ * sprite.trim = true;
+ */
+ get trim () {
+ // return this._isTrimmedMode;
+ return false;
+ }
+
+ set trim (value: boolean) {
+ // if (this._isTrimmedMode !== value) {
+ // this._isTrimmedMode = value;
+ // if ((this._type === SpriteType.SIMPLE || this._type === SpriteType.MESH) &&
+ // this._renderData) {
+ // this.markForUpdateRenderData(true);
+ // }
+ // }
+ if (this._spriteFrame) {
+ this.node.setContentSize(this._spriteFrame.getOriginalSize());
+ }
+ }
+
+ // /**
+ // * !#en specify the size tracing mode.
+ // * !#zh 精灵尺寸调整模式
+ // * @property sizeMode
+ // * @type {Sprite.SizeMode}
+ // * @example
+ // * sprite.sizeMode = cc.Sprite.SizeMode.CUSTOM;
+ // */
+ // get sizeMode() {
+ // return this._sizeMode;
+ // }
+ // set sizeMode(value) {
+ // // this._sizeMode = value;
+ // // if (value !== SizeMode.CUSTOM) {
+ // // this._applySpriteSize();
+ // // }
+ // }
+
+ public static FillType = FillType;
+ public static Type = SpriteType;
+ @property
+ public _spriteFrame: SpriteFrame | null = null;
+ @property
+ public _type: number = SpriteType.SIMPLE;
+ @property
+ public _fillType: number = FillType.HORIZONTAL;
+ // @property
+ // _sizeMode = SizeMode.TRIMMED;
+ @property
+ public _fillCenter: Vec2 = cc.v2(0, 0);
+ @property
+ public _fillStart: number = 0;
+ @property
+ public _fillRange: number = 0;
+ // @property
+ // _isTrimmedMode = true;
+ // _state = 0;
+ // TODO:
+ @property
+ public _atlas: atlas | null = null;
+ public _assembler = null;
+ public _spriteWidget = null;
+ // static SizeMode = SizeMode;
+ // static State = State;
+
+ // /**
+ // * Change the state of sprite.
+ // * @method setState
+ // * @see `SpriteComponent.State`
+ // * @param state {SpriteComponent.State} NORMAL or GRAY State.
+ // */
+ // getState() {
+ // return this._state;
+ // }
+
+ // setState(state) {
+ // if (this._state === state) return;
+ // this._state = state;
+ // this._activateMaterial();
+ // }
+
+ // onLoad() {}
+
+ public onEnable () {
+ super.onEnable();
+ if (this._spriteFrame) {
+ if (!this._spriteFrame.textureLoaded()) {
+ // this._spriteFrame.once('load', this._onTextureLoaded, this);
+ this._spriteFrame.ensureLoadTexture();
+ }
+ }
+
+ this._updateAssembler();
+ this._activateMaterial();
+
+ if (!this._spriteFrame) {
+ this.spriteFrame = cc.BuiltinResMgr['default-spriteframe'];
+ }
+
+ // this.node.on(EventType.SIZE_CHANGED, this._onNodeSizeDirty, this);
+ // this.node.on(EventType.ANCHOR_CHANGED, this._onNodeSizeDirty, this);
+ }
+
+ public updateRenderData (buffer: MeshBuffer) {
+ if (!this._spriteFrame || !this.material) {
+ return;
+ }
+
+ this._assembler.updateRenderData(this);
+ this._assembler.fillBuffers(this, buffer);
+ }
+
+ public onDestroy () {
+ super.onDestroy();
+ this.destroyRenderData();
+ }
+
+ public onDisable () {
+ // this._super();
+ super.onDisable();
+
+ this.node.off(EventType.SIZE_CHANGED, this._onNodeSizeDirty, this);
+ this.node.off(EventType.ANCHOR_CHANGED, this._onNodeSizeDirty, this);
+ }
+
+ public _onNodeSizeDirty () {
+ if (!this._renderData) { return; }
+ this.markForUpdateRenderData(true);
+ }
+
+ public _updateAssembler () {
+ const assembler = SpriteComponent._assembler.getAssembler(this);
+
+ if (this._assembler !== assembler) {
+ this.destroyRenderData();
+ this._assembler = assembler;
+ }
+
+ if (!this._renderData) {
+ this._renderData = this._assembler.createData(this);
+ this._renderData.material = this.material;
+ this.markForUpdateRenderData(true);
+ }
+ }
+
+ public _activateMaterial () {
+ const spriteFrame = this._spriteFrame;
+ let material = this.material;
+ // WebGL
+ if (cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) {
+ if (!material) {
+ this.material = cc.BuiltinResMgr['sprite-material'];
+ material = this.material;
+ if (spriteFrame && spriteFrame.textureLoaded()) {
+ material.setProperty('mainTexture', spriteFrame);
+ this.markForUpdateRenderData(true);
+ }
+ } else {
+ if (spriteFrame && spriteFrame.textureLoaded()) {
+ const matTexture = material.effect && material.effect.getProperty('mainTexture');
+ if (matTexture !== spriteFrame) {
+ material.setProperty('mainTexture', spriteFrame);
+ this.markForUpdateRenderData(true);
+ }
+ }
+ }
+
+ if (this._renderData) {
+ this._renderData.material = material;
+ }
+ } else {
+ this.markForUpdateRenderData(true);
+ // this.markForRender(true);
+ }
+ }
+
+ public _applyAtlas (spriteFrame: SpriteFrame | null) {
+ if (!CC_EDITOR) {
+ return;
+ }
+ // Set atlas
+ if (spriteFrame && spriteFrame._atlasUuid) {
+ const self = this;
+ cc.AssetLibrary.loadAsset(spriteFrame._atlasUuid, function (err, asset) {
+ self._atlas = asset;
+ });
+ } else {
+ this._atlas = null;
+ }
+ }
+
+ public _canRender () {
+ if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) {
+ if (!this._enabled) { return false; }
+ } else {
+ if (!this._enabled || !this.material) { return false; }
+ }
+
+ const spriteFrame = this._spriteFrame;
+ if (!spriteFrame || !spriteFrame.textureLoaded()) {
+ return false;
+ }
+ return true;
+ }
+
+ public markForUpdateRenderData (enable: boolean) {
+ if (enable /*&& this._canRender()*/) {
+ // this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA;
+
+ const renderData = this._renderData;
+ if (renderData) {
+ renderData.uvDirty = true;
+ renderData.vertDirty = true;
+ }
+ }
+ // else if (!enable) {
+ // this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA;
+ // }
+ }
+
+ // _applySpriteSize() {
+ // if (this._spriteFrame) {
+ // if (SizeMode.RAW === this._sizeMode) {
+ // var size = this._spriteFrame.getOriginalSize();
+ // this.node.setContentSize(size);
+ // } else if (SizeMode.TRIMMED === this._sizeMode) {
+ // var rect = this._spriteFrame.getRect();
+ // this.node.setContentSize(rect.width, rect.height);
+ // }
+
+ // this._activateMaterial();
+ // }
+ // }
+
+ // _onTextureLoaded() {
+ // if (!this.isValid) {
+ // return;
+ // }
+
+ // this._applySpriteSize();
+ // }
+
+ public _applySpriteFrame (oldFrame: SpriteFrame | null) {
+ // if (oldFrame && oldFrame.off) {
+ // oldFrame.off('load', this._onTextureLoaded, this);
+ // }
+
+ const spriteFrame = this._spriteFrame;
+ // if (!spriteFrame || (this._material && this._material._texture) !== (spriteFrame && spriteFrame._texture)) {
+ // // disable render flow until texture is loaded
+ // this.markForRender(false);
+ // }
+
+ if (spriteFrame) {
+ if (!oldFrame || spriteFrame !== oldFrame) {
+ // this.material.setProperty('mainTexture', spriteFrame);
+ if (spriteFrame.textureLoaded()) {
+ // this._onTextureLoaded();
+ this._activateMaterial();
+ } else {
+ // spriteFrame.once('load', this._onTextureLoaded, this);
+ spriteFrame.ensureLoadTexture();
+ }
+ }
+ // else {
+ // this._applySpriteSize();
+ // }
+ }
+
+ if (CC_EDITOR) {
+ // Set atlas
+ this._applyAtlas(spriteFrame);
+ }
+ }
+
+ // _resized() {
+ // if (!CC_EDITOR) {
+ // return;
+ // }
+
+ // if (this._spriteFrame) {
+ // var actualSize = this.node.getContentSize();
+ // var expectedW = actualSize.width;
+ // var expectedH = actualSize.height;
+ // if (this._sizeMode === SizeMode.RAW) {
+ // var size = this._spriteFrame.getOriginalSize();
+ // expectedW = size.width;
+ // expectedH = size.height;
+ // } else if (this._sizeMode === SizeMode.TRIMMED) {
+ // var rect = this._spriteFrame.getRect();
+ // expectedW = rect.width;
+ // expectedH = rect.height;
+
+ // }
+
+ // if (expectedW !== actualSize.width || expectedH !== actualSize.height) {
+ // this._sizeMode = SizeMode.CUSTOM;
+ // }
+ // }
+ // }
+}
+
+// if (CC_EDITOR) {
+// // override __preload
+// Sprite.prototype.__superPreload = cc.Component.prototype.__preload;
+// Sprite.prototype.__preload = function () {
+// if (this.__superPreload) this.__superPreload();
+// this.node.on(NodeEvent.SIZE_CHANGED, this._resized, this);
+// };
+// // override onDestroy
+// Sprite.prototype.__superOnDestroy = cc.Component.prototype.onDestroy;
+// Sprite.prototype.onDestroy = function () {
+// if (this.__superOnDestroy) this.__superOnDestroy();
+// this.node.off(NodeEvent.SIZE_CHANGED, this._resized, this);
+// };
+// }
+
+// cc.Sprite = module.exports = Sprite;
diff --git a/cocos/3d/ui/components/toggle-component.ts b/cocos/3d/ui/components/toggle-component.ts
new file mode 100644
index 0000000000..464d4a2c97
--- /dev/null
+++ b/cocos/3d/ui/components/toggle-component.ts
@@ -0,0 +1,294 @@
+/****************************************************************************
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos.com
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated engine source code (the "Software"), a limited,
+ worldwide, royalty-free, non-assignable, revocable and non-exclusive license
+ to use Cocos Creator solely to develop games on your target platforms. You shall
+ not use Cocos Creator software for developing other software or tools that's
+ used for developing games. You are not granted to publish, distribute,
+ sublicense, and/or sell copies of Cocos Creator.
+
+ The software or tools in this License Agreement are licensed, not sold.
+ Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+import ComponentEventHandler from '../../../components/CCComponentEventHandler';
+import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator';
+import ButtonComponent from './button-component';
+// import * as js from '../../core/utils/js';
+import RenderComponent from './render-component';
+import SpriteComponent from './sprite-component';
+import ToggleGroupComponent from './toggle-group-component';
+
+/**
+ * !#en The toggle component is a CheckBox, when it used together with a ToggleGroup, it
+ * could be treated as a RadioButton.
+ * !#zh Toggle 是一个 CheckBox,当它和 ToggleGroup 一起使用的时候,可以变成 RadioButton。
+ * @class Toggle
+ * @extends Button
+ */
+@ccclass('cc.ToggleComponent')
+@executionOrder(100)
+@menu('UI/Toggle')
+@executeInEditMode
+export default class ToggleComponent extends ButtonComponent {
+ @property
+ public _isChecked: boolean = true;
+ @property
+ public _toggleGroup: ToggleGroupComponent | null = null;
+ @property
+ public _checkMark: SpriteComponent | null = null;
+ @property
+ public _checkEvents: ComponentEventHandler[] = [];
+
+ /**
+ * !#en When this value is true, the check mark component will be enabled, otherwise
+ * the check mark component will be disabled.
+ * !#zh 如果这个设置为 true,则 check mark 组件会处于 enabled 状态,否则处于 disabled 状态。
+ * @property {Boolean} isChecked
+ */
+ @property
+ get isChecked () {
+ return this._isChecked;
+ }
+
+ set isChecked (value) {
+ if (this._isChecked === value) {
+ return;
+ }
+
+ this._isChecked = value;
+ this._updateCheckMark();
+ }
+
+ /**
+ * !#en The toggle group which the toggle belongs to, when it is null, the toggle is a CheckBox.
+ * Otherwise, the toggle is a RadioButton.
+ * !#zh Toggle 所属的 ToggleGroup,这个属性是可选的。如果这个属性为 null,则 Toggle 是一个 CheckBox,
+ * 否则,Toggle 是一个 RadioButton。
+ * @property {ToggleGroup} toggleGroup
+ */
+ @property({
+ type: ToggleGroupComponent,
+ })
+ get toggleGroup () {
+ return this._toggleGroup;
+ }
+
+ set toggleGroup (value) {
+ if (this._toggleGroup === value) {
+ return;
+ }
+
+ if (this._toggleGroup) {
+ this._toggleGroup.removeToggle(this);
+ }
+ this._toggleGroup = value;
+ if (this._toggleGroup && this._toggleGroup.enabled) {
+ this._toggleGroup.addToggle(this);
+ }
+ }
+
+ /**
+ * !#en The image used for the checkmark.
+ * !#zh Toggle 处于选中状态时显示的图片
+ * @property {Sprite} checkMark
+ */
+ @property({
+ type: SpriteComponent,
+ })
+ get checkMark () {
+ return this._checkMark;
+ }
+
+ set checkMark (value: SpriteComponent) {
+ if (this._checkMark === value) {
+ return;
+ }
+
+ this._checkMark = value;
+ }
+
+ /**
+ * !#en If Toggle is clicked, it will trigger event's handler
+ * !#zh Toggle 按钮的点击事件列表。
+ * @property {ComponentEventHandler[]} checkEvents
+ */
+ @property({
+ type: ComponentEventHandler,
+ })
+ get checkEvents () {
+ return this._checkEvents;
+ }
+
+ set checkEvents (value: ComponentEventHandler[]) {
+ this._checkEvents = value;
+ }
+
+ set _resizeToTarget (value: boolean) {
+ if (value) {
+ this._resizeNodeToTargetNode();
+ }
+ }
+
+ get _toggleContainer () {
+ const parent = this.node.parent;
+ // TODO:
+ // if (cc.Node.isNode(parent)) {
+ // return parent.getComponent(cc.ToggleContainer);
+ // }
+ return null;
+ }
+
+ public onEnable () {
+ super.onEnable();
+ if (!CC_EDITOR) {
+ this._registerToggleEvent();
+ }
+
+ if (this._toggleGroup && this._toggleGroup.enabled) {
+ this._toggleGroup.addToggle(this);
+ }
+ }
+
+ public onDisable () {
+ super.onEnable();
+ if (!CC_EDITOR) {
+ this._unregisterToggleEvent();
+ }
+ if (this._toggleGroup && this._toggleGroup.enabled) {
+ this._toggleGroup.removeToggle(this);
+ }
+ }
+
+ public _updateCheckMark () {
+ if (this._checkMark) {
+ this._checkMark.node.active = !!this.isChecked;
+ }
+ }
+
+ // _updateDisabledState() {
+ // this._super();
+
+ // if (this._checkMark) {
+ // this._checkMark.setState(0);
+ // }
+ // if (this.enableAutoGrayEffect) {
+ // if (this._checkMark && !this.interactable) {
+ // this._checkMark.setState(1);
+ // }
+ // }
+ // }
+
+ public _registerToggleEvent () {
+ this.node.on('click', this.toggle, this);
+ }
+
+ public _unregisterToggleEvent () {
+ this.node.off('click', this.toggle, this);
+ }
+
+ public toggle (event) {
+ const group = this.toggleGroup || this._toggleContainer;
+
+ if (group && group.enabled && this.isChecked) {
+ if (!group.allowSwitchOff) {
+ return;
+ }
+ }
+
+ this.isChecked = !this.isChecked;
+
+ this._updateCheckMark();
+
+ if (group && group.enabled) {
+ group.updateToggles(this);
+ }
+
+ this._emitToggleEvents();
+ }
+
+ public _emitToggleEvents () {
+ this.node.emit('toggle', this);
+ if (this._checkEvents) {
+ ComponentEventHandler.emitEvents(this._checkEvents, this);
+ }
+ }
+
+ /**
+ * !#en Make the toggle button checked.
+ * !#zh 使 toggle 按钮处于选中状态
+ * @method check
+ */
+ public check () {
+ const group = this.toggleGroup || this._toggleContainer;
+
+ if (group && group.enabled && this.isChecked) {
+ if (!group.allowSwitchOff) {
+ return;
+ }
+ }
+
+ this.isChecked = true;
+
+ if (group && group.enabled) {
+ group.updateToggles(this);
+ }
+
+ this._emitToggleEvents();
+ }
+
+ /**
+ * !#en Make the toggle button unchecked.
+ * !#zh 使 toggle 按钮处于未选中状态
+ * @method uncheck
+ */
+ public uncheck () {
+ const group = this.toggleGroup || this._toggleContainer;
+
+ if (group && group.enabled && this.isChecked) {
+ if (!group.allowSwitchOff) {
+ return;
+ }
+ }
+
+ this.isChecked = false;
+
+ this._emitToggleEvents();
+ }
+}
+
+// cc.Toggle = module.exports = Toggle;
+
+// var js = require('../platform/js');
+
+// js.get(Toggle.prototype, '_toggleContainer',
+// function () {
+// var parent = this.node.parent;
+// if (cc.Node.isNode(parent)) {
+// return parent.getComponent(cc.ToggleContainer);
+// }
+// return null;
+// }
+// );
+
+/**
+ * !#en
+ * Note: This event is emitted from the node to which the component belongs.
+ * !#zh
+ * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
+ * @event toggle
+ * @param {Event.EventCustom} event
+ * @param {Toggle} toggle - The Toggle component.
+ */
diff --git a/cocos/2d/ui/CCToggleContainer.js b/cocos/3d/ui/components/toggle-container-component.ts
similarity index 67%
rename from cocos/2d/ui/CCToggleContainer.js
rename to cocos/3d/ui/components/toggle-container-component.ts
index 3d5801ba21..2a0f400d8e 100644
--- a/cocos/2d/ui/CCToggleContainer.js
+++ b/cocos/3d/ui/components/toggle-container-component.ts
@@ -34,38 +34,41 @@
* @class ToggleContainer
* @extends Component
*/
-var ToggleContainer = cc.Class({
- name: 'cc.ToggleContainer',
- extends: cc.Component,
- editor: CC_EDITOR && {
- menu: 'i18n:MAIN_MENU.component.ui/ToggleContainer',
- help: 'i18n:COMPONENT.help_url.toggleContainer',
- executeInEditMode: true
- },
- properties: {
- /**
- * !#en If this setting is true, a toggle could be switched off and on when pressed.
- * If it is false, it will make sure there is always only one toggle could be switched on
- * and the already switched on toggle can't be switched off.
- * !#zh 如果这个设置为 true, 那么 toggle 按钮在被点击的时候可以反复地被选中和未选中。
- * @property {Boolean} allowSwitchOff
- */
- allowSwitchOff: {
- tooltip: CC_DEV && 'i18n:COMPONENT.toggle_group.allowSwitchOff',
- default: false
- },
- },
+import { Component } from '../../../components/component';
+import { ccclass, executeInEditMode, menu, property } from '../../../core/data/class-decorator';
- updateToggles: function (toggle) {
+@ccclass('cc.ToggleContainerComponent')
+export default class ToggleContainerComponent extends Component {
+ @property
+ protected _allowSwitchOff = false;
+ @property
+ public toggleItems: Component[] = [];
+ /**
+ * !#en If this setting is true, a toggle could be switched off and on when pressed.
+ * If it is false, it will make sure there is always only one toggle could be switched on
+ * and the already switched on toggle can't be switched off.
+ * !#zh 如果这个设置为 true, 那么 toggle 按钮在被点击的时候可以反复地被选中和未选中。
+ * @property {Boolean} allowSwitchOff
+ */
+ @property
+ get allowSwitchOff() {
+ return this._allowSwitchOff;
+ }
+
+ set allowSwitchOff(value) {
+ this._allowSwitchOff = value;
+ }
+
+ updateToggles(toggle) {
this.toggleItems.forEach(function (item) {
if (toggle.isChecked && item !== toggle) {
item.isChecked = false;
}
});
- },
+ }
- _allowOnlyOneToggleChecked: function () {
+ _allowOnlyOneToggleChecked() {
var isChecked = false;
this.toggleItems.forEach(function (item) {
if (isChecked) {
@@ -77,9 +80,9 @@ var ToggleContainer = cc.Class({
});
return isChecked;
- },
+ }
- _makeAtLeastOneToggleChecked: function () {
+ _makeAtLeastOneToggleChecked() {
var isChecked = this._allowOnlyOneToggleChecked();
if (!isChecked && !this.allowSwitchOff) {
@@ -88,33 +91,20 @@ var ToggleContainer = cc.Class({
toggleItems[0].check();
}
}
- },
+ }
- onEnable: function () {
+ onEnable() {
+ this.toggleItems = this.node.getComponentsInChildren(cc.ToggleComponent);
this.node.on('child-added', this._allowOnlyOneToggleChecked, this);
this.node.on('child-removed', this._makeAtLeastOneToggleChecked, this);
- },
+ }
- onDisable: function () {
+ onDisable() {
this.node.off('child-added', this._allowOnlyOneToggleChecked, this);
this.node.off('child-removed', this._makeAtLeastOneToggleChecked, this);
- },
+ }
- start: function () {
+ start() {
this._makeAtLeastOneToggleChecked();
}
-});
-
-/**
- * !#en Read only property, return the toggle items array reference managed by ToggleContainer.
- * !#zh 只读属性,返回 ToggleContainer 管理的 toggle 数组引用
- * @property {Toggle[]} toggleItems
- */
-var js = require('../platform/js');
-js.get(ToggleContainer.prototype, 'toggleItems',
- function () {
- return this.node.getComponentsInChildren(cc.Toggle);
- }
-);
-
-cc.ToggleContainer = module.exports = ToggleContainer;
+}
diff --git a/cocos/2d/ui/CCToggleGroup.js b/cocos/3d/ui/components/toggle-group-component.ts
similarity index 57%
rename from cocos/2d/ui/CCToggleGroup.js
rename to cocos/3d/ui/components/toggle-group-component.ts
index 035598aa62..abea49b12c 100644
--- a/cocos/2d/ui/CCToggleGroup.js
+++ b/cocos/3d/ui/components/toggle-group-component.ts
@@ -23,6 +23,9 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
+import { Component} from '../../../components/component';
+import { ccclass, menu, executionOrder, executeInEditMode, property } from '../../../core/data/class-decorator';
+import ToggleComponent from './toggle-component';
/**
* !#en ToggleGroup is not a visiable UI component but a way to modify the behavior of a set of Toggles.
@@ -32,74 +35,77 @@
* @class ToggleGroup
* @extends Component
*/
-var ToggleGroup = cc.Class({
- name: 'cc.ToggleGroup',
- extends: cc.Component,
- ctor: function () {
- this._toggleItems = [];
- },
- editor: CC_EDITOR && {
- menu: 'i18n:MAIN_MENU.component.ui/ToggleGroup (Legacy)',
- help: 'i18n:COMPONENT.help_url.toggleGroup'
- },
- properties: {
- /**
- * !#en If this setting is true, a toggle could be switched off and on when pressed.
- * If it is false, it will make sure there is always only one toggle could be switched on
- * and the already switched on toggle can't be switched off.
- * !#zh 如果这个设置为 true, 那么 toggle 按钮在被点击的时候可以反复地被选中和未选中。
- * @property {Boolean} allowSwitchOff
- */
- allowSwitchOff: {
- tooltip: CC_DEV && 'i18n:COMPONENT.toggle_group.allowSwitchOff',
- default: false
- },
+@ccclass('cc.ToggleGroupComponent')
+@executionOrder(100)
+@menu('UI/ToggleGroup')
+@executeInEditMode
+export default class ToggleGroupComponent extends Component {
+ @property
+ _allowSwitchOff: boolean = false;
+ _toggleItems: ToggleComponent[] = [];
- /**
- * !#en Read only property, return the toggle items array reference managed by toggleGroup.
- * !#zh 只读属性,返回 toggleGroup 管理的 toggle 数组引用
- * @property {Array} toggleItems
- */
- toggleItems: {
- get: function () {
- return this._toggleItems;
- }
- }
- },
+ /**
+ * !#en If this setting is true, a toggle could be switched off and on when pressed.
+ * If it is false, it will make sure there is always only one toggle could be switched on
+ * and the already switched on toggle can't be switched off.
+ * !#zh 如果这个设置为 true, 那么 toggle 按钮在被点击的时候可以反复地被选中和未选中。
+ * @property {Boolean} allowSwitchOff
+ */
+ @property
+ get allowSwitchOff() {
+ return this._allowSwitchOff;
+ }
- updateToggles: function (toggle) {
- if(!this.enabledInHierarchy) return;
+ set allowSwitchOff(value: boolean) {
+ this._allowSwitchOff = value;
+ }
- this._toggleItems.forEach(function (item){
- if(toggle.isChecked) {
+ /**
+ * !#en Read only property, return the toggle items array reference managed by toggleGroup.
+ * !#zh 只读属性,返回 toggleGroup 管理的 toggle 数组引用
+ * @property {Array} toggleItems
+ */
+ get toggleItems() {
+ return this._toggleItems;
+ }
+
+ start() {
+ this._makeAtLeastOneToggleChecked();
+ }
+
+ updateToggles(toggle: ToggleComponent) {
+ if (!this.enabledInHierarchy) return;
+
+ this._toggleItems.forEach(function (item) {
+ if (toggle.isChecked) {
if (item !== toggle && item.isChecked && item.enabled) {
item.isChecked = false;
}
}
});
- },
+ }
- addToggle: function (toggle) {
+ addToggle(toggle: ToggleComponent) {
var index = this._toggleItems.indexOf(toggle);
if (index === -1) {
this._toggleItems.push(toggle);
}
this._allowOnlyOneToggleChecked();
- },
+ }
- removeToggle: function (toggle) {
+ removeToggle(toggle: ToggleComponent) {
var index = this._toggleItems.indexOf(toggle);
- if(index > -1) {
+ if (index > -1) {
this._toggleItems.splice(index, 1);
}
this._makeAtLeastOneToggleChecked();
- },
+ }
- _allowOnlyOneToggleChecked: function () {
+ _allowOnlyOneToggleChecked() {
var isChecked = false;
this._toggleItems.forEach(function (item) {
- if(isChecked && item.enabled) {
+ if (isChecked && item.enabled) {
item.isChecked = false;
}
@@ -109,31 +115,15 @@ var ToggleGroup = cc.Class({
});
return isChecked;
- },
+ }
- _makeAtLeastOneToggleChecked: function () {
+ _makeAtLeastOneToggleChecked() {
var isChecked = this._allowOnlyOneToggleChecked();
- if(!isChecked && !this.allowSwitchOff) {
- if(this._toggleItems.length > 0) {
+ if (!isChecked && !this._allowSwitchOff) {
+ if (this._toggleItems.length > 0) {
this._toggleItems[0].isChecked = true;
}
}
- },
-
- start: function () {
- this._makeAtLeastOneToggleChecked();
}
-});
-
-var js = require('../platform/js');
-var showed = false;
-js.get(cc, 'ToggleGroup', function () {
- if (!showed) {
- cc.logID(1405, 'cc.ToggleGroup', 'cc.ToggleContainer');
- showed = true;
- }
- return ToggleGroup;
-});
-
-module.exports = ToggleGroup;
+}
diff --git a/cocos/3d/ui/components/ui-render-component.ts b/cocos/3d/ui/components/ui-render-component.ts
new file mode 100644
index 0000000000..1f3db79d2a
--- /dev/null
+++ b/cocos/3d/ui/components/ui-render-component.ts
@@ -0,0 +1,258 @@
+/****************************************************************************
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos.com
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated engine source code (the "Software"), a limited,
+ worldwide, royalty-free, non-assignable, revocable and non-exclusive license
+ to use Cocos Creator solely to develop games on your target platforms. You shall
+ not use Cocos Creator software for developing other software or tools that's
+ used for developing games. You are not granted to publish, distribute,
+ sublicense, and/or sell copies of Cocos Creator.
+
+ The software or tools in this License Agreement are licensed, not sold.
+ Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+import { RenderableComponent } from '../../../3d/framework/renderable-component';
+// import gfx from '../../renderer/gfx/index';
+import {
+ ccclass,
+ executeInEditMode,
+ executionOrder,
+ property,
+ requireComponent,
+} from '../../../core/data/class-decorator';
+import macro from '../../../core/platform/CCMacro';
+import { Color } from '../../../core/value-types/index';
+import { RenderData } from '../../../renderer/ui/renderData';
+import { CanvasComponent } from './canvas-component';
+import { UITransformComponent } from './ui-transfrom-component';
+
+/**
+ * !#en
+ * Base class for components which supports rendering features.
+ * !#zh
+ * 所有支持渲染的组件的基类
+ *
+ * @class RenderComponent
+ * @extends Component
+ */
+@ccclass('cc.RenderComponent')
+@executionOrder(100)
+@requireComponent(UITransformComponent)
+export class RenderComponent extends RenderableComponent {
+
+ /**
+ * !#en specify the source Blend Factor, this will generate a custom material object
+ * please pay attention to the memory cost.
+ * !#zh 指定原图的混合模式,这会克隆一个新的材质对象,注意这带来的
+ * @property srcBlendFactor
+ * sprite.srcBlendFactor = macro.BlendFactor.ONE;
+ */
+ @property({
+ type: macro.BlendFactor,
+ })
+ get srcBlendFactor () {
+ return this._srcBlendFactor;
+ }
+ set srcBlendFactor (value) {
+ if (this._srcBlendFactor === value) { return; }
+ this._srcBlendFactor = value;
+ this._updateBlendFunc(true);
+ }
+
+ /**
+ * !#en specify the destination Blend Factor.
+ * !#zh 指定目标的混合模式
+ * @property dstBlendFactor
+ * @type {macro.BlendFactor}
+ * @example
+ * sprite.dstBlendFactor = cc.macro.BlendFactor.ONE;
+ */
+ @property({
+ type: macro.BlendFactor,
+ })
+ get dstBlendFactor () {
+ return this._dstBlendFactor;
+ }
+
+ set dstBlendFactor (value) {
+ if (this._dstBlendFactor === value) { return; }
+ this._dstBlendFactor = value;
+ this._updateBlendFunc(true);
+ }
+
+ get color () {
+ return this._color;
+ }
+
+ set color (value) {
+ if (this._color === value) {
+ return;
+ }
+
+ this._color = value;
+ }
+
+ get viewID () {
+ return this._viewID;
+ }
+
+ public get renderData () {
+ return this._renderData;
+ }
+
+ public static assembler = null;
+ protected _renderDataPoolID: number = -1;
+ protected _viewID: number = -1;
+
+ protected _srcBlendFactor: number = macro.BlendFactor.SRC_ALPHA;
+ protected _dstBlendFactor: number = macro.BlendFactor.ONE_MINUS_SRC_ALPHA;
+ @property
+ protected _color: Color = Color.WHITE;
+ protected _renderData: RenderData | null = null;
+ // _allocedDatas = [];
+ // _vertexFormat = null;
+ // _toPostHandle = false;
+
+ constructor () {
+ super();
+ // this._assembler = this.constructor._assembler;
+ // this._postAssembler = this.constructor._postAssembler;
+ }
+
+ public onEnable () {
+ let parent = this.node;
+ while (parent) {
+ if (parent) {
+ const canvasComp = parent.getComponent(CanvasComponent);
+ if (canvasComp) {
+ this._viewID = canvasComp.visibility;
+ break;
+ }
+ }
+
+ // @ts-ignore
+ parent = parent.parent;
+ }
+ // if (this.node._renderComponent) {
+ // this.node._renderComponent.enabled = false;
+ // }
+ // this.node._renderComponent = this;
+ // this.node._renderFlag |= RenderFlow.FLAG_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | RenderFlow.FLAG_COLOR;
+ }
+
+ public onDisable () {
+ this._viewID = -1;
+ // this.node._renderComponent = null;
+ // this.disableRender();
+ }
+
+ public onDestroy () {
+ // for (let i = 0, l = this._allocedDatas.length; i < l; i++) {
+ // RenderData.free(this._allocedDatas[i]);
+ // }
+ // this._allocedDatas.length = 0;
+ this.destroyRenderData();
+ this.material = null;
+ this._renderData = null;
+ }
+
+ // _canRender() {
+ // return this._enabled;
+ // }
+
+ // markForUpdateRenderData(enable) {
+ // // if (enable && this._canRender()) {
+ // // this.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA;
+ // // }
+ // // else if (!enable) {
+ // // this.node._renderFlag &= ~RenderFlow.FLAG_UPDATE_RENDER_DATA;
+ // // }
+ // }
+
+ // markForRender(enable) {
+ // // if (enable && this._canRender()) {
+ // // this.node._renderFlag |= RenderFlow.FLAG_RENDER;
+ // // }
+ // // else if (!enable) {
+ // // this.node._renderFlag &= ~RenderFlow.FLAG_RENDER;
+ // // }
+ // }
+
+ // markForCustomIARender(enable) {
+ // // if (enable && this._canRender()) {
+ // // this.node._renderFlag |= RenderFlow.FLAG_CUSTOM_IA_RENDER;
+ // // }
+ // // else if (!enable) {
+ // // this.node._renderFlag &= ~RenderFlow.FLAG_CUSTOM_IA_RENDER;
+ // // }
+ // }
+
+ // disableRender() {
+ // // this.node._renderFlag &= ~(RenderFlow.FLAG_RENDER | RenderFlow.FLAG_CUSTOM_IA_RENDER | RenderFlow.FLAG_UPDATE_RENDER_DATA | RenderFlow.FLAG_COLOR);
+ // }
+
+ public requestRenderData () {
+ const data = RenderData.add();
+ // this._allocedDatas.push(data);
+ this._renderData = data.data;
+ this._renderDataPoolID = data.pooID;
+ return this._renderData;
+ }
+
+ public destroyRenderData () {
+ // let index = this._allocedDatas.indexOf(data);
+ // if (index !== -1) {
+ // this._allocedDatas.splice(index, 1);
+ // RenderData.free(data);
+ // }
+ if (this._renderDataPoolID === -1) {
+ return;
+ }
+
+ RenderData.remove(this._renderDataPoolID);
+ this._renderDataPoolID = -1;
+ this._renderData = null;
+ }
+
+ public _updateColor () {
+ const material = this.material;
+ if (material) {
+ material.setProperty('color', this._color);
+ // material.updateHash();
+ }
+ }
+
+ // TODO:
+ public _updateBlendFunc (updateHash) {
+ // if (!this.material) {
+ // return;
+ // }
+
+ // var pass = this.material._mainTech.passes[0];
+ // pass.setBlend(
+ // gfx.BLEND_FUNC_ADD,
+ // this._srcBlendFactor, this._dstBlendFactor,
+ // gfx.BLEND_FUNC_ADD,
+ // this._srcBlendFactor, this._dstBlendFactor
+ // );
+
+ // if (updateHash) {
+ // this.material.updateHash();
+ // }
+ }
+}
+
+// RenderComponent._assembler = null;
+// RenderComponent._postAssembler = null;
diff --git a/cocos/3d/ui/components/ui-transfrom-component.ts b/cocos/3d/ui/components/ui-transfrom-component.ts
new file mode 100644
index 0000000000..193e1c686b
--- /dev/null
+++ b/cocos/3d/ui/components/ui-transfrom-component.ts
@@ -0,0 +1,286 @@
+import { Component} from '../../../components/component';
+import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator';
+import Event from '../../../core/platform/event-manager/CCEvent.js';
+import Size from '../../../core/value-types/size';
+import Vec2 from '../../../core/value-types/vec2';
+import * as math from '../../../core/vmath/index';
+import { Enum } from '../../../core/value-types';
+
+const _vec2a = cc.v2();
+const _vec2b = cc.v2();
+const _mat4_temp = cc.mat4();
+const _worldMatrix = cc.mat4();
+
+const EventType = Enum({
+ /**
+ * !#en The event type for size change events.
+ * Performance note, this event will be triggered every time corresponding properties being changed,
+ * if the event callback have heavy logic it may have great performance impact, try to avoid such scenario.
+ * !#zh 当节点尺寸改变时触发的事件。
+ * 性能警告:这个事件会在每次对应的属性被修改时触发,如果事件回调损耗较高,有可能对性能有很大的负面影响,请尽量避免这种情况。
+ * @property {String} SIZE_CHANGED
+ * @static
+ */
+ SIZE_CHANGED: 'size-changed',
+ /**
+ * !#en The event type for anchor point change events.
+ * Performance note, this event will be triggered every time corresponding properties being changed,
+ * if the event callback have heavy logic it may have great performance impact, try to avoid such scenario.
+ * !#zh 当节点锚点改变时触发的事件。
+ * 性能警告:这个事件会在每次对应的属性被修改时触发,如果事件回调损耗较高,有可能对性能有很大的负面影响,请尽量避免这种情况。
+ * @property {String} ANCHOR_CHANGED
+ * @static
+ */
+ ANCHOR_CHANGED: 'anchor-changed',
+});
+
+@ccclass('cc.UITransformComponent')
+@executionOrder(100)
+export class UITransformComponent extends Component {
+
+ @property
+ get contentSize () {
+ return this._contentSize;
+ }
+
+ set contentSize (value) {
+ if (this._contentSize === value) {
+ return;
+ }
+
+ this._contentSize = value;
+ this.node.emit(EventType.SIZE_CHANGED);
+ }
+
+ get width () {
+ return this._contentSize.width;
+ }
+
+ set width (value) {
+ if (this._contentSize.width === value) {
+ return;
+ }
+
+ this._contentSize.width = value;
+ this.node.emit(EventType.SIZE_CHANGED);
+ }
+
+ get height () {
+ return this._contentSize.height;
+ }
+
+ set height (value) {
+ if (this._contentSize.height === value) {
+ return;
+ }
+
+ this._contentSize.height = value;
+ this.node.emit(EventType.SIZE_CHANGED);
+ }
+
+ @property
+ get anchorPoint () {
+ return this._anchorPoint;
+ }
+
+ set anchorPoint (value) {
+ if (this._anchorPoint === value) {
+ return;
+ }
+
+ this._anchorPoint = value;
+ this.node.emit(EventType.ANCHOR_CHANGED);
+ }
+
+ get anchorX () {
+ return this._anchorPoint.x;
+ }
+
+ set anchorX (value) {
+ if (this._anchorPoint.x === value) {
+ return;
+ }
+
+ this._anchorPoint.x = value;
+ this.node.emit(EventType.ANCHOR_CHANGED);
+ }
+
+ get anchorY () {
+ return this._anchorPoint.y;
+ }
+
+ set anchorY (value) {
+ if (this._anchorPoint.y === value) {
+ return;
+ }
+
+ this._anchorPoint.y = value;
+ this.node.emit(EventType.ANCHOR_CHANGED);
+ }
+
+ public static EventType = EventType;
+ @property
+ public _contentSize = new cc.Size(100, 100);
+ @property
+ public _anchorPoint = cc.v2(0.5, 0.5);
+
+ public onEnable () {
+ this.node.uiTransfromComp = this;
+ }
+
+ public onDisable () {
+ this.node.uiTransfromComp = null;
+ }
+
+ /**
+ * !#en
+ * Sets the untransformed size of the node.
+ * The contentSize remains the same no matter the node is scaled or rotated.
+ * All nodes has a size. Layer and Scene has the same size of the screen.
+ * !#zh 设置节点原始大小,不受该节点是否被缩放或者旋转的影响。
+ * @method setContentSize
+ * @param {Size|Number} size - The untransformed size of the node or The untransformed size's width of the node.
+ * @param {Number} [height] - The untransformed size's height of the node.
+ * @example
+ * node.setContentSize(cc.size(100, 100));
+ * node.setContentSize(100, 100);
+ */
+ public setContentSize (size: Size, height: number) {
+ const locContentSize = this._contentSize;
+ // var clone;
+ if (height === undefined) {
+ if ((size.width === locContentSize.width) && (size.height === locContentSize.height)) {
+ return;
+ }
+ // if (CC_EDITOR) {
+ // clone = cc.size(locContentSize.width, locContentSize.height);
+ // }
+ locContentSize.width = size.width;
+ locContentSize.height = size.height;
+ } else {
+ if ((size === locContentSize.width) && (height === locContentSize.height)) {
+ return;
+ }
+ // if (CC_EDITOR) {
+ // clone = cc.size(locContentSize.width, locContentSize.height);
+ // }
+ locContentSize.width = size;
+ locContentSize.height = height;
+ }
+ // if (CC_EDITOR) {
+ // this.emit(EventType.SIZE_CHANGED, clone);
+ // }
+ // else {
+ this.node.emit(EventType.SIZE_CHANGED);
+ // }
+ }
+
+ /**
+ * !#en
+ * Sets the anchor point in percent.
+ * anchor point is the point around which all transformations and positioning manipulations take place.
+ * It's like a pin in the node where it is "attached" to its parent.
+ * The anchorPoint is normalized, like a percentage. (0,0) means the bottom-left corner and (1,1) means the top-right corner.
+ * But you can use values higher than (1,1) and lower than (0,0) too.
+ * The default anchor point is (0.5,0.5), so it starts at the center of the node.
+ * !#zh
+ * 设置锚点的百分比。
+ * 锚点应用于所有变换和坐标点的操作,它就像在节点上连接其父节点的大头针。
+ * 锚点是标准化的,就像百分比一样。(0,0) 表示左下角,(1,1) 表示右上角。
+ * 但是你可以使用比(1,1)更高的值或者比(0,0)更低的值。
+ * 默认的锚点是(0.5,0.5),因此它开始于节点的中心位置。
+ * 注意:Creator 中的锚点仅用于定位所在的节点,子节点的定位不受影响。
+ * @method setAnchorPoint
+ * @param {Vec2|Number} point - The anchor point of node or The x axis anchor of node.
+ * @param {Number} [y] - The y axis anchor of node.
+ * @example
+ * node.setAnchorPoint(cc.v2(1, 1));
+ * node.setAnchorPoint(1, 1);
+ */
+ public setAnchorPoint (point: Vec2, y: number) {
+ const locAnchorPoint = this._anchorPoint;
+ if (y === undefined) {
+ if ((point.x === locAnchorPoint.x) && (point.y === locAnchorPoint.y)) {
+ return;
+ }
+ locAnchorPoint.x = point.x;
+ locAnchorPoint.y = point.y;
+ } else {
+ if ((point === locAnchorPoint.x) && (y === locAnchorPoint.y)) {
+ return;
+ }
+ locAnchorPoint.x = point;
+ locAnchorPoint.y = y;
+ }
+ // this.setLocalDirty(LocalDirtyFlag.POSITION);
+ // if (this._eventMask & ANCHOR_ON) {
+ this.node.emit(EventType.ANCHOR_CHANGED);
+ // }
+ }
+
+ public isHit (point: Vec2, listener: Event) {
+ const w = this._contentSize.width;
+ const h = this._contentSize.height;
+ const cameraPt = _vec2a;
+ const testPt = _vec2b;
+
+ const renderComp = this.node.getComponent(cc.RenderComponent);
+ if (!renderComp) {
+ return false;
+ }
+ const canvas = cc.CanvasComponent.findView(renderComp);
+ if (!canvas) {
+ return;
+ }
+
+ canvas.node.getWorldRT(_mat4_temp);
+
+ const m12 = _mat4_temp.m12;
+ const m13 = _mat4_temp.m13;
+
+ const center = cc.visibleRect.center;
+ // let size = cc.view.getFrameSize();
+ // let center = cc.v2(size.width / 2, size.height / 2);
+ // let center = cc.v2(cc.game._renderer._device._gl.canvas.width / 2, cc.game._renderer._device._gl.canvas.height / 2);
+ _mat4_temp.m12 = center.x - (_mat4_temp.m00 * m12 + _mat4_temp.m04 * m13);
+ _mat4_temp.m13 = center.y - (_mat4_temp.m01 * m12 + _mat4_temp.m05 * m13);
+
+ // if (out !== _mat4_temp) {
+ // mat4.copy(out, _mat4_temp);
+ // }
+ math.mat4.invert(_mat4_temp, _mat4_temp);
+ math.vec2.transformMat4(cameraPt, point, _mat4_temp);
+ // let camera = cc.Camera.findCamera(this);
+ // if (camera) {
+ // camera.getCameraToWorldPoint(point, cameraPt);
+ // }
+ // else {
+ // cameraPt.set(point);
+ // }
+
+ this.node.getWorldMatrix(_worldMatrix);
+ math.mat4.invert(_mat4_temp, _worldMatrix);
+ math.vec2.transformMat4(testPt, cameraPt, _mat4_temp);
+ testPt.x += this._anchorPoint.x * w;
+ testPt.y += this._anchorPoint.y * h;
+
+ if (testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h) {
+ if (listener && listener.mask) {
+ const mask = listener.mask;
+ const parent = this;
+ // find mask parent, should hit test it
+ if (parent === mask.node) {
+ const comp = parent.getComponent(cc.Mask);
+ return (comp && comp.enabledInHierarchy) ? comp._hitTest(cameraPt) : true;
+ } else {
+ listener.mask = null;
+ return true;
+ }
+ } else {
+ return true;
+ }
+ } else {
+ return false;
+ }
+ }
+}
diff --git a/cocos/3d/ui/components/widget-component.ts b/cocos/3d/ui/components/widget-component.ts
new file mode 100644
index 0000000000..ceef11cd76
--- /dev/null
+++ b/cocos/3d/ui/components/widget-component.ts
@@ -0,0 +1,660 @@
+/****************************************************************************
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos.com
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated engine source code (the "Software"), a limited,
+ worldwide, royalty-free, non-assignable, revocable and non-exclusive license
+ to use Cocos Creator solely to develop games on your target platforms. You shall
+ not use Cocos Creator software for developing other software or tools that's
+ used for developing games. You are not granted to publish, distribute,
+ sublicense, and/or sell copies of Cocos Creator.
+
+ The software or tools in this License Agreement are licensed, not sold.
+ Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+// var WidgetManager = require('../base-ui/CCWidgetManager');
+import WidgetManager from '../../../2d/base-ui/CCWidgetManager';
+import { Component} from '../../../components/component';
+import { ccclass, property, executeInEditMode, menu, executionOrder } from '../../../core/data/class-decorator';
+import { Node } from '../../../scene-graph/index'
+/**
+ * !#en Enum for Widget's alignment mode, indicating when the widget should refresh.
+ * !#zh Widget 的对齐模式,表示 Widget 应该何时刷新。
+ * @enum Widget.AlignMode
+ */
+/**
+ * !#en
+ * Only align once when the Widget is enabled for the first time.
+ * This will allow the script or animation to continue controlling the current node.
+ * It will only be aligned once before the end of frame when onEnable is called,
+ * then immediately disables the Widget.
+ * !#zh
+ * 仅在 Widget 第一次激活时对齐一次,便于脚本或动画继续控制当前节点。
+ * 开启后会在 onEnable 时所在的那一帧结束前对齐一次,然后立刻禁用该 Widget。
+ * @property {Number} ONCE
+ */
+/**
+ * !#en Align first from the beginning as ONCE, and then realign it every time the window is resized.
+ * !#zh 一开始会像 ONCE 一样对齐一次,之后每当窗口大小改变时还会重新对齐。
+ * @property {Number} ON_WINDOW_RESIZE
+ */
+/**
+ * !#en Keep aligning all the way.
+ * !#zh 始终保持对齐。
+ * @property {Number} ALWAYS
+ */
+var AlignMode = WidgetManager.AlignMode;
+
+var AlignFlags = WidgetManager._AlignFlags;
+var TOP = AlignFlags.TOP;
+var MID = AlignFlags.MID;
+var BOT = AlignFlags.BOT;
+var LEFT = AlignFlags.LEFT;
+var CENTER = AlignFlags.CENTER;
+var RIGHT = AlignFlags.RIGHT;
+var TOP_BOT = TOP | BOT;
+var LEFT_RIGHT = LEFT | RIGHT;
+
+/**
+ * !#en
+ * Stores and manipulate the anchoring based on its parent.
+ * Widget are used for GUI but can also be used for other things.
+ * Widget will adjust current node's position and size automatically, but the results after adjustment can not be obtained until the next frame unless you call {{#crossLink "Widget/updateAlignment:method"}}{{/crossLink}} manually.
+ * !#zh
+ * Widget 组件,用于设置和适配其相对于父节点的边距,Widget 通常被用于 UI 界面,也可以用于其他地方。
+ * Widget 会自动调整当前节点的坐标和宽高,不过目前调整后的结果要到下一帧才能在脚本里获取到,除非你先手动调用 {{#crossLink "Widget/updateAlignment:method"}}{{/crossLink}}。
+ *
+ * @class Widget
+ * @extends Component
+ */
+@ccclass('cc.WidgetComponent')
+@executionOrder(100)
+@menu('UI/Widget')
+@executeInEditMode
+export default class WidgetComponent extends Component {
+ /**
+ * !#zh: 对齐开关,由 AlignFlags 组成
+ *
+ * @property _alignFlags
+ * @type {Number}
+ * @default 0
+ * @private
+ */
+ _alignFlags: number = 0;
+ _wasAlignOnce: boolean = false;
+ @property
+ _target: Node | null = null;
+ @property
+ _isAlignTop: boolean = false;
+ @property
+ _isAlignBottom: boolean = false;
+ @property
+ _isAlignLeft: boolean = false;
+ @property
+ _isAlignRight: boolean = false;
+ @property
+ _left: number = 0;
+ @property
+ _right: number = 0;
+ @property
+ _top: number = 0;
+ @property
+ _bottom: number = 0;
+ @property
+ _horizontalCenter: number = 0;
+ @property
+ _verticalCenter: number = 0;
+ @property
+ _isAbsLeft: boolean = true;
+ @property
+ _isAbsRight: boolean = true;
+ @property
+ _isAbsTop: boolean = true;
+ @property
+ _isAbsBottom: boolean = true;
+ @property
+ _isAbsHorizontalCenter: boolean = true;
+ @property
+ _isAbsVerticalCenter: boolean = true;
+ // original size before align
+ @property
+ _originalWidth: number = 0;
+ @property
+ _originalHeight: number = 0;
+ @property
+ _alignMode: number = AlignMode.ON_WINDOW_RESIZE;
+
+ /**
+ * !#en Specifies an alignment target that can only be one of the parent nodes of the current node.
+ * The default value is null, and when null, indicates the current parent.
+ * !#zh 指定一个对齐目标,只能是当前节点的其中一个父节点,默认为空,为空时表示当前父节点。
+ * @property {Node} target
+ * @default null
+ */
+ @property({
+ type: cc.NodeUI
+ })
+ get target() {
+ return this._target;
+ }
+
+ set target(value) {
+ this._target = value;
+ if (CC_EDITOR && !cc.engine._isPlaying && this.node._parent) {
+ // adjust the offsets to keep the size and position unchanged after target chagned
+ WidgetManager.updateOffsetsToStayPut(this);
+ }
+ }
+
+ // ENABLE ALIGN ?
+
+ /**
+ * !#en Whether to align the top.
+ * !#zh 是否对齐上边。
+ * @property isAlignTop
+ * @type {Boolean}
+ * @default false
+ */
+ @property
+ get isAlignTop() {
+ return (this._alignFlags & TOP) > 0;
+ }
+ set isAlignTop(value) {
+ this._isAlignTop = value;
+ this._setAlign(TOP, value);
+ }
+
+ /**
+ * !#en Whether to align the bottom.
+ * !#zh 是否对齐下边。
+ * @property isAlignBottom
+ * @type {Boolean}
+ * @default false
+ */
+ @property
+ get isAlignBottom() {
+ return (this._alignFlags & BOT) > 0;
+ }
+ set isAlignBottom(value) {
+ this._setAlign(BOT, value);
+ }
+
+ /**
+ * !#en Whether to align the left.
+ * !#zh 是否对齐左边
+ * @property isAlignLeft
+ * @type {Boolean}
+ * @default false
+ */
+ @property
+ get isAlignLeft() {
+ return (this._alignFlags & LEFT) > 0;
+ }
+ set isAlignLeft(value) {
+ this._setAlign(LEFT, value);
+ }
+
+ /**
+ * !#en Whether to align the right.
+ * !#zh 是否对齐右边。
+ * @property isAlignRight
+ * @type {Boolean}
+ * @default false
+ */
+ @property
+ get isAlignRight() {
+ return (this._alignFlags & RIGHT) > 0;
+ }
+ set isAlignRight(value) {
+ this._setAlign(RIGHT, value);
+ }
+
+
+
+ /**
+ * !#en
+ * Vertically aligns the midpoint, This will open the other vertical alignment options cancel.
+ * !#zh
+ * 是否垂直方向对齐中点,开启此项会将垂直方向其他对齐选项取消。
+ * @property isAlignVerticalCenter
+ * @type {Boolean}
+ * @default false
+ */
+ @property
+ get isAlignVerticalCenter() {
+ return (this._alignFlags & MID) > 0;
+ }
+ set isAlignVerticalCenter(value) {
+ if (value) {
+ this.isAlignTop = false;
+ this.isAlignBottom = false;
+ this._alignFlags |= MID;
+ }
+ else {
+ this._alignFlags &= ~MID;
+ }
+ }
+
+ /**
+ * !#en
+ * Horizontal aligns the midpoint. This will open the other horizontal alignment options canceled.
+ * !#zh
+ * 是否水平方向对齐中点,开启此选项会将水平方向其他对齐选项取消。
+ * @property isAlignHorizontalCenter
+ * @type {Boolean}
+ * @default false
+ */
+ @property
+ get isAlignHorizontalCenter() {
+ return (this._alignFlags & CENTER) > 0;
+ }
+ set isAlignHorizontalCenter(value) {
+ if (value) {
+ this.isAlignLeft = false;
+ this.isAlignRight = false;
+ this._alignFlags |= CENTER;
+ }
+ else {
+ this._alignFlags &= ~CENTER;
+ }
+ }
+
+ /**
+ * !#en
+ * Whether the stretched horizontally, when enable the left and right alignment will be stretched horizontally,
+ * the width setting is invalid (read only).
+ * !#zh
+ * 当前是否水平拉伸。当同时启用左右对齐时,节点将会被水平拉伸,此时节点的宽度只读。
+ * @property isStretchWidth
+ * @type {Boolean}
+ * @default false
+ * @readOnly
+ */
+ @property({
+ visible: false
+ })
+ get isStretchWidth() {
+ return (this._alignFlags & LEFT_RIGHT) === LEFT_RIGHT;
+ }
+
+ /**
+ * !#en
+ * Whether the stretched vertically, when enable the left and right alignment will be stretched vertically,
+ * then height setting is invalid (read only)
+ * !#zh
+ * 当前是否垂直拉伸。当同时启用上下对齐时,节点将会被垂直拉伸,此时节点的高度只读。
+ * @property isStretchHeight
+ * @type {Boolean}
+ * @default false
+ * @readOnly
+ */
+ @property({
+ visible: false
+ })
+ get isStretchHeight() {
+ return (this._alignFlags & TOP_BOT) === TOP_BOT;
+ }
+
+ // ALIGN MARGINS
+
+ /**
+ * !#en
+ * The margins between the top of this node and the top of parent node,
+ * the value can be negative, Only available in 'isAlignTop' open.
+ * !#zh
+ * 本节点顶边和父节点顶边的距离,可填写负值,只有在 isAlignTop 开启时才有作用。
+ * @property top
+ * @type {Number}
+ * @default 0
+ */
+ @property
+ get top() {
+ return this._top;
+ }
+ set top(value) {
+ this._top = value;
+ }
+
+ /**
+ * !#en
+ * The margins between the bottom of this node and the bottom of parent node,
+ * the value can be negative, Only available in 'isAlignBottom' open.
+ * !#zh
+ * 本节点底边和父节点底边的距离,可填写负值,只有在 isAlignBottom 开启时才有作用。
+ * @property bottom
+ * @type {Number}
+ * @default 0
+ */
+ @property
+ get bottom() {
+ return this._bottom;
+ }
+ set bottom(value) {
+ this._bottom = value;
+ }
+
+ /**
+ * !#en
+ * The margins between the left of this node and the left of parent node,
+ * the value can be negative, Only available in 'isAlignLeft' open.
+ * !#zh
+ * 本节点左边和父节点左边的距离,可填写负值,只有在 isAlignLeft 开启时才有作用。
+ * @property left
+ * @type {Number}
+ * @default 0
+ */
+ @property
+ get left() {
+ return this._left;
+ }
+ set left(value) {
+ this._left = value;
+ }
+
+ /**
+ * !#en
+ * The margins between the right of this node and the right of parent node,
+ * the value can be negative, Only available in 'isAlignRight' open.
+ * !#zh
+ * 本节点右边和父节点右边的距离,可填写负值,只有在 isAlignRight 开启时才有作用。
+ * @property right
+ * @type {Number}
+ * @default 0
+ */
+ @property
+ get right() {
+ return this._right;
+ }
+ set right(value) {
+ this._right = value;
+ }
+
+ /**
+ * !#en
+ * Horizontal aligns the midpoint offset value,
+ * the value can be negative, Only available in 'isAlignHorizontalCenter' open.
+ * !#zh 水平居中的偏移值,可填写负值,只有在 isAlignHorizontalCenter 开启时才有作用。
+ * @property horizontalCenter
+ * @type {Number}
+ * @default 0
+ */
+ @property
+ get horizontalCenter() {
+ return this._horizontalCenter;
+ }
+ set horizontalCenter(value) {
+ this._horizontalCenter = value;
+ }
+
+ /**
+ * !#en
+ * Vertical aligns the midpoint offset value,
+ * the value can be negative, Only available in 'isAlignVerticalCenter' open.
+ * !#zh 垂直居中的偏移值,可填写负值,只有在 isAlignVerticalCenter 开启时才有作用。
+ * @property verticalCenter
+ * @type {Number}
+ * @default 0
+ */
+ @property
+ get verticalCenter() {
+ return this._verticalCenter;
+ }
+ set verticalCenter(value) {
+ this._verticalCenter = value;
+ }
+
+ /**
+ * !#en
+ * If true, top is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's height.
+ * !#zh
+ * 如果为 true,"top" 将会以像素作为边距,否则将会以相对父物体高度的百分比(0 到 1)作为边距。
+ * @property isAbsoluteTop
+ * @type {Boolean}
+ * @default true
+ */
+ @property
+ get isAbsoluteTop() {
+ return this._isAbsTop;
+ }
+ set isAbsoluteTop(value) {
+ this._isAbsTop = value;
+ }
+
+ /**
+ * !#en
+ * If true, bottom is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's height.
+ * !#zh
+ * 如果为 true,"bottom" 将会以像素作为边距,否则将会以相对父物体高度的百分比(0 到 1)作为边距。
+ * @property isAbsoluteBottom
+ * @type {Boolean}
+ * @default true
+ */
+ @property
+ get isAbsoluteBottom() {
+ return this._isAbsBottom;
+ }
+ set isAbsoluteBottom(value) {
+ this._isAbsBottom = value;
+ }
+
+ /**
+ * !#en
+ * If true, left is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's width.
+ * !#zh
+ * 如果为 true,"left" 将会以像素作为边距,否则将会以相对父物体宽度的百分比(0 到 1)作为边距。
+ * @property isAbsoluteLeft
+ * @type {Boolean}
+ * @default true
+ */
+ @property
+ get isAbsoluteLeft() {
+ return this._isAbsLeft;
+ }
+ set isAbsoluteLeft(value) {
+ this._isAbsLeft = value;
+ }
+
+ /**
+ * !#en
+ * If true, right is pixel margin, otherwise is percentage (0 - 1) margin relative to the parent's width.
+ * !#zh
+ * 如果为 true,"right" 将会以像素作为边距,否则将会以相对父物体宽度的百分比(0 到 1)作为边距。
+ * @property isAbsoluteRight
+ * @type {Boolean}
+ * @default true
+ */
+ @property
+ get isAbsoluteRight() {
+ return this._isAbsRight;
+ }
+ set isAbsoluteRight(value) {
+ this._isAbsRight = value;
+ }
+
+ /**
+ * !#en Specifies the alignment mode of the Widget, which determines when the widget should refresh.
+ * !#zh 指定 Widget 的对齐模式,用于决定 Widget 应该何时刷新。
+ * @property {Widget.AlignMode} alignMode
+ * @example
+ * widget.alignMode = cc.Widget.AlignMode.ON_WINDOW_RESIZE;
+ */
+ @property({
+ type: AlignMode
+ })
+ get alignMode() {
+ return this._alignMode;
+ }
+
+ set alignMode(value) {
+ this._alignMode = value;
+ }
+
+ /**
+ * !#en If true, horizontalCenter is pixel margin, otherwise is percentage (0 - 1) margin.
+ * !#zh 如果为 true,"horizontalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。
+ * @property isAbsoluteHorizontalCenter
+ * @type {Boolean}
+ * @default true
+ */
+ @property
+ get isAbsoluteHorizontalCenter() {
+ return this._isAbsHorizontalCenter;
+ }
+
+ set isAbsoluteHorizontalCenter(value) {
+ this._isAbsHorizontalCenter = value;
+ }
+
+
+ /**
+ * !#en If true, verticalCenter is pixel margin, otherwise is percentage (0 - 1) margin.
+ * !#zh 如果为 true,"verticalCenter" 将会以像素作为偏移值,反之为百分比(0 到 1)。
+ * @property isAbsoluteVerticalCenter
+ * @type {Boolean}
+ * @default true
+ */
+ @property
+ get isAbsoluteVerticalCenter() {
+ return this._isAbsVerticalCenter;
+ }
+ set isAbsoluteVerticalCenter(value) {
+ this._isAbsVerticalCenter = value;
+ }
+
+ static AlignMode = AlignMode;
+
+ onLoad() {
+ if (this._wasAlignOnce) {
+ // migrate for old version
+ this.alignMode = this._wasAlignOnce ? AlignMode.ONCE : AlignMode.ALWAYS;
+ this._wasAlignOnce = false;
+ }
+ }
+
+ onEnable() {
+ WidgetManager.add(this);
+ }
+
+ onDisable() {
+ WidgetManager.remove(this);
+ }
+
+ _setAlign(flag: number, isAlign: boolean) {
+ var current = (this._alignFlags & flag) > 0;
+ if (isAlign == current) {
+ return;
+ }
+ var isHorizontal = (flag & LEFT_RIGHT) > 0;
+ if (isAlign) {
+ this._alignFlags |= flag;
+
+ if (isHorizontal) {
+ this.isAlignHorizontalCenter = false;
+ 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 {
+ this.isAlignVerticalCenter = false;
+ 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 && this.node._parent) {
+ // adjust the offsets to keep the size and position unchanged after alignment chagned
+ WidgetManager.updateOffsetsToStayPut(this, flag);
+ }
+ }
+ else {
+ if (isHorizontal) {
+ if (this.isStretchWidth) {
+ // will cancel stretch
+ this.node.width = this._originalWidth;
+ }
+ }
+ else {
+ if (this.isStretchHeight) {
+ // will cancel stretch
+ this.node.height = this._originalHeight;
+ }
+ }
+
+ this._alignFlags &= ~flag;
+ }
+ }
+
+ /**
+ * !#en
+ * Immediately perform the widget alignment. You need to manually call this method only if
+ * you need to get the latest results after the alignment before the end of current frame.
+ * !#zh
+ * 立刻执行 widget 对齐操作。这个接口一般不需要手工调用。
+ * 只有当你需要在当前帧结束前获得 widget 对齐后的最新结果时才需要手动调用这个方法。
+ *
+ * @method updateAlignment
+ *
+ * @example
+ * widget.top = 10; // change top margin
+ * cc.log(widget.node.y); // not yet changed
+ * widget.updateAlignment();
+ * cc.log(widget.node.y); // changed
+ */
+ updateAlignment() {
+ WidgetManager.updateAlignment(this.node);
+ }
+}
+
+/**
+ * !#en
+ * When turned on, it will only be aligned once at the end of the onEnable frame,
+ * then immediately disables the current component.
+ * This will allow the script or animation to continue controlling the current node.
+ * Note: It will still be aligned at the frame when onEnable is called.
+ * !#zh
+ * 开启后仅会在 onEnable 的当帧结束时对齐一次,然后立刻禁用当前组件。
+ * 这样便于脚本或动画继续控制当前节点。
+ * 注意:onEnable 时所在的那一帧仍然会进行对齐。
+ * @property {Boolean} isAlignOnce
+ * @default false
+ * @deprecated
+ */
+// Object.defineProperty(Widget.prototype, 'isAlignOnce', {
+// get() {
+// if (CC_DEBUG) {
+// cc.warn('`widget.isAlignOnce` is deprecated, use `widget.alignMode === cc.Widget.AlignMode.ONCE` instead please.');
+// }
+// return this.alignMode === AlignMode.ONCE;
+// }
+// set(value) {
+// if (CC_DEBUG) {
+// cc.warn('`widget.isAlignOnce` is deprecated, use `widget.alignMode = cc.Widget.AlignMode.*` instead please.');
+// }
+// this.alignMode = value ? AlignMode.ONCE : AlignMode.ALWAYS;
+// }
+// });
+
+
+// cc.Widget = module.exports = Widget;
diff --git a/cocos/3d/ui/index.ts b/cocos/3d/ui/index.ts
new file mode 100644
index 0000000000..46d62b4fe9
--- /dev/null
+++ b/cocos/3d/ui/index.ts
@@ -0,0 +1,30 @@
+
+import { CanvasComponent} from './components/canvas-component';
+import {RenderComponent} from './components/ui-render-component';
+import { SpriteComponent} from './components/sprite-component';
+import { UITransformComponent } from './components/ui-transfrom-component';
+// import LabelComponent from './components/label-component';
+// import UIRectComponent fro./components/ui-transfrom-componentent';
+// import ButtonComponent from './components/button-component';
+// import ToggleGroupComponent from './components/toggle-group-component';
+// import ToggleComponent from './components/toggle-component';
+// import ToggleContainerComponent from './components/toggle-container-component';
+// import SliderComponent from './components/slider-component';
+// import ProgressBarComponent from './components/progress-bar-component';
+// import WidgetComponent from './components/widget-component';
+// import EditBoxComponent from './components/editbox/edit-box-component';
+import './assembler/index';
+
+cc.CanvasComponent = CanvasComponent;
+cc.RenderComponent = RenderComponent;
+cc.SpriteComponent = SpriteComponent;
+// cc.LabelComponent = LabelComponent;
+// cc.UIRectComponent = UIRectComponent;
+// cc.ButtonComponent = ButtonComponent;
+// cc.ToggleGroupComponent = ToggleGroupComponent;
+// cc.ToggleComponent = ToggleComponent;
+// cc.ToggleContainerComponent = ToggleContainerComponent;
+// cc.SliderComponent = SliderComponent;
+// cc.ProgressBarComponent = ProgressBarComponent;
+// cc.WidgetComponent = WidgetComponent;
+// cc.EditBoxComponent = EditBoxComponent;
diff --git a/cocos/3d/ui/mesh-buffer.ts b/cocos/3d/ui/mesh-buffer.ts
new file mode 100644
index 0000000000..4ec32cda34
--- /dev/null
+++ b/cocos/3d/ui/mesh-buffer.ts
@@ -0,0 +1,228 @@
+// import gfx from '../gfx/index';
+// import VertexFormat from '../gfx/vertex-format';
+// import { UI } from './ui';
+// import { GFXDevice } from '../../gfx/device';
+// import { GFXBuffer } from '../../gfx/buffer';
+import { GFXFormat } from '../../gfx/define';
+import { IGFXInputAttribute } from '../../gfx/input-assembler';
+// import UISystem from '../UISystem';
+
+export interface IMeshBufferInitData {
+ vertexCount: number;
+ indexCount: number;
+ attributes: IGFXInputAttribute[];
+}
+
+export class MeshBuffer {
+ public byteStart: number = 0;
+ public byteOffset: number = 0;
+ public indiceStart: number = 0;
+ public indiceOffset: number = 0;
+ public vertexStart: number = 0;
+ public vertexOffset: number = 0;
+ // public _vb: GFXBuffer | null = null;
+ // public _ib: GFXBuffer | null = null;
+ public vData: Float32Array | null = null;
+ public iData: Uint16Array | null = null;
+ public uintVData: Uint32Array | null = null;
+
+ private _vertexBytes: number = 0;
+ private _vertexFormat: IGFXInputAttribute[] = [];
+ // private _renderer: UI|null = null;
+
+ private _initVDataCount: number = 0; // actually 256 * 4 * (vertexFormat._bytes / 4)
+ private _initIDataCount: number = 0;
+ private _dirty: boolean = false;
+
+ constructor (/*device: GFXDevice*/) {
+
+ // const device = cc.game._renderContext;
+ // this._vertexFormat = vertexFormat;
+
+ // TODO: calculate
+ // this._vertexBytes = this.calculateBytes(vertexFormat)/*this._vertexFormat._bytes*/;
+ // this._vb = new gfx.VertexBuffer(
+ // device,
+ // vertexFormat,
+ // gfx.USAGE_DYNAMIC,
+ // new ArrayBuffer(0),
+ // 0,
+ // );
+ // this._vb = device.createBuffer({
+ // usage: GFXBufferUsageBit.VERTEX,
+ // memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE,
+ // size: 0,
+ // stride: 0,
+ // });
+ // this._ib = new gfx.IndexBuffer(
+ // device,
+ // gfx.INDEX_FMT_UINT16,
+ // gfx.USAGE_STATIC,
+ // new ArrayBuffer(0),
+ // 0,
+ // );
+
+ // this._ib = device.createBuffer({
+ // usage: GFXBufferUsageBit.INDEX,
+ // memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE,
+ // size: 0,
+ // stride: 2,
+ // });
+ // this._renderer = renderer;
+ // this._initVDataCount = 256 * this._vertexBytes;
+ // this._reallocBuffer();
+ }
+
+ public initialize (data: IMeshBufferInitData) {
+ this._vertexFormat = data.attributes;
+ this._vertexBytes = this.calculateBytes(this._vertexFormat);
+ this._initVDataCount = data.vertexCount * this._vertexBytes;
+ this._initIDataCount = data.indexCount;
+ this._reallocBuffer();
+ }
+
+ public uploadData () {
+ if (this.byteOffset === 0 || !this._dirty) {
+ return;
+ }
+
+ // update vertext data
+ // const vertexsData = new Float32Array(this.vData!.buffer, 0, this.byteOffset >> 2);
+ // const indicesData = new Uint16Array(this.iData!.buffer, 0, this.indiceOffset);
+
+ // const vb = this._vb;
+ // vb.update(0, vertexsData);
+
+ // const ib = this._ib;
+ // ib.update(0, indicesData);
+
+ this._dirty = false;
+ }
+
+ public requestStatic (vertexCount, indiceCount) {
+ const byteOffset = this.byteOffset + vertexCount * this._vertexBytes;
+ const indiceOffset = this.indiceOffset + indiceCount;
+
+ let byteLength = this.vData!.byteLength;
+ let indiceLength = this.iData!.length;
+ if (byteOffset > byteLength || indiceOffset > indiceLength) {
+ while (byteLength < byteOffset || indiceLength < indiceOffset) {
+ this._initVDataCount *= 2;
+ this._initIDataCount *= 2;
+
+ byteLength = this._initVDataCount * 4;
+ indiceLength = this._initIDataCount;
+ }
+
+ this._reallocBuffer();
+ }
+
+ this.vertexOffset += vertexCount;
+ this.indiceOffset += indiceCount;
+
+ this.byteOffset = byteOffset;
+
+ this._dirty = true;
+ }
+
+ public request (vertexCount, indiceCount) {
+ // There used to be two buffer, quad and mesh, now together.
+ // if (this._renderer!.buffer !== this) {
+ // this._renderer!.flush();
+ // this._renderer!.buffer = this;
+ // }
+
+ this.requestStatic(vertexCount, indiceCount);
+ }
+
+ public _reallocBuffer () {
+ this._reallocVData(true);
+ this._reallocIData(true);
+ }
+
+ public _reallocVData (copyOldData) {
+ let oldVData;
+ if (this.vData) {
+ oldVData = new Uint8Array(this.vData.buffer);
+ }
+
+ this.vData = new Float32Array(this._initVDataCount);
+ // this.uintVData = new Uint32Array(this.vData.buffer);
+ const newData = new Uint8Array(this.vData.buffer);
+
+ if (oldVData && copyOldData) {
+ for (let i = 0, l = oldVData.length; i < l; i++) {
+ newData[i] = oldVData[i];
+ }
+ }
+
+ // this._vb._bytes = this.vData.byteLength;
+ }
+
+ public _reallocIData (copyOldData) {
+ const oldIData = this.iData;
+
+ this.iData = new Uint16Array(this._initIDataCount);
+
+ if (oldIData && copyOldData) {
+ const iData = this.iData;
+ for (let i = 0, l = oldIData.length; i < l; i++) {
+ iData[i] = oldIData[i];
+ }
+ }
+
+ // this._ib._bytes = this.iData.byteLength;
+ }
+
+ public reset () {
+ this.byteStart = 0;
+ this.byteOffset = 0;
+ this.indiceStart = 0;
+ this.indiceOffset = 0;
+ this.vertexStart = 0;
+ this.vertexOffset = 0;
+ this._dirty = false;
+ }
+
+ public destroy () {
+ // this._ib.destroy();
+ // this._vb.destroy();
+ }
+
+ private calculateBytes (vertexFormat: IGFXInputAttribute[]) {
+ let bytes = 0;
+ let num = 0;
+ for (const attr of vertexFormat) {
+ let name = GFXFormat[attr.format].toString();
+ if (name.startsWith('RGBA')) {
+ num = 4;
+ } else if (name.startsWith('RGB')) {
+ num = 3;
+ } else if (name.startsWith('RG')) {
+ num = 2;
+ } else {
+ num = 1;
+ }
+
+ name = name.substring(num);
+ switch (name) {
+ case '8I':
+ case '8UI':
+ bytes += num * 1;
+ break;
+ case '16I':
+ case '16UI':
+ bytes += num * 2;
+ break;
+ case '32I':
+ case '32UI':
+ case '32F':
+ bytes += num * 4;
+ break;
+ }
+ }
+
+ return bytes;
+ }
+}
+cc.MeshBuffer = MeshBuffer;
diff --git a/cocos/assets/CCSpriteFrame.js b/cocos/assets/CCSpriteFrame.ts
similarity index 51%
rename from cocos/assets/CCSpriteFrame.js
rename to cocos/assets/CCSpriteFrame.ts
index 70012e0056..7e8d3371d3 100644
--- a/cocos/assets/CCSpriteFrame.js
+++ b/cocos/assets/CCSpriteFrame.ts
@@ -25,19 +25,37 @@
THE SOFTWARE.
****************************************************************************/
+import { ccclass, property } from '../core/data/class-decorator';
import EventTarget from '../core/event/event-target';
-import textureUtil from './texture-util';
-import {addon} from '../core/utils/js';
+import { addon } from '../core/utils/js';
+import Rect, { rect } from '../core/value-types/rect';
+import Size, { size } from '../core/value-types/size';
+import Vec2, { v2 } from '../core/value-types/vec2';
import { Asset } from './asset';
-import {ccclass, property} from '../core/data/class-decorator';
-
+import Texture2D from './texture-2d';
+import textureUtil from './texture-util';
const INSET_LEFT = 0;
const INSET_TOP = 1;
const INSET_RIGHT = 2;
const INSET_BOTTOM = 3;
-let temp_uvs = [{u: 0, v: 0}, {u: 0, v: 0}, {u: 0, v: 0}, {u: 0, v: 0}];
+interface IUV {
+ u: number;
+ v: number;
+}
+
+interface IVertices {
+ x: any;
+ y: any;
+ triangles: any;
+ nu: number[];
+ u: number[];
+ nv: number[];
+ v: number[];
+}
+
+const temp_uvs: IUV[] = [{ u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, v: 0 }];
/**
* !#en
@@ -65,22 +83,22 @@ let temp_uvs = [{u: 0, v: 0}, {u: 0, v: 0}, {u: 0, v: 0}, {u: 0, v: 0}];
* });
*/
@ccclass('cc.SpriteFrame')
-export default class SpriteFrame extends Asset {
+export class SpriteFrame extends Texture2D {
// Use this property to set texture when loading dependency
- @property
- set _textureSetter (texture) {
- if (texture) {
- if (CC_EDITOR && !(texture instanceof cc.Texture2D)) {
- // just building
- this._texture = texture;
- return;
- }
- if (this._texture !== texture) {
- this._refreshTexture(texture);
- }
- this._textureFilename = texture.url;
- }
- }
+ // @property
+ // set _textureSetter(texture) {
+ // if (texture) {
+ // if (CC_EDITOR && !(texture instanceof cc.Texture2D)) {
+ // // just building
+ // this._texture = texture;
+ // return;
+ // }
+ // if (this._texture !== texture) {
+ // this._refreshTexture(texture);
+ // }
+ // this._textureFilename = texture.url;
+ // }
+ // }
// _textureFilename: {
// get () {
@@ -104,9 +122,9 @@ export default class SpriteFrame extends Asset {
}
set insetTop (value) {
this._capInsets[INSET_TOP] = value;
- if (this._texture) {
- this._calculateSlicedUV();
- }
+ // if (this._texture) {
+ this._calculateSlicedUV();
+ // }
}
/**
@@ -121,9 +139,9 @@ export default class SpriteFrame extends Asset {
}
set insetBottom (value) {
this._capInsets[INSET_BOTTOM] = value;
- if (this._texture) {
- this._calculateSlicedUV();
- }
+ // if (this._texture) {
+ this._calculateSlicedUV();
+ // }
}
/**
@@ -138,9 +156,9 @@ export default class SpriteFrame extends Asset {
}
set insetLeft (value) {
this._capInsets[INSET_LEFT] = value;
- if (this._texture) {
- this._calculateSlicedUV();
- }
+ // if (this._texture) {
+ this._calculateSlicedUV();
+ // }
}
/**
@@ -155,11 +173,35 @@ export default class SpriteFrame extends Asset {
}
set insetRight (value) {
this._capInsets[INSET_RIGHT] = value;
- if (this._texture) {
- this._calculateSlicedUV();
- }
+ // if (this._texture) {
+ this._calculateSlicedUV();
+ // }
}
+ public vertices: IVertices | null = null;
+
+ public uv: number[] = [];
+
+ public uvSliced: IUV[] = [];
+
+ // the location of the sprite on rendering texture
+ private _rect = new Rect();
+
+ // for trimming
+ private _offset = new Vec2();
+
+ // for trimming
+ private _originalSize = new Size();
+
+ private _rotated = false;
+
+ private _capInsets = [0, 0, 0, 0];
+
+ // store original info before packed to dynamic atlas
+ private _original = null;
+
+ private _atlasUuid?: string;
+
/**
* !#en
* Constructor of SpriteFrame class.
@@ -177,121 +219,86 @@ export default class SpriteFrame extends Asset {
// Init EventTarget data
EventTarget.call(this);
- let filename = arguments[0];
- let rect = arguments[1];
- let rotated = arguments[2];
- let offset = arguments[3];
- let originalSize = arguments[4];
+ // let filename = arguments[0];
+ const rect = arguments[0];
+ const rotated = arguments[1];
+ const offset = arguments[2];
+ const originalSize = arguments[3];
- // the location of the sprite on rendering texture
- this._rect = null;
+ // this._texture = null;
+ // this._textureFilename = '';
- // for trimming
- this._offset = null;
-
- // for trimming
- this._originalSize = null;
-
- this._rotated = false;
-
- this.vertices = null;
-
- this._capInsets = [0, 0, 0, 0];
-
- this.uv = [];
- this.uvSliced = [];
-
- this._texture = null;
- this._textureFilename = '';
-
- // store original info before packed to dynamic atlas
- this._original = null;
+ this._capInsets[INSET_BOTTOM] = 0;
+ this._capInsets[INSET_LEFT] = 0;
+ this._capInsets[INSET_RIGHT] = 1;
+ this._capInsets[INSET_TOP] = 1;
if (CC_EDITOR) {
// Atlas asset uuid
this._atlasUuid = '';
}
-
- if (filename !== undefined) {
- this.setTexture(filename, rect, rotated, offset, originalSize);
- } else {
- //todo log Error
- }
+ // if (filename !== undefined) {
+ // this.setTexture(filename, rect, rotated, offset, originalSize);
+ // } else {
+ // //todo log Error
+ // }
}
/**
* !#en Returns whether the texture have been loaded
* !#zh 返回是否已加载纹理
- * @method textureLoaded
- * @returns {boolean}
*/
- textureLoaded () {
- return this._texture && this._texture.loaded;
+ public textureLoaded () {
+ return this.loaded;
}
/**
* !#en Returns whether the sprite frame is rotated in the texture.
* !#zh 获取 SpriteFrame 是否旋转
- * @method isRotated
- * @return {Boolean}
*/
- isRotated () {
+ public isRotated () {
return this._rotated;
}
/**
* !#en Set whether the sprite frame is rotated in the texture.
* !#zh 设置 SpriteFrame 是否旋转
- * @method setRotated
- * @param {Boolean} bRotated
+ * @param value
*/
- setRotated (bRotated) {
- this._rotated = bRotated;
+ public setRotated (rotated: boolean) {
+ this._rotated = rotated;
}
/**
* !#en Returns the rect of the sprite frame in the texture.
* !#zh 获取 SpriteFrame 的纹理矩形区域
- * @method getRect
- * @return {Rect}
*/
- getRect () {
- return cc.rect(this._rect);
+ public getRect () {
+ return rect(this._rect);
}
/**
* !#en Sets the rect of the sprite frame in the texture.
* !#zh 设置 SpriteFrame 的纹理矩形区域
- * @method setRect
- * @param {Rect} rect
*/
- setRect (rect) {
+ public setRect (rect: Rect) {
this._rect = rect;
}
/**
* !#en Returns the original size of the trimmed image.
* !#zh 获取修剪前的原始大小
- * @method getOriginalSize
- * @return {Size}
*/
- getOriginalSize () {
- return cc.size(this._originalSize);
+ public getOriginalSize () {
+ return size(this._originalSize);
}
/**
* !#en Sets the original size of the trimmed image.
* !#zh 设置修剪前的原始大小
- * @method setOriginalSize
- * @param {Size} size
*/
- setOriginalSize (size) {
- if (!this._originalSize) {
- this._originalSize = cc.size(size);
- } else {
- this._originalSize.width = size.width;
- this._originalSize.height = size.height;
- }
+ public setOriginalSize (size: Size) {
+ this._originalSize.set(size);
}
/**
@@ -300,32 +307,35 @@ export default class SpriteFrame extends Asset {
* @method getTexture
* @return {Texture2D}
*/
- getTexture () {
- return this._texture;
- }
+ // getTexture() {
+ // return this._texture;
+ // }
- _textureLoadedCallback () {
- let self = this;
- let texture = this._texture;
- if (!texture) {
- // clearTexture called while loading texture...
- return;
- }
- let w = texture.width, h = texture.height;
+ public _textureLoadedCallback () {
+ const self = this;
+ // let texture = this._texture;
+ // if (!texture) {
+ // // clearTexture called while loading texture...
+ // return;
+ // }
+ // let w = texture.width, h = texture.height;
+ let w = self.width;
+ let h = self.height;
if (self._rotated && cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) {
// TODO: rotate texture for canvas
// self._texture = _ccsg.Sprite.CanvasRenderCmd._createRotatedTexture(texture, self.getRect());
self._rotated = false;
- w = self._texture.width;
- h = self._texture.height;
+ // w = self._texture.width;
+ // h = self._texture.height;
+ w = self.width;
+ h = self.height;
self.setRect(cc.rect(0, 0, w, h));
}
if (self._rect) {
- self._checkRect(self._texture);
- }
- else {
+ self._checkRect(/*self._texture*/);
+ } else {
self.setRect(cc.rect(0, 0, w, h));
}
@@ -340,7 +350,8 @@ export default class SpriteFrame extends Asset {
self._calculateUV();
// dispatch 'load' event of cc.SpriteFrame
- self.emit("load");
+ // @ts-ignore
+ self.emit('load');
}
/*
@@ -349,33 +360,31 @@ export default class SpriteFrame extends Asset {
* @method _refreshTexture
* @param {Texture2D} texture
*/
- _refreshTexture (texture) {
- this._texture = texture;
- if (texture.loaded) {
- this._textureLoadedCallback();
- }
- else {
- texture.once('load', this._textureLoadedCallback, this);
- }
- }
+ // _refreshTexture(/*texture*/) {
+ // // this._texture = texture;
+ // if (/*texture.loaded*/this.loaded) {
+ // this._textureLoadedCallback();
+ // }
+ // else {
+ // // texture.once('load', this._textureLoadedCallback, this);
+ // this.once('load', this._textureLoadedCallback, this);
+ // }
+ // }
/**
* !#en Returns the offset of the frame in the texture.
* !#zh 获取偏移量
- * @method getOffset
- * @return {Vec2}
*/
- getOffset () {
- return cc.v2(this._offset);
+ public getOffset () {
+ return v2(this._offset);
}
/**
* !#en Sets the offset of the frame in the texture.
* !#zh 设置偏移量
- * @method setOffset
- * @param {Vec2} offsets
+ * @param offsets
*/
- setOffset (offsets) {
+ public setOffset (offsets: Vec2) {
this._offset = cc.v2(offsets);
}
@@ -385,64 +394,71 @@ export default class SpriteFrame extends Asset {
* @method clone
* @return {SpriteFrame}
*/
- clone () {
- return new SpriteFrame(this._texture || this._textureFilename, this._rect, this._rotated, this._offset, this._originalSize);
- }
+ // TODO
+ // clone() {
+ // let cloneSprite = new SpriteFrame(/*this._texture || this._textureFilename,*/ this._rect, this._rotated, this._offset, this._originalSize);
+ // cloneSprite.setWrapMode(this._wrapS, this._wrapT);
+ // cloneSprite.setFilters(this._minFilter, this._magFilter);
+ // cloneSprite.setPremultiplyAlpha(this._premultiplyAlpha);
+ // cloneSprite.setAnisotropy(this._anisotropy);
+ // cloneSprite._mipmaps = this._mipmaps;
+ // return cloneSprite;
+ // }
- /**
- * !#en Set SpriteFrame with Texture, rect, rotated, offset and originalSize.
- * !#zh 通过 Texture,rect,rotated,offset 和 originalSize 设置 SpriteFrame。
- * @method setTexture
- * @param {String|Texture2D} textureOrTextureFile
- * @param {Rect} [rect=null]
- * @param {Boolean} [rotated=false]
- * @param {Vec2} [offset=cc.v2(0,0)]
- * @param {Size} [originalSize=rect.size]
- * @return {Boolean}
- */
- setTexture (textureOrTextureFile, rect, rotated, offset, originalSize) {
- if (rect) {
- this.setRect(rect);
- }
- else {
- this._rect = null;
- }
+ // /**
+ // * !#en Set SpriteFrame with Texture, rect, rotated, offset and originalSize.
+ // * !#zh 通过 Texture,rect,rotated,offset 和 originalSize 设置 SpriteFrame。
+ // * @method setTexture
+ // * @param {String|Texture2D} textureOrTextureFile
+ // * @param {Rect} [rect=null]
+ // * @param {Boolean} [rotated=false]
+ // * @param {Vec2} [offset=cc.v2(0,0)]
+ // * @param {Size} [originalSize=rect.size]
+ // * @return {Boolean}
+ // */
+ // setTexture(textureOrTextureFile, rect, rotated, offset, originalSize) {
+ // if (rect) {
+ // this.setRect(rect);
+ // }
+ // else {
+ // this._rect = null;
+ // }
- if (offset) {
- this.setOffset(offset);
- }
- else {
- this._offset = null;
- }
+ // if (offset) {
+ // this.setOffset(offset);
+ // }
+ // else {
+ // this._offset = null;
+ // }
- if (originalSize) {
- this.setOriginalSize(originalSize);
- }
- else {
- this._originalSize = null;
- }
+ // if (originalSize) {
+ // this.setOriginalSize(originalSize);
+ // }
+ // else {
+ // this._originalSize = null;
+ // }
- this._rotated = rotated || false;
+ // this._rotated = rotated || false;
- // loading texture
- let texture = textureOrTextureFile;
- if (typeof texture === 'string' && texture) {
- this._textureFilename = texture;
- this._loadTexture();
- }
- if (texture instanceof cc.Texture2D && this._texture !== texture) {
- this._refreshTexture(texture);
- }
+ // // loading texture
+ // let texture = textureOrTextureFile;
+ // if (typeof texture === 'string' && texture) {
+ // this._textureFilename = texture;
+ // this._loadTexture();
+ // }
+ // if (texture instanceof cc.Texture2D && this._texture !== texture) {
+ // this._refreshTexture(texture);
+ // }
- return true;
- }
+ // return true;
+ // }
- _loadTexture () {
- if (this._textureFilename) {
- let texture = textureUtil.loadImage(this._textureFilename);
- this._refreshTexture(texture);
- }
- }
+ // _loadTexture() {
+ // if (this._textureFilename) {
+ // let texture = textureUtil.loadImage(this._textureFilename);
+ // this._refreshTexture(texture);
+ // }
+ // }
/**
* !#en If a loading scene (or prefab) is marked as `asyncLoadAssets`, all the textures of the SpriteFrame which
@@ -462,68 +478,77 @@ export default class SpriteFrame extends Asset {
* spriteFrame.ensureLoadTexture();
* }
*/
- ensureLoadTexture () {
- if (this._texture) {
- if (!this._texture.loaded) {
- // load exists texture
- this._refreshTexture(this._texture);
- textureUtil.postLoadTexture(this._texture);
- }
- }
- else if (this._textureFilename) {
- // load new texture
- this._loadTexture();
+ public ensureLoadTexture () {
+ // if (this._texture) {
+ // if (!this._texture.loaded) {
+ if (!this.loaded) {
+ // load exists texture
+ // this._refreshTexture(/*this._texture*/);
+ textureUtil.postLoadTexture(/*this._texture*/this);
}
+ // }
+ // else if (this._textureFilename) {
+ // // load new texture
+ // this._loadTexture();
+ // }
}
- /**
- * !#en
- * If you do not need to use the SpriteFrame temporarily, you can call this method so that its texture could be garbage collected. Then when you need to render the SpriteFrame, you should call `ensureLoadTexture` manually to reload texture.
- * !#zh
- * 当你暂时不再使用这个 SpriteFrame 时,可以调用这个方法来保证引用的贴图对象能被 GC。然后当你要渲染 SpriteFrame 时,你需要手动调用 `ensureLoadTexture` 来重新加载贴图。
- *
- * @method clearTexture
- * @example
- * spriteFrame.clearTexture();
- * // when you need the SpriteFrame again...
- * spriteFrame.once('load', onSpriteFrameLoaded);
- * spriteFrame.ensureLoadTexture();
- */
- clearTexture () {
- this._texture = null; // TODO - release texture
- }
+ // /**
+ // * !#en
+ // * If you do not need to use the SpriteFrame temporarily, you can call this method so that its texture could be garbage collected. Then when you need to render the SpriteFrame, you should call `ensureLoadTexture` manually to reload texture.
+ // * !#zh
+ // * 当你暂时不再使用这个 SpriteFrame 时,可以调用这个方法来保证引用的贴图对象能被 GC。然后当你要渲染 SpriteFrame 时,你需要手动调用 `ensureLoadTexture` 来重新加载贴图。
+ // *
+ // * @method clearTexture
+ // * @example
+ // * spriteFrame.clearTexture();
+ // * // when you need the SpriteFrame again...
+ // * spriteFrame.once('load', onSpriteFrameLoaded);
+ // * spriteFrame.ensureLoadTexture();
+ // */
+ // clearTexture() {
+ // this._texture = null; // TODO - release texture
+ // }
- _checkRect (texture) {
- let rect = this._rect;
- let maxX = rect.x, maxY = rect.y;
+ public _checkRect (/*texture*/) {
+ const rect = this._rect;
+ let maxX = rect.x;
+ let maxY = rect.y;
if (this._rotated) {
maxX += rect.height;
maxY += rect.width;
- }
- else {
+ } else {
maxX += rect.width;
maxY += rect.height;
}
- if (maxX > texture.width) {
- cc.errorID(3300, texture.url + '/' + this.name, maxX, texture.width);
+ // if (maxX > texture.width) {
+ // cc.errorID(3300, texture.url + '/' + this.name, maxX, texture.width);
+ // }
+ // if (maxY > texture.height) {
+ // cc.errorID(3400, texture.url + '/' + this.name, maxY, texture.height);
+ // }
+ if (maxX > this._originalSize.width) {
+ cc.errorID(3300, /*this.url*/ + '/' + this.name, maxX, this._originalSize.width);
}
- if (maxY > texture.height) {
- cc.errorID(3400, texture.url + '/' + this.name, maxY, texture.height);
+ if (maxY > this._originalSize.height) {
+ cc.errorID(3400, /*this.url +*/ '/' + this.name, maxY, this._originalSize.height);
}
}
- _calculateSlicedUV () {
- let rect = this._rect;
- let atlasWidth = this._texture.width;
- let atlasHeight = this._texture.height;
- let leftWidth = this._capInsets[INSET_LEFT];
- let rightWidth = this._capInsets[INSET_RIGHT];
- let centerWidth = rect.width - leftWidth - rightWidth;
- let topHeight = this._capInsets[INSET_TOP];
- let bottomHeight = this._capInsets[INSET_BOTTOM];
- let centerHeight = rect.height - topHeight - bottomHeight;
+ public _calculateSlicedUV () {
+ const rect = this._rect;
+ // let atlasWidth = this._texture.width;
+ // let atlasHeight = this._texture.height;
+ const atlasWidth = this._originalSize.width;
+ const atlasHeight = this._originalSize.height;
+ const leftWidth = this._capInsets[INSET_LEFT];
+ const rightWidth = this._capInsets[INSET_RIGHT];
+ const centerWidth = rect.width - leftWidth - rightWidth;
+ const topHeight = this._capInsets[INSET_TOP];
+ const bottomHeight = this._capInsets[INSET_BOTTOM];
+ const centerHeight = rect.height - topHeight - bottomHeight;
- let uvSliced = this.uvSliced;
+ const uvSliced = this.uvSliced;
uvSliced.length = 0;
if (this._rotated) {
temp_uvs[0].u = (rect.x) / atlasWidth;
@@ -536,17 +561,16 @@ export default class SpriteFrame extends Asset {
temp_uvs[0].v = (rect.y + rect.width) / atlasHeight;
for (let row = 0; row < 4; ++row) {
- let rowD = temp_uvs[row];
+ const rowD = temp_uvs[row];
for (let col = 0; col < 4; ++col) {
- let colD = temp_uvs[3 - col];
+ const colD = temp_uvs[3 - col];
uvSliced.push({
u: rowD.u,
- v: colD.v
+ v: colD.v,
});
}
}
- }
- else {
+ } else {
temp_uvs[0].u = (rect.x) / atlasWidth;
temp_uvs[1].u = (rect.x + leftWidth) / atlasWidth;
temp_uvs[2].u = (rect.x + leftWidth + centerWidth) / atlasWidth;
@@ -557,30 +581,32 @@ export default class SpriteFrame extends Asset {
temp_uvs[0].v = (rect.y + rect.height) / atlasHeight;
for (let row = 0; row < 4; ++row) {
- let rowD = temp_uvs[row];
+ const rowD = temp_uvs[row];
for (let col = 0; col < 4; ++col) {
- let colD = temp_uvs[col];
+ const colD = temp_uvs[col];
uvSliced.push({
u: colD.u,
- v: rowD.v
+ v: rowD.v,
});
}
}
}
}
- _calculateUV () {
- let rect = this._rect,
- texture = this._texture,
- uv = this.uv,
- texw = texture.width,
- texh = texture.height;
+ public _calculateUV () {
+ const rect = this._rect;
+ // texture = this._texture,
+ const uv = this.uv;
+ // texw = texture.width,
+ // texh = texture.height;
+ const texw = this._originalSize.width;
+ const texh = this._originalSize.height;
if (this._rotated) {
- let l = texw === 0 ? 0 : rect.x / texw;
- let r = texw === 0 ? 0 : (rect.x + rect.height) / texw;
- let b = texh === 0 ? 0 : (rect.y + rect.width) / texh;
- let t = texh === 0 ? 0 : rect.y / texh;
+ const l = texw === 0 ? 0 : rect.x / texw;
+ const r = texw === 0 ? 0 : (rect.x + rect.height) / texw;
+ const b = texh === 0 ? 0 : (rect.y + rect.width) / texh;
+ const t = texh === 0 ? 0 : rect.y / texh;
uv[0] = l;
uv[1] = t;
uv[2] = l;
@@ -589,12 +615,11 @@ export default class SpriteFrame extends Asset {
uv[5] = t;
uv[6] = r;
uv[7] = b;
- }
- else {
- let l = texw === 0 ? 0 : rect.x / texw;
- let r = texw === 0 ? 0 : (rect.x + rect.width) / texw;
- let b = texh === 0 ? 0 : (rect.y + rect.height) / texh;
- let t = texh === 0 ? 0 : rect.y / texh;
+ } else {
+ const l = texw === 0 ? 0 : rect.x / texw;
+ const r = texw === 0 ? 0 : (rect.x + rect.width) / texw;
+ const b = texh === 0 ? 0 : (rect.y + rect.height) / texh;
+ const t = texh === 0 ? 0 : rect.y / texh;
uv[0] = l;
uv[1] = b;
uv[2] = r;
@@ -605,13 +630,13 @@ export default class SpriteFrame extends Asset {
uv[7] = t;
}
- let vertices = this.vertices;
+ const vertices = this.vertices;
if (vertices) {
vertices.nu.length = 0;
vertices.nv.length = 0;
for (let i = 0; i < vertices.u.length; i++) {
- vertices.nu[i] = vertices.u[i]/texw;
- vertices.nv[i] = vertices.v[i]/texh;
+ vertices.nu[i] = vertices.u[i] / texw;
+ vertices.nv[i] = vertices.v[i] / texh;
}
}
@@ -620,22 +645,26 @@ export default class SpriteFrame extends Asset {
// SERIALIZATION
- _serialize (exporting) {
- let rect = this._rect;
- let offset = this._offset;
- let size = this._originalSize;
- let uuid;
- let texture = this._texture;
- if (texture) {
- uuid = texture._uuid;
- }
- if (!uuid) {
- let url = this._textureFilename;
- if (url) {
- uuid = Editor.Utils.UuidCache.urlToUuid(url);
- }
- }
+ // @ts-ignore
+ // TODO:
+ public _serialize (exporting) {
+ const rect = this._rect;
+ const offset = this._offset;
+ const size = this._originalSize;
+ let uuid = this._uuid;
+ // let texture = this._texture;
+ // if (texture) {
+ // uuid = texture._uuid;
+ // }
+ // if (!uuid) {
+ // let url = this._textureFilename;
+ // if (url) {
+ // uuid = Editor.Utils.UuidCache.urlToUuid(url);
+ // }
+ // }
if (uuid && exporting) {
+ // @ts-ignore
+ // TODO:
uuid = Editor.Utils.UuidUtils.compressUuid(uuid, true);
}
@@ -646,11 +675,12 @@ export default class SpriteFrame extends Asset {
x: this.vertices.x,
y: this.vertices.y,
u: this.vertices.u,
- v: this.vertices.v
+ v: this.vertices.v,
};
}
return {
+ base: super._serialize(),
name: this._name,
texture: uuid || undefined,
atlas: exporting ? undefined : this._atlasUuid, // strip from json if exporting
@@ -659,17 +689,18 @@ export default class SpriteFrame extends Asset {
originalSize: size ? [size.width, size.height] : undefined,
rotated: this._rotated ? 1 : undefined,
capInsets: this._capInsets,
- vertices: vertices
+ vertices,
};
}
- _deserialize (data, handle) {
- let rect = data.rect;
+ public _deserialize (data, handle) {
+ super._deserialize(data.base, handle);
+ const rect = data.rect;
if (rect) {
- this.setRect(new cc.Rect(rect[0], rect[1], rect[2], rect[3]));
+ this.setRect(new Rect(rect[0], rect[1], rect[2], rect[3]));
}
if (data.offset) {
- this.setOffset(new cc.Vec2(data.offset[0], data.offset[1]));
+ this.setOffset(new Vec2(data.offset[0], data.offset[1]));
}
if (data.originalSize) {
this.setOriginalSize(new cc.Size(data.originalSize[0], data.originalSize[1]));
@@ -677,7 +708,7 @@ export default class SpriteFrame extends Asset {
this._rotated = data.rotated === 1;
this._name = data.name;
- let capInsets = data.capInsets;
+ const capInsets = data.capInsets;
if (capInsets) {
this._capInsets[INSET_LEFT] = capInsets[INSET_LEFT];
this._capInsets[INSET_TOP] = capInsets[INSET_TOP];
@@ -697,18 +728,35 @@ export default class SpriteFrame extends Asset {
}
// load texture via _textureSetter
- let textureUuid = data.texture;
- if (textureUuid) {
- handle.result.push(this, '_textureSetter', textureUuid);
- }
+ // let textureUuid = data.texture;
+ // if (textureUuid) {
+ // handle.result.push(this, '_textureSetter', textureUuid);
+ // }
}
+
+ public onLoaded () {
+ this.loaded = true;
+ if (super.onLoaded) {
+ super.onLoaded();
+ }
+
+ this._textureLoadedCallback();
+ }
+
+ public copyWithZone (...args: any[]) {
+ // return this.clone(...args);
+ }
+
+ public copy (...args: any[]) {
+ // return this.clone(...args);
+ }
+
+ // public initWithTexture (...args: any[]) {
+ // return this.setTexture(...args);
+ // }
}
-let proto = SpriteFrame.prototype;
-
-proto.copyWithZone = proto.clone;
-proto.copy = proto.clone;
-proto.initWithTexture = proto.setTexture;
+const proto = SpriteFrame.prototype;
addon(proto, EventTarget.prototype);
diff --git a/cocos/assets/index.js b/cocos/assets/index.js
index 1124f26705..b4981657a6 100644
--- a/cocos/assets/index.js
+++ b/cocos/assets/index.js
@@ -29,7 +29,7 @@ export { Asset } from './asset';
export {default as Prefab} from './CCPrefab';
export * from './CCScripts';
export {default as SceneAsset} from './CCSceneAsset';
-export {default as SpriteFrame} from './CCSpriteFrame';
+export { SpriteFrame } from './CCSpriteFrame';
export {default as SpriteAtlas} from './CCSpriteAtlas';
export {default as TextAsset} from './CCTextAsset';
export {default as JsonAsset} from './CCJsonAsset';
diff --git a/cocos/components/CCCanvas.js b/cocos/components/CCCanvas.js
deleted file mode 100644
index 6fe2a72a16..0000000000
--- a/cocos/components/CCCanvas.js
+++ /dev/null
@@ -1,243 +0,0 @@
-/****************************************************************************
- Copyright (c) 2013-2016 Chukong Technologies Inc.
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos.com
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated engine source code (the "Software"), a limited,
- worldwide, royalty-free, non-assignable, revocable and non-exclusive license
- to use Cocos Creator solely to develop games on your target platforms. You shall
- not use Cocos Creator software for developing other software or tools that's
- used for developing games. You are not granted to publish, distribute,
- sublicense, and/or sell copies of Cocos Creator.
-
- The software or tools in this License Agreement are licensed, not sold.
- Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-import Camera from '../camera/CCCamera';
-import { Component } from './component';
-import {ccclass, property, executeInEditMode, menu, help, disallowMultiple} from '../core/data/class-decorator';
-
-/**
- * !#zh: 作为 UI 根节点,为所有子节点提供视窗四边的位置信息以供对齐,另外提供屏幕适配策略接口,方便从编辑器设置。
- * 注:由于本节点的尺寸会跟随屏幕拉伸,所以 anchorPoint 只支持 (0.5, 0.5),否则适配不同屏幕时坐标会有偏差。
- *
- * @class Canvas
- * @extends Component
- */
-@ccclass('cc.Canvas')
-@menu('UI/Canvas')
-@help('i18n:COMPONENT.help_url.canvas')
-@executeInEditMode
-@disallowMultiple
-export default class Canvas extends Component {
- /**
- * !#en Current active canvas, the scene should only have one active canvas at the same time.
- * !#zh 当前激活的画布组件,场景同一时间只能有一个激活的画布。
- * @property {Canvas} instance
- * @static
- */
- static instance = null;
-
- /**
- * !#en The desigin resolution for current scene.
- * !#zh 当前场景设计分辨率。
- * @property {Size} designResolution
- * @default new cc.Size(960, 640)
- */
- @property
- _designResolution = cc.size(960, 640);
- @property({
- tooltip: CC_DEV && 'i18n:COMPONENT.canvas.design_resolution',
- type: cc.Size
- })
- get designResolution () {
- return cc.size(this._designResolution);
- }
- set designResolution (value) {
- this._designResolution.width = value.width;
- this._designResolution.height = value.height;
- this.applySettings();
- this.alignWithScreen();
- }
-
- @property
- _fitWidth = false;
- @property
- _fitHeight = true;
-
- /**
- * !#en TODO
- * !#zh: 是否优先将设计分辨率高度撑满视图高度。
- * @property {Boolean} fitHeight
- * @default false
- */
- @property({
- tooltip: CC_DEV && 'i18n:COMPONENT.canvas.fit_height'
- })
- get fitHeight () {
- return this._fitHeight;
- }
- set fitHeight (value) {
- if (this._fitHeight !== value) {
- this._fitHeight = value;
- this.applySettings();
- this.alignWithScreen();
- }
- }
-
- /**
- * !#en TODO
- * !#zh: 是否优先将设计分辨率宽度撑满视图宽度。
- * @property {Boolean} fitWidth
- * @default false
- */
- @property({
- tooltip: CC_DEV && 'i18n:COMPONENT.canvas.fit_width'
- })
- get fitWidth () {
- return this._fitWidth;
- }
- set fitWidth (value) {
- if (this._fitWidth !== value) {
- this._fitWidth = value;
- this.applySettings();
- this.alignWithScreen();
- }
- }
-
- constructor () {
- super();
- this._thisOnResized = this.alignWithScreen.bind(this);
- }
-
- resetInEditor () {
- _Scene._applyCanvasPreferences(this);
- }
-
- __preload () {
- if (CC_DEV) {
- var Flags = cc.Object.Flags;
- this._objFlags |= (Flags.IsPositionLocked | Flags.IsAnchorLocked | Flags.IsSizeLocked);
- }
-
- if (Canvas.instance) {
- return cc.errorID(6700,
- this.node.name, Canvas.instance.node.name);
- }
- Canvas.instance = this;
-
- if (CC_EDITOR) {
- cc.engine.on('design-resolution-changed', this._thisOnResized);
- }
- else {
- if (cc.sys.isMobile) {
- window.addEventListener('resize', this._thisOnResized);
- }
- else {
- cc.view.on('canvas-resize', this._thisOnResized);
- }
- }
-
- this.applySettings();
- this.alignWithScreen();
-
- // Camera could be removed in canvas render mode
- // let cameraNode = cc.find('Main Camera', this.node);
- // if (!cameraNode) {
- // cameraNode = new cc.Node('Main Camera');
- // cameraNode.parent = this.node;
- // cameraNode.setSiblingIndex(0);
- // }
- // let camera = cameraNode.getComponent(Camera);
- // if (!camera) {
- // camera = cameraNode.addComponent(Camera);
-
- // let ClearFlags = Camera.ClearFlags;
- // camera.clearFlags = ClearFlags.COLOR | ClearFlags.DEPTH | ClearFlags.STENCIL;
- // camera.depth = -1;
- // }
- // Camera.main = camera;
- }
-
- onDestroy () {
- if (CC_EDITOR) {
- cc.engine.off('design-resolution-changed', this._thisOnResized);
- }
- else {
- if (cc.sys.isMobile) {
- window.removeEventListener('resize', this._thisOnResized);
- }
- else {
- cc.view.off('canvas-resize', this._thisOnResized);
- }
- }
-
- if (Canvas.instance === this) {
- Canvas.instance = null;
- }
- }
-
- //
-
- alignWithScreen () {
- var designSize, nodeSize;
- if (CC_EDITOR) {
- nodeSize = designSize = cc.engine.getDesignResolutionSize();
- this.node.setPosition(designSize.width * 0.5, designSize.height * 0.5, 1);
- }
- else {
- var canvasSize = nodeSize = cc.visibleRect;
- designSize = cc.view.getDesignResolutionSize();
- var clipTopRight = !this.fitHeight && !this.fitWidth;
- var offsetX = 0;
- var offsetY = 0;
- if (clipTopRight) {
- // offset the canvas to make it in the center of screen
- offsetX = (designSize.width - canvasSize.width) * 0.5;
- offsetY = (designSize.height - canvasSize.height) * 0.5;
- }
- this.node.setPosition(canvasSize.width * 0.5 + offsetX, canvasSize.height * 0.5 + offsetY, 1);
- }
- this.node.width = nodeSize.width;
- this.node.height = nodeSize.height;
- }
-
- applySettings () {
- var ResolutionPolicy = cc.ResolutionPolicy;
- var policy;
-
- if (this.fitHeight && this.fitWidth) {
- policy = ResolutionPolicy.SHOW_ALL;
- }
- else if (!this.fitHeight && !this.fitWidth) {
- policy = ResolutionPolicy.NO_BORDER;
- }
- else if (this.fitWidth) {
- policy = ResolutionPolicy.FIXED_WIDTH;
- }
- else { // fitHeight
- policy = ResolutionPolicy.FIXED_HEIGHT;
- }
-
- var designRes = this._designResolution;
- if (CC_EDITOR) {
- cc.engine.setDesignResolutionSize(designRes.width, designRes.height);
- }
- else {
- cc.view.setDesignResolutionSize(designRes.width, designRes.height, policy);
- }
- }
-}
-
-cc.Canvas = Canvas;
diff --git a/cocos/components/component.d.ts b/cocos/components/component.d.ts
index 86adf832b7..746c5890cc 100644
--- a/cocos/components/component.d.ts
+++ b/cocos/components/component.d.ts
@@ -49,4 +49,8 @@ export class Component extends CCObject {
public scheduleOnce(callback: Function, delay: number): void;
public unschedule(callback: Function): void;
public unscheduleAllCallbacks(): void;
+
+ // friend to class BaseNode
+ public _id: string;
+ public _enabled: boolean;
}
diff --git a/cocos/core/data/object.d.ts b/cocos/core/data/object.d.ts
index 463c47b429..698ce0a7a5 100644
--- a/cocos/core/data/object.d.ts
+++ b/cocos/core/data/object.d.ts
@@ -28,13 +28,13 @@ export class CCObject {
protected _name: string;
protected _objFlags: number;
- public constructor(name: string);
+ public constructor(name?: string);
public name: string;
public isValid: boolean;
public isRealValid: boolean;
- public destroy(): boolean;
+ public destroy(): any;
public realDestroyInEditor(): void;
public _clearDeferredDestroyTimer(): void;
@@ -43,6 +43,6 @@ export class CCObject {
protected _serialize?(): any;
protected _deserialize?(data: any, ctx: any): any;
- protected _onPreDestroy: () => void | null;
+ protected _onPreDestroy (): any;
protected Flags: object;
}
diff --git a/cocos/core/event/callbacks-invoker-base.ts b/cocos/core/event/callbacks-invoker-base.ts
new file mode 100644
index 0000000000..a9a871de01
--- /dev/null
+++ b/cocos/core/event/callbacks-invoker-base.ts
@@ -0,0 +1,241 @@
+/****************************************************************************
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos.com
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated engine source code (the "Software"), a limited,
+ worldwide, royalty-free, non-assignable, revocable and non-exclusive license
+ to use Cocos Creator solely to develop games on your target platforms. You shall
+ not use Cocos Creator software for developing other software or tools that's
+ used for developing games. You are not granted to publish, distribute,
+ sublicense, and/or sell copies of Cocos Creator.
+
+ The software or tools in this License Agreement are licensed, not sold.
+ Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+import * as js from '../utils/js';
+const fastRemoveAt = js.array.fastRemoveAt;
+
+type Constructor