diff --git a/.eslintrc.json b/.eslintrc.json
index 705297c9a8..f53f8b7076 100644
--- a/.eslintrc.json
+++ b/.eslintrc.json
@@ -23,19 +23,20 @@
"globals": {
"cc": false,
"wx": false,
- "CC_EDITOR": false,
- "CC_DEV": false,
- "CC_JSB": false,
- "CC_PREVIEW": false,
- "CC_DEBUG": false,
"CC_BUILD": false,
+ "CC_TEST": false,
+ "CC_EDITOR": false,
+ "CC_PREVIEW": false,
+ "CC_DEV": false,
+ "CC_DEBUG": false,
+ "CC_JSB": false,
+ "CC_WECHATGAME_SUB": false,
"CC_WECHATGAME": false,
"CC_QQPLAY": false,
"CC_RUNTIME": false,
"CC_SUPPORT_JIT": false,
- "CC_PREVIEW": false,
- "CC_PREVIEW": false,
- "CC_PREVIEW": false,
+ "Editor": false,
+ "_Scene": false,
"_ccsg": false
}
}
diff --git a/.gitignore b/.gitignore
index ca53b140ee..d57d13d67d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -10,6 +10,8 @@ node_modules
/package
/tools/jsdoc_toolkit/jsdoc_toolkit-2.4.0
/.project
+/dist
npm-debug.log
DebugInfos.json
/rollup/out
+/package-lock.json
diff --git a/CHANGELOG.txt b/CHANGELOG.txt
index 6c0475d26c..ea43954e0f 100644
--- a/CHANGELOG.txt
+++ b/CHANGELOG.txt
@@ -1,7 +1,7 @@
ChangeLog:
Cocos2d-x v3.8 @ September.6 2015
-
+
[NEW] spine: Supported Spine runtime 2.3 (Both native and web engine)
[NEW] Animate: Added Animate's getCurrentFrameIndex function
[NEW] network: Upgrade SocketIO support to v1.x
@@ -58,9 +58,9 @@ Cocos2d-x v3.7.1 @ August.12 2015
Cocos2d-x v3.7 Final @ July 20 2015
[REFINE] web: Add compatible Uint16Array defintion
-
+
[FIX] web: Fixed url check regular expression not supporting localhost issue
- [FIX] web: Fixed issue that sprite doesn't update texture rect correctly
+ [FIX] web: Fixed issue that sprite doesn't update texture rect correctly
Cocos2d-x v3.7 RC1 @ July 14 2015
[REFINE] Improved localStorage warning when disabled
@@ -181,9 +181,9 @@ Cocos2d-JS v3.5 @ April 1 2015
* Replaced '==' with '===' for better performance.
* Added `path` parameter in `ccs.load` to support modifying cocostudio project resource path.
* Added animationList to Cocostudio ActionTimeline to support playing animation by name.
-* Made ParticleSystem support creation from an map object.
+* Made ParticleSystem support creation from an map object.
* Added missing functions to `cc.Grid3D` and `cc.PageTurn3D`.
-* Added tip message functions to `cc.TextFieldTTF` for mobile browser.
+* Added tip message functions to `cc.TextFieldTTF` for mobile browser.
* Added a function `cc.sys.openURL`.
* Disabled retina display by default for better performance.
* Added Bower support.
@@ -192,15 +192,15 @@ Cocos2d-JS v3.5 @ April 1 2015
* Bug fixes:
1. Fixed a bug of chipmunk.js that it doesn't work under closure compiler advanced mode.
2. Fixed a bug of Cocos Studio parser that widget didn't set its layout component.
- 3. Fixed grammatical mistakes in cocostudio parser logs.
+ 3. Fixed grammatical mistakes in cocostudio parser logs.
4. Fixed memory leak issue in `cc.LabelBMFont`.
5. Fixed a bug of `cc.Scale9Sprite` that its `updateDisplayColor` doesn't take effect.
6. Fixed a bug of Cocos Studio parser that `cc.Scale9Sprite` doesn't display correctly if its texture isn't preloaded.
- 7. Fixed a bug of `cc.MenuItemSprite` that the construction will fail when parameter `selectedSprite` is a Scale9Sprite instance.
+ 7. Fixed a bug of `cc.MenuItemSprite` that the construction will fail when parameter `selectedSprite` is a Scale9Sprite instance.
8. Fixed a bug of Cocos Studio parser that the background color of `ccui.Layout` can't be parsed correctly.
9. Fixed a bug of `cc.ClippingNode` that it doesn't work when set `inverted` to true in Canvas Mode.
10. Fixed a bug of `ccs.Armature` that its name was modified to animation name when loading from json files.
- 11. Fixed a bug of `ccui.PageView` that it cancel child touch during movment of page view.
+ 11. Fixed a bug of `ccui.PageView` that it cancel child touch during movment of page view.
12. Fixed a bug of `cc.Scheduler` that its parameter `repeat` is invalid in schedule function.
13. Fixed a bug of `cc.Scheduler` that `unschedule` function may fail.
@@ -225,19 +225,19 @@ Cocos2d-JS v3.4 Beta0 @ March 19 2015
1. Added `getSpriteFrame` to `cc.Sprite` to fix API inconsistency.
2. Added `getObject` to `cc.TMXObjectGroup` to fix API inconsistency.
3. Added `addImageAsync` to `cc.textureCache` to fix API inconsistency.
- 4. Fixed a bug of `cc.text` that its default font name is incorrect.
+ 4. Fixed a bug of `cc.text` that its default font name is incorrect.
5. Fixed a bug of `ccui.PageView` that its `getPage` doesn't work.
6. Fixed a bug of `ccui.ImageView` that its `loadTexture` doesn't work while it's invoked multiple times at the same frame.
7. Fixed a bug of `ccui` that its load event callbacks have some mistakes.
8. Fixed a bug of `cc.Layer` that its bake function doesn't work when the layer has a parent node.
9. Fixed typos in `cc.ClippingNode.WebGLRenderCmd` and `cc.ParticleSystem.WebGLRenderCmd` creation.
- 10. Fixed a bug of `cc.Sprite` in `setTextureRect`.
+ 10. Fixed a bug of `cc.Sprite` in `setTextureRect`.
11. Fixed a bug of `cc.Screen`.
12. Fixed a bug of `cc.view` that it doesn't work on iOS 8.1.2.
- 13. Fixed a bug of cc.DrawNode that its lineWidth is always to default value when set linewidth to zero.
- 14. Fixed a bug in hack for particles performance on canvas.
+ 13. Fixed a bug of cc.DrawNode that its lineWidth is always to default value when set linewidth to zero.
+ 14. Fixed a bug in hack for particles performance on canvas.
15. Fixed a bug of `cc.audioEngine` that it doesn't work after minified/compiled.
- 16. Fixed a bug in `CCBoot.js` that WebGL is not activated in web view of iOS 8.
+ 16. Fixed a bug in `CCBoot.js` that WebGL is not activated in web view of iOS 8.
17. Fixed a bug of `cc.CheckBox` that its position is incorrect when its texture isn't preloaded.
18. Fixed a bug of `cc.TMXLayer` that it stops to work after `setTileGID` called.
19. Fixed a bug of Cocos parser 2.x that it doesn't set widget's LayoutComponent.
@@ -247,16 +247,16 @@ Cocos2d-JS v3.3 @ Feb.9, 2015
* Upgraded spine runtime to support the latest version and updated its test case.
* Added an option "noCache" for debugging on browsers.
-* Set the default value of `cc.ParticleSystem`'s draw mode to texture mode.
+* Set the default value of `cc.ParticleSystem`'s draw mode to texture mode.
* Added message to `ccs.load` when loading armature json file.
* Improved particle system test case.
* Bug fixes:
- 1. Fixed a bug of `cc.Sprite` that its `setSpriteFrame` doesn't work when sprite frame's `rotated` property is true.
+ 1. Fixed a bug of `cc.Sprite` that its `setSpriteFrame` doesn't work when sprite frame's `rotated` property is true.
2. Fixed a bug of `cc.ClippingNode` when its stencil is `cc.Node` object in canvas mode.
3. Fixed a ccui bug that the position of widgets is incorrect after loaded v2.x json file with `ccs.load`.
- 4. Fixed a bug of `cc.PhysicsSprite` that `setIgnoreBodyRotation` function doesn't work.
- 5. Fixed a bug of `ccui.Button` that setting pressed texture doesn't work when scale9 enabled.
+ 4. Fixed a bug of `cc.PhysicsSprite` that `setIgnoreBodyRotation` function doesn't work.
+ 5. Fixed a bug of `ccui.Button` that setting pressed texture doesn't work when scale9 enabled.
6. Fixed a bug of `ccui.ScrollView` that its `dir` property is null when passing `DIR_NONE` as `direction` in `_endRecordSlidAction` function.
Cocos2d-JS v3.3 RC0 @ Feb.1, 2015
@@ -309,7 +309,7 @@ Cocos2d-JS v3.3 Beta @ Jan.24, 2015
9. Fixed a bug of `cc.audioEngine` that its loading path is incorrect.
10. Fixed a bug of `ccui.Widget` that it can't touch when it's reused.
11. Fixed a bug of UI system that the `setNormalizedPosition` doesn't work.
- 12. Fixed a bug of `cc.ActionInterval` that its `_times` conflict with `cc.Blink`.
+ 12. Fixed a bug of `cc.ActionInterval` that its `_times` conflict with `cc.Blink`.
13. Fixed release texture issue in canvas mode.
14. Fixed a bug of `ccs.actionManager` that its `getActionByName` doesn't work.
15. Fixed a bug of `cc.Sprite` that it can't draw without texture on WebGL mode.
@@ -656,7 +656,7 @@ Cocos2d-html5-v3.0 alpha @ March.15, 2014
* Replace `replaceWithScene` and `runWithScene` with `runScene`.
* move sys.xxx to cc.sys.xxx.
* Refactor CCEGLView.js for better maintainability.
-* Refactor CCScheduler.js for better maintainability.
+* Refactor scheduler.js for better maintainability.
* Remove arguments.callee which is forbidden in ECMAScript strict mode.
* Refactor Array clean function for better performance.
* Refactor some functions about array operation.
diff --git a/EngineErrorMap.md b/EngineErrorMap.md
index 0726b09fc4..de7c7a4c46 100644
--- a/EngineErrorMap.md
+++ b/EngineErrorMap.md
@@ -276,7 +276,7 @@ warning: you CANNOT change update priority in scheduled function
### 1507
-CCScheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f
+scheduler#scheduleSelector. Selector already scheduled. Updating interval from: %.4f to %.4f
### 1508
diff --git a/cocos/2d/base-ui/CCWidgetManager.js b/cocos/2d/base-ui/widget-manager.ts
similarity index 55%
rename from cocos/2d/base-ui/CCWidgetManager.js
rename to cocos/2d/base-ui/widget-manager.ts
index 5bbf5785f8..7f3d37d7cc 100644
--- a/cocos/2d/base-ui/CCWidgetManager.js
+++ b/cocos/2d/base-ui/widget-manager.ts
@@ -2,7 +2,7 @@
Copyright (c) 2013-2016 Chukong Technologies Inc.
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,
@@ -23,41 +23,48 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
+// import { WidgetComponent } from '../../3d/ui/components/widget-component';
+import { array } from '../../core/utils/js';
+import { Enum, Size, Vec3 } from '../../core/value-types';
+import { Node } from '../../scene-graph/node';
+const Event = Node.EventType;
-var Event = require('../CCNode').EventType;
+const TOP = 1 << 0;
+const MID = 1 << 1; // vertical center
+const BOT = 1 << 2;
+const LEFT = 1 << 3;
+const CENTER = 1 << 4; // horizontal center
+const RIGHT = 1 << 5;
+const HORIZONTAL = LEFT | CENTER | RIGHT;
+const VERTICAL = TOP | MID | BOT;
-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;
-
-var AlignMode = cc.Enum({
- ONCE: 0,
- ON_WINDOW_RESIZE: 1,
- ALWAYS: 2,
-});
-
-// returns a readonly size of the node
-function getReadonlyNodeSize (parent) {
- if (parent instanceof cc.Scene) {
- return CC_EDITOR ? cc.engine.getDesignResolutionSize() : cc.visibleRect;
- }
- else {
- return parent._contentSize;
- }
+enum AlignMode {
+ ONCE = 0,
+ ON_WINDOW_RESIZE = 1,
+ ALWAYS = 2,
}
-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;;) {
- var pos = node._position;
+Enum(AlignMode);
+
+// returns a readonly size of the node
+export function getReadonlyNodeSize (parent) {
+ // TODO: check with Editor
+ // if (parent instanceof cc.Scene) {
+ // return CC_EDITOR ? cc.engine.getDesignResolutionSize() : cc.visibleRect;
+ // } else {
+ // return parent._contentSize;
+ // }
+
+ return cc.visibleRect;
+}
+
+export function computeInverseTransForTarget (widgetNode, target, out_inverseTranslate, out_inverseScale) {
+ let scaleX = widgetNode._parent._scale.x;
+ let scaleY = widgetNode._parent._scale.y;
+ let translateX = 0;
+ let translateY = 0;
+ for (let node = widgetNode._parent; ;) {
+ const pos = node._position;
translateX += pos.x;
translateY += pos.y;
node = node._parent; // loop increment
@@ -68,14 +75,13 @@ function computeInverseTransForTarget (widgetNode, target, out_inverseTranslate,
return;
}
if (node !== target) {
- var sx = node._scale.x;
- var sy = node._scale.y;
+ const sx = node._scale.x;
+ const sy = node._scale.y;
translateX *= sx;
translateY *= sy;
scaleX *= sx;
scaleY *= sy;
- }
- else {
+ } else {
break;
}
}
@@ -85,38 +91,40 @@ function computeInverseTransForTarget (widgetNode, target, out_inverseTranslate,
out_inverseTranslate.y = -translateY;
}
-var tInverseTranslate = cc.Vec2.ZERO;
-var tInverseScale = cc.Vec2.ONE;
+const tInverseTranslate = cc.Vec2.ZERO;
+const tInverseScale = cc.Vec2.ONE;
// align to borders by adjusting node's position and size (ignore rotation)
function align (node, widget) {
- var hasTarget = widget._target;
- var target;
- var inverseTranslate, inverseScale;
+ const hasTarget = widget._target;
+ let target;
+ let inverseTranslate;
+ let inverseScale;
if (hasTarget) {
target = hasTarget;
inverseTranslate = tInverseTranslate;
inverseScale = tInverseScale;
computeInverseTransForTarget(node, target, inverseTranslate, inverseScale);
- }
- else {
+ } else {
target = node._parent;
}
- var targetSize = getReadonlyNodeSize(target);
- var targetAnchor = target._anchorPoint;
+ const targetSize = getReadonlyNodeSize(target);
+ const targetAnchor = target._anchorPoint;
- var isRoot = !CC_EDITOR && target instanceof cc.Scene;
- var x = node._position.x, y = node._position.y;
- var anchor = node._anchorPoint;
+ const isRoot = !CC_EDITOR && target instanceof cc.Scene;
+ let x = node._position.x;
+ let y = node._position.y;
+ const anchor = node._anchorPoint;
if (widget._alignFlags & HORIZONTAL) {
- var localLeft, localRight, targetWidth = targetSize.width;
+ let localLeft;
+ let localRight;
+ const targetWidth = targetSize.width;
if (isRoot) {
localLeft = cc.visibleRect.left.x;
localRight = cc.visibleRect.right.x;
- }
- else {
+ } else {
localLeft = -targetAnchor.x * targetWidth;
localRight = localLeft + targetWidth;
}
@@ -132,7 +140,9 @@ function align (node, widget) {
localRight *= inverseScale.x;
}
- var width, anchorX = anchor.x, scaleX = node._scale.x;
+ let width;
+ let anchorX = anchor.x;
+ let scaleX = node._scale.x;
if (scaleX < 0) {
anchorX = 1.0 - anchorX;
scaleX = -scaleX;
@@ -143,23 +153,21 @@ function align (node, widget) {
node.width = width / scaleX;
}
x = localLeft + anchorX * width;
- }
- else {
+ } else {
width = node.width * scaleX;
if (widget.isAlignHorizontalCenter) {
- var localHorizontalCenter = widget._isAbsHorizontalCenter ? widget._horizontalCenter : widget._horizontalCenter * targetWidth;
- var targetCenter = (0.5 - targetAnchor.x) * targetSize.width;
+ let localHorizontalCenter = widget._isAbsHorizontalCenter ?
+ widget._horizontalCenter : widget._horizontalCenter * targetWidth;
+ let targetCenter = (0.5 - targetAnchor.x) * targetSize.width;
if (hasTarget) {
localHorizontalCenter *= inverseScale.x;
targetCenter += inverseTranslate.x;
targetCenter *= inverseScale.x;
}
x = targetCenter + (anchorX - 0.5) * width + localHorizontalCenter;
- }
- else if (widget.isAlignLeft) {
+ } else if (widget.isAlignLeft) {
x = localLeft + anchorX * width;
- }
- else {
+ } else {
x = localRight + (anchorX - 1) * width;
}
}
@@ -167,12 +175,13 @@ function align (node, widget) {
if (widget._alignFlags & VERTICAL) {
- var localTop, localBottom, targetHeight = targetSize.height;
+ let localTop;
+ let localBottom;
+ const targetHeight = targetSize.height;
if (isRoot) {
localBottom = cc.visibleRect.bottom.y;
localTop = cc.visibleRect.top.y;
- }
- else {
+ } else {
localBottom = -targetAnchor.y * targetHeight;
localTop = localBottom + targetHeight;
}
@@ -189,7 +198,9 @@ function align (node, widget) {
localTop *= inverseScale.y;
}
- var height, anchorY = anchor.y, scaleY = node._scale.y;
+ let height;
+ let anchorY = anchor.y;
+ let scaleY = node._scale.y;
if (scaleY < 0) {
anchorY = 1.0 - anchorY;
scaleY = -scaleY;
@@ -200,23 +211,21 @@ function align (node, widget) {
node.height = height / scaleY;
}
y = localBottom + anchorY * height;
- }
- else {
+ } else {
height = node.height * scaleY;
if (widget.isAlignVerticalCenter) {
- var localVerticalCenter = widget._isAbsVerticalCenter ? widget._verticalCenter : widget._verticalCenter * targetHeight;
- var targetMiddle = (0.5 - targetAnchor.y) * targetSize.height;
+ let localVerticalCenter = widget._isAbsVerticalCenter ?
+ widget._verticalCenter : widget._verticalCenter * targetHeight;
+ let targetMiddle = (0.5 - targetAnchor.y) * targetSize.height;
if (hasTarget) {
localVerticalCenter *= inverseScale.y;
targetMiddle += inverseTranslate.y;
targetMiddle *= inverseScale.y;
}
y = targetMiddle + (anchorY - 0.5) * height + localVerticalCenter;
- }
- else if (widget.isAlignBottom) {
+ } else if (widget.isAlignBottom) {
y = localBottom + anchorY * height;
- }
- else {
+ } else {
y = localTop + (anchorY - 1) * height;
}
}
@@ -225,38 +234,29 @@ function align (node, widget) {
node.setPosition(x, y);
}
-function visitNode (node) {
- var widget = node._widget;
+function visitNode (node: Node) {
+ const widget = node.uiWidgetComp;
if (widget) {
if (CC_DEV) {
- var target = widget._target;
- if (target) {
- var isParent = node !== target && node.isChildOf(target);
- if (!isParent) {
- cc.errorID(6500);
- widget._target = null;
- }
- }
+ // widget._validateTargetInDEV();
}
align(node, widget);
- if ((!CC_EDITOR || animationState.animatedSinceLastFrame) && widget.alignMode !== AlignMode.ALWAYS) {
+ if ((!CC_EDITOR /*|| animationState.animatedSinceLastFrame*/) && widget.alignMode !== AlignMode.ALWAYS) {
widget.enabled = false;
- }
- else {
+ } else {
activeWidgets.push(widget);
}
}
- var children = node._children;
- for (var i = 0; i < children.length; i++) {
- var child = children[i];
- if (child._active) {
+ const children = node.children;
+ for (const child of children) {
+ if (child.active) {
visitNode(child);
}
}
}
if (CC_EDITOR) {
- var animationState = {
+ const animationState = {
previewing: false,
time: 0,
animatedSinceLastFrame: false,
@@ -265,109 +265,110 @@ if (CC_EDITOR) {
function refreshScene () {
// check animation editor
- if (CC_EDITOR && !Editor.isBuilder) {
- var AnimUtils = Editor.require('scene://utils/animation');
- var EditMode = Editor.require('scene://edit-mode');
- if (AnimUtils && EditMode) {
- var nowPreviewing = (EditMode.curMode().name === 'animation' && !!AnimUtils.Cache.animation);
- if (nowPreviewing !== animationState.previewing) {
- animationState.previewing = nowPreviewing;
- if (nowPreviewing) {
- animationState.animatedSinceLastFrame = true;
- let component = cc.engine.getInstanceById(AnimUtils.Cache.component);
- if (component) {
- let animation = component.getAnimationState(AnimUtils.Cache.animation);
- animationState.time = animation.time;
- }
- }
- else {
- animationState.animatedSinceLastFrame = false;
- }
- }
- else if (nowPreviewing) {
- let component = cc.engine.getInstanceById(AnimUtils.Cache.component);
- if (component) {
- let animation = component.getAnimationState(AnimUtils.Cache.animation);
- if (animationState.time !== animation.time) {
- animationState.animatedSinceLastFrame = true;
- animationState.time = AnimUtils.Cache.animation.time;
- }
- }
- }
- }
- }
+ // if (CC_EDITOR && !Editor.isBuilder) {
+ // const AnimUtils = Editor.require('scene://utils/animation');
+ // const EditMode = Editor.require('scene://edit-mode');
+ // if (AnimUtils && EditMode) {
+ // const nowPreviewing = (EditMode.curMode().name === 'animation' && !!AnimUtils.Cache.animation);
+ // if (nowPreviewing !== animationState.previewing) {
+ // animationState.previewing = nowPreviewing;
+ // if (nowPreviewing) {
+ // animationState.animatedSinceLastFrame = true;
+ // const component = cc.engine.getInstanceById(AnimUtils.Cache.component);
+ // if (component) {
+ // const animation = component.getAnimationState(AnimUtils.Cache.animation);
+ // animationState.time = animation.time;
+ // }
+ // } else {
+ // animationState.animatedSinceLastFrame = false;
+ // }
+ // } else if (nowPreviewing) {
+ // const component = cc.engine.getInstanceById(AnimUtils.Cache.component);
+ // if (component) {
+ // const animation = component.getAnimationState(AnimUtils.Cache.animation);
+ // if (animationState.time !== animation.time) {
+ // animationState.animatedSinceLastFrame = true;
+ // animationState.time = AnimUtils.Cache.animation.time;
+ // }
+ // }
+ // }
+ // }
+ // }
- var scene = cc.director.getScene();
+ const scene = cc.director.getScene();
if (scene) {
widgetManager.isAligning = true;
if (widgetManager._nodesOrderDirty) {
activeWidgets.length = 0;
visitNode(scene);
widgetManager._nodesOrderDirty = false;
- }
- else {
- var i, widget, iterator = widgetManager._activeWidgetsIterator;
- var AnimUtils;
- if (CC_EDITOR &&
- (AnimUtils = Editor.require('scene://utils/animation')) &&
- AnimUtils.Cache.animation) {
- var editingNode = cc.engine.getInstanceById(AnimUtils.Cache.rNode);
- if (editingNode) {
- for (i = activeWidgets.length - 1; i >= 0; i--) {
- widget = activeWidgets[i];
- var node = widget.node;
- if (widget.alignMode !== AlignMode.ALWAYS &&
- animationState.animatedSinceLastFrame &&
- node.isChildOf(editingNode)
- ) {
- // widget contains in activeWidgets should aligned at least once
- widget.enabled = false;
- }
- else {
- align(node, widget);
- }
- }
- }
- }
- else {
- // loop reversely will not help to prevent out of sync
- // because user may remove more than one item during a step.
- for (iterator.i = 0; iterator.i < activeWidgets.length; ++iterator.i) {
- widget = activeWidgets[iterator.i];
- align(widget.node, widget);
- }
- }
+ } else {
+ // // let i;
+ // let widget;
+ // const iterator = widgetManager._activeWidgetsIterator;
+ // // TODO: animation
+ // let AnimUtils;
+ // if (CC_EDITOR &&
+ // (AnimUtils = Editor.require('scene://utils/animation')) &&
+ // AnimUtils.Cache.animation) {
+ // const editingNode = cc.engine.getInstanceById(AnimUtils.Cache.rNode);
+ // if (editingNode) {
+ // for (i = activeWidgets.length - 1; i >= 0; i--) {
+ // widget = activeWidgets[i];
+ // const node = widget.node;
+ // if (widget.alignMode !== AlignMode.ALWAYS &&
+ // animationState.animatedSinceLastFrame &&
+ // node.isChildOf(editingNode)
+ // ) {
+ // // widget contains in activeWidgets should aligned at least once
+ // widget.enabled = false;
+ // } else {
+ // align(node, widget);
+ // }
+ // }
+ // }
+ // } else {
+ // // loop reversely will not help to prevent out of sync
+ // // because user may remove more than one item during a step.
+ // for (iterator.i = 0; iterator.i < activeWidgets.length; ++iterator.i) {
+ // widget = activeWidgets[iterator.i];
+ // align(widget.node, widget);
+ // }
+ // }
}
widgetManager.isAligning = false;
}
// check animation editor
if (CC_EDITOR) {
- animationState.animatedSinceLastFrame = false;
+ // animationState.animatedSinceLastFrame = false;
}
}
-var adjustWidgetToAllowMovingInEditor = CC_EDITOR && function (oldPos) {
+function adjustWidgetToAllowMovingInEditor (oldPos: Vec3) {
+ if (!CC_EDITOR) {
+ return;
+ }
+
if (widgetManager.isAligning) {
return;
}
- var newPos = this.node.position;
- var delta = newPos.sub(oldPos);
+ const newPos = this.node.position;
+ const delta = newPos.sub(oldPos);
- var target = this.node._parent;
- var inverseScale = cc.Vec2.ONE;
+ let target = this.node._parent;
+ const inverseScale = cc.Vec2.ONE;
if (this._target) {
target = this._target;
computeInverseTransForTarget(this.node, target, new cc.Vec2(), inverseScale);
}
- var targetSize = getReadonlyNodeSize(target);
- var deltaInPercent;
+ const targetSize = getReadonlyNodeSize(target);
+ let deltaInPercent;
if (targetSize.width !== 0 && targetSize.height !== 0) {
deltaInPercent = new cc.Vec2(delta.x / targetSize.width, delta.y / targetSize.height);
- }
- else {
+ } else {
deltaInPercent = cc.Vec2.ZERO;
}
@@ -389,32 +390,35 @@ var adjustWidgetToAllowMovingInEditor = CC_EDITOR && function (oldPos) {
if (this.isAlignVerticalCenter) {
this.verticalCenter += (this.isAbsoluteVerticalCenter ? delta.y : deltaInPercent.y) * inverseScale.y;
}
-};
+}
+
+function adjustWidgetToAllowResizingInEditor (oldSize: Size) {
+ if (!CC_EDITOR) {
+ return;
+ }
-var adjustWidgetToAllowResizingInEditor = CC_EDITOR && function (oldSize) {
if (widgetManager.isAligning) {
return;
}
- var newSize = this.node.getContentSize();
- var delta = cc.v2(newSize.width - oldSize.width, newSize.height - oldSize.height);
+ const newSize = this.node.getContentSize();
+ const delta = cc.v2(newSize.width - oldSize.width, newSize.height - oldSize.height);
- var target = this.node._parent;
- var inverseScale = cc.Vec2.ONE;
+ let target = this.node._parent;
+ const inverseScale = cc.Vec2.ONE;
if (this._target) {
target = this._target;
computeInverseTransForTarget(this.node, target, new cc.Vec2(), inverseScale);
}
- var targetSize = getReadonlyNodeSize(target);
- var deltaInPercent;
+ const targetSize = getReadonlyNodeSize(target);
+ let deltaInPercent;
if (targetSize.width !== 0 && targetSize.height !== 0) {
deltaInPercent = new cc.Vec2(delta.x / targetSize.width, delta.y / targetSize.height);
- }
- else {
+ } else {
deltaInPercent = cc.Vec2.ZERO;
}
- var anchor = this.node._anchorPoint;
+ const anchor = this.node._anchorPoint;
if (this.isAlignTop) {
this.top -= (this.isAbsoluteTop ? delta.y : deltaInPercent.y) * (1 - anchor.y) * inverseScale.y;
@@ -428,52 +432,51 @@ var adjustWidgetToAllowResizingInEditor = CC_EDITOR && function (oldSize) {
if (this.isAlignRight) {
this.right -= (this.isAbsoluteRight ? delta.x : deltaInPercent.x) * (1 - anchor.x) * inverseScale.x;
}
-};
+}
-var activeWidgets = [];
+const activeWidgets = [];
// updateAlignment from scene to node recursively
-function updateAlignment (node) {
- var parent = node._parent;
- if (cc.Node.isNode(parent)) {
+function updateAlignment (node: Node) {
+ const parent = node.parent;
+ if (parent && cc.Node.isNode(parent)) {
updateAlignment(parent);
}
- var widget = node._widget ||
- node.getComponent(cc.Widget); // node._widget will be null when widget is disabled
- if (widget) {
+
+ // node._widget will be null when widget is disabled
+ const widget = node.uiWidgetComp || node.getComponent(cc.WidgetComponent);
+ if (widget && parent) {
align(node, widget);
}
}
-var widgetManager = cc._widgetManager = module.exports = {
+export const widgetManager = cc._widgetManager = {
_AlignFlags: {
- TOP: TOP,
- MID: MID, // vertical center
- BOT: BOT,
- LEFT: LEFT,
- CENTER: CENTER, // horizontal center
- RIGHT: RIGHT
+ TOP,
+ MID, // vertical center
+ BOT,
+ LEFT,
+ CENTER, // horizontal center
+ RIGHT,
},
isAligning: false,
_nodesOrderDirty: false,
- _activeWidgetsIterator: new cc.js.array.MutableForwardIterator(activeWidgets),
+ _activeWidgetsIterator: new array.MutableForwardIterator(activeWidgets),
- init: function (director) {
+ init (director) {
director.on(cc.Director.EVENT_AFTER_UPDATE, refreshScene);
if (CC_EDITOR && cc.engine) {
cc.engine.on('design-resolution-changed', this.onResized.bind(this));
- }
- else {
+ } else {
if (cc.sys.isMobile) {
window.addEventListener('resize', this.onResized.bind(this));
- }
- else {
+ } else {
cc.view.on('canvas-resize', this.onResized, this);
}
}
},
- add: function (widget) {
+ add (widget) {
widget.node._widget = widget;
this._nodesOrderDirty = true;
if (CC_EDITOR && !cc.engine.isPlaying) {
@@ -481,7 +484,7 @@ var widgetManager = cc._widgetManager = module.exports = {
widget.node.on(Event.SIZE_CHANGED, adjustWidgetToAllowResizingInEditor, widget);
}
},
- remove: function (widget) {
+ remove (widget) {
widget.node._widget = null;
this._activeWidgetsIterator.remove(widget);
if (CC_EDITOR && !cc.engine.isPlaying) {
@@ -490,30 +493,24 @@ var widgetManager = cc._widgetManager = module.exports = {
}
},
onResized () {
- var scene = cc.director.getScene();
+ const scene = cc.director.getScene();
if (scene) {
this.refreshWidgetOnResized(scene);
}
},
refreshWidgetOnResized (node) {
- var widget = cc.Node.isNode(node) && node.getComponent(cc.Widget);
+ const widget = cc.Node.isNode(node) && node.getComponent(cc.Widget);
if (widget) {
if (widget.alignMode === AlignMode.ON_WINDOW_RESIZE) {
widget.enabled = true;
}
}
- var children = node._children;
- for (var i = 0; i < children.length; i++) {
- var child = children[i];
+ const children = node._children;
+ for (const child of children) {
this.refreshWidgetOnResized(child);
}
},
- updateAlignment: updateAlignment,
- AlignMode: AlignMode,
+ updateAlignment,
+ AlignMode,
};
-
-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/label-outline.ts
similarity index 57%
rename from cocos/2d/label/CCLabelOutline.js
rename to cocos/2d/label/label-outline.ts
index ae859c1545..578adefa0a 100644
--- a/cocos/2d/label/CCLabelOutline.js
+++ b/cocos/2d/label/label-outline.ts
@@ -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 class LabelOutline extends Component {
+ private _color = cc.color(255, 255, 255, 255);
+ private _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 () {
- let label = this.node.getComponent(cc.Label);
+ set width (value) {
+ this._width = value;
+ this._updateRenderData();
+ }
+
+ private _updateRenderData () {
+ const 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..2adb5d0709 100644
--- a/cocos/2d/renderer/utils/label/ttf.js
+++ b/cocos/2d/renderer/utils/label/ttf.js
@@ -23,14 +23,13 @@
THE SOFTWARE.
****************************************************************************/
-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;
+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 '../../../label/label-outline';
+const Overflow = LabelComponent.Overflow;
const WHITE = cc.Color.WHITE;
const OUTLINE_SUPPORTED = cc.js.isChildClassOf(LabelOutline, Component);
@@ -67,7 +66,7 @@ let _sharedLabelData;
//
let _canvasPool = {
pool: [],
- get () {
+ get() {
let data = this.pool.pop();
if (!data) {
@@ -81,7 +80,7 @@ let _canvasPool = {
return data;
},
- put (canvas) {
+ put(canvas) {
if (this.pool.length >= 32) {
return;
}
@@ -90,32 +89,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 +136,10 @@ module.exports = {
_texture = null;
},
- _updateVerts () {
+ _updateVerts() {
},
- _updateFontFamly (comp) {
+ _updateFontFamly(comp) {
if (!comp.useSystemFont) {
if (comp.font) {
if (comp.font._nativeAsset) {
@@ -163,12 +161,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 +176,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 +206,7 @@ module.exports = {
}
},
- _calculateFillTextStartPosition () {
+ _calculateFillTextStartPosition() {
let lineHeight = this._getLineHeight();
let lineCount = _splitedStrings.length;
let labelX;
@@ -237,7 +235,7 @@ module.exports = {
return cc.v2(labelX, firstLinelabelY);
},
- _updateTexture () {
+ _updateTexture() {
_context.clearRect(0, 0, _canvas.width, _canvas.height);
_context.font = _fontDesc;
@@ -271,10 +269,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 +294,7 @@ module.exports = {
return cc.v2(labelX, firstLinelabelY);
},
- _updateLabelDimensions () {
+ _updateLabelDimensions() {
let paragraphedStrings = _string.split('\n');
if (_overflow === Overflow.RESIZE_HEIGHT) {
@@ -323,7 +322,7 @@ module.exports = {
_canvas.height = _canvasSize.height;
},
- _calculateTextBaseline () {
+ _calculateTextBaseline() {
let node = this._node;
let hAlign;
let vAlign;
@@ -351,7 +350,7 @@ module.exports = {
_context.textBaseline = vAlign;
},
- _calculateSplitedStrings () {
+ _calculateSplitedStrings() {
let paragraphedStrings = _string.split('\n');
if (_isWrapText) {
@@ -360,9 +359,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 +371,7 @@ module.exports = {
},
- _getFontDesc () {
+ _getFontDesc() {
let fontDesc = _fontSize.toString() + 'px ';
fontDesc = fontDesc + _fontFamily;
if (_isBold) {
@@ -382,7 +381,7 @@ module.exports = {
return fontDesc;
},
- _getLineHeight () {
+ _getLineHeight() {
let nodeSpacingY = _lineHeight;
if (nodeSpacingY === 0) {
nodeSpacingY = _fontSize;
@@ -393,7 +392,7 @@ module.exports = {
return nodeSpacingY | 0;
},
- _calculateParagraphLength (paragraphedStrings, ctx) {
+ _calculateParagraphLength(paragraphedStrings, ctx) {
let paragraphLength = [];
for (let i = 0; i < paragraphedStrings.length; ++i) {
@@ -404,20 +403,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 +458,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/label/ttf.js b/cocos/2d/renderer/webgl/assemblers/label/ttf.js
deleted file mode 100644
index 0d980acdc1..0000000000
--- a/cocos/2d/renderer/webgl/assemblers/label/ttf.js
+++ /dev/null
@@ -1,93 +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 js = require('../../../../platform/js');
-const ttfUtls = require('../../../utils/label/ttf');
-
-module.exports = js.addon({
- createData (comp) {
- let renderData = comp.requestRenderData();
-
- renderData.dataLength = 4;
- renderData.vertexCount = 4;
- renderData.indiceCount = 6;
-
- let data = renderData._data;
- data[0].u = 0;
- data[0].v = 1;
- data[1].u = 1;
- data[1].v = 1;
- data[2].u = 0;
- data[2].v = 0;
- data[3].u = 1;
- data[3].v = 0;
- 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;
- }
- },
-
- _updateVerts (comp) {
- let renderData = comp._renderData;
-
- let node = comp.node,
- width = node.width,
- height = node.height,
- appx = node.anchorX * width,
- appy = node.anchorY * height;
-
- let data = renderData._data;
- data[0].x = -appx;
- data[0].y = -appy;
- data[1].x = width - appx;
- data[1].y = -appy;
- data[2].x = -appx;
- data[2].y = height - appy;
- data[3].x = width - appx;
- data[3].y = height - appy;
- }
-}, ttfUtls);
diff --git a/cocos/2d/renderer/webgl/assemblers/mask-assembler.js b/cocos/2d/renderer/webgl/assemblers/mask-assembler.js
deleted file mode 100644
index f73ebd73dc..0000000000
--- a/cocos/2d/renderer/webgl/assemblers/mask-assembler.js
+++ /dev/null
@@ -1,144 +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 StencilManager = require('../stencil-manager');
-const Node = require('../../../CCNode');
-const Mask = require('../../../components/CCMask');
-const Graphics = require('../../../graphics/graphics');
-const RenderFlow = require('../../render-flow');
-
-const spriteAssembler = require('./sprite/simple');
-const graphicsAssembler = require('./graphics');
-
-let _stencilMgr = StencilManager.sharedManager;
-// for nested mask, we might need multiple graphics component to avoid data conflict
-let _graphicsPool = [];
-let _graphicsUsing = [];
-
-function getGraphics () {
- let graphics = _graphicsPool.pop();
-
- if (!graphics) {
- let graphicsNode = new Node();
- graphics = graphicsNode.addComponent(Graphics);
- graphics._activateMaterial();
- graphics.lineWidth = 0;
- graphics.rect(0, 0, cc.visibleRect.width, cc.visibleRect.height);
- graphics.fill();
- graphicsAssembler.updateRenderData(graphics);
- }
- return graphics;
-}
-
-let maskFrontAssembler = {
- updateRenderData (mask) {
- if (!mask._renderData) {
- if (mask._type === Mask.Type.IMAGE_STENCIL) {
- mask._renderData = spriteAssembler.createData(mask);
- }
- else {
- // for updateGraphics calculation
- mask._renderData = mask.requestRenderData();
- }
- }
- let renderData = mask._renderData;
-
- if (mask._type === Mask.Type.IMAGE_STENCIL) {
- if (mask.spriteFrame) {
- let size = mask.node._contentSize;
- let anchor = mask.node._anchorPoint;
- renderData.updateSizeNPivot(size.width, size.height, anchor.x, anchor.y);
- renderData.dataLength = 4;
- spriteAssembler.updateRenderData(mask);
- renderData.material = mask._material;
- }
- else {
- mask._material = null;
- }
- }
- else {
- mask._graphics._material = mask._material;
- graphicsAssembler.updateRenderData(mask._graphics);
- }
- },
-
- fillBuffers (mask, renderer) {
- // Invalid state
- if (mask._type !== Mask.Type.IMAGE_STENCIL || mask.spriteFrame) {
- // HACK: Must push mask after batch, so we can only put this logic in fillVertexBuffer or fillIndexBuffer
- _stencilMgr.pushMask(mask);
- _stencilMgr.clear();
-
- mask._clearGraphics = getGraphics();
- graphicsAssembler.fillBuffers(mask._clearGraphics, renderer);
-
- _stencilMgr.enterLevel();
-
- // vertex buffer
- renderer.node = mask.node;
- renderer.material = mask._material;
- if (mask._type === Mask.Type.IMAGE_STENCIL) {
- spriteAssembler.fillBuffers(mask, renderer);
- renderer._flush();
- }
- else {
- graphicsAssembler.fillBuffers(mask._graphics, renderer);
- }
- }
-
- mask.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA;
- }
-};
-
-let maskEndAssembler = {
- fillBuffers (mask, renderer) {
- // Invalid state
- if (mask._type !== Mask.Type.IMAGE_STENCIL || mask.spriteFrame) {
- // HACK: Must pop mask after batch, so we can only put this logic in fillBuffers
- _stencilMgr.exitMask();
-
- _graphicsUsing.push(mask._clearGraphics);
- mask._clearGraphics = null;
-
- // Clear graphics can only be recycled after the mask stack exits entirely.
- if (_stencilMgr.stage === StencilManager.Stage.DISABLED) {
- for (let i = 0; i < _graphicsUsing.length; i++) {
- _graphicsPool.push(_graphicsUsing[i]);
- }
- _graphicsUsing.length = 0;
- }
- }
-
- mask.node._renderFlag |= RenderFlow.FLAG_UPDATE_RENDER_DATA;
- }
-};
-
-Mask._assembler = maskFrontAssembler;
-Mask._postAssembler = maskEndAssembler;
-
-module.exports = {
- front: maskFrontAssembler,
- end: maskEndAssembler
-}
\ No newline at end of file
diff --git a/cocos/2d/renderer/webgl/assemblers/sprite/bar-filled.js b/cocos/2d/renderer/webgl/assemblers/sprite/bar-filled.js
deleted file mode 100644
index 474fe24380..0000000000
--- a/cocos/2d/renderer/webgl/assemblers/sprite/bar-filled.js
+++ /dev/null
@@ -1,248 +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 Sprite = require('../../../../components/CCSprite');
-const FillType = Sprite.FillType;
-
-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) {
- let uvDirty = renderData.uvDirty,
- vertDirty = renderData.vertDirty;
-
- if (!uvDirty && !vertDirty) {
- return sprite.__allocedDatas;
- }
-
- let fillStart = sprite._fillStart;
- let fillRange = sprite._fillRange;
-
- if (fillRange < 0) {
- fillStart += fillRange;
- fillRange = -fillRange;
- }
-
- fillRange = fillStart + fillRange;
-
- fillStart = fillStart > 1.0 ? 1.0 : fillStart;
- fillStart = fillStart < 0.0 ? 0.0 : fillStart;
-
- fillRange = fillRange > 1.0 ? 1.0 : fillRange;
- fillRange = fillRange < 0.0 ? 0.0 : fillRange;
- fillRange = fillRange - fillStart;
- fillRange = fillRange < 0 ? 0 : fillRange;
-
- let fillEnd = fillStart + fillRange;
- fillEnd = fillEnd > 1 ? 1 : fillEnd;
-
- if (uvDirty) {
- this.updateUVs(sprite, fillStart, fillEnd);
- }
- if (vertDirty) {
- this.updateVerts(sprite, fillStart, fillEnd);
- this.updateWorldVerts(sprite);
- }
- }
- },
-
- 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 textureRect = spriteFrame._rect;
- //uv computation should take spritesheet into account.
- let ul, vb, ur, vt;
- let quadUV0, quadUV1, quadUV2, quadUV3, quadUV4, quadUV5, quadUV6, quadUV7;
- if (spriteFrame._rotated) {
- ul = (textureRect.x) / atlasWidth;
- vb = (textureRect.y + textureRect.width) / atlasHeight;
- ur = (textureRect.x + textureRect.height) / atlasWidth;
- vt = (textureRect.y) / atlasHeight;
-
- quadUV0 = quadUV2 = ul;
- quadUV4 = quadUV6 = ur;
- quadUV3 = quadUV7 = vb;
- quadUV1 = quadUV5 = vt;
- }
- else {
- ul = (textureRect.x) / atlasWidth;
- vb = (textureRect.y + textureRect.height) / atlasHeight;
- ur = (textureRect.x + textureRect.width) / atlasWidth;
- vt = (textureRect.y) / atlasHeight;
-
- 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;
- 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;
- break;
- default:
- cc.errorID(2626);
- break;
- }
-
- renderData.uvDirty = false;
- },
-
- updateVerts (sprite, fillStart, fillEnd) {
- 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 l = -appx, b = -appy,
- r = width-appx, t = height-appy;
-
- let progressStart, progressEnd;
- switch (sprite._fillType) {
- case FillType.HORIZONTAL:
- progressStart = l + (r - l) * fillStart;
- progressEnd = l + (r - l) * fillEnd;
-
- l = progressStart;
- r = progressEnd;
- break;
- case FillType.VERTICAL:
- progressStart = b + (t - b) * fillStart;
- progressEnd = b + (t - b) * fillEnd;
-
- b = progressStart;
- t = progressEnd;
- break;
- default:
- cc.errorID(2626);
- 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;
-
- renderData.vertDirty = false;
- },
-
- createData (sprite) {
- let renderData = sprite.requestRenderData();
- // 0-4 for world verts
- // 5-8 for local verts
- renderData.dataLength = 8;
- renderData.vertexCount = 4;
- renderData.indiceCount = 6;
- 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;
- }
- },
-
- fillBuffers (sprite, renderer) {
- if (renderer.worldMatDirty) {
- this.updateWorldVerts(sprite);
- }
-
- 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;
-
- // 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;
- }
- }
-};
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/sliced.js b/cocos/2d/renderer/webgl/assemblers/sprite/sliced.js
deleted file mode 100644
index 3279497dab..0000000000
--- a/cocos/2d/renderer/webgl/assemblers/sprite/sliced.js
+++ /dev/null
@@ -1,164 +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) {
- let renderData = sprite.requestRenderData();
- // 0-4 for local verts
- // 5-20 for world verts
- renderData.dataLength = 20;
-
- renderData.vertexCount = 16;
- renderData.indiceCount = 54;
- return renderData;
- },
-
- 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();
- }
- }
-
- let renderData = sprite._renderData;
- if (renderData && frame) {
- let vertDirty = renderData.vertDirty;
- if (vertDirty) {
- this.updateVerts(sprite);
- this.updateWorldVerts(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);
- let yScale = height / (topHeight + bottomHeight);
- xScale = (isNaN(xScale) || xScale > 1) ? 1 : xScale;
- 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;
-
- renderData.vertDirty = false;
- },
-
- fillBuffers (sprite, renderer) {
- if (renderer.worldMatDirty) {
- this.updateWorldVerts(sprite);
- }
-
- let renderData = sprite._renderData,
- data = renderData._data;
-
- let buffer = renderer._meshBuffer,
- vertexOffset = buffer.byteOffset >> 2,
- vertexCount = renderData.vertexCount;
-
- let 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,
- ibuf = buffer._iData;
-
- for (let i = 4; i < 20; ++i) {
- let vert = data[i];
- let uvs = uvSliced[i - 4];
-
- vbuf[vertexOffset++] = vert.x;
- vbuf[vertexOffset++] = vert.y;
- vbuf[vertexOffset++] = uvs.u;
- vbuf[vertexOffset++] = uvs.v;
- }
-
- for (let r = 0; r < 3; ++r) {
- for (let c = 0; c < 3; ++c) {
- let start = vertexId + r*4 + c;
- ibuf[indiceOffset++] = start;
- ibuf[indiceOffset++] = start + 1;
- ibuf[indiceOffset++] = start + 4;
- ibuf[indiceOffset++] = start + 1;
- ibuf[indiceOffset++] = start + 5;
- ibuf[indiceOffset++] = start + 4;
- }
- }
- },
-
- 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 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;
- }
- }
- },
-};
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/CCProgressBar.js b/cocos/2d/ui/CCProgressBar.js
deleted file mode 100644
index a90d987d1a..0000000000
--- a/cocos/2d/ui/CCProgressBar.js
+++ /dev/null
@@ -1,297 +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 Enum for ProgressBar mode
- * !#zh 进度条模式
- * @enum ProgressBar.Mode
- */
-var Mode = cc.Enum({
- /**
- * !#en TODO
- * !#zh 水平方向模式
- * @property {Number} HORIZONTAL
- */
- HORIZONTAL: 0,
-
- /**
- * !#en TODO
- * !#zh 垂直方向模式
- * @property {Number} VERTICAL
- */
- VERTICAL: 1,
- /**
- * !#en TODO
- * !#zh 填充模式
- * @property {Number} FILLED
- */
- FILLED: 2,
-});
-
-/**
- * !#en
- * Visual indicator of progress in some operation.
- * Displays a bar to the user representing how far the operation has progressed.
- * !#zh
- * 进度条组件,可用于显示加载资源时的进度。
- * @class ProgressBar
- * @extends Component
- * @example
- * // update progressBar
- * update: function (dt) {
- * var progress = progressBar.progress;
- * if (progress > 0) {
- * progress += dt;
- * }
- * else {
- * progress = 1;
- * }
- * progressBar.progress = progress;
- * }
- *
- */
-var ProgressBar = cc.Class({
- name: 'cc.ProgressBar',
- extends: Component,
-
- editor: CC_EDITOR && {
- menu: 'i18n:MAIN_MENU.component.ui/ProgressBar',
- help: 'i18n:COMPONENT.help_url.progressbar',
- },
-
- _initBarSprite: function() {
- if (this.barSprite) {
- var entity = this.barSprite.node;
- if (!entity) return;
-
- var nodeSize = this.node.getContentSize();
- var nodeAnchor = this.node.getAnchorPoint();
-
- var entitySize = entity.getContentSize();
-
- if(entity.parent === this.node){
- this.node.setContentSize(entitySize);
- }
-
- if (this.barSprite.fillType === cc.Sprite.FillType.RADIAL) {
- this.mode = Mode.FILLED;
- }
-
- var barSpriteSize = entity.getContentSize();
- if (this.mode === Mode.HORIZONTAL) {
- this.totalLength = barSpriteSize.width;
- }
- else if(this.mode === Mode.VERTICAL) {
- this.totalLength = barSpriteSize.height;
- }
- else {
- this.totalLength = this.barSprite.fillRange;
- }
-
- if(entity.parent === this.node){
- var x = - nodeSize.width * nodeAnchor.x;
- var y = 0;
- entity.setPosition(cc.v2(x, y));
- }
- }
- },
-
- _updateBarStatus: function() {
- if (this.barSprite) {
- var entity = this.barSprite.node;
-
- if (!entity) return;
-
- var entityAnchorPoint = entity.getAnchorPoint();
- var entitySize = entity.getContentSize();
- var entityPosition = entity.getPosition();
-
- var anchorPoint = cc.v2(0, 0.5);
- var progress = misc.clamp01(this.progress);
- var actualLenth = this.totalLength * progress;
- var finalContentSize;
- var totalWidth;
- var totalHeight;
- switch (this.mode) {
- case Mode.HORIZONTAL:
- if (this.reverse) {
- anchorPoint = cc.v2(1, 0.5);
- }
- finalContentSize = cc.size(actualLenth, entitySize.height);
- totalWidth = this.totalLength;
- totalHeight = entitySize.height;
- break;
- case Mode.VERTICAL:
- if (this.reverse) {
- anchorPoint = cc.v2(0.5, 1);
- } else {
- anchorPoint = cc.v2(0.5, 0);
- }
- finalContentSize = cc.size(entitySize.width, actualLenth);
- totalWidth = entitySize.width;
- totalHeight = this.totalLength;
- break;
- }
-
- //handling filled mode
- if (this.mode === Mode.FILLED) {
- if (this.barSprite.type !== cc.Sprite.Type.FILLED) {
- cc.warn('ProgressBar FILLED mode only works when barSprite\'s Type is FILLED!');
- } else {
- if (this.reverse) {
- actualLenth = actualLenth * -1;
- }
- this.barSprite.fillRange = actualLenth;
- }
- } else {
- if (this.barSprite.type !== cc.Sprite.Type.FILLED) {
-
- var anchorOffsetX = anchorPoint.x - entityAnchorPoint.x;
- var anchorOffsetY = anchorPoint.y - entityAnchorPoint.y;
- var finalPosition = cc.v2(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY);
-
- entity.setPosition(entityPosition.x + finalPosition.x, entityPosition.y + finalPosition.y);
-
- entity.setAnchorPoint(anchorPoint);
- entity.setContentSize(finalContentSize);
- } else {
- 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/2d/ui/CCScrollBar.js b/cocos/2d/ui/CCScrollBar.js
deleted file mode 100644
index 070f28dbd3..0000000000
--- a/cocos/2d/ui/CCScrollBar.js
+++ /dev/null
@@ -1,357 +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');
-
-var GETTINGSHORTERFACTOR = 20;
-
-/**
- * Enum for Scrollbar direction
- * @enum Scrollbar.Direction
- */
-var Direction = cc.Enum({
- /**
- * @property {Number} HORIZONTAL
- */
- HORIZONTAL: 0,
-
- /**
- * @property {Number} VERTICAL
- */
- VERTICAL: 1
-});
-
-/**
- * !#en
- * The Scrollbar control allows the user to scroll an image or other view that is too large to see completely
- * !#zh 滚动条组件
- * @class Scrollbar
- * @extends Component
- */
-var Scrollbar = cc.Class({
- name: 'cc.Scrollbar',
- extends: require('./CCComponent'),
-
- 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',
- }
- },
-
- statics: {
- Direction: Direction
- },
-
- setTargetScrollView: function(scrollView) {
- this._scrollView = scrollView;
- },
-
- _convertToScrollViewSpace: function(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;
- }
- },
-
- _onScroll: function(outOfBoundary) {
- if (this._scrollView) {
-
- var content = this._scrollView.content;
- if(content){
- var contentSize = content.getContentSize();
- var scrollViewSize = this._scrollView.node.getContentSize();
- var handleNodeSize = this.node.getContentSize();
-
- if(this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
- return;
- }
-
- if (this.enableAutoHide) {
- this._autoHideRemainingTime = this.autoHideTime;
- this._setOpacity(this._opacity);
- }
-
- var contentMeasure = 0;
- var scrollViewMeasure = 0;
- var outOfBoundaryValue = 0;
- var contentPosition = 0;
- var handleNodeMeasure = 0;
-
- 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) {
- contentMeasure = contentSize.height;
- scrollViewMeasure = scrollViewSize.height;
- handleNodeMeasure = handleNodeSize.height;
- outOfBoundaryValue = outOfBoundary.y;
-
- contentPosition = -this._convertToScrollViewSpace(content).y;
- }
-
- var length = this._calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundaryValue);
- var position = this._calculatePosition(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundaryValue, length);
-
- this._updateLength(length);
- this._updateHanlderPosition(position);
- }
- }
- },
-
- _updateHanlderPosition: function(position) {
- if (this.handle) {
- var oldPosition = this._fixupHandlerPosition();
-
- this.handle.node.setPosition(position.x + oldPosition.x, position.y + oldPosition.y);
- }
- },
-
- _fixupHandlerPosition: function() {
- var barSize = this.node.getContentSize();
- var barAnchor = this.node.getAnchorPoint();
- var handleSize = this.handle.node.getContentSize();
-
- 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) {
- fixupPosition = cc.v2(fixupPosition.x, fixupPosition.y + (barSize.height - handleSize.height) / 2);
- } else if (this.direction === Direction.VERTICAL) {
- fixupPosition = cc.v2(fixupPosition.x + (barSize.width - handleSize.width) / 2, fixupPosition.y);
- }
-
- this.handle.node.setPosition(fixupPosition);
-
- return fixupPosition;
- },
-
- _onTouchBegan: function() {
- if (!this.enableAutoHide) {
- return;
- }
- this._touching = true;
- },
-
- _conditionalDisableScrollBar: function (contentSize, scrollViewSize) {
- if(contentSize.width <= scrollViewSize.width
- && this.direction === Direction.HORIZONTAL){
- return true;
- }
-
- if(contentSize.height <= scrollViewSize.height
- && this.direction === Direction.VERTICAL){
- return true;
- }
- return false;
- },
-
- _onTouchEnded: function() {
- if (!this.enableAutoHide) {
- return;
- }
-
- this._touching = false;
-
- if (this.autoHideTime <= 0) {
- return;
- }
-
-
- if (this._scrollView) {
- var content = this._scrollView.content;
- if(content){
- var contentSize = content.getContentSize();
- var scrollViewSize = this._scrollView.node.getContentSize();
-
- if(this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
- return;
- }
- }
- }
-
- this._autoHideRemainingTime = this.autoHideTime;
- },
-
- _calculateLength: function(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundary) {
- var denominatorValue = contentMeasure;
- if (outOfBoundary) {
- denominatorValue += (outOfBoundary > 0 ? outOfBoundary : -outOfBoundary) * GETTINGSHORTERFACTOR;
- }
-
- var lengthRation = scrollViewMeasure / denominatorValue;
- return handleNodeMeasure * lengthRation;
- },
-
- _calculatePosition: function(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundary, actualLenth) {
- var denominatorValue = contentMeasure - scrollViewMeasure;
- if (outOfBoundary) {
- denominatorValue += Math.abs(outOfBoundary);
- }
-
- var positionRatio = 0;
- if (denominatorValue) {
- positionRatio = contentPosition / denominatorValue;
- positionRatio = misc.clamp01(positionRatio);
- }
-
- var position = (handleNodeMeasure - actualLenth) * positionRatio;
- 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;
- var handleNodeSize = handleNode.getContentSize();
- handleNode.setAnchorPoint(cc.v2(0, 0));
- 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) {
- return;
- } else if (this._touching) {
- return;
- }
-
-
- this._autoHideRemainingTime -= deltaTime;
- if (this._autoHideRemainingTime <= this.autoHideTime) {
- this._autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime);
- var opacity = this._opacity * (this._autoHideRemainingTime / this.autoHideTime);
- this._setOpacity(opacity);
- }
- },
-
- start: function() {
- if (this.enableAutoHide) {
- this._setOpacity(0);
- }
- },
-
- hide: function() {
- this._autoHideRemainingTime = 0;
- this._setOpacity(0);
- },
-
- show: function() {
- this._autoHideRemainingTime = this.autoHideTime;
- this._setOpacity(this._opacity);
- },
-
- update: function(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/2d/ui/editbox/CCEditBoxImpl.js b/cocos/2d/ui/editbox/CCEditBoxImpl.js
deleted file mode 100644
index f198c565d7..0000000000
--- a/cocos/2d/ui/editbox/CCEditBoxImpl.js
+++ /dev/null
@@ -1,648 +0,0 @@
-/****************************************************************************
- Copyright (c) 2011-2012 cocos2d-x.org
- Copyright (c) 2012 James Chen
- 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 utils = require('../../platform/utils');
-const macro = require('../../platform/CCMacro');
-const Types = require('./types');
-const InputMode = Types.InputMode;
-const InputFlag = Types.InputFlag;
-const KeyboardReturnType = Types.KeyboardReturnType;
-
-// https://segmentfault.com/q/1010000002914610
-let SCROLLY = 40;
-let LEFT_PADDING = 2;
-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 _vec3 = cc.v3();
-
-let _currentEditBoxImpl = null;
-
-// polyfill
-let polyfill = {
- zoomInvalid: false
-};
-
-if (cc.sys.OS_ANDROID === cc.sys.os &&
- (cc.sys.browserType === cc.sys.BROWSER_TYPE_SOUGOU ||
- cc.sys.browserType === cc.sys.BROWSER_TYPE_360)) {
- polyfill.zoomInvalid = true;
-}
-
-function getKeyboardReturnType (type) {
- switch (type) {
- case KeyboardReturnType.DEFAULT:
- case KeyboardReturnType.DONE:
- return 'done';
- case KeyboardReturnType.SEND:
- return 'send';
- case KeyboardReturnType.SEARCH:
- return 'search';
- case KeyboardReturnType.GO:
- return 'go';
- case KeyboardReturnType.NEXT:
- return 'next';
- }
- 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;
- },
-
- onEnable () {
- if (!this._edTxt) {
- return;
- }
- if (this._alwaysOnTop) {
- this._edTxt.style.display = '';
- }
- else {
- this._edTxt.style.display = 'none';
- }
- },
-
- onDisable () {
- if (!this._edTxt) {
- return;
- }
- this._edTxt.style.display = 'none';
- },
-
- setTabIndex (index) {
- if (this._edTxt) {
- this._edTxt.tabIndex = index;
- }
- },
-
- setFocus () {
- this._beginEditing();
- },
-
- isFocused() {
- if (this._edTxt) {
- return document.activeElement === this._edTxt;
- }
- cc.warnID(4700);
- return false;
- },
-
- 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) {
- if (!isNaN(maxLength)) {
- 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;
- }
- this._maxLength = maxLength;
- this._edTxt && (this._edTxt.maxLength = maxLength);
- }
- },
-
- setString (text) {
- this._text = text;
- this._edTxt && (this._edTxt.value = text);
- },
-
- getString () {
- return this._text;
- },
-
- setPlaceholderText (text) {
- this._placeholderText = text;
- },
-
- getPlaceholderText () {
- return this._placeholderText;
- },
-
- setDelegate (delegate) {
- this._delegate = delegate;
- },
-
- setInputMode (inputMode) {
- if (this._inputMode === inputMode) return;
-
- this._inputMode = inputMode;
- this.createInput();
-
- this._updateDomInputType();
- this._updateSize(this._size.width, this._size.height);
- },
-
- setInputFlag (inputFlag) {
- if (this._inputFlag === inputFlag) return;
-
- this._inputFlag = inputFlag;
- this._updateDomInputType();
-
- let textTransform = 'none';
-
- if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) {
- textTransform = 'uppercase';
- }
- else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) {
- textTransform = 'capitalize';
- }
-
- if (this._edTxt) {
- this._edTxt.style.textTransform = textTransform;
- this._edTxt.value = this._text;
- }
- },
-
- setReturnType (returnType) {
- this._returnType = returnType;
- this._updateDomInputType();
- },
-
- setFontSize (fontSize) {
- this._edFontSize = fontSize || this._edFontSize;
- this._edTxt && (this._edTxt.style.fontSize = this._edFontSize + 'px');
- },
-
- setFontColor (color) {
- this._textColor = color;
- this._edTxt && (this._edTxt.style.color = color.toCSS('rgba'));
- },
-
- setSize (width, height) {
- this._size.width = width;
- this._size.height = height;
- this._updateSize(width, height);
- },
-
- setNode (node) {
- this._node = node;
- },
-
- update () {
- // TODO: find better way to update matrix
- // if (this._editing) {
- this._updateMatrix();
- // }
- },
-
- clear () {
- this._node = null;
- this.setDelegate(null);
- this.removeDom();
- },
-
- _onTouchBegan (touch) {
-
- },
-
- _onTouchEnded () {
- this._beginEditing();
- },
-
- _beginEditing () {
- if (cc.sys.isMobile && !this._editing) {
- // Pre adaptation
- this._beginEditingOnMobile();
- }
-
- if (this._edTxt) {
- this._edTxt.style.display = '';
-
- let self = this;
- function startFocus () {
- self._edTxt.focus();
- }
-
- if (cc.sys.browserType === cc.sys.BROWSER_TYPE_UC) {
- setTimeout(startFocus, FOCUS_DELAY_UC);
- }
- else if (cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX) {
- setTimeout(startFocus, FOCUS_DELAY_FIREFOX);
- }
- else {
- startFocus();
- }
- }
-
- this._editing = true;
- },
-
- _endEditing () {
- let self = this;
- let hideDomInputAndShowLabel = function () {
- if (!self._alwaysOnTop && self._edTxt) {
- self._edTxt.style.display = 'none';
- }
- if (self._delegate && self._delegate.editBoxEditingDidEnded) {
- self._delegate.editBoxEditingDidEnded();
- }
- };
- if (this._editing) {
- if (cc.sys.isMobile) {
- // Delay end editing adaptation to ensure virtual keyboard is disapeared
- setTimeout(function () {
- self._endEditingOnMobile();
- hideDomInputAndShowLabel();
- }, DELAY_TIME);
- }
- else {
- hideDomInputAndShowLabel();
- }
- }
- this._editing = false;
- },
-
- _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) {
- type = 'number';
- } else if(inputMode === InputMode.PHONE_NUMBER) {
- type = 'number';
- edTxt.pattern = '[0-9]*';
- } else if(inputMode === InputMode.URL) {
- type = 'url';
- } else {
- type = 'text';
-
- if (this._returnType === KeyboardReturnType.SEARCH) {
- type = 'search';
- }
- }
-
- edTxt.type = type;
- },
-
- _updateSize (newWidth, newHeight) {
- let edTxt = this._edTxt;
- if (!edTxt) return;
-
- edTxt.style.width = newWidth + 'px';
- edTxt.style.height = newHeight + 'px';
- },
-
- _updateMatrix () {
- if (!this._edTxt) return;
-
- 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;
- }
- else {
- camera = cc.Camera.findCamera(node);
- }
-
- camera.getWorldToCameraMatrix(_matrix_temp);
- 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 () {
- this._node.getWorldMatrix(_matrix);
- let y = _matrix.m13;
- let windowHeight = cc.visibleRect.height;
- let windowWidth = cc.visibleRect.width;
- let factor = 0.5;
- if (windowWidth > windowHeight) {
- factor = 0.7;
- }
- setTimeout(function() {
- if (window.scrollY < SCROLLY && y < windowHeight * factor) {
- let scrollOffset = windowHeight * factor - y - window.scrollY;
- if (scrollOffset < 35) scrollOffset = 35;
- if (scrollOffset > 320) scrollOffset = 320;
- window.scrollTo(0, scrollOffset);
- }
- }, 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);
- }
- 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);
- }
-};
-
-function _inputValueHandle (input, editBoxImpl) {
- if (input.value.length > editBoxImpl._maxLength) {
- input.value = input.value.slice(0, editBoxImpl._maxLength);
- }
- if (editBoxImpl._delegate && editBoxImpl._delegate.editBoxTextChanged) {
- if (editBoxImpl._text !== input.value) {
- editBoxImpl._text = input.value;
- editBoxImpl._delegate.editBoxTextChanged(editBoxImpl._text);
- }
- }
-}
-
-function registerInputEventListener (tmpEdTxt, editBoxImpl, isTextarea) {
- let inputLock = false;
- let cbs = editBoxImpl.__eventListeners;
- cbs.compositionstart = function () {
- inputLock = true;
- };
- tmpEdTxt.addEventListener('compositionstart', cbs.compositionstart);
-
- cbs.compositionend = function () {
- inputLock = false;
- _inputValueHandle(this, editBoxImpl);
- };
- tmpEdTxt.addEventListener('compositionend', cbs.compositionend);
-
- cbs.input = function () {
- if (inputLock) {
- return;
- }
- _inputValueHandle(this, editBoxImpl);
- };
- tmpEdTxt.addEventListener('input', cbs.input);
-
- cbs.focus = function () {
- this.style.fontSize = editBoxImpl._edFontSize + 'px';
- this.style.color = editBoxImpl._textColor.toCSS('rgba');
- // When stayOnTop, input will swallow touch event
- if (editBoxImpl._alwaysOnTop) {
- editBoxImpl._editing = true;
- }
-
- if (cc.sys.isMobile) {
- editBoxImpl._beginEditingOnMobile();
- }
-
- if (editBoxImpl._delegate && editBoxImpl._delegate.editBoxEditingDidBegan) {
- editBoxImpl._delegate.editBoxEditingDidBegan();
- }
-
- };
- tmpEdTxt.addEventListener('focus', cbs.focus);
-
- cbs.keypress = function (e) {
- if (e.keyCode === macro.KEY.enter) {
- e.stopPropagation();
-
- if (editBoxImpl._delegate && editBoxImpl._delegate.editBoxEditingReturn) {
- editBoxImpl._delegate.editBoxEditingReturn();
- }
- if (!isTextarea) {
- editBoxImpl._text = this.value;
- editBoxImpl._endEditing();
- cc.game.canvas.focus();
- }
- }
- };
- tmpEdTxt.addEventListener('keypress', cbs.keypress);
-
- cbs.blur = function () {
- editBoxImpl._text = this.value;
- editBoxImpl._endEditing();
- };
- tmpEdTxt.addEventListener('blur', cbs.blur);
-
- 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/3d/assets/animation-clip.js b/cocos/3d/assets/animation-clip.js
deleted file mode 100644
index 1050517473..0000000000
--- a/cocos/3d/assets/animation-clip.js
+++ /dev/null
@@ -1,398 +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.
- ****************************************************************************/
-
-// @ts-check
-import { _decorator } from "../../core/data/index";
-const { ccclass, property } = _decorator;
-import Asset from "../../assets/CCAsset";
-import vec3 from "../../core/vmath/vec3";
-import quat from "../../core/vmath/quat";
-import { clamp } from "../../core/vmath/utils";
-
-/**
- * @typedef {import("../framework/skeleton-instance").SkeletonMask} SkeletonMask
- * @typedef {import("../../scene-graph/node").default} Node
- */
-
-let tmpvec3 = vec3.create(0, 0, 0);
-let tmpquat = quat.create();
-
-function _binaryIndexOf(array, key) {
- let lo = 0;
- let hi = array.length - 1;
- let mid;
-
- while (lo <= hi) {
- mid = ((lo + hi) >> 1);
- let val = array[mid];
-
- if (val < key) {
- lo = mid + 1;
- } else if (val > key) {
- hi = mid - 1;
- } else {
- return mid;
- }
- }
-
- return lo;
-}
-
-@ccclass('cc.AnimationChannel')
-export class AnimationChannel {
- /**
- * Target node's path into virtual hierarchy.
- * @type {string}
- */
- @property
- target = "";
-
- /**
- * Target node's position animation curve.
- * @type {cc.Vec3[]}
- */
- @property
- positionCurve = [];
-
- /**
- * Target node's scale animation curve.
- * @type {cc.Vec3[]}
- */
- @property
- scaleCurve = [];
-
- /**
- * Target node's rotation animation curve.
- * @type {cc.Quat[]}
- */
- @property
- rotationCurve = [];
-}
-cc.AnimationChannel = AnimationChannel;
-
-@ccclass('cc.AnimationFrame')
-export class AnimationFrame {
- @property
- _name = "";
-
- /**
- * @type {AnimationChannel[]}
- */
- @property
- _channels = [];
-
- /**
- * @type {number[]}
- */
- @property
- _times = [];
-
- get channels() {
- return this._channels;
- }
-
- get times() {
- return this._times;
- }
-}
-cc.AnimationFrame = AnimationFrame;
-
-@ccclass('cc.AnimationClip')
-export default class AnimationClip extends Asset {
- /**
- * @type {AnimationFrame[]}
- */
- @property
- _frames = [];
-
- /**
- * @type {number}
- */
- @property
- _length = 0.0;
-
- get frames() {
- return this._frames;
- }
-
- get length() {
- return this._length;
- }
-}
-cc.AnimationClip = AnimationClip;
-
-export class AnimationTarget {
- constructor() {
- /**
- * @type {Node[]}
- */
- this._nodes = [];
-
- /**
- * @type {Map}
- */
- this._pathMap = new Map();
- }
-
- add(path, node) {
- if (this._pathMap.has(path)) {
- return;
- }
- const index = this._nodes.length;
- this._nodes.push(node);
- this._pathMap.set(path, index);
- }
-
- get(path) {
- return this._pathMap.get(path);
- }
-
- get nodes() {
- return this._nodes;
- }
-
- getDefaultPosition(nodeIndex) {
- return this._nodes[nodeIndex].getPosition();
- //return this._defaultPositions[nodeIndex];
- }
-
- getDefaultScale(nodeIndex) {
- return this._nodes[nodeIndex].getScale();
- //return this._defaultScales[nodeIndex];
- }
-
- getDefaultRotation(nodeIndex) {
- return this._nodes[nodeIndex].getRotation();
- //return this._defaultRotations[nodeIndex];
- }
-
- // _saveDefaultTRS() {
- // this._defaultPositions = new Array(this._nodes.length);
- // this._defaultScales = new Array(this._nodes.length);
- // this._defaultRotations = new Array(this._nodes.length);
- // this._nodes.forEach((node, index) => {
- // this._defaultPositions[index] = node.getPosition();
- // this._defaultScales[index] = node.getScale();
- // this._defaultRotations[index] = node.getRotation();
- // });
- // }
-}
-
-/**
- * The AnimationTarget class represents the progress of blended sampling.
- */
-export class AnimationSampler {
- /**
- *
- * @param {AnimationTarget} animationTarget
- */
- constructor(animationTarget) {
- /**
- * @type {AnimationTarget}
- */
- this._animationTarget = animationTarget;
-
- const targetNodes = this._animationTarget.nodes;
- /**
- * @type {NodeSamplingState[]}
- */
- this._nodeSamplingStates = new Array(targetNodes.length);
- this._animationTarget.nodes.forEach((targetNode, index) => {
- this._nodeSamplingStates[index] = new NodeSamplingState(
- targetNode,
- this._animationTarget.getDefaultPosition(index),
- this._animationTarget.getDefaultScale(index),
- this._animationTarget.getDefaultRotation(index));
- });
- }
-
- /**
- * Resets this state to get sampling start.
- */
- reset() {
- this._nodeSamplingStates.forEach(
- nodeSamlingState => nodeSamlingState.reset());
- }
-
- /**
- * Updates the sampling result.
- */
- apply() {
- this._nodeSamplingStates.forEach(
- nodeSamlingState => nodeSamlingState.apply());
- }
-
- /** Sample data of this animation clip in a specific time and blend that data
- * with a weight together with previous data(if exist, or blank if not exists) sampled before.
- *
- * @param {AnimationClip} clip
- * @param {Number} t The time.
- * @param {Number} weight The weight.
- * @param {SkeletonMask} [mask] The skeleton mask.
- */
- sample(clip, t, weight, mask) {
- t = clamp(t, 0, clip.length);
-
- const getState = /** @param {AnimationChannel} [channel] */(channel) => {
- return this._nodeSamplingStates[this._animationTarget.get(channel.target)];
- };
-
- clip.frames.forEach((frame) => {
- let idx = 0;
- if (frame.times.length != 1)
- idx = _binaryIndexOf(frame.times, t);
- if (idx == 0) {
- frame.channels.forEach((channel) => {
- const nodeSamlingState = getState(channel);
- if (!nodeSamlingState) {
- return;
- }
- if (channel.positionCurve.length != 0) {
- nodeSamlingState.blendPosition(channel.positionCurve[0], weight);
- }
- if (channel.rotationCurve.length != 0) {
- nodeSamlingState.blendRotation(channel.rotationCurve[0], weight);
- }
- if (channel.scaleCurve.length != 0) {
- nodeSamlingState.blendScale(channel.scaleCurve[0], weight);
- }
- });
- }
- else {
- let loIdx = Math.max(idx - 1, 0);
- let hiIdx = Math.min(idx, frame.times.length);
- let ratio = (t - frame.times[loIdx]) / (frame.times[hiIdx] - frame.times[loIdx]);
-
- frame.channels.forEach((channel) => {
- const nodeSamlingState = getState(channel);
- if (!nodeSamlingState) {
- return;
- }
- if (channel.positionCurve.length != 0) {
- let a = channel.positionCurve[loIdx];
- let b = channel.positionCurve[hiIdx];
- vec3.lerp(tmpvec3, a, b, ratio);
- nodeSamlingState.blendPosition(tmpvec3, weight);
- }
- if (channel.rotationCurve.length != 0) {
- let a = channel.rotationCurve[loIdx];
- let b = channel.rotationCurve[hiIdx];
- quat.slerp(tmpquat, a, b, ratio);
- nodeSamlingState.blendRotation(tmpquat, weight);
- }
- if (channel.scaleCurve.length != 0) {
- let a = channel.scaleCurve[loIdx];
- let b = channel.scaleCurve[hiIdx];
- vec3.lerp(tmpvec3, a, b, ratio);
- nodeSamlingState.blendScale(tmpvec3, weight);
- }
- });
- }
- });
- }
-}
-
-class NodeSamplingState {
- /**
- *
- * @param {Node} target
- * @param {cc.Vec3} defaultPosition
- * @param {cc.Vec3} defaultScale
- * @param {cc.Quat} defaultRotation
- */
- constructor(target, defaultPosition, defaultScale, defaultRotation) {
- /**
- * @type {Node}
- */
- this._target = target;
-
- /**
- * @type {cc.Vec3}
- */
- this._defaultPosition = defaultPosition;
-
- /**
- * @type {cc.Vec3}
- */
- this._defaultScale = defaultScale;
-
- /**
- * @type {cc.Quat}
- */
- this._defaultRotation = defaultRotation;
- }
-
- reset() {
- /**
- * @type {Number}
- */
- this._sumPosWeight = 0.0;
-
- /**
- * @type {Number}
- */
- this._sumScaleWeight = 0.0;
-
- /**
- * @type {Number}
- */
- this._sumRotWeight = 0.0;
- this._target.setPosition(0, 0, 0);
- this._target.setScale(0, 0, 0);
- this._target.setRotation(0, 0, 0, 1);
- }
-
- blendPosition(pos, weight) {
- vec3.scaleAndAdd(tmpvec3, this._target._lpos, pos, weight);
- this._target.setPosition(tmpvec3);
- this._sumPosWeight += weight;
- }
-
- blendScale(scale, weight) {
- vec3.scaleAndAdd(tmpvec3, this._target._lscale, scale, weight);
- this._target.setScale(tmpvec3);
- this._sumScaleWeight += weight;
- }
-
- /**
- * Inspired by:
- * https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
- */
- blendRotation(rot, weight) {
- let t = weight / (this._sumRotWeight + weight);
- quat.slerp(tmpquat, this._target._lrot, rot, t);
- this._target.setRotation(tmpquat);
- this._sumRotWeight += weight;
- }
-
- apply() {
- if (this._sumPosWeight < 1.0)
- this.blendPosition(this._defaultPosition, 1.0 - this._sumPosWeight);
- if (this._sumScaleWeight < 1.0)
- this.blendScale(this._defaultScale, 1.0 - this._sumScaleWeight);
- if (this._sumRotWeight < 1.0)
- this.blendRotation(this._defaultRotation, 1.0 - this._sumRotWeight);
- }
-}
\ No newline at end of file
diff --git a/cocos/3d/assets/animation-clip.ts b/cocos/3d/assets/animation-clip.ts
new file mode 100644
index 0000000000..321ff63aaf
--- /dev/null
+++ b/cocos/3d/assets/animation-clip.ts
@@ -0,0 +1,319 @@
+/****************************************************************************
+ 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 { _decorator } from '../../core/data/index';
+const { ccclass, property } = _decorator;
+import { Asset } from '../../assets/asset';
+import { Quat, Vec3 } from '../../core/value-types';
+import quat from '../../core/vmath/quat';
+import { clamp } from '../../core/vmath/utils';
+import vec3 from '../../core/vmath/vec3';
+import { Node } from '../../scene-graph/node';
+
+const tmpvec3 = new Vec3();
+const tmpquat = new Quat();
+
+function _binaryIndexOf (array: number[], key: number) {
+ let lo = 0;
+ let hi = array.length - 1;
+ while (lo <= hi) {
+ const mid = ((lo + hi) >> 1);
+ const val = array[mid];
+ if (val < key) {
+ lo = mid + 1;
+ } else if (val > key) {
+ hi = mid - 1;
+ } else {
+ return mid;
+ }
+ }
+ return lo;
+}
+
+export interface IAnimationChannel {
+ /**
+ * Target node's path in scene graph.
+ */
+ target: string;
+
+ /**
+ * Target node's position animation curve.
+ */
+ positionCurve: Vec3[];
+
+ /**
+ * Target node's scale animation curve.
+ */
+ scaleCurve: Vec3[];
+
+ /**
+ * Target node's rotation animation curve.
+ */
+ rotationCurve: Quat[];
+}
+
+@ccclass('cc.AnimationClip')
+export default class AnimationClip extends Asset {
+ @property
+ private _channels: IAnimationChannel[] = [];
+
+ @property
+ private _times: number[] = [];
+
+ @property
+ private _length: number = 0.0;
+
+ get times () {
+ return this._times;
+ }
+
+ get channels () {
+ return this._channels;
+ }
+
+ get length () {
+ return this._length;
+ }
+}
+cc.AnimationClip = AnimationClip;
+
+export class AnimationTarget {
+ private _nodes: Node[] = [];
+ private _pathMap: Map = new Map();
+
+ public add (path: string, node: Node) {
+ if (this._pathMap.has(path)) {
+ return;
+ }
+ const index = this._nodes.length;
+ this._nodes.push(node);
+ this._pathMap.set(path, index);
+ }
+
+ public get (path: string) {
+ return this._pathMap.get(path);
+ }
+
+ get nodes () {
+ return this._nodes;
+ }
+
+ public getDefaultPosition (nodeIndex: number) {
+ return this._nodes[nodeIndex].getPosition();
+ // return this._defaultPositions[nodeIndex];
+ }
+
+ public getDefaultScale (nodeIndex: number) {
+ return this._nodes[nodeIndex].getScale();
+ // return this._defaultScales[nodeIndex];
+ }
+
+ public getDefaultRotation (nodeIndex: number) {
+ return this._nodes[nodeIndex].getRotation();
+ // return this._defaultRotations[nodeIndex];
+ }
+
+ // _saveDefaultTRS() {
+ // this._defaultPositions = new Array(this._nodes.length);
+ // this._defaultScales = new Array(this._nodes.length);
+ // this._defaultRotations = new Array(this._nodes.length);
+ // this._nodes.forEach((node, index) => {
+ // this._defaultPositions[index] = node.getPosition();
+ // this._defaultScales[index] = node.getScale();
+ // this._defaultRotations[index] = node.getRotation();
+ // });
+ // }
+}
+
+/**
+ * The AnimationTarget class represents the progress of blended sampling.
+ */
+export class AnimationSampler {
+ private _animationTarget: AnimationTarget;
+ private _nodeSamplingStates: NodeSamplingState[];
+
+ constructor (animationTarget: AnimationTarget) {
+ this._animationTarget = animationTarget;
+
+ const targetNodes = this._animationTarget.nodes;
+ this._nodeSamplingStates = new Array(targetNodes.length);
+ this._animationTarget.nodes.forEach((targetNode, index) => {
+ this._nodeSamplingStates[index] = new NodeSamplingState(
+ targetNode,
+ this._animationTarget.getDefaultPosition(index),
+ this._animationTarget.getDefaultScale(index),
+ this._animationTarget.getDefaultRotation(index));
+ });
+ }
+
+ /**
+ * Resets this state to get sampling start.
+ */
+ public reset () {
+ this._nodeSamplingStates.forEach(
+ (nodeSamlingState) => nodeSamlingState.reset());
+ }
+
+ /**
+ * Updates the sampling result.
+ */
+ public apply () {
+ this._nodeSamplingStates.forEach(
+ (nodeSamlingState) => nodeSamlingState.apply());
+ }
+
+ /** Sample data of this animation clip in a specific time and blend that data
+ * with a weight together with previous data(if exist, or blank if not exists) sampled before.
+ *
+ * @param clip
+ * @param t The time.
+ * @param weight The weight.
+ * @param [mask] The skeleton mask.
+ */
+ public sample (clip: AnimationClip, t: number, weight: number, mask?: any) {
+ t = clamp(t, 0, clip.length);
+
+ const getState = (channel: IAnimationChannel) => {
+ const iNode = this._animationTarget.get(channel.target);
+ if (!iNode) {
+ return null;
+ }
+ return this._nodeSamplingStates[iNode];
+ };
+
+ let idx = 0;
+ if (clip.times.length !== 1) {
+ idx = _binaryIndexOf(clip.times, t);
+ }
+ if (idx === 0) {
+ clip.channels.forEach((channel) => {
+ const nodeSamlingState = getState(channel);
+ if (!nodeSamlingState) {
+ return;
+ }
+ if (channel.positionCurve.length !== 0) {
+ nodeSamlingState.blendPosition(channel.positionCurve[0], weight);
+ }
+ if (channel.rotationCurve.length !== 0) {
+ nodeSamlingState.blendRotation(channel.rotationCurve[0], weight);
+ }
+ if (channel.scaleCurve.length !== 0) {
+ nodeSamlingState.blendScale(channel.scaleCurve[0], weight);
+ }
+ });
+ } else {
+ const loIdx = Math.max(idx - 1, 0);
+ const hiIdx = Math.min(idx, clip.times.length);
+ const ratio = (t - clip.times[loIdx]) / (clip.times[hiIdx] - clip.times[loIdx]);
+
+ clip.channels.forEach((channel) => {
+ const nodeSamlingState = getState(channel);
+ if (!nodeSamlingState) {
+ return;
+ }
+ if (channel.positionCurve.length !== 0) {
+ const a = channel.positionCurve[loIdx];
+ const b = channel.positionCurve[hiIdx];
+ vec3.lerp(tmpvec3, a, b, ratio);
+ nodeSamlingState.blendPosition(tmpvec3, weight);
+ }
+ if (channel.rotationCurve.length !== 0) {
+ const a = channel.rotationCurve[loIdx];
+ const b = channel.rotationCurve[hiIdx];
+ quat.slerp(tmpquat, a, b, ratio);
+ nodeSamlingState.blendRotation(tmpquat, weight);
+ }
+ if (channel.scaleCurve.length !== 0) {
+ const a = channel.scaleCurve[loIdx];
+ const b = channel.scaleCurve[hiIdx];
+ vec3.lerp(tmpvec3, a, b, ratio);
+ nodeSamlingState.blendScale(tmpvec3, weight);
+ }
+ });
+ }
+ }
+}
+
+class NodeSamplingState {
+ private _target: Node;
+ private _defaultPosition: Vec3;
+ private _defaultScale: Vec3;
+ private _defaultRotation: Quat;
+ private _sumPosWeight = 0;
+ private _sumScaleWeight = 0;
+ private _sumRotWeight = 0;
+
+ constructor (target: Node, defaultPosition: Vec3, defaultScale: Vec3, defaultRotation: Quat) {
+ this._target = target;
+ this._defaultPosition = defaultPosition;
+ this._defaultScale = defaultScale;
+ this._defaultRotation = defaultRotation;
+ }
+
+ public reset () {
+ this._sumPosWeight = 0.0;
+ this._sumScaleWeight = 0.0;
+ this._sumRotWeight = 0.0;
+ this._target.setPosition(0, 0, 0);
+ this._target.setScale(0, 0, 0);
+ this._target.setRotation(0, 0, 0, 1);
+ }
+
+ public blendPosition (position: Vec3, weight: number) {
+ vec3.scaleAndAdd(tmpvec3, this._target.getPosition(), position, weight);
+ this._target.setPosition(tmpvec3);
+ this._sumPosWeight += weight;
+ }
+
+ public blendScale (scale: Vec3, weight: number) {
+ vec3.scaleAndAdd(tmpvec3, this._target.getScale(), scale, weight);
+ this._target.setScale(tmpvec3);
+ this._sumScaleWeight += weight;
+ }
+
+ /**
+ * Inspired by:
+ * https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
+ */
+ public blendRotation (rotation: Quat, weight: number) {
+ const t = weight / (this._sumRotWeight + weight);
+ quat.slerp(tmpquat, this._target.getRotation(), rotation, t);
+ this._target.setRotation(tmpquat);
+ this._sumRotWeight += weight;
+ }
+
+ public apply () {
+ if (this._sumPosWeight < 1.0) {
+ this.blendPosition(this._defaultPosition, 1.0 - this._sumPosWeight);
+ }
+ if (this._sumScaleWeight < 1.0) {
+ this.blendScale(this._defaultScale, 1.0 - this._sumScaleWeight);
+ }
+ if (this._sumRotWeight < 1.0) {
+ this.blendRotation(this._defaultRotation, 1.0 - this._sumRotWeight);
+ }
+ }
+}
diff --git a/cocos/3d/assets/audio-clip.js b/cocos/3d/assets/audio-clip.js
index eb7684cd20..b2c73509b1 100644
--- a/cocos/3d/assets/audio-clip.js
+++ b/cocos/3d/assets/audio-clip.js
@@ -24,7 +24,7 @@
****************************************************************************/
// @ts-check
import { _decorator } from "../../core/data/index";
-import Asset from "../../assets/CCAsset";
+import { Asset } from "../../assets/asset";
import { EventTarget } from "../../core/event/index";
const { ccclass, mixins } = _decorator;
@@ -117,4 +117,4 @@ export class AudioClip extends Asset {
}
}
-cc.AudioClip = AudioClip;
\ No newline at end of file
+cc.AudioClip = AudioClip;
diff --git a/cocos/3d/assets/bitmap-font.js b/cocos/3d/assets/bitmap-font.js
index 343aa2381c..668669542d 100644
--- a/cocos/3d/assets/bitmap-font.js
+++ b/cocos/3d/assets/bitmap-font.js
@@ -27,7 +27,7 @@ import { _decorator } from "../../core/data/index";
const { ccclass, property } = _decorator;
import Font from "./font";
import vec2 from "../../core/vmath/vec2";
-import Texture2D from "../../assets/texture-2d";
+import { Texture2D } from "../../assets/texture-2d";
@ccclass('cc.BitmapFont')
export class BitmapFont extends Font {
diff --git a/cocos/3d/assets/effect-asset.js b/cocos/3d/assets/effect-asset.js
deleted file mode 100644
index af5ae4aecd..0000000000
--- a/cocos/3d/assets/effect-asset.js
+++ /dev/null
@@ -1,46 +0,0 @@
-import Asset from "../../assets/CCAsset";
-import { property, ccclass } from "../../core/data/class-decorator";
-
-@ccclass('cc.EffectAsset')
-class EffectAsset extends Asset {
- @property
- techniques = [];
-
- @property
- properties = {};
-
- @property
- shaders = [];
-
- onLoaded() {
- let lib = cc.game._renderer._programLib;
- this.shaders.forEach(s => lib.define(s));
- EffectAsset.register(this);
- }
-}
-
-let effects = EffectAsset._effects = {};
-EffectAsset.register = function(asset) {
- effects[asset.name] = asset;
-};
-EffectAsset.remove = function(name) {
- if (effects[name]) { delete effects[name]; return; }
- for (let n in effects) {
- if (effects[n]._uuid === name) {
- delete effects[n];
- return;
- }
- }
-};
-EffectAsset.get = function(name) {
- if (effects[name]) return effects[name];
- for (let n in effects)
- if (effects[n]._uuid === name)
- return effects[n];
-};
-EffectAsset.getAll = function() {
- return effects;
-};
-
-export default EffectAsset;
-cc.EffectAsset = EffectAsset;
diff --git a/cocos/3d/assets/effect-asset.ts b/cocos/3d/assets/effect-asset.ts
new file mode 100644
index 0000000000..3cb9b4e16d
--- /dev/null
+++ b/cocos/3d/assets/effect-asset.ts
@@ -0,0 +1,108 @@
+import { Asset } from '../../assets/asset';
+import { ccclass, property } from '../../core/data/class-decorator';
+import { GFXDynamicState, GFXPrimitiveMode, GFXType } from '../../gfx/define';
+import { GFXBlendState, GFXDepthStencilState, GFXRasterizerState } from '../../gfx/pipeline-state';
+import { IGFXSamplerInfo } from '../../gfx/sampler';
+import { RenderPassStage } from '../../pipeline/define';
+import { programLib } from '../../renderer/core/program-lib';
+
+export interface IPropertyInfo {
+ type: number; // auto-extracted if not specified
+ value?: number[] | string;
+ displayName?: string;
+ sampler?: IGFXSamplerInfo;
+}
+export interface IPassInfo {
+ program: string;
+ // effect-writer part
+ priority?: number;
+ primitive?: GFXPrimitiveMode;
+ stage?: RenderPassStage;
+ rasterizerState?: GFXRasterizerState;
+ depthStencilState?: GFXDepthStencilState;
+ blendState?: GFXBlendState;
+ dynamics?: GFXDynamicState[];
+ properties?: Record;
+}
+export interface ITechniqueInfo {
+ passes: IPassInfo[];
+ queue?: number;
+ priority?: number;
+ lod?: number;
+}
+
+export interface IBlockMember {
+ name: string;
+ type: GFXType;
+ count: number;
+ size: number;
+}
+export interface IBlockInfo {
+ name: string;
+ binding: number;
+ defines: string[];
+ members: IBlockMember[];
+ size: number;
+}
+export interface ISamplerInfo {
+ name: string;
+ binding: number;
+ defines: string[];
+ type: GFXType;
+ count: number;
+}
+export interface IDefineInfo {
+ name: string;
+ type: string;
+ range?: number[];
+ defines: string[];
+}
+export interface IShaderInfo {
+ name: string;
+ vert: string;
+ frag: string;
+ defines: IDefineInfo[];
+ blocks: IBlockInfo[];
+ samplers: ISamplerInfo[];
+ dependencies: Record;
+}
+
+const effects: Record = {};
+
+@ccclass('cc.EffectAsset')
+export class EffectAsset extends Asset {
+ public static register (asset: EffectAsset) { effects[asset.name] = asset; }
+ public static remove (name: string) {
+ if (effects[name]) { delete effects[name]; return; }
+ for (const n in effects) {
+ if (effects[n]._uuid === name) {
+ delete effects[n];
+ return;
+ }
+ }
+ }
+ public static get (name: string) {
+ if (effects[name]) { return effects[name]; }
+ for (const n in effects) {
+ if (effects[n]._uuid === name) {
+ return effects[n];
+ }
+ }
+ return null;
+ }
+ public static getAll () { return effects; }
+ protected static _effects: Record = {};
+
+ @property
+ public techniques: ITechniqueInfo[] = [];
+
+ @property
+ public shaders: IShaderInfo[] = [];
+
+ public onLoaded () {
+ this.shaders.forEach((s) => programLib.define(s));
+ EffectAsset.register(this);
+ }
+}
+
+cc.EffectAsset = EffectAsset;
diff --git a/cocos/3d/assets/font.js b/cocos/3d/assets/font.js
index 319bacfd94..3d0891759b 100644
--- a/cocos/3d/assets/font.js
+++ b/cocos/3d/assets/font.js
@@ -25,13 +25,13 @@
// @ts-check
import { _decorator } from "../../core/data/index";
const {ccclass} = _decorator;
-import Asset from "../../assets/CCAsset";
+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.
@@ -46,7 +46,7 @@ export default class Font extends Asset {
_lineHeight = 32;
/**
- *
+ *
* @type {boolean}
*/
_useKerning = false;
@@ -78,4 +78,4 @@ export default class Font extends Asset {
}
}
-cc.Font = Font;
\ No newline at end of file
+cc.Font = Font;
diff --git a/cocos/3d/assets/index.js b/cocos/3d/assets/index.js
index 6393ed3b4f..4cc366051f 100644
--- a/cocos/3d/assets/index.js
+++ b/cocos/3d/assets/index.js
@@ -4,7 +4,7 @@
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,
+ 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
@@ -14,7 +14,7 @@
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
+ 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
@@ -27,9 +27,9 @@ export { default as AnimationClip } from "./animation-clip";
export { AudioClip } from "./audio-clip";
export { DOMAudioClip } from "./dom-audio-clip";
export { BitmapFont } from "./bitmap-font";
-export { default as EffectAsset } from "./effect-asset";
-export { default as Material } from "./material";
-export { default as Mesh } from "./mesh";
+export { EffectAsset } from "./effect-asset";
+export { Material } from "./material";
+export { Mesh } from "./mesh";
export { default as OpentypeFont } from "./opentype-font";
export { default as Skeleton } from "./skeleton";
export { default as Sprite } from "./sprite";
diff --git a/cocos/3d/assets/material.js b/cocos/3d/assets/material.js
deleted file mode 100644
index 64e59e5c6a..0000000000
--- a/cocos/3d/assets/material.js
+++ /dev/null
@@ -1,149 +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.
- ****************************************************************************/
-// @ts-check
-import { ccclass, property } from "../../core/data/class-decorator";
-import Asset from "../../assets/CCAsset";
-import TextureBase from '../../assets/texture-base';
-import Effect from '../../renderer/core/effect';
-import EffectAsset from './effect-asset';
-
-@ccclass('cc.Material')
-class Material extends Asset {
- /**
- * @type {Object}
- */
- @property
- _defines = {};
-
- /**
- * @type {Object}
- */
- @property
- _props = {};
-
- /**
- * @type {EffectAsset}
- */
- @property(EffectAsset)
- _effectAsset = null;
-
- @property
- set effectAsset(val) {
- if (this.effectName !== val.name) this._setEffect(val);
- }
- get effectAsset() {
- return this._effectAsset;
- }
-
- // helper setter
- @property
- set effectName(val) {
- if (this.effectName !== val) this._setEffect(val);
- }
- get effectName() {
- return this._effectAsset ? this._effectAsset.name : '';
- }
-
- /**
- * @type {Effect}
- */
- _effect = null;
-
- /**
- * @type {Effect}
- */
- get effect() {
- return this._effect;
- }
-
- /**
- *
- * @param {Material} mat
- */
- copy(mat) {
- Object.assign(this._props, mat._props);
- Object.assign(this._defines, mat._defines);
- this._setEffect(mat.effectAsset);
- this._uuid = mat._uuid;
- }
-
- /**
- *
- * @param {string} name
- * @param {*} val
- */
- setProperty(name, val) {
- this._props[name] = val;
- if (this._effect) {
- if (val instanceof TextureBase) this._effect.setProperty(name, val._texture);
- else this._effect.setProperty(name, val);
- }
- }
-
- /**
- *
- * @param {string} name
- * @param {*} val
- */
- define(name, val) {
- this._defines[name] = val;
- if (this._effect) this._effect.define(name, val);
- }
-
- onLoaded() {
- this._setEffect(this.effectAsset);
- }
-
- _setEffect(val) {
- let effectAsset = val;
- if (typeof val === 'string' && !(effectAsset = cc.EffectAsset.get(val))) {
- console.warn(`no effect named '${val}' found`);
- return;
- }
- this._effectAsset = effectAsset;
- if (!effectAsset) return;
- this._effect = Effect.parseEffect(effectAsset);
- for (let def in this._defines)
- this._effect.define(def, this._defines[def]);
- for (let prop in this._props)
- this.setProperty(prop, this._props[prop]);
- }
-
- static getInstantiatedMaterial(mat, rndCom) {
- if (mat._owner === rndCom) {
- return mat;
- }
- else {
- let instance = new Material();
- instance.copy(mat);
- instance._native = mat._native + ' (Instance)';
- instance._owner = rndCom;
- return instance;
- }
- }
-}
-
-export default Material;
-cc.Material = Material;
diff --git a/cocos/3d/assets/material.ts b/cocos/3d/assets/material.ts
new file mode 100644
index 0000000000..e84b52fcee
--- /dev/null
+++ b/cocos/3d/assets/material.ts
@@ -0,0 +1,247 @@
+/****************************************************************************
+ 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 { Asset } from '../../assets/asset';
+import { ccclass, property } from '../../core/data/class-decorator';
+import { murmurhash2_32_gc } from '../../core/utils/murmurhash2_gc';
+import { GFXBindingType } from '../../gfx/define';
+import { GFXTextureView } from '../../gfx/texture-view';
+import { Effect, IDefineMap } from '../../renderer/core/effect';
+import { Pass, PassOverrides } from '../../renderer/core/pass';
+import { RenderableComponent } from '../framework/renderable-component';
+import { EffectAsset } from './effect-asset';
+
+export interface IMaterialInfo {
+ technique?: number;
+ defines?: IDefineMap | IDefineMap[];
+ effectName?: string;
+}
+
+@ccclass('cc.Material')
+export class Material extends Asset {
+ public static getInstantiatedMaterial (mat: Material, rndCom: RenderableComponent, inEditor: boolean) {
+ if (mat._owner === rndCom) {
+ return mat;
+ } else {
+ const instance = new Material();
+ instance.copy(mat);
+ instance._native = mat._native + ' (Instance)';
+ instance._owner = rndCom;
+ if (inEditor) {
+ instance._uuid = mat._uuid;
+ }
+ return instance;
+ }
+ }
+
+ @property(EffectAsset)
+ protected _effectAsset: EffectAsset | null = null;
+ @property
+ protected _techIdx = 0;
+ @property
+ protected _defines: IDefineMap[] = [];
+ @property
+ protected _props: Array> = [];
+
+ protected _passes: Pass[] = [];
+ protected _owner: RenderableComponent | null = null;
+ protected _hash = 0;
+
+ constructor (info?: IMaterialInfo) {
+ super();
+ if (info) {
+ if (info.technique) { this._techIdx = info.technique; }
+ if (info.defines) { this.setDefines(info.defines); }
+ if (info.effectName) { this.effectName = info.effectName; }
+ }
+ }
+
+ @property
+ set effectAsset (val: EffectAsset | null) {
+ if (!val || this.effectName !== val.name) { this.update(val, false); }
+ }
+ get effectAsset () {
+ return this._effectAsset;
+ }
+ // helper setter
+ @property
+ set effectName (val) {
+ if (this.effectName !== val) { this.update(val, false); }
+ }
+ get effectName () {
+ return this._effectAsset ? this._effectAsset.name : '';
+ }
+
+ @property
+ set technique (val: number) {
+ this._techIdx = val;
+ if (val !== this._techIdx) {
+ this._techIdx = val;
+ this.update();
+ }
+ }
+ get technique () {
+ return this._techIdx;
+ }
+
+ get passes () {
+ return this._passes;
+ }
+
+ get hash () {
+ return this._hash;
+ }
+
+ public setDefines (defines: IDefineMap | IDefineMap[]) {
+ this._defines = Array.isArray(defines) ? defines : [defines];
+ this.update();
+ }
+
+ /**
+ * Convenient setter provided for quick material setup.
+ * pass.setUniform should be used instead
+ * if you need to do per-frame property update.
+ */
+ public setProperty (name: string, val: any, passIdx?: number) {
+ let success = false;
+ if (passIdx === undefined) { // set property for all applicable passes
+ const passes = this._passes;
+ const len = passes.length;
+ for (let i = 0; i < len; i++) {
+ const pass = passes[i];
+ if (this._uploadProperty(pass, name, val)) {
+ this._props[i][name] = val;
+ success = true;
+ }
+ }
+ } else {
+ if (passIdx >= this._passes.length) { console.warn(`illegal pass index: ${passIdx}.`); return; }
+ const pass = this._passes[passIdx];
+ if (this._uploadProperty(pass, name, val)) {
+ this._props[passIdx][name] = val;
+ success = true;
+ }
+ }
+ if (!success) { console.warn(`illegal property name: ${name}.`); return; }
+ }
+
+ public copy (mat: Material) {
+ this._techIdx = mat._techIdx;
+ this._props.length = mat._props.length;
+ this._props.fill({});
+ for (let i = 0; i < mat._props.length; i++) {
+ Object.assign(this._props[i], mat._props[i]);
+ }
+ Object.assign(this._defines, mat._defines);
+ this.update(mat.effectAsset);
+ this._uuid = mat._uuid;
+ }
+
+ public onLoaded () {
+ this.update();
+ }
+
+ public overridePipelineStates (overrides: PassOverrides, passIdx?: number) {
+ if (!this._passes || !this._effectAsset) { return; }
+ const passInfos = Effect.getPassInfos(this._effectAsset, this._techIdx);
+ if (passIdx === undefined) {
+ for (let i = 0; i < this._passes.length; i++) {
+ this._passes[i].overridePipelineStates(passInfos[i], overrides);
+ }
+ } else {
+ this._passes[passIdx].overridePipelineStates(passInfos[passIdx], overrides);
+ }
+ this.onPassChange();
+ }
+
+ public update (asset: EffectAsset | string | null = this._effectAsset, keepProps: boolean = true) {
+ // get effect asset
+ if (typeof asset === 'string') {
+ this._effectAsset = EffectAsset.get(asset);
+ if (!this._effectAsset) {
+ console.warn(`no effect named '${asset}' found`);
+ return;
+ }
+ } else {
+ this._effectAsset = asset;
+ }
+ if (!this._effectAsset) { return; }
+ // create passes
+ this._passes = Effect.parseEffect(this._effectAsset, {
+ techIdx: this._techIdx,
+ defines: this._defines,
+ });
+ // handle property values
+ this._props.length = this._passes.length;
+ if (keepProps) {
+ this._passes.forEach((pass, i) => {
+ let props = this._props[i];
+ if (!props) { props = this._props[i] = {}; }
+ for (const p of Object.keys(props)) {
+ const val = props[p];
+ if (!val) { continue; }
+ this._uploadProperty(pass, p, props[p]);
+ }
+ });
+ } else {
+ this._props.fill({});
+ }
+ this.onPassChange();
+ }
+
+ protected _uploadProperty (pass: Pass, name: string, val: any) {
+ const handle = pass.getHandle(name);
+ if (handle === undefined) { return false; }
+ const bindingType = Pass.getBindingTypeFromHandle(handle);
+ if (bindingType === GFXBindingType.UNIFORM_BUFFER) {
+ if (Array.isArray(val)) {
+ pass.setUniformArray(handle, val);
+ } else {
+ pass.setUniform(handle, val);
+ }
+ } else if (bindingType === GFXBindingType.SAMPLER) {
+ const textureView = val instanceof GFXTextureView ? val : val.getGFXTextureView();
+ if (!textureView) { console.warn('texture asset incomplete!'); return false; }
+ const binding = Pass.getBindingFromHandle(handle);
+ pass.bindTextureView(binding, textureView);
+ }
+ return true;
+ }
+
+ protected onPassChange () {
+ let str = '';
+ for (const pass of this._passes) {
+ str += pass.serializePipelineStates();
+ }
+ this._hash = murmurhash2_32_gc(str, 666);
+ if (this._owner) {
+ const comp = this._owner;
+ const index = comp.sharedMaterials.findIndex((m) => m === this);
+ // @ts-ignore
+ if (index >= 0) { comp._onRebuildPSO(index, this); }
+ }
+ }
+}
+
+cc.Material = Material;
diff --git a/cocos/3d/assets/mesh.js b/cocos/3d/assets/mesh.js
deleted file mode 100644
index 35a2de09dd..0000000000
--- a/cocos/3d/assets/mesh.js
+++ /dev/null
@@ -1,272 +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.
- ****************************************************************************/
-
-// @ts-check
-import { _decorator } from "../../core/data/index";
-const { ccclass, property } = _decorator;
-import Asset from "../../assets/CCAsset";
-import gfx from "../../renderer/gfx";
-import { enums as gfxEnums } from "../../renderer/gfx/enums";
-import InputAssembler from "../../renderer/core/input-assembler";
-import BufferRange from "./utils/buffer-range";
-import { Vec3 } from "../../core/value-types";
-
-/**
- * A vertex bundle describes a serials of vertex attributes.
- * These vertex attributes occupy a range of the buffer and
- * are interleaved, no padding bytes, in the range.
- */
-@ccclass("cc.VertexBundle")
-export class VertexBundle {
- /**
- * The data range of this bundle.
- * This range of data is essentially mapped to a GPU vertex buffer.
- * @type {BufferRange}
- */
- @property(BufferRange)
- _data = null;
-
- /**
- * This bundle's vertices count.
- * @type {number}
- */
- @property(Number)
- _verticesCount = 0;
-
- /**
- * The attributes's formats.
- * @type {{name: string, type: number, num: number, normalize: boolean}[]}
- */
- @property
- _formats = [];
-}
-cc.VertexBundle = VertexBundle;
-
-/**
- * A primitive is a geometry constituted with a list of
- * same topology primitive graphic(such as points, lines or triangles).
- */
-@ccclass("cc.Primitive")
-export class Primitive {
-
- /**
- * The vertex bundles that this primitive use.
- * @type {number[]}
- */
- @property([Number])
- _vertexBundelIndices = [];
-
- /**
- * The indices data range of this primitive.
- * @type {BufferRange}
- */
- @property(BufferRange)
- _indices = null;
-
- /**
- * The type of this primitive's indices.
- * @type {number}
- */
- @property(Number)
- _indexUnit = gfxEnums.INDEX_FMT_UINT16;
-
- /**
- * This primitive's topology.
- * @type {number}
- */
- @property(Number)
- _topology = gfxEnums.PT_TRIANGLES;
-}
-cc.Primitive = Primitive;
-
-@ccclass('cc.Mesh')
-export default class Mesh extends Asset {
- /**
- * The vertex bundles that this mesh owns.
- * @type {VertexBundle[]}
- */
- @property([VertexBundle])
- _vertexBundles = [];
-
- /**
- * @type {Primitive[]}
- */
- @property([Primitive])
- _primitives = [];
-
- /**
- * The min position of this mesh's vertices.
- */
- @property(Vec3)
- _minPosition = null;
-
- /**
- * The max position of this mesh's vertices.
- */
- @property(Vec3)
- _maxPosition = null;
-
- constructor() {
- super();
-
- /**
- * @type {InputAssembler[]}
- */
- this._subMeshes = null;
-
- /**
- * @type {Uint8Array}
- */
- this._data = null;
- }
-
- get _nativeAsset() {
- return this._data;
- }
-
- set _nativeAsset(value) {
- this._data = value;
- }
-
- /**
- *
- */
- _lazyInitRenderResources() {
- if (this._subMeshes != null) {
- return;
- }
-
- this._subMeshes = [];
-
- if (this._data === null) {
- return;
- }
- const buffer = this._getBuffer();
- const vertexBuffers = this._vertexBundles.map((vertexBundle) => {
- return new gfx.VertexBuffer(
- cc.game._renderContext,
- new gfx.VertexFormat(vertexBundle._formats),
- gfx.USAGE_STATIC,
- new Uint8Array(buffer, vertexBundle._data._offset, vertexBundle._data._length),
- vertexBundle._verticesCount);
- });
- this._subMeshes = this._primitives.map((primitive) => {
- if (primitive._vertexBundelIndices.length === 0) {
- return null;
- }
-
- // Currently, an IA only has one vertex buffer.
- const vertexBuffer = vertexBuffers[primitive._vertexBundelIndices[0]];
-
- const indexBuffer = new gfx.IndexBuffer(
- cc.game._renderContext,
- primitive._indexUnit,
- gfx.USAGE_STATIC,
- new DataView(buffer, primitive._indices._offset, primitive._indices._length),
- primitive._indices._length / this._getIndexUnitSize(primitive._indexUnit)
- );
-
- return new InputAssembler(vertexBuffer, indexBuffer);
- });
- }
-
- /**
- * !#en
- * Destory this mesh and immediately release its video memory.
- */
- destroy() {
- if (this._subMeshes !== null) {
- // Destroy vertex buffer
- this._subMeshes[0]._vertexBuffer.destroy();
- // Destroy index buffers
- for (let i = 0; i < this._subMeshes.length; ++i) {
- this._subMeshes[i]._indexBuffer.destroy();
- }
- this._subMeshes = null;
- }
-
- return super.destroy();
- }
-
- /**
- * !#en
- * Submeshes count of this mesh.
- * @type {number}
- */
- get subMeshCount() {
- this._lazyInitRenderResources();
- return this._subMeshes.length;
- }
-
- /**
- * !#en
- * Gets the specified submesh.
- * @param {number} index Index of the specified submesh.
- */
- getSubMesh(index) {
- this._lazyInitRenderResources();
- return this._subMeshes[index];
- }
-
- get minPosition() {
- return this._minPosition;
- }
-
- get maxPosition() {
- return this._maxPosition;
- }
-
- // TODO
- // updateData () {
- // // store the data
- // if (this._persist) {
- // if (this._data) {
- // this._data.set(data, offset);
- // } else {
- // this._data = data;
- // }
- // }
- // }
-
- /**
- * @return {ArrayBuffer}
- */
- _getBuffer() {
- return this._data.buffer;
- }
-
- _getIndexUnitSize(indexUnit) {
- switch (indexUnit) {
- case gfxEnums.INDEX_FMT_UINT8:
- return 1;
- case gfxEnums.INDEX_FMT_UINT16:
- return 2;
- case gfxEnums.INDEX_FMT_UINT32:
- return 3;
- }
- return 1;
- }
-}
-cc.Mesh = Mesh;
diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts
new file mode 100644
index 0000000000..a6135dc2d5
--- /dev/null
+++ b/cocos/3d/assets/mesh.ts
@@ -0,0 +1,530 @@
+/****************************************************************************
+ 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 { Asset } from '../../assets/asset';
+import { ccclass, property } from '../../core/data/class-decorator';
+import { Vec3 } from '../../core/value-types';
+import { ccenum } from '../../core/value-types/enum';
+import { GFXBuffer } from '../../gfx/buffer';
+import { GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../gfx/define';
+import { GFXDevice } from '../../gfx/device';
+import { GFXInputAssembler, IGFXInputAssemblerInfo, IGFXInputAttribute } from '../../gfx/input-assembler';
+import { IBufferRange } from './utils/buffer-range';
+
+export enum AttributeBaseType {
+ /**
+ * 8 bits signed integer.
+ */
+ INT8,
+
+ /**
+ * 8 bits unsigned integer.
+ */
+ UINT8,
+
+ /**
+ * 16 bits signed integer.
+ */
+ INT16,
+
+ /**
+ * 16 bits unsigned integer.
+ */
+ UINT16,
+
+ /**
+ * 32 bits signed integer.
+ */
+ INT32,
+
+ /**
+ * 32 bits unsigned integer.
+ */
+ UINT32,
+
+ /**
+ * 32 bits floating number.
+ */
+ FLOAT32,
+}
+
+ccenum(AttributeBaseType);
+
+export enum AttributeType {
+ /**
+ * Scalar.
+ */
+ SCALAR,
+
+ /**
+ * 2 components vector.
+ */
+ VEC2,
+
+ /**
+ * 3 components vector.
+ */
+ VEC3,
+
+ /**
+ * 4 components vector.
+ */
+ VEC4,
+}
+
+ccenum(AttributeType);
+
+export enum IndexUnit {
+ /**
+ * 8 bits unsigned integer.
+ */
+ UINT8,
+
+ /**
+ * 8 bits unsigned integer.
+ */
+ UINT16,
+
+ /**
+ * 8 bits unsigned integer.
+ */
+ UINT32,
+}
+
+ccenum(IndexUnit);
+
+function getIndexUnitStride (indexUnit: IndexUnit) {
+ switch (indexUnit) {
+ case IndexUnit.UINT8: return 1;
+ case IndexUnit.UINT16: return 2;
+ case IndexUnit.UINT32: return 3;
+ }
+ return 1;
+}
+
+function getIndexUnitCtor (indexUnit: IndexUnit) {
+ switch (indexUnit) {
+ case IndexUnit.UINT8: return Uint8Array;
+ case IndexUnit.UINT16: return Uint16Array;
+ case IndexUnit.UINT32: return Uint32Array;
+ }
+ return Uint8Array;
+}
+
+export interface IVertexAttribute {
+ /**
+ * Attribute Name.
+ */
+ name: string;
+
+ /**
+ * Attribute base type.
+ */
+ baseType: AttributeBaseType;
+
+ /**
+ * Attribute type.
+ */
+ type: AttributeType;
+
+ /**
+ * Whether normalize.
+ */
+ normalize: boolean;
+}
+
+function toGFXAttributeType (vertexAttribute: IVertexAttribute) {
+ let formatName = '';
+ switch (vertexAttribute.type) {
+ case AttributeType.SCALAR:
+ formatName = 'R';
+ break;
+ case AttributeType.VEC2:
+ formatName = 'RG';
+ break;
+ case AttributeType.VEC3:
+ formatName = 'RGB';
+ break;
+ case AttributeType.VEC4:
+ formatName = 'RGBA';
+ break;
+ }
+ switch (vertexAttribute.baseType) {
+ case AttributeBaseType.INT8:
+ formatName += '8I';
+ break;
+ case AttributeBaseType.UINT8:
+ formatName += '8UI';
+ break;
+ case AttributeBaseType.INT16:
+ formatName += '16I';
+ break;
+ case AttributeBaseType.UINT16:
+ formatName += '16UI';
+ break;
+ case AttributeBaseType.INT32:
+ formatName += '32I';
+ break;
+ case AttributeBaseType.UINT32:
+ formatName += '32UI';
+ break;
+ case AttributeBaseType.FLOAT32:
+ formatName += '32F';
+ break;
+ }
+
+ const resultFormat = GFXFormat[formatName];
+ if (resultFormat !== undefined) {
+ return resultFormat;
+ }
+
+ return GFXFormat.R8UI;
+}
+
+export interface IVertexBundle {
+ /**
+ * The data range of this bundle.
+ * This range of data is essentially mapped to a GPU vertex buffer.
+ */
+ data: IBufferRange;
+
+ /**
+ * This bundle's vertices count.
+ */
+ verticesCount: number;
+
+ /**
+ * Attributes.
+ */
+ attributes: IVertexAttribute[];
+}
+
+/**
+ * A primitive is a geometry constituted with a list of
+ * same topology primitive graphic(such as points, lines or triangles).
+ */
+export interface IPrimitive {
+ /**
+ * The vertex bundles that this primitive use.
+ */
+ vertexBundelIndices: number[];
+
+ /**
+ * This primitive's topology.
+ */
+ primitiveMode: GFXPrimitiveMode;
+
+ indices?: {
+ /**
+ * The indices data range of this primitive.
+ */
+ range: IBufferRange;
+
+ /**
+ * The type of this primitive's indices.
+ */
+ indexUnit: IndexUnit;
+ };
+
+ /**
+ * Geometric info for raycast purposes.
+ */
+ geometricInfo?: {
+ doubleSided?: boolean;
+ range: IBufferRange;
+ };
+}
+
+/**
+ * Describes a mesh.
+ */
+export interface IMeshStruct {
+ /**
+ * The vertex bundles that this mesh owns.
+ */
+ vertexBundles: IVertexBundle[];
+
+ /**
+ * The primitives that this mesh owns.
+ */
+ primitives: IPrimitive[];
+
+ /**
+ * The min position of this mesh's vertices.
+ */
+ minPosition?: Vec3;
+
+ /**
+ * The max position of this mesh's vertices.
+ */
+ maxPosition?: Vec3;
+}
+
+// for raycast purpose
+export type IBArray = Uint8Array | Uint16Array | Uint32Array;
+export interface IGeometricInfo {
+ positions: Float32Array;
+ indices: IBArray;
+ doubleSided?: boolean;
+}
+
+export interface IRenderingSubmesh {
+ vertexBuffers: GFXBuffer[];
+ indexBuffer: GFXBuffer;
+ indirectBuffer?: GFXBuffer;
+ attributes: IGFXInputAttribute[];
+ primitiveMode: GFXPrimitiveMode;
+ geometricInfo?: IGeometricInfo;
+}
+
+export class RenderingMesh {
+ public constructor (
+ private _subMeshes: Array,
+ private _vertexBuffers: GFXBuffer[],
+ private _indexBuffers: GFXBuffer[]) {
+
+ }
+
+ public get subMeshCount () {
+ return this._subMeshes.length;
+ }
+
+ public getSubmesh (index: number) {
+ return this._subMeshes[index];
+ }
+
+ public destroy () {
+ this._vertexBuffers.forEach((vertexBuffer) => {
+ vertexBuffer.destroy();
+ });
+ this._vertexBuffers.length = 0;
+
+ this._indexBuffers.forEach((indexBuffer) => {
+ indexBuffer.destroy();
+ });
+ this._indexBuffers.length = 0;
+ this._subMeshes.length = 0;
+ }
+}
+
+@ccclass('cc.Mesh')
+export class Mesh extends Asset {
+
+ get _nativeAsset () {
+ return this._data;
+ }
+
+ set _nativeAsset (value) {
+ this._data = value;
+ }
+
+ /**
+ * Submeshes count of this mesh.
+ * @deprecated Use this.renderingMesh.subMeshCount instead.
+ */
+ get subMeshCount () {
+ const renderingMesh = this.renderingMesh;
+ return renderingMesh ? renderingMesh.subMeshCount : 0;
+ }
+
+ /**
+ * Min position of this mesh.
+ * @deprecated Use this.struct.minPosition instead.
+ */
+ get minPosition () {
+ return this.struct.minPosition;
+ }
+
+ /**
+ * Max position of this mesh.
+ * @deprecated Use this.struct.maxPosition instead.
+ */
+ get maxPosition () {
+ return this.struct.maxPosition;
+ }
+
+ get struct () {
+ return this._struct;
+ }
+
+ get data () {
+ return this._data;
+ }
+
+ @property
+ private _struct: IMeshStruct = {
+ vertexBundles: [],
+ primitives: [],
+ };
+
+ private _data: Uint8Array | null = null;
+
+ private _initialized = false;
+
+ private _renderingMesh: RenderingMesh | null = null;
+
+ constructor () {
+ super();
+ }
+
+ /**
+ * Destory this mesh and immediately release its GPU resources.
+ */
+ public destroy () {
+ this._tryDestroyRenderingMesh();
+ return super.destroy();
+ }
+
+ /**
+ * Assigns new mesh struct to this.
+ * @param struct The new mesh's struct.
+ * @param data The new mesh's data.
+ */
+ public assign (struct: IMeshStruct, data: Uint8Array) {
+ this._struct = struct;
+ this._data = data;
+ this._tryDestroyRenderingMesh();
+ }
+
+ /**
+ * Gets the rendering mesh.
+ */
+ public get renderingMesh () {
+ this._deferredInit();
+ return this._renderingMesh;
+ }
+
+ /**
+ * !#en
+ * Gets the specified submesh.
+ * @param index Index of the specified submesh.
+ * @deprecated Use this.renderingMesh.getSubmesh(index).inputAssembler instead.
+ */
+ public getSubMesh (index: number) {
+ const renderingSubmesh = this.renderingMesh ? this.renderingMesh.getSubmesh(index) : null;
+ return renderingSubmesh;
+ }
+
+ private _deferredInit () {
+ if (this._initialized) {
+ return;
+ }
+
+ this._initialized = true;
+
+ if (this._data === null) {
+ return;
+ }
+
+ const buffer = this._data.buffer;
+
+ const gfxDevice = cc.director.root.device as GFXDevice;
+
+ const vertexBuffers = this._createVertexBuffers(gfxDevice, buffer);
+
+ const indexBuffers: GFXBuffer[] = [];
+
+ const renderingSubmeshes = this._struct.primitives.map((primitive) => {
+ if (primitive.vertexBundelIndices.length === 0) {
+ return null;
+ }
+
+ let indexBuffer: GFXBuffer | null = null;
+ let ib: any = null;
+ if (primitive.indices) {
+ const indices = primitive.indices;
+
+ indexBuffer = gfxDevice.createBuffer({
+ usage: GFXBufferUsageBit.INDEX | GFXBufferUsageBit.TRANSFER_DST,
+ memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE,
+ size: indices.range.length,
+ stride: getIndexUnitStride(indices.indexUnit),
+ });
+ indexBuffers.push(indexBuffer);
+
+ ib = new (getIndexUnitCtor(indices.indexUnit))(buffer, indices.range.offset,
+ indices.range.length / getIndexUnitStride(indices.indexUnit));
+ indexBuffer.update(ib);
+ }
+
+ const gfxAttributes: IGFXInputAttribute[] = [];
+ primitive.vertexBundelIndices.forEach((iVertexBundle) => {
+ const vertexBundle = this._struct.vertexBundles[iVertexBundle];
+ vertexBundle.attributes.forEach((attribute) => {
+ const gfxAttribute: IGFXInputAttribute = {
+ name: attribute.name,
+ format: toGFXAttributeType(attribute),
+ stream: iVertexBundle,
+ };
+ if ('normalize' in attribute) {
+ gfxAttribute.isNormalized = attribute.normalize;
+ }
+ gfxAttributes.push(gfxAttribute);
+ });
+ });
+
+ const vbReference = primitive.vertexBundelIndices.map(
+ (i) => vertexBuffers[i]);
+
+ const geomInfo: any = primitive.geometricInfo;
+ if (geomInfo) {
+ geomInfo.indices = ib;
+ geomInfo.positions = new Float32Array(buffer, geomInfo.range.offset, geomInfo.range.length / 4);
+ }
+
+ return {
+ primitiveMode: primitive.primitiveMode,
+ vertexBuffers: vbReference,
+ indexBuffer,
+ attributes: gfxAttributes,
+ geometricInfo: geomInfo,
+ } as IRenderingSubmesh;
+ });
+
+ this._renderingMesh = new RenderingMesh(renderingSubmeshes, vertexBuffers, indexBuffers);
+ }
+
+ private _createVertexBuffers (gfxDevice: GFXDevice, data: ArrayBuffer): GFXBuffer[] {
+ return this._struct.vertexBundles.map((vertexBundle) => {
+ const vertexBuffer = gfxDevice.createBuffer({
+ usage: GFXBufferUsageBit.VERTEX | GFXBufferUsageBit.TRANSFER_DST,
+ memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE,
+ size: vertexBundle.data.length,
+ stride: vertexBundle.data.length / vertexBundle.verticesCount,
+ });
+ vertexBuffer.update(new Uint8Array(data, vertexBundle.data.offset, vertexBundle.data.length));
+ return vertexBuffer;
+ });
+ }
+
+ private _tryDestroyRenderingMesh () {
+ if (this._renderingMesh) {
+ this._renderingMesh.destroy();
+ this._renderingMesh = null;
+ this._initialized = false;
+ }
+ }
+}
+cc.Mesh = Mesh;
diff --git a/cocos/3d/assets/opentype-font.js b/cocos/3d/assets/opentype-font.js
index bcf867b98b..12ac748ac5 100644
--- a/cocos/3d/assets/opentype-font.js
+++ b/cocos/3d/assets/opentype-font.js
@@ -23,13 +23,12 @@
THE SOFTWARE.
****************************************************************************/
// @ts-check
-import { _decorator } from "../../core/data/index";
-const {ccclass} = _decorator;
+import { ccclass } from "../../core/data/class-decorator";
import Font from "./font";
-import vec2 from "../../core/vmath/vec2";
+import { vec2 } from "../../core/vmath";
import ShelfPack from "./utils/shelf-pack";
-import ImageAsset from "../../assets/image-asset";
-import Texture2D from "../../assets/texture-2d";
+import { ImageAsset } from "../../assets/image-asset";
+import { Texture2D } from "../../assets/texture-2d";
@ccclass('cc.OpentypeFont')
export default class OpentypeFont extends Font {
diff --git a/cocos/3d/assets/physics/material.ts b/cocos/3d/assets/physics/material.ts
index accaa91ba0..6e7d6293f2 100644
--- a/cocos/3d/assets/physics/material.ts
+++ b/cocos/3d/assets/physics/material.ts
@@ -2,7 +2,7 @@
// @ts-check
import CANNON from 'cannon';
-import Asset from '../../../assets/CCAsset';
+import { Asset } from '../../../assets/asset';
import { ccclass, property } from '../../../core/data/class-decorator';
@ccclass('cc.PhysicalMaterial')
diff --git a/cocos/3d/assets/skeleton.js b/cocos/3d/assets/skeleton.ts
similarity index 67%
rename from cocos/3d/assets/skeleton.js
rename to cocos/3d/assets/skeleton.ts
index 3efca75a9d..e3d9d5806d 100644
--- a/cocos/3d/assets/skeleton.js
+++ b/cocos/3d/assets/skeleton.ts
@@ -23,11 +23,10 @@
THE SOFTWARE.
****************************************************************************/
-// @ts-check
-import { _decorator } from "../../core/data";
+import { _decorator } from '../../core/data';
const { ccclass, property } = _decorator;
-import Asset from "../../assets/CCAsset";
-import { Mat4 } from "../../core/value-types";
+import { Asset } from '../../assets/asset';
+import { Mat4 } from '../../core/value-types';
/**
* CLASS Skeleton
@@ -40,42 +39,46 @@ import { Mat4 } from "../../core/value-types";
*/
@ccclass('cc.Skeleton')
export default class Skeleton extends Asset {
- /**
- * The path of joints.
- * @type {string[]}
- */
- @property([String])
- _joints = [];
+ /**
+ * The path of joints.
+ */
+ @property([String])
+ private _joints: string[] = [];
- /**
- * The inverse bind matrices of joints.
- * @type {Mat4[]}
- */
- @property([Mat4])
- _inverseBindMatrices = [];
+ /**
+ * The inverse bind matrices of joints.
+ */
+ @property([Mat4])
+ private _inverseBindMatrices: Mat4[] = [];
- /**
- * Gets the bind pose matrices of joints.
- * @type {Mat4[]}
- */
- get bindposes() {
- return this._inverseBindMatrices;
- }
+ /**
+ * Gets the bind pose matrices of joints.
+ */
+ get bindposes () {
+ return this._inverseBindMatrices;
+ }
- /**
- * Sets the bind pose matrices of joints.
- * @type {Mat4[]}
- */
- set bindposes(value) {
- this._inverseBindMatrices = value;
- }
+ /**
+ * Sets the bind pose matrices of joints.
+ */
+ set bindposes (value) {
+ this._inverseBindMatrices = value;
+ }
- /**
- * Gets the paths of joints.
- * @type {string[]}
- */
- get joints() {
- return this._joints;
- }
+ /**
+ * Gets the paths of joints.
+ */
+ get joints () {
+ return this._joints;
+ }
+
+ /**
+ * Sets the paths of joints.
+ */
+ set joints (value) {
+ this._joints = value;
+ }
}
-cc.Skeleton = Skeleton;
\ No newline at end of file
+
+// tslint:disable-next-line
+cc['Skeleton'] = Skeleton;
diff --git a/cocos/3d/assets/sprite.js b/cocos/3d/assets/sprite.js
index 93c544ea7b..48144fa563 100644
--- a/cocos/3d/assets/sprite.js
+++ b/cocos/3d/assets/sprite.js
@@ -25,7 +25,7 @@
// @ts-check
import { _decorator } from "../../core/data/index";
const { ccclass } = _decorator;
-import Asset from "../../assets/CCAsset";
+import { Asset } from "../../assets/asset";
import { vec3, mat4 } from '../../core/vmath/index';
let _t_tmp = vec3.create(0, 0, 0);
@@ -200,4 +200,4 @@ export default class Sprite extends Asset {
}
}
-cc.Sprite = Sprite;
\ No newline at end of file
+cc.Sprite = Sprite;
diff --git a/cocos/3d/assets/texture-cube.js b/cocos/3d/assets/texture-cube.js
deleted file mode 100644
index 8b22687e16..0000000000
--- a/cocos/3d/assets/texture-cube.js
+++ /dev/null
@@ -1,285 +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.
- ****************************************************************************/
-// @ts-check
-import GFXTextureCube from '../../renderer/gfx/texture-cube';
-import TextureBase from '../../assets/texture-base';
-import { ccclass, property } from '../../core/data/class-decorator';
-import ImageAsset from '../../assets/image-asset';
-
-/**
- * @typedef {import("../../assets/texture-2d")} Texture2D
- * @typedef {import("../../assets/texture-base").ImageSource} ImageSource
- * @typedef {import("../../assets/texture-base").TextureUpdateOpts} TextureUpdateOpts
- * @typedef {import("../../assets/texture-base").HTMLImageSource} HTMLImageSource
- * @typedef {{front: HTMLImageSource, back: HTMLImageSource, left: HTMLImageSource, right: HTMLImageSource, top: HTMLImageSource, bottom: HTMLImageSource}} MipmapHTMLImageSource
- * @typedef {{front: ImageAsset, back: ImageAsset, left: ImageAsset, right: ImageAsset, top: ImageAsset, bottom: ImageAsset}} Mipmap
- */
-
-/**
- * @enum {number}
- */
-const FaceIndex = cc.Enum({
- right: 0,
- left: 1,
- top: 2,
- bottom: 3,
- front: 4,
- back: 5
-});
-
-@ccclass('cc.TextureCube')
-export default class TextureCube extends TextureBase {
- /**
- * @type {Mipmap[]}
- */
- @property
- _mipmaps = [];
-
- constructor() {
- super();
-
- /**
- * @type {GFXTextureCube}
- */
- this._texture = null;
- }
-
- /**
- * Gets the mipmap images.
- * Note that the result do not contains the auto generated mipmaps.
- * @type {Mipmap[]}
- */
- get mipmaps() {
- return this._mipmaps;
- }
-
- /**
- * Sets the mipmaps images.
- * @type {Mipmap[]}
- */
- set mipmaps(value) {
- this._setMipmaps(value);
- }
-
- /**
- * Gets the mipmap image at level 0.
- * @type {Mipmap}
- */
- get image() {
- return this._mipmaps.length === 0 ? null : this._mipmaps[0];
- }
-
- /**
- * Sets the mipmap images as a single mipmap image.
- * @type {Mipmap}
- */
- set image(value) {
- this.mipmaps = [value];
- }
-
- /**
- * Gets the underlying texture object.
- */
- getImpl () {
- return this._texture;
- }
-
- /**
- * !#en
- * Destory this texture and immediately release its video memory. (Inherit from cc.Object.destroy)
- * After destroy, this object is not usable any more.
- * You can use cc.isValid(obj) to check whether the object is destroyed before accessing it.
- * !#zh
- * 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)
- * 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。
- * @method destroy
- * @return {Boolean} inherit from the CCObject
- */
- destroy () {
- this.releaseTexture();
- // TODO cc.textureUtil ?
- // cc.textureCache.removeTextureForKey(this.url); // item.rawUrl || item.url
- return super.destroy();
- }
-
- /**
- * !#en
- * Release texture, please use destroy instead.
- * !#zh 释放纹理,请使用 destroy 替代。
- * @method releaseTexture
- * @deprecated since v2.0
- */
- releaseTexture () {
- this._setMipmaps([]);
- this._texture && this._texture.destroy();
- }
-
- /**
- * Sets the _mipmaps to specified value, and updates the width and height accordingly.
- * If available, synchronize the mipmap data to underlying texture.
- * @param {Mipmap[]} mipmaps
- */
- _setMipmaps(mipmaps) {
- this._mipmaps = mipmaps;
- if (mipmaps.length === 0) {
- super.update({
- width: 0,
- height: 0
- });
- } else {
- super.update({
- width: this._mipmaps[0].front.width,
- height: this._mipmaps[0].front.height,
- format: this._mipmaps[0].front._format
- });
- }
-
- let counter = 0;
- const inc = () => {
- ++counter;
- if (counter === this._mipmaps.length * 6) {
- this._updateMipmaps(this._mipmaps.map(mipmap => TextureCube._toMipmapArray(mipmap)));
- }
- };
- mipmaps.forEach(mipmap => {
- TextureCube._forEachFace(mipmap, face => {
- if (face.loaded) {
- inc();
- } else {
- face.addEventListener("load", () => inc());
- }
- });
- });
- }
-
- /**
- * Updates mipmaps of the underlying texture.
- * @param {ImageSource[][]} mipmapSources
- */
- _updateMipmaps(mipmapSources) {
- const opts = this._getOpts();
- opts.images = mipmapSources;
- if (!this._texture) {
- this._texture = new GFXTextureCube(cc.game._renderContext, opts);
- } else {
- this._texture.update(opts);
- }
- }
-
- /**
- * Update texture options, not available in Canvas render mode.
- * image, format, premultiplyAlpha can not be updated in native.
- * @method update
- */
- update (options) {
- if (!options) return;
-
- super.update(options);
-
- // TODO: options.image
-
- if (this._texture) {
- this._texture.update(options);
- }
- }
-
- /**
- * @param {Mipmap} mipmap
- * @return {ImageSource[]}
- */
- static _toMipmapArray(mipmap) {
- /** @type {ImageSource[]} */
- const result = new Array();
- result[FaceIndex.front] = mipmap.front.data;
- result[FaceIndex.back] = mipmap.back.data;
- result[FaceIndex.left] = mipmap.left.data;
- result[FaceIndex.right] = mipmap.right.data;
- result[FaceIndex.top] = mipmap.top.data;
- result[FaceIndex.bottom] = mipmap.bottom.data;
- return result;
- }
-
- /**
- * @param {Mipmap} mipmap
- * @param {(face: ImageAsset) => void} callback
- */
- static _forEachFace(mipmap, callback) {
- for (let face in mipmap) {
- callback(mipmap[face]);
- }
- }
-
- /**
- * @param {Texture2D[]} textures
- */
- static fromTexture2DArray(textures, out) {
- let res = [], mips = textures.length / 6;
- for (let i = 0; i < mips; i++) {
- res.push(textures.splice(0, 6).reduce((acc, img, i) => {
- acc[FaceIndex[i]] = img.image;
- return acc;
- }, {}));
- }
- if (!out) out = new TextureCube();
- out.mipmaps = res;
- return out;
- }
-
- _serialize() {
- return {
- base: super._serialize(),
- mipmaps: this._mipmaps.map(mipmap => {return {
- front: mipmap.front._uuid,
- back: mipmap.back._uuid,
- left: mipmap.left._uuid,
- right: mipmap.right._uuid,
- top: mipmap.top._uuid,
- bottom: mipmap.bottom._uuid,
- };})
- };
- }
-
- _deserialize (data, handle) {
- super._deserialize(data.base);
-
- this._mipmaps = new Array(data.mipmaps.length);
- this._mipmaps.fill({});
- for (let i = 0; i < data.mipmaps.length; ++i) {
- const mipmap = data.mipmaps[i];
- handle.result.push(this._mipmaps[i], `front`, mipmap.front);
- handle.result.push(this._mipmaps[i], `back`, mipmap.back);
- handle.result.push(this._mipmaps[i], `left`, mipmap.left);
- handle.result.push(this._mipmaps[i], `right`, mipmap.right);
- handle.result.push(this._mipmaps[i], `top`, mipmap.top);
- handle.result.push(this._mipmaps[i], `bottom`, mipmap.bottom);
- }
- }
-
- onLoaded() {
- this.mipmaps = this._mipmaps;
- }
-}
-
-cc.TextureCube = TextureCube;
diff --git a/cocos/3d/assets/texture-cube.ts b/cocos/3d/assets/texture-cube.ts
new file mode 100644
index 0000000000..22073f3130
--- /dev/null
+++ b/cocos/3d/assets/texture-cube.ts
@@ -0,0 +1,225 @@
+/****************************************************************************
+ 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 { Texture2D } from '../../assets';
+import { ImageAsset } from '../../assets/image-asset';
+import { TextureBase } from '../../assets/texture-base';
+import { ccclass, property } from '../../core/data/class-decorator';
+import { GFXTextureFlagBit, GFXTextureViewType } from '../../gfx/define';
+
+interface ITextureCubeMipmap {
+ front: ImageAsset;
+ back: ImageAsset;
+ left: ImageAsset;
+ right: ImageAsset;
+ top: ImageAsset;
+ bottom: ImageAsset;
+}
+
+@ccclass('cc.TextureCube')
+export class TextureCube extends TextureBase {
+ /**
+ * Gets the mipmap images.
+ * Note that the result do not contains the auto generated mipmaps.
+ */
+ get mipmaps () {
+ return this._mipmaps;
+ }
+
+ /**
+ * Sets the mipmaps images.
+ */
+ set mipmaps (value) {
+ this._mipmaps = value;
+ this.create(
+ value.length === 0 ? 0 : value[0].front.width,
+ value.length === 0 ? 0 : value[0].front.height,
+ undefined,
+ this._mipmaps.length);
+ this._mipmaps.forEach((mipmap, level) => {
+ _forEachFace(mipmap, (face, faceIndex) => {
+ this._assignImage(face, level, faceIndex);
+ });
+ });
+ }
+
+ /**
+ * Gets the mipmap image at level 0.
+ */
+ get image () {
+ return this._mipmaps.length === 0 ? null : this._mipmaps[0];
+ }
+
+ /**
+ * Sets the mipmap images as a single mipmap image.
+ */
+ set image (value) {
+ this.mipmaps = value ? [value] : [];
+ }
+
+ /**
+ * @param textures
+ * @deprecated Manually assign to mipmaps property instead.
+ */
+ public static fromTexture2DArray (textures: Texture2D[], out?: TextureCube) {
+ const mipmaps: ITextureCubeMipmap[] = [];
+ const nMipmaps = textures.length / 6;
+ for (let i = 0; i < nMipmaps; i++) {
+ const x = i * 6;
+ mipmaps.push({
+ front: textures[x + FaceIndex.front].image!,
+ back: textures[x + FaceIndex.back].image!,
+ left: textures[x + FaceIndex.left].image!,
+ right: textures[x + FaceIndex.right].image!,
+ top: textures[x + FaceIndex.top].image!,
+ bottom: textures[x + FaceIndex.bottom].image!,
+ });
+ }
+ if (!out) { out = new TextureCube(); }
+ out.mipmaps = mipmaps;
+ return out;
+ }
+
+ @property
+ public _mipmaps: ITextureCubeMipmap[] = [];
+
+ constructor () {
+ super();
+ }
+
+ /**
+ * !#en
+ * Destory this texture and immediately release its video memory. (Inherit from cc.Object.destroy)
+ * After destroy, this object is not usable any more.
+ * You can use cc.isValid(obj) to check whether the object is destroyed before accessing it.
+ * !#zh
+ * 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)
+ * 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。
+ */
+ public destroy () {
+ this._mipmaps = [];
+ return super.destroy();
+ }
+
+ /**
+ * !#en
+ * Release texture, please use destroy instead.
+ * !#zh 释放纹理,请使用 destroy 替代。
+ * @deprecated Since v2.0.
+ */
+ public releaseTexture () {
+ this.mipmaps = [];
+ }
+
+ public _serialize () {
+ return {
+ base: super._serialize(),
+ mipmaps: this._mipmaps.map((mipmap) => {return {
+ front: mipmap.front._uuid,
+ back: mipmap.back._uuid,
+ left: mipmap.left._uuid,
+ right: mipmap.right._uuid,
+ top: mipmap.top._uuid,
+ bottom: mipmap.bottom._uuid,
+ }; }),
+ };
+ }
+
+ public _deserialize (serializedData: ITextureCubeSerializeData, handle: any) {
+ const data = serializedData as ITextureCubeSerializeData;
+ super._deserialize(data.base, handle);
+
+ this._mipmaps = new Array(data.mipmaps.length);
+ for (let i = 0; i < data.mipmaps.length; ++i) {
+ // Prevent resource load failed
+ this._mipmaps[i] = {
+ front: new ImageAsset(),
+ back: new ImageAsset(),
+ left: new ImageAsset(),
+ right: new ImageAsset(),
+ top: new ImageAsset(),
+ bottom: new ImageAsset(),
+ };
+ const mipmap = data.mipmaps[i];
+ handle.result.push(this._mipmaps[i], `front`, mipmap.front);
+ handle.result.push(this._mipmaps[i], `back`, mipmap.back);
+ handle.result.push(this._mipmaps[i], `left`, mipmap.left);
+ handle.result.push(this._mipmaps[i], `right`, mipmap.right);
+ handle.result.push(this._mipmaps[i], `top`, mipmap.top);
+ handle.result.push(this._mipmaps[i], `bottom`, mipmap.bottom);
+ }
+ }
+
+ protected _getTextureCreateInfo () {
+ const result = super._getTextureCreateInfo();
+ result.arrayLayer = 6;
+ result.flags = (result.flags || 0) | GFXTextureFlagBit.CUBEMAP;
+ return result;
+ }
+
+ protected _getTextureViewCreateInfo () {
+ const result = super._getTextureViewCreateInfo();
+ result.type = GFXTextureViewType.CUBE;
+ result.layerCount = 6;
+ return result;
+ }
+}
+
+/* tslint:disable:no-string-literal */
+cc['TextureCube'] = TextureCube;
+
+interface ITextureCubeSerializeData {
+ base: string;
+ mipmaps: Array<{
+ front: string;
+ back: string;
+ left: string;
+ right: string;
+ top: string;
+ bottom: string;
+ }>;
+}
+
+enum FaceIndex {
+ right = 0,
+ left = 1,
+ top = 2,
+ bottom = 3,
+ front = 4,
+ back = 5,
+}
+
+/**
+ * @param {Mipmap} mipmap
+ * @param {(face: ImageAsset) => void} callback
+ */
+function _forEachFace (mipmap: ITextureCubeMipmap, callback: (face: ImageAsset, faceIndex: number) => void) {
+ callback(mipmap.front, FaceIndex.front);
+ callback(mipmap.back, FaceIndex.back);
+ callback(mipmap.left, FaceIndex.left);
+ callback(mipmap.right, FaceIndex.right);
+ callback(mipmap.top, FaceIndex.top);
+ callback(mipmap.bottom, FaceIndex.bottom);
+}
diff --git a/cocos/3d/assets/texture-sprite.js b/cocos/3d/assets/texture-sprite.js
index 1bc29e5e1b..50fc175f66 100644
--- a/cocos/3d/assets/texture-sprite.js
+++ b/cocos/3d/assets/texture-sprite.js
@@ -23,9 +23,8 @@
THE SOFTWARE.
****************************************************************************/
// @ts-check
-import { _decorator } from "../../core/data/index";
-const { ccclass, property } = _decorator;
-import Texture2D from '../../assets/texture-2d';
+import { ccclass, property } from "../../core/data/class-decorator";
+import { Texture2D } from '../../assets/texture-2d';
import Sprite from "./sprite";
@ccclass('cc.TextureSprite')
diff --git a/cocos/2d/renderer/webgl/assemblers/index.js b/cocos/3d/assets/utils/buffer-range.ts
similarity index 73%
rename from cocos/2d/renderer/webgl/assemblers/index.js
rename to cocos/3d/assets/utils/buffer-range.ts
index 65a9b28071..25f2f386ed 100644
--- a/cocos/2d/renderer/webgl/assemblers/index.js
+++ b/cocos/3d/assets/utils/buffer-range.ts
@@ -5,11 +5,11 @@
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
+ 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.
+ 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.
@@ -23,8 +23,7 @@
THE SOFTWARE.
****************************************************************************/
-require('./sprite');
-require('./mask-assembler');
-require('./graphics');
-require('./label');
-require('./motion-streak');
+export interface IBufferRange {
+ offset: number;
+ length: number;
+}
diff --git a/cocos/3d/builtin/effects.js b/cocos/3d/builtin/effects.js
index 9e58c5f82d..81f033dd9e 100644
--- a/cocos/3d/builtin/effects.js
+++ b/cocos/3d/builtin/effects.js
@@ -1,54 +1,106 @@
+// absolute essential effects
export default [
{
- "name": "builtin-effect-unlit",
- "techniques": [{"queue":0,"lod":100,"passes":[{"stage":1,"cullMode":1029,"depthTest":true,"depthWrite":true,"program":"aa204b4f36b7a4b0c9e10806d01c41a2dcdfba410236f788b8f97fc9"}],"priority":0}],
- "properties": {"color":{"type":9,"value":[1,1,1,1]},"mainTiling":{"type":5,"value":[1,1]},"mainOffset":{"type":5,"value":[0,0]},"mainTexture":{"type":13,"value":null}},
+ "name": "builtin-effect-particle-add",
+ "techniques": [{"passes":[{"rasterizerState":{"cullMode":0}, "depthStencilState":{"depthTest":true, "depthWrite":false}, "blendState":{"targets":[{"blend":true, "blendSrc":2, "blendDst":1, "blendSrcAlpha":2, "blendDstAlpha":1}]}, "program":"builtin-effect-particle-add|particle-vs-legacy:lpvs_main|particle-add-fs", "properties":{"mainTexture":{"type":29, "value":"grey"}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "frameTile":{"type":14, "value":[1, 1]}, "velocityScale":{"type":13, "value":[0]}, "lengthScale":{"type":13, "value":[0]}, "tintColor":{"type":17, "value":[0.5, 0.5, 0.5, 0.5]}}}]}],
"shaders": [
{
- "name": "aa204b4f36b7a4b0c9e10806d01c41a2dcdfba410236f788b8f97fc9",
- "vert": "\nattribute vec3 a_position;\nuniform mat4 _model;\nuniform mat4 _viewProj;\n#if USE_TEXTURE\n attribute vec2 a_uv0;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n varying vec2 uv0;\n#endif\n#if USE_SKINNING\n \nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if USE_JOINTS_TEXTURE\nuniform sampler2D _u_jointsTexture;\nuniform float _u_jointsTextureSize;\nmat4 getBoneMatrix(const in float i) {\n float size = _u_jointsTextureSize;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(_u_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(_u_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(_u_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(_u_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nuniform mat4 _u_jointMatrices[128];\nmat4 getBoneMatrix(const in float i) {\n return _u_jointMatrices[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w\n ;\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if USE_SKINNING\n pos = skinMatrix() * pos;\n #endif\n pos = _viewProj * _model * pos;\n #if USE_TEXTURE\n uv0 = a_uv0 * mainTiling + mainOffset;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n",
- "frag": "\n#if USE_TEXTURE\n uniform sampler2D mainTexture;\n varying vec2 uv0;\n#endif\n#if USE_COLOR\n uniform vec4 color;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture2D(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n",
+ "name": "builtin-effect-particle-add|particle-vs-legacy:lpvs_main|particle-add-fs",
+ "vert": "\n uniform vec2 frameTile;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n uniform float velocityScale;\n uniform float lengthScale;\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection[4];\n uniform vec4 cc_dirLightColor[4];\n uniform vec4 cc_pointLightPositionAndRange[4];\n uniform vec4 cc_pointLightColor[4];\n uniform vec4 cc_spotLightPositionAndRange[4];\n uniform vec4 cc_spotLightDirection[4];\n uniform vec4 cc_spotLightColor[4];\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n uniform mat4 cc_matWorld;\n uniform mat4 cc_matWorldIT;\nvarying vec2 uv;\nvarying vec4 color;\nvoid computeVertPos(inout vec4 pos, vec2 vertOffset\n#if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , mat4 view\n#endif\n#if USE_STRETCHED_BILLBOARD\n , vec3 eye\n , vec4 velocity\n , float velocityScale\n , float lengthScale\n , float size\n , float xIndex\n#endif\n) {\n#if USE_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = normalize(vec3(view[0][1], view[1][1], view[2][1]));\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_STRETCHED_BILLBOARD\n vec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz));\n vec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * size;\n pos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif USE_HORIZONTAL_BILLBOARD\n vec3 camRight = vec3(1, 0, 0);\n vec3 camUp = vec3(0, 0, -1);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#elif USE_VERTICAL_BILLBOARD\n vec3 camRight = normalize(vec3(view[0][0], view[1][0], view[2][0]));\n vec3 camUp = vec3(0, 1, 0);\n pos.xyz += (camRight * vertOffset.x) + (camUp * vertOffset.y);\n#else\n pos.x += vertOffset.x;\n pos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV(float frameIndex, vec2 vertIndex, vec2 frameTile) {\n vec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\n aniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n \n vertIndex.x = 1. - vertIndex.x;\n return (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nvoid rotateCorner(inout vec2 corner, float angle) {\n float xOS = cos(angle) * corner.x - sin(angle) * corner.y;\n float yOS = sin(angle) * corner.x + cos(angle) * corner.y;\n corner.x = xOS;\n corner.y = yOS;\n}\nattribute vec3 a_position; \nattribute vec3 a_texCoord; \nattribute vec2 a_texCoord1; \nattribute vec4 a_color;\n#if USE_STRETCHED_BILLBOARD\nattribute vec3 a_color1; \n#endif\nvec4 lpvs_main() {\n vec4 pos = vec4(a_position, 1);\n#if USE_STRETCHED_BILLBOARD\n vec4 velocity = vec4(a_color1.xyz, 0);\n#endif\n#if !USE_WORLD_SPACE\n pos = cc_matWorld * pos;\n #if USE_STRETCHED_BILLBOARD\n velocity = cc_matWorld * velocity;\n #endif\n#endif\n vec2 cornerOffset = vec2((a_texCoord.xy - 0.5) * a_texCoord1.x);\n#if !USE_STRETCHED_BILLBOARD\n \n rotateCorner(cornerOffset, a_texCoord1.y);\n#endif\n computeVertPos(pos, cornerOffset\n #if USE_BILLBOARD || USE_VERTICAL_BILLBOARD\n , cc_matView\n #endif\n #if USE_STRETCHED_BILLBOARD\n , cc_cameraPos\n , velocity\n , velocityScale\n , lengthScale\n , a_texCoord1.x\n , a_texCoord.x\n #endif\n );\n pos = cc_matViewProj * pos;\n uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile) * mainTiling + mainOffset;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = lpvs_main(); }\n",
+ "frag": "\n uniform sampler2D mainTexture;\n uniform vec4 tintColor;\n varying vec2 uv;\n varying vec4 color;\n void main () {\n \n gl_FragColor = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n }\n",
"defines": [
- {"name": "USE_TEXTURE", "type": "boolean"},
- {"name": "USE_SKINNING", "type": "boolean"},
- {"name": "USE_JOINTS_TEXTURE", "type": "boolean"},
- {"name": "USE_COLOR", "type": "boolean"}
+ {"name":"USE_BILLBOARD", "type":"boolean", "defines":[]},
+ {"name":"USE_STRETCHED_BILLBOARD", "type":"boolean", "defines":[]},
+ {"name":"USE_HORIZONTAL_BILLBOARD", "type":"boolean", "defines":[]},
+ {"name":"USE_VERTICAL_BILLBOARD", "type":"boolean", "defines":[]},
+ {"name":"USE_WORLD_SPACE", "type":"boolean", "defines":[]}
],
- "uniforms": [
- {"name": "mainTiling", "type": 5, "defines": ["USE_TEXTURE"]},
- {"name": "mainOffset", "type": 5, "defines": ["USE_TEXTURE"]},
- {"name": "mainTexture", "type": 13, "defines": ["USE_TEXTURE"]},
- {"name": "color", "type": 7, "defines": ["USE_COLOR"]}
+ "blocks": [
+ {"name": "Constants", "size": 32, "defines": [], "binding": 0, "members": [
+ {"name":"frameTile", "type":14, "count":1, "size":8},
+ {"name":"mainTiling", "type":14, "count":1, "size":8},
+ {"name":"mainOffset", "type":14, "count":1, "size":8},
+ {"name":"velocityScale", "type":13, "count":1, "size":4},
+ {"name":"lengthScale", "type":13, "count":1, "size":4}
+ ]},
+ {"name": "FragConstants", "size": 16, "defines": [], "binding": 1, "members": [
+ {"name":"tintColor", "type":16, "count":1, "size":16}
+ ]}
],
- "attributes": [
- {"name": "a_position", "type": 6, "defines": []},
- {"name": "a_uv0", "type": 5, "defines": ["USE_TEXTURE"]},
- {"name": "a_weights", "type": 7, "defines": ["USE_SKINNING"]},
- {"name": "a_joints", "type": 7, "defines": ["USE_SKINNING"]}
+ "samplers": [
+ {"name":"mainTexture", "type":29, "count":1, "defines":[], "binding":2}
],
- "extensions": []
+ "dependencies": {}
}
]
},
{
"name": "builtin-effect-skybox",
- "techniques": [{"queue":0,"lod":200,"passes":[{"stage":1,"cullMode":0,"program":"c4056e849fac08f88d82336386873a650bc636f4349623fecbf96c52"}],"priority":-1000}],
- "properties": {"cubeMap":{"type":14,"value":null}},
+ "techniques": [{"passes":[{"rasterizerState":{"cullMode":0}, "depthStencilState":{"depthTest":false, "depthWrite":false}, "program":"builtin-effect-skybox|sky-vs|sky-fs", "properties":{"cubeMap":{"type":32, "value":"white-cube"}}, "priority":245}]}],
"shaders": [
{
- "name": "c4056e849fac08f88d82336386873a650bc636f4349623fecbf96c52",
- "vert": "\n attribute vec3 a_position;\n uniform mat4 _view;\n uniform mat4 _proj;\n varying vec3 viewDir;\n void main() {\n mat4 rotView = mat4(mat3(_view));\n vec4 clipPos = _proj * rotView * vec4(a_position, 1.0);\n gl_Position = clipPos.xyww;\n viewDir = a_position;\n }\n",
+ "name": "builtin-effect-skybox|sky-vs|sky-fs",
+ "vert": "\n attribute vec3 a_position;\n \n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection[4];\n uniform vec4 cc_dirLightColor[4];\n uniform vec4 cc_pointLightPositionAndRange[4];\n uniform vec4 cc_pointLightColor[4];\n uniform vec4 cc_spotLightPositionAndRange[4];\n uniform vec4 cc_spotLightDirection[4];\n uniform vec4 cc_spotLightColor[4];\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n varying vec3 viewDir;\n void main() {\n mat4 matViewRotOnly = mat4(mat3(cc_matView));\n vec4 clipPos = cc_matProj * matViewRotOnly * vec4(a_position, 1.0);\n gl_Position = clipPos.xyww;\n viewDir = a_position;\n }\n",
"frag": "\n varying vec3 viewDir;\n uniform samplerCube cubeMap;\n \nvec3 gammaToLinearSpaceRGB(vec3 sRGB) { \n return sRGB * (sRGB * (sRGB * 0.305306011 + 0.682171111) + 0.012522878);\n}\nvec3 linearToGammaSpaceRGB(vec3 RGB) { \n vec3 S1 = sqrt(RGB);\n vec3 S2 = sqrt(S1);\n vec3 S3 = sqrt(S2);\n return 0.585122381 * S1 + 0.783140355 * S2 - 0.368262736 * S3;\n}\nvec4 gammaToLinearSpaceRGBA(vec4 sRGBA) {\n return vec4(gammaToLinearSpaceRGB(sRGBA.rgb), sRGBA.a);\n}\nvec4 linearToGammaSpaceRGBA(vec4 RGBA) {\n return vec4(linearToGammaSpaceRGB(RGBA.rgb), RGBA.a);\n}\nfloat gammaToLinearSpaceExact(float val) {\n if (val <= 0.04045) {\n return val / 12.92;\n } else if (val < 1.0) {\n return pow((val + 0.055) / 1.055, 2.4);\n } else {\n return pow(val, 2.2);\n }\n}\nfloat linearToGammaSpaceExact(float val) {\n if (val <= 0.0) {\n return 0.0;\n } else if (val <= 0.0031308) {\n return 12.92 * val;\n } else if (val < 1.0) {\n return 1.055 * pow(val, 0.4166667) - 0.055;\n } else {\n return pow(val, 0.45454545);\n }\n}\n \nvec3 unpackNormal(vec4 nmap) {\n return nmap.xyz * 2.0 - 1.0;\n}\nvec3 unpackRGBE(vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\n void main() {\n #if USE_RGBE_CUBEMAP\n vec3 c = unpackRGBE(textureCube(cubeMap, viewDir));\n c = linearToGammaSpaceRGB(c / (1.0 + c));\n gl_FragColor = vec4(c, 1.0);\n #else\n gl_FragColor = textureCube(cubeMap, viewDir);\n #endif\n }\n",
"defines": [
- {"name": "USE_RGBE_CUBEMAP", "type": "boolean"}
+ {"name":"USE_RGBE_CUBEMAP", "type":"boolean", "defines":[]}
],
- "uniforms": [
- {"name": "cubeMap", "type": 14, "defines": []}
+ "blocks": [],
+ "samplers": [
+ {"name":"cubeMap", "type":32, "count":1, "defines":[], "binding":0}
],
- "attributes": [
- {"name": "a_position", "type": 6, "defines": []}
+ "dependencies": {}
+ }
+ ]
+ },
+ {
+ "name": "builtin-effect-sprite",
+ "techniques": [{"passes":[{"depthStencilState":{"depthTest":true, "depthWrite":false}, "blendState":{"targets":[{"blend":true, "blendSrc":2, "blendDst":4, "blendDstAlpha":4}]}, "program":"builtin-effect-sprite|sprite-vs:vert|sprite-fs:frag", "properties":{"u_texSampler":{"type":29, "value":"default", "sampler":{"minFilter":2, "magFilter":2, "mipFilter":0, "addressU":2, "addressV":2}}}}]}],
+ "shaders": [
+ {
+ "name": "builtin-effect-sprite|sprite-vs:vert|sprite-fs:frag",
+ "vert": "\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\n uniform mat4 cc_matViewProj;\nvarying vec2 v_uv0;\nvarying vec4 v_color;\nvec4 vert () {\n vec4 pos = cc_matViewProj * vec4(a_position, 1);\n v_uv0 = a_texCoord;\n v_color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n",
+ "frag": "\nuniform sampler2D u_texSampler;\nvarying vec2 v_uv0;\nvarying vec4 v_color;\nvec4 frag () {\n return texture2D(u_texSampler, v_uv0) * v_color;\n \n}\nvoid main() { gl_FragColor = frag(); }\n",
+ "defines": [],
+ "blocks": [
+ {"name": "UI", "size": 64, "defines": [], "binding": 0, "members": [
+ {"name":"cc_matViewProj", "type":26, "count":1, "size":64}
+ ]}
],
- "extensions": []
+ "samplers": [
+ {"name":"u_texSampler", "type":29, "count":1, "defines":[], "binding":1}
+ ],
+ "dependencies": {}
+ }
+ ]
+ },
+ {
+ "name": "builtin-effect-unlit",
+ "techniques": [{"passes":[{"program":"builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag", "properties":{"color":{"type":17, "value":[1, 1, 1, 1]}, "mainTiling":{"type":14, "value":[1, 1]}, "mainOffset":{"type":14, "value":[0, 0]}, "mainTexture":{"type":29, "value":"grey"}}}]}],
+ "shaders": [
+ {
+ "name": "builtin-effect-unlit|unlit-vs:vert|unlit-fs:frag",
+ "vert": "\nattribute vec3 a_position;\n uniform vec4 cc_time;\n uniform vec4 cc_screenSize;\n uniform vec4 cc_screenScale;\n uniform mat4 cc_matProj;\n uniform mat4 cc_matProjInv;\n uniform mat4 cc_matView;\n uniform mat4 cc_matViewInv;\n uniform mat4 cc_matViewProj;\n uniform mat4 cc_matViewProjInv;\n uniform vec4 cc_cameraPos;\n uniform vec4 cc_dirLightDirection[4];\n uniform vec4 cc_dirLightColor[4];\n uniform vec4 cc_pointLightPositionAndRange[4];\n uniform vec4 cc_pointLightColor[4];\n uniform vec4 cc_spotLightPositionAndRange[4];\n uniform vec4 cc_spotLightDirection[4];\n uniform vec4 cc_spotLightColor[4];\n uniform mat4 cc_matViewProjLight;\n uniform vec4 cc_shadowParam1;\n uniform vec4 cc_shadowParam2;\n uniform mat4 cc_matWorld;\n uniform mat4 cc_matWorldIT;\n#if USE_TEXTURE\n attribute vec2 a_texCoord;\n uniform vec2 mainTiling;\n uniform vec2 mainOffset;\n varying vec2 uv0;\n#endif\n#if CC_USE_SKINNING\n \nattribute vec4 a_weights;\nattribute vec4 a_joints;\n uniform mat4 cc_matJoint[128];\n uniform vec4 cc_jointsTextureSize;\n#if CC_USE_JOINTS_TEXTURE\nuniform sampler2D cc_jointsTexture;\nmat4 getBoneMatrix(const in float i) {\n float size = cc_jointsTextureSize.x;\n float j = i * 4.0;\n float x = mod(j, size);\n float y = floor(j / size);\n float dx = 1.0 / size;\n float dy = 1.0 / size;\n y = dy * (y + 0.5);\n vec4 v1 = texture2D(cc_jointsTexture, vec2(dx * (x + 0.5), y));\n vec4 v2 = texture2D(cc_jointsTexture, vec2(dx * (x + 1.5), y));\n vec4 v3 = texture2D(cc_jointsTexture, vec2(dx * (x + 2.5), y));\n vec4 v4 = texture2D(cc_jointsTexture, vec2(dx * (x + 3.5), y));\n return mat4(v1, v2, v3, v4);\n}\n#else\nmat4 getBoneMatrix(const in float i) {\n return cc_matJoint[int(i)];\n}\n#endif\nmat4 skinMatrix() {\n return\n getBoneMatrix(a_joints.x) * a_weights.x +\n getBoneMatrix(a_joints.y) * a_weights.y +\n getBoneMatrix(a_joints.z) * a_weights.z +\n getBoneMatrix(a_joints.w) * a_weights.w;\n}\nvoid skinVertex(inout vec4 a1) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n}\nvoid skinVertex(inout vec4 a1, inout vec4 a2, inout vec4 a3) {\n mat4 m = skinMatrix();\n a1 = m * a1;\n a2 = m * a2;\n a3 = m * a3;\n}\n#endif\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if CC_USE_SKINNING\n skinVertex(pos);\n #endif\n pos = cc_matViewProj * cc_matWorld * pos;\n #if USE_TEXTURE\n uv0 = a_texCoord * mainTiling + mainOffset;\n #endif\n return pos;\n}\nvoid main() { gl_Position = vert(); }\n",
+ "frag": "\n#if USE_TEXTURE\n uniform sampler2D mainTexture;\n varying vec2 uv0;\n#endif\n#if USE_COLOR\n uniform vec4 color;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture2D(mainTexture, uv0);\n #endif\n #if USE_COLOR\n o *= color;\n #endif\n return o;\n}\nvoid main() { gl_FragColor = frag(); }\n",
+ "defines": [
+ {"name":"USE_TEXTURE", "type":"boolean", "defines":[]},
+ {"name":"CC_USE_SKINNING", "type":"boolean", "defines":[]},
+ {"name":"CC_USE_JOINTS_TEXTURE", "type":"boolean", "defines":["CC_USE_SKINNING"]},
+ {"name":"USE_COLOR", "type":"boolean", "defines":[]}
+ ],
+ "blocks": [
+ {"name": "TexCoords", "size": 16, "defines": ["USE_TEXTURE"], "binding": 0, "members": [
+ {"name":"mainTiling", "type":14, "count":1, "size":8},
+ {"name":"mainOffset", "type":14, "count":1, "size":8}
+ ]},
+ {"name": "Constant", "size": 16, "defines": ["USE_COLOR"], "binding": 1, "members": [
+ {"name":"color", "type":16, "count":1, "size":16}
+ ]}
+ ],
+ "samplers": [
+ {"name":"mainTexture", "type":29, "count":1, "defines":["USE_TEXTURE"], "binding":2}
+ ],
+ "dependencies": {}
}
]
}
diff --git a/cocos/3d/builtin/index.js b/cocos/3d/builtin/index.js
deleted file mode 100644
index e69de29bb2..0000000000
diff --git a/cocos/3d/builtin/index.ts b/cocos/3d/builtin/index.ts
new file mode 100644
index 0000000000..e0ce4607f2
--- /dev/null
+++ b/cocos/3d/builtin/index.ts
@@ -0,0 +1,3 @@
+
+export * from './init';
+export { default as effects } from './effects';
diff --git a/cocos/3d/builtin/init.js b/cocos/3d/builtin/init.js
deleted file mode 100644
index 6cc622f6f0..0000000000
--- a/cocos/3d/builtin/init.js
+++ /dev/null
@@ -1,112 +0,0 @@
-import Texture2D from '../../assets/texture-2d';
-import TextureCube from '../assets/texture-cube';
-import ImageAsset from '../../assets/image-asset';
-import Material from '../assets/material';
-import EffectAsset from '../assets/effect-asset';
-import effects from './effects';
-
-let builtinResMgr = {
- // this should be called after renderer initialized
- initBuiltinRes: function(device) {
- builtinResMgr.device = device;
- let canvas = document.createElement('canvas');
- let context = canvas.getContext('2d');
-
- // ============================
- // 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);
-
- 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-cube
- let defaultTextureCube = new TextureCube();
- defaultTextureCube._uuid = 'default-texture-cube';
- defaultTextureCube.image = {
- front: canvasImage,
- back: canvasImage,
- left: canvasImage,
- right: canvasImage,
- top: canvasImage,
- bottom: canvasImage,
- };
-
- // 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;
-
- // 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;
-
- // essential builtin effects
- let efxs = effects.map(e => {
- let effect = Object.assign(new EffectAsset(), e);
- effect.onLoaded(); return effect;
- });
-
- // default material
- let defaultMtl = new Material();
- defaultMtl._uuid = 'default-material';
- defaultMtl.effectAsset = efxs[0];
- defaultMtl.define('USE_COLOR', true);
- defaultMtl.setProperty('color', cc.color('#FF00FF'));
-
- let builtins = {
- [defaultTexture._uuid]: defaultTexture,
- [defaultTextureCube._uuid]: defaultTextureCube,
- [blackTexture._uuid]: blackTexture,
- [whiteTexture._uuid]: whiteTexture,
- [defaultMtl._uuid]: defaultMtl
- };
- return Object.assign(builtinResMgr, builtins);
- },
- initEffects(effectUUIDs, OnComplete) {
- // ============================
- // async builtin effects
- // ============================
- let remainingJobs = effectUUIDs.length;
- for (let i = 0; i < effectUUIDs.length; ++i) {
- let uuid = effectUUIDs[i];
- cc.AssetLibrary.loadAsset(uuid, err => {
- if (err) console.error(err);
- if (!--remainingJobs) OnComplete();
- });
- }
- }
-};
-
-cc.BuiltinResMgr = builtinResMgr;
-export default builtinResMgr;
diff --git a/cocos/3d/builtin/init.ts b/cocos/3d/builtin/init.ts
new file mode 100644
index 0000000000..4ff4440c16
--- /dev/null
+++ b/cocos/3d/builtin/init.ts
@@ -0,0 +1,138 @@
+import { Asset } from '../../assets/asset';
+import { SpriteFrame } from '../../assets/CCSpriteFrame';
+import { ImageAsset } from '../../assets/image-asset';
+import { Texture2D } from '../../assets/texture-2d';
+import { Rect } from '../../core/value-types';
+import { GFXDevice } from '../../gfx/device';
+import { EffectAsset } from '../assets/effect-asset';
+import { TextureCube } from '../assets/texture-cube';
+import effects from './effects';
+
+class BuiltinResMgr {
+ protected _device: GFXDevice | null = null;
+ protected _resources: Record = {};
+
+ // this should be called after renderer initialized
+ public initBuiltinRes (device: GFXDevice) {
+ this._device = device;
+ const resources = this._resources;
+ const canvas = document.createElement('canvas');
+ const context = canvas.getContext('2d')!;
+ const imgAsset = new ImageAsset(canvas);
+ const l = canvas.width = canvas.height = 2;
+ const hl = l / 2;
+
+ // ============================
+ // builtin textures
+ // ============================
+
+ // black texture
+ context.fillStyle = '#000';
+ context.fillRect(0, 0, l, l);
+ const blackTexture = new Texture2D();
+ blackTexture._uuid = 'black-texture';
+ blackTexture.image = imgAsset;
+ resources[blackTexture._uuid] = blackTexture;
+
+ // grey texture
+ context.fillStyle = '#777';
+ context.fillRect(0, 0, l, l);
+ const greyTexture = new Texture2D();
+ greyTexture._uuid = 'grey-texture';
+ greyTexture.image = imgAsset;
+ resources[greyTexture._uuid] = greyTexture;
+
+ // white texture
+ context.fillStyle = '#fff';
+ context.fillRect(0, 0, l, l);
+ const whiteTexture = new Texture2D();
+ whiteTexture._uuid = 'white-texture';
+ whiteTexture.image = imgAsset;
+ resources[whiteTexture._uuid] = whiteTexture;
+
+ // white cube texture
+ // const whiteCubeTexture = new TextureCube();
+ // whiteCubeTexture._uuid = 'white-cube-texture';
+ // whiteCubeTexture.image = {
+ // front: new ImageAsset(canvas),
+ // back: new ImageAsset(canvas),
+ // left: new ImageAsset(canvas),
+ // right: new ImageAsset(canvas),
+ // top: new ImageAsset(canvas),
+ // bottom: new ImageAsset(canvas),
+ // };
+ // whiteCubeTexture.onLoaded();
+ // resources[whiteCubeTexture._uuid] = whiteCubeTexture;
+
+ // normal texture
+ context.fillStyle = '#7f7fff';
+ context.fillRect(0, 0, l, l);
+ const normalTexture = new Texture2D();
+ normalTexture._uuid = 'normal-texture';
+ normalTexture.image = imgAsset;
+ resources[normalTexture._uuid] = normalTexture;
+
+ // default texture
+ canvas.width = canvas.height = 16;
+ context.fillStyle = '#ddd';
+ context.fillRect(0, 0, 16, 16);
+ context.fillStyle = '#555';
+ context.fillRect(0, 0, 8, 8);
+ context.fillStyle = '#555';
+ context.fillRect(8, 8, 8, 8);
+ const defaultTexture = new Texture2D();
+ defaultTexture._uuid = 'default-texture';
+ defaultTexture.image = imgAsset;
+ resources[defaultTexture._uuid] = defaultTexture;
+
+ // default cube texture
+ // const defaultCubeTexture = new TextureCube();
+ // defaultCubeTexture._uuid = 'default-cube-texture';
+ // defaultCubeTexture.image = {
+ // front: new ImageAsset(canvas),
+ // back: new ImageAsset(canvas),
+ // left: new ImageAsset(canvas),
+ // right: new ImageAsset(canvas),
+ // top: new ImageAsset(canvas),
+ // bottom: new ImageAsset(canvas),
+ // };
+ // defaultCubeTexture.onLoaded();
+ // resources.push(defaultCubeTexture);
+
+ const spriteFrame = new SpriteFrame();
+ spriteFrame._uuid = 'default-spriteframe';
+ spriteFrame.setOriginalSize(cc.size(imgAsset.width, imgAsset.height));
+ spriteFrame.setRect(new Rect(0, 0, imgAsset.width, imgAsset.height));
+ spriteFrame.image = imgAsset;
+ spriteFrame.onLoaded();
+ resources[spriteFrame._uuid] = spriteFrame;
+
+ // builtin effects
+ effects.forEach((e: any) => {
+ const effect = Object.assign(new EffectAsset(), e);
+ effect.onLoaded();
+ });
+
+ // default material
+ const defaultMtl = new cc.Material();
+ defaultMtl._uuid = 'default-material';
+ defaultMtl.setDefines({ USE_COLOR: true });
+ defaultMtl.effectName = 'builtin-effect-unlit';
+ defaultMtl.setProperty('color', cc.color('#FF00FF'));
+ resources[defaultMtl._uuid] = defaultMtl;
+
+ // sprite material
+ const spriteMtl = new cc.Material();
+ spriteMtl._uuid = 'sprite-material';
+ spriteMtl.effectName = 'builtin-effect-sprite';
+ spriteMtl.setProperty('u_texSampler', defaultTexture);
+ resources[spriteMtl._uuid] = spriteMtl;
+ }
+
+ public get (uuid: string): T {
+ return this._resources[uuid] as T;
+ }
+}
+
+const builtinResMgr = cc.builtinResMgr = new BuiltinResMgr();
+export { builtinResMgr };
diff --git a/cocos/3d/debugger/draw-mng.js b/cocos/3d/debugger/draw-mng.js
index e4e211cea3..590b0e53e8 100644
--- a/cocos/3d/debugger/draw-mng.js
+++ b/cocos/3d/debugger/draw-mng.js
@@ -2,7 +2,7 @@ import { vec3, color3, mat4 } from '../vmath';
import { LinkedArray } from '../memop';
import { Node } from '../scene-graph';
import gfx from '../gfx';
-import { renderer } from '../renderer';
+import * as renderer from '../renderer';
import { sphere, wireframe } from '../primitives';
let _right = vec3.create(1, 0, 0);
diff --git a/cocos/3d/debugger/index.js b/cocos/3d/debugger/index.js
index 0cf5cfbaf5..eb7518cfe3 100644
--- a/cocos/3d/debugger/index.js
+++ b/cocos/3d/debugger/index.js
@@ -1,4 +1,4 @@
-import { renderer } from '../../renderer';
+import * as renderer from '../../renderer';
import OrbitCamera from './orbit-camera';
import DrawMng from './draw-mng';
import { createGrid } from './utils';
diff --git a/cocos/3d/debugger/utils.js b/cocos/3d/debugger/utils.js
index d42febdbca..a84285605f 100644
--- a/cocos/3d/debugger/utils.js
+++ b/cocos/3d/debugger/utils.js
@@ -1,4 +1,4 @@
-import { renderer } from '../renderer';
+import * as renderer from '../renderer';
import { vec3, color3 } from '../vmath';
import { Node } from '../scene-graph';
diff --git a/cocos/3d/framework/animation-component.js b/cocos/3d/framework/animation-component.js
deleted file mode 100644
index 961ad8488e..0000000000
--- a/cocos/3d/framework/animation-component.js
+++ /dev/null
@@ -1,495 +0,0 @@
-/****************************************************************************
- Copyright (c) 2013-2016 Chukong Technologies Inc.
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos2d-x.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-// @ts-check
-import Component from '../../components/CCComponent';
-import { ccclass, property, executionOrder, menu, executeInEditMode } from '../../core/data/class-decorator';
-import Enum from '../../core/value-types/enum';
-import AnimationClip, { AnimationTarget, AnimationSampler } from '../assets/animation-clip';
-
-/**
- * !#en Animation State Class
- *
- * !#ch 动画状态类
- * @class AnimationState
- */
-class AnimationState {
- constructor(clip) {
- /**
- * !#en An animation clip that is played through this state
- *
- * !#ch 通过此状态播放的动画剪辑
- * @property clip
- * @type {AnimationClip}
- */
- this.clip = clip;
-
- /**
- * !#en Blend mode
- *
- * !#ch 混合模式
- * @property blendMode
- * @type {String}
- */
- this.blendMode = AnimationState.BlendMode.Blend;
-
- /**
- * !#en Wrapping mode
- *
- * !#ch 循环模式
- * @property wrapMode
- * @type {String}
- */
- this.wrapMode = AnimationState.WrapMode.Loop;
-
- /**
- * !#en The playback speed
- *
- * !#ch 播放速度
- * @property speed
- * @type {Number}
- */
- this.speed = 1.0;
-
- /**
- * !#en The current time of the animation.
- *
- * !#ch 当前动画播放时间
- * @property time
- * @type {Number}
- */
- this.time = 0.0;
-
- /**
- * !#en The weight of animation.
- *
- * !#ch 动画权重
- * @property weight
- * @type {Number}
- */
- this.weight = 1.0;
- }
-
- /**
- * !#en The blend mode of animation state
- *
- * !#ch 动画状态的混合模式
- * @static
- * @enum AnimationState.BlendMode
- */
- static BlendMode = Enum({
- /**
- * !#en Animations will be blended.
- *
- * !#ch 动画将被混合
- * @property Blend
- * @readonly
- * @type {String}
- */
- Blend: 'blend',
- /**
- * !#en Animations will be added.
- *
- * !#ch 动画将被附加
- * @property Additive
- * @readonly
- * @type {String}
- */
- Additive: 'additive'
- });
-
- /**
- * !#en Wrapping mode of the animation.
- *
- * !#ch 动画状态的循环模式
- * @static
- * @enum AnimationState.WrapMode
- */
- static WrapMode = Enum({
- /**
- * !#en Only once
- *
- * !#ch 只播放一次
- * @property Once
- * @readonly
- * @type {String}
- */
- Once: 'once',
- /**
- * !#en Loop
- *
- * !#ch 循环播放
- * @property Additive
- * @readonly
- * @type {String}
- */
- Loop: 'loop',
- /**
- * !#en Ping Pong
- *
- * !#ch 乒乓模式播放
- * @property PinpPong
- * @readonly
- * @type {String}
- */
- PinpPong: 'ping-pong',
- /**
- * !#en Plays back the animation. The last frame is played until the end.
- *
- * !#ch 回放动画。当到结尾时,会持续播放最后一帧。
- * @property Clamp
- * @readonly
- * @type {String}
- */
- Clamp: 'clamp'
- });
-}
-
-/**
- * !#en Animation Controller
- *
- * !#ch 动画控制器
- * @class AnimationCtrl
- */
-class AnimationCtrl {
- constructor() {
- /**
- * @type {AnimationTarget}
- */
- this._animationTarget = null;
-
- /**
- * @type {AnimationSampler}
- */
- this._animationSampler = null;
-
- this._current = null;
-
- this._next = null;
-
- this._blendTime = 0.0;
-
- this._blendDuration = 0.3;
- }
-
- /**
- * !#en Set up the animation target
- *
- * !#ch 设置动画目标
- * @param {AnimationTarget} animationTarget
- */
- setAnimationTarget(animationTarget) {
- this._animationTarget = animationTarget;
- if (this._animationTarget) {
- this._animationSampler = new AnimationSampler(this._animationTarget);
- }
- this._nodeIndexers = new Map();
- }
-
- /**
- * !#en Animation fades in and out
- *
- * !#ch 动画的淡入淡出功能
- * @param {AnimationState} to
- * @param {Number} duration
- */
- crossFade(to, duration) {
- if (this._current && duration > 0.0) {
- this._next = to;
- this._blendTime = 0.0;
- this._blendDuration = duration;
- } else {
- this._current = to;
- this._next = null;
- }
- }
-
- tick(dt) {
- if (!this._animationSampler) {
- return;
- }
-
- this._animationSampler.reset();
-
- // handle blend
- if (this._current && this._next) {
- let t0 = this._getTime(this._current);
- let t1 = this._getTime(this._next);
-
- let alpha = this._blendTime / this._blendDuration;
-
- this._current.time += dt;
- this._next.time += dt;
- this._blendTime += dt;
-
- if (alpha > 1.0) {
- this._current = this._next;
- this._next = null;
- this._animationSampler.sample(this._current.clip, t1, 1.0);
- } else {
- this._animationSampler.sample(this._current.clip, t0, alpha);
- this._animationSampler.sample(this._next.clip, t1, 1.0 - alpha);
- }
- }
-
- // handle playing
- if (this._current) {
- let t0 = this._getTime(this._current);
- this._animationSampler.sample(this._current.clip, t0, 1.0);
- this._current.time += dt;
- }
-
- this._animationSampler.apply();
- }
-
- /**
- * !#en Get the play time of an animation clip in current animation state
- *
- * !#ch 返回当前动画状态下的动画剪辑播放时间
- * @param {AnimationState} state - Specify animation status
- */
- _getTime(state) {
- let t = state.time;
- let length = state.clip.length;
- t *= state.speed;
-
- if (state.wrapMode === 'once') {
- if (t > length) {
- t = 0.0;
- }
- } else if (state.wrapMode === 'loop') {
- t %= length;
- } else if (state.wrapMode === 'ping-pong') {
- let order = Math.floor(t / length);
- if (order % 2 === 1) {
- t = length - t % length;
- }
- }
-
- return t;
- }
-}
-
-/**
- * !#en
- * Basic animation component for playing animation
- *
- * !#ch
- * 基础动画组件用于动画播放
- * @class AnimationComponent
- * @extends Component
- */
-@ccclass('cc.AnimationComponent')
-@executionOrder(99)
-@executeInEditMode
-@menu('Components/AnimationComponent')
-export default class AnimationComponent extends Component {
- /**
- * @type {AnimationClip[]}
- */
- @property
- _clips = [];
-
- /**
- * !#en Current clip
- *
- * !#ch 当前动画剪辑
- * @property currentClip
- * @type {AnimationClip}
- */
- @property({type:AnimationClip})
- currentClip = null;
-
- /**
- * !#en Whether to start the animation automatically
- *
- * !#ch 是否启动时自动播放动画
- * @property playAutomatically
- * @type {Boolean}
- */
- @property
- playAutomatically = false;
-
- _preview = false;
-
- @property({type: Boolean})
- get preview() {
- return this._preview;
- }
-
- set preview(value) {
- this._preview = value;
- if (value) {
- if (this.currentClip) {
- cc.engine.animatingInEditMode = true;
- this.play(this.currentClip.name);
- }
- } else {
- cc.engine.animatingInEditMode = false;
- this._animCtrl.crossFade(null, 0);
- }
- }
-
- /**
- * !#en Animation state
- *
- * !#ch 动画状态列表
- * @type {Object}
- */
- _name2states = {};
-
- constructor() {
- super();
-
- /**
- * @type {AnimationTarget}
- */
- this._target = null;
-
- /**
- * !#en Animation controller
- *
- * !#ch 动画控制器
- * @type {AnimationCtrl}
- */
- this._animCtrl = new AnimationCtrl();
- }
-
- /**
- * !#en Clip required for animation playback
- *
- * !#ch 动画剪辑列表
- * @property clips
- * @type {AnimationClip[]}
- */
- @property([AnimationClip])
- get clips() {
- return this._clips;
- }
-
- set clips(val) {
- this._clips = val;
- }
-
- onLoad() {
- this._clips.forEach(clip => {
- this._name2states[clip.name] = new AnimationState(clip);
- });
-
- this._resetTarget();
-
- if (this.playAutomatically != undefined &&
- this.playAutomatically &&
- this.currentClip != undefined &&
- this.currentClip) {
- this.play(this.currentClip.name);
- }
- }
-
- update(dt) {
- this._animCtrl.tick(dt);
- }
-
- onDestroy() {
- }
-
- onEnable() {
- }
-
- onDisable() {
- this._target = null;
- this._animCtrl.setAnimationTarget(null);
- }
-
- /**
- * !#en Add an animation clip to the animation status list
- *
- * !#ch 添加动画剪辑到动画状态列表
- * @param {String} name - The name of animation clip
- * @param {AnimationClip} animClip - Animation clip
- */
- addClip(name, animClip) {
- if (this._name2states[name]) {
- console.warn(`Failed to add clip ${name}, the name already exsits.`);
- return;
- }
-
- this._clips.push(animClip);
- this._name2states[name] = new AnimationState(animClip);
- }
-
- /**
- * !#en Get the animation state through the animation clip name
- *
- * !#ch 返回动画剪辑相对应的动画状态
- * @param {String} name - The name of animation clip
- */
- getState(name) {
- return this._name2states[name];
- }
-
- /**
- * !#en Play the name of the animation clip
- *
- * !#ch 播放相对应名字的动画剪辑
- * @param {String} name - The name of animation clip
- * @param {Number} fadeDuration - Fade duration
- */
- play(name, fadeDuration = 0.3) {
- if (!this._target) {
- return;
- }
-
- if (!this._name2states[name]) {
- console.warn(`Failed to play animation ${name}, not found.`);
- return;
- }
-
- let animState = this._name2states[name];
- animState.time = 0.0;
-
- this._animCtrl.crossFade(animState, fadeDuration);
- }
-
- _resetTarget() {
- this._target = new AnimationTarget();
- this._clips.forEach(clip => {
- clip.frames.forEach(frame => {
- frame.channels.forEach(channel => {
- const targetPath = channel.target;
- if (this._target.get(targetPath)) {
- return;
- }
- const targetNode = this.node.getChildByPath(targetPath);
- if (!targetNode) {
- console.warn(`Animation target ${targetPath} not found in scene graph.`);
- return;
- }
- this._target.add(targetPath, targetNode);
- });
- });
- });
- this._animCtrl.setAnimationTarget(this._target);
- }
-}
diff --git a/cocos/3d/framework/animation-component.ts b/cocos/3d/framework/animation-component.ts
new file mode 100644
index 0000000000..c308fb1f82
--- /dev/null
+++ b/cocos/3d/framework/animation-component.ts
@@ -0,0 +1,426 @@
+/****************************************************************************
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+// @ts-check
+import { Component } from '../../components/component';
+import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator';
+import { ccenum } from '../../core/value-types/enum';
+import AnimationClip, { AnimationSampler, AnimationTarget } from '../assets/animation-clip';
+
+enum BlendMode {
+ /**
+ * !#en Animations will be blended.
+ *
+ * !#ch 动画将被混合
+ */
+ Blend = 'blend',
+ /**
+ * !#en Animations will be added.
+ *
+ * !#ch 动画将被附加
+ */
+ Additive = 'additive',
+}
+
+ccenum(BlendMode);
+
+enum WrapMode {
+ /**
+ * !#en Only once
+ *
+ * !#ch 只播放一次
+ */
+ Once = 'once',
+
+ /**
+ * !#en Loop
+ *
+ * !#ch 循环播放
+ */
+ Loop = 'loop',
+
+ /**
+ * !#en Ping Pong
+ *
+ * !#ch 乒乓模式播放
+ */
+ PinpPong = 'ping-pong',
+
+ /**
+ * !#en Plays back the animation. The last frame is played until the end.
+ *
+ * !#ch 回放动画。当到结尾时,会持续播放最后一帧。
+ */
+ Clamp = 'clamp',
+}
+
+ccenum(WrapMode);
+
+/**
+ * !#en Animation State Class
+ *
+ * !#ch 动画状态类
+ */
+class AnimationState {
+ /**
+ * !#en The blend mode of animation state.
+ *
+ * !#ch 动画状态的混合模式
+ */
+ public static BlendMode = BlendMode;
+
+ /**
+ * !#en Wrapping mode of the animation.
+ *
+ * !#ch 动画状态的循环模式
+ */
+ public static WrapMode = WrapMode;
+
+ /**
+ * !#en An animation clip that is played through this state
+ *
+ * !#ch 通过此状态播放的动画剪辑
+ */
+ public clip: AnimationClip;
+
+ /**
+ * !#en Blend mode
+ *
+ * !#ch 混合模式
+ */
+ public blendMode: BlendMode = BlendMode.Blend;
+
+ /**
+ * !#en Wrapping mode
+ *
+ * !#ch 循环模式
+ */
+ public wrapMode: WrapMode = WrapMode.Loop;
+
+ /**
+ * !#en The playback speed
+ *
+ * !#ch 播放速度
+ */
+ public speed = 1.0;
+
+ /**
+ * !#en The current time of the animation.
+ *
+ * !#ch 当前动画播放时间
+ */
+ public time: number = 0.0;
+
+ /**
+ * !#en The weight of animation.
+ *
+ * !#ch 动画权重
+ */
+ public weight: number = 1.0;
+
+ constructor (clip: AnimationClip) {
+ this.clip = clip;
+ }
+}
+
+/**
+ * !#en Animation Controller
+ *
+ * !#ch 动画控制器
+ */
+class AnimationCtrl {
+ private _animationTarget: AnimationTarget | null = null;
+ private _animationSampler: AnimationSampler | null = null;
+ private _current: AnimationState | null = null;
+ private _next: AnimationState | null = null;
+ private _blendTime = 0.0;
+ private _blendDuration = 0.3;
+
+ /**
+ * !#en Set up the animation target
+ *
+ * !#ch 设置动画目标
+ */
+ public setAnimationTarget (animationTarget: AnimationTarget | null) {
+ this._animationTarget = animationTarget;
+ if (this._animationTarget) {
+ this._animationSampler = new AnimationSampler(this._animationTarget);
+ }
+ }
+
+ /**
+ * !#en Animation fades in and out
+ *
+ * !#ch 动画的淡入淡出功能
+ * @param to
+ * @param duration
+ */
+ public crossFade (to: AnimationState | null, duration: number) {
+ if (this._current && duration > 0.0) {
+ this._next = to;
+ this._blendTime = 0.0;
+ this._blendDuration = duration;
+ } else {
+ this._current = to;
+ this._next = null;
+ }
+ }
+
+ public tick (deltaTime: number) {
+ if (!this._animationSampler) {
+ return;
+ }
+
+ this._animationSampler.reset();
+
+ // handle blend
+ if (this._current && this._next) {
+ const t0 = this._getTime(this._current);
+ const t1 = this._getTime(this._next);
+
+ const alpha = this._blendTime / this._blendDuration;
+
+ this._current.time += deltaTime;
+ this._next.time += deltaTime;
+ this._blendTime += deltaTime;
+
+ if (alpha > 1.0) {
+ this._current = this._next;
+ this._next = null;
+ this._animationSampler.sample(this._current.clip, t1, 1.0);
+ } else {
+ this._animationSampler.sample(this._current.clip, t0, alpha);
+ this._animationSampler.sample(this._next.clip, t1, 1.0 - alpha);
+ }
+ }
+
+ // handle playing
+ if (this._current) {
+ const t0 = this._getTime(this._current);
+ this._animationSampler.sample(this._current.clip, t0, 1.0);
+ this._current.time += deltaTime;
+ }
+
+ this._animationSampler.apply();
+ }
+
+ /**
+ * !#en Get the play time of an animation clip in current animation state
+ *
+ * !#ch 返回当前动画状态下的动画剪辑播放时间
+ * @param state - Specify animation status
+ */
+ private _getTime (state: AnimationState) {
+ let t = state.time;
+ const length = state.clip.length;
+ t *= state.speed;
+
+ if (state.wrapMode === 'once') {
+ if (t > length) {
+ t = 0.0;
+ }
+ } else if (state.wrapMode === 'loop') {
+ t %= length;
+ } else if (state.wrapMode === 'ping-pong') {
+ const order = Math.floor(t / length);
+ if (order % 2 === 1) {
+ t = length - t % length;
+ }
+ }
+
+ return t;
+ }
+}
+
+/**
+ * !#en
+ * Basic animation component for playing animation
+ *
+ * !#ch
+ * 基础动画组件用于动画播放
+ */
+@ccclass('cc.AnimationComponent')
+@executionOrder(99)
+@executeInEditMode
+@menu('Components/AnimationComponent')
+export default class AnimationComponent extends Component {
+ @property({ type: [AnimationClip] })
+ public _clips: AnimationClip[] = [];
+
+ /**
+ * !#en Current clip
+ *
+ * !#ch 当前动画剪辑
+ */
+ @property({ type: AnimationClip })
+ public currentClip: AnimationClip | null = null;
+
+ /**
+ * !#en Whether to start the animation automatically
+ *
+ * !#ch 是否启动时自动播放动画
+ */
+ @property
+ public playAutomatically: boolean = false;
+
+ private _preview = false;
+
+ private _animationController: AnimationCtrl = new AnimationCtrl();
+
+ private _name2states: { [x: string]: AnimationState | undefined; } = {};
+
+ private _animationTarget: AnimationTarget | null = null;
+
+ @property({ type: Boolean })
+ get preview () {
+ return this._preview;
+ }
+
+ set preview (value) {
+ this._preview = value;
+ if (value) {
+ if (this.currentClip) {
+ cc.engine.animatingInEditMode = true;
+ this.play(this.currentClip.name);
+ }
+ } else {
+ cc.engine.animatingInEditMode = false;
+ this._animationController.crossFade(null, 0);
+ }
+ }
+
+ constructor () {
+ super();
+ }
+
+ /**
+ * !#en Clip required for animation playback
+ *
+ * !#ch 动画剪辑列表
+ */
+ @property({ type: [AnimationClip] })
+ get clips () {
+ return this._clips;
+ }
+
+ set clips (val) {
+ this._clips = val;
+ }
+
+ public onLoad () {
+ this._clips.forEach((clip) => {
+ this._name2states[clip.name] = new AnimationState(clip);
+ });
+
+ this._resetTarget();
+
+ if (!CC_EDITOR && this.playAutomatically && this.currentClip) {
+ this.play(this.currentClip.name);
+ }
+ }
+
+ public update (deltaTime: number) {
+ this._animationController.tick(deltaTime);
+ }
+
+ public onDestroy () {
+ }
+
+ public onEnable () {
+ }
+
+ public onDisable () {
+ this._animationTarget = null;
+ this._animationController.setAnimationTarget(null);
+ }
+
+ /**
+ * !#en Add an animation clip to the animation status list
+ *
+ * !#ch 添加动画剪辑到动画状态列表
+ * @param name - The name of animation clip
+ * @param animationClip - Animation clip
+ */
+ public addClip (name: string, animationClip: AnimationClip) {
+ if (this._name2states[name]) {
+ console.warn(`Failed to add clip ${name}, the name already exsits.`);
+ return;
+ }
+
+ this._clips.push(animationClip);
+ this._name2states[name] = new AnimationState(animationClip);
+ }
+
+ /**
+ * !#en Get the animation state through the animation clip name
+ *
+ * !#ch 返回动画剪辑相对应的动画状态
+ * @param name - The name of animation clip
+ */
+ public getState (name: string) {
+ return this._name2states[name];
+ }
+
+ /**
+ * !#en Play the name of the animation clip
+ *
+ * !#ch 播放相对应名字的动画剪辑
+ * @param name - The name of animation clip
+ * @param fadeDuration - Fade duration
+ */
+ public play (name: string, fadeDuration = 0.3) {
+ if (!this._animationTarget) {
+ return;
+ }
+
+ const state = this._name2states[name];
+ if (!state) {
+ console.warn(`Failed to play animation ${name}, not found.`);
+ return;
+ }
+
+ state.time = 0.0;
+ this._animationController.crossFade(state, fadeDuration);
+ }
+
+ public _resetTarget () {
+ const animationTarget = new AnimationTarget();
+ this._clips.forEach((clip) => {
+ clip.channels.forEach((channel) => {
+ const targetPath = channel.target;
+ if (animationTarget.get(targetPath)) {
+ return;
+ }
+ const targetNode = this.node.getChildByPath(targetPath);
+ if (!targetNode) {
+ console.warn(`Animation target ${targetPath} not found in scene graph.`);
+ return;
+ }
+ animationTarget.add(targetPath, targetNode);
+ });
+ });
+ this._animationTarget = animationTarget;
+ this._animationController.setAnimationTarget(this._animationTarget);
+ }
+}
diff --git a/cocos/3d/framework/animation-system.js b/cocos/3d/framework/animation-system.js
deleted file mode 100644
index c68d3b8165..0000000000
--- a/cocos/3d/framework/animation-system.js
+++ /dev/null
@@ -1,63 +0,0 @@
-/****************************************************************************
- Copyright (c) 2013-2016 Chukong Technologies Inc.
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos2d-x.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-// @ts-check
-import System from '../ecs/system';
-import { FixedArray } from '../memop';
-/**
- * @typedef {import('./animation-component').default} AnimationComponent
- */
-
-export default class AnimationSystem extends System {
- constructor() {
- super();
-
- this._anims = new FixedArray(200);
- }
-
- add(comp) {
- this._anims.push(comp);
- }
-
- remove(comp) {
- this._anims.fastRemove(this._anims.indexOf(comp));
- }
-
-// update() {
-// for (let i = 0; i < this._anims.length; ++i) {
-// let anim = this._anims.data[i];
-// if (!anim.enabled) {
-// continue;
-// }
-// if (!anim.skeleton) {
-// // console.error(`Animation component depends on skinning model component.`);
-// let skeleton = findSkeleton(anim._entity);
-// anim.skeleton = skeleton;
-// }
-// if (anim.skeleton) {
-// anim._animCtrl.tick(this._app.deltaTime);
-// }
-// }
-// }
-}
diff --git a/cocos/3d/framework/camera-component.js b/cocos/3d/framework/camera-component.ts
similarity index 54%
rename from cocos/3d/framework/camera-component.js
rename to cocos/3d/framework/camera-component.ts
index b2d516fe65..f3fc42378d 100644
--- a/cocos/3d/framework/camera-component.js
+++ b/cocos/3d/framework/camera-component.ts
@@ -22,17 +22,13 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
-// @ts-check
-import RenderSystemActor from './renderSystemActor';
-import { renderer } from '../../renderer/index';
-import { toRadian } from '../../core/vmath';
-import { ccclass, menu, property, executeInEditMode } from "../../core/data/class-decorator";
-import { Color, Enum, Rect } from '../../core/value-types';
-import enums from '../../renderer/enums';
-
-/**
- * @typedef {import('../../core/value-types/index').Color} Color
- */
+import { ray } from '../../3d/geom-utils';
+import { Component } from '../../components/component';
+import { ccclass, executeInEditMode, menu, property } from '../../core/data/class-decorator';
+import { Enum, Rect, Vec3 } from '../../core/value-types';
+import { color4, toRadian } from '../../core/vmath';
+import { GFXClearFlag } from '../../gfx/define';
+import { Camera } from '../../renderer';
/**
* !#en The light source type
@@ -41,7 +37,7 @@ import enums from '../../renderer/enums';
* @static
* @enum CameraComponent.Projection
*/
-let CameraProjection = Enum({
+const ProjectionType = Enum({
/**
* !#en The orthogonal camera
*
@@ -59,14 +55,14 @@ let CameraProjection = Enum({
* @readonly
* @type {Number}
*/
- PERSPECTIVE: 1
+ PERSPECTIVE: 1,
});
-let CameraClearFlag = Enum({
- SKYBOX: enums.CLEAR_SKYBOX | enums.CLEAR_DEPTH | enums.CLEAR_STENCIL,
- SOLID_COLOR: enums.CLEAR_COLOR | enums.CLEAR_DEPTH | enums.CLEAR_STENCIL,
- DEPTH_ONLY: enums.CLEAR_DEPTH | enums.CLEAR_STENCIL,
- DONT_CLEAR: 0
+const CameraClearFlag = Enum({
+ SKYBOX: GFXClearFlag.SKYBOX | GFXClearFlag.DEPTH | GFXClearFlag.STENCIL,
+ SOLID_COLOR: GFXClearFlag.COLOR | GFXClearFlag.DEPTH | GFXClearFlag.STENCIL,
+ DEPTH_ONLY: GFXClearFlag.DEPTH | GFXClearFlag.STENCIL,
+ DONT_CLEAR: GFXClearFlag.NONE,
});
/**
@@ -74,44 +70,44 @@ let CameraClearFlag = Enum({
*
* !#ch 相机组件
* @class CameraComponent
- * @extends RenderSystemActor
+ * @extends Component
*/
@ccclass('cc.CameraComponent')
@menu('Components/CameraComponent')
@executeInEditMode
-export default class CameraComponent extends RenderSystemActor{
- @property
- _projection = CameraProjection.PERSPECTIVE;
+export class CameraComponent extends Component {
+ public static ProjectionType = ProjectionType;
@property
- _priority = 0;
-
+ protected _projection = ProjectionType.PERSPECTIVE;
@property
- _fov = 45;
-
+ protected _priority = 0;
@property
- _orthoHeight = 10;
-
+ protected _fov = 45;
@property
- _near = 0.01;
-
+ protected _orthoHeight = 10;
@property
- _far = 1000.0;
-
+ protected _near = 0.01;
@property
- _color = cc.color('#334C78');
-
+ protected _far = 1000.0;
@property
- _depth = 1;
-
+ protected _color = cc.color('#334C78');
@property
- _stencil = 0;
-
+ protected _depth = 1;
@property
- _clearFlags = CameraClearFlag.SOLID_COLOR;
-
+ protected _stencil = 0;
@property
- _rect = new Rect(0, 0, 1, 1);
+ protected _clearFlags = CameraClearFlag.SOLID_COLOR;
+ @property
+ protected _rect = new Rect(0, 0, 1, 1);
+ @property
+ protected _targetDisplay = 0;
+
+ protected _camera: Camera | null = null;
+
+ constructor () {
+ super();
+ }
/**
* !#en The projection type of the camera
@@ -120,36 +116,15 @@ export default class CameraComponent extends RenderSystemActor{
* @type {Number}
*/
@property({
- type: CameraProjection
+ type: ProjectionType,
})
- get projection() {
+ get projection () {
return this._projection;
}
- set projection(val) {
+ set projection (val) {
this._projection = val;
-
- let type = renderer.PROJ_PERSPECTIVE;
- if (this._projection === CameraProjection.Ortho) {
- type = renderer.PROJ_ORTHO;
- }
- this._camera.setType(type);
- }
-
- /**
- * !#en The camera priority
- *
- * !#ch 相机的优先级,优先级低的优先渲染
- * @type {Number}
- */
- @property
- get priority() {
- return this._priority;
- }
-
- set priority(val) {
- this._priority = val;
- this._camera.setPriority(val);
+ if (this._camera) { this._camera.projectionType = val; }
}
/**
@@ -159,13 +134,13 @@ export default class CameraComponent extends RenderSystemActor{
* @type {Number}
*/
@property
- get fov() {
+ get fov () {
return this._fov;
}
- set fov(val) {
+ set fov (val) {
this._fov = val;
- this._camera.setFov(toRadian(val));
+ if (this._camera) { this._camera.fov = toRadian(val); }
}
/**
@@ -175,13 +150,13 @@ export default class CameraComponent extends RenderSystemActor{
* @type {Number}
*/
@property
- get orthoHeight() {
+ get orthoHeight () {
return this._orthoHeight;
}
- set orthoHeight(val) {
+ set orthoHeight (val) {
this._orthoHeight = val;
- this._camera.setOrthoHeight(val);
+ if (this._camera) { this._camera.orthoHeight = val; }
}
/**
@@ -191,13 +166,13 @@ export default class CameraComponent extends RenderSystemActor{
* @type {Number}
*/
@property
- get near() {
+ get near () {
return this._near;
}
- set near(val) {
+ set near (val) {
this._near = val;
- this._camera.setNear(val);
+ if (this._camera) { this._camera.nearClip = val; }
}
/**
@@ -207,13 +182,13 @@ export default class CameraComponent extends RenderSystemActor{
* @type {Number}
*/
@property
- get far() {
+ get far () {
return this._far;
}
- set far(val) {
+ set far (val) {
this._far = val;
- this._camera.setFar(val);
+ if (this._camera) { this._camera.farClip = val; }
}
/**
@@ -223,13 +198,15 @@ export default class CameraComponent extends RenderSystemActor{
* @type {Color}
*/
@property
- get color() {
+ get color () {
return this._color;
}
- set color(val) {
+ set color (val) {
this._color = val;
- this._camera.setColor(val.r / 255, val.g / 255, val.b / 255, val.a / 255);
+ if (this._camera) { this._camera.clearColor =
+ color4.create(val.r / 255, val.g / 255, val.b / 255, val.a / 255);
+ }
}
/**
@@ -239,13 +216,13 @@ export default class CameraComponent extends RenderSystemActor{
* @type {Number}
*/
@property
- get depth() {
+ get depth () {
return this._depth;
}
- set depth(val) {
+ set depth (val) {
this._depth = val;
- this._camera.setDepth(val);
+ if (this._camera) { this._camera.clearDepth = val; }
}
/**
@@ -255,13 +232,13 @@ export default class CameraComponent extends RenderSystemActor{
* @type {Number}
*/
@property
- get stencil() {
+ get stencil () {
return this._stencil;
}
- set stencil(val) {
+ set stencil (val) {
this._stencil = val;
- this._camera.setStencil(val);
+ if (this._camera) { this._camera.clearStencil = val; }
}
/**
@@ -271,15 +248,15 @@ export default class CameraComponent extends RenderSystemActor{
* @type {Number}
*/
@property({
- type: CameraClearFlag
+ type: CameraClearFlag,
})
- get clearFlags() {
+ get clearFlags () {
return this._clearFlags;
}
- set clearFlags(val) {
+ set clearFlags (val) {
this._clearFlags = val;
- this._camera.setClearFlags(val);
+ if (this._camera) { this._camera.clearFlag = val; }
}
/**
@@ -289,55 +266,55 @@ export default class CameraComponent extends RenderSystemActor{
* @type {Rect}
*/
@property
- get rect() {
+ get rect () {
return this._rect;
}
- set rect(val) {
+ set rect (val) {
this._rect = val;
- this._camera.setRect(val.x, val.y, val.width, val.height);
+ if (this._camera) { this._camera.viewport = val; }
}
- static Projection = CameraProjection;
-
- constructor() {
- super();
- this._camera = new renderer.Camera();
+ @property
+ get targetDisplay () {
+ return this._targetDisplay;
+ }
+ set targetDisplay (val) {
+ this._targetDisplay = val;
+ if (this._camera) { this._camera.changeTargetDisplay(val); }
}
- onLoad() {
- this.projection = this._projection;
- this.priority = this._priority;
- this.fov = this._fov;
- this.orthoHeight = this._orthoHeight;
- this.near = this._near;
- this.far = this._far;
- this.color = this._color;
- this.depth = this._depth;
- this.stencil = this._stencil;
- this.clearFlags = this._clearFlags;
- this.rect = this._rect;
- this._camera.setStages(renderer.PassStage.DEFAULT | renderer.PassStage.FORWARD);
- this._camera.setNode(this.node);
+ public onLoad () {
+
}
- onEnable() {
- this.scene.addCamera(this._camera);
+ public onEnable () {
+ this._camera = this._getRenderScene().createCamera(this);
}
- onDisable() {
- this.scene.removeCamera(this._camera);
+ public onDisable () {
+ if (this._camera) { this._getRenderScene().destroyCamera(this._camera); }
}
- /**
- * transform a screen position to world space
- * @param out the resulting vector
- * @param screenPos the screen position to be transformed
- * @param width framebuffer width
- * @param height framebuffer height
- * @returns the resulting vector
- */
- screenToWorld(out, screenPos, width, height) {
- return this._camera.screenToWorld(out, screenPos, width, height);
+ public onDestroy () {
+
+ }
+
+ public screenPointToRay (x: number, y: number, out?: ray) {
+ if (!out) { out = ray.create(); }
+ if (this._camera) { this._camera.screenPointToRay(out, x, y); }
+ return out;
+ }
+
+ public worldToScreen (worldPos: Vec3, out?: Vec3) {
+ if (!out) { out = new Vec3(); }
+ if (this._camera) { this._camera.worldToScreen(out, worldPos); }
+ return out;
+ }
+
+ public screenToWorld (screenPos: Vec3, out?: Vec3) {
+ if (!out) { out = this.node.getWorldPosition(); }
+ if (this._camera) { this._camera.screenToWorld(out, screenPos); }
+ return out;
}
}
diff --git a/cocos/3d/framework/index.js b/cocos/3d/framework/index.js
index eeaeffaafe..cfabdc8433 100644
--- a/cocos/3d/framework/index.js
+++ b/cocos/3d/framework/index.js
@@ -24,10 +24,10 @@
THE SOFTWARE.
****************************************************************************/
-import CameraComponent from './camera-component';
+import { CameraComponent } from './camera-component';
import AnimationComponent from './animation-component';
import LightComponent from './light-component';
-import ModelComponent from './model-component';
+import { ModelComponent } from './model-component';
import SkinningModelComponent from './skinning-model-component';
import SkyboxComponent from './skybox-component';
import { BoxColliderComponent, SphereColliderComponent } from './physics/collider-component';
diff --git a/cocos/3d/framework/light-component.js b/cocos/3d/framework/light-component.js
deleted file mode 100644
index 853118b51d..0000000000
--- a/cocos/3d/framework/light-component.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.cocos2d-x.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-// @ts-check
-import RenderSystemActor from './renderSystemActor';
-import { renderer } from '../../renderer/index';
-import { Color, Enum } from '../../core/value-types';
-import { toRadian } from '../../core/vmath';
-import { ccclass, menu, property, executeInEditMode } from "../../core/data/class-decorator";
-
-/**
- * !#en The light source type
- *
- * !#ch 光源类型
- * @static
- * @enum LightComponent.Type
- */
-const LightType = Enum({
- /**
- * !#en The direction of light
- *
- * !#ch 平行光
- * @property Directional
- * @readonly
- * @type {Number}
- */
- Directional: 0,
- /**
- * !#en The point of light
- *
- * !#ch 点光源
- * @property Point
- * @readonly
- * @type {Number}
- */
- Point: 1,
- /**
- * !#en The spot of light
- *
- * !#ch 聚光灯
- * @property Spot
- * @readonly
- * @type {Number}
- */
- Spot: 2,
-});
-
-/**
- * !#en The shadow type
- *
- * !#ch 阴影类型
- * @static
- * @enum LightComponent.ShadowType
- */
-const LightShadowType = Enum({
- /**
- * !#en No shadows
- *
- * !#ch 阴影关闭
- * @property None
- * @readonly
- * @type {Number}
- */
- None: 0,
- /**
- * !#en Soft shadows
- *
- * !#ch 软阴影
- * @property Soft
- * @readonly
- * @type {Number}
- */
- Soft: 1,
- /**
- * !#en Hard shadows
- *
- * !#ch 阴硬影
- * @property Hard
- * @readonly
- * @type {Number}
- */
- Hard: 2,
-});
-
-/**
- * !#en The Light Component
- *
- * !#ch 光源组件
- * @class LightComponent
- * @extends RenderSystemActor
- */
-@ccclass('cc.LightComponent')
-@menu('Components/LightComponent')
-@executeInEditMode
-export default class LightComponent extends RenderSystemActor {
- @property
- _type = LightType.Directional;
-
- @property
- _color = Color.WHITE;
-
- @property
- _intensity = 1;
-
- @property
- _range = 1;
-
- @property
- _spotAngle = 60;
-
- @property
- _spotExp = 1;
-
- @property
- _shadowType = LightShadowType.None;
-
- @property
- _shadowResolution = 1024;
-
- @property
- _shadowDarkness = 0.5;
-
- @property
- _shadowMinDepth = 1;
-
- @property
- _shadowMaxDepth = 1000;
-
- @property
- _shadowDepthScale = 250;
-
- @property
- _shadowFrustumSize = 50;
-
- @property
- _shadowBias = 0.0005;
-
- /**
- * !#en The light source type
- *
- * !#ch 光源类型
- *
- * @type {Number}
- */
- @property({
- type: LightType
- })
- get type() {
- return this._type;
- }
-
- set type(val) {
- this._type = val;
-
- let type = renderer.LIGHT_DIRECTIONAL;
- if (this._type === LightType.Point) {
- type = renderer.LIGHT_POINT;
- } else if (this._type === LightType.Spot) {
- type = renderer.LIGHT_SPOT;
- }
- this._light.setType(type);
- }
-
- /**
- * !#en The light source color
- *
- * !#ch 光源颜色
- * @type {Color}
- */
- @property
- get color() {
- return this._color;
- }
-
- set color(val) {
- this._color = val;
- this._light.setColor(val.r / 255, val.g / 255, val.b / 255);
- }
-
- /**
- * !#en The light source intensity
- *
- * !#ch 光源强度
- * @type {Number}
- */
- @property
- get intensity() {
- return this._intensity;
- }
-
- set intensity(val) {
- this._intensity = val;
- this._light.setIntensity(val);
- }
-
- /**
- * !#en The light range, used for spot and point light
- *
- * !#ch 针对聚光灯和点光源设置光源范围
- * @type {Number}
- */
- @property
- get range() {
- return this._range;
- }
-
- set range(val) {
- this._range = val;
- this._light.setRange(val);
- }
-
- /**
- * !#en The spot light cone angle
- *
- * !#ch 聚光灯锥角
- * @type {Number}
- */
- @property
- get spotAngle() {
- return this._spotAngle;
- }
-
- set spotAngle(val) {
- this._spotAngle = val;
- this._light.setSpotAngle(toRadian(val));
- }
-
- /**
- * !#en The spot light exponential
- *
- * !#ch 聚光灯指数
- * @type {Number}
- */
- @property
- get spotExp() {
- return this._spotExp;
- }
-
- set spotExp(val) {
- this._spotExp = val;
- this._light.setSpotExp(val);
- }
-
- /**
- * !#en The shadow type
- *
- * !#ch 阴影类型
- * @type {Number} shadowType
- */
- @property({
- type: LightShadowType
- })
- get shadowType() {
- return this._shadowType;
- }
-
- set shadowType(val) {
- this._shadowType = val;
-
- let type = renderer.SHADOW_NONE;
- if (val === LightShadowType.Hard) {
- type = renderer.SHADOW_HARD;
- } else if (val === LightShadowType.Soft) {
- type = renderer.SHADOW_SOFT;
- }
- this._light.setShadowType(type);
- }
-
- /**
- * !#en The shadow resolution
- *
- * !#ch 阴影分辨率
- *
- * @type {Number}
- */
- @property
- get shadowResolution() {
- return this._shadowResolution;
- }
-
- set shadowResolution(val) {
- this._shadowResolution = val;
- this._light.setShadowResolution(val);
- }
-
- /**
- * !#en The shadow darkness
- *
- * !#ch 阴影灰度值
- *
- * @type {Number}
- */
- @property
- get shadowDarkness() {
- return this._shadowDarkness;
- }
-
- set shadowDarkness(val) {
- this._shadowDarkness = val;
- this._light.setShadowDarkness(val);
- }
-
- /**
- * !#en The shadow min depth
- *
- * !#ch 阴影最小深度
- *
- * @type {Number}
- */
- @property
- get shadowMinDepth() {
- return this._shadowMinDepth;
- }
-
- set shadowMinDepth(val) {
- this._shadowMinDepth = val;
- this._light.setShadowMinDepth(val);
- }
-
- /**
- * !#en The shadow max depth
- *
- * !#ch 阴影最大深度
- *
- * @type {Number}
- */
- @property
- get shadowMaxDepth() {
- return this._shadowMaxDepth;
- }
-
- set shadowMaxDepth(val) {
- this._shadowMaxDepth = val;
- this._light.setShadowMaxDepth(val);
- }
-
- /**
- * !#en The shadow depth scale
- *
- * !#ch 阴影深度比例
- *
- * @type {Number}
- */
- @property
- get shadowDepthScale() {
- return this._shadowDepthScale;
- }
-
- set shadowDepthScale(val) {
- this._shadowDepthScale = val;
- this._light.setShadowDepthScale(val);
- }
-
- /**
- * !#en The shadow frustum size
- *
- * !#ch 阴影截锥体大小
- *
- * @type {Number}
- */
- @property
- get shadowFrustumSize() {
- return this._shadowFrustumSize;
- }
-
- set shadowFrustumSize(val) {
- this._shadowFrustumSize = val;
- this._light.setShadowFrustumSize(val);
- }
-
- /**
- * !#en The shadow bias
- *
- * !#ch 阴影偏移量
- *
- * @type {Number}
- */
- @property
- get shadowBias() {
- return this._shadowBias;
- }
-
- set shadowBias(val) {
- this._shadowBias = val;
- this._light.setShadowBias(val);
- }
-
- static Type = LightType;
-
- static ShadowType = LightShadowType;
-
- constructor() {
- super();
-
- this._light = new renderer.Light();
- }
-
- onLoad() {
- this._light.setNode(this.node);
- this.type = this._type;
- this.color = this._color;
- this.intensity = this._intensity;
- this.range = this._range;
- this.spotAngle = this._spotAngle;
- this.spotExp = this._spotExp;
- this.shadowType = this._shadowType;
- this.shadowResolution = this._shadowResolution;
- this.shadowDarkness = this._shadowDarkness;
- this.shadowMaxDepth = this._shadowMaxDepth;
- this.shadowDepthScale = this._shadowDepthScale;
- this.shadowFrustumSize = this._shadowFrustumSize;
- this.shadowBias = this._shadowBias;
- }
-
- onEnable() {
- this.scene.addLight(this._light);
- }
-
- onDisable() {
- this.scene.removeLight(this._light);
- }
-}
diff --git a/cocos/3d/framework/light-component.ts b/cocos/3d/framework/light-component.ts
new file mode 100644
index 0000000000..56de33dff6
--- /dev/null
+++ b/cocos/3d/framework/light-component.ts
@@ -0,0 +1,306 @@
+/****************************************************************************
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+import { Component } from '../../components/component';
+import { ccclass, executeInEditMode, menu, property } from '../../core/data/class-decorator';
+import { Color, Enum } from '../../core/value-types';
+import { toRadian } from '../../core/vmath';
+import { Light, LightType } from '../../renderer/scene/light';
+import { PointLight } from '../../renderer/scene/point-light';
+import { SpotLight } from '../../renderer/scene/spot-light';
+
+/**
+ * !#en The light source type
+ *
+ * !#ch 光源类型
+ * @static
+ * @enum LightComponent.Type
+ */
+const Type = Enum({
+ /**
+ * !#en The direction of light
+ *
+ * !#ch 平行光
+ * @property Directional
+ * @readonly
+ * @type {Number}
+ */
+ DIRECTIONAL: LightType.DIRECTIONAL,
+ /**
+ * !#en The point of light
+ *
+ * !#ch 点光源
+ * @property Point
+ * @readonly
+ * @type {Number}
+ */
+ POINT: LightType.POINT,
+ /**
+ * !#en The spot of light
+ *
+ * !#ch 聚光灯
+ * @property Spot
+ * @readonly
+ * @type {Number}
+ */
+ SPOT: LightType.SPOT,
+});
+
+/**
+ * !#en The shadow type
+ *
+ * !#ch 阴影类型
+ * @static
+ * @enum LightComponent.ShadowType
+ */
+const LightShadowType = Enum({
+ /**
+ * !#en No shadows
+ *
+ * !#ch 阴影关闭
+ * @property None
+ * @readonly
+ * @type {Number}
+ */
+ None: 0,
+ /**
+ * !#en Soft shadows
+ *
+ * !#ch 软阴影
+ * @property Soft
+ * @readonly
+ * @type {Number}
+ */
+ Soft: 1,
+ /**
+ * !#en Hard shadows
+ *
+ * !#ch 阴硬影
+ * @property Hard
+ * @readonly
+ * @type {Number}
+ */
+ Hard: 2,
+});
+
+/**
+ * !#en The Light Component
+ *
+ * !#ch 光源组件
+ * @class LightComponent
+ * @extends Component
+ */
+@ccclass('cc.LightComponent')
+@menu('Components/LightComponent')
+@executeInEditMode
+export default class LightComponent extends Component {
+
+ public static Type = Type;
+ public static ShadowType = LightShadowType;
+
+ @property
+ protected _type = Type.DIRECTIONAL;
+ @property
+ protected _color = Color.WHITE;
+ @property
+ protected _intensity = 1;
+ @property
+ protected _range = 10;
+ @property
+ protected _spotAngle = 60;
+
+ // @property
+ // protected _shadowType = LightShadowType.None;
+ // @property
+ // protected _shadowResolution = 1024;
+ // @property
+ // protected _shadowDarkness = 0.5;
+ // @property
+ // protected _shadowMinDepth = 1;
+ // @property
+ // protected _shadowMaxDepth = 1000;
+ // @property
+ // protected _shadowDepthScale = 250;
+ // @property
+ // protected _shadowFrustumSize = 50;
+ // @property
+ // protected _shadowBias = 0.0005;
+
+ protected _light: Light | null = null;
+ protected _colorData = [1, 1, 1];
+
+ /**
+ * !#en The light source type
+ *
+ * !#ch 光源类型
+ *
+ * @type {Number}
+ */
+ @property({
+ type: Type,
+ })
+ get type () {
+ return this._type;
+ }
+
+ set type (val) {
+ this._destroyLight();
+ this._type = parseInt(val);
+ this._createLight();
+ }
+
+ /**
+ * !#en The light source color
+ *
+ * !#ch 光源颜色
+ * @type {Color}
+ */
+ @property
+ get color () {
+ return this._color;
+ }
+
+ set color (val) {
+ this._color = val;
+ const scale = this._intensity / 255;
+ this._colorData[0] = val.r * scale;
+ this._colorData[1] = val.g * scale;
+ this._colorData[2] = val.b * scale;
+ if (this._light) {
+ this._light.color = this._colorData;
+ }
+ }
+
+ /**
+ * !#en The light source intensity
+ *
+ * !#ch 光源强度
+ * @type {Number}
+ */
+ @property
+ get intensity () {
+ return this._intensity;
+ }
+
+ set intensity (val) {
+ this._intensity = val;
+ const scale = val / 255;
+ this._colorData[0] = this._color.r * scale;
+ this._colorData[1] = this._color.g * scale;
+ this._colorData[2] = this._color.b * scale;
+ if (this._light) {
+ this._light.color = this._colorData;
+ }
+ }
+
+ /**
+ * !#en The light range, used for spot and point light
+ *
+ * !#ch 针对聚光灯和点光源设置光源范围
+ * @type {Number}
+ */
+ @property
+ get range () {
+ return this._range;
+ }
+
+ set range (val) {
+ this._range = val;
+ if (this._light && this._light instanceof PointLight || this._light instanceof SpotLight) {
+ this._light.range = val;
+ }
+ }
+
+ /**
+ * !#en The spot light cone angle
+ *
+ * !#ch 聚光灯锥角
+ * @type {Number}
+ */
+ @property
+ get spotAngle () {
+ return this._spotAngle;
+ }
+
+ set spotAngle (val) {
+ this._spotAngle = val;
+ if (this._light && this._light instanceof SpotLight) {
+ this._light.spotAngle = toRadian(val);
+ }
+ }
+
+ public onEnable () {
+ this._createLight();
+ if (this._light) { this._light.enabled = true; return; }
+ }
+
+ public onDisable () {
+ if (this._light) { this._light.enabled = false; }
+ }
+
+ public onDestroy () {
+ this._destroyLight();
+ }
+
+ protected _createLight () {
+ if (!this.node._scene || this._light) { return; }
+ const scene = this._getRenderScene();
+ switch (this._type) {
+ case Type.DIRECTIONAL:
+ this._light = scene.createDirectionalLight(this.name, this.node);
+ break;
+ case Type.POINT:
+ this._light = scene.createPointLight(this.name, this.node);
+ this.range = this._range;
+ break;
+ case Type.SPOT:
+ this._light = scene.createSpotLight(this.name, this.node);
+ this.range = this._range;
+ this.spotAngle = this._spotAngle;
+ break;
+ default:
+ console.warn(`illegal light type ${this._type}`);
+ return;
+ }
+ if (!this._light) { console.warn('we don\'t support this many lights in forward pipeline.'); }
+ this.color = this._color;
+ }
+
+ protected _destroyLight () {
+ if (!this.node._scene || !this._light) { return; }
+ const scene = this._getRenderScene();
+ switch (this._type) {
+ case Type.DIRECTIONAL:
+ scene.destroyDirectionalLight(this._light);
+ break;
+ case Type.POINT:
+ scene.destroyPointLight(this._light);
+ break;
+ case Type.SPOT:
+ scene.destroySpotLight(this._light);
+ break;
+ }
+ this._light = null;
+ }
+}
diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js
deleted file mode 100644
index cd656e6650..0000000000
--- a/cocos/3d/framework/model-component.js
+++ /dev/null
@@ -1,281 +0,0 @@
-/****************************************************************************
- Copyright (c) 2013-2016 Chukong Technologies Inc.
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos2d-x.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-// @ts-check
-import Model from '../../renderer/scene/model';
-import { ccclass, property, menu, executionOrder, executeInEditMode } from '../../core/data/class-decorator';
-import Mesh from '../assets/mesh';
-import Enum from '../../core/value-types/enum';
-import RenderableComponent from './renderable-component';
-/**
- * @typedef {import('../assets/material').default} Material
- */
-
-/**
- * !#en Shadow projection mode
- *
- * !#ch 阴影投射方式
- * @static
- * @enum ModelComponent.ShadowCastingMode
- */
-let ModelShadowCastingMode = Enum({
- /**
- * !#en
- *
- * !#ch 关闭阴影投射
- * @property Off
- * @readonly
- * @type {Number}
- */
- Off: 0,
- /**
- * !#en
- *
- * !#ch 开启阴影投射,当阴影光产生的时候
- * @property On
- * @readonly
- * @type {Number}
- */
- On: 1,
- /**
- * !#en
- *
- * !#ch 可以从网格的任意一遍投射出阴影
- * @property TwoSided
- * @readonly
- * @type {Number}
- */
- TwoSided: 2,
- /**
- * !#en
- *
- * !#ch 只显示阴影
- * @property ShadowsOnly
- * @readonly
- * @type {Number}
- */
- ShadowsOnly: 3,
-});
-
-/**
- * !#en The Model Component
- *
- * !#ch 模型组件
- * @class ModelComponent
- * @extends RenderableComponent
- */
-@ccclass('cc.ModelComponent')
-@executionOrder(100)
-@menu('Components/ModelComponent')
-@executeInEditMode
-export default class ModelComponent extends RenderableComponent {
-
- /**
- * @type {Mesh}
- */
- @property
- _mesh = null;
-
- @property
- _shadowCastingMode = ModelShadowCastingMode.Off;
-
- @property
- _receiveShadows = false;
-
- /**
- * @type {Material}
- */
- static _builtinMaterial = null;
-
- /**
- * !#en The mesh of the model
- *
- * !#ch 模型网格
- * @type {Mesh}
- */
- @property({
- type: Mesh
- })
- get mesh() {
- return this._mesh;
- }
-
- set mesh(val) {
- this._mesh = val;
- this._updateModels();
- }
-
- /**
- * !#en The shadow casting mode
- *
- * !#ch 投射阴影方式
- * @type {Number}
- */
- @property({
- type: ModelShadowCastingMode
- })
- get shadowCastingMode() {
- return this._shadowCastingMode;
- }
-
- set shadowCastingMode(val) {
- this._shadowCastingMode = val;
- this._updateCastShadow();
- }
-
- /**
- * !#en Does this model receive shadows?
- *
- * !#ch 是否接受阴影?
- * @type {Boolean}
- */
- @property
- get receiveShadows() {
- return this._receiveShadows;
- }
-
- set receiveShadows(val) {
- this._receiveShadows = val;
- this._updateReceiveShadow();
- }
-
- static ShadowCastingMode = ModelShadowCastingMode;
-
- constructor() {
- super();
- /**
- * @type {Model[]}
- */
- this._models = [];
- }
-
- onLoad() {
- this._updateModels();
- this._updateCastShadow();
- this._updateReceiveShadow();
- }
-
- onEnable() {
- for (let i = 0; i < this._models.length; ++i) {
- this.scene.addModel(this._models[i]);
- }
- }
-
- onDisable() {
- for (let i = 0; i < this._models.length; ++i) {
- this.scene.removeModel(this._models[i]);
- }
- }
-
- _updateModels() {
- let meshCount = this._mesh ? this._mesh.subMeshCount : 0;
- let oldModels = this._models;
-
- this._models = new Array(meshCount);
- for (let i = 0; i < meshCount; ++i) {
- let model = this._createModel();
- model.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition);
- this._models[i] = model;
- }
-
- this._updateModelParams();
-
- if (this.enabled) {
- for (let i = 0; i < oldModels.length; ++i) {
- this.scene.removeModel(oldModels[i]);
- }
- for (let i = 0; i < this._models.length; ++i) {
- this.scene.addModel(this._models[i]);
- }
- }
- }
-
- _createModel() {
- return new Model();
- }
-
- _updateModelParams() {
- this.node._hasChanged = true;
- for (let i = 0; i < this._models.length; ++i) {
- let model = this._models[i];
- let material = this.getSharedMaterial(i);
- let inputAssembler = this._mesh.getSubMesh(i);
-
- model.setInputAssembler(inputAssembler);
- model.setNode(this.node);
- this._updateModelMaterial(model, material);
- }
- }
-
- _onMaterialModified(idx, material) {
- if (idx < this._models.length) {
- this._updateModelMaterial(this._models[idx], material);
- }
- }
-
- _clearMaterials() {
- for (let i = 0; i < this._models.length; ++i) {
- this._onMaterialModified(i, null);
- }
- }
-
- /**
- *
- * @param {Model} model
- * @param {Material} material
- */
- _updateModelMaterial(model, material) {
- model.setEffect((material ? material.effect : null) || this._getBuiltinMaterial().effect);
- }
-
- _updateCastShadow() {
- if (this._shadowCastingMode === ModelShadowCastingMode.Off) {
- for (let i = 0; i < this._models.length; ++i) {
- let model = this._models[i];
- model._castShadow = false;
- }
- } else if (this._shadowCastingMode === ModelShadowCastingMode.On) {
- for (let i = 0; i < this._models.length; ++i) {
- let model = this._models[i];
- model._castShadow = true;
- }
- } else {
- console.warn(`ShadowCastingMode ${this._shadowCastingMode} is not supported.`);
- }
- }
-
- _updateReceiveShadow() {
- for (let i = 0; i < this._models.length; ++i) {
- let model = this._models[i];
- if (model._defines['_USE_SHADOW_MAP'] != undefined) {
- this.getMaterial(i).define('_USE_SHADOW_MAP', this._receiveShadows);
- }
- }
- }
-
- _getBuiltinMaterial() {
- // classic ugly pink indicating missing material
- return cc.BuiltinResMgr['default-material'];
- }
-}
diff --git a/cocos/3d/framework/model-component.ts b/cocos/3d/framework/model-component.ts
new file mode 100644
index 0000000000..2063beb14c
--- /dev/null
+++ b/cocos/3d/framework/model-component.ts
@@ -0,0 +1,289 @@
+/****************************************************************************
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+import { builtinResMgr } from '../../3d/builtin';
+import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator';
+import Enum from '../../core/value-types/enum';
+import { Model } from '../../renderer/scene/model';
+import { Material } from '../assets/material';
+import { Mesh } from '../assets/mesh';
+import { RenderableComponent } from './renderable-component';
+
+/**
+ * !#en Shadow projection mode
+ *
+ * !#ch 阴影投射方式
+ * @static
+ * @enum ModelComponent.ShadowCastingMode
+ */
+const ModelShadowCastingMode = Enum({
+ /**
+ * !#en
+ *
+ * !#ch 关闭阴影投射
+ * @property Off
+ * @readonly
+ * @type {Number}
+ */
+ Off: 0,
+ /**
+ * !#en
+ *
+ * !#ch 开启阴影投射,当阴影光产生的时候
+ * @property On
+ * @readonly
+ * @type {Number}
+ */
+ On: 1,
+ /**
+ * !#en
+ *
+ * !#ch 可以从网格的任意一遍投射出阴影
+ * @property TwoSided
+ * @readonly
+ * @type {Number}
+ */
+ TwoSided: 2,
+ /**
+ * !#en
+ *
+ * !#ch 只显示阴影
+ * @property ShadowsOnly
+ * @readonly
+ * @type {Number}
+ */
+ ShadowsOnly: 3,
+});
+
+/**
+ * !#en The Model Component
+ *
+ * !#ch 模型组件
+ * @class ModelComponent
+ * @extends RenderableComponent
+ */
+@ccclass('cc.ModelComponent')
+@executionOrder(100)
+@menu('Components/ModelComponent')
+@executeInEditMode
+export class ModelComponent extends RenderableComponent {
+
+ /**
+ * !#en The mesh of the model
+ *
+ * !#ch 模型网格
+ * @type {Mesh}
+ */
+ @property({
+ type: Mesh,
+ })
+ get mesh () {
+ return this._mesh;
+ }
+
+ set mesh (val) {
+ this._mesh = val;
+ this._updateModels();
+ }
+
+ /**
+ * !#en The shadow casting mode
+ *
+ * !#ch 投射阴影方式
+ * @type {Number}
+ */
+ @property({
+ type: ModelShadowCastingMode,
+ })
+ get shadowCastingMode () {
+ return this._shadowCastingMode;
+ }
+
+ set shadowCastingMode (val) {
+ this._shadowCastingMode = val;
+ this._updateCastShadow();
+ }
+
+ /**
+ * !#en Does this model receive shadows?
+ *
+ * !#ch 是否接受阴影?
+ * @type {Boolean}
+ */
+ @property
+ get receiveShadows () {
+ return this._receiveShadows;
+ }
+
+ set receiveShadows (val) {
+ this._receiveShadows = val;
+ this._updateReceiveShadow();
+ }
+
+ get model () {
+ return this._model;
+ }
+
+ public static ShadowCastingMode = ModelShadowCastingMode;
+
+ protected _model: Model | null = null;
+
+ @property
+ private _mesh: Mesh | null = null;
+
+ @property
+ private _shadowCastingMode = ModelShadowCastingMode.Off;
+
+ @property
+ private _receiveShadows = false;
+
+ constructor () {
+ super();
+ }
+
+ public onLoad () {
+ super.onLoad();
+ }
+
+ public onEnable () {
+ if (!this._model) { this._updateModels(); }
+ this._updateCastShadow();
+ this._updateReceiveShadow();
+ if (this._model) {
+ this._model.enabled = true;
+ }
+ }
+
+ public onDisable () {
+ if (this._model) {
+ this._model.enabled = false;
+ }
+ }
+
+ public onDestroy () {
+ if (this._model) {
+ this._getRenderScene().destroyModel(this._model);
+ }
+ }
+
+ protected _updateModels () {
+ if (!this.enabledInHierarchy || !this.node._scene || !this._mesh) {
+ return;
+ }
+
+ if (this._model) {
+ this._model.destroy();
+ } else {
+ this._model = this._createModel();
+ }
+
+ this._model!.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition);
+
+ this._updateModelParams();
+
+ if (this._model) {
+ this._model.enabled = true;
+ }
+ }
+
+ protected _createModel () {
+ return this._getRenderScene().createModel(Model, this.node);
+ }
+
+ protected _updateModelParams () {
+ this.node._hasChanged = true;
+ if (!this._mesh || !this._model) {
+ return;
+ }
+ const meshCount = this._mesh ? this._mesh.subMeshCount : 0;
+ for (let i = 0; i < meshCount; ++i) {
+ const material = this.getSharedMaterial(i);
+ const renderingMesh = this._mesh.renderingMesh;
+ if (renderingMesh) {
+ const subMeshData = renderingMesh.getSubmesh(i);
+ if (subMeshData) {
+ this._model.initSubModel(i, subMeshData, material || this._getBuiltinMaterial());
+ }
+ }
+ }
+ }
+
+ protected _onMaterialModified (idx: number, material: Material | null) {
+ if (this._model == null) {
+ return;
+ }
+ this._onRebuildPSO(idx, material || this._getBuiltinMaterial());
+ }
+
+ protected _onRebuildPSO (idx: number, material: Material) {
+ if (this._model) {
+ this._model.setSubModelMaterial(idx, material);
+ }
+ }
+
+ protected _clearMaterials () {
+ if (this._model == null) {
+ return;
+ }
+ for (let i = 0; i < this._model.subModelNum; ++i) {
+ this._onMaterialModified(i, null);
+ }
+ }
+
+ private _updateCastShadow () {
+ if (!this.enabledInHierarchy || !this._model) {
+ return;
+ }
+ if (this._shadowCastingMode === ModelShadowCastingMode.Off) {
+ for (let i = 0; i < this._model.subModelNum; ++i) {
+ const subModel = this._model.getSubModel(i);
+ subModel.castShadow = false;
+ }
+ } else if (this._shadowCastingMode === ModelShadowCastingMode.On) {
+ for (let i = 0; i < this._model.subModelNum; ++i) {
+ const subModel = this._model.getSubModel(i);
+ subModel.castShadow = true;
+ }
+ } else {
+ console.warn(`ShadowCastingMode ${this._shadowCastingMode} is not supported.`);
+ }
+ }
+
+ private _updateReceiveShadow () {
+ if (!this.enabledInHierarchy || !this._model) {
+ return;
+ }
+ // for (let i = 0; i < this._model.subModelNum; ++i) {
+ // const subModel = this._model.getSubModel(i);
+ // if (subModel._defines['CC_USE_SHADOW_MAP'] != undefined) {
+ // this.getMaterial(i).define('CC_USE_SHADOW_MAP', this._receiveShadows);
+ // }
+ // }
+ }
+
+ private _getBuiltinMaterial () {
+ // classic ugly pink indicating missing material
+ return builtinResMgr.get('default-material');
+ }
+}
diff --git a/cocos/3d/framework/particle/animator/color-overtime.js b/cocos/3d/framework/particle/animator/color-overtime.ts
similarity index 78%
rename from cocos/3d/framework/particle/animator/color-overtime.js
rename to cocos/3d/framework/particle/animator/color-overtime.ts
index 0076e83137..082de437cb 100644
--- a/cocos/3d/framework/particle/animator/color-overtime.js
+++ b/cocos/3d/framework/particle/animator/color-overtime.ts
@@ -2,6 +2,9 @@ import { color4, pseudoRandom } from '../../../../core/vmath';
import { CCClass } from '../../../../core/data';
import GradientRange from './gradient-range';
import { property, ccclass } from '../../../../core/data/class-decorator';
+import Particle from '../particle';
+
+// tslint:disable: max-line-length
const COLOR_OVERTIME_RAND_OFFSET = 91041;
@@ -9,14 +12,14 @@ const COLOR_OVERTIME_RAND_OFFSET = 91041;
export default class ColorOvertimeModule {
@property
- enable = false;
+ public enable = false;
@property({
- type: GradientRange
+ type: GradientRange,
})
- color = new GradientRange();
+ public color = new GradientRange();
- animate(particle) {
+ public animate (particle: Particle) {
if (this.enable) {
color4.multiply(particle.color, particle.startColor01, this.color.evaluate(1.0 - particle.remainingLifetime / particle.startLifetime, pseudoRandom(particle.randomSeed + COLOR_OVERTIME_RAND_OFFSET)));
}
diff --git a/cocos/3d/framework/particle/animator/curve-range.js b/cocos/3d/framework/particle/animator/curve-range.ts
similarity index 76%
rename from cocos/3d/framework/particle/animator/curve-range.js
rename to cocos/3d/framework/particle/animator/curve-range.ts
index 501e516025..dd1e3eb3aa 100644
--- a/cocos/3d/framework/particle/animator/curve-range.js
+++ b/cocos/3d/framework/particle/animator/curve-range.ts
@@ -8,7 +8,7 @@ const Mode = Enum({
Constant: 0,
Curve: 1,
TwoCurves: 2,
- TwoConstants: 3
+ TwoConstants: 3,
});
@ccclass('cc.CurveRange')
@@ -20,37 +20,37 @@ export default class CurveRange {
mode = Mode.Constant;
@property({
- type: AnimationCurve
+ type: AnimationCurve,
})
- curve = new AnimationCurve();
+ public curve = new AnimationCurve();
@property({
- type: AnimationCurve
+ type: AnimationCurve,
})
- curveMin = new AnimationCurve();
+ public curveMin = new AnimationCurve();
@property({
- type: AnimationCurve
+ type: AnimationCurve,
})
- curveMax = new AnimationCurve();
+ public curveMax = new AnimationCurve();
@property
- constant = 0;
+ public constant = 0;
@property
- constantMin = 0;
+ public constantMin = 0;
@property
- constantMax = 0;
+ public constantMax = 0;
@property
- multiplier = 1;
+ public multiplier = 1;
- constructor() {
+ constructor () {
}
- evaluate(time, rndRatio) {
+ public evaluate (time: number, rndRatio: number) {
switch (this.mode) {
case Mode.Constant:
return this.constant;
diff --git a/cocos/3d/framework/particle/animator/force-overtime.js b/cocos/3d/framework/particle/animator/force-overtime.ts
similarity index 50%
rename from cocos/3d/framework/particle/animator/force-overtime.js
rename to cocos/3d/framework/particle/animator/force-overtime.ts
index cd5cac5587..3c3c35068f 100644
--- a/cocos/3d/framework/particle/animator/force-overtime.js
+++ b/cocos/3d/framework/particle/animator/force-overtime.ts
@@ -4,46 +4,53 @@ import CurveRange from './curve-range';
import { CCClass } from '../../../../core/data';
import { property, ccclass } from '../../../../core/data/class-decorator';
+// tslint:disable: max-line-length
const FORCE_OVERTIME_RAND_OFFSET = 212165;
@ccclass('cc.ForceOvertimeModule')
export default class ForceOvertimeModule {
@property
- enable = false;
+ public enable = false;
@property({
- type: CurveRange
+ type: CurveRange,
})
- x = new CurveRange();
+ public x = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- y = new CurveRange();
+ public y = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- z = new CurveRange();
+ public z = new CurveRange();
- @property
- space = Space.Local;
+ @property({
+ type: Space,
+ })
+ public space = Space.Local;
// TODO:currently not supported
- randomized = false;
+ public randomized = false;
- constructor() {
+ private rotation: quat;
+ private needTransform: boolean;
+
+ constructor () {
this.rotation = quat.create();
+ this.needTransform = false;
}
- update(space, worldTransform) {
- this.needTransform = calculateTransform(space, this._space, worldTransform, this.rotation);
+ public update (space, worldTransform) {
+ this.needTransform = calculateTransform(space, this.space, worldTransform, this.rotation);
}
- animate(p, dt) {
- let normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
- let force = vec3.create(this.x.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)), this.y.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)), this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)));
+ public animate (p, dt) {
+ const normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
+ const force = vec3.create(this.x.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)), this.y.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)), this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + FORCE_OVERTIME_RAND_OFFSET)));
if (this.needTransform) {
vec3.transformQuat(force, force, this.rotation);
}
diff --git a/cocos/3d/framework/particle/animator/gradient-range.js b/cocos/3d/framework/particle/animator/gradient-range.ts
similarity index 56%
rename from cocos/3d/framework/particle/animator/gradient-range.js
rename to cocos/3d/framework/particle/animator/gradient-range.ts
index d716ba4d82..e32ab1d365 100644
--- a/cocos/3d/framework/particle/animator/gradient-range.js
+++ b/cocos/3d/framework/particle/animator/gradient-range.ts
@@ -4,6 +4,8 @@ import Gradient from './gradient';
import { CCClass } from '../../../../core/data';
import { property, ccclass } from '../../../../core/data/class-decorator';
+// tslint:disable: max-line-length
+
const GRADIENT_MODE_FIX = 0;
const GRADIENT_MODE_BLEND = 1;
@@ -18,7 +20,7 @@ const Mode = Enum({
Gradient: 1,
TwoColors: 2,
TwoGradients: 3,
- RandomColor: 4
+ RandomColor: 4,
});
@ccclass('cc.GradientRange')
@@ -30,30 +32,30 @@ export default class GradientRange {
mode = Mode.Color;
@property
- color = cc.Color.WHITE;
+ public color = cc.Color.WHITE;
@property
- colorMin = cc.Color.WHITE;
+ public colorMin = cc.Color.WHITE;
@property
- colorMax = cc.Color.WHITE;
+ public colorMax = cc.Color.WHITE;
@property({
- type: Gradient
+ type: Gradient,
})
- gradient = new Gradient();
+ public gradient = new Gradient();
@property({
- type: Gradient
+ type: Gradient,
})
- gradientMin = new Gradient();
+ public gradientMin = new Gradient();
@property({
- type: Gradient
+ type: Gradient,
})
- gradientMax = new Gradient();
+ public gradientMax = new Gradient();
- evaluate(time, rndRatio) {
+ public evaluate (time: number, rndRatio: number) {
switch (this.mode) {
case Mode.Color:
return this.color;
@@ -84,60 +86,72 @@ export default class GradientRange {
// });
export class GradientUniform {
- constructor(gr) {
+ public gr: GradientRange;
+ public minColor: Float32Array;
+ public maxColor: Float32Array;
+ public minColorKeyTime: Float32Array;
+ public minColorKeyValue: Float32Array;
+ public minAlphaKeyTime: Float32Array;
+ public minAlphaKeyValue: Float32Array;
+ public maxColorKeyTime: Float32Array;
+ public maxColorKeyValue: Float32Array;
+ public maxAlphaKeyTime: Float32Array;
+ public maxAlphaKeyValue: Float32Array;
+
+ constructor (gr: GradientRange) {
this.gr = gr;
- if (gr._mode == 'color') {
+ if (gr.mode === 'color') {
this.minColor = new Float32Array(4);
- color4.array(this.minColor, gr._color);
- } else if (gr._mode == 'twoColors') {
+ color4.array(this.minColor, gr.color);
+ } else if (gr.mode === 'twoColors') {
this.minColor = new Float32Array(4);
this.maxColor = new Float32Array(4);
- color4.array(this.minColor, gr._colorMin);
- color4.array(this.maxColor, gr._colorMax);
- } else if (gr._mode == 'gradient') {
- this.minColorKeyTime = new Float32Array(gr._gradient._colorKeys.length);
+ color4.array(this.minColor, gr.colorMin);
+ color4.array(this.maxColor, gr.colorMax);
+ } else if (gr.mode === 'gradient') {
+ this.minColorKeyTime = new Float32Array(gr.gradient.colorKeys.length);
this.minColorKeyValue = new Float32Array(3 * this.minColorKeyTime.length);
- this.minAlphaKeyTime = new Float32Array(gr._gradient._alphaKeys.length);
+ this.minAlphaKeyTime = new Float32Array(gr.gradient.alphaKeys.length);
this.minAlphaKeyValue = new Float32Array(this.minAlphaKeyTime.length);
- this.constructor.generateGradientUniform(gr._gradient, this.minColorKeyTime, this.minColorKeyValue, this.minAlphaKeyTime, this.minAlphaKeyValue);
- } else if (gr._mode == 'twoGradients') {
- this.minColorKeyTime = new Float32Array(gr._gradientMin._colorKeys.length);
+ this.constructor.generateGradientUniform(gr.gradient, this.minColorKeyTime, this.minColorKeyValue, this.minAlphaKeyTime, this.minAlphaKeyValue);
+ } else if (gr.mode === 'twoGradients') {
+ this.minColorKeyTime = new Float32Array(gr.gradientMin.colorKeys.length);
this.minColorKeyValue = new Float32Array(3 * this.minColorKeyTime.length);
- this.minAlphaKeyTime = new Float32Array(gr._gradientMin._alphaKeys.length);
+ this.minAlphaKeyTime = new Float32Array(gr.gradientMin.alphaKeys.length);
this.minAlphaKeyValue = new Float32Array(this.minAlphaKeyTime.length);
- this.constructor.generateGradientUniform(gr._gradientMin, this.minColorKeyTime, this.minColorKeyValue, this.minAlphaKeyTime, this.minAlphaKeyValue);
- this.maxColorKeyTime = new Float32Array(gr._gradientMax._colorKeys.length);
+ this.constructor.generateGradientUniform(gr.gradientMin, this.minColorKeyTime, this.minColorKeyValue, this.minAlphaKeyTime, this.minAlphaKeyValue);
+ this.maxColorKeyTime = new Float32Array(gr.gradientMax.colorKeys.length);
this.maxColorKeyValue = new Float32Array(3 * this.maxColorKeyTime.length);
- this.maxAlphaKeyTime = new Float32Array(gr._gradientMax._alphaKeys.length);
+ this.maxAlphaKeyTime = new Float32Array(gr.gradientMax.alphaKeys.length);
this.maxAlphaKeyValue = new Float32Array(this.maxAlphaKeyTime.length);
- this.constructor.generateGradientUniform(gr._gradientMax, this.maxColorKeyTime, this.maxColorKeyValue, this.maxAlphaKeyTime, this.maxAlphaKeyValue);
+ this.constructor.generateGradientUniform(gr.gradientMax, this.maxColorKeyTime, this.maxColorKeyValue, this.maxAlphaKeyTime, this.maxAlphaKeyValue);
}
}
- uploadUniform(device, name) {
- if (this.gr._mode == 'color') {
+ public uploadUniform (device: any, name: string) {
+ if (this.gr.mode === 'color') {
device.setUniform('u_' + name + '_rangeMode', GRADIENT_RANGE_MODE_COLOR);
device.setUniform('u_' + name + '_minColor', this.minColor);
- } else if (this.gr._mode == 'twoColors') {
+ } else if (this.gr.mode === 'twoColors') {
device.setUniform('u_' + name + '_rangeMode', GRADIENT_RANGE_MODE_TWO_COLOR);
device.setUniform('u_' + name + '_minColor', this.minColor);
device.setUniform('u_' + name + '_maxColor', this.maxColor);
- } else if (this.gr._mode == 'gradient') {
+ } else if (this.gr.mode === 'gradient') {
device.setUniform('u_' + name + '_rangeMode', GRADIENT_RANGE_MODE_GRADIENT);
- device.setUniform('u_' + name + '_minGradMode', this.gr._gradient._mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX);
+ device.setUniform('u_' + name + '_minGradMode', this.gr.gradient.mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX);
device.setUniform('u_' + name + '_minColorKeyValue', this.minColorKeyValue);
device.setUniform('u_' + name + '_minColorKeyTime', this.minColorKeyTime);
device.setUniform('u_' + name + '_minAlphaKeyValue', this.minAlphaKeyValue);
device.setUniform('u_' + name + '_minAlphaKeyTime', this.minAlphaKeyTime);
- } else if (this.gr._mode == 'twoGradients') {
+ } else if (this.gr.mode === 'twoGradients') {
device.setUniform('u_' + name + '_rangeMode', GRADIENT_RANGE_MODE_TWO_GRADIENT);
- device.setUniform('u_' + name + '_minGradMode', this.gr._gradientMin._mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX);
+ device.setUniform('u_' + name + '_minGradMode', this.gr.gradientMin.mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX);
device.setUniform('u_' + name + '_minColorKeyValue', this.minColorKeyValue);
device.setUniform('u_' + name + '_minColorKeyTime', this.minColorKeyTime);
device.setUniform('u_' + name + '_minAlphaKeyValue', this.minAlphaKeyValue);
device.setUniform('u_' + name + '_minAlphaKeyTime', this.minAlphaKeyTime);
- device.setUniform('u_' + name + '_maxGradMode', this.gr._gradientMax._mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX);
+ device.setUniform('u_' + name + '_maxGradMode', this.gr.gradientMax.mode === 'blend' ? GRADIENT_MODE_BLEND : GRADIENT_MODE_FIX);
device.setUniform('u_' + name + '_maxColorKeyValue', this.maxColorKeyValue);
device.setUniform('u_' + name + '_maxColorKeyTime', this.maxColorKeyTime);
device.setUniform('u_' + name + '_maxAlphaKeyValue', this.maxAlphaKeyValue);
@@ -145,16 +159,16 @@ export class GradientUniform {
}
}
- static generateGradientUniform(gradient, colorKeyTime, colorKeyValue, alphaKeyTime, alphaKeyValue) {
- for (let i = 0; i < gradient._colorKeys.length; i++) {
- colorKeyTime[i] = gradient._colorKeys[i]._time;
- colorKeyValue[i * 3] = gradient._colorKeys[i]._color.r;
- colorKeyValue[i * 3 + 1] = gradient._colorKeys[i]._color.g;
- colorKeyValue[i * 3 + 2] = gradient._colorKeys[i]._color.b;
+ public static generateGradientUniform (gradient: Gradient, colorKeyTime: number, colorKeyValue: Float32Array, alphaKeyTime: number, alphaKeyValue: Float32Array) {
+ for (let i = 0; i < gradient.colorKeys.length; i++) {
+ colorKeyTime[i] = gradient.colorKeys[i].time;
+ colorKeyValue[i * 3] = gradient.colorKeys[i].color.r;
+ colorKeyValue[i * 3 + 1] = gradient.colorKeys[i].color.g;
+ colorKeyValue[i * 3 + 2] = gradient.colorKeys[i].color.b;
}
- for (let i = 0; i < gradient._alphaKeys.length; i++) {
- alphaKeyTime[i] = gradient._alphaKeys[i]._time;
- alphaKeyValue[i] = gradient._alphaKeys[i]._alpha;
+ for (let i = 0; i < gradient.alphaKeys.length; i++) {
+ alphaKeyTime[i] = gradient.alphaKeys[i].time;
+ alphaKeyValue[i] = gradient.alphaKeys[i].alpha;
}
}
}
diff --git a/cocos/3d/framework/particle/animator/gradient.js b/cocos/3d/framework/particle/animator/gradient.ts
similarity index 66%
rename from cocos/3d/framework/particle/animator/gradient.js
rename to cocos/3d/framework/particle/animator/gradient.ts
index 2061b768d2..e1d81d01e2 100644
--- a/cocos/3d/framework/particle/animator/gradient.js
+++ b/cocos/3d/framework/particle/animator/gradient.ts
@@ -1,21 +1,21 @@
import { repeat } from '../../../../core/vmath';
-import { Enum, ValueType } from '../../../../core/value-types';
+import { Enum, ValueType, Color } from '../../../../core/value-types';
import { CCClass } from '../../../../core/data';
import { property, ccclass } from '../../../../core/data/class-decorator';
const Mode = Enum({
Blend: 0,
- Fixed: 1
+ Fixed: 1,
});
@ccclass('cc.ColorKey')
export class ColorKey {
@property
- color = cc.Color.WHITE;
+ public color = cc.Color.WHITE;
@property
- time = 0;
+ public time = 0;
}
// CCClass.fastDefine('cc.ColorKey', ColorKey, {
@@ -27,10 +27,10 @@ export class ColorKey {
export class AlphaKey {
@property
- alpha = 1;
+ public alpha = 1;
@property
- time = 0;
+ public time = 0;
}
// CCClass.fastDefine('cc.AlphaKey', AlphaKey, {
@@ -42,24 +42,26 @@ export class AlphaKey {
export default class Gradient {
@property
- colorKeys = [];
+ public colorKeys = new Array();
@property
- alphaKeys = []
+ public alphaKeys = new Array();
@property
- mode = Mode.Blend;
+ public mode = Mode.Blend;
- constructor() {
+ private _color: Color;
+
+ constructor () {
this._color = cc.Color.WHITE;
}
- setKeys(colorKeys, alphaKeys) {
+ public setKeys (colorKeys, alphaKeys) {
this.colorKeys = colorKeys;
this.alphaKeys = alphaKeys;
}
- sortKeys() {
+ public sortKeys () {
if (this.colorKeys.length > 1) {
this.colorKeys.sort((a, b) => a.time - b.time);
}
@@ -68,17 +70,17 @@ export default class Gradient {
}
}
- getRGB(time) {
+ private getRGB (time: number) {
if (this.colorKeys.length > 1) {
time = repeat(time, 1);
for (let i = 1; i < this.colorKeys.length; ++i) {
- let preTime = this.colorKeys[i - 1].time;
- let curTime = this.colorKeys[i].time;
+ const preTime = this.colorKeys[i - 1].time;
+ const curTime = this.colorKeys[i].time;
if (time >= preTime && time < curTime) {
- if (this._mode === 'fixed') {
+ if (this.mode === 'fixed') {
return this.colorKeys[i].color;
}
- let factor = (time - preTime) / (curTime - preTime);
+ const factor = (time - preTime) / (curTime - preTime);
this.colorKeys[i - 1].color.lerp(this.colorKeys[i].color, factor, this._color);
return this._color;
}
@@ -96,17 +98,17 @@ export default class Gradient {
}
}
- getAlpha(time) {
+ private getAlpha (time) {
if (this.alphaKeys.length > 1) {
time = repeat(time, 1);
for (let i = 1; i < this.alphaKeys.length; ++i) {
- let preTime = this.alphaKeys[i - 1].time;
- let curTime = this.alphaKeys[i].time;
+ const preTime = this.alphaKeys[i - 1].time;
+ const curTime = this.alphaKeys[i].time;
if (time >= preTime && time < curTime) {
- if (this._mode === 'fixed') {
+ if (this.mode === 'fixed') {
return this.alphaKeys[i].alpha;
}
- let factor = (time - preTime) / (curTime - preTime);
+ const factor = (time - preTime) / (curTime - preTime);
return (this.alphaKeys[i - 1].alpha * (1 - factor) + this.alphaKeys[i].alpha * factor);
}
}
@@ -118,19 +120,19 @@ export default class Gradient {
}
}
- evaluate(time) {
+ public evaluate (time) {
this.getRGB(time);
- this._color.a = this.getAlpha(time);
+ this._color.a = this.getAlpha(time)!;
return this._color;
}
- randomColor() {
- let c = this.colorKeys[Math.trunc(Math.random() * this.colorKeys.length)];
- let a = this.alphaKeys[Math.trunc(Math.random() * this.alphaKeys.length)];
- this._color.r = c.r;
- this._color.g = c.g;
- this._color.b = c.b;
- this._color.a = a;
+ public randomColor () {
+ const c = this.colorKeys[Math.trunc(Math.random() * this.colorKeys.length)];
+ const a = this.alphaKeys[Math.trunc(Math.random() * this.alphaKeys.length)];
+ this._color.r = c.color.r;
+ this._color.g = c.color.g;
+ this._color.b = c.color.b;
+ this._color.a = a.alpha;
return this._color;
}
}
diff --git a/cocos/3d/framework/particle/animator/limit-velocity-overtime.js b/cocos/3d/framework/particle/animator/limit-velocity-overtime.ts
similarity index 64%
rename from cocos/3d/framework/particle/animator/limit-velocity-overtime.js
rename to cocos/3d/framework/particle/animator/limit-velocity-overtime.ts
index f7307cd5e5..5c7ad59f4a 100644
--- a/cocos/3d/framework/particle/animator/limit-velocity-overtime.js
+++ b/cocos/3d/framework/particle/animator/limit-velocity-overtime.ts
@@ -3,73 +3,78 @@ import { CCClass } from '../../../../core/data';
import { Space } from '../particle-general-function';
import { property, ccclass } from '../../../../core/data/class-decorator';
import CurveRange from './curve-range';
+import Particle from '../particle';
+// tslint:disable: max-line-length
const LIMIT_VELOCITY_RAND_OFFSET = 23541;
@ccclass('cc.LimitVelocityOvertimeModule')
export default class LimitVelocityOvertimeModule {
- enable = false;
+ @property
+ public enable = false;
@property({
- type: CurveRange
+ type: CurveRange,
})
- limitX = new CurveRange();
+ public limitX = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- limitY = new CurveRange();
+ public limitY = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- limitZ = new CurveRange();
+ public limitZ = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- limit = new CurveRange();
+ public limit = new CurveRange();
@property
- dampen = 0;
+ public dampen = 0;
@property
- separateAxes = false;
+ public separateAxes = false;
- @property
- space = Space.Local;
+ @property({
+ type: Space,
+ })
+ public space = Space.Local;
// TODO:functions related to drag are temporarily not supported
- drag = null;
+ public drag = null;
- multiplyDragByParticleSize = false;
+ public multiplyDragByParticleSize = false;
- multiplyDragByParticleVelocity = false;
+ public multiplyDragByParticleVelocity = false;
- constructor() {
+ constructor () {
}
- animate(p) {
- let normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
- let dampedVel = vec3.create(0, 0, 0);
+ public animate (p: Particle) {
+ const normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
+ const dampedVel = vec3.create(0, 0, 0);
if (this.separateAxes) {
vec3.set(dampedVel,
- dampenBeyondLimit(p.ultimateVelocity.x, this.limitX.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET)), this.dampen),
- dampenBeyondLimit(p.ultimateVelocity.y, this.limitY.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET)), this.dampen),
- dampenBeyondLimit(p.ultimateVelocity.z, this.limitZ.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET)), this.dampen));
+ dampenBeyondLimit(p.ultimateVelocity.x, this.limitX.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen),
+ dampenBeyondLimit(p.ultimateVelocity.y, this.limitY.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen),
+ dampenBeyondLimit(p.ultimateVelocity.z, this.limitZ.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen));
}
else {
vec3.normalize(dampedVel, p.ultimateVelocity);
- vec3.scale(dampedVel, dampedVel, dampenBeyondLimit(vec3.magnitude(p.ultimateVelocity), this.limit.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET)), this.dampen));
+ vec3.scale(dampedVel, dampedVel, dampenBeyondLimit(vec3.magnitude(p.ultimateVelocity), this.limit.evaluate(normalizedTime, pseudoRandom(p.randomSeed + LIMIT_VELOCITY_RAND_OFFSET))!, this.dampen));
}
vec3.copy(p.ultimateVelocity, dampedVel);
}
}
-function dampenBeyondLimit(vel, limit, dampen) {
- let sgn = Math.sign(vel);
+function dampenBeyondLimit (vel: number, limit: number, dampen: number) {
+ const sgn = Math.sign(vel);
let abs = Math.abs(vel);
if (abs > limit) {
abs = lerp(abs, limit, dampen);
diff --git a/cocos/3d/framework/particle/animator/optimized-curve.js b/cocos/3d/framework/particle/animator/optimized-curve.js
deleted file mode 100644
index c022c98dbe..0000000000
--- a/cocos/3d/framework/particle/animator/optimized-curve.js
+++ /dev/null
@@ -1,297 +0,0 @@
-import { OptimizedKey, evalOptCurve } from "../../../geom-utils/curve";
-import { repeat } from "../../../../core/vmath";
-
-const CURVE_MODE_CONSTANT = 0;
-const CURVE_MODE_RANDOM_CONSTANT = 1;
-const CURVE_MODE_CURVE = 2;
-const CURVE_MODE_RANDOM_CURVE = 3;
-
-const UNIFORM_CURVE_KEY_NUM = 8;
-
-//calculate the coefficience of the first order integral of the curve
-function integrateKeyframe(coef) {
- coef[0] = coef[0] / 4;
- coef[1] = coef[1] / 3;
- coef[2] = coef[2] / 2;
- coef[3] = coef[3];
- return coef;
-}
-
-//calculate the coefficience of the second order integral of the curve
-function integrateKeyframeTwice(coef) {
- coef[0] = coef[0] / 20;
- coef[1] = coef[1] / 12;
- coef[2] = coef[2] / 6;
- coef[3] = coef[3] / 2;
- return coef;
-}
-
-export class OptimizedCurve {
- constructor(constructUniform = false) {
- this.optimizedKeys = new Array; //the i-th optimezed key stores coefficients of [i,i+1] segment in the original curve,so if the time of last key of the original key is 1,the last key won't be kept in the opt curve.
- this.integral = new Array; //the integral of the curve between 0 and corresponding key,the i-th integral corresponds to the i+1-th key in optimizedKeys (because the integral of the first key is always zero,the first key won't be stored)
- this.constructUniform = constructUniform;
- }
-
- buildCurve(animationCurve, multiplier = 1) {
- let keyNum = animationCurve.keyFrames.length - 1;
- let i = 0;
- if (this.optimizedKeys.length < keyNum) {
- let keyToAdd = keyNum - this.optimizedKeys.length;
- for (i = 0; i < keyToAdd; i++) {
- let optKey = new OptimizedKey();
- this.optimizedKeys.push(optKey);
- }
- } else {
- this.optimizedKeys.splice(keyNum);
- }
- if (animationCurve.keyFrames.length === 1) {
- this.optimizedKeys[0].coefficient[3] = animationCurve.keyFrames[0].value * multiplier;
- this.optimizedKeys[0].time = 0;
- this.optimizedKeys[0].endTime = 1;
- } else {
- let keyOffset = 0;
- if (animationCurve.keyFrames[0].time !== 0) {
- this.optimizedKeys.splice(0, 0, new OptimizedKey());
- this.optimizedKeys[0].time = 0;
- this.optimizedKeys[0].endTime = animationCurve.keyFrames[0].time;
- this.optimizedKeys[0].coefficient[3] = animationCurve.keyFrames[0].value;
- keyOffset = 1;
- }
- for (i = 0; i < keyNum; i++) {
- animationCurve.calcOptimizedKey(this.optimizedKeys[i + keyOffset], i, Math.min(i + 1, keyNum));
- this.optimizedKeys[i + keyOffset].index += keyOffset;
- }
- if (animationCurve.keyFrames[animationCurve.keyFrames.length - 1].time !== 1) {
- this.optimizedKeys.push(new OptimizedKey());
- this.optimizedKeys[this.optimizedKeys.length - 1].time = animationCurve.keyFrames[animationCurve.length - 1].time;
- this.optimizedKeys[this.optimizedKeys.length - 1].endTime = 1;
- this.optimizedKeys[this.optimizedKeys.length - 1].coefficient[3] = animationCurve.keyFrames[animationCurve.length - 1].value;
- }
- }
- for (i = 0; i < this.optimizedKeys.length; i++) {
- this.optimizedKeys[i].coefficient[0] *= multiplier;
- this.optimizedKeys[i].coefficient[1] *= multiplier;
- this.optimizedKeys[i].coefficient[2] *= multiplier;
- this.optimizedKeys[i].coefficient[3] *= multiplier;
- }
- if (this.constructUniform) {
- this.coefUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM * 4);
- this.timeUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM);
- this.updateKeyUniform();
- }
- }
-
- evaluate(time) {
- time = repeat(time, 1);
- for (let i = 1; i < this.optimizedKeys.length; i++) {
- if (time < this.optimizedKeys[i].time) {
- return this.optimizedKeys[i - 1].evaluate(time);
- }
- }
- return this.optimizedKeys[this.optimizedKeys.length - 1].evaluate(time);
- }
-
- //calculate first order integral coefficients of all keys
- integrateOnce() {
- let i = 0;
- if (this.integral.length + 1 < this.optimizedKeys.length) {
- for (i = 0; i < this.optimizedKeys.length - this.integral.length - 1; i++) {
- this.integral.push(0);
- }
- } else {
- this.integral.splice(this.optimizedKeys.length - 1);
- }
- for (i = 0; i < this.integral.length; i++) {
- integrateKeyframe(this.optimizedKeys[i].coefficient);
- let deltaT = this.optimizedKeys[i + 1].time - this.optimizedKeys[i].time;
- let prevIntegral = i === 0 ? 0 : this.integral[i - 1];
- this.integral[i] = prevIntegral + (deltaT * evalOptCurve(deltaT, this.optimizedKeys[i].coefficient));
- }
- integrateKeyframe(this.optimizedKeys[this.optimizedKeys.length - 1].coefficient);
- if (this.constructUniform) {
- this.updateKeyUniform();
- this.updateIntegralUniform();
- }
- }
-
- //get the integral of the curve using calculated coefficients
- evaluateIntegral(t, ts = 1) {
- t = repeat(t, 1);
- for (let i = 1; i < this.optimizedKeys.length; i++) {
- if (t < this.optimizedKeys[i].time) {
- let prevInt = i === 1 ? 0 : this.integral[i - 2];
- let dt = t - this.optimizedKeys[i - 1].time;
- return ts * (prevInt + (dt * evalOptCurve(dt, this.optimizedKeys[i - 1].coefficient)));
- }
- }
- let dt = t - this.optimizedKeys[this.optimizedKeys.length - 1].time;
- return ts * (this.integral[this.integral.length - 1] + (dt * evalOptCurve(dt, this.optimizedKeys[this.optimizedKeys.length - 1].coefficient)));
- }
-
- //calculate second order integral coefficients of all keys
- integrateTwice() {
- let i = 0;
- if (this.integral.length + 1 < this.optimizedKeys.length) {
- for (i = 0; i < this.optimizedKeys.length - this.integral.length - 1; i++) {
- this.integral.push(0);
- }
- } else {
- this.integral.splice(this.optimizedKeys.length - 1);
- }
- for (i = 0; i < this.integral.length; i++) {
- integrateKeyframeTwice(this.optimizedKeys[i].coefficient);
- let deltaT = this.optimizedKeys[i + 1].time - this.optimizedKeys[i].time;
- let prevIntegral = i === 0 ? 0 : this.integral[i - 1];
- this.integral[i] = prevIntegral + (deltaT * deltaT * evalOptCurve(deltaT, this.optimizedKeys[i].coefficient));
- }
- integrateKeyframeTwice(this.optimizedKeys[this.optimizedKeys.length - 1].coefficient);
- if (this.constructUniform) {
- this.updateKeyUniform();
- this.updateIntegralUniform();
- }
- }
-
- //get the second order integral of the curve using calculated coefficients
- evaluateIntegralTwice(t, ts = 1) {
- t = repeat(t, 1);
- for (let i = 1; i < this.optimizedKeys.length; i++) {
- if (t < this.optimizedKeys[i].time) {
- let prevInt = i === 1 ? 0 : this.integral[i - 2];
- let dt = t - this.optimizedKeys[i - 1].time;
- return ts * ts * (prevInt + (dt * dt * evalOptCurve(dt, this.optimizedKeys[i - 1].coefficient)));
- }
- }
- let dt = t - this.optimizedKeys[this.optimizedKeys.length - 1].time;
- return ts * ts * (this.integral[this.integral.length - 1] + (dt * dt * evalOptCurve(dt, this.optimizedKeys[this.optimizedKeys.length - 1].coefficient)));
- }
-
- updateKeyUniform() {
- for (let i = 0; i < this.optimizedKeys.length; i++) {
- this.coefUniform[i * 4] = this.optimizedKeys[i].coefficient[0];
- this.coefUniform[i * 4 + 1] = this.optimizedKeys[i].coefficient[1];
- this.coefUniform[i * 4 + 2] = this.optimizedKeys[i].coefficient[2];
- this.coefUniform[i * 4 + 3] = this.optimizedKeys[i].coefficient[3];
- this.timeUniform[i] = this.optimizedKeys[i].endTime;
- }
- }
-
- updateIntegralUniform() {
- this.integralUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM - 1);
- for (let i = 0; i < this.integral.length; i++) {
- this.integralUniform[i] = this.integral[i];
- }
- }
-}
-
-export class CurveUniform {
- constructCurve(cr) {
- this.mode = cr.mode;
- switch (cr.mode) {
- case 'constant':
- this.minConstant = cr.constant;
- break;
- case 'twoConstants':
- this.minConstant = cr.constantMin;
- this.maxConstant = cr.constantMax;
- break;
- case 'curve':
- this.minCurve = new OptimizedCurve(true);
- this.minCurve.buildCurve(cr.curve, cr.multiplier);
- break;
- case 'twoCurves':
- this.minCurve = new OptimizedCurve(true);
- this.minCurve.buildCurve(cr.curveMin, cr.multiplier);
- this.maxCurve = new OptimizedCurve(true);
- this.maxCurve.buildCurve(cr.curveMax, cr.multiplier);
- break;
- }
- }
-
- constructCurveIntegral(cr) {
- this.mode = cr.mode;
- switch (cr.mode) {
- case 'constant':
- this.minConstant = cr.constant;
- break;
- case 'twoConstants':
- this.minConstant = cr.constantMin;
- this.maxConstant = cr.constantMax;
- break;
- case 'curve':
- this.minCurve = new OptimizedCurve(true);
- this.minCurve.buildCurve(cr.curve, cr.multiplier);
- this.minCurve.integrateOnce();
- break;
- case 'twoCurves':
- this.minCurve = new OptimizedCurve(true);
- this.minCurve.buildCurve(cr.curveMin, cr.multiplier);
- this.minCurve.integrateOnce();
- this.maxCurve = new OptimizedCurve(true);
- this.maxCurve.buildCurve(cr.curveMax, cr.multiplier);
- this.maxCurve.integrateOnce();
- break;
- }
- }
-
- constructCurveIntegralTwice(cr) {
- this.mode = cr.mode;
- switch (cr.mode) {
- case 'constant':
- this.minConstant = cr.constant;
- break;
- case 'twoConstants':
- this.minConstant = cr.constantMin;
- this.maxConstant = cr.constantMax;
- break;
- case 'curve':
- this.minCurve = new OptimizedCurve(true);
- this.minCurve.buildCurve(cr.curve, cr.multiplier);
- this.minCurve.integrateTwice();
- break;
- case 'twoCurves':
- this.minCurve = new OptimizedCurve(true);
- this.minCurve.buildCurve(cr.curveMin, cr.multiplier);
- this.minCurve.integrateTwice();
- this.maxCurve = new OptimizedCurve(true);
- this.maxCurve.buildCurve(cr.curveMax, cr.multiplier);
- this.maxCurve.integrateTwice();
- break;
- }
- }
-
- uploadUniform(device, name) {
- switch (this.mode) {
- case 'constant':
- device.setUniform('u_' + name + '_curveMode', CURVE_MODE_CONSTANT);
- device.setUniform('u_' + name + '_minConstant', this.minConstant);
- break;
- case 'twoConstants':
- device.setUniform('u_' + name + '_curveMode', CURVE_MODE_RANDOM_CONSTANT);
- device.setUniform('u_' + name + '_minConstant', this.minConstant);
- device.setUniform('u_' + name + '_maxConstant', this.maxConstant);
- break;
- case 'curve':
- device.setUniform('u_' + name + '_curveMode', CURVE_MODE_CURVE);
- device.setUniform('u_' + name + '_minKeyTime', this.minCurve.timeUniform);
- device.setUniform('u_' + name + '_minKeyCoef', this.minCurve.coefUniform);
- if (this.minCurve.integralUniform !== undefined) {
- device.setUniform('u_' + name + '_minIntegral', this.minCurve.integralUniform);
- }
- break;
- case 'twoCurves':
- device.setUniform('u_' + name + '_curveMode', CURVE_MODE_RANDOM_CURVE);
- device.setUniform('u_' + name + '_minKeyTime', this.minCurve.timeUniform);
- device.setUniform('u_' + name + '_minKeyCoef', this.minCurve.coefUniform);
- if (this.minCurve.integralUniform !== undefined) {
- device.setUniform('u_' + name + '_minIntegral', this.minCurve.integralUniform);
- }
- device.setUniform('u_' + name + '_maxKeyTime', this.maxCurve.timeUniform);
- device.setUniform('u_' + name + '_maxKeyCoef', this.maxCurve.coefUniform);
- if (this.minCurve.integralUniform !== undefined) {
- device.setUniform('u_' + name + '_maxIntegral', this.maxCurve.integralUniform);
- }
- break;
- }
- }
-}
diff --git a/cocos/3d/framework/particle/animator/optimized-curve.ts b/cocos/3d/framework/particle/animator/optimized-curve.ts
new file mode 100644
index 0000000000..ded36f8cd3
--- /dev/null
+++ b/cocos/3d/framework/particle/animator/optimized-curve.ts
@@ -0,0 +1,313 @@
+import { OptimizedKey, evalOptCurve, AnimationCurve } from "../../../geom-utils/curve";
+import { repeat } from "../../../../core/vmath";
+import CurveRange from "./curve-range";
+
+// tslint:disable: max-line-length
+
+const CURVE_MODE_CONSTANT = 0;
+const CURVE_MODE_RANDOM_CONSTANT = 1;
+const CURVE_MODE_CURVE = 2;
+const CURVE_MODE_RANDOM_CURVE = 3;
+
+const UNIFORM_CURVE_KEY_NUM = 8;
+
+// calculate the coefficience of the first order integral of the curve
+function integrateKeyframe (coef: Float32Array) {
+ coef[0] = coef[0] / 4;
+ coef[1] = coef[1] / 3;
+ coef[2] = coef[2] / 2;
+ coef[3] = coef[3];
+ return coef;
+}
+
+// calculate the coefficience of the second order integral of the curve
+function integrateKeyframeTwice (coef: Float32Array) {
+ coef[0] = coef[0] / 20;
+ coef[1] = coef[1] / 12;
+ coef[2] = coef[2] / 6;
+ coef[3] = coef[3] / 2;
+ return coef;
+}
+
+export class OptimizedCurve {
+ private optimizedKeys: OptimizedKey[];
+ private integral: number[];
+ private constructUniform: boolean;
+ private coefUniform: Float32Array;
+ private timeUniform: Float32Array;
+ private integralUniform: Float32Array;
+
+ constructor (constructUniform = false) {
+ this.optimizedKeys = new Array(); // the i-th optimezed key stores coefficients of [i,i+1] segment in the original curve,so if the time of last key of the original key is 1,the last key won't be kept in the opt curve.
+ this.integral = new Array(); // the integral of the curve between 0 and corresponding key,the i-th integral corresponds to the i+1-th key in optimizedKeys (because the integral of the first key is always zero,the first key won't be stored)
+ this.constructUniform = constructUniform;
+ }
+
+ public buildCurve (animationCurve: AnimationCurve, multiplier: number = 1) {
+ const keyNum = animationCurve.keyFrames!.length - 1;
+ let i = 0;
+ if (this.optimizedKeys.length < keyNum) {
+ const keyToAdd = keyNum - this.optimizedKeys.length;
+ for (i = 0; i < keyToAdd; i++) {
+ const optKey = new OptimizedKey();
+ this.optimizedKeys.push(optKey);
+ }
+ } else {
+ this.optimizedKeys.splice(keyNum);
+ }
+ if (animationCurve.keyFrames!.length === 1) {
+ this.optimizedKeys[0].coefficient[3] = animationCurve.keyFrames![0].value * multiplier;
+ this.optimizedKeys[0].time = 0;
+ this.optimizedKeys[0].endTime = 1;
+ } else {
+ let keyOffset = 0;
+ if (animationCurve.keyFrames![0].time !== 0) {
+ this.optimizedKeys.splice(0, 0, new OptimizedKey());
+ this.optimizedKeys[0].time = 0;
+ this.optimizedKeys[0].endTime = animationCurve.keyFrames![0].time;
+ this.optimizedKeys[0].coefficient[3] = animationCurve.keyFrames![0].value;
+ keyOffset = 1;
+ }
+ for (i = 0; i < keyNum; i++) {
+ animationCurve.calcOptimizedKey(this.optimizedKeys[i + keyOffset], i, Math.min(i + 1, keyNum));
+ this.optimizedKeys[i + keyOffset].index += keyOffset;
+ }
+ if (animationCurve.keyFrames![animationCurve.keyFrames!.length - 1].time !== 1) {
+ this.optimizedKeys.push(new OptimizedKey());
+ this.optimizedKeys[this.optimizedKeys.length - 1].time = animationCurve.keyFrames![animationCurve.keyFrames!.length - 1].time;
+ this.optimizedKeys[this.optimizedKeys.length - 1].endTime = 1;
+ this.optimizedKeys[this.optimizedKeys.length - 1].coefficient[3] = animationCurve.keyFrames![animationCurve.keyFrames!.length - 1].value;
+ }
+ }
+ for (i = 0; i < this.optimizedKeys.length; i++) {
+ this.optimizedKeys[i].coefficient[0] *= multiplier;
+ this.optimizedKeys[i].coefficient[1] *= multiplier;
+ this.optimizedKeys[i].coefficient[2] *= multiplier;
+ this.optimizedKeys[i].coefficient[3] *= multiplier;
+ }
+ if (this.constructUniform) {
+ this.coefUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM * 4);
+ this.timeUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM);
+ this.updateKeyUniform();
+ }
+ }
+
+ public evaluate (time: number) {
+ time = repeat(time, 1);
+ for (let i = 1; i < this.optimizedKeys.length; i++) {
+ if (time < this.optimizedKeys[i].time) {
+ return this.optimizedKeys[i - 1].evaluate(time);
+ }
+ }
+ return this.optimizedKeys[this.optimizedKeys.length - 1].evaluate(time);
+ }
+
+ // calculate first order integral coefficients of all keys
+ public integrateOnce () {
+ let i = 0;
+ if (this.integral.length + 1 < this.optimizedKeys.length) {
+ for (i = 0; i < this.optimizedKeys.length - this.integral.length - 1; i++) {
+ this.integral.push(0);
+ }
+ } else {
+ this.integral.splice(this.optimizedKeys.length - 1);
+ }
+ for (i = 0; i < this.integral.length; i++) {
+ integrateKeyframe(this.optimizedKeys[i].coefficient);
+ const deltaT = this.optimizedKeys[i + 1].time - this.optimizedKeys[i].time;
+ const prevIntegral = i === 0 ? 0 : this.integral[i - 1];
+ this.integral[i] = prevIntegral + (deltaT * evalOptCurve(deltaT, this.optimizedKeys[i].coefficient));
+ }
+ integrateKeyframe(this.optimizedKeys[this.optimizedKeys.length - 1].coefficient);
+ if (this.constructUniform) {
+ this.updateKeyUniform();
+ this.updateIntegralUniform();
+ }
+ }
+
+ // get the integral of the curve using calculated coefficients
+ public evaluateIntegral (t: number, ts: number = 1) {
+ t = repeat(t, 1);
+ for (let i = 1; i < this.optimizedKeys.length; i++) {
+ if (t < this.optimizedKeys[i].time) {
+ const prevInt = i === 1 ? 0 : this.integral[i - 2];
+ const dt = t - this.optimizedKeys[i - 1].time;
+ return ts * (prevInt + (dt * evalOptCurve(dt, this.optimizedKeys[i - 1].coefficient)));
+ }
+ }
+ const dt = t - this.optimizedKeys[this.optimizedKeys.length - 1].time;
+ return ts * (this.integral[this.integral.length - 1] + (dt * evalOptCurve(dt, this.optimizedKeys[this.optimizedKeys.length - 1].coefficient)));
+ }
+
+ // calculate second order integral coefficients of all keys
+ public integrateTwice () {
+ let i = 0;
+ if (this.integral.length + 1 < this.optimizedKeys.length) {
+ for (i = 0; i < this.optimizedKeys.length - this.integral.length - 1; i++) {
+ this.integral.push(0);
+ }
+ } else {
+ this.integral.splice(this.optimizedKeys.length - 1);
+ }
+ for (i = 0; i < this.integral.length; i++) {
+ integrateKeyframeTwice(this.optimizedKeys[i].coefficient);
+ const deltaT = this.optimizedKeys[i + 1].time - this.optimizedKeys[i].time;
+ const prevIntegral = i === 0 ? 0 : this.integral[i - 1];
+ this.integral[i] = prevIntegral + (deltaT * deltaT * evalOptCurve(deltaT, this.optimizedKeys[i].coefficient));
+ }
+ integrateKeyframeTwice(this.optimizedKeys[this.optimizedKeys.length - 1].coefficient);
+ if (this.constructUniform) {
+ this.updateKeyUniform();
+ this.updateIntegralUniform();
+ }
+ }
+
+ // get the second order integral of the curve using calculated coefficients
+ public evaluateIntegralTwice (t: number, ts: number = 1) {
+ t = repeat(t, 1);
+ for (let i = 1; i < this.optimizedKeys.length; i++) {
+ if (t < this.optimizedKeys[i].time) {
+ const prevInt = i === 1 ? 0 : this.integral[i - 2];
+ const dt = t - this.optimizedKeys[i - 1].time;
+ return ts * ts * (prevInt + (dt * dt * evalOptCurve(dt, this.optimizedKeys[i - 1].coefficient)));
+ }
+ }
+ const dt = t - this.optimizedKeys[this.optimizedKeys.length - 1].time;
+ return ts * ts * (this.integral[this.integral.length - 1] + (dt * dt * evalOptCurve(dt, this.optimizedKeys[this.optimizedKeys.length - 1].coefficient)));
+ }
+
+ public updateKeyUniform () {
+ for (let i = 0; i < this.optimizedKeys.length; i++) {
+ this.coefUniform[i * 4] = this.optimizedKeys[i].coefficient[0];
+ this.coefUniform[i * 4 + 1] = this.optimizedKeys[i].coefficient[1];
+ this.coefUniform[i * 4 + 2] = this.optimizedKeys[i].coefficient[2];
+ this.coefUniform[i * 4 + 3] = this.optimizedKeys[i].coefficient[3];
+ this.timeUniform[i] = this.optimizedKeys[i].endTime;
+ }
+ }
+
+ public updateIntegralUniform () {
+ this.integralUniform = new Float32Array(UNIFORM_CURVE_KEY_NUM - 1);
+ for (let i = 0; i < this.integral.length; i++) {
+ this.integralUniform[i] = this.integral[i];
+ }
+ }
+}
+
+export class CurveUniform {
+ private mode: number;
+ private minConstant: number;
+ private maxConstant: number;
+ private minCurve: OptimizedCurve;
+ private maxCurve: OptimizedCurve;
+
+ public constructCurve (cr: CurveRange) {
+ this.mode = cr.mode;
+ switch (cr.mode) {
+ case 'constant':
+ this.minConstant = cr.constant;
+ break;
+ case 'twoConstants':
+ this.minConstant = cr.constantMin;
+ this.maxConstant = cr.constantMax;
+ break;
+ case 'curve':
+ this.minCurve = new OptimizedCurve(true);
+ this.minCurve.buildCurve(cr.curve, cr.multiplier);
+ break;
+ case 'twoCurves':
+ this.minCurve = new OptimizedCurve(true);
+ this.minCurve.buildCurve(cr.curveMin, cr.multiplier);
+ this.maxCurve = new OptimizedCurve(true);
+ this.maxCurve.buildCurve(cr.curveMax, cr.multiplier);
+ break;
+ }
+ }
+
+ public constructCurveIntegral (cr: CurveRange) {
+ this.mode = cr.mode;
+ switch (cr.mode) {
+ case 'constant':
+ this.minConstant = cr.constant;
+ break;
+ case 'twoConstants':
+ this.minConstant = cr.constantMin;
+ this.maxConstant = cr.constantMax;
+ break;
+ case 'curve':
+ this.minCurve = new OptimizedCurve(true);
+ this.minCurve.buildCurve(cr.curve, cr.multiplier);
+ this.minCurve.integrateOnce();
+ break;
+ case 'twoCurves':
+ this.minCurve = new OptimizedCurve(true);
+ this.minCurve.buildCurve(cr.curveMin, cr.multiplier);
+ this.minCurve.integrateOnce();
+ this.maxCurve = new OptimizedCurve(true);
+ this.maxCurve.buildCurve(cr.curveMax, cr.multiplier);
+ this.maxCurve.integrateOnce();
+ break;
+ }
+ }
+
+ public constructCurveIntegralTwice (cr: CurveRange) {
+ this.mode = cr.mode;
+ switch (cr.mode) {
+ case 'constant':
+ this.minConstant = cr.constant;
+ break;
+ case 'twoConstants':
+ this.minConstant = cr.constantMin;
+ this.maxConstant = cr.constantMax;
+ break;
+ case 'curve':
+ this.minCurve = new OptimizedCurve(true);
+ this.minCurve.buildCurve(cr.curve, cr.multiplier);
+ this.minCurve.integrateTwice();
+ break;
+ case 'twoCurves':
+ this.minCurve = new OptimizedCurve(true);
+ this.minCurve.buildCurve(cr.curveMin, cr.multiplier);
+ this.minCurve.integrateTwice();
+ this.maxCurve = new OptimizedCurve(true);
+ this.maxCurve.buildCurve(cr.curveMax, cr.multiplier);
+ this.maxCurve.integrateTwice();
+ break;
+ }
+ }
+
+ public uploadUniform (device: any, name: number) {
+ switch (this.mode) {
+ case 'constant':
+ device.setUniform('u_' + name + '_curveMode', CURVE_MODE_CONSTANT);
+ device.setUniform('u_' + name + '_minConstant', this.minConstant);
+ break;
+ case 'twoConstants':
+ device.setUniform('u_' + name + '_curveMode', CURVE_MODE_RANDOM_CONSTANT);
+ device.setUniform('u_' + name + '_minConstant', this.minConstant);
+ device.setUniform('u_' + name + '_maxConstant', this.maxConstant);
+ break;
+ case 'curve':
+ device.setUniform('u_' + name + '_curveMode', CURVE_MODE_CURVE);
+ device.setUniform('u_' + name + '_minKeyTime', this.minCurve.timeUniform);
+ device.setUniform('u_' + name + '_minKeyCoef', this.minCurve.coefUniform);
+ if (this.minCurve.integralUniform !== undefined) {
+ device.setUniform('u_' + name + '_minIntegral', this.minCurve.integralUniform);
+ }
+ break;
+ case 'twoCurves':
+ device.setUniform('u_' + name + '_curveMode', CURVE_MODE_RANDOM_CURVE);
+ device.setUniform('u_' + name + '_minKeyTime', this.minCurve.timeUniform);
+ device.setUniform('u_' + name + '_minKeyCoef', this.minCurve.coefUniform);
+ if (this.minCurve.integralUniform !== undefined) {
+ device.setUniform('u_' + name + '_minIntegral', this.minCurve.integralUniform);
+ }
+ device.setUniform('u_' + name + '_maxKeyTime', this.maxCurve.timeUniform);
+ device.setUniform('u_' + name + '_maxKeyCoef', this.maxCurve.coefUniform);
+ if (this.minCurve.integralUniform !== undefined) {
+ device.setUniform('u_' + name + '_maxIntegral', this.maxCurve.integralUniform);
+ }
+ break;
+ }
+ }
+}
diff --git a/cocos/3d/framework/particle/animator/rotation-overtime.js b/cocos/3d/framework/particle/animator/rotation-overtime.ts
similarity index 65%
rename from cocos/3d/framework/particle/animator/rotation-overtime.js
rename to cocos/3d/framework/particle/animator/rotation-overtime.ts
index d015e9ceb5..29d1de795a 100644
--- a/cocos/3d/framework/particle/animator/rotation-overtime.js
+++ b/cocos/3d/framework/particle/animator/rotation-overtime.ts
@@ -2,23 +2,26 @@ import { pseudoRandom } from "../../../../core/vmath";
import { CCClass } from "../../../../core/data";
import CurveRange from "./curve-range";
import { property, ccclass } from "../../../../core/data/class-decorator";
+import Particle from "../particle";
+// tslint:disable: max-line-length
const ROTATION_OVERTIME_RAND_OFFSET = 125292;
@ccclass('cc.RotationOvertimeModule')
export default class RotationOvertimeModule {
@property
- enable = false;
+ public enable = false;
@property
- _separateAxes = false;
+ private _separateAxes = false;
- get separateAxes() {
+ @property
+ get separateAxes () {
return this._separateAxes;
}
- set separateAxes(val) {
+ set separateAxes (val) {
if (!val) {
this._separateAxes = val;
}
@@ -28,28 +31,28 @@ export default class RotationOvertimeModule {
}
@property({
- type: CurveRange
+ type: CurveRange,
})
- x = new CurveRange();
+ public x = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- y = new CurveRange();
+ public y = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- z = new CurveRange();
+ public z = new CurveRange();
- constructor() {
+ constructor () {
}
- animate(p, dt) {
- let normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
+ public animate (p: Particle, dt: number) {
+ const normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
if (!this._separateAxes) {
- p.rotation.x += this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + ROTATION_OVERTIME_RAND_OFFSET)) * dt;
+ p.rotation.x += this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + ROTATION_OVERTIME_RAND_OFFSET))! * dt;
}
else {
// TODO: separateAxes is temporarily not supported!
diff --git a/cocos/3d/framework/particle/animator/size-overtime.js b/cocos/3d/framework/particle/animator/size-overtime.ts
similarity index 69%
rename from cocos/3d/framework/particle/animator/size-overtime.js
rename to cocos/3d/framework/particle/animator/size-overtime.ts
index 63f77d09aa..d885bb5521 100644
--- a/cocos/3d/framework/particle/animator/size-overtime.js
+++ b/cocos/3d/framework/particle/animator/size-overtime.ts
@@ -2,41 +2,43 @@ import { vec3, pseudoRandom } from '../../../../core/vmath';
import CurveRange from './curve-range';
import { CCClass } from '../../../../core/data';
import { property, ccclass } from '../../../../core/data/class-decorator';
+import Particle from '../particle';
+// tslint:disable: max-line-length
const SIZE_OVERTIME_RAND_OFFSET = 39825;
@ccclass('cc.SizeOvertimeModule')
export default class SizeOvertimeModule {
@property
- enable = false;
+ public enable = false;
@property
- separateAxes = false;
+ public separateAxes = false;
@property({
- type: CurveRange
+ type: CurveRange,
})
- size = new CurveRange();
+ public size = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- x = new CurveRange();
+ public x = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- y = new CurveRange();
+ public y = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- z = new CurveRange();
+ public z = new CurveRange();
- animate(particle) {
+ public animate (particle: Particle) {
if (!this.separateAxes) {
- vec3.scale(particle.size, particle.startSize, this.size.evaluate(1 - particle.remainingLifetime / particle.startLifetime, pseudoRandom(particle.randomSeed + SIZE_OVERTIME_RAND_OFFSET)));
+ vec3.scale(particle.size, particle.startSize, this.size.evaluate(1 - particle.remainingLifetime / particle.startLifetime, pseudoRandom(particle.randomSeed + SIZE_OVERTIME_RAND_OFFSET))!);
}
}
}
diff --git a/cocos/3d/framework/particle/animator/texture-animation.js b/cocos/3d/framework/particle/animator/texture-animation.ts
similarity index 51%
rename from cocos/3d/framework/particle/animator/texture-animation.js
rename to cocos/3d/framework/particle/animator/texture-animation.ts
index 6c04f88d3b..071a112510 100644
--- a/cocos/3d/framework/particle/animator/texture-animation.js
+++ b/cocos/3d/framework/particle/animator/texture-animation.ts
@@ -3,42 +3,45 @@ import { Enum } from "../../../../core/value-types";
import CurveRange from "./curve-range";
import { CCClass } from "../../../../core/data";
import { property, ccclass } from "../../../../core/data/class-decorator";
+import ParticleSystemComponent from "../particle-system-component";
+import Particle from "../particle";
+// tslint:disable: max-line-length
const TEXTURE_ANIMATION_RAND_OFFSET = 90794;
const Mode = Enum({
Grid: 0,
- Sprites: 1
+ Sprites: 1,
});
const Animation = Enum({
WholeSheet: 0,
- SingleRow: 1
+ SingleRow: 1,
});
@ccclass('cc.TextureAnimationModule')
export default class TextureAnimationModule {
@property
- _enable = false;
+ private _enable = false;
- get enable() {
+ get enable () {
return this._enable;
}
- set enable(val) {
+ set enable (val) {
this._enable = val;
- this.ps.renderer._updateMaterialParams();
+ this.ps!.renderer!._updateMaterialParams();
}
@property
- _mode = Mode.Grid
+ private _mode = Mode.Grid;
- get mode() {
+ get mode () {
return this._mode;
}
- set mode(val) {
+ set mode (val) {
if (val === Mode.Sprites) {
console.error("particle texture animation's sprites is not supported!");
return;
@@ -46,89 +49,91 @@ export default class TextureAnimationModule {
}
@property
- numTilesX = 0;
+ public numTilesX = 0;
@property
- numTilesY = 0;
+ public numTilesY = 0;
@property
- animation = Animation.WholeSheet;
+ public animation = Animation.WholeSheet;
@property({
- type: CurveRange
+ type: CurveRange,
})
- frameOverTime = new CurveRange();
+ public frameOverTime = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- startFrame = new CurveRange();
+ public startFrame = new CurveRange();
@property
- cycleCount = 0;
+ public cycleCount = 0;
@property
- _flipU = 0;
+ private _flipU = 0;
- get flipU() {
+ get flipU () {
return this._flipU;
}
- set flipU(val) {
+ set flipU (val) {
console.error("particle texture animation's flipU is not supported!");
}
@property
- _flipV = 0;
+ private _flipV = 0;
- get flipV() {
+ get flipV () {
return this._flipV;
}
- set flipV(val) {
+ set flipV (val) {
console.error("particle texture animation's flipV is not supported!");
}
@property
- _uvChannelMask = -1
+ private _uvChannelMask = -1;
- get uvChannelMask() {
+ get uvChannelMask () {
return this._uvChannelMask;
}
- set uvChannelMask(val) {
+ set uvChannelMask (val) {
console.error("particle texture animation's uvChannelMask is not supported!");
}
@property
- randomRow = false;
+ public randomRow = false;
@property
- rowIndex = 0;
+ public rowIndex = 0;
- onInit(ps) {
+ private ps: ParticleSystemComponent | null = null;
+
+ public onInit (ps: ParticleSystemComponent) {
this.ps = ps;
}
- animate(p) {
- let normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
- let startFrame = this.startFrame.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET)) / (this.numTilesX * this.numTilesY);
- if (this.animation == Animation.WholeSheet) {
- p.frameIndex = repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET)) + startFrame), 1);
+ public animate (p: Particle) {
+ const normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
+ const startFrame = this.startFrame.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET))! / (this.numTilesX * this.numTilesY);
+ if (this.animation === Animation.WholeSheet) {
+ p.frameIndex = repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET))! + startFrame), 1);
}
- else if (this.animation == Animation.SingleRow) {
- let rowLength = 1 / this.numTilesY;
- if (this._randomRow) {
- let f = repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET)) + startFrame), 1);
- let startRow = Math.floor(Math.random() * this.numTilesY);
- let from = startRow * rowLength;
- let to = from + rowLength;
+ else if (this.animation === Animation.SingleRow) {
+ const rowLength = 1 / this.numTilesY;
+ if (this.randomRow) {
+ const f = repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET))! + startFrame), 1);
+ const startRow = Math.floor(Math.random() * this.numTilesY);
+ const from = startRow * rowLength;
+ const to = from + rowLength;
p.frameIndex = lerp(from, to, f);
}
else {
- let from = this.rowIndex * rowLength;
- let to = from + rowLength;
- p.frameIndex = lerp(from, to, repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET)) + startFrame), 1));
+ const from = this.rowIndex * rowLength;
+ const to = from + rowLength;
+ p.frameIndex = lerp(from, to, repeat(this.cycleCount * (this.frameOverTime.evaluate(normalizedTime, pseudoRandom(p.randomSeed + TEXTURE_ANIMATION_RAND_OFFSET))! + startFrame), 1));
}
}
}
diff --git a/cocos/3d/framework/particle/animator/velocity-overtime.js b/cocos/3d/framework/particle/animator/velocity-overtime.ts
similarity index 51%
rename from cocos/3d/framework/particle/animator/velocity-overtime.js
rename to cocos/3d/framework/particle/animator/velocity-overtime.ts
index 465aaecb84..90acc40c17 100644
--- a/cocos/3d/framework/particle/animator/velocity-overtime.js
+++ b/cocos/3d/framework/particle/animator/velocity-overtime.ts
@@ -1,57 +1,66 @@
-import { vec3, quat, pseudoRandom } from '../../../../core/vmath';
+import { vec3, quat, pseudoRandom, mat4 } from '../../../../core/vmath';
import { calculateTransform, Space } from '../particle-general-function';
import CurveRange from './curve-range';
import { CCClass } from '../../../../core/data';
import { property, ccclass } from '../../../../core/data/class-decorator';
+import Particle from '../particle';
+// tslint:disable: max-line-length
const VELOCITY_OVERTIME_RAND_OFFSET = 197866;
@ccclass('cc.VelocityOvertimeModule')
export default class VelocityOvertimeModule {
@property
- enable = false;
+ public enable = false;
@property({
- type: CurveRange
+ type: CurveRange,
})
- x = new CurveRange();
+ public x = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- y = new CurveRange();
+ public y = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- z = new CurveRange();
+ public z = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- speedModifier = new CurveRange();
+ public speedModifier = new CurveRange();
- @property
- space = Space.Local;
+ @property({
+ type: Space,
+ })
+ public space = Space.Local;
- constructor() {
+ private rotation: quat;
+ private needTransform: boolean;
+
+ constructor () {
this.rotation = quat.create();
+ this.speedModifier.constant = 1;
+ this.needTransform = false;
}
- update(space, worldTransform) {
+ public update (space: number, worldTransform: mat4) {
this.needTransform = calculateTransform(space, this.space, worldTransform, this.rotation);
}
- animate(p) {
- let normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
- let vel = vec3.create(this.x.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)), this.y.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)), this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)));
+ public animate (p: Particle) {
+ const normalizedTime = 1 - p.remainingLifetime / p.startLifetime;
+ const vel = vec3.create(this.x.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)), this.y.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)), this.z.evaluate(normalizedTime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)));
if (this.needTransform) {
vec3.transformQuat(vel, vel, this.rotation);
}
vec3.add(p.animatedVelocity, p.animatedVelocity, vel);
vec3.add(p.ultimateVelocity, p.velocity, p.animatedVelocity);
- vec3.scale(p.ultimateVelocity, p.ultimateVelocity, this.speedModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET)));
+ vec3.scale(p.ultimateVelocity, p.ultimateVelocity, this.speedModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, pseudoRandom(p.randomSeed + VELOCITY_OVERTIME_RAND_OFFSET))!);
}
}
diff --git a/cocos/3d/framework/particle/emitter/shape-module.js b/cocos/3d/framework/particle/emitter/shape-module.ts
similarity index 74%
rename from cocos/3d/framework/particle/emitter/shape-module.js
rename to cocos/3d/framework/particle/emitter/shape-module.ts
index 2b7877a368..031824820d 100644
--- a/cocos/3d/framework/particle/emitter/shape-module.js
+++ b/cocos/3d/framework/particle/emitter/shape-module.ts
@@ -1,12 +1,14 @@
import { randomUnitVector, particleEmitZAxis, randomSortArray, randomSign, randomPointBetweenSphere, randomPointInCube, randomPointBetweenCircleAtFixedAngle, fixedAngleUnitVector2 } from '../particle-general-function';
-import { vec3, vec2, random, randomRange, mat4, quat, clamp, repeat, pingPong } from '../../../../core/vmath';
+import { vec3, vec2, random, randomRange, mat4, quat, clamp, repeat, pingPong, toRadian, toDegree } from '../../../../core/vmath';
import { Enum, Vec3 } from '../../../../core/value-types';
import CurveRange from '../animator/curve-range';
import { CCClass } from '../../../../core/data';
import { property, ccclass } from '../../../../core/data/class-decorator';
+import ParticleSystemComponent from '../particle-system-component';
-let _intermediVec = vec3.create(0, 0, 0);
-let _intermediArr = new Array();
+// tslint:disable: max-line-length
+const _intermediVec = vec3.create(0, 0, 0);
+const _intermediArr = new Array();
const _unitBoxExtent = vec3.create(0.5, 0.5, 0.5);
const ShapeType = Enum({
@@ -14,126 +16,162 @@ const ShapeType = Enum({
Circle: 1,
Cone: 2,
Sphere: 3,
- Hemisphere: 4
+ Hemisphere: 4,
});
const EmitLocation = Enum({
Base: 0,
Edge: 1,
Shell: 2,
- Volume: 3
+ Volume: 3,
});
const ArcMode = Enum({
Random: 0,
Loop: 1,
- PingPong: 2
+ PingPong: 2,
});
@ccclass('cc.ShapeModule')
export default class ShapeModule {
@property
- enable = false;
+ public enable = false;
+
+ @property({
+ type: ShapeType,
+ })
+ public shapeType = ShapeType.Box;
+
+ @property({
+ type: EmitLocation,
+ })
+ public emitFrom = EmitLocation.Volume;
@property
- shapeType = ShapeType.Box;
+ private _position = new Vec3(0, 0, 0);
@property
- emitFrom = EmitLocation.Base;
-
- @property
- _position = new Vec3(0, 0, 0);
-
- get position() {
+ get position () {
return this._position;
}
- set position(val) {
+ set position (val) {
this._position = val;
this.constructMat();
}
@property
- _rotation = new Vec3(0, 0, 0);
+ private _rotation = new Vec3(0, 0, 0);
- get rotation() {
+ @property
+ get rotation () {
return this._rotation;
}
- set rotation(val) {
+ set rotation (val) {
this._rotation = val;
this.constructMat();
}
@property
- _scale = new Vec3(0, 0, 0);
+ private _scale = new Vec3(1, 1, 1);
- get scale() {
+ @property
+ get scale () {
return this._scale;
}
- set scale(val) {
+ set scale (val) {
this._scale = val;
this.constructMat();
}
@property
- alignToDirection = false;
+ public alignToDirection = false;
@property
- randomDirectionAmount = 0;
+ public randomDirectionAmount = 0;
@property
- sphericalDirectionAmount = 0;
+ public sphericalDirectionAmount = 0;
@property
- randomPositionAmount = 0;
+ public randomPositionAmount = 0;
@property
- radius = 0;
+ public radius = 1;
@property
- radiusThickness = 1;
+ public radiusThickness = 1;
@property
- arc = 0;
+ private _arc = toRadian(360);
@property
- arcMode = ArcMode.Random;
-
- @property
- arcSpread = 0;
-
- @property({
- type: CurveRange
- })
- arcSpeed = new CurveRange();
-
- @property
- angle = 0;
-
- @property
- length = 0;
-
- @property
- boxThickness = new Vec3(0, 0, 0);
-
- constructor() {
- this.mat = mat4.create();
- this.quat = quat.create();
+ get arc () {
+ return toDegree(this._arc);
}
- onInit(ps) {
+ set arc (val) {
+ this._arc = toRadian(val);
+ }
+
+ @property({
+ type: ArcMode,
+ })
+ public arcMode = ArcMode.Random;
+
+ @property
+ public arcSpread = 0;
+
+ @property({
+ type: CurveRange,
+ })
+ public arcSpeed = new CurveRange();
+
+ @property
+ private _angle = toRadian(25);
+
+ @property
+ get angle () {
+ return toDegree(this._angle);
+ }
+
+ set angle (val) {
+ this._angle = toRadian(val);
+ }
+
+ @property
+ public length = 0;
+
+ @property
+ public boxThickness = new Vec3(0, 0, 0);
+
+ private mat: mat4;
+ private quat: quat;
+ private particleSystem: ParticleSystemComponent | null;
+ private lastTime: number;
+ private totalAngle: number;
+
+ constructor () {
+ this.mat = mat4.create();
+ this.quat = quat.create();
+ this.particleSystem = null;
+ this.lastTime = 0;
+ this.totalAngle = 0;
+ }
+
+ public onInit (ps: ParticleSystemComponent) {
this.constructMat();
this.particleSystem = ps;
this.lastTime = ps._time;
this.totalAngle = 0;
}
- constructMat() {
+ private constructMat () {
quat.fromEuler(this.quat, this._rotation.x, this._rotation.y, this._rotation.z);
mat4.fromRTS(this.mat, this.quat, this._position, this._scale);
}
- emit(p) {
+ public emit (p) {
switch (this.shapeType) {
case ShapeType.Box:
boxEmit(this.emitFrom, this.boxThickness, p.position, p.velocity);
@@ -142,7 +180,7 @@ export default class ShapeModule {
circleEmit(this.radius, this.radiusThickness, this.generateArcAngle(), p.position, p.velocity);
break;
case ShapeType.Cone:
- coneEmit(this.emitFrom, this.radius, this.radiusThickness, this.generateArcAngle(), this.angle, this.length, p.position, p.velocity);
+ coneEmit(this.emitFrom, this.radius, this.radiusThickness, this.generateArcAngle(), this._angle, this.length, p.position, p.velocity);
break;
case ShapeType.Sphere:
sphereEmit(this.emitFrom, this.radius, this.radiusThickness, p.position, p.velocity);
@@ -161,31 +199,31 @@ export default class ShapeModule {
vec3.transformQuat(p.velocity, p.velocity, this.quat);
vec3.transformMat4(p.position, p.position, this.mat);
if (this.sphericalDirectionAmount > 0) {
- let sphericalVel = vec3.normalize(_intermediVec, p.position);
+ const sphericalVel = vec3.normalize(_intermediVec, p.position);
vec3.lerp(p.velocity, p.velocity, sphericalVel, this.sphericalDirectionAmount);
}
- this.lastTime = this.particleSystem._time;
+ this.lastTime = this.particleSystem!._time;
}
- generateArcAngle() {
+ private generateArcAngle () {
if (this.arcMode === ArcMode.Random) {
- return randomRange(0, this.arc);
+ return randomRange(0, this._arc);
}
- let angle = this.totalAngle + 2 * Math.PI * this.arcSpeed.evaluate(this.particleSystem._time) * (this.particleSystem._time - this.lastTime);
+ let angle = this.totalAngle + 2 * Math.PI * this.arcSpeed.evaluate(this.particleSystem!._time, 1)! * (this.particleSystem!._time - this.lastTime);
this.totalAngle = angle;
if (this.arcSpread !== 0) {
- angle = Math.floor(angle / (this.arc * this.arcSpread)) * this.arc * this.arcSpread;
+ angle = Math.floor(angle / (this._arc * this.arcSpread)) * this._arc * this.arcSpread;
}
switch (this.arcMode) {
case ArcMode.Loop:
- return repeat(angle, this.arc);
+ return repeat(angle, this._arc);
case ArcMode.PingPong:
- return pingPong(angle, this.arc);
+ return pingPong(angle, this._arc);
}
}
}
-function sphereEmit(emitFrom, radius, radiusThickness, pos, dir) {
+function sphereEmit (emitFrom, radius, radiusThickness, pos, dir) {
switch (emitFrom) {
case EmitLocation.Volume:
randomPointBetweenSphere(pos, radius * (1 - radiusThickness), radius);
@@ -202,7 +240,7 @@ function sphereEmit(emitFrom, radius, radiusThickness, pos, dir) {
}
}
-function hemisphereEmit(emitFrom, radius, radiusThickness, pos, dir) {
+function hemisphereEmit (emitFrom, radius, radiusThickness, pos, dir) {
switch (emitFrom) {
case EmitLocation.Volume:
randomPointBetweenSphere(pos, radius * (1 - radiusThickness), radius);
@@ -225,7 +263,7 @@ function hemisphereEmit(emitFrom, radius, radiusThickness, pos, dir) {
}
}
-function coneEmit(emitFrom, radius, radiusThickness, theta, angle, length, pos, dir) {
+function coneEmit (emitFrom, radius, radiusThickness, theta, angle, length, pos, dir) {
switch (emitFrom) {
case EmitLocation.Base:
randomPointBetweenCircleAtFixedAngle(pos, radius * (1 - radiusThickness), radius, theta);
@@ -255,7 +293,7 @@ function coneEmit(emitFrom, radius, radiusThickness, theta, angle, length, pos,
}
}
-function boxEmit(emitFrom, boxThickness, pos, dir) {
+function boxEmit (emitFrom, boxThickness, pos, dir) {
switch (emitFrom) {
case EmitLocation.Volume:
randomPointInCube(pos, _unitBoxExtent);
@@ -285,12 +323,12 @@ function boxEmit(emitFrom, boxThickness, pos, dir) {
vec3.copy(dir, particleEmitZAxis);
}
-function circleEmit(radius, radiusThickness, theta, pos, dir) {
+function circleEmit (radius, radiusThickness, theta, pos, dir) {
randomPointBetweenCircleAtFixedAngle(pos, radius * (1 - radiusThickness), radius, theta);
vec3.normalize(dir, pos);
}
-function applyBoxThickness(pos, thickness) {
+function applyBoxThickness (pos, thickness) {
if (thickness.x > 0) {
pos[0] += 0.5 * randomRange(-thickness.x, thickness.x);
pos[0] = clamp(pos[0], -0.5, 0.5);
diff --git a/cocos/3d/framework/particle/particle-general-function.js b/cocos/3d/framework/particle/particle-general-function.ts
similarity index 63%
rename from cocos/3d/framework/particle/particle-general-function.js
rename to cocos/3d/framework/particle/particle-general-function.ts
index 06076406e8..adc6ae69f9 100644
--- a/cocos/3d/framework/particle/particle-general-function.js
+++ b/cocos/3d/framework/particle/particle-general-function.ts
@@ -7,10 +7,10 @@ export const particleEmitZAxis = vec3.create(0, 0, -1);
export const Space = Enum({
World: 0,
Local: 1,
- Custom: 2
+ Custom: 2,
});
-export function calculateTransform(systemSpace, moduleSpace, worldTransform, outQuat) {
+export function calculateTransform (systemSpace, moduleSpace, worldTransform, outQuat) {
if (moduleSpace !== systemSpace) {
if (systemSpace === 'world') {
mat4.getRotation(outQuat, worldTransform);
@@ -27,67 +27,70 @@ export function calculateTransform(systemSpace, moduleSpace, worldTransform, out
}
}
-export function fixedAngleUnitVector2(out, theta) {
+export function fixedAngleUnitVector2 (out, theta) {
vec2.set(out, Math.cos(theta), Math.sin(theta));
}
-export function randomUnitVector2(out) {
- let a = randomRange(0, 2 * Math.PI);
- let x = Math.cos(a);
- let y = Math.sin(a);
+export function randomUnitVector2 (out) {
+ const a = randomRange(0, 2 * Math.PI);
+ const x = Math.cos(a);
+ const y = Math.sin(a);
vec2.set(out, x, y);
}
-export function randomUnitVector(out) {
- let z = randomRange(-1, 1);
- let a = randomRange(0, 2 * Math.PI);
- let r = Math.sqrt(1 - z * z);
- let x = r * Math.cos(a);
- let y = r * Math.sin(a);
+export function randomUnitVector (out) {
+ const z = randomRange(-1, 1);
+ const a = randomRange(0, 2 * Math.PI);
+ const r = Math.sqrt(1 - z * z);
+ const x = r * Math.cos(a);
+ const y = r * Math.sin(a);
vec3.set(out, x, y, z);
}
-export function randomPointInUnitSphere(out) {
+export function randomPointInUnitSphere (out) {
randomUnitVector(out);
vec3.scale(out, out, random());
}
-export function randomPointBetweenSphere(out, minRadius, maxRadius) {
+export function randomPointBetweenSphere (out, minRadius, maxRadius) {
randomUnitVector(out);
vec3.scale(out, out, minRadius + (maxRadius - minRadius) * random());
}
-export function randomPointInUnitCircle(out) {
+export function randomPointInUnitCircle (out) {
randomUnitVector2(out);
+ out.z = 0;
vec3.scale(out, out, random());
}
-export function randomPointBetweenCircle(out, minRadius, maxRadius) {
+export function randomPointBetweenCircle (out, minRadius, maxRadius) {
randomUnitVector2(out);
+ out.z = 0;
vec3.scale(out, out, minRadius + (maxRadius - minRadius) * random());
}
-export function randomPointBetweenCircleAtFixedAngle(out, minRadius, maxRadius, theta) {
+export function randomPointBetweenCircleAtFixedAngle (out, minRadius, maxRadius, theta) {
fixedAngleUnitVector2(out, theta);
+ out.z = 0;
vec3.scale(out, out, minRadius + (maxRadius - minRadius) * random());
}
-export function randomPointInCube(out, extents) {
+export function randomPointInCube (out, extents) {
vec3.set(out,
randomRange(-extents.x, extents.x),
randomRange(-extents.y, extents.y),
randomRange(-extents.z, extents.z));
}
-export function randomPointBetweenCube(out, minBox, maxBox) {
+export function randomPointBetweenCube (out, minBox, maxBox) {
const subscript = ['x', 'y', 'z'];
- let edge = randomRangeInt(0, 3);
+ const edge = randomRangeInt(0, 3);
for (let i = 0; i < 3; i++) {
if (i === edge) {
out[subscript[i]] = randomRange(-maxBox[subscript[i]], maxBox[subscript[i]]);
continue;
}
- let x = random() * 2 - 1;
+ const x = random() * 2 - 1;
if (x < 0) {
out[subscript[i]] = -minBox[subscript[i]] + x * (maxBox[subscript[i]] - minBox[subscript[i]]);
}
@@ -98,16 +101,16 @@ export function randomPointBetweenCube(out, minBox, maxBox) {
}
// Fisher–Yates shuffle
-export function randomSortArray(arr) {
+export function randomSortArray (arr) {
for (let i = 0; i < arr.length; i++) {
- let transpose = i + randomRangeInt(0, arr.length - i);
- let val = arr[transpose];
+ const transpose = i + randomRangeInt(0, arr.length - i);
+ const val = arr[transpose];
arr[transpose] = arr[i];
arr[i] = val;
}
}
-export function randomSign() {
+export function randomSign () {
let sgn = randomRange(-1, 1);
sgn === 0 ? sgn++ : sgn;
return sign(sgn);
diff --git a/cocos/3d/framework/particle/particle-system-component.js b/cocos/3d/framework/particle/particle-system-component.ts
similarity index 57%
rename from cocos/3d/framework/particle/particle-system-component.js
rename to cocos/3d/framework/particle/particle-system-component.ts
index 91e3799e19..b4092697d7 100644
--- a/cocos/3d/framework/particle/particle-system-component.js
+++ b/cocos/3d/framework/particle/particle-system-component.ts
@@ -1,6 +1,6 @@
// Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-import Component from '../../../components/CCComponent';
+import { Component } from '../../../components/component';
import { vec3, vec2, mat4, quat, randomRangeInt, pseudoRandom } from '../../../core/vmath';
import CurveRange from './animator/curve-range';
import GradientRange from './animator/gradient-range';
@@ -18,7 +18,7 @@ import { particleEmitZAxis, Space } from './particle-general-function';
import { INT_MAX } from '../../../core/vmath/bits';
import { ccclass, executionOrder, executeInEditMode, property, requireComponent, menu } from '../../../core/data/class-decorator';
-let _world_mat = mat4.create();
+const _world_mat = mat4.create();
@ccclass('cc.ParticleSystemComponent')
@menu('Components/ParticleSystemComponent')
@@ -28,157 +28,172 @@ let _world_mat = mat4.create();
export default class ParticleSystemComponent extends Component {
@property
- capacity = 2000;
+ public capacity = 2000;
@property({
- type:GradientRange
+ type: GradientRange,
})
- startColor = new GradientRange();
+ public startColor = new GradientRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- startSize = new CurveRange();
+ public startSize = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- startSpeed = new CurveRange();
+ public startSpeed = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- startRotation = new CurveRange();
+ public startRotation = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- startDelay = new CurveRange();
+ public startDelay = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- startLifetime = new CurveRange();
+ public startLifetime = new CurveRange();
@property
- duration = 5.0;
+ public duration = 5.0;
@property
- loop = true;
+ public loop = true;
@property
- _prewarm = false;
+ private _prewarm = false;
@property
- get prewarm() {
+ get prewarm () {
return this._prewarm;
}
- set prewarm(val) {
- if (val === true && this._loop === false) {
+ set prewarm (val) {
+ if (val === true && this.loop === false) {
// console.warn('prewarm only works if loop is also enabled.');
}
this._prewarm = val;
}
@property
- _simulationSpace = Space.Local;
+ private _simulationSpace = Space.Local;
@property({
- type: Space
+ type: Space,
})
- get simulationSpace() {
+ get simulationSpace () {
return this._simulationSpace;
}
- set simulationSpace(val) {
- if (val === Space.World) {
- this._renderer._material.define('USE_WORLD_SPACE', true);
- } else {
- this._renderer._material.define('USE_WORLD_SPACE', false);
+ set simulationSpace (val) {
+ if (val !== this._simulationSpace) {
+ this._simulationSpace = val;
+ this.renderer!._updateMaterialParams();
}
- this._simulationSpace = val;
}
@property
- simulationSpeed = 1.0;
+ public simulationSpeed = 1.0;
@property
- playOnAwake = false;
+ public playOnAwake = true;
@property({
- type: CurveRange
+ type: CurveRange,
})
- gravityModifier = new CurveRange();
+ public gravityModifier = new CurveRange();
// emission module
@property({
- type: CurveRange
+ type: CurveRange,
})
- rateOverTime = new CurveRange();
+ public rateOverTime = new CurveRange();
@property({
- type: CurveRange
+ type: CurveRange,
})
- rateOverDistance = new CurveRange();
+ public rateOverDistance = new CurveRange();
@property({
- type: [Burst]
+ type: [Burst],
})
- bursts = new Array();
+ public bursts = new Array();
// color over lifetime module
@property({
- type: ColorOverLifetimeModule
+ type: ColorOverLifetimeModule,
})
- colorOverLifetimeModule = new ColorOverLifetimeModule();
+ public colorOverLifetimeModule = new ColorOverLifetimeModule();
// shpae module
@property({
- type: ShapeModule
+ type: ShapeModule,
})
- shapeModule = new ShapeModule();
-
- // particle system renderer
- @property({
- type: ParticleSystemRenderer
- })
- renderer = null;
+ public shapeModule = new ShapeModule();
// size over lifetime module
@property({
- type: SizeOvertimeModule
+ type: SizeOvertimeModule,
})
- sizeOvertimeModule = new SizeOvertimeModule();
+ public sizeOvertimeModule = new SizeOvertimeModule();
@property({
- type: VelocityOvertimeModule
+ type: VelocityOvertimeModule,
})
- velocityOvertimeModule = new VelocityOvertimeModule();
+ public velocityOvertimeModule = new VelocityOvertimeModule();
@property({
- type: ForceOvertimeModule
+ type: ForceOvertimeModule,
})
- forceOvertimeModule = new ForceOvertimeModule();
+ public forceOvertimeModule = new ForceOvertimeModule();
@property({
- type: LimitVelocityOvertimeModule
+ type: LimitVelocityOvertimeModule,
})
- limitVelocityOvertimeModule = new LimitVelocityOvertimeModule();
+ public limitVelocityOvertimeModule = new LimitVelocityOvertimeModule();
@property({
- type: RotationOvertimeModule
+ type: RotationOvertimeModule,
})
- rotationOvertimeModule = new RotationOvertimeModule();
+ public rotationOvertimeModule = new RotationOvertimeModule();
@property({
- type: TextureAnimationModule
+ type: TextureAnimationModule,
})
- textureAnimationModule = new TextureAnimationModule();
+ public textureAnimationModule = new TextureAnimationModule();
- constructor() {
+ // particle system renderer
+ private renderer: ParticleSystemRenderer | null;
+ private _isPlaying: boolean;
+ private _isPaused: boolean;
+ private _isStopped: boolean;
+ private _isEmitting: boolean;
+
+ private _time: number; // playback position in seconds.
+ private _emitRateTimeCounter: number;
+ private _emitRateDistanceCounter: number;
+ private _oldWPos: vec3;
+ private _curWPos: vec3;
+
+ private _customData1: vec2;
+ private _customData2: vec2;
+
+ private _subEmitters: any[]; // array of { emitter: ParticleSystemComponent, type: 'birth', 'collision' or 'death'}
+
+ constructor () {
super();
+ this.rateOverTime.constant = 10;
+ this.startLifetime.constant = 5;
+ this.startSize.constant = 1;
+ this.startSpeed.constant = 1;
+
// internal status
this._isPlaying = false;
this._isPaused = false;
@@ -195,9 +210,10 @@ export default class ParticleSystemComponent extends Component {
this._customData2 = vec2.create(0, 0);
this._subEmitters = []; // array of { emitter: ParticleSystemComponent, type: 'birth', 'collision' or 'death'}
+ this.renderer = null;
}
- onLoad() {
+ private onLoad () {
// HACK, TODO
this.renderer = this.getComponent(ParticleSystemRenderer);
this.renderer.onInit();
@@ -210,17 +226,17 @@ export default class ParticleSystemComponent extends Component {
// this._system.add(this);
}
- onDestroy() {
+ private onDestroy () {
// this._system.remove(this);
}
- onEnable() {
- if (this._playOnAwake) {
+ private onEnable () {
+ if (this.playOnAwake) {
this.play();
}
}
- onDisable() {
+ private onDisable () {
}
@@ -229,7 +245,7 @@ export default class ParticleSystemComponent extends Component {
// }
- play() {
+ public play () {
if (this._isPaused) {
this._isPaused = false;
}
@@ -249,7 +265,7 @@ export default class ParticleSystemComponent extends Component {
}
}
- pause() {
+ public pause () {
if (this._isStopped) {
console.warn('pause(): particle system is already stopped.');
return;
@@ -261,7 +277,7 @@ export default class ParticleSystemComponent extends Component {
this._isPaused = true;
}
- stop() {
+ public stop () {
if (this._isPlaying) {
this._isPlaying = false;
}
@@ -278,21 +294,21 @@ export default class ParticleSystemComponent extends Component {
}
// remove all particles from current particle system.
- clear() {
- this._particles.reset();
- this._renderer._model.clear();
+ public clear () {
+ this.renderer!.clear();
}
- emit(count, emitParams = null) {
+ private emit (count, emitParams = null) {
if (emitParams !== null) {
// TODO:
}
for (let i = 0; i < count; ++i) {
- let particle = this.renderer._getFreeParticle();
- if (particle === null)
+ const particle = this.renderer!._getFreeParticle();
+ if (particle === null) {
return;
- let rand = pseudoRandom(randomRangeInt(0, INT_MAX));
+ }
+ const rand = pseudoRandom(randomRangeInt(0, INT_MAX));
if (this.shapeModule.enable) {
this.shapeModule.emit(particle);
@@ -307,13 +323,12 @@ export default class ParticleSystemComponent extends Component {
switch (this._simulationSpace) {
case Space.Local:
break;
- case Space.World: {
+ case Space.World:
this.node.getWorldMatrix(_world_mat);
vec3.transformMat4(particle.position, particle.position, _world_mat);
- let worldRot = quat.create();
+ const worldRot = quat.create();
this.node.getWorldRotation(worldRot);
vec3.transformQuat(particle.velocity, particle.velocity, worldRot);
- }
break;
case Space.Custom:
// TODO:
@@ -337,88 +352,28 @@ export default class ParticleSystemComponent extends Component {
particle.randomSeed = randomRangeInt(0, 233280);
- this.renderer._setNewParticle(particle);
+ this.renderer!._setNewParticle(particle);
} // end of particles forLoop.
}
- // simulation, update particles.
- _updateParticles(dt) {
- this._entity.getWorldMatrix(_world_mat);
- if (this._velocityOvertimeModule.enable) {
- this._velocityOvertimeModule.update(this._simulationSpace, _world_mat);
- }
- if (this._forceOvertimeModule.enable) {
- this._forceOvertimeModule.update(this._simulationSpace, _world_mat);
- }
- for (let i = 0; i < this._particles.length; ++i) {
- let p = this._particles.data[i];
- p.remainingLifetime -= dt;
- vec3.set(p.animatedVelocity, 0, 0, 0);
-
- if (p.remainingLifetime < 0.0) {
- // subEmitter
- // if (this._subEmitters.length > 0) {
- // for (let idx = 0; idx < this._subEmitters.length; ++idx) {
- // let subEmitter = this._subEmitters[idx];
- // if (subEmitter.type === 'death') {
- // vec3.copy(subEmitter.emitter.entity.lpos, p.position);
- // subEmitter.emitter.play();
- // }
- // }
- // }
-
- this._particles.remove(i);
- --i;
- continue;
- }
-
- p.velocity.y -= this._gravityModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, p.randomSeed) * 9.8 * dt; // apply gravity.
- if (this._sizeOvertimeModule.enable) {
- this._sizeOvertimeModule.animate(p);
- }
- if (this._colorOverLifetimeModule.enable) {
- this._colorOverLifetimeModule.animate(p);
- }
- if (this._forceOvertimeModule.enable) {
- this._forceOvertimeModule.animate(p, dt);
- }
- if (this._velocityOvertimeModule.enable) {
- this._velocityOvertimeModule.animate(p);
- }
- else {
- vec3.copy(p.ultimateVelocity, p.velocity);
- }
- if (this._limitVelocityOvertimeModule.enable) {
- this._limitVelocityOvertimeModule.animate(p);
- }
- if (this._rotationOvertimeModule.enable) {
- this._rotationOvertimeModule.animate(p, dt);
- }
- if (this._textureAnimationModule.enable) {
- this._textureAnimationModule.animate(p);
- }
- vec3.scaleAndAdd(p.position, p.position, p.ultimateVelocity, dt); // apply velocity.
- }
- }
-
// initialize particle system as though it had already completed a full cycle.
- _prewarmSystem() {
- this._startDelay.mode = 'constant'; // clear startDelay.
- this._startDelay.constant = 0;
- let dt = 1.0; // should use varying value?
- let cnt = this.duration / dt;
+ private _prewarmSystem () {
+ this.startDelay.mode = 'constant'; // clear startDelay.
+ this.startDelay.constant = 0;
+ const dt = 1.0; // should use varying value?
+ const cnt = this.duration / dt;
for (let i = 0; i < cnt; ++i) {
this._time += dt;
this._emit(dt);
- this._renderer._updateParticles(dt);
+ this.renderer!._updateParticles(dt);
}
}
// internal function
- _emit(dt) {
+ private _emit (dt) {
// emit particles.
- let startDelay = this.startDelay.evaluate();
+ const startDelay = this.startDelay.evaluate();
if (this._time > startDelay) {
if (!this._isStopped) {
this._isEmitting = true;
@@ -436,30 +391,30 @@ export default class ParticleSystemComponent extends Component {
// emit by rateOverTime
this._emitRateTimeCounter += this.rateOverTime.evaluate(this._time / this.duration, 1) * dt;
if (this._emitRateTimeCounter > 1 && this._isEmitting) {
- let emitNum = Math.floor(this._emitRateTimeCounter);
+ const emitNum = Math.floor(this._emitRateTimeCounter);
this._emitRateTimeCounter -= emitNum;
this.emit(emitNum);
}
// emit by rateOverDistance
this.node.getWorldPosition(this._curWPos);
- let distance = vec3.distance(this._curWPos, this._oldWPos);
+ const distance = vec3.distance(this._curWPos, this._oldWPos);
vec3.copy(this._oldWPos, this._curWPos);
this._emitRateDistanceCounter += distance * this.rateOverDistance.evaluate(this._time / this.duration, 1);
if (this._emitRateDistanceCounter > 1 && this._isEmitting) {
- let emitNum = Math.floor(this._emitRateDistanceCounter);
+ const emitNum = Math.floor(this._emitRateDistanceCounter);
this._emitRateDistanceCounter -= emitNum;
this.emit(emitNum);
}
// bursts
- for (let i = 0; i < this.bursts.length; ++i) {
- this.bursts[i].update(this, dt);
+ for (const burst of this.bursts) {
+ burst.update(this, dt);
}
}
}
- update(dt) {
- let scaledDeltaTime = dt * this.simulationSpeed;
+ private update (dt) {
+ const scaledDeltaTime = dt * this.simulationSpeed;
if (this._isPlaying) {
this._time += scaledDeltaTime;
@@ -467,58 +422,58 @@ export default class ParticleSystemComponent extends Component {
this._emit(scaledDeltaTime);
// simulation, update particles.
- this.renderer._updateParticles(scaledDeltaTime);
+ this.renderer!._updateParticles(scaledDeltaTime);
// update render data
- this.renderer._updateRenderData();
+ this.renderer!._updateRenderData();
}
}
- addSubEmitter(subEmitter) {
+ private addSubEmitter (subEmitter) {
this._subEmitters.push(subEmitter);
}
- removeSubEmitter(idx) {
- this._subEmitters.remove(idx);
+ private removeSubEmitter (idx) {
+ this._subEmitters.splice(this._subEmitters.indexOf(idx), 1);
}
- addBurst(burst) {
- this._bursts.push(burst);
+ private addBurst (burst) {
+ this.bursts.push(burst);
}
- removeBurst(idx) {
- this._bursts.remove(idx);
+ private removeBurst (idx) {
+ this.bursts.splice(this.bursts.indexOf(idx), 1);
}
- getParticleCount() {
- return this._particles.length;
+ public getParticleCount () {
+ return this.renderer!.getParticleCount();
}
- setCustomData1(x, y) {
+ public setCustomData1 (x, y) {
vec2.set(this._customData1, x, y);
}
- setCustomData2(x, y) {
+ public setCustomData2 (x, y) {
vec2.set(this._customData2, x, y);
}
- get isPlaying() {
+ get isPlaying () {
return this._isPlaying;
}
- get isPaused() {
+ get isPaused () {
return this._isPaused;
}
- get isStopped() {
+ get isStopped () {
return this._isStopped;
}
- get isEmitting() {
+ get isEmitting () {
return this._isEmitting;
}
- get time() {
+ get time () {
return this._time;
}
}
diff --git a/cocos/3d/framework/particle/particle.js b/cocos/3d/framework/particle/particle.ts
similarity index 53%
rename from cocos/3d/framework/particle/particle.js
rename to cocos/3d/framework/particle/particle.ts
index 82228dc683..291ee35ea9 100644
--- a/cocos/3d/framework/particle/particle.js
+++ b/cocos/3d/framework/particle/particle.ts
@@ -1,7 +1,29 @@
import { vec3, color4 } from '../../../core/vmath';
+import { Color } from '../../../core/value-types';
+import ParticleSystemComponent from './particle-system-component';
export default class Particle {
- constructor(particleSystem) {
+ public particleSystem: ParticleSystemComponent;
+ public position: vec3;
+ public velocity: vec3;
+ public animatedVelocity: vec3;
+ public ultimateVelocity: vec3;
+ public angularVelocity: vec3;
+ public axisOfRotation: vec3;
+ public rotation: vec3;
+ public startSize: vec3;
+ public size: vec3;
+ public startColor: Color;
+ public startColor01: color4;
+ public color = cc.Color.WHITE;
+ public randomSeed: number; // uint
+ public remainingLifetime: number;
+ public startLifetime: number;
+ public emitAccumulator0: number;
+ public emitAccumulator1: number;
+ public frameIndex: number;
+
+ constructor (particleSystem: any) {
this.particleSystem = particleSystem;
this.position = vec3.create(0, 0, 0);
this.velocity = vec3.create(0, 0, 0);
diff --git a/cocos/3d/framework/particle/renderer/particle-system-gpu-renderer.js b/cocos/3d/framework/particle/renderer/particle-system-gpu-renderer.js
index ad4cbe5525..e67a3cebea 100644
--- a/cocos/3d/framework/particle/renderer/particle-system-gpu-renderer.js
+++ b/cocos/3d/framework/particle/renderer/particle-system-gpu-renderer.js
@@ -1,5 +1,5 @@
import ParticleSystemRenderer from "./particle-system-renderer";
-import Material from "../../../assets/material";
+import { Material } from "../../../assets/material";
import Particle from "../particle";
import gfx from "../../../../renderer/gfx";
import { CurveUniform } from "../animator/optimized-curve";
diff --git a/cocos/3d/framework/particle/renderer/particle-system-renderer.js b/cocos/3d/framework/particle/renderer/particle-system-renderer.js
deleted file mode 100644
index d4ee9e6787..0000000000
--- a/cocos/3d/framework/particle/renderer/particle-system-renderer.js
+++ /dev/null
@@ -1,296 +0,0 @@
-import { renderer } from '../../../../renderer';
-import { vec3, vec4, vec2, mat4 } from '../../../../core/vmath';
-import gfx from '../../../../renderer/gfx';
-import Material from '../../../assets/material';
-import { RecyclePool } from '../../../memop';
-import Particle from '../particle';
-import RenderableComponent from '../../renderable-component';
-import { Enum } from '../../../../core/value-types';
-import { property, ccclass, executeInEditMode } from '../../../../core/data/class-decorator';
-import { Space } from '../particle-general-function';
-
-let _tempAttribUV = vec3.create();
-let _tempAttribUV0 = vec2.create();
-let _tempAttribColor = vec4.create();
-let _tempWorldTrans = mat4.create();
-
-let _uvs = [
- 0, 0, // bottom-left
- 1, 0, // bottom-right
- 0, 1, // top-left
- 1, 1 // top-right
-];
-
-const RenderMode = Enum({
- Billboard: 0,
- StrecthedBillboard: 1,
- HorizontalBillboard: 2,
- VerticalBillboard: 3,
- Mesh: 4
-});
-
-@ccclass('cc.ParticleSystemRenderer')
-@executeInEditMode
-export default class ParticleSystemRenderer extends RenderableComponent {
-
- @property({
- type: RenderMode
- })
- _renderMode = RenderMode.Billboard;
-
- @property({
- type: RenderMode
- })
- get renderMode() {
- return this._renderMode;
- }
-
- set renderMode(val) {
- if (this._renderMode === val) {
- return;
- }
- this._renderMode = val;
- this._updateMaterialParams();
- this._updateModel();
- }
-
- @property
- _velocityScale = 1;
-
- @property
- get velocityScale() {
- return this._velocityScale;
- }
-
- set velocityScale(val) {
- this._velocityScale = val;
- this._updateMaterialParams();
- this._updateModel();
- }
-
- @property
- _lengthScale = 1;
-
- @property
- get lengthScale() {
- return this._lengthScale;
- }
-
- set lengthScale(val) {
- this._lengthScale = val;
- this._updateMaterialParams();
- this._updateModel();
- }
-
- constructor() {
- super();
- this._model = null;
-
- this.frameTile = cc.v2(1, 1);
- this.attrs = new Array(5);
-
- this.device = cc.game._renderContext;
- }
-
- onInit() {
- this._vertAttrs = [
- { name: gfx.ATTR_POSITION, type: gfx.ATTR_TYPE_FLOAT32, num: 3, index: gfx.ATTR_INDEX_POSITION },
- { name: gfx.ATTR_UV, type: gfx.ATTR_TYPE_FLOAT32, num: 3, index: gfx.ATTR_INDEX_UV },
- { name: gfx.ATTR_UV0, type: gfx.ATTR_TYPE_FLOAT32, num: 2, index: gfx.ATTR_INDEX_UV0 },
- { name: gfx.ATTR_COLOR, type: gfx.ATTR_TYPE_UINT8, num: 4, index: gfx.ATTR_INDEX_COLOR, normalize: true }
- ];
- this.particleSystem = this.node.getComponent('cc.ParticleSystemComponent');
- this._particles = new RecyclePool(() => {
- return new Particle(this);
- }, this.particleSystem.capacity);
- if (this.sharedMaterial == null) {
- this.material = new Material();
- this.sharedMaterial.effectAsset = cc.EffectAsset.get('builtin-effect-particle-add');
- }
- this._updateMaterialParams();
- this._updateModel();
- this.onEnable();
- }
-
- onEnable() {
- if (this._model != null)
- this._scene.addModel(this._model);
- }
-
- onDisable() {
- this._scene.removeModel(this._model);
- }
-
- onDestroy() {
- this._model.destroy();
- }
-
- _updateMaterialParams() {
- if (!this.particleSystem) {
- return;
- }
- if (this.particleSystem._simulationSpace === Space.World) {
- this.sharedMaterial.define('USE_WORLD_SPACE', true);
- } else {
- this.sharedMaterial.define('USE_WORLD_SPACE', false);
- }
-
- if (this._renderMode === RenderMode.Billboard) {
- this.sharedMaterial.define('USE_BILLBOARD', true);
- this.sharedMaterial.define('USE_STRETCHED_BILLBOARD', false);
- this.sharedMaterial.define('USE_HORIZONTAL_BILLBOARD', false);
- this.sharedMaterial.define('USE_VERTICAL_BILLBOARD', false);
- } else if (this._renderMode === RenderMode.StrecthedBillboard) {
- this.sharedMaterial.define('USE_BILLBOARD', false);
- this.sharedMaterial.define('USE_STRETCHED_BILLBOARD', true);
- this.sharedMaterial.define('USE_HORIZONTAL_BILLBOARD', false);
- this.sharedMaterial.define('USE_VERTICAL_BILLBOARD', false);
- this.sharedMaterial.setProperty('velocityScale', this._velocityScale);
- this.sharedMaterial.setProperty('lengthScale', this._lengthScale);
- } else if (this._renderMode === RenderMode.HorizontalBillboard) {
- this.sharedMaterial.define('USE_BILLBOARD', false);
- this.sharedMaterial.define('USE_STRETCHED_BILLBOARD', false);
- this.sharedMaterial.define('USE_HORIZONTAL_BILLBOARD', true);
- this.sharedMaterial.define('USE_VERTICAL_BILLBOARD', false);
- } else if (this._renderMode === RenderMode.VerticalBillboard) {
- this.sharedMaterial.define('USE_BILLBOARD', false);
- this.sharedMaterial.define('USE_STRETCHED_BILLBOARD', false);
- this.sharedMaterial.define('USE_HORIZONTAL_BILLBOARD', false);
- this.sharedMaterial.define('USE_VERTICAL_BILLBOARD', true);
- } else {
- console.warn(`particle system renderMode ${this._renderMode} not support.`);
- }
-
- if (this.particleSystem.textureAnimationModule.enable) {
- this.sharedMaterial.setProperty('frameTile', vec2.set(this.frameTile, this.particleSystem.textureAnimationModule.numTilesX, this.particleSystem.textureAnimationModule.numTilesY));
- }
- else {
- this.sharedMaterial.setProperty('frameTile', this.frameTile);
- }
- }
-
- _updateModel() {
- if (!this.particleSystem) {
- return;
- }
- if (this._model === null) {
- this._model = new renderer.ParticleBatchModel(this.device, this.particleSystem.capacity, this._vertAttrs);
- this._model.setParticleRenderer(this);
- this._model.setNode(this.node);
- }
- this._model.setEffect(this.sharedMaterial ? this.sharedMaterial.effect : null);
- if (Object.getPrototypeOf(this).constructor.name === 'ParticleSystemGpuRenderer')
- return;
- if (this._renderMode === RenderMode.StrecthedBillboard) {
- this._model.enableStretchedBillboard();
- } else {
- this._model.disableStretchedBillboard();
- }
- }
-
- _getFreeParticle() {
- if (this._particles.length >= this.particleSystem._capacity)
- return null;
- return this._particles.add();
- }
-
- _setNewParticle(p) {
-
- }
-
- _updateParticles(dt) {
- this.node.getWorldMatrix(_tempWorldTrans);
- if (this.particleSystem.velocityOvertimeModule.enable) {
- this.particleSystem.velocityOvertimeModule.update(this.particleSystem._simulationSpace, _tempWorldTrans);
- }
- if (this.particleSystem.forceOvertimeModule.enable) {
- this.particleSystem.forceOvertimeModule.update(this.particleSystem._simulationSpace, _tempWorldTrans);
- }
- for (let i = 0; i < this._particles.length; ++i) {
- let p = this._particles.data[i];
- p.remainingLifetime -= dt;
- vec3.set(p.animatedVelocity, 0, 0, 0);
-
- if (p.remainingLifetime < 0.0) {
- this._particles.remove(i);
- --i;
- continue;
- }
-
- p.velocity.y -= this.particleSystem.gravityModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, p.randomSeed) * 9.8 * dt; // apply gravity.
- if (this.particleSystem.sizeOvertimeModule.enable) {
- this.particleSystem.sizeOvertimeModule.animate(p);
- }
- if (this.particleSystem.colorOverLifetimeModule.enable) {
- this.particleSystem.colorOverLifetimeModule.animate(p);
- }
- if (this.particleSystem.forceOvertimeModule.enable) {
- this.particleSystem.forceOvertimeModule.animate(p, dt);
- }
- if (this.particleSystem.velocityOvertimeModule.enable) {
- this.particleSystem.velocityOvertimeModule.animate(p);
- }
- else {
- vec3.copy(p.ultimateVelocity, p.velocity);
- }
- if (this.particleSystem.limitVelocityOvertimeModule.enable) {
- this.particleSystem.limitVelocityOvertimeModule.animate(p);
- }
- if (this.particleSystem.rotationOvertimeModule.enable) {
- this.particleSystem.rotationOvertimeModule.animate(p, dt);
- }
- if (this.particleSystem.textureAnimationModule.enable) {
- this.particleSystem.textureAnimationModule.animate(p);
- }
- vec3.scaleAndAdd(p.position, p.position, p.ultimateVelocity, dt); // apply velocity.
- }
- }
-
- // internal function
- _updateRenderData() {
- // update vertex buffer
- let idx = 0;
- let uploadVel = this._renderMode == RenderMode.StrecthedBillboard;
- for (let i = 0; i < this._particles.length; ++i) {
- let p = this._particles.data[i];
- let fi = 0;
- if (this.particleSystem.textureAnimationModule.enable) {
- fi = p.frameIndex;
- }
- idx = i * 4;
- let attrNum = 0;
- for (let j = 0; j < 4; ++j) { // four verts per particle.
- attrNum = 0;
- this.attrs[attrNum++] = p.position;
- _tempAttribUV.x = _uvs[2 * j];
- _tempAttribUV.y = _uvs[2 * j + 1];
- _tempAttribUV.z = fi;
- this.attrs[attrNum++] = _tempAttribUV;
- _tempAttribUV0.x = p.size.x;
- _tempAttribUV0.y = p.rotation.x;
- this.attrs[attrNum++] = _tempAttribUV0;
- this.attrs[attrNum++] = p.color._val;
-
- if (uploadVel) {
- this.attrs[attrNum++] = p.ultimateVelocity;
- }
-
- this._model.addParticleVertexData(idx++, this.attrs);
- }
- }
-
- // because we use index buffer, per particle index count = 6.
- this._model.updateIA(this._particles.length * 6);
- }
-
- updateShaderUniform() {
-
- }
-
- _onMaterialModified(index, material) {
- this._updateMaterialParams();
- this._updateModel();
- }
-}
-
-Object.assign(ParticleSystemRenderer, { uv: _uvs });
diff --git a/cocos/3d/framework/particle/renderer/particle-system-renderer.ts b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts
new file mode 100644
index 0000000000..af4d8caf62
--- /dev/null
+++ b/cocos/3d/framework/particle/renderer/particle-system-renderer.ts
@@ -0,0 +1,339 @@
+import { ccclass, executeInEditMode, property } from '../../../../core/data/class-decorator';
+import { Enum, Vec2 } from '../../../../core/value-types';
+import { mat4, vec2, vec3, vec4 } from '../../../../core/vmath';
+import { GFXAttributeName, GFXFormat } from '../../../../gfx/define';
+import { IGFXInputAttribute } from '../../../../gfx/input-assembler';
+import * as renderer from '../../../../renderer';
+import gfx from '../../../../renderer/gfx';
+import ParticleBatchModel from '../../../../renderer/models/particle-batch-model';
+import { Material } from '../../../assets/material';
+import RecyclePool from '../../../memop/recycle-pool';
+import Particle from '../particle';
+import { RenderableComponent } from '../../renderable-component';
+import { Space } from '../particle-general-function';
+// import ParticleSystemComponent from '../particle-system-component';
+
+const _tempAttribUV: vec3 = vec3.create();
+const _tempAttribUV0: vec2 = vec2.create();
+const _tempAttribColor: vec4 = vec4.create();
+const _tempWorldTrans: mat4 = mat4.create();
+
+const _uvs = [
+ 0, 0, // bottom-left
+ 1, 0, // bottom-right
+ 0, 1, // top-left
+ 1, 1, // top-right
+];
+
+const RenderMode = Enum({
+ Billboard: 0,
+ StrecthedBillboard: 1,
+ HorizontalBillboard: 2,
+ VerticalBillboard: 3,
+ Mesh: 4,
+});
+
+const USE_WORLD_SPACE = 'USE_WORLD_SPACE';
+const USE_BILLBOARD = 'USE_BILLBOARD';
+const USE_STRETCHED_BILLBOARD = 'USE_STRETCHED_BILLBOARD';
+const USE_HORIZONTAL_BILLBOARD = 'USE_HORIZONTAL_BILLBOARD';
+const USE_VERTICAL_BILLBOARD = 'USE_VERTICAL_BILLBOARD';
+
+@ccclass('cc.ParticleSystemRenderer')
+@executeInEditMode
+export default class ParticleSystemRenderer extends RenderableComponent {
+
+ @property({
+ type: RenderMode,
+ })
+ public get renderMode () {
+ return this._renderMode;
+ }
+
+ public set renderMode (val) {
+ if (this._renderMode === val) {
+ return;
+ }
+ this._renderMode = val;
+ this._updateMaterialParams();
+ this._updateModel();
+ }
+
+ @property
+ public get velocityScale () {
+ return this._velocityScale;
+ }
+
+ public set velocityScale (val) {
+ this._velocityScale = val;
+ this._updateMaterialParams();
+ this._updateModel();
+ }
+
+ @property
+ public get lengthScale () {
+ return this._lengthScale;
+ }
+
+ public set lengthScale (val) {
+ this._lengthScale = val;
+ this._updateMaterialParams();
+ this._updateModel();
+ }
+
+ @property({
+ type: RenderMode,
+ })
+ private _renderMode = RenderMode.Billboard;
+
+ @property
+ private _velocityScale = 1;
+
+ @property
+ private _lengthScale = 1;
+
+ private _defines: { [index: string]: boolean };
+ private _model: ParticleBatchModel | null;
+ private frameTile: Vec2;
+ private attrs: any[];
+ private _vertAttrs: IGFXInputAttribute[];
+ private particleSystem: any;
+ private _particles: RecyclePool;
+
+ constructor () {
+ super();
+ this._model = null;
+
+ this.frameTile = cc.v2(1, 1);
+ this.attrs = new Array(5);
+ this._vertAttrs = [
+ { name: GFXAttributeName.ATTR_POSITION, format: GFXFormat.RGB32F },
+ { name: GFXAttributeName.ATTR_TEX_COORD, format: GFXFormat.RGB32F },
+ { name: GFXAttributeName.ATTR_TEX_COORD1, format: GFXFormat.RG32F },
+ { name: GFXAttributeName.ATTR_COLOR, format: GFXFormat.RGBA8, isNormalized: true },
+ ];
+ this._defines = {
+ USE_WORLD_SPACE: true,
+ USE_BILLBOARD: true,
+ USE_STRETCHED_BILLBOARD: false,
+ USE_HORIZONTAL_BILLBOARD: false,
+ USE_VERTICAL_BILLBOARD: false,
+ };
+ }
+
+ public onInit () {
+ this.particleSystem = this.node.getComponent('cc.ParticleSystemComponent');
+ this._particles = new RecyclePool(() => {
+ return new Particle(this);
+ }, 16);
+ if (this.sharedMaterial == null) {
+ this.setMaterial(new Material(), 0, false);
+ this.sharedMaterial!._owner = this;
+ this.sharedMaterial!.effectName = 'builtin-effect-particle-add';
+ }
+ this.onEnable();
+ this._updateMaterialParams();
+ this._updateModel();
+ }
+
+ public onEnable () {
+ if (!this.particleSystem) {
+ return;
+ }
+ if (this._model == null) {
+ this._model = this._getRenderScene().createModel(ParticleBatchModel, this.node) as ParticleBatchModel;
+ this._model.setCapacity(this.particleSystem.capacity);
+ this._model.setVertexAttributes(this._vertAttrs);
+ this._model.node = this.node;
+ this._model.enabled = this.enabledInHierarchy;
+ }
+ }
+
+ public onDisable () {
+ this._getRenderScene().destroyModel(this._model!);
+ }
+
+ public onDestroy () {
+ this._model!.destroy();
+ }
+
+ private clear () {
+ this._particles.reset();
+ this._model!.destroy();
+ }
+
+ public _getFreeParticle (): Particle | null {
+ if (this._particles.length >= this.particleSystem._capacity) {
+ return null;
+ }
+ return this._particles.add();
+ }
+
+ public _setNewParticle (p: Particle) {
+
+ }
+
+ public _updateParticles (dt: number) {
+ this.node.getWorldMatrix(_tempWorldTrans);
+ if (this.particleSystem.velocityOvertimeModule.enable) {
+ this.particleSystem.velocityOvertimeModule.update(this.particleSystem._simulationSpace, _tempWorldTrans);
+ }
+ if (this.particleSystem.forceOvertimeModule.enable) {
+ this.particleSystem.forceOvertimeModule.update(this.particleSystem._simulationSpace, _tempWorldTrans);
+ }
+ for (let i = 0; i < this._particles.length; ++i) {
+ const p = this._particles.data[i];
+ p.remainingLifetime -= dt;
+ vec3.set(p.animatedVelocity, 0, 0, 0);
+
+ if (p.remainingLifetime < 0.0) {
+ this._particles.removeAt(i);
+ --i;
+ continue;
+ }
+
+ p.velocity.y -= this.particleSystem.gravityModifier.evaluate(1 - p.remainingLifetime / p.startLifetime, p.randomSeed) * 9.8 * dt; // apply gravity.
+ if (this.particleSystem.sizeOvertimeModule.enable) {
+ this.particleSystem.sizeOvertimeModule.animate(p);
+ }
+ if (this.particleSystem.colorOverLifetimeModule.enable) {
+ this.particleSystem.colorOverLifetimeModule.animate(p);
+ }
+ if (this.particleSystem.forceOvertimeModule.enable) {
+ this.particleSystem.forceOvertimeModule.animate(p, dt);
+ }
+ if (this.particleSystem.velocityOvertimeModule.enable) {
+ this.particleSystem.velocityOvertimeModule.animate(p);
+ } else {
+ vec3.copy(p.ultimateVelocity, p.velocity);
+ }
+ if (this.particleSystem.limitVelocityOvertimeModule.enable) {
+ this.particleSystem.limitVelocityOvertimeModule.animate(p);
+ }
+ if (this.particleSystem.rotationOvertimeModule.enable) {
+ this.particleSystem.rotationOvertimeModule.animate(p, dt);
+ }
+ if (this.particleSystem.textureAnimationModule.enable) {
+ this.particleSystem.textureAnimationModule.animate(p);
+ }
+ vec3.scaleAndAdd(p.position, p.position, p.ultimateVelocity, dt); // apply velocity.
+ }
+ }
+
+ // internal function
+ public _updateRenderData () {
+ // update vertex buffer
+ let idx = 0;
+ const uploadVel = this._renderMode === RenderMode.StrecthedBillboard;
+ for (let i = 0; i < this._particles.length; ++i) {
+ const p = this._particles.data[i];
+ let fi = 0;
+ if (this.particleSystem.textureAnimationModule.enable) {
+ fi = p.frameIndex;
+ }
+ idx = i * 4;
+ let attrNum = 0;
+ for (let j = 0; j < 4; ++j) { // four verts per particle.
+ attrNum = 0;
+ this.attrs[attrNum++] = p.position;
+ _tempAttribUV.x = _uvs[2 * j];
+ _tempAttribUV.y = _uvs[2 * j + 1];
+ _tempAttribUV.z = fi;
+ this.attrs[attrNum++] = _tempAttribUV;
+ _tempAttribUV0.x = p.size.x;
+ _tempAttribUV0.y = p.rotation.x;
+ this.attrs[attrNum++] = _tempAttribUV0;
+ this.attrs[attrNum++] = p.color._val;
+
+ if (uploadVel) {
+ this.attrs[attrNum++] = p.ultimateVelocity;
+ }
+
+ this._model!.addParticleVertexData(idx++, this.attrs);
+ }
+ }
+
+ // because we use index buffer, per particle index count = 6.
+ this._model!.updateIA(this._particles.length * 6);
+ }
+
+ public updateShaderUniform () {
+
+ }
+
+ public getParticleCount (): number {
+ return this._particles.length;
+ }
+
+ public _onMaterialModified (index: number, material: Material) {
+ this._updateMaterialParams();
+ this._updateModel();
+ }
+
+ public _onRebuildPSO (index: number, material: Material) {
+ if (this._model) {
+ this._model.setSubModelMaterial(0, material);
+ }
+ }
+
+ private _updateMaterialParams () {
+ if (!this.particleSystem) {
+ return;
+ }
+ if (this.particleSystem._simulationSpace === Space.World) {
+ this._defines[USE_WORLD_SPACE] = true;
+ } else {
+ this._defines[USE_WORLD_SPACE] = false;
+ }
+
+ if (this._renderMode === RenderMode.Billboard) {
+ this._defines[USE_BILLBOARD] = true;
+ this._defines[USE_STRETCHED_BILLBOARD] = false;
+ this._defines[USE_HORIZONTAL_BILLBOARD] = false;
+ this._defines[USE_VERTICAL_BILLBOARD] = false;
+ } else if (this._renderMode === RenderMode.StrecthedBillboard) {
+ this._defines[USE_BILLBOARD] = false;
+ this._defines[USE_STRETCHED_BILLBOARD] = true;
+ this._defines[USE_HORIZONTAL_BILLBOARD] = false;
+ this._defines[USE_VERTICAL_BILLBOARD] = false;
+ this.sharedMaterial!.setProperty('velocityScale', this._velocityScale);
+ this.sharedMaterial!.setProperty('lengthScale', this._lengthScale);
+ } else if (this._renderMode === RenderMode.HorizontalBillboard) {
+ this._defines[USE_BILLBOARD] = false;
+ this._defines[USE_STRETCHED_BILLBOARD] = false;
+ this._defines[USE_HORIZONTAL_BILLBOARD] = true;
+ this._defines[USE_VERTICAL_BILLBOARD] = false;
+ } else if (this._renderMode === RenderMode.VerticalBillboard) {
+ this._defines[USE_BILLBOARD] = false;
+ this._defines[USE_STRETCHED_BILLBOARD] = false;
+ this._defines[USE_HORIZONTAL_BILLBOARD] = false;
+ this._defines[USE_VERTICAL_BILLBOARD] = true;
+ } else {
+ console.warn(`particle system renderMode ${this._renderMode} not support.`);
+ }
+ this.getMaterial(0, CC_EDITOR)!.setDefines(this._defines);
+
+ if (this.particleSystem.textureAnimationModule.enable) {
+ this.getMaterial(0, CC_EDITOR)!.setProperty('frameTile', vec2.set(this.frameTile, this.particleSystem.textureAnimationModule.numTilesX, this.particleSystem.textureAnimationModule.numTilesY));
+ } else {
+ this.getMaterial(0, CC_EDITOR)!.setProperty('frameTile', this.frameTile);
+ }
+ }
+
+ private _updateModel () {
+ if (!this.particleSystem) {
+ return;
+ }
+ this._model!.setSubModelMaterial(0, this.sharedMaterial ? this.sharedMaterial : null);
+ if (Object.getPrototypeOf(this).constructor.name === 'ParticleSystemGpuRenderer') {
+ return;
+ }
+ if (this._renderMode === RenderMode.StrecthedBillboard) {
+ this._model!.enableStretchedBillboard();
+ } else {
+ this._model!.disableStretchedBillboard();
+ }
+ }
+}
+
+Object.assign(ParticleSystemRenderer, { uv: _uvs });
diff --git a/cocos/3d/framework/physics/body.ts b/cocos/3d/framework/physics/body.ts
index f183d680f9..1f9a8c63aa 100644
--- a/cocos/3d/framework/physics/body.ts
+++ b/cocos/3d/framework/physics/body.ts
@@ -1,7 +1,7 @@
import CANNON from 'cannon';
import Vec3 from '../../../core/value-types/vec3';
import { vec3 } from '../../../core/vmath';
-import Node from '../../../scene-graph/node';
+import { Node } from '../../../scene-graph/node';
import { PhysicsMaterial as PhysicsMaterial } from '../../assets/physics/material';
import { setWrap, getWrap } from './util';
import { Quat } from '../../../core/value-types';
diff --git a/cocos/3d/framework/physics/collider-component.ts b/cocos/3d/framework/physics/collider-component.ts
index 132ecd0508..25762d8f0e 100644
--- a/cocos/3d/framework/physics/collider-component.ts
+++ b/cocos/3d/framework/physics/collider-component.ts
@@ -4,7 +4,7 @@ import {
executeInEditMode,
executionOrder,
menu,
- property
+ property,
} from '../../../core/data/class-decorator';
import Vec3 from '../../../core/value-types/vec3';
import { PhysicsBoxShape, PhysicsShape, PhysicsSphereShape } from './body';
@@ -17,37 +17,39 @@ export class ColliderComponentBase extends PhysicsBasedComponent {
@property
private _center: Vec3 = new cc.Vec3(0, 0, 0);
- constructor(shape: PhysicsShape) {
+ constructor (shape: PhysicsShape) {
super();
this._center = new Vec3(0, 0, 0);
this._shape = shape;
}
- public get body() {
+ public get body () {
return this._body;
}
- public onLoad() {
+ public onLoad () {
super.onLoad();
this.center = this._center;
}
- public onEnable() {
+ public onEnable () {
super.onEnable();
this._body!.addShape(this._shape);
}
- public onDisable() {
+ public onDisable () {
super.onDisable();
this._body!.removeShape(this._shape);
}
- @property(Vec3)
- get center() {
+ @property({
+ type: Vec3,
+ })
+ get center () {
return this._center;
}
- set center(value: Vec3) {
+ set center (value: Vec3) {
this._center = new Vec3(value.x, value.y, value.z);
this._shape.center = value;
}
@@ -61,24 +63,26 @@ export class BoxColliderComponent extends ColliderComponentBase {
@property
private _size: Vec3 = new Vec3(0, 0, 0);
- constructor() {
+ constructor () {
super(new PhysicsBoxShape(new Vec3(0, 0, 0)));
}
- public onLoad() {
+ public onLoad () {
super.onLoad();
this.size = this._size;
}
- @property(Vec3)
- get size() {
+ @property({
+ type: Vec3,
+ })
+ get size () {
return this._size;
}
/**
* Note, shall not specify size with component 0
*/
- set size(value) {
+ set size (value) {
this._size = value;
(this._shape as PhysicsBoxShape).size = this._size;
if (this._body) {
@@ -95,21 +99,21 @@ export class SphereColliderComponent extends ColliderComponentBase {
@property
private _radius: number = 0;
- constructor() {
+ constructor () {
super(new PhysicsSphereShape(0));
}
- public onLoad() {
+ public onLoad () {
super.onLoad();
this.radius = this._radius;
}
@property
- get radius() {
+ get radius () {
return this._radius;
}
- set radius(value) {
+ set radius (value) {
this._radius = value;
(this._shape as PhysicsSphereShape).radius = value;
if (this._body) {
diff --git a/cocos/3d/framework/physics/detail/physics-based-component.ts b/cocos/3d/framework/physics/detail/physics-based-component.ts
index 5cfadbeb12..dcde768e92 100644
--- a/cocos/3d/framework/physics/detail/physics-based-component.ts
+++ b/cocos/3d/framework/physics/detail/physics-based-component.ts
@@ -1,5 +1,5 @@
-import Component from '../../../../components/CCComponent';
+import { Component } from '../../../../components/component';
import { ccclass } from '../../../../core/data/class-decorator';
import { PhysicsBody } from '../body';
diff --git a/cocos/3d/framework/physics/rigid-body-component.ts b/cocos/3d/framework/physics/rigid-body-component.ts
index 37309ba6aa..3d4b7cc157 100644
--- a/cocos/3d/framework/physics/rigid-body-component.ts
+++ b/cocos/3d/framework/physics/rigid-body-component.ts
@@ -4,11 +4,17 @@ import {
executeInEditMode,
executionOrder,
menu,
- property
+ property,
} from '../../../core/data/class-decorator';
import { PhysicsMaterial } from '../../assets/physics/material';
import { PhysicsBasedComponent } from './detail/physics-based-component';
+const NonRigidBodyProperties = {
+ mass: 0,
+ linearDamping: 0,
+ angularDamping: 0,
+};
+
@ccclass('cc.RigidBodyComponent')
@executionOrder(100)
@menu('Components/RigidBodyComponent')
@@ -26,38 +32,40 @@ export class RigidBodyComponent extends PhysicsBasedComponent {
@property
private _angularDamping: number = NonRigidBodyProperties.angularDamping;
- constructor() {
+ constructor () {
super();
}
- public get body() {
+ public get body () {
return this._body;
}
- public onLoad() {
+ public onLoad () {
super.onLoad();
}
- public onEnable() {
+ public onEnable () {
super.onEnable();
this.mass = this._mass;
this.linearDamping = this._linearDamping;
this.angularDamping = this._angularDamping;
}
- public onDisable() {
+ public onDisable () {
super.onDisable();
this.mass = NonRigidBodyProperties.mass;
this.linearDamping = NonRigidBodyProperties.linearDamping;
this.angularDamping = NonRigidBodyProperties.angularDamping;
}
- @property(PhysicsMaterial)
- get material() {
+ @property({
+ type: PhysicsMaterial,
+ })
+ get material () {
return this._material;
}
- set material(value) {
+ set material (value) {
this._material = value;
if (this._body) {
this._body.material = this._material;
@@ -65,11 +73,11 @@ export class RigidBodyComponent extends PhysicsBasedComponent {
}
@property
- get mass() {
+ get mass () {
return this._mass;
}
- set mass(value) {
+ set mass (value) {
this._mass = value;
if (this._body) {
this._body.mass = value;
@@ -77,11 +85,11 @@ export class RigidBodyComponent extends PhysicsBasedComponent {
}
@property
- get linearDamping() {
+ get linearDamping () {
return this._linearDamping;
}
- set linearDamping(value) {
+ set linearDamping (value) {
this._linearDamping = value;
if (this._body) {
this._body.linearDamping = value;
@@ -89,26 +97,20 @@ export class RigidBodyComponent extends PhysicsBasedComponent {
}
@property
- get angularDamping() {
+ get angularDamping () {
return this._angularDamping;
}
- set angularDamping(value) {
+ set angularDamping (value) {
this._angularDamping = value;
if (this._body) {
this._body.angularDamping = value;
}
}
- public pullTransform() {
+ public pullTransform () {
if (this._body) {
this._body.pullTransform();
}
}
}
-
-const NonRigidBodyProperties = {
- mass: 0,
- linearDamping: 0,
- angularDamping: 0,
-};
diff --git a/cocos/3d/framework/physics/world.ts b/cocos/3d/framework/physics/world.ts
index 866d0eb09e..20d1a7aec3 100644
--- a/cocos/3d/framework/physics/world.ts
+++ b/cocos/3d/framework/physics/world.ts
@@ -46,8 +46,10 @@ export class PhysicsWorld {
constructor() {
this._defaultMaterial = new PhysicsMaterial();
- this._defaultContactMaterial = new ContactMaterial(
- this._defaultMaterial, this._defaultMaterial, { friction: 0.3, restitution: 0.0 });
+ const mtl = new PhysicsMaterial();
+ mtl.friction = 0.3;
+ mtl.restitution = 0;
+ this._defaultContactMaterial = new ContactMaterial(this._defaultMaterial, mtl);
this._cannonWorld = new CANNON.World();
setWrap(this._cannonWorld, this);
diff --git a/cocos/3d/framework/render-system.js b/cocos/3d/framework/render-system.js
deleted file mode 100644
index d51bd637bb..0000000000
--- a/cocos/3d/framework/render-system.js
+++ /dev/null
@@ -1,21 +0,0 @@
-import { renderer } from '../../renderer';
-export default class RenderSystem {
- constructor () {
- this._scene = new renderer.Scene();
- }
-
- init () {
-
- }
-
- update (dt) {
- this._scene.tick();
- cc.game._renderer.render(this._scene);
- this._scene.reset();
- if (cc.director._scene) cc.director._scene.resetHasChanged();
- }
-
- get scene () {
- return this._scene;
- }
-}
diff --git a/cocos/3d/framework/renderSystemActor.js b/cocos/3d/framework/renderSystemActor.js
deleted file mode 100644
index eaf5ed65d5..0000000000
--- a/cocos/3d/framework/renderSystemActor.js
+++ /dev/null
@@ -1,41 +0,0 @@
-import Component from '../../components/CCComponent';
-
-class RenderSystemActorListener {
- constructor() {
- this._renderSystem = null;
- }
-
- onRenderableComponentCreated(comp) {
- if(this._renderSystem === null) {
- this._renderSystem = cc.director._renderSystem;
- }
- comp._system = this._renderSystem;
- if (this._renderSystem) {
- comp._scene = this._renderSystem.scene;
- }
- }
-}
-
-let listener = new RenderSystemActorListener();
-
-/**
- * @class RenderSystemActor
- * @extends Component
- * RenderSystemActor is used to access Rendersystem
- */
-export default class RenderSystemActor extends Component {
- constructor() {
- super();
- this._system = null;
- this._scene = null;
- listener.onRenderableComponentCreated(this);
- }
-
- get renderSystem() {
- return this._system;
- }
-
- get scene() {
- return this._scene;
- }
-}
diff --git a/cocos/3d/framework/renderable-component.js b/cocos/3d/framework/renderable-component.ts
similarity index 59%
rename from cocos/3d/framework/renderable-component.js
rename to cocos/3d/framework/renderable-component.ts
index 744cdf8a6a..bbf38ac38c 100644
--- a/cocos/3d/framework/renderable-component.js
+++ b/cocos/3d/framework/renderable-component.ts
@@ -1,30 +1,31 @@
-//@ts-check
-import RenderSystemActor from "./renderSystemActor";
+// @ts-check
+import { Component } from '../../components/component';
import { _decorator } from '../../core/data/index';
-import Material from "../assets/material";
+import { Material } from '../assets/material';
const { ccclass, property } = _decorator;
@ccclass('cc.RenderableComponent')
-export default class RenderableComponent extends RenderSystemActor {
- /**
- * @type {Material[]}
- */
- @property([Material])
- _materials = [];
+export class RenderableComponent extends Component {
+ @property({ type: [Material] })
+ private _materials: Array = [];
- constructor() {
+ constructor () {
super();
}
+ public onLoad () {
+ this.sharedMaterials = this._materials.concat();
+ }
+
@property({
type: [Material],
- displayName: 'Materials'
+ displayName: 'Materials',
})
- get sharedMaterials() {
+ get sharedMaterials () {
return this._materials;
}
- set sharedMaterials(val) {
+ set sharedMaterials (val) {
// 因为现在编辑器的做法是,当这个val传进来时,内部的materials已经被修改了。
// 我们没办法做到上面的最优化,只能先清理ModelComponent里所有Submodel的材质,再重新关联。
this._clearMaterials();
@@ -37,14 +38,14 @@ export default class RenderableComponent extends RenderSystemActor {
* !#ch 模型材质
* @type {Material[]}
*/
- get materials() {
+ get materials () {
for (let i = 0; i < this._materials.length; i++) {
- this._materials[i] = this.getMaterial(i);
+ this._materials[i] = this.getMaterial(i)!;
}
return this._materials;
}
- set materials(val) {
+ set materials (val) {
const dLen = val.length - this._materials.length;
if (dLen > 0) {
this._materials = this._materials.concat(new Array(dLen).fill(null));
@@ -62,51 +63,53 @@ export default class RenderableComponent extends RenderSystemActor {
* !#ch 返回相对应序号的材质
* @param {Number} idx - Look for the material list number
*/
- getMaterial(idx) {
- if (idx < 0 || idx >= this._materials.length || this._materials[idx] == null) {
- return null;
- }
-
- let instantiated = Material.getInstantiatedMaterial(this._materials[idx], this);
+ public getMaterial (idx: number, inEditor: boolean = false): Material | null {
+ const mat = this._materials[idx];
+ if (!mat) { return null; }
+ const instantiated = Material.getInstantiatedMaterial(mat, this, inEditor);
if (instantiated !== this._materials[idx]) {
- this.setMaterial(instantiated, idx);
+ this.setMaterial(instantiated, idx, !inEditor);
}
-
return this._materials[idx];
}
- getSharedMaterial(idx) {
+ public getSharedMaterial (idx: number): Material | null {
if (idx < 0 || idx >= this._materials.length) {
return null;
}
return this._materials[idx];
}
- get material() {
+ get material () {
return this.getMaterial(0);
}
- get sharedMaterial() {
- return this.getSharedMaterial(0);
- }
-
- set material(val) {
+ set material (val) {
if (this._materials.length === 1 && this._materials[0] === val) {
return;
}
this.setMaterial(val, 0);
}
- setMaterial(material, index) {
+ get sharedMaterial () {
+ return this.getSharedMaterial(0);
+ }
+
+ public setMaterial (material: Material | null, index: number, notify: boolean = true) {
this._materials[index] = material;
- this._onMaterialModified(index, material);
+ if (notify) {
+ this._onMaterialModified(index, material);
+ }
}
- _onMaterialModified(index, material) {
+ protected _onMaterialModified (index: number, material: Material | null) {
}
- _clearMaterials() {
+ protected _onRebuildPSO (index: number, material: Material | null) {
+ }
+
+ protected _clearMaterials () {
}
}
diff --git a/cocos/3d/framework/skeleton-instance.js b/cocos/3d/framework/skeleton-instance.js
deleted file mode 100644
index 92ac204819..0000000000
--- a/cocos/3d/framework/skeleton-instance.js
+++ /dev/null
@@ -1,176 +0,0 @@
-// @ts-check
-import { vec3, quat, mat4 } from '../../core/vmath';
-import { Node } from '../../scene-graph';
-
-let _v3_tmp = vec3.create();
-let _qt_tmp = quat.create();
-
-/**
- *
- * @param {cc.Node} node
- * @param {(node: cc.Node)=>void} fx
- */
-function _walk(node, fx) {
- fx(node);
- for (let i = 0; i < node.childrenCount; ++i) {
- _walk(node.children[i], fx);
- }
-}
-
-export default class SkeletonInstance {
- /**
- *
- * @param {import("../assets/skeleton").default} skeleton
- */
- constructor(skeleton) {
- this._skeleton = skeleton;
-
- /**
- * @type {cc.Node[]}
- */
- this._nodes = this._copyNodesForest(skeleton._nodes);
-
- /**
- * @type {mat4[]}
- */
- this._matrices = new Array(this._nodes.length);
- for (let i = 0; i < this._nodes.length; ++i) {
- this._matrices[i] = mat4.create();
- }
-
- this.updateMatrices();
- }
-
- /**
- *
- * @param {cc.Node[]} nodes
- */
- _copyNodesForest(nodes) {
- /** @type {cc.Node[]} */
- const newNodes = new Array(nodes.length);
- nodes.forEach((node, index) => {
- newNodes[index] = this._copyNode(node);
- });
- nodes.forEach((node, index) => {
- const newNode = newNodes[index];
- node.children.forEach(childNode => {
- const childIndex = nodes.indexOf(childNode);
- newNode.addChild(newNodes[childIndex]);
- });
- });
- return newNodes;
- }
-
- /**
- *
- * @param {cc.Node} node
- */
- _copyNode(node) {
- const newNode = new Node(node.name);
- newNode.setPosition(node.getPosition());
- newNode.setScale(node.getScale());
- newNode.setRotation(node.getRotation());
- return newNode;
- }
-
- blend(fromSkel, toSkel, alpha) {
- for (let i = 0; i < this._nodes.length; ++i) {
- let joint = this._nodes[i];
- let jointFrom = fromSkel._nodes[i];
- let jointTo = toSkel._nodes[i];
-
- vec3.lerp(_v3_tmp, jointFrom._lpos, jointTo._lpos, alpha);
- joint.setPosition(_v3_tmp);
-
- vec3.lerp(_v3_tmp, jointFrom._lscale, jointTo._lscale, alpha);
- joint.setScale(_v3_tmp);
-
- quat.lerp(_qt_tmp, jointFrom._lrot, jointTo._lrot, alpha);
- joint.setRotation(_qt_tmp);
- }
- }
-
- updateMatrices() {
- for (let i = 0; i < this._nodes.length; ++i) {
- this._nodes[i].getWorldMatrix(this._matrices[i]);
- }
- }
-
- /**
- *
- * @param {number} i Index of the node.
- */
- getWorldMatrix(i) {
- return this._matrices[i];
- }
-
- getJointIndex(jointName) {
- for (let i = 0; i < this._nodes.length; ++i) {
- let joint = this._nodes[i];
- if (joint.name == jointName) {
- return i;
- }
- }
- return -1;
- }
-
- getJointIndexFromOrignalNodeIndex(index) {
- return index;
- }
-
- clone() {
- return new SkeletonInstance(this._skeleton);
- }
-
- createMask() {
- return new SkeletonMask(this);
- }
-}
-
-export class SkeletonMask {
- /**
- *
- * @param {SkeletonInstance} skeleton
- */
- constructor(skeleton) {
- /**
- * @type {SkeletonInstance}
- * */
- this._skeleton = skeleton;
-
- this._isMaskedArray = new Array(skeleton._nodes.length);
- for (let i = 0; i < this._isMaskedArray.length; ++i) {
- this._isMaskedArray[i] = false;
- }
- }
-
- setMasked(jointIndex, masked = true) {
- this._isMaskedArray[jointIndex] = masked;
- }
-
- setMaskedRecursive(jointIndex, masked = true) {
- if (jointIndex < 0 || jointIndex >= this._skeleton._nodes.length) {
- return;
- }
-
- this._isMaskedArray[jointIndex] = masked;
- _walk(this._skeleton._nodes[0], joint => {
- let idx = this._skeleton._nodes.indexOf(joint);
- if (idx >= 0) {
- this._isMaskedArray[idx] = masked;
- }
- });
- }
-
- isMasked(jointIndex) {
- return this._isMaskedArray[jointIndex];
- }
-
- complement() {
- let ret = new SkeletonMask(this._skeleton);
- for (let i = 0; i < this._isMaskedArray.length; ++i) {
- ret._isMaskedArray[i] = !this._isMaskedArray[i];
- }
- return ret;
- }
-}
\ No newline at end of file
diff --git a/cocos/3d/framework/skinning-model-component.js b/cocos/3d/framework/skinning-model-component.js
deleted file mode 100644
index c3c9349a69..0000000000
--- a/cocos/3d/framework/skinning-model-component.js
+++ /dev/null
@@ -1,253 +0,0 @@
-/****************************************************************************
- Copyright (c) 2013-2016 Chukong Technologies Inc.
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos2d-x.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-
-// @ts-check
-import { mat4 } from '../../core/vmath';
-import ModelComponent from './model-component';
-import { renderer } from '../../renderer/index';
-import { ccclass, property, executionOrder, menu,executeInEditMode } from '../../core/data/class-decorator';
-import utils from '../misc/utils';
-import Skeleton from '../assets/skeleton';
-import Node from '../../scene-graph/node';
-
-/**
- * @typedef {import("../framework/skeleton-instance").default} SkeletonInstance
- */
-let _m4_tmp = mat4.create();
-
-/**
- * !#en The Skinning Model Component
- *
- * !#ch 皮肤模型组件
- * @class SkinningModelComponent
- * @extends ModelComponent
- */
-@ccclass('cc.SkinningModelComponent')
-@executionOrder(100)
-@executeInEditMode
-@menu('Components/SkinningModelComponent')
-export default class SkinningModelComponent extends ModelComponent {
- /**
- * @type {Skeleton}
- */
- @property(Skeleton)
- _skeleton = null;
-
- /**
- * @type {Node}
- */
- @property(Node)
- _skinningRoot = null;
-
- constructor() {
- super();
-
- /**
- * @type {Map}
- */
- this._skinningTarget = null;
-
- /**
- * @type {import("../../renderer/gfx/texture-2d").default}
- */
- this._jointsTexture = null;
-
- /**
- * @type {Float32Array}
- */
- this._jointMatricesData = null;
- }
-
- /**
- * !#en The bone nodes
- *
- * !#ch 骨骼节点
- * @type {Skeleton}
- */
- @property({type: Skeleton})
- get skeleton() {
- return this._skeleton;
- }
-
- set skeleton(val) {
- this._skeleton = val;
- }
-
- @property({type: Node})
- get skinningRoot() {
- return this._skinningRoot;
- }
-
- set skinningRoot(value) {
- this._skinningRoot = value;
- this._resetTarget();
- }
-
- onLoad() {
- this._resetTarget();
- this._reInitJointsData();
- this._updateModels();
- this._updateCastShadow();
- this._updateReceiveShadow();
- }
-
- update(dt) {
- this._updateMatrices();
- }
-
-
- onDestroy() {
- }
-
- _updateMatrices() {
- if (!this._mesh || !this._skeleton || !this._skinningTarget) {
- return;
- }
-
- // /** @type {import("../assets/utils/gltf-utils").GltfMeshResource} */
- // const res = this._mesh.resource;
- // const gltf = res.gltfAsset.description;
-
- // /** @type {Node[]} */
- // const nodes = [];
- // gltf.nodes.forEach((gltfNode, index) => nodes[index] = createNode(gltfNode));
- // gltf.nodes.forEach((gltfNode, index) => {
- // if (gltfNode.children) {
- // const node = nodes[index];
- // gltfNode.children.forEach((childIndex) => {
- // nodes[childIndex].setParent(node);
- // });
- // }
- // });
-
- const cancelThisNoTransform = this.node.getWorldMatrix();
- mat4.invert(cancelThisNoTransform, cancelThisNoTransform);
-
- this._skeleton.joints.forEach((joint, index) => {
- // const debugNode = nodes[this._skeleton._debugjoints[index]];
- // let wm = debugNode.getWorldMatrix();
-
- const targetNode = this._skinningTarget.get(joint);
- if (!targetNode) {
- return;
- }
- const bindpose = this._skeleton.bindposes[index];
-
- // 1. transform mesh to joint's local space
- // 2. transform from joint' local space to world space
- // 3. because it has been in world space, just cancel this mesh's original local-world transform
- const jointMatrix = _m4_tmp;
- mat4.multiply(jointMatrix, cancelThisNoTransform, targetNode.getWorldMatrix());
- mat4.multiply(jointMatrix, jointMatrix, bindpose);
- this._setJointMatrix(index, jointMatrix);
- });
-
- this._commitJointsData();
- }
-
- _createModel() {
- return new renderer.SkinningModel();
- }
-
- _updateModelParams() {
- super._updateModelParams();
- for (let i = 0; i < this._models.length; ++i)
- this._updateModelJointParam(this._models[i]);
- }
-
- _reInitJointsData() {
- if (this._jointsTexture) {
- this._jointsTexture.destroy();
- }
-
- if (!this._skeleton) {
- this._jointMatricesData = null;
- return;
- }
-
- if (cc.game._renderContext.allowFloatTexture()) {
- this._jointsTexture = utils.createJointsTexture(this._skeleton);
- this._jointMatricesData = new Float32Array(this._jointsTexture._width * this._jointsTexture._height * 4);
- } else {
- this._jointMatricesData = new Float32Array(this._skeleton.joints.length * 16);
- }
- }
-
- _commitJointsData() {
- if (this._jointsTexture != null) {
- this._jointsTexture.updateImage({
- image: this._jointMatricesData,
- width: this._jointsTexture._width,
- height: this._jointsTexture._height,
- level: 0,
- flipY: false,
- premultiplyAlpha: false
- });
- }
- }
-
- _updateModelJointParam(model) {
- if (this._jointsTexture != null) {
- model.setJointsTexture(this._jointsTexture);
- } else {
- model.setJointsMatrixArray(this._jointMatricesData);
- }
- }
-
- _setJointMatrix(iMatrix, matrix) {
- this._jointMatricesData[16 * iMatrix + 0] = matrix.m00;
- this._jointMatricesData[16 * iMatrix + 1] = matrix.m01;
- this._jointMatricesData[16 * iMatrix + 2] = matrix.m02;
- this._jointMatricesData[16 * iMatrix + 3] = matrix.m03;
- this._jointMatricesData[16 * iMatrix + 4] = matrix.m04;
- this._jointMatricesData[16 * iMatrix + 5] = matrix.m05;
- this._jointMatricesData[16 * iMatrix + 6] = matrix.m06;
- this._jointMatricesData[16 * iMatrix + 7] = matrix.m07;
- this._jointMatricesData[16 * iMatrix + 8] = matrix.m08;
- this._jointMatricesData[16 * iMatrix + 9] = matrix.m09;
- this._jointMatricesData[16 * iMatrix + 10] = matrix.m10;
- this._jointMatricesData[16 * iMatrix + 11] = matrix.m11;
- this._jointMatricesData[16 * iMatrix + 12] = matrix.m12;
- this._jointMatricesData[16 * iMatrix + 13] = matrix.m13;
- this._jointMatricesData[16 * iMatrix + 14] = matrix.m14;
- this._jointMatricesData[16 * iMatrix + 15] = matrix.m15;
- }
-
- _resetTarget() {
- this._skinningTarget = new Map();
- if (!this._skeleton || !this._skinningRoot) {
- return;
- }
- const rootNode = this._skinningRoot;
- this._skeleton.joints.forEach(joint => {
- const targetNode = rootNode.getChildByPath(joint);
- if (!targetNode) {
- console.warn(`Skinning target ${joint} not found in scene graph.`);
- return;
- }
- this._skinningTarget.set(joint, targetNode);
- });
- }
-}
diff --git a/cocos/3d/framework/skinning-model-component.ts b/cocos/3d/framework/skinning-model-component.ts
new file mode 100644
index 0000000000..a4f6e0bbea
--- /dev/null
+++ b/cocos/3d/framework/skinning-model-component.ts
@@ -0,0 +1,178 @@
+/****************************************************************************
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+// @ts-check
+import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../core/data/class-decorator';
+import { mat4 } from '../../core/vmath';
+import { GFXDevice, GFXFeature } from '../../gfx/device';
+import { SkinningModel, __FORCE_USE_UNIFORM_STORAGE__ } from '../../renderer/models/skinning-model';
+import { Node } from '../../scene-graph/node';
+import { Material } from '../assets/material';
+import Skeleton from '../assets/skeleton';
+import { ModelComponent } from './model-component';
+
+const _m4_tmp = mat4.create();
+
+type SkinningTarget = Map;
+
+/**
+ * !#en The Skinning Model Component
+ * !#ch 皮肤模型组件
+ */
+@ccclass('cc.SkinningModelComponent')
+@executionOrder(100)
+@executeInEditMode
+@menu('Components/SkinningModelComponent')
+export default class SkinningModelComponent extends ModelComponent {
+
+ /**
+ * !#en The bone nodes
+ *
+ * !#ch 骨骼节点
+ */
+ @property({type: Skeleton})
+ get skeleton () {
+ return this._skeleton;
+ }
+
+ set skeleton (val) {
+ this._skeleton = val;
+ this._resetSkinningTarget();
+ this._bindSkeleton();
+ }
+
+ @property({type: Node})
+ get skinningRoot () {
+ return this._skinningRoot;
+ }
+
+ set skinningRoot (value) {
+ this._skinningRoot = value;
+ this._resetSkinningTarget();
+ }
+ @property(Skeleton)
+ private _skeleton: Skeleton | null = null;
+
+ @property(Node)
+ private _skinningRoot: Node | null = null;
+
+ private _skinningTarget: SkinningTarget | null = null;
+
+ constructor () {
+ super();
+ }
+
+ public onLoad () {
+ super.onLoad();
+ this._resetSkinningTarget();
+ }
+
+ public update (dt) {
+ this._tryUpdateMatrices();
+ }
+
+ public onDestroy () {
+ }
+
+ public _tryUpdateMatrices () {
+ if (!this._skeleton || !this._skinningTarget || !this._model) {
+ return;
+ }
+
+ const skinningModel = this._model as SkinningModel;
+ const skeleton = this._skeleton;
+ const skinningTarget = this._skinningTarget;
+
+ const cancelThisNodeTransform = this.node.getWorldMatrix();
+ mat4.invert(cancelThisNodeTransform, cancelThisNodeTransform);
+ this._skeleton.joints.forEach((joint, index) => {
+ // If target joint doesn't exists in scene graph, skip it.
+ const targetNode = skinningTarget.get(joint);
+ if (!targetNode) {
+ return;
+ }
+ // 1. transform mesh to joint's local space
+ // 2. transform from joint' local space to world space
+ // 3. because it has been in world space, just cancel this mesh's original local-world transform
+ const bindpose = skeleton.bindposes[index];
+ const jointMatrix = _m4_tmp;
+ mat4.multiply(jointMatrix, cancelThisNodeTransform, targetNode.getWorldMatrix());
+ mat4.multiply(jointMatrix, jointMatrix, bindpose);
+ skinningModel.updateJointMatrix(index, jointMatrix);
+ });
+
+ skinningModel.commitJointMatrices();
+ }
+
+ public _createModel () {
+ return this._getRenderScene().createModel(SkinningModel, this.node);
+ }
+
+ public _updateModelParams () {
+ // Should bind skeleton before super create pso
+ this._bindSkeleton();
+ super._updateModelParams();
+ }
+
+ protected _onMaterialModified (index: number, material: Material) {
+ super._onMaterialModified(index, material);
+
+ const device = _getGlobalDevice();
+ const useJointTexture = !__FORCE_USE_UNIFORM_STORAGE__ && device !== null && device.hasFeature(GFXFeature.TEXTURE_FLOAT);
+ this.getMaterial(0, CC_EDITOR)!.setDefines({
+ CC_USE_SKINNING: true,
+ CC_USE_JOINTS_TEXTURE: useJointTexture,
+ });
+ }
+
+ private _bindSkeleton () {
+ if (this._model && this._skeleton) {
+ (this._model as SkinningModel).bindSkeleton(this._skeleton);
+ }
+ }
+
+ private _resetSkinningTarget () {
+ if (!this._skeleton || !this._skinningRoot) {
+ return;
+ }
+
+ // Collect target to skin.
+ this._skinningTarget = new Map();
+ const rootNode = this._skinningRoot;
+ this._skeleton.joints.forEach((joint) => {
+ const targetNode = rootNode.getChildByPath(joint);
+ if (!targetNode) {
+ console.warn(`Skinning target ${joint} not found in scene graph.`);
+ return;
+ }
+ this._skinningTarget!.set(joint, targetNode);
+ });
+ }
+}
+
+function _getGlobalDevice (): GFXDevice | null {
+ // @ts-ignore
+ return cc.director.root.device;
+}
diff --git a/cocos/3d/framework/skinning-model-system.js b/cocos/3d/framework/skinning-model-system.js
deleted file mode 100644
index 25d4542bf1..0000000000
--- a/cocos/3d/framework/skinning-model-system.js
+++ /dev/null
@@ -1,76 +0,0 @@
-/****************************************************************************
- Copyright (c) 2013-2016 Chukong Technologies Inc.
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos2d-x.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-// @ts-check
-import { System } from '../ecs';
-import { FixedArray } from '../memop';
-import { _decorator } from '../../core/data/index';
-const { ccclass, property } = _decorator;
-
-/**
- * !#en Skinning Model Component Management System
- *
- * !#ch 皮肤模型管理系统
- * @class SkinningModelSystem
- * @extends System
- */
-@ccclass('cc.SkinningModelSystem')
-export default class SkinningModelSystem extends System {
- constructor() {
- super();
-
- this._comps = new FixedArray(200);
- }
-
- /**
- * !# Add skinning model component
- *
- * !#ch 添加需要统一管理的皮肤模型
- * @param {SkinningModelComponent} comp
- */
- add(comp) {
- this._comps.push(comp);
- }
-
- /**
- * !# Add skinning model component
- *
- * !#ch 添加需要统一管理的皮肤模型
- * @param {SkinningModelComponent} comp
- */
- remove(comp) {
- this._comps.fastRemove(this._comps.indexOf(comp));
- }
-
-// update() {
-// for (let i = 0; i < this._comps.length; ++i) {
-// let comp = this._comps.data[i];
-// if (comp.enabled === false) {
-// continue;
-// }
-
-// comp._updateMatrices();
-// }
-// }
-}
diff --git a/cocos/3d/framework/skybox-component.js b/cocos/3d/framework/skybox-component.js
deleted file mode 100644
index ce398e6ca8..0000000000
--- a/cocos/3d/framework/skybox-component.js
+++ /dev/null
@@ -1,120 +0,0 @@
-/****************************************************************************
- Copyright (c) 2013-2016 Chukong Technologies Inc.
- Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
-
- http://www.cocos2d-x.org
-
- Permission is hereby granted, free of charge, to any person obtaining a copy
- of this software and associated documentation files (the "Software"), to deal
- in the Software without restriction, including without limitation the rights
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
- copies of the Software, and to permit persons to whom the Software is
- furnished to do so, subject to the following conditions:
-
- The above copyright notice and this permission notice shall be included in
- all copies or substantial portions of the Software.
-
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
- THE SOFTWARE.
- ****************************************************************************/
-// @ts-check
-import { renderer } from '../../renderer/index';
-import { box } from '../primitive/index';
-import Material from '../assets/material';
-import { ccclass, property, menu, executeInEditMode } from '../../core/data/class-decorator';
-import TextureCube from '../assets/texture-cube';
-import Component from '../../components/CCComponent';
-
-/**
- * !#en The Skybox Component
- *
- * !#ch 天空盒组件
- * @class SkyboxComponent
- * @extends Component
- */
-@ccclass('cc.SkyboxComponent')
-@menu('Components/SkyboxComponent')
-@executeInEditMode
-export default class SkyboxComponent extends Component {
-
- @property
- _cubemap = null;
- @property
- _rgbeTexture = false;
-
- @property({
- type: TextureCube,
- displayName: 'Cubemap'
- })
- get cubemap() {
- return this._cubemap;
- }
-
- set cubemap(val) {
- this._cubemap = val;
- this._updateMaterialParams();
- }
-
- @property({
- type: Boolean,
- displayName: 'RGBE Texture'
- })
- set rgbeTexture(v) {
- this._rgbeTexture = v;
- this._updateMaterialParams();
- }
- get rgbeTexture() {
- return this._rgbeTexture;
- }
-
- constructor() {
- super();
-
- this._model = new renderer.Model();
- this._attachedCamera = null;
- }
-
- onLoad() {
- this._model.setNode(this.node);
-
- let ia = renderer.createIA(cc.game._renderContext, box(2, 2, 2));
- this._model.setInputAssembler(ia);
-
- if (!this._material) {
- this._material = new Material();
- let skyboxEffect = cc.EffectAsset.get('builtin-effect-skybox');
- if (skyboxEffect) this._material.effectAsset = skyboxEffect;
- }
-
- this._updateMaterialParams();
- this._model.setEffect(this._material.effect);
- }
-
- onEnable() {
- if (this.node) {
- let cameraComponent = this.getComponent(cc.CameraComponent);
- if (cameraComponent && (cameraComponent._clearFlags & renderer.CLEAR_SKYBOX)) {
- this._attachedCamera = cameraComponent._camera;
- this._attachedCamera._clearModel = this._model;
- }
- }
- }
-
- onDisable() {
- if (this._attachedCamera) {
- this._attachedCamera._clearModel = null;
- this._attachedCamera = null;
- }
- }
-
- _updateMaterialParams() {
- if (!this._material) return;
- if (this._cubemap) this._material.setProperty('cubeMap', this._cubemap);
- this._material.define('USE_RGBE_CUBEMAP', this._rgbeTexture);
- }
-}
diff --git a/cocos/3d/framework/skybox-component.ts b/cocos/3d/framework/skybox-component.ts
new file mode 100644
index 0000000000..45b316293a
--- /dev/null
+++ b/cocos/3d/framework/skybox-component.ts
@@ -0,0 +1,106 @@
+/****************************************************************************
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
+ Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
+
+ http://www.cocos2d-x.org
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to deal
+ in the Software without restriction, including without limitation the rights
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
+ THE SOFTWARE.
+ ****************************************************************************/
+
+import { Component } from '../../components/component';
+import { ccclass, executeInEditMode, menu, property } from '../../core/data/class-decorator';
+import { Camera, Model } from '../../renderer';
+import { Material } from '../assets/material';
+import { Mesh } from '../assets/mesh';
+import { TextureCube } from '../assets/texture-cube';
+import { createMesh } from '../misc/utils';
+import { box } from '../primitive';
+
+/**
+ * !#en The Skybox Component
+ *
+ * !#ch 天空盒组件
+ * @class SkyboxComponent
+ * @extends Component
+ */
+@ccclass('cc.SkyboxComponent')
+@menu('Components/SkyboxComponent')
+@executeInEditMode
+export default class SkyboxComponent extends Component {
+
+ @property
+ protected _cubemap = null;
+ @property
+ protected _rgbeTexture = false;
+
+ @property({
+ type: TextureCube,
+ displayName: 'Cubemap',
+ })
+ get cubemap () {
+ return this._cubemap;
+ }
+
+ set cubemap (val) {
+ this._cubemap = val;
+ if (this._material) { this._material.setProperty('cubeMap', this._cubemap); }
+ }
+
+ @property({
+ type: Boolean,
+ displayName: 'RGBE Texture',
+ })
+ set rgbeTexture (v) {
+ this._rgbeTexture = v;
+ if (this._material) { this._material.setDefines({ USE_RGBE_CUBEMAP: v }); }
+ }
+ get rgbeTexture () {
+ return this._rgbeTexture;
+ }
+
+ protected _attachedCamera: Camera | null = null;
+ protected _model: Model | null = null;
+ protected _mesh: Mesh | null = null;
+ protected _material: Material | null = null;
+
+ public onLoad () {
+ this._model = this._getRenderScene().createModel(Model, this.node);
+ this._mesh = createMesh(box({ width: 2, height: 2, length: 2 }));
+ this._material = new Material({
+ effectName: 'builtin-effect-skybox',
+ defines: { USE_RGBE_CUBEMAP: this._rgbeTexture },
+ });
+ if (this._cubemap) { this._material.setProperty('cubeMap', this._cubemap); }
+
+ const subMeshData = this._mesh.renderingMesh!.getSubmesh(0);
+ this._model.initSubModel(0, subMeshData!, this._material);
+ }
+
+ public onEnable () {
+ if (this._model) { this._model.enabled = true; }
+ }
+
+ public onDisable () {
+ if (this._model) { this._model.enabled = false; }
+ }
+
+ public onDestroy () {
+ if (this._model) { this._model.destroy(); this._model = null; }
+ }
+}
diff --git a/cocos/3d/geom-utils/aabb.js b/cocos/3d/geom-utils/aabb.ts
similarity index 64%
rename from cocos/3d/geom-utils/aabb.js
rename to cocos/3d/geom-utils/aabb.ts
index 523d831776..d702c33402 100644
--- a/cocos/3d/geom-utils/aabb.js
+++ b/cocos/3d/geom-utils/aabb.ts
@@ -1,12 +1,12 @@
+import { mat3, mat4, vec3 } from '../../core/vmath';
import enums from './enums';
-import { vec3, mat3 } from '../../core/vmath';
-let _v3_tmp = vec3.create();
-let _v3_tmp2 = vec3.create();
-let _m3_tmp = mat3.create();
+const _v3_tmp = vec3.create();
+const _v3_tmp2 = vec3.create();
+const _m3_tmp = mat3.create();
// https://zeuxcg.org/2010/10/17/aabb-from-obb-with-component-wise-abs/
-let transform_extent_m4 = function(out, extent, m4) {
+const transform_extent_m4 = (out: vec3, extent: vec3, m4: mat4) => {
_m3_tmp.m00 = Math.abs(m4.m00); _m3_tmp.m01 = Math.abs(m4.m01); _m3_tmp.m02 = Math.abs(m4.m02);
_m3_tmp.m03 = Math.abs(m4.m04); _m3_tmp.m04 = Math.abs(m4.m05); _m3_tmp.m05 = Math.abs(m4.m06);
_m3_tmp.m06 = Math.abs(m4.m08); _m3_tmp.m07 = Math.abs(m4.m09); _m3_tmp.m08 = Math.abs(m4.m10);
@@ -14,34 +14,29 @@ let transform_extent_m4 = function(out, extent, m4) {
};
export default class aabb {
- constructor(px = 0, py = 0, pz = 0, w = 1, h = 1, l = 1) {
- this._type = enums.SHAPE_AABB;
- this.center = vec3.create(px, py, pz);
- this.halfExtents = vec3.create(w, h, l);
- }
/**
* create a new aabb
*
- * @param {number} px X coordinates for aabb's original point
- * @param {number} py Y coordinates for aabb's original point
- * @param {number} pz Z coordinates for aabb's original point
- * @param {number} w the half of aabb width
- * @param {number} h the half of aabb height
- * @param {number} l the half of aabb length
- * @return {aabb}
+ * @param px - X coordinates for aabb's original point
+ * @param py - Y coordinates for aabb's original point
+ * @param pz - Z coordinates for aabb's original point
+ * @param w - the half of aabb width
+ * @param h - the half of aabb height
+ * @param l - the half of aabb length
+ * @returns the resulting aabb
*/
- static create(px, py, pz, w, h, l) {
+ public static create (px?: number, py?: number, pz?: number, w?: number, h?: number, l?: number) {
return new aabb(px, py, pz, w, h, l);
}
/**
* clone a new aabb
*
- * @param {aabb} a the source aabb
- * @return {aabb}
+ * @param a - the source aabb
+ * @returns the cloned aabb
*/
- static clone(a) {
+ public static clone (a: aabb) {
return new aabb(a.center.x, a.center.y, a.center.z,
a.halfExtents.x, a.halfExtents.y, a.halfExtents.z);
}
@@ -53,7 +48,7 @@ export default class aabb {
* @param {aabb} a the source aabb
* @return {aabb}
*/
- static copy(out, a) {
+ public static copy (out, a) {
vec3.copy(out.center, a.center);
vec3.copy(out.halfExtents, a.halfExtents);
@@ -63,17 +58,17 @@ export default class aabb {
/**
* create a new aabb from two corner points
*
- * @param {aabb} out the receiving aabb
- * @param {vec3} minPos lower corner position of the aabb
- * @param {vec3} maxPos upper corner position of the aabb
- * @return {aabb}
+ * @param out - the receiving aabb
+ * @param minPos - lower corner position of the aabb
+ * @param maxPos - upper corner position of the aabb
+ * @returns the resulting aabb
*/
- static fromPoints(out, minPos, maxPos) {
+ public static fromPoints (out: aabb, minPos: vec3, maxPos: vec3) {
vec3.scale(out.center, vec3.add(_v3_tmp, minPos, maxPos), 0.5);
vec3.scale(out.halfExtents, vec3.sub(_v3_tmp2, maxPos, minPos), 0.5);
return out;
}
-
+
/**
* Set the components of a aabb to the given values
*
@@ -87,18 +82,27 @@ export default class aabb {
* @return {aabb} out
* @function
*/
- static set(out, px, py, pz, w, h, l) {
+ public static set (out, px, py, pz, w, h, l) {
vec3.set(out.center, px, py, pz);
vec3.set(out.halfExtents, w, h, l);
return out;
}
+ public center: vec3;
+ public halfExtents: vec3;
+ protected _type: number = enums.SHAPE_AABB;
+
+ constructor (px = 0, py = 0, pz = 0, w = 1, h = 1, l = 1) {
+ this.center = vec3.create(px, py, pz);
+ this.halfExtents = vec3.create(w, h, l);
+ }
+
/**
* Get the bounding points of this shape
* @param {vec3} minPos
* @param {vec3} maxPos
*/
- getBoundary(minPos, maxPos) {
+ public getBoundary (minPos, maxPos) {
vec3.sub(minPos, this.center, this.halfExtents);
vec3.add(maxPos, this.center, this.halfExtents);
}
@@ -111,9 +115,13 @@ export default class aabb {
* @param {vec3} scale the scale part of the transform
* @param {aabb} [out] the target shape
*/
- transform(m, pos, rot, scale, out) {
- if (!out) out = this;
+ public transform (m, pos, rot, scale, out) {
+ if (!out) { out = this; }
vec3.transformMat4(out.center, this.center, m);
transform_extent_m4(out.halfExtents, this.halfExtents, m);
}
+
+ get type (){
+ return this._type;
+ }
}
diff --git a/cocos/3d/geom-utils/curve.js b/cocos/3d/geom-utils/curve.ts
similarity index 53%
rename from cocos/3d/geom-utils/curve.js
rename to cocos/3d/geom-utils/curve.ts
index cbf3d1e342..0824fcf8d2 100644
--- a/cocos/3d/geom-utils/curve.js
+++ b/cocos/3d/geom-utils/curve.ts
@@ -9,70 +9,77 @@ const WrapMode = Enum({
Once: 1,
Loop: 2,
PingPong: 3,
- ClampForever: 4
+ ClampForever: 4,
});
export class Keyframe {
- time = 0;
+ public time = 0;
- value = 0;
+ public value = 0;
- inTangent = 0;
+ public inTangent = 0;
- outTangent = 0;
+ public outTangent = 0;
}
CCClass.fastDefine('cc.Keyframe', Keyframe, {
time: 0,
value: 0,
inTangent: 0,
- outTangent: 0
+ outTangent: 0,
});
export class OptimizedKey {
- constructor() {
+ public index: number;
+ public time: number;
+ public endTime: number;
+ public coefficient: Float32Array;
+ constructor () {
this.index = -1;
this.time = 0;
this.endTime = 0;
this.coefficient = new Float32Array(4);
}
- evaluate(T) {
- let t = T - this.time;
+ public evaluate (T: number) {
+ const t = T - this.time;
return evalOptCurve(t, this.coefficient);
}
}
-export function evalOptCurve(t, coefs) {
+export function evalOptCurve (t: number, coefs: Float32Array) {
return (t * (t * (t * coefs[0] + coefs[1]) + coefs[2])) + coefs[3];
}
export class AnimationCurve {
- keyFrames = null;
+ public keyFrames: Keyframe[] | null;
- preWrapMode = WrapMode.Default;
+ public preWrapMode: number = WrapMode.Default;
- postWrapMode = WrapMode.Default;
+ public postWrapMode: number = WrapMode.Default;
- constructor(keyFrames) {
+ private cachedKey: OptimizedKey;
+
+ constructor (keyFrames: Keyframe[] | null = null) {
this.keyFrames = keyFrames;
this.cachedKey = new OptimizedKey();
}
- addKey(keyFrame) {
- if (this.keyFrames == null)
+ public addKey (keyFrame: Keyframe) {
+ if (this.keyFrames == null) {
this.keyFrames = [];
+ }
this.keyFrames.push(keyFrame);
}
- //cubic Hermite spline
- evaluate_slow(time) {
+ // cubic Hermite spline
+ public evaluate_slow (time: number) {
let wrappedTime = time;
- let wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode;
- let startTime = this.keyFrames[0].time;
- let endTime = this.keyFrames[this.keyFrames.length - 1].time;
+ const wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode;
+ const startTime = this.keyFrames![0].time;
+ const endTime = this.keyFrames![this.keyFrames!.length - 1].time;
switch (wrapMode) {
case WrapMode.Loop:
wrappedTime = repeat(time - startTime, endTime - startTime) + startTime;
@@ -85,43 +92,44 @@ export class AnimationCurve {
break;
}
let preKFIndex = 0;
- if (wrappedTime > this.keyFrames[0].time) {
- if (wrappedTime >= this.keyFrames[this.keyFrames.length - 1].time)
- preKFIndex = this.keyFrames.length - 2;
+ if (wrappedTime > this.keyFrames![0].time) {
+ if (wrappedTime >= this.keyFrames![this.keyFrames!.length - 1].time) {
+ preKFIndex = this.keyFrames!.length - 2;
+ }
else {
- for (let i = 0; i < this.keyFrames.length - 1; i++) {
- if (wrappedTime >= this.keyFrames[0].time && wrappedTime <= this.keyFrames[i + 1].time) {
+ for (let i = 0; i < this.keyFrames!.length - 1; i++) {
+ if (wrappedTime >= this.keyFrames![0].time && wrappedTime <= this.keyFrames![i + 1].time) {
preKFIndex = i;
break;
}
}
}
}
- let keyframe0 = this.keyFrames[preKFIndex];
- let keyframe1 = this.keyFrames[preKFIndex + 1];
+ const keyframe0 = this.keyFrames![preKFIndex];
+ const keyframe1 = this.keyFrames![preKFIndex + 1];
- let t = inverseLerp(keyframe0.time, keyframe1.time, wrappedTime);
- let dt = keyframe1.time - keyframe0.time;
+ const t = inverseLerp(keyframe0.time, keyframe1.time, wrappedTime);
+ const dt = keyframe1.time - keyframe0.time;
- let m0 = keyframe0.outTangent * dt;
- let m1 = keyframe1.inTangent * dt;
+ const m0 = keyframe0.outTangent * dt;
+ const m1 = keyframe1.inTangent * dt;
- let t2 = t * t;
- let t3 = t2 * t;
+ const t2 = t * t;
+ const t3 = t2 * t;
- let a = 2 * t3 - 3 * t2 + 1;
- let b = t3 - 2 * t2 + t;
- let c = t3 - t2;
- let d = -2 * t3 + 3 * t2;
+ const a = 2 * t3 - 3 * t2 + 1;
+ const b = t3 - 2 * t2 + t;
+ const c = t3 - t2;
+ const d = -2 * t3 + 3 * t2;
return a * keyframe0.value + b * m0 + c * m1 + d * keyframe1.value;
}
- evaluate(time) {
+ public evaluate (time) {
let wrappedTime = time;
- let wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode;
- let startTime = this.keyFrames[0].time;
- let endTime = this.keyFrames[this.keyFrames.length - 1].time;
+ const wrapMode = time < 0 ? this.preWrapMode : this.postWrapMode;
+ const startTime = this.keyFrames![0].time;
+ const endTime = this.keyFrames![this.keyFrames!.length - 1].time;
switch (wrapMode) {
case WrapMode.Loop:
wrappedTime = repeat(time - startTime, endTime - startTime) + startTime;
@@ -136,9 +144,9 @@ export class AnimationCurve {
if (wrappedTime >= this.cachedKey.time && wrappedTime < this.cachedKey.endTime) {
return this.cachedKey.evaluate(wrappedTime);
} else {
- let leftIndex = this.findIndex(this.cachedKey, wrappedTime);
+ const leftIndex = this.findIndex(this.cachedKey, wrappedTime);
let rightIndex = leftIndex + 1;
- if (rightIndex == this.keyFrames.length) {
+ if (rightIndex === this.keyFrames!.length) {
rightIndex -= 1;
}
this.calcOptimizedKey(this.cachedKey, leftIndex, rightIndex);
@@ -146,18 +154,18 @@ export class AnimationCurve {
}
}
- calcOptimizedKey(optKey, leftIndex, rightIndex) {
- let lhs = this.keyFrames[leftIndex];
- let rhs = this.keyFrames[rightIndex];
+ private calcOptimizedKey (optKey: OptimizedKey, leftIndex: number, rightIndex: number) {
+ const lhs = this.keyFrames![leftIndex];
+ const rhs = this.keyFrames![rightIndex];
optKey.index = leftIndex;
optKey.time = lhs.time;
optKey.endTime = rhs.time;
- let dx = rhs.time - lhs.time;
- let dy = rhs.value - lhs.value;
- let length = 1 / (dx * dx);
- let d1 = lhs.outTangent * dx;
- let d2 = rhs.inTangent * dx;
+ const dx = rhs.time - lhs.time;
+ const dy = rhs.value - lhs.value;
+ const length = 1 / (dx * dx);
+ const d1 = lhs.outTangent * dx;
+ const d2 = rhs.inTangent * dx;
optKey.coefficient[0] = (d1 + d2 - dy - dy) * length / dx;
optKey.coefficient[1] = (dy + dy + dy - d1 - d1 - d2) * length;
@@ -165,31 +173,31 @@ export class AnimationCurve {
optKey.coefficient[3] = lhs.value;
}
- findIndex(optKey, t) {
- let cachedIndex = optKey.index;
+ private findIndex (optKey: OptimizedKey, t: number) {
+ const cachedIndex = optKey.index;
if (cachedIndex !== -1) {
- let cachedTime = this.keyFrames[cachedIndex].time;
+ const cachedTime = this.keyFrames![cachedIndex].time;
if (t > cachedTime) {
for (let i = 0; i < LOOK_FORWARD; i++) {
- let currIndex = cachedIndex + i;
- if (currIndex + 1 < this.keyFrames.length && this.keyFrames[currIndex + 1].time > t) {
+ const currIndex = cachedIndex + i;
+ if (currIndex + 1 < this.keyFrames!.length && this.keyFrames![currIndex + 1].time > t) {
return currIndex;
}
}
} else {
for (let i = 0; i < LOOK_FORWARD; i++) {
- let currIndex = cachedIndex - i;
- if (currIndex >= 0 && this.keyFrames[currIndex - 1].time <= t) {
+ const currIndex = cachedIndex - i;
+ if (currIndex >= 0 && this.keyFrames![currIndex - 1].time <= t) {
return currIndex - 1;
}
}
}
}
let left = 0;
- let right = this.keyFrames.length;
+ let right = this.keyFrames!.length;
let mid = parseInt((left + right) / 2);
while (right - left > 1) {
- if (this.keyFrames[mid].time >= t) {
+ if (this.keyFrames![mid].time >= t) {
right = mid;
} else {
left = mid + 1;
@@ -203,5 +211,5 @@ export class AnimationCurve {
CCClass.fastDefine('cc.AnimationCurve', AnimationCurve, {
preWrapMode: WrapMode.Default,
postWrapMode: WrapMode.Default,
- keyFrames: []
+ keyFrames: [],
});
diff --git a/cocos/3d/geom-utils/frustum.js b/cocos/3d/geom-utils/frustum.js
deleted file mode 100644
index d75fa293fa..0000000000
--- a/cocos/3d/geom-utils/frustum.js
+++ /dev/null
@@ -1,119 +0,0 @@
-import enums from './enums';
-import plane from './plane';
-import { vec3 } from '../../core/vmath';
-
-let _v = new Array(8);
-_v[0] = vec3.create( 1, 1, 1);
-_v[1] = vec3.create(-1, 1, 1);
-_v[2] = vec3.create(-1, -1, 1);
-_v[3] = vec3.create( 1, -1, 1);
-_v[4] = vec3.create( 1, 1, -1);
-_v[5] = vec3.create(-1, 1, -1);
-_v[6] = vec3.create(-1, -1, -1);
-_v[7] = vec3.create( 1, -1, -1);
-
-export default class frustum {
- constructor() {
- this._type = enums.SHAPE_FRUSTUM;
- this.planes = new Array(6);
- for (let i = 0; i < 6; ++i) {
- this.planes[i] = plane.create();
- }
- this.vertices = new Array(8);
- for (let i = 0; i < 8; ++i) {
- this.vertices[i] = vec3.create();
- }
- }
-
- /**
- * create a new frustum
- *
- * @return {frustum}
- */
- static create() {
- return new frustum();
- }
-
- /**
- * Clone a frustum
- *
- * @param {frustum} f frustum to clone
- * @return {frustum} the new frustum
- */
- static clone(f) {
- return frustum.copy(new frustum(), f);
- }
-
- /**
- * Copy the values from one frustum to another
- *
- * @param {frustum} out the receiving frustum
- * @param {frustum} f the source frustum
- * @return {frustum}
- */
- static copy(out, f) {
- out._type = f._type;
- for (let i = 0; i < 6; ++i) {
- plane.copy(out.planes[i], f.planes[i]);
- }
- for (let i = 0; i < 8; ++i) {
- vec3.copy(out.vertices[i], f.vertices[i]);
- }
- return out;
- }
-
- /**
- * Set whether to use accurate intersection testing function on this frustum
- *
- * @param {boolean} b
- */
- set accurate(b) {
- this._type = b ? enums.SHAPE_FRUSTUM_ACCURATE : enums.SHAPE_FRUSTUM;
- }
-
- /**
- * Update the frustum information according to the given transform matrix.
- * Note that the resulting planes are not normalized under normal mode.
- *
- * @param {mat4} m the view-projection matrix
- * @param {mat4} inv the inverse view-projection matrix
- */
- update(m, inv) {
- // RTR4, ch. 22.14.1, p. 983
- // extract frustum planes from view-proj matrix.
-
- // left plane
- vec3.set(this.planes[0].n, m.m03 + m.m00, m.m07 + m.m04, m.m11 + m.m08);
- this.planes[0].d = -(m.m15 + m.m12);
- // right plane
- vec3.set(this.planes[1].n, m.m03 - m.m00, m.m07 - m.m04, m.m11 - m.m08);
- this.planes[1].d = -(m.m15 - m.m12);
- // bottom plane
- vec3.set(this.planes[2].n, m.m03 + m.m01, m.m07 + m.m05, m.m11 + m.m09);
- this.planes[2].d = -(m.m15 + m.m13);
- // top plane
- vec3.set(this.planes[3].n, m.m03 - m.m01, m.m07 - m.m05, m.m11 - m.m09);
- this.planes[3].d = -(m.m15 - m.m13);
- // near plane
- vec3.set(this.planes[4].n, m.m03 + m.m02, m.m07 + m.m06, m.m11 + m.m10);
- this.planes[4].d = -(m.m15 + m.m14);
- // far plane
- vec3.set(this.planes[5].n, m.m03 - m.m02, m.m07 - m.m06, m.m11 - m.m10);
- this.planes[5].d = -(m.m15 - m.m14);
-
- if (this._type !== enums.SHAPE_FRUSTUM_ACCURATE) return;
-
- // normalize planes
- for (let i = 0; i < 6; i++) {
- let plane = this.planes[i];
- let invDist = 1 / vec3.magnitude(plane.n);
- vec3.scale(plane.n, plane.n, invDist);
- plane.d *= invDist;
- }
-
- // update frustum vertices
- for (let i = 0; i < 8; i++) {
- vec3.transformMat4(this.vertices[i], _v[i], inv);
- }
- }
-}
diff --git a/cocos/3d/geom-utils/frustum.ts b/cocos/3d/geom-utils/frustum.ts
new file mode 100644
index 0000000000..26330d9e37
--- /dev/null
+++ b/cocos/3d/geom-utils/frustum.ts
@@ -0,0 +1,116 @@
+import { mat4, vec3 } from '../../core/vmath';
+import enums from './enums';
+import plane from './plane';
+
+const _v = new Array(8);
+_v[0] = vec3.create(1, 1, 1);
+_v[1] = vec3.create(-1, 1, 1);
+_v[2] = vec3.create(-1, -1, 1);
+_v[3] = vec3.create(1, -1, 1);
+_v[4] = vec3.create(1, 1, -1);
+_v[5] = vec3.create(-1, 1, -1);
+_v[6] = vec3.create(-1, -1, -1);
+_v[7] = vec3.create(1, -1, -1);
+
+// tslint:disable-next-line: class-name
+export class frustum {
+
+ /**
+ * Set whether to use accurate intersection testing function on this frustum
+ */
+ set accurate (b: boolean) {
+ this._type = b ? enums.SHAPE_FRUSTUM_ACCURATE : enums.SHAPE_FRUSTUM;
+ }
+
+ /**
+ * create a new frustum
+ *
+ * @return {frustum}
+ */
+ public static create () {
+ return new frustum();
+ }
+
+ /**
+ * Clone a frustum
+ */
+ public static clone (f: frustum): frustum {
+ return frustum.copy(new frustum(), f);
+ }
+
+ /**
+ * Copy the values from one frustum to another
+ */
+ public static copy (out: frustum, f: frustum): frustum {
+ out._type = f._type;
+ for (let i = 0; i < 6; ++i) {
+ plane.copy(out.planes[i], f.planes[i]);
+ }
+ for (let i = 0; i < 8; ++i) {
+ vec3.copy(out.vertices[i], f.vertices[i]);
+ }
+ return out;
+ }
+
+ public planes: plane[];
+ public vertices: vec3[];
+ private _type: number;
+
+ constructor () {
+ this._type = enums.SHAPE_FRUSTUM;
+ this.planes = new Array(6);
+ for (let i = 0; i < 6; ++i) {
+ this.planes[i] = plane.create();
+ }
+ this.vertices = new Array(8);
+ for (let i = 0; i < 8; ++i) {
+ this.vertices[i] = vec3.create();
+ }
+ }
+
+ /**
+ * Update the frustum information according to the given transform matrix.
+ * Note that the resulting planes are not normalized under normal mode.
+ *
+ * @param {mat4} m the view-projection matrix
+ * @param {mat4} inv the inverse view-projection matrix
+ */
+ public update (m: mat4, inv: mat4) {
+ // RTR4, ch. 22.14.1, p. 983
+ // extract frustum planes from view-proj matrix.
+
+ // left plane
+ vec3.set(this.planes[0].n, m.m03 + m.m00, m.m07 + m.m04, m.m11 + m.m08);
+ this.planes[0].d = -(m.m15 + m.m12);
+ // right plane
+ vec3.set(this.planes[1].n, m.m03 - m.m00, m.m07 - m.m04, m.m11 - m.m08);
+ this.planes[1].d = -(m.m15 - m.m12);
+ // bottom plane
+ vec3.set(this.planes[2].n, m.m03 + m.m01, m.m07 + m.m05, m.m11 + m.m09);
+ this.planes[2].d = -(m.m15 + m.m13);
+ // top plane
+ vec3.set(this.planes[3].n, m.m03 - m.m01, m.m07 - m.m05, m.m11 - m.m09);
+ this.planes[3].d = -(m.m15 - m.m13);
+ // near plane
+ vec3.set(this.planes[4].n, m.m03 + m.m02, m.m07 + m.m06, m.m11 + m.m10);
+ this.planes[4].d = -(m.m15 + m.m14);
+ // far plane
+ vec3.set(this.planes[5].n, m.m03 - m.m02, m.m07 - m.m06, m.m11 - m.m10);
+ this.planes[5].d = -(m.m15 - m.m14);
+
+ if (this._type !== enums.SHAPE_FRUSTUM_ACCURATE) { return; }
+
+ // normalize planes
+ for (let i = 0; i < 6; i++) {
+ const pl = this.planes[i];
+ const invDist = 1 / vec3.magnitude(pl.n);
+ vec3.scale(pl.n, pl.n, invDist);
+ pl.d *= invDist;
+ }
+
+ // update frustum vertices
+ for (let i = 0; i < 8; i++) {
+ vec3.transformMat4(this.vertices[i], _v[i], inv);
+ }
+ }
+}
diff --git a/cocos/3d/geom-utils/index.js b/cocos/3d/geom-utils/index.ts
similarity index 91%
rename from cocos/3d/geom-utils/index.js
rename to cocos/3d/geom-utils/index.ts
index 30b4011744..99bd86140e 100644
--- a/cocos/3d/geom-utils/index.js
+++ b/cocos/3d/geom-utils/index.ts
@@ -8,6 +8,6 @@ export { default as triangle } from './triangle';
export { default as sphere } from './sphere';
export { default as aabb } from './aabb';
export { default as obb } from './obb';
-export { default as frustum } from './frustum';
+export { frustum } from './frustum';
export { default as Octree } from './octree';
export { Keyframe, AnimationCurve } from './curve';
diff --git a/cocos/3d/index.js b/cocos/3d/index.js
index 8f70aeeed1..c3998ccf3c 100644
--- a/cocos/3d/index.js
+++ b/cocos/3d/index.js
@@ -27,9 +27,10 @@ export * from './assets';
export * from './builtin';
export * from './framework';
export * from './memop';
-import utils from './misc/utils';
+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/3d/memop/recycle-pool.js b/cocos/3d/memop/recycle-pool.js
deleted file mode 100644
index 98f8097312..0000000000
--- a/cocos/3d/memop/recycle-pool.js
+++ /dev/null
@@ -1,57 +0,0 @@
-import sort from './timsort';
-
-export default class RecyclePool {
- constructor(fn, size) {
- this._fn = fn;
- this._count = 0;
- this._data = new Array(size);
-
- for (let i = 0; i < size; ++i) {
- this._data[i] = fn();
- }
- }
-
- get length() {
- return this._count;
- }
-
- get data() {
- return this._data;
- }
-
- reset() {
- this._count = 0;
- }
-
- resize(size) {
- if (size > this._data.length) {
- for (let i = this._data.length; i < size; ++i) {
- this._data[i] = this._fn();
- }
- }
- }
-
- add() {
- if (this._count >= this._data.length) {
- this.resize(this._data.length * 2);
- }
-
- return this._data[this._count++];
- }
-
- remove(idx) {
- if (idx >= this._count) {
- return;
- }
-
- let last = this._count - 1;
- let tmp = this._data[idx];
- this._data[idx] = this._data[last];
- this._data[last] = tmp;
- this._count -= 1;
- }
-
- sort(cmp) {
- return sort(this._data, 0, this._count, cmp);
- }
-}
\ No newline at end of file
diff --git a/cocos/3d/memop/recycle-pool.ts b/cocos/3d/memop/recycle-pool.ts
new file mode 100644
index 0000000000..67f8b5a89f
--- /dev/null
+++ b/cocos/3d/memop/recycle-pool.ts
@@ -0,0 +1,72 @@
+import sort from './timsort';
+
+export default class RecyclePool {
+ private _fn: () => T;
+ private _count = 0;
+ private _data: T[];
+ private _objIdx: Map;
+
+ constructor (fn: () => T, size: number) {
+ this._fn = fn;
+ this._data = new Array(size);
+ this._objIdx = new Map();
+
+ for (let i = 0; i < size; ++i) {
+ this._data[i] = fn();
+ this._objIdx.set(this._data[i], i);
+ }
+ }
+
+ get length () {
+ return this._count;
+ }
+
+ get data () {
+ return this._data;
+ }
+
+ public reset () {
+ this._count = 0;
+ }
+
+ public resize (size: number) {
+ if (size > this._data.length) {
+ for (let i = this._data.length; i < size; ++i) {
+ this._data[i] = this._fn();
+ this._objIdx.set(this._data[i], i);
+ }
+ }
+ }
+
+ public add () {
+ if (this._count >= this._data.length) {
+ this.resize(this._data.length * 2);
+ }
+
+ return this._data[this._count++];
+ }
+
+ public removeAt (idx: number) {
+ if (idx >= this._count) {
+ return;
+ }
+
+ const last = this._count - 1;
+ const tmp = this._data[idx];
+ this._data[idx] = this._data[last];
+ this._data[last] = tmp;
+ this._objIdx.set(this._data[idx], idx);
+ this._objIdx.set(this._data[last], last);
+ this._count -= 1;
+ }
+
+ public remove (obj: T) {
+ if (this._objIdx.has(obj)) {
+ this.removeAt(this._objIdx.get(obj)!);
+ }
+ }
+
+ public sort (compare: (a: T, b: T) => number) {
+ return sort(this._data, 0, this._count, compare);
+ }
+}
diff --git a/cocos/3d/misc/utils.js b/cocos/3d/misc/utils.js
deleted file mode 100644
index f4f7bde08a..0000000000
--- a/cocos/3d/misc/utils.js
+++ /dev/null
@@ -1,67 +0,0 @@
-import { renderer } from '../../renderer';
-import find from '../../scene-graph/find';
-import Mesh from '../assets/mesh';
-import gfx from '../../renderer/gfx/index';
-
-/**
- *
- * @param {import("../assets/skeleton").default} skinning
- */
-function createJointsTexture(skinning) {
- const jointCount = skinning.joints.length;
-
- // Set jointsTexture.
- // A squared texture with side length N(N > 1) multiples of 2 can store
- // 2 ^ (2 * N - 2) matrices.
- // We support most 1024 joints.
- let size;
- if (jointCount > 1024) {
- throw "To many joints(more than 1024).";
- } else if (jointCount > 256) {
- size = 64;
- } else if (jointCount > 64) {
- size = 32;
- } else if (jointCount > 16) {
- size = 16;
- } else if (jointCount > 4) {
- size = 8;
- } else {
- size = 4;
- }
-
- return new gfx.Texture2D(cc.game._renderContext, {
- width: size,
- height: size,
- format: gfx.TEXTURE_FMT_RGBA32F,
- minFilter: gfx.FILTER_NEAREST,
- magFilter: gfx.FILTER_NEAREST,
- wrapS: gfx.WRAP_CLAMP,
- wrapT: gfx.WRAP_CLAMP,
- mipmap: false
- });
-}
-
-function createMesh(context, data) {
- let ia = renderer.createIA(context, data);
- let meshAsset = new Mesh();
- meshAsset._subMeshes = [ia];
- meshAsset._minPosition = data.minPos;
- meshAsset._maxPosition = data.maxPos;
-
- return meshAsset;
-}
-
-/**
- * @param {Uint8Array} buffer
- */
-function toPPM(buffer, w, h) {
- return `P3 ${w} ${h} 255\n${buffer.filter((e, i) => i % 4 < 3).toString()}\n`;
-}
-
-export default {
- createJointsTexture,
- createMesh,
-
- find,
- toPPM
-};
diff --git a/cocos/3d/misc/utils.ts b/cocos/3d/misc/utils.ts
new file mode 100644
index 0000000000..7b2e70722c
--- /dev/null
+++ b/cocos/3d/misc/utils.ts
@@ -0,0 +1,245 @@
+import { GFXAttributeName, GFXPrimitiveMode } from '../../gfx/define';
+export { default as find } from '../../scene-graph/find';
+import { Vec3 } from '../../core/value-types';
+import { AttributeBaseType, AttributeType,
+ IMeshStruct, IndexUnit, IPrimitive, IVertexAttribute, IVertexBundle, Mesh } from '../assets/mesh';
+import { IGeometry } from '../primitive/define';
+
+const copyAttribute = (attribute: IVertexAttribute) => Object.assign({}, attribute);
+export function createMesh (geometry: IGeometry) {
+ // Collect attributes and calculate length of result vertex buffer.
+ const attributes: IVertexAttribute[] = [];
+ let stride = 0;
+ const channels: Array<{ offset: number; data: number[]; attribute: IVertexAttribute; }> = [];
+ let verticesCount = 0;
+ const addAttribute = (attribute: IVertexAttribute, data: number[]) => {
+ const componentCount = _getComponentCount(attribute);
+ const componentBytesLength = _getComponentByteLength(attribute);
+ const bytesLength = componentBytesLength * componentCount;
+ attributes.push(attribute);
+ channels.push({ offset: stride, data, attribute });
+ stride += bytesLength;
+ verticesCount = Math.max(verticesCount, Math.floor(data.length / componentCount));
+ };
+ addAttribute(copyAttribute(predefinedAttributes.positions), geometry.positions);
+ if (geometry.normals) {
+ addAttribute(copyAttribute(predefinedAttributes.normals), geometry.normals);
+ }
+ if (geometry.uvs) {
+ addAttribute(copyAttribute(predefinedAttributes.uvs), geometry.uvs);
+ }
+ if (geometry.colors) {
+ addAttribute(copyAttribute(predefinedAttributes.colors), geometry.colors);
+ }
+
+ // Use this to generate final merged buffer.
+ const bufferBlob = new BufferBlob();
+
+ // Fill vertex buffer.
+ const vertexBuffer = new ArrayBuffer(verticesCount * stride);
+ const vertexBufferView = new DataView(vertexBuffer);
+ for (const channel of channels) {
+ _writeVertices(vertexBufferView, channel.offset, stride, channel.attribute, channel.data);
+ }
+ const vertexBundle: IVertexBundle = {
+ verticesCount,
+ attributes,
+ data: {
+ offset: bufferBlob.getLength(),
+ length: vertexBuffer.byteLength,
+ },
+ };
+ bufferBlob.addBuffer(vertexBuffer);
+
+ // Fill index buffer.
+ let indexBuffer: ArrayBuffer | null = null;
+ const targetIndexUnit = IndexUnit.UINT16;
+ if (geometry.indices) {
+ const { indices } = geometry;
+ const indexUnitBytesLength = 2;
+ indexBuffer = new ArrayBuffer(indexUnitBytesLength * indices.length);
+ const indexBufferView = new DataView(indexBuffer);
+ const writer = _getIndicesWriter(indexBufferView, targetIndexUnit);
+ for (let i = 0; i < indices.length; ++i) {
+ writer(indexUnitBytesLength * i, indices[i]);
+ }
+ }
+
+ // Create primitive.
+ const primitive: IPrimitive = {
+ primitiveMode: geometry.primitiveMode || GFXPrimitiveMode.TRIANGLE_LIST,
+ vertexBundelIndices: [0],
+ };
+ // geometric info for raycasting
+ if (primitive.primitiveMode >= GFXPrimitiveMode.TRIANGLE_LIST) {
+ const geomInfo = Float32Array.from(geometry.positions);
+ primitive.geometricInfo = {
+ doubleSided: geometry.doubleSided,
+ range: { offset: bufferBlob.getLength(), length: geomInfo.byteLength },
+ };
+ bufferBlob.addBuffer(geomInfo.buffer);
+ }
+
+ if (indexBuffer) {
+ primitive.indices = {
+ indexUnit: targetIndexUnit,
+ range: {
+ offset: bufferBlob.getLength(),
+ length: indexBuffer.byteLength,
+ },
+ };
+ bufferBlob.addBuffer(indexBuffer);
+ }
+
+ // Create mesh struct.
+ const meshStruct: IMeshStruct = {
+ vertexBundles: [vertexBundle],
+ primitives: [primitive],
+ minPosition: geometry.minPos && new Vec3(geometry.minPos.x, geometry.minPos.y, geometry.minPos.z),
+ maxPosition: geometry.maxPos && new Vec3(geometry.maxPos.x, geometry.maxPos.y, geometry.maxPos.z),
+ };
+
+ // Create mesh.
+ const mesh = new Mesh();
+ mesh.assign(meshStruct, new Uint8Array(bufferBlob.getCombined()));
+
+ return mesh;
+}
+
+/**
+ *
+ */
+export function toPPM (buffer: Uint8Array, w: number, h: number) {
+ return `P3 ${w} ${h} 255\n${buffer.filter((e, i) => i % 4 < 3).toString()}\n`;
+}
+
+const predefinedAttributes = {
+ positions: {
+ name: GFXAttributeName.ATTR_POSITION,
+ baseType: AttributeBaseType.FLOAT32,
+ type: AttributeType.VEC3,
+ normalize: false,
+ },
+ normals: {
+ name: GFXAttributeName.ATTR_NORMAL,
+ baseType: AttributeBaseType.FLOAT32,
+ type: AttributeType.VEC3,
+ normalize: false,
+ },
+ uvs: {
+ name: GFXAttributeName.ATTR_TEX_COORD,
+ baseType: AttributeBaseType.FLOAT32,
+ type: AttributeType.VEC2,
+ normalize: false,
+ },
+ colors: {
+ name: GFXAttributeName.ATTR_COLOR,
+ baseType: AttributeBaseType.FLOAT32,
+ type: AttributeType.VEC4,
+ normalize: false,
+ },
+};
+
+class BufferBlob {
+ private _arrayBuffers: ArrayBuffer[] = [];
+ private _length = 0;
+
+ public addBuffer (arrayBuffer: ArrayBuffer) {
+ const result = this._length;
+ this._arrayBuffers.push(arrayBuffer);
+ this._length += arrayBuffer.byteLength;
+ return result;
+ }
+
+ public getLength () {
+ return this._length;
+ }
+
+ public getCombined () {
+ let length = 0;
+ this._arrayBuffers.forEach((arrayBuffer) => length += arrayBuffer.byteLength);
+ const result = new Uint8Array(length);
+ let counter = 0;
+ this._arrayBuffers.forEach((arrayBuffer) => {
+ result.set(new Uint8Array(arrayBuffer), counter);
+ counter += arrayBuffer.byteLength;
+ });
+ return result.buffer;
+ }
+}
+
+function _writeVertices (
+ target: DataView, offset: number, stride: number, attribute: IVertexAttribute, data: number[]) {
+ const writer = _getVerticesWriter(target, attribute.baseType);
+ const componentCount = _getComponentCount(attribute);
+ const componentBytesLength = _getComponentByteLength(attribute);
+ const nVertices = Math.floor(data.length / componentCount);
+
+ for (let iVertex = 0; iVertex < nVertices; ++iVertex) {
+ const x = offset + stride * iVertex;
+ for (let iComponent = 0; iComponent < componentCount; ++iComponent) {
+ const y = x + componentBytesLength * iComponent;
+ writer(y, data[componentCount * iVertex + iComponent]);
+ }
+ }
+}
+
+function _getComponentByteLength (vertexAttribute: IVertexAttribute) {
+ switch (vertexAttribute.baseType) {
+ case AttributeBaseType.INT8:
+ case AttributeBaseType.UINT8:
+ return 1;
+ case AttributeBaseType.INT16:
+ case AttributeBaseType.UINT16:
+ return 2;
+ case AttributeBaseType.INT32:
+ case AttributeBaseType.UINT32:
+ case AttributeBaseType.FLOAT32:
+ return 4;
+ }
+ return 1;
+}
+
+function _getComponentCount (vertexAttribute: IVertexAttribute) {
+ switch (vertexAttribute.type) {
+ case AttributeType.SCALAR: return 1;
+ case AttributeType.VEC2: return 2;
+ case AttributeType.VEC3: return 3;
+ case AttributeType.VEC4: return 4;
+ }
+ return 1;
+}
+
+const isLittleEndian = cc.sys.isLittleEndian;
+
+function _getVerticesWriter (dataView: DataView, baseType: AttributeBaseType) {
+ switch (baseType) {
+ case AttributeBaseType.INT8:
+ return (offset: number, value: number) => dataView.setInt8(offset, value);
+ case AttributeBaseType.UINT8:
+ return (offset: number, value: number) => dataView.setUint8(offset, value);
+ case AttributeBaseType.INT16:
+ return (offset: number, value: number) => dataView.setInt16(offset, value, isLittleEndian);
+ case AttributeBaseType.UINT16:
+ return (offset: number, value: number) => dataView.setUint16(offset, value, isLittleEndian);
+ case AttributeBaseType.INT32:
+ return (offset: number, value: number) => dataView.setInt32(offset, value, isLittleEndian);
+ case AttributeBaseType.UINT32:
+ return (offset: number, value: number) => dataView.setUint32(offset, value, isLittleEndian);
+ case AttributeBaseType.FLOAT32:
+ return (offset: number, value: number) => dataView.setFloat32(offset, value, isLittleEndian);
+ }
+ return (offset: number, value: number) => dataView.setUint8(offset, value);
+}
+
+function _getIndicesWriter (dataView: DataView, indexUnit: IndexUnit) {
+ switch (indexUnit) {
+ case IndexUnit.UINT8:
+ return (offset: number, value: number) => dataView.setUint8(offset, value);
+ case IndexUnit.UINT16:
+ return (offset: number, value: number) => dataView.setUint16(offset, value, isLittleEndian);
+ case IndexUnit.UINT32:
+ return (offset: number, value: number) => dataView.setUint32(offset, value, isLittleEndian);
+ }
+ return (offset: number, value: number) => dataView.setUint8(offset, value);
+}
diff --git a/cocos/3d/primitive/box.js b/cocos/3d/primitive/box.js
deleted file mode 100644
index e9aa1b0873..0000000000
--- a/cocos/3d/primitive/box.js
+++ /dev/null
@@ -1,130 +0,0 @@
-'use strict';
-
-import { vec3 } from '../../core/vmath';
-
-let temp1 = vec3.create(0, 0, 0);
-let temp2 = vec3.create(0, 0, 0);
-let temp3 = vec3.create(0, 0, 0);
-let r = vec3.create(0, 0, 0);
-let c0 = vec3.create(0, 0, 0);
-let c1 = vec3.create(0, 0, 0);
-let c2 = vec3.create(0, 0, 0);
-let c3 = vec3.create(0, 0, 0);
-let c4 = vec3.create(0, 0, 0);
-let c5 = vec3.create(0, 0, 0);
-let c6 = vec3.create(0, 0, 0);
-let c7 = vec3.create(0, 0, 0);
-
-/**
- * @param {Number} width
- * @param {Number} height
- * @param {Number} length
- * @param {Object} opts
- * @param {Number} opts.widthSegments
- * @param {Number} opts.heightSegments
- * @param {Number} opts.lengthSegments
- */
-export default function (width = 1, height = 1, length = 1, opts = {}) {
- let ws = opts.widthSegments !== undefined ? opts.widthSegments : 1;
- let hs = opts.heightSegments !== undefined ? opts.heightSegments : 1;
- let ls = opts.lengthSegments !== undefined ? opts.lengthSegments : 1;
- let inv = opts.invWinding !== undefined ? opts.invWinding : false;
-
- let hw = width * 0.5;
- let hh = height * 0.5;
- let hl = length * 0.5;
-
- let corners = [
- vec3.set(c0, -hw, -hh, hl),
- vec3.set(c1, hw, -hh, hl),
- vec3.set(c2, hw, hh, hl),
- vec3.set(c3, -hw, hh, hl),
- vec3.set(c4, hw, -hh, -hl),
- vec3.set(c5, -hw, -hh, -hl),
- vec3.set(c6, -hw, hh, -hl),
- vec3.set(c7, hw, hh, -hl),
- ];
-
- let faceAxes = [
- [ 2, 3, 1 ], // FRONT
- [ 4, 5, 7 ], // BACK
- [ 7, 6, 2 ], // TOP
- [ 1, 0, 4 ], // BOTTOM
- [ 1, 4, 2 ], // RIGHT
- [ 5, 0, 6 ] // LEFT
- ];
-
- let faceNormals = [
- [ 0, 0, 1 ], // FRONT
- [ 0, 0, -1 ], // BACK
- [ 0, 1, 0 ], // TOP
- [ 0, -1, 0 ], // BOTTOM
- [ 1, 0, 0 ], // RIGHT
- [ -1, 0, 0 ] // LEFT
- ];
-
- let positions = [];
- let normals = [];
- let uvs = [];
- let indices = [];
- let minPos = vec3.create(-hw, -hh, -hl);
- let maxPos = vec3.create(hw, hh, hl);
- let boundingRadius = Math.sqrt(hw * hw + hh * hh + hl * hl);
-
- function _buildPlane (side, uSegments, vSegments) {
- let u, v;
- let ix, iy;
- let offset = positions.length / 3;
- let faceAxe = faceAxes[side];
- let faceNormal = faceNormals[side];
-
- for (iy = 0; iy <= vSegments; iy++) {
- for (ix = 0; ix <= uSegments; ix++) {
- u = ix / uSegments;
- v = iy / vSegments;
-
- vec3.lerp(temp1, corners[faceAxe[0]], corners[faceAxe[1]], u);
- vec3.lerp(temp2, corners[faceAxe[0]], corners[faceAxe[2]], v);
- vec3.sub(temp3, temp2, corners[faceAxe[0]]);
- vec3.add(r, temp1, temp3);
-
- positions.push(r.x, r.y, r.z);
- normals.push(faceNormal[0], faceNormal[1], faceNormal[2]);
- uvs.push(u, v);
-
- if ((ix < uSegments) && (iy < vSegments)) {
- let useg1 = uSegments + 1;
- let a = ix + iy * useg1;
- let b = ix + (iy + 1) * useg1;
- let c = (ix + 1) + (iy + 1) * useg1;
- let d = (ix + 1) + iy * useg1;
-
- if (inv) {
- indices.push(offset + a, offset + b, offset + d);
- indices.push(offset + d, offset + b, offset + c);
- } else {
- indices.push(offset + a, offset + d, offset + b);
- indices.push(offset + b, offset + d, offset + c);
- }
- }
- }
- }
- }
-
- _buildPlane(0, ws, hs); // FRONT
- _buildPlane(4, ls, hs); // RIGHT
- _buildPlane(1, ws, hs); // BACK
- _buildPlane(5, ls, hs); // LEFT
- _buildPlane(3, ws, ls); // BOTTOM
- _buildPlane(2, ws, ls); // TOP
-
- return {
- positions,
- normals,
- uvs,
- indices,
- minPos,
- maxPos,
- boundingRadius
- };
-}
diff --git a/cocos/3d/primitive/box.ts b/cocos/3d/primitive/box.ts
new file mode 100644
index 0000000000..e67755f41c
--- /dev/null
+++ b/cocos/3d/primitive/box.ts
@@ -0,0 +1,155 @@
+import { Vec3 } from '../../core/value-types';
+import { vec3 } from '../../core/vmath';
+import { IGeometry, IGeometryOptions } from './define';
+
+interface IBoxOptions extends RecursivePartial {
+ /**
+ * Box extent on X-axis.
+ */
+ width?: number;
+
+ /**
+ * Box extent on Y-axis.
+ */
+ height?: number;
+
+ /**
+ * Box extent on Z-axis.
+ */
+ length?: number;
+
+ /**
+ * Segment count on X-axis.
+ */
+ widthSegments?: number;
+
+ /**
+ * Segment count on Y-axis.
+ */
+ heightSegments?: number;
+
+ /**
+ * Segment count on Z-axis.
+ */
+ lengthSegments?: number;
+}
+
+/**
+ * This function generates a box with specified extents and centered at origin,
+ * but may be repositioned through `center` option).
+ * @param options Options.
+ */
+export default function box (options?: IBoxOptions): IGeometry {
+ options = options || {};
+ const ws = options.widthSegments || 1;
+ const hs = options.heightSegments || 1;
+ const ls = options.lengthSegments || 1;
+
+ const hw = (options.width || 1) / 2;
+ const hh = (options.height || 1) / 2;
+ const hl = (options.length || 1) / 2;
+
+ const corners = [
+ vec3.set(c0, -hw, -hh, hl),
+ vec3.set(c1, hw, -hh, hl),
+ vec3.set(c2, hw, hh, hl),
+ vec3.set(c3, -hw, hh, hl),
+ vec3.set(c4, hw, -hh, -hl),
+ vec3.set(c5, -hw, -hh, -hl),
+ vec3.set(c6, -hw, hh, -hl),
+ vec3.set(c7, hw, hh, -hl),
+ ];
+
+ const faceAxes = [
+ [2, 3, 1], // FRONT
+ [4, 5, 7], // BACK
+ [7, 6, 2], // TOP
+ [1, 0, 4], // BOTTOM
+ [1, 4, 2], // RIGHT
+ [5, 0, 6], // LEFT
+ ];
+
+ const faceNormals = [
+ [0, 0, 1], // FRONT
+ [0, 0, -1], // BACK
+ [0, 1, 0], // TOP
+ [0, -1, 0], // BOTTOM
+ [1, 0, 0], // RIGHT
+ [-1, 0, 0], // LEFT
+ ];
+
+ const positions: number[] = [];
+ const normals: number[] = [];
+ const uvs: number[] = [];
+ const indices: number[] = [];
+ const minPos = new Vec3(-hw, -hh, -hl);
+ const maxPos = new Vec3(hw, hh, hl);
+ const boundingRadius = Math.sqrt(hw * hw + hh * hh + hl * hl);
+
+ function _buildPlane (side: number, uSegments: number, vSegments: number) {
+ let u: number;
+ let v: number;
+ let ix: number;
+ let iy: number;
+ const offset = positions.length / 3;
+ const faceAxe = faceAxes[side];
+ const faceNormal = faceNormals[side];
+
+ for (iy = 0; iy <= vSegments; iy++) {
+ for (ix = 0; ix <= uSegments; ix++) {
+ u = ix / uSegments;
+ v = iy / vSegments;
+
+ vec3.lerp(temp1, corners[faceAxe[0]], corners[faceAxe[1]], u);
+ vec3.lerp(temp2, corners[faceAxe[0]], corners[faceAxe[2]], v);
+ vec3.sub(temp3, temp2, corners[faceAxe[0]]);
+ vec3.add(r, temp1, temp3);
+
+ positions.push(r.x, r.y, r.z);
+ normals.push(faceNormal[0], faceNormal[1], faceNormal[2]);
+ uvs.push(u, v);
+
+ if ((ix < uSegments) && (iy < vSegments)) {
+ const useg1 = uSegments + 1;
+ const a = ix + iy * useg1;
+ const b = ix + (iy + 1) * useg1;
+ const c = (ix + 1) + (iy + 1) * useg1;
+ const d = (ix + 1) + iy * useg1;
+
+ indices.push(offset + a, offset + d, offset + b);
+ indices.push(offset + b, offset + d, offset + c);
+ }
+ }
+ }
+ }
+
+ _buildPlane(0, ws, hs); // FRONT
+ _buildPlane(4, ls, hs); // RIGHT
+ _buildPlane(1, ws, hs); // BACK
+ _buildPlane(5, ls, hs); // LEFT
+ _buildPlane(3, ws, ls); // BOTTOM
+ _buildPlane(2, ws, ls); // TOP
+
+ return {
+ positions,
+ normals,
+ uvs,
+ indices,
+ minPos,
+ maxPos,
+ boundingRadius,
+ };
+}
+
+const temp1 = new Vec3();
+const temp2 = new Vec3();
+const temp3 = new Vec3();
+const r = new Vec3();
+const c0 = new Vec3();
+const c1 = new Vec3();
+const c2 = new Vec3();
+const c3 = new Vec3();
+const c4 = new Vec3();
+const c5 = new Vec3();
+const c6 = new Vec3();
+const c7 = new Vec3();
diff --git a/cocos/3d/primitive/circle.ts b/cocos/3d/primitive/circle.ts
new file mode 100644
index 0000000000..eb20f37dc5
--- /dev/null
+++ b/cocos/3d/primitive/circle.ts
@@ -0,0 +1,56 @@
+import { GFXPrimitiveMode } from '../../gfx/define';
+import { applyDefaultGeometryOptions, IGeometry, IGeometryOptions } from './define';
+
+interface ICircleOptions extends IGeometryOptions {
+ // The segments. Default to 64.
+ segments: number;
+}
+
+function applyDefaultCircleOptions (options?: RecursivePartial): ICircleOptions {
+ options = applyDefaultGeometryOptions(options);
+ options.segments = 64;
+ return options as ICircleOptions;
+}
+
+/**
+ * Generate a circle with radius 1, centered at origin.
+ * @param options Options.
+ */
+export default function circle (options?: RecursivePartial | ICircleOptions): IGeometry {
+ const normalizedOptions = applyDefaultCircleOptions(options);
+ const segments = normalizedOptions.segments;
+
+ const positions = new Array(3 * (segments + 1));
+ positions[0] = 0;
+ positions[1] = 0;
+ positions[2] = 0;
+ const indices = new Array(1 + segments * 2);
+ indices[0] = 0;
+ const step = Math.PI * 2 / segments;
+ for (let iSegment = 0; iSegment < segments; ++iSegment) {
+ const angle = step * iSegment;
+ const x = Math.cos(angle);
+ const y = Math.sin(angle);
+ const p = (iSegment + 1) * 3;
+ positions[p + 0] = x;
+ positions[p + 1] = y;
+ positions[p + 2] = 0;
+ const i = iSegment * 2;
+ indices[1 + (i)] = iSegment + 1;
+ indices[1 + (i + 1)] = iSegment + 2;
+ }
+ if (segments > 0) {
+ indices[indices.length - 1] = 1;
+ }
+
+ const result: IGeometry = {
+ positions,
+ indices,
+ minPos: { x: 1, y: 1, z: 0 },
+ maxPos: { x: -1, y: -1, z: 0 },
+ boundingRadius: 1,
+ primitiveMode: GFXPrimitiveMode.TRIANGLE_FAN,
+ };
+
+ return result;
+}
diff --git a/cocos/3d/primitive/define.ts b/cocos/3d/primitive/define.ts
new file mode 100644
index 0000000000..b4f555e759
--- /dev/null
+++ b/cocos/3d/primitive/define.ts
@@ -0,0 +1,85 @@
+import { GFXPrimitiveMode } from '../../gfx/define';
+
+export interface IGeometryOptions {
+ /**
+ * Whether to include normal. Default to true.
+ */
+ includeNormal: boolean;
+
+ /**
+ * Whether to include uv. Default to true.
+ */
+ includeUV: boolean;
+}
+
+export function applyDefaultGeometryOptions (
+ options?: RecursivePartial): GeometryOptions {
+ options = options || {};
+ if (options.includeNormal === undefined) {
+ options.includeNormal = true;
+ }
+ if (options.includeUV === undefined) {
+ options.includeUV = true;
+ }
+ return options as GeometryOptions;
+}
+
+export interface IGeometry {
+ /**
+ * Vertex positions.
+ */
+ positions: number[];
+
+ /**
+ * Min position.
+ */
+ minPos: {
+ x: number;
+ y: number;
+ z: number;
+ };
+
+ /**
+ * Max position.
+ */
+ maxPos: {
+ x: number;
+ y: number;
+ z: number;
+ };
+
+ /**
+ * Bounding sphere radius.
+ */
+ boundingRadius: number;
+
+ /**
+ * Gemetry indices, if one needs indexed-draw.
+ */
+ indices?: number[];
+
+ /**
+ * Vertex normals.
+ */
+ normals?: number[];
+
+ /**
+ * Texture coordinates.
+ */
+ uvs?: number[];
+
+ /**
+ * Vertex colors.
+ */
+ colors?: number[];
+
+ /**
+ * Topology of the geometry vertices. Default is TRIANGLE_LIST.
+ */
+ primitiveMode?: GFXPrimitiveMode;
+
+ /**
+ * whether rays casting from the back face of this geometry could collide with it
+ */
+ doubleSided?: boolean;
+}
diff --git a/cocos/3d/primitive/index.js b/cocos/3d/primitive/index.ts
similarity index 70%
rename from cocos/3d/primitive/index.js
rename to cocos/3d/primitive/index.ts
index f69ede2753..9d77900f62 100644
--- a/cocos/3d/primitive/index.js
+++ b/cocos/3d/primitive/index.ts
@@ -6,4 +6,6 @@ export { default as plane } from './plane';
export { default as quad } from './quad';
export { default as sphere } from './sphere';
export { default as torus } from './torus';
-export { default as capsule } from './capsule';
\ No newline at end of file
+export { default as capsule } from './capsule';
+export { default as circle } from './circle';
+export { translate, scale } from './transform';
\ No newline at end of file
diff --git a/cocos/3d/primitive/quad.js b/cocos/3d/primitive/quad.js
deleted file mode 100644
index 503702c5a0..0000000000
--- a/cocos/3d/primitive/quad.js
+++ /dev/null
@@ -1,46 +0,0 @@
-'use strict';
-
-import { vec3 } from '../../core/vmath';
-
-let positions = [
- -0.5, -0.5, 0, // bottom-left
- -0.5, 0.5, 0, // top-left
- 0.5, 0.5, 0, // top-right
- 0.5, -0.5, 0, // bottom-right
-];
-
-let normals = [
- 0, 0, 1,
- 0, 0, 1,
- 0, 0, 1,
- 0, 0, 1,
-];
-
-let uvs = [
- 0, 0,
- 0, 1,
- 1, 1,
- 1, 0,
-];
-
-let indices = [
- 0, 3, 1,
- 3, 2, 1
-];
-
-// TODO: ?
-let minPos = vec3.create(-0.5, -0.5, 0);
-let maxPos = vec3.create(0.5, 0.5, 0);
-let boundingRadius = Math.sqrt(0.5 * 0.5 + 0.5 * 0.5);
-
-export default function () {
- return {
- positions,
- indices,
- normals,
- uvs,
- minPos,
- maxPos,
- boundingRadius
- };
-}
diff --git a/cocos/3d/primitive/quad.ts b/cocos/3d/primitive/quad.ts
new file mode 100644
index 0000000000..a142a6cd8d
--- /dev/null
+++ b/cocos/3d/primitive/quad.ts
@@ -0,0 +1,47 @@
+'use strict';
+
+import { applyDefaultGeometryOptions, IGeometry, IGeometryOptions } from './define';
+
+/**
+ * Generate a quad with width and height both to 1, centered at origin.
+ * @param options Options.
+ */
+export default function quad (options?: IGeometryOptions): IGeometry {
+ const normalizedOptions = applyDefaultGeometryOptions(options);
+ const result: IGeometry = {
+ positions: [
+ -0.5, -0.5, 0, // bottom-left
+ -0.5, 0.5, 0, // top-left
+ 0.5, 0.5, 0, // top-right
+ 0.5, -0.5, 0, // bottom-right
+ ],
+ indices: [
+ 0, 3, 1,
+ 3, 2, 1,
+ ],
+ minPos: {
+ x: -0.5, y: -0.5, z: 0,
+ },
+ maxPos: {
+ x: 0.5, y: 0.5, z: 0,
+ },
+ boundingRadius: Math.sqrt(0.5 * 0.5 + 0.5 * 0.5),
+ };
+ if (normalizedOptions.includeNormal !== false) {
+ result.normals = [
+ 0, 0, 1,
+ 0, 0, 1,
+ 0, 0, 1,
+ 0, 0, 1,
+ ];
+ }
+ if (normalizedOptions.includeUV !== false) {
+ result.uvs = [
+ 0, 0,
+ 0, 1,
+ 1, 1,
+ 1, 0,
+ ];
+ }
+ return result;
+}
diff --git a/cocos/3d/primitive/sphere.js b/cocos/3d/primitive/sphere.js
index f7e1037801..9e22d56bce 100644
--- a/cocos/3d/primitive/sphere.js
+++ b/cocos/3d/primitive/sphere.js
@@ -1,6 +1,7 @@
'use strict';
import { vec3 } from '../../core/vmath';
+import { GFXPrimitiveMode } from '../../gfx/define';
/**
* @param {Number} radius
diff --git a/cocos/3d/primitive/transform.ts b/cocos/3d/primitive/transform.ts
new file mode 100644
index 0000000000..57eb6bd39f
--- /dev/null
+++ b/cocos/3d/primitive/transform.ts
@@ -0,0 +1,46 @@
+import { IGeometry } from './define';
+
+export function translate (geometry: IGeometry, offset: { x?: number; y?: number; z?: number; }) {
+ const x = offset.x || 0;
+ const y = offset.y || 0;
+ const z = offset.z || 0;
+ const nVertex = Math.floor(geometry.positions.length / 3);
+ for (let iVertex = 0; iVertex < nVertex; ++iVertex) {
+ const iX = iVertex * 3;
+ const iY = iVertex * 3 + 1;
+ const iZ = iVertex * 3 + 2;
+ geometry.positions[iX] = geometry.positions[iX] + x;
+ geometry.positions[iY] = geometry.positions[iY] + y;
+ geometry.positions[iZ] = geometry.positions[iZ] + z;
+ }
+ geometry.minPos.x += x;
+ geometry.minPos.y += y;
+ geometry.minPos.z += z;
+ geometry.maxPos.x += x;
+ geometry.maxPos.y += y;
+ geometry.maxPos.z += z;
+ return geometry;
+}
+
+export function scale (geometry: IGeometry, value: { x?: number; y?: number; z?: number }) {
+ const x = value.x || 0;
+ const y = value.y || 0;
+ const z = value.z || 0;
+ const nVertex = Math.floor(geometry.positions.length / 3);
+ for (let iVertex = 0; iVertex < nVertex; ++iVertex) {
+ const iX = iVertex * 3;
+ const iY = iVertex * 3 + 1;
+ const iZ = iVertex * 3 + 2;
+ geometry.positions[iX] *= x;
+ geometry.positions[iY] *= y;
+ geometry.positions[iZ] *= z;
+ }
+ geometry.minPos.x *= x;
+ geometry.minPos.y *= y;
+ geometry.minPos.z *= z;
+ geometry.maxPos.x *= x;
+ geometry.maxPos.y *= y;
+ geometry.maxPos.z *= z;
+ geometry.boundingRadius = Math.max(Math.max(x, y), z);
+ return geometry;
+}
diff --git a/cocos/3d/ui/assembler/assembler.ts b/cocos/3d/ui/assembler/assembler.ts
new file mode 100644
index 0000000000..ed8d1ed208
--- /dev/null
+++ b/cocos/3d/ui/assembler/assembler.ts
@@ -0,0 +1,39 @@
+/****************************************************************************
+ 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 { UIRenderComponent } from '../components/ui-render-component';
+import { RenderData } from '../../../renderer/ui/renderData';
+import { UI } from '../../../renderer/ui/ui';
+
+export interface IAssembler {
+
+ useModel: boolean;
+ fillBuffers (component: UIRenderComponent, render: UI): void;
+ updateRenderData (component: UIRenderComponent): void;
+ createData (component: UIRenderComponent): RenderData;
+ updateVerts (component: UIRenderComponent, start?: number, end?: number): void;
+ updateWorldVerts? (component: UIRenderComponent): void;
+ updateUVs?(component: UIRenderComponent, start?: number, end?: number);
+}
diff --git a/cocos/2d/renderer/webgl/assemblers/assembler.js b/cocos/3d/ui/assembler/index.ts
similarity index 89%
rename from cocos/2d/renderer/webgl/assemblers/assembler.js
rename to cocos/3d/ui/assembler/index.ts
index b9096953f6..3f8c710bb4 100644
--- a/cocos/2d/renderer/webgl/assemblers/assembler.js
+++ b/cocos/3d/ui/assembler/index.ts
@@ -23,7 +23,9 @@
THE SOFTWARE.
****************************************************************************/
-module.exports = {
- useModel: false,
- datas: []
-};
\ No newline at end of file
+// require('./sprite');
+// require('./mask-assembler');
+// require('./graphics');
+import './label/index';
+import './sprite/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.ts
similarity index 74%
rename from cocos/2d/renderer/webgl/assemblers/label/index.js
rename to cocos/3d/ui/assembler/label/index.ts
index fe44c9af4d..9e79489c73 100644
--- a/cocos/2d/renderer/webgl/assemblers/label/index.js
+++ b/cocos/3d/ui/assembler/label/index.ts
@@ -23,27 +23,32 @@
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 { ttf } from './ttf';
+// import bmfontAssembler from './bmfont';
-var labelAssembler = {
+const labelAssembler = {
getAssembler (comp) {
- let assembler = ttfAssembler;
-
+ const assembler = ttf;
+
if (comp.font instanceof cc.BitmapFont) {
- assembler = bmfontAssembler;
+ // assembler = bmfontAssembler;
}
return assembler;
},
// Skip invalid labels (without own _assembler)
- updateRenderData (label) {
- return label.__allocedDatas;
- }
+ // updateRenderData(label) {
+ // return label.__allocedDatas;
+ // }
};
-Label._assembler = labelAssembler;
+export {
+ labelAssembler,
+};
-module.exports = labelAssembler;
\ No newline at end of file
+LabelComponent.Assembler = labelAssembler;
diff --git a/cocos/3d/ui/assembler/label/ttf.ts b/cocos/3d/ui/assembler/label/ttf.ts
new file mode 100644
index 0000000000..edd7a7a8a4
--- /dev/null
+++ b/cocos/3d/ui/assembler/label/ttf.ts
@@ -0,0 +1,85 @@
+/****************************************************************************
+ 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 ttfUtls from '../../../../2d/renderer/utils/label/ttf';
+import * as js from '../../../../core/utils/js';
+import { RenderData } from '../../../../renderer/ui/renderData';
+import { UI } from '../../../../renderer/ui/ui';
+import { LabelComponent } from '../../components/label-component';
+import { IAssembler} from '../assembler';
+import { fillMeshVertices3D } from '../utils';
+
+const WHITE = cc.color(255, 255, 255, 255);
+
+export const ttf: IAssembler = {
+ useModel: false,
+
+ createData (comp: LabelComponent) {
+ const renderData: RenderData|null = comp.requestRenderData();
+
+ renderData!.dataLength = 4;
+ renderData!.vertexCount = 4;
+ renderData!.indiceCount = 6;
+
+ const datas = renderData!.datas;
+ datas[0].u = 0;
+ datas[0].v = 1;
+ datas[1].u = 1;
+ datas[1].v = 1;
+ datas[2].u = 0;
+ datas[2].v = 0;
+ datas[3].u = 1;
+ datas[3].v = 0;
+ return renderData as RenderData;
+ },
+
+ fillBuffers (comp: LabelComponent, /*renderer*/buffer: UI) {
+ fillMeshVertices3D(comp.node, /*renderer._quadBuffer3D*/buffer, comp.renderData, WHITE);
+ },
+
+ updateVerts (comp: LabelComponent) {
+ const renderData: RenderData|null = comp.renderData;
+
+ const node = comp.node;
+ const width = node.width;
+ const height = node.height;
+ const appx = node.anchorX * width;
+ const appy = node.anchorY * height;
+
+ const datas = renderData!.datas;
+ datas[0].x = -appx;
+ datas[0].y = -appy;
+ datas[1].x = width - appx;
+ datas[1].y = -appy;
+ datas[2].x = -appx;
+ datas[2].y = height - appy;
+ datas[3].x = width - appx;
+ datas[3].y = height - appy;
+ },
+
+ updateRenderData (comp: LabelComponent) {},
+};
+
+js.addon(ttf, ttfUtls);
diff --git a/cocos/3d/ui/assembler/mask-assembler.ts b/cocos/3d/ui/assembler/mask-assembler.ts
new file mode 100644
index 0000000000..2b2f09747f
--- /dev/null
+++ b/cocos/3d/ui/assembler/mask-assembler.ts
@@ -0,0 +1,213 @@
+/****************************************************************************
+ 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 { vec3 } from '../../../core/vmath';
+import { GFXComparisonFunc, GFXStencilOp } from '../../../gfx/define';
+import { IUIRenderData, UI } from '../../../renderer/ui/ui';
+import { Material } from '../../assets/material';
+import { IGeometry } from '../../primitive/define';
+import { MaskComponent } from '../components/mask-component';
+import { IAssembler } from './assembler';
+
+interface IStencilState {
+ stencilTest?: boolean;
+ func?: GFXComparisonFunc;
+ readMask?: number;
+ writeMask?: number;
+ failOp?: GFXStencilOp;
+ zFailOp?: GFXStencilOp;
+ passOp?: GFXStencilOp;
+ ref?: number;
+}
+
+interface IStencilStateUpdate {
+ func: GFXComparisonFunc;
+ writeMask: number;
+ ref: number;
+}
+
+function overrideStencilState (material: Material, state: IStencilState) {
+ material.overridePipelineStates({
+ depthStencilState: {
+ stencilTestFront: state.stencilTest,
+ stencilFuncFront: state.func,
+ stencilReadMaskFront: state.readMask,
+ stencilWriteMaskFront: state.writeMask,
+ stencilFailOpFront: state.failOp,
+ stencilZFailOpFront: state.zFailOp,
+ stencilPassOpFront: state.passOp,
+ stencilRefFront: state.ref,
+ stencilTestBack: state.stencilTest,
+ stencilFuncBack: state.func,
+ stencilReadMaskBack: state.readMask,
+ stencilWriteMaskBack: state.writeMask,
+ stencilFailOpBack: state.failOp,
+ stencilZFailOpBack: state.zFailOp,
+ stencilPassOpBack: state.passOp,
+ stencilRefBack: state.ref,
+ },
+ });
+}
+
+function updateDynamicStencilStates (material: Material, state: IStencilStateUpdate) {
+
+}
+
+class StencilManager {
+ private _maskStack: MaskComponent[] = [];
+
+ public enter (mask: MaskComponent) {
+ this._maskStack.push(mask);
+ }
+
+ public exit () {
+ this._maskStack.pop();
+ }
+
+ public updateMaskMaterial (material: Material) {
+ updateDynamicStencilStates(material, {
+ func: GFXComparisonFunc.ALWAYS,
+ writeMask: this._protectAncestorMasks(),
+ ref: this._getWriteMaskForTopMask(),
+ });
+ }
+
+ public updateClearMaskMaterial (material: Material) {
+ updateDynamicStencilStates(material, {
+ func: GFXComparisonFunc.ALWAYS,
+ writeMask: this._protectAncestorMasks(),
+ ref: 0,
+ });
+ }
+
+ private _readAncestorMasks (): number {
+ let result = 0;
+ this._maskStack.forEach((mask, iBit) => {
+ result |= (1 << iBit);
+ });
+ return result;
+ }
+
+ private _protectAncestorMasks (): number {
+ return ~this._readAncestorMasks();
+ }
+
+ private _getWriteMaskForTopMask (): number {
+ return 1 << this._maskStack.length;
+ }
+}
+
+const stencilManager = new StencilManager();
+
+export const maskAssembler: IAssembler = {
+ fillBuffers (mask: MaskComponent, ui: UI) {
+ stencilManager.enter(mask);
+
+ const maskGeometry = mask._getMaskGeometry();
+ const maskMaterial = mask._getMaskMaterial();
+ if (maskGeometry && maskMaterial) {
+ const meshBuffer = createMeshBuffer(ui, maskGeometry);
+ const nVert = Math.floor(maskGeometry.positions.length / 3);
+ const v = new vec3();
+ const worldMatrix = mask.node.getWorldMatrix();
+ for (let i = 0; i < nVert; ++i) {
+ vec3.set(v,
+ maskGeometry.positions[3 * i + 0],
+ maskGeometry.positions[3 * i + 1],
+ maskGeometry.positions[3 * i + 2]);
+ vec3.transformMat4(v, v, worldMatrix);
+ meshBuffer.vData![3 * i + 0] = v.x;
+ meshBuffer.vData![3 * i + 1] = v.y;
+ meshBuffer.vData![3 * i + 2] = v.z;
+ }
+ const maskRenderData = ui.createUIRenderData() as IUIRenderData;
+ maskRenderData.meshBuffer = meshBuffer;
+ maskRenderData.material = maskMaterial;
+ ui.addToQueue(maskRenderData);
+ }
+ },
+};
+
+export const maskEndAssembler: IAssembler = {
+ fillBuffers (mask: MaskComponent, ui: UI) {
+ stencilManager.exit();
+
+ const clearGeometry = mask._getClearGeometry();
+ const clearMaterial = mask._getClearMaterial();
+ if (clearGeometry && clearMaterial) {
+ const meshBuffer = createMeshBuffer(ui, clearGeometry);
+ meshBuffer.vData!.set(clearGeometry.positions);
+ const clearMaskRenderData = ui.createUIRenderData() as IUIRenderData;
+ clearMaskRenderData.meshBuffer = meshBuffer;
+ clearMaskRenderData.material = clearMaterial;
+ }
+ },
+};
+
+export function setupMaskMaterial (material: Material) {
+ overrideStencilState(material, {
+ stencilTest: true,
+ func: GFXComparisonFunc.ALWAYS,
+ readMask: 0xffffffff,
+ failOp: GFXStencilOp.KEEP,
+ zFailOp: GFXStencilOp.KEEP,
+ passOp: GFXStencilOp.REPLACE,
+ });
+}
+
+export function setupClearMaskMaterial (material: Material) {
+ overrideStencilState(material, {
+ stencilTest: true,
+ func: GFXComparisonFunc.ALWAYS,
+ readMask: 0xffffffff,
+ failOp: GFXStencilOp.KEEP,
+ zFailOp: GFXStencilOp.KEEP,
+ passOp: GFXStencilOp.REPLACE,
+ ref: 0,
+ });
+}
+
+export function setupMaskTargetMaterial (material: Material) {
+ overrideStencilState(material, {
+ stencilTest: true,
+ func: GFXComparisonFunc.NOT_EQUAL,
+ readMask: 0xffffffff,
+ writeMask: 0xffffffff,
+ failOp: GFXStencilOp.KEEP,
+ zFailOp: GFXStencilOp.KEEP,
+ passOp: GFXStencilOp.KEEP,
+ ref: 0,
+ });
+}
+
+function createMeshBuffer (ui: UI, geometry: IGeometry) {
+ const nVert = Math.floor(geometry.positions.length / 3);
+ const meshBuffer = ui.createBuffer(nVert, geometry.indices ? geometry.indices.length : 0);
+ if (geometry.indices) {
+ meshBuffer.iData!.set(geometry.indices);
+ }
+ // geometry.primitiveMode === undefined ? GFXPrimitiveMode.TRIANGLE_LIST : geometry.primitiveMode;
+ return meshBuffer;
+}
diff --git a/cocos/3d/ui/assembler/sprite/bar-filled.ts b/cocos/3d/ui/assembler/sprite/bar-filled.ts
new file mode 100644
index 0000000000..c039b5d77a
--- /dev/null
+++ b/cocos/3d/ui/assembler/sprite/bar-filled.ts
@@ -0,0 +1,298 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+// @ts-check
+import { SpriteComponent } from '../../components/sprite-component';
+const FillType = SpriteComponent.FillType;
+
+// const dynamicAtlasManager = require('../../../../utils/dynamic-atlas/manager');
+import { Mat4 } from '../../../../core/value-types';
+import { vec3 } from '../../../../core/vmath/index';
+import { IRenderData, RenderData } from '../../../../renderer/ui/renderData';
+import { IUIRenderData, UI } from '../../../../renderer/ui/ui';
+import { Node } from '../../../../scene-graph/node';
+import { MeshBuffer } from '../../mesh-buffer';
+import { IAssembler } from '../assembler';
+import { fillVerticesWithoutCalc3D } from '../utils';
+
+const matrix = new Mat4();
+
+export const barFilled: IAssembler = {
+ useModel: false,
+ updateRenderData (sprite: SpriteComponent) {
+ const 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();
+ // }
+ // }
+
+ const renderData = sprite.renderData;
+ if (renderData && frame) {
+ const uvDirty = renderData.uvDirty;
+ const vertDirty = renderData.vertDirty;
+
+ if (!uvDirty && !vertDirty) {
+ // return sprite.__allocedDatas;
+ return;
+ }
+
+ let fillStart = sprite._fillStart;
+ let fillRange = sprite._fillRange;
+
+ if (fillRange < 0) {
+ fillStart += fillRange;
+ fillRange = -fillRange;
+ }
+
+ fillRange = fillStart + fillRange;
+
+ fillStart = fillStart > 1.0 ? 1.0 : fillStart;
+ fillStart = fillStart < 0.0 ? 0.0 : fillStart;
+
+ fillRange = fillRange > 1.0 ? 1.0 : fillRange;
+ fillRange = fillRange < 0.0 ? 0.0 : fillRange;
+ fillRange = fillRange - fillStart;
+ fillRange = fillRange < 0 ? 0 : fillRange;
+
+ let fillEnd = fillStart + fillRange;
+ fillEnd = fillEnd > 1 ? 1 : fillEnd;
+
+ if (uvDirty) {
+ this.updateUVs!(sprite, fillStart, fillEnd);
+ }
+ if (vertDirty) {
+ this.updateVerts(sprite, fillStart, fillEnd);
+ this.updateWorldVerts!(sprite);
+ }
+ }
+ },
+
+ updateUVs (sprite: SpriteComponent, fillStart: number, fillEnd: number) {
+ const spriteFrame = sprite.spriteFrame;
+ const renderData = sprite.renderData;
+ const datas = renderData!.datas;
+
+ // build uvs
+ const atlasWidth = spriteFrame!.width;
+ const atlasHeight = spriteFrame!.height;
+ const textureRect = spriteFrame!.getRect();
+ // uv computation should take spritesheet into account.
+ let ul = 0;
+ let vb = 0;
+ let ur = 0;
+ let vt = 0;
+ let quadUV0 = 0;
+ let quadUV1 = 0;
+ let quadUV2 = 0;
+ let quadUV3 = 0;
+ let quadUV4 = 0;
+ let quadUV5 = 0;
+ let quadUV6 = 0;
+ let quadUV7 = 0;
+ if (spriteFrame!.isRotated) {
+ ul = (textureRect.x) / atlasWidth;
+ vb = (textureRect.y + textureRect.width) / atlasHeight;
+ ur = (textureRect.x + textureRect.height) / atlasWidth;
+ vt = (textureRect.y) / atlasHeight;
+
+ quadUV0 = quadUV2 = ul;
+ quadUV4 = quadUV6 = ur;
+ quadUV3 = quadUV7 = vb;
+ quadUV1 = quadUV5 = vt;
+ } else {
+ ul = (textureRect.x) / atlasWidth;
+ vb = (textureRect.y + textureRect.height) / atlasHeight;
+ ur = (textureRect.x + textureRect.width) / atlasWidth;
+ vt = (textureRect.y) / atlasHeight;
+
+ quadUV0 = quadUV4 = ul;
+ quadUV2 = quadUV6 = ur;
+ quadUV1 = quadUV3 = vb;
+ quadUV5 = quadUV7 = vt;
+ }
+
+ switch (sprite.fillType) {
+ case FillType.HORIZONTAL:
+ // datas[0].u = ul + (ur - ul) * fillStart;
+ // datas[0].v = vb;
+ // datas[1].u = ul + (ur - ul) * fillEnd;
+ // datas[1].v = vb;
+ // datas[2].u = ul + (ur - ul) * fillStart;
+ // datas[2].v = vt;
+ // datas[3].u = ul + (ur - ul) * fillEnd;
+ // datas[3].v = vt;
+
+ datas[0].u = quadUV0 + (quadUV2 - quadUV0) * fillStart;
+ datas[0].v = quadUV1 + (quadUV3 - quadUV1) * fillStart;
+ datas[1].u = quadUV0 + (quadUV2 - quadUV0) * fillEnd;
+ datas[1].v = quadUV1 + (quadUV3 - quadUV1) * fillEnd;
+ datas[2].u = quadUV4 + (quadUV6 - quadUV4) * fillStart;
+ datas[2].v = quadUV5 + (quadUV7 - quadUV5) * fillStart;
+ datas[3].u = quadUV4 + (quadUV6 - quadUV4) * fillEnd;
+ datas[3].v = quadUV5 + (quadUV7 - quadUV5) * fillEnd;
+ break;
+ case FillType.VERTICAL:
+ // datas[0].u = ul;
+ // datas[0].v = vb + (vt - vb) * fillStart;
+ // datas[1].u = ur;
+ // datas[1].v = vb + (vt - vb) * fillStart;
+ // datas[2].u = ul;
+ // datas[2].v = vb + (vt - vb) * fillEnd;
+ // datas[3].u = ur;
+ // datas[3].v = vb + (vt - vb) * fillEnd;
+
+ datas[0].u = quadUV0 + (quadUV4 - quadUV0) * fillStart;
+ datas[0].v = quadUV1 + (quadUV5 - quadUV1) * fillStart;
+ datas[1].u = quadUV2 + (quadUV6 - quadUV2) * fillStart;
+ datas[1].v = quadUV3 + (quadUV7 - quadUV3) * fillStart;
+ datas[2].u = quadUV0 + (quadUV4 - quadUV0) * fillEnd;
+ datas[2].v = quadUV1 + (quadUV5 - quadUV1) * fillEnd;
+ datas[3].u = quadUV2 + (quadUV6 - quadUV2) * fillEnd;
+ datas[3].v = quadUV3 + (quadUV7 - quadUV3) * fillEnd;
+ break;
+ default:
+ cc.errorID(2626);
+ break;
+ }
+
+ renderData!.uvDirty = false;
+ },
+
+ updateVerts (sprite: SpriteComponent, fillStart: number, fillEnd: number) {
+ const renderData: RenderData|null = sprite.renderData;
+ const datas: IRenderData[] = renderData!.datas;
+ const node: Node = sprite.node;
+ const width = node.width;
+ const height = node.height;
+ const appx = node.anchorX * width;
+ const appy = node.anchorY * height;
+
+ let l = -appx;
+ let b = -appy;
+ let r = width - appx;
+ let t = height - appy;
+
+ let progressStart = 0;
+ let progressEnd = 0;
+ switch (sprite._fillType) {
+ case FillType.HORIZONTAL:
+ progressStart = l + (r - l) * fillStart;
+ progressEnd = l + (r - l) * fillEnd;
+
+ l = progressStart;
+ r = progressEnd;
+ break;
+ case FillType.VERTICAL:
+ progressStart = b + (t - b) * fillStart;
+ progressEnd = b + (t - b) * fillEnd;
+
+ b = progressStart;
+ t = progressEnd;
+ break;
+ default:
+ cc.errorID(2626);
+ break;
+ }
+
+ datas[0].x = l;
+ datas[0].y = b;
+ datas[1].x = r;
+ datas[1].y = b;
+ datas[2].x = l;
+ datas[2].y = t;
+ datas[3].x = r;
+ datas[3].y = t;
+
+ renderData!.vertDirty = false;
+ },
+
+ createData (sprite: SpriteComponent) {
+ const renderData: RenderData|null = sprite.requestRenderData();
+ // 0-4 for world verts
+ // 5-8 for local verts
+ renderData!.dataLength = 8;
+ renderData!.vertexCount = 4;
+ renderData!.indiceCount = 6;
+
+ const datas = renderData!.datas;
+ for (const data of datas) {
+ data.z = 0;
+ }
+
+ return renderData as RenderData;
+ },
+
+ updateWorldVerts (sprite: SpriteComponent) {
+ const node = sprite.node;
+ const datas = sprite.renderData!.datas;
+
+ // node._updateWorldMatrix();
+ // const matrix = node._worldMatrix;
+ for (let i = 0; i < 4; i++) {
+ const local = datas[i + 4];
+ const world = datas[i];
+ vec3.transformMat4(world, local, matrix);
+ }
+ },
+
+ fillBuffers (sprite: SpriteComponent, renderer: UI) {
+ const buffer: MeshBuffer = renderer.createBuffer(
+ sprite.renderData!.vertexCount,
+ sprite.renderData!.indiceCount,
+ );
+ const commitBuffer: IUIRenderData = renderer.createUIRenderData();
+ // if (renderer.worldMatDirty) {
+ // this.updateWorldVerts(sprite);
+ // }
+
+ // buffer
+ let indiceOffset: number = buffer.indiceOffset;
+ const vertexId: number = buffer.vertexOffset;
+
+ const node = sprite.node;
+ fillVerticesWithoutCalc3D(node, buffer, sprite.renderData, sprite.color);
+
+ // buffer data may be realloc, need get reference after request.
+ const 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;
+
+ commitBuffer.meshBuffer = buffer;
+ commitBuffer.material = sprite.material!;
+ commitBuffer.texture = sprite.spriteFrame!;
+ commitBuffer.priority = sprite.priority;
+ renderer.addToQueue(commitBuffer);
+ },
+};
diff --git a/cocos/2d/renderer/webgl/assemblers/sprite/index.js b/cocos/3d/ui/assembler/sprite/index.ts
similarity index 68%
rename from cocos/2d/renderer/webgl/assemblers/sprite/index.js
rename to cocos/3d/ui/assembler/sprite/index.ts
index c59947b09c..bd8a7e2e81 100644
--- a/cocos/2d/renderer/webgl/assemblers/sprite/index.js
+++ b/cocos/3d/ui/assembler/sprite/index.ts
@@ -23,42 +23,43 @@
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 { simple } from './simple';
+import { sliced } from './sliced';
+import { tilled } from './tiled';
+import { radialFilled } from './radial-filled';
+import { barFilled } from './bar-filled';
+import { Utils } from 'cannon';
+// import meshRenderUtil from './mesh';
// Inline all type switch to avoid jit deoptimization during inlined function change
-let spriteAssembler = {
+const spriteAssembler = {
getAssembler (sprite) {
- let util = simpleRenderUtil;
-
+ let util = simple;
+
switch (sprite.type) {
case SpriteType.SLICED:
- util = slicedRenderUtil;
+ util = sliced;
break;
case SpriteType.TILED:
- util = tiledRenderUtil;
+ util = tilled;
break;
case SpriteType.FILLED:
if (sprite._fillType === FillType.RADIAL) {
- util = radialFilledRenderUtil;
- }
- else {
- util = barFilledRenderUtil;
+ util = radialFilled;
+ } else {
+ util = barFilled;
}
break;
- case SpriteType.MESH:
- util = meshRenderUtil;
- break;
+ // case SpriteType.MESH:
+ // util = meshRenderUtil;
+ // break;
}
return util;
@@ -67,9 +68,11 @@ let spriteAssembler = {
// Skip invalid sprites (without own _assembler)
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.ts b/cocos/3d/ui/assembler/sprite/radial-filled.ts
new file mode 100644
index 0000000000..2175eeac93
--- /dev/null
+++ b/cocos/3d/ui/assembler/sprite/radial-filled.ts
@@ -0,0 +1,387 @@
+/****************************************************************************
+ 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 { Color, Vec2 } from '../../../../core/value-types';
+import { RenderData } from '../../../../renderer/ui/renderData';
+import { IUIRenderData, UI } from '../../../../renderer/ui/ui';
+import { SpriteComponent } from '../../components/sprite-component';
+import { MeshBuffer } from '../../mesh-buffer';
+import { IAssembler } from '../assembler';
+import { fillVertices3D } from '../utils';
+
+const PI_2 = Math.PI * 2;
+
+const _vertPos: Vec2[] = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];
+const _vertices: number[] = [0, 0, 0, 0];
+const _uvs: number[] = [0, 0, 0, 0, 0, 0, 0, 0];
+const _intersectPoint_1: Vec2[] = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];
+const _intersectPoint_2: Vec2[] = [new Vec2(), new Vec2(), new Vec2(), new Vec2()];
+const _center = new Vec2();
+const _triangles: [[number, number], [number, number], [number, number], [number, number]] = [
+ [0, 0], [0, 0], [0, 0], [0, 0],
+];
+
+function _calcInsectedPoints (left, right, bottom, top, center, angle, intersectPoints) {
+ // left bottom, right, top
+ const sinAngle = Math.sin(angle);
+ const cosAngle = Math.cos(angle);
+ let tanAngle = 0;
+ let cotAngle = 0;
+ if (cosAngle !== 0) {
+ tanAngle = sinAngle / cosAngle;
+ // calculate right and left
+ if ((left - center.x) * cosAngle > 0) {
+ const yleft = center.y + tanAngle * (left - center.x);
+ intersectPoints[0].x = left;
+ intersectPoints[0].y = yleft;
+ }
+ if ((right - center.x) * cosAngle > 0) {
+ const 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) {
+ const xtop = center.x + cotAngle * (top - center.y);
+ intersectPoints[3].x = xtop;
+ intersectPoints[3].y = top;
+ }
+ if ((bottom - center.y) * sinAngle > 0) {
+ const xbottom = center.x + cotAngle * (bottom - center.y);
+ intersectPoints[1].x = xbottom;
+ intersectPoints[1].y = bottom;
+ }
+
+ }
+}
+
+function _calculateVertices (sprite) {
+ const node = sprite.node;
+ const width = node.width;
+ const height = node.height;
+ const appx = node.anchorX * width;
+ const appy = node.anchorY * height;
+
+ const l = -appx;
+ const b = -appy;
+ const r = width - appx;
+ const t = height - appy;
+
+ const vertices = _vertices;
+ vertices[0] = l;
+ vertices[1] = b;
+ vertices[2] = r;
+ vertices[3] = t;
+
+ const fillCenter = sprite._fillCenter;
+ const cx = _center.x = Math.min(Math.max(0, fillCenter.x), 1) * (r - l) + l;
+ const 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;
+
+ for (let num of _triangles) {
+ num = [0, 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) {
+ const atlasWidth = spriteFrame.width;
+ const atlasHeight = spriteFrame.height;
+ const textureRect = spriteFrame._rect;
+
+ let u0 = 0;
+ let u1 = 0;
+ let v0 = 0;
+ let v1 = 0;
+ const 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) {
+ const placementX = end.x - start.x;
+ const placementY = end.y - start.y;
+
+ if (placementX === 0 && placementY === 0) {
+ return 0;
+ } 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) {
+ const vertices = _vertices;
+ const v0x = vertices[0];
+ const v0y = vertices[1];
+ const v1x = vertices[2];
+ const 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;
+ let 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) {
+ const uvs = _uvs;
+ const px1 = uvs[0] + (uvs[2] - uvs[0]) * progressX;
+ const px2 = uvs[4] + (uvs[6] - uvs[4]) * progressX;
+ const py1 = uvs[1] + (uvs[3] - uvs[1]) * progressX;
+ const py2 = uvs[5] + (uvs[7] - uvs[5]) * progressX;
+ const uv = data[offset];
+ uv.u = px1 + (px2 - px1) * progressY;
+ uv.v = py1 + (py2 - py1) * progressY;
+}
+
+export const radialFilled: IAssembler = {
+ useModel: false,
+
+ createData (sprite: SpriteComponent) {
+ return sprite.requestRenderData();
+ },
+
+ updateRenderData (sprite: SpriteComponent) {
+ const 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();
+ // }
+ // }
+
+ const renderData = sprite.renderData;
+ if (renderData && frame) {
+ if (renderData.vertDirty || renderData.uvDirty) {
+ const datas = renderData.datas;
+
+ 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;
+ const 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) {
+ const triangle = _triangles[triangleIndex];
+ if (!triangle) {
+ continue;
+ }
+ // all in
+ if (fillRange >= PI_2) {
+ renderData.dataLength = offset + 3;
+ _generateTriangle(datas, 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(
+ datas, offset, _center,
+ _vertPos[triangle[0]],
+ _intersectPoint_2[triangleIndex],
+ );
+ } else {
+ // startAngle to endAngle
+ _generateTriangle(datas, 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(datas, offset, _center,
+ _intersectPoint_1[triangleIndex],
+ _vertPos[triangle[1]],
+ );
+ offset += 3;
+ } else {
+ renderData.dataLength = offset + 3;
+ // fillStart to fillEnd
+ _generateTriangle(datas, 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: SpriteComponent, renderer: UI) {
+ const buffer: MeshBuffer = renderer.createBuffer(
+ comp.renderData!.vertexCount,
+ comp.renderData!.indiceCount,
+ );
+ const commitBuffer: IUIRenderData = renderer.createUIRenderData();
+
+ const node = comp.node;
+ const color: Color = comp.color;
+ /*buffer = renderer._meshBuffer3D,*/
+ const renderData: RenderData|null = comp.renderData;
+ const indiceOffset = buffer!.indiceOffset;
+ const vertexId = buffer.vertexOffset;
+ fillVertices3D(node, buffer, renderData, color);
+
+ // buffer data may be realloc, need get reference after request.
+ const ibuf = buffer.iData;
+ for (let i = 0; i < renderData!.dataLength; i++) {
+ ibuf![indiceOffset + i] = vertexId + i;
+ }
+
+ commitBuffer.meshBuffer = buffer;
+ commitBuffer.material = comp.material!;
+ commitBuffer.texture = comp.spriteFrame!;
+ commitBuffer.priority = comp.priority;
+ renderer.addToQueue(commitBuffer);
+ },
+};
diff --git a/cocos/3d/ui/assembler/sprite/simple.ts b/cocos/3d/ui/assembler/sprite/simple.ts
new file mode 100644
index 0000000000..45c66cc429
--- /dev/null
+++ b/cocos/3d/ui/assembler/sprite/simple.ts
@@ -0,0 +1,197 @@
+/****************************************************************************
+ 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 { Color, Vec3 } from '../../../../core/value-types';
+import { vec3 } from '../../../../core/vmath/index';
+import { IRenderData, RenderData } from '../../../../renderer/ui/renderData';
+import { IUIRenderData, UI } from '../../../../renderer/ui/ui';
+import { Node } from '../../../../scene-graph/node';
+import { SpriteComponent } from '../../components/sprite-component';
+import { MeshBuffer } from '../../mesh-buffer';
+import { IAssembler } from '../assembler';
+// const dynamicAtlasManager = require('../../../../utils/dynamic-atlas/manager');
+const matrix = cc.mat4();
+const vec3_temps: Vec3[] = [];
+for (let i = 0; i < 4; i++) {
+ vec3_temps.push(new Vec3());
+}
+
+export const simple: IAssembler = {
+
+ useModel: false,
+
+ createData (sprite: SpriteComponent) {
+ const renderData = sprite.requestRenderData();
+ renderData!.dataLength = 4;
+ renderData!.vertexCount = 4;
+ renderData!.indiceCount = 6;
+ return renderData as RenderData;
+ },
+
+ updateRenderData (sprite: SpriteComponent) {
+ const 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();
+ // }
+ // }
+
+ const renderData = sprite.renderData;
+ if (renderData && frame) {
+ if (renderData.vertDirty) {
+ this.updateVerts(sprite);
+ }
+ }
+ },
+
+ fillBuffers (sprite: SpriteComponent, renderer: UI) {
+ if (sprite === null) {
+ return;
+ }
+
+ const buffer: MeshBuffer = renderer.createBuffer(
+ sprite.renderData!.vertexCount,
+ sprite.renderData!.indiceCount,
+ );
+ const commitBuffer: IUIRenderData = renderer.createUIRenderData();
+ const datas: IRenderData[] = sprite!.renderData!.datas;
+ const node: Node = sprite.node;
+ const color: Color = sprite.color;
+
+ node.getWorldMatrix(matrix);
+
+ let vertexOffset: number = buffer.byteOffset >> 2;
+ let indiceOffset: number = buffer.indiceOffset;
+ const vertexId: number = buffer.vertexOffset;
+
+ buffer.request(4, 6);
+
+ // buffer data may be realloc, need get reference after request.
+ const vbuf: Float32Array|null = buffer.vData;
+ // const uintbuf = buffer.uintVData;
+ const ibuf: Uint16Array|null = buffer.iData;
+
+ const data0 = datas[0];
+ const data3 = datas[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
+ const uv = sprite!.spriteFrame!.uv;
+ for (let i = 0; i < 4; i++) {
+ // vertex
+ const vertex = vec3_temps[i];
+ vec3.transformMat4(vertex, vertex, matrix);
+
+ vbuf![vertexOffset++] = vertex.x;
+ vbuf![vertexOffset++] = vertex.y;
+ vbuf![vertexOffset++] = vertex.z;
+
+ // uv
+ const 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;
+
+ commitBuffer.meshBuffer = buffer;
+ commitBuffer.material = sprite.material!;
+ commitBuffer.texture = sprite.spriteFrame!;
+ commitBuffer.priority = sprite.priority;
+ renderer.addToQueue(commitBuffer);
+ },
+
+ updateVerts (sprite: SpriteComponent) {
+ const renderData: RenderData|null = sprite.renderData;
+ if (!renderData) {
+ return;
+ }
+
+ const node: Node = sprite.node;
+ const datas: IRenderData[] = renderData.datas;
+ const cw: number = node.width;
+ const ch: number = node.height;
+ const appx: number = node.anchorX * cw;
+ const appy: number = node.anchorY * ch;
+ let l: number = 0;
+ let b: number = 0;
+ let r: number = 0;
+ let t: number = 0;
+ // 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;
+ // }
+
+ datas[0].x = l;
+ datas[0].y = b;
+ // datas[1].x = r;
+ // datas[1].y = b;
+ // datas[2].x = l;
+ // datas[2].y = t;
+ datas[3].x = r;
+ datas[3].y = t;
+
+ renderData.vertDirty = false;
+ },
+};
diff --git a/cocos/3d/ui/assembler/sprite/sliced.ts b/cocos/3d/ui/assembler/sprite/sliced.ts
new file mode 100644
index 0000000000..979d3e30a0
--- /dev/null
+++ b/cocos/3d/ui/assembler/sprite/sliced.ts
@@ -0,0 +1,195 @@
+/****************************************************************************
+ 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 { IUV, SpriteFrame } from '../../../../assets/CCSpriteFrame';
+import { Color, Mat4 } from '../../../../core/value-types';
+import { vec3 } from '../../../../core/vmath/index';
+import { IRenderData, RenderData } from '../../../../renderer/ui/renderData';
+import { IUIRenderData } from '../../../../renderer/ui/ui';
+import { Node } from '../../../../scene-graph/node';
+import { SpriteComponent } from '../../components/sprite-component';
+import { MeshBuffer } from '../../mesh-buffer';
+import { IAssembler } from '../assembler';
+
+const vec3_temp = vec3.create();
+const matrix = new Mat4();
+
+export const sliced: IAssembler = {
+ useModel: false,
+
+ createData (sprite: SpriteComponent) {
+ const renderData: RenderData | null = sprite.requestRenderData();
+ // 0-4 for local verts
+ // 5-20 for world verts
+ renderData!.dataLength = 20;
+
+ renderData!.vertexCount = 16;
+ renderData!.indiceCount = 54;
+ return renderData as RenderData;
+ },
+
+ updateRenderData (sprite: SpriteComponent) {
+ const 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();
+ // }
+ // }
+
+ const renderData = sprite.renderData;
+ if (renderData && frame) {
+ const vertDirty = renderData.vertDirty;
+ if (vertDirty) {
+ this.updateVerts(sprite);
+ this.updateWorldVerts!(sprite);
+ }
+ }
+ },
+
+ updateVerts (sprite: SpriteComponent) {
+ const renderData: RenderData | null = sprite.renderData;
+ const datas: IRenderData[] = renderData!.datas;
+ const node: Node = sprite.node;
+ const width = node.width;
+ const height = node.height;
+ const appx = node.anchorX * width;
+ const appy = node.anchorY * height;
+
+ const frame: SpriteFrame|null = sprite.spriteFrame;
+ const leftWidth = frame!.insetLeft;
+ const rightWidth = frame!.insetRight;
+ const topHeight = frame!.insetTop;
+ const bottomHeight = frame!.insetBottom;
+
+ let sizableWidth = width - leftWidth - rightWidth;
+ let sizableHeight = height - topHeight - bottomHeight;
+ let xScale = width / (leftWidth + rightWidth);
+ let yScale = height / (topHeight + bottomHeight);
+ xScale = (isNaN(xScale) || xScale > 1) ? 1 : xScale;
+ yScale = (isNaN(yScale) || yScale > 1) ? 1 : yScale;
+ sizableWidth = sizableWidth < 0 ? 0 : sizableWidth;
+ sizableHeight = sizableHeight < 0 ? 0 : sizableHeight;
+
+ datas[0].x = -appx;
+ datas[0].y = -appy;
+ datas[1].x = leftWidth * xScale - appx;
+ datas[1].y = bottomHeight * yScale - appy;
+ datas[2].x = datas[1].x + sizableWidth;
+ datas[2].y = datas[1].y + sizableHeight;
+ datas[3].x = width - appx;
+ datas[3].y = height - appy;
+
+ renderData!.vertDirty = false;
+ },
+
+ fillBuffers (sprite: SpriteComponent, renderer) {
+ // if (renderer.worldMatDirty) {
+ // this.updateWorldVerts(sprite);
+ // }
+
+ const buffer: MeshBuffer = renderer.createBuffer(
+ sprite.renderData!.vertexCount,
+ sprite.renderData!.indiceCount,
+ );
+ const commitBuffer: IUIRenderData = renderer.createUIRenderData();
+ const renderData: RenderData|null = sprite.renderData;
+ const node: Node = sprite.node;
+ const color: Color = sprite.color;
+ const datas: IRenderData[] = renderData!.datas;
+
+ let vertexOffset = buffer.byteOffset >> 2;
+ const vertexCount = renderData!.vertexCount;
+ let indiceOffset: number = buffer.indiceOffset;
+ const vertexId: number = buffer.vertexOffset;
+
+ const uvSliced: IUV[] = sprite!.spriteFrame!.uvSliced;
+
+ buffer.request(vertexCount, renderData!.indiceCount);
+
+ // buffer data may be realloc, need get reference after request.
+ const vbuf: Float32Array|null = buffer.vData;
+ // const uintbuf = buffer._uintVData,
+ const ibuf: Uint16Array|null = buffer.iData;
+
+ // for (let i = 4; i < 20; ++i) {
+ for (let i = 4; i < 16; ++i) {
+ const vert = datas[i];
+ const uvs = uvSliced[i - 4];
+
+ vbuf![vertexOffset++] = vert.x;
+ vbuf![vertexOffset++] = vert.y;
+ vbuf![vertexOffset++] = vert.z;
+ vbuf![vertexOffset++] = uvs.u;
+ vbuf![vertexOffset++] = uvs.v;
+ vbuf![vertexOffset++] = color.r;
+ vbuf![vertexOffset++] = color.g;
+ vbuf![vertexOffset++] = color.b;
+ vbuf![vertexOffset++] = color.a;
+ // uintbuf[vertexOffset++] = color;
+ }
+
+ for (let r = 0; r < 3; ++r) {
+ for (let c = 0; c < 3; ++c) {
+ const start = vertexId + r * 4 + c;
+ ibuf![indiceOffset++] = start;
+ ibuf![indiceOffset++] = start + 1;
+ ibuf![indiceOffset++] = start + 4;
+ ibuf![indiceOffset++] = start + 1;
+ ibuf![indiceOffset++] = start + 5;
+ ibuf![indiceOffset++] = start + 4;
+ }
+ }
+
+ commitBuffer.meshBuffer = buffer;
+ commitBuffer.material = sprite.material!;
+ commitBuffer.texture = sprite.spriteFrame!;
+ commitBuffer.priority = sprite.priority;
+ renderer.addToQueue(commitBuffer);
+ },
+
+ updateWorldVerts (sprite: SpriteComponent) {
+ const node: Node = sprite.node;
+ const datas: IRenderData[] = sprite!.renderData!.datas;
+
+ node.getWorldMatrix(matrix);
+ for (let row = 0; row < 4; ++row) {
+ const rowD = datas[row];
+ for (let col = 0; col < 4; ++col) {
+ const colD = datas[col];
+ const world = datas[4 + row * 4 + col];
+
+ vec3.set(vec3_temp, colD.x, rowD.y, 0);
+ vec3.transformMat4(world, vec3_temp, matrix);
+ }
+ }
+ },
+};
diff --git a/cocos/3d/ui/assembler/sprite/tiled.ts b/cocos/3d/ui/assembler/sprite/tiled.ts
new file mode 100644
index 0000000000..234d66da96
--- /dev/null
+++ b/cocos/3d/ui/assembler/sprite/tiled.ts
@@ -0,0 +1,283 @@
+/****************************************************************************
+ 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 { Mat4, Vec3 } from '../../../../core/value-types';
+import { vec3 } from '../../../../core/vmath/index';
+import { RenderData } from '../../../../renderer/ui/renderData';
+import { IUIRenderData, UI } from '../../../../renderer/ui/ui';
+import { SpriteComponent } from '../../components/sprite-component';
+import { UIRenderComponent } from '../../components/ui-render-component';
+import { MeshBuffer } from '../../mesh-buffer';
+import { IAssembler } from '../assembler';
+
+const matrix = new Mat4();
+
+const vec3_temps: Vec3[] = [];
+for (let i = 0; i < 4; i++) {
+ vec3_temps.push(new Vec3());
+}
+
+const _tempVertexOffset = 6;
+const _tempUvOffset = 3;
+const _tempColorOffset = 5;
+
+export const tilled: IAssembler = {
+ useModel: false,
+
+ createData (sprite: UIRenderComponent) {
+ return sprite.requestRenderData() as RenderData;
+ },
+
+ updateRenderData (sprite: SpriteComponent) {
+ const 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();
+ // }
+ // }
+
+ const renderData = sprite.renderData;
+ if (!frame || !renderData ||
+ !(renderData.uvDirty || renderData.vertDirty)) {
+ return;
+ }
+
+ const node = sprite.node;
+ // contentWidth = Math.abs(node.width),
+ // contentHeight = Math.abs(node.height),
+ const contentWidth = Math.abs(node.width);
+ const contentHeight = Math.abs(node.height);
+ const appx = node.anchorX * contentWidth;
+ const appy = node.anchorY * contentHeight;
+ // node._updateWorldMatrix();
+
+ const rect = frame.getRect();
+ const rectWidth = rect.width;
+ const rectHeight = rect.height;
+ const hRepeat = contentWidth / rectWidth;
+ const vRepeat = contentHeight / rectHeight;
+ const row = Math.ceil(vRepeat);
+ const col = Math.ceil(hRepeat);
+
+ const data = renderData.datas;
+ 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: SpriteComponent, renderer: UI) {
+ const buffer: MeshBuffer = renderer.createBuffer(
+ sprite.renderData!.vertexCount,
+ sprite.renderData!.indiceCount,
+ );
+ const commitBuffer: IUIRenderData = renderer.createUIRenderData();
+
+ const node = sprite.node;
+ const color = sprite.color;
+ const renderData = sprite.renderData;
+ const datas = renderData!.datas;
+
+ // buffer
+ let vertexOffset = buffer.byteOffset >> 2;
+ let indiceOffset = buffer.indiceOffset;
+ let vertexId = buffer.vertexOffset;
+
+ buffer.request(renderData!.vertexCount, renderData!.indiceCount);
+
+ // buffer data may be realloc, need get reference after request.
+ const vbuf = buffer.vData;
+ // uintbuf = buffer._uintVData,
+ const ibuf = buffer.iData;
+
+ const rotated = sprite.spriteFrame!.isRotated;
+ const uv = sprite.spriteFrame!.uv;
+ const rect = sprite.spriteFrame!.getRect();
+ const contentWidth = Math.abs(node.width);
+ const contentHeight = Math.abs(node.height);
+ const hRepeat = contentWidth / rect.width;
+ const vRepeat = contentHeight / rect.height;
+ const row = Math.ceil(vRepeat);
+ const col = Math.ceil(hRepeat);
+
+ // const matrix = node._worldMatrix;
+
+ // this.updateVerts(vbuf, vertexOffset, matrix, row, col, datas);
+ // updataVerts
+ let x = 0;
+ let x1 = 0;
+ let y = 0;
+ let y1 = 0;
+ for (let yindex = 0, ylength = row; yindex < ylength; ++yindex) {
+ y = datas[yindex].y;
+ y1 = datas[yindex + 1].y;
+ for (let xindex = 0, xlength = col; xindex < xlength; ++xindex) {
+ x = datas[xindex].x;
+ x1 = datas[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++) {
+ const vec3_temp = vec3_temps[i];
+ vec3.transformMat4(vec3_temp, vec3_temp, matrix);
+ const move = i * 6;
+ vbuf![vertexOffset + move] = vec3_temp.x;
+ vbuf![vertexOffset + move + 1] = vec3_temp.y;
+ vbuf![vertexOffset + move + 2] = vec3_temp.z;
+ }
+
+ vertexOffset += 24;
+ }
+ }
+
+ const offset = _tempVertexOffset;
+ const uvOffset = _tempUvOffset;
+ const colorOffset = _tempColorOffset;
+ const offset1 = offset;
+ const offset2 = offset * 2;
+ const offset3 = offset * 3;
+ const offset4 = offset * 4;
+ let coefu = 0;
+ let coefv = 0;
+ 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);
+
+ const vertexOffsetU = vertexOffset + uvOffset;
+ const 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];
+ }
+ // TODO: addColor
+ // color
+ // uintbuf[vertexOffset + colorOffset] = color;
+ // uintbuf[vertexOffset + colorOffset + offset1] = color;
+ // uintbuf[vertexOffset + colorOffset + offset2] = color;
+ // uintbuf[vertexOffset + colorOffset + offset3] = color;
+ vertexOffset += offset4;
+ }
+ }
+
+ // update indices
+ const 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;
+ }
+
+ commitBuffer.meshBuffer = buffer;
+ commitBuffer.material = sprite.material!;
+ commitBuffer.texture = sprite.spriteFrame!;
+ commitBuffer.priority = sprite.priority;
+ renderer.addToQueue(commitBuffer);
+ },
+
+ updateVerts (sprite: SpriteComponent) {
+ // const renderData = sprite.renderData;
+ // const datas = renderData!.datas;
+ // const vbuf;
+ // const vertexOffset;
+ // sprite.node.getWorldMatrix(matrix);
+ // const row;
+ // const col;
+ // const 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;
+ // }
+ // }
+ },
+};
diff --git a/cocos/3d/ui/assembler/utils.ts b/cocos/3d/ui/assembler/utils.ts
new file mode 100644
index 0000000000..ba3d32d004
--- /dev/null
+++ b/cocos/3d/ui/assembler/utils.ts
@@ -0,0 +1,216 @@
+
+import { mat4, vec3 } from '../../../core/vmath/index';
+
+const vec3_temp = vec3.create();
+const _worldMatrix = mat4.create();
+
+export function fillVertices (node, buffer, renderData, color) {
+ const data = renderData._data;
+ let vertexOffset = buffer.byteOffset >> 2;
+
+ const vertexCount = renderData.vertexCount;
+ buffer.request(vertexCount, renderData.indiceCount);
+
+ // buffer data may be realloc, need get reference after request.
+ const vbuf = buffer.vData;
+ // uintbuf = buffer._uintVData;
+
+ // let matrix = node._worldMatrix;
+ node.getWorldMatrix(_worldMatrix);
+ const matrix = _worldMatrix;
+ const a = matrix.m00;
+ const b = matrix.m01;
+ const c = matrix.m04;
+ const d = matrix.m05;
+ const tx = matrix.m12;
+ const ty = matrix.m13;
+ for (let i = 0; i < vertexCount; i++) {
+ const 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;
+ vbuf[vertexOffset++] = color.r;
+ vbuf[vertexOffset++] = color.g;
+ vbuf[vertexOffset++] = color.b;
+ vbuf[vertexOffset++] = color.a;
+ }
+}
+
+export function fillMeshVertices (node, buffer, renderData, color) {
+ const datas = renderData.datas;
+ let vertexOffset = buffer.byteOffset >> 2;
+
+ const vertexCount = renderData.vertexCount;
+ let indiceOffset = buffer.indiceOffset;
+ const vertexId = buffer.vertexOffset;
+
+ buffer.request(vertexCount, renderData.indiceCount);
+
+ // buffer data may be realloc, need get reference after request.
+ const vbuf = buffer.vData;
+ // uintbuf = buffer._uintVData,
+ const ibuf = buffer._iData;
+
+ // let matrix = node._worldMatrix;
+ node.getWorldMatrix(_worldMatrix);
+ const matrix = _worldMatrix;
+ const a = matrix.m00;
+ const b = matrix.m01;
+ const c = matrix.m04;
+ const d = matrix.m05;
+ const tx = matrix.m12;
+ const ty = matrix.m13;
+ for (let i = 0; i < vertexCount; i++) {
+ const vert = datas[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;
+ vbuf[vertexOffset++] = color.r;
+ vbuf[vertexOffset++] = color.g;
+ vbuf[vertexOffset++] = color.b;
+ vbuf[vertexOffset++] = color.a;
+ }
+
+ // fill indice data
+ for (let i = 0, count = vertexCount / 4; i < count; i++) {
+ const 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) {
+ const datas = renderData.datas;
+ let vertexOffset = buffer.byteOffset >> 2;
+
+ const vertexCount = renderData.vertexCount;
+ buffer.request(vertexCount, renderData.indiceCount);
+
+ // buffer data may be realloc, need get reference after request.
+ const vbuf = buffer.vData;
+ // uintbuf = buffer._uintVData;
+
+ // let matrix = node._worldMatrix;
+ node.getWorldMatrix(_worldMatrix);
+
+ for (let i = 0; i < vertexCount; i++) {
+ const vert = datas[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;
+ vbuf[vertexOffset++] = color.r;
+ vbuf[vertexOffset++] = color.g;
+ vbuf[vertexOffset++] = color.b;
+ vbuf[vertexOffset++] = color.a;
+ // uintbuf[vertexOffset++] = color;
+ }
+}
+
+export function fillMeshVertices3D (node, buffer, renderData, color) {
+ const datas = renderData.datas;
+ let vertexOffset = buffer.byteOffset >> 2;
+
+ const vertexCount = renderData.vertexCount;
+ let indiceOffset = buffer.indiceOffset;
+ const vertexId = buffer.vertexOffset;
+
+ buffer.request(vertexCount, renderData.indiceCount);
+
+ // buffer data may be realloc, need get reference after request.
+ const vbuf = buffer.vData;
+ // uintbuf = buffer._uintVData,
+ const ibuf = buffer.iData;
+
+ // let matrix = node._worldMatrix;
+ node.getWorldMatrix(_worldMatrix);
+
+ for (let i = 0; i < vertexCount; i++) {
+ const vert = datas[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;
+ vbuf[vertexOffset++] = color.r;
+ vbuf[vertexOffset++] = color.g;
+ vbuf[vertexOffset++] = color.b;
+ vbuf[vertexOffset++] = color.a;
+ // uintbuf[vertexOffset++] = color;
+ }
+
+ // fill indice data
+ for (let i = 0, count = vertexCount / 4; i < count; i++) {
+ const 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) {
+ const datas = renderData.datas;
+ let vertexOffset = buffer.byteOffset >> 2;
+
+ const vertexCount = renderData.vertexCount;
+ buffer.request(vertexCount, renderData.indiceCount);
+
+ // buffer data may be realloc, need get reference after request.
+ const vbuf = buffer.vData;
+ // uintbuf = buffer._uintVData;
+
+ for (let i = 0; i < vertexCount; i++) {
+ const vert = datas[i];
+ vbuf[vertexOffset++] = vert.x;
+ vbuf[vertexOffset++] = vert.y;
+ vbuf[vertexOffset++] = vert.u;
+ vbuf[vertexOffset++] = vert.v;
+ // uintbuf[vertexOffset++] = color;
+ vbuf[vertexOffset++] = color.r;
+ vbuf[vertexOffset++] = color.g;
+ vbuf[vertexOffset++] = color.b;
+ vbuf[vertexOffset++] = color.a;
+ }
+}
+
+export function fillVerticesWithoutCalc3D (node, buffer, renderData, color) {
+ const datas = renderData.datas;
+ let vertexOffset = buffer.byteOffset >> 2;
+
+ const vertexCount = renderData.vertexCount;
+ buffer.request(vertexCount, renderData.indiceCount);
+
+ // buffer data may be realloc, need get reference after request.
+ const vbuf = buffer.vData;
+ // const uintbuf = buffer._uintVData;
+
+ for (let i = 0; i < vertexCount; i++) {
+ const vert = datas[i];
+ vbuf[vertexOffset++] = vert.x;
+ vbuf[vertexOffset++] = vert.y;
+ vbuf[vertexOffset++] = vert.z;
+ vbuf[vertexOffset++] = vert.u;
+ vbuf[vertexOffset++] = vert.v;
+ // uintbuf[vertexOffset++] = color;
+ vbuf[vertexOffset++] = color.r;
+ vbuf[vertexOffset++] = color.g;
+ vbuf[vertexOffset++] = color.b;
+ vbuf[vertexOffset++] = color.a;
+ }
+}
diff --git a/cocos/3d/ui/components/button-component.ts b/cocos/3d/ui/components/button-component.ts
new file mode 100644
index 0000000000..95bd18b3e7
--- /dev/null
+++ b/cocos/3d/ui/components/button-component.ts
@@ -0,0 +1,813 @@
+/****************************************************************************
+ 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 { EventTouch } from '../../../core/platform/event-manager';
+import { lerp } from '../../../core/utils/misc';
+import { Color, Enum, 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
+ */
+enum Transition {
+ /**
+ * !#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,
+}
+
+Enum(Transition);
+
+/**
+ * !#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
+ * })
+ *
+ */
+
+@ccclass('cc.ButtonComponent')
+@executionOrder(100)
+@menu('UI/Button')
+@executeInEditMode
+export 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: Transition) {
+ 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 = new Color(214, 214, 214);
+ @property
+ public _hoverColor: Color = new Color(211, 211, 211);
+ @property
+ public _pressColor: Color = Color.WHITE;
+ @property
+ public _disabledColor: Color = new 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: SpriteFrame | null = 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 = new Color();
+ public _toColor: Color = new Color();
+ public _time: number = 0;
+ public _transitionFinished: boolean = true;
+ public _fromScale: Vec3 = new Vec3();
+ public _toScale: Vec3 = new Vec3();
+ public _originalScale: Vec3 = new Vec3();
+ 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', (comp) => {
+ if (this._transition === Transition.SPRITE) {
+ this._normalSprite = comp.spriteFrame;
+ }
+ }, this);
+ }
+ }
+
+ public 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');
+ }
+ }
+
+ public update (dt: number) {
+ 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.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);
+ }
+
+ 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 && 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
+ if (!event) {
+ return false;
+ }
+
+ const touch = (event as EventTouch).touch;
+ if (!touch) {
+ return false;
+ }
+
+ const hit = this.node.uiTransfromComp!.isHit(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 && 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/components/CCCanvas.js b/cocos/3d/ui/components/canvas-component.ts
similarity index 53%
rename from cocos/components/CCCanvas.js
rename to cocos/3d/ui/components/canvas-component.ts
index c74ac8df5f..fde3a3a512 100644
--- a/cocos/components/CCCanvas.js
+++ b/cocos/3d/ui/components/canvas-component.ts
@@ -24,9 +24,13 @@
THE SOFTWARE.
****************************************************************************/
-import Camera from '../camera/CCCamera';
-import Component from './CCComponent';
-import {ccclass, property, executeInEditMode, menu, help, disallowMultiple} from '../core/data/class-decorator';
+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, ICameraInfo } from '../../../renderer/scene/camera';
/**
* !#zh: 作为 UI 根节点,为所有子节点提供视窗四边的位置信息以供对齐,另外提供屏幕适配策略接口,方便从编辑器设置。
@@ -35,60 +39,37 @@ import {ccclass, property, executeInEditMode, menu, help, disallowMultiple} from
* @class Canvas
* @extends Component
*/
-@ccclass('cc.Canvas')
+@ccclass('cc.CanvasComponent')
+@executionOrder(100)
@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;
+// @disallowMultiple
+export class CanvasComponent extends Component {
- /**
- * !#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
+ type: Size,
})
get designResolution () {
return cc.size(this._designResolution);
}
- set designResolution (value) {
+ set designResolution (value: Size) {
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'
- })
+ @property()
get fitHeight () {
return this._fitHeight;
}
- set fitHeight (value) {
+ set fitHeight (value: boolean) {
if (this._fitHeight !== value) {
this._fitHeight = value;
this.applySettings();
@@ -102,13 +83,11 @@ export default class Canvas extends Component {
* @property {Boolean} fitWidth
* @default false
*/
- @property({
- tooltip: CC_DEV && 'i18n:COMPONENT.canvas.fit_width'
- })
+ @property()
get fitWidth () {
return this._fitWidth;
}
- set fitWidth (value) {
+ set fitWidth (value: boolean) {
if (this._fitWidth !== value) {
this._fitWidth = value;
this.applySettings();
@@ -116,28 +95,103 @@ export default class Canvas extends Component {
}
}
+ // /**
+ // * !#en priority in render
+ // * !#zh 显示优先级
+ // */
+ // @property
+ // get priority () {
+ // return this._priority;
+ // }
+
+ // set priority (value: number) {
+ // this._priority = value;
+ // }
+
+ get visibility () {
+ if (this._camera) {
+ return this._camera.view.visibility;
+ }
+
+ return -1;
+ }
+
+ get camera () {
+ return this._camera;
+ }
+
+ 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: ()=>void;
+
+ private _camera: Camera | null = null;
+ private _cameraInfo: ICameraInfo | 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);
}
- resetInEditor () {
- _Scene._applyCanvasPreferences(this);
+ // public onLoad () {}
+
+ public resetInEditor () {
+ // _Scene._applyCanvasPreferences(this);
}
- __preload () {
- if (CC_DEV) {
- var Flags = cc.Object.Flags;
- this._objFlags |= (Flags.IsPositionLocked | Flags.IsAnchorLocked | Flags.IsSizeLocked);
- }
+ public __preload () {
+ this._cameraInfo = {
+ name: 'ui',
+ node: this.node,
+ projection: CameraComponent.ProjectionType.ORTHO,
+ fov: 45,
+ stencil: 0,
+ orthoHeight: 10,
+ far: 4096,
+ near: -0.1,
+ color: cc.color(0, 0, 0, 255),
+ clearFlags: GFXClearFlag.DEPTH | GFXClearFlag.STENCIL,
+ rect: new Rect(0, 0, 1, 1),
+ depth: 1,
+ isUI: true,
+ } as ICameraInfo;
+ this._camera = this._getRenderScene().createCamera(this._cameraInfo);
+ cc.director.root.ui.addScreen(this);
- if (Canvas.instance) {
- return cc.errorID(6700,
- this.node.name, Canvas.instance.node.name);
- }
- Canvas.instance = this;
+ // 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.director.on(cc.Director.EVENT_AFTER_UPDATE, this.alignWithScreen, this);
cc.engine.on('design-resolution-changed', this._thisOnResized);
}
else {
@@ -151,57 +205,51 @@ export default class Canvas extends Component {
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 () {
+ public onDisable () {
+ if (this._camera) {
+ this._getRenderScene().destroyCamera(this._camera);
+ cc.director.root.ui.removeScreen(this);
+ }
+ }
+
+ public onDestroy () {
if (CC_EDITOR) {
+ cc.director.off(cc.Director.EVENT_AFTER_UPDATE, this.alignWithScreen, this);
cc.engine.off('design-resolution-changed', this._thisOnResized);
}
else {
if (cc.sys.isMobile) {
window.removeEventListener('resize', this._thisOnResized);
- }
- else {
+ } else {
cc.view.off('canvas-resize', this._thisOnResized);
}
}
- if (Canvas.instance === this) {
- Canvas.instance = null;
- }
+ cc.view.off('design-resolution-changed', this._thisOnResized);
+
+ // if (CanvasComponent.instance === this) {
+ // CanvasComponent.instance = null;
+ // }
}
//
- alignWithScreen () {
- var designSize, nodeSize;
+ public alignWithScreen() {
+ let nodeSize, designSize;
if (CC_EDITOR) {
- nodeSize = designSize = cc.engine.getDesignResolutionSize();
+ // nodeSize = designSize = cc.engine.getDesignResolutionSize();
+ nodeSize = designSize = this._designResolution;
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;
+ const canvasSize = cc.visibleRect;
+ 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;
@@ -213,31 +261,26 @@ export default class Canvas extends Component {
this.node.height = nodeSize.height;
}
- applySettings () {
- var ResolutionPolicy = cc.ResolutionPolicy;
- var policy;
+ public applySettings () {
+ const ResolutionPolicy = cc.ResolutionPolicy;
+ let policy;
if (this.fitHeight && this.fitWidth) {
policy = ResolutionPolicy.SHOW_ALL;
- }
- else if (!this.fitHeight && !this.fitWidth) {
+ } else if (!this.fitHeight && !this.fitWidth) {
policy = ResolutionPolicy.NO_BORDER;
- }
- else if (this.fitWidth) {
+ } else if (this.fitWidth) {
policy = ResolutionPolicy.FIXED_WIDTH;
- }
- else { // fitHeight
+ } else { // fitHeight
policy = ResolutionPolicy.FIXED_HEIGHT;
}
- var designRes = this._designResolution;
+ const designRes = this._designResolution;
if (CC_EDITOR) {
- cc.engine.setDesignResolutionSize(designRes.width, designRes.height);
+ // cc.engine.setDesignResolutionSize(designRes.width, designRes.height);
}
else {
cc.view.setDesignResolutionSize(designRes.width, designRes.height, policy);
}
}
}
-
-cc.Canvas = Canvas;
\ No newline at end of file
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..fc6f9a32f8
--- /dev/null
+++ b/cocos/3d/ui/components/editbox/edit-box-component.ts
@@ -0,0 +1,825 @@
+/****************************************************************************
+ 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 ComponentEventHandler from '../../../../components/CCComponentEventHandler';
+import { Component } from '../../../../components/component';
+import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../../core/data/class-decorator';
+import macro from '../../../../core/platform/CCMacro';
+import Color from '../../../../core/value-types/color';
+import { LabelComponent } from '../label-component';
+import { SpriteComponent } from '../sprite-component';
+import { UIRenderComponent } from '../ui-render-component';
+import { UITransformComponent } from '../ui-transfrom-component';
+import { EditBoxImpl} from './edit-box-impl';
+import { InputFlag, InputMode, KeyboardReturnType } from './types';
+
+const LEFT_PADDING = 2;
+
+function capitalize (string) {
+ return string.replace(/(?:^|\s)\S/g, (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 class EditBoxComponent extends Component {
+
+ /**
+ * !#en Input string of EditBox.
+ * !#zh 输入框的初始输入内容,如果为空则会显示占位符的文本。
+ * @property {String} string
+ */
+ @property
+ get string () {
+ return this._string;
+ }
+
+ set string (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
+ */
+ @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: KeyboardReturnType) {
+ 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: InputFlag) {
+ 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: InputMode) {
+ 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) {
+ 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) {
+ 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;
+ const renderComp = this._textLabel.node.getComponent(UIRenderComponent);
+ if (renderComp) {
+ renderComp.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) {
+ 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) {
+ 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) {
+ const comp = this._placeholderLabel.node.getComponent(UIRenderComponent);
+ if (comp) {
+ comp.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) {
+ 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) {
+ 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) {
+ this._tabIndex = value;
+ if (this._impl) {
+ this._impl.setTabIndex(value);
+ }
+ }
+
+ public static _EditBoxImpl = EditBoxImpl;
+ public static KeyboardReturnType = KeyboardReturnType;
+ public static InputFlag = InputFlag;
+ public static InputMode = InputMode;
+ @property
+ public _useOriginalSize = true;
+ @property
+ public _string = '';
+ @property
+ public _tabIndex = 0;
+ @property
+ public _backgroundImage: SpriteFrame | null = null;
+ @property
+ public _returnType = KeyboardReturnType.DEFAULT;
+ @property
+ public _inputFlag = InputFlag.DEFAULT;
+ @property
+ public _inputMode = InputMode.SINGLE_LINE;
+ @property
+ public _fontSize = 20;
+ @property
+ public _lineHeight = 40;
+ @property
+ public _maxLength = 20;
+ @property
+ public _fontColor: Color = Color.WHITE;
+ @property
+ public _placeholder = 'Enter text here...';
+ @property
+ public _placeholderFontSize = 20;
+ @property
+ public _placeholderFontColor: Color = Color.GRAY;
+ @property
+ public _stayOnTop = false;
+ /**
+ * !#en The event handler to be called when EditBox began to edit text.
+ * !#zh 开始编辑文本输入框触发的事件回调。
+ * @property {Component.EventHandler[]} editingDidBegan
+ */
+ @property
+ public editingDidBegan: ComponentEventHandler[] = [];
+
+ /**
+ * !#en The event handler to be called when EditBox text changes.
+ * !#zh 编辑文本输入框时触发的事件回调。
+ * @property {Component.EventHandler[]} textChanged
+ */
+ @property
+ public textChanged: ComponentEventHandler[] = [];
+
+ /**
+ * !#en The event handler to be called when EditBox edit ends.
+ * !#zh 结束编辑文本输入框时触发的事件回调。
+ * @property {Component.EventHandler[]} editingDidEnded
+ */
+ @property
+ public editingDidEnded: ComponentEventHandler[] = [];
+
+ /**
+ * !#en The event handler to be called when return key is pressed. Windows is not supported.
+ * !#zh 当用户按下回车按键时的事件回调,目前不支持 windows 平台
+ * @property {Component.EventHandler[]} editingReturn
+ */
+ @property
+ public editingReturn: ComponentEventHandler[] = [];
+
+ public _impl: EditBoxImpl | null = null;
+ public _textLabel: LabelComponent | null = null;
+ public _placeholderLabel: LabelComponent | null = null;
+ public _background: SpriteComponent | null = null;
+
+ public onEnable () {
+ this._impl && this._impl.onEnable();
+ }
+
+ public onDisable () {
+ this._impl && this._impl.onDisable();
+ }
+
+ public onDestroy () {
+ this._impl && this._impl.clear();
+ }
+
+ public _init () {
+ this._createBackgroundSprite();
+ this._createLabels();
+ this.node.on(cc.Node.EventType.SIZE_CHANGED, this._resizeChildNodes, this);
+
+ const 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();
+ }
+
+ public __preload () {
+ if (!CC_EDITOR) {
+ this._registerEvent();
+ }
+ this._init();
+ }
+
+ public _registerEvent () {
+ this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this);
+ this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
+ }
+
+ public _updateStayOnTop () {
+ if (this.stayOnTop) {
+ this._hideLabels();
+ } else {
+ this._showLabels();
+ }
+ this._impl && this._impl.stayOnTop(this.stayOnTop);
+ }
+
+ public _syncSize () {
+ const size = this.node.getContentSize();
+
+ this._background && this._background.node.setAnchorPoint(this.node.getAnchorPoint());
+ this._background && this._background.node.setContentSize(size);
+
+ this._updateLabelPosition(size);
+ this._impl && this._impl.setSize(size.width, size.height);
+ }
+
+ public _updateLabelPosition (size) {
+ const node = this.node;
+ const offx = -node.anchorX * node.width;
+ const offy = -node.anchorY * node.height;
+
+ const placeholderLabel = this._placeholderLabel;
+ const textLabel = this._textLabel;
+ if (textLabel) {
+ textLabel.node.setContentSize(size.width - LEFT_PADDING, size.height);
+ textLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height, textLabel.node.getPosition().z);
+ textLabel.verticalAlign = this._inputMode === InputMode.ANY ? macro.VerticalTextAlignment.TOP : macro.VerticalTextAlignment.CENTER;
+ textLabel.enableWrapText = this._inputMode === InputMode.ANY ? true : false;
+ }
+
+ if (placeholderLabel) {
+ placeholderLabel.node.setContentSize(size.width - LEFT_PADDING, size.height);
+ placeholderLabel.lineHeight = size.height;
+ placeholderLabel.node.setPosition(offx + LEFT_PADDING, offy + size.height, placeholderLabel.node.getPosition().z);
+ placeholderLabel.verticalAlign = this._inputMode === InputMode.ANY ?
+ macro.VerticalTextAlignment.TOP : macro.VerticalTextAlignment.CENTER;
+ placeholderLabel.enableWrapText = this._inputMode === InputMode.ANY ? true : false;
+ }
+ }
+
+ public _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.Node('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;
+ }
+
+ public _createLabels () {
+ if (!this._textLabel) {
+ let node = this.node.getChildByName('TEXT_LABEL');
+ if (!node) {
+ node = new cc.Node('TEXT_LABEL');
+ }
+ let textLabel = node!.getComponent(LabelComponent);
+ node!.parent = this.node;
+
+ if (!textLabel) {
+ textLabel = node!.addComponent(LabelComponent);
+ }
+
+ const transformComp = node!.getComponent(UITransformComponent);
+ transformComp!.setAnchorPoint(0, 1);
+ textLabel!.color = this._fontColor;
+ 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.Node('PLACEHOLDER_LABEL');
+ }
+ let placeholderLabel = node!.getComponent(LabelComponent);
+ if (!placeholderLabel) {
+ placeholderLabel = node!.addComponent(LabelComponent);
+ }
+ const transform = node!.getComponent(UITransformComponent);
+
+ node!.parent = this.node;
+ placeholderLabel!.color = this._placeholderFontColor;
+ transform!.setAnchorPoint(0, 1);
+
+ placeholderLabel!.overflow = LabelComponent.Overflow.CLAMP;
+ placeholderLabel!.fontSize = this._placeholderFontSize;
+ placeholderLabel!.string = this._placeholder;
+ this._placeholderLabel = placeholderLabel;
+ }
+ }
+
+ public _resizeChildNodes () {
+ const textLabelNode = this._textLabel && this._textLabel.node;
+ if (textLabelNode) {
+ textLabelNode.setPosition(-this.node.width / 2, this.node.height / 2, textLabelNode.getPosition().z);
+ textLabelNode.width = this.node.width;
+ textLabelNode.height = this.node.height;
+ }
+ const placeholderLabelNode = this._placeholderLabel && this._placeholderLabel.node;
+ if (placeholderLabelNode) {
+ placeholderLabelNode.setPosition(-this.node.width / 2, this.node.height / 2, placeholderLabelNode.getPosition().z);
+ placeholderLabelNode.width = this.node.width;
+ placeholderLabelNode.height = this.node.height;
+ }
+ const backgroundNode = this._background && this._background.node;
+ if (backgroundNode) {
+ backgroundNode.width = this.node.width;
+ backgroundNode.height = this.node.height;
+ }
+ }
+
+ public _showLabels () {
+ if (this._textLabel) {
+ const displayText = this._textLabel.string;
+ this._textLabel.node.active = displayText !== '';
+ if (this._placeholderLabel) {
+ this._placeholderLabel.node.active = displayText === '';
+ }
+ }
+ }
+
+ public _hideLabels () {
+ if (this._textLabel) {
+ this._textLabel.node.active = false;
+ }
+ if (this._placeholderLabel) {
+ this._placeholderLabel.node.active = false;
+ }
+ }
+
+ public _updateString (text) {
+ const textLabel = this._textLabel;
+ // Not inited yet
+ if (!textLabel) {
+ return;
+ }
+
+ let displayText = text;
+ if (displayText) {
+ displayText = this._updateLabelStringStyle(displayText);
+ }
+
+ textLabel.string = displayText;
+ if (this._impl) {
+ this._impl.setString(text);
+ if (!this._impl.editing && !this.stayOnTop) {
+ this._showLabels();
+ }
+ }
+ }
+
+ public _updateLabelStringStyle (text: string, ignorePassword: boolean = false) {
+ const inputFlag = this._inputFlag;
+ if (!ignorePassword && inputFlag === InputFlag.PASSWORD) {
+ let passwordString = '';
+ const 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;
+ }
+
+ public editBoxEditingDidBegan () {
+ this._hideLabels();
+ ComponentEventHandler.emitEvents(this.editingDidBegan, this);
+ this.node.emit('editing-did-began', this);
+ }
+
+ public editBoxEditingDidEnded () {
+ if (!this.stayOnTop) {
+ this._showLabels();
+ }
+ ComponentEventHandler.emitEvents(this.editingDidEnded, this);
+ this.node.emit('editing-did-ended', this);
+ }
+
+ public editBoxTextChanged (text) {
+ text = this._updateLabelStringStyle(text, true);
+ this.string = text;
+ ComponentEventHandler.emitEvents(this.textChanged, text, this);
+ this.node.emit('text-changed', this);
+ }
+
+ public editBoxEditingReturn () {
+ ComponentEventHandler.emitEvents(this.editingReturn, this);
+ this.node.emit('editing-return', this);
+ }
+
+ public _onTouchBegan (event) {
+ if (this._impl) {
+ this._impl._onTouchBegan(event.touch);
+ }
+ event.stopPropagation();
+ }
+
+ public _onTouchCancel (event) {
+ // if (this._impl) {
+ // this._impl._onTouchCancel();
+ // }
+ event.stopPropagation();
+ }
+
+ public _onTouchEnded (event) {
+ if (this._impl) {
+ this._impl._onTouchEnded();
+ }
+ event.stopPropagation();
+ }
+
+ /**
+ * !#en Let the EditBox get focus
+ * !#zh 让当前 EditBox 获得焦点
+ * @method setFocus
+ */
+ public 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
+ */
+ public isFocused () {
+ let isFocused = false;
+ if (this._impl) {
+ isFocused = this._impl.isFocused();
+ }
+ return isFocused;
+ }
+
+ public 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/3d/ui/components/editbox/edit-box-impl.ts b/cocos/3d/ui/components/editbox/edit-box-impl.ts
new file mode 100644
index 0000000000..47aa5c7fdb
--- /dev/null
+++ b/cocos/3d/ui/components/editbox/edit-box-impl.ts
@@ -0,0 +1,714 @@
+/****************************************************************************
+ Copyright (c) 2011-2012 cocos2d-x.org
+ Copyright (c) 2012 James Chen
+ 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 } from '../../../../core/data/class-decorator';
+import macro from '../../../../core/platform/CCMacro';
+import { contains } from '../../../../core/utils/misc';
+import { Color, Size } from '../../../../core/value-types';
+import * as math from '../../../../core/vmath';
+import { Node } from '../../../../scene-graph/node';
+import { UIRenderComponent } from '../ui-render-component';
+import { EditBoxComponent} from './edit-box-component';
+// import { InputMode, InputFlag, KeyboardReturnType } from './types';
+import * as Types from './types';
+const InputMode = Types.InputMode;
+const InputFlag = Types.InputFlag;
+const KeyboardReturnType = Types.KeyboardReturnType;
+
+// https://segmentfault.com/q/1010000002914610
+const SCROLLY = 40;
+const LEFT_PADDING = 2;
+const DELAY_TIME = 400;
+const FOCUS_DELAY_UC = 400;
+const FOCUS_DELAY_FIREFOX = 0;
+
+const _matrix = cc.mat4();
+const _matrix_temp = cc.mat4();
+const _vec3 = cc.v3();
+
+let _currentEditBoxImpl: EditBoxImpl | null = null;
+
+// polyfill
+const polyfill = {
+ zoomInvalid: false,
+};
+
+if (cc.sys.OS_ANDROID === cc.sys.os &&
+ (cc.sys.browserType === cc.sys.BROWSER_TYPE_SOUGOU ||
+ cc.sys.browserType === cc.sys.BROWSER_TYPE_360)) {
+ polyfill.zoomInvalid = true;
+}
+
+function getKeyboardReturnType (type) {
+ switch (type) {
+ case KeyboardReturnType.DEFAULT:
+ case KeyboardReturnType.DONE:
+ return 'done';
+ case KeyboardReturnType.SEND:
+ return 'send';
+ case KeyboardReturnType.SEARCH:
+ return 'search';
+ case KeyboardReturnType.GO:
+ return 'go';
+ case KeyboardReturnType.NEXT:
+ return 'next';
+ }
+ return 'done';
+}
+
+@ccclass
+export class EditBoxImpl {
+ private _delegate: EditBoxComponent | null = null;
+ private _inputMode = -1;
+ private _inputFlag = -1;
+ private _returnType = KeyboardReturnType.DEFAULT;
+ private _maxLength = 50;
+ private _text = '';
+ private _placeholderText = '';
+ private _alwaysOnTop = false;
+ private _size: Size = cc.size();
+ private _node: Node | null = null;
+ private _editing = false;
+ private __eventListeners: any = {};
+ private __fullscreen = false;
+ private __autoResize = false;
+ private __rotateScreen = false;
+ private __orientationChanged: any;
+ private _edTxt: HTMLElement | null = null;
+ private _textColor: Color = Color.WHITE;
+ private _edFontSize = 14;
+
+ get text () {
+ return this._text;
+ }
+
+ set text (value: string) {
+ this._text = value;
+ }
+
+ get textColor () {
+ return this._textColor;
+ }
+
+ get fontSize () {
+ return this._edFontSize;
+ }
+
+ set returnType (value: Types.KeyboardReturnType) {
+ this._returnType = value;
+ }
+
+ get alwayOnTop () {
+ return this._alwaysOnTop;
+ }
+
+ set editing (value: boolean) {
+ this._editing = value;
+ }
+
+ get delegate () {
+ return this._delegate;
+ }
+
+ get eventListeners () {
+ return this.__eventListeners;
+ }
+
+ public onEnable () {
+ if (!this._edTxt) {
+ return;
+ }
+ if (this._alwaysOnTop) {
+ this._edTxt.style.display = '';
+ } else {
+ this._edTxt.style.display = 'none';
+ }
+ }
+
+ public onDisable () {
+ if (!this._edTxt) {
+ return;
+ }
+ this._edTxt.style.display = 'none';
+ }
+
+ public setTabIndex (index) {
+ if (this._edTxt) {
+ this._edTxt.tabIndex = index;
+ }
+ }
+
+ public setFocus () {
+ this._beginEditing();
+ }
+
+ public isFocused () {
+ if (this._edTxt) {
+ return document.activeElement === this._edTxt;
+ }
+ cc.warnID(4700);
+ return false;
+ }
+
+ public stayOnTop (flag) {
+ if (this._alwaysOnTop === flag || !this._edTxt) { return; }
+
+ this._alwaysOnTop = flag;
+
+ if (flag) {
+ this._edTxt.style.display = '';
+ } else {
+ this._edTxt.style.display = 'none';
+ }
+ }
+
+ public setMaxLength (maxLength) {
+ if (!isNaN(maxLength)) {
+ 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;
+ }
+ this._maxLength = maxLength;
+ if (this._edTxt) {
+ this._edTxt.maxLength = maxLength;
+ }
+ }
+ }
+
+ public setString (text) {
+ this._text = text;
+ if (this._edTxt) {
+ this._edTxt.value = text;
+ }
+ }
+
+ public getString () {
+ return this._text;
+ }
+
+ public setPlaceholderText (text) {
+ this._placeholderText = text;
+ }
+
+ public getPlaceholderText () {
+ return this._placeholderText;
+ }
+
+ public setDelegate (delegate) {
+ this._delegate = delegate;
+ }
+
+ public setInputMode (inputMode) {
+ if (this._inputMode === inputMode) { return; }
+
+ this._inputMode = inputMode;
+ this.createInput();
+
+ this._updateDomInputType();
+ this._updateSize(this._size.width, this._size.height);
+ }
+
+ public setInputFlag (inputFlag) {
+ if (this._inputFlag === inputFlag) { return; }
+
+ this._inputFlag = inputFlag;
+ this._updateDomInputType();
+
+ let textTransform = 'none';
+
+ if (inputFlag === InputFlag.INITIAL_CAPS_ALL_CHARACTERS) {
+ textTransform = 'uppercase';
+ } else if (inputFlag === InputFlag.INITIAL_CAPS_WORD) {
+ textTransform = 'capitalize';
+ }
+
+ if (this._edTxt) {
+ this._edTxt.style.textTransform = textTransform;
+ this._edTxt.value = this._text;
+ }
+ }
+
+ public setReturnType (returnType) {
+ this._returnType = returnType;
+ this._updateDomInputType();
+ }
+
+ public setFontSize (fontSize) {
+ this._edFontSize = fontSize || this._edFontSize;
+ if (this._edTxt) {
+ this._edTxt.style.fontSize = this._edFontSize + 'px';
+ }
+ }
+
+ public setFontColor (color) {
+ this._textColor = color;
+ if (this._edTxt) {
+ this._edTxt.style.color = color.toCSS('rgba');
+ }
+ }
+
+ public setSize (width, height) {
+ this._size.width = width;
+ this._size.height = height;
+ this._updateSize(width, height);
+ }
+
+ public setNode (node) {
+ this._node = node;
+ }
+
+ public update () {
+ // TODO: find better way to update matrix
+ // if (this._editing) {
+ this._updateMatrix();
+ // }
+ }
+
+ public clear () {
+ this._node = null;
+ this.setDelegate(null);
+ this.removeDom();
+ }
+
+ public _onTouchBegan (touch) {
+
+ }
+
+ public _onTouchEnded () {
+ this._beginEditing();
+ }
+
+ public _beginEditing () {
+ if (cc.sys.isMobile && !this._editing) {
+ // Pre adaptation
+ this._beginEditingOnMobile();
+ }
+
+ if (this._edTxt) {
+ this._edTxt.style.display = '';
+
+ const self = this;
+ function startFocus () {
+ self._edTxt!.focus();
+ }
+
+ if (cc.sys.browserType === cc.sys.BROWSER_TYPE_UC) {
+ setTimeout(startFocus, FOCUS_DELAY_UC);
+ } else if (cc.sys.browserType === cc.sys.BROWSER_TYPE_FIREFOX) {
+ setTimeout(startFocus, FOCUS_DELAY_FIREFOX);
+ } else {
+ startFocus();
+ }
+ }
+
+ this._editing = true;
+ }
+
+ public _endEditing () {
+ const self = this;
+ const hideDomInputAndShowLabel = () => {
+ if (!self._alwaysOnTop && self._edTxt) {
+ self._edTxt.style.display = 'none';
+ }
+ if (self._delegate && self._delegate.editBoxEditingDidEnded) {
+ self._delegate.editBoxEditingDidEnded();
+ }
+ };
+ if (this._editing) {
+ if (cc.sys.isMobile) {
+ // Delay end editing adaptation to ensure virtual keyboard is disapeared
+ setTimeout(() => {
+ self._endEditingOnMobile();
+ hideDomInputAndShowLabel();
+ }, DELAY_TIME);
+ } else {
+ hideDomInputAndShowLabel();
+ }
+ }
+ this._editing = false;
+ }
+
+ public _updateDomInputType () {
+ const inputMode = this._inputMode;
+ const edTxt = this._edTxt as HTMLInputElement;
+ 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) {
+ type = 'number';
+ } else if (inputMode === InputMode.PHONE_NUMBER) {
+ type = 'number';
+ edTxt.pattern = '[0-9]*';
+ } else if (inputMode === InputMode.URL) {
+ type = 'url';
+ } else {
+ type = 'text';
+
+ if (this._returnType === KeyboardReturnType.SEARCH) {
+ type = 'search';
+ }
+ }
+
+ edTxt.type = type;
+ }
+
+ public _updateSize (newWidth, newHeight) {
+ const edTxt = this._edTxt;
+ if (!edTxt) { return; }
+
+ edTxt.style.width = newWidth + 'px';
+ edTxt.style.height = newHeight + 'px';
+ }
+
+ public _updateMatrix () {
+ if (!this._edTxt) { return; }
+
+ const node = this._node;
+ let scaleX = cc.view._scaleX;
+ let scaleY = cc.view._scaleY;
+ const viewport = cc.view._viewportRect;
+ const dpr = cc.view._devicePixelRatio;
+
+ node!.getWorldMatrix(_matrix);
+ const transform = node!.uiTransfromComp;
+ if (transform) {
+ _vec3.x = -transform.anchorX.x * transform.width;
+ _vec3.y = -transform.anchorY.y * transform.height;
+ }
+
+ math.mat4.translate(_matrix, _matrix, _vec3);
+
+ // let camera;
+ // can't find camera in editor
+ // if (CC_EDITOR) {
+ // camera = cc.Camera.main;
+ // }
+ // else {
+ // camera = cc.Camera.findCamera(node);
+ // }
+ const renderComp = node!.getComponent(UIRenderComponent);
+ if (!renderComp) {
+ return false;
+ }
+ // let canvas = cc.CanvasComponent.findView(renderComp);
+ const canvas = cc.director.root.ui.getScreen(renderComp.visibility);
+ if (!canvas) {
+ return;
+ }
+
+ // camera.getWorldToCameraMatrix(_matrix_temp);
+ canvas.node.getWorldRT(_matrix_temp);
+ const m12 = _matrix_temp.m12;
+ const m13 = _matrix_temp.m13;
+ const 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;
+
+ const container = cc.game.container;
+ let a = _matrix_temp.m00 * scaleX;
+ const b = _matrix.m01;
+ const c = _matrix.m04;
+ let 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;
+ const tx = _matrix_temp.m12 * scaleX + offsetX;
+ const ty = _matrix_temp.m13 * scaleY + offsetY;
+
+ if (polyfill.zoomInvalid) {
+ this._updateSize(this._size.width * a, this._size.height * d);
+ a = 1;
+ d = 1;
+ }
+
+ const 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';
+ }
+
+ public _adjustEditBoxPosition () {
+ this._node!.getWorldMatrix(_matrix);
+ const y = _matrix.m13;
+ const windowHeight = cc.visibleRect.height;
+ const windowWidth = cc.visibleRect.width;
+ let factor = 0.5;
+ if (windowWidth > windowHeight) {
+ factor = 0.7;
+ }
+ setTimeout(() => {
+ if (window.scrollY < SCROLLY && y < windowHeight * factor) {
+ let scrollOffset = windowHeight * factor - y - window.scrollY;
+ if (scrollOffset < 35) { scrollOffset = 35; }
+ if (scrollOffset > 320) { scrollOffset = 320; }
+ window.scrollTo(0, scrollOffset);
+ }
+ }, DELAY_TIME);
+ }
+
+ public createInput () {
+ if (this._inputMode === InputMode.ANY) {
+ this._createDomTextArea();
+ } else {
+ this._createDomInput();
+ }
+ }
+
+ // Called before editbox focus to register cc.view status
+ public _beginEditingOnMobile () {
+ const self = this;
+ this.__orientationChanged = () => {
+ 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
+ public _endEditingOnMobile () {
+ if (this.__rotateScreen) {
+ cc.game.container.style['-webkit-transform'] = 'rotate(90deg)';
+ cc.game.container.style.transform = 'rotate(90deg)';
+
+ const view = cc.view;
+ const width = view._originalDesignResolutionSize.width;
+ const height = view._originalDesignResolutionSize.height;
+ if (width > 0) {
+ view.setDesignResolutionSize(width, height, view._resolutionPolicy);
+ }
+ this.__rotateScreen = false;
+ }
+
+ if (this.__orientationChanged) {
+ 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);
+ }
+ }
+
+ public _createDomInput () {
+ this.removeDom();
+
+ const tmpEdTxt = this._edTxt = document.createElement('input');
+ tmpEdTxt.type = 'text';
+ tmpEdTxt.style.fontSize = this._edFontSize + 'px';
+ tmpEdTxt.style.color = '#000000';
+ tmpEdTxt.style.border = '0px';
+ 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.className = 'cocosEditBox';
+ tmpEdTxt.style.fontFamily = 'Arial';
+
+ registerInputEventListener(tmpEdTxt, this);
+
+ return tmpEdTxt;
+ }
+
+ public _createDomTextArea () {
+ this.removeDom();
+
+ const 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.overflowY = 'scroll';
+ tmpEdTxt.style.display = 'none';
+ tmpEdTxt.style.position = 'absolute';
+ tmpEdTxt.style.bottom = '0px';
+ tmpEdTxt.style.left = LEFT_PADDING + 'px';
+ tmpEdTxt.className = 'cocosEditBox';
+ tmpEdTxt.style.fontFamily = 'Arial';
+
+ registerInputEventListener(tmpEdTxt, this, true);
+
+ return tmpEdTxt;
+ }
+
+ public _addDomToGameContainer () {
+ cc.game.container.appendChild(this._edTxt);
+ }
+
+ public removeDom () {
+ const edTxt = this._edTxt;
+ if (edTxt) {
+ // Remove listeners
+ const 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;
+
+ const 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);
+ }
+ if (editBoxImpl._delegate && editBoxImpl._delegate.editBoxTextChanged) {
+ if (editBoxImpl._text !== input.value) {
+ editBoxImpl._text = input.value;
+ editBoxImpl._delegate.editBoxTextChanged(editBoxImpl._text);
+ }
+ }
+}
+
+function registerInputEventListener (tmpEdTxt: HTMLElement, editBoxImpl: EditBoxImpl, isTextarea = false) {
+ let inputLock = false;
+ const cbs = editBoxImpl.eventListeners;
+ cbs.compositionstart = () => {
+ inputLock = true;
+ };
+ tmpEdTxt.addEventListener('compositionstart', cbs.compositionstart);
+
+ cbs.compositionend = function () {
+ inputLock = false;
+ _inputValueHandle(this, editBoxImpl);
+ };
+ tmpEdTxt.addEventListener('compositionend', cbs.compositionend);
+
+ cbs.input = function () {
+ if (inputLock) {
+ return;
+ }
+ _inputValueHandle(this, editBoxImpl);
+ };
+ tmpEdTxt.addEventListener('input', cbs.input);
+
+ cbs.focus = function () {
+ this.style.fontSize = editBoxImpl.fontSize + 'px';
+ this.style.color = editBoxImpl.textColor.toCSS('rgba');
+ // When stayOnTop, input will swallow touch event
+ if (editBoxImpl.alwayOnTop) {
+ editBoxImpl.editing = true;
+ }
+
+ if (cc.sys.isMobile) {
+ editBoxImpl._beginEditingOnMobile();
+ }
+
+ if (editBoxImpl.delegate && editBoxImpl.delegate.editBoxEditingDidBegan) {
+ editBoxImpl.delegate.editBoxEditingDidBegan();
+ }
+
+ };
+ tmpEdTxt.addEventListener('focus', cbs.focus);
+
+ cbs.keypress = function (e) {
+ if (e.keyCode === macro.KEY.enter) {
+ e.stopPropagation();
+
+ if (editBoxImpl.delegate && editBoxImpl.delegate.editBoxEditingReturn) {
+ editBoxImpl.delegate.editBoxEditingReturn();
+ }
+ if (!isTextarea) {
+ editBoxImpl.text = this.value;
+ editBoxImpl._endEditing();
+ cc.game.canvas.focus();
+ }
+ }
+ };
+ tmpEdTxt.addEventListener('keypress', cbs.keypress);
+
+ cbs.blur = function () {
+ editBoxImpl.text = this.value;
+ editBoxImpl._endEditing();
+ };
+ tmpEdTxt.addEventListener('blur', cbs.blur);
+
+ editBoxImpl._addDomToGameContainer();
+}
diff --git a/cocos/2d/ui/editbox/types.js b/cocos/3d/ui/components/editbox/types.ts
similarity index 90%
rename from cocos/2d/ui/editbox/types.js
rename to cocos/3d/ui/components/editbox/types.ts
index ca1757d2e4..49b1bb0570 100644
--- a/cocos/2d/ui/editbox/types.js
+++ b/cocos/3d/ui/components/editbox/types.ts
@@ -22,50 +22,53 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
+
+import { Enum } from '../../../../core/value-types';
/**
* !#en Enum for keyboard return types
* !#zh 键盘的返回键类型
* @readonly
* @enum EditBox.KeyboardReturnType
*/
-let KeyboardReturnType = cc.Enum({
+export enum KeyboardReturnType {
/**
* !#en TODO
* !#zh 默认
* @property {Number} DEFAULT
*/
- DEFAULT: 0,
+ DEFAULT = 0,
/**
* !#en TODO
* !#zh 完成类型
* @property {Number} DONE
*/
- DONE: 1,
+ DONE = 1,
/**
* !#en TODO
* !#zh 发送类型
* @property {Number} SEND
*/
- SEND: 2,
+ SEND = 2,
/**
* !#en TODO
* !#zh 搜索类型
* @property {Number} SEARCH
*/
- SEARCH: 3,
+ SEARCH = 3,
/**
* !#en TODO
* !#zh 跳转类型
* @property {Number} GO
*/
- GO: 4,
+ GO = 4,
/**
* !#en TODO
* !#zh 下一个类型
* @property {Number} NEXT
*/
- NEXT: 5
-});
+ NEXT = 5,
+}
+Enum(KeyboardReturnType);
/**
* !#en The EditBox's InputMode defines the type of text that the user is allowed to enter.
@@ -73,37 +76,37 @@ let KeyboardReturnType = cc.Enum({
* @readonly
* @enum EditBox.InputMode
*/
-let InputMode = cc.Enum({
+export enum InputMode {
/**
* !#en TODO
* !#zh 用户可以输入任何文本,包括换行符。
* @property {Number} ANY
*/
- ANY: 0,
+ ANY = 0,
/**
* !#en The user is allowed to enter an e-mail address.
* !#zh 允许用户输入一个电子邮件地址。
* @property {Number} EMAIL_ADDR
*/
- EMAIL_ADDR: 1,
+ EMAIL_ADDR = 1,
/**
* !#en The user is allowed to enter an integer value.
* !#zh 允许用户输入一个整数值。
* @property {Number} NUMERIC
*/
- NUMERIC: 2,
+ NUMERIC = 2,
/**
* !#en The user is allowed to enter a phone number.
* !#zh 允许用户输入一个电话号码。
* @property {Number} PHONE_NUMBER
*/
- PHONE_NUMBER: 3,
+ PHONE_NUMBER = 3,
/**
* !#en The user is allowed to enter a URL.
* !#zh 允许用户输入一个 URL。
* @property {Number} URL
*/
- URL: 4,
+ URL = 4,
/**
* !#en
* The user is allowed to enter a real number value.
@@ -112,14 +115,16 @@ let InputMode = cc.Enum({
* 允许用户输入一个实数。
* @property {Number} DECIMAL
*/
- DECIMAL: 5,
+ DECIMAL = 5,
/**
* !#en The user is allowed to enter any text, except for line breaks.
* !#zh 除了换行符以外,用户可以输入任何文本。
* @property {Number} SINGLE_LINE
*/
- SINGLE_LINE: 6
-});
+ SINGLE_LINE = 6,
+}
+
+Enum(InputMode);
/**
* !#en Enum for the EditBox's input flags
@@ -127,7 +132,7 @@ let InputMode = cc.Enum({
* @readonly
* @enum EditBox.InputFlag
*/
-let InputFlag = cc.Enum({
+export enum InputFlag {
/**
* !#en
* Indicates that the text entered is confidential data that should be
@@ -136,7 +141,7 @@ let InputFlag = cc.Enum({
* 表明输入的文本是保密的数据,任何时候都应该隐藏起来,它隐含了 EDIT_BOX_INPUT_FLAG_SENSITIVE。
* @property {Number} PASSWORD
*/
- PASSWORD: 0,
+ PASSWORD = 0,
/**
* !#en
* Indicates that the text entered is sensitive data that the
@@ -148,7 +153,7 @@ let InputFlag = cc.Enum({
* 一个信用卡号码就是一个敏感数据的例子。
* @property {Number} SENSITIVE
*/
- SENSITIVE: 1,
+ SENSITIVE = 1,
/**
* !#en
* This flag is a hint to the implementation that during text editing,
@@ -157,7 +162,7 @@ let InputFlag = cc.Enum({
* 这个标志用来指定在文本编辑的时候,是否把每一个单词的首字母大写。
* @property {Number} INITIAL_CAPS_WORD
*/
- INITIAL_CAPS_WORD: 2,
+ INITIAL_CAPS_WORD = 2,
/**
* !#en
* This flag is a hint to the implementation that during text editing,
@@ -166,22 +171,18 @@ let InputFlag = cc.Enum({
* 这个标志用来指定在文本编辑是否每个句子的首字母大写。
* @property {Number} INITIAL_CAPS_SENTENCE
*/
- INITIAL_CAPS_SENTENCE: 3,
+ INITIAL_CAPS_SENTENCE = 3,
/**
* !#en Capitalize all characters automatically.
* !#zh 自动把输入的所有字符大写。
* @property {Number} INITIAL_CAPS_ALL_CHARACTERS
*/
- INITIAL_CAPS_ALL_CHARACTERS: 4,
+ INITIAL_CAPS_ALL_CHARACTERS = 4,
/**
* Don't do anything with the input text.
* @property {Number} DEFAULT
*/
- DEFAULT: 5
-});
+ DEFAULT = 5,
+}
-module.exports = {
- KeyboardReturnType: KeyboardReturnType,
- InputMode: InputMode,
- InputFlag: InputFlag
-};
+Enum(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..79b96d186c
--- /dev/null
+++ b/cocos/3d/ui/components/label-component.ts
@@ -0,0 +1,693 @@
+/****************************************************************************
+ 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 Font from '../../../assets/CCFont';
+import { ImageAsset } from '../../../assets/image-asset';
+import { Texture2D } from '../../../assets/texture-2d';
+// import { vec2, vec3, mat4, color4 } from '../../../core/vmath/index';
+import {
+ ccclass,
+ executeInEditMode,
+ executionOrder,
+ menu,
+ property,
+} from '../../../core/data/class-decorator';
+import macro from '../../../core/platform/CCMacro';
+import { Enum } from '../../../core/value-types';
+import { MeshBuffer } from '../mesh-buffer';
+import { UIRenderComponent } from './ui-render-component';
+// 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 UIRenderComponent
+ */
+@ccclass('cc.LabelComponent')
+@executionOrder(100)
+@menu('UI/Label')
+@executeInEditMode
+export class LabelComponent extends UIRenderComponent {
+
+ /**
+ * !#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;
+
+ 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 _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.get('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('u_texSampler', 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/2d/ui/CCLayout.js b/cocos/3d/ui/components/layout-component.ts
similarity index 52%
rename from cocos/2d/ui/CCLayout.js
rename to cocos/3d/ui/components/layout-component.ts
index ad0c8b7ff9..c19b245d94 100644
--- a/cocos/2d/ui/CCLayout.js
+++ b/cocos/3d/ui/components/layout-component.ts
@@ -24,66 +24,72 @@
THE SOFTWARE.
****************************************************************************/
-const NodeEvent = require('../CCNode').EventType;
-
+import { Component } from '../../../components/component';
+import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator';
+import { Enum, Size } from '../../../core/value-types';
+import { Node } from '../../../scene-graph/node';
+const NodeEvent = Node.EventType;
/**
* !#en Enum for Layout type
* !#zh 布局类型
* @enum Layout.Type
*/
-var Type = cc.Enum({
+enum Type {
/**
* !#en None Layout
* !#zh 取消布局
- *@property {Number} NONE
*/
- NONE: 0,
+ NONE = 0,
/**
* !#en Horizontal Layout
* !#zh 水平布局
* @property {Number} HORIZONTAL
*/
- HORIZONTAL: 1,
+ HORIZONTAL = 1,
/**
* !#en Vertical Layout
* !#zh 垂直布局
* @property {Number} VERTICAL
*/
- VERTICAL: 2,
+ VERTICAL = 2,
/**
* !#en Grid Layout
* !#zh 网格布局
* @property {Number} GRID
*/
- GRID: 3,
-});
+ GRID = 3,
+}
+
+Enum(Type);
/**
* !#en Enum for Layout Resize Mode
* !#zh 缩放模式
* @enum Layout.ResizeMode
*/
-var ResizeMode = cc.Enum({
+enum ResizeMode {
/**
* !#en Don't do any scale.
* !#zh 不做任何缩放
* @property {Number} NONE
*/
- NONE: 0,
+ NONE = 0,
/**
* !#en The container size will be expanded with its children's size.
* !#zh 容器的大小会根据子节点的大小自动缩放。
* @property {Number} CONTAINER
*/
- CONTAINER: 1,
+ CONTAINER = 1,
/**
* !#en Child item size will be adjusted with the container's size.
* !#zh 子节点的大小会随着容器的大小自动缩放。
* @property {Number} CHILDREN
*/
- CHILDREN: 2
-});
+ CHILDREN = 2,
+}
+
+Enum(ResizeMode);
/**
* !#en Enum for Grid Layout start axis direction.
@@ -91,20 +97,22 @@ var ResizeMode = cc.Enum({
* !#zh 布局轴向,只用于 GRID 布局。
* @enum Layout.AxisDirection
*/
-var AxisDirection = cc.Enum({
+enum AxisDirection {
/**
* !#en The horizontal axis.
* !#zh 进行水平方向布局
* @property {Number} HORIZONTAL
*/
- HORIZONTAL: 0,
+ HORIZONTAL = 0,
/**
* !#en The vertical axis.
* !#zh 进行垂直方向布局
* @property {Number} VERTICAL
*/
- VERTICAL: 1,
-});
+ VERTICAL = 1,
+}
+
+Enum(AxisDirection);
/**
* !#en Enum for vertical layout direction.
@@ -112,20 +120,22 @@ var AxisDirection = cc.Enum({
* !#zh 垂直方向布局方式
* @enum Layout.VerticalDirection
*/
-var VerticalDirection = cc.Enum({
+enum VerticalDirection {
/**
* !#en Items arranged from bottom to top.
* !#zh 从下到上排列
* @property {Number} BOTTOM_TO_TOP
*/
- BOTTOM_TO_TOP: 0,
+ BOTTOM_TO_TOP = 0,
/**
* !#en Items arranged from top to bottom.
* !#zh 从上到下排列
* @property {Number} TOP_TO_BOTTOM
*/
- TOP_TO_BOTTOM: 1,
-});
+ TOP_TO_BOTTOM = 1,
+}
+
+Enum(VerticalDirection);
/**
* !#en Enum for horizontal layout direction.
@@ -133,20 +143,20 @@ var VerticalDirection = cc.Enum({
* !#zh 水平方向布局方式
* @enum Layout.HorizontalDirection
*/
-var HorizontalDirection = cc.Enum({
+enum HorizontalDirection {
/**
* !#en Items arranged from left to right.
* !#zh 从左往右排列
- * @property {Number} LEFT_TO_RIGHT
*/
- LEFT_TO_RIGHT: 0,
+ LEFT_TO_RIGHT = 0,
/**
* !#en Items arranged from right to left.
* !#zh 从右往左排列
- *@property {Number} RIGHT_TO_LEFT
*/
- RIGHT_TO_LEFT: 1,
-});
+ RIGHT_TO_LEFT = 1,
+}
+
+Enum(HorizontalDirection);
/**
* !#en
@@ -163,257 +173,333 @@ var HorizontalDirection = cc.Enum({
* @class Layout
* @extends Component
*/
-var Layout = cc.Class({
- name: 'cc.Layout',
- extends: require('./CCComponent'),
+@ccclass('cc.LayoutComponent')
+@executionOrder(100)
+@menu('UI/Layout')
+@executeInEditMode
+export class LayoutComponent extends Component {
- editor: CC_EDITOR && {
- menu: 'i18n:MAIN_MENU.component.ui/Layout',
- help: 'i18n:COMPONENT.help_url.layout',
- inspector: 'packages://inspector/inspectors/comps/cclayout.js',
- executeInEditMode: true,
- },
+ /**
+ * !#en The layout type.
+ * !#zh 布局类型
+ * @property {Layout.Type} type
+ * @default Layout.Type.NONE
+ */
+ @property
+ get type () {
+ return this._N$layoutType;
+ }
- properties: {
- _layoutSize: cc.size(300, 200),
- _layoutDirty: {
- default: true,
- serializable: false,
- },
+ set type (value) {
+ this._N$layoutType = value;
- _resize: ResizeMode.NONE,
+ if (CC_EDITOR && this.type !== Type.NONE && this._resize === ResizeMode.CONTAINER && !cc.engine.isPlaying) {
+ // const reLayouted = _Scene.DetectConflict.checkConflict_Layout(this);
+ // if (reLayouted) {
+ // return;
+ // }
+ }
+ this._doLayoutDirty();
+ }
+ /**
+ * !#en
+ * The are three resize modes for Layout.
+ * None, resize Container and resize children.
+ * !#zh 缩放模式
+ * @property {Layout.ResizeMode} resizeMode
+ * @default ResizeMode.NONE
+ */
+ @property({
+ type: ResizeMode,
+ })
+ get resizeMode () {
+ return this._resize;
+ }
+ set resizeMode (value) {
+ if (this.type === Type.NONE && value === ResizeMode.CHILDREN) {
+ return;
+ }
- //TODO: refactoring this name after data upgrade machanism is out.
- _N$layoutType: Type.NONE,
- /**
- * !#en The layout type.
- * !#zh 布局类型
- * @property {Layout.Type} type
- * @default Layout.Type.NONE
- */
- type: {
- type: Type,
- get: function () {
- return this._N$layoutType;
- },
- set: function (value) {
- this._N$layoutType = value;
+ this._resize = value;
+ if (CC_EDITOR && value === ResizeMode.CONTAINER && !cc.engine.isPlaying) {
+ // const reLayouted = _Scene.DetectConflict.checkConflict_Layout(this);
+ // if (reLayouted) {
+ // return;
+ // }
+ }
+ this._doLayoutDirty();
+ }
- if (CC_EDITOR && this.type !== Type.NONE && this._resize === ResizeMode.CONTAINER && !cc.engine.isPlaying) {
- var reLayouted = _Scene.DetectConflict.checkConflict_Layout(this);
- if (reLayouted) {
- return;
- }
- }
- this._doLayoutDirty();
- },
- tooltip: CC_DEV && 'i18n:COMPONENT.layout.layout_type',
- animatable: false,
- },
+ /**
+ * !#en The cell size for grid layout.
+ * !#zh 每个格子的大小,只有布局类型为 GRID 的时候才有效。
+ * @property {Size} cellSize
+ * @default cc.size(40, 40)
+ */
+ @property
+ get cellSize () {
+ return this._cellSize;
+ }
+ set cellSize (value: Size) {
+ if (this._cellSize === value) {
+ return;
+ }
- /**
- * !#en
- * The are three resize modes for Layout.
- * None, resize Container and resize children.
- * !#zh 缩放模式
- * @property {Layout.ResizeMode} resizeMode
- * @default ResizeMode.NONE
- */
- resizeMode: {
- type: ResizeMode,
- tooltip: CC_DEV && 'i18n:COMPONENT.layout.resize_mode',
- animatable: false,
- get: function () {
- return this._resize;
- },
- set: function (value) {
- if (this.type === Type.NONE && value === ResizeMode.CHILDREN) {
- return;
- }
+ this._cellSize = value;
+ this._doLayoutDirty();
+ }
- this._resize = value;
- if (CC_EDITOR && value === ResizeMode.CONTAINER && !cc.engine.isPlaying) {
- var reLayouted = _Scene.DetectConflict.checkConflict_Layout(this);
- if (reLayouted) {
- return;
- }
- }
- this._doLayoutDirty();
- },
- },
+ /**
+ * !#en
+ * The start axis for grid layout. If you choose horizontal, then children will layout horizontally at first,
+ * and then break line on demand. Choose vertical if you want to layout vertically at first .
+ * !#zh 起始轴方向类型,可进行水平和垂直布局排列,只有布局类型为 GRID 的时候才有效。
+ * @property {Layout.AxisDirection} startAxis
+ */
+ @property
+ get startAxis () {
+ return this._startAxis;
+ }
- /**
- * !#en The cell size for grid layout.
- * !#zh 每个格子的大小,只有布局类型为 GRID 的时候才有效。
- * @property {Size} cellSize
- * @default cc.size(40, 40)
- */
- cellSize: {
- default: cc.size(40, 40),
- tooltip: CC_DEV && 'i18n:COMPONENT.layout.cell_size',
- type: cc.Size,
- notify: function () {
- this._doLayoutDirty();
- },
- },
+ set startAxis (value) {
+ if (this._startAxis === value) {
+ return;
+ }
- /**
- * !#en
- * The start axis for grid layout. If you choose horizontal, then children will layout horizontally at first,
- * and then break line on demand. Choose vertical if you want to layout vertically at first .
- * !#zh 起始轴方向类型,可进行水平和垂直布局排列,只有布局类型为 GRID 的时候才有效。
- * @property {Layout.AxisDirection} startAxis
- */
- startAxis: {
- default: AxisDirection.HORIZONTAL,
- tooltip: CC_DEV && 'i18n:COMPONENT.layout.start_axis',
- type: AxisDirection,
- notify: function () {
- if (CC_EDITOR && this._resize === ResizeMode.CONTAINER && !cc.engine.isPlaying) {
- var reLayouted = _Scene.DetectConflict.checkConflict_Layout(this);
- if (reLayouted) {
- return;
- }
- }
- this._doLayoutDirty();
- },
- animatable: false
- },
+ if (CC_EDITOR && this._resize === ResizeMode.CONTAINER && !cc.engine.isPlaying) {
+ // const reLayouted = _Scene.DetectConflict.checkConflict_Layout(this);
+ // if (reLayouted) {
+ // return;
+ // }
+ }
- _N$padding: {
- default: 0
- },
- /**
- * !#en The left padding of layout, it only effect the layout in one direction.
- * !#zh 容器内左边距,只会在一个布局方向上生效。
- * @property {Number} paddingLeft
- */
- paddingLeft: {
- default: 0,
- tooltip: CC_DEV && 'i18n:COMPONENT.layout.padding_left',
- notify: function () {
- this._doLayoutDirty();
- },
- },
+ this._startAxis = value;
+ this._doLayoutDirty();
+ }
+ /**
+ * !#en The left padding of layout, it only effect the layout in one direction.
+ * !#zh 容器内左边距,只会在一个布局方向上生效。
+ * @property {Number} paddingLeft
+ */
+ @property
+ get paddingLeft () {
+ return this._paddingLeft;
+ }
+ set paddingLeft (value) {
+ if (this._paddingLeft === value) {
+ return;
+ }
- /**
- * !#en The right padding of layout, it only effect the layout in one direction.
- * !#zh 容器内右边距,只会在一个布局方向上生效。
- * @property {Number} paddingRight
- */
- paddingRight: {
- default: 0,
- tooltip: CC_DEV && 'i18n:COMPONENT.layout.padding_right',
- notify: function () {
- this._doLayoutDirty();
- },
- },
+ this._paddingLeft = value;
+ this._doLayoutDirty();
+ }
- /**
- * !#en The top padding of layout, it only effect the layout in one direction.
- * !#zh 容器内上边距,只会在一个布局方向上生效。
- * @property {Number} paddingTop
- */
- paddingTop: {
- default: 0,
- tooltip: CC_DEV && 'i18n:COMPONENT.layout.padding_top',
- notify: function () {
- this._doLayoutDirty();
- },
- },
+ /**
+ * !#en The right padding of layout, it only effect the layout in one direction.
+ * !#zh 容器内右边距,只会在一个布局方向上生效。
+ * @property {Number} paddingRight
+ */
+ @property
+ get paddingRight () {
+ return this._paddingRight;
+ }
+ set paddingRight (value) {
+ if (this._paddingRight === value) {
+ return;
+ }
- /**
- * !#en The bottom padding of layout, it only effect the layout in one direction.
- * !#zh 容器内下边距,只会在一个布局方向上生效。
- * @property {Number} paddingBottom
- */
- paddingBottom: {
- default: 0,
- tooltip: CC_DEV && 'i18n:COMPONENT.layout.padding_bottom',
- notify: function () {
- this._doLayoutDirty();
- },
- },
+ this._paddingRight = value;
+ this._doLayoutDirty();
+ }
- /**
- * !#en The distance in x-axis between each element in layout.
- * !#zh 子节点之间的水平间距。
- * @property {Number} spacingX
- */
- spacingX: {
- default: 0,
- notify: function () {
- this._doLayoutDirty();
- },
- tooltip: CC_DEV && 'i18n:COMPONENT.layout.space_x'
- },
+ /**
+ * !#en The top padding of layout, it only effect the layout in one direction.
+ * !#zh 容器内上边距,只会在一个布局方向上生效。
+ * @property {Number} paddingTop
+ */
+ @property
+ get paddingTop () {
+ return this._paddingTop;
+ }
+ set paddingTop (value) {
+ if (this._paddingTop === value) {
+ return;
+ }
- /**
- * !#en The distance in y-axis between each element in layout.
- * !#zh 子节点之间的垂直间距。
- * @property {Number} spacingY
- */
- spacingY: {
- default: 0,
- notify: function () {
- this._doLayoutDirty();
- },
- tooltip: CC_DEV && 'i18n:COMPONENT.layout.space_y'
- },
+ this._paddingTop = value;
+ this._doLayoutDirty();
+ }
- /**
- * !#en
- * Only take effect in Vertical layout mode.
- * This option changes the start element's positioning.
- * !#zh 垂直排列子节点的方向。
- * @property {Layout.VerticalDirection} verticalDirection
- */
- verticalDirection: {
- default: VerticalDirection.TOP_TO_BOTTOM,
- type: VerticalDirection,
- notify: function () {
- this._doLayoutDirty();
- },
- tooltip: CC_DEV && 'i18n:COMPONENT.layout.vertical_direction',
- animatable: false
- },
+ /**
+ * !#en The bottom padding of layout, it only effect the layout in one direction.
+ * !#zh 容器内下边距,只会在一个布局方向上生效。
+ * @property {Number} paddingBottom
+ */
+ @property
+ get paddingBottom () {
+ return this._paddingBottom;
+ }
+ set paddingBottom (value) {
+ if (this._paddingBottom === value) {
+ return;
+ }
- /**
- * !#en
- * Only take effect in Horizontal layout mode.
- * This option changes the start element's positioning.
- * !#zh 水平排列子节点的方向。
- * @property {Layout.HorizontalDirection} horizontalDirection
- */
- horizontalDirection: {
- default: HorizontalDirection.LEFT_TO_RIGHT,
- type: HorizontalDirection,
- notify: function () {
- this._doLayoutDirty();
- },
- tooltip: CC_DEV && 'i18n:COMPONENT.layout.horizontal_direction',
- animatable: false
- },
- },
+ this._paddingBottom = value;
+ this._doLayoutDirty();
+ }
- statics: {
- Type: Type,
- VerticalDirection: VerticalDirection,
- HorizontalDirection: HorizontalDirection,
- ResizeMode: ResizeMode,
- AxisDirection: AxisDirection,
- },
+ /**
+ * !#en The distance in x-axis between each element in layout.
+ * !#zh 子节点之间的水平间距。
+ * @property {Number} spacingX
+ */
+ get spacingX () {
+ return this._spacingX;
+ }
- _migratePaddingData: function () {
+ set spacingX (value) {
+ if (this._spacingX === value) {
+ return;
+ }
+
+ this._spacingX = value;
+ this._doLayoutDirty();
+ }
+
+ /**
+ * !#en The distance in y-axis between each element in layout.
+ * !#zh 子节点之间的垂直间距。
+ * @property {Number} spacingY
+ */
+ @property
+ get spacingY () {
+ return this._spacingY;
+ }
+
+ set spacingY (value) {
+ if (this._spacingY === value) {
+ return;
+ }
+
+ this._spacingY = value;
+ this._doLayoutDirty();
+ }
+
+ /**
+ * !#en
+ * Only take effect in Vertical layout mode.
+ * This option changes the start element's positioning.
+ * !#zh 垂直排列子节点的方向。
+ * @property {VerticalDirection} verticalDirection
+ */
+ @property({
+ type: VerticalDirection,
+ })
+ get verticalDirection () {
+ return this._verticalDirection;
+ }
+
+ set verticalDirection (value: VerticalDirection) {
+ if (this._verticalDirection === value) {
+ return;
+ }
+
+ this._verticalDirection = value;
+ this._doLayoutDirty();
+ }
+
+ /**
+ * !#en
+ * Only take effect in Horizontal layout mode.
+ * This option changes the start element's positioning.
+ * !#zh 水平排列子节点的方向。
+ * @property {Layout.HorizontalDirection} horizontalDirection
+ */
+ @property({
+ type: HorizontalDirection,
+ })
+ get horizontalDirection () {
+ return this._horizontalDirection;
+ }
+
+ set horizontalDirection (value: HorizontalDirection) {
+ if (this._horizontalDirection === value) {
+ return;
+ }
+
+ this._horizontalDirection = value;
+ this._doLayoutDirty();
+ }
+
+ /**
+ * !#en The padding of layout, it effects the layout in four direction.
+ * !#zh 容器内边距,该属性会在四个布局方向上生效。
+ * @property {Number} padding
+ */
+ @property
+ get padding() {
+ return this._paddingLeft;
+ }
+
+ set padding(value) {
+ this._N$padding = value;
+
+ this._migratePaddingData();
+ this._doLayoutDirty();
+ }
+
+ /**
+ * !#en Adjust the layout if the children scaled.
+ * !#zh 子节点缩放比例是否影响布局。
+ * @property affectedByScale
+ * @type {Boolean}
+ * @default false
+ */
+ @property
+ get affectedByScale() {
+ return this._affectedByScale;
+ }
+
+ set affectedByScale(value) {
+ this._affectedByScale = value;
+ this._doLayoutDirty();
+ }
+
+ public static Type = Type;
+ public static VerticalDirection = VerticalDirection;
+ public static HorizontalDirection = HorizontalDirection;
+ public static ResizeMode = ResizeMode;
+ public static AxisDirection = AxisDirection;
+
+ private _layoutDirty = true;
+ private _resize = ResizeMode.NONE;
+
+ // TODO: refactoring this name after data upgrade machanism is out.
+ private _N$layoutType = Type.NONE;
+ private _N$padding = 0;
+ private _cellSize = cc.size(40, 40);
+ private _startAxis = AxisDirection.HORIZONTAL;
+ private _paddingLeft = 0;
+ private _paddingRight = 0;
+ private _paddingTop = 0;
+ private _paddingBottom = 0;
+ private _spacingX = 0;
+ private _spacingY = 0;
+ private _layoutSize = cc.size(300, 200);
+ private _verticalDirection = VerticalDirection.TOP_TO_BOTTOM;
+ private _horizontalDirection = HorizontalDirection.LEFT_TO_RIGHT;
+ private _affectedByScale = false;
+
+ private _migratePaddingData () {
this.paddingLeft = this._N$padding;
this.paddingRight = this._N$padding;
this.paddingTop = this._N$padding;
this.paddingBottom = this._N$padding;
this._N$padding = 0;
- },
+ }
- onEnable: function () {
+ protected onEnable () {
this._addEventListeners();
if (this.node.getContentSize().equals(cc.size(0, 0))) {
@@ -425,17 +511,13 @@ var Layout = cc.Class({
}
this._doLayoutDirty();
- },
+ }
- onDisable: function () {
+ protected onDisable () {
this._removeEventListeners();
- },
+ }
- _doLayoutDirty: function () {
- this._layoutDirty = true;
- },
-
- _addEventListeners: function () {
+ private _addEventListeners () {
cc.director.on(cc.Director.EVENT_AFTER_UPDATE, this.updateLayout, this);
this.node.on(NodeEvent.SIZE_CHANGED, this._resized, this);
this.node.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this);
@@ -443,9 +525,9 @@ var Layout = cc.Class({
this.node.on(NodeEvent.CHILD_REMOVED, this._childRemoved, this);
this.node.on(NodeEvent.CHILD_REORDER, this._doLayoutDirty, this);
this._addChildrenEventListeners();
- },
+ }
- _removeEventListeners: function () {
+ private _removeEventListeners () {
cc.director.off(cc.Director.EVENT_AFTER_UPDATE, this.updateLayout, this);
this.node.off(NodeEvent.SIZE_CHANGED, this._resized, this);
this.node.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this);
@@ -453,96 +535,98 @@ var Layout = cc.Class({
this.node.off(NodeEvent.CHILD_REMOVED, this._childRemoved, this);
this.node.off(NodeEvent.CHILD_REORDER, this._doLayoutDirty, this);
this._removeChildrenEventListeners();
- },
+ }
- _addChildrenEventListeners: function () {
- var children = this.node.children;
- for (var i = 0; i < children.length; ++i) {
- var child = children[i];
+ private _addChildrenEventListeners () {
+ const children = this.node.children;
+ for (const child of children) {
+ child.on(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this);
child.on(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this);
child.on(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this);
child.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this);
child.on('active-in-hierarchy-changed', this._doLayoutDirty, this);
}
- },
+ }
- _removeChildrenEventListeners: function () {
- var children = this.node.children;
- for (var i = 0; i < children.length; ++i) {
- var child = children[i];
+ private _removeChildrenEventListeners () {
+ const children = this.node.children;
+ for (const child of children) {
+ child.off(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this);
child.off(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this);
child.off(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this);
child.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this);
child.off('active-in-hierarchy-changed', this._doLayoutDirty, this);
}
- },
+ }
- _childAdded: function (child) {
+ private _childAdded (child) {
+ child.on(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this);
child.on(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this);
child.on(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this);
child.on(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this);
child.on('active-in-hierarchy-changed', this._doLayoutDirty, this);
this._doLayoutDirty();
- },
+ }
- _childRemoved: function (child) {
+ private _childRemoved (child) {
+ child.off(NodeEvent.SCALE_CHANGED, this._doScaleDirty, this);
child.off(NodeEvent.SIZE_CHANGED, this._doLayoutDirty, this);
child.off(NodeEvent.POSITION_CHANGED, this._doLayoutDirty, this);
child.off(NodeEvent.ANCHOR_CHANGED, this._doLayoutDirty, this);
child.off('active-in-hierarchy-changed', this._doLayoutDirty, this);
this._doLayoutDirty();
- },
+ }
- _resized: function () {
+ private _resized () {
this._layoutSize = this.node.getContentSize();
this._doLayoutDirty();
- },
+ }
- _doLayoutHorizontally: function (baseWidth, rowBreak, fnPositionY, applyChildren) {
- var layoutAnchor = this.node.getAnchorPoint();
- var children = this.node.children;
+ private _doLayoutHorizontally (baseWidth, rowBreak, fnPositionY, applyChildren) {
+ const layoutAnchor = this.node.getAnchorPoint();
+ const children = this.node.children;
- var sign = 1;
- var paddingX = this.paddingLeft;
- var leftBoundaryOfLayout = -layoutAnchor.x * baseWidth;
+ let sign = 1;
+ let paddingX = this.paddingLeft;
+ let leftBoundaryOfLayout = -layoutAnchor.x * baseWidth;
if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) {
sign = -1;
leftBoundaryOfLayout = (1 - layoutAnchor.x) * baseWidth;
paddingX = this.paddingRight;
}
- var nextX = leftBoundaryOfLayout + sign * paddingX - sign * this.spacingX;
- var rowMaxHeight = 0;
- var tempMaxHeight = 0;
- var secondMaxHeight = 0;
- var row = 0;
- var containerResizeBoundary = 0;
+ let nextX = leftBoundaryOfLayout + sign * paddingX - sign * this.spacingX;
+ let rowMaxHeight = 0;
+ let tempMaxHeight = 0;
+ let secondMaxHeight = 0;
+ let row = 0;
+ let containerResizeBoundary = 0;
- var maxHeightChildAnchorY = 0;
+ let maxHeightChildAnchorY = 0;
+
+ let activeChildCount = 0;
+ for (const child of children) {
- var activeChildCount = 0;
- for (var i = 0; i < children.length; ++i) {
- var child = children[i];
if (child.activeInHierarchy) {
activeChildCount++;
}
}
- var newChildWidth = this.cellSize.width;
+ let newChildWidth = this.cellSize.width;
if (this.type !== Type.GRID && this.resizeMode === ResizeMode.CHILDREN) {
newChildWidth = (baseWidth - (this.paddingLeft + this.paddingRight) - (activeChildCount - 1) * this.spacingX) / activeChildCount;
}
- for (var i = 0; i < children.length; ++i) {
- var child = children[i];
- let childScaleX = Math.abs(child.scaleX);
- let childScaleY = Math.abs(child.scaleY);
+ for (const child of children) {
+
+ const childScaleX = this._getUsedScaleValue(child.scaleX);
+ const childScaleY = this._getUsedScaleValue(child.scaleY);
if (!child.activeInHierarchy) {
continue;
}
- //for resizing children
+ // for resizing children
if (this._resize === ResizeMode.CHILDREN) {
child.width = newChildWidth / childScaleX;
if (this.type === Type.GRID) {
@@ -550,9 +634,9 @@ var Layout = cc.Class({
}
}
- var anchorX = child.anchorX;
- var childBoundingBoxWidth = child.width * childScaleX;
- var childBoundingBoxHeight = child.height * childScaleY;
+ let anchorX = child.anchorX;
+ const childBoundingBoxWidth = child.width * childScaleX;
+ const childBoundingBoxHeight = child.height * childScaleY;
if (secondMaxHeight > tempMaxHeight) {
tempMaxHeight = secondMaxHeight;
@@ -568,12 +652,12 @@ var Layout = cc.Class({
anchorX = 1 - child.anchorX;
}
nextX = nextX + sign * anchorX * childBoundingBoxWidth + sign * this.spacingX;
- var rightBoundaryOfChild = sign * (1 - anchorX) * childBoundingBoxWidth;
+ const rightBoundaryOfChild = sign * (1 - anchorX) * childBoundingBoxWidth;
if (rowBreak) {
- var rowBreakBoundary = nextX + rightBoundaryOfChild + sign * (sign > 0 ? this.paddingRight : this.paddingLeft);
- var leftToRightRowBreak = this.horizontalDirection === HorizontalDirection.LEFT_TO_RIGHT && rowBreakBoundary > (1 - layoutAnchor.x) * baseWidth;
- var rightToLeftRowBreak = this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT && rowBreakBoundary < -layoutAnchor.x * baseWidth;
+ const rowBreakBoundary = nextX + rightBoundaryOfChild + sign * (sign > 0 ? this.paddingRight : this.paddingLeft);
+ const leftToRightRowBreak = this.horizontalDirection === HorizontalDirection.LEFT_TO_RIGHT && rowBreakBoundary > (1 - layoutAnchor.x) * baseWidth;
+ const rightToLeftRowBreak = this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT && rowBreakBoundary < -layoutAnchor.x * baseWidth;
if (leftToRightRowBreak || rightToLeftRowBreak) {
@@ -583,8 +667,7 @@ var Layout = cc.Class({
}
rowMaxHeight += secondMaxHeight;
secondMaxHeight = tempMaxHeight;
- }
- else {
+ } else {
rowMaxHeight += tempMaxHeight;
secondMaxHeight = childBoundingBoxHeight;
tempMaxHeight = 0;
@@ -594,16 +677,16 @@ var Layout = cc.Class({
}
}
- var finalPositionY = fnPositionY(child, rowMaxHeight, row);
+ const finalPositionY = fnPositionY(child, rowMaxHeight, row);
if (baseWidth >= (childBoundingBoxWidth + this.paddingLeft + this.paddingRight)) {
if (applyChildren) {
child.setPosition(cc.v2(nextX, finalPositionY));
}
}
- var signX = 1;
- var tempFinalPositionY;
- var topMarign = (tempMaxHeight === 0) ? childBoundingBoxHeight : tempMaxHeight;
+ let signX = 1;
+ let tempFinalPositionY;
+ const topMarign = (tempMaxHeight === 0) ? childBoundingBoxHeight : tempMaxHeight;
if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) {
containerResizeBoundary = containerResizeBoundary || this.node._contentSize.height;
@@ -612,8 +695,7 @@ var Layout = cc.Class({
if (tempFinalPositionY < containerResizeBoundary) {
containerResizeBoundary = tempFinalPositionY;
}
- }
- else {
+ } else {
containerResizeBoundary = containerResizeBoundary || -this.node._contentSize.height;
tempFinalPositionY = finalPositionY + signX * (topMarign * maxHeightChildAnchorY + this.paddingTop);
if (tempFinalPositionY > containerResizeBoundary) {
@@ -625,71 +707,68 @@ var Layout = cc.Class({
}
return containerResizeBoundary;
- },
+ }
- _getVerticalBaseHeight: function (children) {
- var newHeight = 0;
- var activeChildCount = 0;
+ private _getVerticalBaseHeight (children) {
+ let newHeight = 0;
+ let activeChildCount = 0;
if (this.resizeMode === ResizeMode.CONTAINER) {
- for (var i = 0; i < children.length; ++i) {
- var child = children[i];
+ for (const child of children) {
if (child.activeInHierarchy) {
activeChildCount++;
- newHeight += child.height * Math.abs(child.scaleY);
+ newHeight += child.height * this._getUsedScaleValue(child.scaleY);
}
}
newHeight += (activeChildCount - 1) * this.spacingY + this.paddingBottom + this.paddingTop;
- }
- else {
+ } else {
newHeight = this.node.getContentSize().height;
}
return newHeight;
- },
+ }
- _doLayoutVertically: function (baseHeight, columnBreak, fnPositionX, applyChildren) {
- var layoutAnchor = this.node.getAnchorPoint();
- var children = this.node.children;
+ private _doLayoutVertically (baseHeight, columnBreak, fnPositionX, applyChildren) {
+ const layoutAnchor = this.node.getAnchorPoint();
+ const children = this.node.children;
- var sign = 1;
- var paddingY = this.paddingBottom;
- var bottomBoundaryOfLayout = -layoutAnchor.y * baseHeight;
+ let sign = 1;
+ let paddingY = this.paddingBottom;
+ let bottomBoundaryOfLayout = -layoutAnchor.y * baseHeight;
if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) {
sign = -1;
bottomBoundaryOfLayout = (1 - layoutAnchor.y) * baseHeight;
paddingY = this.paddingTop;
}
- var nextY = bottomBoundaryOfLayout + sign * paddingY - sign * this.spacingY;
- var columnMaxWidth = 0;
- var tempMaxWidth = 0;
- var secondMaxWidth = 0;
- var column = 0;
- var containerResizeBoundary = 0;
- var maxWidthChildAnchorX = 0;
+ let nextY = bottomBoundaryOfLayout + sign * paddingY - sign * this.spacingY;
+ let columnMaxWidth = 0;
+ let tempMaxWidth = 0;
+ let secondMaxWidth = 0;
+ let column = 0;
+ let containerResizeBoundary = 0;
+ let maxWidthChildAnchorX = 0;
- var activeChildCount = 0;
- for (var i = 0; i < children.length; ++i) {
- var child = children[i];
+ let activeChildCount = 0;
+ for (const child of children) {
if (child.activeInHierarchy) {
activeChildCount++;
}
}
- var newChildHeight = this.cellSize.height;
+ let newChildHeight = this.cellSize.height;
if (this.type !== Type.GRID && this.resizeMode === ResizeMode.CHILDREN) {
newChildHeight = (baseHeight - (this.paddingTop + this.paddingBottom) - (activeChildCount - 1) * this.spacingY) / activeChildCount;
}
- for (var i = 0; i < children.length; ++i) {
- var child = children[i];
- let childScaleX = Math.abs(child.scaleX);
- let childScaleY = Math.abs(child.scaleY);
+ for (const child of children) {
+
+ const childScaleX = this._getUsedScaleValue(child.scaleX);
+ const childScaleY = this._getUsedScaleValue(child.scaleY);
if (!child.activeInHierarchy) {
continue;
}
- //for resizing children
+ // for resizing children
if (this.resizeMode === ResizeMode.CHILDREN) {
child.height = newChildHeight / childScaleY;
if (this.type === Type.GRID) {
@@ -697,9 +776,9 @@ var Layout = cc.Class({
}
}
- var anchorY = child.anchorY;
- var childBoundingBoxWidth = child.width * childScaleX;
- var childBoundingBoxHeight = child.height * childScaleY;
+ let anchorY = child.anchorY;
+ const childBoundingBoxWidth = child.width * childScaleX;
+ const childBoundingBoxHeight = child.height * childScaleY;
if (secondMaxWidth > tempMaxWidth) {
tempMaxWidth = secondMaxWidth;
@@ -715,12 +794,12 @@ var Layout = cc.Class({
anchorY = 1 - child.anchorY;
}
nextY = nextY + sign * anchorY * childBoundingBoxHeight + sign * this.spacingY;
- var topBoundaryOfChild = sign * (1 - anchorY) * childBoundingBoxHeight;
+ const topBoundaryOfChild = sign * (1 - anchorY) * childBoundingBoxHeight;
if (columnBreak) {
- var columnBreakBoundary = nextY + topBoundaryOfChild + sign * (sign > 0 ? this.paddingTop : this.paddingBottom);
- var bottomToTopColumnBreak = this.verticalDirection === VerticalDirection.BOTTOM_TO_TOP && columnBreakBoundary > (1 - layoutAnchor.y) * baseHeight;
- var topToBottomColumnBreak = this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM && columnBreakBoundary < -layoutAnchor.y * baseHeight;
+ const columnBreakBoundary = nextY + topBoundaryOfChild + sign * (sign > 0 ? this.paddingTop : this.paddingBottom);
+ const bottomToTopColumnBreak = this.verticalDirection === VerticalDirection.BOTTOM_TO_TOP && columnBreakBoundary > (1 - layoutAnchor.y) * baseHeight;
+ const topToBottomColumnBreak = this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM && columnBreakBoundary < -layoutAnchor.y * baseHeight;
if (bottomToTopColumnBreak || topToBottomColumnBreak) {
if (childBoundingBoxWidth >= tempMaxWidth) {
@@ -729,8 +808,7 @@ var Layout = cc.Class({
}
columnMaxWidth += secondMaxWidth;
secondMaxWidth = tempMaxWidth;
- }
- else {
+ } else {
columnMaxWidth += tempMaxWidth;
secondMaxWidth = childBoundingBoxWidth;
tempMaxWidth = 0;
@@ -740,17 +818,17 @@ var Layout = cc.Class({
}
}
- var finalPositionX = fnPositionX(child, columnMaxWidth, column);
+ const finalPositionX = fnPositionX(child, columnMaxWidth, column);
if (baseHeight >= (childBoundingBoxHeight + (this.paddingTop + this.paddingBottom))) {
if (applyChildren) {
child.setPosition(cc.v2(finalPositionX, nextY));
}
}
- var signX = 1;
- var tempFinalPositionX;
- //when the item is the last column break item, the tempMaxWidth will be 0.
- var rightMarign = (tempMaxWidth === 0) ? childBoundingBoxWidth : tempMaxWidth;
+ let signX = 1;
+ let tempFinalPositionX;
+ // when the item is the last column break item, the tempMaxWidth will be 0.
+ const rightMarign = (tempMaxWidth === 0) ? childBoundingBoxWidth : tempMaxWidth;
if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) {
signX = -1;
@@ -759,8 +837,7 @@ var Layout = cc.Class({
if (tempFinalPositionX < containerResizeBoundary) {
containerResizeBoundary = tempFinalPositionX;
}
- }
- else {
+ } else {
containerResizeBoundary = containerResizeBoundary || -this.node._contentSize.width;
tempFinalPositionX = finalPositionX + signX * (rightMarign * maxWidthChildAnchorX + this.paddingRight);
if (tempFinalPositionX > containerResizeBoundary) {
@@ -773,66 +850,67 @@ var Layout = cc.Class({
}
return containerResizeBoundary;
- },
+ }
- _doLayoutBasic: function () {
- var children = this.node.children;
+ private _doLayoutBasic () {
+ const children = this.node.children;
- var allChildrenBoundingBox = null;
+ let allChildrenBoundingBox = null;
- for (var i = 0; i < children.length; ++i) {
- var child = children[i];
+ for (const child of children) {
if (child.activeInHierarchy) {
if (!allChildrenBoundingBox) {
allChildrenBoundingBox = child.getBoundingBoxToWorld();
} else {
- allChildrenBoundingBox.union(allChildrenBoundingBox, child.getBoundingBoxToWorld());
+ // allChildrenBoundingBox.union(allChildrenBoundingBox, child.getBoundingBoxToWorld());
}
}
}
if (allChildrenBoundingBox) {
- var leftBottomInParentSpace = this.node.parent.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x, allChildrenBoundingBox.y));
+ let leftBottomInParentSpace = this.node.parent.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x, allChildrenBoundingBox.y));
leftBottomInParentSpace = cc.v2(leftBottomInParentSpace.x - this.paddingLeft, leftBottomInParentSpace.y - this.paddingBottom);
- var rightTopInParentSpace = this.node.parent.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x + allChildrenBoundingBox.width,
- allChildrenBoundingBox.y + allChildrenBoundingBox.height));
+ let rightTopInParentSpace = this.node.parent.convertToNodeSpaceAR(cc.v2(allChildrenBoundingBox.x + allChildrenBoundingBox.width,
+ allChildrenBoundingBox.y + allChildrenBoundingBox.height));
rightTopInParentSpace = cc.v2(rightTopInParentSpace.x + this.paddingRight, rightTopInParentSpace.y + this.paddingTop);
- var newSize = cc.size(parseFloat((rightTopInParentSpace.x - leftBottomInParentSpace.x).toFixed(2)),
- parseFloat((rightTopInParentSpace.y - leftBottomInParentSpace.y).toFixed(2)));
+ const newSize = cc.size(parseFloat((rightTopInParentSpace.x - leftBottomInParentSpace.x).toFixed(2)),
+ parseFloat((rightTopInParentSpace.y - leftBottomInParentSpace.y).toFixed(2)));
- var layoutPosition = this.node.getPosition();
- var newAnchorX = (layoutPosition.x - leftBottomInParentSpace.x) / newSize.width;
- var newAnchorY = (layoutPosition.y - leftBottomInParentSpace.y) / newSize.height;
- var newAnchor = cc.v2(parseFloat(newAnchorX.toFixed(2)), parseFloat(newAnchorY.toFixed(2)));
-
- this.node.setAnchorPoint(newAnchor);
+ const layoutPosition = this.node.getPosition();
+ if (newSize.width !== 0) {
+ const newAnchorX = (layoutPosition.x - leftBottomInParentSpace.x) / newSize.width;
+ this.node.anchorX = parseFloat(newAnchorX.toFixed(2));
+ }
+ if (newSize.height !== 0) {
+ const newAnchorY = (layoutPosition.y - leftBottomInParentSpace.y) / newSize.height;
+ this.node.anchorY = parseFloat(newAnchorY.toFixed(2));
+ }
this.node.setContentSize(newSize);
}
- },
+ }
- _doLayoutGridAxisHorizontal: function (layoutAnchor, layoutSize) {
- var baseWidth = layoutSize.width;
+ private _doLayoutGridAxisHorizontal (layoutAnchor, layoutSize) {
+ const baseWidth = layoutSize.width;
- var sign = 1;
- var bottomBoundaryOfLayout = -layoutAnchor.y * layoutSize.height;
- var paddingY = this.paddingBottom;
+ let sign = 1;
+ let bottomBoundaryOfLayout = -layoutAnchor.y * layoutSize.height;
+ let paddingY = this.paddingBottom;
if (this.verticalDirection === VerticalDirection.TOP_TO_BOTTOM) {
sign = -1;
bottomBoundaryOfLayout = (1 - layoutAnchor.y) * layoutSize.height;
paddingY = this.paddingTop;
}
- var fnPositionY = function (child, topOffset, row) {
- return bottomBoundaryOfLayout + sign * (topOffset + child.anchorY * child.height * Math.abs(child.scaleY) + paddingY + row * this.spacingY);
+ const fnPositionY = function (child, topOffset, row) {
+ return bottomBoundaryOfLayout + sign * (topOffset + child.anchorY * child.height * this._getUsedScaleValue(child.scaleY) + paddingY + row * this.spacingY);
}.bind(this);
-
- var newHeight = 0;
+ let newHeight = 0;
if (this.resizeMode === ResizeMode.CONTAINER) {
- //calculate the new height of container, it won't change the position of it's children
- var boundary = this._doLayoutHorizontally(baseWidth, true, fnPositionY, false);
+ // calculate the new height of container, it won't change the position of it's children
+ const boundary = this._doLayoutHorizontally(baseWidth, true, fnPositionY, false);
newHeight = bottomBoundaryOfLayout - boundary;
if (newHeight < 0) {
newHeight *= -1;
@@ -851,27 +929,27 @@ var Layout = cc.Class({
if (this.resizeMode === ResizeMode.CONTAINER) {
this.node.setContentSize(baseWidth, newHeight);
}
- },
+ }
- _doLayoutGridAxisVertical: function (layoutAnchor, layoutSize) {
- var baseHeight = layoutSize.height;
+ private _doLayoutGridAxisVertical (layoutAnchor, layoutSize) {
+ const baseHeight = layoutSize.height;
- var sign = 1;
- var leftBoundaryOfLayout = -layoutAnchor.x * layoutSize.width;
- var paddingX = this.paddingLeft;
+ let sign = 1;
+ let leftBoundaryOfLayout = -layoutAnchor.x * layoutSize.width;
+ let paddingX = this.paddingLeft;
if (this.horizontalDirection === HorizontalDirection.RIGHT_TO_LEFT) {
sign = -1;
leftBoundaryOfLayout = (1 - layoutAnchor.x) * layoutSize.width;
paddingX = this.paddingRight;
}
- var fnPositionX = function (child, leftOffset, column) {
- return leftBoundaryOfLayout + sign * (leftOffset + child.anchorX * child.width * Math.abs(child.scaleX) + paddingX + column * this.spacingX);
+ const fnPositionX = function (child, leftOffset, column) {
+ return leftBoundaryOfLayout + sign * (leftOffset + child.anchorX * child.width * this._getUsedScaleValue(child.scaleX) + paddingX + column * this.spacingX);
}.bind(this);
- var newWidth = 0;
+ let newWidth = 0;
if (this.resizeMode === ResizeMode.CONTAINER) {
- var boundary = this._doLayoutVertically(baseHeight, true, fnPositionX, false);
+ const boundary = this._doLayoutVertically(baseHeight, true, fnPositionX, false);
newWidth = leftBoundaryOfLayout - boundary;
if (newWidth < 0) {
newWidth *= -1;
@@ -890,74 +968,72 @@ var Layout = cc.Class({
if (this.resizeMode === ResizeMode.CONTAINER) {
this.node.setContentSize(newWidth, baseHeight);
}
- },
+ }
- _doLayoutGrid: function () {
- var layoutAnchor = this.node.getAnchorPoint();
- var layoutSize = this.node.getContentSize();
+ private _doLayoutGrid () {
+ const layoutAnchor = this.node.getAnchorPoint();
+ const layoutSize = this.node.getContentSize();
if (this.startAxis === AxisDirection.HORIZONTAL) {
this._doLayoutGridAxisHorizontal(layoutAnchor, layoutSize);
- }
- else if (this.startAxis === AxisDirection.VERTICAL) {
+ } else if (this.startAxis === AxisDirection.VERTICAL) {
this._doLayoutGridAxisVertical(layoutAnchor, layoutSize);
}
- },
+ }
- _getHorizontalBaseWidth: function (children) {
- var newWidth = 0;
- var activeChildCount = 0;
+ private _getHorizontalBaseWidth (children) {
+ let newWidth = 0;
+ let activeChildCount = 0;
if (this.resizeMode === ResizeMode.CONTAINER) {
- for (var i = 0; i < children.length; ++i) {
- var child = children[i];
+ for (const child of children) {
if (child.activeInHierarchy) {
activeChildCount++;
- newWidth += child.width * Math.abs(child.scaleX);
+ newWidth += child.width * this._getUsedScaleValue(child.scaleX);
}
}
newWidth += (activeChildCount - 1) * this.spacingX + this.paddingLeft + this.paddingRight;
- }
- else {
+ } else {
newWidth = this.node.getContentSize().width;
}
return newWidth;
- },
+ }
- _doLayout: function () {
+ private _doLayout () {
if (this.type === Type.HORIZONTAL) {
- var newWidth = this._getHorizontalBaseWidth(this.node.children);
+ const newWidth = this._getHorizontalBaseWidth(this.node.children);
- var fnPositionY = function (child) {
+ const fnPositionY = (child) => {
return child.y;
};
this._doLayoutHorizontally(newWidth, false, fnPositionY, true);
this.node.width = newWidth;
- }
- else if (this.type === Type.VERTICAL) {
- var newHeight = this._getVerticalBaseHeight(this.node.children);
+ } else if (this.type === Type.VERTICAL) {
+ const newHeight = this._getVerticalBaseHeight(this.node.children);
- var fnPositionX = function (child) {
+ const fnPositionX = (child) => {
return child.x;
};
this._doLayoutVertically(newHeight, false, fnPositionX, true);
this.node.height = newHeight;
- }
- else if (this.type === Type.NONE) {
+ } else if (this.type === Type.NONE) {
if (this.resizeMode === ResizeMode.CONTAINER) {
this._doLayoutBasic();
}
- }
- else if (this.type === Type.GRID) {
+ } else if (this.type === Type.GRID) {
this._doLayoutGrid();
}
- },
+ }
+
+ private _getUsedScaleValue (value) {
+ return this.affectedByScale ? Math.abs(value) : 1;
+ }
/**
* !#en Perform the layout update
@@ -972,31 +1048,19 @@ var Layout = cc.Class({
* layout.updateLayout();
* cc.log(childNode.x); // changed
*/
- updateLayout: function () {
+ public updateLayout () {
if (this._layoutDirty && this.node.children.length > 0) {
this._doLayout();
this._layoutDirty = false;
}
}
-});
-
-/**
- * !#en The padding of layout, it effects the layout in four direction.
- * !#zh 容器内边距,该属性会在四个布局方向上生效。
- * @property {Number} padding
- */
-Object.defineProperty(Layout.prototype, "padding", {
- get: function () {
- cc.warnID(4100);
- return this.paddingLeft;
- },
- set: function (value) {
- this._N$padding = value;
-
- this._migratePaddingData();
- this._doLayoutDirty();
+ private _doLayoutDirty () {
+ this._layoutDirty = true;
}
-});
-cc.Layout = module.exports = Layout;
+ private _doScaleDirty () {
+ this._layoutDirty = this._layoutDirty || this.affectedByScale;
+ }
+
+}
diff --git a/cocos/3d/ui/components/mask-component.ts b/cocos/3d/ui/components/mask-component.ts
new file mode 100644
index 0000000000..dd8eee5516
--- /dev/null
+++ b/cocos/3d/ui/components/mask-component.ts
@@ -0,0 +1,328 @@
+/****************************************************************************
+ 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 { Material } from '../../assets/material';
+import circle from '../../primitive/circle';
+import { IGeometry } from '../../primitive/define';
+import quad from '../../primitive/quad';
+import { scale, translate } from '../../primitive/transform';
+import { setupClearMaskMaterial, setupMaskMaterial } from '../assembler/mask-assembler';
+import { UIRenderComponent } from './ui-render-component';
+import { UITransformComponent } from './ui-transfrom-component';
+
+/**
+ * !#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 UIRenderComponent {
+ 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) {
+ if (this._spriteFrame === value) {
+ return;
+ }
+ this._applySpriteFrame(value);
+ }
+
+ /**
+ * !#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;
+ }
+
+ /**
+ * !#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);
+ }
+
+ @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 _maskMaterial: Material | null = null;
+
+ private _clearMaskMaterial: Material | null = null;
+
+ private _maskGeometry: IGeometry | null = null;
+
+ private _clearGeometry: IGeometry | null = null;
+
+ public onLoad () {
+ this._activateMaterial();
+ }
+
+ public onEnable () {
+ super.onEnable();
+ 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();
+ }
+
+ // _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;
+ }
+ // 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 () {
+ if (!this._maskMaterial) {
+ this._maskMaterial = Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-material'), this);
+ setupMaskMaterial(this._maskMaterial);
+ }
+
+ if (!this._clearMaskMaterial) {
+ this._clearMaskMaterial = Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-material'), this);
+ setupClearMaskMaterial(this._clearMaskMaterial);
+ }
+ }
+
+ public _getMaskGeometry () {
+ return this._maskGeometry;
+ }
+
+ public _getClearGeometry () {
+ return this._clearGeometry;
+ }
+
+ public _getMaskMaterial (): Material | null {
+ return this._maskMaterial;
+ }
+
+ public _getClearMaterial (): Material | null {
+ return this._clearMaskMaterial;
+ }
+
+ private _updateGraphics () {
+ this._maskGeometry = this._getGraphics();
+ this._clearGeometry = this._drawRect(
+ 0, 0, cc.visibleRect.width, cc.visibleRect.height);
+ }
+
+ private _getGraphics () {
+ const uiTransform = this.node.getComponent(UITransformComponent);
+ if (!uiTransform) {
+ return null;
+ }
+ const width = uiTransform.width;
+ const height = uiTransform.height;
+ const x = -width * uiTransform.anchorPoint.x;
+ const y = -height * uiTransform.anchorPoint.y;
+ switch (this._type) {
+ case MaskType.RECT:
+ case MaskType.IMAGE_STENCIL:
+ return this._drawRect(x, y, width, height);
+ case MaskType.ELLIPSE:
+ const cx = x + width / 2;
+ const cy = y + height / 2;
+ const rx = width / 2;
+ const ry = height / 2;
+ return this._drawEllipse(cx, cy, rx, ry);
+ }
+ return null;
+ }
+
+ private _drawRect (x: number, y: number, width: number, height: number) {
+ const geometry = quad({ includeNormal: false, includeUV: false });
+ scale(geometry, { x: width, y: height });
+ translate(geometry, { x: x + width / 2, y: y + height / 2 });
+ return geometry;
+ }
+
+ private _drawEllipse (cx: number, cy: number, rx: number, ry: number) {
+ const geometry = circle({ includeNormal: false, includeUV: false });
+ scale(geometry, { x: rx, y: ry });
+ translate(geometry, { x: cx, y: cy });
+ return geometry;
+ }
+}
+
+// tslint:disable-next-line
+cc['MaskComponent'] = MaskComponent;
diff --git a/cocos/3d/ui/components/progress-bar-component.ts b/cocos/3d/ui/components/progress-bar-component.ts
new file mode 100644
index 0000000000..019653a675
--- /dev/null
+++ b/cocos/3d/ui/components/progress-bar-component.ts
@@ -0,0 +1,316 @@
+/****************************************************************************
+ 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 { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator';
+import { clamp01 } from '../../../core/utils/misc';
+import { Enum } from '../../../core/value-types';
+import { SpriteComponent } from './sprite-component';
+
+/**
+ * !#en Enum for ProgressBar mode
+ * !#zh 进度条模式
+ * @enum ProgressBar.Mode
+ */
+enum Mode {
+ /**
+ * !#en TODO
+ * !#zh 水平方向模式
+ * @property {Number} HORIZONTAL
+ */
+ HORIZONTAL = 0,
+
+ /**
+ * !#en TODO
+ * !#zh 垂直方向模式
+ * @property {Number} VERTICAL
+ */
+ VERTICAL = 1,
+ /**
+ * !#en TODO
+ * !#zh 填充模式
+ * @property {Number} FILLED
+ */
+ FILLED = 2,
+}
+
+Enum(Mode);
+
+/**
+ * !#en
+ * Visual indicator of progress in some operation.
+ * Displays a bar to the user representing how far the operation has progressed.
+ * !#zh
+ * 进度条组件,可用于显示加载资源时的进度。
+ * @class ProgressBar
+ * @extends Component
+ * @example
+ * // update progressBar
+ * update(dt) {
+ * var progress = progressBar.progress;
+ * if (progress > 0) {
+ * progress += dt;
+ * }
+ * else {
+ * progress = 1;
+ * }
+ * progressBar.progress = progress;
+ * }
+ *
+ */
+@ccclass('cc.ProgressBarComponent')
+@executionOrder(100)
+@menu('UI/ProgressBar')
+// @executeInEditMode
+export class ProgressBarComponent extends Component {
+
+ /**
+ * !#en The targeted Sprite which will be changed progressively.
+ * !#zh 用来显示进度条比例的 Sprite 对象。
+ * @property {Sprite} barSprite
+ */
+ @property({
+ type: SpriteComponent,
+ })
+ get barSprite () {
+ return this._barSprite;
+ }
+
+ 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: Mode) {
+ if (this._mode === value) {
+ return;
+ }
+
+ this._mode = value;
+ if (this._barSprite) {
+ const entity = this._barSprite.node;
+ if (!entity) { return; }
+
+ const 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({
+ range: [0, 1, 0.1],
+ slide: true,
+ })
+ 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();
+ }
+
+ public static Mode = Mode;
+ @property
+ private _barSprite: SpriteComponent | null = null;
+ @property
+ private _mode: number = Mode.HORIZONTAL;
+ private _N$totalLength: number = 1;
+ @property
+ private _progress: number = 0.1;
+ @property
+ private _reverse: boolean = false;
+
+ public _initBarSprite () {
+ if (this._barSprite) {
+ const entity = this._barSprite.node;
+ if (!entity) { return; }
+
+ const nodeSize = this.node.getContentSize();
+ const nodeAnchor = this.node.getAnchorPoint();
+
+ const entitySize = entity.getContentSize();
+
+ if (entity.parent === this.node) {
+ this.node.setContentSize(entitySize);
+ }
+
+ if (this._barSprite.fillType === cc.SpriteComponent.FillType.RADIAL) {
+ this._mode = Mode.FILLED;
+ }
+
+ const barSpriteSize = entity.getContentSize();
+ if (this._mode === Mode.HORIZONTAL) {
+ this.totalLength = barSpriteSize.width;
+ } else if (this._mode === Mode.VERTICAL) {
+ this.totalLength = barSpriteSize.height;
+ } else {
+ this.totalLength = this._barSprite.fillRange;
+ }
+
+ if (entity.parent === this.node) {
+ const x = - nodeSize.width * nodeAnchor.x;
+ const y = 0;
+ entity.setPosition(cc.v2(x, y));
+ }
+ }
+ }
+
+ public _updateBarStatus () {
+ if (this._barSprite) {
+ const entity = this._barSprite.node;
+
+ if (!entity) { return; }
+
+ const entityAnchorPoint = entity.getAnchorPoint();
+ const entitySize = entity.getContentSize();
+ const entityPosition = entity.getPosition();
+
+ let anchorPoint = cc.v2(0, 0.5);
+ const progress = clamp01(this._progress);
+ let actualLenth = this.totalLength * progress;
+ let finalContentSize;
+ let totalWidth;
+ let totalHeight;
+ switch (this._mode) {
+ case Mode.HORIZONTAL:
+ if (this._reverse) {
+ anchorPoint = cc.v2(1, 0.5);
+ }
+ finalContentSize = cc.size(actualLenth, entitySize.height);
+ totalWidth = this.totalLength;
+ totalHeight = entitySize.height;
+ break;
+ case Mode.VERTICAL:
+ if (this._reverse) {
+ anchorPoint = cc.v2(0.5, 1);
+ } else {
+ anchorPoint = cc.v2(0.5, 0);
+ }
+ finalContentSize = cc.size(entitySize.width, actualLenth);
+ totalWidth = entitySize.width;
+ totalHeight = this.totalLength;
+ break;
+ }
+
+ // handling filled mode
+ 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) {
+ actualLenth = actualLenth * -1;
+ }
+ this._barSprite.fillRange = actualLenth;
+ }
+ } else {
+ if (this._barSprite.type !== cc.SpriteComponent.Type.FILLED) {
+
+ const anchorOffsetX = anchorPoint.x - entityAnchorPoint.x;
+ const anchorOffsetY = anchorPoint.y - entityAnchorPoint.y;
+ const finalPosition = cc.v2(totalWidth * anchorOffsetX, totalHeight * anchorOffsetY);
+
+ entity.setPosition(entityPosition.x + finalPosition.x, entityPosition.y + finalPosition.y, entity.getPosition().z);
+
+ entity.setAnchorPoint(anchorPoint);
+ entity.setContentSize(finalContentSize);
+ } else {
+ cc.warn('ProgressBar non-FILLED mode only works when barSprite\'s Type is non-FILLED!');
+ }
+ }
+ }
+ }
+}
diff --git a/cocos/3d/ui/components/scroll-bar-component.ts b/cocos/3d/ui/components/scroll-bar-component.ts
new file mode 100644
index 0000000000..2910c625de
--- /dev/null
+++ b/cocos/3d/ui/components/scroll-bar-component.ts
@@ -0,0 +1,408 @@
+/****************************************************************************
+ 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, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator';
+import { UIRenderComponent } from './ui-render-component';
+import { Vec2 } from '../../../core/value-types';
+import { Node } from '../../../scene-graph/node';
+
+var GETTINGSHORTERFACTOR = 20;
+
+/**
+ * Enum for Scrollbar direction
+ * @enum Scrollbar.Direction
+ */
+var Direction = cc.Enum({
+ /**
+ * @property {Number} HORIZONTAL
+ */
+ HORIZONTAL: 0,
+
+ /**
+ * @property {Number} VERTICAL
+ */
+ VERTICAL: 1
+});
+
+/**
+ * !#en
+ * The Scrollbar control allows the user to scroll an image or other view that is too large to see completely
+ * !#zh 滚动条组件
+ * @class Scrollbar
+ * @extends Component
+ */
+@ccclass('cc.ScrollBarComponent')
+@executionOrder(100)
+@executeInEditMode
+export class ScrollBarComponent extends Component {
+ @property
+ private _scrollView: Component | null = null;
+ @property
+ private _handle: UIRenderComponent | null = null;
+ @property
+ private _direction = Direction.HORIZONTAL;
+ @property
+ private _enableAutoHide = false;
+ @property
+ private _autoHideTime = 1.0;
+
+ private _touching = false;
+ private _opacity = 0;
+ private _autoHideRemainingTime = 0;
+
+ /**
+ * !#en The "handle" part of the scrollbar.
+ * !#zh 作为当前滚动区域位置显示的滑块 Sprite。
+ * @property {Sprite} handle
+ */
+ @property({
+ type: UIRenderComponent
+ })
+ get handle() {
+ return this._handle;
+ }
+
+ set handle(value: UIRenderComponent) {
+ 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;
+ }
+
+ set direction(value) {
+ if (this._direction === value) {
+ return;
+ }
+
+ 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;
+ if(this._enableAutoHide){
+ this._setOpacity(0);
+ }
+ }
+
+ /**
+ * !#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;
+
+ protected onEnable() {
+ let renderComp = this.node.getComponent(UIRenderComponent);
+ if (renderComp) {
+ this._opacity = renderComp.color.a;
+ }
+ }
+
+ protected start() {
+ if (this._enableAutoHide) {
+ this._setOpacity(0);
+ }
+ }
+
+ public hide() {
+ this._autoHideRemainingTime = 0;
+ this._setOpacity(0);
+ }
+
+ public show() {
+ this._autoHideRemainingTime = this._autoHideTime;
+ this._setOpacity(this._opacity);
+ }
+
+ protected update(dt) {
+ this._processAutoHide(dt);
+ }
+
+ private _convertToScrollViewSpace(content: Node) {
+ return new Vec2(0, 0);
+ if (!this._scrollView){
+ return;
+ }
+
+ // TODO:
+ // var worldSpacePos = content.convertToWorldSpace(new Vec2(0, 0));
+ // var scrollViewSpacePos = this._scrollView.node.convertToNodeSpace(worldSpacePos);
+ // return scrollViewSpacePos;
+ }
+
+ private _setOpacity(opacity: number) {
+ if (this._handle) {
+ let renderComp = this.node.getComponent(UIRenderComponent);
+ if (renderComp){
+ renderComp.color.a = opacity;
+ }
+
+ renderComp = this._handle.getComponent(UIRenderComponent);
+ if (renderComp) {
+ renderComp.color.a = opacity;
+ }
+ }
+ }
+
+ public onScroll(outOfBoundary) {
+ if (this._scrollView) {
+
+ var content = this._scrollView.content;
+ if (content) {
+ var contentSize = content.getContentSize();
+ var scrollViewSize = this._scrollView.node.getContentSize();
+ var handleNodeSize = this.node.getContentSize();
+
+ if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
+ return;
+ }
+
+ if (this._enableAutoHide) {
+ this._autoHideRemainingTime = this._autoHideTime;
+ // this._setOpacity(this._opacity);
+ }
+
+ var contentMeasure = 0;
+ var scrollViewMeasure = 0;
+ var outOfBoundaryValue = 0;
+ var contentPosition = 0;
+ var handleNodeMeasure = 0;
+
+ 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) {
+ contentMeasure = contentSize.height;
+ scrollViewMeasure = scrollViewSize.height;
+ handleNodeMeasure = handleNodeSize.height;
+ outOfBoundaryValue = outOfBoundary.y;
+
+ contentPosition = -this._convertToScrollViewSpace(content).y;
+ }
+
+ var length = this._calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundaryValue);
+ var position = this._calculatePosition(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundaryValue, length);
+
+ this._updateLength(length);
+ this._updateHanlderPosition(position);
+ }
+ }
+ }
+
+ // FIXME: use ScrollViewComponent
+ public setScrollView(scrollView: Component) {
+ this._scrollView = scrollView;
+ }
+
+ private _updateHanlderPosition(position) {
+ if (this._handle) {
+ var oldPosition = this._fixupHandlerPosition();
+
+ this._handle.node.setPosition(position.x + oldPosition.x, position.y + oldPosition.y);
+ }
+ }
+
+ private _fixupHandlerPosition() {
+ if(!this._handle){
+ return;
+ }
+
+ var barSize = this.node.getContentSize();
+ var barAnchor = this.node.getAnchorPoint();
+ var handleSize = this._handle.node.getContentSize();
+
+ 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) {
+ fixupPosition = cc.v2(fixupPosition.x, fixupPosition.y + (barSize.height - handleSize.height) / 2);
+ } else if (this._direction === Direction.VERTICAL) {
+ fixupPosition = cc.v2(fixupPosition.x + (barSize.width - handleSize.width) / 2, fixupPosition.y);
+ }
+
+ this._handle.node.setPosition(fixupPosition);
+
+ return fixupPosition;
+ }
+
+ public onTouchBegan() {
+ if (!this._enableAutoHide) {
+ return;
+ }
+ this._touching = true;
+ }
+
+ private _conditionalDisableScrollBar(contentSize, scrollViewSize) {
+ if (contentSize.width <= scrollViewSize.width
+ && this._direction === Direction.HORIZONTAL) {
+ return true;
+ }
+
+ if (contentSize.height <= scrollViewSize.height
+ && this._direction === Direction.VERTICAL) {
+ return true;
+ }
+ return false;
+ }
+
+ public onTouchEnded() {
+ if (!this._enableAutoHide) {
+ return;
+ }
+
+ this._touching = false;
+
+ if (this._autoHideTime <= 0) {
+ return;
+ }
+
+
+ if (this._scrollView) {
+ var content = this._scrollView.content;
+ if (content) {
+ var contentSize = content.getContentSize();
+ var scrollViewSize = this._scrollView.node.getContentSize();
+
+ if (this._conditionalDisableScrollBar(contentSize, scrollViewSize)) {
+ return;
+ }
+ }
+ }
+
+ this._autoHideRemainingTime = this._autoHideTime;
+ }
+
+ private _calculateLength(contentMeasure, scrollViewMeasure, handleNodeMeasure, outOfBoundary) {
+ var denominatorValue = contentMeasure;
+ if (outOfBoundary) {
+ denominatorValue += (outOfBoundary > 0 ? outOfBoundary : -outOfBoundary) * GETTINGSHORTERFACTOR;
+ }
+
+ var lengthRation = scrollViewMeasure / denominatorValue;
+ return handleNodeMeasure * lengthRation;
+ }
+
+ private _calculatePosition(contentMeasure, scrollViewMeasure, handleNodeMeasure, contentPosition, outOfBoundary, actualLenth) {
+ var denominatorValue = contentMeasure - scrollViewMeasure;
+ if (outOfBoundary) {
+ denominatorValue += Math.abs(outOfBoundary);
+ }
+
+ var positionRatio = 0;
+ if (denominatorValue) {
+ positionRatio = contentPosition / denominatorValue;
+ positionRatio = clamp01(positionRatio);
+ }
+
+ var position = (handleNodeMeasure - actualLenth) * positionRatio;
+ if (this._direction === Direction.VERTICAL) {
+ return cc.v2(0, position);
+ } else {
+ return cc.v2(position, 0);
+ }
+ }
+
+ private _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) {
+ handleNode.setContentSize(length, handleNodeSize.height);
+ } else {
+ handleNode.setContentSize(handleNodeSize.width, length);
+ }
+ }
+ }
+
+ private _processAutoHide(deltaTime) {
+ if (!this._enableAutoHide || this._autoHideRemainingTime <= 0) {
+ return;
+ } else if (this._touching) {
+ return;
+ }
+
+
+ this._autoHideRemainingTime -= deltaTime;
+ if (this._autoHideRemainingTime <= this._autoHideTime) {
+ this._autoHideRemainingTime = Math.max(0, this._autoHideRemainingTime);
+ // var opacity = this._opacity * (this._autoHideRemainingTime / this._autoHideTime);
+ // this._setOpacity(opacity);
+ }
+ }
+}
diff --git a/cocos/2d/ui/CCScrollView.js b/cocos/3d/ui/components/scroll-view-component.ts
similarity index 70%
rename from cocos/2d/ui/CCScrollView.js
rename to cocos/3d/ui/components/scroll-view-component.ts
index 8c32b746b0..8c96d96499 100644
--- a/cocos/2d/ui/CCScrollView.js
+++ b/cocos/3d/ui/components/scroll-view-component.ts
@@ -23,20 +23,28 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
+import { Node } from '../../../scene-graph/node';
+import { Enum, Vec2, Vec3, Size } from '../../../core/value-types';
+import { ViewGroupComponent } from './view-group-component';
+import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator';
+import { ScrollBarComponent } from './scroll-bar-component';
+import ComponentEventHandler from '../../../components/CCComponentEventHandler';
+import { LayoutComponent } from './layout-component';
-const NodeEvent = require('../CCNode').EventType;
+const NodeEvent = Node.EventType;
const NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED = 5;
const OUT_OF_BOUNDARY_BREAKING_FACTOR = 0.05;
const EPSILON = 1e-4;
const MOVEMENT_FACTOR = 0.7;
+const _vec3Zero = new Vec3();
-let quintEaseOut = function(time) {
+let quintEaseOut = function (time) {
time -= 1;
return (time * time * time * time * time + 1);
};
-let getTimeInMilliseconds = function() {
+let getTimeInMilliseconds = function () {
let currentTime = new Date();
return currentTime.getMilliseconds();
};
@@ -46,100 +54,102 @@ let getTimeInMilliseconds = function() {
* !#zh 滚动视图事件类型
* @enum ScrollView.EventType
*/
-const EventType = cc.Enum({
+enum EventType {
/**
* !#en The event emmitted when ScrollView scroll to the top boundary of inner container
* !#zh 滚动视图滚动到顶部边界事件
* @property {Number} SCROLL_TO_TOP
*/
- SCROLL_TO_TOP : 0,
+ SCROLL_TO_TOP = 0,
/**
* !#en The event emmitted when ScrollView scroll to the bottom boundary of inner container
* !#zh 滚动视图滚动到底部边界事件
* @property {Number} SCROLL_TO_BOTTOM
*/
- SCROLL_TO_BOTTOM : 1,
+ SCROLL_TO_BOTTOM = 1,
/**
* !#en The event emmitted when ScrollView scroll to the left boundary of inner container
* !#zh 滚动视图滚动到左边界事件
* @property {Number} SCROLL_TO_LEFT
*/
- SCROLL_TO_LEFT : 2,
+ SCROLL_TO_LEFT = 2,
/**
* !#en The event emmitted when ScrollView scroll to the right boundary of inner container
* !#zh 滚动视图滚动到右边界事件
* @property {Number} SCROLL_TO_RIGHT
*/
- SCROLL_TO_RIGHT : 3,
+ SCROLL_TO_RIGHT = 3,
/**
* !#en The event emmitted when ScrollView is scrolling
* !#zh 滚动视图正在滚动时发出的事件
* @property {Number} SCROLLING
*/
- SCROLLING : 4,
+ SCROLLING = 4,
/**
* !#en The event emmitted when ScrollView scroll to the top boundary of inner container and start bounce
* !#zh 滚动视图滚动到顶部边界并且开始回弹时发出的事件
* @property {Number} BOUNCE_TOP
*/
- BOUNCE_TOP : 5,
+ BOUNCE_TOP = 5,
/**
* !#en The event emmitted when ScrollView scroll to the bottom boundary of inner container and start bounce
* !#zh 滚动视图滚动到底部边界并且开始回弹时发出的事件
* @property {Number} BOUNCE_BOTTOM
*/
- BOUNCE_BOTTOM : 6,
+ BOUNCE_BOTTOM = 6,
/**
* !#en The event emmitted when ScrollView scroll to the left boundary of inner container and start bounce
* !#zh 滚动视图滚动到左边界并且开始回弹时发出的事件
* @property {Number} BOUNCE_LEFT
*/
- BOUNCE_LEFT : 7,
+ BOUNCE_LEFT = 7,
/**
* !#en The event emmitted when ScrollView scroll to the right boundary of inner container and start bounce
* !#zh 滚动视图滚动到右边界并且开始回弹时发出的事件
* @property {Number} BOUNCE_RIGHT
*/
- BOUNCE_RIGHT : 8,
+ BOUNCE_RIGHT = 8,
/**
* !#en The event emmitted when ScrollView auto scroll ended
* !#zh 滚动视图滚动结束的时候发出的事件
* @property {Number} SCROLL_ENDED
*/
- SCROLL_ENDED : 9,
+ SCROLL_ENDED = 9,
/**
* !#en The event emmitted when user release the touch
* !#zh 当用户松手的时候会发出一个事件
* @property {Number} TOUCH_UP
*/
- TOUCH_UP : 10,
+ TOUCH_UP = 10,
/**
* !#en The event emmitted when ScrollView auto scroll ended with a threshold
* !#zh 滚动视图自动滚动快要结束的时候发出的事件
* @property {Number} AUTOSCROLL_ENDED_WITH_THRESHOLD
*/
- AUTOSCROLL_ENDED_WITH_THRESHOLD: 11,
+ AUTOSCROLL_ENDED_WITH_THRESHOLD = 11,
/**
* !#en The event emmitted when ScrollView scroll began
* !#zh 滚动视图滚动开始时发出的事件
* @property {Number} SCROLL_BEGAN
*/
- SCROLL_BEGAN: 12
-});
+ SCROLL_BEGAN = 12
+}
+
+Enum(EventType);
const eventMap = {
- 'scroll-to-top' : EventType.SCROLL_TO_TOP,
+ 'scroll-to-top': EventType.SCROLL_TO_TOP,
'scroll-to-bottom': EventType.SCROLL_TO_BOTTOM,
- 'scroll-to-left' : EventType.SCROLL_TO_LEFT,
- 'scroll-to-right' : EventType.SCROLL_TO_RIGHT,
- 'scrolling' : EventType.SCROLLING,
- 'bounce-bottom' : EventType.BOUNCE_BOTTOM,
- 'bounce-left' : EventType.BOUNCE_LEFT,
- 'bounce-right' : EventType.BOUNCE_RIGHT,
- 'bounce-top' : EventType.BOUNCE_TOP,
+ 'scroll-to-left': EventType.SCROLL_TO_LEFT,
+ 'scroll-to-right': EventType.SCROLL_TO_RIGHT,
+ 'scrolling': EventType.SCROLLING,
+ 'bounce-bottom': EventType.BOUNCE_BOTTOM,
+ 'bounce-left': EventType.BOUNCE_LEFT,
+ 'bounce-right': EventType.BOUNCE_RIGHT,
+ 'bounce-top': EventType.BOUNCE_TOP,
'scroll-ended': EventType.SCROLL_ENDED,
- 'touch-up' : EventType.TOUCH_UP,
- 'scroll-ended-with-threshold' : EventType.AUTOSCROLL_ENDED_WITH_THRESHOLD,
+ 'touch-up': EventType.TOUCH_UP,
+ 'scroll-ended-with-threshold': EventType.AUTOSCROLL_ENDED_WITH_THRESHOLD,
'scroll-began': EventType.SCROLL_BEGAN
};
@@ -153,197 +163,190 @@ const eventMap = {
* @class ScrollView
* @extends Component
*/
-let ScrollView = cc.Class({
- name: 'cc.ScrollView',
- extends: require('./CCViewGroup'),
- editor: CC_EDITOR && {
- menu: 'i18n:MAIN_MENU.component.ui/ScrollView',
- help: 'i18n:COMPONENT.help_url.scrollview',
- executeInEditMode: false,
- },
+@ccclass('cc.ScrollViewComponent')
+@executionOrder(100)
+@menu('UI/ScrollView')
+@executeInEditMode
+export class ScrollViewComponent extends ViewGroupComponent {
+ /**
+ * !#en Enable horizontal scroll.
+ * !#zh 是否开启水平滚动。
+ * @property {Boolean} horizontal
+ */
+ @property
+ public horizontal = true;
- ctor () {
- this._topBoundary = 0;
- this._bottomBoundary = 0;
- this._leftBoundary = 0;
- this._rightBoundary = 0;
+ /**
+ * !#en Enable vertical scroll.
+ * !#zh 是否开启垂直滚动。
+ * @property {Boolean} vertical
+ */
+ @property
+ public vertical = true;
- this._touchMoveDisplacements = [];
- this._touchMoveTimeDeltas = [];
- this._touchMovePreviousTimestamp = 0;
- this._touchMoved = false;
+ /**
+ * !#en When inertia is set, the content will continue to move when touch ended.
+ * !#zh 是否开启滚动惯性。
+ * @property {Boolean} inertia
+ */
+ @property
+ public inertia = true;
- this._autoScrolling = false;
- this._autoScrollAttenuate = false;
- this._autoScrollStartPosition = cc.v2(0, 0);
- this._autoScrollTargetDelta = cc.v2(0, 0);
- this._autoScrollTotalTime = 0;
- this._autoScrollAccumulatedTime = 0;
- this._autoScrollCurrentlyOutOfBoundary = false;
- this._autoScrollBraking = false;
- this._autoScrollBrakingStartPosition = cc.v2(0, 0);
+ /**
+ * !#en
+ * It determines how quickly the content stop moving. A value of 1 will stop the movement immediately.
+ * A value of 0 will never stop the movement until it reaches to the boundary of scrollview.
+ * !#zh
+ * 开启惯性后,在用户停止触摸后滚动多快停止,0表示永不停止,1表示立刻停止。
+ * @property {Number} brake
+ */
+ @property({
+ range: [0, 1, 0.1]
+ })
+ public brake = 0.5;
- this._outOfBoundaryAmount = cc.v2(0, 0);
- this._outOfBoundaryAmountDirty = true;
- this._stopMouseWheel = false;
- this._mouseWheelEventElapsedTime = 0.0;
- this._isScrollEndedWithThresholdEventFired = false;
- //use bit wise operations to indicate the direction
- this._scrollEventEmitMask = 0;
- this._isBouncing = false;
- this._scrolling = false;
- },
+ /**
+ * !#en When elastic is set, the content will be bounce back when move out of boundary.
+ * !#zh 是否允许滚动内容超过边界,并在停止触摸后回弹。
+ */
+ @property
+ public elastic = true;
- properties: {
- /**
- * !#en This is a reference to the UI element to be scrolled.
- * !#zh 可滚动展示内容的节点。
- * @property {Node} content
- */
- content: {
- default: undefined,
- type: cc.Node,
- tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.content',
- formerlySerializedAs: 'content',
- notify (oldValue) {
- this._calculateBoundary();
- }
- },
+ /**
+ * !#en The elapse time of bouncing back. A value of 0 will bounce back immediately.
+ * !#zh 回弹持续的时间,0 表示将立即反弹。
+ * @property {Number} bounceDuration
+ */
+ @property({
+ range: [1, 10]
+ })
+ public bounceDuration = 1;
- /**
- * !#en Enable horizontal scroll.
- * !#zh 是否开启水平滚动。
- * @property {Boolean} horizontal
- */
- horizontal: {
- default: true,
- animatable: false,
- tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.horizontal',
- },
+ /**
+ * !#en Scrollview events callback
+ * !#zh 滚动视图的事件回调函数
+ * @property {Component.EventHandler[]} scrollEvents
+ */
+ @property
+ public scrollEvents: ComponentEventHandler[] = [];
- /**
- * !#en Enable vertical scroll.
- * !#zh 是否开启垂直滚动。
- * @property {Boolean} vertical
- */
- vertical: {
- default: true,
- animatable: false,
- tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.vertical',
- },
+ /**
+ * !#en If cancelInnerEvents is set to true, the scroll behavior will cancel touch events on inner content nodes
+ * It's set to true by default.
+ * !#zh 如果这个属性被设置为 true,那么滚动行为会取消子节点上注册的触摸事件,默认被设置为 true。
+ * 注意,子节点上的 touchstart 事件仍然会触发,触点移动距离非常短的情况下 touchmove 和 touchend 也不会受影响。
+ * @property {Boolean} cancelInnerEvents
+ */
+ @property
+ public cancelInnerEvents = true;
+ @property
+ private _content: Node | null = null;
+ @property
+ private _horizontalScrollBar: ScrollBarComponent | null = null;
+ @property
+ private _verticalScrollBar: ScrollBarComponent | null = null;
- /**
- * !#en When inertia is set, the content will continue to move when touch ended.
- * !#zh 是否开启滚动惯性。
- * @property {Boolean} inertia
- */
- inertia: {
- default: true,
- tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.inertia',
- },
+ private _topBoundary = 0;
+ private _bottomBoundary = 0;
+ private _leftBoundary = 0;
+ private _rightBoundary = 0;
- /**
- * !#en
- * It determines how quickly the content stop moving. A value of 1 will stop the movement immediately.
- * A value of 0 will never stop the movement until it reaches to the boundary of scrollview.
- * !#zh
- * 开启惯性后,在用户停止触摸后滚动多快停止,0表示永不停止,1表示立刻停止。
- * @property {Number} brake
- */
- brake: {
- default: 0.5,
- type: 'Float',
- range: [0, 1, 0.1],
- tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.brake',
- },
+ private _touchMoveDisplacements: Vec3[] = [];
+ private _touchMoveTimeDeltas: number[] = [];
+ private _touchMovePreviousTimestamp = 0;
+ private _touchMoved = false;
- /**
- * !#en When elastic is set, the content will be bounce back when move out of boundary.
- * !#zh 是否允许滚动内容超过边界,并在停止触摸后回弹。
- * @property {Boolean} elastic
- */
- elastic: {
- default: true,
- animatable: false,
- tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.elastic',
- },
+ private _autoScrolling = false;
+ private _autoScrollAttenuate = false;
+ private _autoScrollStartPosition = new Vec3(0, 0);
+ private _autoScrollTargetDelta = new Vec3(0, 0);
+ private _autoScrollTotalTime = 0;
+ private _autoScrollAccumulatedTime = 0;
+ private _autoScrollCurrentlyOutOfBoundary = false;
+ private _autoScrollBraking = false;
+ private _autoScrollBrakingStartPosition = new Vec3(0, 0);
- /**
- * !#en The elapse time of bouncing back. A value of 0 will bounce back immediately.
- * !#zh 回弹持续的时间,0 表示将立即反弹。
- * @property {Number} bounceDuration
- */
- bounceDuration: {
- default: 1,
- range: [0, 10],
- tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.bounceDuration',
- },
+ private _outOfBoundaryAmount = new Vec3(0, 0);
+ private _outOfBoundaryAmountDirty = true;
+ private _stopMouseWheel = false;
+ private _mouseWheelEventElapsedTime = 0.0;
+ private _isScrollEndedWithThresholdEventFired = false;
+ //use bit wise operations to indicate the direction
+ private _scrollEventEmitMask = 0;
+ private _isBouncing = false;
+ private _scrolling = false;
+ private _contentPos = new Vec3();
- /**
- * !#en The horizontal scrollbar reference.
- * !#zh 水平滚动的 ScrollBar。
- * @property {Scrollbar} horizontalScrollBar
- */
- horizontalScrollBar: {
- default: undefined,
- type: cc.Scrollbar,
- tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.horizontal_bar',
- notify () {
- if (this.horizontalScrollBar) {
- this.horizontalScrollBar.setTargetScrollView(this);
- this._updateScrollBar(0);
- }
- },
- animatable: false
- },
-
- /**
- * !#en The vertical scrollbar reference.
- * !#zh 垂直滚动的 ScrollBar。
- * @property {Scrollbar} verticalScrollBar
- */
- verticalScrollBar: {
- default: undefined,
- type: cc.Scrollbar,
- tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.vertical_bar',
- notify () {
- if (this.verticalScrollBar) {
- this.verticalScrollBar.setTargetScrollView(this);
- this._updateScrollBar(0);
- }
- },
- animatable: false
- },
-
- /**
- * !#en Scrollview events callback
- * !#zh 滚动视图的事件回调函数
- * @property {Component.EventHandler[]} scrollEvents
- */
- scrollEvents: {
- default: [],
- type: cc.Component.EventHandler,
- tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.scrollEvents'
- },
-
- /**
- * !#en If cancelInnerEvents is set to true, the scroll behavior will cancel touch events on inner content nodes
- * It's set to true by default.
- * !#zh 如果这个属性被设置为 true,那么滚动行为会取消子节点上注册的触摸事件,默认被设置为 true。
- * 注意,子节点上的 touchstart 事件仍然会触发,触点移动距离非常短的情况下 touchmove 和 touchend 也不会受影响。
- * @property {Boolean} cancelInnerEvents
- */
- cancelInnerEvents: {
- default: true,
- animatable: false,
- tooltip: CC_DEV && 'i18n:COMPONENT.scrollview.cancelInnerEvents'
+ /**
+ * !#en This is a reference to the UI element to be scrolled.
+ * !#zh 可滚动展示内容的节点。
+ * @property {Node} content
+ */
+ @property({
+ type: Node
+ })
+ get content() {
+ return this._content;
+ }
+ set content(value: Node) {
+ if(this._content === value){
+ return;
}
- },
- statics: {
- EventType: EventType,
- },
+ this._content = value;
+ this._calculateBoundary();
+ }
+
+ /**
+ * !#en The horizontal scrollbar reference.
+ * !#zh 水平滚动的 ScrollBar。
+ * @property {Scrollbar} horizontalScrollBar
+ */
+ @property({
+ type: ScrollBarComponent
+ })
+ get horizontalScrollBar() {
+ return this._horizontalScrollBar;
+ }
+
+ set horizontalScrollBar(value: ScrollBarComponent) {
+ if(this._horizontalScrollBar === value){
+ return;
+ }
+
+ this._horizontalScrollBar = value;
+
+ if (this._horizontalScrollBar) {
+ this._horizontalScrollBar.setScrollView(this);
+ this._updateScrollBar(0);
+ }
+ }
+
+ /**
+ * !#en The vertical scrollbar reference.
+ * !#zh 垂直滚动的 ScrollBar。
+ * @property {Scrollbar} verticalScrollBar
+ */
+ @property
+ get verticalScrollBar() {
+ return this._verticalScrollBar;
+ }
+
+ set verticalScrollBar(value: ScrollBarComponent) {
+ if (this._verticalScrollBar === value) {
+ return;
+ }
+
+ this._verticalScrollBar = value;
+
+ if (this._verticalScrollBar) {
+ this._verticalScrollBar.setScrollView(this);
+ this._updateScrollBar(0);
+ }
+ }
+
+ static EventType = EventType;
/**
* !#en Scroll the content to the bottom boundary of ScrollView.
@@ -356,9 +359,9 @@ let ScrollView = cc.Class({
* // Scroll to the bottom of the view.
* scrollView.scrollToBottom(0.1);
*/
- scrollToBottom (timeInSecond, attenuated) {
+ scrollToBottom(timeInSecond: number, attenuated: boolean) {
let moveDelta = this._calculateMovePercentDelta({
- anchor: cc.v2(0, 0),
+ anchor: new Vec2(0, 0),
applyToHorizontal: false,
applyToVertical: true,
});
@@ -368,7 +371,7 @@ let ScrollView = cc.Class({
} else {
this._moveContent(moveDelta, true);
}
- },
+ }
/**
* !#en Scroll the content to the top boundary of ScrollView.
@@ -381,9 +384,9 @@ let ScrollView = cc.Class({
* // Scroll to the top of the view.
* scrollView.scrollToTop(0.1);
*/
- scrollToTop (timeInSecond, attenuated) {
+ scrollToTop(timeInSecond: number, attenuated: boolean) {
let moveDelta = this._calculateMovePercentDelta({
- anchor: cc.v2(0, 1),
+ anchor: new Vec2(0, 1),
applyToHorizontal: false,
applyToVertical: true,
});
@@ -393,7 +396,7 @@ let ScrollView = cc.Class({
} else {
this._moveContent(moveDelta);
}
- },
+ }
/**
* !#en Scroll the content to the left boundary of ScrollView.
@@ -406,9 +409,9 @@ let ScrollView = cc.Class({
* // Scroll to the left of the view.
* scrollView.scrollToLeft(0.1);
*/
- scrollToLeft (timeInSecond, attenuated) {
+ scrollToLeft(timeInSecond: number, attenuated: boolean) {
let moveDelta = this._calculateMovePercentDelta({
- anchor: cc.v2(0, 0),
+ anchor: new Vec2(0, 0),
applyToHorizontal: true,
applyToVertical: false,
});
@@ -418,7 +421,7 @@ let ScrollView = cc.Class({
} else {
this._moveContent(moveDelta);
}
- },
+ }
/**
* !#en Scroll the content to the right boundary of ScrollView.
@@ -431,9 +434,9 @@ let ScrollView = cc.Class({
* // Scroll to the right of the view.
* scrollView.scrollToRight(0.1);
*/
- scrollToRight (timeInSecond, attenuated) {
+ scrollToRight(timeInSecond, attenuated) {
let moveDelta = this._calculateMovePercentDelta({
- anchor: cc.v2(1, 0),
+ anchor: new Vec2(1, 0),
applyToHorizontal: true,
applyToVertical: false,
});
@@ -443,7 +446,7 @@ let ScrollView = cc.Class({
} else {
this._moveContent(moveDelta);
}
- },
+ }
/**
* !#en Scroll the content to the top left boundary of ScrollView.
@@ -456,9 +459,9 @@ let ScrollView = cc.Class({
* // Scroll to the upper left corner of the view.
* scrollView.scrollToTopLeft(0.1);
*/
- scrollToTopLeft (timeInSecond, attenuated) {
+ scrollToTopLeft(timeInSecond, attenuated) {
let moveDelta = this._calculateMovePercentDelta({
- anchor: cc.v2(0, 1),
+ anchor: new Vec2(0, 1),
applyToHorizontal: true,
applyToVertical: true,
});
@@ -468,7 +471,7 @@ let ScrollView = cc.Class({
} else {
this._moveContent(moveDelta);
}
- },
+ }
/**
* !#en Scroll the content to the top right boundary of ScrollView.
@@ -481,9 +484,9 @@ let ScrollView = cc.Class({
* // Scroll to the top right corner of the view.
* scrollView.scrollToTopRight(0.1);
*/
- scrollToTopRight (timeInSecond, attenuated) {
+ scrollToTopRight(timeInSecond, attenuated) {
let moveDelta = this._calculateMovePercentDelta({
- anchor: cc.v2(1, 1),
+ anchor: new Vec2(1, 1),
applyToHorizontal: true,
applyToVertical: true,
});
@@ -493,7 +496,7 @@ let ScrollView = cc.Class({
} else {
this._moveContent(moveDelta);
}
- },
+ }
/**
* !#en Scroll the content to the bottom left boundary of ScrollView.
@@ -506,9 +509,9 @@ let ScrollView = cc.Class({
* // Scroll to the lower left corner of the view.
* scrollView.scrollToBottomLeft(0.1);
*/
- scrollToBottomLeft (timeInSecond, attenuated) {
+ scrollToBottomLeft(timeInSecond, attenuated) {
let moveDelta = this._calculateMovePercentDelta({
- anchor: cc.v2(0, 0),
+ anchor: new Vec2(0, 0),
applyToHorizontal: true,
applyToVertical: true,
});
@@ -518,7 +521,7 @@ let ScrollView = cc.Class({
} else {
this._moveContent(moveDelta);
}
- },
+ }
/**
* !#en Scroll the content to the bottom right boundary of ScrollView.
@@ -531,9 +534,9 @@ let ScrollView = cc.Class({
* // Scroll to the lower right corner of the view.
* scrollView.scrollToBottomRight(0.1);
*/
- scrollToBottomRight (timeInSecond, attenuated) {
+ scrollToBottomRight(timeInSecond, attenuated) {
let moveDelta = this._calculateMovePercentDelta({
- anchor: cc.v2(1, 0),
+ anchor: new Vec2(1, 0),
applyToHorizontal: true,
applyToVertical: true,
});
@@ -543,7 +546,7 @@ let ScrollView = cc.Class({
} else {
this._moveContent(moveDelta);
}
- },
+ }
/**
@@ -558,12 +561,12 @@ let ScrollView = cc.Class({
* @example
* // Scroll to middle position in 0.1 second in x-axis
* let maxScrollOffset = this.getMaxScrollOffset();
- * scrollView.scrollToOffset(cc.v2(maxScrollOffset.x / 2, 0), 0.1);
+ * scrollView.scrollToOffset(new Vec3(maxScrollOffset.x / 2, 0, 0), 0.1);
*/
- scrollToOffset (offset, timeInSecond, attenuated) {
+ scrollToOffset(offset, timeInSecond, attenuated) {
let maxScrollOffset = this.getMaxScrollOffset();
- let anchor = cc.v2(0, 0);
+ let anchor = new Vec2(0, 0);
//if maxScrollOffset is 0, then always align the content's top left origin to the top left corner of its parent
if (maxScrollOffset.x === 0) {
anchor.x = 0;
@@ -574,11 +577,11 @@ let ScrollView = cc.Class({
if (maxScrollOffset.y === 0) {
anchor.y = 1;
} else {
- anchor.y = (maxScrollOffset.y - offset.y ) / maxScrollOffset.y;
+ anchor.y = (maxScrollOffset.y - offset.y) / maxScrollOffset.y;
}
this.scrollTo(anchor, timeInSecond, attenuated);
- },
+ }
/**
* !#en Get the positive offset value corresponds to the content's top left boundary.
@@ -586,12 +589,12 @@ let ScrollView = cc.Class({
* @method getScrollOffset
* @return {Vec2} - A Vec2 value indicate the current scroll offset.
*/
- getScrollOffset () {
- let topDelta = this._getContentTopBoundary() - this._topBoundary;
+ getScrollOffset() {
+ let topDelta = this._getContentTopBoundary() - this._topBoundary;
let leftDeta = this._getContentLeftBoundary() - this._leftBoundary;
- return cc.v2(leftDeta, topDelta);
- },
+ return new Vec2(leftDeta, topDelta);
+ }
/**
* !#en Get the maximize available scroll offset
@@ -599,16 +602,16 @@ let ScrollView = cc.Class({
* @method getMaxScrollOffset
* @return {Vec2} - A Vec2 value indicate the maximize scroll offset in x and y axis.
*/
- getMaxScrollOffset () {
+ getMaxScrollOffset() {
let scrollSize = this.node.getContentSize();
- let contentSize = this.content.getContentSize();
- let horizontalMaximizeOffset = contentSize.width - scrollSize.width;
+ let contentSize = this._content!.getContentSize();
+ let horizontalMaximizeOffset = contentSize.width - scrollSize.width;
let verticalMaximizeOffset = contentSize.height - scrollSize.height;
horizontalMaximizeOffset = horizontalMaximizeOffset >= 0 ? horizontalMaximizeOffset : 0;
- verticalMaximizeOffset = verticalMaximizeOffset >=0 ? verticalMaximizeOffset : 0;
+ verticalMaximizeOffset = verticalMaximizeOffset >= 0 ? verticalMaximizeOffset : 0;
- return cc.v2(horizontalMaximizeOffset, verticalMaximizeOffset);
- },
+ return new Vec2(horizontalMaximizeOffset, verticalMaximizeOffset);
+ }
/**
* !#en Scroll the content to the horizontal percent position of ScrollView.
@@ -622,9 +625,9 @@ let ScrollView = cc.Class({
* // Scroll to middle position.
* scrollView.scrollToBottomRight(0.5, 0.1);
*/
- scrollToPercentHorizontal (percent, timeInSecond, attenuated) {
+ scrollToPercentHorizontal(percent, timeInSecond, attenuated) {
let moveDelta = this._calculateMovePercentDelta({
- anchor: cc.v2(percent, 0),
+ anchor: new Vec2(percent, 0),
applyToHorizontal: true,
applyToVertical: false,
});
@@ -634,36 +637,36 @@ let ScrollView = cc.Class({
} else {
this._moveContent(moveDelta);
}
- },
+ }
/**
* !#en Scroll the content to the percent position of ScrollView in any direction.
* !#zh 视图内容在规定时间内进行垂直方向和水平方向的滚动,并且滚动到指定百分比位置上。
* @method scrollTo
- * @param {Vec2} anchor - A point which will be clamp between cc.v2(0,0) and cc.v2(1,1).
+ * @param {Vec2} anchor - A point which will be clamp between new Vec2(0,0) and new Vec2(1,1).
* @param {Number} [timeInSecond=0] - Scroll time in second, if you don't pass timeInSecond,
* the content will jump to the percent position of ScrollView immediately.
* @param {Boolean} [attenuated=true] - Whether the scroll acceleration attenuated, default is true.
* @example
* // Vertical scroll to the bottom of the view.
- * scrollView.scrollTo(cc.v2(0, 1), 0.1);
+ * scrollView.scrollTo(new Vec2(0, 1), 0.1);
*
* // Horizontal scroll to view right.
- * scrollView.scrollTo(cc.v2(1, 0), 0.1);
+ * scrollView.scrollTo(new Vec2(1, 0), 0.1);
*/
- scrollTo (anchor, timeInSecond, attenuated) {
+ scrollTo(anchor: Vec2, timeInSecond: number, attenuated?: boolean) {
let moveDelta = this._calculateMovePercentDelta({
- anchor: cc.v2(anchor),
+ anchor: new Vec2(anchor),
applyToHorizontal: true,
applyToVertical: true,
});
if (timeInSecond) {
- this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
+ this._startAutoScroll(moveDelta, timeInSecond, attenuated);
} else {
this._moveContent(moveDelta);
}
- },
+ }
/**
* !#en Scroll the content to the vertical percent position of ScrollView.
@@ -676,29 +679,29 @@ let ScrollView = cc.Class({
* // Scroll to middle position.
* scrollView.scrollToPercentVertical(0.5, 0.1);
*/
- scrollToPercentVertical (percent, timeInSecond, attenuated) {
+ scrollToPercentVertical(percent: number, timeInSecond: number, attenuated?: boolean) {
let moveDelta = this._calculateMovePercentDelta({
- anchor: cc.v2(0, percent),
+ anchor: new Vec2(0, percent),
applyToHorizontal: false,
applyToVertical: true,
});
if (timeInSecond) {
- this._startAutoScroll(moveDelta, timeInSecond, attenuated !== false);
+ this._startAutoScroll(moveDelta, timeInSecond, attenuated);
} else {
this._moveContent(moveDelta);
}
- },
+ }
/**
* !#en Stop auto scroll immediately
* !#zh 停止自动滚动, 调用此 API 可以让 Scrollview 立即停止滚动
* @method stopAutoScroll
*/
- stopAutoScroll () {
+ stopAutoScroll() {
this._autoScrolling = false;
this._autoScrollAccumulatedTime = this._autoScrollTotalTime;
- },
+ }
/**
* !#en Modify the content position.
@@ -706,14 +709,14 @@ let ScrollView = cc.Class({
* @method setContentPosition
* @param {Vec2} position - The position in content's parent space.
*/
- setContentPosition (position) {
+ setContentPosition(position: Vec3) {
if (position.fuzzyEquals(this.getContentPosition(), EPSILON)) {
return;
}
- this.content.setPosition(position);
+ this._content!.setPosition(position);
this._outOfBoundaryAmountDirty = true;
- },
+ }
/**
* !#en Query the content's position in its parent space.
@@ -721,19 +724,20 @@ let ScrollView = cc.Class({
* @method getContentPosition
* @returns {Position} - The content's position in its parent space.
*/
- getContentPosition () {
- return this.content.getPosition();
- },
-
+ getContentPosition() {
+ this._content!.getPosition(this._contentPos);
+ return this._contentPos;
+ }
+
/**
* !#en Query whether the user is currently dragging the ScrollView to scroll it
* !#zh 用户是否在拖拽当前滚动视图
* @method isScrolling
* @returns {Boolean} - Whether the user is currently dragging the ScrollView to scroll it
*/
- isScrolling () {
+ isScrolling() {
return this._scrolling;
- },
+ }
/**
* !#en Query whether the ScrollView is currently scrolling because of a bounceback or inertia slowdown.
@@ -741,60 +745,60 @@ let ScrollView = cc.Class({
* @method isAutoScrolling
* @returns {Boolean} - Whether the ScrollView is currently scrolling because of a bounceback or inertia slowdown.
*/
- isAutoScrolling () {
+ isAutoScrolling() {
return this._autoScrolling;
- },
-
+ }
+
//private methods
- _registerEvent () {
+ _registerEvent() {
this.node.on(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this, true);
this.node.on(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this, true);
this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this, true);
this.node.on(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this, true);
this.node.on(cc.Node.EventType.MOUSE_WHEEL, this._onMouseWheel, this, true);
- },
+ }
- _unregisterEvent () {
+ _unregisterEvent() {
this.node.off(cc.Node.EventType.TOUCH_START, this._onTouchBegan, this, true);
this.node.off(cc.Node.EventType.TOUCH_MOVE, this._onTouchMoved, this, true);
this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this, true);
this.node.off(cc.Node.EventType.TOUCH_CANCEL, this._onTouchCancelled, this, true);
this.node.off(cc.Node.EventType.MOUSE_WHEEL, this._onMouseWheel, this, true);
- },
+ }
- _onMouseWheel (event, captureListeners) {
+ _onMouseWheel(event, captureListeners) {
if (!this.enabledInHierarchy) return;
if (this._hasNestedViewGroup(event, captureListeners)) return;
- let deltaMove = cc.v2(0, 0);
+ let deltaMove = new Vec3();
let wheelPrecision = -0.1;
- if(CC_JSB) {
+ if (CC_JSB) {
wheelPrecision = -7;
}
- if(this.vertical) {
- deltaMove = cc.v2(0, event.getScrollY() * wheelPrecision);
+ if (this.vertical) {
+ deltaMove = new Vec3(0, event.getScrollY() * wheelPrecision);
}
- else if(this.horizontal) {
- deltaMove = cc.v2(event.getScrollY() * wheelPrecision, 0);
+ else if (this.horizontal) {
+ deltaMove = new Vec3(event.getScrollY() * wheelPrecision, 0);
}
this._mouseWheelEventElapsedTime = 0;
this._processDeltaMove(deltaMove);
- if(!this._stopMouseWheel) {
+ if (!this._stopMouseWheel) {
this._handlePressLogic();
this.schedule(this._checkMouseWheel, 1.0 / 60);
this._stopMouseWheel = true;
}
this._stopPropagationIfTargetIsMe(event);
- },
+ }
- _checkMouseWheel (dt) {
+ _checkMouseWheel(dt: number) {
let currentOutOfBoundary = this._getHowMuchOutOfBoundary();
let maxElapsedTime = 0.1;
- if (!currentOutOfBoundary.fuzzyEquals(cc.v2(0, 0), EPSILON)) {
+ if (!currentOutOfBoundary.fuzzyEquals(_vec3Zero, EPSILON)) {
this._processInertiaScroll();
this.unschedule(this._checkMouseWheel);
this._stopMouseWheel = false;
@@ -809,25 +813,25 @@ let ScrollView = cc.Class({
this.unschedule(this._checkMouseWheel);
this._stopMouseWheel = false;
}
- },
+ }
- _calculateMovePercentDelta (options) {
+ _calculateMovePercentDelta(options) {
let anchor = options.anchor;
let applyToHorizontal = options.applyToHorizontal;
let applyToVertical = options.applyToVertical;
this._calculateBoundary();
- anchor = anchor.clampf(cc.v2(0, 0), cc.v2(1, 1));
+ anchor = anchor.clampf(new Vec2(0, 0), new Vec2(1, 1));
let scrollSize = this.node.getContentSize();
- let contentSize = this.content.getContentSize();
+ let contentSize = this._content!.getContentSize();
let bottomDeta = this._getContentBottomBoundary() - this._bottomBoundary;
bottomDeta = -bottomDeta;
let leftDeta = this._getContentLeftBoundary() - this._leftBoundary;
leftDeta = -leftDeta;
- let moveDelta = cc.v2(0, 0);
+ let moveDelta = new Vec3(0, 0);
let totalScrollDelta = 0;
if (applyToHorizontal) {
totalScrollDelta = contentSize.width - scrollSize.width;
@@ -840,14 +844,14 @@ let ScrollView = cc.Class({
}
return moveDelta;
- },
+ }
- _moveContentToTopLeft (scrollViewSize) {
- let contentSize = this.content.getContentSize();
+ _moveContentToTopLeft(scrollViewSize: Size) {
+ let contentSize = this._content!.getContentSize();
let bottomDeta = this._getContentBottomBoundary() - this._bottomBoundary;
bottomDeta = -bottomDeta;
- let moveDelta = cc.v2(0, 0);
+ let moveDelta = new Vec3(0, 0);
let totalScrollDelta = 0;
let leftDeta = this._getContentLeftBoundary() - this._leftBoundary;
@@ -870,54 +874,57 @@ let ScrollView = cc.Class({
totalScrollDelta = contentSize.width - scrollViewSize.width;
moveDelta.x = leftDeta;
- if (this.horizontalScrollBar) {
- this.horizontalScrollBar.hide();
+ if (this._horizontalScrollBar) {
+ this._horizontalScrollBar.hide();
}
} else {
- if (this.horizontalScrollBar) {
- this.horizontalScrollBar.show();
+ if (this._horizontalScrollBar) {
+ this._horizontalScrollBar.show();
}
}
this._moveContent(moveDelta);
this._adjustContentOutOfBoundary();
- },
+ }
- _calculateBoundary () {
- if (this.content) {
- //refresh content size
- let layout = this.content.getComponent(cc.Layout);
- if(layout && layout.enabledInHierarchy) {
- layout.updateLayout();
- }
- let viewSize = this.content.parent.getContentSize();
-
- let leftBottomPosition = this._convertToContentParentSpace(cc.v2(0, 0));
- this._leftBoundary = leftBottomPosition.x;
- this._bottomBoundary = leftBottomPosition.y;
-
- let topRightPosition = this._convertToContentParentSpace(cc.v2(viewSize.width, viewSize.height));
- this._rightBoundary = topRightPosition.x;
- this._topBoundary = topRightPosition.y;
-
- this._moveContentToTopLeft(viewSize);
+ _calculateBoundary() {
+ if (this._content) {
+ return;
}
- },
+ //refresh content size
+ let layout = this._content!.getComponent(LayoutComponent);
+ if (layout && layout.enabledInHierarchy) {
+ layout!.updateLayout();
+ }
+ let viewSize = this._content!.parent!.getContentSize();
- _convertToContentParentSpace (position) {
- let contentParent = this.content.parent;
+ let leftBottomPosition = this._convertToContentParentSpace(new Vec3(0, 0));
+ this._leftBoundary = leftBottomPosition.x;
+ this._bottomBoundary = leftBottomPosition.y;
+
+ let topRightPosition = this._convertToContentParentSpace(new Vec3(viewSize.width, viewSize.height));
+ this._rightBoundary = topRightPosition.x;
+ this._topBoundary = topRightPosition.y;
+
+ this._moveContentToTopLeft(viewSize);
+
+ }
+
+ _convertToContentParentSpace(position: Vec3) {
+ let contentParent = this._content!.parent;
+ // TODO:
let viewPositionInWorldSpace = contentParent.convertToWorldSpace(position);
return contentParent.convertToNodeSpaceAR(viewPositionInWorldSpace);
- },
+ }
//this is for nested scrollview
- _hasNestedViewGroup (event, captureListeners) {
+ _hasNestedViewGroup(event, captureListeners) {
if (event.eventPhase !== cc.Event.CAPTURING_PHASE) return;
if (captureListeners) {
//captureListeners are arranged from child to parent
- for (let i = 0; i < captureListeners.length; ++i){
+ for (let i = 0; i < captureListeners.length; ++i) {
let item = captureListeners[i];
if (this.node === item) {
@@ -927,40 +934,40 @@ let ScrollView = cc.Class({
return false;
}
- if(item.getComponent(cc.ViewGroup)) {
+ if (item.getComponent(cc.ViewGroup)) {
return true;
}
}
}
return false;
- },
+ }
//This is for Scrollview as children of a Button
- _stopPropagationIfTargetIsMe (event) {
+ _stopPropagationIfTargetIsMe(event) {
if (event.eventPhase === cc.Event.AT_TARGET && event.target === this.node) {
event.stopPropagation();
}
- },
+ }
// touch event handler
- _onTouchBegan (event, captureListeners) {
- if (!this.enabledInHierarchy) return;
+ _onTouchBegan(event, captureListeners) {
+ if (!this.enabledInHierarchy||!this._content) return;
if (this._hasNestedViewGroup(event, captureListeners)) return;
let touch = event.touch;
- if (this.content) {
- this._handlePressLogic(touch);
+ if (this._content) {
+ this._handlePressLogic();
}
this._touchMoved = false;
this._stopPropagationIfTargetIsMe(event);
- },
+ }
- _onTouchMoved (event, captureListeners) {
- if (!this.enabledInHierarchy) return;
+ _onTouchMoved(event, captureListeners) {
+ if (!this.enabledInHierarchy || !this._content) return;
if (this._hasNestedViewGroup(event, captureListeners)) return;
let touch = event.touch;
- if (this.content) {
+ if (this._content) {
this._handleMoveLogic(touch);
}
// Do not prevent touch events in inner nodes
@@ -982,16 +989,16 @@ let ScrollView = cc.Class({
}
}
this._stopPropagationIfTargetIsMe(event);
- },
+ }
- _onTouchEnded (event, captureListeners) {
- if (!this.enabledInHierarchy) return;
+ _onTouchEnded(event, captureListeners) {
+ if (!this.enabledInHierarchy || !this._content) return;
if (this._hasNestedViewGroup(event, captureListeners)) return;
this._dispatchEvent('touch-up');
let touch = event.touch;
- if (this.content) {
+ if (this._content) {
this._handleReleaseLogic(touch);
}
if (this._touchMoved) {
@@ -999,33 +1006,33 @@ let ScrollView = cc.Class({
} else {
this._stopPropagationIfTargetIsMe(event);
}
- },
-
- _onTouchCancelled (event, captureListeners) {
- if (!this.enabledInHierarchy) return;
+ }
+
+ _onTouchCancelled(event, captureListeners) {
+ if (!this.enabledInHierarchy || !this._content) return;
if (this._hasNestedViewGroup(event, captureListeners)) return;
// Filte touch cancel event send from self
if (!event.simulate) {
let touch = event.touch;
- if(this.content){
+ if (this._content) {
this._handleReleaseLogic(touch);
}
}
this._stopPropagationIfTargetIsMe(event);
- },
+ }
- _processDeltaMove (deltaMove) {
+ _processDeltaMove(deltaMove: Vec3) {
this._scrollChildren(deltaMove);
this._gatherTouchMove(deltaMove);
- },
+ }
- _handleMoveLogic (touch) {
+ _handleMoveLogic(touch) {
let deltaMove = touch.getDelta();
this._processDeltaMove(deltaMove);
- },
+ }
- _scrollChildren (deltaMove) {
+ _scrollChildren(deltaMove: Vec3) {
deltaMove = this._clampDelta(deltaMove);
let realMove = deltaMove;
@@ -1041,30 +1048,32 @@ let ScrollView = cc.Class({
realMove = realMove.add(outOfBoundary);
}
- let scrollEventType = -1;
+ let scrollEventType = '';
+ let pos = new Vec3();
+ this._content!.getPosition(pos);
if (realMove.y > 0) { //up
- let icBottomPos = this.content.y - this.content.anchorY * this.content.height;
+ let icBottomPos = pos.y - this._content!.anchorY * this._content!.height;
if (icBottomPos + realMove.y > this._bottomBoundary) {
scrollEventType = 'scroll-to-bottom';
}
}
else if (realMove.y < 0) { //down
- let icTopPos = this.content.y - this.content.anchorY * this.content.height + this.content.height;
+ let icTopPos = pos.y - this._content!.anchorY * this._content!.height + this._content!.height;
if (icTopPos + realMove.y <= this._topBoundary) {
scrollEventType = 'scroll-to-top';
}
}
else if (realMove.x < 0) { //left
- let icRightPos = this.content.x - this.content.anchorX * this.content.width + this.content.width;
+ let icRightPos = pos.x - this._content!.anchorX * this._content!.width + this._content!.width;
if (icRightPos + realMove.x <= this._rightBoundary) {
scrollEventType = 'scroll-to-right';
}
}
else if (realMove.x > 0) { //right
- let icLeftPos = this.content.x - this.content.anchorX * this.content.width;
+ let icLeftPos = pos.x - this._content!.anchorX * this._content!.width;
if (icLeftPos + realMove.x >= this._leftBoundary) {
scrollEventType = 'scroll-to-left';
}
@@ -1080,13 +1089,13 @@ let ScrollView = cc.Class({
this._dispatchEvent('scrolling');
}
- if (scrollEventType !== -1) {
+ if (scrollEventType.length > 0) {
this._dispatchEvent(scrollEventType);
}
- },
+ }
- _handlePressLogic () {
+ _handlePressLogic() {
if (this._autoScrolling) {
this._dispatchEvent('scroll-ended');
}
@@ -1098,10 +1107,10 @@ let ScrollView = cc.Class({
this._touchMoveTimeDeltas.length = 0;
this._onScrollBarTouchBegan();
- },
+ }
- _clampDelta (delta) {
- let contentSize = this.content.getContentSize();
+ _clampDelta(delta: Vec3) {
+ let contentSize = this._content!.getContentSize();
let scrollViewSize = this.node.getContentSize();
if (contentSize.width < scrollViewSize.width) {
delta.x = 0;
@@ -1111,9 +1120,9 @@ let ScrollView = cc.Class({
}
return delta;
- },
+ }
- _gatherTouchMove (delta) {
+ _gatherTouchMove(delta: Vec3) {
delta = this._clampDelta(delta);
while (this._touchMoveDisplacements.length >= NUMBER_OF_GATHERED_TOUCHES_FOR_MOVE_SPEED) {
@@ -1126,9 +1135,9 @@ let ScrollView = cc.Class({
let timeStamp = getTimeInMilliseconds();
this._touchMoveTimeDeltas.push((timeStamp - this._touchMovePreviousTimestamp) / 1000);
this._touchMovePreviousTimestamp = timeStamp;
- },
+ }
- _startBounceBackIfNeeded () {
+ _startBounceBackIfNeeded() {
if (!this.elastic) {
return false;
}
@@ -1136,7 +1145,7 @@ let ScrollView = cc.Class({
let bounceBackAmount = this._getHowMuchOutOfBoundary();
bounceBackAmount = this._clampDelta(bounceBackAmount);
- if (bounceBackAmount.fuzzyEquals(cc.v2(0, 0), EPSILON)) {
+ if (bounceBackAmount.fuzzyEquals(_vec3Zero, EPSILON)) {
return false;
}
@@ -1152,21 +1161,21 @@ let ScrollView = cc.Class({
}
return true;
- },
+ }
- _processInertiaScroll () {
+ _processInertiaScroll() {
let bounceBackStarted = this._startBounceBackIfNeeded();
if (!bounceBackStarted && this.inertia) {
let touchMoveVelocity = this._calculateTouchMoveVelocity();
- if (!touchMoveVelocity.fuzzyEquals(cc.v2(0, 0), EPSILON) && this.brake < 1) {
+ if (!touchMoveVelocity.fuzzyEquals(_vec3Zero, EPSILON) && this.brake < 1) {
this._startInertiaScroll(touchMoveVelocity);
}
}
this._onScrollBarTouchEnded();
- },
+ }
- _handleReleaseLogic (touch) {
+ _handleReleaseLogic(touch) {
let delta = touch.getDelta();
this._gatherTouchMove(delta);
this._processInertiaScroll();
@@ -1177,14 +1186,14 @@ let ScrollView = cc.Class({
this._dispatchEvent('scroll-ended');
}
}
- },
+ }
- _isOutOfBoundary () {
+ _isOutOfBoundary() {
let outOfBoundary = this._getHowMuchOutOfBoundary();
- return !outOfBoundary.fuzzyEquals(cc.v2(0, 0), EPSILON);
- },
+ return !outOfBoundary.fuzzyEquals(_vec3Zero, EPSILON);
+ }
- _isNecessaryAutoScrollBrake () {
+ _isNecessaryAutoScrollBrake() {
if (this._autoScrollBraking) {
return true;
}
@@ -1202,13 +1211,13 @@ let ScrollView = cc.Class({
}
return false;
- },
+ }
- getScrollEndedEventTiming () {
+ getScrollEndedEventTiming() {
return EPSILON;
- },
+ }
- _processAutoScrolling (dt) {
+ _processAutoScrolling(dt) {
let isAutoScrollBrake = this._isNecessaryAutoScrollBrake();
let brakingFactor = isAutoScrollBrake ? OUT_OF_BOUNDARY_BREAKING_FACTOR : 1;
this._autoScrollAccumulatedTime += dt * (1 / brakingFactor);
@@ -1236,7 +1245,7 @@ let ScrollView = cc.Class({
} else {
let moveDelta = newPosition.sub(this.getContentPosition());
let outOfBoundary = this._getHowMuchOutOfBoundary(moveDelta);
- if (!outOfBoundary.fuzzyEquals(cc.v2(0, 0), EPSILON)) {
+ if (!outOfBoundary.fuzzyEquals(_vec3Zero, EPSILON)) {
newPosition = newPosition.add(outOfBoundary);
reachedEnd = true;
}
@@ -1254,28 +1263,28 @@ let ScrollView = cc.Class({
this._isBouncing = false;
this._dispatchEvent('scroll-ended');
}
- },
+ }
- _startInertiaScroll (touchMoveVelocity) {
+ _startInertiaScroll(touchMoveVelocity: Vec3) {
let inertiaTotalMovement = touchMoveVelocity.mul(MOVEMENT_FACTOR);
this._startAttenuatingAutoScroll(inertiaTotalMovement, touchMoveVelocity);
- },
+ }
- _calculateAttenuatedFactor (distance) {
- if (this.brake <= 0){
+ _calculateAttenuatedFactor(distance: number) {
+ if (this.brake <= 0) {
return (1 - this.brake);
}
//attenuate formula from: http://learnopengl.com/#!Lighting/Light-casters
return (1 - this.brake) * (1 / (1 + distance * 0.000014 + distance * distance * 0.000000008));
- },
+ }
- _startAttenuatingAutoScroll (deltaMove, initialVelocity) {
+ _startAttenuatingAutoScroll(deltaMove: Vec3, initialVelocity: Vec3) {
let time = this._calculateAutoScrollTimeByInitalSpeed(initialVelocity.mag());
let targetDelta = deltaMove.normalize();
- let contentSize = this.content.getContentSize();
+ let contentSize = this._content!.getContentSize();
let scrollviewSize = this.node.getContentSize();
let totalMoveWidth = (contentSize.width - scrollviewSize.width);
@@ -1284,7 +1293,7 @@ let ScrollView = cc.Class({
let attenuatedFactorX = this._calculateAttenuatedFactor(totalMoveWidth);
let attenuatedFactorY = this._calculateAttenuatedFactor(totalMoveHeight);
- targetDelta = cc.v2(targetDelta.x * totalMoveWidth * (1 - this.brake) * attenuatedFactorX, targetDelta.y * totalMoveHeight * attenuatedFactorY * (1 - this.brake));
+ targetDelta = new Vec3(targetDelta.x * totalMoveWidth * (1 - this.brake) * attenuatedFactorX, targetDelta.y * totalMoveHeight * attenuatedFactorY * (1 - this.brake));
let originalMoveLength = deltaMove.mag();
let factor = targetDelta.mag() / originalMoveLength;
@@ -1305,13 +1314,13 @@ let ScrollView = cc.Class({
}
this._startAutoScroll(targetDelta, time, true);
- },
+ }
- _calculateAutoScrollTimeByInitalSpeed (initalSpeed) {
+ _calculateAutoScrollTimeByInitalSpeed(initalSpeed) {
return Math.sqrt(Math.sqrt(initalSpeed / 5));
- },
+ }
- _startAutoScroll (deltaMove, timeInSecond, attenuated) {
+ _startAutoScroll(deltaMove, timeInSecond, attenuated) {
let adjustedDeltaMove = this._flattenVectorByDirection(deltaMove);
this._autoScrolling = true;
@@ -1322,41 +1331,41 @@ let ScrollView = cc.Class({
this._autoScrollAccumulatedTime = 0;
this._autoScrollBraking = false;
this._isScrollEndedWithThresholdEventFired = false;
- this._autoScrollBrakingStartPosition = cc.v2(0, 0);
+ this._autoScrollBrakingStartPosition = new Vec3(0, 0);
let currentOutOfBoundary = this._getHowMuchOutOfBoundary();
- if (!currentOutOfBoundary.fuzzyEquals(cc.v2(0, 0), EPSILON)) {
+ if (!currentOutOfBoundary.fuzzyEquals(_vec3Zero, EPSILON)) {
this._autoScrollCurrentlyOutOfBoundary = true;
}
- },
+ }
- _calculateTouchMoveVelocity () {
+ _calculateTouchMoveVelocity() {
let totalTime = 0;
- totalTime = this._touchMoveTimeDeltas.reduce(function(a, b) {
+ totalTime = this._touchMoveTimeDeltas.reduce(function (a, b) {
return a + b;
}, totalTime);
if (totalTime <= 0 || totalTime >= 0.5) {
- return cc.v2(0, 0);
+ return new Vec3(0, 0);
}
- let totalMovement = cc.v2(0, 0);
- totalMovement = this._touchMoveDisplacements.reduce(function(a, b) {
+ let totalMovement = new Vec3(0, 0);
+ totalMovement = this._touchMoveDisplacements.reduce(function (a, b) {
return a.add(b);
}, totalMovement);
- return cc.v2(totalMovement.x * (1 - this.brake) / totalTime,
- totalMovement.y * (1 - this.brake) / totalTime);
- },
+ return new Vec3(totalMovement.x * (1 - this.brake) / totalTime,
+ totalMovement.y * (1 - this.brake) / totalTime);
+ }
- _flattenVectorByDirection (vector) {
+ _flattenVectorByDirection(vector: Vec3) {
let result = vector;
result.x = this.horizontal ? result.x : 0;
result.y = this.vertical ? result.y : 0;
return result;
- },
+ }
- _moveContent (deltaMove, canStartBounceBack) {
+ _moveContent(deltaMove: Vec3, canStartBounceBack?: boolean) {
let adjustedMove = this._flattenVectorByDirection(deltaMove);
let newPosition = this.getContentPosition().add(adjustedMove);
@@ -1368,35 +1377,35 @@ let ScrollView = cc.Class({
if (this.elastic && canStartBounceBack) {
this._startBounceBackIfNeeded();
}
- },
+ }
- _getContentLeftBoundary () {
+ _getContentLeftBoundary() {
let contentPos = this.getContentPosition();
- return contentPos.x - this.content.getAnchorPoint().x * this.content.getContentSize().width;
- },
+ return contentPos.x - this._content!.getAnchorPoint().x * this._content!.getContentSize().width;
+ }
- _getContentRightBoundary () {
- let contentSize = this.content.getContentSize();
+ _getContentRightBoundary() {
+ let contentSize = this._content!.getContentSize();
return this._getContentLeftBoundary() + contentSize.width;
- },
+ }
- _getContentTopBoundary () {
- let contentSize = this.content.getContentSize();
+ _getContentTopBoundary() {
+ let contentSize = this._content!.getContentSize();
return this._getContentBottomBoundary() + contentSize.height;
- },
+ }
- _getContentBottomBoundary () {
+ _getContentBottomBoundary() {
let contentPos = this.getContentPosition();
- return contentPos.y - this.content.getAnchorPoint().y * this.content.getContentSize().height;
- },
+ return contentPos.y - this._content!.getAnchorPoint().y * this._content!.getContentSize().height;
+ }
- _getHowMuchOutOfBoundary (addition) {
- addition = addition || cc.v2(0, 0);
- if (addition.fuzzyEquals(cc.v2(0, 0), EPSILON) && !this._outOfBoundaryAmountDirty) {
+ _getHowMuchOutOfBoundary(addition?: Vec3) {
+ addition = addition || new Vec3(0, 0);
+ if (addition.fuzzyEquals(_vec3Zero, EPSILON) && !this._outOfBoundaryAmountDirty) {
return this._outOfBoundaryAmount;
}
- let outOfBoundaryAmount = cc.v2(0, 0);
+ let outOfBoundaryAmount = new Vec3(0, 0);
if (this._getContentLeftBoundary() + addition.x > this._leftBoundary) {
outOfBoundaryAmount.x = this._leftBoundary - (this._getContentLeftBoundary() + addition.x);
} else if (this._getContentRightBoundary() + addition.x < this._rightBoundary) {
@@ -1409,7 +1418,7 @@ let ScrollView = cc.Class({
outOfBoundaryAmount.y = this._bottomBoundary - (this._getContentBottomBoundary() + addition.y);
}
- if (addition.fuzzyEquals(cc.v2(0, 0), EPSILON)) {
+ if (addition.fuzzyEquals(_vec3Zero, EPSILON)) {
this._outOfBoundaryAmount = outOfBoundaryAmount;
this._outOfBoundaryAmountDirty = false;
}
@@ -1417,46 +1426,46 @@ let ScrollView = cc.Class({
outOfBoundaryAmount = this._clampDelta(outOfBoundaryAmount);
return outOfBoundaryAmount;
- },
+ }
- _updateScrollBar (outOfBoundary) {
- if (this.horizontalScrollBar) {
- this.horizontalScrollBar._onScroll(outOfBoundary);
+ _updateScrollBar(outOfBoundary) {
+ if (this._horizontalScrollBar) {
+ this._horizontalScrollBar.onScroll(outOfBoundary);
}
if (this.verticalScrollBar) {
- this.verticalScrollBar._onScroll(outOfBoundary);
+ this.verticalScrollBar.onScroll(outOfBoundary);
}
- },
+ }
- _onScrollBarTouchBegan () {
- if (this.horizontalScrollBar) {
- this.horizontalScrollBar._onTouchBegan();
+ _onScrollBarTouchBegan() {
+ if (this._horizontalScrollBar) {
+ this._horizontalScrollBar.onTouchBegan();
}
if (this.verticalScrollBar) {
- this.verticalScrollBar._onTouchBegan();
+ this.verticalScrollBar.onTouchBegan();
}
- },
+ }
- _onScrollBarTouchEnded () {
- if (this.horizontalScrollBar) {
- this.horizontalScrollBar._onTouchEnded();
+ _onScrollBarTouchEnded() {
+ if (this._horizontalScrollBar) {
+ this._horizontalScrollBar.onTouchEnded();
}
if (this.verticalScrollBar) {
- this.verticalScrollBar._onTouchEnded();
+ this.verticalScrollBar.onTouchEnded();
}
- },
+ }
- _dispatchEvent (event) {
+ _dispatchEvent(event) {
if (event === 'scroll-ended') {
this._scrollEventEmitMask = 0;
} else if (event === 'scroll-to-top'
- || event === 'scroll-to-bottom'
- || event === 'scroll-to-left'
- || event === 'scroll-to-right') {
+ || event === 'scroll-to-bottom'
+ || event === 'scroll-to-left'
+ || event === 'scroll-to-right') {
let flag = (1 << eventMap[event]);
if (this._scrollEventEmitMask & flag) {
@@ -1468,94 +1477,96 @@ let ScrollView = cc.Class({
cc.Component.EventHandler.emitEvents(this.scrollEvents, this, eventMap[event]);
this.node.emit(event, this);
- },
+ }
+
+ _adjustContentOutOfBoundary() {
+ if(!this._content){
+ return;
+ }
- _adjustContentOutOfBoundary () {
this._outOfBoundaryAmountDirty = true;
if (this._isOutOfBoundary()) {
- let outOfBoundary = this._getHowMuchOutOfBoundary(cc.v2(0, 0));
+ let outOfBoundary = this._getHowMuchOutOfBoundary(new Vec3(0, 0));
let newPosition = this.getContentPosition().add(outOfBoundary);
- if (this.content) {
- this.content.setPosition(newPosition);
+ if (this._content) {
+ this._content.setPosition(newPosition);
this._updateScrollBar(0);
}
}
- },
+ }
- start () {
+ start() {
this._calculateBoundary();
//Because widget component will adjust content position and scrollview position is correct after visit
//So this event could make sure the content is on the correct position after loading.
- if (this.content) {
+ if (this._content) {
cc.director.once(cc.Director.EVENT_BEFORE_DRAW, this._adjustContentOutOfBoundary, this);
}
- },
+ }
- _hideScrollbar () {
- if (this.horizontalScrollBar) {
- this.horizontalScrollBar.hide();
+ _hideScrollbar() {
+ if (this._horizontalScrollBar) {
+ this._horizontalScrollBar.hide();
}
if (this.verticalScrollBar) {
this.verticalScrollBar.hide();
}
- },
+ }
- _showScrollbar () {
- if (this.horizontalScrollBar) {
- this.horizontalScrollBar.show();
+ _showScrollbar() {
+ if (this._horizontalScrollBar) {
+ this._horizontalScrollBar.show();
}
if (this.verticalScrollBar) {
this.verticalScrollBar.show();
}
- },
+ }
- onDisable () {
+ onDisable() {
if (!CC_EDITOR) {
this._unregisterEvent();
this.node.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this);
this.node.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this);
- if (this.content) {
- this.content.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this);
- this.content.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this);
- if (this.content.parent) {
- this.content.parent.off(NodeEvent.POSITION_CHANGED, this._calculateBoundary, this);
- this.content.parent.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this);
- this.content.parent.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this);
+ if (this._content) {
+ this._content.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this);
+ this._content.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this);
+ if (this._content.parent) {
+ this._content.parent.off(NodeEvent.POSITION_CHANGED, this._calculateBoundary, this);
+ this._content.parent.off(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this);
+ this._content.parent.off(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this);
}
}
}
this._hideScrollbar();
this.stopAutoScroll();
- },
+ }
- onEnable () {
+ onEnable() {
if (!CC_EDITOR) {
this._registerEvent();
this.node.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this);
this.node.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this);
- if (this.content) {
- this.content.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this);
- this.content.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this);
- if (this.content.parent) {
- this.content.parent.on(NodeEvent.POSITION_CHANGED, this._calculateBoundary, this);
- this.content.parent.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this);
- this.content.parent.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this);
+ if (this._content) {
+ this._content.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this);
+ this._content.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this);
+ if (this._content.parent) {
+ this._content.parent.on(NodeEvent.POSITION_CHANGED, this._calculateBoundary, this);
+ this._content.parent.on(NodeEvent.SCALE_CHANGED, this._calculateBoundary, this);
+ this._content.parent.on(NodeEvent.SIZE_CHANGED, this._calculateBoundary, this);
}
}
}
this._showScrollbar();
- },
+ }
- update (dt) {
+ update(dt) {
if (this._autoScrolling) {
this._processAutoScrolling(dt);
}
}
-});
-
-cc.ScrollView = module.exports = ScrollView;
+}
/**
* !#en
@@ -1667,12 +1678,12 @@ cc.ScrollView = module.exports = ScrollView;
* @param {ScrollView} scrollView - The ScrollView component.
*/
- /**
- * !#en
- * Note: This event is emitted from the node to which the component belongs.
- * !#zh
- * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
- * @event scroll-began
- * @param {Event.EventCustom} event
- * @param {ScrollView} scrollView - The ScrollView component.
- */
+/**
+* !#en
+* Note: This event is emitted from the node to which the component belongs.
+* !#zh
+* 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。
+* @event scroll-began
+* @param {Event.EventCustom} event
+* @param {ScrollView} scrollView - The ScrollView component.
+*/
diff --git a/cocos/3d/ui/components/slider-component.ts b/cocos/3d/ui/components/slider-component.ts
new file mode 100644
index 0000000000..6e96eef091
--- /dev/null
+++ b/cocos/3d/ui/components/slider-component.ts
@@ -0,0 +1,281 @@
+/****************************************************************************
+ 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 { Component} from '../../../components/component';
+import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator';
+import Event from '../../../core/event/event';
+import { EventTouch } from '../../../core/platform/event-manager/CCEvent';
+import { clamp01 } from '../../../core/utils/misc';
+import { Enum, Vec2 } from '../../../core/value-types/index';
+import { SpriteComponent} from './sprite-component';
+import { UITransformComponent } from './ui-transfrom-component';
+/**
+ * !#en The Slider Direction
+ * !#zh 滑动器方向
+ * @enum Slider.Direction
+ */
+enum Direction {
+ /**
+ * !#en The horizontal direction.
+ * !#zh 水平方向
+ * @property {Number} Horizontal
+ */
+ Horizontal = 0,
+ /**
+ * !#en The vertical direction.
+ * !#zh 垂直方向
+ * @property {Number} Vertical
+ */
+ Vertical = 1,
+}
+
+Enum(Direction);
+
+/**
+ * !#en The Slider Control
+ * !#zh 滑动器组件
+ * @class Slider
+ * @extends Component
+ */
+@ccclass('cc.SliderComponent')
+@executionOrder(100)
+@menu('UI/Slider')
+// @executeInEditMode
+export class SliderComponent extends Component {
+
+ /**
+ * !#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({
+ slide: true,
+ range: [0.1, 1, 0.01],
+ })
+ 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;
+ }
+
+ public static Direction = Direction;
+ @property
+ public _handle: SpriteComponent | null = null;
+ @property
+ public _direction: number = Direction.Horizontal;
+ @property
+ public _progress: number = 0.1;
+ @property
+ public _slideEvents: ComponentEventHandler[] = [];
+
+ public _offset: Vec2 = new Vec2();
+ public _dragging = false;
+ public _touchHandle = false;
+
+ public __preload () {
+ this._updateHandlePosition();
+ }
+
+ // 注册事件
+ public 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);
+ }
+ }
+
+ public 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);
+ }
+ }
+
+ public _onHandleDragStart (event: Event) {
+ if (!event) {
+ return;
+ }
+
+ this._dragging = true;
+ this._touchHandle = true;
+ this._offset = this._handle && this._handle.node.uiTransfromComp && this._handle.node.uiTransfromComp.convertToNodeSpaceAR((event as EventTouch).touch.getLocation());
+
+ event.stopPropagation();
+ }
+
+ public _onTouchBegan (event: Event) {
+ if (!this._handle) { return; }
+ this._dragging = true;
+ if (!this._touchHandle) {
+ this._handleSliderLogic((event as EventTouch).touch);
+ }
+
+ event.stopPropagation();
+ }
+
+ public _onTouchMoved (event: Event) {
+ if (!this._dragging) { return; }
+ this._handleSliderLogic((event as EventTouch).touch);
+ event.stopPropagation();
+ }
+
+ public _onTouchEnded (event: Event) {
+ this._dragging = false;
+ this._touchHandle = false;
+ this._offset = cc.v2();
+ event.stopPropagation();
+ }
+
+ public _onTouchCancelled (event: Event) {
+ this._dragging = false;
+ event.stopPropagation();
+ }
+
+ public _handleSliderLogic (touch) {
+ this._updateProgress(touch);
+ this._emitSlideEvent();
+ }
+
+ public _emitSlideEvent () {
+ cc.Component.EventHandler.emitEvents(this.slideEvents, this);
+ this.node.emit('slide', this);
+ }
+
+ public _updateProgress (touch: EventTouch) {
+ if (!this._handle) { return; }
+ const localTouchPos = this.node.uiTransfromComp!.convertToNodeSpaceAR((touch as EventTouch).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);
+ }
+ }
+
+ public _updateHandlePosition () {
+ if (!this._handle) { return; }
+ let 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);
+ }
+ const worldSpacePos = this.node.uiTransfromComp!.convertToWorldSpaceAR(handlelocalPos);
+ const transform: UITransformComponent | null = this._handle.node.parent && this._handle.node.parent.getComponent(cc.UITransformComponent);
+ if (transform) {
+ this._handle.node.setPosition(transform.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..b819f2d84b
--- /dev/null
+++ b/cocos/3d/ui/components/sprite-component.ts
@@ -0,0 +1,619 @@
+/****************************************************************************
+ 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 { UIRenderComponent } from './ui-render-component';
+import { Node } from '../../../scene-graph/node';
+import { UI } from '../../../renderer/ui/ui';
+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 UIRenderComponent {
+
+ /**
+ * !#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 _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.get('default-spriteframe');
+ }
+
+ // this.node.on(EventType.SIZE_CHANGED, this._onNodeSizeDirty, this);
+ // this.node.on(EventType.ANCHOR_CHANGED, this._onNodeSizeDirty, this);
+ }
+
+ public updateAssembler (render: UI) {
+ if (!this._spriteFrame || !this.material) {
+ return;
+ }
+ super.updateAssembler(render);
+ }
+
+ 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) {
+ if (this._assembler) {
+ 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.get('sprite-material');
+ material = this.material;
+ if (spriteFrame && spriteFrame.textureLoaded()) {
+ material!.setProperty('u_texSampler', spriteFrame);
+ this.markForUpdateRenderData(true);
+ }
+ }
+ // TODO:
+ // else {
+ // if (spriteFrame && spriteFrame.textureLoaded()) {
+ // const matTexture = material && material.getProperty('u_texSampler');
+ // if (matTexture !== spriteFrame) {
+ // material.setProperty('u_texSampler', 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, (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..f91afe63f3
--- /dev/null
+++ b/cocos/3d/ui/components/toggle-component.ts
@@ -0,0 +1,292 @@
+/****************************************************************************
+ 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 { 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 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..0df82c396e 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 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..e27de57a10 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 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..87b5b57160
--- /dev/null
+++ b/cocos/3d/ui/components/ui-render-component.ts
@@ -0,0 +1,304 @@
+/****************************************************************************
+ 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 { UI } from '../../../renderer/ui/ui';
+import { IAssembler } from '../assembler/assembler';
+import { MeshBuffer } from '../mesh-buffer';
+import { CanvasComponent } from './canvas-component';
+import { UITransformComponent } from './ui-transfrom-component';
+
+/**
+ * !#en
+ * Base class for components which supports rendering features.
+ * !#zh
+ * 所有支持渲染的组件的基类
+ *
+ * @class UIRenderComponent
+ * @extends Component
+ */
+@ccclass('cc.UIRenderComponent')
+@executionOrder(100)
+@requireComponent(UITransformComponent)
+export class UIRenderComponent 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);
+ }
+
+ /**
+ * !#en render order, render order according to width, and arrange once under the same level node.
+ * !#zh 渲染先后顺序,按照广度渲染排列,同级节点下进行一次排列
+ */
+ @property
+ get priority() {
+ return this._priority;
+ }
+
+ set priority(value) {
+ this._priority = value;
+ }
+
+ /**
+ * !#en render color
+ * !#zh 渲染颜色
+ * @property color
+ */
+ get color() {
+ return this._color;
+ }
+
+ set color(value) {
+ if (this._color === value) {
+ return;
+ }
+
+ this._color = value;
+ }
+
+ get visibility () {
+ return this._visibility;
+ }
+
+ get renderData () {
+ return this._renderData;
+ }
+
+ public static assembler = null;
+
+ protected _assembler: IAssembler | null = null;
+
+ protected _postAssembler: IAssembler | null = null;
+ protected _renderDataPoolID: number = -1;
+ protected _visibility: number = -1;
+
+ protected _srcBlendFactor: number = macro.BlendFactor.SRC_ALPHA;
+ protected _dstBlendFactor: number = macro.BlendFactor.ONE_MINUS_SRC_ALPHA;
+ @property
+ protected _color: Color = Color.WHITE;
+ @property
+ protected _priority: number = 0;
+ 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._visibility = 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._visibility = -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();
+ // }
+ }
+
+ public updateAssembler (render: UI) {
+ if (!this._assembler) {
+ return;
+ }
+ if (this._assembler.updateRenderData) {
+ this._assembler.updateRenderData(this);
+ }
+ this._assembler.fillBuffers(this, render);
+ }
+
+ public postUpdateAssembler () {
+ if (!this._postAssembler) {
+ return;
+ }
+ if (this._postAssembler.updateRenderData) {
+ this._postAssembler.updateRenderData(this);
+ }
+ }
+}
+
+// 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..bc113e7d4f
--- /dev/null
+++ b/cocos/3d/ui/components/ui-transfrom-component.ts
@@ -0,0 +1,325 @@
+import { Component} from '../../../components/component';
+import { ccclass, executeInEditMode, executionOrder, property } from '../../../core/data/class-decorator';
+import Event from '../../../core/event/event';
+import { Enum, Mat4 } from '../../../core/value-types';
+import Size from '../../../core/value-types/size';
+import Vec2 from '../../../core/value-types/vec2';
+import * as math from '../../../core/vmath/index';
+
+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)
+@executeInEditMode
+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 __preload () {
+ this.node.uiTransfromComp = this;
+ }
+
+ public onDestroy () {
+ 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|number, height?: number) {
+ const locContentSize = this._contentSize;
+ // var clone;
+ if (height === undefined) {
+ size = size as Size;
+ 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 | number, y?: number) {
+ const locAnchorPoint = this._anchorPoint;
+ if (y === undefined) {
+ point = point as Vec2;
+ 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|null = null) {
+ 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.node.uiTransfromComp!.isHit(cameraPt) : true;
+ } else {
+ listener.mask = null;
+ return true;
+ }
+ } else {
+ return true;
+ }
+ } else {
+ return false;
+ }
+ }
+
+ /**
+ * !#en
+ * Converts a Point to node (local) space coordinates in which the anchor point is the origin position.
+ * !#zh
+ * 将一个点转换到节点 (局部) 空间坐标系,这个坐标系以锚点为原点。
+ * @method convertToNodeSpaceAR
+ * @param {Vec2} worldPoint
+ * @return {Vec2}
+ * @example
+ * var newVec2 = node.convertToNodeSpaceAR(cc.v2(100, 100));
+ */
+ public convertToNodeSpaceAR (worldPoint) {
+ const matrix = new Mat4();
+ this.node.getWorldMatrix(matrix);
+ math.mat4.invert(_mat4_temp, matrix);
+ const out = new cc.Vec2();
+ return math.vec2.transformMat4(out, worldPoint, _mat4_temp);
+ }
+
+ /**
+ * !#en
+ * Converts a Point in node coordinates to world space coordinates.
+ * !#zh
+ * 将节点坐标系下的一个点转换到世界空间坐标系。
+ * @method convertToWorldSpaceAR
+ * @param {Vec2} nodePoint
+ * @return {Vec2}
+ * @example
+ * var newVec2 = node.convertToWorldSpaceAR(cc.v2(100, 100));
+ */
+ public convertToWorldSpaceAR (nodePoint) {
+ this.node.getWorldMatrix(_worldMatrix);
+ const out = new cc.Vec2();
+ return math.vec2.transformMat4(out, nodePoint, _worldMatrix);
+ }
+}
diff --git a/cocos/2d/ui/CCViewGroup.js b/cocos/3d/ui/components/view-group-component.ts
similarity index 94%
rename from cocos/2d/ui/CCViewGroup.js
rename to cocos/3d/ui/components/view-group-component.ts
index 04b7b2f79f..9317c26127 100644
--- a/cocos/2d/ui/CCViewGroup.js
+++ b/cocos/3d/ui/components/view-group-component.ts
@@ -39,11 +39,9 @@
* @class ViewGroup
* @extends Component
*/
-var ViewGroup = cc.Class({
- name: 'cc.ViewGroup',
- extends: require('./CCComponent')
-});
+import { Component } from "../../../components/component";
+export class ViewGroupComponent extends Component{
-cc.ViewGroup = module.exports = ViewGroup;
+}
diff --git a/cocos/3d/ui/components/widget-component.ts b/cocos/3d/ui/components/widget-component.ts
new file mode 100644
index 0000000000..24c9160a1d
--- /dev/null
+++ b/cocos/3d/ui/components/widget-component.ts
@@ -0,0 +1,645 @@
+/****************************************************************************
+ 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 { widgetManager } from '../../../2d/base-ui/widget-manager';
+import { Component} from '../../../components/component';
+import { ccclass, executeInEditMode, executionOrder, menu, property } 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
+ */
+const AlignMode = widgetManager.AlignMode;
+
+const AlignFlags = widgetManager._AlignFlags;
+const TOP = AlignFlags.TOP;
+const MID = AlignFlags.MID;
+const BOT = AlignFlags.BOT;
+const LEFT = AlignFlags.LEFT;
+const CENTER = AlignFlags.CENTER;
+const RIGHT = AlignFlags.RIGHT;
+const TOP_BOT = TOP | BOT;
+const 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 class WidgetComponent extends Component {
+
+ /**
+ * !#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: Node,
+ })
+ 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._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;
+ }
+
+ public static AlignMode = AlignMode;
+ /**
+ * !#zh: 对齐开关,由 AlignFlags 组成
+ *
+ * @property _alignFlags
+ * @type {Number}
+ * @default 0
+ * @private
+ */
+ private _alignFlags = 0;
+ private _wasAlignOnce = false;
+ @property
+ private _target: Node | null = null;
+ @property
+ private _left = 0;
+ @property
+ private _right = 0;
+ @property
+ private _top = 0;
+ @property
+ private _bottom = 0;
+ @property
+ private _horizontalCenter = 0;
+ @property
+ private _verticalCenter = 0;
+ @property
+ private _isAbsLeft = true;
+ @property
+ private _isAbsRight = true;
+ @property
+ private _isAbsTop = true;
+ @property
+ private _isAbsBottom = true;
+ @property
+ private _isAbsHorizontalCenter = true;
+ @property
+ private _isAbsVerticalCenter = true;
+ // original size before align
+ @property
+ private _originalWidth = 0;
+ @property
+ private _originalHeight = 0;
+ @property
+ private _alignMode = AlignMode.ON_WINDOW_RESIZE;
+
+ /**
+ * !#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
+ */
+ public updateAlignment () {
+ widgetManager.updateAlignment(this.node);
+ }
+
+ protected onLoad () {
+ // TODO:
+ // if (this._wasAlignOnce) {
+ // // migrate for old version
+ // this.alignMode = this._wasAlignOnce ? AlignMode.ONCE : AlignMode.ALWAYS;
+ // this._wasAlignOnce = false;
+ // }
+ if(this._alignMode === AlignMode.ONCE){
+ this._wasAlignOnce = true;
+ }
+ }
+
+ protected onEnable () {
+ widgetManager.add(this);
+ }
+
+ protected onDisable () {
+ widgetManager.remove(this);
+ }
+
+ private _setAlign (flag, isAlign) {
+ const current = (this._alignFlags & flag) > 0;
+ if (isAlign === current) {
+ return;
+ }
+ const 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
+ * 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..9ff479d8fc
--- /dev/null
+++ b/cocos/3d/ui/index.ts
@@ -0,0 +1,37 @@
+
+import { CanvasComponent } from './components/canvas-component';
+import { UIRenderComponent } from './components/ui-render-component';
+import './components/ui-transfrom-component';
+import { SpriteComponent } from './components/sprite-component';
+import { LabelComponent } from './components/label-component';
+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';
+import { ScrollBarComponent } from './components/scroll-bar-component';
+import { ViewGroupComponent } from './components/view-group-component';
+import { ScrollViewComponent } from './components/scroll-view-component';
+import { LayoutComponent } from './components/layout-component';
+
+cc.CanvasComponent = CanvasComponent;
+cc.UIRenderComponent = UIRenderComponent;
+cc.SpriteComponent = SpriteComponent;
+cc.LabelComponent = LabelComponent;
+cc.ButtonComponent = ButtonComponent;
+cc.ToggleGroupComponent = ToggleGroupComponent;
+cc.ToggleComponent = ToggleComponent;
+cc.ToggleContainerComponent = ToggleContainerComponent;
+cc.SliderComponent = SliderComponent;
+cc.ProgressBarComponent = ProgressBarComponent;
+cc.WidgetComponent = WidgetComponent;
+cc.EditBoxComponent = EditBoxComponent;
+cc.ViewGroupComponent = ViewGroupComponent;
+cc.ScrollBarComponent = ScrollBarComponent;
+cc.ScrollViewComponent = ScrollViewComponent;
+cc.LayoutComponent = LayoutComponent;
+
diff --git a/cocos/3d/ui/mesh-buffer.ts b/cocos/3d/ui/mesh-buffer.ts
new file mode 100644
index 0000000000..35e439bfc0
--- /dev/null
+++ b/cocos/3d/ui/mesh-buffer.ts
@@ -0,0 +1,246 @@
+// 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, GFXPrimitiveMode } from '../../gfx/define';
+import { IGFXInputAttribute } from '../../gfx/input-assembler';
+// import UISystem from '../UISystem';
+
+export interface IMeshBufferInitData {
+ vertexCount: number;
+ indiceCount: 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;
+ public primitiveMode: GFXPrimitiveMode = GFXPrimitiveMode.TRIANGLE_LIST;
+
+ 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.indiceCount;
+ this.primitiveMode = GFXPrimitiveMode.TRIANGLE_LIST;
+ this.byteOffset = 0;
+ this.byteStart = 0;
+ this.indiceStart = 0;
+ this.indiceOffset = 0;
+ this.vertexStart = 0;
+ this.vertexOffset = 0;
+ 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) {
+ // if (this._initVDataCount * 4 > this.vData.byteLength){
+ // oldVData = new Uint8Array(this.vData.buffer);
+ // }
+ // }
+
+ if (this.vData && this.vData.byteLength === this._initVDataCount) {
+ return;
+ }
+
+ 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;
+
+ if (this.iData && this.iData.byteLength === this._initIDataCount) {
+ return;
+ }
+
+ 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/animation/CCAnimation.js b/cocos/animation/CCAnimation.js
index 587ed549d5..6314d5d338 100644
--- a/cocos/animation/CCAnimation.js
+++ b/cocos/animation/CCAnimation.js
@@ -62,7 +62,7 @@ var EventType = cc.Enum({
/**
* !#en Emit when pause animation
* !#zh 暂停播放时触发
- * @property {String} PAUSE
+ * @property {String} PAUSE
* @static
*/
PAUSE: 'pause',
@@ -91,7 +91,7 @@ var EventType = cc.Enum({
/**
* !#en The animation component is used to play back animations.
- *
+ *
* Animation provide several events to register:
* - play : Emit when begin playing animation
* - stop : Emit when stop playing animation
@@ -101,7 +101,7 @@ var EventType = cc.Enum({
* - finished : Emit when finish playing animation
*
* !#zh Animation 组件用于播放动画。
- *
+ *
* Animation 提供了一系列可注册的事件:
* - play : 开始播放时
* - stop : 停止播放时
@@ -109,14 +109,14 @@ var EventType = cc.Enum({
* - resume : 恢复播放时
* - lastframe : 假如动画循环次数大于 1,当动画播放到最后一帧时
* - finished : 动画播放完成时
- *
+ *
* @class Animation
* @extends Component
* @uses EventTarget
*/
var Animation = cc.Class({
name: 'cc.Animation',
- extends: require('./CCComponent'),
+ extends: require('./component'),
mixins: [EventTarget],
editor: CC_EDITOR && {
@@ -305,7 +305,7 @@ var Animation = cc.Class({
if (state) {
this.enabled = true;
-
+
var animator = this._animator;
if (animator.isPlaying && state.isPlaying) {
if (state.isPaused) {
@@ -488,7 +488,7 @@ var Animation = cc.Class({
},
/**
- * !#en
+ * !#en
* Remove clip from the animation list. This will remove the clip and any animation states based on it.
* If there are animation states depand on the clip are playing or clip is defaultClip, it will not delete the clip.
* But if force is true, then will always remove the clip and any animation states based on it. If clip is defaultClip, defaultClip will be reset to null
@@ -521,7 +521,7 @@ var Animation = cc.Class({
else {
if (!CC_TEST) cc.warnID(3902);
return;
- }
+ }
}
if (state && state.isPlaying) {
@@ -537,7 +537,7 @@ var Animation = cc.Class({
});
if (state) {
- delete this._nameToState[state.name];
+ delete this._nameToState[state.name];
}
},
@@ -565,7 +565,7 @@ var Animation = cc.Class({
/**
- * !#en
+ * !#en
* Register animation event callback.
* The event arguments will provide the AnimationState which emit the event.
* When play an animation, will auto register the event callback to the AnimationState, and unregister the event callback from the AnimationState when animation stopped.
@@ -577,7 +577,7 @@ var Animation = cc.Class({
* @param {String} type - A string representing the event type to listen for.
* @param {Function} callback - The callback that will be invoked when the event is dispatched.
* The callback is ignored if it is a duplicate (the callbacks are unique).
- * @param {cc.AnimationState} state
+ * @param {cc.AnimationState} state
* @param {Object} [target] - The target (this object) to invoke the callback, can be null
* @param {Boolean} [useCapture=false] - When set to true, the capture argument prevents callback
* from being invoked when the event's eventPhase attribute value is BUBBLING_PHASE.
@@ -592,7 +592,7 @@ var Animation = cc.Class({
* onPlay: function (type, state) {
* // callback
* }
- *
+ *
* // register event to all animation
* animation.on('play', this.onPlay, this);
*/
@@ -658,7 +658,7 @@ var Animation = cc.Class({
_createStates: function() {
this._nameToState = js.createMap(true);
-
+
// create animation states
var state = null;
var defaultClipState = false;
diff --git a/cocos/assets/CCAssetLibrary.js b/cocos/assets/CCAssetLibrary.js
index bfdf1d27a2..fb6020b08a 100644
--- a/cocos/assets/CCAssetLibrary.js
+++ b/cocos/assets/CCAssetLibrary.js
@@ -25,7 +25,7 @@
****************************************************************************/
import {createMap, isChildClassOf, _getClassById} from '../core/utils/js';
-import Asset from './CCAsset';
+import { Asset } from './asset';
import {callInNextTick} from '../core/utils/misc';
import decodeUuid from '../core/utils/decode-uuid';
import Loader from '../load-pipeline/CCLoader';
@@ -348,11 +348,11 @@ let AssetLibrary = {
_uuidToRawAsset[uuid] = new RawAssetEntry(mountPoint + '/' + url, type);
// init resources
var isSubAsset = info[2] === 1;
-
+
if (!assetTables[mountPoint]) {
assetTables[mountPoint] = new AssetTable();
- }
-
+ }
+
assetTables[mountPoint].add(url, uuid, type, !isSubAsset);
}
}
diff --git a/cocos/assets/CCFont.js b/cocos/assets/CCFont.js
index 3c0cb6e939..37dcfe23e6 100644
--- a/cocos/assets/CCFont.js
+++ b/cocos/assets/CCFont.js
@@ -24,7 +24,7 @@
THE SOFTWARE.
****************************************************************************/
-import Asset from './CCAsset';
+import { Asset } from './asset';
import {ccclass} from '../core/data/class-decorator';
/**
diff --git a/cocos/assets/CCGLTFAsset.js b/cocos/assets/CCGLTFAsset.js
index 4e8c114118..b44718a902 100644
--- a/cocos/assets/CCGLTFAsset.js
+++ b/cocos/assets/CCGLTFAsset.js
@@ -26,7 +26,7 @@
import { _decorator } from "../core/data/index";
const { ccclass, property } = _decorator;
import BufferAsset from "./CCBufferAsset";
-import Asset from "./CCAsset";
+import { Asset } from "./asset";
/**
* @typedef {import("../../../types/glTF/glTF").GlTf} GlTf
@@ -37,7 +37,7 @@ import Asset from "./CCAsset";
* Class for GLTF file.
*
* !#zh
- * GLTF 资源类。
+ * GLTF 资溝类。
*
* @class GLTFAsset
* @extends Asset
@@ -80,4 +80,4 @@ export default class GLTFAsset extends Asset {
}
}
-cc.GLTFAsset = GLTFAsset;
\ No newline at end of file
+cc.GLTFAsset = GLTFAsset;
diff --git a/cocos/assets/CCJsonAsset.js b/cocos/assets/CCJsonAsset.js
index 9ace3831ed..07185e57a9 100644
--- a/cocos/assets/CCJsonAsset.js
+++ b/cocos/assets/CCJsonAsset.js
@@ -23,7 +23,7 @@
THE SOFTWARE.
****************************************************************************/
-import Asset from './CCAsset';
+import { Asset } from './asset';
import {ccclass, property} from '../core/data/class-decorator';
/**
diff --git a/cocos/assets/CCPrefab.js b/cocos/assets/CCPrefab.js
index 08083bfca1..c53d4c4b79 100644
--- a/cocos/assets/CCPrefab.js
+++ b/cocos/assets/CCPrefab.js
@@ -27,7 +27,7 @@
import {compile} from '../core/data/instantiate-jit';
import Enum from '../core/value-types/enum';
import {obsolete} from '../core/utils/js';
-import Asset from './CCAsset';
+import { Asset } from './asset';
import {ccclass, property} from '../core/data/class-decorator';
/**
@@ -203,4 +203,4 @@ export default class Prefab extends Asset {
}
cc.Prefab = Prefab;
-obsolete(cc, 'cc._Prefab', 'Prefab');
\ No newline at end of file
+obsolete(cc, 'cc._Prefab', 'Prefab');
diff --git a/cocos/assets/CCSceneAsset.js b/cocos/assets/CCSceneAsset.js
index 1058ad9092..dd948ec349 100644
--- a/cocos/assets/CCSceneAsset.js
+++ b/cocos/assets/CCSceneAsset.js
@@ -24,7 +24,7 @@
THE SOFTWARE.
****************************************************************************/
-import Asset from './CCAsset';
+import { Asset } from './asset';
import {ccclass, property} from '../core/data/class-decorator';
/**
@@ -60,4 +60,4 @@ export default class SceneAsset extends Asset {
//}
}
-cc.SceneAsset = SceneAsset;
\ No newline at end of file
+cc.SceneAsset = SceneAsset;
diff --git a/cocos/assets/CCScripts.js b/cocos/assets/CCScripts.js
index aca55d426f..9a1bf850db 100644
--- a/cocos/assets/CCScripts.js
+++ b/cocos/assets/CCScripts.js
@@ -24,7 +24,7 @@
THE SOFTWARE.
****************************************************************************/
-import Asset from './CCAsset';
+import { Asset } from './asset';
import {ccclass} from '../core/data/class-decorator';
/**
@@ -36,7 +36,7 @@ import {ccclass} from '../core/data/class-decorator';
* @private
*/
@ccclass('cc.Script')
-class Script extends Asset {
+export class Script extends Asset {
}
cc._Script = Script;
@@ -62,4 +62,4 @@ cc._JavaScript = JavaScript;
@ccclass('cc.TypeScript')
export class TypeScript extends Script {
}
-cc._TypeScript = TypeScript;
\ No newline at end of file
+cc._TypeScript = TypeScript;
diff --git a/cocos/assets/CCSpriteAtlas.js b/cocos/assets/CCSpriteAtlas.js
index 85667e295f..e8ed5d5220 100644
--- a/cocos/assets/CCSpriteAtlas.js
+++ b/cocos/assets/CCSpriteAtlas.js
@@ -24,7 +24,7 @@
THE SOFTWARE.
****************************************************************************/
-import Asset from './CCAsset';
+import { Asset } from './asset';
import {ccclass, property} from '../core/data/class-decorator';
/**
@@ -64,7 +64,7 @@ export default class SpriteAtlas extends Asset {
let sf = this._spriteFrames[key];
if (!sf) {
return null;
- }
+ }
if (!sf.name) {
sf.name = key;
}
@@ -88,4 +88,4 @@ export default class SpriteAtlas extends Asset {
}
}
-cc.SpriteAtlas = SpriteAtlas;
\ No newline at end of file
+cc.SpriteAtlas = SpriteAtlas;
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 6d28070663..2000d6a05c 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 { 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 { Texture2D } from './texture-2d';
import textureUtil from './texture-util';
-import {addon} from '../core/utils/js';
-import Asset from './CCAsset';
-import {ccclass, property} from '../core/data/class-decorator';
-
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}];
+export 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,39 @@ export default class SpriteFrame extends Asset {
}
set insetRight (value) {
this._capInsets[INSET_RIGHT] = value;
- if (this._texture) {
- this._calculateSlicedUV();
- }
+ // if (this._texture) {
+ this._calculateSlicedUV();
+ // }
}
+ get atlasUuid () {
+ return this._atlasUuid;
+ }
+
+ 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 +223,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] = 0;
+ this._capInsets[INSET_TOP] = 0;
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 +311,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 +354,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 +364,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 +398,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 +482,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 +565,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 +585,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 +619,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 +634,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 +649,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 +679,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 +693,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 +712,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,19 +732,36 @@ 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);
-cc.SpriteFrame = SpriteFrame;
\ No newline at end of file
+cc.SpriteFrame = SpriteFrame;
diff --git a/cocos/assets/CCTextAsset.js b/cocos/assets/CCTextAsset.js
index 904afcdad4..5d99e80bcb 100644
--- a/cocos/assets/CCTextAsset.js
+++ b/cocos/assets/CCTextAsset.js
@@ -24,7 +24,7 @@
THE SOFTWARE.
****************************************************************************/
-import Asset from './CCAsset';
+import { Asset } from './asset';
import {ccclass, property} from '../core/data/class-decorator';
/**
@@ -54,4 +54,4 @@ export default class TextAsset extends Asset {
}
}
-cc.TextAsset = TextAsset;
\ No newline at end of file
+cc.TextAsset = TextAsset;
diff --git a/cocos/assets/asset.d.ts b/cocos/assets/asset.d.ts
new file mode 100644
index 0000000000..9055813b31
--- /dev/null
+++ b/cocos/assets/asset.d.ts
@@ -0,0 +1,43 @@
+/****************************************************************************
+ 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 { RawAsset } from "./raw-asset";
+
+export class Asset extends RawAsset {
+ protected _native: string;
+ protected loaded: boolean;
+
+ public _nativeAsset: any;
+ public nativeUrl: string;
+
+ static preventDeferredLoadDependents: boolean;
+ static preventPreloadNativeObject: boolean;
+ static deserialize(data: string): object;
+
+ public createNode: (err: string, node: object) => void | null;
+ public toString(): string;
+ public serialize(): string;
+ protected _setRawAsset(filename: string, inLibrary: boolean): void;
+}
diff --git a/cocos/assets/CCAsset.js b/cocos/assets/asset.js
similarity index 98%
rename from cocos/assets/CCAsset.js
rename to cocos/assets/asset.js
index cc051ced5e..050dcdfabc 100644
--- a/cocos/assets/CCAsset.js
+++ b/cocos/assets/asset.js
@@ -25,7 +25,7 @@
****************************************************************************/
import { ccclass, property } from '../core/data/class-decorator';
-import RawAsset from './CCRawAsset';
+import { RawAsset } from './raw-asset';
/**
* !#en
@@ -49,7 +49,7 @@ import RawAsset from './CCRawAsset';
* @extends RawAsset
*/
@ccclass('cc.Asset')
-export default class Asset extends RawAsset {
+export class Asset extends RawAsset {
constructor () {
super();
/**
@@ -221,4 +221,4 @@ export default class Asset extends RawAsset {
*/
Asset.prototype.createNode = null;
-cc.Asset = Asset;
\ No newline at end of file
+cc.Asset = Asset;
diff --git a/cocos/assets/image-asset.js b/cocos/assets/image-asset.js
deleted file mode 100644
index 9644ebed06..0000000000
--- a/cocos/assets/image-asset.js
+++ /dev/null
@@ -1,243 +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.
- ****************************************************************************/
-//@ts-check
-import {ccclass, property} from "../core/data/class-decorator";
-import EventTarget from '../core/event/event-target';
-import {addon} from '../core/utils/js';
-
-/**
- * @typedef {{ _data: ArrayBufferView, _compressed: boolean, width: number, height: number, format: number}} RawImageData
- */
-
-const CHAR_CODE_0 = 48; // '0'
-
-/**
- * Class ImageAsset.
- */
-@ccclass('cc.ImageAsset')
-export default class ImageAsset extends cc.Asset {
-
- static extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.etc'];
-
- /**
- * @param {HTMLCanvasElement | HTMLImageElement | RawImageData} nativeAsset
- */
- constructor(nativeAsset = undefined) {
- super();
- EventTarget.call(this);
-
- /**
- * !#en
- * The url of the texture, this could be empty if the texture wasn't created via a file.
- * !#zh
- * 图像文件的 url,当图像不是由文件创建时值可能为空
- * @property url
- * @type {String}
- * @readonly
- */
- // TODO - use nativeUrl directly
- this.url = "";
-
- /**
- * @type {HTMLCanvasElement | HTMLImageElement | RawImageData}
- */
- this._nativeData = {
- _data: null,
- width: 0,
- height: 0,
- format: 0,
- _compressed: false
- };
-
- if (CC_EDITOR) {
- this._exportedExts = null;
- }
-
- if (nativeAsset !== undefined) {
- this._nativeAsset = nativeAsset;
- }
- }
-
- /**
- * @type {HTMLCanvasElement | HTMLImageElement | RawImageData}
- */
- @property({
- override: true
- })
- get _nativeAsset () {
- // maybe returned to pool in webgl
- return this._nativeData;
- }
-
- /**
- * @param {HTMLCanvasElement | HTMLImageElement | RawImageData} value
- */
- set _nativeAsset (value) {
- this.reset(value);
- }
-
- /**
- * @type {HTMLCanvasElement | HTMLImageElement | ArrayBufferView}
- */
- get data() {
- return this._nativeData instanceof HTMLElement ? this._nativeData : this._nativeData._data;
- }
-
- /**
- * @param {HTMLCanvasElement | HTMLImageElement | RawImageData} data
- */
- reset(data) {
- if (!(data instanceof HTMLElement)) {
- this._nativeData = Object.create(data);
- this._onDataComplete();
- } else {
- this._nativeData = data;
- if (CC_WECHATGAME || CC_QQPLAY || data.complete || data instanceof HTMLCanvasElement) {
- this._onDataComplete();
- } else {
- this.loaded = false;
- data.addEventListener('load', () => {
- this._onDataComplete();
- });
- data.addEventListener('error', (err) => {
- cc.warnID(3119, err.message);
- });
- }
- }
- }
-
- get width() {
- return this._nativeData.width;
- }
-
- get height() {
- return this._nativeData.height;
- }
-
- get format() {
- if (this._nativeData instanceof HTMLElement) {
- return undefined;
- }
- return this._nativeData.format;
- }
-
- // destroy() {
- // if (cc.macro.CLEANUP_IMAGE_CACHE) {
- // if (this._data instanceof HTMLImageElement) {
- // this._data.src = "";
- // cc.loader.removeItem(this._data.id);
- // }
- // }
- // }
-
- // SERIALIZATION
-
- _serialize () {
- let extId = "";
- let exportedExts = this._exportedExts;
- if (!exportedExts && this._native) {
- exportedExts = [this._native];
- }
- if (exportedExts) {
- let exts = [];
- for (let i = 0; i < exportedExts.length; i++) {
- let extId = "";
- let ext = exportedExts[i];
- if (ext) {
- // ext@format
- let extFormat = ext.split('@');
- extId = ImageAsset.extnames.indexOf(extFormat[0]);
- if (extId < 0) {
- extId = ext;
- }
- if (extFormat[1]) {
- extId += '@' + extFormat[1];
- }
- }
- exts.push(extId);
- }
- extId = exts.join('_');
- }
- return "" + extId;
- }
-
- _deserialize (data, handle) {
- let fields = data.split(',');
- // decode extname
- var extIdStr = fields[0];
- if (extIdStr) {
- let extIds = extIdStr.split('_');
-
- let extId = 999;
- let ext = '';
- let format = this._format;
- let SupportTextureFormats = cc.macro.SUPPORT_TEXTURE_FORMATS;
- for (let i = 0; i < extIds.length; i++) {
- let extFormat = extIds[i].split('@');
- let tmpExt = extFormat[0];
- tmpExt = tmpExt.charCodeAt(0) - CHAR_CODE_0;
- tmpExt = ImageAsset.extnames[tmpExt] || extFormat;
-
- let index = SupportTextureFormats.indexOf(tmpExt);
- if (index !== -1 && index < extId) {
- extId = index;
- ext = tmpExt;
- format = extFormat[1] ? parseInt(extFormat[1]) : this._format;
- }
- }
-
- if (ext) {
- this._setRawAsset(ext);
- this._format = format;
- }
-
- // preset uuid to get correct nativeUrl
- let loadingItem = handle.customEnv;
- let uuid = loadingItem && loadingItem.uuid;
- if (uuid) {
- this._uuid = uuid;
- var url = this.nativeUrl;
- this.url = url;
- }
- }
- }
-
- _onDataComplete() {
- this.loaded = true;
- this.emit("load");
- }
-}
-
-/**
- * !#zh
- * 当该资源加载成功后触发该事件
- * !#en
- * This event is emitted when the asset is loaded
- *
- * @event load
- */
-addon(ImageAsset.prototype, EventTarget.prototype);
-
-cc.ImageAsset = ImageAsset;
\ No newline at end of file
diff --git a/cocos/assets/image-asset.ts b/cocos/assets/image-asset.ts
new file mode 100644
index 0000000000..708fc1c0ed
--- /dev/null
+++ b/cocos/assets/image-asset.ts
@@ -0,0 +1,231 @@
+/****************************************************************************
+ 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 {ccclass, property} from '../core/data/class-decorator';
+import EventTarget from '../core/event/event-target';
+import {addon} from '../core/utils/js';
+import { Asset } from './asset';
+
+export interface IMemoryImageSource {
+ _data: ArrayBufferView | null;
+ _compressed: boolean;
+ width: number;
+ height: number;
+ format: number;
+}
+
+export type ImageSource = HTMLCanvasElement | HTMLImageElement | IMemoryImageSource;
+
+/**
+ * Class ImageAsset.
+ */
+@ccclass('cc.ImageAsset')
+export class ImageAsset extends Asset {
+
+ @property({override: true})
+ get _nativeAsset () {
+ // Maybe returned to pool in webgl.
+ return this._nativeData;
+ }
+
+ set _nativeAsset (value: ImageSource) {
+ this.reset(value);
+ }
+
+ get data () {
+ return this._nativeData instanceof HTMLElement ? this._nativeData : this._nativeData._data;
+ }
+
+ get width () {
+ return this._nativeData.width;
+ }
+
+ get height () {
+ return this._nativeData.height;
+ }
+
+ get format () {
+ if (this._nativeData instanceof HTMLElement) {
+ return undefined;
+ }
+ return this._nativeData.format;
+ }
+
+ /**
+ * !#en
+ * The url of the texture, this could be empty if the texture wasn't created via a file.
+ * !#zh
+ * 图像文件的 url,当图像不是由文件创建时值可能为空
+ */
+ // TODO - use nativeUrl directly
+ get url () {
+ return this._url;
+ }
+
+ private static extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.etc'];
+
+ private _nativeData: ImageSource;
+
+ private _url: string;
+
+ private _exportedExts: string[] | null | undefined = undefined;
+
+ private _format: string = '';
+
+ /**
+ * @param nativeAsset
+ */
+ constructor (nativeAsset?: ImageSource) {
+ super();
+ // @ts-ignore
+ EventTarget.call(this);
+
+ this._url = '';
+
+ this._nativeData = {
+ _data: null,
+ width: 0,
+ height: 0,
+ format: 0,
+ _compressed: false,
+ };
+
+ if (CC_EDITOR) {
+ this._exportedExts = null;
+ }
+
+ if (nativeAsset !== undefined) {
+ this._nativeAsset = nativeAsset;
+ }
+ }
+
+ public reset (data: ImageSource) {
+ if (!(data instanceof HTMLElement)) {
+ this._nativeData = Object.create(data);
+ this._onDataComplete();
+ } else {
+ this._nativeData = data;
+ if (CC_WECHATGAME || CC_QQPLAY || (data as any).complete || data instanceof HTMLCanvasElement) {
+ this._onDataComplete();
+ } else {
+ this.loaded = false;
+ data.addEventListener('load', () => {
+ this._onDataComplete();
+ });
+ data.addEventListener('error', (err) => {
+ cc.warnID(3119, err.message);
+ });
+ }
+ }
+ }
+
+ // destroy() {
+ // if (cc.macro.CLEANUP_IMAGE_CACHE) {
+ // if (this._data instanceof HTMLImageElement) {
+ // this._data.src = "";
+ // cc.loader.removeItem(this._data.id);
+ // }
+ // }
+ // }
+
+ // SERIALIZATION
+
+ public _serialize () {
+ let targetExtensions = this._exportedExts;
+ if (!targetExtensions && this._native) {
+ targetExtensions = [this._native];
+ }
+
+ if (!targetExtensions) {
+ return '';
+ }
+
+ const extensionIndices: string[] = [];
+ for (const targetExtension of targetExtensions) {
+ const extensionFormat = targetExtension.split('@');
+ const i = ImageAsset.extnames.indexOf(extensionFormat[0]);
+ let exportedExtensionID = i < 0 ? targetExtension : `${i}`;
+ if (extensionFormat[1]) {
+ exportedExtensionID += '@' + extensionFormat[1];
+ }
+ extensionIndices.push(exportedExtensionID);
+ }
+ return extensionIndices.join('_');
+ }
+
+ public _deserialize (data: string, handle: any) {
+ const extensionIDs = data.split('_');
+
+ let preferedExtensionIndex = Number.MAX_VALUE;
+ let format = this._format;
+ let ext = '';
+ const SupportTextureFormats = cc.macro.SUPPORT_TEXTURE_FORMATS as string[];
+ for (const extensionID of extensionIDs) {
+ const extFormat = extensionID.split('@');
+
+ const i = parseInt(extFormat[0], undefined);
+ const tmpExt = ImageAsset.extnames[i] || extFormat.join();
+
+ const index = SupportTextureFormats.indexOf(tmpExt);
+ if (index !== -1 && index < preferedExtensionIndex) {
+ preferedExtensionIndex = index;
+ ext = tmpExt;
+ format = extFormat[1] ? extFormat[1] : this._format;
+ }
+ }
+
+ if (ext) {
+ // @ts-ignore
+ this._setRawAsset(ext);
+ this._format = format;
+ }
+
+ // preset uuid to get correct nativeUrl
+ const loadingItem = handle.customEnv;
+ const uuid = loadingItem && loadingItem.uuid;
+ if (uuid) {
+ this._uuid = uuid;
+ this._url = this.nativeUrl;
+ }
+ }
+
+ public _onDataComplete () {
+ this.loaded = true;
+ // @ts-ignore
+ this.emit('load');
+ }
+}
+
+/**
+ * !#zh
+ * 当该资源加载成功后触发该事件
+ * !#en
+ * This event is emitted when the asset is loaded
+ *
+ * @event load
+ */
+addon(ImageAsset.prototype, EventTarget.prototype);
+
+cc.ImageAsset = ImageAsset;
diff --git a/cocos/assets/index.js b/cocos/assets/index.js
index b39587bccc..fd95924b0c 100644
--- a/cocos/assets/index.js
+++ b/cocos/assets/index.js
@@ -24,18 +24,18 @@
THE SOFTWARE.
****************************************************************************/
-export {default as RawAsset} from './CCRawAsset';
-export {default as Asset} from './CCAsset';
+export { RawAsset } from './raw-asset';
+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';
export {default as GLTFAsset} from './CCGLTFAsset';
export {default as BufferAsset} from './CCBufferAsset';
export {default as AssetLibrary} from './CCAssetLibrary';
-export {default as ImageAsset} from './image-asset';
-export {default as Texture2D} from './texture-2d';
-export {default as RenderTexture} from './render-texture';
+export { ImageAsset } from './image-asset';
+export { Texture2D } from './texture-2d';
+export { RenderTexture } from './render-texture';
diff --git a/cocos/3d/assets/utils/buffer-range.js b/cocos/assets/raw-asset.d.ts
similarity index 70%
rename from cocos/3d/assets/utils/buffer-range.js
rename to cocos/assets/raw-asset.d.ts
index bbd720b2df..a7d7b2e319 100644
--- a/cocos/3d/assets/utils/buffer-range.js
+++ b/cocos/assets/raw-asset.d.ts
@@ -1,4 +1,5 @@
/****************************************************************************
+ Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
@@ -23,33 +24,10 @@
THE SOFTWARE.
****************************************************************************/
-// @ts-check
-import { _decorator } from "../../../core/data";
-const { ccclass, property } = _decorator;
+import { CCObject } from '../core/data/object';
-/**
- * The class BufferRange denotes a range of the buffer.
- */
-@ccclass("cc.BufferRange")
-export default class BufferRange {
- /**
- * The offset of the range.
- * @type {Number}
- */
- @property(Number)
- _offset = 0;
-
- /**
- * The length of the range, in bytes.
- * @type {Number}
- */
- @property(Number)
- _length = 0;
-
- constructor(offset, length) {
- this._offset = offset;
- this._length = length;
- }
+export class RawAsset extends CCObject {
+ _uuid: string;
+ public constructor();
+ static isRawAssetType(ctor: Function): boolean;
}
-
-cc.BufferRange = BufferRange;
\ No newline at end of file
diff --git a/cocos/assets/CCRawAsset.js b/cocos/assets/raw-asset.js
similarity index 91%
rename from cocos/assets/CCRawAsset.js
rename to cocos/assets/raw-asset.js
index d433c0c493..52b902900a 100644
--- a/cocos/assets/CCRawAsset.js
+++ b/cocos/assets/raw-asset.js
@@ -24,9 +24,9 @@
THE SOFTWARE.
****************************************************************************/
-import {isChildClassOf} from '../core/utils/js';
-import CCObject from '../core/data/object';
-import {ccclass} from '../core/data/class-decorator';
+import { isChildClassOf } from '../core/utils/js';
+import { CCObject } from '../core/data/object';
+import { ccclass } from '../core/data/class-decorator';
/**
* !#en
@@ -38,7 +38,7 @@ import {ccclass} from '../core/data/class-decorator';
* @extends Object
*/
@ccclass('cc.RawAsset')
-export default class RawAsset extends CCObject {
+export class RawAsset extends CCObject {
constructor () {
super();
/**
diff --git a/cocos/assets/render-texture.js b/cocos/assets/render-texture.js
deleted file mode 100644
index 5b3302620f..0000000000
--- a/cocos/assets/render-texture.js
+++ /dev/null
@@ -1,135 +0,0 @@
-import gfx from '../renderer/gfx';
-import Texture2D from './texture-2d';
-import { ccclass } from '../core/data/class-decorator';
-
-/**
- * Render textures are textures that can be rendered to.
- * @class RenderTexture
- * @extends Texture2D
- */
-@ccclass('cc.RenderTexture')
-export default class RenderTexture extends Texture2D {
-
- constructor () {
- super();
- this._framebuffer = null;
- }
-
- /**
- * !#en
- * Init the render texture with size.
- * !#zh
- * 初始化 render texture
- * @param {Number} [width]
- * @param {Number} [height]
- * @param {Number} [depthStencilFormat]
- * @method initWithSize
- */
- initWithSize (width, height, depthStencilFormat) {
- this.width = Math.floor(width || cc.visibleRect.width);
- this.height = Math.floor(height || cc.visibleRect.height);
- this._resetUnderlyingMipmaps();
-
- let opts = {
- colors: [ this._texture ],
- };
- if (depthStencilFormat) {
- if (this.depthStencilBuffer) this.depthStencilBuffer.destroy();
- let depthStencilBuffer = new gfx.RenderBuffer(cc.game._renderContext, depthStencilFormat, this.width, this.height);
- if (depthStencilFormat === gfx.RB_FMT_D24S8) {
- opts.depthStencil = depthStencilBuffer;
- }
- else if (depthStencilFormat === gfx.RB_FMT_S8) {
- opts.stencil = depthStencilBuffer;
- }
- else if (depthStencilFormat === gfx.RB_FMT_D16) {
- opts.depth = depthStencilBuffer;
- }
- this.depthStencilBuffer = depthStencilBuffer;
- this.depthStencilFormat = depthStencilFormat;
- }
-
- if (this._framebuffer) this._framebuffer.destroy();
- this._framebuffer = new gfx.FrameBuffer(cc.game._renderContext, this.width, this.height, opts);
-
- this.loaded = true;
- this.emit("load");
- }
-
- updateSize(width, height) {
- this.width = Math.floor(width || cc.visibleRect.width);
- this.height = Math.floor(height || cc.visibleRect.height);
- this._resetUnderlyingMipmaps();
-
- let rbo = this.depthStencilBuffer;
- if (rbo) rbo.update(this.width, this.height);
- this._framebuffer._width = width;
- this._framebuffer._height = height;
- }
-
- /**
- * !#en Draw a texture to the specified position
- * !#zh 将指定的图片渲染到指定的位置上
- * @param {Texture2D} texture
- * @param {Number} x
- * @param {Number} y
- */
- drawTextureAt (texture, x, y) {
- if (!texture._image) return;
-
- this._texture.updateSubImage({
- x, y,
- image: texture._image,
- width: texture.width,
- height: texture.height,
- level: 0,
- flipY: false,
- premultiplyAlpha: texture._premultiplyAlpha
- })
- }
-
- /**
- * !#en
- * Get pixels from render texture, the pixels data stores in a RGBA Uint8Array.
- * It will return a new (width * height * 4) length Uint8Array by default。
- * You can specify a data to store the pixels to reuse the data,
- * you and can specify other params to specify the texture region to read.
- * !#zh
- * 从 render texture 读取像素数据,数据类型为 RGBA 格式的 Uint8Array 数组。
- * 默认每次调用此函数会生成一个大小为 (长 x 高 x 4) 的 Uint8Array。
- * 你可以通过传入 data 来接收像素数据,也可以通过传参来指定需要读取的区域的像素。
- * @method readPixels
- * @param {Uint8Array} [data]
- * @param {Number} [x]
- * @param {Number} [y]
- * @param {Number} [w]
- * @param {Number} [h]
- * @return {Uint8Array}
- */
- readPixels (data, x, y, w, h) {
- if (!this._framebuffer || !this._texture) return data;
-
- x = x || 0;
- y = y || 0;
- let width = w || this.width;
- let height = h || this.height;
- data = data || new Uint8Array(width * height * 4);
-
- let gl = cc.game._renderContext._gl;
- let oldFBO = gl.getParameter(gl.FRAMEBUFFER_BINDING);
- gl.bindFramebuffer(gl.FRAMEBUFFER, this._framebuffer._glID);
- gl.readPixels(x, y, width, height, gl.RGBA, gl.UNSIGNED_BYTE, data);
- gl.bindFramebuffer(gl.FRAMEBUFFER, oldFBO);
-
- return data;
- }
-
- destroy () {
- super.destroy();
- if (this._framebuffer) {
- this._framebuffer.destroy();
- }
- }
-}
-
-cc.RenderTexture = RenderTexture;
diff --git a/cocos/assets/render-texture.ts b/cocos/assets/render-texture.ts
new file mode 100644
index 0000000000..d535942467
--- /dev/null
+++ b/cocos/assets/render-texture.ts
@@ -0,0 +1,215 @@
+import { ccclass } from '../core/data/class-decorator';
+import { IRect2D, normalizeRect2D } from '../core/vmath/rect';
+import { GFXFormat, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../gfx/define';
+import { GFXFramebuffer } from '../gfx/framebuffer';
+import { GFXTexture } from '../gfx/texture';
+import { GFXTextureView } from '../gfx/texture-view';
+import { RenderPassStage } from '../pipeline/define';
+import { ImageAsset } from './image-asset';
+import { Texture2D } from './texture-2d';
+
+type DSFormat = 'D24S8' | 'S8' | 'D16';
+const _formatMap = {
+ D24S8: GFXFormat.D24S8,
+ S8: GFXFormat.R8UI,
+ D16: GFXFormat.D16,
+};
+
+/**
+ * Render textures are textures that can be rendered to.
+ * @class RenderTexture
+ * @extends Texture2D
+ */
+@ccclass('cc.RenderTexture')
+export class RenderTexture extends Texture2D {
+ private _framebuffer: GFXFramebuffer | null = null;
+
+ private _depthStencilTexture: GFXTexture | null = null;
+
+ private _depthStencilTextureView: GFXTextureView | null = null;
+
+ constructor () {
+ super();
+ }
+
+ /**
+ * !#en
+ * Init the render texture with size.
+ * !#zh
+ * 初始化 render texture
+ * @param [width]
+ * @param [height]
+ * @param [string]
+ * @method initWithSize
+ */
+ public initWithSize (width?: number, height?: number, format?: DSFormat) {
+ this.destroy();
+
+ const gfxDevice = this._getGlobalDevice();
+ if (!gfxDevice) {
+ return;
+ }
+
+ const w = Math.floor(width || cc.visibleRect.width);
+ const h = Math.floor(height || cc.visibleRect.height);
+ const image = new ImageAsset({
+ width: w,
+ height: h,
+ format: GFXFormat.RGBA8UI,
+ _data: new Uint8Array(w * h * 4),
+ _compressed: false,
+ });
+
+ this.image = image;
+
+ if (!this._texture) {
+ return;
+ }
+
+ const colorView = gfxDevice.createTextureView({
+ texture: this._texture,
+ type: GFXTextureViewType.TV2D,
+ format: this._getGfxFormat(),
+ });
+
+ if (!colorView) {
+ return;
+ }
+
+ if (format !== undefined) {
+ this._depthStencilTexture = gfxDevice.createTexture({
+ type: GFXTextureType.TEX2D,
+ usage: GFXTextureUsageBit.DEPTH_STENCIL_ATTACHMENT,
+ format: _formatMap[format],
+ width: w,
+ height: h,
+ });
+ if (!this._depthStencilTexture) {
+ return;
+ }
+ this._depthStencilTextureView = gfxDevice.createTextureView({
+ texture: this._depthStencilTexture,
+ type: GFXTextureViewType.TV2D,
+ format: _formatMap[format],
+ });
+ }
+
+ if (this._depthStencilTextureView === null) {
+ return;
+ }
+
+ this._framebuffer = gfxDevice.createFramebuffer({
+ renderPass: cc.director.root.pipeline.getRenderPass(RenderPassStage.DEFAULT),
+ colorViews: [ colorView ],
+ depthStencilView: this._depthStencilTextureView === null ? undefined : this._depthStencilTextureView,
+ isOffscreen: true,
+ });
+
+ this.loaded = true;
+ // @ts-ignore
+ this.emit('load');
+ }
+
+ public destroy () {
+ if (this._framebuffer) {
+ this._framebuffer.destroy();
+ this._framebuffer = null;
+ }
+ if (this._depthStencilTextureView) {
+ this._depthStencilTextureView.destroy();
+ this._depthStencilTextureView = null;
+ }
+ if (this._depthStencilTexture) {
+ this._depthStencilTexture.destroy();
+ this._depthStencilTexture = null;
+ }
+ return super.destroy();
+ }
+
+ // TODO:
+ // public updateSize (width, height) {
+ // this.width = Math.floor(width || cc.visibleRect.width);
+ // this.height = Math.floor(height || cc.visibleRect.height);
+ // this._resetUnderlyingMipmaps();
+
+ // const rbo = this.depthStencilBuffer;
+ // if (rbo) { rbo.update(this.width, this.height); }
+ // this._framebuffer._width = width;
+ // this._framebuffer._height = height;
+ // }
+
+ /**
+ * !#en Draw a texture to the specified position
+ * !#zh 将指定的图片渲染到指定的位置上
+ * @param texture
+ * @param x
+ * @param y
+ */
+ public drawTextureAt (texture: Texture2D, x: number, y: number) {
+ if (!this._texture) {
+ return;
+ }
+
+ const image = texture.image;
+
+ if (!image) {
+ return;
+ }
+
+ this._assignImage(image, 0);
+ }
+
+ /**
+ * !#en
+ * Get pixels from render texture, the pixels data stores in a RGBA Uint8Array.
+ * It will return a new (width * height * 4) length Uint8Array by default。
+ * You can specify a data to store the pixels to reuse the data,
+ * you and can specify other params to specify the texture region to read.
+ * !#zh
+ * 从 render texture 读取像素数据,数据类型为 RGBA 格式的 Uint8Array 数组。
+ * 默认每次调用此函数会生成一个大小为 (长 x 高 x 4) 的 Uint8Array。
+ * 你可以通过传入 data 来接收像素数据,也可以通过传参来指定需要读取的区域的像素。
+ * @param [data]
+ * @param [rect]
+ */
+ public readPixels (data?: Uint8Array, rect: IRect2D = {}) {
+ if (!this._framebuffer || !this._texture) {
+ return undefined;
+ }
+
+ const gfxDevice = this._getGlobalDevice();
+ if (!gfxDevice) {
+ return;
+ }
+
+ const normalizedRect = normalizeRect2D(rect, this.width, this.height);
+
+ data = data || new Uint8Array(normalizedRect.width * normalizedRect.height * 4);
+
+ gfxDevice.copyFramebufferToBuffer(this._framebuffer, data.buffer, [{
+ buffOffset: 0,
+ buffStride: 0,
+ buffTexHeight: 0,
+ texOffset: {
+ x: normalizedRect.x,
+ y: normalizedRect.y,
+ z: 0,
+ },
+ texExtent: {
+ width: normalizedRect.width,
+ height: normalizedRect.height,
+ depth: 1,
+ },
+ texSubres: {
+ baseMipLevel: 0,
+ levelCount: 1,
+ baseArrayLayer: 0,
+ layerCount: 1,
+ },
+ }]);
+
+ return data;
+ }
+}
+
+cc.RenderTexture = RenderTexture;
diff --git a/cocos/assets/texture-2d.js b/cocos/assets/texture-2d.js
deleted file mode 100644
index 544984835b..0000000000
--- a/cocos/assets/texture-2d.js
+++ /dev/null
@@ -1,327 +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.
- ****************************************************************************/
-// @ts-check
-import GFXTexture2D from '../renderer/gfx/texture-2d';
-import {ccclass, property} from '../core/data/class-decorator';
-import TextureBase from './texture-base';
-import ImageAsset from './image-asset';
-
-/**
- * @typedef {import("./texture-base").ImageSource} ImageSource
- * @typedef {import("./texture-base").TextureUpdateOpts} TextureUpdateOpts
- */
-
-/**
- *
- * This class allows to easily create OpenGL or Canvas 2D textures from images, text or raw data.
- * The created cc.Texture2D object will always have power-of-two dimensions.
- * Depending on how you create the cc.Texture2D object, the actual image area of the texture might be smaller than the texture dimensions
- * i.e. "contentSize" != (pixelsWide, pixelsHigh) and (maxS, maxT) != (1.0, 1.0).
- * Be aware that the content of the generated textures will be upside-down!
-
- * @class Texture2D
- * @extends TextureBase
- */
-@ccclass('cc.Texture2D')
-export default class Texture2D extends TextureBase {
- @property({
- override: true
- })
- _flipY = true;
-
- /**
- * @type {ImageAsset[]}
- */
- @property([ImageAsset])
- _mipmaps = [];
-
- constructor () {
- super();
-
- /**
- * @type {GFXTexture2D}
- */
- this._texture = null;
- }
-
- /**
- * Gets the mipmap images.
- * Note that the result do not contains the auto generated mipmaps.
- * @return {ImageAsset[]}
- */
- get mipmaps() {
- return this._mipmaps;
- }
-
- /**
- * Sets the mipmaps images.
- * @param {ImageAsset[]} value
- */
- set mipmaps(value) {
- this._setMipmaps(value);
- }
-
- /**
- * Gets the mipmap image at level 0.
- * @return {ImageAsset}
- */
- get image() {
- return this._mipmaps.length === 0 ? null : this._mipmaps[0];
- }
-
- /**
- * Sets the mipmap images as a single mipmap image.
- * @param {ImageAsset} value
- */
- set image(value) {
- this.mipmaps = [value];
- }
-
- /**
- * Gets the underlying texture object.
- */
- getImpl () {
- return this._texture;
- }
-
- /**
- * Returns the string representation of this texture.
- */
- toString () {
- return this._mipmaps.length !== 0 ? this._mipmaps[0].url : "";
- }
-
- /**
- * Update texture options, not available in Canvas render mode.
- * image, format, premultiplyAlpha can not be updated in native.
- * @method update
- * @param {TextureUpdateOpts} options
- */
- update (options) {
- if (!options) {
- return;
- }
-
- super.update(options);
-
- if (options.image) {
- options.images = [options.image];
- }
-
- if (options.images !== undefined && options.images.length !== 0) {
- this._setMipmaps(options.images.map(image => {
- const mipmap = new ImageAsset();
- mipmap.reset(image instanceof HTMLElement ? image : {
- _data: image,
- width: this.width,
- height: this.height,
- format: this._format,
- _compressed: false
- });
- return mipmap;
- }));
- }
-
- if (this._texture) {
- this._texture.update(options);
- }
- }
-
- /**
- *
- * @param {ImageSource} source
- */
- updateImage(source) {
- this.updateMipmaps([source]);
- }
-
- /**
- * Updates mipmaps at specified range of levels.
- * @param {ImageSource[]} sources The image sources.
- * @param {number} firstLevel The first level from which the sources update.
- * @description
- * If the range specified by [firstLevel, firstLevel + sources.length) exceeds
- * the actually range of mipmaps this texture contains, only overlaped mipmaps are updated.
- */
- updateMipmaps(sources, firstLevel = 0) {
- if (firstLevel >= sources.length) {
- return;
- }
-
- const nUpdate = Math.min(sources.length, this._mipmaps.length - firstLevel);
- for (let i = 0; i < nUpdate; ++i) {
- const level = firstLevel + i;
- const mipmap = this._mipmaps[level];
- const source = sources[i];
- mipmap.reset(source instanceof HTMLElement ? source : {
- _data: source,
- width: mipmap.width,
- height: mipmap.height,
- format: mipmap._format,
- _compressed: false
- });
- this._texture.updateImage({
- width: this.width,
- height: this.height,
- level: level,
- image: sources[i],
- flipY: false,
- premultiplyAlpha: false
- });
- }
- }
-
- /**
- * !#en
- * HTMLElement Object getter, available only on web.
- * !#zh 获取当前贴图对应的 HTML Image 或 Canvas 对象,只在 Web 平台下有效。
- * @method getHtmlElementObj
- * @return {HTMLImageElement|HTMLCanvasElement}
- * @deprecated Use this.image.data instead.
- */
- getHtmlElementObj () {
- return (this._mipmaps[0] && (this._mipmaps[0].data instanceof HTMLElement)) ? this._mipmaps[0].data: null;
- }
-
- /**
- * !#en
- * Destory this texture and immediately release its video memory. (Inherit from cc.Object.destroy)
- * After destroy, this object is not usable any more.
- * You can use cc.isValid(obj) to check whether the object is destroyed before accessing it.
- * !#zh
- * 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)
- * 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。
- * @method destroy
- * @return {Boolean} inherit from the CCObject
- */
- destroy () {
- this.releaseTexture();
- // TODO cc.textureUtil ?
- // cc.textureCache.removeTextureForKey(this.url); // item.rawUrl || item.url
- return super.destroy();
- }
-
- /**
- * !#en
- * Description of cc.Texture2D.
- * !#zh cc.Texture2D 描述。
- * @method description
- * @returns {String}
- */
- description () {
- return "";
- }
-
- /**
- * !#en
- * Release texture, please use destroy instead.
- * !#zh 释放纹理,请使用 destroy 替代。
- * @method releaseTexture
- * @deprecated since v2.0, use destroy instead.
- */
- releaseTexture () {
- this._setMipmaps([]);
- this._texture && this._texture.destroy();
- }
-
- /**
- * Sets the _mipmaps to specified value, and updates the width and height accordingly.
- * If available, synchronize the mipmap data to underlying texture.
- * @param {ImageAsset[]} mipmaps
- */
- _setMipmaps(mipmaps) {
- this._mipmaps = mipmaps;
- if (mipmaps.length === 0) {
- super.update({
- width: 0,
- height: 0
- });
- } else {
- const level0 = this._mipmaps[0];
- super.update({
- width: level0.width,
- height: level0.height,
- format: level0._format
- });
- }
-
- let counter = 0;
- const inc = () => {
- ++counter;
- if (counter === mipmaps.length) {
- this._resetUnderlyingMipmaps(mipmaps.map(mipmap => mipmap.data));
- }
- };
- mipmaps.forEach(mipmap => {
- if (mipmap.loaded) {
- inc();
- } else {
- mipmap.addEventListener("load", () => {
- inc();
- });
- }
- });
- }
-
- /**
- * Resets sources and amount of the underlying texture's the mipmaps.
- * @param {ImageSource[]} mipmapSources
- */
- _resetUnderlyingMipmaps(mipmapSources = [null]) {
- const opts = this._getOpts();
- opts.images = mipmapSources;
- if (!this._texture) {
- this._texture = new GFXTexture2D(cc.game._renderContext, opts);
- } else {
- this._texture.update(opts);
- }
- }
-
- _serialize() {
- return {
- base: super._serialize(),
- mipmaps: this._mipmaps.map(mipmap => mipmap._uuid)
- };
- }
-
- _deserialize (data, handle) {
- super._deserialize(data.base);
-
- this._mipmaps = new Array(data.mipmaps.length);
- for (let i = 0; i < data.mipmaps.length; ++i) {
- // Prevent resource load failed
- this._mipmaps[i] = new ImageAsset();
- const mipmapUUID = data.mipmaps[i];
- handle.result.push(this._mipmaps, `${i}`, mipmapUUID);
- }
- }
-
- onLoaded() {
- this.mipmaps = this._mipmaps;
- }
-}
-
-cc.Texture2D = Texture2D;
diff --git a/cocos/assets/texture-2d.ts b/cocos/assets/texture-2d.ts
new file mode 100644
index 0000000000..d5a5afd186
--- /dev/null
+++ b/cocos/assets/texture-2d.ts
@@ -0,0 +1,194 @@
+/****************************************************************************
+ 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 { ccclass, property } from '../core/data/class-decorator';
+import { ImageAsset, ImageSource } from './image-asset';
+import { TextureBase } from './texture-base';
+
+/**
+ * Represents a 2-dimension texture.
+ */
+@ccclass('cc.Texture2D')
+export class Texture2D extends TextureBase {
+ /**
+ * Gets the mipmap images.
+ * Note that the result do not contains the auto generated mipmaps.
+ */
+ get mipmaps () {
+ return this._mipmaps;
+ }
+
+ /**
+ * Sets the mipmaps images.
+ */
+ set mipmaps (value) {
+ this._mipmaps = value;
+ this.create(
+ value.length === 0 ? 0 : value[0].width,
+ value.length === 0 ? 0 : value[0].height,
+ undefined,
+ this._mipmaps.length);
+ this._mipmaps.forEach((mipmap, level) => {
+ this._assignImage(mipmap, level);
+ });
+ }
+
+ /**
+ * Gets the mipmap image at level 0.
+ */
+ get image () {
+ return this._mipmaps.length === 0 ? null : this._mipmaps[0];
+ }
+
+ /**
+ * Sets the mipmap images as a single mipmap image.
+ */
+ set image (value) {
+ this.mipmaps = value ? [value] : [];
+ }
+
+ @property([ImageAsset])
+ public _mipmaps: ImageAsset[] = [];
+
+ constructor () {
+ super(true);
+ }
+
+ /**
+ * Returns the string representation of this texture.
+ */
+ public toString () {
+ return this._mipmaps.length !== 0 ? this._mipmaps[0].url : '';
+ }
+
+ /**
+ * Updates mipmaps at level 0.
+ */
+ public updateImage () {
+ this.updateMipmaps(0);
+ }
+
+ /**
+ * Updates mipmaps at specified range of levels.
+ * @param firstLevel The first level from which the sources update.
+ * @description
+ * If the range specified by [firstLevel, firstLevel + sources.length) exceeds
+ * the actually range of mipmaps this texture contains, only overlaped mipmaps are updated.
+ * Use this method if your mipmap data are modified.
+ */
+ public updateMipmaps (firstLevel: number = 0, count?: number) {
+ if (firstLevel >= this._mipmaps.length) {
+ return;
+ }
+
+ const nUpdate = Math.min(
+ count === undefined ? this._mipmaps.length : count,
+ this._mipmaps.length - firstLevel);
+
+ for (let i = 0; i < nUpdate; ++i) {
+ const level = firstLevel + i;
+ this._assignImage(this._mipmaps[level], level);
+ }
+ }
+
+ public directUpdate (source: HTMLImageElement | HTMLCanvasElement | ArrayBuffer, level: number = 0) {
+ this._uploadData(source, level);
+ }
+
+ /**
+ * !#en
+ * HTMLElement Object getter, available only on web.
+ * !#zh 获取当前贴图对应的 HTML Image 或 Canvas 对象,只在 Web 平台下有效。
+ * @method getHtmlElementObj
+ * @return {HTMLImageElement|HTMLCanvasElement}
+ * @deprecated Use this.image.data instead.
+ */
+ public getHtmlElementObj () {
+ return (this._mipmaps[0] && (this._mipmaps[0].data instanceof HTMLElement)) ? this._mipmaps[0].data : null;
+ }
+
+ /**
+ * !#en
+ * Destory this texture and immediately release its video memory. (Inherit from cc.Object.destroy)
+ * After destroy, this object is not usable any more.
+ * You can use cc.isValid(obj) to check whether the object is destroyed before accessing it.
+ * !#zh
+ * 销毁该贴图,并立即释放它对应的显存。(继承自 cc.Object.destroy)
+ * 销毁后,该对象不再可用。您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。
+ */
+ public destroy () {
+ this._mipmaps = [];
+ return super.destroy();
+ }
+
+ /**
+ * !#en
+ * Description of cc.Texture2D.
+ * !#zh cc.Texture2D 描述。
+ */
+ public description () {
+ const url = this._mipmaps[0] ? this._mipmaps[0].url : '';
+ return ``;
+ }
+
+ /**
+ * !#en
+ * Release texture, please use destroy instead.
+ * !#zh 释放纹理,请使用 destroy 替代。
+ * @deprecated Since v2.0, use destroy instead.
+ */
+ public releaseTexture () {
+ this.mipmaps = [];
+ }
+
+ public _serialize () {
+ return {
+ base: super._serialize(),
+ mipmaps: this._mipmaps.map((mipmap) => mipmap._uuid),
+ };
+ }
+
+ public _deserialize (serializedData: any, handle: any) {
+ const data = serializedData as ITexture2DSerializeData;
+ super._deserialize(data.base, handle);
+
+ this._mipmaps = new Array(data.mipmaps.length);
+ for (let i = 0; i < data.mipmaps.length; ++i) {
+ // Prevent resource load failed
+ this._mipmaps[i] = new ImageAsset();
+ const mipmapUUID = data.mipmaps[i];
+ handle.result.push(this._mipmaps, `${i}`, mipmapUUID);
+ }
+ }
+}
+
+/* tslint:disable:no-string-literal */
+cc['Texture2D'] = Texture2D;
+
+interface ITexture2DSerializeData {
+ base: string;
+ mipmaps: string[];
+}
diff --git a/cocos/assets/texture-base.js b/cocos/assets/texture-base.js
deleted file mode 100644
index 28fc526f3e..0000000000
--- a/cocos/assets/texture-base.js
+++ /dev/null
@@ -1,602 +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.
- ****************************************************************************/
-// @ts-check
-import EventTarget from '../core/event/event-target';
-import IDGenerator from '../core/utils/id-generator';
-import Enum from '../core/value-types/enum';
-import {addon} from '../core/utils/js';
-import {enums} from '../renderer/gfx/enums';
-import Asset from './CCAsset';
-import {ccclass, property} from '../core/data/class-decorator';
-
-/**
- * @typedef {import("../renderer/gfx/texture-2d").HTMLImageSource} HTMLImageSource
- * @typedef {import("../renderer/gfx/texture-2d").ImageSource} ImageSource
- * @typedef {import("../renderer/gfx/texture-2d").TextureUpdateOpts} TextureUpdateOpts
- *
- * @exports HTMLImageSource
- * @exports ImageSource
- * @exports TextureUpdateOpts
- */
-
-let _images = [];
-
-const CHAR_CODE_1 = 49; // '1'
-
-const GL_NEAREST = 9728; // gl.NEAREST
-const GL_LINEAR = 9729; // gl.LINEAR
-const GL_REPEAT = 10497; // gl.REPEAT
-const GL_CLAMP_TO_EDGE = 33071; // gl.CLAMP_TO_EDGE
-const GL_MIRRORED_REPEAT = 33648; // gl.MIRRORED_REPEAT
-
-var idGenerator = new IDGenerator('Tex');
-
-/**
- * The texture pixel format, default value is RGBA8888,
- * you should note that textures loaded by normal image files (png, jpg) can only support RGBA8888 format,
- * other formats are supported by compressed file types or raw data.
- * @enum {number}
- */
-const PixelFormat = Enum({
- /**
- * 16-bit texture without Alpha channel
- * @property RGB565
- * @readonly
- * @type {Number}
- */
- RGB565: enums.TEXTURE_FMT_R5_G6_B5,
- /**
- * 16-bit textures: RGB5A1
- * @property RGB5A1
- * @readonly
- * @type {Number}
- */
- RGB5A1: enums.TEXTURE_FMT_R5_G5_B5_A1,
- /**
- * 16-bit textures: RGBA4444
- * @property RGBA4444
- * @readonly
- * @type {Number}
- */
- RGBA4444: enums.TEXTURE_FMT_R4_G4_B4_A4,
- /**
- * 24-bit texture: RGB888
- * @property RGB888
- * @readonly
- * @type {Number}
- */
- RGB888: enums.TEXTURE_FMT_RGB8,
- /**
- * 32-bit texture: RGBA8888
- * @property RGBA8888
- * @readonly
- * @type {Number}
- */
- RGBA8888: enums.TEXTURE_FMT_RGBA8,
- /**
- * 32-bit float texture: RGBA32F
- * @property RGBA32F
- * @readonly
- * @type {Number}
- */
- RGBA32F: enums.TEXTURE_FMT_RGBA32F,
- /**
- * 8-bit textures used as masks
- * @property A8
- * @readonly
- * @type {Number}
- */
- A8: enums.TEXTURE_FMT_A8,
- /**
- * 8-bit intensity texture
- * @property I8
- * @readonly
- * @type {Number}
- */
- I8: enums.TEXTURE_FMT_L8,
- /**
- * 16-bit textures used as masks
- * @property AI88
- * @readonly
- * @type {Number}
- */
- AI8: enums.TEXTURE_FMT_L8_A8,
-
- /**
- * rgb 2 bpp pvrtc
- * @property RGB_PVRTC_2BPPV1
- * @readonly
- * @type {Number}
- */
- RGB_PVRTC_2BPPV1: enums.TEXTURE_FMT_RGB_PVRTC_2BPPV1,
- /**
- * rgba 2 bpp pvrtc
- * @property RGBA_PVRTC_2BPPV1
- * @readonly
- * @type {Number}
- */
- RGBA_PVRTC_2BPPV1: enums.TEXTURE_FMT_RGBA_PVRTC_2BPPV1,
- /**
- * rgb 4 bpp pvrtc
- * @property RGB_PVRTC_4BPPV1
- * @readonly
- * @type {Number}
- */
- RGB_PVRTC_4BPPV1: enums.TEXTURE_FMT_RGB_PVRTC_4BPPV1,
- /**
- * rgba 4 bpp pvrtc
- * @property RGBA_PVRTC_4BPPV1
- * @readonly
- * @type {Number}
- */
- RGBA_PVRTC_4BPPV1: enums.TEXTURE_FMT_RGBA_PVRTC_4BPPV1,
-});
-
-/**
- * The texture wrap mode
- * @enum {number}
- */
-export const WrapMode = Enum({
- /**
- * The constant variable equals gl.REPEAT for texture
- * @property REPEAT
- * @type {Number}
- * @readonly
- */
- REPEAT: GL_REPEAT,
- /**
- * The constant variable equals gl.CLAMP_TO_EDGE for texture
- * @property CLAMP_TO_EDGE
- * @type {Number}
- * @readonly
- */
- CLAMP_TO_EDGE: GL_CLAMP_TO_EDGE,
- /**
- * The constant variable equals gl.MIRRORED_REPEAT for texture
- * @property MIRRORED_REPEAT
- * @type {Number}
- * @readonly
- */
- MIRRORED_REPEAT: GL_MIRRORED_REPEAT
-});
-
-/**
- * The texture filter mode
- * @enum {number}
- */
-export const Filter = Enum({
- /**
- * The constant variable equals gl.LINEAR for texture
- * @property LINEAR
- * @type {Number}
- * @readonly
- */
- LINEAR: GL_LINEAR,
- /**
- * The constant variable equals gl.NEAREST for texture
- * @property NEAREST
- * @type {Number}
- * @readonly
- */
- NEAREST: GL_NEAREST
-});
-
-const FilterIndex = {
- 9728: 0, // GL_NEAREST
- 9729: 1, // GL_LINEAR
-};
-
-/**
- * @type TextureUpdateOpts
- */
-let _sharedOpts = {
- width: undefined,
- height: undefined,
- minFilter: undefined,
- magFilter: undefined,
- mipFilter: undefined,
- wrapS: undefined,
- wrapT: undefined,
- format: undefined,
- mipmap: undefined,
- images: undefined,
- image: undefined,
- flipY: undefined,
- premultiplyAlpha: undefined,
- anisotropy: undefined
-};
-function _getSharedOptions () {
- for (var key in _sharedOpts) {
- _sharedOpts[key] = undefined;
- }
- _images.length = 0;
- _sharedOpts.images = _images;
- _sharedOpts.flipY = false;
- return _sharedOpts;
-}
-
-@ccclass('cc.TextureBase')
-export default class TextureBase extends Asset {
- @property
- _genMipmap = false;
-
- @property
- _format = PixelFormat.RGBA8888;
-
- @property
- _premultiplyAlpha = false;
-
- @property
- _flipY = false;
-
- @property
- _minFilter = Filter.LINEAR;
-
- @property
- _magFilter = Filter.LINEAR;
-
- @property
- _mipFilter = Filter.LINEAR;
-
- @property
- _wrapS = WrapMode.CLAMP_TO_EDGE;
-
- @property
- _wrapT = WrapMode.CLAMP_TO_EDGE;
-
- @property
- _anisotropy = 1;
-
- static PixelFormat = PixelFormat;
-
- static WrapMode = WrapMode;
-
- static Filter = Filter;
-
- /**
- *
- * @param {TextureBase} texture
- */
- static _isCompressed (texture) {
- return texture._format >= PixelFormat.RGB_PVRTC_2BPPV1 && texture._format <= PixelFormat.RGBA_PVRTC_4BPPV1;
- }
-
- constructor () {
- super();
- EventTarget.call(this);
-
- // Id for generate hash in material
- this._id = idGenerator.getNewId();
-
- /**
- * !#en
- * Whether the texture is loaded or not
- * !#zh
- * 贴图是否已经成功加载
- * @property loaded
- * @type {Boolean}
- */
- this.loaded = false;
- /**
- * !#en
- * Texture width, in pixels.
- * For 2D texture, the width of texture is equal to its very first mipmap's width;
- * For Cubemap texture, the width of texture is equal to its every sides's very first mipmaps's width.
- * !#zh
- * 贴图像素宽度
- * @property width
- * @type {Number}
- */
- this.width = 0;
- /**
- * !#en
- * Texture height, in pixels.
- * For 2D texture, the height of texture is equal to its very first mipmap's height;
- * For Cubemap texture, the height of texture is equal to its every sides's very first mipmaps's height.
- * !#zh
- * 贴图像素高度
- * @property height
- * @type {Number}
- */
- this.height = 0;
- }
-
- getId () {
- return this._id;
- }
-
- /**
- * Update texture sampler options.
- * @method update
- * @param {TextureUpdateOpts} options
- */
- update (options) {
- if (!options) {
- return;
- }
-
- if (options.width !== undefined) {
- this.width = options.width;
- }
- if (options.height !== undefined) {
- this.height = options.height;
- }
- if (options.minFilter !== undefined) {
- this._minFilter = options.minFilter;
- options.minFilter = FilterIndex[options.minFilter];
- }
- if (options.magFilter !== undefined) {
- this._magFilter = options.magFilter;
- options.magFilter = FilterIndex[options.magFilter];
- }
- if (options.mipFilter !== undefined) {
- this._mipFilter = options.mipFilter;
- options.mipFilter = FilterIndex[options.mipFilter];
- }
- if (options.wrapS !== undefined) {
- this._wrapS = options.wrapS;
- }
- if (options.wrapT !== undefined) {
- this._wrapT = options.wrapT;
- }
- if (options.format !== undefined) {
- this._format = options.format;
- }
- if (options.flipY !== undefined) {
- this._flipY = options.flipY;
- }
- if (options.premultiplyAlpha !== undefined) {
- this._premultiplyAlpha = options.premultiplyAlpha;
- }
- if (options.anisotropy !== undefined) {
- this._anisotropy = options.anisotropy;
- }
- if (options.mipmap !== undefined) {
- this._genMipmap = options.mipmap;
- }
- }
-
- _getOpts() {
- let opts = _getSharedOptions();
- opts.width = this.width;
- opts.height = this.height;
- opts.mipmap = this._genMipmap;
- opts.format = this._format;
- opts.premultiplyAlpha = this._premultiplyAlpha;
- opts.anisotropy = this._anisotropy;
- opts.flipY = this._flipY;
- opts.minFilter = FilterIndex[this._minFilter];
- opts.magFilter = FilterIndex[this._magFilter];
- opts.mipFilter = FilterIndex[this._mipFilter];
- opts.wrapS = this._wrapS;
- opts.wrapT = this._wrapT;
- return opts;
- }
-
- /**
- * !#en
- * Pixel format of the texture.
- * !#zh 获取纹理的像素格式。
- * @method getPixelFormat
- * @return {Number}
- */
- getPixelFormat () {
- //support only in WebGl rendering mode
- return this._format;
- }
-
- /**
- * !#en
- * Whether or not the texture has their Alpha premultiplied.
- * !#zh 检查纹理在上传 GPU 时预乘选项是否开启。
- * @method hasPremultipliedAlpha
- * @return {Boolean}
- */
- hasPremultipliedAlpha () {
- return this._premultiplyAlpha || false;
- }
-
- /**
- * !#en Anisotropy of the texture.
- * !#zh 获取纹理的各向异性。
- * @method getAnisotropy
- * @return {Number}
- */
- getAnisotropy() {
- return this._anisotropy;
- }
-
- /**
- * !#en
- * Whether or not to generate mipmap.
- * !#zh 检查纹理在上传 GPU 时是否生成 mipmap。
- * @method hasMipmap
- * @return {Boolean}
- */
- genMipmap () {
- return this._genMipmap || false;
- }
-
- /**
- * !#en Sets the wrap s and wrap t options.
- * If the texture size is NPOT (non power of 2), then in can only use gl.CLAMP_TO_EDGE in gl.TEXTURE_WRAP_{S,T}.
- * !#zh 设置纹理包装模式。
- * 若纹理贴图尺寸是 NPOT(non power of 2),则只能使用 Texture2D.WrapMode.CLAMP_TO_EDGE。
- * @method setTexParameters
- * @param {WrapMode} wrapS
- * @param {WrapMode} wrapT
- */
- setWrapMode (wrapS, wrapT) {
- if (this._wrapS !== wrapS || this._wrapT !== wrapT) {
- var opts = _getSharedOptions();
- opts.wrapS = wrapS;
- opts.wrapT = wrapT;
- this.update(opts);
- }
- }
-
- /**
- * !#en Sets the minFilter and magFilter options
- * !#zh 设置纹理贴图缩小和放大过滤器算法选项。
- * @method setFilters
- * @param {Filter} minFilter
- * @param {Filter} magFilter
- */
- setFilters (minFilter, magFilter) {
- if (this._minFilter !== minFilter || this._magFilter !== magFilter) {
- var opts = _getSharedOptions();
- opts.minFilter = minFilter;
- opts.magFilter = magFilter;
- this.update(opts);
- }
- }
-
- /**
- * !#en Sets the mipFilter options
- * !#zh 设置纹理Mipmap过滤算法选项。
- * @method setMipFilter
- * @param {Filter} mipFilter
- */
- setMipFilter (mipFilter) {
- if (this._mipFilter !== mipFilter) {
- var opts = _getSharedOptions();
- opts.mipFilter = mipFilter;
- this.update(opts);
- }
- }
-
- /**
- * !#en
- * Sets the flipY options
- * !#zh 设置贴图的纵向翻转选项。
- * @method setFlipY
- * @param {Boolean} flipY
- */
- setFlipY (flipY) {
- if (this._flipY !== flipY) {
- var opts = _getSharedOptions();
- opts.flipY = flipY;
- this.update(opts);
- }
- }
-
- /**
- * !#en
- * Sets the premultiply alpha options
- * !#zh 设置贴图的预乘选项。
- * @method setPremultiplyAlpha
- * @param {Boolean} premultiply
- */
- setPremultiplyAlpha (premultiply) {
- if (this._premultiplyAlpha !== premultiply) {
- var opts = _getSharedOptions();
- opts.premultiplyAlpha = premultiply;
- this.update(opts);
- }
- }
-
- /**
- * !#en Sets the anisotropy of the texture
- * !#zh 设置贴图的各向异性。
- * @method setAnisotropy
- * @param {number} anisotropy
- */
- setAnisotropy(anisotropy) {
- if (this._anisotropy != anisotropy) {
- var opts = _getSharedOptions();
- opts.anisotropy = anisotropy;
- this.update(opts);
- }
- }
-
- /**
- * !#en
- * Sets whether generate mipmaps for the texture
- * !#zh 是否为纹理设置生成 mipmaps。
- * @method setGenerateMipmap
- * @param {Boolean} mipmap
- */
- setGenMipmap (mipmap) {
- if (this._genMipmap !== mipmap) {
- var opts = _getSharedOptions();
- opts.mipmap = mipmap;
- this.update(opts);
- }
- }
-
- // SERIALIZATION
-
- /**
- * @return {any}
- */
- _serialize () {
- return this._minFilter + "," + this._magFilter + "," +
- this._wrapS + "," + this._wrapT + "," +
- (this._premultiplyAlpha ? 1 : 0) + "," +
- this._mipFilter + "," + this._anisotropy + "," +
- (this._flipY ? 1 : 0) + "," +
- (this._genMipmap ? 1 : 0);
- }
-
- /**
- *
- * @param {string} data
- */
- _deserialize (data) {
- let fields = data.split(',');
- fields.unshift("");
- if (fields.length >= 6) {
- // decode filters
- this._minFilter = parseInt(fields[1]);
- this._magFilter = parseInt(fields[2]);
- // decode wraps
- this._wrapS = parseInt(fields[3]);
- this._wrapT = parseInt(fields[4]);
- // decode premultiply alpha
- this._premultiplyAlpha = fields[5].charCodeAt(0) === CHAR_CODE_1;
- }
- if (fields.length >= 8) {
- this._mipFilter = parseInt(fields[6]);
- this._anisotropy = parseInt(fields[7]);
- }
- if (fields.length >= 10) {
- this._flipY = fields[8].charCodeAt(0) === CHAR_CODE_1;
- this._genMipmap = fields[9].charCodeAt(0) === CHAR_CODE_1;
- }
- }
-}
-
-/**
- * !#zh
- * 当该资源加载成功后触发该事件
- * !#en
- * This event is emitted when the asset is loaded
- *
- * @event load
- */
-
-addon(TextureBase.prototype, EventTarget.prototype);
-cc.TextureBase = TextureBase;
diff --git a/cocos/assets/texture-base.ts b/cocos/assets/texture-base.ts
new file mode 100644
index 0000000000..5f8812de9e
--- /dev/null
+++ b/cocos/assets/texture-base.ts
@@ -0,0 +1,644 @@
+/****************************************************************************
+ 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 {ccclass, property} from '../core/data/class-decorator';
+import EventTarget from '../core/event/event-target';
+import IDGenerator from '../core/utils/id-generator';
+import {addon} from '../core/utils/js';
+import { ccenum } from '../core/value-types/enum';
+import { GFXAddress, GFXBufferTextureCopy, GFXFilter, GFXFormat,
+ GFXTextureFlagBit, GFXTextureType, GFXTextureUsageBit, GFXTextureViewType } from '../gfx/define';
+import { GFXDevice } from '../gfx/device';
+import { GFXSampler } from '../gfx/sampler';
+import { GFXTexture, IGFXTextureInfo } from '../gfx/texture';
+import { GFXTextureView, IGFXTextureViewInfo } from '../gfx/texture-view';
+import { Asset } from './asset';
+import { ImageAsset, ImageSource } from './image-asset';
+
+const CHAR_CODE_1 = 49; // '1'
+
+const idGenerator = new IDGenerator('Tex');
+
+/**
+ * The texture pixel format, default value is RGBA8888,
+ * you should note that textures loaded by normal image files (png, jpg) can only support RGBA8888 format,
+ * other formats are supported by compressed file types or raw data.
+ * @enum {number}
+ */
+export enum PixelFormat {
+ /**
+ * 16-bit texture without Alpha channel
+ */
+ RGB565 = GFXFormat.R5G6B5,
+ /**
+ * 16-bit textures: RGB5A1
+ */
+ RGB5A1 = GFXFormat.RGB5A1,
+ /**
+ * 16-bit textures: RGBA4444
+ */
+ RGBA4444 = GFXFormat.RGBA4,
+ /**
+ * 24-bit texture: RGB888
+ */
+ RGB888 = GFXFormat.RGB8,
+ /**
+ * 32-bit texture: RGBA8888
+ */
+ RGBA8888 = GFXFormat.RGBA8,
+ /**
+ * 32-bit float texture: RGBA32F
+ */
+ RGBA32F = GFXFormat.RGBA32F,
+ /**
+ * 8-bit textures used as masks
+ */
+ A8 = GFXFormat.A8,
+ /**
+ * 8-bit intensity texture
+ */
+ I8 = GFXFormat.L8,
+ /**
+ * 16-bit textures used as masks
+ */
+ AI8 = GFXFormat.LA8,
+ /**
+ * rgb 2 bpp pvrtc
+ */
+ RGB_PVRTC_2BPPV1 = GFXFormat.PVRTC_RGB2,
+ /**
+ * rgba 2 bpp pvrtc
+ */
+ RGBA_PVRTC_2BPPV1 = GFXFormat.PVRTC_RGBA2,
+ /**
+ * rgb 4 bpp pvrtc
+ */
+ RGB_PVRTC_4BPPV1 = GFXFormat.PVRTC_RGB4,
+ /**
+ * rgba 4 bpp pvrtc
+ */
+ RGBA_PVRTC_4BPPV1 = GFXFormat.PVRTC_RGBA4,
+}
+ccenum(PixelFormat);
+
+function toGfxFormat (pixelFormat: PixelFormat) {
+ return pixelFormat as unknown as GFXFormat;
+}
+
+/**
+ * The texture wrap mode.
+ * @enum {number}
+ */
+export enum WrapMode {
+ /**
+ * Specifies that the repeat warp mode will be used.
+ */
+ REPEAT = GFXAddress.WRAP,
+ /**
+ * Specifies that the clamp to edge warp mode will be used.
+ */
+ CLAMP_TO_EDGE = GFXAddress.CLAMP,
+ /**
+ * Specifies that the mirrored repeat warp mode will be used.
+ */
+ MIRRORED_REPEAT = GFXAddress.MIRROR,
+ /**
+ * Specifies that the clamp to border wrap mode will be used.
+ */
+ CLAMP_TO_BORDER = GFXAddress.BORDER,
+}
+ccenum(WrapMode);
+
+function toGfxAddressMode (wrapMode: WrapMode) {
+ return wrapMode as unknown as GFXAddress;
+}
+
+/**
+ * The texture filter mode
+ * @enum {number}
+ */
+export enum Filter {
+ /**
+ * Specifies linear filtering.
+ */
+ LINEAR = GFXFilter.LINEAR,
+ /**
+ * Specifies nearest filtering.
+ */
+ NEAREST = GFXFilter.POINT,
+}
+ccenum(Filter);
+
+function toGfxFilterMode (filter: Filter) {
+ return filter as unknown as GFXFilter;
+}
+
+@ccclass('cc.TextureBase')
+export class TextureBase extends Asset {
+
+ /**
+ * !#en
+ * Texture width, in pixels.
+ * For 2D texture, the width of texture is equal to its very first mipmap's width;
+ * For Cubemap texture, the width of texture is equal to its every sides's very first mipmaps's width.
+ * !#zh
+ * 贴图像素宽度
+ */
+ public get width (): number {
+ return this._texture ? this._texture.width : 0;
+ }
+
+ /**
+ * !#en
+ * Texture height, in pixels.
+ * For 2D texture, the height of texture is equal to its very first mipmap's height;
+ * For Cubemap texture, the height of texture is equal to its every sides's very first mipmaps's height.
+ * !#zh
+ * 贴图像素高度
+ */
+ public get height (): number {
+ return this._texture ? this._texture.height : 0;
+ }
+
+ public static PixelFormat = PixelFormat;
+
+ public static WrapMode = WrapMode;
+
+ public static Filter = Filter;
+
+ /**
+ *
+ * @param texture
+ */
+ public static _isCompressed (texture: TextureBase) {
+ return texture._format >= PixelFormat.RGB_PVRTC_2BPPV1 && texture._format <= PixelFormat.RGBA_PVRTC_4BPPV1;
+ }
+
+ protected _texture: GFXTexture | null = null;
+
+ protected _textureView: GFXTextureView | null = null;
+
+ private _potientialWidth: number = 0;
+
+ private _potientialHeight: number = 0;
+
+ private _mipmapLevel: number = 1;
+
+ @property
+ private _genMipmap = false;
+
+ @property
+ private _format: PixelFormat = PixelFormat.RGBA8888;
+
+ @property
+ private _premultiplyAlpha = false;
+
+ @property
+ private _flipY = false;
+
+ @property
+ private _minFilter = Filter.LINEAR;
+
+ @property
+ private _magFilter = Filter.LINEAR;
+
+ @property
+ private _mipFilter = Filter.LINEAR;
+
+ @property
+ private _wrapS: WrapMode = WrapMode.CLAMP_TO_EDGE;
+
+ @property
+ private _wrapT: WrapMode = WrapMode.CLAMP_TO_EDGE;
+
+ @property
+ private _anisotropy = 1;
+
+ private _sampler: GFXSampler | null = null;
+
+ private _id: string;
+
+ protected constructor (flipY: boolean = false) {
+ super();
+ // @ts-ignore
+ EventTarget.call(this);
+
+ this._flipY = flipY;
+
+ // Id for generate hash in material
+ this._id = idGenerator.getNewId();
+
+ /**
+ * !#en
+ * Whether the texture is loaded or not
+ * !#zh
+ * 贴图是否已经成功加载
+ * @property loaded
+ * @type {Boolean}
+ */
+ // @ts-ignore
+ this.loaded = false;
+ }
+
+ public create (width: number, height: number, format = PixelFormat.RGBA8888, mipmapLevel = 1) {
+ this._potientialWidth = width;
+ this._potientialHeight = height;
+ this._format = format;
+ this._mipmapLevel = mipmapLevel;
+ this._updateSampler();
+ this._recreateTexture();
+ }
+
+ /**
+ * Gets the underlying texture object.
+ * @deprecated Use getGfxTexture() instead.
+ */
+ public getImpl () {
+ return this._texture;
+ }
+
+ public getId () {
+ return this._id;
+ }
+
+ /**
+ * !#en
+ * Pixel format of the texture.
+ * !#zh 获取纹理的像素格式。
+ * @return
+ */
+ public getPixelFormat () {
+ // support only in WebGl rendering mode
+ return this._format;
+ }
+
+ /**
+ * !#en
+ * Whether or not the texture has their Alpha premultiplied.
+ * !#zh 检查纹理在上传 GPU 时预乘选项是否开启。
+ * @return
+ */
+ public hasPremultipliedAlpha () {
+ return this._premultiplyAlpha || false;
+ }
+
+ /**
+ * !#en Anisotropy of the texture.
+ * !#zh 获取纹理的各向异性。
+ * @return
+ */
+ public getAnisotropy () {
+ return this._anisotropy;
+ }
+
+ /**
+ * !#en
+ * Whether or not to generate mipmap.
+ * !#zh 检查纹理在上传 GPU 时是否生成 mipmap。
+ * @return
+ */
+ public genMipmap () {
+ return this._genMipmap || false;
+ }
+
+ /**
+ * !#en Sets the wrap s and wrap t options.
+ * If the texture size is NPOT (non power of 2), then in can only use gl.CLAMP_TO_EDGE in gl.TEXTURE_WRAP_{S,T}.
+ * !#zh 设置纹理包装模式。
+ * 若纹理贴图尺寸是 NPOT(non power of 2),则只能使用 Texture2D.WrapMode.CLAMP_TO_EDGE。
+ * @param wrapS
+ * @param wrapT
+ */
+ public setWrapMode (wrapS: WrapMode, wrapT: WrapMode) {
+ if (this._wrapS !== wrapS || this._wrapT !== wrapT) {
+ this._wrapS = wrapS;
+ this._wrapT = wrapT;
+ this._updateSampler();
+ }
+ }
+
+ /**
+ * !#en Sets the minFilter and magFilter options
+ * !#zh 设置纹理贴图缩小和放大过滤器算法选项。
+ * @param minFilter
+ * @param magFilter
+ */
+ public setFilters (minFilter: Filter, magFilter: Filter) {
+ if (this._minFilter !== minFilter || this._magFilter !== magFilter) {
+ this._minFilter = minFilter;
+ this._magFilter = magFilter;
+ this._updateSampler();
+ }
+ }
+
+ /**
+ * !#en Sets the mipFilter options
+ * !#zh 设置纹理Mipmap过滤算法选项。
+ * @param mipFilter
+ */
+ public setMipFilter (mipFilter: Filter) {
+ if (this._mipFilter !== mipFilter) {
+ this._mipFilter = mipFilter;
+ this._updateSampler();
+ }
+ }
+
+ /**
+ * !#en
+ * Sets the flipY options
+ * !#zh 设置贴图的纵向翻转选项。
+ * @param flipY
+ */
+ public setFlipY (flipY: boolean) {
+ if (this._flipY !== flipY) {
+ this._flipY = flipY;
+ this._updateSampler();
+ }
+ }
+
+ /**
+ * !#en
+ * Sets the premultiply alpha options
+ * !#zh 设置贴图的预乘选项。
+ * @param premultiply
+ */
+ public setPremultiplyAlpha (premultiply: boolean) {
+ if (this._premultiplyAlpha !== premultiply) {
+ this._premultiplyAlpha = premultiply;
+ this._updateSampler();
+ }
+ }
+
+ /**
+ * !#en Sets the anisotropy of the texture
+ * !#zh 设置贴图的各向异性。
+ * @param anisotropy
+ */
+ public setAnisotropy (anisotropy: number) {
+ if (this._anisotropy !== anisotropy) {
+ this._anisotropy = anisotropy;
+ this._updateSampler();
+ }
+ }
+
+ /**
+ * !#en
+ * Sets whether generate mipmaps for the texture
+ * !#zh 是否为纹理设置生成 mipmaps。
+ * @param mipmap
+ */
+ public setGenMipmap (mipmap: boolean) {
+ if (this._genMipmap !== mipmap) {
+ this._genMipmap = mipmap;
+ this._updateSampler();
+ }
+ }
+
+ public destroy () {
+ this._destroyTexture();
+
+ if (this._sampler) {
+ this._sampler.destroy();
+ }
+
+ return true;
+ }
+
+ public getGFXTexture () {
+ return this._texture;
+ }
+
+ public getGFXTextureView () {
+ return this._textureView;
+ }
+
+ public getGFXSampler () {
+ return this._sampler;
+ }
+
+ // SERIALIZATION
+
+ /**
+ * @return
+ */
+ public _serialize (): any {
+ return this._minFilter + ',' + this._magFilter + ',' +
+ this._wrapS + ',' + this._wrapT + ',' +
+ (this._premultiplyAlpha ? 1 : 0) + ',' +
+ this._mipFilter + ',' + this._anisotropy + ',' +
+ (this._flipY ? 1 : 0) + ',' +
+ (this._genMipmap ? 1 : 0);
+ }
+
+ /**
+ *
+ * @param data
+ */
+ public _deserialize (serializedData: any, handle: any) {
+ const data = serializedData as string;
+ const fields = data.split(',');
+ fields.unshift('');
+ if (fields.length >= 6) {
+ // decode filters
+ this._minFilter = parseInt(fields[1], undefined);
+ this._magFilter = parseInt(fields[2], undefined);
+ // decode wraps
+ this._wrapS = parseInt(fields[3], undefined);
+ this._wrapT = parseInt(fields[4], undefined);
+ // decode premultiply alpha
+ this._premultiplyAlpha = fields[5].charCodeAt(0) === CHAR_CODE_1;
+ }
+ if (fields.length >= 8) {
+ this._mipFilter = parseInt(fields[6], undefined);
+ this._anisotropy = parseInt(fields[7], undefined);
+ }
+ if (fields.length >= 10) {
+ this._flipY = fields[8].charCodeAt(0) === CHAR_CODE_1;
+ this._genMipmap = fields[9].charCodeAt(0) === CHAR_CODE_1;
+ }
+ }
+
+ public onLoaded () {
+ this._updateSampler();
+ this._recreateTexture();
+ }
+
+ protected _getGlobalDevice (): GFXDevice | null {
+ // @ts-ignore
+ return cc.director.root.device;
+ }
+
+ protected _getGfxFormat () {
+ return toGfxFormat(this._format);
+ }
+
+ protected _assignImage (image: ImageAsset, level: number, arrayIndex?: number) {
+ const upload = () => {
+ if (!image.data) {
+ return;
+ }
+ let source: HTMLCanvasElement | HTMLImageElement | ArrayBuffer;
+ if (image.data instanceof HTMLElement) {
+ source = image.data;
+ } else {
+ source = image.data.buffer;
+ }
+ this._uploadData(source, level, arrayIndex);
+ };
+ // @ts-ignore
+ if (image.loaded) {
+ upload();
+ } else {
+ // @ts-ignore
+ image.addEventListener('load', () => {
+ upload();
+ });
+ }
+ }
+
+ protected _uploadData (
+ source: HTMLCanvasElement | HTMLImageElement | ArrayBuffer, level: number, arrayIndex?: number) {
+ if (!this._texture) {
+ return;
+ }
+
+ if (level >= this._texture.mipLevel) {
+ return;
+ }
+
+ const gfxDevice = this._getGlobalDevice();
+ if (!gfxDevice) {
+ return;
+ }
+
+ const region: GFXBufferTextureCopy = {
+ buffOffset: 0,
+ buffStride: 0,
+ buffTexHeight: 0,
+ texOffset: {
+ x: 0,
+ y: 0,
+ z: 0,
+ },
+ texExtent: {
+ width: this._texture.width,
+ height: this._texture.height,
+ depth: 1,
+ },
+ texSubres: {
+ baseMipLevel: level,
+ levelCount: 1,
+ baseArrayLayer: arrayIndex || 0,
+ layerCount: 1,
+ },
+ };
+
+ if (source instanceof HTMLElement) {
+ gfxDevice.copyImageSourceToTexture(source, this._texture, [region]);
+ } else {
+ gfxDevice.copyBufferToTexture(source, this._texture, [region]);
+ }
+ }
+
+ protected _getTextureCreateInfo (): IGFXTextureInfo {
+ return {
+ type: GFXTextureType.TEX2D,
+ usage: GFXTextureUsageBit.SAMPLED | GFXTextureUsageBit.TRANSFER_DST,
+ format: toGfxFormat(this._format),
+ width: this._potientialWidth,
+ height: this._potientialHeight,
+ mipLevel: this._mipmapLevel,
+ flags: this._genMipmap ? GFXTextureFlagBit.GEN_MIPMAP : GFXTextureFlagBit.NONE,
+ };
+ }
+
+ protected _getTextureViewCreateInfo (): IGFXTextureViewInfo {
+ return {
+ texture: this._texture!,
+ type: GFXTextureViewType.TV2D,
+ format: this._getGfxFormat(),
+ };
+ }
+
+ protected _recreateTexture () {
+ this._destroyTexture();
+
+ const gfxDevice = this._getGlobalDevice();
+ if (!gfxDevice) {
+ return;
+ }
+
+ this._texture = gfxDevice.createTexture(this._getTextureCreateInfo());
+
+ this._textureView = gfxDevice.createTextureView(this._getTextureViewCreateInfo());
+ }
+
+ private _destroyTexture () {
+ if (this._textureView) {
+ this._textureView.destroy();
+ this._textureView = null;
+ }
+
+ if (this._texture) {
+ this._texture.destroy();
+ this._texture = null;
+ }
+ }
+
+ private _updateSampler () {
+ if (this._sampler) {
+ this._sampler.destroy();
+ }
+
+ const gfxDevice = this._getGlobalDevice();
+ if (!gfxDevice) {
+ return;
+ }
+
+ this._sampler = gfxDevice.createSampler({
+ name: `Sampler of ${this.name}`,
+ minFilter: toGfxFilterMode(this._minFilter),
+ magFilter: toGfxFilterMode(this._magFilter),
+ addressU: toGfxAddressMode(this._wrapS),
+ addressV: toGfxAddressMode(this._wrapT),
+ maxAnisotropy: this._anisotropy,
+ });
+ }
+}
+
+/* tslint:disable:no-string-literal */
+cc['TextureBase'] = TextureBase;
+
+/**
+ * !#zh
+ * 当该资源加载成功后触发该事件
+ * !#en
+ * This event is emitted when the asset is loaded
+ *
+ * @event load
+ */
+
+addon(TextureBase.prototype, EventTarget.prototype);
diff --git a/cocos/assets/texture-util.js b/cocos/assets/texture-util.js
index 35d75a2fe3..0278ade825 100644
--- a/cocos/assets/texture-util.js
+++ b/cocos/assets/texture-util.js
@@ -24,8 +24,8 @@
THE SOFTWARE.
****************************************************************************/
-import ImageAsset from './image-asset';
-import Texture2D from './texture-2d';
+import { ImageAsset } from './image-asset';
+import { Texture2D } from './texture-2d';
/**
* cc.textureUtil is a singleton object, it can load cc.Texture2D asynchronously
diff --git a/cocos/audio/CCAudioSource.js b/cocos/audio/CCAudioSource.js
index ff525592d9..fd49ab31bd 100644
--- a/cocos/audio/CCAudioSource.js
+++ b/cocos/audio/CCAudioSource.js
@@ -24,9 +24,9 @@
THE SOFTWARE.
****************************************************************************/
-const misc = require('../utils/misc');
-const Component = require('./CCComponent');
-const AudioClip = require('../assets/CCAudioClip');
+import * as misc from '../core/utils/misc';
+import { Component } from './component';
+import AudioClip from '../assets/CCAudioClip';
/**
* !#en Audio Source.
diff --git a/cocos/camera/CCCamera.js b/cocos/camera/CCCamera.js
index 6c8c05e592..bafb0e903f 100644
--- a/cocos/camera/CCCamera.js
+++ b/cocos/camera/CCCamera.js
@@ -24,14 +24,14 @@
THE SOFTWARE.
****************************************************************************/
-import game from '../core/CCGame';
+import game from '../core/game';
import AffineTrans from '../core/value-types/affine-transform';
import mat4 from '../core/vmath/mat4';
import vec2 from '../core/vmath/vec2';
import vec3 from '../core/vmath/vec3';
-import Component from '../components/CCComponent';
+import { Component } from '../components/component';
// TODO fix import from renderer
-import {default as Renderer_Camera} from '../renderer/scene/camera';
+import { Camera as Renderer_Camera} from '../renderer/scene/camera';
import {default as Renderer_View} from '../renderer/core/view';
import {ccclass, property, executeInEditMode, menu, inspector} from '../core/data/class-decorator';
diff --git a/cocos/components/WXSubContextView.js b/cocos/components/WXSubContextView.js
index 183c617e2a..cf1fc17dd2 100644
--- a/cocos/components/WXSubContextView.js
+++ b/cocos/components/WXSubContextView.js
@@ -23,8 +23,8 @@
THE SOFTWARE.
****************************************************************************/
-const Component = require('./CCComponent');
-const ImageAsset = require('../assets/image-asset');
+import { Component } from './component';
+const { ImageAsset } = require('../assets/image-asset');
let WXSubContextView;
@@ -37,7 +37,7 @@ if (!CC_EDITOR && !CC_WECHATGAME) {
else {
/**
* !#en WXSubContextView is a view component which controls open data context viewport in Wechat game platform.
- * The component's node size decide the viewport of the sub context content in main context,
+ * The component's node size decide the viewport of the sub context content in main context,
* the entire sub context texture will be scaled to the node's bounding box area.
* This component provides multiple important features:
* 1. Sub context could use its own resolution size and policy.
@@ -45,7 +45,7 @@ else {
* 3. Resolution of sub context content could be increased.
* 4. User touch input is transformed to the correct viewport.
* 5. Texture update is handled by this component. User don't need to worry.
- * One important thing to be noted, whenever the node's bounding box change,
+ * One important thing to be noted, whenever the node's bounding box change,
* you need to manually reset the viewport of sub context using updateSubContextViewport.
* !#zh WXSubContextView 可以用来控制微信小游戏平台开放数据域在主域中的视窗的位置。
* 这个组件的节点尺寸决定了开放数据域内容在主域中的尺寸,整个开放数据域会被缩放到节点的包围盒范围内。
@@ -134,4 +134,4 @@ else {
}
-cc.WXSubContextView = module.exports = WXSubContextView;
\ No newline at end of file
+cc.WXSubContextView = module.exports = WXSubContextView;
diff --git a/cocos/components/component.d.ts b/cocos/components/component.d.ts
new file mode 100644
index 0000000000..c8cbc9b011
--- /dev/null
+++ b/cocos/components/component.d.ts
@@ -0,0 +1,56 @@
+/****************************************************************************
+ 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 { CCObject } from '../core/data/object';
+import { getClassName, value } from '../core/utils/js';
+import IDGenerator from '../core/utils/id-generator';
+import { ccclass, property } from '../core/data/class-decorator';
+import { Node } from '../scene-graph';
+import { RenderScene } from '../renderer/scene/render-scene';
+
+export class Component extends CCObject {
+ node: Node;
+ uuid: string;
+ enabled: boolean;
+ enabledInHierarchy: boolean;
+
+ public constructor();
+
+ protected _getRenderScene (): RenderScene;
+ public addComponent (typeOrClassName: string | (new () => T)): T;
+ public getComponent (typeOrClassName: string | (new () => T)): T;
+ public getComponents (typeOrClassName: string | (new () => T)): T[];
+ public getComponentInChildren (typeOrClassName: string | (new () => T)): T;
+ public getComponentsInChildren (typeOrClassName: string | (new () => T)): T[];
+ public schedule (callback: Function, interval: number, repeat: number, delay: number): void;
+ 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/components/CCComponent.js b/cocos/components/component.js
similarity index 98%
rename from cocos/components/CCComponent.js
rename to cocos/components/component.js
index ad5e99f5c0..867c106ea6 100644
--- a/cocos/components/CCComponent.js
+++ b/cocos/components/component.js
@@ -24,10 +24,11 @@
THE SOFTWARE.
****************************************************************************/
-import CCObject from '../core/data/object';
+import { CCObject } from '../core/data/object';
import {getClassName, value} from '../core/utils/js';
import IDGenerator from '../core/utils/id-generator';
import {ccclass, property} from '../core/data/class-decorator';
+import {Script} from '../assets';
let idGenerator = new IDGenerator('Comp');
const IsOnEnableCalled = CCObject.Flags.IsOnEnableCalled;
@@ -102,10 +103,10 @@ class Component extends CCObject {
@property({
displayName: 'Script',
- type: cc._Script,
+ type: Script,
tooltip: CC_DEV && 'i18n:INSPECTOR.component.script'
})
- get __scriptAsset () {}
+ get __scriptAsset () { return null; }
//set __scriptAsset (value) {
// if (this.__scriptUuid !== value) {
// if (value && Editor.Utils.UuidUtils.isUuid(value._uuid)) {
@@ -177,7 +178,7 @@ class Component extends CCObject {
visible: false
})
get enabledInHierarchy () {
- return (this._objFlags & IsOnEnableCalled) > 0;
+ return this._enabled && this.node._activeInHierarchy;
}
/**
@@ -195,6 +196,10 @@ class Component extends CCObject {
static system = null;
+ _getRenderScene() {
+ return this.node._scene._renderScene;
+ }
+
constructor () {
super();
if (CC_EDITOR) {
@@ -718,4 +723,4 @@ value(Component, '_registerEditorProps', function (cls, props) {
Component.prototype.__scriptUuid = '';
cc.Component = Component;
-export default Component;
\ No newline at end of file
+export { Component };
diff --git a/cocos/components/index.js b/cocos/components/index.js
index 8f1c1b533c..0e9980ec24 100644
--- a/cocos/components/index.js
+++ b/cocos/components/index.js
@@ -24,7 +24,6 @@
THE SOFTWARE.
****************************************************************************/
-export {default as Component} from './CCComponent';
+export {Component} from './component';
export {default as EventHandler} from './CCComponentEventHandler';
export {default as MissingScript} from './missing-script';
-export {default as Canvas} from './CCCanvas';
\ No newline at end of file
diff --git a/cocos/components/missing-script.js b/cocos/components/missing-script.js
index 6dae7bc849..4ee8d0ceab 100644
--- a/cocos/components/missing-script.js
+++ b/cocos/components/missing-script.js
@@ -26,7 +26,7 @@
import {_getClassById} from '../core/utils/js';
import {BUILTIN_CLASSID_RE} from '../core/utils/misc';
-import Component from './CCComponent';
+import { Component } from './component';
import {ccclass, property, inspector} from '../core/data/class-decorator';
/*
@@ -48,7 +48,7 @@ class MissingClass {
@ccclass('cc.MissingScript')
@inspector('packages://inspector/inspectors/comps/missing-script.js')
export default class MissingScript extends Component {
-
+
//_scriptUuid: {
// get: function () {
// var id = this._$erialized.__type__;
diff --git a/cocos/core/data/class.js b/cocos/core/data/class.js
index 503a106fa0..cfac3fc81d 100644
--- a/cocos/core/data/class.js
+++ b/cocos/core/data/class.js
@@ -144,7 +144,7 @@ function defineProp (cls, className, propName, val, es6) {
appendProp(cls, propName);
// apply attributes
- var attrs = parseAttributes(cls, val, className, propName, false);
+ var attrs = parseAttributes(cls, val, className, propName, false);
if (attrs) {
var onAfterProp = tmpArray;
for (var i = 0; i < attrs.length; i++) {
@@ -1240,4 +1240,4 @@ CCClass.escapeForJS = escapeForJS;
CCClass.IDENTIFIER_RE = IDENTIFIER_RE;
CCClass.getNewValueTypeCode = CC_SUPPORT_JIT && getNewValueTypeCodeJit;
-cc.Class = CCClass;
\ No newline at end of file
+cc.Class = CCClass;
diff --git a/cocos/core/data/index.js b/cocos/core/data/index.js
index 25869cc301..8ae9b09a7b 100644
--- a/cocos/core/data/index.js
+++ b/cocos/core/data/index.js
@@ -27,6 +27,6 @@ import * as _decorator from './class-decorator';
cc._decorator = _decorator;
export { _decorator };
export { default as CCClass } from './class';
-export { default as CCObject } from './object';
+export { CCObject } from './object';
export { default as deserialize } from './deserialize';
export { default as instantiate } from './instantiate';
diff --git a/cocos/core/data/instantiate-jit.js b/cocos/core/data/instantiate-jit.js
index 4b1b0435f3..5a92e17733 100644
--- a/cocos/core/data/instantiate-jit.js
+++ b/cocos/core/data/instantiate-jit.js
@@ -28,7 +28,7 @@
import * as js from '../utils/js';
import CCClass from './class';
-import CCObject from './object';
+import { CCObject } from './object';
import * as Attr from './utils/attribute';
import {flattenCodeArray} from './utils/compiler';
diff --git a/cocos/core/data/instantiate.js b/cocos/core/data/instantiate.js
index 2a978447f0..f86904a04e 100644
--- a/cocos/core/data/instantiate.js
+++ b/cocos/core/data/instantiate.js
@@ -24,9 +24,9 @@
THE SOFTWARE.
****************************************************************************/
-import CCObject from './object';
-import ValueType from '../value-types/value-type';
-import {isDomNode} from '../utils/misc';
+import { CCObject } from './object';
+import { ValueType } from '../value-types/value-type';
+import { isDomNode } from '../utils/misc';
const Destroyed = CCObject.Flags.Destroyed;
const PersistentMask = CCObject.Flags.PersistentMask;
diff --git a/cocos/core/data/object.d.ts b/cocos/core/data/object.d.ts
new file mode 100644
index 0000000000..96b70896d5
--- /dev/null
+++ b/cocos/core/data/object.d.ts
@@ -0,0 +1,48 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+export class CCObject {
+ protected static _deferredDestroy(): void;
+ protected _name: string;
+ protected _objFlags: number;
+
+ public constructor(name?: string);
+
+ public name: string;
+ public isValid: boolean;
+ public isRealValid: boolean;
+
+ public destroy(): any;
+ public realDestroyInEditor(): void;
+ public _clearDeferredDestroyTimer(): void;
+
+ protected _destruct(): void;
+ protected _destroyImmediate(): void;
+
+ protected _serialize?(exporting?: any): any;
+ protected _deserialize?(data: any, ctx: any): any;
+ protected _onPreDestroy (): any;
+ protected Flags: object;
+}
diff --git a/cocos/core/data/object.js b/cocos/core/data/object.js
index 77811fee5b..28f6d03d37 100644
--- a/cocos/core/data/object.js
+++ b/cocos/core/data/object.js
@@ -536,4 +536,4 @@ if (CC_EDITOR || CC_TEST) {
}
cc.Object = CCObject;
-export default CCObject;
+export { CCObject };
diff --git a/cocos/core/CCDirector.js b/cocos/core/director.js
similarity index 97%
rename from cocos/core/CCDirector.js
rename to cocos/core/director.js
index 9fd24790a6..d701c45a1c 100644
--- a/cocos/core/CCDirector.js
+++ b/cocos/core/director.js
@@ -27,17 +27,16 @@
import EventTarget from './event/event-target';
import eventManager from './platform/event-manager/CCEventManager';
-import ccobject from './data/object';
-import game from './CCGame';
-import Scheduler from './CCScheduler';
+import { CCObject } from './data/object';
+import game from './game';
+import Scheduler from './scheduler';
import { autoRelease } from '../load-pipeline/auto-release-utils';
import ComponentScheduler from '../scene-graph/component-scheduler';
import NodeActivator from '../scene-graph/node-activator';
-// import AnimationSystem from '../3d/framework/animation-system';
// import SkinningModelSystem from '../3d/framework/skinning-model-system';
-import RenderSystem from '../3d/framework/render-system';
import { PhysicsSystem } from '../3d/framework/physics/physics-system';
import { getClassByName } from './utils/js';
+import { Root } from './root';
// const ComponentScheduler = require('./component-scheduler');
// const NodeActivator = require('./node-activator');
@@ -122,6 +121,9 @@ class Director extends EventTarget {
// purge?
this._purgeDirectorInNextLoop = false;
+ // root
+ this._root = null;
+
// scenes
this._loadingScene = '';
this._scene = null;
@@ -156,6 +158,13 @@ class Director extends EventTarget {
}
init () {
+
+ this._root = new Root(game._gfxDevice);
+ let rootInfo = {};
+ if(!this._root.initialize(rootInfo)) {
+ return false;
+ }
+
this._totalFrames = 0;
this._lastUpdate = performance.now();
this._paused = false;
@@ -184,6 +193,7 @@ class Director extends EventTarget {
// this.registerSystem('animation', AnimationSystem, ['AnimationComponent'], 200);
// this.registerSystem('skinning-model', SkinningModelSystem, ['SkinningModelComponent'], 100);
// init renderSystem
+ /*
{
this._renderSystem = new RenderSystem();
let renderComps = ['cc.CameraComponent'];
@@ -191,6 +201,7 @@ class Director extends EventTarget {
getClassByName(compName).system = this._renderSystem;
});
}
+ */
{
this._physicsSystem = new PhysicsSystem();
@@ -216,7 +227,7 @@ class Director extends EventTarget {
* !#en
* Converts a view coordinate to an WebGL coordinate
* Useful to convert (multi) touches coordinates to the current layout (portrait or landscape)
- * Implementation can be found in CCDirectorWebGL.
+ * Implementation can be found in directorWebGL.
* !#zh 将触摸点的屏幕坐标转换为 WebGL View 下的坐标。
* @method convertToGL
* @param {Vec2} uiPoint
@@ -238,7 +249,7 @@ class Director extends EventTarget {
* !#en
* Converts an OpenGL coordinate to a view coordinate
* Useful to convert node points to window points for calls such as glScissor
- * Implementation can be found in CCDirectorWebGL.
+ * Implementation can be found in directorWebGL.
* !#zh 将触摸点的 WebGL View 坐标转换为屏幕坐标。
* @method convertToUI
* @param {Vec2} glPoint
@@ -349,6 +360,9 @@ class Director extends EventTarget {
this.stopAnimation();
+ this._root.destroy();
+ this._root = null;
+
// Clear all caches
cc.loader.releaseAll();
}
@@ -424,7 +438,7 @@ class Director extends EventTarget {
this._scene = null;
// purge destroyed nodes belongs to old scene
- ccobject._deferredDestroy();
+ CCObject._deferredDestroy();
CC_BUILD && CC_DEBUG && console.timeEnd('Destroy');
if (onBeforeLoadScene) {
@@ -664,7 +678,7 @@ class Director extends EventTarget {
/**
* !#en
* Enables or disables WebGL depth test.
- * Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js
+ * Implementation can be found in directorCanvas.js/directorWebGL.js
* !#zh 启用/禁用深度测试(在 Canvas 渲染模式下不会生效)。
* @method setDepthTest
* @param {Boolean} on
@@ -680,7 +694,7 @@ class Director extends EventTarget {
/**
* !#en
* Set color for clear screen.
- * (Implementation can be found in CCDirectorCanvas.js/CCDirectorWebGL.js)
+ * (Implementation can be found in directorCanvas.js/directorWebGL.js)
* !#zh
* 设置场景的默认擦除颜色。
* 支持全透明,但不支持透明度为中间值。要支持全透明需手工开启 cc.macro.ENABLE_TRANSPARENT_CANVAS。
@@ -695,6 +709,10 @@ class Director extends EventTarget {
cc.Camera.main.backgroundColor = clearColor;
}
+ get root() {
+ return this._root;
+ }
+
/**
* !#en Returns current logic Scene.
* !#zh 获取当前逻辑场景。
@@ -896,17 +914,17 @@ class Director extends EventTarget {
// User can use this event to do things after update
this.emit(cc.Director.EVENT_AFTER_UPDATE);
// Destroy entities that have been removed recently
- ccobject._deferredDestroy();
+ CCObject._deferredDestroy();
}
- // Render
this._physicsSystem.update(this._deltaTime);
+
this.emit(cc.Director.EVENT_BEFORE_DRAW);
- this._renderSystem.update(this._deltaTime);
- // After draw
+ this._root.frameMove(this._deltaTime); // Render
this.emit(cc.Director.EVENT_AFTER_DRAW);
eventManager.frameUpdateListeners();
+ if (this._scene) { this._scene.resetHasChanged(); }
this._totalFrames++;
}
}
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 = new (...args: any[]) => T;
+
+class CallbackList {
+ public callbacks: Array = [];
+
+ public targets: Array
+ * Removes a child from the container.
+ * It will also cleanup all running actions depending on the cleanup parameter.
* If the cleanup parameter is not passed, it will force a cleanup.
* "remove" logic MUST only be on this method
* If a class wants to extend the 'removeChild' behavior it only needs
@@ -705,14 +710,14 @@ export default class BaseNode extends CCObject {
* !#zh
* 移除节点中指定的子节点,是否需要清理所有正在运行的行为取决于 cleanup 参数。
* 如果 cleanup 参数不传入,默认为 true 表示清理。
- * @method removeChild
- * @param {Node} child - The child node which will be removed.
- * @param {Boolean} [cleanup=true] - true if all running actions and callbacks on the child node will be cleanup, false otherwise.
+ * @param child - The child node which will be removed.
+ * @param [cleanup=true] - true if all running actions and callbacks on the child node
+ * will be cleanup, false otherwise.
* @example
* node.removeChild(newNode);
* node.removeChild(newNode, false);
*/
- removeChild (child, cleanup) {
+ public removeChild (child: this, cleanup?: boolean) {
if (this._children.indexOf(child) > -1) {
// If you don't do cleanup, the child's actions will not get removed and the
if (cleanup || cleanup === undefined) {
@@ -725,28 +730,31 @@ export default class BaseNode extends CCObject {
/**
* !#en
- * Removes all children from the container and do a cleanup all running actions depending on the cleanup parameter.
+ * Removes all children from the container and
+ * do a cleanup all running actions depending on the cleanup parameter.
* If the cleanup parameter is not passed, it will force a cleanup.
* !#zh
* 移除节点所有的子节点,是否需要清理所有正在运行的行为取决于 cleanup 参数。
* 如果 cleanup 参数不传入,默认为 true 表示清理。
- * @method removeAllChildren
- * @param {Boolean} [cleanup=true] - true if all running actions on all children nodes should be cleanup, false otherwise.
+ * @param [cleanup=true] - true if all running actions on all children nodes
+ * should be cleanup, false otherwise.
* @example
* node.removeAllChildren();
* node.removeAllChildren(false);
*/
- removeAllChildren (cleanup) {
+ public removeAllChildren (cleanup?: boolean) {
// not using detachChild improves speed here
- var children = this._children;
- if (cleanup === undefined)
+ const children = this._children;
+ if (cleanup === undefined) {
cleanup = true;
- for (var i = children.length - 1; i >= 0; i--) {
- var node = children[i];
+ }
+ for (let i = children.length - 1; i >= 0; i--) {
+ const node = children[i];
if (node) {
// If you don't do cleanup, the node's actions will not get removed and the
- if (cleanup)
+ if (cleanup) {
node.cleanup();
+ }
node.parent = null;
}
@@ -757,14 +765,12 @@ export default class BaseNode extends CCObject {
/**
* !#en Is this node a child of the given node?
* !#zh 是否是指定节点的子节点?
- * @method isChildOf
- * @param {Node} parent
- * @return {Boolean} - Returns true if this node is a child, deep child or identical to the given node.
+ * @return True if this node is a child, deep child or identical to the given node.
* @example
* node.isChildOf(newNode);
*/
- isChildOf (parent) {
- var child = this;
+ public isChildOf (parent: this) {
+ let child: this | null = this;
do {
if (child === parent) {
return true;
@@ -784,22 +790,29 @@ export default class BaseNode extends CCObject {
* !#zh
* 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。
* 传入参数也可以是脚本的名称。
- * @method getComponent
- * @param {Function|String} typeOrClassName
- * @return {Component | null}
* @example
* // get sprite component.
* var sprite = node.getComponent(cc.Sprite);
+ */
+ public getComponent (classConstructor: Constructor): T | null;
+
+ /**
+ * !#en
+ * Returns the component of supplied type if the node has one attached, null if it doesn't.
+ * You can also get component in the node by passing in the name of the script.
+ * !#zh
+ * 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。
+ * 传入参数也可以是脚本的名称。
+ * @example
* // get custom test calss.
* var test = node.getComponent("Test");
- * @typescript
- * getComponent(type: {prototype: T}): T
- * getComponent(className: string): any
*/
- getComponent (typeOrClassName) {
- var constructor = getConstructor(typeOrClassName);
+ public getComponent (className: string): Component | null;
+
+ public getComponent (typeOrClassName: string | Function) {
+ const constructor = getConstructor(typeOrClassName);
if (constructor) {
- return findComponent(this, constructor);
+ return BaseNode._findComponent(this, constructor);
}
return null;
}
@@ -807,20 +820,24 @@ export default class BaseNode extends CCObject {
/**
* !#en Returns all components of supplied type in the node.
* !#zh 返回节点上指定类型的所有组件。
- * @method getComponents
- * @param {Function|String} typeOrClassName
- * @return {Component[]}
* @example
* var sprites = node.getComponents(cc.Sprite);
- * var tests = node.getComponents("Test");
- * @typescript
- * getComponents(type: {prototype: T}): T[]
- * getComponents(className: string): any[]
*/
- getComponents (typeOrClassName) {
- var constructor = getConstructor(typeOrClassName), components = [];
+ public getComponents (classConstructor: Constructor): T[];
+
+ /**
+ * !#en Returns all components of supplied type in the node.
+ * !#zh 返回节点上指定类型的所有组件。
+ * @example
+ * var tests = node.getComponents("Test");
+ */
+ public getComponents (className: string): Component[];
+
+ public getComponents (typeOrClassName: string | Function) {
+ const constructor = getConstructor(typeOrClassName);
+ const components: Component[] = [];
if (constructor) {
- findComponents(this, constructor, components);
+ BaseNode._findComponents(this, constructor, components);
}
return components;
}
@@ -828,20 +845,23 @@ export default class BaseNode extends CCObject {
/**
* !#en Returns the component of supplied type in any of its children using depth first search.
* !#zh 递归查找所有子节点中第一个匹配指定类型的组件。
- * @method getComponentInChildren
- * @param {Function|String} typeOrClassName
- * @return {Component}
* @example
* var sprite = node.getComponentInChildren(cc.Sprite);
- * var Test = node.getComponentInChildren("Test");
- * @typescript
- * getComponentInChildren(type: {prototype: T}): T
- * getComponentInChildren(className: string): any
*/
- getComponentInChildren (typeOrClassName) {
- var constructor = getConstructor(typeOrClassName);
+ public getComponentInChildren (classConstructor: Constructor): T | null;
+
+ /**
+ * !#en Returns the component of supplied type in any of its children using depth first search.
+ * !#zh 递归查找所有子节点中第一个匹配指定类型的组件。
+ * @example
+ * var Test = node.getComponentInChildren("Test");
+ */
+ public getComponentInChildren (className: string): Component | null;
+
+ public getComponentInChildren (typeOrClassName: string | Function) {
+ const constructor = getConstructor(typeOrClassName);
if (constructor) {
- return findChildComponent(this._children, constructor);
+ return BaseNode._findChildComponent(this._children, constructor);
}
return null;
}
@@ -849,21 +869,25 @@ export default class BaseNode extends CCObject {
/**
* !#en Returns all components of supplied type in self or any of its children.
* !#zh 递归查找自身或所有子节点中指定类型的组件
- * @method getComponentsInChildren
- * @param {Function|String} typeOrClassName
- * @return {Component[]}
* @example
* var sprites = node.getComponentsInChildren(cc.Sprite);
- * var tests = node.getComponentsInChildren("Test");
- * @typescript
- * getComponentsInChildren(type: {prototype: T}): T[]
- * getComponentsInChildren(className: string): any[]
*/
- getComponentsInChildren (typeOrClassName) {
- var constructor = getConstructor(typeOrClassName), components = [];
+ public getComponentsInChildren (classConstructor: Constructor): T[];
+
+ /**
+ * !#en Returns all components of supplied type in self or any of its children.
+ * !#zh 递归查找自身或所有子节点中指定类型的组件
+ * @example
+ * var tests = node.getComponentsInChildren("Test");
+ */
+ public getComponentsInChildren (className: string): Component[];
+
+ public getComponentsInChildren (typeOrClassName: string | Function) {
+ const constructor = getConstructor(typeOrClassName);
+ const components: Component[] = [];
if (constructor) {
- findComponents(this, constructor, components);
- findChildComponents(this._children, constructor, components);
+ BaseNode._findComponents(this, constructor, components);
+ BaseNode._findChildComponents(this._children, constructor, components);
}
return components;
}
@@ -871,17 +895,20 @@ export default class BaseNode extends CCObject {
/**
* !#en Adds a component class to the node. You can also add component to node by passing in the name of the script.
* !#zh 向节点添加一个指定类型的组件类,你还可以通过传入脚本的名称来添加组件。
- * @method addComponent
- * @param {Function|String} typeOrClassName - The constructor or the class name of the component to add
- * @return {Component} - The newly added component
* @example
* var sprite = node.addComponent(cc.Sprite);
- * var test = node.addComponent("Test");
- * @typescript
- * addComponent(type: {new(): T}): T
- * addComponent(className: string): any
*/
- addComponent (typeOrClassName) {
+ public addComponent (classConstructor: Constructor): T | null;
+
+ /**
+ * !#en Adds a component class to the node. You can also add component to node by passing in the name of the script.
+ * !#zh 向节点添加一个指定类型的组件类,你还可以通过传入脚本的名称来添加组件。
+ * @example
+ * var test = node.addComponent("Test");
+ */
+ public addComponent (className: string): Component | null;
+
+ public addComponent (typeOrClassName: string | Function) {
if (CC_EDITOR && (this._objFlags & Destroying)) {
cc.error('isDestroying');
return null;
@@ -889,7 +916,7 @@ export default class BaseNode extends CCObject {
// get component
- var constructor;
+ let constructor;
if (typeof typeOrClassName === 'string') {
constructor = js.getClassByName(typeOrClassName);
if (!constructor) {
@@ -899,8 +926,7 @@ export default class BaseNode extends CCObject {
}
return null;
}
- }
- else {
+ } else {
if (!typeOrClassName) {
cc.errorID(3804);
return null;
@@ -920,16 +946,16 @@ export default class BaseNode extends CCObject {
}
if (CC_EDITOR && constructor._disallowMultiple) {
- if (!this._checkMultipleComp(constructor)) {
+ if (!this._checkMultipleComp!(constructor)) {
return null;
}
}
// check requirement
- var ReqComp = constructor._requireComponent;
+ const ReqComp = constructor._requireComponent;
if (ReqComp && !this.getComponent(ReqComp)) {
- var depended = this.addComponent(ReqComp);
+ const depended = this.addComponent(ReqComp);
if (!depended) {
// depend conflicts
return null;
@@ -938,13 +964,13 @@ export default class BaseNode extends CCObject {
//// check conflict
//
- //if (CC_EDITOR && !_Scene.DetectConflict.beforeAddComponent(this, constructor)) {
+ // if (CC_EDITOR && !_Scene.DetectConflict.beforeAddComponent(this, constructor)) {
// return null;
- //}
+ // }
//
- var component = new constructor();
+ const component = new constructor();
component.node = this;
this._components.push(component);
if ((CC_EDITOR || CC_TEST) && cc.engine && (this._id in cc.engine.attachedObjsForEditor)) {
@@ -964,68 +990,47 @@ export default class BaseNode extends CCObject {
* !#zh
* 删除节点上的指定组件,传入参数可以是一个组件构造函数或组件名,也可以是已经获得的组件引用。
* 如果你已经获得组件引用,你也可以直接调用 component.destroy()
- * @method removeComponent
- * @param {String|Function|Component} component - The need remove component.
* @deprecated please destroy the component to remove it.
* @example
* node.removeComponent(cc.Sprite);
- * var Test = require("Test");
- * node.removeComponent(Test);
*/
- removeComponent (component) {
+ public removeComponent (classConstructor: Constructor): void;
+
+ /**
+ * !#en
+ * Removes a component identified by the given name or removes the component object given.
+ * You can also use component.destroy() if you already have the reference.
+ * !#zh
+ * 删除节点上的指定组件,传入参数可以是一个组件构造函数或组件名,也可以是已经获得的组件引用。
+ * 如果你已经获得组件引用,你也可以直接调用 component.destroy()
+ * @deprecated please destroy the component to remove it.
+ * @example
+ * const sprite = node.getComponent(CC.Sprite);
+ * if (sprite) {
+ * node.removeComponent(sprite);
+ * }
+ * node.removeComponent('cc.Sprite');
+ */
+ public removeComponent (classNameOrInstance: string | Component): void;
+
+ public removeComponent (component: any) {
if (!component) {
cc.errorID(3813);
return;
}
- if (!(component instanceof cc.Component)) {
- component = this.getComponent(component);
+ let componentInstance: Component | null = null;
+ if (component instanceof Component) {
+ componentInstance = component;
+ } else {
+ componentInstance = this.getComponent(component);
}
- if (component) {
- component.destroy();
+ if (componentInstance) {
+ componentInstance.destroy();
}
}
- // do remove component, only used internally
- _removeComponent (component) {
- if (!component) {
- cc.errorID(3814);
- return;
- }
-
- if (!(this._objFlags & Destroying)) {
- var i = this._components.indexOf(component);
- if (i !== -1) {
- this._components.splice(i, 1);
- if ((CC_EDITOR || CC_TEST) && cc.engine) {
- delete cc.engine.attachedObjsForEditor[component._id];
- }
- }
- else if (component.node !== this) {
- cc.errorID(3815);
- }
- }
- }
-
- _disableChildComps () {
- // leave this._activeInHierarchy unmodified
- var i, len = this._components.length;
- for (i = 0; i < len; ++i) {
- var component = this._components[i];
- if (component._enabled) {
- cc.director._compScheduler.disableComp(component);
- }
- }
- // deactivate recursively
- for (i = 0, len = this._children.length; i < len; ++i) {
- var node = this._children[i];
- if (node._active) {
- node._disableChildComps();
- }
- }
- }
-
- destroy () {
- if (cc.Object.prototype.destroy.call(this)) {
+ public destroy () {
+ if (super.destroy()) {
// disable hierarchy
if (this._activeInHierarchy) {
this._disableChildComps();
@@ -1040,25 +1045,81 @@ export default class BaseNode extends CCObject {
* !#zh
* 销毁所有子节点,并释放所有它们对其它对象的引用。
* 实际销毁操作会延迟到当前帧渲染前执行。
- * @method destroyAllChildren
* @example
* node.destroyAllChildren();
*/
- destroyAllChildren () {
- var children = this._children;
- for (var i = 0; i < children.length; ++i) {
- children[i].destroy();
+ public destroyAllChildren () {
+ for (const child of this._children) {
+ child.destroy();
}
}
- cleanup () {}
- _onSetParent (/*oldParent*/) {}
- _onPostActivated () {}
- _onBatchRestored () {}
- _onBatchCreated () {}
+ public cleanup () {
+ return;
+ }
- _onHierarchyChanged (oldParent) {
- var newParent = this._parent;
+ public emit? (type: string, ...args: any[]): void;
+
+ protected _onSetParent (oldParent: this | null) {
+ if (this._parent) {
+ if ((oldParent == null || oldParent._scene !== this._parent._scene) && this._parent._scene != null) {
+ this.walk((node) => {
+ BaseNode._setScene(node);
+ });
+ }
+ }
+ }
+
+ protected _onPostActivated () {
+ return;
+ }
+
+ protected _onBatchRestored () {
+ return;
+ }
+
+ protected _onBatchCreated () {
+ return;
+ }
+
+ protected _onPreDestroy () {
+ this._onPreDestroyBase();
+ }
+
+ protected _onHierarchyChanged (oldParent: this | null) {
+ return this._onHierarchyChangedBase(oldParent);
+ }
+
+ protected _instantiate (cloned) {
+ if (!cloned) {
+ cloned = cc.instantiate._clone(this, this);
+ }
+
+ const thisPrefabInfo = this._prefab;
+ if (CC_EDITOR && thisPrefabInfo) {
+ if (this !== thisPrefabInfo.root) {
+ // var PrefabUtils = Editor.require('scene://utils/prefab');
+ // PrefabUtils.initClonedChildOfPrefab(cloned);
+ }
+ }
+ const syncing = thisPrefabInfo && this === thisPrefabInfo.root && thisPrefabInfo.sync;
+ if (syncing) {
+ // if (thisPrefabInfo._synced) {
+ // return clone;
+ // }
+ } else if (CC_EDITOR && cc.engine._isPlaying) {
+ cloned._name += ' (Clone)';
+ }
+
+ // reset and init
+ cloned._parent = null;
+ cloned._onBatchRestored();
+
+ return cloned;
+ }
+
+ private _onHierarchyChangedBase (oldParent: this | null) {
+ const newParent = this._parent;
if (this._persistNode && !(newParent instanceof cc.Scene)) {
cc.game.removePersistRootNode(this);
if (CC_EDITOR) {
@@ -1067,21 +1128,20 @@ export default class BaseNode extends CCObject {
}
if (CC_EDITOR || CC_TEST) {
- var scene = cc.director.getScene();
- var inCurrentSceneBefore = oldParent && oldParent.isChildOf(scene);
- var inCurrentSceneNow = newParent && newParent.isChildOf(scene);
+ const scene = cc.director.getScene();
+ const inCurrentSceneBefore = oldParent && oldParent.isChildOf(scene);
+ const inCurrentSceneNow = newParent && newParent.isChildOf(scene);
if (!inCurrentSceneBefore && inCurrentSceneNow) {
// attached
- this._registerIfAttached(true);
- }
- else if (inCurrentSceneBefore && !inCurrentSceneNow) {
+ this._registerIfAttached!(true);
+ } else if (inCurrentSceneBefore && !inCurrentSceneNow) {
// detached
- this._registerIfAttached(false);
+ this._registerIfAttached!(false);
}
// update prefab
- var newPrefabRoot = newParent && newParent._prefab && newParent._prefab.root;
- var myPrefabInfo = this._prefab;
+ const newPrefabRoot = newParent && newParent._prefab && newParent._prefab.root;
+ const myPrefabInfo = this._prefab;
// var PrefabUtils = Editor.require('scene://utils/prefab');
// if (myPrefabInfo) {
// if (newPrefabRoot) {
@@ -1102,77 +1162,47 @@ export default class BaseNode extends CCObject {
// }
// conflict detection
- //_Scene.DetectConflict.afterAddChild(this);
+ // _Scene.DetectConflict.afterAddChild(this);
}
- var shouldActiveNow = this._active && !!(newParent && newParent._activeInHierarchy);
+ const shouldActiveNow = this._active && !!(newParent && newParent._activeInHierarchy);
if (this._activeInHierarchy !== shouldActiveNow) {
cc.director._nodeActivator.activateNode(this, shouldActiveNow);
}
}
- _instantiate (cloned) {
- if (!cloned) {
- cloned = cc.instantiate._clone(this, this);
- }
-
- var thisPrefabInfo = this._prefab;
- if (CC_EDITOR && thisPrefabInfo) {
- if (this !== thisPrefabInfo.root) {
- //var PrefabUtils = Editor.require('scene://utils/prefab');
- //PrefabUtils.initClonedChildOfPrefab(cloned);
- }
- }
- var syncing = thisPrefabInfo && this === thisPrefabInfo.root && thisPrefabInfo.sync;
- if (syncing) {
- //if (thisPrefabInfo._synced) {
- // return clone;
- //}
- }
- else if (CC_EDITOR && cc.engine._isPlaying) {
- cloned._name += ' (Clone)';
- }
-
- // reset and init
- cloned._parent = null;
- cloned._onBatchRestored();
-
- return cloned;
- }
-
- _onPreDestroy () {
- var i, len;
-
+ private _onPreDestroyBase () {
// marked as destroying
this._objFlags |= Destroying;
// detach self and children from editor
- var parent = this._parent;
- var destroyByParent = parent && (parent._objFlags & Destroying);
+ const parent = this._parent;
+ const destroyByParent: boolean = (parent !== null) && ((parent._objFlags & Destroying) !== 0);
if (!destroyByParent && (CC_EDITOR || CC_TEST)) {
- this._registerIfAttached(false);
+ this._registerIfAttached!(false);
}
// destroy children
- var children = this._children;
- for (i = 0, len = children.length; i < len; ++i) {
+ // destroy children
+ for (const child of this._children) {
// destroy immediate so its _onPreDestroy can be called
- children[i]._destroyImmediate();
+ child._destroyImmediate();
}
// destroy self components
- for (i = 0, len = this._components.length; i < len; ++i) {
- var component = this._components[i];
+ for (const component of this._components) {
// destroy immediate so its _onPreDestroy can be called
+ // TO DO
+ // @ts-ignore
component._destroyImmediate();
}
- var eventTargets = this.__eventTargets;
- for (i = 0, len = eventTargets.length; i < len; ++i) {
- var target = eventTargets[i];
- target && target.targetOff(this);
+ for (const eventTarget of this.__eventTargets) {
+ if (eventTarget) {
+ eventTarget.targetOff(this);
+ }
}
- eventTargets.length = 0;
+ this.__eventTargets.length = 0;
// remove from persist
if (this._persistNode) {
@@ -1182,172 +1212,60 @@ export default class BaseNode extends CCObject {
if (!destroyByParent) {
// remove from parent
if (parent) {
- var childIndex = parent._children.indexOf(this);
+ const childIndex = parent._children.indexOf(this);
parent._children.splice(childIndex, 1);
- parent.emit && parent.emit('child-removed', this);
+ if (parent.emit) {
+ parent.emit('child-removed', this);
+ }
}
}
return destroyByParent;
}
-}
-BaseNode.prototype._onPreDestroyBase = BaseNode.prototype._onPreDestroy;
-BaseNode.prototype._onHierarchyChangedBase = BaseNode.prototype._onHierarchyChanged;
-
-if (CC_EDITOR) {
- BaseNode.prototype._checkMultipleComp = function (ctor) {
- var existing = this.getComponent(ctor._disallowMultiple);
- if (existing) {
- if (existing.constructor === ctor) {
- cc.errorID(3805, js.getClassName(ctor), this._name);
- }
- else {
- cc.errorID(3806, js.getClassName(ctor), this._name, js.getClassName(existing));
- }
- return false;
- }
- return true;
- };
-
- /**
- * This api should only used by undo system
- * @method _addComponentAt
- * @param {Component} comp
- * @param {Number} index
- * @private
- */
- BaseNode.prototype._addComponentAt = function (comp, index) {
- if (this._objFlags & Destroying) {
- return cc.error('isDestroying');
- }
- if (!(comp instanceof cc.Component)) {
- return cc.errorID(3811);
- }
- if (index > this._components.length) {
- return cc.errorID(3812);
+ // do remove component, only used internally
+ private _removeComponent (component: Component) {
+ if (!component) {
+ cc.errorID(3814);
+ return;
}
- // recheck attributes because script may changed
- var ctor = comp.constructor;
- if (ctor._disallowMultiple) {
- if (!this._checkMultipleComp(ctor)) {
- return;
- }
- }
- var ReqComp = ctor._requireComponent;
- if (ReqComp && !this.getComponent(ReqComp)) {
- if (index === this._components.length) {
- // If comp should be last component, increase the index because required component added
- ++index;
- }
- var depended = this.addComponent(ReqComp);
- if (!depended) {
- // depend conflicts
- return null;
- }
- }
-
- comp.node = this;
- this._components.splice(index, 0, comp);
- if ((CC_EDITOR || CC_TEST) && cc.engine && (this._id in cc.engine.attachedObjsForEditor)) {
- cc.engine.attachedObjsForEditor[comp._id] = comp;
- }
- if (this._activeInHierarchy) {
- cc.director._nodeActivator.activateComp(comp);
- }
- };
-
- /**
- * @method _getDependComponent
- * @param {Component} depended
- * @return {Component}
- * @private
- */
- BaseNode.prototype._getDependComponent = function (depended) {
- for (var i = 0; i < this._components.length; i++) {
- var comp = this._components[i];
- if (comp !== depended && comp.isValid && !cc.Object._willDestroy(comp)) {
- var depend = comp.constructor._requireComponent;
- if (depend && depended instanceof depend) {
- return comp;
+ if (!(this._objFlags & Destroying)) {
+ const i = this._components.indexOf(component);
+ if (i !== -1) {
+ this._components.splice(i, 1);
+ if ((CC_EDITOR || CC_TEST) && cc.engine) {
+ delete cc.engine.attachedObjsForEditor[component._id];
}
+ } else if ((component.node as BaseNode) !== this) {
+ cc.errorID(3815);
}
}
- return null;
- };
+ }
- BaseNode.prototype.onRestore = function () {
- // check activity state
- var shouldActiveNow = this._active && !!(this._parent && this._parent._activeInHierarchy);
- if (this._activeInHierarchy !== shouldActiveNow) {
- cc.director._nodeActivator.activateNode(this, shouldActiveNow);
+ private _disableChildComps () {
+ // leave this._activeInHierarchy unmodified
+ for (const component of this._components) {
+ if (component._enabled) {
+ cc.director._compScheduler.disableComp(component);
+ }
}
- };
-
- BaseNode.prototype._onPreDestroy = function () {
- var destroyByParent = this._onPreDestroyBase();
- if (!destroyByParent) {
- // ensure this node can reattach to scene by undo system
- // (simulate some destruct logic to make undo system work correctly)
- this._parent = null;
+ // deactivate recursively
+ for (const node of this._children) {
+ if (node._active) {
+ node._disableChildComps();
+ }
}
- return destroyByParent;
- };
+ }
- BaseNode.prototype._onRestoreBase = BaseNode.prototype.onRestore;
+ private _onSiblingIndexChanged? (siblingIndex: number): void;
+
+ private _registerIfAttached? (attached: boolean): void;
+
+ private _checkMultipleComp? (constructor: Function): boolean;
}
-if (CC_EDITOR || CC_TEST) {
- BaseNode.prototype._registerIfAttached = function (register) {
- var attachedObjsForEditor = cc.engine.attachedObjsForEditor;
- if (register) {
- attachedObjsForEditor[this._id] = this;
- for (let i = 0; i < this._components.length; i++) {
- let comp = this._components[i];
- attachedObjsForEditor[comp._id] = comp;
- }
- cc.engine.emit('node-attach-to-scene', this);
- }
- else {
- cc.engine.emit('node-detach-from-scene', this);
- delete attachedObjsForEditor[this._id];
- for (let i = 0; i < this._components.length; i++) {
- let comp = this._components[i];
- delete attachedObjsForEditor[comp._id];
- }
- }
- var children = this._children;
- for (let i = 0, len = children.length; i < len; ++i) {
- var child = children[i];
- child._registerIfAttached(register);
- }
- };
-}
-
-if (CC_DEV) {
- // promote debug info
- js.get(BaseNode.prototype, ' INFO ', function () {
- var path = '';
- var node = this;
- while (node && !(node instanceof cc.Scene)) {
- if (path) {
- path = node.name + '/' + path;
- }
- else {
- path = node.name;
- }
- node = node._parent;
- }
- return this.name + ', path: ' + path;
- });
-}
-
-BaseNode.idGenerator = idGenerator;
-
-// For walk
-BaseNode._stacks = [[]];
-BaseNode._stackId = 0;
+baseNodePolyfill(BaseNode);
/**
* !#en
diff --git a/cocos/scene-graph/component-scheduler.js b/cocos/scene-graph/component-scheduler.js
index 121d83b9df..925649e49c 100644
--- a/cocos/scene-graph/component-scheduler.js
+++ b/cocos/scene-graph/component-scheduler.js
@@ -24,7 +24,7 @@
THE SOFTWARE.
****************************************************************************/
-import CCObject from '../core/data/object';
+import { CCObject } from '../core/data/object';
import { MutableForwardIterator } from '../core/utils/array';
import { tryCatchFunctor_EDITOR } from '../core/utils/misc';
@@ -193,7 +193,7 @@ class ReusableInvoker extends LifeCycleInvoker {
}
}
}
-
+
invoke (dt) {
if (this._neg.array.length > 0) {
this._invoke(this._neg, dt);
@@ -479,4 +479,4 @@ if (CC_EDITOR) {
};
}
-export default ComponentScheduler;
\ No newline at end of file
+export default ComponentScheduler;
diff --git a/cocos/scene-graph/index.js b/cocos/scene-graph/index.js
index d3cab311db..94e05131b6 100644
--- a/cocos/scene-graph/index.js
+++ b/cocos/scene-graph/index.js
@@ -24,10 +24,10 @@
THE SOFTWARE.
****************************************************************************/
-export { default as BaseNode } from './base-node';
-export { default as Node } from './node';
+export { BaseNode } from './base-node';
+export { Node } from './node';
export { default as PrivateNode } from './private-node';
export { default as NodeActivator } from './node-activator';
export { default as Scene } from './scene';
export { default as find } from './find';
-export { default as Layers } from './layers';
+export { Layers } from './layers';
diff --git a/cocos/scene-graph/layers.js b/cocos/scene-graph/layers.ts
similarity index 50%
rename from cocos/scene-graph/layers.js
rename to cocos/scene-graph/layers.ts
index cbf668b1b3..47ac5ad384 100644
--- a/cocos/scene-graph/layers.js
+++ b/cocos/scene-graph/layers.ts
@@ -2,15 +2,27 @@
/**
* Entity layer system
*/
-class Layers {
+export class Layers {
+
+ // built-in layers, reserved up to (1 << 7)
+ public static Default = (1 << 0);
+ public static IgnoreRaycast = (1 << 1);
+ public static Gizmos = (1 << 2);
+ public static Editor = (1 << 3);
+ // masks
+ public static All = Layers.makeExclusiveMask([Layers.Gizmos, Layers.Editor]);
+ public static RaycastMask = Layers.makeExclusiveMask([Layers.Gizmos, Layers.Editor, Layers.IgnoreRaycast]);
+
/**
* Add a new layer
* @param {string} name name of the new layer
* @return {number} new layer's index
*/
- static addLayer(name) {
- if (Layers._nextAvailable > 31)
- return new Error('maximum layers reached.');
+ public static addLayer (name: string): number | undefined {
+ if (Layers._nextAvailable > 31) {
+ console.warn('maximum layers reached.');
+ return;
+ }
Layers[name] = (1 << Layers._nextAvailable++);
return Layers[name];
}
@@ -20,10 +32,11 @@ class Layers {
* @param {number[]} includes layers accepted by the mask
* @return {number} the specified layer mask
*/
- static makeInclusiveMask(includes) {
+ public static makeInclusiveMask (includes: number[]): number {
let mask = 0;
- for (let i = 0; i < includes.length; i++)
- mask |= includes[i];
+ for (const inc of includes) {
+ mask |= inc;
+ }
return mask;
}
@@ -32,7 +45,7 @@ class Layers {
* @param {number[]} excludes layers rejected by the mask
* @return {number} the specified layer mask
*/
- static makeExclusiveMask(excludes) {
+ public static makeExclusiveMask (excludes: number[]): number {
return ~Layers.makeInclusiveMask(excludes);
}
@@ -42,22 +55,11 @@ class Layers {
* @param {number} mask the testing layer mask
* @return {boolean} true if accepted
*/
- static check(layer, mask) {
- return (layer & mask) == layer;
+ public static check (layer: number, mask: number): boolean {
+ return (layer & mask) === layer;
}
+
+ private static _nextAvailable = 8;
}
-Layers._nextAvailable = 8;
-
-// built-in layers, reserved up to (1 << 7)
-Layers.Default = (1 << 0);
-Layers.IgnoreRaycast = (1 << 1);
-Layers.Gizmos = (1 << 2);
-Layers.Editor = (1 << 3);
-
-// masks
-Layers.All = Layers.makeExclusiveMask([Layers.Gizmos, Layers.Editor]);
-Layers.RaycastMask = Layers.makeExclusiveMask([Layers.Gizmos, Layers.Editor, Layers.IgnoreRaycast]);
-
-export default Layers;
cc.Layers = Layers;
diff --git a/cocos/scene-graph/node-2d.js b/cocos/scene-graph/node-2d.js
index b26011c840..1b277b416a 100644
--- a/cocos/scene-graph/node-2d.js
+++ b/cocos/scene-graph/node-2d.js
@@ -32,8 +32,9 @@ import eventManager from '../core/platform/event-manager/CCEventManager';
import macro from '../core/platform/CCMacro';
import * as js from '../core/utils/js';
import EventTarget from '../core/event/event-target';
-import BaseNode from './base-node';
+import { BaseNode } from './base-node';
import { ccclass, property } from '../core/data/class-decorator';
+import { vec3 } from '../core/vmath/index';
const Flags = cc.Object.Flags;
const Destroying = Flags.Destroying;
@@ -414,7 +415,7 @@ var _mouseWheelHandler = function (event) {
}
};
-function _searchMaskInParent (node) {
+function _searchMaskInParent(node) {
var Mask = cc.Mask;
if (Mask) {
var index = 0;
@@ -430,7 +431,7 @@ function _searchMaskInParent (node) {
return null;
}
-function _checkListeners (node, events) {
+function _checkListeners(node, events) {
if (!(node._objFlags & Destroying)) {
var i = 0;
if (node._bubblingListeners) {
@@ -452,7 +453,7 @@ function _checkListeners (node, events) {
return true;
}
-function _doDispatchEvent (owner, event) {
+function _doDispatchEvent(owner, event) {
var target, i;
event.target = owner;
@@ -522,47 +523,19 @@ if (CC_EDITOR) {
* @class Node
* @extends _BaseNode
*/
- @ccclass("cc.Node")
-export default class Node extends BaseNode {
+@ccclass("cc.NodeUI")
+export default class NodeUI extends BaseNode {
@property
- _opacity = 255;
-
- @property
- _color = cc.Color.WHITE;
-
- @property
- _contentSize = new cc.Size();
-
+ _contentSize = new cc.Size(100, 100);
@property
_anchorPoint = cc.v2(0.5, 0.5);
-
@property
- _position = cc.v3();
-
+ _lpos = cc.v3();
@property
- _scaleX = 1.0;
-
+ _lscale = cc.v3(1, 1, 1);
@property
- _scaleY = 1.0;
-
- @property
- _scale = cc.v3(1, 1, 1);
-
- @property
- _rotationX = 0.0;
-
- @property
- _rotationY = 0.0;
-
- @property
- _quat = new cc.Quat();
-
- @property
- _skewX = 0.0;
-
- @property
- _skewY = 0.0;
-
+ _lrot = cc.quat();
+ _eulerAngles = cc.v3();
@property({
serializable: false
})
@@ -571,8 +544,15 @@ export default class Node extends BaseNode {
@property
_zIndex = 0;
- @property
- _is3DNode = false;
+ // world transform
+ _pos = cc.v3();
+ _rot = cc.quat();
+ _scale = cc.v3(1, 1, 1);
+ _worldMatrix = cc.mat4();
+
+ _hasChanged = false;
+ _dirty = false;
+ _matDirty = false;
// internal properties
@@ -632,10 +612,10 @@ export default class Node extends BaseNode {
*/
@property
get x() {
- return this._position.x;
+ return this._lpos.x;
}
set x(value) {
- var localPosition = this._position;
+ var localPosition = this._lpos;
if (value !== localPosition.x) {
if (!CC_EDITOR || isFinite(value)) {
if (CC_EDITOR) {
@@ -644,12 +624,13 @@ export default class Node extends BaseNode {
localPosition.x = value;
this.setLocalDirty(LocalDirtyFlag.POSITION);
-
+ // this._renderFlag |= RenderFlow.FLAG_WORLD_TRANSFORM;
+
// fast check event
if (this._eventMask & POSITION_ON) {
// send event
if (CC_EDITOR) {
- this.emit(EventType.POSITION_CHANGED, new cc.Vec2(oldValue, localPosition.y));
+ this.emit(EventType.POSITION_CHANGED, new cc.Vec3(oldValue, localPosition.y, localPosition.z));
}
else {
this.emit(EventType.POSITION_CHANGED);
@@ -673,10 +654,10 @@ export default class Node extends BaseNode {
*/
@property
get y() {
- return this._position.y;
+ return this._lpos.y;
}
set y(value) {
- var localPosition = this._position;
+ var localPosition = this._lpos;
if (value !== localPosition.y) {
if (!CC_EDITOR || isFinite(value)) {
if (CC_EDITOR) {
@@ -685,12 +666,13 @@ export default class Node extends BaseNode {
localPosition.y = value;
this.setLocalDirty(LocalDirtyFlag.POSITION);
+ // this._renderFlag |= RenderFlow.FLAG_WORLD_TRANSFORM;
// fast check event
if (this._eventMask & POSITION_ON) {
// send event
if (CC_EDITOR) {
- this.emit(EventType.POSITION_CHANGED, new cc.Vec2(localPosition.x, oldValue));
+ this.emit(EventType.POSITION_CHANGED, new cc.Vec3(localPosition.x, oldValue, localPosition.z));
}
else {
this.emit(EventType.POSITION_CHANGED);
@@ -702,13 +684,13 @@ export default class Node extends BaseNode {
}
}
}
-
+
@property
get z() {
- return this._position.z;
+ return this._lpos.z;
}
set z(value) {
- var localPosition = this._position;
+ var localPosition = this._lpos;
if (value !== localPosition.z) {
if (!CC_EDITOR || isFinite(value)) {
localPosition.z = value;
@@ -735,37 +717,35 @@ export default class Node extends BaseNode {
*/
@property
get rotation() {
- return this._rotationX;
+ // return this._rotationX;
+ return -this.eulerAngles;
}
set rotation(value) {
- if (this._rotationX !== value || this._rotationY !== value) {
- this._rotationX = this._rotationY = value;
- // Update quaternion from rotation
- math.quat.fromEuler(this._quat, 0, 0, -value);
- this.setLocalDirty(LocalDirtyFlag.ROTATION);
-
- if (this._eventMask & ROTATION_ON) {
- this.emit(EventType.ROTATION_CHANGED);
- }
- }
+ this.eulerAngles = -value;
}
/**
- * !#en The rotation as Euler angles in degrees, used in 2.5D project.
- * !#zh 该节点的欧拉角度,用于 2.5D 项目。
+ * !#en
+ * Angle of node, the positive value is anti-clockwise direction.
+ * !#zh
+ * 该节点的旋转角度,正值为逆时针方向。
* @property eulerAngles
- * @type {Vec3}
+ * @type {Number}
*/
@property
get eulerAngles() {
- return cc.v3(this._rotationX, this._rotationY, this._rotationZ);
+ return this._eulerAngles.z;
}
- set eulerAngles(v) {
- this._rotationX = v.x;
- this._rotationY = v.y;
- this._rotationZ = v.z;
- math.quat.fromEuler(this._quat, v.x, v.y, v.z);
+
+ set eulerAngles(value) {
+ math.vec3.set(this._eulerAngles, 0, 0, value);
+ this._fromEuler();
this.setLocalDirty(LocalDirtyFlag.ROTATION);
+ // this._renderFlag |= RenderFlow.FLAG_TRANSFORM;
+
+ if (this._eventMask & ROTATION_ON) {
+ this.emit(EventType.ROTATION_CHANGED);
+ }
}
/**
@@ -779,19 +759,20 @@ export default class Node extends BaseNode {
*/
@property
get rotationX() {
- return this._rotationX;
+ return this._eulerAngles.x;
}
set rotationX(value) {
- if (this._rotationX !== value) {
- this._rotationX = value;
+ if (this._eulerAngles.x !== value) {
+ this._eulerAngles.x = value;
// Update quaternion from rotation
- if (this._rotationX === this._rotationY) {
- math.quat.fromEuler(this._quat, 0, 0, -value);
+ if (this._eulerAngles.x === this._eulerAngles.y) {
+ math.quat.fromEuler(this._lrot, 0, 0, -value);
}
else {
- math.quat.fromEuler(this._quat, value, this._rotationY, 0);
+ math.quat.fromEuler(this._lrot, value, this._eulerAngles.y, 0);
}
this.setLocalDirty(LocalDirtyFlag.ROTATION);
+ // this._renderFlag |= RenderFlow.FLAG_TRANSFORM;
if (this._eventMask & ROTATION_ON) {
this.emit(EventType.ROTATION_CHANGED);
@@ -810,19 +791,20 @@ export default class Node extends BaseNode {
*/
@property
get rotationY() {
- return this._rotationY;
+ return this._eulerAngles.y;
}
set rotationY(value) {
- if (this._rotationY !== value) {
- this._rotationY = value;
+ if (this._eulerAngles.y !== value) {
+ this._eulerAngles.y = value;
// Update quaternion from rotation
- if (this._rotationX === this._rotationY) {
- math.quat.fromEuler(this._quat, 0, 0, -value);
+ if (this._eulerAngles.x === this._eulerAngles.y) {
+ math.quat.fromEuler(this._lrot, 0, 0, -value);
}
else {
- math.quat.fromEuler(this._quat, this._rotationX, value, 0);
+ math.quat.fromEuler(this._lrot, this._eulerAngles.x, value, 0);
}
this.setLocalDirty(LocalDirtyFlag.ROTATION);
+ // this._renderFlag |= RenderFlow.FLAG_TRANSFORM;
if (this._eventMask & ROTATION_ON) {
this.emit(EventType.ROTATION_CHANGED);
@@ -850,12 +832,13 @@ export default class Node extends BaseNode {
*/
@property
get scaleX() {
- return this._scale.x;
+ return this._lscale.x;
}
set scaleX(value) {
- if (this._scale.x !== value) {
- this._scale.x = value;
+ if (this._lscale.x !== value) {
+ this._lscale.x = value;
this.setLocalDirty(LocalDirtyFlag.SCALE);
+ // this._renderFlag |= RenderFlow.FLAG_TRANSFORM;
if (this._eventMask & SCALE_ON) {
this.emit(EventType.SCALE_CHANGED);
@@ -872,14 +855,15 @@ export default class Node extends BaseNode {
* node.scaleY = 0.5;
* cc.log("Node Scale Y: " + node.scaleY);
*/
- @property
+
get scaleY() {
- return this._scale.y;
+ return this._lscale.y;
}
set scaleY(value) {
- if (this._scale.y !== value) {
- this._scale.y = value;
+ if (this._lscale.y !== value) {
+ this._lscale.y = value;
this.setLocalDirty(LocalDirtyFlag.SCALE);
+ // this._renderFlag |= RenderFlow.FLAG_TRANSFORM;
if (this._eventMask & SCALE_ON) {
this.emit(EventType.SCALE_CHANGED);
@@ -896,14 +880,14 @@ export default class Node extends BaseNode {
* node.skewX = 0;
* cc.log("Node SkewX: " + node.skewX);
*/
- @property
- get skewX() {
- return this._skewX;
- }
- set skewX(value) {
- this._skewX = value;
- this.setLocalDirty(LocalDirtyFlag.SKEW);
- }
+ // @property
+ // get skewX() {
+ // return this._skewX;
+ // }
+ // set skewX(value) {
+ // this._skewX = value;
+ // this.setLocalDirty(LocalDirtyFlag.SKEW);
+ // }
/**
* !#en Skew y
@@ -914,14 +898,14 @@ export default class Node extends BaseNode {
* node.skewY = 0;
* cc.log("Node SkewY: " + node.skewY);
*/
- @property
- get skewY() {
- return this._skewY;
- }
- set skewY(value) {
- this._skewY = value;
- this.setLocalDirty(LocalDirtyFlag.SKEW);
- }
+ // @property
+ // get skewY() {
+ // return this._skewY;
+ // }
+ // set skewY(value) {
+ // this._skewY = value;
+ // this.setLocalDirty(LocalDirtyFlag.SKEW);
+ // }
/**
* !#en Opacity of node, default value is 255.
@@ -931,17 +915,17 @@ export default class Node extends BaseNode {
* @example
* node.opacity = 255;
*/
- @property({
- range: [0, 255, 1]
- })
- get opacity() {
- return this._opacity;
- }
- set opacity(value) {
- if (this._opacity !== value) {
- this._opacity = value;
- }
- }
+ // @property({
+ // range: [0, 255, 1]
+ // })
+ // get opacity() {
+ // return this._opacity;
+ // }
+ // set opacity(value) {
+ // if (this._opacity !== value) {
+ // this._opacity = value;
+ // }
+ // }
/**
* !#en Color of node, default value is white: (255, 255, 255).
@@ -951,18 +935,18 @@ export default class Node extends BaseNode {
* @example
* node.color = new cc.Color(255, 255, 255);
*/
- @property
- get color() {
- return this._color.clone();
- }
- set color(value) {
- if (!this._color.equals(value)) {
- this._color.set(value);
- if (CC_DEV && value.a !== 255) {
- cc.warnID(1626);
- }
- }
- }
+ // @property
+ // get color() {
+ // return this._color.clone();
+ // }
+ // set color(value) {
+ // if (!this._color.equals(value)) {
+ // this._color.set(value);
+ // if (CC_DEV && value.a !== 255) {
+ // cc.warnID(1626);
+ // }
+ // }
+ // }
/**
* !#en Anchor point's position on x axis.
@@ -1114,7 +1098,7 @@ export default class Node extends BaseNode {
static BuiltinGroupIndex = BuiltinGroupIndex;
// is node but not scene
- static isNode (obj) {
+ static isNode(obj) {
return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene));
}
@@ -1123,10 +1107,10 @@ export default class Node extends BaseNode {
* @method constructor
* @param {String} [name]
*/
- constructor (name) {
+ constructor(name) {
super(name);
this._reorderChildDirty = false;
-
+
// cache component
this._widget = null;
// fast render component access
@@ -1140,24 +1124,25 @@ export default class Node extends BaseNode {
this._mouseListener = null;
// default scale
- this._scale.x = 1;
- this._scale.y = 1;
- this._scale.z = 1;
+ this._lscale.x = 1;
+ this._lscale.y = 1;
+ this._lscale.z = 1;
this._matrix = _mat4Pool.get();
this._worldMatrix = _mat4Pool.get();
this._localMatDirty = LocalDirtyFlag.ALL;
this._worldMatDirty = true;
+
this._eventMask = 0;
this._cullingMask = 1 << this.groupIndex;
- this._rotationZ = 0;
+ // this._rotationZ = 0;
}
// OVERRIDES
- _onSiblingIndexChanged (/*index*/) {
+ _onSiblingIndexChanged(/*index*/) {
// update rendering scene graph, sort them by arrivalOrder
var parent = this._parent;
var siblings = parent._children;
@@ -1170,7 +1155,7 @@ export default class Node extends BaseNode {
parent._delaySort();
}
- _onPreDestroy () {
+ _onPreDestroy() {
var destroyByParent = this._onPreDestroyBase();
// Actions
@@ -1216,7 +1201,7 @@ export default class Node extends BaseNode {
}
}
- _onPostActivated (active) {
+ _onPostActivated(active) {
var actionManager = ActionManagerExist ? cc.director.getActionManager() : null;
if (active) {
// ActionManager & EventManager
@@ -1239,30 +1224,38 @@ export default class Node extends BaseNode {
}
}
- _onHierarchyChanged (oldParent) {
- this._updateOrderOfArrival();
- if (this._parent) {
- this._parent._delaySort();
- }
- this._onHierarchyChangedBase(oldParent);
- if (cc._widgetManager) {
- cc._widgetManager._nodesOrderDirty = true;
- }
- }
+ // _onHierarchyChanged(oldParent) {
+ // this._updateOrderOfArrival();
+ // if (this._parent) {
+ // this._parent._delaySort();
+ // }
+ // this._onHierarchyChangedBase(oldParent);
+ // if (cc._widgetManager) {
+ // cc._widgetManager._nodesOrderDirty = true;
+ // }
+ // }
// INTERNAL
- _upgrade_1x_to_2x () {
+ _toEuler() {
+ math.quat.toEuler(this._eulerAngles, this._lrot);
+ }
+
+ _fromEuler() {
+ math.quat.fromEuler(this._lrot, this._eulerAngles.x, this._eulerAngles.y, this._eulerAngles.z);
+ }
+
+ _upgrade_1x_to_2x() {
// Upgrade scaleX, scaleY from v1.x
// TODO: remove in future version, 3.0 ?
- if (this._scaleX !== undefined) {
- this._scale.x = this._scaleX;
- this._scaleX = undefined;
- }
- if (this._scaleY !== undefined) {
- this._scale.y = this._scaleY;
- this._scaleY = undefined;
- }
+ // if (this._scaleX !== undefined) {
+ // this._lscale.x = this._scaleX;
+ // this._scaleX = undefined;
+ // }
+ // if (this._scaleY !== undefined) {
+ // this._lscale.y = this._scaleY;
+ // this._scaleY = undefined;
+ // }
if (this._localZOrder !== 0) {
this._zIndex = (this._localZOrder & 0xffff0000) >> 16;
@@ -1271,39 +1264,32 @@ export default class Node extends BaseNode {
// TODO: remove _rotationX & _rotationY in future version, 3.0 ?
// Update quaternion from rotation, when upgrade from 1.x to 2.0
// If rotation x & y is 0 in old version, then update rotation from default quaternion is ok too
- if (this._rotationX !== 0 || this._rotationY !== 0) {
+ let quat = this._lrot;
+ if ((this._rotationX || this._rotationY) &&
+ (quat.x === 0 && quat.y === 0 && quat.z === 0 && quat.w === 1)) {
if (this._rotationX === this._rotationY) {
- math.quat.fromEuler(this._quat, 0, 0, -this._rotationX);
+ math.quat.fromEuler(quat, 0, 0, -this._rotationX);
}
else {
- math.quat.fromEuler(this._quat, this._rotationX, this._rotationY, 0);
- }
- }
- // Update rotation from quaternion
- else {
- let rotx = this._quat.getRoll();
- let roty = this._quat.getPitch();
- if (rotx === 0 && roty === 0) {
- this._rotationX = this._rotationY = -this._quat.getYaw();
- }
- else {
- this._rotationX = rotx;
- this._rotationY = roty;
+ math.quat.fromEuler(quat, this._rotationX, this._rotationY, 0);
}
+ this._rotationX = this._rotationY = undefined;
}
+ this._toEuler();
+
// Upgrade from 2.0.0 preview 4 & earlier versions
// TODO: Remove after final version
- if (this._color.a < 255 && this._opacity === 255) {
- this._opacity = this._color.a;
- this._color.a = 255;
- }
+ // if (this._color.a < 255 && this._opacity === 255) {
+ // this._opacity = this._color.a;
+ // this._color.a = 255;
+ // }
}
/*
* The initializer for Node which will be called before all components onLoad
*/
- _onBatchCreated () {
+ _onBatchCreated() {
this._upgrade_1x_to_2x();
this._updateOrderOfArrival();
@@ -1329,15 +1315,19 @@ export default class Node extends BaseNode {
for (let i = 0, len = children.length; i < len; i++) {
children[i]._onBatchCreated();
}
+
+ // if (children.length > 0) {
+ // this._renderFlag |= RenderFlow.FLAG_CHILDREN;
+ // }
}
// the same as _onBatchCreated but untouch prefab
- _onBatchRestored () {
+ _onBatchRestored() {
this._upgrade_1x_to_2x();
if (!this._activeInHierarchy) {
// deactivate ActionManager and EventManager by default
-
+
// ActionManager may not be inited in the editor worker.
let manager = cc.director.getActionManager();
manager && manager.pauseTarget(this);
@@ -1349,11 +1339,15 @@ export default class Node extends BaseNode {
for (var i = 0, len = children.length; i < len; i++) {
children[i]._onBatchRestored();
}
+
+ // if (children.length > 0) {
+ // this._renderFlag |= RenderFlow.FLAG_CHILDREN;
+ // }
}
// EVENT TARGET
- _checknSetupSysEvent (type) {
+ _checknSetupSysEvent(type) {
let newAdded = false;
let forDispatch = false;
if (_touchEvents.indexOf(type) !== -1) {
@@ -1445,7 +1439,7 @@ export default class Node extends BaseNode {
* node.on(cc.Node.EventType.TOUCH_CANCEL, callback, this);
* node.on(cc.Node.EventType.ANCHOR_CHANGED, callback);
*/
- on (type, callback, target, useCapture) {
+ on(type, callback, target, useCapture) {
let forDispatch = this._checknSetupSysEvent(type);
if (forDispatch) {
return this._onDispatch(type, callback, target, useCapture);
@@ -1453,20 +1447,20 @@ export default class Node extends BaseNode {
else {
switch (type) {
case EventType.POSITION_CHANGED:
- this._eventMask |= POSITION_ON;
- break;
+ this._eventMask |= POSITION_ON;
+ break;
case EventType.SCALE_CHANGED:
- this._eventMask |= SCALE_ON;
- break;
+ this._eventMask |= SCALE_ON;
+ break;
case EventType.ROTATION_CHANGED:
- this._eventMask |= ROTATION_ON;
- break;
+ this._eventMask |= ROTATION_ON;
+ break;
case EventType.SIZE_CHANGED:
- this._eventMask |= SIZE_ON;
- break;
+ this._eventMask |= SIZE_ON;
+ break;
case EventType.ANCHOR_CHANGED:
- this._eventMask |= ANCHOR_ON;
- break;
+ this._eventMask |= ANCHOR_ON;
+ break;
}
if (!this._bubblingListeners) {
this._bubblingListeners = new EventTarget();
@@ -1497,7 +1491,7 @@ export default class Node extends BaseNode {
* @example
* node.once(cc.Node.EventType.ANCHOR_CHANGED, callback);
*/
- once (type, callback, target, useCapture) {
+ once(type, callback, target, useCapture) {
let forDispatch = this._checknSetupSysEvent(type);
let eventType_hasOnceListener = '__ONCE_FLAG:' + type;
@@ -1522,7 +1516,7 @@ export default class Node extends BaseNode {
}
}
- _onDispatch (type, callback, target, useCapture) {
+ _onDispatch(type, callback, target, useCapture) {
// Accept also patameters like: (type, callback, useCapture)
if (typeof target === 'boolean') {
useCapture = target;
@@ -1542,7 +1536,7 @@ export default class Node extends BaseNode {
listeners = this._bubblingListeners = this._bubblingListeners || new EventTarget();
}
- if ( !listeners.hasEventListener(type, callback, target) ) {
+ if (!listeners.hasEventListener(type, callback, target)) {
listeners.add(type, callback, target);
if (target && target.__eventTargets)
@@ -1567,7 +1561,7 @@ export default class Node extends BaseNode {
* node.off(cc.Node.EventType.TOUCH_START, callback, this.node);
* node.off(cc.Node.EventType.ANCHOR_CHANGED, callback, this);
*/
- off (type, callback, target, useCapture) {
+ off(type, callback, target, useCapture) {
let touchEvent = _touchEvents.indexOf(type) !== -1;
let mouseEvent = !touchEvent && _mouseEvents.indexOf(type) !== -1;
if (touchEvent || mouseEvent) {
@@ -1594,26 +1588,26 @@ export default class Node extends BaseNode {
if (!hasListeners) {
switch (type) {
case EventType.POSITION_CHANGED:
- this._eventMask &= ~POSITION_ON;
- break;
+ this._eventMask &= ~POSITION_ON;
+ break;
case EventType.SCALE_CHANGED:
- this._eventMask &= ~SCALE_ON;
- break;
+ this._eventMask &= ~SCALE_ON;
+ break;
case EventType.ROTATION_CHANGED:
- this._eventMask &= ~ROTATION_ON;
- break;
+ this._eventMask &= ~ROTATION_ON;
+ break;
case EventType.SIZE_CHANGED:
- this._eventMask &= ~SIZE_ON;
- break;
+ this._eventMask &= ~SIZE_ON;
+ break;
case EventType.ANCHOR_CHANGED:
- this._eventMask &= ~ANCHOR_ON;
- break;
+ this._eventMask &= ~ANCHOR_ON;
+ break;
}
}
}
}
- _offDispatch (type, callback, target, useCapture) {
+ _offDispatch(type, callback, target, useCapture) {
// Accept also patameters like: (type, callback, useCapture)
if (typeof target === 'boolean') {
useCapture = target;
@@ -1628,12 +1622,12 @@ export default class Node extends BaseNode {
var listeners = useCapture ? this._capturingListeners : this._bubblingListeners;
if (listeners) {
listeners.remove(type, callback, target);
-
+
if (target && target.__eventTargets) {
js.array.fastRemove(target.__eventTargets, this);
}
}
-
+
}
}
@@ -1645,7 +1639,7 @@ export default class Node extends BaseNode {
* @example
* node.targetOff(target);
*/
- targetOff (target) {
+ targetOff(target) {
let listeners = this._bubblingListeners;
if (listeners) {
listeners.targetOff(target);
@@ -1688,7 +1682,7 @@ export default class Node extends BaseNode {
* @param {String} type - The type of event.
* @return {Boolean} True if a callback of the specified type is registered; false otherwise.
*/
- hasEventListener (type) {
+ hasEventListener(type) {
let has = false;
if (this._bubblingListeners) {
has = this._bubblingListeners.hasEventListener(type);
@@ -1713,11 +1707,11 @@ export default class Node extends BaseNode {
* @param {*} [arg4] - Fourth argument in callback
* @param {*} [arg5] - Fifth argument in callback
* @example
- *
+ *
* eventTarget.emit('fire', event);
* eventTarget.emit('fire', message, emitter);
*/
- emit (type, arg1, arg2, arg3, arg4, arg5) {
+ emit(type, arg1, arg2, arg3, arg4, arg5) {
if (this._bubblingListeners) {
this._bubblingListeners.emit(type, arg1, arg2, arg3, arg4, arg5);
}
@@ -1732,7 +1726,7 @@ export default class Node extends BaseNode {
* @method dispatchEvent
* @param {Event} event - The Event object that is dispatched into the event flow
*/
- dispatchEvent (event) {
+ dispatchEvent(event) {
_doDispatchEvent(this, event);
_cachedArray.length = 0;
}
@@ -1749,7 +1743,7 @@ export default class Node extends BaseNode {
* @example
* node.pauseSystemEvents(true);
*/
- pauseSystemEvents (recursive) {
+ pauseSystemEvents(recursive) {
eventManager.pauseTarget(this, recursive);
}
@@ -1765,24 +1759,50 @@ export default class Node extends BaseNode {
* @example
* node.resumeSystemEvents(true);
*/
- resumeSystemEvents (recursive) {
+ resumeSystemEvents(recursive) {
eventManager.resumeTarget(this, recursive);
}
- _hitTest (point, listener) {
+ _hitTest(point, listener) {
let w = this._contentSize.width,
h = this._contentSize.height,
cameraPt = _vec2a,
testPt = _vec2b;
-
- let camera = cc.Camera.findCamera(this);
- if (camera) {
- camera.getCameraToWorldPoint(point, cameraPt);
+
+ let renderComp = this.getComponent(cc.RenderComponent);
+ if (!renderComp) {
+ return false;
}
- else {
- cameraPt.set(point);
+ let canvas = cc.CanvasComponent.findView(renderComp);
+ if (!canvas) {
+ return;
}
+ canvas.node.getWorldRT(_mat4_temp);
+
+ let m12 = _mat4_temp.m12;
+ let m13 = _mat4_temp.m13;
+
+ let 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._updateWorldMatrix();
math.mat4.invert(_mat4_temp, this._worldMatrix);
math.vec2.transformMat4(testPt, cameraPt, _mat4_temp);
@@ -1825,7 +1845,7 @@ export default class Node extends BaseNode {
* @param {Array} array - the array to receive targets
* @example {@link cocos2d/core/event/_getCapturingTargets.js}
*/
- _getCapturingTargets (type, array) {
+ _getCapturingTargets(type, array) {
var parent = this.parent;
while (parent) {
if (parent._capturingListeners && parent._capturingListeners.hasEventListener(type)) {
@@ -1834,7 +1854,7 @@ export default class Node extends BaseNode {
parent = parent.parent;
}
}
-
+
/**
* Get all the targets listening to the supplied type of event in the target's bubbling phase.
* The bubbling phase comprises any SUBSEQUENT nodes encountered on the return trip to the root of the tree.
@@ -1846,7 +1866,7 @@ export default class Node extends BaseNode {
* @param {String} type - the event type
* @param {Array} array - the array to receive targets
*/
- _getBubblingTargets (type, array) {
+ _getBubblingTargets(type, array) {
var parent = this.parent;
while (parent) {
if (parent._bubblingListeners && parent._bubblingListeners.hasEventListener(type)) {
@@ -1856,7 +1876,7 @@ export default class Node extends BaseNode {
}
}
-// TRANSFORM RELATED
+ // TRANSFORM RELATED
/**
* !#en Returns a copy of the position (x, y) of the node in its parent's coordinates.
* !#zh 获取节点在父节点坐标系中的位置(x, y)。
@@ -1865,8 +1885,8 @@ export default class Node extends BaseNode {
* @example
* cc.log("Node Position: " + node.getPosition());
*/
- getPosition () {
- return new cc.Vec2(this._position);
+ getPosition() {
+ return new cc.Vec2(this._lpos);
}
/**
@@ -1884,7 +1904,7 @@ export default class Node extends BaseNode {
* @param {Number} [y] - Y coordinate for position
* @example {@link cocos2d/core/utils/base-node/setPosition.js}
*/
- setPosition (newPosOrX, y) {
+ setPosition(newPosOrX, y) {
var x;
if (y === undefined) {
x = newPosOrX.x;
@@ -1894,7 +1914,7 @@ export default class Node extends BaseNode {
x = newPosOrX;
}
- var locPosition = this._position;
+ var locPosition = this._lpos;
if (locPosition.x === x && locPosition.y === y) {
return;
}
@@ -1911,7 +1931,7 @@ export default class Node extends BaseNode {
if (!CC_EDITOR || isFinite(y)) {
locPosition.y = y;
}
- else {
+ else {
return cc.error(ERR_INVALID_NUMBER, 'y of new position');
}
this.setLocalDirty(LocalDirtyFlag.POSITION);
@@ -1938,10 +1958,10 @@ export default class Node extends BaseNode {
* @example
* cc.log("Node Scale: " + node.getScale());
*/
- getScale () {
- if (this._scale.x !== this._scale.y)
+ getScale() {
+ if (this._lscale.x !== this._lscale.y)
cc.logID(1603);
- return this._scale.x;
+ return this._lscale.x;
}
/**
@@ -1954,7 +1974,7 @@ export default class Node extends BaseNode {
* node.setScale(cc.v2(1, 1));
* node.setScale(1);
*/
- setScale (x, y) {
+ setScale(x, y) {
if (x && typeof x !== 'number') {
y = x.y;
x = x.x;
@@ -1962,9 +1982,9 @@ export default class Node extends BaseNode {
else if (y === undefined) {
y = x;
}
- if (this._scale.x !== x || this._scale.y !== y) {
- this._scale.x = x;
- this._scale.y = y;
+ if (this._lscale.x !== x || this._lscale.y !== y) {
+ this._lscale.x = x;
+ this._lscale.y = y;
this.setLocalDirty(LocalDirtyFlag.SCALE);
if (this._eventMask & SCALE_ON) {
@@ -1998,7 +2018,7 @@ export default class Node extends BaseNode {
* @example
* cc.log("Content Size: " + node.getContentSize());
*/
- getContentSize () {
+ getContentSize() {
return cc.size(this._contentSize.width, this._contentSize.height);
}
@@ -2015,7 +2035,7 @@ export default class Node extends BaseNode {
* node.setContentSize(cc.size(100, 100));
* node.setContentSize(100, 100);
*/
- setContentSize (size, height) {
+ setContentSize(size, height) {
var locContentSize = this._contentSize;
var clone;
if (height === undefined) {
@@ -2065,7 +2085,7 @@ export default class Node extends BaseNode {
* @example
* cc.log("Node AnchorPoint: " + node.getAnchorPoint());
*/
- getAnchorPoint () {
+ getAnchorPoint() {
return cc.v2(this._anchorPoint);
}
@@ -2091,7 +2111,7 @@ export default class Node extends BaseNode {
* node.setAnchorPoint(cc.v2(1, 1));
* node.setAnchorPoint(1, 1);
*/
- setAnchorPoint (point, y) {
+ setAnchorPoint(point, y) {
var locAnchorPoint = this._anchorPoint;
if (y === undefined) {
if ((point.x === locAnchorPoint.x) && (point.y === locAnchorPoint.y))
@@ -2116,7 +2136,7 @@ export default class Node extends BaseNode {
* @param {Vec3} out
* @param {Vec3} vec3
*/
- _invTransformPoint (out, pos) {
+ _invTransformPoint(out, pos) {
if (this._parent) {
this._parent._invTransformPoint(out, pos);
} else {
@@ -2124,36 +2144,36 @@ export default class Node extends BaseNode {
}
// out = parent_inv_pos - pos
- math.vec3.sub(out, out, this._position);
+ math.vec3.sub(out, out, this._lpos);
// out = inv(rot) * out
- math.quat.conjugate(_quat_temp, this._quat);
+ math.quat.conjugate(_quat_temp, this._lrot);
math.vec3.transformQuat(out, out, _quat_temp);
// out = (1/scale) * out
- math.vec3.inverseSafe(_vec3_temp, this._scale);
+ math.vec3.inverseSafe(_vec3_temp, this._lscale);
math.vec3.mul(out, out, _vec3_temp);
return out;
}
-
+
/*
* Calculate and return world position.
* This is not a public API yet, its usage could be updated
- * @method getWorldPos
+ * @method getWorldPosition
* @param {Vec3} out
* @return {Vec3}
*/
- getWorldPos (out) {
- math.vec3.copy(out, this._position);
+ getWorldPosition(out) {
+ math.vec3.copy(out, this._lpos);
let curr = this._parent;
while (curr) {
- // out = parent_scale * pos
- math.vec3.mul(out, out, curr._scale);
+ // out = parent_lscale * pos
+ math.vec3.mul(out, out, curr._lscale);
// out = parent_quat * out
- math.vec3.transformQuat(out, out, curr._quat);
+ math.vec3.transformQuat(out, out, curr._lrot);
// out = out + pos
- math.vec3.add(out, out, curr._position);
+ math.vec3.add(out, out, curr._lpos);
curr = curr._parent;
}
return out;
@@ -2162,16 +2182,16 @@ export default class Node extends BaseNode {
/*
* Set world position.
* This is not a public API yet, its usage could be updated
- * @method setWorldPos
+ * @method setWorldPosition
* @param {vec3} pos
*/
- setWorldPos (pos) {
+ setWorldPosition(pos) {
// NOTE: this is faster than invert world matrix and transform the point
if (this._parent) {
- this._parent._invTransformPoint(this._position, pos);
+ this._parent._invTransformPoint(this._lpos, pos);
}
else {
- math.vec3.copy(this._position, pos);
+ math.vec3.copy(this._lpos, pos);
}
this.setLocalDirty(LocalDirtyFlag.POSITION);
@@ -2190,15 +2210,15 @@ export default class Node extends BaseNode {
/*
* Calculate and return world rotation
* This is not a public API yet, its usage could be updated
- * @method getWorldRot
+ * @method getWorldRotation
* @param {Quat} out
* @return {Quat}
*/
- getWorldRot (out) {
- math.quat.copy(out, this._quat);
+ getWorldRotation(out) {
+ math.quat.copy(out, this._lrot);
let curr = this._parent;
while (curr) {
- math.quat.mul(out, curr._quat, out);
+ math.quat.mul(out, curr._lrot, out);
curr = curr._parent;
}
return out;
@@ -2207,41 +2227,40 @@ export default class Node extends BaseNode {
/*
* Set world rotation with quaternion
* This is not a public API yet, its usage could be updated
- * @method setWorldRot
+ * @method setWorldRotation
* @param {Quat} rot
*/
- setWorldRot (quat) {
+ setWorldRotation(quat) {
if (this._parent) {
- this._parent.getWorldRot(this._quat);
- math.quat.conjugate(this._quat, this._quat);
- math.quat.mul(this._quat, this._quat, quat);
+ this._parent.getWorldRotation(this._lrot);
+ math.quat.conjugate(this._lrot, this._lrot);
+ math.quat.mul(this._lrot, this._lrot, quat);
}
else {
- math.quat.copy(this._quat, quat);
+ math.quat.copy(this._lrot, quat);
}
this.setLocalDirty(LocalDirtyFlag.ROTATION);
}
- getWorldRT (out) {
+ getWorldRT(out) {
let opos = _vec3_temp;
let orot = _quat_temp;
- math.vec3.copy(opos, this._position);
- math.quat.copy(orot, this._quat);
+ math.vec3.copy(opos, this._lpos);
+ math.quat.copy(orot, this._lrot);
let curr = this._parent;
while (curr) {
// opos = parent_lscale * lpos
math.vec3.mul(opos, opos, curr._scale);
// opos = parent_lrot * opos
- math.vec3.transformQuat(opos, opos, curr._quat);
+ math.vec3.transformQuat(opos, opos, curr._lrot);
// opos = opos + lpos
- math.vec3.add(opos, opos, curr._position);
+ math.vec3.add(opos, opos, curr._lpos);
// orot = lrot * orot
- math.quat.mul(orot, curr._quat, orot);
+ math.quat.mul(orot, curr._lrot, orot);
curr = curr._parent;
}
math.mat4.fromRT(out, orot, opos);
- return out;
}
/**
@@ -2251,29 +2270,51 @@ export default class Node extends BaseNode {
* @param {Vec3} pos
* @param {Vec3} [up] - default is (0,1,0)
*/
- lookAt (pos, up) {
- this.getWorldPos(_vec3_temp);
+ lookAt(pos, up) {
+ this.getWorldPosition(_vec3_temp);
math.vec3.sub(_vec3_temp, _vec3_temp, pos); // NOTE: we use -z for view-dir
math.vec3.normalize(_vec3_temp, _vec3_temp);
math.quat.fromViewUp(_quat_temp, _vec3_temp, up);
-
- this.setWorldRot(_quat_temp);
+
+ this.setWorldRotation(_quat_temp);
}
- _updateLocalMatrix () {
+ resetHasChanged() {
+ this._hasChanged = false;
+ let len = this._children.length;
+ for (let i = 0; i < len; ++i) {
+ this._children[i].resetHasChanged();
+ }
+ }
+
+ /**
+ * invalidate the world transform information
+ * for this node and all its children recursively
+ */
+ invalidateChildren() {
+ if (this._dirty && this._hasChanged) return;
+ this._dirty = this._hasChanged = true;
+
+ let len = this._children.length;
+ for (let i = 0; i < len; ++i) {
+ this._children[i].invalidateChildren();
+ }
+ }
+
+ _updateLocalMatrix() {
let dirtyFlag = this._localMatDirty;
if (!dirtyFlag) return;
// Update transform
let t = this._matrix;
- //math.mat4.fromRTS(t, this._quat, this._position, this._scale);
+ //math.mat4.fromRTS(t, this._lrot, this._lpos, this._lscale);
if (dirtyFlag & (LocalDirtyFlag.RT | LocalDirtyFlag.SKEW)) {
let hasRotation = this._rotationX || this._rotationY;
- let hasSkew = this._skewX || this._skewY;
- let sx = this._scale.x, sy = this._scale.y;
+ // let hasSkew = this._skewX || this._skewY;
+ let sx = this._lscale.x, sy = this._lscale.y;
- if (hasRotation || hasSkew) {
+ if (hasRotation /*|| hasSkew*/) {
let a = 1, b = 0, c = 0, d = 1;
// rotation
if (hasRotation) {
@@ -2296,19 +2337,19 @@ export default class Node extends BaseNode {
t.m04 = c *= sy;
t.m05 = d *= sy;
// skew
- if (hasSkew) {
- let a = t.m00, b = t.m01, c = t.m04, d = t.m05;
- let skx = Math.tan(this._skewX * ONE_DEGREE);
- let sky = Math.tan(this._skewY * ONE_DEGREE);
- if (skx === Infinity)
- skx = 99999999;
- if (sky === Infinity)
- sky = 99999999;
- t.m00 = a + c * sky;
- t.m01 = b + d * sky;
- t.m04 = c + a * skx;
- t.m05 = d + b * skx;
- }
+ // if (hasSkew) {
+ // let a = t.m00, b = t.m01, c = t.m04, d = t.m05;
+ // let skx = Math.tan(this._skewX * ONE_DEGREE);
+ // let sky = Math.tan(this._skewY * ONE_DEGREE);
+ // if (skx === Infinity)
+ // skx = 99999999;
+ // if (sky === Infinity)
+ // sky = 99999999;
+ // t.m00 = a + c * sky;
+ // t.m01 = b + d * sky;
+ // t.m04 = c + a * skx;
+ // t.m05 = d + b * skx;
+ // }
}
else {
t.m00 = sx;
@@ -2319,20 +2360,20 @@ export default class Node extends BaseNode {
}
// position
- t.m12 = this._position.x;
- t.m13 = this._position.y;
-
+ t.m12 = this._lpos.x;
+ t.m13 = this._lpos.y;
+
this._localMatDirty = 0;
// Register dirty status of world matrix so that it can be recalculated
this._worldMatDirty = true;
}
- _calculWorldMatrix () {
+ _calculWorldMatrix() {
// Avoid as much function call as possible
if (this._localMatDirty) {
this._updateLocalMatrix();
}
-
+
// Assume parent world matrix is correct
let parent = this._parent;
if (parent) {
@@ -2344,9 +2385,9 @@ export default class Node extends BaseNode {
this._worldMatDirty = false;
}
- _mulMat (out, a, b) {
- let aa=a.m00, ab=a.m01, ac=a.m04, ad=a.m05, atx=a.m12, aty=a.m13;
- let ba=b.m00, bb=b.m01, bc=b.m04, bd=b.m05, btx=b.m12, bty=b.m13;
+ _mulMat(out, a, b) {
+ let aa = a.m00, ab = a.m01, ac = a.m04, ad = a.m05, atx = a.m12, aty = a.m13;
+ let ba = b.m00, bb = b.m01, bc = b.m04, bd = b.m05, btx = b.m12, bty = b.m13;
if (ab !== 0 || ac !== 0) {
out.m00 = ba * aa + bb * ac;
out.m01 = ba * ab + bb * ad;
@@ -2365,7 +2406,7 @@ export default class Node extends BaseNode {
}
}
- _updateWorldMatrix () {
+ _updateWorldMatrix() {
if (this._parent) {
this._parent._updateWorldMatrix();
}
@@ -2379,12 +2420,12 @@ export default class Node extends BaseNode {
}
}
- setLocalDirty (flag) {
+ setLocalDirty(flag) {
this._localMatDirty = this._localMatDirty | flag;
this._worldMatDirty = true;
}
- setWorldDirty () {
+ setWorldDirty() {
this._worldMatDirty = true;
}
@@ -2399,11 +2440,11 @@ export default class Node extends BaseNode {
* let mat4 = cc.mat4();
* node.getLocalMatrix(mat4);
*/
- getLocalMatrix (out) {
+ getLocalMatrix(out) {
this._updateLocalMatrix();
return math.mat4.copy(out, this._matrix);
}
-
+
/**
* !#en
* Get the world transform matrix (4x4)
@@ -2415,9 +2456,14 @@ export default class Node extends BaseNode {
* let mat4 = cc.mat4();
* node.getWorldMatrix(mat4);
*/
- getWorldMatrix (out) {
+ getWorldMatrix(out) {
this._updateWorldMatrix();
- return math.mat4.copy(out, this._worldMatrix);
+
+ if (out) {
+ return math.mat4.copy(out, this._worldMatrix);
+ } else {
+ return math.mat4.copy(cc.mat4(), this._worldMatrix);
+ }
}
/**
@@ -2433,7 +2479,7 @@ export default class Node extends BaseNode {
* @example
* var newVec2 = node.convertToNodeSpace(cc.v2(100, 100));
*/
- convertToNodeSpace (worldPoint) {
+ convertToNodeSpace(worldPoint) {
this._updateWorldMatrix();
math.mat4.invert(_mat4_temp, this._worldMatrix);
let out = new cc.Vec2();
@@ -2454,7 +2500,7 @@ export default class Node extends BaseNode {
* @example
* var newVec2 = node.convertToWorldSpace(cc.v2(100, 100));
*/
- convertToWorldSpace (nodePoint) {
+ convertToWorldSpace(nodePoint) {
this._updateWorldMatrix();
let out = new cc.Vec2(
nodePoint.x - this._anchorPoint.x * this._contentSize.width,
@@ -2474,7 +2520,7 @@ export default class Node extends BaseNode {
* @example
* var newVec2 = node.convertToNodeSpaceAR(cc.v2(100, 100));
*/
- convertToNodeSpaceAR (worldPoint) {
+ convertToNodeSpaceAR(worldPoint) {
this._updateWorldMatrix();
math.mat4.invert(_mat4_temp, this._worldMatrix);
let out = new cc.Vec2();
@@ -2492,13 +2538,13 @@ export default class Node extends BaseNode {
* @example
* var newVec2 = node.convertToWorldSpaceAR(cc.v2(100, 100));
*/
- convertToWorldSpaceAR (nodePoint) {
+ convertToWorldSpaceAR(nodePoint) {
this._updateWorldMatrix();
let out = new cc.Vec2();
return math.vec2.transformMat4(out, nodePoint, this._worldMatrix);
}
-// OLD TRANSFORM ACCESS APIs
+ // OLD TRANSFORM ACCESS APIs
/**
* !#en
* Returns the matrix that transform the node's (local) space coordinates into the parent's space coordinates.
@@ -2512,12 +2558,12 @@ export default class Node extends BaseNode {
* let affineTransform = cc.AffineTransform.create();
* node.getNodeToParentTransform(affineTransform);
*/
- getNodeToParentTransform (out) {
+ getNodeToParentTransform(out) {
if (!out) {
out = AffineTrans.identity();
}
this._updateLocalMatrix();
-
+
var contentSize = this._contentSize;
_vec3_temp.x = -this._anchorPoint.x * contentSize.width;
_vec3_temp.y = -this._anchorPoint.y * contentSize.height;
@@ -2544,7 +2590,7 @@ export default class Node extends BaseNode {
* let affineTransform = cc.AffineTransform.create();
* node.getNodeToParentTransformAR(affineTransform);
*/
- getNodeToParentTransformAR (out) {
+ getNodeToParentTransformAR(out) {
if (!out) {
out = AffineTrans.identity();
}
@@ -2563,12 +2609,12 @@ export default class Node extends BaseNode {
* let affineTransform = cc.AffineTransform.create();
* node.getNodeToWorldTransform(affineTransform);
*/
- getNodeToWorldTransform (out) {
+ getNodeToWorldTransform(out) {
if (!out) {
out = AffineTrans.identity();
}
this._updateWorldMatrix();
-
+
var contentSize = this._contentSize;
_vec3_temp.x = -this._anchorPoint.x * contentSize.width;
_vec3_temp.y = -this._anchorPoint.y * contentSize.height;
@@ -2594,7 +2640,7 @@ export default class Node extends BaseNode {
* let affineTransform = cc.AffineTransform.create();
* node.getNodeToWorldTransformAR(affineTransform);
*/
- getNodeToWorldTransformAR (out) {
+ getNodeToWorldTransformAR(out) {
if (!out) {
out = AffineTrans.identity();
}
@@ -2617,7 +2663,7 @@ export default class Node extends BaseNode {
* let affineTransform = cc.AffineTransform.create();
* node.getParentToNodeTransform(affineTransform);
*/
- getParentToNodeTransform (out) {
+ getParentToNodeTransform(out) {
if (!out) {
out = AffineTrans.identity();
}
@@ -2637,7 +2683,7 @@ export default class Node extends BaseNode {
* let affineTransform = cc.AffineTransform.create();
* node.getWorldToNodeTransform(affineTransform);
*/
- getWorldToNodeTransform (out) {
+ getWorldToNodeTransform(out) {
if (!out) {
out = AffineTrans.identity();
}
@@ -2656,7 +2702,7 @@ export default class Node extends BaseNode {
* @example
* var newVec2 = node.convertTouchToNodeSpace(touch);
*/
- convertTouchToNodeSpace (touch) {
+ convertTouchToNodeSpace(touch) {
return this.convertToNodeSpace(touch.getLocation());
}
@@ -2670,10 +2716,10 @@ export default class Node extends BaseNode {
* @example
* var newVec2 = node.convertTouchToNodeSpaceAR(touch);
*/
- convertTouchToNodeSpaceAR (touch) {
+ convertTouchToNodeSpaceAR(touch) {
return this.convertToNodeSpaceAR(touch.getLocation());
}
-
+
/**
* !#en
* Returns a "local" axis aligned bounding box of the node.
@@ -2684,14 +2730,14 @@ export default class Node extends BaseNode {
* @example
* var boundingBox = node.getBoundingBox();
*/
- getBoundingBox () {
+ getBoundingBox() {
this._updateLocalMatrix();
let width = this._contentSize.width;
let height = this._contentSize.height;
let rect = cc.rect(
- -this._anchorPoint.x * width,
- -this._anchorPoint.y * height,
- width,
+ -this._anchorPoint.x * width,
+ -this._anchorPoint.y * height,
+ width,
height);
return rect.transformMat4(rect, this._matrix);
}
@@ -2708,7 +2754,7 @@ export default class Node extends BaseNode {
* @example
* var newRect = node.getBoundingBoxToWorld();
*/
- getBoundingBoxToWorld () {
+ getBoundingBoxToWorld() {
if (this._parent) {
this._parent._updateWorldMatrix();
return this._getBoundingBoxTo(this._parent._worldMatrix);
@@ -2718,14 +2764,14 @@ export default class Node extends BaseNode {
}
}
- _getBoundingBoxTo (parentMat) {
+ _getBoundingBoxTo(parentMat) {
this._updateLocalMatrix();
let width = this._contentSize.width;
let height = this._contentSize.height;
let rect = cc.rect(
- -this._anchorPoint.x * width,
- -this._anchorPoint.y * height,
- width,
+ -this._anchorPoint.x * width,
+ -this._anchorPoint.y * height,
+ width,
height);
var pMat = math.mat4.mul(this._worldMatrix, parentMat, this._matrix);
@@ -2747,40 +2793,40 @@ export default class Node extends BaseNode {
return rect;
}
- _updateOrderOfArrival () {
+ _updateOrderOfArrival() {
var arrivalOrder = ++_globalOrderOfArrival;
this._localZOrder = (this._localZOrder & 0xffff0000) | arrivalOrder;
}
- /**
- * !#en
- * Adds a child to the node with z order and name.
- * !#zh
- * 添加子节点,并且可以修改该节点的 局部 Z 顺序和名字。
- * @method addChild
- * @param {Node} child - A child node
- * @param {Number} [zIndex] - Z order for drawing priority. Please refer to zIndex property
- * @param {String} [name] - A name to identify the node easily. Please refer to name property
- * @example
- * node.addChild(newNode, 1, "node");
- */
- addChild (child, zIndex, name) {
- if (CC_DEV && !cc.Node.isNode(child)) {
- return cc.errorID(1634, cc.js.getClassName(child));
- }
- cc.assertID(child, 1606);
- cc.assertID(child._parent === null, 1605);
+ // /**
+ // * !#en
+ // * Adds a child to the node with z order and name.
+ // * !#zh
+ // * 添加子节点,并且可以修改该节点的 局部 Z 顺序和名字。
+ // * @method addChild
+ // * @param {Node} child - A child node
+ // * @param {Number} [zIndex] - Z order for drawing priority. Please refer to zIndex property
+ // * @param {String} [name] - A name to identify the node easily. Please refer to name property
+ // * @example
+ // * node.addChild(newNode, 1, "node");
+ // */
+ // addChild(child, zIndex, name) {
+ // if (CC_DEV && !cc.Node.isNode(child)) {
+ // return cc.errorID(1634, cc.js.getClassName(child));
+ // }
+ // cc.assertID(child, 1606);
+ // cc.assertID(child._parent === null, 1605);
- // invokes the parent setter
- child.parent = this;
+ // // invokes the parent setter
+ // child.parent = this;
- if (zIndex !== undefined) {
- child.zIndex = zIndex;
- }
- if (name !== undefined) {
- child.name = name;
- }
- }
+ // if (zIndex !== undefined) {
+ // child.zIndex = zIndex;
+ // }
+ // if (name !== undefined) {
+ // child.name = name;
+ // }
+ // }
/**
* !#en Stops all running actions and schedulers.
@@ -2789,7 +2835,7 @@ export default class Node extends BaseNode {
* @example
* node.cleanup();
*/
- cleanup () {
+ cleanup() {
// actions
ActionManagerExist && cc.director.getActionManager().removeAllActionsFromTarget(this);
// event
@@ -2811,7 +2857,7 @@ export default class Node extends BaseNode {
*
* @method sortAllChildren
*/
- sortAllChildren () {
+ sortAllChildren() {
if (this._reorderChildDirty) {
this._reorderChildDirty = false;
var _children = this._children;
@@ -2839,14 +2885,14 @@ export default class Node extends BaseNode {
}
}
- _delaySort () {
+ _delaySort() {
if (!this._reorderChildDirty) {
this._reorderChildDirty = true;
cc.director.__fastOn(cc.Director.EVENT_AFTER_UPDATE, this.sortAllChildren, this);
}
}
- _restoreProperties () {
+ _restoreProperties() {
/*
* TODO: Refine this code after completing undo/redo 2.0.
* The node will be destroyed when deleting in the editor,
@@ -2862,6 +2908,7 @@ export default class Node extends BaseNode {
this._localMatDirty = LocalDirtyFlag.ALL;
this._worldMatDirty = true;
+
if (this._renderComponent) {
if (this._renderComponent.enabled) {
this._renderComponent.markForUpdateRenderData(true);
@@ -2894,9 +2941,9 @@ if (CC_EDITOR) {
// 3D Node Property
/**
- * !en
+ * !en
* Switch 2D/3D node. The 2D nodes will run faster.
- * !zh
+ * !zh
* 切换 2D/3D 节点,2D 节点会有更高的运行效率
* @property {Boolean} is3DNode
* @default false
@@ -3019,4 +3066,4 @@ js.getset(_p, 'rotation', _p.getRotation, _p.setRotation);
js.getset(_p, 'position', _p.getPosition, _p.setPosition, false, true);
js.getset(_p, 'scale', _p.getScale, _p.setScale, false, true);
-cc.Node2D = Node;
+cc.NodeUI = NodeUI;
diff --git a/cocos/scene-graph/node-activator.js b/cocos/scene-graph/node-activator.js
index 907826095f..aa6443538b 100644
--- a/cocos/scene-graph/node-activator.js
+++ b/cocos/scene-graph/node-activator.js
@@ -25,7 +25,7 @@
****************************************************************************/
import ComponentScheduler from './component-scheduler';
-import CCObject from '../core/data/object';
+import { CCObject } from '../core/data/object';
import { Pool, array } from '../core/utils/js';
import { tryCatchFunctor_EDITOR } from '../core/utils/misc';
diff --git a/cocos/scene-graph/node.js b/cocos/scene-graph/node.js
deleted file mode 100644
index 1767b63fce..0000000000
--- a/cocos/scene-graph/node.js
+++ /dev/null
@@ -1,493 +0,0 @@
-import { vec3, mat4, quat } from '../core/vmath';
-import { Vec3 } from '../core/value-types';
-import BaseNode from './base-node';
-import Layers from './layers';
-import { EventTarget } from "../core/event";
-import { ccclass, property, mixins } from '../core/data/class-decorator';
-
-let v3_a = cc.v3();
-let q_a = cc.quat();
-let array_a = new Array(10);
-
-let EventType = cc.Enum({
- TRANSFORM_CHANGED: 'transform-changed',
- POSITION_PART: 1,
- ROTATION_PART: 2,
- SCALE_PART: 4
-});
-
-@ccclass('cc.Node')
-@mixins(EventTarget)
-class Node extends BaseNode {
- // local transform
- @property
- _lpos = cc.v3();
- @property
- _lrot = cc.quat();
- @property
- _lscale = cc.v3(1, 1, 1);
- @property
- _layer = Layers.Default; // the layer this node belongs to
-
- @property
- _euler = cc.v3(); // local rotation in euler angles, maintained here so that rotation angles could be greater than 360 degree.
-
- @property({
- type: Vec3
- })
- set eulerAngles(val) {
- this.setRotationFromEuler(val.x, val.y, val.z);
- }
- get eulerAngles() {
- if (this._eulerDirty) {
- quat.toEuler(this._euler, this._lrot);
- this._eulerDirty = false;
- }
- return this._euler;
- }
-
- set layer(l) {
- this._layer = l;
- }
-
- get layer() {
- return this._layer;
- }
-
- // world transform
- _pos = cc.v3();
- _rot = cc.quat();
- _scale = cc.v3(1, 1, 1);
- _mat = cc.mat4();
-
- _dirty = false; // does the world transform need to update?
- _hasChanged = false; // has the transform changed in this frame?
-
- _matDirty = false;
- _eulerDirty = false;
-
- // is node but not scene
- static isNode (obj) {
- return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene));
- }
-
- static EventType = EventType;
-
- constructor (name) {
- super(name);
- EventTarget.call(this);
- }
-
-
- // ===============================
- // hierarchy
- // ===============================
-
- /**
- * invalidate all children after relevant events
- */
- onRestore() {
- super.onRestore();
- this.invalidateChildren();
- }
-
- _onSetParent(/*oldParent*/) {
- this.invalidateChildren();
- }
-
- _onPostActivated() {
- this.invalidateChildren();
- }
-
- // ===============================
- // transform helper
- // ===============================
-
- /**
- * Set rotation by lookAt target point
- * @param {vec3} pos target position
- * @param {vec3} up the up vector, default to (0,1,0)
- */
- lookAt(pos, up) {
- this.getWorldPosition(v3_a);
- vec3.sub(v3_a, v3_a, pos); // NOTE: we use -z for view-dir
- vec3.normalize(v3_a, v3_a);
- quat.fromViewUp(q_a, v3_a, up);
-
- this.setWorldRotation(q_a);
- }
-
- /**
- * Reset the `hasChanged` flag recursively
- */
- resetHasChanged() {
- this._hasChanged = false;
- let len = this._children.length;
- for (let i = 0; i < len; ++i) {
- this._children[i].resetHasChanged();
- }
- }
-
- /**
- * invalidate the world transform information
- * for this node and all its children recursively
- */
- invalidateChildren() {
- if (this._dirty && this._hasChanged) return;
- this._dirty = this._hasChanged = true;
-
- let len = this._children.length;
- for (let i = 0; i < len; ++i) {
- this._children[i].invalidateChildren();
- }
- }
-
- /**
- * update the world transform information if outdated
- */
- updateWorldTransform() {
- if (!this._dirty) return;
- let cur = this, child, i = 0;
- while (cur._dirty) {
- // top level node
- array_a[i++] = cur;
- cur = cur._parent;
- if (!cur) break;
- }
- while (i) {
- child = array_a[--i];
- if (cur) {
- vec3.mul(child._pos, child._lpos, cur._scale);
- vec3.transformQuat(child._pos, child._pos, cur._rot);
- vec3.add(child._pos, child._pos, cur._pos);
- quat.mul(child._rot, cur._rot, child._lrot);
- vec3.mul(child._scale, cur._scale, child._lscale);
- }
- child._matDirty = true; // further deferred eval
- child._dirty = false;
- cur = child;
- }
- }
-
- updateWorldTransformFull() {
- this.updateWorldTransform();
- if (!this._matDirty) return;
- mat4.fromRTS(this._mat, this._rot, this._pos, this._scale);
- this._matDirty = false;
- }
-
- // ===============================
- // transform
- // ===============================
-
- /**
- * set local position
- * @param {vec3|number} val the new local position, or the x component of it
- * @param {number} [y] the y component of the new local position
- * @param {number} [z] the z component of the new local position
- */
- setPosition(val, y, z) {
- if (arguments.length === 1) {
- vec3.copy(this._lpos, val);
- } else if (arguments.length === 3) {
- vec3.set(this._lpos, val, y, z);
- }
-
- this.invalidateChildren();
- this.emit(EventType.TRANSFORM_CHANGED, EventType.POSITION_PART);
- }
-
- /**
- * get local position
- * @param {vec3} [out] the receiving vector
- * @return {vec3} the resulting vector
- */
- getPosition(out) {
- if (out) {
- return vec3.set(out, this._lpos.x, this._lpos.y, this._lpos.z);
- } else {
- return vec3.copy(cc.v3(), this._lpos);
- }
- }
-
- /**
- * set local rotation
- * @param {quat|number} val the new local rotation, or the x component of it
- * @param {number} [y] the y component of the new local rotation
- * @param {number} [z] the z component of the new local rotation
- * @param {number} [w] the w component of the new local rotation
- */
- setRotation(val, y, z, w) {
- if (arguments.length === 1) {
- quat.copy(this._lrot, val);
- } else if (arguments.length === 4) {
- quat.set(this._lrot, val, y, z, w);
- }
- this._eulerDirty = true;
-
- this.invalidateChildren();
- this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART);
- }
-
- /**
- * set local rotation from euler angles
- * @param {number} x - Angle to rotate around X axis in degrees.
- * @param {number} y - Angle to rotate around Y axis in degrees.
- * @param {number} z - Angle to rotate around Z axis in degrees.
- */
- setRotationFromEuler(x, y, z) {
- vec3.set(this._euler, x, y, z);
- this._eulerDirty = false;
- quat.fromEuler(this._lrot, x, y, z);
-
- this.invalidateChildren();
- this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART);
- }
-
- /**
- * get local rotation
- * @param {quat} [out] the receiving quaternion
- * @return {quat} the resulting quaternion
- */
- getRotation(out) {
- if (out) {
- return quat.set(out, this._lrot.x, this._lrot.y, this._lrot.z, this._lrot.w);
- } else {
- return quat.copy(cc.quat(), this._lrot);
- }
- }
-
- /**
- * set local scale
- * @param {vec3|number} val the new local scale, or the x component of it
- * @param {number} [y] the y component of the new local scale
- * @param {number} [z] the z component of the new local scale
- */
- setScale(val, y, z) {
- if (arguments.length === 1) {
- vec3.copy(this._lscale, val);
- } else if (arguments.length === 3) {
- vec3.set(this._lscale, val, y, z);
- }
-
- this.invalidateChildren();
- this.emit(EventType.TRANSFORM_CHANGED, EventType.SCALE_PART);
- }
-
- /**
- * get local scale
- * @param {vec3} [out] the receiving vector
- * @return {vec3} the resulting vector
- */
- getScale(out) {
- if (out) {
- return vec3.set(out, this._lscale.x, this._lscale.y, this._lscale.z);
- } else {
- return vec3.copy(cc.v3(), this._lscale);
- }
- }
-
- /**
- * set world position
- * @param {vec3|number} val the new world position, or the x component of it
- * @param {number} [y] the y component of the new world position
- * @param {number} [z] the z component of the new world position
- */
- setWorldPosition(val, y, z) {
- if (arguments.length === 1) {
- vec3.copy(this._pos, val);
- } else if (arguments.length === 3) {
- vec3.set(this._pos, val, y, z);
- }
- let parent = this._parent, local = this._lpos;
- if (parent) {
- parent.updateWorldTransform();
- vec3.sub(local, this._pos, parent._pos);
- vec3.transformQuat(local, local, quat.conjugate(q_a, parent._rot));
- vec3.div(local, local, parent._scale);
- } else {
- vec3.copy(this._lpos, this._pos);
- }
-
- this.invalidateChildren();
- this.emit(EventType.TRANSFORM_CHANGED, EventType.POSITION_PART);
- }
-
- /**
- * get world position
- * @param {vec3} [out] the receiving vector
- * @return {vec3} the resulting vector
- */
- getWorldPosition(out) {
- this.updateWorldTransform();
- if (out) {
- return vec3.copy(out, this._pos);
- } else {
- return vec3.copy(cc.v3(), this._pos);
- }
- }
-
- /**
- * set world rotation
- * @param {quat|number} val the new world rotation, or the x component of it
- * @param {number} [y] the y component of the new world rotation
- * @param {number} [z] the z component of the new world rotation
- * @param {number} [w] the w component of the new world rotation
- */
- setWorldRotation(val, y, z, w) {
- if (arguments.length === 1) {
- quat.copy(this._rot, val);
- } else if (arguments.length === 4) {
- quat.set(this._rot, val, y, z, w);
- }
- if (this._parent) {
- this._parent.getWorldRotation(q_a);
- quat.mul(this._lrot, quat.conjugate(q_a, q_a), this._rot);
- } else {
- quat.copy(this._lrot, this._rot);
- }
- this._eulerDirty = true;
-
- this.invalidateChildren();
- this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART);
- }
-
- /**
- * set world rotation from euler angles
- * @param {number} x - Angle to rotate around X axis in degrees.
- * @param {number} y - Angle to rotate around Y axis in degrees.
- * @param {number} z - Angle to rotate around Z axis in degrees.
- */
- setWorldRotationFromEuler(x, y, z) {
- vec3.set(this._euler, x, y, z);
- this._eulerDirty = false;
- quat.fromEuler(this._rot, x, y, z);
- if (this._parent) {
- this._parent.getWorldRotation(q_a);
- quat.mul(this._lrot, this._rot, quat.conjugate(q_a, q_a));
- } else {
- quat.copy(this._lrot, this._rot);
- }
-
- this.invalidateChildren();
- this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART);
- }
-
- /**
- * get world rotation
- * @param {quat} [out] the receiving quaternion
- * @return {quat} the resulting quaternion
- */
- getWorldRotation(out) {
- this.updateWorldTransform();
- if (out) {
- return quat.copy(out, this._rot);
- } else {
- return quat.copy(cc.quat(), this._rot);
- }
- }
-
- /**
- * set world scale
- * @param {vec3|number} val the new world scale, or the x component of it
- * @param {number} [y] the y component of the new world scale
- * @param {number} [z] the z component of the new world scale
- */
- setWorldScale(val, y, z) {
- if (arguments.length === 1) {
- vec3.copy(this._scale, val);
- } else if (arguments.length === 3) {
- vec3.set(this._scale, val, y, z);
- }
- if (this._parent) {
- this._parent.getWorldScale(v3_a);
- vec3.div(this._lscale, this._scale, v3_a);
- } else {
- vec3.copy(this._lscale, this._scale);
- }
-
- this.invalidateChildren();
- this.emit(EventType.TRANSFORM_CHANGED, EventType.SCALE_PART);
- }
-
- /**
- * get world scale
- * @param {vec3} [out] the receiving vector
- * @return {vec3} the resulting vector
- */
- getWorldScale(out) {
- this.updateWorldTransform();
- if (out) {
- return vec3.copy(out, this._scale);
- } else {
- return vec3.copy(cc.v3(), this._scale);
- }
- }
-
- /**
- * get the matrix that transforms a point from local space into world space
- * @param {mat4} [out] the receiving matrix
- * @return {mat4} the resulting matrix
- */
- getWorldMatrix(out) {
- this.updateWorldTransformFull();
- if (out) {
- return mat4.copy(out, this._mat);
- } else {
- return mat4.copy(cc.mat4(), this._mat);
- }
- }
-
- /**
- * get world transform matrix (with only rotation and scale)
- * @param {mat4} [out] the receiving matrix
- * @return {mat4} the resulting matrix
- */
- getWorldRS(out) {
- this.updateWorldTransformFull();
- if (out) {
- mat4.copy(out, this._mat);
- } else {
- out = mat4.copy(cc.mat4(), this._mat);
- }
- out.m12 = 0; out.m13 = 0; out.m14 = 0;
- return out;
- }
-
- /**
- * get world transform matrix (with only rotation and translation)
- * @param {mat4} [out] the receiving matrix
- * @return {mat4} the resulting matrix
- */
- getWorldRT(out) {
- this.updateWorldTransform();
- if (!out) {
- out = cc.mat4();
- }
- return mat4.fromRT(out, this._rot, this._pos);
- }
-}
-
-if (CC_EDITOR) {
- let repeat = (t, l) => t - Math.floor(t / l) * l;
- let desc = {
- set(val) {
- this.setRotationFromEuler(val.x, val.y, val.z);
- },
- get() {
- if (this._eulerDirty) {
- let eu = this._euler;
- quat.toEuler(v3_a, this._lrot);
- eu.x = repeat(v3_a.x - eu.x + 180, 360) + eu.x - 180;
- eu.y = repeat(v3_a.y - eu.y + 180, 360) + eu.y - 180;
- eu.z = repeat(v3_a.z - eu.z + 180, 360) + eu.z - 180;
- this._eulerDirty = false;
- }
- return this._euler;
- }
- };
- Object.defineProperty(Node.prototype, 'eulerAngles', desc);
-}
-
-cc.Node = Node;
-export default Node;
diff --git a/cocos/scene-graph/node.ts b/cocos/scene-graph/node.ts
new file mode 100644
index 0000000000..c9acd92d01
--- /dev/null
+++ b/cocos/scene-graph/node.ts
@@ -0,0 +1,1287 @@
+import { UITransformComponent } from '../3d/ui/components/ui-transfrom-component';
+import { ccclass, mixins, property } from '../core/data/class-decorator';
+import { DefaultEventTarget, EventTarget } from '../core/event/event-target-base';
+import { Enum, Mat4, Quat, Vec3 } from '../core/value-types';
+import Size from '../core/value-types/size';
+import Vec2 from '../core/value-types/vec2';
+import { mat4, quat, vec3 } from '../core/vmath';
+import { BaseNode } from './base-node';
+import { Layers } from './layers';
+import { WidgetComponent } from '../3d/ui/components/widget-component';
+
+const v3_a = new Vec3();
+const q_a = new Quat();
+const array_a = new Array(10);
+const _cachedArray = new Array(16);
+_cachedArray.length = 0;
+
+const EventType = Enum({
+ TRANSFORM_CHANGED: 'transform-changed',
+ POSITION_PART: 1,
+ ROTATION_PART: 2,
+ SCALE_PART: 4,
+ TOUCH_START: 'touch-start',
+ TOUCH_MOVE: 'touch-move',
+ TOUCH_END: 'touch-end',
+ TOUCH_CANCEL: 'touch-cancel',
+ MOUSE_DOWN: 'mouse-down',
+ MOUSE_ENTER: 'mouse-enter',
+ MOUSE_MOVE: 'mouse-move',
+ MOUSE_LEAVE: 'mouse-leave',
+ MOUSE_UP: 'mouse-up',
+ MOUSE_WHEEL: 'mouse-wheel',
+});
+
+const _touchEvents = [
+ EventType.TOUCH_START,
+ EventType.TOUCH_MOVE,
+ EventType.TOUCH_END,
+ EventType.TOUCH_CANCEL,
+];
+const _mouseEvents = [
+ EventType.MOUSE_DOWN,
+ EventType.MOUSE_ENTER,
+ EventType.MOUSE_MOVE,
+ EventType.MOUSE_LEAVE,
+ EventType.MOUSE_UP,
+ EventType.MOUSE_WHEEL,
+];
+
+const _touchStartHandler = function (touch, event) {
+ const pos = touch.getLocation();
+ const node = this.owner;
+
+ if (node._hitTest(pos, this)) {
+ event.type = EventType.TOUCH_START;
+ event.touch = touch;
+ event.bubbles = true;
+ node.dispatchEvent(event);
+ return true;
+ }
+ return false;
+};
+const _touchMoveHandler = function (touch, event) {
+ const node = this.owner;
+ event.type = EventType.TOUCH_MOVE;
+ event.touch = touch;
+ event.bubbles = true;
+ node.dispatchEvent(event);
+};
+const _touchEndHandler = function (touch, event) {
+ const pos = touch.getLocation();
+ const node = this.owner;
+
+ if (node._hitTest(pos, this)) {
+ event.type = EventType.TOUCH_END;
+ } else {
+ event.type = EventType.TOUCH_CANCEL;
+ }
+ event.touch = touch;
+ event.bubbles = true;
+ node.dispatchEvent(event);
+};
+const _touchCancelHandler = function (touch, event) {
+ const node = this.owner;
+
+ event.type = EventType.TOUCH_CANCEL;
+ event.touch = touch;
+ event.bubbles = true;
+ node.dispatchEvent(event);
+};
+
+const _mouseDownHandler = function (event) {
+ const pos = event.getLocation();
+ const node = this.owner;
+
+ if (node._hitTest(pos, this)) {
+ event.type = EventType.MOUSE_DOWN;
+ event.bubbles = true;
+ node.dispatchEvent(event);
+ }
+};
+const _mouseMoveHandler = function (event) {
+ const pos = event.getLocation();
+ const node = this.owner;
+ const hit = node._hitTest(pos, this);
+ if (hit) {
+ if (!this._previousIn) {
+ // Fix issue when hover node switched, previous hovered node won't get MOUSE_LEAVE notification
+ if (_currentHovered && _currentHovered._mouseListener) {
+ event.type = EventType.MOUSE_LEAVE;
+ _currentHovered.dispatchEvent(event);
+ _currentHovered._mouseListener._previousIn = false;
+ }
+ _currentHovered = this.owner;
+ event.type = EventType.MOUSE_ENTER;
+ node.dispatchEvent(event);
+ this._previousIn = true;
+ }
+ event.type = EventType.MOUSE_MOVE;
+ event.bubbles = true;
+ node.dispatchEvent(event);
+ } else if (this._previousIn) {
+ event.type = EventType.MOUSE_LEAVE;
+ node.dispatchEvent(event);
+ this._previousIn = false;
+ _currentHovered = null;
+ } else {
+ // continue dispatching
+ return;
+ }
+
+ // Event processed, cleanup
+ event.stopPropagation();
+};
+const _mouseUpHandler = function (event) {
+ const pos = event.getLocation();
+ const node = this.owner;
+
+ if (node._hitTest(pos, this)) {
+ event.type = EventType.MOUSE_UP;
+ event.bubbles = true;
+ node.dispatchEvent(event);
+ event.stopPropagation();
+ }
+};
+const _mouseWheelHandler = function (event) {
+ const pos = event.getLocation();
+ const node = this.owner;
+
+ if (node._hitTest(pos, this)) {
+ event.type = EventType.MOUSE_WHEEL;
+ event.bubbles = true;
+ node.dispatchEvent(event);
+ event.stopPropagation();
+ }
+};
+
+function _doDispatchEvent (owner, event) {
+ let target, i;
+ event.target = owner;
+
+ // Event.CAPTURING_PHASE
+ _cachedArray.length = 0;
+ owner._getCapturingTargets(event.type, _cachedArray);
+ // capturing
+ event.eventPhase = 1;
+ for (i = _cachedArray.length - 1; i >= 0; --i) {
+ target = _cachedArray[i];
+ if (target._capturingListeners) {
+ event.currentTarget = target;
+ // fire event
+ target._capturingListeners.emit(event.type, event, _cachedArray);
+ // check if propagation stopped
+ if (event._propagationStopped) {
+ _cachedArray.length = 0;
+ return;
+ }
+ }
+ }
+ _cachedArray.length = 0;
+
+ // Event.AT_TARGET
+ // checks if destroyed in capturing callbacks
+ event.eventPhase = 2;
+ event.currentTarget = owner;
+ if (owner._capturingListeners) {
+ owner._capturingListeners.emit(event.type, event);
+ }
+ if (!event._propagationImmediateStopped && owner._bubblingListeners) {
+ owner._bubblingListeners.emit(event.type, event);
+ }
+
+ if (!event._propagationStopped && event.bubbles) {
+ // Event.BUBBLING_PHASE
+ owner._getBubblingTargets(event.type, _cachedArray);
+ // propagate
+ event.eventPhase = 3;
+ for (i = 0; i < _cachedArray.length; ++i) {
+ target = _cachedArray[i];
+ if (target._bubblingListeners) {
+ event.currentTarget = target;
+ // fire event
+ target._bubblingListeners.emit(event.type, event);
+ // check if propagation stopped
+ if (event._propagationStopped) {
+ _cachedArray.length = 0;
+ return;
+ }
+ }
+ }
+ }
+ _cachedArray.length = 0;
+}
+
+enum NodeSpace {
+ LOCAL,
+ WORLD,
+}
+
+@ccclass('cc.Node')
+@mixins(EventTarget)
+class Node extends EventTarget(BaseNode) {
+ public static EventType = EventType;
+ public static NodeSpace = NodeSpace;
+
+ // is node but not scene
+ public static isNode (obj: object) {
+ return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene));
+ }
+ public uiTransfromComp: UITransformComponent | null = null;
+ public uiWidgetComp: WidgetComponent | null = null;
+
+ // local transform
+ @property
+ protected _lpos = new Vec3();
+ @property
+ protected _lrot = new Quat();
+ @property
+ protected _lscale = new Vec3(1, 1, 1);
+ @property
+ protected _layer = Layers.Default; // the layer this node belongs to
+
+ // local rotation in euler angles, maintained here so that rotation angles could be greater than 360 degree.
+ @property
+ protected _euler = new Vec3();
+
+ // world transform
+ protected _pos = new Vec3();
+ protected _rot = new Quat();
+ protected _scale = new Vec3(1, 1, 1);
+ protected _mat = new Mat4();
+
+ protected _dirty = false; // does the world transform need to update?
+ protected _hasChanged = false; // has the transform changed in this frame?
+
+ protected _matDirty = false;
+ protected _eulerDirty = false;
+
+ protected _bubblingListeners: EventTarget|null = null;
+ protected _capturingListeners: EventTarget | null = null;
+
+ @property({
+ type: Vec3,
+ })
+ set eulerAngles (val) {
+ this.setRotationFromEuler(val.x, val.y, val.z);
+ }
+ get eulerAngles () {
+ if (this._eulerDirty) {
+ quat.toEuler(this._euler, this._lrot);
+ this._eulerDirty = false;
+ }
+ return this._euler;
+ }
+
+ get hasChanged () {
+ return this._hasChanged;
+ }
+
+ set layer (l) {
+ this._layer = l;
+ }
+
+ get layer () {
+ return this._layer;
+ }
+
+ get width () {
+ if (!this.uiTransfromComp) {
+ return;
+ }
+
+ return this.uiTransfromComp.width;
+ }
+
+ set width (value) {
+ if (!this.uiTransfromComp) {
+ return;
+ }
+
+ this.uiTransfromComp.width = value;
+ }
+
+ get height () {
+ if (!this.uiTransfromComp) {
+ return;
+ }
+
+ return this.uiTransfromComp.height;
+ }
+
+ set height (value) {
+ if (!this.uiTransfromComp) {
+ return;
+ }
+ this.uiTransfromComp.height = value;
+ }
+
+ get anchorX () {
+ if (!this.uiTransfromComp) {
+ return;
+ }
+
+ return this.uiTransfromComp.anchorX;
+ }
+
+ set anchorX (value) {
+ if (!this.uiTransfromComp) {
+ return;
+ }
+
+ this.uiTransfromComp.anchorX = value;
+ }
+
+ get anchorY () {
+ if (!this.uiTransfromComp) {
+ return;
+ }
+
+ return this.uiTransfromComp.anchorY;
+ }
+
+ set anchorY (value) {
+ if (!this.uiTransfromComp) {
+ return;
+ }
+
+ this.uiTransfromComp.anchorY = value;
+ }
+
+ constructor (name: string) {
+ super(name);
+ // EventTarget.call(this);
+ }
+
+ // ===============================
+ // hierarchy
+ // ===============================
+
+ /**
+ * invalidate all children after relevant events
+ */
+ public onRestore () {
+ super.onRestore();
+ this.invalidateChildren();
+ }
+
+ public _onSetParent (oldParent: this) {
+ super._onSetParent(oldParent);
+ this.invalidateChildren();
+ }
+
+ public _onPostActivated () {
+ this.invalidateChildren();
+ }
+
+ // ===============================
+ // transform helper, convenient but not the most efficient
+ // ===============================
+
+ /**
+ * Rotate the node
+ * @param rot - rotation to apply
+ * @param ns - the operating space
+ */
+ public rotate (rot: Quat, ns?: NodeSpace) {
+ const space = ns || NodeSpace.LOCAL;
+ if (space === NodeSpace.LOCAL) {
+ this.getRotation(q_a);
+ this.setRotation(quat.multiply(q_a, q_a, rot));
+ } else if (space === NodeSpace.WORLD) {
+ this.getWorldRotation(q_a);
+ this.setWorldRotation(quat.multiply(q_a, rot, q_a));
+ }
+ }
+
+ /**
+ * rotate the node around X axis
+ * @param rad - rotating angle
+ * @param ns - the operating space
+ */
+ public pitch (rad: number, ns?: NodeSpace) {
+ const space = ns || NodeSpace.LOCAL;
+ if (space === NodeSpace.LOCAL) {
+ this.getWorldRotation(q_a);
+ quat.toAxisX(v3_a, q_a);
+ quat.fromAxisAngle(q_a, v3_a, rad);
+ this.rotate(q_a, ns);
+ } else if (space === NodeSpace.WORLD) {
+ quat.fromAxisAngle(q_a, vec3.UNIT_X, rad);
+ this.rotate(q_a, ns);
+ }
+ }
+
+ /**
+ * rotate the node around Y axis
+ * @param rad - rotating angle
+ * @param ns - the operating space
+ */
+ public yaw (rad: number, ns?: NodeSpace) {
+ const space = ns || NodeSpace.LOCAL;
+ if (space === NodeSpace.LOCAL) {
+ this.getWorldRotation(q_a);
+ quat.toAxisY(v3_a, q_a);
+ quat.fromAxisAngle(q_a, v3_a, rad);
+ this.rotate(q_a, ns);
+ } else if (space === NodeSpace.WORLD) {
+ quat.fromAxisAngle(q_a, vec3.UNIT_Y, rad);
+ this.rotate(q_a, ns);
+ }
+ }
+
+ /**
+ * rotate the node around Z axis
+ * @param rad - rotating angle
+ * @param ns - the operating space
+ */
+ public roll (rad: number, ns?: NodeSpace) {
+ const space = (ns !== undefined ? ns : NodeSpace.LOCAL);
+ if (space === NodeSpace.LOCAL) {
+ this.getWorldRotation(q_a);
+ quat.toAxisZ(v3_a, q_a);
+ quat.fromAxisAngle(q_a, v3_a, rad);
+ this.rotate(q_a, ns);
+ } else if (space === NodeSpace.WORLD) {
+ quat.fromAxisAngle(q_a, vec3.UNIT_Z, rad);
+ this.rotate(q_a, ns);
+ }
+ }
+
+ public get direction (): Vec3 {
+ this.getRotation(q_a);
+ return vec3.transformQuat(new Vec3(), vec3.UNIT_Z, q_a);
+ }
+
+ public set direction (dir: Vec3) {
+ quat.rotationTo(q_a, vec3.UNIT_Z, dir);
+ this.setRotation(q_a);
+ }
+
+ /**
+ * Set rotation by lookAt target point
+ * @param pos - target position
+ * @param up - the up vector, default to (0,1,0)
+ */
+ public lookAt (pos: Vec3, up: Vec3) {
+ this.getWorldPosition(v3_a);
+ vec3.sub(v3_a, v3_a, pos); // NOTE: we use -z for view-dir
+ vec3.normalize(v3_a, v3_a);
+ quat.fromViewUp(q_a, v3_a, up);
+
+ this.setWorldRotation(q_a);
+ }
+
+ // ===============================
+ // transform maintainer
+ // ===============================
+
+ /**
+ * Reset the `hasChanged` flag recursively
+ */
+ public resetHasChanged () {
+ this._hasChanged = false;
+ const len = this._children.length;
+ for (let i = 0; i < len; ++i) {
+ this._children[i].resetHasChanged();
+ }
+ }
+
+ /**
+ * invalidate the world transform information
+ * for this node and all its children recursively
+ */
+ public invalidateChildren () {
+ if (this._dirty && this._hasChanged) { return; }
+ this._dirty = this._hasChanged = true;
+ for (const child of this._children) {
+ child.invalidateChildren();
+ }
+ }
+
+ /**
+ * update the world transform information if outdated
+ * here we assume all nodes are children of a scene node,
+ * which is always not dirty, has an identity transform and no parent.
+ */
+ public updateWorldTransform () {
+ if (!this._dirty) { return; }
+ let cur: this | null = this;
+ let i = 0;
+ while (cur._dirty) {
+ // top level node
+ array_a[i++] = cur;
+ cur = cur._parent;
+ if (!cur || !cur._parent) {
+ cur = null;
+ break;
+ }
+ }
+ let child: this;
+ while (i) {
+ child = array_a[--i];
+ if (cur) {
+ vec3.mul(child._pos, child._lpos, cur._scale);
+ vec3.transformQuat(child._pos, child._pos, cur._rot);
+ vec3.add(child._pos, child._pos, cur._pos);
+ quat.mul(child._rot, cur._rot, child._lrot);
+ vec3.mul(child._scale, cur._scale, child._lscale);
+ }
+ child._matDirty = true; // further deferred eval
+ child._dirty = false;
+ cur = child;
+ }
+ }
+
+ public updateWorldTransformFull () {
+ this.updateWorldTransform();
+ if (!this._matDirty) { return; }
+ mat4.fromRTS(this._mat, this._rot, this._pos, this._scale);
+ this._matDirty = false;
+ }
+
+ // ===============================
+ // transform
+ // ===============================
+
+ /**
+ * Sets local position.
+ * @param position - The new local position.
+ */
+ public setPosition (position: Vec3): void;
+
+ /**
+ * Sets local position.
+ * @param x - The x component of the new local position.
+ * @param y - The y component of the new local position.
+ * @param z - The z component of the new local position.
+ * @param w - The w component of the new local position.
+ */
+ public setPosition (x: number, y: number, z: number): void;
+
+ /**
+ * set local position
+ * @param val - the new local position, or the x component of it
+ * @param y - the y component of the new local position
+ * @param z - the z component of the new local position
+ */
+ public setPosition (val: Vec3 | number, y?: number, z?: number) {
+ if (y === undefined || z === undefined) {
+ vec3.copy(this._lpos, val as Vec3);
+ } else if (arguments.length === 3) {
+ vec3.set(this._lpos, val as number, y, z);
+ }
+ vec3.copy(this._pos, this._lpos);
+
+ this.invalidateChildren();
+ this.emit(EventType.TRANSFORM_CHANGED, EventType.POSITION_PART);
+ }
+
+ /**
+ * get local position
+ * @param out the receiving vector
+ * @returns the resulting vector
+ */
+ public getPosition (out?: Vec3): Vec3 {
+ if (out) {
+ return vec3.set(out, this._lpos.x, this._lpos.y, this._lpos.z);
+ } else {
+ return vec3.copy(new Vec3(), this._lpos);
+ }
+ }
+
+ /**
+ * Sets local rotation.
+ * @param rotation - The new local rotation.
+ */
+ public setRotation (rotation: Quat): void;
+
+ /**
+ * Sets local rotation.
+ * @param x - The x component of the new local rotation.
+ * @param y - The y component of the new local rotation.
+ * @param z - The z component of the new local rotation.
+ * @param w - The w component of the new local rotation.
+ */
+ public setRotation (x: number, y: number, z: number, w: number): void;
+
+ public setRotation (val: Quat | number, y?: number, z?: number, w?: number) {
+ if (y === undefined || z === undefined || w === undefined) {
+ quat.copy(this._lrot, val as Quat);
+ } else if (arguments.length === 4) {
+ quat.set(this._lrot, val as number, y, z, w);
+ }
+ quat.copy(this._rot, this._lrot);
+ this._eulerDirty = true;
+
+ this.invalidateChildren();
+ this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART);
+ }
+
+ /**
+ * set local rotation from euler angles
+ * @param x - Angle to rotate around X axis in degrees.
+ * @param y - Angle to rotate around Y axis in degrees.
+ * @param z - Angle to rotate around Z axis in degrees.
+ */
+ public setRotationFromEuler (x: number, y: number, z: number) {
+ vec3.set(this._euler, x, y, z);
+ this._eulerDirty = false;
+ quat.fromEuler(this._lrot, x, y, z);
+ quat.copy(this._rot, this._lrot);
+
+ this.invalidateChildren();
+ this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART);
+ }
+
+ /**
+ * get local rotation
+ * @param out - the receiving quaternion
+ * @returns the resulting quaternion
+ */
+ public getRotation (out?: Quat): Quat {
+ if (out) {
+ return quat.set(out, this._lrot.x, this._lrot.y, this._lrot.z, this._lrot.w);
+ } else {
+ return quat.copy(new Quat(), this._lrot);
+ }
+ }
+
+ /**
+ * Sets local scale.
+ * @param scale - The new local scale.
+ */
+ public setScale (scale: Vec3): void;
+
+ /**
+ * Sets local scale.
+ * @param x - The x component of the new local scale.
+ * @param y - The y component of the new local scale.
+ * @param z - The z component of the new local scale.
+ */
+ public setScale (x: number, y: number, z: number): void;
+
+ /**
+ * set local scale
+ * @param val - the new local scale, or the x component of it
+ * @param y - the y component of the new local scale
+ * @param z - the z component of the new local scale
+ */
+ public setScale (val: Vec3 | number, y?: number, z?: number) {
+ if (y === undefined || z === undefined) {
+ vec3.copy(this._lscale, val as Vec3);
+ } else if (arguments.length === 3) {
+ vec3.set(this._lscale, val as number, y, z);
+ }
+ vec3.copy(this._scale, this._lscale);
+
+ this.invalidateChildren();
+ this.emit(EventType.TRANSFORM_CHANGED, EventType.SCALE_PART);
+ }
+
+ /**
+ * get local scale
+ * @param out - the receiving vector
+ * @returns the resulting vector
+ */
+ public getScale (out?: Vec3): Vec3 {
+ if (out) {
+ return vec3.set(out, this._lscale.x, this._lscale.y, this._lscale.z);
+ } else {
+ return vec3.copy(new Vec3(), this._lscale);
+ }
+ }
+
+ /**
+ * Sets world position.
+ * @param position - The new world position.
+ */
+ public setWorldPosition (position: Vec3): void;
+
+ /**
+ * Sets world position.
+ * @param x - The x component of the new world position.
+ * @param y - The y component of the new world position.
+ * @param z - The z component of the new world position.
+ */
+ public setWorldPosition (x: number, y: number, z: number): void;
+
+ /**
+ * set world position
+ * @param val - the new world position, or the x component of it
+ * @param y - the y component of the new world position
+ * @param z - the z component of the new world position
+ */
+ public setWorldPosition (val: Vec3 | number, y?: number, z?: number) {
+ if (y === undefined || z === undefined) {
+ vec3.copy(this._pos, val as Vec3);
+ } else if (arguments.length === 3) {
+ vec3.set(this._pos, val as number, y, z);
+ }
+ const parent = this._parent;
+ const local = this._lpos;
+ if (parent) {
+ parent.updateWorldTransform();
+ vec3.sub(local, this._pos, parent._pos);
+ vec3.transformQuat(local, local, quat.conjugate(q_a, parent._rot));
+ vec3.div(local, local, parent._scale);
+ } else {
+ vec3.copy(this._lpos, this._pos);
+ }
+
+ this.invalidateChildren();
+ this.emit(EventType.TRANSFORM_CHANGED, EventType.POSITION_PART);
+ }
+
+ /**
+ * get world position
+ * @param out - the receiving vector
+ * @returns the resulting vector
+ */
+ public getWorldPosition (out?: Vec3): Vec3 {
+ this.updateWorldTransform();
+ if (out) {
+ return vec3.copy(out, this._pos);
+ } else {
+ return vec3.copy(new Vec3(), this._pos);
+ }
+ }
+
+ /**
+ * Sets world rotation.
+ * @param rotation - The new world rotation.
+ */
+ public setWorldRotation (rotation: Quat): void;
+
+ /**
+ * Sets world rotation.
+ * @param x - The x component of the new world rotation.
+ * @param y - The y component of the new world rotation.
+ * @param z - The z component of the new world rotation.
+ * @param w - The w component of the new world rotation.
+ */
+ public setWorldRotation (x: number, y: number, z: number, w: number): void;
+
+ /**
+ * set world rotation
+ * @param val - the new world rotation, or the x component of it
+ * @param y - the y component of the new world rotation
+ * @param z - the z component of the new world rotation
+ * @param w - the w component of the new world rotation
+ */
+ public setWorldRotation (val: Quat | number, y?: number, z?: number, w?: number) {
+ if (y === undefined || z === undefined || w === undefined) {
+ quat.copy(this._rot, val as Quat);
+ } else if (arguments.length === 4) {
+ quat.set(this._rot, val as number, y, z, w);
+ }
+ if (this._parent) {
+ this._parent.getWorldRotation(q_a);
+ quat.mul(this._lrot, quat.conjugate(q_a, q_a), this._rot);
+ } else {
+ quat.copy(this._lrot, this._rot);
+ }
+ this._eulerDirty = true;
+
+ this.invalidateChildren();
+ this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART);
+ }
+
+ /**
+ * set world rotation from euler angles
+ * @param x - Angle to rotate around X axis in degrees.
+ * @param y - Angle to rotate around Y axis in degrees.
+ * @param z - Angle to rotate around Z axis in degrees.
+ */
+ public setWorldRotationFromEuler (x: number, y: number, z: number) {
+ vec3.set(this._euler, x, y, z);
+ this._eulerDirty = false;
+ quat.fromEuler(this._rot, x, y, z);
+ if (this._parent) {
+ this._parent.getWorldRotation(q_a);
+ quat.mul(this._lrot, this._rot, quat.conjugate(q_a, q_a));
+ } else {
+ quat.copy(this._lrot, this._rot);
+ }
+
+ this.invalidateChildren();
+ this.emit(EventType.TRANSFORM_CHANGED, EventType.ROTATION_PART);
+ }
+
+ /**
+ * get world rotation
+ * @param out - the receiving quaternion
+ * @returns the resulting quaternion
+ */
+ public getWorldRotation (out?: Quat): Quat {
+ this.updateWorldTransform();
+ if (out) {
+ return quat.copy(out, this._rot);
+ } else {
+ return quat.copy(new Quat(), this._rot);
+ }
+ }
+
+ /**
+ * Sets world scale.
+ * @param scale - The new world scale.
+ */
+ public setWorldScale (scale: Vec3): void;
+
+ /**
+ * Sets world scale.
+ * @param x - The x component of the new world scale.
+ * @param y - The y component of the new world scale.
+ * @param z - The z component of the new world scale.
+ */
+ public setWorldScale (x: number, y: number, z: number): void;
+
+ /**
+ * set world scale
+ * @param val - the new world scale, or the x component of it
+ * @param y - the y component of the new world scale
+ * @param z - the z component of the new world scale
+ */
+ public setWorldScale (val: Vec3 | number, y?: number, z?: number) {
+ if (y === undefined || z === undefined) {
+ vec3.copy(this._scale, val as Vec3);
+ } else if (arguments.length === 3) {
+ vec3.set(this._scale, val as number, y, z);
+ }
+ if (this._parent) {
+ this._parent.getWorldScale(v3_a);
+ vec3.div(this._lscale, this._scale, v3_a);
+ } else {
+ vec3.copy(this._lscale, this._scale);
+ }
+
+ this.invalidateChildren();
+ this.emit(EventType.TRANSFORM_CHANGED, EventType.SCALE_PART);
+ }
+
+ /**
+ * get world scale
+ * @param out - the receiving vector
+ * @returns the resulting vector
+ */
+ public getWorldScale (out?: Vec3): Vec3 {
+ this.updateWorldTransform();
+ if (out) {
+ return vec3.copy(out, this._scale);
+ } else {
+ return vec3.copy(new Vec3(), this._scale);
+ }
+ }
+
+ /**
+ * get the matrix that transforms a point from local space into world space
+ * @param out - the receiving matrix
+ * @returns the - resulting matrix
+ */
+ public getWorldMatrix (out?: Mat4): Mat4 {
+ this.updateWorldTransformFull();
+ if (out) {
+ return mat4.copy(out, this._mat);
+ } else {
+ return mat4.copy(new Mat4(), this._mat);
+ }
+ }
+
+ /**
+ * get world transform matrix (with only rotation and scale)
+ * @param out - the receiving matrix
+ * @returns the - resulting matrix
+ */
+ public getWorldRS (out?: Mat4): Mat4 {
+ this.updateWorldTransformFull();
+ if (out === undefined) { out = new Mat4(); }
+ mat4.copy(out, this._mat);
+ out.m12 = 0; out.m13 = 0; out.m14 = 0;
+ return out;
+ }
+
+ /**
+ * get world transform matrix (with only rotation and translation)
+ * @param out - the receiving matrix
+ * @returns the - resulting matrix
+ */
+ public getWorldRT (out?: Mat4): Mat4 {
+ this.updateWorldTransform();
+ if (!out) {
+ out = new Mat4();
+ }
+ return mat4.fromRT(out, this._rot, this._pos);
+ }
+
+ public getAnchorPoint () {
+ if (!this.uiTransfromComp) {
+ return;
+ }
+
+ return this.uiTransfromComp.anchorPoint;
+ }
+
+ public setAnchorPoint (point: Vec2, y: number) {
+ if (!this.uiTransfromComp) {
+ return;
+ }
+
+ this.uiTransfromComp.setAnchorPoint(point, y);
+ }
+
+ public getContentSize () {
+ if (!this.uiTransfromComp) {
+ return;
+ }
+
+ return this.uiTransfromComp.contentSize;
+ }
+
+ public setContentSize (size: Size, height?: number) {
+ if (!this.uiTransfromComp) {
+ return;
+ }
+
+ this.uiTransfromComp.setContentSize(size, height);
+ }
+
+ // EVENT TARGET
+
+ public _checknSetupSysEvent (type) {
+ let newAdded = false;
+ let forDispatch = false;
+ if (_touchEvents.indexOf(type) !== -1) {
+ if (!this._touchListener) {
+ this._touchListener = cc.EventListener.create({
+ event: cc.EventListener.TOUCH_ONE_BY_ONE,
+ swallowTouches: true,
+ owner: this,
+ mask: _searchMaskInParent(this),
+ onTouchBegan: _touchStartHandler,
+ onTouchMoved: _touchMoveHandler,
+ onTouchEnded: _touchEndHandler,
+ onTouchCancelled: _touchCancelHandler,
+ });
+ eventManager.addListener(this._touchListener, this);
+ newAdded = true;
+ }
+ forDispatch = true;
+ } else if (_mouseEvents.indexOf(type) !== -1) {
+ if (!this._mouseListener) {
+ this._mouseListener = cc.EventListener.create({
+ event: cc.EventListener.MOUSE,
+ _previousIn: false,
+ owner: this,
+ mask: _searchMaskInParent(this),
+ onMouseDown: _mouseDownHandler,
+ onMouseMove: _mouseMoveHandler,
+ onMouseUp: _mouseUpHandler,
+ onMouseScroll: _mouseWheelHandler,
+ });
+ eventManager.addListener(this._mouseListener, this);
+ newAdded = true;
+ }
+ forDispatch = true;
+ }
+ if (newAdded && !this._activeInHierarchy) {
+ cc.director.getScheduler().schedule(function () {
+ if (!this._activeInHierarchy) {
+ eventManager.pauseTarget(this);
+ }
+ }, this, 0, 0, 0, false);
+ }
+ return forDispatch;
+ }
+
+ /**
+ * !#en
+ * Register a callback of a specific event type on Node.
+ * Use this method to register touch or mouse event permit propagation based on scene graph,
+ * These kinds of event are triggered with dispatchEvent, the dispatch process has three steps:
+ * 1. Capturing phase: dispatch in capture targets (`_getCapturingTargets`), e.g. parents in node tree, from root to the real target
+ * 2. At target phase: dispatch to the listeners of the real target
+ * 3. Bubbling phase: dispatch in bubble targets (`_getBubblingTargets`), e.g. parents in node tree, from the real target to root
+ * In any moment of the dispatching process, it can be stopped via `event.stopPropagation()` or `event.stopPropagationImmidiate()`.
+ * It's the recommended way to register touch/mouse event for Node,
+ * please do not use cc.eventManager directly for Node.
+ * You can also register custom event and use `emit` to trigger custom event on Node.
+ * For such events, there won't be capturing and bubbling phase, your event will be dispatched directly to its listeners registered on the same node.
+ * You can also pass event callback parameters with `emit` by passing parameters after `type`.
+ * !#zh
+ * 在节点上注册指定类型的回调函数,也可以设置 target 用于绑定响应函数的 this 对象。
+ * 鼠标或触摸事件会被系统调用 dispatchEvent 方法触发,触发的过程包含三个阶段:
+ * 1. 捕获阶段:派发事件给捕获目标(通过 `_getCapturingTargets` 获取),比如,节点树中注册了捕获阶段的父节点,从根节点开始派发直到目标节点。
+ * 2. 目标阶段:派发给目标节点的监听器。
+ * 3. 冒泡阶段:派发事件给冒泡目标(通过 `_getBubblingTargets` 获取),比如,节点树中注册了冒泡阶段的父节点,从目标节点开始派发知道根节点。
+ * 同时您可以将事件派发到父节点或者通过调用 stopPropagation 拦截它。
+ * 推荐使用这种方式来监听节点上的触摸或鼠标事件,请不要在节点上直接使用 cc.eventManager。
+ * 你也可以注册自定义事件到节点上,并通过 emit 方法触发此类事件,对于这类事件,不会发生捕获冒泡阶段,只会直接派发给注册在该节点上的监听器
+ * 你可以通过在 emit 方法调用时在 type 之后传递额外的参数作为事件回调的参数列表
+ * @method on
+ * @param {String|Node.EventType} type - A string representing the event type to listen for. See {{#crossLink "Node/EventTyupe/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events.
+ * @param {Function} callback - The callback that will be invoked when the event is dispatched. The callback is ignored if it is a duplicate (the callbacks are unique).
+ * @param {Event|any} [callback.event] event or first argument when emit
+ * @param {any} [callback.arg2] arg2
+ * @param {any} [callback.arg3] arg3
+ * @param {any} [callback.arg4] arg4
+ * @param {any} [callback.arg5] arg5
+ * @param {Object} [target] - The target (this object) to invoke the callback, can be null
+ * @param {Boolean} [useCapture=false] - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase.
+ * @return {Function} - Just returns the incoming callback so you can save the anonymous function easier.
+ * @typescript
+ * on(type: string, callback: T, target?: any, useCapture?: boolean): T
+ * @example
+ * this.node.on(cc.Node.EventType.TOUCH_START, this.memberFunction, this); // if "this" is component and the "memberFunction" declared in CCClass.
+ * node.on(cc.Node.EventType.TOUCH_START, callback, this);
+ * node.on(cc.Node.EventType.TOUCH_MOVE, callback, this);
+ * node.on(cc.Node.EventType.TOUCH_END, callback, this);
+ * node.on(cc.Node.EventType.TOUCH_CANCEL, callback, this);
+ * node.on(cc.Node.EventType.ANCHOR_CHANGED, callback);
+ */
+ public on (type, callback, target, useCapture?: number) {
+ const forDispatch = this._checknSetupSysEvent(type);
+ if (forDispatch) {
+ return this._onDispatch(type, callback, target, useCapture);
+ } else {
+ // switch (type) {
+ // case EventType.POSITION_CHANGED:
+ // this._eventMask |= POSITION_ON;
+ // break;
+ // case EventType.SCALE_CHANGED:
+ // this._eventMask |= SCALE_ON;
+ // break;
+ // case EventType.ROTATION_CHANGED:
+ // this._eventMask |= ROTATION_ON;
+ // break;
+ // case EventType.SIZE_CHANGED:
+ // this._eventMask |= SIZE_ON;
+ // break;
+ // case EventType.ANCHOR_CHANGED:
+ // this._eventMask |= ANCHOR_ON;
+ // break;
+ // }
+ if (!this._bubblingListeners) {
+ this._bubblingListeners = new DefaultEventTarget();
+ }
+ return this._bubblingListeners.on(type, callback, target);
+ }
+ }
+
+ // /**
+ // * !#en
+ // * Register an callback of a specific event type on the Node,
+ // * the callback will remove itself after the first time it is triggered.
+ // * !#zh
+ // * 注册节点的特定事件类型回调,回调会在第一时间被触发后删除自身。
+ // *
+ // * @method once
+ // * @param {String} type - A string representing the event type to listen for.
+ // * @param {Function} callback - The callback that will be invoked when the event is dispatched.
+ // * The callback is ignored if it is a duplicate (the callbacks are unique).
+ // * @param {Event|any} [callback.event] event or first argument when emit
+ // * @param {any} [callback.arg2] arg2
+ // * @param {any} [callback.arg3] arg3
+ // * @param {any} [callback.arg4] arg4
+ // * @param {any} [callback.arg5] arg5
+ // * @param {Object} [target] - The target (this object) to invoke the callback, can be null
+ // * @typescript
+ // * once(type: string, callback: T, target?: any, useCapture?: boolean): T
+ // * @example
+ // * node.once(cc.Node.EventType.ANCHOR_CHANGED, callback);
+ // */
+ // once(type, callback, target, useCapture) {
+ // let forDispatch = this._checknSetupSysEvent(type);
+ // let eventType_hasOnceListener = '__ONCE_FLAG:' + type;
+
+ // let listeners = null;
+ // if (forDispatch && useCapture) {
+ // listeners = this._capturingListeners = this._capturingListeners || new DefaultEventTarget();
+ // }
+ // else {
+ // listeners = this._bubblingListeners = this._bubblingListeners || new DefaultEventTarget();
+ // }
+
+ // let hasOnceListener = listeners.hasEventListener(eventType_hasOnceListener, callback, target);
+ // if (!hasOnceListener) {
+ // let self = this;
+ // let onceWrapper = function (arg1, arg2, arg3, arg4, arg5) {
+ // self.off(type, onceWrapper, target);
+ // listeners.remove(eventType_hasOnceListener, callback, target);
+ // callback.call(this, arg1, arg2, arg3, arg4, arg5);
+ // };
+ // this.on(type, onceWrapper, target);
+ // listeners.add(eventType_hasOnceListener, callback, target);
+ // }
+ // }
+
+ public _onDispatch (type, callback, target, useCapture) {
+ // Accept also patameters like: (type, callback, useCapture)
+ if (typeof target === 'boolean') {
+ useCapture = target;
+ target = undefined;
+ } else { useCapture = !!useCapture; }
+ if (!callback) {
+ cc.errorID(6800);
+ return;
+ }
+
+ let listeners = null;
+ if (useCapture) {
+ listeners = this._capturingListeners = this._capturingListeners || new DefaultEventTarget();
+ } else {
+ listeners = this._bubblingListeners = this._bubblingListeners || new DefaultEventTarget();
+ }
+
+ if (!listeners.hasEventListener(type, callback, target)) {
+ listeners.add(type, callback, target);
+
+ if (target && target.__eventTargets) {
+ target.__eventTargets.push(this);
+ }
+ }
+
+ return callback;
+ }
+
+ /**
+ * !#en
+ * Removes the callback previously registered with the same type, callback, target and or useCapture.
+ * This method is merely an alias to removeEventListener.
+ * !#zh 删除之前与同类型,回调,目标或 useCapture 注册的回调。
+ * @method off
+ * @param {String} type - A string representing the event type being removed.
+ * @param {Function} [callback] - The callback to remove.
+ * @param {Object} [target] - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed
+ * @param {Boolean} [useCapture=false] - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase.
+ * @example
+ * this.node.off(cc.Node.EventType.TOUCH_START, this.memberFunction, this);
+ * node.off(cc.Node.EventType.TOUCH_START, callback, this.node);
+ * node.off(cc.Node.EventType.ANCHOR_CHANGED, callback, this);
+ */
+ public off (type, callback, target, useCapture?: number) {
+ const touchEvent = _touchEvents.indexOf(type) !== -1;
+ const mouseEvent = !touchEvent && _mouseEvents.indexOf(type) !== -1;
+ if (touchEvent || mouseEvent) {
+ this._offDispatch(type, callback, target, useCapture);
+
+ if (touchEvent) {
+ if (this._touchListener && !_checkListeners(this, _touchEvents)) {
+ eventManager.removeListener(this._touchListener);
+ this._touchListener = null;
+ }
+ } else if (mouseEvent) {
+ if (this._mouseListener && !_checkListeners(this, _mouseEvents)) {
+ eventManager.removeListener(this._mouseListener);
+ this._mouseListener = null;
+ }
+ }
+ } else if (this._bubblingListeners) {
+ this._bubblingListeners.off(type, callback, target);
+
+ const hasListeners = this._bubblingListeners.hasEventListener(type);
+ // All listener removed
+ // if (!hasListeners) {
+ // switch (type) {
+ // case EventType.POSITION_CHANGED:
+ // this._eventMask &= ~POSITION_ON;
+ // break;
+ // case EventType.SCALE_CHANGED:
+ // this._eventMask &= ~SCALE_ON;
+ // break;
+ // case EventType.ROTATION_CHANGED:
+ // this._eventMask &= ~ROTATION_ON;
+ // break;
+ // case EventType.SIZE_CHANGED:
+ // this._eventMask &= ~SIZE_ON;
+ // break;
+ // case EventType.ANCHOR_CHANGED:
+ // this._eventMask &= ~ANCHOR_ON;
+ // break;
+ // }
+ // }
+ }
+ }
+
+ public _offDispatch (type, callback, target, useCapture) {
+ // Accept also patameters like: (type, callback, useCapture)
+ if (typeof target === 'boolean') {
+ useCapture = target;
+ target = undefined;
+ } else { useCapture = !!useCapture; }
+ if (!callback) {
+ this._capturingListeners && this._capturingListeners.removeAll(type);
+ this._bubblingListeners && this._bubblingListeners.removeAll(type);
+ } else {
+ const listeners = useCapture ? this._capturingListeners : this._bubblingListeners;
+ if (listeners) {
+ listeners.remove(type, callback, target);
+
+ if (target && target.__eventTargets) {
+ js.array.fastRemove(target.__eventTargets, this);
+ }
+ }
+
+ }
+ }
+
+ /**
+ * !#en
+ * Trigger an event directly with the event name and necessary arguments.
+ * !#zh
+ * 通过事件名发送自定义事件
+ *
+ * @method emit
+ * @param {String} type - event type
+ * @param {*} [arg1] - First argument in callback
+ * @param {*} [arg2] - Second argument in callback
+ * @param {*} [arg3] - Third argument in callback
+ * @param {*} [arg4] - Fourth argument in callback
+ * @param {*} [arg5] - Fifth argument in callback
+ * @example
+ *
+ * eventTarget.emit('fire', event);
+ * eventTarget.emit('fire', message, emitter);
+ */
+ public emit (type, ...args: any[]) {
+ if (this._bubblingListeners) {
+ this._bubblingListeners.emit(type, ...args);
+ }
+ }
+
+ /**
+ * !#en
+ * Dispatches an event into the event flow.
+ * The event target is the EventTarget object upon which the dispatchEvent() method is called.
+ * !#zh 分发事件到事件流中。
+ *
+ * @method dispatchEvent
+ * @param {Event} event - The Event object that is dispatched into the event flow
+ */
+ public dispatchEvent (event) {
+ _doDispatchEvent(this, event);
+ _cachedArray.length = 0;
+ }
+}
+
+if (CC_EDITOR) {
+ const repeat = (t: number, l: number) => t - Math.floor(t / l) * l;
+ Object.defineProperty(Node.prototype, 'eulerAngles', {
+ set (val: Vec3) {
+ this.setRotationFromEuler(val.x, val.y, val.z);
+ },
+ get () {
+ if (this._eulerDirty) {
+ const eu = this._euler;
+ quat.toEuler(v3_a, this._lrot);
+ eu.x = repeat(v3_a.x - eu.x + 180, 360) + eu.x - 180;
+ eu.y = repeat(v3_a.y - eu.y + 180, 360) + eu.y - 180;
+ eu.z = repeat(v3_a.z - eu.z + 180, 360) + eu.z - 180;
+ this._eulerDirty = false;
+ }
+ return this._euler;
+ },
+ });
+}
+
+cc.Node = Node;
+export { Node };
diff --git a/cocos/scene-graph/private-node.js b/cocos/scene-graph/private-node.js
index 50c22cb9bf..f17569b64e 100644
--- a/cocos/scene-graph/private-node.js
+++ b/cocos/scene-graph/private-node.js
@@ -25,7 +25,7 @@
'use strict';
-import Node from './node';
+import { Node } from './node';
import { ccclass, property } from '../core/data/class-decorator';
const LocalDirtyFlag = Node._LocalDirtyFlag;
@@ -164,4 +164,4 @@ export default class PrivateNode extends Node {
cc.js.getset(PrivateNode.prototype, "parent", PrivateNode.prototype.getParent, PrivateNode.prototype.setParent);
cc.js.getset(PrivateNode.prototype, "position", PrivateNode.prototype.getPosition, PrivateNode.prototype.setPosition);
-cc.PrivateNode = PrivateNode;
\ No newline at end of file
+cc.PrivateNode = PrivateNode;
diff --git a/cocos/scene-graph/scene.js b/cocos/scene-graph/scene.js
index d1cee7d257..e35a4bdef8 100644
--- a/cocos/scene-graph/scene.js
+++ b/cocos/scene-graph/scene.js
@@ -23,8 +23,9 @@
THE SOFTWARE.
****************************************************************************/
-import Node from './node';
+import { Node } from './node';
import { ccclass, property } from '../core/data/class-decorator';
+import { BaseNode } from './base-node';
/**
* !#en
@@ -38,6 +39,7 @@ import { ccclass, property } from '../core/data/class-decorator';
*/
@ccclass("cc.Scene")
export default class Scene extends Node {
+
constructor(name) {
super(name);
@@ -50,6 +52,10 @@ export default class Scene extends Node {
// cache all depend assets for auto release
this.dependAssets = null;
+
+ if (cc.director && cc.director.root) {
+ this._renderScene = cc.director.root.createScene({});
+ }
}
/**
@@ -58,20 +64,21 @@ export default class Scene extends Node {
* @property {Boolean} autoReleaseAssets
* @default false
*/
- @property({
+ @property({
type: cc.Boolean
- })
+ })
autoReleaseAssets = undefined;
- destroy () {
+ destroy() {
super.destroy();
+ cc.director.root.destroyScene(this._renderScene);
this._activeInHierarchy = false;
}
- _onHierarchyChanged() {}
- _instantiate() {}
+ _onHierarchyChanged() { }
+ _instantiate() { }
- _load () {
+ _load() {
if (!this._inited) {
if (CC_TEST) {
cc.assert(!this._activeInHierarchy, 'Should deactivate ActionManager and EventManager by default');
@@ -84,9 +91,10 @@ export default class Scene extends Node {
}
this._inited = true;
}
+ this.walk(BaseNode._setScene);
}
- _activate (active) {
+ _activate(active) {
active = (active !== false);
if (CC_EDITOR || CC_TEST) {
// register all nodes to editor
diff --git a/docs/apisrc.json b/docs/apisrc.json
index 2c235ed36c..a0e00ced60 100644
--- a/docs/apisrc.json
+++ b/docs/apisrc.json
@@ -17,12 +17,12 @@
"./cocos2d/audio/**/*",
"./cocos2d/core/CCDebug.js",
- "./cocos2d/core/CCDirector.js",
+ "./cocos2d/core/director.js",
"./cocos2d/core/CCNode.js",
"./cocos2d/core/CCPrivateNode.js",
"./cocos2d/core/CCScene.js",
- "./cocos2d/core/CCGame.js",
- "./cocos2d/core/CCScheduler.js",
+ "./cocos2d/core/game.js",
+ "./cocos2d/core/scheduler.js",
"./cocos2d/core/assets/**/*",
@@ -42,7 +42,7 @@
"!./cocos2d/core/load-pipeline/asset-table.js",
"./cocos2d/core/physics/**/*",
-
+
"./cocos2d/core/platform/**/*",
"!./cocos2d/core/platform/BKInputManager.js",
"!./cocos2d/core/platform/CCAssetLibrary.js",
@@ -79,4 +79,4 @@
"./extensions/ccpool/*.js",
"./extensions/spine/*.js",
"./extensions/dragonbones/*.js"
-]
\ No newline at end of file
+]
diff --git a/globals.d.ts b/globals.d.ts
new file mode 100644
index 0000000000..8c476a4668
--- /dev/null
+++ b/globals.d.ts
@@ -0,0 +1,57 @@
+/****************************************************************************
+ 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.
+ ****************************************************************************/
+
+declare const CC_BUILD: boolean;
+declare const CC_TEST: boolean;
+declare const CC_EDITOR: boolean;
+declare const CC_PREVIEW: boolean;
+declare const CC_DEV: boolean;
+declare const CC_DEBUG: boolean;
+declare const CC_JSB: boolean;
+declare const CC_WECHATGAME_SUB: boolean;
+declare const CC_WECHATGAME: boolean;
+declare const CC_QQPLAY: boolean;
+declare const CC_RUNTIME: boolean;
+declare const CC_SUPPORT_JIT: boolean;
+
+declare const cc: any;
+
+declare const _cc: any;
+
+type RecursivePartial = {
+ [P in keyof T]?:
+ T[P] extends Array ? Array> :
+ T[P] extends ReadonlyArray ? ReadonlyArray> : RecursivePartial;
+};
+
+declare module "webgl-debug" {
+ export function makeDebugContext(
+ webGLRenderingContext: WebGLRenderingContext,
+ throwOnGLError: (err: GLenum, funcName: string, ...args: any[]) => void
+ ): WebGLRenderingContext;
+
+ export function glEnumToString(glEnum: GLenum): string;
+}
\ No newline at end of file
diff --git a/index.js b/index.js
index c68709743e..f301a466cc 100644
--- a/index.js
+++ b/index.js
@@ -31,12 +31,16 @@ import cc from './predefine';
// LOAD ENGINE CORE
export * from './cocos/core';
export * from './cocos/scene-graph';
-export * from './cocos/renderer';
+import * as renderer from './cocos/renderer';
+export { renderer };
+cc.renderer = renderer;
export * from './cocos/assets';
export * from './cocos/load-pipeline';
export * from './cocos/components';
export * from './cocos/animation';
export * from './cocos/3d';
+export * from './cocos/gfx';
+export * from './cocos/pipeline';
// export default cc;
diff --git a/package.json b/package.json
index a4635ad24b..7e5cabdfa4 100644
--- a/package.json
+++ b/package.json
@@ -77,6 +77,7 @@
"vinyl-buffer": "1.0.0",
"vinyl-source-stream": "1.0.0",
"watchify": "^3.7.0",
+ "webgl-debug": "github:cocos-creator/webgl-debug#4e535ed",
"yargs": "^12.0.5"
}
}
diff --git a/playground/camera.js b/playground/camera.js
new file mode 100644
index 0000000000..ed608e6761
--- /dev/null
+++ b/playground/camera.js
@@ -0,0 +1,233 @@
+// camera
+
+ "use strict";
+
+var _dec, _class;
+
+function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
+
+function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
+
+function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
+
+function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
+
+function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
+
+function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
+
+function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
+
+function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
+
+function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
+
+var FirstPersonCamera = (_dec = cc._decorator.ccclass(), _dec(_class =
+/*#__PURE__*/
+function (_cc$Component) {
+ _inherits(FirstPersonCamera, _cc$Component);
+
+ function FirstPersonCamera() {
+ var _this;
+
+ _classCallCheck(this, FirstPersonCamera);
+
+ _this = _possibleConstructorReturn(this, _getPrototypeOf(FirstPersonCamera).call(this));
+ _this._lbtnDown = false;
+ _this._rbtnDown = false;
+ _this._keyStates = new Array(128);
+
+ _this._keyStates.fill(false);
+
+ return _this;
+ }
+
+ _createClass(FirstPersonCamera, [{
+ key: "start",
+ value: function start() {
+ var _this2 = this;
+
+ var cameraComponent = this.node.getComponent("cc.CameraComponent");
+
+ if (!cameraComponent) {
+ console.error("Cannot find cc.CameraComponent on node ".concat(this.node.name));
+ }
+
+ cc.eventManager.setEnabled(true);
+ var mouseListener = cc.EventListener.create({
+ event: cc.EventListener.MOUSE,
+ onMouseDown: function onMouseDown() {
+ return _this2._mouseDownHandler.apply(_this2, arguments);
+ },
+ onMouseMove: function onMouseMove() {
+ return _this2._mouseMoveHandler.apply(_this2, arguments);
+ },
+ onMouseUp: function onMouseUp() {
+ return _this2._mouseUpHandler.apply(_this2, arguments);
+ },
+ onMouseScroll: function onMouseScroll() {
+ return _this2._mouseWheelHandler.apply(_this2, arguments);
+ }
+ });
+ cc.eventManager.addListener(mouseListener, 1);
+ var keyListener = cc.EventListener.create({
+ event: cc.EventListener.KEYBOARD,
+ onKeyPressed: function onKeyPressed() {
+ return _this2._keyDownHandler.apply(_this2, arguments);
+ },
+ onKeyReleased: function onKeyReleased() {
+ return _this2._keyUpHandler.apply(_this2, arguments);
+ }
+ });
+ cc.eventManager.addListener(keyListener, 1);
+ }
+ }, {
+ key: "update",
+ value: function update(dt) {
+ var _this3 = this;
+
+ var translationDelta = dt * 10;
+
+ var isKeyPressing = function isKeyPressing(keystr) {
+ return _this3._keyStates[keystr.charCodeAt(0)];
+ };
+
+ if (isKeyPressing("W")) {
+ this._translate(this._getForward(), translationDelta);
+ }
+
+ if (isKeyPressing("S")) {
+ this._translate(this._getForward(), -translationDelta);
+ }
+
+ if (isKeyPressing("A")) {
+ this._translate(this._getRight(), -translationDelta);
+ }
+
+ if (isKeyPressing("D")) {
+ this._translate(this._getRight(), translationDelta);
+ }
+
+ if (isKeyPressing("Q")) {
+ this._translate(cc.v3(0, 1, 0), -translationDelta);
+ }
+
+ if (isKeyPressing("E")) {
+ this._translate(cc.v3(0, 1, 0), translationDelta);
+ }
+ }
+ }, {
+ key: "_mouseWheelHandler",
+ value: function _mouseWheelHandler(event) {
+ var delta = event._scrollY / 120; // forward to screen is positive
+
+ this._translate(this._getForward(), delta);
+ }
+ }, {
+ key: "_mouseDownHandler",
+ value: function _mouseDownHandler(event) {
+ if (event._button === 0) {
+ this._lbtnDown = true;
+ } else if (event._button === 1) {
+ this._mbtnDown = true;
+ } else if (event._button === 2) {
+ cc.game.canvas.requestPointerLock();
+ this._rbtnDown = true;
+ }
+ }
+ }, {
+ key: "_mouseUpHandler",
+ value: function _mouseUpHandler(event) {
+ if (event._button === 0) {
+ this._lbtnDown = false;
+ } else if (event._button === 1) {
+ this._mbtnDown = false;
+ } else if (event._button === 2) {
+ document.exitPointerLock();
+ this._rbtnDown = false;
+ }
+ }
+ }, {
+ key: "_mouseMoveHandler",
+ value: function _mouseMoveHandler(event) {
+ var dx = event.movementX;
+ var dy = -event.movementY;
+
+ if (dx !== 0) {
+ if (this._rbtnDown) {
+ this._rotateSelfHorizon(dx / 5);
+ }
+ }
+
+ if (dy !== 0) {
+ if (this._rbtnDown) {
+ this._rotateSelfVertical(dy / 5);
+ }
+ }
+ }
+ }, {
+ key: "_keyDownHandler",
+ value: function _keyDownHandler(keycode) {
+ if (keycode < this._keyStates.length) {
+ this._keyStates[keycode] = true;
+ }
+ }
+ }, {
+ key: "_keyUpHandler",
+ value: function _keyUpHandler(keycode) {
+ if (keycode < this._keyStates.length) {
+ this._keyStates[keycode] = false;
+ }
+ }
+ }, {
+ key: "_translate",
+ value: function _translate(direction, delta) {
+ var position = this.node.getPosition();
+ cc.vmath.vec3.scaleAndAdd(position, position, direction, delta);
+ this.node.setPosition(position);
+ }
+ }, {
+ key: "_rotateSelfHorizon",
+ value: function _rotateSelfHorizon(delta) {
+ var rotation = this.node.getRotation();
+ var up = cc.v3(0, 1, 0); //const up = this._getUp();
+
+ cc.vmath.quat.rotateAround(rotation, rotation, up, -delta / 360.0 * 3.14159265);
+ this.node.setRotation(rotation);
+ }
+ }, {
+ key: "_rotateSelfVertical",
+ value: function _rotateSelfVertical(delta) {
+ var rotation = this.node.getRotation(); //const right = cc.v3(1, 0, 0);
+
+ var right = this._getRight();
+
+ cc.vmath.quat.rotateAround(rotation, rotation, right, delta / 360.0 * 3.14159265);
+ this.node.setRotation(rotation);
+ }
+ }, {
+ key: "_getForward",
+ value: function _getForward() {
+ return this._getDirection(0, 0, -1);
+ }
+ }, {
+ key: "_getRight",
+ value: function _getRight() {
+ return this._getDirection(1, 0, 0);
+ }
+ }, {
+ key: "_getUp",
+ value: function _getUp() {
+ return this._getDirection(0, 1, 0);
+ }
+ }, {
+ key: "_getDirection",
+ value: function _getDirection(x, y, z) {
+ var result = cc.v3(x, y, z);
+ cc.vmath.vec3.transformQuat(result, result, this.node.getRotation());
+ return result;
+ }
+ }]);
+
+ return FirstPersonCamera;
+}(cc.Component)) || _class);
diff --git a/playground/cocos2d-x.png b/playground/cocos2d-x.png
new file mode 100644
index 0000000000..6a78452419
Binary files /dev/null and b/playground/cocos2d-x.png differ
diff --git a/playground/cubetexture.png b/playground/cubetexture.png
new file mode 100644
index 0000000000..078b19a569
Binary files /dev/null and b/playground/cubetexture.png differ
diff --git a/playground/files.js b/playground/files.js
index af6dc0f92c..9964bb6342 100644
--- a/playground/files.js
+++ b/playground/files.js
@@ -1,6 +1,7 @@
window.files = {
"aa": [
- "simple"
+ "simple",
+ "ui"
],
// "animation": [
// "spec-skeleton"
diff --git a/playground/gizmo.html b/playground/gizmo.html
new file mode 100644
index 0000000000..e85417c61f
--- /dev/null
+++ b/playground/gizmo.html
@@ -0,0 +1,154 @@
+
+
+
+
+ gizmo
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/playground/simple.html b/playground/simple.html
index 7442f8e105..93fcfb7096 100644
--- a/playground/simple.html
+++ b/playground/simple.html
@@ -2,7 +2,7 @@
- spec-scroll-view
+ simple
+
+
+
+
+
+
+
+
+
+
diff --git a/rollup/build-engine.ts b/rollup/build-engine.ts
index 4a437caf29..7586926293 100644
--- a/rollup/build-engine.ts
+++ b/rollup/build-engine.ts
@@ -66,6 +66,7 @@ async function _doBundle (options: IBuildOptions) {
commonjs({
namedExports: {
cannon: ['CANNON', 'Shape'],
+ 'webgl-debug': ['makeDebugContext', 'glEnumToString'],
},
}),
];
diff --git a/rollup/config.js b/rollup/config.js
index 1bc59f2ff8..58c99afb04 100644
--- a/rollup/config.js
+++ b/rollup/config.js
@@ -60,7 +60,8 @@ export default {
commonjs({
namedExports: {
- 'cannon': ['CANNON']
+ 'cannon': ['CANNON'],
+ 'webgl-debug': ['makeDebugContext', 'glEnumToString']
}
}),
]
diff --git a/tsconfig.json b/tsconfig.json
new file mode 100644
index 0000000000..19b0f7c62d
--- /dev/null
+++ b/tsconfig.json
@@ -0,0 +1,63 @@
+{
+ "compilerOptions": {
+ /* Basic Options */
+ "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */
+ "lib": ["es2015", "es2017", "dom"],
+ "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
+ // "lib": [], /* Specify library files to be included in the compilation. */
+ "allowJs": false, /* Allow javascript files to be compiled. */
+ // "checkJs": true, /* Report errors in .js files. */
+ // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
+ // "declaration": true, /* Generates corresponding '.d.ts' file. */
+ // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
+ "sourceMap": true, /* Generates corresponding '.map' file. */
+ // "outFile": "./", /* Concatenate and emit output to single file. */
+ "outDir": "./dist", /* Redirect output structure to the directory. */
+ "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
+ // "composite": true, /* Enable project compilation */
+ // "removeComments": true, /* Do not emit comments to output. */
+ // "noEmit": true, /* Do not emit outputs. */
+ // "importHelpers": true, /* Import emit helpers from 'tslib'. */
+ // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
+ // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
+
+ /* Strict Type-Checking Options */
+ "strict": true, /* Enable all strict type-checking options. */
+ "noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */
+ // "strictNullChecks": true, /* Enable strict null checks. */
+ // "strictFunctionTypes": true, /* Enable strict checking of function types. */
+ // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
+ // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
+ // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
+ // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
+
+ /* Additional Checks */
+ // "noUnusedLocals": true, /* Report errors on unused locals. */
+ // "noUnusedParameters": true, /* Report errors on unused parameters. */
+ // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
+ // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
+
+ /* Module Resolution Options */
+ // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
+ // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
+ // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
+ // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
+ // "typeRoots": [], /* List of folders to include type definitions from. */
+ // "types": [], /* Type declaration files to be included in compilation. */
+ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
+ "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
+ // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
+
+ /* Source Map Options */
+ // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
+ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
+ // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
+ // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
+
+ /* Experimental Options */
+ "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
+ // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
+ }
+ //"include" : ["./source"]
+ //"exclude" : ["js"]
+ }
diff --git a/tslint.json b/tslint.json
index f1676c13ea..605e6fb73e 100644
--- a/tslint.json
+++ b/tslint.json
@@ -5,12 +5,23 @@
],
"jsRules": {},
"rules": {
- "quotemark": [ true, "single" ],
+ "quotemark": [
+ true,
+ "single"
+ ],
+ "one-line": [
+ true,
+ "check-open-brace"
+ ],
"no-console": false,
"space-before-function-paren": true,
"max-classes-per-file": false,
"variable-name": false,
- "object-literal-sort-keys": false
+ "object-literal-sort-keys": false,
+ "ban-types": false,
+ "no-bitwise": false,
+ "no-empty": false,
+ "radix": false,
},
"rulesDirectory": []
}
diff --git a/wx.d.ts b/wx.d.ts
new file mode 100644
index 0000000000..12434cc7fc
--- /dev/null
+++ b/wx.d.ts
@@ -0,0 +1,11 @@
+
+declare interface IWXEventManager {
+ (listener: (event: Event) => void): void;
+}
+
+declare namespace wx {
+ const onTouchStart: IWXEventManager;
+ const onTouchMove: IWXEventManager;
+ const onTouchEnd: IWXEventManager;
+ const onTouchCancel: IWXEventManager;
+}