Merge pull request #3787 from jerrywwl/3d

3d
This commit is contained in:
Weiliang Wang
2019-01-25 18:48:57 +08:00
committed by GitHub
371 changed files with 38335 additions and 28970 deletions
+9 -8
View File
@@ -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
}
}
+2
View File
@@ -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
+19 -19
View File
@@ -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.
+1 -1
View File
@@ -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
@@ -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;
}
-620
View File
@@ -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;
@@ -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;
-443
View File
@@ -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) <br/>
* The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold. <br/>
* Should be a float between 0 and 1. <br/>
* 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 模式)<br/>
* 只有当模板的像素的 alpha 大于 alphaThreshold 时,才会绘制内容。<br/>
* 该数值 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;
-224
View File
@@ -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;
-661
View File
@@ -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;
+81 -69
View File
@@ -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;
+51 -52
View File
@@ -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;
@@ -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);
@@ -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
}
@@ -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;
}
}
};
@@ -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;
}
},
};
@@ -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;
}
};
@@ -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;
}
}
},
};
@@ -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;
}
},
};
-687
View File
@@ -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<br/>
* When Button state changed:<br/>
* If Transition type is Button.Transition.NONE, Button will do nothing<br/>
* If Transition type is Button.Transition.COLOR, Button will change target's color<br/>
* If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite<br/>
* If Transition type is Button.Transition.SCALE, Button will change target node's scale<br/>
*
* Button will trigger 5 events:<br/>
* Button.EVENT_TOUCH_DOWN<br/>
* Button.EVENT_TOUCH_UP<br/>
* Button.EVENT_HOVER_IN<br/>
* Button.EVENT_HOVER_MOVE<br/>
* Button.EVENT_HOVER_OUT<br/>
*
* !#zh
* 按钮组件。可以被按下,或者点击。<br/>
*
* 按钮可以通过修改 Transition 来设置按钮状态过渡的方式:<br/>
* -Button.Transition.NONE // 不做任何过渡<br/>
* -Button.Transition.COLOR // 进行颜色之间过渡<br/>
* -Button.Transition.SPRITE // 进行精灵之间过渡<br/>
* -Button.Transition.SCALE // 进行缩放过渡<br/>
*
* 按钮可以绑定事件(但是必须要在按钮的 Node 上才能绑定事件):<br/>
* // 以下事件可以在全平台上都触发<br/>
* -cc.Node.EventType.TOUCH_START // 按下时事件<br/>
* -cc.Node.EventType.TOUCH_Move // 按住移动后事件<br/>
* -cc.Node.EventType.TOUCH_END // 按下后松开后事件<br/>
* -cc.Node.EventType.TOUCH_CANCEL // 按下取消事件<br/>
* // 以下事件只在 PC 平台上触发<br/>
* -cc.Node.EventType.MOUSE_DOWN // 鼠标按下时事件<br/>
* -cc.Node.EventType.MOUSE_MOVE // 鼠标按住移动后事件<br/>
* -cc.Node.EventType.MOUSE_ENTER // 鼠标进入目标事件<br/>
* -cc.Node.EventType.MOUSE_LEAVE // 鼠标离开目标事件<br/>
* -cc.Node.EventType.MOUSE_UP // 鼠标松开事件<br/>
* -cc.Node.EventType.MOUSE_WHEEL // 鼠标滚轮事件<br/>
*
* @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.
*/
-297
View File
@@ -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;
-357
View File
@@ -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;
-240
View File
@@ -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.
*/
-243
View File
@@ -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.
*/
-685
View File
@@ -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;
-729
View File
@@ -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
*/
-648
View File
@@ -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;
-398
View File
@@ -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<string, number>}
*/
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);
}
}
+319
View File
@@ -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<string, number> = 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);
}
}
}
+2 -2
View File
@@ -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;
cc.AudioClip = AudioClip;
+1 -1
View File
@@ -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 {
-46
View File
@@ -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;
+108
View File
@@ -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<string, IPropertyInfo>;
}
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<string, string>;
}
const effects: Record<string, EffectAsset> = {};
@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<string, EffectAsset> = {};
@property
public techniques: ITechniqueInfo[] = [];
@property
public shaders: IShaderInfo[] = [];
public onLoaded () {
this.shaders.forEach((s) => programLib.define(s));
EffectAsset.register(this);
}
}
cc.EffectAsset = EffectAsset;
+6 -6
View File
@@ -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;
cc.Font = Font;
+5 -5
View File
@@ -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";
-149
View File
@@ -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;
+247
View File
@@ -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<Record<string, any>> = [];
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;
-272
View File
@@ -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;
+530
View File
@@ -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<IRenderingSubmesh | null>,
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;
+4 -5
View File
@@ -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 {
+1 -1
View File
@@ -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')
@@ -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;
// tslint:disable-next-line
cc['Skeleton'] = Skeleton;
+2 -2
View File
@@ -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;
cc.Sprite = Sprite;
-285
View File
@@ -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)<br>
* 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)<br/>
* 销毁后,该对象不再可用。您可以在访问对象之前使用 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;
+225
View File
@@ -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)<br>
* 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)<br/>
* 销毁后,该对象不再可用。您可以在访问对象之前使用 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);
}
+2 -3
View File
@@ -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')
@@ -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;
}
+83 -31
View File
@@ -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": {}
}
]
}
View File
+3
View File
@@ -0,0 +1,3 @@
export * from './init';
export { default as effects } from './effects';
-112
View File
@@ -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;
+138
View File
@@ -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<string, Asset> = {};
// 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<T extends Asset> (uuid: string): T {
return this._resources[uuid] as T;
}
}
const builtinResMgr = cc.builtinResMgr = new BuiltinResMgr();
export { builtinResMgr };
+1 -1
View File
@@ -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);
+1 -1
View File
@@ -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';
+1 -1
View File
@@ -1,4 +1,4 @@
import { renderer } from '../renderer';
import * as renderer from '../renderer';
import { vec3, color3 } from '../vmath';
import { Node } from '../scene-graph';
-495
View File
@@ -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);
}
}
+426
View File
@@ -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);
}
}
-63
View File
@@ -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);
// }
// }
// }
}
@@ -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;
}
}
+2 -2
View File
@@ -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';
-443
View File
@@ -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);
}
}
+306
View File
@@ -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;
}
}
-281
View File
@@ -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'];
}
}
+289
View File
@@ -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<Material>('default-material');
}
}
@@ -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)));
}
@@ -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;
@@ -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);
}
@@ -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;
}
}
}
@@ -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<ColorKey>();
@property
alphaKeys = []
public alphaKeys = new Array<AlphaKey>();
@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;
}
}
@@ -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);
@@ -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;
}
}
}
@@ -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<OptimizedKey>(); // 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<number>(); // 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;
}
}
}
@@ -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!
@@ -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))!);
}
}
}
@@ -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));
}
}
}
@@ -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))!);
}
}
@@ -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);
@@ -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);
@@ -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;
}
}
@@ -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);
@@ -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";
@@ -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 });
@@ -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 });
+1 -1
View File
@@ -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';
@@ -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) {
@@ -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';
@@ -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,
};
+4 -2
View File
@@ -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<PhysicsWorld>(this._cannonWorld, this);
-21
View File
@@ -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;
}
}
-41
View File
@@ -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;
}
}
@@ -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<Material | null> = [];
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 () {
}
}
-176
View File
@@ -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;
}
}
@@ -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<string, Node>}
*/
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);
});
}
}
@@ -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<string, Node>;
/**
* !#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;
}
@@ -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();
// }
// }
}
-120
View File
@@ -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);
}
}
+106
View File
@@ -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; }
}
}
@@ -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;
}
}
@@ -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: [],
});
-119
View File
@@ -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);
}
}
}

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