This commit is contained in:
jerrywwl
2019-04-10 17:04:13 +08:00
55 changed files with 3481 additions and 3907 deletions
+8 -8
View File
@@ -37,11 +37,11 @@
* node.parent = this.node;
*/
import { Component } from '../../components/component';
import { Color } from '../../core/value-types';
import { LabelComponent } from '../../3d/ui/components/label-component';
import { UIComponent } from '../../3d/ui/components/ui-component';
import { Color } from '../../core/value-types';
export class LabelOutline extends Component {
export class LabelOutlineComponent extends UIComponent {
private _color = new Color(255, 255, 255, 255);
private _width = 1;
@@ -57,8 +57,8 @@ export class LabelOutline extends Component {
return this._color;
}
set color (value) {
if(this._color === value){
return
if (this._color === value){
return;
}
this._color = value;
@@ -73,11 +73,11 @@ export class LabelOutline extends Component {
* @example
* outline.width = 3;
*/
get width() {
get width () {
return this._width;
}
set width(value) {
set width (value) {
if (this._width === value) {
return;
}
@@ -94,4 +94,4 @@ export class LabelOutline extends Component {
}
}
cc.LabelOutline = LabelOutline;
cc.LabelOutlineComponent = LabelOutlineComponent;
-855
View File
@@ -1,855 +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 js = require('../platform/js');
const macro = require('../platform/CCMacro');
const textUtils = require('../utils/text-utils');
const HtmlTextParser = require('../utils/html-text-parser');
const _htmlTextParser = new HtmlTextParser();
const HorizontalAlign = macro.TextAlignment;
const VerticalAlign = macro.VerticalTextAlignment;
const RichTextChildName = "RICHTEXT_CHILD";
const RichTextChildImageName = "RICHTEXT_Image_CHILD";
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
let timeout;
return function () {
let context = this;
let later = function () {
timeout = null;
if (!immediate) func.apply(context, arguments);
};
let callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, arguments);
};
}
/**
* RichText pool
*/
let pool = new js.Pool(function (node) {
if (CC_EDITOR) {
return false;
}
if (CC_DEV) {
cc.assert(!node._parent, 'Recycling node\'s parent should be null!');
}
if (!cc.isValid(node)) {
return false;
}
else if (node.getComponent(cc.LabelOutline)) {
return false;
}
return true;
}, 20);
pool.get = function (string, fontAsset, fontSize) {
let labelNode = this._get();
if (!labelNode) {
labelNode = new cc.PrivateNode(RichTextChildName);
}
let labelComponent = labelNode.getComponent(cc.Label);
if (!labelComponent) {
labelComponent = labelNode.addComponent(cc.Label);
}
labelNode.setPosition(0, 0);
labelNode.setAnchorPoint(0.5, 0.5);
labelNode.setContentSize(128, 128);
labelNode.skewX = 0;
if (typeof string !== 'string') {
string = '' + string;
}
let isAsset = fontAsset instanceof cc.Font;
if (isAsset) {
labelComponent.font = fontAsset;
} else {
labelComponent.fontFamily = "Arial";
}
labelComponent.string = string;
labelComponent.horizontalAlign = HorizontalAlign.LEFT;
labelComponent.verticalAlign = VerticalAlign.TOP;
labelComponent.fontSize = fontSize || 40;
labelComponent.overflow = 0;
labelComponent.enableWrapText = true;
labelComponent.lineHeight = 40;
labelComponent._enableBold(false);
labelComponent._enableItalics(false);
labelComponent._enableUnderline(false);
return labelNode;
};
/**
* !#en The RichText Component.
* !#zh 富文本组件
* @class RichText
* @extends Component
*/
let RichText = cc.Class({
name: 'cc.RichText',
extends: cc.Component,
ctor: function () {
this._textArray = null;
this._labelSegments = [];
this._labelSegmentsCache = [];
this._linesWidth = [];
if (CC_EDITOR) {
this._updateRichTextStatus = debounce(this._updateRichText, 200);
}
else {
this._updateRichTextStatus = this._updateRichText;
}
},
editor: CC_EDITOR && {
menu: 'i18n:MAIN_MENU.component.renderers/RichText',
help: 'i18n:COMPONENT.help_url.richtext',
executeInEditMode: true
},
properties: {
/**
* !#en Content string of RichText.
* !#zh 富文本显示的文本内容。
* @property {String} string
*/
string: {
default: '<color=#00ff00>Rich</c><color=#0fffff>Text</color>',
multiline: true,
tooltip: CC_DEV && 'i18n:COMPONENT.richtext.string',
notify: function () {
this._updateRichTextStatus();
}
},
/**
* !#en Horizontal Alignment of each line in RichText.
* !#zh 文本内容的水平对齐方式。
* @property {macro.TextAlignment} horizontalAlign
*/
horizontalAlign: {
default: HorizontalAlign.LEFT,
type: HorizontalAlign,
tooltip: CC_DEV && 'i18n:COMPONENT.richtext.horizontal_align',
animatable: false,
notify: function (oldValue) {
if (this.horizontalAlign === oldValue) return;
this._layoutDirty = true;
this._updateRichTextStatus();
}
},
/**
* !#en Font size of RichText.
* !#zh 富文本字体大小。
* @property {Number} fontSize
*/
fontSize: {
default: 40,
tooltip: CC_DEV && 'i18n:COMPONENT.richtext.font_size',
notify: function (oldValue) {
if (this.fontSize === oldValue) return;
this._layoutDirty = true;
this._updateRichTextStatus();
}
},
/**
* !#en Custom TTF font of RichText
* !#zh 富文本定制字体
* @property {cc.TTFFont} font
*/
font: {
default: null,
type: cc.TTFFont,
tooltip: CC_DEV && 'i18n:COMPONENT.richtext.font',
notify: function (oldValue) {
if (this.font === oldValue) return;
this._layoutDirty = true;
if (this.font) {
this._onTTFLoaded();
}
this._updateRichTextStatus();
}
},
/**
* !#en The maximize width of the RichText
* !#zh 富文本的最大宽度
* @property {Number} maxWidth
*/
maxWidth: {
default: 0,
tooltip: CC_DEV && 'i18n:COMPONENT.richtext.max_width',
notify: function (oldValue) {
if (this.maxWidth === oldValue) return;
this._layoutDirty = true;
this._updateRichTextStatus();
}
},
/**
* !#en Line Height of RichText.
* !#zh 富文本行高。
* @property {Number} lineHeight
*/
lineHeight: {
default: 40,
tooltip: CC_DEV && 'i18n:COMPONENT.richtext.line_height',
notify: function (oldValue) {
if (this.lineHeight === oldValue) return;
this._layoutDirty = true;
this._updateRichTextStatus();
}
},
/**
* !#en The image atlas for the img tag. For each src value in the img tag, there should be a valid spriteFrame in the image atlas.
* !#zh 对于 img 标签里面的 src 属性名称,都需要在 imageAtlas 里面找到一个有效的 spriteFrame,否则 img tag 会判定为无效。
* @property {SpriteAtlas} imageAtlas
*/
imageAtlas: {
default: null,
type: cc.SpriteAtlas,
tooltip: CC_DEV && 'i18n:COMPONENT.richtext.image_atlas',
notify: function (oldValue) {
if (this.imageAtlas === oldValue) return;
this._layoutDirty = true;
this._updateRichTextStatus();
}
},
/**
* !#en
* Once checked, the RichText will block all input events (mouse and touch) within
* the bounding box of the node, preventing the input from penetrating into the underlying node.
* !#zh
* 选中此选项后,RichText 将阻止节点边界框中的所有输入事件(鼠标和触摸),从而防止输入事件穿透到底层节点。
* @property {Boolean} handleTouchEvent
* @default true
*/
handleTouchEvent: {
default: true,
tooltip: CC_DEV && 'i18n:COMPONENT.richtext.handleTouchEvent',
notify: function (oldValue) {
if (this.handleTouchEvent === oldValue) return;
if (this.enabledInHierarchy) {
this.handleTouchEvent ? this._addEventListeners() : this._removeEventListeners();
}
}
}
},
statics: {
HorizontalAlign: HorizontalAlign,
VerticalAlign: VerticalAlign
},
onEnable () {
if (this.handleTouchEvent) {
this._addEventListeners();
}
this._updateRichText();
this._activateChildren(true);
},
onDisable () {
if (this.handleTouchEvent) {
this._removeEventListeners();
}
this._activateChildren(false);
},
start () {
this._onTTFLoaded();
},
_addEventListeners () {
this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
},
_removeEventListeners () {
this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
},
_updateLabelSegmentTextAttributes () {
this._labelSegments.forEach(function (item) {
this._applyTextAttribute(item);
}.bind(this));
},
_createFontLabel (string) {
return pool.get(string, this.font, this.fontSize);
},
_onTTFLoaded () {
if (this.font instanceof cc.TTFFont) {
if (this.font._nativeAsset) {
this._layoutDirty = true;
this._updateRichText();
}
else {
let self = this;
cc.loader.load(this.font.nativeUrl, function (err, fontFamily) {
self._layoutDirty = true;
self._updateRichText();
});
}
}
else {
this._layoutDirty = true;
this._updateRichText();
}
},
_measureText (styleIndex, string) {
let self = this;
let func = function (string) {
let label;
if (self._labelSegmentsCache.length === 0) {
label = self._createFontLabel(string);
self._labelSegmentsCache.push(label);
}
else {
label = self._labelSegmentsCache[0];
label.getComponent(cc.Label).string = string;
}
label._styleIndex = styleIndex;
self._applyTextAttribute(label);
let labelSize = label.getContentSize();
return labelSize.width;
};
if (string) {
return func(string);
}
else {
return func;
}
},
_onTouchEnded (event) {
let components = this.node.getComponents(cc.Component);
for (let i = 0; i < this._labelSegments.length; ++i) {
let labelSegment = this._labelSegments[i];
let clickHandler = labelSegment._clickHandler;
if (clickHandler && this._containsTouchLocation(labelSegment, event.touch.getLocation())) {
components.forEach(function (component) {
if (component.enabledInHierarchy && component[clickHandler]) {
component[clickHandler](event);
}
});
event.stopPropagation();
}
}
},
_containsTouchLocation (label, point) {
let myRect = label.getBoundingBoxToWorld();
return myRect.contains(point);
},
_resetState () {
let children = this.node.children;
for (let i = children.length - 1; i >= 0; i--) {
let child = children[i];
if (child.name === RichTextChildName || child.name === RichTextChildImageName) {
if (child.parent === this.node) {
child.parent = null;
}
else {
// In case child.parent !== this.node, child cannot be removed from children
children.splice(i, 1);
}
if (child.name === RichTextChildName) {
pool.put(child);
}
}
}
this._labelSegments.length = 0;
this._labelSegmentsCache.length = 0;
this._linesWidth.length = 0;
this._lineOffsetX = 0;
this._lineCount = 1;
this._labelWidth = 0;
this._labelHeight = 0;
this._layoutDirty = true;
},
onRestore: CC_EDITOR && function () {
// TODO: refine undo/redo system
// Because undo/redo will not call onEnable/onDisable,
// we need call onEnable/onDisable manually to active/disactive children nodes.
if (this.enabledInHierarchy) {
this.onEnable();
}
else {
this.onDisable();
}
},
_activateChildren (active) {
for (let i = this.node.children.length - 1; i >= 0; i--) {
let child = this.node.children[i];
if (child.name === RichTextChildName || child.name === RichTextChildImageName) {
child.active = active;
}
}
},
_addLabelSegment (stringToken, styleIndex) {
let labelSegment;
if (this._labelSegmentsCache.length === 0) {
labelSegment = this._createFontLabel(stringToken);
}
else {
labelSegment = this._labelSegmentsCache.pop();
labelSegment.getComponent(cc.Label).string = stringToken;
}
labelSegment._styleIndex = styleIndex;
labelSegment._lineCount = this._lineCount;
labelSegment.setAnchorPoint(0, 0);
this._applyTextAttribute(labelSegment);
this.node.addChild(labelSegment);
this._labelSegments.push(labelSegment);
return labelSegment;
},
_updateRichTextWithMaxWidth (labelString, labelWidth, styleIndex) {
let fragmentWidth = labelWidth;
let labelSegment;
if (this._lineOffsetX > 0 && fragmentWidth + this._lineOffsetX > this.maxWidth) {
//concat previous line
let checkStartIndex = 0;
while (this._lineOffsetX <= this.maxWidth) {
let checkEndIndex = this._getFirstWordLen(labelString,
checkStartIndex,
labelString.length);
let checkString = labelString.substr(checkStartIndex, checkEndIndex);
let checkStringWidth = this._measureText(styleIndex, checkString);
if (this._lineOffsetX + checkStringWidth <= this.maxWidth) {
this._lineOffsetX += checkStringWidth;
checkStartIndex += checkEndIndex;
}
else {
if (checkStartIndex > 0) {
let remainingString = labelString.substr(0, checkStartIndex);
this._addLabelSegment(remainingString, styleIndex);
labelString = labelString.substr(checkStartIndex, labelString.length);
fragmentWidth = this._measureText(styleIndex, labelString);
}
this._updateLineInfo();
break;
}
}
}
if (fragmentWidth > this.maxWidth) {
let fragments = textUtils.fragmentText(labelString,
fragmentWidth,
this.maxWidth,
this._measureText(styleIndex));
for (let k = 0; k < fragments.length; ++k) {
let splitString = fragments[k];
labelSegment = this._addLabelSegment(splitString, styleIndex);
let labelSize = labelSegment.getContentSize();
this._lineOffsetX += labelSize.width;
if (fragments.length > 1 && k < fragments.length - 1) {
this._updateLineInfo();
}
}
}
else {
this._lineOffsetX += fragmentWidth;
this._addLabelSegment(labelString, styleIndex);
}
},
_isLastComponentCR (stringToken) {
return stringToken.length - 1 === stringToken.lastIndexOf("\n");
},
_updateLineInfo () {
this._linesWidth.push(this._lineOffsetX);
this._lineOffsetX = 0;
this._lineCount++;
},
_needsUpdateTextLayout (newTextArray) {
if (this._layoutDirty || !this._textArray || !newTextArray) {
return true;
}
if (this._textArray.length !== newTextArray.length) {
return true;
}
for (let i = 0; i < this._textArray.length; ++i) {
let oldItem = this._textArray[i];
let newItem = newTextArray[i];
if (oldItem.text !== newItem.text) {
return true;
}
else {
if (oldItem.style) {
if (newItem.style) {
if (!!newItem.style.outline !== !!oldItem.style.outline) {
return true;
}
if (oldItem.style.size !== newItem.style.size
|| oldItem.style.italic !== newItem.style.italic
|| oldItem.style.isImage !== newItem.style.isImage) {
return true;
}
if (oldItem.style.isImage === newItem.style.isImage) {
if (oldItem.style.src !== newItem.style.src) {
return true;
}
}
}
else {
if (oldItem.style.size || oldItem.style.italic || oldItem.style.isImage || oldItem.style.outline) {
return true;
}
}
}
else {
if (newItem.style) {
if (newItem.style.size || newItem.style.italic || newItem.style.isImage || newItem.style.outline) {
return true;
}
}
}
}
}
return false;
},
_addRichTextImageElement (richTextElement) {
let spriteFrameName = richTextElement.style.src;
let spriteFrame = this.imageAtlas.getSpriteFrame(spriteFrameName);
if (spriteFrame) {
let spriteNode = new cc.PrivateNode(RichTextChildImageName);
let spriteComponent = spriteNode.addComponent(cc.Sprite);
spriteNode.setAnchorPoint(0, 0);
spriteComponent.type = cc.Sprite.Type.SLICED;
spriteComponent.sizeMode = cc.Sprite.SizeMode.CUSTOM;
this.node.addChild(spriteNode);
this._labelSegments.push(spriteNode);
let spriteRect = spriteFrame.getRect();
let scaleFactor = 1;
let spriteWidth = spriteRect.width;
let spriteHeight = spriteRect.height;
let expectWidth = richTextElement.style.imageWidth;
let expectHeight = richTextElement.style.imageHeight;
//follow the original rule, expectHeight must less then lineHeight
if (expectHeight > 0 && expectHeight < this.lineHeight) {
scaleFactor = expectHeight / spriteHeight;
spriteWidth = spriteWidth * scaleFactor;
spriteHeight = spriteHeight * scaleFactor;
}
else {
scaleFactor = this.lineHeight / spriteHeight;
spriteWidth = spriteWidth * scaleFactor;
spriteHeight = spriteHeight * scaleFactor;
}
if (expectWidth > 0) spriteWidth = expectWidth;
if (this.maxWidth > 0) {
if (this._lineOffsetX + spriteWidth > this.maxWidth) {
this._updateLineInfo();
}
this._lineOffsetX += spriteWidth;
}
else {
this._lineOffsetX += spriteWidth;
if (this._lineOffsetX > this._labelWidth) {
this._labelWidth = this._lineOffsetX;
}
}
spriteComponent.spriteFrame = spriteFrame;
spriteNode.setContentSize(spriteWidth, spriteHeight);
spriteNode._lineCount = this._lineCount;
if (richTextElement.style.event) {
if (richTextElement.style.event.click) {
spriteNode._clickHandler = richTextElement.style.event.click;
}
}
}
else {
cc.warnID(4400);
}
},
_updateRichText () {
if (!this.enabled) return;
let newTextArray = _htmlTextParser.parse(this.string);
if (!this._needsUpdateTextLayout(newTextArray)) {
this._textArray = newTextArray;
this._updateLabelSegmentTextAttributes();
return;
}
this._textArray = newTextArray;
this._resetState();
let lastEmptyLine = false;
let label;
let labelSize;
for (let i = 0; i < this._textArray.length; ++i) {
let richTextElement = this._textArray[i];
let text = richTextElement.text;
//handle <br/> <img /> tag
if (text === "") {
if (richTextElement.style && richTextElement.style.newline) {
this._updateLineInfo();
continue;
}
if (richTextElement.style && richTextElement.style.isImage && this.imageAtlas) {
this._addRichTextImageElement(richTextElement);
continue;
}
}
let multilineTexts = text.split("\n");
for (let j = 0; j < multilineTexts.length; ++j) {
let labelString = multilineTexts[j];
if (labelString === "") {
//for continues \n
if (this._isLastComponentCR(text)
&& j === multilineTexts.length - 1) {
continue;
}
this._updateLineInfo();
lastEmptyLine = true;
continue;
}
lastEmptyLine = false;
if (this.maxWidth > 0) {
let labelWidth = this._measureText(i, labelString);
this._updateRichTextWithMaxWidth(labelString, labelWidth, i);
if (multilineTexts.length > 1 && j < multilineTexts.length - 1) {
this._updateLineInfo();
}
}
else {
label = this._addLabelSegment(labelString, i);
labelSize = label.getContentSize();
this._lineOffsetX += labelSize.width;
if (this._lineOffsetX > this._labelWidth) {
this._labelWidth = this._lineOffsetX;
}
if (multilineTexts.length > 1 && j < multilineTexts.length - 1) {
this._updateLineInfo();
}
}
}
}
if (!lastEmptyLine) {
this._linesWidth.push(this._lineOffsetX);
}
if (this.maxWidth > 0) {
this._labelWidth = this.maxWidth;
}
this._labelHeight = this._lineCount * this.lineHeight;
// trigger "size-changed" event
this.node.setContentSize(this._labelWidth, this._labelHeight);
this._updateRichTextPosition();
this._layoutDirty = false;
},
_getFirstWordLen (text, startIndex, textLen) {
let character = text.charAt(startIndex);
if (textUtils.isUnicodeCJK(character)
|| textUtils.isUnicodeSpace(character)) {
return 1;
}
let len = 1;
for (let index = startIndex + 1; index < textLen; ++index) {
character = text.charAt(index);
if (textUtils.isUnicodeSpace(character)
|| textUtils.isUnicodeCJK(character)) {
break;
}
len++;
}
return len;
},
_updateRichTextPosition () {
let nextTokenX = 0;
let nextLineIndex = 1;
let totalLineCount = this._lineCount;
for (let i = 0; i < this._labelSegments.length; ++i) {
let label = this._labelSegments[i];
let lineCount = label._lineCount;
if (lineCount > nextLineIndex) {
nextTokenX = 0;
nextLineIndex = lineCount;
}
let lineOffsetX = 0;
// let nodeAnchorXOffset = (0.5 - this.node.anchorX) * this._labelWidth;
switch (this.horizontalAlign) {
case HorizontalAlign.LEFT:
lineOffsetX = - this._labelWidth / 2;
break;
case HorizontalAlign.CENTER:
lineOffsetX = - this._linesWidth[lineCount - 1] / 2;
break;
case HorizontalAlign.RIGHT:
lineOffsetX = this._labelWidth / 2 - this._linesWidth[lineCount - 1];
break;
default:
break;
}
label.x = nextTokenX + lineOffsetX;
let labelSize = label.getContentSize();
label.y = this.lineHeight * (totalLineCount - lineCount) - this._labelHeight / 2;
if (lineCount === nextLineIndex) {
nextTokenX += labelSize.width;
}
}
},
_convertLiteralColorValue (color) {
let colorValue = color.toUpperCase();
if (cc.Color[colorValue]) {
return cc.Color[colorValue];
}
else {
let out = cc.color();
return out.fromHEX(color);
}
},
_applyTextAttribute (labelNode) {
let labelComponent = labelNode.getComponent(cc.Label);
if (!labelComponent) {
return;
}
let index = labelNode._styleIndex;
labelComponent.lineHeight = this.lineHeight;
labelComponent.horizontalAlign = HorizontalAlign.LEFT;
labelComponent.verticalAlign = VerticalAlign.CENTER;
let textStyle = null;
if (this._textArray[index]) {
textStyle = this._textArray[index].style;
}
if (textStyle && textStyle.color) {
labelNode.color = this._convertLiteralColorValue(textStyle.color);
}else {
labelNode.color = this._convertLiteralColorValue("white");
}
labelComponent._enableBold(textStyle && textStyle.bold);
labelComponent._enableItalics(textStyle && textStyle.italic);
//TODO: temporary implementation, the italic effect should be implemented in the internal of label-assembler.
if (textStyle && textStyle.italic) {
labelNode.skewX = 12;
}
labelComponent._enableUnderline(textStyle && textStyle.underline);
if (textStyle && textStyle.outline) {
let labelOutlineComponent = labelNode.getComponent(cc.LabelOutline);
if (!labelOutlineComponent) {
labelOutlineComponent = labelNode.addComponent(cc.LabelOutline);
}
labelOutlineComponent.color = this._convertLiteralColorValue(textStyle.outline.color);
labelOutlineComponent.width = textStyle.outline.width;
}
if (textStyle && textStyle.size) {
labelComponent.fontSize = textStyle.size;
}
else {
labelComponent.fontSize = this.fontSize;
}
labelComponent._updateRenderData(true);
if (textStyle && textStyle.event) {
if (textStyle.event.click) {
labelNode._clickHandler = textStyle.event.click;
}
}
},
onDestroy () {
for (let i = 0; i < this._labelSegments.length; ++i) {
this._labelSegments[i].removeFromParent();
pool.put(this._labelSegments[i]);
}
},
});
cc.RichText = module.exports = RichText;
-371
View File
@@ -1,371 +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/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';
import { ccenum } from '../../core/value-types/enum';
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 enum AnimationTargetProperty {
position,
rotation,
scale,
}
cc.AnimationTargetProperty = AnimationTargetProperty;
ccenum(AnimationTargetProperty);
export interface IPropertyAnimation {
/**
* Target Property to animate.
*/
property: AnimationTargetProperty;
/**
* Index of keys into animation's keysList property;
*/
indexOfKeys: number;
/**
* Property values.
*/
values: number[];
}
export interface IAnimationChannel {
/**
* Target node's path in scene graph.
*/
target: string;
/**
* Properties animation.
*/
propertyAnimations: IPropertyAnimation[];
}
@ccclass('cc.AnimationClip')
export default class AnimationClip extends Asset {
@property
private _channels: IAnimationChannel[] = [];
@property
private _keysList: number[][] = [];
@property
private _length: number = 0.0;
get keysList () {
return this._keysList;
}
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 binaryIndicesOfKeysList: number[] = new Array(clip.keysList.length);
binaryIndicesOfKeysList.fill(-1);
const calcBinarayIndicesOfKeys = (iKeys: number) => {
let v = binaryIndicesOfKeysList[iKeys];
if (v < 0) {
const keys = clip.keysList[iKeys];
if (keys.length === 1) {
v = 0;
} else {
v = _binaryIndexOf(keys, t);
}
binaryIndicesOfKeysList[iKeys] = v;
}
return v;
};
const getState = (channel: IAnimationChannel) => {
const iNode = this._animationTarget.get(channel.target);
if (iNode === undefined) {
return null;
}
return this._nodeSamplingStates[iNode];
};
const tempVec3_1 = new Vec3();
const tempVec3_2 = new Vec3();
const tempQuat_1 = new Quat();
const tempQuat_2 = new Quat();
clip.channels.forEach((channel) => {
const nodeSamlingState = getState(channel);
if (!nodeSamlingState) {
return;
}
channel.propertyAnimations.forEach((propertyAnimation) => {
const getPositionAt = (index: number, out: Vec3) => vec3.set(out,
propertyAnimation.values[index * 3 + 0],
propertyAnimation.values[index * 3 + 1],
propertyAnimation.values[index * 3 + 2]);
const getRotationAt = (index: number, out: Quat) => quat.set(out,
propertyAnimation.values[index * 4 + 0],
propertyAnimation.values[index * 4 + 1],
propertyAnimation.values[index * 4 + 2],
propertyAnimation.values[index * 4 + 3]);
const getScaleAt = getPositionAt;
const keys = clip.keysList[propertyAnimation.indexOfKeys];
const idx = calcBinarayIndicesOfKeys(propertyAnimation.indexOfKeys);
if (idx === 0) {
if (propertyAnimation.property === AnimationTargetProperty.position) {
const p = getPositionAt(0, tempVec3_1);
nodeSamlingState.blendPosition(p, weight);
} else if (propertyAnimation.property === AnimationTargetProperty.rotation) {
const r = getRotationAt(0, tempQuat_1);
nodeSamlingState.blendRotation(r, weight);
} else if (propertyAnimation.property === AnimationTargetProperty.scale) {
const s = getScaleAt(0, tempVec3_1);
nodeSamlingState.blendScale(s, weight);
}
} else {
const loIdx = Math.max(idx - 1, 0);
const hiIdx = Math.min(idx, keys.length);
const ratio = (t - keys[loIdx]) / (keys[hiIdx] - keys[loIdx]);
if (propertyAnimation.property === AnimationTargetProperty.position) {
const a = getPositionAt(loIdx, tempVec3_1);
const b = getPositionAt(hiIdx, tempVec3_2);
vec3.lerp(tmpvec3, a, b, ratio);
nodeSamlingState.blendPosition(tmpvec3, weight);
} else if (propertyAnimation.property === AnimationTargetProperty.rotation) {
const a = getRotationAt(loIdx, tempQuat_1);
const b = getRotationAt(hiIdx, tempQuat_2);
quat.slerp(tmpquat, a, b, ratio);
nodeSamlingState.blendRotation(tmpquat, weight);
} else if (propertyAnimation.property === AnimationTargetProperty.scale) {
const a = getScaleAt(loIdx, tempVec3_1);
const b = getScaleAt(hiIdx, tempVec3_2);
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) {
if (weight === 0) {
return;
}
const t = weight / (this._sumRotWeight + weight);
quat.slerp(tmpquat, this._target.getRotation(), rotation, t);
this._target.setRotation(tmpquat);
this._sumRotWeight += weight;
}
public apply () {
if (CC_DEV) {
if (this._sumPosWeight > 1.0 || this._sumRotWeight > 1.0 || this._sumScaleWeight > 1.0) {
throw new Error(`Unexpected.`);
}
}
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);
}
}
}
+1 -1
View File
@@ -81,7 +81,7 @@ export class AudioClip extends EventTargetFactory(Asset) {
@property(AudioType)
protected _loadMode = AudioType.UNKNOWN_AUDIO;
private _audio: any = null;
protected _audio: any = null;
private _player: AudioPlayer | null = null;
public play () { if (this._player) { this._player.play(); } }
-156
View File
@@ -1,156 +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 } = _decorator;
import { AudioClip, AudioType, PlayingState } from './audio-clip';
/**
* WeChat audio to port. https://developers.weixin.qq.com/minigame/dev/document/media/audio/InnerAudioContext.html
*/
@ccclass('cc.WxGameAudioClip')
export default class WxGameAudioClip extends AudioClip {
constructor() {
super();
this.loadMode = AudioType.WX_GAME_AUDIO;
this._volume = 1;
this._loop = false;
this._oneShoting = false;
this._currentTime = 0.0;
}
setNativeAsset(clip, info) {
// typeof clip === innerAudioContext
if (!clip) {
console.warn('There is no audio in the current clip');
return;
}
super.setNativeAsset(clip, info);
this._initEventsListener();
clip.volume = this._volume;
clip.loop = this._loop;
}
_initEventsListener() {
this._audio.onPlay(() => {
this._state = PlayingState.PLAYING;
this._currentTime = this._audio.currentTime;
// @ts-ignore
this.emit('started');
});
this._audio.onPause(() => {
this._state = PlayingState.STOPPED;
this._oneShoting = false;
});
this._audio.onStop(() => {
this._state = PlayingState.STOPPED;
this._oneShoting = false;
this._currentTime = 0;
});
this._audio.onEnded(() => {
this._state = PlayingState.STOPPED;
this._currentTime = 0;
// @ts-ignore
this.emit('ended');
if (this._oneShoting) {
this._audio.volume = this._volume;
this._audio.loop = this._loop;
this._oneShoting = false;
}
});
}
play() {
if (!this._audio || this._state === PlayingState.PLAYING) {
return;
}
this._audio.play();
}
pause() {
if (this._state !== PlayingState.PLAYING) {
return;
}
this._audio.pause();
}
stop() {
if (this._state === PlayingState.STOPPED) {
return;
}
this._audio.stop();
}
playOneShot(volume = 1) {
/* HTMLMediaElement doesn't support multiple playback at the
same time so here we fall back to re-start style cc.gameroach */
if (!this._audio) return;
this._audio.volume = volume;
if (this._oneShoting) return;
this._audio.loop = false;
this._oneShoting = true;
this._audio.play();
}
getCurrentTime() {
return this._currentTime;
}
setCurrentTime(val) {
this._currentTime = val;
this._audio.seek(this._currentTime);
}
getDuration() {
return this._audio ? this._audio.duration : 0;
}
getVolume() {
return this._audio ? this._audio.volume : this._volume;
}
setVolume(val) {
this._volume = val;
if (this._audio) this._audio.volume = val;
}
getLoop() {
return this._loop;
}
setLoop(val) {
this._loop = val;
if (this._audio) this._audio.loop = val;
}
}
cc.WxGameAudioClip = WxGameAudioClip;
+161
View File
@@ -0,0 +1,161 @@
/****************************************************************************
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 { _decorator } from '../../../core/data/index';
const { ccclass } = _decorator;
import { AudioClip, AudioType } from './clip';
import { PlayingState } from './player';
/**
* WeChat audio to port. https://developers.weixin.qq.com/minigame/dev/document/media/audio/InnerAudioContext.html
*/
@ccclass('cc.WxGameAudioClip')
export default class WxGameAudioClip extends AudioClip {
private _volume: number;
private _loop: boolean;
private _oneShoting: boolean;
private _currentTime: number;
private _state = PlayingState.STOPPED;
constructor () {
super();
this._loadMode = AudioType.WX_GAME_AUDIO;
this._volume = 1;
this._loop = false;
this._oneShoting = false;
this._currentTime = 0.0;
}
public setNativeAsset (clip, info) {
// typeof clip === innerAudioContext
if (!clip) {
console.warn('There is no audio in the current clip');
return;
}
super.setNativeAsset(clip, info);
this._initEventsListener();
clip.volume = this._volume;
clip.loop = this._loop;
}
public _initEventsListener () {
this._audio.onPlay(() => {
this._state = PlayingState.PLAYING;
this._currentTime = this._audio.currentTime;
// @ts-ignore
this.emit('started');
});
this._audio.onPause(() => {
this._state = PlayingState.STOPPED;
this._oneShoting = false;
});
this._audio.onStop(() => {
this._state = PlayingState.STOPPED;
this._oneShoting = false;
this._currentTime = 0;
});
this._audio.onEnded(() => {
this._state = PlayingState.STOPPED;
this._currentTime = 0;
// @ts-ignore
this.emit('ended');
if (this._oneShoting) {
this._audio.volume = this._volume;
this._audio.loop = this._loop;
this._oneShoting = false;
}
});
}
public play () {
if (!this._audio || this._state === PlayingState.PLAYING) {
return;
}
this._audio.play();
}
public pause () {
if (this._state !== PlayingState.PLAYING) {
return;
}
this._audio.pause();
}
public stop () {
if (this._state === PlayingState.STOPPED) {
return;
}
this._audio.stop();
}
public playOneShot (volume = 1) {
/* HTMLMediaElement doesn't support multiple playback at the
same time so here we fall back to re-start style cc.gameroach */
if (!this._audio) { return; }
this._audio.volume = volume;
if (this._oneShoting) { return; }
this._audio.loop = false;
this._oneShoting = true;
this._audio.play();
}
public getCurrentTime () {
return this._currentTime;
}
public setCurrentTime (val) {
this._currentTime = val;
this._audio.seek(this._currentTime);
}
public getDuration () {
return this._audio ? this._audio.duration : 0;
}
public getVolume () {
return this._audio ? this._audio.volume : this._volume;
}
public setVolume (val) {
this._volume = val;
if (this._audio) { this._audio.volume = val; }
}
public getLoop () {
return this._loop;
}
public setLoop (val) {
this._loop = val;
if (this._audio) { this._audio.loop = val; }
}
}
cc.WxGameAudioClip = WxGameAudioClip;
-1
View File
@@ -23,7 +23,6 @@
THE SOFTWARE.
****************************************************************************/
export { default as AnimationClip } from './animation-clip';
export { AudioClip } from './audio/clip';
export { EffectAsset } from './effect-asset';
export { Material } from './material';
-421
View File
@@ -1,421 +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/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';
import { clamp01 } from '../../core/vmath';
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;
}
}
interface IBlendedAnimationState {
state: AnimationState | null;
blendTime: number;
blendDuration: number;
}
/**
* !#en Animation Controller
*
* !#ch 动画控制器
*/
class AnimationCtrl {
private _animationTarget: AnimationTarget | null = null;
private _animationSampler: AnimationSampler | null = null;
private _animations: IBlendedAnimationState[] = [];
/**
* !#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) {
this._animations.unshift({
state: to,
blendDuration: duration,
blendTime: 0.0,
});
}
public tick (deltaTime: number) {
if (!this._animationSampler) {
return;
}
if (this._animations.length === 0) {
return;
}
this._animationSampler.reset();
let absoluteWeight = 1.0;
for (let i = 0; i < this._animations.length; ++i) {
if (absoluteWeight === 0) {
this._animations.splice(i);
break;
}
const ba = this._animations[i];
ba.blendTime += deltaTime;
const relativeWeight = clamp01(ba.blendTime / ba.blendDuration);
const weight = relativeWeight * absoluteWeight;
absoluteWeight = absoluteWeight * (1.0 - relativeWeight);
if (ba.state) {
ba.state.time += deltaTime;
const t = this._getTime(ba.state);
this._animationSampler.sample(ba.state.clip, t, weight);
}
}
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 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);
}
}
+5 -4
View File
@@ -24,24 +24,23 @@
THE SOFTWARE.
****************************************************************************/
import { AnimationComponent } from './animation-component';
import { AudioSourceComponent } from './audio-source-component';
import { CameraComponent } from './camera-component';
import { DirectionalLightComponent } from './directional-light-component';
import { EditorCameraComponent } from './editor-camera-component';
import { LightComponent } from './light-component';
import { ModelComponent } from './model-component';
import { ParticleSystemComponent } from './particle/particle-system-component';
import { ParticleUtils } from './particle/particle-utils';
import { BoxColliderComponent, SphereColliderComponent } from './physics/collider-component';
import { RigidBodyComponent } from './physics/rigid-body-component';
import { RenderableComponent } from './renderable-component';
import { SkinningModelComponent } from './skinning-model-component';
import { SphereLightComponent } from './sphere-light-component';
import { SpotLightComponent } from './spot-light-component';
import { EditorCameraComponent } from './editor-camera-component';
export * from './physics';
export {
AnimationComponent,
AudioSourceComponent,
CameraComponent,
LightComponent,
@@ -54,7 +53,7 @@ export {
SphereColliderComponent,
};
cc.AnimationComponent = AnimationComponent;
// cc.AnimationComponent = AnimationComponent;
cc.AudioSourceComponent = AudioSourceComponent;
cc.CameraComponent = CameraComponent;
cc.EditorComponent = EditorCameraComponent;
@@ -71,3 +70,5 @@ cc.BoxColliderComponent = BoxColliderComponent;
cc.ParticleSystemComponent = ParticleSystemComponent;
cc.RigidBodyComponent = RigidBodyComponent;
cc.SphereColliderComponent = SphereColliderComponent;
cc.ParticleUtils = ParticleUtils;
@@ -0,0 +1,53 @@
import { ParticleSystemComponent } from '..';
import { CCObject } from '../../../core';
import { Node } from '../../../scene-graph';
import { Pool } from '../../memop';
export class ParticleUtils {
private static particleSystemPool: Map<string, Pool<CCObject>> = new Map<string, Pool<CCObject>>();
private static registeredSceneEvent: boolean = false;
/**
* instantiate
*/
public static instantiate (prefab) {
if (!this.registeredSceneEvent) {
cc.director.on(cc.Director.EVENT_BEFORE_SCENE_LAUNCH, this.onSceneUnload, this);
this.registeredSceneEvent = true;
}
if (!this.particleSystemPool.has(prefab._uuid)) {
this.particleSystemPool.set(prefab._uuid, new Pool<CCObject>(() => {
return cc.instantiate(prefab);
}, 1));
}
return this.particleSystemPool.get(prefab._uuid)!.alloc();
}
public static destroy (prefab) {
if (this.particleSystemPool.has(prefab._prefab.asset._uuid)) {
this.stop(prefab);
this.particleSystemPool.get(prefab._prefab.asset._uuid)!.free(prefab);
}
}
private static onSceneUnload () {
for (const p of this.particleSystemPool.values()) {
p.clear((prefab) => {
prefab.destroy();
});
}
this.particleSystemPool.clear();
}
public static play (rootNode: Node) {
for (const ps of rootNode.getComponentsInChildren(cc.ParticleSystemComponent)) {
(ps as ParticleSystemComponent).play();
}
}
public static stop (rootNode: Node) {
for (const ps of rootNode.getComponentsInChildren(cc.ParticleSystemComponent)) {
(ps as ParticleSystemComponent).stop();
}
}
}
@@ -34,11 +34,11 @@ const RenderMode = Enum({
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';
const CC_USE_WORLD_SPACE = 'CC_USE_WORLD_SPACE';
const CC_USE_BILLBOARD = 'CC_USE_BILLBOARD';
const CC_USE_STRETCHED_BILLBOARD = 'CC_USE_STRETCHED_BILLBOARD';
const CC_USE_HORIZONTAL_BILLBOARD = 'CC_USE_HORIZONTAL_BILLBOARD';
const CC_USE_VERTICAL_BILLBOARD = 'CC_USE_VERTICAL_BILLBOARD';
@ccclass('cc.ParticleSystemRenderer')
@executeInEditMode
@@ -120,11 +120,11 @@ export default class ParticleSystemRenderer extends RenderableComponent {
{ 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,
CC_USE_WORLD_SPACE: true,
CC_USE_BILLBOARD: true,
CC_USE_STRETCHED_BILLBOARD: false,
CC_USE_HORIZONTAL_BILLBOARD: false,
CC_USE_VERTICAL_BILLBOARD: false,
};
}
@@ -290,33 +290,33 @@ export default class ParticleSystemRenderer extends RenderableComponent {
}
const mat: Material | null = this.sharedMaterial ? this.getMaterial(0, CC_EDITOR)! : this._defaultMat;
if (this.particleSystem._simulationSpace === Space.World) {
this._defines[USE_WORLD_SPACE] = true;
this._defines[CC_USE_WORLD_SPACE] = true;
} else {
this._defines[USE_WORLD_SPACE] = false;
this._defines[CC_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;
this._defines[CC_USE_BILLBOARD] = true;
this._defines[CC_USE_STRETCHED_BILLBOARD] = false;
this._defines[CC_USE_HORIZONTAL_BILLBOARD] = false;
this._defines[CC_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._defines[CC_USE_BILLBOARD] = false;
this._defines[CC_USE_STRETCHED_BILLBOARD] = true;
this._defines[CC_USE_HORIZONTAL_BILLBOARD] = false;
this._defines[CC_USE_VERTICAL_BILLBOARD] = false;
this.frameTile_velLenScale.z = this._velocityScale;
this.frameTile_velLenScale.w = 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;
this._defines[CC_USE_BILLBOARD] = false;
this._defines[CC_USE_STRETCHED_BILLBOARD] = false;
this._defines[CC_USE_HORIZONTAL_BILLBOARD] = true;
this._defines[CC_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;
this._defines[CC_USE_BILLBOARD] = false;
this._defines[CC_USE_STRETCHED_BILLBOARD] = false;
this._defines[CC_USE_HORIZONTAL_BILLBOARD] = false;
this._defines[CC_USE_VERTICAL_BILLBOARD] = true;
} else {
console.warn(`particle system renderMode ${this._renderMode} not support.`);
}
@@ -19,7 +19,7 @@ const NonRigidBodyProperties = {
};
@ccclass('cc.RigidBodyComponent')
@executionOrder(100)
@executionOrder(101)
@menu('Components/RigidBodyComponent')
@executeInEditMode
export class RigidBodyComponent extends PhysicsBasedComponent {
+1 -1
View File
@@ -36,7 +36,7 @@ export class SphereLightComponent extends LightComponent {
@property
protected _size = 0.15;
@property
protected _luminance = 1700 / nt2lm(this._size);
protected _luminance = 1700 / nt2lm(0.15);
@property
protected _term = PhotometricTerm.LUMINOUS_POWER;
@property
+1 -1
View File
@@ -37,7 +37,7 @@ export class SpotLightComponent extends LightComponent {
@property
protected _size = 0.15;
@property
protected _luminance = 1700 / nt2lm(this._size);
protected _luminance = 1700 / nt2lm(0.15);
@property
protected _term = PhotometricTerm.LUMINOUS_POWER;
@property
-918
View File
@@ -1,918 +0,0 @@
import { mat3, vec3 } from '../../core/vmath';
import * as distance from './distance';
import enums from './enums';
/**
* ray-plane intersect
*
* @param {ray} ray
* @param {plane} plane
* @return {number}
*/
let ray_plane = (function () {
let pt = vec3.create(0, 0, 0);
return function (ray, plane) {
const denom = vec3.dot(ray.d, plane.n);
if (Math.abs(denom) < Number.EPSILON) return 0;
vec3.scale(pt, plane.n, plane.d);
const t = vec3.dot(vec3.sub(pt, pt, ray.o), plane.n) / denom;
if (t < 0) return 0;
return t;
};
})();
/**
* line-plane intersect
*
* @param {line} line
* @param {plane} plane
* @return {number}
*/
let line_plane = (function () {
let ab = vec3.create(0, 0, 0);
return function (line, plane) {
vec3.sub(ab, line.e, line.s);
let t = (plane.d - vec3.dot(line.s, plane.n)) / vec3.dot(ab, plane.n);
if (t < 0 || t > 1) return 0;
return t;
};
})();
/**
* ray-triangle intersect
* based on http://fileadmin.cs.lth.se/cs/Personal/Tomas_Akenine-Moller/raytri/
*
* @param {ray} ray
* @param {triangle} triangle
* @return {number}
*/
let ray_triangle = (function () {
let ab = vec3.create(0, 0, 0);
let ac = vec3.create(0, 0, 0);
let pvec = vec3.create(0, 0, 0);
let tvec = vec3.create(0, 0, 0);
let qvec = vec3.create(0, 0, 0);
return function (ray, triangle, doubleSided) {
vec3.sub(ab, triangle.b, triangle.a);
vec3.sub(ac, triangle.c, triangle.a);
vec3.cross(pvec, ray.d, ac);
let det = vec3.dot(ab, pvec);
if (det < Number.EPSILON && (!doubleSided || det > -Number.EPSILON)) return 0;
let inv_det = 1 / det;
vec3.sub(tvec, ray.o, triangle.a);
let u = vec3.dot(tvec, pvec) * inv_det;
if (u < 0 || u > 1) return 0;
vec3.cross(qvec, tvec, ab);
let v = vec3.dot(ray.d, qvec) * inv_det;
if (v < 0 || u + v > 1) return 0;
let t = vec3.dot(ac, qvec) * inv_det;
return t < 0 ? 0 : t;
};
})();
/**
* line-triangle intersect
*
* @param {line} line
* @param {triangle} triangle
* @param {vec3} outPt the intersect point if provide
* @return {number}
*/
let line_triangle = (function () {
let ab = vec3.create(0, 0, 0);
let ac = vec3.create(0, 0, 0);
let qp = vec3.create(0, 0, 0);
let ap = vec3.create(0, 0, 0);
let n = vec3.create(0, 0, 0);
let e = vec3.create(0, 0, 0);
return function (line, triangle, outPt) {
vec3.sub(ab, triangle.b, triangle.a);
vec3.sub(ac, triangle.c, triangle.a);
vec3.sub(qp, line.s, line.e);
vec3.cross(n, ab, ac);
let det = vec3.dot(qp, n);
if (det <= 0.0) {
return 0;
}
vec3.sub(ap, line.s, triangle.a);
let t = vec3.dot(ap, n);
if (t < 0 || t > det) {
return 0;
}
vec3.cross(e, qp, ap);
let v = vec3.dot(ac, e);
if (v < 0 || v > det) {
return 0;
}
let w = -vec3.dot(ab, e);
if (w < 0.0 || v + w > det) {
return 0;
}
if (outPt) {
let invDet = 1.0 / det;
v *= invDet;
w *= invDet;
let u = 1.0 - v - w;
// outPt = u*a + v*d + w*c;
vec3.set(outPt,
triangle.a.x * u + triangle.b.x * v + triangle.c.x * w,
triangle.a.y * u + triangle.b.y * v + triangle.c.y * w,
triangle.a.z * u + triangle.b.z * v + triangle.c.z * w
);
}
return 1;
};
})();
/**
* line-quad intersect
*
* @param {vec3} p
* @param {vec3} q
* @param {vec3} a
* @param {vec3} b
* @param {vec3} c
* @param {vec3} d
* @param {vec3} outPt the intersect point if provide
* @return {number}
*/
let line_quad = (function () {
let pq = vec3.create(0, 0, 0);
let pa = vec3.create(0, 0, 0);
let pb = vec3.create(0, 0, 0);
let pc = vec3.create(0, 0, 0);
let pd = vec3.create(0, 0, 0);
let m = vec3.create(0, 0, 0);
let tmp = vec3.create(0, 0, 0);
return function (p, q, a, b, c, d, outPt) {
vec3.sub(pq, q, p);
vec3.sub(pa, a, p);
vec3.sub(pb, b, p);
vec3.sub(pc, c, p);
// Determine which triangle to test against by testing against diagonal first
vec3.cross(m, pc, pq);
let v = vec3.dot(pa, m);
if (v >= 0) {
// Test intersection against triangle abc
let u = -vec3.dot(pb, m);
if (u < 0) {
return 0;
}
let w = vec3.dot(vec3.cross(tmp, pq, pb), pa);
if (w < 0) {
return 0;
}
// outPt = u*a + v*b + w*c;
if (outPt) {
let denom = 1.0 / (u + v + w);
u *= denom;
v *= denom;
w *= denom;
vec3.set(outPt,
a.x * u + b.x * v + c.x * w,
a.y * u + b.y * v + c.y * w,
a.z * u + b.z * v + c.z * w
);
}
} else {
// Test intersection against triangle dac
vec3.sub(pd, d, p);
let u = vec3.dot(pd, m);
if (u < 0) {
return 0;
}
let w = vec3.dot(vec3.cross(tmp, pq, pa), pd);
if (w < 0) {
return 0;
}
// outPt = u*a + v*d + w*c;
if (outPt) {
v = -v;
let denom = 1.0 / (u + v + w);
u *= denom;
v *= denom;
w *= denom;
vec3.set(outPt,
a.x * u + d.x * v + c.x * w,
a.y * u + d.y * v + c.y * w,
a.z * u + d.z * v + c.z * w
);
}
}
return 1;
};
})();
/**
* ray-sphere intersect
*
* @param {ray} ray
* @param {sphere} sphere
* @return {number}
*/
let ray_sphere = (function () {
let e = vec3.create(0, 0, 0);
return function (ray, sphere) {
let r = sphere.r;
let c = sphere.c;
let o = ray.o;
let d = ray.d;
let rSq = r * r;
vec3.sub(e, c, o);
let eSq = vec3.sqrMag(e);
let aLength = vec3.dot(e, d); // assume ray direction already normalized
let fSq = rSq - (eSq - aLength * aLength);
if (fSq < 0) return 0;
let f = Math.sqrt(fSq);
let t = eSq < rSq ? aLength + f : aLength - f;
if (t < 0) return 0;
return t;
};
})();
/**
* ray-aabb intersect
*
* @param {ray} ray
* @param {aabb} aabb
* @return {number}
*/
let ray_aabb = (function() {
let min = vec3.create();
let max = vec3.create();
return function(ray, aabb) {
let o = ray.o, d = ray.d;
let ix = 1 / d.x, iy = 1 / d.y, iz = 1 / d.z;
vec3.sub(min, aabb.center, aabb.halfExtents);
vec3.add(max, aabb.center, aabb.halfExtents);
let t1 = (min.x - o.x) * ix;
let t2 = (max.x - o.x) * ix;
let t3 = (min.y - o.y) * iy;
let t4 = (max.y - o.y) * iy;
let t5 = (min.z - o.z) * iz;
let t6 = (max.z - o.z) * iz;
let tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));
let tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6));
if (tmax < 0 || tmin > tmax) return 0;
return tmin;
};
})();
/**
* ray-obb intersect
*
* @param {ray} ray
* @param {obb} obb
* @return {number}
*/
let ray_obb = (function () {
let center = vec3.create();
let o = vec3.create();
let d = vec3.create();
let X = vec3.create();
let Y = vec3.create();
let Z = vec3.create();
let p = vec3.create();
let size = new Array(3);
let f = new Array(3);
let e = new Array(3);
let t = new Array(6);
return function (ray, obb) {
size[0] = obb.halfExtents.x;
size[1] = obb.halfExtents.y;
size[2] = obb.halfExtents.z;
center = obb.center;
o = ray.o;
d = ray.d;
vec3.set(X, obb.orientation.m00, obb.orientation.m01, obb.orientation.m02);
vec3.set(Y, obb.orientation.m03, obb.orientation.m04, obb.orientation.m05);
vec3.set(Z, obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
vec3.sub(p, center, o);
//The cos values of the ray on the X, Y, Z
f[0] = vec3.dot(X, d);
f[1] = vec3.dot(Y, d);
f[2] = vec3.dot(Z, d);
//The projection length of P on X, Y, Z
e[0] = vec3.dot(X, p);
e[1] = vec3.dot(Y, p);
e[2] = vec3.dot(Z, p);
for (let i = 0; i < 3; ++i) {
if (f[i] === 0) {
if (-e[i] - size[i] > 0 || -e[i] + size[i] < 0) {
return 0;
}
// Avoid div by 0!
f[i] = 0.0000001;
}
// min
t[i * 2 + 0] = (e[i] + size[i]) / f[i];
// max
t[i * 2 + 1] = (e[i] - size[i]) / f[i];
}
let tmin = Math.max(
Math.max(
Math.min(t[0], t[1]),
Math.min(t[2], t[3])),
Math.min(t[4], t[5])
);
let tmax = Math.min(
Math.min(
Math.max(t[0], t[1]),
Math.max(t[2], t[3])),
Math.max(t[4], t[5])
);
if (tmax < 0 || tmin > tmax || tmin < 0) {
return 0;
}
return tmin;
};
})();
/**
* aabb-aabb intersect
*
* @param {aabb} aabb1
* @param {aabb} aabb2
* @return {number}
*/
let aabb_aabb = (function () {
let aMin = vec3.create();
let aMax = vec3.create();
let bMin = vec3.create();
let bMax = vec3.create();
return function(aabb1, aabb2) {
vec3.sub(aMin, aabb1.center, aabb1.halfExtents);
vec3.add(aMax, aabb1.center, aabb1.halfExtents);
vec3.sub(bMin, aabb2.center, aabb2.halfExtents);
vec3.add(bMax, aabb2.center, aabb2.halfExtents);
return (aMin.x <= bMax.x && aMax.x >= bMin.x) &&
(aMin.y <= bMax.y && aMax.y >= bMin.y) &&
(aMin.z <= bMax.z && aMax.z >= bMin.z);
};
})();
function getAABBVertices(min, max, out) {
vec3.set(out[0], min.x, max.y, max.z);
vec3.set(out[1], min.x, max.y, min.z);
vec3.set(out[2], min.x, min.y, max.z);
vec3.set(out[3], min.x, min.y, min.z);
vec3.set(out[4], max.x, max.y, max.z);
vec3.set(out[5], max.x, max.y, min.z);
vec3.set(out[6], max.x, min.y, max.z);
vec3.set(out[7], max.x, min.y, min.z);
}
function getOBBVertices(c, e, a1, a2, a3, out) {
vec3.set(out[0],
c.x + a1.x * e.x + a2.x * e.y + a3.x * e.z,
c.y + a1.y * e.x + a2.y * e.y + a3.y * e.z,
c.z + a1.z * e.x + a2.z * e.y + a3.z * e.z
);
vec3.set(out[1],
c.x - a1.x * e.x + a2.x * e.y + a3.x * e.z,
c.y - a1.y * e.x + a2.y * e.y + a3.y * e.z,
c.z - a1.z * e.x + a2.z * e.y + a3.z * e.z
);
vec3.set(out[2],
c.x + a1.x * e.x - a2.x * e.y + a3.x * e.z,
c.y + a1.y * e.x - a2.y * e.y + a3.y * e.z,
c.z + a1.z * e.x - a2.z * e.y + a3.z * e.z
);
vec3.set(out[3],
c.x + a1.x * e.x + a2.x * e.y - a3.x * e.z,
c.y + a1.y * e.x + a2.y * e.y - a3.y * e.z,
c.z + a1.z * e.x + a2.z * e.y - a3.z * e.z
);
vec3.set(out[4],
c.x - a1.x * e.x - a2.x * e.y - a3.x * e.z,
c.y - a1.y * e.x - a2.y * e.y - a3.y * e.z,
c.z - a1.z * e.x - a2.z * e.y - a3.z * e.z
);
vec3.set(out[5],
c.x + a1.x * e.x - a2.x * e.y - a3.x * e.z,
c.y + a1.y * e.x - a2.y * e.y - a3.y * e.z,
c.z + a1.z * e.x - a2.z * e.y - a3.z * e.z
);
vec3.set(out[6],
c.x - a1.x * e.x + a2.x * e.y - a3.x * e.z,
c.y - a1.y * e.x + a2.y * e.y - a3.y * e.z,
c.z - a1.z * e.x + a2.z * e.y - a3.z * e.z
);
vec3.set(out[7],
c.x - a1.x * e.x - a2.x * e.y + a3.x * e.z,
c.y - a1.y * e.x - a2.y * e.y + a3.y * e.z,
c.z - a1.z * e.x - a2.z * e.y + a3.z * e.z
);
}
function getInterval(vertices, axis) {
let min = vec3.dot(axis, vertices[0]), max = min;
for (let i = 1; i < 8; ++i) {
let projection = vec3.dot(axis, vertices[i]);
min = (projection < min) ? projection : min;
max = (projection > max) ? projection : max;
}
return [min, max];
}
/**
* aabb-obb intersect
*
* @param {aabb} aabb
* @param {obb} obb
* @return {number}
*/
let aabb_obb = (function () {
let test = new Array(15);
for (let i = 0; i < 15; i++) {
test[i] = vec3.create(0, 0, 0);
}
let vertices = new Array(8);
let vertices2 = new Array(8);
for (let i = 0; i < 8; i++) {
vertices[i] = vec3.create(0, 0, 0);
vertices2[i] = vec3.create(0, 0, 0);
}
let min = vec3.create();
let max = vec3.create();
return function(aabb, obb) {
vec3.set(test[0], 1, 0, 0);
vec3.set(test[1], 0, 1, 0);
vec3.set(test[2], 0, 0, 1);
vec3.set(test[3], obb.orientation.m00, obb.orientation.m01, obb.orientation.m02);
vec3.set(test[4], obb.orientation.m03, obb.orientation.m04, obb.orientation.m05);
vec3.set(test[5], obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
for (let i = 0; i < 3; ++i) { // Fill out rest of axis
vec3.cross(test[6 + i * 3 + 0], test[i], test[0]);
vec3.cross(test[6 + i * 3 + 1], test[i], test[1]);
vec3.cross(test[6 + i * 3 + 1], test[i], test[2]);
}
vec3.sub(min, aabb.center, aabb.halfExtents);
vec3.add(max, aabb.center, aabb.halfExtents);
getAABBVertices(min, max, vertices);
getOBBVertices(obb.center, obb.halfExtents, test[3], test[4], test[5], vertices2);
for (let j = 0; j < 15; ++j) {
let a = getInterval(vertices, test[j]);
let b = getInterval(vertices2, test[j]);
if (b[0] > a[1] || a[0] > b[1]) {
return 0; // Seperating axis found
}
}
return 1;
};
})();
/**
* aabb-plane intersect
*
* @param {aabb} aabb
* @param {plane} plane
* @return {number} inside(back) = -1, outside(front) = 0, intersect = 1
*/
let aabb_plane = function(aabb, plane) {
let r = aabb.halfExtents.x * Math.abs(plane.n.x) +
aabb.halfExtents.y * Math.abs(plane.n.y) +
aabb.halfExtents.z * Math.abs(plane.n.z);
let dot = vec3.dot(plane.n, aabb.center);
if (dot + r < plane.d) return -1;
else if (dot - r > plane.d) return 0;
return 1;
};
/**
* aabb-frustum intersect, faster but has
* false positive corner cases
*
* @param {aabb} aabb
* @param {planes: plane[], vertices: vec3[]} frustum
* @return {number}
*/
let aabb_frustum = function (aabb, frustum) {
for (let i = 0; i < frustum.planes.length; i++)
// frustum plane normal points to the inside
if (aabb_plane(aabb, frustum.planes[i]) == -1)
return 0; // completely outside
return 1;
};
/**
* aabb-frustum intersect, handles most of the false positives correctly, read more here:
* https://cesium.com/blog/2017/02/02/tighter-frustum-culling-and-why-you-may-want-to-disregard-it/
*
* @param {aabb} aabb
* @param {planes: plane[], vertices: vec3[]} frustum
* @return {number}
*/
let aabb_frustum_accurate = (function () {
let tmp = new Array(8), out1 = 0, out2 = 0;
for (let i = 0; i < tmp.length; i++) {
tmp[i] = vec3.create(0, 0, 0);
}
return function (aabb, frustum) {
let result = 0, intersects = false;
// 1. aabb inside/outside frustum test
for (let i = 0; i < frustum.planes.length; i++) {
result = aabb_plane(aabb, frustum.planes[i]);
// frustum plane normal points to the inside
if (result == -1) return 0; // completely outside
else if (result == 1) intersects = true;
}
if (!intersects) return 1; // completely inside
// in case of false positives
// 2. frustum inside/outside aabb test
for (let i = 0; i < frustum.vertices.length; i++)
vec3.sub(tmp[i], frustum.vertices[i], aabb.center);
out1 = 0, out2 = 0;
for (let i = 0; i < frustum.vertices.length; i++) {
if (tmp[i].x > aabb.halfExtents.x) out1++;
else if (tmp[i].x < -aabb.halfExtents.x) out2++;
}
if (out1 == frustum.vertices.length || out2 == frustum.vertices.length) return 0;
out1 = 0; out2 = 0;
for (let i = 0; i < frustum.vertices.length; i++) {
if (tmp[i].y > aabb.halfExtents.y) out1++;
else if (tmp[i].y < -aabb.halfExtents.y) out2++;
}
if (out1 == frustum.vertices.length || out2 == frustum.vertices.length) return 0;
out1 = 0; out2 = 0;
for (let i = 0; i < frustum.vertices.length; i++) {
if (tmp[i].z > aabb.halfExtents.z) out1++;
else if (tmp[i].z < -aabb.halfExtents.z) out2++;
}
if (out1 == frustum.vertices.length || out2 == frustum.vertices.length) return 0;
return 1;
};
})();
/**
* obb-point intersect
*
* @param {obb} obb
* @param {vec3} point
* @return {number}
*/
let obb_point = (function () {
let tmp = vec3.create(0, 0, 0), m3 = mat3.create();
let lessThan = function(a, b) { return Math.abs(a.x) < b.x && Math.abs(a.y) < b.y && Math.abs(a.z) < b.z; };
return function(obb, point) {
vec3.sub(tmp, point, obb.center);
vec3.transformMat3(tmp, tmp, mat3.transpose(m3, obb.orientation));
return lessThan(tmp, obb.halfExtents);
};
})();
/**
* obb-plane intersect
*
* @param {obb} obb
* @param {plane} plane
* @return {number} inside(back) = -1, outside(front) = 0, intersect = 1
*/
let obb_plane = (function () {
let absDot = function(n, x, y, z) {
return Math.abs(n.x * x + n.y * y + n.z * z);
};
return function (obb, plane) {
// Real-Time Collision Detection, Christer Ericson, p. 163.
let r = obb.halfExtents.x * absDot(plane.n, obb.orientation.m00, obb.orientation.m01, obb.orientation.m02) +
obb.halfExtents.y * absDot(plane.n, obb.orientation.m03, obb.orientation.m04, obb.orientation.m05) +
obb.halfExtents.z * absDot(plane.n, obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
let dot = vec3.dot(plane.n, obb.center);
if (dot + r < plane.d) return -1;
else if (dot - r > plane.d) return 0;
return 1;
};
})();
/**
* obb-frustum intersect, faster but has
* false positive corner cases
*
* @param {obb} obb
* @param {planes: plane[], vertices: vec3[]} frustum
* @return {number}
*/
let obb_frustum = function (obb, frustum) {
for (let i = 0; i < frustum.planes.length; i++)
// frustum plane normal points to the inside
if (obb_plane(obb, frustum.planes[i]) == -1)
return 0; // completely outside
return 1;
};
/**
* obb-frustum intersect, handles most of the false positives correctly, read more here:
* https://cesium.com/blog/2017/02/02/tighter-frustum-culling-and-why-you-may-want-to-disregard-it/
*
* @param {obb} obb
* @param {planes: plane[], vertices: vec3[]} frustum
* @return {number}
*/
let obb_frustum_accurate = (function () {
let tmp = new Array(8), dist = 0, out1 = 0, out2 = 0;
for (let i = 0; i < tmp.length; i++) {
tmp[i] = vec3.create(0, 0, 0);
}
let dot = function(n, x, y, z) {
return n.x * x + n.y * y + n.z * z;
};
return function (obb, frustum) {
let result = 0, intersects = false;
// 1. obb inside/outside frustum test
for (let i = 0; i < frustum.planes.length; i++) {
result = obb_plane(obb, frustum.planes[i]);
// frustum plane normal points to the inside
if (result == -1) return 0; // completely outside
else if (result == 1) intersects = true;
}
if (!intersects) return 1; // completely inside
// in case of false positives
// 2. frustum inside/outside obb test
for (let i = 0; i < frustum.vertices.length; i++)
vec3.sub(tmp[i], frustum.vertices[i], obb.center);
out1 = 0, out2 = 0;
for (let i = 0; i < frustum.vertices.length; i++) {
dist = dot(tmp[i], obb.orientation.m00, obb.orientation.m01, obb.orientation.m02);
if (dist > obb.halfExtents.x) out1++;
else if (dist < -obb.halfExtents.x) out2++;
}
if (out1 == frustum.vertices.length || out2 == frustum.vertices.length) return 0;
out1 = 0; out2 = 0;
for (let i = 0; i < frustum.vertices.length; i++) {
dist = dot(tmp[i], obb.orientation.m03, obb.orientation.m04, obb.orientation.m05);
if (dist > obb.halfExtents.y) out1++;
else if (dist < -obb.halfExtents.y) out2++;
}
if (out1 == frustum.vertices.length || out2 == frustum.vertices.length) return 0;
out1 = 0; out2 = 0;
for (let i = 0; i < frustum.vertices.length; i++) {
dist = dot(tmp[i], obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
if (dist > obb.halfExtents.z) out1++;
else if (dist < -obb.halfExtents.z) out2++;
}
if (out1 == frustum.vertices.length || out2 == frustum.vertices.length) return 0;
return 1;
};
})();
/**
* obb-obb intersect
*
* @param {obb} obb
* @return {number}
*/
let obb_obb = (function () {
let test = new Array(15);
for (let i = 0; i < 15; i++) {
test[i] = vec3.create(0, 0, 0);
}
let vertices = new Array(8);
let vertices2 = new Array(8);
for (let i = 0; i < 8; i++) {
vertices[i] = vec3.create(0, 0, 0);
vertices2[i] = vec3.create(0, 0, 0);
}
return function (obb1, obb2) {
vec3.set(test[0], obb1.orientation.m00, obb1.orientation.m01, obb1.orientation.m02);
vec3.set(test[1], obb1.orientation.m03, obb1.orientation.m04, obb1.orientation.m05);
vec3.set(test[2], obb1.orientation.m06, obb1.orientation.m07, obb1.orientation.m08);
vec3.set(test[3], obb2.orientation.m00, obb2.orientation.m01, obb2.orientation.m02);
vec3.set(test[4], obb2.orientation.m03, obb2.orientation.m04, obb2.orientation.m05);
vec3.set(test[5], obb2.orientation.m06, obb2.orientation.m07, obb2.orientation.m08);
for (let i = 0; i < 3; ++i) { // Fill out rest of axis
vec3.cross(test[6 + i * 3 + 0], test[i], test[0]);
vec3.cross(test[6 + i * 3 + 1], test[i], test[1]);
vec3.cross(test[6 + i * 3 + 1], test[i], test[2]);
}
getOBBVertices(obb1.center, obb1.halfExtents, test[0], test[1], test[2], vertices);
getOBBVertices(obb2.center, obb2.halfExtents, test[3], test[4], test[5], vertices2);
for (let i = 0; i < 15; ++i) {
let a = getInterval(vertices, test[i]);
let b = getInterval(vertices2, test[i]);
if (b[0] > a[1] || a[0] > b[1]) {
return 0; // Seperating axis found
}
}
return 1;
};
})();
/**
* sphere-plane intersect, not necessarily faster than obb-plane
* due to the length calculation of the plane normal to factor out
* the unnomalized plane distance
*
* @param {sphere} sphere
* @param {plane} plane
* @return {number} inside(back) = -1, outside(front) = 0, intersect = 1
*/
let sphere_plane = function (sphere, plane) {
let dot = vec3.dot(plane.n, sphere.c);
let r = sphere.r * vec3.magnitude(plane.n);
if (dot + r < plane.d) return -1;
else if (dot - r > plane.d) return 0;
return 1;
};
/**
* sphere-frustum intersect, faster but has
* false positive corner cases
*
* @param {sphere} sphere
* @param {planes: plane[], vertices: vec3[]} frustum
* @return {number}
*/
let sphere_frustum = function (sphere, frustum) {
for (let i = 0; i < frustum.planes.length; i++)
// frustum plane normal points to the inside
if (sphere_plane(sphere, frustum.planes[i]) == -1)
return 0; // completely outside
return 1;
};
/**
* sphere-frustum intersect, handles the false positives correctly, read more here:
* https://stackoverflow.com/questions/20912692/view-frustum-culling-corner-cases
*
* @param {sphere} sphere
* @param {planes: plane[], vertices: vec3[]} frustum
* @return {number}
*/
let sphere_frustum_accurate = (function () {
let pt = vec3.create(0, 0, 0), map = [1, -1, 1, -1, 1, -1];
return function (sphere, frustum) {
for (let i = 0; i < 6; i++) {
let plane = frustum.planes[i];
let r = sphere.r, c = sphere.c;
let n = plane.n, d = plane.d;
let dot = vec3.dot(n, c);
// frustum plane normal points to the inside
if (dot + r < d) return 0; // completely outside
else if (dot - r > d) continue;
// in case of false positives
// has false negatives, still working on it
vec3.add(pt, c, vec3.scale(pt, n, r));
for (let j = 0; j < 6; j++) {
if (j == i || j == i + map[i]) continue;
let test = frustum.planes[j];
if (vec3.dot(test.n, pt) < test.d) return 0;
}
}
return 1;
};
})();
/**
* sphere-sphere intersect
*
* @param {sphere} sphere0
* @param {sphere} sphere1
* @return {number}
*/
let sphere_sphere = function (sphere0, sphere1) {
let r = sphere0.r + sphere1.r;
return vec3.sqrDist(sphere0.c, sphere1.c) < r * r;
};
/**
* sphere-aabb intersect
*
* @param {sphere} sphere
* @param {aabb} aabb
* @return {number}
*/
let sphere_aabb = (function() {
let pt = vec3.create();
return function(sphere, aabb) {
distance.pt_point_aabb(pt, sphere.o, aabb);
return vec3.sqrDist(sphere.o, pt) < sphere.r * sphere.r;
};
})();
/**
* sphere-obb intersect
*
* @param {sphere} sphere
* @param {obb} obb
* @return {number}
*/
let sphere_obb = (function () {
let pt = vec3.create();
return function (sphere, obb) {
distance.pt_point_obb(pt, sphere.c, obb);
return vec3.sqrDist(sphere.c, pt) < sphere.r * sphere.r;
};
})();
let intersect = {
ray_sphere,
ray_aabb,
ray_obb,
ray_plane,
ray_triangle,
line_plane,
line_triangle,
line_quad,
sphere_sphere,
sphere_aabb,
sphere_obb,
sphere_plane,
sphere_frustum,
sphere_frustum_accurate,
aabb_aabb,
aabb_obb,
aabb_plane,
aabb_frustum,
aabb_frustum_accurate,
obb_obb,
obb_plane,
obb_frustum,
obb_frustum_accurate,
obb_point,
};
intersect[enums.SHAPE_RAY | enums.SHAPE_SPHERE] = ray_sphere;
intersect[enums.SHAPE_RAY | enums.SHAPE_AABB] = ray_aabb;
intersect[enums.SHAPE_RAY | enums.SHAPE_OBB] = ray_obb;
intersect[enums.SHAPE_RAY | enums.SHAPE_PLANE] = ray_plane;
intersect[enums.SHAPE_RAY | enums.SHAPE_TRIANGLE] = ray_triangle;
intersect[enums.SHAPE_LINE | enums.SHAPE_PLANE] = line_plane;
intersect[enums.SHAPE_LINE | enums.SHAPE_TRIANGLE] = line_triangle;
intersect[enums.SHAPE_SPHERE] = sphere_sphere;
intersect[enums.SHAPE_SPHERE | enums.SHAPE_AABB] = sphere_aabb;
intersect[enums.SHAPE_SPHERE | enums.SHAPE_OBB] = sphere_obb;
intersect[enums.SHAPE_SPHERE | enums.SHAPE_PLANE] = sphere_plane;
intersect[enums.SHAPE_SPHERE | enums.SHAPE_FRUSTUM] = sphere_frustum;
intersect[enums.SHAPE_SPHERE | enums.SHAPE_FRUSTUM_ACCURATE] = sphere_frustum_accurate;
intersect[enums.SHAPE_AABB] = aabb_aabb;
intersect[enums.SHAPE_AABB | enums.SHAPE_OBB] = aabb_obb;
intersect[enums.SHAPE_AABB | enums.SHAPE_PLANE] = aabb_plane;
intersect[enums.SHAPE_AABB | enums.SHAPE_FRUSTUM] = aabb_frustum;
intersect[enums.SHAPE_AABB | enums.SHAPE_FRUSTUM_ACCURATE] = aabb_frustum_accurate;
intersect[enums.SHAPE_OBB] = obb_obb;
intersect[enums.SHAPE_OBB | enums.SHAPE_PLANE] = obb_plane;
intersect[enums.SHAPE_OBB | enums.SHAPE_FRUSTUM] = obb_frustum;
intersect[enums.SHAPE_OBB | enums.SHAPE_FRUSTUM_ACCURATE] = obb_frustum_accurate;
intersect.resolve = function(g1, g2, outPt = null) {
let type1 = g1._type, type2 = g2._type;
let resolver = this[type1 | type2];
if (type1 < type2) return resolver(g1, g2, outPt);
else return resolver(g2, g1, outPt);
};
export default intersect;
+932
View File
@@ -0,0 +1,932 @@
import { mat3, vec3 } from '../../core/vmath';
import * as distance from './distance';
import enums from './enums';
// tslint:disable:only-arrow-functions
// tslint:disable:one-variable-per-declaration
// tslint:disable:prefer-for-of
/**
* ray-plane intersect
*
* @param {ray} ray
* @param {plane} plane
* @return {number}
*/
const ray_plane = (function () {
const pt = vec3.create(0, 0, 0);
return function (ray, plane) {
const denom = vec3.dot(ray.d, plane.n);
if (Math.abs(denom) < Number.EPSILON) { return 0; }
vec3.scale(pt, plane.n, plane.d);
const t = vec3.dot(vec3.sub(pt, pt, ray.o), plane.n) / denom;
if (t < 0) { return 0; }
return t;
};
})();
/**
* line-plane intersect
*
* @param {line} line
* @param {plane} plane
* @return {number}
*/
const line_plane = (function () {
const ab = vec3.create(0, 0, 0);
return function (line, plane) {
vec3.sub(ab, line.e, line.s);
const t = (plane.d - vec3.dot(line.s, plane.n)) / vec3.dot(ab, plane.n);
if (t < 0 || t > 1) { return 0; }
return t;
};
})();
/**
* ray-triangle intersect
* based on http://fileadmin.cs.lth.se/cs/Personal/Tomas_Akenine-Moller/raytri/
*
* @param {ray} ray
* @param {triangle} triangle
* @return {number}
*/
const ray_triangle = (function () {
const ab = vec3.create(0, 0, 0);
const ac = vec3.create(0, 0, 0);
const pvec = vec3.create(0, 0, 0);
const tvec = vec3.create(0, 0, 0);
const qvec = vec3.create(0, 0, 0);
return function (ray, triangle, doubleSided) {
vec3.sub(ab, triangle.b, triangle.a);
vec3.sub(ac, triangle.c, triangle.a);
vec3.cross(pvec, ray.d, ac);
const det = vec3.dot(ab, pvec);
if (det < Number.EPSILON && (!doubleSided || det > -Number.EPSILON)) { return 0; }
const inv_det = 1 / det;
vec3.sub(tvec, ray.o, triangle.a);
const u = vec3.dot(tvec, pvec) * inv_det;
if (u < 0 || u > 1) { return 0; }
vec3.cross(qvec, tvec, ab);
const v = vec3.dot(ray.d, qvec) * inv_det;
if (v < 0 || u + v > 1) { return 0; }
const t = vec3.dot(ac, qvec) * inv_det;
return t < 0 ? 0 : t;
};
})();
/**
* line-triangle intersect
*
* @param {line} line
* @param {triangle} triangle
* @param {vec3} outPt the intersect point if provide
* @return {number}
*/
const line_triangle = (function () {
const ab = vec3.create(0, 0, 0);
const ac = vec3.create(0, 0, 0);
const qp = vec3.create(0, 0, 0);
const ap = vec3.create(0, 0, 0);
const n = vec3.create(0, 0, 0);
const e = vec3.create(0, 0, 0);
return function (line, triangle, outPt) {
vec3.sub(ab, triangle.b, triangle.a);
vec3.sub(ac, triangle.c, triangle.a);
vec3.sub(qp, line.s, line.e);
vec3.cross(n, ab, ac);
const det = vec3.dot(qp, n);
if (det <= 0.0) {
return 0;
}
vec3.sub(ap, line.s, triangle.a);
const t = vec3.dot(ap, n);
if (t < 0 || t > det) {
return 0;
}
vec3.cross(e, qp, ap);
let v = vec3.dot(ac, e);
if (v < 0 || v > det) {
return 0;
}
let w = -vec3.dot(ab, e);
if (w < 0.0 || v + w > det) {
return 0;
}
if (outPt) {
const invDet = 1.0 / det;
v *= invDet;
w *= invDet;
const u = 1.0 - v - w;
// outPt = u*a + v*d + w*c;
vec3.set(outPt,
triangle.a.x * u + triangle.b.x * v + triangle.c.x * w,
triangle.a.y * u + triangle.b.y * v + triangle.c.y * w,
triangle.a.z * u + triangle.b.z * v + triangle.c.z * w,
);
}
return 1;
};
})();
/**
* line-quad intersect
*
* @param {vec3} p
* @param {vec3} q
* @param {vec3} a
* @param {vec3} b
* @param {vec3} c
* @param {vec3} d
* @param {vec3} outPt the intersect point if provide
* @return {number}
*/
const line_quad = (function () {
const pq = vec3.create(0, 0, 0);
const pa = vec3.create(0, 0, 0);
const pb = vec3.create(0, 0, 0);
const pc = vec3.create(0, 0, 0);
const pd = vec3.create(0, 0, 0);
const m = vec3.create(0, 0, 0);
const tmp = vec3.create(0, 0, 0);
return function (p, q, a, b, c, d, outPt) {
vec3.sub(pq, q, p);
vec3.sub(pa, a, p);
vec3.sub(pb, b, p);
vec3.sub(pc, c, p);
// Determine which triangle to test against by testing against diagonal first
vec3.cross(m, pc, pq);
let v = vec3.dot(pa, m);
if (v >= 0) {
// Test intersection against triangle abc
let u = -vec3.dot(pb, m);
if (u < 0) {
return 0;
}
let w = vec3.dot(vec3.cross(tmp, pq, pb), pa);
if (w < 0) {
return 0;
}
// outPt = u*a + v*b + w*c;
if (outPt) {
const denom = 1.0 / (u + v + w);
u *= denom;
v *= denom;
w *= denom;
vec3.set(outPt,
a.x * u + b.x * v + c.x * w,
a.y * u + b.y * v + c.y * w,
a.z * u + b.z * v + c.z * w,
);
}
} else {
// Test intersection against triangle dac
vec3.sub(pd, d, p);
let u = vec3.dot(pd, m);
if (u < 0) {
return 0;
}
let w = vec3.dot(vec3.cross(tmp, pq, pa), pd);
if (w < 0) {
return 0;
}
// outPt = u*a + v*d + w*c;
if (outPt) {
v = -v;
const denom = 1.0 / (u + v + w);
u *= denom;
v *= denom;
w *= denom;
vec3.set(outPt,
a.x * u + d.x * v + c.x * w,
a.y * u + d.y * v + c.y * w,
a.z * u + d.z * v + c.z * w,
);
}
}
return 1;
};
})();
/**
* ray-sphere intersect
*
* @param {ray} ray
* @param {sphere} sphere
* @return {number}
*/
const ray_sphere = (function () {
const e = vec3.create(0, 0, 0);
return function (ray, sphere) {
const r = sphere.r;
const c = sphere.c;
const o = ray.o;
const d = ray.d;
const rSq = r * r;
vec3.sub(e, c, o);
const eSq = vec3.sqrMag(e);
const aLength = vec3.dot(e, d); // assume ray direction already normalized
const fSq = rSq - (eSq - aLength * aLength);
if (fSq < 0) { return 0; }
const f = Math.sqrt(fSq);
const t = eSq < rSq ? aLength + f : aLength - f;
if (t < 0) { return 0; }
return t;
};
})();
/**
* ray-aabb intersect
*
* @param {ray} ray
* @param {aabb} aabb
* @return {number}
*/
const ray_aabb = (function () {
const min = vec3.create();
const max = vec3.create();
return function (ray, aabb) {
const o = ray.o, d = ray.d;
const ix = 1 / d.x, iy = 1 / d.y, iz = 1 / d.z;
vec3.sub(min, aabb.center, aabb.halfExtents);
vec3.add(max, aabb.center, aabb.halfExtents);
const t1 = (min.x - o.x) * ix;
const t2 = (max.x - o.x) * ix;
const t3 = (min.y - o.y) * iy;
const t4 = (max.y - o.y) * iy;
const t5 = (min.z - o.z) * iz;
const t6 = (max.z - o.z) * iz;
const tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6));
const tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6));
if (tmax < 0 || tmin > tmax) { return 0; }
return tmin;
};
})();
/**
* ray-obb intersect
*
* @param {ray} ray
* @param {obb} obb
* @return {number}
*/
const ray_obb = (function () {
let center = vec3.create();
let o = vec3.create();
let d = vec3.create();
const X = vec3.create();
const Y = vec3.create();
const Z = vec3.create();
const p = vec3.create();
const size = new Array(3);
const f = new Array(3);
const e = new Array(3);
const t = new Array(6);
return function (ray, obb) {
size[0] = obb.halfExtents.x;
size[1] = obb.halfExtents.y;
size[2] = obb.halfExtents.z;
center = obb.center;
o = ray.o;
d = ray.d;
vec3.set(X, obb.orientation.m00, obb.orientation.m01, obb.orientation.m02);
vec3.set(Y, obb.orientation.m03, obb.orientation.m04, obb.orientation.m05);
vec3.set(Z, obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
vec3.sub(p, center, o);
// The cos values of the ray on the X, Y, Z
f[0] = vec3.dot(X, d);
f[1] = vec3.dot(Y, d);
f[2] = vec3.dot(Z, d);
// The projection length of P on X, Y, Z
e[0] = vec3.dot(X, p);
e[1] = vec3.dot(Y, p);
e[2] = vec3.dot(Z, p);
for (let i = 0; i < 3; ++i) {
if (f[i] === 0) {
if (-e[i] - size[i] > 0 || -e[i] + size[i] < 0) {
return 0;
}
// Avoid div by 0!
f[i] = 0.0000001;
}
// min
t[i * 2 + 0] = (e[i] + size[i]) / f[i];
// max
t[i * 2 + 1] = (e[i] - size[i]) / f[i];
}
const tmin = Math.max(
Math.max(
Math.min(t[0], t[1]),
Math.min(t[2], t[3])),
Math.min(t[4], t[5]),
);
const tmax = Math.min(
Math.min(
Math.max(t[0], t[1]),
Math.max(t[2], t[3])),
Math.max(t[4], t[5]),
);
if (tmax < 0 || tmin > tmax || tmin < 0) {
return 0;
}
return tmin;
};
})();
/**
* aabb-aabb intersect
*
* @param {aabb} aabb1
* @param {aabb} aabb2
* @return {number}
*/
const aabb_aabb = (function () {
const aMin = vec3.create();
const aMax = vec3.create();
const bMin = vec3.create();
const bMax = vec3.create();
return function (aabb1, aabb2) {
vec3.sub(aMin, aabb1.center, aabb1.halfExtents);
vec3.add(aMax, aabb1.center, aabb1.halfExtents);
vec3.sub(bMin, aabb2.center, aabb2.halfExtents);
vec3.add(bMax, aabb2.center, aabb2.halfExtents);
return (aMin.x <= bMax.x && aMax.x >= bMin.x) &&
(aMin.y <= bMax.y && aMax.y >= bMin.y) &&
(aMin.z <= bMax.z && aMax.z >= bMin.z);
};
})();
function getAABBVertices (min, max, out) {
vec3.set(out[0], min.x, max.y, max.z);
vec3.set(out[1], min.x, max.y, min.z);
vec3.set(out[2], min.x, min.y, max.z);
vec3.set(out[3], min.x, min.y, min.z);
vec3.set(out[4], max.x, max.y, max.z);
vec3.set(out[5], max.x, max.y, min.z);
vec3.set(out[6], max.x, min.y, max.z);
vec3.set(out[7], max.x, min.y, min.z);
}
function getOBBVertices (c, e, a1, a2, a3, out) {
vec3.set(out[0],
c.x + a1.x * e.x + a2.x * e.y + a3.x * e.z,
c.y + a1.y * e.x + a2.y * e.y + a3.y * e.z,
c.z + a1.z * e.x + a2.z * e.y + a3.z * e.z,
);
vec3.set(out[1],
c.x - a1.x * e.x + a2.x * e.y + a3.x * e.z,
c.y - a1.y * e.x + a2.y * e.y + a3.y * e.z,
c.z - a1.z * e.x + a2.z * e.y + a3.z * e.z,
);
vec3.set(out[2],
c.x + a1.x * e.x - a2.x * e.y + a3.x * e.z,
c.y + a1.y * e.x - a2.y * e.y + a3.y * e.z,
c.z + a1.z * e.x - a2.z * e.y + a3.z * e.z,
);
vec3.set(out[3],
c.x + a1.x * e.x + a2.x * e.y - a3.x * e.z,
c.y + a1.y * e.x + a2.y * e.y - a3.y * e.z,
c.z + a1.z * e.x + a2.z * e.y - a3.z * e.z,
);
vec3.set(out[4],
c.x - a1.x * e.x - a2.x * e.y - a3.x * e.z,
c.y - a1.y * e.x - a2.y * e.y - a3.y * e.z,
c.z - a1.z * e.x - a2.z * e.y - a3.z * e.z,
);
vec3.set(out[5],
c.x + a1.x * e.x - a2.x * e.y - a3.x * e.z,
c.y + a1.y * e.x - a2.y * e.y - a3.y * e.z,
c.z + a1.z * e.x - a2.z * e.y - a3.z * e.z,
);
vec3.set(out[6],
c.x - a1.x * e.x + a2.x * e.y - a3.x * e.z,
c.y - a1.y * e.x + a2.y * e.y - a3.y * e.z,
c.z - a1.z * e.x + a2.z * e.y - a3.z * e.z,
);
vec3.set(out[7],
c.x - a1.x * e.x - a2.x * e.y + a3.x * e.z,
c.y - a1.y * e.x - a2.y * e.y + a3.y * e.z,
c.z - a1.z * e.x - a2.z * e.y + a3.z * e.z,
);
}
function getInterval (vertices, axis) {
let min = vec3.dot(axis, vertices[0]), max = min;
for (let i = 1; i < 8; ++i) {
const projection = vec3.dot(axis, vertices[i]);
min = (projection < min) ? projection : min;
max = (projection > max) ? projection : max;
}
return [min, max];
}
/**
* aabb-obb intersect
*
* @param {aabb} aabb
* @param {obb} obb
* @return {number}
*/
const aabb_obb = (function () {
const test = new Array(15);
for (let i = 0; i < 15; i++) {
test[i] = vec3.create(0, 0, 0);
}
const vertices = new Array(8);
const vertices2 = new Array(8);
for (let i = 0; i < 8; i++) {
vertices[i] = vec3.create(0, 0, 0);
vertices2[i] = vec3.create(0, 0, 0);
}
const min = vec3.create();
const max = vec3.create();
return function (aabb, obb) {
vec3.set(test[0], 1, 0, 0);
vec3.set(test[1], 0, 1, 0);
vec3.set(test[2], 0, 0, 1);
vec3.set(test[3], obb.orientation.m00, obb.orientation.m01, obb.orientation.m02);
vec3.set(test[4], obb.orientation.m03, obb.orientation.m04, obb.orientation.m05);
vec3.set(test[5], obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
for (let i = 0; i < 3; ++i) { // Fill out rest of axis
vec3.cross(test[6 + i * 3 + 0], test[i], test[0]);
vec3.cross(test[6 + i * 3 + 1], test[i], test[1]);
vec3.cross(test[6 + i * 3 + 1], test[i], test[2]);
}
vec3.sub(min, aabb.center, aabb.halfExtents);
vec3.add(max, aabb.center, aabb.halfExtents);
getAABBVertices(min, max, vertices);
getOBBVertices(obb.center, obb.halfExtents, test[3], test[4], test[5], vertices2);
for (let j = 0; j < 15; ++j) {
const a = getInterval(vertices, test[j]);
const b = getInterval(vertices2, test[j]);
if (b[0] > a[1] || a[0] > b[1]) {
return 0; // Seperating axis found
}
}
return 1;
};
})();
/**
* aabb-plane intersect
*
* @param {aabb} aabb
* @param {plane} plane
* @return {number} inside(back) = -1, outside(front) = 0, intersect = 1
*/
const aabb_plane = function (aabb, plane) {
const r = aabb.halfExtents.x * Math.abs(plane.n.x) +
aabb.halfExtents.y * Math.abs(plane.n.y) +
aabb.halfExtents.z * Math.abs(plane.n.z);
const dot = vec3.dot(plane.n, aabb.center);
if (dot + r < plane.d) { return -1; }
else if (dot - r > plane.d) { return 0; }
return 1;
};
/**
* aabb-frustum intersect, faster but has
* false positive corner cases
*
* @param {aabb} aabb
* @param {planes: plane[], vertices: vec3[]} frustum
* @return {number}
*/
const aabb_frustum = function (aabb, frustum) {
for (let i = 0; i < frustum.planes.length; i++) {
// frustum plane normal points to the inside
if (aabb_plane(aabb, frustum.planes[i]) === -1) {
return 0;
}
} // completely outside
return 1;
};
/**
* aabb-frustum intersect, handles most of the false positives correctly, read more here:
* https://cesium.com/blog/2017/02/02/tighter-frustum-culling-and-why-you-may-want-to-disregard-it/
*
* @param {aabb} aabb
* @param {planes: plane[], vertices: vec3[]} frustum
* @return {number}
*/
const aabb_frustum_accurate = (function () {
const tmp = new Array(8);
let out1 = 0, out2 = 0;
for (let i = 0; i < tmp.length; i++) {
tmp[i] = vec3.create(0, 0, 0);
}
return function (aabb, frustum) {
let result = 0, intersects = false;
// 1. aabb inside/outside frustum test
for (let i = 0; i < frustum.planes.length; i++) {
result = aabb_plane(aabb, frustum.planes[i]);
// frustum plane normal points to the inside
if (result === -1) { return 0; } // completely outside
else if (result === 1) { intersects = true; }
}
if (!intersects) { return 1; } // completely inside
// in case of false positives
// 2. frustum inside/outside aabb test
for (let i = 0; i < frustum.vertices.length; i++) {
vec3.sub(tmp[i], frustum.vertices[i], aabb.center);
}
out1 = 0, out2 = 0;
for (let i = 0; i < frustum.vertices.length; i++) {
if (tmp[i].x > aabb.halfExtents.x) { out1++; }
else if (tmp[i].x < -aabb.halfExtents.x) { out2++; }
}
if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) { return 0; }
out1 = 0; out2 = 0;
for (let i = 0; i < frustum.vertices.length; i++) {
if (tmp[i].y > aabb.halfExtents.y) { out1++; }
else if (tmp[i].y < -aabb.halfExtents.y) { out2++; }
}
if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) { return 0; }
out1 = 0; out2 = 0;
for (let i = 0; i < frustum.vertices.length; i++) {
if (tmp[i].z > aabb.halfExtents.z) { out1++; }
else if (tmp[i].z < -aabb.halfExtents.z) { out2++; }
}
if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) { return 0; }
return 1;
};
})();
/**
* obb-point intersect
*
* @param {obb} obb
* @param {vec3} point
* @return {number}
*/
const obb_point = (function () {
const tmp = vec3.create(0, 0, 0), m3 = mat3.create();
const lessThan = function (a, b) { return Math.abs(a.x) < b.x && Math.abs(a.y) < b.y && Math.abs(a.z) < b.z; };
return function (obb, point) {
vec3.sub(tmp, point, obb.center);
vec3.transformMat3(tmp, tmp, mat3.transpose(m3, obb.orientation));
return lessThan(tmp, obb.halfExtents);
};
})();
/**
* obb-plane intersect
*
* @param {obb} obb
* @param {plane} plane
* @return {number} inside(back) = -1, outside(front) = 0, intersect = 1
*/
const obb_plane = (function () {
const absDot = function (n, x, y, z) {
return Math.abs(n.x * x + n.y * y + n.z * z);
};
return function (obb, plane) {
// Real-Time Collision Detection, Christer Ericson, p. 163.
const r = obb.halfExtents.x * absDot(plane.n, obb.orientation.m00, obb.orientation.m01, obb.orientation.m02) +
obb.halfExtents.y * absDot(plane.n, obb.orientation.m03, obb.orientation.m04, obb.orientation.m05) +
obb.halfExtents.z * absDot(plane.n, obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
const dot = vec3.dot(plane.n, obb.center);
if (dot + r < plane.d) { return -1; }
else if (dot - r > plane.d) { return 0; }
return 1;
};
})();
/**
* obb-frustum intersect, faster but has
* false positive corner cases
*
* @param {obb} obb
* @param {planes: plane[], vertices: vec3[]} frustum
* @return {number}
*/
const obb_frustum = function (obb, frustum) {
for (let i = 0; i < frustum.planes.length; i++) {
// frustum plane normal points to the inside
if (obb_plane(obb, frustum.planes[i]) === -1) {
return 0;
}
} // completely outside
return 1;
};
/**
* obb-frustum intersect, handles most of the false positives correctly, read more here:
* https://cesium.com/blog/2017/02/02/tighter-frustum-culling-and-why-you-may-want-to-disregard-it/
*
* @param {obb} obb
* @param {planes: plane[], vertices: vec3[]} frustum
* @return {number}
*/
const obb_frustum_accurate = (function () {
const tmp = new Array(8);
let dist = 0, out1 = 0, out2 = 0;
for (let i = 0; i < tmp.length; i++) {
tmp[i] = vec3.create(0, 0, 0);
}
const dot = function (n, x, y, z) {
return n.x * x + n.y * y + n.z * z;
};
return function (obb, frustum) {
let result = 0, intersects = false;
// 1. obb inside/outside frustum test
for (let i = 0; i < frustum.planes.length; i++) {
result = obb_plane(obb, frustum.planes[i]);
// frustum plane normal points to the inside
if (result === -1) { return 0; } // completely outside
else if (result === 1) { intersects = true; }
}
if (!intersects) { return 1; } // completely inside
// in case of false positives
// 2. frustum inside/outside obb test
for (let i = 0; i < frustum.vertices.length; i++) {
vec3.sub(tmp[i], frustum.vertices[i], obb.center);
}
out1 = 0, out2 = 0;
for (let i = 0; i < frustum.vertices.length; i++) {
dist = dot(tmp[i], obb.orientation.m00, obb.orientation.m01, obb.orientation.m02);
if (dist > obb.halfExtents.x) { out1++; }
else if (dist < -obb.halfExtents.x) { out2++; }
}
if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) { return 0; }
out1 = 0; out2 = 0;
for (let i = 0; i < frustum.vertices.length; i++) {
dist = dot(tmp[i], obb.orientation.m03, obb.orientation.m04, obb.orientation.m05);
if (dist > obb.halfExtents.y) { out1++; }
else if (dist < -obb.halfExtents.y) { out2++; }
}
if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) { return 0; }
out1 = 0; out2 = 0;
for (let i = 0; i < frustum.vertices.length; i++) {
dist = dot(tmp[i], obb.orientation.m06, obb.orientation.m07, obb.orientation.m08);
if (dist > obb.halfExtents.z) { out1++; }
else if (dist < -obb.halfExtents.z) { out2++; }
}
if (out1 === frustum.vertices.length || out2 === frustum.vertices.length) { return 0; }
return 1;
};
})();
/**
* obb-obb intersect
*
* @param {obb} obb
* @return {number}
*/
const obb_obb = (function () {
const test = new Array(15);
for (let i = 0; i < 15; i++) {
test[i] = vec3.create(0, 0, 0);
}
const vertices = new Array(8);
const vertices2 = new Array(8);
for (let i = 0; i < 8; i++) {
vertices[i] = vec3.create(0, 0, 0);
vertices2[i] = vec3.create(0, 0, 0);
}
return function (obb1, obb2) {
vec3.set(test[0], obb1.orientation.m00, obb1.orientation.m01, obb1.orientation.m02);
vec3.set(test[1], obb1.orientation.m03, obb1.orientation.m04, obb1.orientation.m05);
vec3.set(test[2], obb1.orientation.m06, obb1.orientation.m07, obb1.orientation.m08);
vec3.set(test[3], obb2.orientation.m00, obb2.orientation.m01, obb2.orientation.m02);
vec3.set(test[4], obb2.orientation.m03, obb2.orientation.m04, obb2.orientation.m05);
vec3.set(test[5], obb2.orientation.m06, obb2.orientation.m07, obb2.orientation.m08);
for (let i = 0; i < 3; ++i) { // Fill out rest of axis
vec3.cross(test[6 + i * 3 + 0], test[i], test[0]);
vec3.cross(test[6 + i * 3 + 1], test[i], test[1]);
vec3.cross(test[6 + i * 3 + 1], test[i], test[2]);
}
getOBBVertices(obb1.center, obb1.halfExtents, test[0], test[1], test[2], vertices);
getOBBVertices(obb2.center, obb2.halfExtents, test[3], test[4], test[5], vertices2);
for (let i = 0; i < 15; ++i) {
const a = getInterval(vertices, test[i]);
const b = getInterval(vertices2, test[i]);
if (b[0] > a[1] || a[0] > b[1]) {
return 0; // Seperating axis found
}
}
return 1;
};
})();
/**
* sphere-plane intersect, not necessarily faster than obb-plane
* due to the length calculation of the plane normal to factor out
* the unnomalized plane distance
*
* @param {sphere} sphere
* @param {plane} plane
* @return {number} inside(back) = -1, outside(front) = 0, intersect = 1
*/
const sphere_plane = function (sphere, plane) {
const dot = vec3.dot(plane.n, sphere.c);
const r = sphere.r * vec3.magnitude(plane.n);
if (dot + r < plane.d) { return -1; }
else if (dot - r > plane.d) { return 0; }
return 1;
};
/**
* sphere-frustum intersect, faster but has
* false positive corner cases
*
* @param {sphere} sphere
* @param {planes: plane[], vertices: vec3[]} frustum
* @return {number}
*/
const sphere_frustum = function (sphere, frustum) {
for (let i = 0; i < frustum.planes.length; i++) {
// frustum plane normal points to the inside
if (sphere_plane(sphere, frustum.planes[i]) === -1) {
return 0;
}
} // completely outside
return 1;
};
/**
* sphere-frustum intersect, handles the false positives correctly, read more here:
* https://stackoverflow.com/questions/20912692/view-frustum-culling-corner-cases
*
* @param {sphere} sphere
* @param {planes: plane[], vertices: vec3[]} frustum
* @return {number}
*/
const sphere_frustum_accurate = (function () {
const pt = vec3.create(0, 0, 0), map = [1, -1, 1, -1, 1, -1];
return function (sphere, frustum) {
for (let i = 0; i < 6; i++) {
const plane = frustum.planes[i];
const r = sphere.r, c = sphere.c;
const n = plane.n, d = plane.d;
const dot = vec3.dot(n, c);
// frustum plane normal points to the inside
if (dot + r < d) { return 0; } // completely outside
else if (dot - r > d) { continue; }
// in case of false positives
// has false negatives, still working on it
vec3.add(pt, c, vec3.scale(pt, n, r));
for (let j = 0; j < 6; j++) {
if (j === i || j === i + map[i]) { continue; }
const test = frustum.planes[j];
if (vec3.dot(test.n, pt) < test.d) { return 0; }
}
}
return 1;
};
})();
/**
* sphere-sphere intersect
*
* @param {sphere} sphere0
* @param {sphere} sphere1
* @return {number}
*/
const sphere_sphere = function (sphere0, sphere1) {
const r = sphere0.r + sphere1.r;
return vec3.sqrDist(sphere0.c, sphere1.c) < r * r;
};
/**
* sphere-aabb intersect
*
* @param {sphere} sphere
* @param {aabb} aabb
* @return {number}
*/
const sphere_aabb = (function () {
const pt = vec3.create();
return function (sphere, aabb) {
distance.pt_point_aabb(pt, sphere.o, aabb);
return vec3.sqrDist(sphere.o, pt) < sphere.r * sphere.r;
};
})();
/**
* sphere-obb intersect
*
* @param {sphere} sphere
* @param {obb} obb
* @return {number}
*/
const sphere_obb = (function () {
const pt = vec3.create();
return function (sphere, obb) {
distance.pt_point_obb(pt, sphere.c, obb);
return vec3.sqrDist(sphere.c, pt) < sphere.r * sphere.r;
};
})();
const intersect = {
ray_sphere,
ray_aabb,
ray_obb,
ray_plane,
ray_triangle,
line_plane,
line_triangle,
line_quad,
sphere_sphere,
sphere_aabb,
sphere_obb,
sphere_plane,
sphere_frustum,
sphere_frustum_accurate,
aabb_aabb,
aabb_obb,
aabb_plane,
aabb_frustum,
aabb_frustum_accurate,
obb_obb,
obb_plane,
obb_frustum,
obb_frustum_accurate,
obb_point,
resolve (g1, g2, outPt = null) {
const type1 = g1._type, type2 = g2._type;
const resolver = this[type1 | type2];
if (type1 < type2) { return resolver(g1, g2, outPt); }
else { return resolver(g2, g1, outPt); }
},
};
intersect[enums.SHAPE_RAY | enums.SHAPE_SPHERE] = ray_sphere;
intersect[enums.SHAPE_RAY | enums.SHAPE_AABB] = ray_aabb;
intersect[enums.SHAPE_RAY | enums.SHAPE_OBB] = ray_obb;
intersect[enums.SHAPE_RAY | enums.SHAPE_PLANE] = ray_plane;
intersect[enums.SHAPE_RAY | enums.SHAPE_TRIANGLE] = ray_triangle;
intersect[enums.SHAPE_LINE | enums.SHAPE_PLANE] = line_plane;
intersect[enums.SHAPE_LINE | enums.SHAPE_TRIANGLE] = line_triangle;
intersect[enums.SHAPE_SPHERE] = sphere_sphere;
intersect[enums.SHAPE_SPHERE | enums.SHAPE_AABB] = sphere_aabb;
intersect[enums.SHAPE_SPHERE | enums.SHAPE_OBB] = sphere_obb;
intersect[enums.SHAPE_SPHERE | enums.SHAPE_PLANE] = sphere_plane;
intersect[enums.SHAPE_SPHERE | enums.SHAPE_FRUSTUM] = sphere_frustum;
intersect[enums.SHAPE_SPHERE | enums.SHAPE_FRUSTUM_ACCURATE] = sphere_frustum_accurate;
intersect[enums.SHAPE_AABB] = aabb_aabb;
intersect[enums.SHAPE_AABB | enums.SHAPE_OBB] = aabb_obb;
intersect[enums.SHAPE_AABB | enums.SHAPE_PLANE] = aabb_plane;
intersect[enums.SHAPE_AABB | enums.SHAPE_FRUSTUM] = aabb_frustum;
intersect[enums.SHAPE_AABB | enums.SHAPE_FRUSTUM_ACCURATE] = aabb_frustum_accurate;
intersect[enums.SHAPE_OBB] = obb_obb;
intersect[enums.SHAPE_OBB | enums.SHAPE_PLANE] = obb_plane;
intersect[enums.SHAPE_OBB | enums.SHAPE_FRUSTUM] = obb_frustum;
intersect[enums.SHAPE_OBB | enums.SHAPE_FRUSTUM_ACCURATE] = obb_frustum_accurate;
export default intersect;
-203
View File
@@ -1,203 +0,0 @@
'use strict';
import { vec3 } from '../../core/vmath';
let temp1 = vec3.create(0, 0, 0);
let temp2 = vec3.create(0, 0, 0);
/**
* @param {Number} radiusTop
* @param {Number} radiusBottom
* @param {Number} height
* @param {Object} opts
* @param {Number} opts.sides
* @param {Number} opts.heightSegments
* @param {Boolean} opts.capped
* @param {Number} opts.arc
*/
export default function (radiusTop = 0.5, radiusBottom = 0.5, height = 2, opts = {}) {
let torsoHeight = height - radiusTop - radiusBottom;
let sides = opts.sides || 32;
let heightSegments = opts.heightSegments || 32;
let bottomProp = radiusBottom / height;
let torProp = torsoHeight / height;
let topProp = radiusTop / height;
let bottomSegments = Math.floor(heightSegments * bottomProp);
let topSegments = Math.floor(heightSegments * topProp);
let torSegments = Math.floor(heightSegments * torProp);
let topOffset = torsoHeight + radiusBottom - height / 2;
let torOffset = radiusBottom - height / 2;
let bottomOffset = radiusBottom - height / 2;
let arc = opts.arc || 2.0 * Math.PI;
// calculate vertex count
let positions = [];
let normals = [];
let uvs = [];
let indices = [];
let maxRadius = Math.max(radiusTop, radiusBottom);
let minPos = vec3.create(-maxRadius, -height / 2, -maxRadius);
let maxPos = vec3.create(maxRadius, height / 2, maxRadius);
let boundingRadius = height / 2;
let index = 0;
let indexArray = [];
generateBottom();
generateTorso();
generateTop();
return {
positions,
normals,
uvs,
indices,
minPos,
maxPos,
boundingRadius
};
// =======================
// internal fucntions
// =======================
function generateTorso() {
// this will be used to calculate the normal
let slope = (radiusTop - radiusBottom) / torsoHeight;
// generate positions, normals and uvs
for (let y = 0; y <= torSegments; y++) {
let indexRow = [];
let lat = y / torSegments;
let radius = lat * (radiusTop - radiusBottom) + radiusBottom;
for (let x = 0; x <= sides; ++x) {
let u = x / sides;
let v = lat * torProp + bottomProp;
let theta = u * arc - (arc / 4);
let sinTheta = Math.sin(theta);
let cosTheta = Math.cos(theta);
// vertex
positions.push(radius * sinTheta);
positions.push(lat * torsoHeight + torOffset);
positions.push(radius * cosTheta);
// normal
vec3.normalize(temp1, vec3.set(temp2, sinTheta, -slope, cosTheta));
normals.push(temp1.x);
normals.push(temp1.y);
normals.push(temp1.z);
// uv
uvs.push(u,v);
// save index of vertex in respective row
indexRow.push(index);
// increase index
++index;
}
// now save positions of the row in our index array
indexArray.push(indexRow);
}
// generate indices
for (let y = 0; y < torSegments; ++y) {
for (let x = 0; x < sides; ++x) {
// we use the index array to access the correct indices
let i1 = indexArray[y][x];
let i2 = indexArray[y + 1][x];
let i3 = indexArray[y + 1][x + 1];
let i4 = indexArray[y][x + 1];
// face one
indices.push(i1);
indices.push(i4);
indices.push(i2);
// face two
indices.push(i4);
indices.push(i3);
indices.push(i2);
}
}
}
function generateBottom() {
for (let lat = 0; lat <= bottomSegments; ++lat) {
let theta = lat * Math.PI / bottomSegments / 2;
let sinTheta = Math.sin(theta);
let cosTheta = -Math.cos(theta);
for (let lon = 0; lon <= sides; ++lon) {
let phi = lon * 2 * Math.PI / sides - Math.PI / 2.0;
let sinPhi = Math.sin(phi);
let cosPhi = Math.cos(phi);
let x = sinPhi * sinTheta;
let y = cosTheta;
let z = cosPhi * sinTheta;
let u = lon / sides;
let v = lat / heightSegments;
positions.push(x * radiusBottom, y * radiusBottom + bottomOffset, z * radiusBottom);
normals.push(x, y, z);
uvs.push(u, v);
if ((lat < bottomSegments) && (lon < sides)) {
let seg1 = sides + 1;
let a = seg1 * lat + lon;
let b = seg1 * (lat + 1) + lon;
let c = seg1 * (lat + 1) + lon + 1;
let d = seg1 * lat + lon + 1;
indices.push(a, d, b);
indices.push(d, c, b);
}
++index;
}
}
}
function generateTop() {
for (let lat = 0; lat <= topSegments; ++lat) {
let theta = lat * Math.PI / topSegments / 2 + Math.PI / 2;
let sinTheta = Math.sin(theta);
let cosTheta = -Math.cos(theta);
for (let lon = 0; lon <= sides; ++lon) {
let phi = lon * 2 * Math.PI / sides - Math.PI / 2.0;
let sinPhi = Math.sin(phi);
let cosPhi = Math.cos(phi);
let x = sinPhi * sinTheta;
let y = cosTheta;
let z = cosPhi * sinTheta;
let u = lon / sides;
let v = lat / heightSegments + (1-topProp);
positions.push(x * radiusTop, y * radiusTop + topOffset, z * radiusTop);
normals.push(x, y, z);
uvs.push(u, v);
if ((lat < topSegments) && (lon < sides)) {
let seg1 = sides + 1;
let a = seg1 * lat + lon + indexArray[torSegments][sides] + 1;
let b = seg1 * (lat + 1) + lon + indexArray[torSegments][sides] + 1;
let c = seg1 * (lat + 1) + lon + 1 + indexArray[torSegments][sides] + 1;
let d = seg1 * lat + lon + 1 + indexArray[torSegments][sides] + 1;
indices.push(a, d, b);
indices.push(d, c, b);
}
}
}
}
}
+198
View File
@@ -0,0 +1,198 @@
import { vec3 } from '../../core/vmath';
export interface ICapsuteOptions {
sides: number;
heightSegments: number;
capped: boolean;
arc: number;
}
const temp1 = vec3.create(0, 0, 0);
const temp2 = vec3.create(0, 0, 0);
export default function (radiusTop = 0.5, radiusBottom = 0.5, height = 2, opts: RecursivePartial<ICapsuteOptions> = {}) {
const torsoHeight = height - radiusTop - radiusBottom;
const sides = opts.sides || 32;
const heightSegments = opts.heightSegments || 32;
const bottomProp = radiusBottom / height;
const torProp = torsoHeight / height;
const topProp = radiusTop / height;
const bottomSegments = Math.floor(heightSegments * bottomProp);
const topSegments = Math.floor(heightSegments * topProp);
const torSegments = Math.floor(heightSegments * torProp);
const topOffset = torsoHeight + radiusBottom - height / 2;
const torOffset = radiusBottom - height / 2;
const bottomOffset = radiusBottom - height / 2;
const arc = opts.arc || 2.0 * Math.PI;
// calculate vertex count
const positions: number[] = [];
const normals: number[] = [];
const uvs: number[] = [];
const indices: number[] = [];
const maxRadius = Math.max(radiusTop, radiusBottom);
const minPos = vec3.create(-maxRadius, -height / 2, -maxRadius);
const maxPos = vec3.create(maxRadius, height / 2, maxRadius);
const boundingRadius = height / 2;
let index = 0;
const indexArray: number[][] = [];
generateBottom();
generateTorso();
generateTop();
return {
positions,
normals,
uvs,
indices,
minPos,
maxPos,
boundingRadius,
};
// =======================
// internal fucntions
// =======================
function generateTorso () {
// this will be used to calculate the normal
const slope = (radiusTop - radiusBottom) / torsoHeight;
// generate positions, normals and uvs
for (let y = 0; y <= torSegments; y++) {
const indexRow: number[] = [];
const lat = y / torSegments;
const radius = lat * (radiusTop - radiusBottom) + radiusBottom;
for (let x = 0; x <= sides; ++x) {
const u = x / sides;
const v = lat * torProp + bottomProp;
const theta = u * arc - (arc / 4);
const sinTheta = Math.sin(theta);
const cosTheta = Math.cos(theta);
// vertex
positions.push(radius * sinTheta);
positions.push(lat * torsoHeight + torOffset);
positions.push(radius * cosTheta);
// normal
vec3.normalize(temp1, vec3.set(temp2, sinTheta, -slope, cosTheta));
normals.push(temp1.x);
normals.push(temp1.y);
normals.push(temp1.z);
// uv
uvs.push(u, v);
// save index of vertex in respective row
indexRow.push(index);
// increase index
++index;
}
// now save positions of the row in our index array
indexArray.push(indexRow);
}
// generate indices
for (let y = 0; y < torSegments; ++y) {
for (let x = 0; x < sides; ++x) {
// we use the index array to access the correct indices
const i1 = indexArray[y][x];
const i2 = indexArray[y + 1][x];
const i3 = indexArray[y + 1][x + 1];
const i4 = indexArray[y][x + 1];
// face one
indices.push(i1);
indices.push(i4);
indices.push(i2);
// face two
indices.push(i4);
indices.push(i3);
indices.push(i2);
}
}
}
function generateBottom () {
for (let lat = 0; lat <= bottomSegments; ++lat) {
const theta = lat * Math.PI / bottomSegments / 2;
const sinTheta = Math.sin(theta);
const cosTheta = -Math.cos(theta);
for (let lon = 0; lon <= sides; ++lon) {
const phi = lon * 2 * Math.PI / sides - Math.PI / 2.0;
const sinPhi = Math.sin(phi);
const cosPhi = Math.cos(phi);
const x = sinPhi * sinTheta;
const y = cosTheta;
const z = cosPhi * sinTheta;
const u = lon / sides;
const v = lat / heightSegments;
positions.push(x * radiusBottom, y * radiusBottom + bottomOffset, z * radiusBottom);
normals.push(x, y, z);
uvs.push(u, v);
if ((lat < bottomSegments) && (lon < sides)) {
const seg1 = sides + 1;
const a = seg1 * lat + lon;
const b = seg1 * (lat + 1) + lon;
const c = seg1 * (lat + 1) + lon + 1;
const d = seg1 * lat + lon + 1;
indices.push(a, d, b);
indices.push(d, c, b);
}
++index;
}
}
}
function generateTop () {
for (let lat = 0; lat <= topSegments; ++lat) {
const theta = lat * Math.PI / topSegments / 2 + Math.PI / 2;
const sinTheta = Math.sin(theta);
const cosTheta = -Math.cos(theta);
for (let lon = 0; lon <= sides; ++lon) {
const phi = lon * 2 * Math.PI / sides - Math.PI / 2.0;
const sinPhi = Math.sin(phi);
const cosPhi = Math.cos(phi);
const x = sinPhi * sinTheta;
const y = cosTheta;
const z = cosPhi * sinTheta;
const u = lon / sides;
const v = lat / heightSegments + (1 - topProp);
positions.push(x * radiusTop, y * radiusTop + topOffset, z * radiusTop);
normals.push(x, y, z);
uvs.push(u, v);
if ((lat < topSegments) && (lon < sides)) {
const seg1 = sides + 1;
const a = seg1 * lat + lon + indexArray[torSegments][sides] + 1;
const b = seg1 * (lat + 1) + lon + indexArray[torSegments][sides] + 1;
const c = seg1 * (lat + 1) + lon + 1 + indexArray[torSegments][sides] + 1;
const d = seg1 * lat + lon + 1 + indexArray[torSegments][sides] + 1;
indices.push(a, d, b);
indices.push(d, c, b);
}
}
}
}
}
-16
View File
@@ -1,16 +0,0 @@
'use strict';
import cylinder from './cylinder';
/**
* @param {Number} radius
* @param {Number} height
* @param {Object} opts
* @param {Number} opts.radialSegments
* @param {Number} opts.heightSegments
* @param {Boolean} opts.capped
* @param {Number} opts.arc
*/
export default function (radius = 0.5, height = 1, opts = {}) {
return cylinder(0, radius, height, opts);
}
+9
View File
@@ -0,0 +1,9 @@
'use strict';
import cylinder, { ICylinderOptions } from './cylinder';
type IConeOptions = ICylinderOptions;
export default function (radius = 0.5, height = 1, opts: RecursivePartial<IConeOptions> = {}) {
return cylinder(0, radius, height, opts);
}
@@ -1,26 +1,22 @@
'use strict';
import { vec3 } from '../../core/vmath';
import { IGeometry, IGeometryOptions } from './define';
let temp1 = vec3.create(0, 0, 0);
let temp2 = vec3.create(0, 0, 0);
export interface ICylinderOptions extends IGeometryOptions {
radialSegments: number;
heightSegments: number;
capped: boolean;
arc: number;
}
/**
* @param {Number} radiusTop
* @param {Number} radiusBottom
* @param {Number} height
* @param {Object} opts
* @param {Number} opts.radialSegments
* @param {Number} opts.heightSegments
* @param {Boolean} opts.capped
* @param {Number} opts.arc
*/
export default function (radiusTop = 0.5, radiusBottom = 0.5, height = 2, opts = {}) {
let halfHeight = height * 0.5;
let radialSegments = opts.radialSegments || 32;
let heightSegments = opts.heightSegments || 1;
let capped = opts.capped !== undefined ? opts.capped : true;
let arc = opts.arc || 2.0 * Math.PI;
const temp1 = vec3.create(0, 0, 0);
const temp2 = vec3.create(0, 0, 0);
export default function (radiusTop = 0.5, radiusBottom = 0.5, height = 2, opts: RecursivePartial<ICylinderOptions> = {}): IGeometry {
const halfHeight = height * 0.5;
const radialSegments = opts.radialSegments || 32;
const heightSegments = opts.heightSegments || 1;
const capped = opts.capped !== undefined ? opts.capped : true;
const arc = opts.arc || 2.0 * Math.PI;
let cntCap = 0;
if (!capped) {
@@ -45,14 +41,14 @@ export default function (radiusTop = 0.5, radiusBottom = 0.5, height = 2, opts =
indexCount += radialSegments * cntCap * 3;
}
let indices = new Array(indexCount);
let positions = new Array(vertCount * 3);
let normals = new Array(vertCount * 3);
let uvs = new Array(vertCount * 2);
let maxRadius = Math.max(radiusTop, radiusBottom);
let minPos = vec3.create(-maxRadius, -halfHeight, -maxRadius);
let maxPos = vec3.create(maxRadius, halfHeight, maxRadius);
let boundingRadius = Math.sqrt(maxRadius * maxRadius + halfHeight * halfHeight);
const indices = new Array(indexCount);
const positions = new Array(vertCount * 3);
const normals = new Array(vertCount * 3);
const uvs = new Array(vertCount * 2);
const maxRadius = Math.max(radiusTop, radiusBottom);
const minPos = vec3.create(-maxRadius, -halfHeight, -maxRadius);
const maxPos = vec3.create(maxRadius, halfHeight, maxRadius);
const boundingRadius = Math.sqrt(maxRadius * maxRadius + halfHeight * halfHeight);
let index = 0;
let indexOffset = 0;
@@ -76,34 +72,34 @@ export default function (radiusTop = 0.5, radiusBottom = 0.5, height = 2, opts =
indices,
minPos,
maxPos,
boundingRadius
boundingRadius,
};
// =======================
// internal fucntions
// =======================
function generateTorso() {
let indexArray = [];
function generateTorso () {
const indexArray: number[][] = [];
// this will be used to calculate the normal
let r = radiusTop - radiusBottom;
let slope = r * r / height * Math.sign(r);
const r = radiusTop - radiusBottom;
const slope = r * r / height * Math.sign(r);
// generate positions, normals and uvs
for (let y = 0; y <= heightSegments; y++) {
let indexRow = [];
let v = y / heightSegments;
const indexRow: number[] = [];
const v = y / heightSegments;
// calculate the radius of the current row
let radius = v * r + radiusBottom;
const radius = v * r + radiusBottom;
for (let x = 0; x <= radialSegments; ++x) {
let u = x / radialSegments;
let theta = u * arc;
const u = x / radialSegments;
const theta = u * arc;
let sinTheta = Math.sin(theta);
let cosTheta = Math.cos(theta);
const sinTheta = Math.sin(theta);
const cosTheta = Math.cos(theta);
// vertex
positions[3 * index] = radius * sinTheta;
@@ -135,10 +131,10 @@ export default function (radiusTop = 0.5, radiusBottom = 0.5, height = 2, opts =
for (let y = 0; y < heightSegments; ++y) {
for (let x = 0; x < radialSegments; ++x) {
// we use the index array to access the correct indices
let i1 = indexArray[y][x];
let i2 = indexArray[y + 1][x];
let i3 = indexArray[y + 1][x + 1];
let i4 = indexArray[y][x + 1];
const i1 = indexArray[y][x];
const i2 = indexArray[y + 1][x];
const i3 = indexArray[y + 1][x + 1];
const i4 = indexArray[y][x + 1];
// face one
indices[indexOffset] = i1; ++indexOffset;
@@ -153,14 +149,12 @@ export default function (radiusTop = 0.5, radiusBottom = 0.5, height = 2, opts =
}
}
function generateCap(top) {
let centerIndexStart, centerIndexEnd;
let radius = top ? radiusTop : radiusBottom;
let sign = top ? 1 : - 1;
function generateCap (top) {
const radius = top ? radiusTop : radiusBottom;
const sign = top ? 1 : - 1;
// save the index of the first center vertex
centerIndexStart = index;
const centerIndexStart = index;
// first we generate the center vertex data of the cap.
// because the geometry needs one set of uvs per face,
@@ -186,16 +180,16 @@ export default function (radiusTop = 0.5, radiusBottom = 0.5, height = 2, opts =
}
// save the index of the last center vertex
centerIndexEnd = index;
const centerIndexEnd = index;
// now we generate the surrounding positions, normals and uvs
for (let x = 0; x <= radialSegments; ++x) {
let u = x / radialSegments;
let theta = u * arc;
const u = x / radialSegments;
const theta = u * arc;
let cosTheta = Math.cos(theta);
let sinTheta = Math.sin(theta);
const cosTheta = Math.cos(theta);
const sinTheta = Math.sin(theta);
// vertex
positions[3 * index] = radius * sinTheta;
@@ -218,8 +212,8 @@ export default function (radiusTop = 0.5, radiusBottom = 0.5, height = 2, opts =
// generate indices
for (let x = 0; x < radialSegments; ++x) {
let c = centerIndexStart + x;
let i = centerIndexEnd + x;
const c = centerIndexStart + x;
const i = centerIndexEnd + x;
if (top) {
// face top
-68
View File
@@ -1,68 +0,0 @@
'use strict';
import { vec3 } from '../../core/vmath';
import { GFXPrimitiveMode } from '../../gfx/define';
/**
* @param {Number} radius
* @param {Object} opts
* @param {Number} opts.segments
*/
export default function (radius = 0.5, opts = {}) {
let segments = opts.segments !== undefined ? opts.segments : 32;
// lat === latitude
// lon === longitude
let positions = [];
let normals = [];
let uvs = [];
let indices = [];
let minPos = vec3.create(-radius, -radius, -radius);
let maxPos = vec3.create(radius, radius, radius);
let boundingRadius = radius;
for (let lat = 0; lat <= segments; ++lat) {
let theta = lat * Math.PI / segments;
let sinTheta = Math.sin(theta);
let cosTheta = -Math.cos(theta);
for (let lon = 0; lon <= segments; ++lon) {
let phi = lon * 2 * Math.PI / segments - Math.PI / 2.0;
let sinPhi = Math.sin(phi);
let cosPhi = Math.cos(phi);
let x = sinPhi * sinTheta;
let y = cosTheta;
let z = cosPhi * sinTheta;
let u = lon / segments;
let v = lat / segments;
positions.push(x * radius, y * radius, z * radius);
normals.push(x, y, z);
uvs.push(u, v);
if ((lat < segments) && (lon < segments)) {
let seg1 = segments + 1;
let a = seg1 * lat + lon;
let b = seg1 * (lat + 1) + lon;
let c = seg1 * (lat + 1) + lon + 1;
let d = seg1 * lat + lon + 1;
indices.push(a, d, b);
indices.push(d, c, b);
}
}
}
return {
positions,
indices,
normals,
uvs,
minPos,
maxPos,
boundingRadius
};
}
+64
View File
@@ -0,0 +1,64 @@
import { vec3 } from '../../core/vmath';
import { IGeometry, IGeometryOptions } from './define';
interface ISphereOptions extends IGeometryOptions {
segments: number;
}
export default function (radius = 0.5, opts: RecursivePartial<ISphereOptions> = {}): IGeometry {
const segments = opts.segments !== undefined ? opts.segments : 32;
// lat === latitude
// lon === longitude
const positions: number[] = [];
const normals: number[] = [];
const uvs: number[] = [];
const indices: number[] = [];
const minPos = vec3.create(-radius, -radius, -radius);
const maxPos = vec3.create(radius, radius, radius);
const boundingRadius = radius;
for (let lat = 0; lat <= segments; ++lat) {
const theta = lat * Math.PI / segments;
const sinTheta = Math.sin(theta);
const cosTheta = -Math.cos(theta);
for (let lon = 0; lon <= segments; ++lon) {
const phi = lon * 2 * Math.PI / segments - Math.PI / 2.0;
const sinPhi = Math.sin(phi);
const cosPhi = Math.cos(phi);
const x = sinPhi * sinTheta;
const y = cosTheta;
const z = cosPhi * sinTheta;
const u = lon / segments;
const v = lat / segments;
positions.push(x * radius, y * radius, z * radius);
normals.push(x, y, z);
uvs.push(u, v);
if ((lat < segments) && (lon < segments)) {
const seg1 = segments + 1;
const a = seg1 * lat + lon;
const b = seg1 * (lat + 1) + lon;
const c = seg1 * (lat + 1) + lon + 1;
const d = seg1 * lat + lon + 1;
indices.push(a, d, b);
indices.push(d, c, b);
}
}
}
return {
positions,
indices,
normals,
uvs,
minPos,
maxPos,
boundingRadius,
};
}
-69
View File
@@ -1,69 +0,0 @@
'use strict';
import { vec3 } from '../../core/vmath';
/**
* @param {Number} radius
* @param {Number} tube
* @param {Object} opts
* @param {Number} opts.radialSegments
* @param {Number} opts.tubularSegments
* @param {Number} opts.arc
*/
export default function (radius = 0.4, tube = 0.1, opts = {}) {
let radialSegments = opts.radialSegments || 32;
let tubularSegments = opts.tubularSegments || 32;
let arc = opts.arc || 2.0 * Math.PI;
let positions = [];
let normals = [];
let uvs = [];
let indices = [];
let minPos = vec3.create(-radius - tube, -tube, -radius - tube);
let maxPos = vec3.create(radius + tube, tube, radius + tube);
let boundingRadius = radius + tube;
for (let j = 0; j <= radialSegments; j++) {
for (let i = 0; i <= tubularSegments; i++) {
let u = i / tubularSegments;
let v = j / radialSegments;
let u1 = u * arc;
let v1 = v * Math.PI * 2;
// vertex
let x = (radius + tube * Math.cos(v1)) * Math.sin(u1);
let y = tube * Math.sin(v1);
let z = (radius + tube * Math.cos(v1)) * Math.cos(u1);
// this vector is used to calculate the normal
let nx = Math.sin(u1) * Math.cos(v1);
let ny = Math.sin(v1);
let nz = Math.cos(u1) * Math.cos(v1);
positions.push(x, y, z);
normals.push(nx, ny, nz);
uvs.push(u, v);
if ((i < tubularSegments) && (j < radialSegments)) {
let seg1 = tubularSegments + 1;
let a = seg1 * j + i;
let b = seg1 * (j + 1) + i;
let c = seg1 * (j + 1) + i + 1;
let d = seg1 * j + i + 1;
indices.push(a, d, b);
indices.push(d, c, b);
}
}
}
return {
positions,
normals,
uvs,
indices,
minPos,
maxPos,
boundingRadius
};
}
+67
View File
@@ -0,0 +1,67 @@
import { vec3 } from '../../core/vmath';
import { IGeometryOptions } from './define';
interface ITorusOptions extends IGeometryOptions {
radialSegments: number;
tubularSegments: number;
arc: number;
}
export default function (radius = 0.4, tube = 0.1, opts: RecursivePartial<ITorusOptions> = {}) {
const radialSegments = opts.radialSegments || 32;
const tubularSegments = opts.tubularSegments || 32;
const arc = opts.arc || 2.0 * Math.PI;
const positions: number[] = [];
const normals: number[] = [];
const uvs: number[] = [];
const indices: number[] = [];
const minPos = vec3.create(-radius - tube, -tube, -radius - tube);
const maxPos = vec3.create(radius + tube, tube, radius + tube);
const boundingRadius = radius + tube;
for (let j = 0; j <= radialSegments; j++) {
for (let i = 0; i <= tubularSegments; i++) {
const u = i / tubularSegments;
const v = j / radialSegments;
const u1 = u * arc;
const v1 = v * Math.PI * 2;
// vertex
const x = (radius + tube * Math.cos(v1)) * Math.sin(u1);
const y = tube * Math.sin(v1);
const z = (radius + tube * Math.cos(v1)) * Math.cos(u1);
// this vector is used to calculate the normal
const nx = Math.sin(u1) * Math.cos(v1);
const ny = Math.sin(v1);
const nz = Math.cos(u1) * Math.cos(v1);
positions.push(x, y, z);
normals.push(nx, ny, nz);
uvs.push(u, v);
if ((i < tubularSegments) && (j < radialSegments)) {
const seg1 = tubularSegments + 1;
const a = seg1 * j + i;
const b = seg1 * (j + 1) + i;
const c = seg1 * (j + 1) + i + 1;
const d = seg1 * j + i + 1;
indices.push(a, d, b);
indices.push(d, c, b);
}
}
}
return {
positions,
normals,
uvs,
indices,
minPos,
maxPos,
boundingRadius,
};
}
-65
View File
@@ -1,65 +0,0 @@
export function wireframe(indices) {
const offsets = [[0, 1], [1, 2], [2, 0]];
let lines = [];
let lineIDs = {};
for (let i = 0; i < indices.length; i += 3) {
for (let k = 0; k < 3; ++k) {
let i1 = indices[i + offsets[k][0]];
let i2 = indices[i + offsets[k][1]];
// check if we already have the line in our lines
let id = (i1 > i2) ? ((i2 << 16) | i1) : ((i1 << 16) | i2);
if (lineIDs[id] === undefined) {
lineIDs[id] = 0;
lines.push(i1, i2);
}
}
}
return lines;
}
export function invWinding(indices) {
let newIB = [];
for (let i = 0; i < indices.length; i += 3)
newIB.push(indices[i], indices[i + 2], indices[i + 1]);
return newIB;
}
export function toWavefrontOBJ(primitive, scale = 1) {
let v = primitive.positions, t = primitive.uvs, n = primitive.normals, IB = primitive.indices;
let V = i => `${IB[i]+1}/${IB[i]+1}/${IB[i]+1}`;
let content = '';
for (let i = 0; i < v.length; i += 3)
content += `v ${v[i]*scale} ${v[i+1]*scale} ${v[i+2]*scale}\n`;
for (let i = 0; i < t.length; i += 2)
content += `vt ${t[i]} ${t[i+1]}\n`;
for (let i = 0; i < n.length; i += 3)
content += `vn ${n[i]} ${n[i+1]} ${n[i+2]}\n`;
for (let i = 0; i < IB.length; i += 3)
content += `f ${V(i)} ${V(i+1)} ${V(i+2)}\n`;
return content;
}
export function normals(positions, normals, length = 1) {
let verts = new Array(2 * positions.length);
for (let i = 0; i < positions.length/3; ++i) {
let i3 = 3*i;
let i6 = 6*i;
// line start
verts[i6 + 0] = positions[i3 + 0];
verts[i6 + 1] = positions[i3 + 1];
verts[i6 + 2] = positions[i3 + 2];
// line end
verts[i6 + 3] = positions[i3 + 0] + normals[i3 + 0] * length;
verts[i6 + 4] = positions[i3 + 1] + normals[i3 + 1] * length;
verts[i6 + 5] = positions[i3 + 2] + normals[i3 + 2] * length;
}
return verts;
}
+93
View File
@@ -0,0 +1,93 @@
import { GFXPrimitiveMode } from '../../gfx/define';
import { IGeometry } from './define';
/**
* @deprecated
*/
export function wireframe (indices: number[]) {
const offsets = [[0, 1], [1, 2], [2, 0]];
const lines: number[] = [];
const lineIDs = {};
for (let i = 0; i < indices.length; i += 3) {
for (let k = 0; k < 3; ++k) {
const i1 = indices[i + offsets[k][0]];
const i2 = indices[i + offsets[k][1]];
// check if we already have the line in our lines
const id = (i1 > i2) ? ((i2 << 16) | i1) : ((i1 << 16) | i2);
if (lineIDs[id] === undefined) {
lineIDs[id] = 0;
lines.push(i1, i2);
}
}
}
return lines;
}
/**
* @deprecated
*/
export function invWinding (indices: number[]) {
const newIB: number[] = [];
for (let i = 0; i < indices.length; i += 3) {
newIB.push(indices[i], indices[i + 2], indices[i + 1]);
}
return newIB;
}
/**
* @deprecated
*/
export function toWavefrontOBJ (primitive: IGeometry, scale = 1) {
if (!primitive.indices ||
!primitive.uvs ||
!primitive.normals ||
(primitive.primitiveMode !== undefined && primitive.primitiveMode !== GFXPrimitiveMode.TRIANGLE_LIST)) {
return '';
}
const v = primitive.positions;
const t = primitive.uvs;
const n = primitive.normals;
const IB = primitive.indices;
const V = (i) => `${IB[i] + 1}/${IB[i] + 1}/${IB[i] + 1}`;
let content = '';
for (let i = 0; i < v.length; i += 3) {
content += `v ${v[i] * scale} ${v[i + 1] * scale} ${v[i + 2] * scale}\n`;
}
for (let i = 0; i < t.length; i += 2) {
content += `vt ${t[i]} ${t[i + 1]}\n`;
}
for (let i = 0; i < n.length; i += 3) {
content += `vn ${n[i]} ${n[i + 1]} ${n[i + 2]}\n`;
}
for (let i = 0; i < IB.length; i += 3) {
content += `f ${V(i)} ${V(i + 1)} ${V(i + 2)}\n`;
}
return content;
}
/**
* @deprecated
*/
export function normals (positions: number[], normals: number[], length = 1) {
const verts = new Array(2 * positions.length);
for (let i = 0; i < positions.length / 3; ++i) {
const i3 = 3 * i;
const i6 = 6 * i;
// line start
verts[i6 + 0] = positions[i3 + 0];
verts[i6 + 1] = positions[i3 + 1];
verts[i6 + 2] = positions[i3 + 2];
// line end
verts[i6 + 3] = positions[i3 + 0] + normals[i3 + 0] * length;
verts[i6 + 4] = positions[i3 + 1] + normals[i3 + 1] * length;
verts[i6 + 5] = positions[i3 + 2] + normals[i3 + 2] * length;
}
return verts;
}
+3 -3
View File
@@ -23,7 +23,7 @@
THE SOFTWARE.
****************************************************************************/
import { LabelOutline } from '../../../../2d/label/label-outline';
import { LabelOutlineComponent } from '../../../../2d/label/label-outline';
import { SpriteFrame } from '../../../../assets/CCSpriteFrame';
import { Component } from '../../../../components/component';
import { fragmentText, safeMeasureText } from '../../../../core/utils/text-utils';
@@ -32,7 +32,7 @@ import { HorizontalTextAlignment, LabelComponent, VerticalTextAlignment } from '
const Overflow = LabelComponent.Overflow;
const WHITE = Color.WHITE;
const OUTLINE_SUPPORTED = cc.js.isChildClassOf(LabelOutline, Component);
const OUTLINE_SUPPORTED = cc.js.isChildClassOf(LabelOutlineComponent, Component);
let _context: CanvasRenderingContext2D | null = null;
let _canvas: HTMLCanvasElement | null = null;
@@ -207,7 +207,7 @@ export const ttfUtils = {
}
// outline
const outline = OUTLINE_SUPPORTED && comp.getComponent(LabelOutline);
const outline = OUTLINE_SUPPORTED && comp.getComponent(LabelOutlineComponent);
if (outline && outline.enabled) {
_isOutlined = true;
_margin = _outlineWidth = outline.width;
+3 -4
View File
@@ -40,7 +40,7 @@ import { UIRenderComponent } from '../components/ui-render-component';
*/
@ccclass('cc.GraphicsComponent')
@executionOrder(100)
@menu('UI/Graphics')
@menu('UI/Render/Graphics')
export class GraphicsComponent extends UIRenderComponent {
/**
@@ -197,7 +197,7 @@ export class GraphicsComponent extends UIRenderComponent {
constructor (){
super();
this._flushAssembler();
this.impl = this._assembler && (this._assembler as IAssembler).createImpl!(this);
}
public onRestore () {
@@ -475,12 +475,11 @@ export class GraphicsComponent extends UIRenderComponent {
this._updateMaterial(mat);
}
private _flushAssembler (){
protected _flushAssembler (){
const assembler = GraphicsComponent.Assembler!.getAssembler(this);
if (this._assembler !== assembler) {
this._assembler = assembler;
this.impl = (assembler as IAssembler).createImpl!(this);
}
}
+9 -9
View File
@@ -634,12 +634,12 @@ export class LabelComponent extends UIRenderComponent {
if (this._sharedMaterial) {
mat = Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false);
} else {
if (UIRenderComponent.addColorMat) {
if (UIRenderComponent.addTextureMat) {
mat = new Material();
mat.copy(UIRenderComponent.addColorMat);
mat.copy(UIRenderComponent.addTextureMat);
} else {
mat = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-material'), new RenderableComponent(), CC_EDITOR ? true : false);
mat.initialize({ defines: { USE_TEXTURE: false } });
mat.initialize({ defines: { USE_TEXTURE: true } });
UIRenderComponent.addColorMat = mat;
}
}
@@ -647,11 +647,7 @@ export class LabelComponent extends UIRenderComponent {
this._updateMaterial(mat);
}
private _checkStringEmpty () {
this._renderPermit = !!this.string;
}
private _flushAssembler () {
protected _flushAssembler () {
const assembler = LabelComponent.Assembler!.getAssembler(this);
if (this._assembler !== assembler) {
@@ -662,11 +658,15 @@ export class LabelComponent extends UIRenderComponent {
if (!this._renderData) {
if (this._assembler && this._assembler.createData){
this._renderData = this._assembler.createData(this);
this._renderData.material = this._material;
this._renderData!.material = this._material;
}
}
}
private _checkStringEmpty () {
this._renderPermit = !!this.string;
}
private _flushMaterial () {
const material = this._material;
// Setup blend function for premultiplied ttf label texture
+4 -9
View File
@@ -86,7 +86,7 @@ const SEGEMENTS_MAX = 10000;
*/
@ccclass('cc.MaskComponent')
@executionOrder(100)
@menu('UI/Mask')
@menu('UI/Render/Mask')
export class MaskComponent extends UIRenderComponent {
/**
* !#en The mask type.
@@ -247,11 +247,6 @@ export class MaskComponent extends UIRenderComponent {
private _graphics: GraphicsComponent | null = null;
private _clearGraphics: GraphicsComponent | null = null;
constructor (){
super();
this._flushAssembler();
}
public onLoad (){
this._createGraphics();
}
@@ -341,9 +336,9 @@ export class MaskComponent extends UIRenderComponent {
const py = testPt.y - 0.5 * h;
result = px * px / (rx * rx) + py * py / (ry * ry) < 1;
}
if (this.inverted) {
result = !result;
}
// if (this.inverted) {
// result = !result;
// }
return result;
}
+974
View File
@@ -0,0 +1,974 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
import { LabelOutlineComponent } from '../../../2d/label/label-outline';
import { SpriteAtlas, TTFFont } from '../../../assets';
import { Font } from '../../../assets/font';
import { Color, Vec2 } from '../../../core';
import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator';
import { EventTouch } from '../../../core/platform/event-manager';
import { HtmlTextParser, IHtmlTextParserResultObj, IHtmlTextParserStack } from '../../../core/utils/html-text-parser';
import Pool from '../../../core/utils/pool';
import { fragmentText, isUnicodeCJK, isUnicodeSpace } from '../../../core/utils/text-utils';
import { Node, PrivateNode } from '../../../scene-graph';
import { HorizontalTextAlignment, LabelComponent, VerticalTextAlignment } from './label-component';
import { SpriteComponent } from './sprite-component';
import { UIComponent } from './ui-component';
import { UIRenderComponent } from './ui-render-component';
import { UITransformComponent } from './ui-transfrom-component';
const _htmlTextParser = new HtmlTextParser();
const HorizontalAlign = HorizontalTextAlignment;
const VerticalAlign = VerticalTextAlignment;
const RichTextChildName = 'RICHTEXT_CHILD';
const RichTextChildImageName = 'RICHTEXT_Image_CHILD';
// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce (func: Function, wait: number, immediate?: boolean) {
let timeout;
return function (this: any) {
const context = this;
const later = () => {
timeout = null;
if (!immediate) { func.apply(context, arguments); }
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) { func.apply(context, arguments); }
};
}
/**
* RichText pool
*/
const pool = new Pool((node: Node) => {
if (CC_EDITOR) {
return false;
}
if (CC_DEV) {
cc.assert(!node.parent, 'Recycling node\'s parent should be null!');
}
if (!cc.isValid(node)) {
return false;
}
else if (node.getComponent(cc.LabelOutline)) {
return false;
}
return true;
}, 20);
pool.get = function (string: string, richtext: RichTextComponent) {
let labelNode = this._get();
if (!labelNode) {
labelNode = new PrivateNode(RichTextChildName);
}
let labelComponent: LabelComponent = labelNode.getComponent(LabelComponent);
if (!labelComponent) {
labelComponent = labelNode.addComponent(LabelComponent);
}
labelNode.setPosition(0, 0, 0);
// labelNode.setAnchorPoint(0.5, 0.5);
labelNode.setContentSize(128, 128);
// labelNode.skewX = 0;
if (typeof string !== 'string') {
string = '' + string;
}
const isAsset = richtext.font instanceof Font;
if (isAsset) {
labelComponent.font = richtext.font;
} else {
labelComponent.fontFamily = 'Arial';
}
labelComponent.string = string;
labelComponent.horizontalAlign = HorizontalAlign.LEFT;
labelComponent.verticalAlign = VerticalAlign.TOP;
labelComponent.fontSize = richtext.fontSize || 40;
labelComponent.overflow = 0;
labelComponent.enableWrapText = true;
labelComponent.lineHeight = 40;
labelComponent.isBold = false;
labelComponent.isItalic = false;
labelComponent.isUnderline = false;
const labelObj: ILabelSegment = {
node: labelNode,
comp: labelComponent,
lineCount: 0,
clickHandler: '',
styleIndex: 0,
};
return labelObj;
};
interface ILabelSegment{
node: PrivateNode;
comp: UIRenderComponent | null;
clickHandler: '';
styleIndex: number;
lineCount: number;
}
/**
* !#en The RichText Component.
* !#zh 富文本组件
* @class RichText
* @extends Component
*/
@ccclass('cc.RichTextComponent')
@executionOrder(100)
@menu('UI/RichText')
@executeInEditMode
export class RichTextComponent extends UIComponent {
/**
* !#en Content string of RichText.
* !#zh 富文本显示的文本内容。
* @property {String} string
*/
@property({
multiline: true,
})
get string () {
return this._string;
}
set string (value) {
if (this._string === value){
return;
}
this._string = value;
this._updateRichTextStatus();
}
/**
* !#en Horizontal Alignment of each line in RichText.
* !#zh 文本内容的水平对齐方式。
* @property {macro.TextAlignment} horizontalAlign
*/
@property({
type: HorizontalAlign,
})
get horizontalAlign () {
return this._horizontalAlign;
}
set horizontalAlign (value) {
if (this.horizontalAlign === value) {
return;
}
this._horizontalAlign = value;
this._layoutDirty = true;
this._updateRichTextStatus();
}
/**
* !#en Font size of RichText.
* !#zh 富文本字体大小。
* @property {Number} fontSize
*/
@property
get fontSize () {
return this._fontSize;
}
set fontSize (value) {
if (this._fontSize === value) {
return;
}
this._fontSize = value;
this._layoutDirty = true;
this._updateRichTextStatus();
}
/**
* !#en Custom TTF font of RichText
* !#zh 富文本定制字体
* @property {cc.TTFFont} font
*/
@property({
type: TTFFont,
})
get font () {
return this._font;
}
set font (value) {
if (this._font === value) {
return;
}
this._font = value;
this._layoutDirty = true;
if (this._font) {
this._onTTFLoaded();
}
this._updateRichTextStatus();
}
/**
* !#en The maximize width of the RichText
* !#zh 富文本的最大宽度
* @property {Number} maxWidth
*/
@property
get maxWidth () {
return this._maxWidth;
}
set maxWidth (value) {
if (this._maxWidth === value) {
return;
}
this._maxWidth = value;
this._layoutDirty = true;
this._updateRichTextStatus();
}
/**
* !#en Line Height of RichText.
* !#zh 富文本行高。
* @property {Number} lineHeight
*/
@property
get lineHeight () {
return this._lineHeight;
}
set lineHeight (value) {
if (this._lineHeight === value) {
return;
}
this._lineHeight = value;
this._layoutDirty = true;
this._updateRichTextStatus();
}
/**
* !#en The image atlas for the img tag. For each src value in the img tag, there should be a valid spriteFrame in the image atlas.
* !#zh 对于 img 标签里面的 src 属性名称,都需要在 imageAtlas 里面找到一个有效的 spriteFrame,否则 img tag 会判定为无效。
* @property {SpriteAtlas} imageAtlas
*/
@property({
type: SpriteAtlas,
})
get imageAtlas () {
return this._imageAtlas;
}
set imageAtlas (value) {
if (this._imageAtlas === value) {
return;
}
this._imageAtlas = value;
this._layoutDirty = true;
this._updateRichTextStatus();
}
/**
* !#en
* Once checked, the RichText will block all input events (mouse and touch) within
* the bounding box of the node, preventing the input from penetrating into the underlying node.
* !#zh
* 选中此选项后,RichText 将阻止节点边界框中的所有输入事件(鼠标和触摸),从而防止输入事件穿透到底层节点。
* @property {Boolean} handleTouchEvent
* @default true
*/
@property
get handleTouchEvent (){
return this._handleTouchEvent;
}
set handleTouchEvent (value) {
if (this._handleTouchEvent === value) {
return;
}
this._handleTouchEvent = value;
if (this.enabledInHierarchy) {
this.handleTouchEvent ? this._addEventListeners() : this._removeEventListeners();
}
}
public static HorizontalAlign = HorizontalAlign;
public static VerticalAlign = VerticalAlign;
@property
private _lineHeight = 40;
@property
private _string = '<color=#00ff00>Rich</c><color=#0fffff>Text</color>';
// private _updateRichTextStatus =
@property
private _horizontalAlign = HorizontalAlign.LEFT;
@property
private _fontSize = 40;
@property
private _maxWidth = 0;
@property
private _font: TTFFont | null = null;
@property
private _imageAtlas: SpriteAtlas | null = null;
@property
private _handleTouchEvent = true;
private _textArray: IHtmlTextParserResultObj[] = [];
private _labelSegments: ILabelSegment[] = [];
private _labelSegmentsCache: ILabelSegment[] = [];
private _linesWidth: number[] = [];
private _lineCount = 1;
private _labelWidth = 0;
private _labelHeight = 0;
private _layoutDirty = true;
private _lineOffsetX = 0;
private _updateRichTextStatus: () => void;
constructor () {
super();
if (CC_EDITOR) {
this._updateRichTextStatus = debounce(this._updateRichText, 200);
}
else {
this._updateRichTextStatus = this._updateRichText;
}
}
public onEnable () {
if (this.handleTouchEvent) {
this._addEventListeners();
}
this._updateRichText();
this._activateChildren(true);
}
public onDisable () {
if (this.handleTouchEvent) {
this._removeEventListeners();
}
this._activateChildren(false);
}
public start () {
this._onTTFLoaded();
}
public onRestore () {
if (!CC_EDITOR){
return;
}
// TODO: refine undo/redo system
// Because undo/redo will not call onEnable/onDisable,
// we need call onEnable/onDisable manually to active/disactive children nodes.
if (this.enabledInHierarchy) {
this.onEnable();
}
else {
this.onDisable();
}
}
public onDestroy () {
for (const seg of this._labelSegments) {
seg.node.removeFromParent();
pool.put(seg);
}
}
private _addEventListeners () {
this.node.on(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
}
private _removeEventListeners () {
this.node.off(cc.Node.EventType.TOUCH_END, this._onTouchEnded, this);
}
private _updateLabelSegmentTextAttributes () {
this._labelSegments.forEach((item) => {
this._applyTextAttribute(item);
});
}
private _createFontLabel (string: string) {
return pool.get(string, this);
}
private _onTTFLoaded () {
if (this._font instanceof TTFFont) {
if (this._font._nativeAsset) {
this._layoutDirty = true;
this._updateRichText();
}
else {
const self = this;
cc.loader.load(this._font.nativeUrl, (err, fontFamily) => {
self._layoutDirty = true;
self._updateRichText();
});
}
}
else {
this._layoutDirty = true;
this._updateRichText();
}
}
private _measureText (styleIndex: number, string?: string) {
const self = this;
const func = (s: string) => {
let label: ILabelSegment;
if (self._labelSegmentsCache.length === 0) {
label = self._createFontLabel(s);
self._labelSegmentsCache.push(label);
}
else {
label = self._labelSegmentsCache[0];
label.node.getComponent(LabelComponent)!.string = s;
}
label.styleIndex = styleIndex;
self._applyTextAttribute(label);
const labelSize = label.node.getContentSize();
return labelSize.width;
};
if (string) {
return func(string);
}
else {
return func;
}
}
private _onTouchEnded (event: EventTouch) {
const components = this.node.getComponents(UIComponent);
const self = this;
for (const seg of this._labelSegments) {
const clickHandler = seg.clickHandler;
if (clickHandler && this._containsTouchLocation(seg, event.touch!.getUILocation())) {
components.forEach((component) => {
const func = component[clickHandler] as Function;
if (component.enabledInHierarchy && func) {
func.call(self, event);
}
});
event.propagationStopped = true;
}
}
}
private _containsTouchLocation (label: ILabelSegment, point: Vec2) {
const comp = label.node.getComponent(UITransformComponent);
if (!comp){
return false;
}
const myRect = comp.getBoundingBoxToWorld();
return myRect.contains(point);
}
private _resetState () {
const children = this.node.children;
for (let i = children.length - 1; i >= 0; i--) {
const child = children[i];
if (child.name === RichTextChildName || child.name === RichTextChildImageName) {
if (child.parent === this.node) {
child.parent = null;
}
else {
// In case child.parent !== this.node, child cannot be removed from children
children.splice(i, 1);
}
if (child.name === RichTextChildName) {
pool.put(child);
}
}
}
this._labelSegments.length = 0;
this._labelSegmentsCache.length = 0;
this._linesWidth.length = 0;
this._lineOffsetX = 0;
this._lineCount = 1;
this._labelWidth = 0;
this._labelHeight = 0;
this._layoutDirty = true;
}
private _activateChildren (active) {
for (let i = this.node.children.length - 1; i >= 0; i--) {
const child = this.node.children[i];
if (child.name === RichTextChildName || child.name === RichTextChildImageName) {
child.active = active;
}
}
}
private _addLabelSegment (stringToken: string, styleIndex: number) {
let labelSegment: ILabelSegment;
if (this._labelSegmentsCache.length === 0) {
labelSegment = this._createFontLabel(stringToken);
} else {
labelSegment = this._labelSegmentsCache.pop()!;
const label = labelSegment.node.getComponent(LabelComponent);
if (label) {
label.string = stringToken;
}
}
labelSegment.styleIndex = styleIndex;
labelSegment.lineCount = this._lineCount;
labelSegment.node.setAnchorPoint(0, 0);
this._applyTextAttribute(labelSegment);
this.node.addChild(labelSegment.node);
this._labelSegments.push(labelSegment);
return labelSegment;
}
private _updateRichTextWithMaxWidth (labelString: string, labelWidth: number, styleIndex: number) {
let fragmentWidth = labelWidth;
let labelSegment: ILabelSegment;
if (this._lineOffsetX > 0 && fragmentWidth + this._lineOffsetX > this.maxWidth) {
// concat previous line
let checkStartIndex = 0;
while (this._lineOffsetX <= this.maxWidth) {
const checkEndIndex = this._getFirstWordLen(labelString,
checkStartIndex,
labelString.length);
const checkString = labelString.substr(checkStartIndex, checkEndIndex);
const checkStringWidth = this._measureText(styleIndex, checkString) as number;
if (this._lineOffsetX + checkStringWidth <= this.maxWidth) {
this._lineOffsetX += checkStringWidth;
checkStartIndex += checkEndIndex;
}
else {
if (checkStartIndex > 0) {
const remainingString = labelString.substr(0, checkStartIndex);
this._addLabelSegment(remainingString, styleIndex);
labelString = labelString.substr(checkStartIndex, labelString.length);
fragmentWidth = this._measureText(styleIndex, labelString) as number;
}
this._updateLineInfo();
break;
}
}
}
if (fragmentWidth > this.maxWidth) {
const fragments = fragmentText(labelString,
fragmentWidth,
this.maxWidth,
this._measureText(styleIndex) as (s: string) => number);
for (let k = 0; k < fragments.length; ++k) {
const splitString = fragments[k];
labelSegment = this._addLabelSegment(splitString, styleIndex);
const labelSize = labelSegment.node.getContentSize();
this._lineOffsetX += labelSize.width;
if (fragments.length > 1 && k < fragments.length - 1) {
this._updateLineInfo();
}
}
}
else {
this._lineOffsetX += fragmentWidth;
this._addLabelSegment(labelString, styleIndex);
}
}
private _isLastComponentCR (stringToken) {
return stringToken.length - 1 === stringToken.lastIndexOf('\n');
}
private _updateLineInfo () {
this._linesWidth.push(this._lineOffsetX);
this._lineOffsetX = 0;
this._lineCount++;
}
private _needsUpdateTextLayout (newTextArray: IHtmlTextParserResultObj[]) {
if (this._layoutDirty || !this._textArray || !newTextArray) {
return true;
}
if (this._textArray.length !== newTextArray.length) {
return true;
}
for (let i = 0; i < this._textArray.length; i++) {
const oldItem = this._textArray[i];
const newItem = newTextArray[i];
if (oldItem.text !== newItem.text) {
return true;
}
else {
if (oldItem.style) {
if (newItem.style) {
if (!!newItem.style.outline !== !!oldItem.style.outline) {
return true;
}
if (oldItem.style.size !== newItem.style.size
|| oldItem.style.italic !== newItem.style.italic
|| oldItem.style.isImage !== newItem.style.isImage) {
return true;
}
if (oldItem.style.isImage === newItem.style.isImage) {
if (oldItem.style.src !== newItem.style.src) {
return true;
}
}
}
else {
if (oldItem.style.size || oldItem.style.italic || oldItem.style.isImage || oldItem.style.outline) {
return true;
}
}
}
else {
if (newItem.style) {
if (newItem.style.size || newItem.style.italic || newItem.style.isImage || newItem.style.outline) {
return true;
}
}
}
}
}
return false;
}
private _addRichTextImageElement (richTextElement: IHtmlTextParserResultObj) {
if (!richTextElement.style){
return;
}
const spriteFrameName = richTextElement.style.src;
const spriteFrame = this._imageAtlas && spriteFrameName && this._imageAtlas.getSpriteFrame(spriteFrameName);
if (spriteFrame) {
const spriteNode = new PrivateNode(RichTextChildImageName);
const spriteComponent = spriteNode.addComponent(SpriteComponent);
spriteNode.setAnchorPoint(0, 0);
spriteComponent!.type = cc.SpriteComponent.Type.SLICED;
spriteComponent!.sizeMode = cc.SpriteComponent.SizeMode.CUSTOM;
this.node.addChild(spriteNode);
const obj: ILabelSegment = {
node: spriteNode,
comp: spriteComponent,
lineCount: 0,
clickHandler: '',
styleIndex: 0,
};
this._labelSegments.push(obj);
const spriteRect = spriteFrame.getRect();
let scaleFactor = 1;
let spriteWidth = spriteRect.width;
let spriteHeight = spriteRect.height;
const expectWidth = richTextElement.style.imageWidth;
const expectHeight = richTextElement.style.imageHeight;
// follow the original rule, expectHeight must less then lineHeight
if (expectHeight !== undefined && expectHeight > 0 && expectHeight < this.lineHeight) {
scaleFactor = expectHeight / spriteHeight;
spriteWidth = spriteWidth * scaleFactor;
spriteHeight = spriteHeight * scaleFactor;
} else {
scaleFactor = this.lineHeight / spriteHeight;
spriteWidth = spriteWidth * scaleFactor;
spriteHeight = spriteHeight * scaleFactor;
}
if (expectWidth !== undefined && expectWidth > 0) {
spriteWidth = expectWidth;
}
if (this.maxWidth > 0) {
if (this._lineOffsetX + spriteWidth > this.maxWidth) {
this._updateLineInfo();
}
this._lineOffsetX += spriteWidth;
}
else {
this._lineOffsetX += spriteWidth;
if (this._lineOffsetX > this._labelWidth) {
this._labelWidth = this._lineOffsetX;
}
}
spriteComponent!.spriteFrame = spriteFrame;
spriteNode.setContentSize(spriteWidth, spriteHeight);
obj.lineCount = this._lineCount;
if (richTextElement.style.event) {
const c = 'click';
if (richTextElement.style.event[c]) {
obj.clickHandler = richTextElement.style.event[c];
}
}
}
else {
cc.warnID(4400);
}
}
private _updateRichText () {
if (!this.enabled) {
return;
}
const newTextArray = _htmlTextParser.parse(this._string);
if (!this._needsUpdateTextLayout(newTextArray)) {
this._textArray = newTextArray.slice();
this._updateLabelSegmentTextAttributes();
return;
}
this._textArray = newTextArray.slice();
this._resetState();
let lastEmptyLine = false;
let label: ILabelSegment;
let labelSize;
for (let i = 0; i < this._textArray.length; ++i) {
const richTextElement = this._textArray[i];
const text = richTextElement.text;
if (text === undefined){
continue;
}
// handle <br/> <img /> tag
if (text === '') {
if (richTextElement.style && richTextElement.style.isNewLine) {
this._updateLineInfo();
continue;
}
if (richTextElement.style && richTextElement.style.isImage && this.imageAtlas) {
this._addRichTextImageElement(richTextElement);
continue;
}
}
const multilineTexts = text.split('\n');
for (let j = 0; j < multilineTexts.length; ++j) {
const labelString = multilineTexts[j];
if (labelString === '') {
// for continues \n
if (this._isLastComponentCR(text)
&& j === multilineTexts.length - 1) {
continue;
}
this._updateLineInfo();
lastEmptyLine = true;
continue;
}
lastEmptyLine = false;
if (this.maxWidth > 0) {
const labelWidth = this._measureText(i, labelString) as number;
this._updateRichTextWithMaxWidth(labelString, labelWidth, i);
if (multilineTexts.length > 1 && j < multilineTexts.length - 1) {
this._updateLineInfo();
}
}
else {
label = this._addLabelSegment(labelString, i);
labelSize = label.node.getContentSize();
this._lineOffsetX += labelSize.width;
if (this._lineOffsetX > this._labelWidth) {
this._labelWidth = this._lineOffsetX;
}
if (multilineTexts.length > 1 && j < multilineTexts.length - 1) {
this._updateLineInfo();
}
}
}
}
if (!lastEmptyLine) {
this._linesWidth.push(this._lineOffsetX);
}
if (this.maxWidth > 0) {
this._labelWidth = this.maxWidth;
}
this._labelHeight = this._lineCount * this.lineHeight;
// trigger "size-changed" event
this.node.setContentSize(this._labelWidth, this._labelHeight);
this._updateRichTextPosition();
this._layoutDirty = false;
}
private _getFirstWordLen (text: string, startIndex: number, textLen: number) {
let character = text.charAt(startIndex);
if (isUnicodeCJK(character) || isUnicodeSpace(character)) {
return 1;
}
let len = 1;
for (let index = startIndex + 1; index < textLen; ++index) {
character = text.charAt(index);
if (isUnicodeSpace(character) || isUnicodeCJK(character)) {
break;
}
len++;
}
return len;
}
private _updateRichTextPosition () {
let nextTokenX = 0;
let nextLineIndex = 1;
const totalLineCount = this._lineCount;
for (const label of this._labelSegments) {
const lineCount = label.lineCount;
if (lineCount > nextLineIndex) {
nextTokenX = 0;
nextLineIndex = lineCount;
}
let lineOffsetX = 0;
// let nodeAnchorXOffset = (0.5 - this.node.anchorX) * this._labelWidth;
switch (this.horizontalAlign) {
case HorizontalAlign.LEFT:
lineOffsetX = - this._labelWidth / 2;
break;
case HorizontalAlign.CENTER:
lineOffsetX = - this._linesWidth[lineCount - 1] / 2;
break;
case HorizontalAlign.RIGHT:
lineOffsetX = this._labelWidth / 2 - this._linesWidth[lineCount - 1];
break;
default:
break;
}
const labelSize = label.node.getContentSize();
const pos = label.node.getPosition();
label.node.setPosition(nextTokenX + lineOffsetX,
this.lineHeight * (totalLineCount - lineCount) - this._labelHeight / 2,
pos.x,
);
if (lineCount === nextLineIndex) {
nextTokenX += labelSize.width;
}
}
}
private _convertLiteralColorValue (color: string) {
const colorValue = color.toUpperCase();
if (Color[colorValue]) {
return Color[colorValue];
}
else {
const out = new Color();
return out.fromHEX(color);
}
}
private _applyTextAttribute (labelSeg: ILabelSegment) {
const labelComponent = labelSeg.node.getComponent(LabelComponent);
if (!labelComponent) {
return;
}
const index = labelSeg.styleIndex;
labelComponent.lineHeight = this.lineHeight;
labelComponent.horizontalAlign = HorizontalAlign.LEFT;
labelComponent.verticalAlign = VerticalAlign.CENTER;
let textStyle: IHtmlTextParserStack | undefined;
if (this._textArray[index]) {
textStyle = this._textArray[index].style;
}
const labelComp = labelSeg.node.getComponent(LabelComponent);
if (labelComp) {
if (textStyle && textStyle.color) {
labelComp.color = this._convertLiteralColorValue(textStyle.color);
} else {
labelComp.color = this._convertLiteralColorValue('white');
}
}
labelComponent.isBold = !!(textStyle && textStyle.bold);
labelComponent.isItalic = !!(textStyle && textStyle.italic);
// TODO: temporary implementation, the italic effect should be implemented in the internal of label-assembler.
// if (textStyle && textStyle.italic) {
// labelNode.skewX = 12;
// }
labelComponent.isUnderline = !!(textStyle && textStyle.underline);
if (textStyle && textStyle.outline) {
let labelOutlineComponent = labelSeg.node.getComponent(LabelOutlineComponent);
if (!labelOutlineComponent) {
labelOutlineComponent = labelSeg.node.addComponent(LabelOutlineComponent);
}
labelOutlineComponent!.color = this._convertLiteralColorValue(textStyle.outline.color);
labelOutlineComponent!.width = textStyle.outline.width;
}
if (textStyle && textStyle.size) {
labelComponent.fontSize = textStyle.size;
}
else {
labelComponent.fontSize = this._fontSize;
}
labelComponent.updateRenderData(true);
if (textStyle && textStyle.event) {
const c = 'click';
if (textStyle.event[c]) {
labelSeg.clickHandler = textStyle.event[c];
}
}
}
}
cc.RichTextComponent = RichTextComponent;
+2 -2
View File
@@ -149,7 +149,7 @@ ccenum(SizeMode);
@ccclass('cc.SpriteComponent')
@executionOrder(100)
@menu('UI/Sprite')
@menu('UI/Render/Sprite')
export class SpriteComponent extends UIRenderComponent {
/**
@@ -536,7 +536,7 @@ export class SpriteComponent extends UIRenderComponent {
this._updateMaterial(mat);
}
private _flushAssembler () {
protected _flushAssembler () {
const assembler = SpriteComponent.Assembler!.getAssembler(this);
if (this._assembler !== assembler) {
+11 -1
View File
@@ -202,10 +202,19 @@ export class UIRenderComponent extends UIComponent {
rasterizerState: {},
};
public __preload (){
constructor (){
super();
if (this._instanceMaterial) {
this._instanceMaterial();
}
if (this._flushAssembler) {
this._flushAssembler();
}
}
public __preload (){
}
public onEnable () {
@@ -359,6 +368,7 @@ export class UIRenderComponent extends UIComponent {
}
protected _instanceMaterial? (): void;
protected _flushAssembler? (): void;
}
cc.UIRenderComponent = UIRenderComponent;
+1
View File
@@ -7,6 +7,7 @@ import './components/label-component';
import './components/layout-component';
import './components/mask-component';
import './components/progress-bar-component';
import './components/rich-text';
import './components/scroll-bar-component';
import './components/scroll-view-component';
import './components/slider-component';
+14 -15
View File
@@ -1,10 +1,9 @@
import { LegacyAnimationComponent } from '../components/legacy-animation-component';
import { AnimationComponent } from '../components/animation-component';
import { binarySearchEpsilon as binarySearch } from '../core/data/utils/binary-search';
import { MutableForwardIterator } from '../core/utils/array';
import { Node } from '../scene-graph';
import { LegacyAnimationClip } from './animation-clip';
import { EventAnimCurve, EventInfo } from './animation-curve';
import { LegacyAnimationState } from './animation-state';
import { AnimationState } from './animation-state';
import { Playable } from './playable';
import { WrapModeMask } from './types';
@@ -12,13 +11,13 @@ import { WrapModeMask } from './types';
* The actual animator for Animation Component.
*/
export class AnimationAnimator extends Playable {
public _anims = new MutableForwardIterator<LegacyAnimationState>([]);
public _anims = new MutableForwardIterator<AnimationState>([]);
constructor (public target: Node, public animation: LegacyAnimationComponent) {
constructor (public target: Node, public animation: AnimationComponent) {
super();
}
public playState (state: LegacyAnimationState, startTime?: number) {
public playState (state: AnimationState, startTime?: number) {
if (!state.clip) {
return;
}
@@ -37,7 +36,7 @@ export class AnimationAnimator extends Playable {
this.play();
}
public stopStatesExcept (state: LegacyAnimationState) {
public stopStatesExcept (state: AnimationState) {
const iterator = this._anims;
const array = iterator.array;
for (iterator.i = 0; iterator.i < array.length; ++iterator.i) {
@@ -84,19 +83,19 @@ export class AnimationAnimator extends Playable {
}
}
public stopState (state: LegacyAnimationState) {
public stopState (state: AnimationState) {
if (state) {
state.stop();
}
}
public pauseState (state: LegacyAnimationState) {
public pauseState (state: AnimationState) {
if (state) {
state.pause();
}
}
public resumeState (state: LegacyAnimationState) {
public resumeState (state: AnimationState) {
if (state) {
state.resume();
}
@@ -106,14 +105,14 @@ export class AnimationAnimator extends Playable {
}
}
public setStateTime (state: LegacyAnimationState, time: number): void;
public setStateTime (state: AnimationState, time: number): void;
public setStateTime (time: number): void;
public setStateTime (state: LegacyAnimationState | number, time?: number) {
public setStateTime (state: AnimationState | number, time?: number) {
if (time !== undefined) {
(state as LegacyAnimationState).setTime(time);
(state as LegacyAnimationState).sample();
(state as AnimationState).setTime(time);
(state as AnimationState).sample();
}
else {
for (const anim of this._anims.array) {
@@ -149,7 +148,7 @@ export class AnimationAnimator extends Playable {
}
}
public _reloadClip (state: LegacyAnimationState) {
public _reloadClip (state: AnimationState) {
initClipData(this.target, state);
}
}
+4 -4
View File
@@ -43,8 +43,8 @@ function isLerpable (object: any): object is ILerpable {
return object.lerp;
}
@ccclass('cc.LegacyAnimationClip')
export class LegacyAnimationClip extends Asset {
@ccclass('cc.AnimationClip')
export class AnimationClip extends Asset {
/**
* !#en Duration of this animation.
@@ -67,7 +67,7 @@ export class LegacyAnimationClip extends Asset {
return null;
}
const clip = new LegacyAnimationClip();
const clip = new AnimationClip();
clip.sample = sample || clip.sample;
clip._duration = spriteFrames.length / clip.sample;
@@ -289,4 +289,4 @@ function lerpObject (from: ILerpable, to: ILerpable, t: number): ILerpable {
return from.lerp(to, t);
}
cc.LegacyAnimationClip = LegacyAnimationClip;
cc.AnimationClip = AnimationClip;
+3 -3
View File
@@ -1,7 +1,7 @@
import { ccclass } from '../core/data/class-decorator';
import { errorID } from '../core/platform/CCDebug';
import { Node } from '../scene-graph';
import { LegacyAnimationState } from './animation-state';
import { AnimationState } from './animation-state';
@ccclass
export class AnimationManager {
@@ -36,14 +36,14 @@ export class AnimationManager {
}
public addAnimation (anim: LegacyAnimationState) {
public addAnimation (anim: AnimationState) {
const index = this._anims.array.indexOf(anim);
if (index === -1) {
this._anims.push(anim);
}
}
public removeAnimation (anim: LegacyAnimationState) {
public removeAnimation (anim: AnimationState) {
const index = this._anims.array.indexOf(anim);
if (index >= 0) {
this._anims.fastRemoveAt(index);
+5 -5
View File
@@ -1,6 +1,6 @@
import { Node } from '../scene-graph';
import { AnimationAnimator } from './animation-animator';
import { LegacyAnimationClip } from './animation-clip';
import { AnimationClip } from './animation-clip';
import { AnimCurve } from './animation-curve';
import { Playable } from './playable';
import { WrapMode, WrapModeMask, WrappedInfo } from './types';
@@ -14,7 +14,7 @@ import { WrapMode, WrapModeMask, WrappedInfo } from './types';
* 大多数情况下 动画组件 是足够和易于使用的。如果您需要更多的动画控制接口,请使用 AnimationState。
*
*/
export class LegacyAnimationState extends Playable {
export class AnimationState extends Playable {
/**
* !#en The clip that is being played by this animation state.
@@ -176,11 +176,11 @@ export class LegacyAnimationState extends Playable {
private _lastWrappedInfo: WrappedInfo | null = null;
private _process = this.process;
private _target: Node | null = null;
private _clip: LegacyAnimationClip;
private _clip: AnimationClip;
private _name: string;
private _lastIterations?: number;
constructor (clip: LegacyAnimationClip, name?: string) {
constructor (clip: AnimationClip, name?: string) {
super();
this._clip = clip;
this._name = name || (clip && clip.name);
@@ -460,4 +460,4 @@ export class LegacyAnimationState extends Playable {
}
}
cc.LegacyAnimationState = LegacyAnimationState;
cc.AnimationState = AnimationState;
+3 -1
View File
@@ -104,6 +104,8 @@ export class SpriteAtlas extends Asset {
for (const key of Object.keys(this.spriteFrames)) {
const spriteFrame = this.spriteFrames[key];
const id = spriteFrame ? spriteFrame._uuid : '';
const name = id.split('@')[1];
frames.push(name);
frames.push(id);
}
@@ -119,7 +121,7 @@ export class SpriteAtlas extends Asset {
const frames = data.spriteFrames;
this.spriteFrames = js.createMap();
for (let i = 0; i < frames.length; i += 2) {
handle.result.push(this.spriteFrames, i, frames[i]);
handle.result.push(this.spriteFrames, frames[i], frames[i + 1]);
}
}
}
@@ -1,5 +1,5 @@
import { AnimationAnimator, LegacyAnimationClip, LegacyAnimationState } from '../animation';
import { AnimationAnimator, AnimationClip, AnimationState } from '../animation';
import { ccclass, executeInEditMode, executionOrder, menu, property } from '../core/data/class-decorator';
import { EventTargetFactory, IEventTargetCallback } from '../core/event/event-target-factory';
import { warnID } from '../core/platform/CCDebug';
@@ -67,11 +67,11 @@ ccenum(EventType);
* - lastframe : 假如动画循环次数大于 1,当动画播放到最后一帧时
* - finished : 动画播放完成时
*/
@ccclass('cc.LegacyAnimationComponent')
@ccclass('cc.AnimationComponent')
@executionOrder(99)
@executeInEditMode
@menu('Components/AnimationComponent')
export class LegacyAnimationComponent extends EventTargetFactory(Component) {
export class AnimationComponent extends EventTargetFactory(Component) {
@property({ type: Boolean })
get preview () {
@@ -93,7 +93,7 @@ export class LegacyAnimationComponent extends EventTargetFactory(Component) {
* !#en Animation will play the default clip when start game.
* !#zh 在勾选自动播放或调用 play() 时默认播放的动画剪辑。
*/
@property({ type: LegacyAnimationClip })
@property({ type: AnimationClip })
get defaultClip () {
return this._defaultClip;
}
@@ -132,7 +132,7 @@ export class LegacyAnimationComponent extends EventTargetFactory(Component) {
this._currentClip = value;
}
@property({ type: [LegacyAnimationClip] })
@property({ type: [AnimationClip] })
get clips () {
return this._clips;
}
@@ -149,17 +149,17 @@ export class LegacyAnimationComponent extends EventTargetFactory(Component) {
private _animator: AnimationAnimator | null = null;
private _nameToState = createMap(true);
private _didInit = false;
private _currentClip: LegacyAnimationClip | null = null;
private _currentClip: AnimationClip | null = null;
/**
* !#en All the clips used in this animation.
* !#zh 通过脚本可以访问并播放的 AnimationClip 列表。
*/
@property({ type: [LegacyAnimationClip] })
private _clips: LegacyAnimationClip[] = [];
@property({ type: [AnimationClip] })
private _clips: AnimationClip[] = [];
@property
private _defaultClip: LegacyAnimationClip | null = null;
private _defaultClip: AnimationClip | null = null;
constructor () {
super();
@@ -378,7 +378,7 @@ export class LegacyAnimationComponent extends EventTargetFactory(Component) {
* @param clip the clip to add
* @return The AnimationState which gives full control over the animation clip.
*/
public addClip (clip: LegacyAnimationClip, newName?: string): LegacyAnimationState | undefined {
public addClip (clip: AnimationClip, newName?: string): AnimationState | undefined {
if (!clip) {
warnID(3900);
return;
@@ -406,7 +406,7 @@ export class LegacyAnimationComponent extends EventTargetFactory(Component) {
}
// replace state
const newState = new LegacyAnimationState(clip, newName);
const newState = new AnimationState(clip, newName);
this._nameToState[newName] = newState;
return newState;
}
@@ -422,7 +422,7 @@ export class LegacyAnimationComponent extends EventTargetFactory(Component) {
* 但是如果 force 参数为 true,则会强制停止该动画,然后移除该动画剪辑和相关的动画。这时候如果 clip 是 defaultClip,defaultClip 将会被重置为 null。
* @param {Boolean} [force=false] - If force is true, then will always remove the clip and any animation states based on it.
*/
public removeClip (clip: LegacyAnimationClip, force?: boolean) {
public removeClip (clip: AnimationClip, force?: boolean) {
if (!clip) {
warnID(3901);
return;
@@ -512,7 +512,7 @@ export class LegacyAnimationComponent extends EventTargetFactory(Component) {
* // register event to all animation
* animation.on('play', this.onPlay, this);
*/
public on (type: string, callback: (state: LegacyAnimationState) => void, target?: Object | null, useCapture?: boolean) {
public on (type: string, callback: (state: AnimationState) => void, target?: Object | null, useCapture?: boolean) {
this._init();
const ret = super.on(type, callback, target, useCapture);
@@ -578,11 +578,11 @@ export class LegacyAnimationComponent extends EventTargetFactory(Component) {
this._nameToState = createMap(true);
// create animation states
let state: LegacyAnimationState | null = null;
let defaultClipState: LegacyAnimationState | undefined;
let state: AnimationState | null = null;
let defaultClipState: AnimationState | undefined;
for (const clip of this._clips) {
if (clip) {
state = new LegacyAnimationState(clip);
state = new AnimationState(clip);
if (CC_EDITOR) {
this._animator!._reloadClip(state);
@@ -595,7 +595,7 @@ export class LegacyAnimationComponent extends EventTargetFactory(Component) {
}
}
if (this._defaultClip && !defaultClipState) {
state = new LegacyAnimationState(this._defaultClip);
state = new AnimationState(this._defaultClip);
if (CC_EDITOR) {
this._animator!._reloadClip(state);
@@ -606,9 +606,9 @@ export class LegacyAnimationComponent extends EventTargetFactory(Component) {
}
}
cc.LegacyAnimationComponent = LegacyAnimationComponent;
cc.AnimationComponent = AnimationComponent;
function equalClips (clip1: LegacyAnimationClip | null, clip2: LegacyAnimationClip | null) {
function equalClips (clip1: AnimationClip | null, clip2: AnimationClip | null) {
if (clip1 === clip2) {
return true;
}
-57
View File
@@ -1,57 +0,0 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
import { CCObject } from '../core/data/object';
import { getClassName, value } from '../core/utils/js';
import IDGenerator from '../core/utils/id-generator';
import { ccclass, property } from '../core/data/class-decorator';
import { Node } from '../scene-graph/node';
import { RenderScene } from '../renderer/scene/render-scene';
import { EventTarget } from '../core/event/event-target';
export class Component extends CCObject {
node: Node;
uuid: string;
enabled: boolean;
enabledInHierarchy: boolean;
public constructor();
protected _getRenderScene (): RenderScene;
public addComponent<T extends Component> (typeOrClassName: string | (new () => T)): T;
public getComponent<T extends Component> (typeOrClassName: string | (new () => T)): T;
public getComponents<T extends Component> (typeOrClassName: string | (new () => T)): T[];
public getComponentInChildren<T extends Component> (typeOrClassName: string | (new () => T)): T;
public getComponentsInChildren<T extends Component> (typeOrClassName: string | (new () => T)): T[];
public schedule (callback: Function, interval: number, repeat: number, delay: number): void;
public scheduleOnce (callback: Function, delay: number): void;
public unschedule (callback: Function): void;
public unscheduleAllCallbacks (): void;
// friend to class BaseNode
public _id: string;
public _enabled: boolean;
}
@@ -24,19 +24,24 @@
THE SOFTWARE.
****************************************************************************/
import { CCObject } from '../core/data/object';
import {getClassName, value} from '../core/utils/js';
import IDGenerator from '../core/utils/id-generator';
import {ccclass, property} from '../core/data/class-decorator';
import {Script} from '../assets';
// tslint:disable
let idGenerator = new IDGenerator('Comp');
import { Script } from '../assets';
import { ccclass, property } from '../core/data/class-decorator';
import { CCObject } from '../core/data/object';
import IDGenerator from '../core/utils/id-generator';
import { getClassName, value } from '../core/utils/js';
import { Node } from '../scene-graph';
import { RenderScene } from '../renderer/scene/render-scene';
import { Rect } from '../core';
const idGenerator = new IDGenerator('Comp');
// @ts-ignore
const IsOnEnableCalled = CCObject.Flags.IsOnEnableCalled;
// @ts-ignore
const IsOnLoadCalled = CCObject.Flags.IsOnLoadCalled;
/**
* @typedef {import('../scene-graph/index').Node} Node
*/
const NullNode = null as unknown as Node;
/**
* !#en
@@ -54,28 +59,16 @@ const IsOnLoadCalled = CCObject.Flags.IsOnLoadCalled;
*/
@ccclass('cc.Component')
class Component extends CCObject {
/**
* !#en The node this component is attached to. A component is always attached to a node.
* !#zh 该组件被附加到的节点。组件总会附加到一个节点。
* @property node
* @type {Node}
* @example
* cc.log(comp.node);
*/
@property({
visible: false
})
node = null;
@property({
visible: false
visible: false,
})
get name () {
if (this._name) {
return this._name;
}
var className = getClassName(this);
var trimLeft = className.lastIndexOf('.');
let className = getClassName(this);
const trimLeft = className.lastIndexOf('.');
if (trimLeft >= 0) {
className = className.slice(trimLeft + 1);
}
@@ -95,7 +88,7 @@ class Component extends CCObject {
* cc.log(comp.uuid);
*/
@property({
visible: false
visible: false,
})
get uuid () {
return this._id;
@@ -104,35 +97,9 @@ class Component extends CCObject {
@property({
displayName: 'Script',
type: Script,
tooltip: CC_DEV && 'i18n:INSPECTOR.component.script'
tooltip: CC_DEV && 'i18n:INSPECTOR.component.script',
})
get __scriptAsset () { return null; }
//set __scriptAsset (value) {
// if (this.__scriptUuid !== value) {
// if (value && Editor.Utils.UuidUtils.isUuid(value._uuid)) {
// var classId = Editor.Utils.UuidUtils.compressUuid(value._uuid);
// var NewComp = cc.js._getClassById(classId);
// if (cc.js.isChildClassOf(NewComp, cc.Component)) {
// cc.warn('Sorry, replacing component script is not yet implemented.');
// //Editor.Ipc.sendToWins('reload:window-scripts', Editor._Sandbox.compiled);
// }
// else {
// cc.error('Can not find a component in the script which uuid is "%s".', value._uuid);
// }
// }
// else {
// cc.error('Invalid Script');
// }
// }
//}
/**
* @property _enabled
* @type {Boolean}
* @private
*/
@property
_enabled = true;
/**
* !#en indicates whether this component is enabled or not.
@@ -145,7 +112,7 @@ class Component extends CCObject {
* cc.log(comp.enabled);
*/
@property({
visible: false
visible: false,
})
get enabled () {
return this._enabled;
@@ -153,8 +120,8 @@ class Component extends CCObject {
set enabled (value) {
if (this._enabled !== value) {
this._enabled = value;
if (this.node._activeInHierarchy) {
var compScheduler = cc.director._compScheduler;
if (this.node.activeInHierarchy) {
const compScheduler = cc.director._compScheduler;
if (value) {
compScheduler.enableComp(this);
}
@@ -175,10 +142,10 @@ class Component extends CCObject {
* cc.log(comp.enabledInHierarchy);
*/
@property({
visible: false
visible: false,
})
get enabledInHierarchy () {
return this._enabled && this.node._activeInHierarchy;
return this._enabled && this.node.activeInHierarchy;
}
/**
@@ -194,56 +161,104 @@ class Component extends CCObject {
return this._objFlags & IsOnLoadCalled;
}
static system = null;
public static system = null;
/**
* !#en The node this component is attached to. A component is always attached to a node.
* !#zh 该组件被附加到的节点。组件总会附加到一个节点。
* @property node
* @type {Node}
* @example
* cc.log(comp.node);
*/
@property({
visible: false,
})
public node: Node = NullNode;
// set __scriptAsset (value) {
// if (this.__scriptUuid !== value) {
// if (value && Editor.Utils.UuidUtils.isUuid(value._uuid)) {
// var classId = Editor.Utils.UuidUtils.compressUuid(value._uuid);
// var NewComp = cc.js._getClassById(classId);
// if (cc.js.isChildClassOf(NewComp, cc.Component)) {
// cc.warn('Sorry, replacing component script is not yet implemented.');
// //Editor.Ipc.sendToWins('reload:window-scripts', Editor._Sandbox.compiled);
// }
// else {
// cc.error('Can not find a component in the script which uuid is "%s".', value._uuid);
// }
// }
// else {
// cc.error('Invalid Script');
// }
// }
// }
_sceneGetter = null;
/**
* @property _enabled
* @type {Boolean}
* @private
*/
@property
public _enabled = true;
_getRenderScene() {
if (this._sceneGetter) {
return this._sceneGetter();
} else {
return this.node._scene._renderScene;
}
}
public _sceneGetter: null | (() => RenderScene) = null;
/**
* For internal usage.
*/
public _id: string;
/**
* Register all related EventTargets,
* all event callbacks will be removed in _onPreDestroy
*/
private _eventTargets: any[] = [];
private __scriptUuid = '';
constructor () {
super();
if (CC_EDITOR) {
// @ts-ignore
if (window._Scene && _Scene.AssetsWatcher) {
// @ts-ignore
_Scene.AssetsWatcher.initComponent(this);
}
// @ts-ignore
this._id = Editor.Utils.UuidUtils.uuid();
}
else {
this._id = idGenerator.getNewId();
}
}
/**
* Register all related EventTargets,
* all event callbacks will be removed in _onPreDestroy
* @property {Array} _eventTargets
* @private
*/
this._eventTargets = [];
public _getRenderScene () {
if (this._sceneGetter) {
return this._sceneGetter();
} else {
return this.node.scene._renderScene!;
}
}
// PUBLIC
/**
* !#en Adds a component class to the node. You can also add component to node by passing in the name of the script.
* !#zh 向节点添加一个组件类,你还可以通过传入脚本的名称来添加组件。
*
* @method addComponent
* @param {Function|String} typeOrClassName - the constructor or the class name of the component to add
* @return {Component} - the newly added component
* !#zh 向节点添加一个指定类型的组件类,你还可以通过传入脚本的名称来添加组件。
* @example
* var sprite = node.addComponent(cc.Sprite);
* var test = node.addComponent("Test");
* @typescript
* addComponent<T extends Component>(type: {new(): T}): T
* addComponent(className: string): any
*/
addComponent (typeOrClassName) {
public addComponent<T extends Component> (classConstructor: Constructor<T>): T | null;
/**
* !#en Adds a component class to the node. You can also add component to node by passing in the name of the script.
* !#zh 向节点添加一个指定类型的组件类,你还可以通过传入脚本的名称来添加组件。
* @example
* var test = node.addComponent("Test");
*/
public addComponent (className: string): Component | null;
public addComponent (typeOrClassName: any) {
return this.node.addComponent(typeOrClassName);
}
@@ -254,108 +269,122 @@ class Component extends CCObject {
* !#zh
* 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。<br/>
* 传入参数也可以是脚本的名称。
*
* @method getComponent
* @param {Function|String} typeOrClassName
* @return {Component | null}
* @example
* // get sprite component.
* var sprite = node.getComponent(cc.Sprite);
*/
public getComponent<T extends Component> (classConstructor: Constructor<T>): T | null;
/**
* !#en
* Returns the component of supplied type if the node has one attached, null if it doesn't.<br/>
* You can also get component in the node by passing in the name of the script.
* !#zh
* 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。<br/>
* 传入参数也可以是脚本的名称。
* @example
* // get custom test calss.
* var test = node.getComponent("Test");
* @typescript
* getComponent<T extends Component>(type: {prototype: T}): T
* getComponent(className: string): any
*/
getComponent (typeOrClassName) {
public getComponent (className: string): Component | null;
public getComponent (typeOrClassName: any) {
return this.node.getComponent(typeOrClassName);
}
/**
* !#en Returns all components of supplied Type in the node.
* !#en Returns all components of supplied type in the node.
* !#zh 返回节点上指定类型的所有组件。
*
* @method getComponents
* @param {Function|String} typeOrClassName
* @return {Component[]}
* @example
* var sprites = node.getComponents(cc.Sprite);
* var tests = node.getComponents("Test");
* @typescript
* getComponents<T extends Component>(type: {prototype: T}): T[]
* getComponents(className: string): any[]
*/
getComponents (typeOrClassName) {
public getComponents<T extends Component> (classConstructor: Constructor<T>): T[];
/**
* !#en Returns all components of supplied type in the node.
* !#zh 返回节点上指定类型的所有组件。
* @example
* var tests = node.getComponents("Test");
*/
public getComponents (className: string): Component[];
public getComponents<T extends Component> (typeOrClassName: any) {
return this.node.getComponents(typeOrClassName);
}
/**
* !#en Returns the component of supplied type in any of its children using depth first search.
* !#zh 递归查找所有子节点中第一个匹配指定类型的组件。
*
* @method getComponentInChildren
* @param {Function|String} typeOrClassName
* @returns {Component}
* @example
* var sprite = node.getComponentInChildren(cc.Sprite);
* var Test = node.getComponentInChildren("Test");
* @typescript
* getComponentInChildren<T extends Component>(type: {prototype: T}): T
* getComponentInChildren(className: string): any
*/
getComponentInChildren (typeOrClassName) {
public getComponentInChildren<T extends Component> (classConstructor: Constructor<T>): T | null;
/**
* !#en Returns the component of supplied type in any of its children using depth first search.
* !#zh 递归查找所有子节点中第一个匹配指定类型的组件。
* @example
* var Test = node.getComponentInChildren("Test");
*/
public getComponentInChildren (className: string): Component | null;
public getComponentInChildren (typeOrClassName: any) {
return this.node.getComponentInChildren(typeOrClassName);
}
/**
* !#en Returns the components of supplied type in self or any of its children using depth first search.
* !#en Returns all components of supplied type in self or any of its children.
* !#zh 递归查找自身或所有子节点中指定类型的组件
*
* @method getComponentsInChildren
* @param {Function|String} typeOrClassName
* @returns {Component[]}
* @example
* var sprites = node.getComponentsInChildren(cc.Sprite);
* var tests = node.getComponentsInChildren("Test");
* @typescript
* getComponentsInChildren<T extends Component>(type: {prototype: T}): T[]
* getComponentsInChildren(className: string): any[]
*/
getComponentsInChildren (typeOrClassName) {
public getComponentsInChildren<T extends Component> (classConstructor: Constructor<T>): T[];
/**
* !#en Returns all components of supplied type in self or any of its children.
* !#zh 递归查找自身或所有子节点中指定类型的组件
* @example
* var tests = node.getComponentsInChildren("Test");
*/
public getComponentsInChildren (className: string): Component[];
public getComponentsInChildren (typeOrClassName: any) {
return this.node.getComponentsInChildren(typeOrClassName);
}
// OVERRIDE
destroy () {
public destroy () {
if (CC_EDITOR) {
var depend = this.node._getDependComponent(this);
// @ts-ignore
const depend = this.node._getDependComponent(this);
if (depend) {
return cc.errorID(3626,
getClassName(this), getClassName(depend));
}
}
if (super.destroy()) {
if (this._enabled && this.node._activeInHierarchy) {
if (this._enabled && this.node.activeInHierarchy) {
cc.director._compScheduler.disableComp(this);
}
}
}
_onPreDestroy () {
public _onPreDestroy () {
// Schedules
this.unscheduleAllCallbacks();
// Remove all listeners
var eventTargets = this._eventTargets;
for (var i = 0, l = eventTargets.length; i < l; ++i) {
var target = eventTargets[i];
const eventTargets = this._eventTargets;
for (let i = 0, l = eventTargets.length; i < l; ++i) {
const target = eventTargets[i];
target && target.targetOff(this);
}
eventTargets.length = 0;
//
if (CC_EDITOR && !CC_TEST) {
// @ts-ignore
_Scene.AssetsWatcher.stop(this);
}
@@ -366,7 +395,7 @@ class Component extends CCObject {
this.node._removeComponent(this);
}
_instantiate (cloned) {
public _instantiate (cloned) {
if (!cloned) {
cloned = cc.instantiate._clone(this, this);
}
@@ -374,7 +403,7 @@ class Component extends CCObject {
return cloned;
}
// Scheduler
// Scheduler
/**
* !#en
@@ -394,7 +423,7 @@ class Component extends CCObject {
* }
* this.schedule(timeCallback, 1);
*/
schedule (callback, interval, repeat, delay) {
public schedule (callback, interval, repeat, delay) {
cc.assertID(callback, 1619);
cc.assertID(interval >= 0, 1620);
@@ -402,13 +431,13 @@ class Component extends CCObject {
repeat = isNaN(repeat) ? cc.macro.REPEAT_FOREVER : repeat;
delay = delay || 0;
var scheduler = cc.director.getScheduler();
const scheduler = cc.director.getScheduler();
// should not use enabledInHierarchy to judge whether paused,
// because enabledInHierarchy is assigned after onEnable.
// Actually, if not yet scheduled, resumeTarget/pauseTarget has no effect on component,
// therefore there is no way to guarantee the paused state other than isTargetPaused.
var paused = scheduler.isTargetPaused(this);
const paused = scheduler.isTargetPaused(this);
scheduler.schedule(callback, this, interval, repeat, delay, paused);
}
@@ -426,7 +455,7 @@ class Component extends CCObject {
* }
* this.scheduleOnce(timeCallback, 2);
*/
scheduleOnce (callback, delay) {
public scheduleOnce (callback, delay) {
this.schedule(callback, 0, 0, delay);
}
@@ -439,9 +468,10 @@ class Component extends CCObject {
* @example
* this.unschedule(_callback);
*/
unschedule (callback_fn) {
if (!callback_fn)
public unschedule (callback_fn) {
if (!callback_fn) {
return;
}
cc.director.getScheduler().unschedule(callback_fn, this);
}
@@ -455,192 +485,203 @@ class Component extends CCObject {
* @example
* this.unscheduleAllCallbacks();
*/
unscheduleAllCallbacks () {
public unscheduleAllCallbacks () {
cc.director.getScheduler().unscheduleAllForTarget(this);
}
// LIFECYCLE METHODS
// Fireball provides lifecycle methods that you can specify to hook into this process.
// We provide Pre methods, which are called right before something happens, and Post methods which are called right after something happens.
/**
* !#en Update is called every frame, if the Component is enabled.<br/>
* This is a lifecycle method. It may not be implemented in the super class.
* You can only call its super class method inside it. It should not be called manually elsewhere.
* !#zh 如果该组件启用,则每帧调用 update。<br/>
* 该方法为生命周期方法,父类未必会有实现。并且你只能在该方法内部调用父类的实现,不可在其它地方直接调用该方法。
* @param dt - the delta time in seconds it took to complete the last frame
*/
protected update? (dt: number): void;
/**
* !#en LateUpdate is called every frame, if the Component is enabled.<br/>
* This is a lifecycle method. It may not be implemented in the super class.
* You can only call its super class method inside it. It should not be called manually elsewhere.
* !#zh 如果该组件启用,则每帧调用 LateUpdate。<br/>
* 该方法为生命周期方法,父类未必会有实现。并且你只能在该方法内部调用父类的实现,不可在其它地方直接调用该方法。
*/
protected lateUpdate? (): void;
/**
* `__preload` is called before every onLoad.
* It is used to initialize the builtin components internally,
* to avoid checking whether onLoad is called before every public method calls.
* This method should be removed if script priority is supported.
* @private
*/
protected __preload? (): void;
/**
* !#en
* When attaching to an active node or its node first activated.
* onLoad is always called before any start functions, this allows you to order initialization of scripts.<br/>
* This is a lifecycle method. It may not be implemented in the super class.
* You can only call its super class method inside it. It should not be called manually elsewhere.
* !#zh
* 当附加到一个激活的节点上或者其节点第一次激活时候调用。onLoad 总是会在任何 start 方法调用前执行,这能用于安排脚本的初始化顺序。<br/>
* 该方法为生命周期方法,父类未必会有实现。并且你只能在该方法内部调用父类的实现,不可在其它地方直接调用该方法。
*/
protected onLoad? (): void;
/**
* !#en
* Called before all scripts' update if the Component is enabled the first time.
* Usually used to initialize some logic which need to be called after all components' `onload` methods called.<br/>
* This is a lifecycle method. It may not be implemented in the super class.
* You can only call its super class method inside it. It should not be called manually elsewhere.
* !#zh
* 如果该组件第一次启用,则在所有组件的 update 之前调用。通常用于需要在所有组件的 onLoad 初始化完毕后执行的逻辑。<br/>
* 该方法为生命周期方法,父类未必会有实现。并且你只能在该方法内部调用父类的实现,不可在其它地方直接调用该方法。
*/
protected start? (): void;
/**
* !#en Called when this component becomes enabled and its node is active.<br/>
* This is a lifecycle method. It may not be implemented in the super class.
* You can only call its super class method inside it. It should not be called manually elsewhere.
* !#zh 当该组件被启用,并且它的节点也激活时。<br/>
* 该方法为生命周期方法,父类未必会有实现。并且你只能在该方法内部调用父类的实现,不可在其它地方直接调用该方法。
*/
protected onEnable? (): void;
/**
* !#en Called when this component becomes disabled or its node becomes inactive.<br/>
* This is a lifecycle method. It may not be implemented in the super class.
* You can only call its super class method inside it. It should not be called manually elsewhere.
* !#zh 当该组件被禁用或节点变为无效时调用。<br/>
* 该方法为生命周期方法,父类未必会有实现。并且你只能在该方法内部调用父类的实现,不可在其它地方直接调用该方法。
*/
protected onDisable? (): void;
/**
* !#en Called when this component will be destroyed.<br/>
* This is a lifecycle method. It may not be implemented in the super class.
* You can only call its super class method inside it. It should not be called manually elsewhere.
* !#zh 当该组件被销毁时调用<br/>
* 该方法为生命周期方法,父类未必会有实现。并且你只能在该方法内部调用父类的实现,不可在其它地方直接调用该方法。
*/
protected onDestroy? (): void;
protected onFocusInEditor? (): void;
protected onLostFocusInEditor? (): void;
/**
* !#en Called to initialize the component or node’s properties when adding the component the first time or when the Reset command is used.
* This function is only called in editor.
* !#zh 用来初始化组件或节点的一些属性,当该组件被第一次添加到节点上或用户点击了它的 Reset 菜单时调用。这个回调只会在编辑器下调用。
*/
protected resetInEditor? (): void;
// VIRTUAL
/**
* !#en
* If the component's bounding box is different from the node's, you can implement this method to supply
* a custom axis aligned bounding box (AABB), so the editor's scene view can perform hit test properly.
* !#zh
* 如果组件的包围盒与节点不同,您可以实现该方法以提供自定义的轴向对齐的包围盒(AABB),
* 以便编辑器的场景视图可以正确地执行点选测试。
* @param out_rect - the Rect to receive the bounding box
*/
protected _getLocalBounds? (out_rect: Rect): void;
/**
* !#en
* onRestore is called after the user clicks the Reset item in the Inspector's context menu or performs
* an undo operation on this component.<br/>
* <br/>
* If the component contains the "internal state", short for "temporary member variables which not included<br/>
* in its CCClass properties", then you may need to implement this function.<br/>
* <br/>
* The editor will call the getset accessors of your component to record/restore the component's state<br/>
* for undo/redo operation. However, in extreme cases, it may not works well. Then you should implement<br/>
* this function to manually synchronize your component's "internal states" with its public properties.<br/>
* Once you implement this function, all the getset accessors of your component will not be called when<br/>
* the user performs an undo/redo operation. Which means that only the properties with default value<br/>
* will be recorded or restored by editor.<br/>
* <br/>
* Similarly, the editor may failed to reset your component correctly in extreme cases. Then if you need<br/>
* to support the reset menu, you should manually synchronize your component's "internal states" with its<br/>
* properties in this function. Once you implement this function, all the getset accessors of your component<br/>
* will not be called during reset operation. Which means that only the properties with default value<br/>
* will be reset by editor.
*
* This function is only called in editor mode.
* !#zh
* onRestore 是用户在检查器菜单点击 Reset 时,对此组件执行撤消操作后调用的。<br/>
* <br/>
* 如果组件包含了“内部状态”(不在 CCClass 属性中定义的临时成员变量),那么你可能需要实现该方法。<br/>
* <br/>
* 编辑器执行撤销/重做操作时,将调用组件的 get set 来录制和还原组件的状态。
* 然而,在极端的情况下,它可能无法良好运作。<br/>
* 那么你就应该实现这个方法,手动根据组件的属性同步“内部状态”。
* 一旦你实现这个方法,当用户撤销或重做时,组件的所有 get set 都不会再被调用。
* 这意味着仅仅指定了默认值的属性将被编辑器记录和还原。<br/>
* <br/>
* 同样的,编辑可能无法在极端情况下正确地重置您的组件。<br/>
* 于是如果你需要支持组件重置菜单,你需要在该方法中手工同步组件属性到“内部状态”。<br/>
* 一旦你实现这个方法,组件的所有 get set 都不会在重置操作时被调用。
* 这意味着仅仅指定了默认值的属性将被编辑器重置。
* <br/>
* 此方法仅在编辑器下会被调用。
*/
protected onRestore? (): void;
}
let proto = Component.prototype;
// LIFECYCLE METHODS
// Fireball provides lifecycle methods that you can specify to hook into this process.
// We provide Pre methods, which are called right before something happens, and Post methods which are called right after something happens.
/**
* !#en Update is called every frame, if the Component is enabled.<br/>
* This is a lifecycle method. It may not be implemented in the super class. You can only call its super class method inside it. It should not be called manually elsewhere.
* !#zh 如果该组件启用,则每帧调用 update。<br/>
* 该方法为生命周期方法,父类未必会有实现。并且你只能在该方法内部调用父类的实现,不可在其它地方直接调用该方法。
* @method update
* @param {Number} dt - the delta time in seconds it took to complete the last frame
* @protected
*/
const proto = Component.prototype;
// @ts-ignore
proto.update = null;
/**
* !#en LateUpdate is called every frame, if the Component is enabled.<br/>
* This is a lifecycle method. It may not be implemented in the super class. You can only call its super class method inside it. It should not be called manually elsewhere.
* !#zh 如果该组件启用,则每帧调用 LateUpdate。<br/>
* 该方法为生命周期方法,父类未必会有实现。并且你只能在该方法内部调用父类的实现,不可在其它地方直接调用该方法。
* @method lateUpdate
* @protected
*/
// @ts-ignore
proto.lateUpdate = null;
/**
* `__preload` is called before every onLoad.
* It is used to initialize the builtin components internally,
* to avoid checking whether onLoad is called before every public method calls.
* This method should be removed if script priority is supported.
*
* @method __preload
* @private
*/
// @ts-ignore
proto.__preload = null;
/**
* !#en
* When attaching to an active node or its node first activated.
* onLoad is always called before any start functions, this allows you to order initialization of scripts.<br/>
* This is a lifecycle method. It may not be implemented in the super class. You can only call its super class method inside it. It should not be called manually elsewhere.
* !#zh
* 当附加到一个激活的节点上或者其节点第一次激活时候调用。onLoad 总是会在任何 start 方法调用前执行,这能用于安排脚本的初始化顺序。<br/>
* 该方法为生命周期方法,父类未必会有实现。并且你只能在该方法内部调用父类的实现,不可在其它地方直接调用该方法。
* @method onLoad
* @protected
*/
// @ts-ignore
proto.onLoad = null;
/**
* !#en
* Called before all scripts' update if the Component is enabled the first time.
* Usually used to initialize some logic which need to be called after all components' `onload` methods called.<br/>
* This is a lifecycle method. It may not be implemented in the super class. You can only call its super class method inside it. It should not be called manually elsewhere.
* !#zh
* 如果该组件第一次启用,则在所有组件的 update 之前调用。通常用于需要在所有组件的 onLoad 初始化完毕后执行的逻辑。<br/>
* 该方法为生命周期方法,父类未必会有实现。并且你只能在该方法内部调用父类的实现,不可在其它地方直接调用该方法。
* @method start
* @protected
*/
// @ts-ignore
proto.start = null;
/**
* !#en Called when this component becomes enabled and its node is active.<br/>
* This is a lifecycle method. It may not be implemented in the super class. You can only call its super class method inside it. It should not be called manually elsewhere.
* !#zh 当该组件被启用,并且它的节点也激活时。<br/>
* 该方法为生命周期方法,父类未必会有实现。并且你只能在该方法内部调用父类的实现,不可在其它地方直接调用该方法。
* @method onEnable
* @protected
*/
// @ts-ignore
proto.onEnable = null;
/**
* !#en Called when this component becomes disabled or its node becomes inactive.<br/>
* This is a lifecycle method. It may not be implemented in the super class. You can only call its super class method inside it. It should not be called manually elsewhere.
* !#zh 当该组件被禁用或节点变为无效时调用。<br/>
* 该方法为生命周期方法,父类未必会有实现。并且你只能在该方法内部调用父类的实现,不可在其它地方直接调用该方法。
* @method onDisable
* @protected
*/
// @ts-ignore
proto.onDisable = null;
/**
* !#en Called when this component will be destroyed.<br/>
* This is a lifecycle method. It may not be implemented in the super class. You can only call its super class method inside it. It should not be called manually elsewhere.
* !#zh 当该组件被销毁时调用<br/>
* 该方法为生命周期方法,父类未必会有实现。并且你只能在该方法内部调用父类的实现,不可在其它地方直接调用该方法。
* @method onDestroy
* @protected
*/
// @ts-ignore
proto.onDestroy = null;
/**
* @method onFocusInEditor
* @protected
*/
// @ts-ignore
proto.onFocusInEditor = null;
/**
* @method onLostFocusInEditor
* @protected
*/
// @ts-ignore
proto.onLostFocusInEditor = null;
/**
* !#en Called to initialize the component or node’s properties when adding the component the first time or when the Reset command is used. This function is only called in editor.
* !#zh 用来初始化组件或节点的一些属性,当该组件被第一次添加到节点上或用户点击了它的 Reset 菜单时调用。这个回调只会在编辑器下调用。
* @method resetInEditor
* @protected
*/
// @ts-ignore
proto.resetInEditor = null;
// VIRTUAL
/**
* !#en
* If the component's bounding box is different from the node's, you can implement this method to supply
* a custom axis aligned bounding box (AABB), so the editor's scene view can perform hit test properly.
* !#zh
* 如果组件的包围盒与节点不同,您可以实现该方法以提供自定义的轴向对齐的包围盒(AABB),
* 以便编辑器的场景视图可以正确地执行点选测试。
*
* @method _getLocalBounds
* @param {Rect} out_rect - the Rect to receive the bounding box
*/
// @ts-ignore
proto._getLocalBounds = null;
/**
* !#en
* onRestore is called after the user clicks the Reset item in the Inspector's context menu or performs
* an undo operation on this component.<br/>
* <br/>
* If the component contains the "internal state", short for "temporary member variables which not included<br/>
* in its CCClass properties", then you may need to implement this function.<br/>
* <br/>
* The editor will call the getset accessors of your component to record/restore the component's state<br/>
* for undo/redo operation. However, in extreme cases, it may not works well. Then you should implement<br/>
* this function to manually synchronize your component's "internal states" with its public properties.<br/>
* Once you implement this function, all the getset accessors of your component will not be called when<br/>
* the user performs an undo/redo operation. Which means that only the properties with default value<br/>
* will be recorded or restored by editor.<br/>
* <br/>
* Similarly, the editor may failed to reset your component correctly in extreme cases. Then if you need<br/>
* to support the reset menu, you should manually synchronize your component's "internal states" with its<br/>
* properties in this function. Once you implement this function, all the getset accessors of your component<br/>
* will not be called during reset operation. Which means that only the properties with default value<br/>
* will be reset by editor.
*
* This function is only called in editor mode.
* !#zh
* onRestore 是用户在检查器菜单点击 Reset 时,对此组件执行撤消操作后调用的。<br/>
* <br/>
* 如果组件包含了“内部状态”(不在 CCClass 属性中定义的临时成员变量),那么你可能需要实现该方法。<br/>
* <br/>
* 编辑器执行撤销/重做操作时,将调用组件的 get set 来录制和还原组件的状态。
* 然而,在极端的情况下,它可能无法良好运作。<br/>
* 那么你就应该实现这个方法,手动根据组件的属性同步“内部状态”。
* 一旦你实现这个方法,当用户撤销或重做时,组件的所有 get set 都不会再被调用。
* 这意味着仅仅指定了默认值的属性将被编辑器记录和还原。<br/>
* <br/>
* 同样的,编辑可能无法在极端情况下正确地重置您的组件。<br/>
* 于是如果你需要支持组件重置菜单,你需要在该方法中手工同步组件属性到“内部状态”。<br/>
* 一旦你实现这个方法,组件的所有 get set 都不会在重置操作时被调用。
* 这意味着仅仅指定了默认值的属性将被编辑器重置。
* <br/>
* 此方法仅在编辑器下会被调用。
* @method onRestore
*/
// @ts-ignore
proto.onRestore = null;
// @ts-ignore
Component._requireComponent = null;
// @ts-ignore
Component._executionOrder = 0;
if (CC_EDITOR || CC_TEST) {
// INHERITABLE STATIC MEMBERS
// @ts-ignore
Component._executeInEditMode = false;
// @ts-ignore
Component._playOnFocus = false;
// @ts-ignore
Component._disallowMultiple = null;
// @ts-ignore
Component._help = '';
// NON-INHERITED STATIC MEMBERS
@@ -652,30 +693,30 @@ if (CC_EDITOR || CC_TEST) {
// COMPONENT HELPERS
cc._componentMenuItems = [];
// @ts-ignore
Component._addMenuItem = function (cls, path, priority) {
cc._componentMenuItems.push({
component: cls,
menuPath: path,
priority: priority
priority,
});
};
}
// we make this non-enumerable, to prevent inherited by sub classes.
value(Component, '_registerEditorProps', function (cls, props) {
var reqComp = props.requireComponent;
const reqComp = props.requireComponent;
if (reqComp) {
cls._requireComponent = reqComp;
}
var order = props.executionOrder;
const order = props.executionOrder;
if (order && typeof order === 'number') {
cls._executionOrder = order;
}
if (CC_EDITOR || CC_TEST) {
var name = getClassName(cls);
for (var key in props) {
var val = props[key];
const name = getClassName(cls);
for (const key in props) {
const val = props[key];
switch (key) {
case 'executeInEditMode':
cls._executeInEditMode = !!val;
@@ -683,7 +724,7 @@ value(Component, '_registerEditorProps', function (cls, props) {
case 'playOnFocus':
if (val) {
var willExecuteInEditMode = ('executeInEditMode' in props) ? props.executeInEditMode : cls._executeInEditMode;
const willExecuteInEditMode = ('executeInEditMode' in props) ? props.executeInEditMode : cls._executeInEditMode;
if (willExecuteInEditMode) {
cls._playOnFocus = true;
}
@@ -702,6 +743,7 @@ value(Component, '_registerEditorProps', function (cls, props) {
break;
case 'menu':
// @ts-ignore
Component._addMenuItem(cls, val, props.menuPriority);
break;
@@ -726,7 +768,5 @@ value(Component, '_registerEditorProps', function (cls, props) {
}
});
Component.prototype.__scriptUuid = '';
cc.Component = Component;
export { Component };
+1 -1
View File
@@ -27,4 +27,4 @@
export { Component } from './component';
export { EventHandler } from './component-event-handler';
export {default as MissingScript} from './missing-script';
export { LegacyAnimationComponent } from './legacy-animation-component';
export { AnimationComponent } from './animation-component';
@@ -338,7 +338,8 @@ class InputManager {
const length = event.changedTouches.length;
for (let i = 0; i < length; i++) {
const changedTouch = event.changedTouches.item(i);
// const changedTouch = event.changedTouches.item(i);
const changedTouch = event.changedTouches[i];
if (!changedTouch) {
continue;
}
@@ -24,16 +24,38 @@
THE SOFTWARE.
****************************************************************************/
const EVENT_REGX = /^(click)(\s)*=/;
const IMAGE_ATTR_REG = /(\s)*src(\s)*=|(\s)*height(\s)*=|(\s)*width(\s)*=|(\s)*click(\s)*=/;
const eventRegx = /^(click)(\s)*=|(param)(\s)*=/;
const imageAttrReg = /(\s)*src(\s)*=|(\s)*height(\s)*=|(\s)*width(\s)*=|(\s)*click(\s)*=|(\s)*param(\s)*=/;
/**
* A utils class for parsing HTML texts. The parsed results will be an object array.
*/
export default class HtmlTextParser {
constructor () {
this._parsedObject = {};
this._specialSymbolArray = [];
export interface IHtmlTextParserResultObj{
text?: string;
style?: IHtmlTextParserStack;
}
export interface IHtmlTextParserStack{
color?: string;
size?: number;
event?: Map<string, string>;
isNewLine?: boolean;
isImage?: boolean;
src?: string;
imageWidth?: number;
imageHeight?: number;
underline?: boolean;
italic?: boolean;
bold?: boolean;
outline?: { color: string, width: number };
}
export class HtmlTextParser {
private _specialSymbolArray: Array<[RegExp, string]> = [];
private _stack: IHtmlTextParserStack[] = [];
private _resultObjectArray: IHtmlTextParserResultObj[] = [];
constructor (){
this._specialSymbolArray.push([/&lt;/g, '<']);
this._specialSymbolArray.push([/&gt;/g, '>']);
this._specialSymbolArray.push([/&amp;/g, '&']);
@@ -41,14 +63,14 @@ export default class HtmlTextParser {
this._specialSymbolArray.push([/&apos;/g, '\'']);
}
parse (htmlString) {
this._resultObjectArray = [];
this._stack = [];
public parse (htmlString: string) {
this._resultObjectArray.length = 0;
this._stack.length = 0;
var startIndex = 0;
var length = htmlString.length;
let startIndex = 0;
const length = htmlString.length;
while (startIndex < length) {
var tagBeginIndex = htmlString.indexOf('<', startIndex);
const tagBeginIndex = htmlString.indexOf('<', startIndex);
if (tagBeginIndex < 0) {
this._stack.pop();
this._processResult(htmlString.substring(startIndex));
@@ -56,11 +78,11 @@ export default class HtmlTextParser {
} else {
this._processResult(htmlString.substring(startIndex, tagBeginIndex));
var tagEndIndex = htmlString.indexOf('>', startIndex);
let tagEndIndex = htmlString.indexOf('>', startIndex);
if (tagEndIndex === -1) {
// cc.error('The HTML tag is invalid!');
tagEndIndex = tagBeginIndex;
} else if (htmlString.charAt(tagBeginIndex + 1) === '\/'){
} else if (htmlString.charAt(tagBeginIndex + 1) === '\/') {
this._stack.pop();
} else {
this._addToStack(htmlString.substring(tagBeginIndex + 1, tagEndIndex));
@@ -69,102 +91,111 @@ export default class HtmlTextParser {
}
}
return this._resultObjectArray;
}
_attributeToObject (attribute) {
private _attributeToObject (attribute: string) {
attribute = attribute.trim();
var obj = {};
var header = attribute.match(/^(color|size)(\s)*=/);
var tagName;
var nextSpace;
var eventObj;
var eventHanlderString;
const obj: IHtmlTextParserStack = {};
let header = attribute.match(/^(color|size)(\s)*=/);
let tagName = '';
let nextSpace = 0;
let eventHanlderString = '';
if (header) {
tagName = header[0];
attribute = attribute.substring(tagName.length).trim();
if(attribute === "") return obj;
//parse color
nextSpace = attribute.indexOf(' ');
switch(tagName[0]){
case 'c':
if (nextSpace > -1) {
obj.color = attribute.substring(0, nextSpace).trim();
} else {
obj.color = attribute;
}
break;
case 's':
obj.size = parseInt(attribute);
break;
if (attribute === '') {
return obj;
}
//tag has event arguments
if(nextSpace > -1) {
eventHanlderString = attribute.substring(nextSpace+1).trim();
eventObj = this._processEventHandler(eventHanlderString);
obj.event = eventObj;
// parse color
nextSpace = attribute.indexOf(' ');
switch (tagName[0]) {
case 'c':
if (nextSpace > -1) {
obj.color = attribute.substring(0, nextSpace).trim();
} else {
obj.color = attribute;
}
break;
case 's':
obj.size = parseInt(attribute);
break;
}
// tag has event arguments
if (nextSpace > -1) {
eventHanlderString = attribute.substring(nextSpace + 1).trim();
obj.event = this._processEventHandler(eventHanlderString);
}
return obj;
}
header = attribute.match(/^(br(\s)*\/)/);
if(header && header[0].length > 0) {
if (header && header[0].length > 0) {
tagName = header[0].trim();
if(tagName.startsWith("br") && tagName[tagName.length-1] === "/") {
if (tagName.startsWith('br') && tagName[tagName.length - 1] === '/') {
obj.isNewLine = true;
this._resultObjectArray.push({text: "", style: {newline: true}});
this._resultObjectArray.push({ text: '', style: { newline: true } as IHtmlTextParserStack });
return obj;
}
}
header = attribute.match(/^(img(\s)*src(\s)*=[^>]+\/)/);
if(header && header[0].length > 0) {
let remainingArgument = '';
if (header && header[0].length > 0) {
tagName = header[0].trim();
if(tagName.startsWith("img") && tagName[tagName.length-1] === "/") {
header = attribute.match(IMAGE_ATTR_REG);
var tagValue;
var remainingArgument;
var isValidImageTag = false;
if (tagName.startsWith('img') && tagName[tagName.length - 1] === '/') {
header = attribute.match(imageAttrReg);
let tagValue;
let isValidImageTag = false;
while (header) {
//skip the invalid tags at first
// skip the invalid tags at first
attribute = attribute.substring(attribute.indexOf(header[0]));
tagName = attribute.substr(0, header[0].length);
//remove space and = character
// remove space and = character
remainingArgument = attribute.substring(tagName.length).trim();
nextSpace = remainingArgument.indexOf(' ');
tagValue = (nextSpace > -1) ? remainingArgument.substr(0, nextSpace) : remainingArgument;
tagName = tagName.replace(/[^a-zA-Z]/g, "").trim();
tagName = tagName.replace(/[^a-zA-Z]/g, '').trim();
tagName = tagName.toLocaleLowerCase();
attribute = remainingArgument.substring(nextSpace).trim();
if (tagName === "src") {
obj.isImage = true
if( tagValue.endsWith( '\/' ) ) tagValue = tagValue.substring( 0, tagValue.length - 1 );
if( tagValue.indexOf('\'')===0 ) {
isValidImageTag = true;
tagValue = tagValue.substring( 1, tagValue.length - 1 );
} else if( tagValue.indexOf('"')===0 ) {
isValidImageTag = true;
tagValue = tagValue.substring( 1, tagValue.length - 1 );
if (tagName === 'src') {
obj.isImage = true;
if (tagValue.endsWith('\/')) {
tagValue = tagValue.substring(0, tagValue.length - 1);
}
if (tagValue.indexOf('\'') === 0) {
isValidImageTag = true;
tagValue = tagValue.substring(1, tagValue.length - 1);
} else if (tagValue.indexOf('"') === 0) {
isValidImageTag = true;
tagValue = tagValue.substring(1, tagValue.length - 1);
}
obj.src = tagValue;
} else if (tagName === "height") {
} else if (tagName === 'height') {
obj.imageHeight = parseInt(tagValue);
} else if (tagName === "width") {
} else if (tagName === 'width') {
obj.imageWidth = parseInt(tagValue);
} else if (tagName === "click") {
obj.event = this._processEventHandler(tagName + "=" + tagValue);
} else if (tagName === 'click') {
obj.event = this._processEventHandler(tagName + '=' + tagValue);
}
header = attribute.match(IMAGE_ATTR_REG);
if (obj.event && tagName === 'param') {
obj.event[tagName] = tagValue.replace(/^\"|\"$/g, '');
}
header = attribute.match(imageAttrReg);
}
if( isValidImageTag && obj.isImage )
{
this._resultObjectArray.push({text: "", style: obj});
if (isValidImageTag && obj.isImage) {
this._resultObjectArray.push({ text: '', style: obj });
}
return {};
@@ -173,17 +204,17 @@ export default class HtmlTextParser {
header = attribute.match(/^(outline(\s)*[^>]*)/);
if (header) {
attribute = header[0].substring("outline".length).trim();
var defaultOutlineObject = {color: "#ffffff", width: 1};
attribute = header[0].substring('outline'.length).trim();
const defaultOutlineObject = { color: '#ffffff', width: 1 };
if (attribute) {
var outlineAttrReg = /(\s)*color(\s)*=|(\s)*width(\s)*=|(\s)*click(\s)*=/;
const outlineAttrReg = /(\s)*color(\s)*=|(\s)*width(\s)*=|(\s)*click(\s)*=|(\s)*param(\s)*=/;
header = attribute.match(outlineAttrReg);
var tagValue;
let tagValue;
while (header) {
//skip the invalid tags at first
// skip the invalid tags at first
attribute = attribute.substring(attribute.indexOf(header[0]));
tagName = attribute.substr(0, header[0].length);
//remove space and = character
// remove space and = character
remainingArgument = attribute.substring(tagName.length).trim();
nextSpace = remainingArgument.indexOf(' ');
if (nextSpace > -1) {
@@ -191,17 +222,22 @@ export default class HtmlTextParser {
} else {
tagValue = remainingArgument;
}
tagName = tagName.replace(/[^a-zA-Z]/g, "").trim();
tagName = tagName.replace(/[^a-zA-Z]/g, '').trim();
tagName = tagName.toLocaleLowerCase();
attribute = remainingArgument.substring(nextSpace).trim();
if (tagName === "click") {
obj.event = this._processEventHandler(tagName + "=" + tagValue);
} else if (tagName === "color") {
if (tagName === 'click') {
obj.event = this._processEventHandler(tagName + '=' + tagValue);
} else if (tagName === 'color') {
defaultOutlineObject.color = tagValue;
} else if (tagName === "width") {
} else if (tagName === 'width') {
defaultOutlineObject.width = parseInt(tagValue);
}
if (obj.event && tagName === 'param') {
obj.event[tagName] = tagValue.replace(/^\"|\"$/g, '');
}
header = attribute.match(outlineAttrReg);
}
}
@@ -209,88 +245,89 @@ export default class HtmlTextParser {
}
header = attribute.match(/^(on|u|b|i)(\s)*/);
if(header && header[0].length > 0) {
if (header && header[0].length > 0) {
tagName = header[0];
attribute = attribute.substring(tagName.length).trim();
switch(tagName[0]){
case 'u':
obj.underline = true;
break;
case 'i':
obj.italic = true;
break;
case 'b':
obj.bold = true;
break;
switch (tagName[0]) {
case 'u':
obj.underline = true;
break;
case 'i':
obj.italic = true;
break;
case 'b':
obj.bold = true;
break;
}
if(attribute === "") {
if (attribute === '') {
return obj;
}
eventObj = this._processEventHandler(attribute);
obj.event = eventObj;
obj.event = this._processEventHandler(attribute);
}
return obj;
}
_processEventHandler (eventString) {
var index = 0;
var obj = {};
var eventNames = eventString.match(EVENT_REGX);
var isValidTag = false;
while(eventNames) {
var eventName = eventNames[0];
var eventValue = "";
private _processEventHandler (eventString: string) {
let index = 0;
const obj = new Map<string, string>();
let eventNames = eventString.match(eventRegx);
let isValidTag = false;
while (eventNames) {
let eventName = eventNames[0];
let eventValue = '';
isValidTag = false;
eventString = eventString.substring(eventName.length).trim();
if(eventString.charAt(0) === "\"") {
index = eventString.indexOf("\"", 1);
if (eventString.charAt(0) === '\"') {
index = eventString.indexOf('\"', 1);
if (index > -1) {
eventValue = eventString.substring(1, index).trim();
isValidTag = true;
}
index++;
} else if(eventString.charAt(0) === "\'") {
} else if (eventString.charAt(0) === '\'') {
index = eventString.indexOf('\'', 1);
if(index > -1) {
if (index > -1) {
eventValue = eventString.substring(1, index).trim();
isValidTag = true;
}
index++;
} else {
//skip the invalid attribute value
var match = eventString.match(/(\S)+/);
if(match) {
// skip the invalid attribute value
const match = eventString.match(/(\S)+/);
if (match) {
eventValue = match[0];
} else {
eventValue = "";
eventValue = '';
}
index = eventValue.length;
}
if(isValidTag) {
eventName = eventName.substring(0, eventName.length-1).trim();
if (isValidTag) {
eventName = eventName.substring(0, eventName.length - 1).trim();
obj[eventName] = eventValue;
}
eventString = eventString.substring(index).trim();
eventNames = eventString.match(EVENT_REGX);
eventNames = eventString.match(eventRegx);
}
return obj;
}
_addToStack (attribute) {
var obj = this._attributeToObject(attribute);
private _addToStack (attribute: string) {
const obj = this._attributeToObject(attribute);
if (this._stack.length === 0){
if (this._stack.length === 0) {
this._stack.push(obj);
} else {
if(obj.isNewLine || obj.isImage) {
if (obj.isNewLine || obj.isImage) {
return;
}
//for nested tags
var previousTagObj = this._stack[this._stack.length - 1];
for (var key in previousTagObj) {
// for nested tags
const previousTagObj = this._stack[this._stack.length - 1];
for (const key in previousTagObj) {
if (!(obj[key])) {
obj[key] = previousTagObj[key];
}
@@ -299,30 +336,31 @@ export default class HtmlTextParser {
}
}
_processResult (value) {
if (value === "") {
private _processResult (value: string) {
if (value.length === 0) {
return;
}
value = this._escapeSpecialSymbol(value);
if (this._stack.length > 0) {
this._resultObjectArray.push({text: value, style: this._stack[this._stack.length - 1]});
this._resultObjectArray.push({ text: value, style: this._stack[this._stack.length - 1] });
} else {
this._resultObjectArray.push({text: value});
this._resultObjectArray.push({ text: value } as IHtmlTextParserResultObj);
}
}
_escapeSpecialSymbol (str) {
for(var i = 0; i < this._specialSymbolArray.length; ++i) {
var key = this._specialSymbolArray[i][0];
var value = this._specialSymbolArray[i][1];
private _escapeSpecialSymbol (str: string) {
for (const symbolArr of this._specialSymbolArray) {
const key = symbolArr[0];
const value = symbolArr[1];
str = str.replace(key, value);
}
return str;
}
};
}
if (CC_TEST) {
cc._Test.HtmlTextParser = HtmlTextParser;
}
}
+11
View File
@@ -16,6 +16,17 @@ export enum WebGLEXT {
COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 0x8C03,
COMPRESSED_RGB_ETC1_WEBGL = 0x8D64,
COMPRESSED_R11_EAC = 0x9270,
COMPRESSED_SIGNED_R11_EAC = 0x9271,
COMPRESSED_RG11_EAC = 0x9272,
COMPRESSED_SIGNED_RG11_EAC = 0x9273,
COMPRESSED_RGB8_ETC2 = 0x9274,
COMPRESSED_SRGB8_ETC2 = 0x9275,
COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9276,
COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2 = 0x9277,
COMPRESSED_RGBA8_ETC2_EAC = 0x9278,
COMPRESSED_SRGB8_ALPHA8_ETC2_EAC = 0x9279,
}
export const GFX_MAX_VERTEX_ATTRIBUTES: number = 16;
+4
View File
@@ -26,6 +26,10 @@ export enum GFXFeature {
TEXTURE_HALF_FLOAT,
FORMAT_R11G11B10F,
FORMAT_D24S8,
FORMAT_ETC1,
FORMAT_ETC2,
FORMAT_DXT,
FORMAT_PVRTC,
MSAA,
COUNT,
}
+25
View File
@@ -0,0 +1,25 @@
// note that ETC1 is not supported with the compressedTexSubImage2D() method
interface WEBGL_compressed_texture_etc1 {
readonly COMPRESSED_RGB_ETC1_WEBGL: GLenum;
}
interface WEBGL_compressed_texture_etc {
readonly COMPRESSED_R11_EAC: GLenum;
readonly COMPRESSED_SIGNED_R11_EAC: GLenum;
readonly COMPRESSED_RG11_EAC: GLenum;
readonly COMPRESSED_SIGNED_RG11_EAC: GLenum;
readonly COMPRESSED_RGB8_ETC2: GLenum;
readonly COMPRESSED_RGBA8_ETC2_EAC: GLenum;
readonly COMPRESSED_SRGB8_ETC2: GLenum;
readonly COMPRESSED_SRGB8_ALPHA8_ETC2_EAC: GLenum;
readonly COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2: GLenum;
readonly COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2: GLenum;
}
interface WEBGL_compressed_texture_pvrtc {
readonly COMPRESSED_RGB_PVRTC_4BPPV1_IMG: GLenum;
readonly COMPRESSED_RGBA_PVRTC_4BPPV1_IMG: GLenum;
readonly COMPRESSED_RGB_PVRTC_2BPPV1_IMG: GLenum;
readonly COMPRESSED_RGBA_PVRTC_2BPPV1_IMG: GLenum;
}
+10
View File
@@ -235,6 +235,16 @@ function GFXFormatToWebGLFormat (format: GFXFormat): GLenum {
case GFXFormat.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
case GFXFormat.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL;
case GFXFormat.ETC2_RGB8: return WebGLEXT.COMPRESSED_RGB8_ETC2;
case GFXFormat.ETC2_SRGB8: return WebGLEXT.COMPRESSED_SRGB8_ETC2;
case GFXFormat.ETC2_RGB8_A1: return WebGLEXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
case GFXFormat.ETC2_SRGB8_A1: return WebGLEXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;
case GFXFormat.ETC2_RGBA8: return WebGLEXT.COMPRESSED_RGBA8_ETC2_EAC;
case GFXFormat.ETC2_SRGB8_A8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
case GFXFormat.EAC_R11: return WebGLEXT.COMPRESSED_R11_EAC;
case GFXFormat.EAC_R11SN: return WebGLEXT.COMPRESSED_SIGNED_R11_EAC;
case GFXFormat.EAC_RG11: return WebGLEXT.COMPRESSED_RG11_EAC;
case GFXFormat.EAC_RG11SN: return WebGLEXT.COMPRESSED_SIGNED_RG11_EAC;
case GFXFormat.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
case GFXFormat.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
+37
View File
@@ -89,6 +89,14 @@ export class WebGLGFXDevice extends GFXDevice {
return this._WEBGL_color_buffer_float;
}
public get WEBGL_compressed_texture_etc1 (): WEBGL_compressed_texture_etc1 | null {
return this._WEBGL_compressed_texture_etc1;
}
public get WEBGL_compressed_texture_pvrtc (): WEBGL_compressed_texture_pvrtc | null {
return this._WEBGL_compressed_texture_pvrtc;
}
public get WEBGL_compressed_texture_astc (): WEBGL_compressed_texture_astc | null {
return this._WEBGL_compressed_texture_astc;
}
@@ -160,6 +168,9 @@ export class WebGLGFXDevice extends GFXDevice {
private _EXT_sRGB: EXT_sRGB | null = null;
private _OES_vertex_array_object: OES_vertex_array_object | null = null;
private _WEBGL_color_buffer_float: WEBGL_color_buffer_float | null = null;
private _WEBGL_compressed_texture_etc1: WEBGL_compressed_texture_etc1 | null = null;
private _WEBGL_compressed_texture_etc: WEBGL_compressed_texture_etc | null = null;
private _WEBGL_compressed_texture_pvrtc: WEBGL_compressed_texture_pvrtc | null = null;
private _WEBGL_compressed_texture_astc: WEBGL_compressed_texture_astc | null = null;
private _WEBGL_compressed_texture_s3tc: WEBGL_compressed_texture_s3tc | null = null;
private _WEBGL_compressed_texture_s3tc_srgb: WEBGL_compressed_texture_s3tc_srgb | null = null;
@@ -273,6 +284,9 @@ export class WebGLGFXDevice extends GFXDevice {
this._EXT_sRGB = gl.getExtension('EXT_sRGB');
this._OES_vertex_array_object = gl.getExtension('OES_vertex_array_object');
this._WEBGL_color_buffer_float = gl.getExtension('WEBGL_color_buffer_float');
this._WEBGL_compressed_texture_etc1 = gl.getExtension('WEBGL_compressed_texture_etc1');
this._WEBGL_compressed_texture_etc = gl.getExtension('WEBGL_compressed_texture_etc');
this._WEBGL_compressed_texture_pvrtc = gl.getExtension('WEBGL_compressed_texture_pvrtc');
this._WEBGL_compressed_texture_astc = gl.getExtension('WEBGL_compressed_texture_astc');
this._WEBGL_compressed_texture_s3tc = gl.getExtension('WEBGL_compressed_texture_s3tc');
this._WEBGL_compressed_texture_s3tc_srgb = gl.getExtension('WEBGL_compressed_texture_s3tc_srgb');
@@ -300,6 +314,28 @@ export class WebGLGFXDevice extends GFXDevice {
this._features[GFXFeature.FORMAT_D24S8] = true;
}
let compressedFormat: string = '';
if (this._WEBGL_compressed_texture_etc1) {
this._features[GFXFeature.FORMAT_ETC1] = true;
compressedFormat += 'etc1 ';
}
if (this._WEBGL_compressed_texture_etc) {
this._features[GFXFeature.FORMAT_ETC2] = true;
compressedFormat += 'etc2 ';
}
if (this._WEBGL_compressed_texture_s3tc) {
this._features[GFXFeature.FORMAT_DXT] = true;
compressedFormat += 'dxt ';
}
if (this._WEBGL_compressed_texture_pvrtc) {
this._features[GFXFeature.FORMAT_PVRTC] = true;
compressedFormat += 'pvrtc ';
}
this._features[GFXFeature.MSAA] = false;
if (this._OES_vertex_array_object) {
@@ -325,6 +361,7 @@ export class WebGLGFXDevice extends GFXDevice {
console.info('MAX_TEXTURE_MAX_ANISOTROPY_EXT: ' + this._EXT_texture_filter_anisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
}
console.info('USE_VAO: ' + this._useVAO);
console.info('COMPRESSED_FORMAT: ' + compressedFormat);
// init states
this.initStates(gl);
+10 -1
View File
@@ -249,7 +249,16 @@ function GFXFormatToWebGLInternalFormat (format: GFXFormat): GLenum {
case GFXFormat.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT;
case GFXFormat.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL;
case GFXFormat.ETC2_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL;
case GFXFormat.ETC2_RGB8: return WebGLEXT.COMPRESSED_RGB8_ETC2;
case GFXFormat.ETC2_SRGB8: return WebGLEXT.COMPRESSED_SRGB8_ETC2;
case GFXFormat.ETC2_RGB8_A1: return WebGLEXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2;
case GFXFormat.ETC2_SRGB8_A1: return WebGLEXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2;
case GFXFormat.ETC2_RGBA8: return WebGLEXT.COMPRESSED_RGBA8_ETC2_EAC;
case GFXFormat.ETC2_SRGB8_A8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC;
case GFXFormat.EAC_R11: return WebGLEXT.COMPRESSED_R11_EAC;
case GFXFormat.EAC_R11SN: return WebGLEXT.COMPRESSED_SIGNED_R11_EAC;
case GFXFormat.EAC_RG11: return WebGLEXT.COMPRESSED_RG11_EAC;
case GFXFormat.EAC_RG11SN: return WebGLEXT.COMPRESSED_SIGNED_RG11_EAC;
case GFXFormat.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;
case GFXFormat.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG;
+42
View File
@@ -77,6 +77,18 @@ export class WebGL2GFXDevice extends GFXDevice {
return this._EXT_disjoint_timer_query_webgl2;
}
public get WEBGL_compressed_texture_etc1 (): WEBGL_compressed_texture_etc1 | null {
return this._WEBGL_compressed_texture_etc1;
}
public get WEBGL_compressed_texture_etc (): WEBGL_compressed_texture_etc | null {
return this._WEBGL_compressed_texture_etc;
}
public get WEBGL_compressed_texture_pvrtc (): WEBGL_compressed_texture_pvrtc | null {
return this._WEBGL_compressed_texture_pvrtc;
}
public get WEBGL_compressed_texture_s3tc (): WEBGL_compressed_texture_s3tc | null {
return this._WEBGL_compressed_texture_s3tc;
}
@@ -99,6 +111,9 @@ export class WebGL2GFXDevice extends GFXDevice {
private _OES_texture_float_linear: OES_texture_float_linear | null = null;
private _EXT_color_buffer_float: EXT_color_buffer_float | null = null;
private _EXT_disjoint_timer_query_webgl2: EXT_disjoint_timer_query_webgl2 | null = null;
private _WEBGL_compressed_texture_etc1: WEBGL_compressed_texture_etc1 | null = null;
private _WEBGL_compressed_texture_etc: WEBGL_compressed_texture_etc | null = null;
private _WEBGL_compressed_texture_pvrtc: WEBGL_compressed_texture_pvrtc | null = null;
private _WEBGL_compressed_texture_s3tc: WEBGL_compressed_texture_s3tc | null = null;
private _WEBGL_compressed_texture_s3tc_srgb: WEBGL_compressed_texture_s3tc_srgb | null = null;
private _WEBGL_debug_renderer_info: WEBGL_debug_renderer_info | null = null;
@@ -214,6 +229,9 @@ export class WebGL2GFXDevice extends GFXDevice {
this._EXT_color_buffer_float = gl.getExtension('EXT_color_buffer_float');
this._EXT_disjoint_timer_query_webgl2 = gl.getExtension('EXT_disjoint_timer_query_webgl2');
this._OES_texture_float_linear = gl.getExtension('OES_texture_float_linear');
this._WEBGL_compressed_texture_etc1 = gl.getExtension('WEBGL_compressed_texture_etc1');
this._WEBGL_compressed_texture_etc = gl.getExtension('WEBGL_compressed_texture_etc');
this._WEBGL_compressed_texture_pvrtc = gl.getExtension('WEBGL_compressed_texture_pvrtc');
this._WEBGL_compressed_texture_s3tc = gl.getExtension('WEBGL_compressed_texture_s3tc');
this._WEBGL_compressed_texture_s3tc_srgb = gl.getExtension('WEBGL_compressed_texture_s3tc_srgb');
this._WEBGL_texture_storage_multisample = gl.getExtension('WEBGL_texture_storage_multisample');
@@ -225,8 +243,31 @@ export class WebGL2GFXDevice extends GFXDevice {
this._features[GFXFeature.TEXTURE_HALF_FLOAT] = true;
this._features[GFXFeature.FORMAT_R11G11B10F] = true;
this._features[GFXFeature.FORMAT_D24S8] = true;
this._features[GFXFeature.FORMAT_ETC2] = true;
this._features[GFXFeature.MSAA] = true;
let compressedFormat: string = '';
if (this._WEBGL_compressed_texture_etc1) {
this._features[GFXFeature.FORMAT_ETC1] = true;
compressedFormat += 'etc1 ';
}
if (this._WEBGL_compressed_texture_etc) {
this._features[GFXFeature.FORMAT_ETC2] = true;
compressedFormat += 'etc2 ';
}
if (this._WEBGL_compressed_texture_s3tc) {
this._features[GFXFeature.FORMAT_DXT] = true;
compressedFormat += 'dxt ';
}
if (this._WEBGL_compressed_texture_pvrtc) {
this._features[GFXFeature.FORMAT_PVRTC] = true;
compressedFormat += 'pvrtc ';
}
console.info('RENDERER: ' + this._renderer);
console.info('VENDOR: ' + this._vendor);
console.info('VERSION: ' + this._version);
@@ -250,6 +291,7 @@ export class WebGL2GFXDevice extends GFXDevice {
console.info('MAX_TEXTURE_MAX_ANISOTROPY_EXT: ' + this._EXT_texture_filter_anisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
}
console.info('USE_VAO: ' + this._useVAO);
console.info('COMPRESSED_FORMAT: ' + compressedFormat);
// init states
this.initStates(gl);
+1 -1
View File
@@ -30,5 +30,5 @@ export { Node } from './node';
export { Scene } from './scene';
export { Layers } from './layers';
export { find } from './find';
export { default as PrivateNode } from './private-node';
export { PrivateNode } from './private-node';
export { default as NodeActivator } from './node-activator';
@@ -25,11 +25,14 @@
'use strict';
import { CCObject } from '../core';
import { ccclass } from '../core/data/class-decorator';
import { Node } from './node';
import { ccclass, property } from '../core/data/class-decorator';
const LocalDirtyFlag = Node._LocalDirtyFlag;
const POSITION_ON = 1 << 0;
// const LocalDirtyFlag = Node._LocalDirtyFlag;
// const POSITION_ON = 1 << 0;
// @ts-ignore
const HideInHierarchy = CCObject.Flags.HideInHierarchy;
/**
* !#en
@@ -55,113 +58,115 @@ const POSITION_ON = 1 << 0;
* @param {String} name
* @extends Node
*/
@ccclass("cc.PrivateNode")
export default class PrivateNode extends Node {
@property({
override: true
})
get x() {
return this._originPos.x;
}
set x(value) {
var localPosition = this._originPos;
if (value !== localPosition.x) {
localPosition.x = value;
this._posDirty(true);
}
}
@ccclass('cc.PrivateNode')
export class PrivateNode extends Node {
// @property({
// override: true
// })
// get x() {
// return this._originPos.x;
// }
// set x(value) {
// var localPosition = this._originPos;
// if (value !== localPosition.x) {
// localPosition.x = value;
// this._posDirty(true);
// }
// }
@property({
override: true
})
get y() {
return this._originPos.y;
}
set y(value) {
var localPosition = this._originPos;
if (value !== localPosition.y) {
localPosition.y = value;
this._posDirty(true);
}
}
// @property({
// override: true
// })
// get y() {
// return this._originPos.y;
// }
// set y(value) {
// var localPosition = this._originPos;
// if (value !== localPosition.y) {
// localPosition.y = value;
// this._posDirty(true);
// }
// }
@property({
override: true
})
get zIndex() {
return cc.macro.MIN_ZINDEX;
}
set zIndex(val) {
cc.warnID(1638);
}
// @property({
// override: true
// })
// get zIndex() {
// return cc.macro.MIN_ZINDEX;
// }
// set zIndex(val) {
// cc.warnID(1638);
// }
/**
* @method constructor
* @param {String} [name]
*/
constructor (name) {
constructor (name: string) {
super(name);
this._localZOrder = cc.macro.MIN_ZINDEX << 16;
this._originPos = cc.v2();
// this._localZOrder = cc.macro.MIN_ZINDEX << 16;
// this._originPos = cc.v2();
this._objFlags |= HideInHierarchy;
}
_posDirty (sendEvent) {
this.setLocalDirty(LocalDirtyFlag.POSITION);
if (sendEvent === true && (this._eventMask & POSITION_ON)) {
this.emit(Node.EventType.POSITION_CHANGED);
}
}
// _posDirty (sendEvent) {
// this.setLocalDirty(LocalDirtyFlag.POSITION);
// if (sendEvent === true && (this._eventMask & POSITION_ON)) {
// this.emit(Node.EventType.POSITION_CHANGED);
// }
// }
_updateLocalMatrix() {
if (!this._localMatDirty) return;
// _updateLocalMatrix() {
// if (!this._localMatDirty) return;
let parent = this.parent;
if (parent) {
// Position correction for transform calculation
this._position.x = this._originPos.x - (parent._anchorPoint.x - 0.5) * parent._contentSize.width;
this._position.y = this._originPos.y - (parent._anchorPoint.y - 0.5) * parent._contentSize.height;
}
// let parent = this.parent;
// if (parent) {
// // Position correction for transform calculation
// this._position.x = this._originPos.x - (parent._anchorPoint.x - 0.5) * parent._contentSize.width;
// this._position.y = this._originPos.y - (parent._anchorPoint.y - 0.5) * parent._contentSize.height;
// }
super._updateLocalMatrix();
}
// super._updateLocalMatrix();
// }
getPosition () {
return new cc.Vec2(this._originPos);
}
// getPosition () {
// return new cc.Vec2(this._originPos);
// }
setPosition (x, y) {
if (y === undefined) {
x = x.x;
y = x.y;
}
// setPosition (x, y) {
// if (y === undefined) {
// x = x.x;
// y = x.y;
// }
let pos = this._originPos;
if (pos.x === x && pos.y === y) {
return;
}
pos.x = x;
pos.y = y;
this._posDirty(true);
}
// let pos = this._originPos;
// if (pos.x === x && pos.y === y) {
// return;
// }
// pos.x = x;
// pos.y = y;
// this._posDirty(true);
// }
setParent(value) {
let oldParent = this._parent;
super.setParent(value);
if (oldParent !== value) {
if (oldParent) {
oldParent.off(Node.EventType.ANCHOR_CHANGED, this._posDirty, this);
}
if (value) {
value.on(Node.EventType.ANCHOR_CHANGED, this._posDirty, this);
}
}
}
// setParent(value) {
// let oldParent = this._parent;
// super.setParent(value);
// if (oldParent !== value) {
// if (oldParent) {
// oldParent.off(Node.EventType.ANCHOR_CHANGED, this._posDirty, this);
// }
// if (value) {
// value.on(Node.EventType.ANCHOR_CHANGED, this._posDirty, this);
// }
// }
// }
// do not update order of arrival
_updateOrderOfArrival() {}
// public _updateOrderOfArrival () {}
}
cc.js.getset(PrivateNode.prototype, "parent", PrivateNode.prototype.getParent, PrivateNode.prototype.setParent);
cc.js.getset(PrivateNode.prototype, "position", PrivateNode.prototype.getPosition, PrivateNode.prototype.setPosition);
// cc.js.getset(PrivateNode.prototype, 'parent', PrivateNode.prototype.getParent, PrivateNode.prototype.setParent);
// cc.js.getset(PrivateNode.prototype, 'position', PrivateNode.prototype.getPosition, PrivateNode.prototype.setPosition);
cc.PrivateNode = PrivateNode;