add graphics (#4119)

This commit is contained in:
JoneLau
2019-03-30 18:18:44 +08:00
committed by Weiliang Wang
parent fdaaf22ea4
commit eebccf3e27
26 changed files with 2443 additions and 2346 deletions
-159
View File
@@ -1,159 +0,0 @@
/****************************************************************************
Copyright (c) 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 Helper = require('../../../../graphics/helper');
const Types = require('../../../../graphics/types');
const js = require('../../../../platform/js');
const PointFlags = Types.PointFlags;
const LineJoin = Types.LineJoin;
const LineCap = Types.LineCap;
function Impl () {
this.cmds = [];
this.style = {
strokeStyle: 'black',
fillStyle: 'white',
lineCap: 'butt',
lineJoin: 'miter',
miterLimit: 10
};
}
let _proto = Impl.prototype;
js.mixin(_proto, {
moveTo (x, y) {
this.cmds.push(['moveTo', [x, y]]);
},
lineTo (x, y) {
this.cmds.push(['lineTo', [x, y]]);
},
bezierCurveTo (c1x, c1y, c2x, c2y, x, y) {
this.cmds.push(['bezierCurveTo', [c1x, c1y, c2x, c2y, x, y]]);
},
quadraticCurveTo (cx, cy, x, y) {
this.cmds.push(['quadraticCurveTo', [cx, cy, x, y]]);
},
arc (cx, cy, r, startAngle, endAngle, counterclockwise) {
Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise);
},
ellipse (cx, cy, rx, ry) {
Helper.ellipse(this, cx, cy, rx, ry);
},
circle (cx, cy, r) {
Helper.ellipse(this, cx, cy, r, r);
},
rect (x, y, w, h) {
this.moveTo(x, y);
this.lineTo(x, y + h);
this.lineTo(x + w, y + h);
this.lineTo(x + w, y);
this.close();
},
roundRect (x, y, w, h, r) {
Helper.roundRect(this, x, y, w, h, r);
},
clear (comp, clean) {
this.cmds.length = 0;
},
close () {
this.cmds.push(['closePath', []]);
},
stroke () {
this.cmds.push(['stroke', []]);
},
fill () {
this.cmds.push(['fill', []]);
}
});
js.set(_proto, 'strokeColor', function (v) {
var strokeStyle = 'rgba(' + (0 | v.r) + ',' + (0 | v.g) + ',' + (0 | v.b) + ',' + v.a / 255 + ')';
this.cmds.push(['strokeStyle', strokeStyle]);
this.style.strokeStyle = strokeStyle;
});
js.set(_proto, 'fillColor', function (v) {
var fillStyle = 'rgba(' + (0 | v.r) + ',' + (0 | v.g) + ',' + (0 | v.b) + ',' + v.a / 255 + ')';
this.cmds.push(['fillStyle', fillStyle]);
this.style.fillStyle = fillStyle;
});
js.set(_proto, 'lineWidth', function (v) {
this.cmds.push(['lineWidth', v]);
this.style.lineWidth = v;
});
js.set(_proto, 'lineCap', function (v) {
var lineCap = 'butt';
if (v === LineCap.BUTT) {
lineCap = 'butt';
}
else if (v === LineCap.ROUND) {
lineCap = 'round';
}
else if (v === LineCap.SQUARE) {
lineCap = 'square';
}
this.cmds.push(['lineCap', lineCap]);
this.style.lineCap = lineCap;
});
js.set(_proto, 'lineJoin', function (v) {
var lineJoin = 'bevel';
if (v === LineJoin.BEVEL) {
lineJoin = 'bevel';
}
else if (v === LineJoin.ROUND) {
lineJoin = 'round';
}
else if (v === LineJoin.MITER) {
lineJoin = 'miter';
}
this.cmds.push(['lineJoin', lineJoin]);
this.style.lineJoin = lineJoin;
});
js.set(_proto, 'miterLimit', function (v) {
this.cmds.push(['miterLimit', v]);
this.style.miterLimit = v;
});
module.exports = Impl;
-88
View File
@@ -1,88 +0,0 @@
/****************************************************************************
Copyright (c) 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 Impl = require('./impl');
module.exports = {
createImpl () {
return new Impl();
},
draw (ctx, comp) {
let node = comp.node;
// Transform
let matrix = node._worldMatrix;
let a = matrix.m00, b = matrix.m01, c = matrix.m04, d = matrix.m05,
tx = matrix.m12, ty = matrix.m13;
ctx.transform(a, b, c, d, tx, ty);
ctx.save();
// TODO: handle blend function
// opacity
ctx.globalAlpha = node.opacity / 255;
let style = comp._impl.style;
ctx.strokeStyle = style.strokeStyle;
ctx.fillStyle = style.fillStyle;
ctx.lineWidth = style.lineWidth;
ctx.lineJoin = style.lineJoin;
ctx.miterLimit = style.miterLimit;
let endPath = true;
let cmds = comp._impl.cmds;
for (let i = 0, l = cmds.length; i < l; i++) {
let cmd = cmds[i];
let ctxCmd = cmd[0], args = cmd[1];
if (ctxCmd === 'moveTo' && endPath) {
ctx.beginPath();
endPath = false;
}
else if (ctxCmd === 'fill' || ctxCmd === 'stroke' || ctxCmd === 'fillRect') {
endPath = true;
}
if (typeof ctx[ctxCmd] === 'function') {
ctx[ctxCmd].apply(ctx, args);
}
else {
ctx[ctxCmd] = args;
}
}
ctx.restore();
return 1;
},
stroke (comp) {
comp._impl.stroke();
},
fill (comp) {
comp._impl.fill();
}
}
-386
View File
@@ -1,386 +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 RenderComponent = require('../components/CCRenderComponent');
const SpriteMaterial = require('../renderer/render-engine').SpriteMaterial;
const Types = require('./types');
const LineCap = Types.LineCap;
const LineJoin = Types.LineJoin;
/**
* @class Graphics
* @extends Component
*/
let Graphics = cc.Class({
name: 'cc.Graphics',
extends: RenderComponent,
editor: CC_EDITOR && {
menu: 'i18n:MAIN_MENU.component.renderers/Graphics',
},
ctor () {
this._impl = Graphics._assembler.createImpl(this);
},
properties: {
_lineWidth: 1,
_strokeColor: cc.Color.BLACK,
_lineJoin: LineJoin.MITER,
_lineCap: LineCap.BUTT,
_fillColor: cc.Color.WHITE,
_miterLimit: 10,
/**
* !#en
* Current line width.
* !#zh
* 当前线条宽度
* @property {Number} lineWidth
* @default 1
*/
lineWidth: {
get () {
return this._lineWidth;
},
set (value) {
this._lineWidth = value;
this._impl.lineWidth = value;
}
},
/**
* !#en
* lineJoin determines how two connecting segments (of lines, arcs or curves) with non-zero lengths in a shape are joined together.
* !#zh
* lineJoin 用来设置2个长度不为0的相连部分(线段,圆弧,曲线)如何连接在一起的属性。
* @property {Graphics.LineJoin} lineJoin
* @default LineJoin.MITER
*/
lineJoin: {
get () {
return this._lineJoin;
},
set (value) {
this._lineJoin = value;
this._impl.lineJoin = value;
},
type: LineJoin
},
/**
* !#en
* lineCap determines how the end points of every line are drawn.
* !#zh
* lineCap 指定如何绘制每一条线段末端。
* @property {Graphics.LineCap} lineCap
* @default LineCap.BUTT
*/
lineCap: {
get () {
return this._lineCap;
},
set (value) {
this._lineCap = value;
this._impl.lineCap = value;
},
type: LineCap
},
/**
* !#en
* stroke color
* !#zh
* 线段颜色
* @property {Color} strokeColor
* @default Color.BLACK
*/
strokeColor: {
get () {
return this._strokeColor;
},
set (value) {
this._impl.strokeColor = this._strokeColor = cc.color(value);
}
},
/**
* !#en
* fill color
* !#zh
* 填充颜色
* @property {Color} fillColor
* @default Color.WHITE
*/
fillColor: {
get () {
return this._fillColor;
},
set (value) {
this._impl.fillColor = this._fillColor = cc.color(value);
}
},
/**
* !#en
* Sets the miter limit ratio
* !#zh
* 设置斜接面限制比例
* @property {Number} miterLimit
* @default 10
*/
miterLimit: {
get () {
return this._miterLimit;
},
set (value) {
this._miterLimit = value;
this._impl.miterLimit = value;
}
}
},
statics: {
LineJoin: LineJoin,
LineCap: LineCap
},
onRestore () {
if (!this._impl) {
this._impl = Graphics._assembler.createImpl();
}
},
onEnable () {
this._super();
this._activateMaterial();
},
onDestroy () {
this._super();
this._impl.clear(this, true);
this._impl = null;
},
_activateMaterial () {
// Ignore material in canvas
if (cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) {
return;
}
this.node._renderFlag &= ~cc.RenderFlow.FLAG_RENDER;
this.node._renderFlag |= cc.RenderFlow.FLAG_CUSTOM_IA_RENDER;
if (this._material) {
return;
}
let material = new SpriteMaterial();
material.useColor = false;
material.useTexture = false;
material.useModel = true;
this._updateMaterial(material);
},
/**
* !#en Move path start point to (x,y).
* !#zh 移动路径起点到坐标(x, y)
* @method moveTo
* @param {Number} [x] The x axis of the coordinate for the end point.
* @param {Number} [y] The y axis of the coordinate for the end point.
*/
moveTo (x, y) {
if (CC_DEBUG && x instanceof cc.Vec2) {
cc.warn('[moveTo] : Can not pass Vec2 as [x, y] value, please check it.');
return;
}
this._impl.moveTo(x, y);
},
/**
* !#en Adds a straight line to the path
* !#zh 绘制直线路径
* @method lineTo
* @param {Number} [x] The x axis of the coordinate for the end point.
* @param {Number} [y] The y axis of the coordinate for the end point.
*/
lineTo (x, y) {
if (CC_DEBUG && x instanceof cc.Vec2) {
cc.warn('[moveTo] : Can not pass Vec2 as [x, y] value, please check it.');
return;
}
this._impl.lineTo(x, y);
},
/**
* !#en Adds a cubic Bézier curve to the path
* !#zh 绘制三次贝赛尔曲线路径
* @method bezierCurveTo
* @param {Number} [c1x] The x axis of the coordinate for the first control point.
* @param {Number} [c1y] The y axis of the coordinate for first control point.
* @param {Number} [c2x] The x axis of the coordinate for the second control point.
* @param {Number} [c2y] The y axis of the coordinate for the second control point.
* @param {Number} [x] The x axis of the coordinate for the end point.
* @param {Number} [y] The y axis of the coordinate for the end point.
*/
bezierCurveTo (c1x, c1y, c2x, c2y, x, y) {
this._impl.bezierCurveTo(c1x, c1y, c2x, c2y, x, y);
},
/**
* !#en Adds a quadratic Bézier curve to the path
* !#zh 绘制二次贝赛尔曲线路径
* @method quadraticCurveTo
* @param {Number} [cx] The x axis of the coordinate for the control point.
* @param {Number} [cy] The y axis of the coordinate for the control point.
* @param {Number} [x] The x axis of the coordinate for the end point.
* @param {Number} [y] The y axis of the coordinate for the end point.
*/
quadraticCurveTo (cx, cy, x, y) {
this._impl.quadraticCurveTo(cx, cy, x, y);
},
/**
* !#en Adds an arc to the path which is centered at (cx, cy) position with radius r starting at startAngle and ending at endAngle going in the given direction by counterclockwise (defaulting to false).
* !#zh 绘制圆弧路径。圆弧路径的圆心在 (cx, cy) 位置,半径为 r ,根据 counterclockwise (默认为false)指定的方向从 startAngle 开始绘制,到 endAngle 结束。
* @method arc
* @param {Number} [cx] The x axis of the coordinate for the center point.
* @param {Number} [cy] The y axis of the coordinate for the center point.
* @param {Number} [r] The arc's radius.
* @param {Number} [startAngle] The angle at which the arc starts, measured clockwise from the positive x axis and expressed in radians.
* @param {Number} [endAngle] The angle at which the arc ends, measured clockwise from the positive x axis and expressed in radians.
* @param {Boolean} [counterclockwise] An optional Boolean which, if true, causes the arc to be drawn counter-clockwise between the two angles. By default it is drawn clockwise.
*/
arc (cx, cy, r, startAngle, endAngle, counterclockwise) {
this._impl.arc(cx, cy, r, startAngle, endAngle, counterclockwise);
},
/**
* !#en Adds an ellipse to the path.
* !#zh 绘制椭圆路径。
* @method ellipse
* @param {Number} [cx] The x axis of the coordinate for the center point.
* @param {Number} [cy] The y axis of the coordinate for the center point.
* @param {Number} [rx] The ellipse's x-axis radius.
* @param {Number} [ry] The ellipse's y-axis radius.
*/
ellipse (cx, cy, rx, ry) {
this._impl.ellipse(cx, cy, rx, ry);
},
/**
* !#en Adds an circle to the path.
* !#zh 绘制圆形路径。
* @method circle
* @param {Number} [cx] The x axis of the coordinate for the center point.
* @param {Number} [cy] The y axis of the coordinate for the center point.
* @param {Number} [r] The circle's radius.
*/
circle (cx, cy, r) {
this._impl.circle(cx, cy, r);
},
/**
* !#en Adds an rectangle to the path.
* !#zh 绘制矩形路径。
* @method rect
* @param {Number} [x] The x axis of the coordinate for the rectangle starting point.
* @param {Number} [y] The y axis of the coordinate for the rectangle starting point.
* @param {Number} [w] The rectangle's width.
* @param {Number} [h] The rectangle's height.
*/
rect (x, y, w, h) {
this._impl.rect(x, y, w, h);
},
/**
* !#en Adds an round corner rectangle to the path.
* !#zh 绘制圆角矩形路径。
* @method roundRect
* @param {Number} [x] The x axis of the coordinate for the rectangle starting point.
* @param {Number} [y] The y axis of the coordinate for the rectangle starting point.
* @param {Number} [w] The rectangles width.
* @param {Number} [h] The rectangle's height.
* @param {Number} [r] The radius of the rectangle.
*/
roundRect (x, y, w, h, r) {
this._impl.roundRect(x, y, w, h, r);
},
/**
* !#en Draws a filled rectangle.
* !#zh 绘制填充矩形。
* @method fillRect
* @param {Number} [x] The x axis of the coordinate for the rectangle starting point.
* @param {Number} [y] The y axis of the coordinate for the rectangle starting point.
* @param {Number} [w] The rectangle's width.
* @param {Number} [h] The rectangle's height.
*/
fillRect (x, y, w, h) {
this.rect(x, y, w, h);
this.fill();
},
/**
* !#en Erasing any previously drawn content.
* !#zh 擦除之前绘制的所有内容的方法。
* @method clear
* @param {Boolean} [clean] Whether to clean the graphics inner cache.
*/
clear (clean) {
this._impl.clear(this, clean);
},
/**
* !#en Causes the point of the pen to move back to the start of the current path. It tries to add a straight line from the current point to the start.
* !#zh 将笔点返回到当前路径起始点的。它尝试从当前点到起始点绘制一条直线。
* @method close
*/
close () {
this._impl.close();
},
/**
* !#en Strokes the current or given path with the current stroke style.
* !#zh 根据当前的画线样式,绘制当前或已经存在的路径。
* @method stroke
*/
stroke () {
Graphics._assembler.stroke(this);
},
/**
* !#en Fills the current or given path with the current fill style.
* !#zh 根据当前的画线样式,填充当前或已经存在的路径。
* @method fill
*/
fill () {
Graphics._assembler.fill(this);
}
});
cc.Graphics = module.exports = Graphics;
-669
View File
@@ -1,669 +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.
****************************************************************************/
'use strict';
module.exports = earcut;
function earcut(data, holeIndices, dim) {
dim = dim || 2;
var hasHoles = holeIndices && holeIndices.length,
outerLen = hasHoles ? holeIndices[0] * dim : data.length,
outerNode = linkedList(data, 0, outerLen, dim, true),
triangles = [];
if (!outerNode) return triangles;
var minX, minY, maxX, maxY, x, y, size;
if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
// if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
if (data.length > 80 * dim) {
minX = maxX = data[0];
minY = maxY = data[1];
for (var i = dim; i < outerLen; i += dim) {
x = data[i];
y = data[i + 1];
if (x < minX) minX = x;
if (y < minY) minY = y;
if (x > maxX) maxX = x;
if (y > maxY) maxY = y;
}
// minX, minY and size are later used to transform coords into integers for z-order calculation
size = Math.max(maxX - minX, maxY - minY);
}
earcutLinked(outerNode, triangles, dim, minX, minY, size);
return triangles;
}
// create a circular doubly linked list from polygon points in the specified winding order
function linkedList(data, start, end, dim, clockwise) {
var i, last;
if (clockwise === (signedArea(data, start, end, dim) > 0)) {
for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last);
} else {
for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last);
}
if (last && equals(last, last.next)) {
removeNode(last);
last = last.next;
}
return last;
}
// eliminate colinear or duplicate points
function filterPoints(start, end) {
if (!start) return start;
if (!end) end = start;
var p = start,
again;
do {
again = false;
if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
removeNode(p);
p = end = p.prev;
if (p === p.next) return null;
again = true;
} else {
p = p.next;
}
} while (again || p !== end);
return end;
}
// main ear slicing loop which triangulates a polygon (given as a linked list)
function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
if (!ear) return;
// interlink polygon nodes in z-order
if (!pass && size) indexCurve(ear, minX, minY, size);
var stop = ear,
prev, next;
// iterate through ears, slicing them one by one
while (ear.prev !== ear.next) {
prev = ear.prev;
next = ear.next;
if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
// cut off the triangle
triangles.push(prev.i / dim);
triangles.push(ear.i / dim);
triangles.push(next.i / dim);
removeNode(ear);
// skipping the next vertice leads to less sliver triangles
ear = next.next;
stop = next.next;
continue;
}
ear = next;
// if we looped through the whole remaining polygon and can't find any more ears
if (ear === stop) {
// try filtering points and slicing again
if (!pass) {
earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1);
// if this didn't work, try curing all small self-intersections locally
} else if (pass === 1) {
ear = cureLocalIntersections(ear, triangles, dim);
earcutLinked(ear, triangles, dim, minX, minY, size, 2);
// as a last resort, try splitting the remaining polygon into two
} else if (pass === 2) {
splitEarcut(ear, triangles, dim, minX, minY, size);
}
break;
}
}
}
// check whether a polygon node forms a valid ear with adjacent nodes
function isEar(ear) {
var a = ear.prev,
b = ear,
c = ear.next;
if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
// now make sure we don't have other points inside the potential ear
var p = ear.next.next;
while (p !== ear.prev) {
if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
area(p.prev, p, p.next) >= 0) return false;
p = p.next;
}
return true;
}
function isEarHashed(ear, minX, minY, size) {
var a = ear.prev,
b = ear,
c = ear.next;
if (area(a, b, c) >= 0) return false; // reflex, can't be an ear
// triangle bbox; min & max are calculated like this for speed
var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x),
minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y),
maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x),
maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
// z-order range for the current triangle bbox;
var minZ = zOrder(minTX, minTY, minX, minY, size),
maxZ = zOrder(maxTX, maxTY, minX, minY, size);
// first look for points inside the triangle in increasing z-order
var p = ear.nextZ;
while (p && p.z <= maxZ) {
if (p !== ear.prev && p !== ear.next &&
pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
area(p.prev, p, p.next) >= 0) return false;
p = p.nextZ;
}
// then look for points in decreasing z-order
p = ear.prevZ;
while (p && p.z >= minZ) {
if (p !== ear.prev && p !== ear.next &&
pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
area(p.prev, p, p.next) >= 0) return false;
p = p.prevZ;
}
return true;
}
// go through all polygon nodes and cure small local self-intersections
function cureLocalIntersections(start, triangles, dim) {
var p = start;
do {
var a = p.prev,
b = p.next.next;
if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
triangles.push(a.i / dim);
triangles.push(p.i / dim);
triangles.push(b.i / dim);
// remove two nodes involved
removeNode(p);
removeNode(p.next);
p = start = b;
}
p = p.next;
} while (p !== start);
return p;
}
// try splitting polygon into two and triangulate them independently
function splitEarcut(start, triangles, dim, minX, minY, size) {
// look for a valid diagonal that divides the polygon into two
var a = start;
do {
var b = a.next.next;
while (b !== a.prev) {
if (a.i !== b.i && isValidDiagonal(a, b)) {
// split the polygon in two by the diagonal
var c = splitPolygon(a, b);
// filter colinear points around the cuts
a = filterPoints(a, a.next);
c = filterPoints(c, c.next);
// run earcut on each half
earcutLinked(a, triangles, dim, minX, minY, size);
earcutLinked(c, triangles, dim, minX, minY, size);
return;
}
b = b.next;
}
a = a.next;
} while (a !== start);
}
// link every hole into the outer loop, producing a single-ring polygon without holes
function eliminateHoles(data, holeIndices, outerNode, dim) {
var queue = [],
i, len, start, end, list;
for (i = 0, len = holeIndices.length; i < len; i++) {
start = holeIndices[i] * dim;
end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
list = linkedList(data, start, end, dim, false);
if (list === list.next) list.steiner = true;
queue.push(getLeftmost(list));
}
queue.sort(compareX);
// process holes from left to right
for (i = 0; i < queue.length; i++) {
eliminateHole(queue[i], outerNode);
outerNode = filterPoints(outerNode, outerNode.next);
}
return outerNode;
}
function compareX(a, b) {
return a.x - b.x;
}
// find a bridge between vertices that connects hole with an outer ring and and link it
function eliminateHole(hole, outerNode) {
outerNode = findHoleBridge(hole, outerNode);
if (outerNode) {
var b = splitPolygon(outerNode, hole);
filterPoints(b, b.next);
}
}
// David Eberly's algorithm for finding a bridge between hole and outer polygon
function findHoleBridge(hole, outerNode) {
var p = outerNode,
hx = hole.x,
hy = hole.y,
qx = -Infinity,
m;
// find a segment intersected by a ray from the hole's leftmost point to the left;
// segment's endpoint with lesser x will be potential connection point
do {
if (hy <= p.y && hy >= p.next.y) {
var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
if (x <= hx && x > qx) {
qx = x;
if (x === hx) {
if (hy === p.y) return p;
if (hy === p.next.y) return p.next;
}
m = p.x < p.next.x ? p : p.next;
}
}
p = p.next;
} while (p !== outerNode);
if (!m) return null;
if (hx === qx) return m.prev; // hole touches outer segment; pick lower endpoint
// look for points inside the triangle of hole point, segment intersection and endpoint;
// if there are no points found, we have a valid connection;
// otherwise choose the point of the minimum angle with the ray as connection point
var stop = m,
mx = m.x,
my = m.y,
tanMin = Infinity,
tan;
p = m.next;
while (p !== stop) {
if (hx >= p.x && p.x >= mx &&
pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
m = p;
tanMin = tan;
}
}
p = p.next;
}
return m;
}
// interlink polygon nodes in z-order
function indexCurve(start, minX, minY, size) {
var p = start;
do {
if (p.z === null) p.z = zOrder(p.x, p.y, minX, minY, size);
p.prevZ = p.prev;
p.nextZ = p.next;
p = p.next;
} while (p !== start);
p.prevZ.nextZ = null;
p.prevZ = null;
sortLinked(p);
}
// Simon Tatham's linked list merge sort algorithm
// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
function sortLinked(list) {
var i, p, q, e, tail, numMerges, pSize, qSize,
inSize = 1;
do {
p = list;
list = null;
tail = null;
numMerges = 0;
while (p) {
numMerges++;
q = p;
pSize = 0;
for (i = 0; i < inSize; i++) {
pSize++;
q = q.nextZ;
if (!q) break;
}
qSize = inSize;
while (pSize > 0 || (qSize > 0 && q)) {
if (pSize === 0) {
e = q;
q = q.nextZ;
qSize--;
} else if (qSize === 0 || !q) {
e = p;
p = p.nextZ;
pSize--;
} else if (p.z <= q.z) {
e = p;
p = p.nextZ;
pSize--;
} else {
e = q;
q = q.nextZ;
qSize--;
}
if (tail) tail.nextZ = e;
else list = e;
e.prevZ = tail;
tail = e;
}
p = q;
}
tail.nextZ = null;
inSize *= 2;
} while (numMerges > 1);
return list;
}
// z-order of a point given coords and size of the data bounding box
function zOrder(x, y, minX, minY, size) {
// coords are transformed into non-negative 15-bit integer range
x = 32767 * (x - minX) / size;
y = 32767 * (y - minY) / size;
x = (x | (x << 8)) & 0x00FF00FF;
x = (x | (x << 4)) & 0x0F0F0F0F;
x = (x | (x << 2)) & 0x33333333;
x = (x | (x << 1)) & 0x55555555;
y = (y | (y << 8)) & 0x00FF00FF;
y = (y | (y << 4)) & 0x0F0F0F0F;
y = (y | (y << 2)) & 0x33333333;
y = (y | (y << 1)) & 0x55555555;
return x | (y << 1);
}
// find the leftmost node of a polygon ring
function getLeftmost(start) {
var p = start,
leftmost = start;
do {
if (p.x < leftmost.x) leftmost = p;
p = p.next;
} while (p !== start);
return leftmost;
}
// check if a point lies within a convex triangle
function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
(ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
(bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
}
// check if a diagonal between two polygon nodes is valid (lies in polygon interior)
function isValidDiagonal(a, b) {
return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) &&
locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
}
// signed area of a triangle
function area(p, q, r) {
return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
}
// check if two points are equal
function equals(p1, p2) {
return p1.x === p2.x && p1.y === p2.y;
}
// check if two segments intersect
function intersects(p1, q1, p2, q2) {
if ((equals(p1, q1) && equals(p2, q2)) ||
(equals(p1, q2) && equals(p2, q1))) return true;
return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
}
// check if a polygon diagonal intersects any polygon segments
function intersectsPolygon(a, b) {
var p = a;
do {
if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i &&
intersects(p, p.next, a, b)) return true;
p = p.next;
} while (p !== a);
return false;
}
// check if a polygon diagonal is locally inside the polygon
function locallyInside(a, b) {
return area(a.prev, a, a.next) < 0 ?
area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 :
area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
}
// check if the middle point of a polygon diagonal is inside the polygon
function middleInside(a, b) {
var p = a,
inside = false,
px = (a.x + b.x) / 2,
py = (a.y + b.y) / 2;
do {
if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
inside = !inside;
p = p.next;
} while (p !== a);
return inside;
}
// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
// if one belongs to the outer ring and another to a hole, it merges it into a single ring
function splitPolygon(a, b) {
var a2 = new Node(a.i, a.x, a.y),
b2 = new Node(b.i, b.x, b.y),
an = a.next,
bp = b.prev;
a.next = b;
b.prev = a;
a2.next = an;
an.prev = a2;
b2.next = a2;
a2.prev = b2;
bp.next = b2;
b2.prev = bp;
return b2;
}
// create a node and optionally link it with previous one (in a circular doubly linked list)
function insertNode(i, x, y, last) {
var p = new Node(i, x, y);
if (!last) {
p.prev = p;
p.next = p;
} else {
p.next = last.next;
p.prev = last;
last.next.prev = p;
last.next = p;
}
return p;
}
function removeNode(p) {
p.next.prev = p.prev;
p.prev.next = p.next;
if (p.prevZ) p.prevZ.nextZ = p.nextZ;
if (p.nextZ) p.nextZ.prevZ = p.prevZ;
}
function Node(i, x, y) {
// vertice index in coordinates array
this.i = i;
// vertex coordinates
this.x = x;
this.y = y;
// previous and next vertice nodes in a polygon ring
this.prev = null;
this.next = null;
// z-order curve value
this.z = null;
// previous and next nodes in z-order
this.prevZ = null;
this.nextZ = null;
// indicates whether this is a steiner point
this.steiner = false;
}
// return a percentage difference between the polygon area and its triangulation area;
// used to verify correctness of triangulation
earcut.deviation = function (data, holeIndices, dim, triangles) {
var hasHoles = holeIndices && holeIndices.length;
var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
if (hasHoles) {
for (var i = 0, len = holeIndices.length; i < len; i++) {
var start = holeIndices[i] * dim;
var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
polygonArea -= Math.abs(signedArea(data, start, end, dim));
}
}
var trianglesArea = 0;
for (i = 0; i < triangles.length; i += 3) {
var a = triangles[i] * dim;
var b = triangles[i + 1] * dim;
var c = triangles[i + 2] * dim;
trianglesArea += Math.abs(
(data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
(data[a] - data[b]) * (data[c + 1] - data[a + 1]));
}
return polygonArea === 0 && trianglesArea === 0 ? 0 :
Math.abs((trianglesArea - polygonArea) / polygonArea);
};
function signedArea(data, start, end, dim) {
var sum = 0;
for (var i = start, j = end - dim; i < end; i += dim) {
sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
j = i;
}
return sum;
}
// turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
earcut.flatten = function (data) {
var dim = data[0][0].length,
result = {vertices: [], holes: [], dimensions: dim},
holeIndex = 0;
for (var i = 0; i < data.length; i++) {
for (var j = 0; j < data[i].length; j++) {
for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]);
}
if (i > 0) {
holeIndex += data[i - 1].length;
result.holes.push(holeIndex);
}
}
return result;
};
-242
View File
@@ -1,242 +0,0 @@
const Helper = require('../../../../graphics/helper');
const PointFlags = require('../../../../graphics/types').PointFlags;
const MeshBuffer = require('../../mesh-buffer');
const vfmtPosColor = require('../../vertex-format').vfmtPosColor;
const renderer = require('../../../index');
const renderEngine = renderer.renderEngine;
const IARenderData = renderEngine.IARenderData;
const InputAssembler = renderEngine.InputAssembler;
let Point = cc.Class({
name: 'cc.GraphicsPoint',
extends: cc.Vec2,
ctor (x, y) {
this.reset();
},
reset () {
this.dx = 0;
this.dy = 0;
this.dmx = 0;
this.dmy = 0;
this.flags = 0;
this.len = 0;
}
});
function Path () {
this.reset();
}
cc.js.mixin(Path.prototype, {
reset () {
this.closed = false;
this.nbevel = 0;
this.complex = true;
if (this.points) {
this.points.length = 0;
}
else {
this.points = [];
}
}
});
function Impl (graphics) {
// inner properties
this._tessTol = 0.25;
this._distTol = 0.01;
this._updatePathOffset = false;
this._paths = null;
this._pathLength = 0;
this._pathOffset = 0;
this._points = null;
this._pointsOffset = 0;
this._commandx = 0;
this._commandy = 0;
this._paths = [];
this._points = [];
this._renderDatas = [];
this._dataOffset = 0;
}
cc.js.mixin(Impl.prototype, {
moveTo (x, y) {
if (this._updatePathOffset) {
this._pathOffset = this._pathLength;
this._updatePathOffset = false;
}
this._addPath();
this._addPoint(x, y, PointFlags.PT_CORNER);
this._commandx = x;
this._commandy = y;
},
lineTo (x, y) {
this._addPoint(x, y, PointFlags.PT_CORNER);
this._commandx = x;
this._commandy = y;
},
bezierCurveTo (c1x, c1y, c2x, c2y, x, y) {
var path = this._curPath;
var last = path.points[path.points.length - 1];
if (last.x === c1x && last.y === c1y && c2x === x && c2y === y) {
this.lineTo(x, y);
return;
}
Helper.tesselateBezier(this, last.x, last.y, c1x, c1y, c2x, c2y, x, y, 0, PointFlags.PT_CORNER);
this._commandx = x;
this._commandy = y;
},
quadraticCurveTo (cx, cy, x, y) {
var x0 = this._commandx;
var y0 = this._commandy;
this.bezierCurveTo(x0 + 2.0 / 3.0 * (cx - x0), y0 + 2.0 / 3.0 * (cy - y0), x + 2.0 / 3.0 * (cx - x), y + 2.0 / 3.0 * (cy - y), x, y);
},
arc (cx, cy, r, startAngle, endAngle, counterclockwise) {
Helper.arc(this, cx, cy, r, startAngle, endAngle, counterclockwise);
},
ellipse (cx, cy, rx, ry) {
Helper.ellipse(this, cx, cy, rx, ry);
this._curPath.complex = false;
},
circle (cx, cy, r) {
Helper.ellipse(this, cx, cy, r, r);
this._curPath.complex = false;
},
rect (x, y, w, h) {
this.moveTo(x, y);
this.lineTo(x, y + h);
this.lineTo(x + w, y + h);
this.lineTo(x + w, y);
this.close();
this._curPath.complex = false;
},
roundRect (x, y, w, h, r) {
Helper.roundRect(this, x, y, w, h, r);
this._curPath.complex = false;
},
clear (comp, clean) {
this._pathLength = 0;
this._pathOffset = 0;
this._pointsOffset = 0;
this._dataOffset = 0;
this._curPath = null;
let datas = this._renderDatas;
if (clean) {
this._paths.length = 0;
this._points.length = 0;
// manually destroy render datas
for (let i = 0, l = datas.length; i < l; i++) {
let data = datas[i];
data.meshbuffer.destroy();
data.meshbuffer = null;
}
datas.length = 0;
}
else {
for (let i = 0, l = datas.length; i < l; i++) {
let data = datas[i];
let meshbuffer = data.meshbuffer;
meshbuffer.reset();
}
}
},
close () {
this._curPath.closed = true;
},
_addPath () {
var offset = this._pathLength;
var path = this._paths[offset];
if (!path) {
path = new Path();
this._paths.push(path);
} else {
path.reset();
}
this._pathLength++;
this._curPath = path;
return path;
},
_addPoint (x, y, flags) {
var path = this._curPath;
if (!path) return;
var pt;
var points = this._points;
var pathPoints = path.points;
var offset = this._pointsOffset++;
pt = points[offset];
if (!pt) {
pt = new Point(x, y);
points.push(pt);
} else {
pt.x = x;
pt.y = y;
}
pt.flags = flags;
pathPoints.push(pt);
},
requestRenderData () {
let renderData = new IARenderData();
let meshbuffer = new MeshBuffer(renderer._walker, vfmtPosColor);
renderData.meshbuffer = meshbuffer;
this._renderDatas.push(renderData);
let ia = new InputAssembler();
ia._vertexBuffer = meshbuffer._vb;
ia._indexBuffer = meshbuffer._ib;
ia._start = 0;
renderData.ia = ia;
return renderData;
},
getRenderDatas () {
if (this._renderDatas.length === 0) {
this.requestRenderData();
}
return this._renderDatas;
}
});
module.exports = Impl;
-634
View File
@@ -1,634 +0,0 @@
/****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
const Graphics = require('../../../../graphics/graphics');
const PointFlags = require('../../../../graphics/types').PointFlags;
const LineJoin = Graphics.LineJoin;
const LineCap = Graphics.LineCap;
const Earcut = require('./earcut');
const Impl = require('./impl');
const MAX_VERTEX = 65535;
const MAX_INDICE = MAX_VERTEX * 2;
const PI = Math.PI;
const min = Math.min;
const max = Math.max;
const ceil = Math.ceil;
const acos = Math.acos;
const cos = Math.cos;
const sin = Math.sin;
const atan2 = Math.atan2;
const abs = Math.abs;
let _renderData = null;
let _impl = null;
let _curColor = 0;
function curveDivs (r, arc, tol) {
let da = acos(r / (r + tol)) * 2.0;
return max(2, ceil(arc / da));
}
function clamp (v, min, max) {
if (v < min) {
return min;
}
else if (v > max) {
return max;
}
return v;
}
let graphicsAssembler = {
useModel: true,
createImpl (graphics) {
return new Impl(graphics);
},
updateRenderData (graphics) {
let datas = graphics._impl.getRenderDatas();
for (let i = 0, l = datas.length; i < l; i++) {
datas[i].material = graphics.getMaterial();
}
},
fillBuffers (graphics, renderer) {
renderer._flush();
let tempNode = renderer.node;
renderer.node = graphics.node;
this.renderIA(graphics, renderer);
renderer.node = tempNode;
},
renderIA (graphics, renderer) {
let node = graphics.node;
let nodeColor = node.color,
nodeR = nodeColor.r / 255,
nodeG = nodeColor.g / 255,
nodeB = nodeColor.b / 255,
nodeA = nodeColor.a / 255;
let impl = graphics._impl;
let renderDatas = impl.getRenderDatas();
for (let index = 0, length = renderDatas.length; index < length; index++) {
let renderData = renderDatas[index];
let meshbuffer = renderData.meshbuffer;
renderData.ia._count = meshbuffer.indiceStart;
renderer._flushIA(renderData);
meshbuffer.uploadData();
}
},
genRenderData (graphics, cverts) {
let renderDatas = _impl.getRenderDatas();
let renderData = renderDatas[_impl._dataOffset];
let meshbuffer = renderData.meshbuffer;
let maxVertsCount = meshbuffer.vertexStart + cverts;
if (maxVertsCount > MAX_VERTEX ||
maxVertsCount * 3 > MAX_INDICE) {
++_impl._dataOffset;
maxVertsCount = cverts;
if (_impl._dataOffset < renderDatas.length) {
renderData = renderDatas[_impl._dataOffset];
}
else {
renderData = _impl.requestRenderData(graphics);
renderDatas[_impl._dataOffset] = renderData;
}
renderData.material = graphics.getMaterial();
meshbuffer = renderData.meshbuffer;
}
if (maxVertsCount > meshbuffer.vertexOffset) {
meshbuffer.requestStatic(cverts, cverts*3);
}
return renderData;
},
stroke (graphics) {
_curColor = graphics._strokeColor._val;
this._flattenPaths(graphics._impl);
this._expandStroke(graphics);
graphics._impl._updatePathOffset = true;
},
fill (graphics) {
_curColor = graphics._fillColor._val;
this._expandFill(graphics);
graphics._impl._updatePathOffset = true;
},
_expandStroke (graphics) {
let w = graphics.lineWidth * 0.5,
lineCap = graphics.lineCap,
lineJoin = graphics.lineJoin,
miterLimit = graphics.miterLimit;
_impl = graphics._impl;
let ncap = curveDivs(w, PI, _impl._tessTol);
this._calculateJoins(_impl, w, lineJoin, miterLimit);
let paths = _impl._paths;
// Calculate max vertex usage.
let cverts = 0;
for (let i = _impl._pathOffset, l = _impl._pathLength; i < l; i++) {
let path = paths[i];
let pointsLength = path.points.length;
if (lineJoin === LineJoin.ROUND) cverts += (pointsLength + path.nbevel * (ncap + 2) + 1) * 2; // plus one for loop
else cverts += (pointsLength + path.nbevel * 5 + 1) * 2; // plus one for loop
if (!path.closed) {
// space for caps
if (lineCap === LineCap.ROUND) {
cverts += (ncap * 2 + 2) * 2;
} else {
cverts += (3 + 3) * 2;
}
}
}
let renderData = _renderData = this.genRenderData(graphics, cverts),
meshbuffer = renderData.meshbuffer,
vData = meshbuffer._vData,
iData = meshbuffer._iData;
for (let i = _impl._pathOffset, l = _impl._pathLength; i < l; i++) {
let path = paths[i];
let pts = path.points;
let pointsLength = pts.length;
let offset = meshbuffer.vertexStart;
let p0, p1;
let start, end, loop;
loop = path.closed;
if (loop) {
// Looping
p0 = pts[pointsLength - 1];
p1 = pts[0];
start = 0;
end = pointsLength;
} else {
// Add cap
p0 = pts[0];
p1 = pts[1];
start = 1;
end = pointsLength - 1;
}
if (!loop) {
// Add cap
let dPos = p1.sub(p0);
dPos.normalizeSelf();
let dx = dPos.x;
let dy = dPos.y;
if (lineCap === LineCap.BUTT)
this._buttCap(p0, dx, dy, w, 0);
else if (lineCap === LineCap.SQUARE)
this._buttCap(p0, dx, dy, w, w);
else if (lineCap === LineCap.ROUND)
this._roundCapStart(p0, dx, dy, w, ncap);
}
for (let j = start; j < end; ++j) {
if (lineJoin === LineJoin.ROUND) {
this._roundJoin(p0, p1, w, w, ncap);
}
else if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) {
this._bevelJoin(p0, p1, w, w);
}
else {
this._vset(p1.x + p1.dmx * w, p1.y + p1.dmy * w);
this._vset(p1.x - p1.dmx * w, p1.y - p1.dmy * w);
}
p0 = p1;
p1 = pts[j + 1];
}
if (loop) {
// Loop it
let vDataoOfset = offset * 3;
this._vset(vData[vDataoOfset], vData[vDataoOfset+1]);
this._vset(vData[vDataoOfset+3], vData[vDataoOfset+4]);
} else {
// Add cap
let dPos = p1.sub(p0);
dPos.normalizeSelf();
let dx = dPos.x;
let dy = dPos.y;
if (lineCap === LineCap.BUTT)
this._buttCap(p1, dx, dy, w, 0);
else if (lineCap === LineCap.BUTT || lineCap === LineCap.SQUARE)
this._buttCap(p1, dx, dy, w, w);
else if (lineCap === LineCap.ROUND)
this._roundCapEnd(p1, dx, dy, w, ncap);
}
// stroke indices
let indicesOffset = meshbuffer.indiceStart;
for (let start = offset+2, end = meshbuffer.vertexStart; start < end; start++) {
iData[indicesOffset++] = start - 2;
iData[indicesOffset++] = start - 1;
iData[indicesOffset++] = start;
}
meshbuffer.indiceStart = indicesOffset;
}
_renderData = null;
_impl = null;
},
_expandFill (graphics) {
_impl = graphics._impl;
let paths = _impl._paths;
// Calculate max vertex usage.
let cverts = 0;
for (let i = _impl._pathOffset, l = _impl._pathLength; i < l; i++) {
let path = paths[i];
let pointsLength = path.points.length;
cverts += pointsLength;
}
let renderData = _renderData = this.genRenderData(graphics, cverts),
meshbuffer = renderData.meshbuffer,
vData = meshbuffer._vData,
iData = meshbuffer._iData;
for (let i = _impl._pathOffset, l = _impl._pathLength; i < l; i++) {
let path = paths[i];
let pts = path.points;
let pointsLength = pts.length;
if (pointsLength === 0) {
continue;
}
// Calculate shape vertices.
let offset = meshbuffer.vertexStart;
for (let j = 0; j < pointsLength; ++j) {
this._vset(pts[j].x, pts[j].y);
}
let indicesOffset = meshbuffer.indiceStart;
if (path.complex) {
let earcutData = [];
for (let j = offset, end = meshbuffer.vertexStart; j < end; j++) {
let vDataOffset = j * 3;
earcutData.push(vData[vDataOffset]);
earcutData.push(vData[vDataOffset+1]);
}
let newIndices = Earcut(earcutData, null, 2);
if (!newIndices || newIndices.length === 0) {
continue;
}
for (let j = 0, nIndices = newIndices.length; j < nIndices; j++) {
iData[indicesOffset++] = newIndices[j] + offset;
}
}
else {
let first = offset;
for (let start = offset+2, end = meshbuffer.vertexStart; start < end; start++) {
iData[indicesOffset++] = first;
iData[indicesOffset++] = start - 1;
iData[indicesOffset++] = start;
}
}
meshbuffer.indiceStart = indicesOffset;
}
_renderData = null;
_impl = null;
},
_calculateJoins (impl, w, lineJoin, miterLimit) {
let iw = 0.0;
if (w > 0.0) {
iw = 1 / w;
}
// Calculate which joins needs extra vertices to append, and gather vertex count.
let paths = impl._paths;
for (let i = impl._pathOffset, l = impl._pathLength; i < l; i++) {
let path = paths[i];
let pts = path.points;
let ptsLength = pts.length;
let p0 = pts[ptsLength - 1];
let p1 = pts[0];
let nleft = 0;
path.nbevel = 0;
for (let j = 0; j < ptsLength; j++) {
let dmr2, cross, limit;
// perp normals
let dlx0 = p0.dy;
let dly0 = -p0.dx;
let dlx1 = p1.dy;
let dly1 = -p1.dx;
// Calculate extrusions
p1.dmx = (dlx0 + dlx1) * 0.5;
p1.dmy = (dly0 + dly1) * 0.5;
dmr2 = p1.dmx * p1.dmx + p1.dmy * p1.dmy;
if (dmr2 > 0.000001) {
let scale = 1 / dmr2;
if (scale > 600) {
scale = 600;
}
p1.dmx *= scale;
p1.dmy *= scale;
}
// Keep track of left turns.
cross = p1.dx * p0.dy - p0.dx * p1.dy;
if (cross > 0) {
nleft++;
p1.flags |= PointFlags.PT_LEFT;
}
// Calculate if we should use bevel or miter for inner join.
limit = max(11, min(p0.len, p1.len) * iw);
if (dmr2 * limit * limit < 1) {
p1.flags |= PointFlags.PT_INNERBEVEL;
}
// Check to see if the corner needs to be beveled.
if (p1.flags & PointFlags.PT_CORNER) {
if (dmr2 * miterLimit * miterLimit < 1 || lineJoin === LineJoin.BEVEL || lineJoin === LineJoin.ROUND) {
p1.flags |= PointFlags.PT_BEVEL;
}
}
if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) {
path.nbevel++;
}
p0 = p1;
p1 = pts[j + 1];
}
}
},
_flattenPaths (impl) {
let paths = impl._paths;
for (let i = impl._pathOffset, l = impl._pathLength; i < l; i++) {
let path = paths[i];
let pts = path.points;
let p0 = pts[pts.length - 1];
let p1 = pts[0];
if (p0.equals(p1)) {
path.closed = true;
pts.pop();
p0 = pts[pts.length - 1];
}
for (let j = 0, size = pts.length; j < size; j++) {
// Calculate segment direction and length
let dPos = p1.sub(p0);
p0.len = dPos.mag();
if (dPos.x || dPos.y)
dPos.normalizeSelf();
p0.dx = dPos.x;
p0.dy = dPos.y;
// Advance
p0 = p1;
p1 = pts[j + 1];
}
}
},
_chooseBevel (bevel, p0, p1, w) {
let x = p1.x;
let y = p1.y;
let x0, y0, x1, y1;
if (bevel !== 0) {
x0 = x + p0.dy * w;
y0 = y - p0.dx * w;
x1 = x + p1.dy * w;
y1 = y - p1.dx * w;
} else {
x0 = x1 = x + p1.dmx * w;
y0 = y1 = y + p1.dmy * w;
}
return [x0, y0, x1, y1];
},
_buttCap (p, dx, dy, w, d) {
let px = p.x - dx * d;
let py = p.y - dy * d;
let dlx = dy;
let dly = -dx;
this._vset(px + dlx * w, py + dly * w);
this._vset(px - dlx * w, py - dly * w);
},
_roundCapStart (p, dx, dy, w, ncap) {
let px = p.x;
let py = p.y;
let dlx = dy;
let dly = -dx;
for (let i = 0; i < ncap; i++) {
let a = i / (ncap - 1) * PI;
let ax = cos(a) * w,
ay = sin(a) * w;
this._vset(px - dlx * ax - dx * ay, py - dly * ax - dy * ay);
this._vset(px, py);
}
this._vset(px + dlx * w, py + dly * w);
this._vset(px - dlx * w, py - dly * w);
},
_roundCapEnd (p, dx, dy, w, ncap) {
let px = p.x;
let py = p.y;
let dlx = dy;
let dly = -dx;
this._vset(px + dlx * w, py + dly * w);
this._vset(px - dlx * w, py - dly * w);
for (let i = 0; i < ncap; i++) {
let a = i / (ncap - 1) * PI;
let ax = cos(a) * w,
ay = sin(a) * w;
this._vset(px, py);
this._vset(px - dlx * ax + dx * ay, py - dly * ax + dy * ay);
}
},
_roundJoin (p0, p1, lw, rw, ncap) {
let dlx0 = p0.dy;
let dly0 = -p0.dx;
let dlx1 = p1.dy;
let dly1 = -p1.dx;
let p1x = p1.x;
let p1y = p1.y;
if ((p1.flags & PointFlags.PT_LEFT) !== 0) {
let out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw);
let lx0 = out[0];
let ly0 = out[1];
let lx1 = out[2];
let ly1 = out[3];
let a0 = atan2(-dly0, -dlx0);
let a1 = atan2(-dly1, -dlx1);
if (a1 > a0) a1 -= PI * 2;
this._vset(lx0, ly0);
this._vset(p1x - dlx0 * rw, p1.y - dly0 * rw);
let n = clamp(ceil((a0 - a1) / PI) * ncap, 2, ncap);
for (let i = 0; i < n; i++) {
let u = i / (n - 1);
let a = a0 + u * (a1 - a0);
let rx = p1x + cos(a) * rw;
let ry = p1y + sin(a) * rw;
this._vset(p1x, p1y);
this._vset(rx, ry);
}
this._vset(lx1, ly1);
this._vset(p1x - dlx1 * rw, p1y - dly1 * rw);
} else {
let out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw);
let rx0 = out[0];
let ry0 = out[1];
let rx1 = out[2];
let ry1 = out[3];
let a0 = atan2(dly0, dlx0);
let a1 = atan2(dly1, dlx1);
if (a1 < a0) a1 += PI * 2;
this._vset(p1x + dlx0 * rw, p1y + dly0 * rw);
this._vset(rx0, ry0);
let n = clamp(ceil((a1 - a0) / PI) * ncap, 2, ncap);
for (let i = 0; i < n; i++) {
let u = i / (n - 1);
let a = a0 + u * (a1 - a0);
let lx = p1x + cos(a) * lw;
let ly = p1y + sin(a) * lw;
this._vset(lx, ly);
this._vset(p1x, p1y);
}
this._vset(p1x + dlx1 * rw, p1y + dly1 * rw);
this._vset(rx1, ry1);
}
},
_bevelJoin (p0, p1, lw, rw) {
let rx0, ry0, rx1, ry1;
let lx0, ly0, lx1, ly1;
let dlx0 = p0.dy;
let dly0 = -p0.dx;
let dlx1 = p1.dy;
let dly1 = -p1.dx;
if (p1.flags & PointFlags.PT_LEFT) {
let out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw);
lx0 = out[0];
ly0 = out[1];
lx1 = out[2];
ly1 = out[3];
this._vset(lx0, ly0);
this._vset(p1.x - dlx0 * rw, p1.y - dly0 * rw);
this._vset(lx1, ly1);
this._vset(p1.x - dlx1 * rw, p1.y - dly1 * rw);
} else {
let out = this._chooseBevel(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw);
rx0 = out[0];
ry0 = out[1];
rx1 = out[2];
ry1 = out[3];
this._vset(p1.x + dlx0 * lw, p1.y + dly0 * lw);
this._vset(rx0, ry0);
this._vset(p1.x + dlx1 * lw, p1.y + dly1 * lw);
this._vset(rx1, ry1);
}
},
_vset (x, y) {
let meshbuffer = _renderData.meshbuffer;
let dataOffset = meshbuffer.vertexStart * 3;
let vData = meshbuffer._vData;
let uintVData = meshbuffer._uintVData;
vData[dataOffset] = x;
vData[dataOffset+1] = y;
uintVData[dataOffset+2] = _curColor;
meshbuffer.vertexStart ++;
meshbuffer._dirty = true;
}
};
Graphics._assembler = graphicsAssembler;
module.exports = graphicsAssembler;
+7 -1
View File
@@ -158,11 +158,17 @@ class BuiltinResMgr {
// sprite material
const spriteMtl = new cc.Material();
spriteMtl._uuid = 'sprite-material';
spriteMtl._uuid = 'ui-sprite-material';
spriteMtl.initialize({ effectName: 'builtin-sprite' });
spriteMtl.setProperty('mainTexture', defaultTexture);
resources[spriteMtl._uuid] = spriteMtl;
// ui base material
const baseMtl = new cc.Material();
baseMtl._uuid = 'ui-base-material';
baseMtl.initialize({ effectName: 'builtin-base' });
resources[baseMtl._uuid] = baseMtl;
// default particle material
const defaultParticleMtl = new cc.Material();
defaultParticleMtl._uuid = 'default-particle-material';
+16 -16
View File
@@ -14,22 +14,6 @@ export default class Pool<T> {
}
}
private _expand (size: number) {
const old = this._frees;
this._frees = new Array(size);
const len = size - old.length;
for (let i = 0; i < len; ++i) {
this._frees[i] = this._fn();
}
for (let i = len, j = 0; i < size; ++i, ++j) {
this._frees[i] = old[j];
}
this._idx += len;
}
public alloc (): T {
// create some more space (expand by 20%, minimum 1)
if (this._idx < 0) {
@@ -57,4 +41,20 @@ export default class Pool<T> {
this._frees.splice(0);
this._idx = -1;
}
private _expand (size: number) {
const old = this._frees;
this._frees = new Array(size);
const len = size - old.length;
for (let i = 0; i < len; ++i) {
this._frees[i] = this._fn();
}
for (let i = len, j = 0; i < size; ++i, ++j) {
this._frees[i] = old[j];
}
this._idx += len;
}
}
+9 -16
View File
@@ -23,25 +23,18 @@
THE SOFTWARE.
****************************************************************************/
import { SpriteFrame } from '../../../assets/CCSpriteFrame';
import { Rect } from '../../../core/value-types';
import { RenderData } from '../../../renderer/ui/renderData';
import { UI } from '../../../renderer/ui/ui';
// import { SpriteFrame } from '../../../assets/CCSpriteFrame';
// import { Rect } from '../../../core/value-types';
// import { IARenderData, RenderData } from '../../../renderer/ui/renderData';
// import { UI } from '../../../renderer/ui/ui';
// import { GraphicsComponent } from '../components/graphics-component';
import { UIRenderComponent } from '../components/ui-render-component';
import { ISharedLabelData } from './label/ttfUtils';
// import { LineJoin } from './graphics/types';
// import { Impl, Point } from './graphics/webgl/impl';
// import { ISharedLabelData } from './label/ttfUtils';
export interface IAssembler {
useModel?: boolean;
fillBuffers (component: UIRenderComponent, render: UI): void;
updateRenderData? (component: UIRenderComponent): void;
createData? (component: UIRenderComponent): RenderData;
updateVerts? (component: UIRenderComponent, start?: number, end?: number): void;
updateWorldVerts? (component: UIRenderComponent): void;
updateUVs? (component: UIRenderComponent, start?: number, end?: number);
getAssemblerData? (): ISharedLabelData;
resetAssemblerData? (assemblerData: ISharedLabelData): void;
appendQuad? (renderData: RenderData, texture: SpriteFrame, rect: Rect, rotated: boolean, x: number, y: number, scale: number): void;
[key: string]: any;
}
export interface IAssemblerManager {
@@ -23,25 +23,38 @@
THE SOFTWARE.
****************************************************************************/
const PointFlags = require('./types').PointFlags;
import { PointFlags } from './types';
import { Impl } from './webgl/impl';
var PI = Math.PI;
var min = Math.min;
var max = Math.max;
var cos = Math.cos;
var sin = Math.sin;
var abs = Math.abs;
var sign = Math.sign;
const PI = Math.PI;
const min = Math.min;
const max = Math.max;
const cos = Math.cos;
const sin = Math.sin;
const abs = Math.abs;
const sign = Math.sign;
var KAPPA90 = 0.5522847493;
const KAPPA90 = 0.5522847493;
function arc (ctx, cx, cy, r, startAngle, endAngle, counterclockwise) {
export function arc (ctx: Impl, cx: number, cy: number, r: number, startAngle: number, endAngle: number, counterclockwise: boolean) {
counterclockwise = counterclockwise || false;
var a = 0, da = 0, hda = 0, kappa = 0;
var dx = 0, dy = 0, x = 0, y = 0, tanx = 0, tany = 0;
var px = 0, py = 0, ptanx = 0, ptany = 0;
var i, ndivs;
let a = 0;
let da = 0;
let hda = 0;
let kappa = 0;
let dx = 0;
let dy = 0;
let x = 0;
let y = 0;
let tanx = 0;
let tany = 0;
let px = 0;
let py = 0;
let ptanx = 0;
let ptany = 0;
let i = 0;
let ndivs = 0;
// Clamp angles
da = endAngle - startAngle;
@@ -49,13 +62,13 @@ function arc (ctx, cx, cy, r, startAngle, endAngle, counterclockwise) {
if (abs(da) >= PI * 2) {
da = PI * 2;
} else {
while (da < 0) da += PI * 2;
while (da < 0) { da += PI * 2; }
}
} else {
if (abs(da) >= PI * 2) {
da = -PI * 2;
} else {
while (da > 0) da -= PI * 2;
while (da > 0) { da -= PI * 2; }
}
}
@@ -64,7 +77,7 @@ function arc (ctx, cx, cy, r, startAngle, endAngle, counterclockwise) {
hda = da / ndivs / 2.0;
kappa = abs(4.0 / 3.0 * (1 - cos(hda)) / sin(hda));
if (!counterclockwise) kappa = -kappa;
if (!counterclockwise) { kappa = -kappa; }
for (i = 0; i <= ndivs; i++) {
a = startAngle + da * (i / ndivs);
@@ -87,7 +100,7 @@ function arc (ctx, cx, cy, r, startAngle, endAngle, counterclockwise) {
}
}
function ellipse (ctx, cx, cy, rx, ry) {
export function ellipse (ctx: Impl, cx: number, cy: number, rx: number, ry: number) {
ctx.moveTo(cx - rx, cy);
ctx.bezierCurveTo(cx - rx, cy + ry * KAPPA90, cx - rx * KAPPA90, cy + ry, cx, cy + ry);
ctx.bezierCurveTo(cx + rx * KAPPA90, cy + ry, cx + rx, cy + ry * KAPPA90, cx + rx, cy);
@@ -96,13 +109,13 @@ function ellipse (ctx, cx, cy, rx, ry) {
ctx.close();
}
function roundRect (ctx, x, y, w, h, r) {
export function roundRect (ctx: Impl, x: number, y: number, w: number, h: number, r: number) {
if (r < 0.1) {
ctx.rect(x, y, w, h);
return;
} else {
var rx = min(r, abs(w) * 0.5) * sign(w),
ry = min(r, abs(h) * 0.5) * sign(h);
const rx = min(r, abs(w) * 0.5) * sign(w);
const ry = min(r, abs(h) * 0.5) * sign(h);
ctx.moveTo(x, y + ry);
ctx.lineTo(x, y + h - ry);
@@ -117,11 +130,33 @@ function roundRect (ctx, x, y, w, h, r) {
}
}
function tesselateBezier (ctx, x1, y1, x2, y2, x3, y3, x4, y4, level, type) {
var x12, y12, x23, y23, x34, y34, x123, y123, x234, y234, x1234, y1234;
var dx, dy, d2, d3;
export function tesselateBezier (
ctx: Impl, x1: number, y1: number,
x2: number, y2: number,
x3: number, y3: number,
x4: number, y4: number,
level: number, type: number,
) {
let x12 = 0;
let y12 = 0;
let x23 = 0;
let y23 = 0;
let x34 = 0;
let y34 = 0;
let x123 = 0;
let y123 = 0;
let x234 = 0;
let y234 = 0;
let x1234 = 0;
let y1234 = 0;
let dx = 0;
let dy = 0;
let d2 = 0;
let d3 = 0;
if (level > 10) return;
if (level > 10) {
return;
}
x12 = (x1 + x2) * 0.5;
y12 = (y1 + y2) * 0.5;
@@ -137,8 +172,8 @@ function tesselateBezier (ctx, x1, y1, x2, y2, x3, y3, x4, y4, level, type) {
d2 = abs((x2 - x4) * dy - (y2 - y4) * dx);
d3 = abs((x3 - x4) * dy - (y3 - y4) * dx);
if ((d2 + d3) * (d2 + d3) < ctx._tessTol * (dx * dx + dy * dy)) {
ctx._addPoint(x4, y4, type === 0 ? type | PointFlags.PT_BEVEL : type);
if ((d2 + d3) * (d2 + d3) < ctx.tessTol * (dx * dx + dy * dy)) {
ctx.addPoint(x4, y4, type === 0 ? type | PointFlags.PT_BEVEL : type);
return;
}
@@ -150,10 +185,3 @@ function tesselateBezier (ctx, x1, y1, x2, y2, x3, y3, x4, y4, level, type) {
tesselateBezier(ctx, x1, y1, x12, y12, x123, y123, x1234, y1234, level + 1, 0);
tesselateBezier(ctx, x1234, y1234, x234, y234, x34, y34, x4, y4, level + 1, type);
}
module.exports = {
arc: arc,
ellipse: ellipse,
roundRect: roundRect,
tesselateBezier: tesselateBezier
};
@@ -26,4 +26,4 @@
'use strict';
require('./graphics');
// import './graphics-component';
@@ -23,76 +23,75 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
'use strict';
import { ccenum } from '../../../../core/value-types/enum';
/**
* !#en Enum for LineCap.
* !#zh 线段末端属性
* @enum Graphics.LineCap
*/
var LineCap = cc.Enum({
export enum LineCap {
/**
* !#en The ends of lines are squared off at the endpoints.
* !#zh 线段末端以方形结束。
* @property {Number} BUTT
*/
BUTT: 0,
BUTT = 0,
/**
* !#en The ends of lines are rounded.
* !#zh 线段末端以圆形结束。
* @property {Number} ROUND
*/
ROUND: 1,
ROUND = 1,
/**
* !#en The ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness.
* !#zh 线段末端以方形结束,但是增加了一个宽度和线段相同,高度是线段厚度一半的矩形区域。
* @property {Number} SQUARE
*/
SQUARE: 2,
});
SQUARE = 2,
}
ccenum(LineCap);
/**
* !#en Enum for LineJoin.
* !#zh 线段拐角属性
* @enum Graphics.LineJoin
*/
var LineJoin = cc.Enum({
export enum LineJoin {
/**
* !#en Fills an additional triangular area between the common endpoint of connected segments, and the separate outside rectangular corners of each segment.
* !#zh 在相连部分的末端填充一个额外的以三角形为底的区域, 每个部分都有各自独立的矩形拐角。
* @property {Number} BEVEL
*/
BEVEL: 0,
BEVEL = 0,
/**
* !#en Rounds off the corners of a shape by filling an additional sector of disc centered at the common endpoint of connected segments. The radius for these rounded corners is equal to the line width.
* !#zh 通过填充一个额外的,圆心在相连部分末端的扇形,绘制拐角的形状。 圆角的半径是线段的宽度。
* @property {Number} ROUND
*/
ROUND: 1,
ROUND = 1,
/**
* !#en Connected segments are joined by extending their outside edges to connect at a single point, with the effect of filling an additional lozenge-shaped area.
* !#zh 通过延伸相连部分的外边缘,使其相交于一点,形成一个额外的菱形区域。
* @property {Number} MITER
*/
MITER: 2
});
MITER = 2,
}
ccenum(LineJoin);
// PointFlags
var PointFlags = cc.Enum({
PT_CORNER: 0x01,
PT_LEFT: 0x02,
PT_BEVEL: 0x04,
PT_INNERBEVEL: 0x08,
});
export enum PointFlags {
PT_CORNER = 0x01,
PT_LEFT = 0x02,
PT_BEVEL = 0x04,
PT_INNERBEVEL = 0x08,
}
module.exports = {
LineCap: LineCap,
LineJoin: LineJoin,
PointFlags: PointFlags
};
ccenum(PointFlags);
@@ -0,0 +1,744 @@
/****************************************************************************
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.
****************************************************************************/
'use strict';
class Aim {
// vertice index in coordinates array
public i: number;
// vertex coordinates
public x: number;
public y: number;
// previous and next vertice nodes in a polygon ring
public prev: Aim | null = null;
public next: Aim | null = null;
// z-order curve value
// public z = null;
public z = 0;
// previous and next nodes in z-order
public prevZ: Aim | null = null;
public nextZ: Aim | null = null;
// indicates whether this is a steiner point
public steiner = false;
constructor (i: number, x: number, y: number) {
this.i = i;
this.x = x;
this.y = y;
}
}
// create a circular doubly linked list from polygon points in the specified winding order
function linkedList (datas: number[], start: number, end: number, dim: number, clockwise: boolean) {
let i = 0;
let last: Aim | null = null;
if (clockwise === (signedArea(datas, start, end, dim) > 0)) {
for (i = start; i < end; i += dim) {
last = insertNode(i, datas[i], datas[i + 1], last);
}
} else {
for (i = end - dim; i >= start; i -= dim) {
last = insertNode(i, datas[i], datas[i + 1], last);
}
}
if (last && equals(last, last.next!)) {
removeNode(last);
last = last.next;
}
return last;
}
// eliminate colinear or duplicate points
function filterPoints (start: Aim | null, end: Aim | null = null) {
if (!start) {
return start;
}
if (!end) {
end = start;
}
let p = start;
let again: boolean = false;
do {
again = false;
if (!p.steiner && (equals(p, p.next!) || area(p.prev!, p, p.next!) === 0)) {
removeNode(p);
p = end = p.prev!;
if (p === p.next) {
return null;
}
again = true;
} else {
p = p.next!;
}
} while (again || p !== end);
return end;
}
// main ear slicing loop which triangulates a polygon (given as a linked list)
function earcutLinked (ear: Aim | null, triangles: number[], dim: number, minX: number, minY: number, size: number, pass: number = 0) {
if (!ear) {
return;
}
// interlink polygon nodes in z-order
if (!pass && size) {
indexCurve(ear, minX, minY, size);
}
let stop: Aim | null = ear;
let prev: Aim | null = null;
let next: Aim | null = null;
// iterate through ears, slicing them one by one
while (ear!.prev !== ear!.next) {
prev = ear!.prev!;
next = ear!.next!;
if (size ? isEarHashed(ear!, minX, minY, size) : isEar(ear!)) {
// cut off the triangle
triangles.push(prev.i / dim);
triangles.push(ear!.i / dim);
triangles.push(next.i / dim);
removeNode(ear!);
// skipping the next vertice leads to less sliver triangles
ear = next.next;
stop = next.next;
continue;
}
ear = next;
// if we looped through the whole remaining polygon and can't find any more ears
if (ear === stop) {
// try filtering points and slicing again
if (!pass) {
earcutLinked(filterPoints(ear), triangles, dim, minX, minY, size, 1);
// if this didn't work, try curing all small self-intersections locally
} else if (pass === 1) {
ear = cureLocalIntersections(ear, triangles, dim);
earcutLinked(ear, triangles, dim, minX, minY, size, 2);
// as a last resort, try splitting the remaining polygon into two
} else if (pass === 2) {
splitEarcut(ear, triangles, dim, minX, minY, size);
}
break;
}
}
}
// check whether a polygon node forms a valid ear with adjacent nodes
function isEar (ear: Aim) {
const a = ear.prev!;
const b = ear;
const c = ear.next!;
if (area(a, b, c) >= 0) { return false; } // reflex, can't be an ear
// now make sure we don't have other points inside the potential ear
let p = ear.next!.next!;
while (p !== ear.prev) {
if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
area(p.prev!, p, p.next!) >= 0) { return false; }
p = p.next!;
}
return true;
}
function isEarHashed (ear: Aim, minX: number, minY: number, size) {
const a = ear.prev!;
const b = ear;
const c = ear.next!;
if (area(a, b, c) >= 0) { return false; } // reflex, can't be an ear
// triangle bbox; min & max are calculated like this for speed
const minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x);
const minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y);
const maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x);
const maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
// z-order range for the current triangle bbox;
const minZ = zOrder(minTX, minTY, minX, minY, size);
const maxZ = zOrder(maxTX, maxTY, minX, minY, size);
// first look for points inside the triangle in increasing z-order
let p = ear.nextZ;
while (p && p.z <= maxZ) {
if (p !== ear.prev && p !== ear.next &&
pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
area(p.prev!, p, p.next!) >= 0) { return false; }
p = p.nextZ;
}
// then look for points in decreasing z-order
p = ear.prevZ;
while (p && p.z >= minZ) {
if (p !== ear.prev && p !== ear.next &&
pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
area(p.prev!, p, p.next!) >= 0) {
return false;
}
p = p.prevZ;
}
return true;
}
// go through all polygon nodes and cure small local self-intersections
function cureLocalIntersections (start: Aim, triangles: number[], dim: number) {
let p = start;
do {
const a = p.prev!;
const b = p.next!.next!;
if (!equals(a, b) && intersects(a, p, p.next!, b) && locallyInside(a, b) && locallyInside(b, a)) {
triangles.push(a.i / dim);
triangles.push(p.i / dim);
triangles.push(b.i / dim);
// remove two nodes involved
removeNode(p);
removeNode(p.next!);
p = start = b;
}
p = p.next!;
} while (p !== start);
return p;
}
// try splitting polygon into two and triangulate them independently
function splitEarcut (start: Aim | null, triangles: number[], dim: number, minX: number, minY: number, size: number) {
// look for a valid diagonal that divides the polygon into two
let a = start!;
do {
let b = a.next!.next;
while (b !== a.prev) {
if (a.i !== b!.i && isValidDiagonal(a, b!)) {
// split the polygon in two by the diagonal
let c = splitPolygon(a, b!);
// filter colinear points around the cuts
a = filterPoints(a, a.next)!;
c = filterPoints(c, c.next!)!;
// run earcut on each half
earcutLinked(a, triangles, dim, minX, minY, size);
earcutLinked(c, triangles, dim, minX, minY, size);
return;
}
b = b!.next;
}
a = a!.next!;
} while (a !== start);
}
// link every hole into the outer loop, producing a single-ring polygon without holes
function eliminateHoles (datas: number[], holeIndices: number[], outerNode: Aim | null, dim: number) {
const queue: Aim[] = [];
let i = 0;
let len = 0;
let start = 0;
let end = 0;
let list: Aim | null = null;
for (i = 0, len = holeIndices.length; i < len; i++) {
start = holeIndices[i] * dim;
end = i < len - 1 ? holeIndices[i + 1] * dim : datas.length;
list = linkedList(datas, start, end, dim, false);
if (!list){
continue;
}
if (list === list.next) {
list.steiner = true;
}
queue.push(getLeftmost(list));
}
queue.sort(compareX);
if (!outerNode){
return outerNode;
}
// process holes from left to right
for (i = 0; i < queue.length; i++) {
eliminateHole(queue[i], outerNode);
outerNode = filterPoints(outerNode, outerNode!.next);
}
return outerNode;
}
function compareX (a, b) {
return a.x - b.x;
}
// find a bridge between vertices that connects hole with an outer ring and and link it
function eliminateHole (hole: Aim, outerNode: Aim | null) {
outerNode = findHoleBridge(hole, outerNode!);
if (outerNode) {
const b = splitPolygon(outerNode, hole);
filterPoints(b, b.next!);
}
}
// David Eberly's algorithm for finding a bridge between hole and outer polygon
function findHoleBridge (hole: Aim, outerNode: Aim) {
let p = outerNode;
const hx = hole.x;
const hy = hole.y;
let qx = -Infinity;
let m: Aim | null = null;
// find a segment intersected by a ray from the hole's leftmost point to the left;
// segment's endpoint with lesser x will be potential connection point
do {
if (hy <= p.y && hy >= p.next!.y) {
const x = p.x + (hy - p.y) * (p.next!.x - p.x) / (p.next!.y - p.y);
if (x <= hx && x > qx) {
qx = x;
if (x === hx) {
if (hy === p.y) { return p; }
if (hy === p.next!.y) { return p.next; }
}
m = p.x < p.next!.x ? p : p.next!;
}
}
p = p.next!;
} while (p !== outerNode);
if (!m) {
return null;
}
if (hx === qx) {
return m.prev;
} // hole touches outer segment; pick lower endpoint
// look for points inside the triangle of hole point, segment intersection and endpoint;
// if there are no points found, we have a valid connection;
// otherwise choose the point of the minimum angle with the ray as connection point
const stop = m;
const mx = m.x;
const my = m.y;
let tanMin = Infinity;
let tan;
p = m.next!;
while (p !== stop) {
if (hx >= p.x && p.x >= mx &&
pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
m = p;
tanMin = tan;
}
}
p = p.next!;
}
return m;
}
// interlink polygon nodes in z-order
function indexCurve (start: Aim, minX: number, minY: number, size: number) {
let p = start;
do {
if (p.z === null) {
p.z = zOrder(p.x, p.y, minX, minY, size);
}
p.prevZ = p.prev;
p.nextZ = p.next;
p = p.next!;
} while (p !== start);
p.prevZ!.nextZ = null;
p.prevZ = null;
sortLinked(p);
}
// Simon Tatham's linked list merge sort algorithm
// http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
function sortLinked (list: Aim | null) {
let i = 0;
let p: Aim | null = null;
let q: Aim | null = null;
let e: Aim | null = null;
let tail: Aim | null = null;
let numMerges = 0;
let pSize = 0;
let qSize = 0;
let inSize = 1;
do {
p = list;
list = null;
tail = null;
numMerges = 0;
while (p) {
numMerges++;
q = p;
pSize = 0;
for (i = 0; i < inSize; i++) {
pSize++;
q = q.nextZ;
if (!q) { break; }
}
qSize = inSize;
while (pSize > 0 || (qSize > 0 && q)) {
if (pSize === 0) {
e = q;
q = q!.nextZ;
qSize--;
} else if (qSize === 0 || !q) {
e = p;
p = p!.nextZ;
pSize--;
} else if (p!.z <= q.z) {
e = p;
p = p!.nextZ;
pSize--;
} else {
e = q;
q = q.nextZ;
qSize--;
}
if (tail) { tail.nextZ = e; }
else { list = e; }
e!.prevZ = tail;
tail = e;
}
p = q;
}
tail!.nextZ = null;
inSize *= 2;
} while (numMerges > 1);
return list;
}
// z-order of a point given coords and size of the data bounding box
function zOrder (x: number, y: number, minX: number, minY: number, size: number) {
// coords are transformed into non-negative 15-bit integer range
x = 32767 * (x - minX) / size;
y = 32767 * (y - minY) / size;
x = (x | (x << 8)) & 0x00FF00FF;
x = (x | (x << 4)) & 0x0F0F0F0F;
x = (x | (x << 2)) & 0x33333333;
x = (x | (x << 1)) & 0x55555555;
y = (y | (y << 8)) & 0x00FF00FF;
y = (y | (y << 4)) & 0x0F0F0F0F;
y = (y | (y << 2)) & 0x33333333;
y = (y | (y << 1)) & 0x55555555;
return x | (y << 1);
}
// find the leftmost node of a polygon ring
function getLeftmost (start: Aim) {
let p = start;
let leftmost = start;
do {
if (p.x < leftmost.x) {
leftmost = p;
}
p = p.next!;
} while (p !== start);
return leftmost;
}
// check if a point lies within a convex triangle
function pointInTriangle (ax: number, ay: number, bx: number, by: number, cx: number, cy: number, px: number, py: number) {
return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
(ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
(bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
}
// check if a diagonal between two polygon nodes is valid (lies in polygon interior)
function isValidDiagonal (a: Aim, b: Aim) {
return a.next!.i !== b.i && a.prev!.i !== b.i && !intersectsPolygon(a, b) &&
locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b);
}
// signed area of a triangle
function area (p: Aim, q: Aim, r: Aim) {
return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
}
// check if two points are equal
function equals (p1: Aim, p2: Aim) {
return p1.x === p2.x && p1.y === p2.y;
}
// check if two segments intersect
function intersects (p1: Aim, q1: Aim, p2: Aim, q2: Aim) {
if ((equals(p1, q1) && equals(p2, q2)) ||
(equals(p1, q2) && equals(p2, q1))) {
return true;
}
return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
}
// check if a polygon diagonal intersects any polygon segments
function intersectsPolygon (a: Aim, b: Aim) {
let p = a;
do {
if (p.i !== a.i && p.next!.i !== a.i && p.i !== b.i && p.next!.i !== b.i &&
intersects(p, p.next!, a, b)) { return true; }
p = p.next!;
} while (p !== a);
return false;
}
// check if a polygon diagonal is locally inside the polygon
function locallyInside (a: Aim, b: Aim) {
return area(a.prev!, a, a.next!) < 0 ?
area(a, b, a.next!) >= 0 && area(a, a.prev!, b) >= 0 :
area(a, b, a.prev!) < 0 || area(a, a.next!, b) < 0;
}
// check if the middle point of a polygon diagonal is inside the polygon
function middleInside (a: Aim, b: Aim) {
let p = a;
let inside = false;
const px = (a.x + b.x) / 2;
const py = (a.y + b.y) / 2;
do {
if (((p.y > py) !== (p.next!.y > py)) && (px < (p.next!.x - p.x) * (py - p.y) / (p.next!.y - p.y) + p.x)) {
inside = !inside;
}
p = p.next!;
} while (p !== a);
return inside;
}
// link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
// if one belongs to the outer ring and another to a hole, it merges it into a single ring
function splitPolygon (a: Aim, b: Aim) {
const a2 = new Aim(a.i, a.x, a.y);
const b2 = new Aim(b.i, b.x, b.y);
const an = a.next!;
const bp = b.prev!;
a.next = b;
b.prev = a;
a2.next = an;
an.prev = a2;
b2.next = a2;
a2.prev = b2;
bp.next = b2;
b2.prev = bp;
return b2;
}
// create a node and optionally link it with previous one (in a circular doubly linked list)
function insertNode (i: number, x: number, y: number, last: Aim | null) {
const p = new Aim(i, x, y);
if (!last) {
p.prev = p;
p.next = p;
} else {
p.next = last.next;
p.prev = last;
last.next!.prev = p;
last.next = p;
}
return p;
}
function removeNode (p: Aim) {
p.next!.prev = p.prev;
p.prev!.next = p.next;
if (p.prevZ) {
p.prevZ.nextZ = p.nextZ;
}
if (p.nextZ) {
p.nextZ.prevZ = p.prevZ;
}
}
function signedArea (datas: number[], start: number, end: number, dim: number) {
let sum = 0;
for (let i = start, j = end - dim; i < end; i += dim) {
sum += (datas[j] - datas[i]) * (datas[i + 1] + datas[j + 1]);
j = i;
}
return sum;
}
export function earcut (datas: number[], holeIndices: number[] | null, dim: number) {
dim = dim || 3;
const hasHoles = holeIndices ? holeIndices.length : 0;
const outerLen = hasHoles ? holeIndices![0] * dim : datas.length;
let outerNode = linkedList(datas, 0, outerLen, dim, true);
const triangles = [];
if (!outerNode) {
return triangles;
}
let minX = 0;
let minY = 0;
let maxX = 0;
let maxY = 0;
let x = 0;
let y = 0;
let size = 0;
if (hasHoles) {
outerNode = eliminateHoles(datas, holeIndices!, outerNode, dim);
}
// if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
if (datas.length > 80 * dim) {
minX = maxX = datas[0];
minY = maxY = datas[1];
for (let i = dim; i < outerLen; i += dim) {
x = datas[i];
y = datas[i + 1];
if (x < minX) { minX = x; }
if (y < minY) { minY = y; }
if (x > maxX) { maxX = x; }
if (y > maxY) { maxY = y; }
}
// minX, minY and size are later used to transform coords into integers for z-order calculation
size = Math.max(maxX - minX, maxY - minY);
}
earcutLinked(outerNode, triangles, dim, minX, minY, size);
return triangles;
}
// // return a percentage difference between the polygon area and its triangulation area;
// // used to verify correctness of triangulation
// earcut.deviation = function (data, holeIndices, dim, triangles) {
// const hasHoles = holeIndices && holeIndices.length;
// const outerLen = hasHoles ? holeIndices[0] * dim : data.length;
// let polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
// if (hasHoles) {
// for (let i = 0, len = holeIndices.length; i < len; i++) {
// const start = holeIndices[i] * dim;
// const end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
// polygonArea -= Math.abs(signedArea(data, start, end, dim));
// }
// }
// let trianglesArea = 0;
// for (i = 0; i < triangles.length; i += 3) {
// const a = triangles[i] * dim;
// const b = triangles[i + 1] * dim;
// const c = triangles[i + 2] * dim;
// trianglesArea += Math.abs(
// (data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
// (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
// }
// return polygonArea === 0 && trianglesArea === 0 ? 0 :
// Math.abs((trianglesArea - polygonArea) / polygonArea);
// };
// // turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
// earcut.flatten = function (data) {
// let dim = data[0][0].length,
// result = {vertices: [], holes: [], dimensions: dim},
// holeIndex = 0;
// for (let i = 0; i < data.length; i++) {
// for (let j = 0; j < data[i].length; j++) {
// for (let d = 0; d < dim; d++) { result.vertices.push(data[i][j][d]); }
// }
// if (i > 0) {
// holeIndex += data[i - 1].length;
// result.holes.push(holeIndex);
// }
// }
// return result;
// };
@@ -0,0 +1,725 @@
/****************************************************************************
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 { Color, Mat4, Vec3 } from '../../../../../core/value-types';
import { color4, vec3 } from '../../../../../core/vmath';
import { IARenderData } from '../../../../../renderer/ui/renderData';
import { UI } from '../../../../../renderer/ui/ui';
import { GraphicsComponent } from '../../../components/graphics-component';
import { IAssembler } from '../../assembler';
import { LineCap, LineJoin, PointFlags } from '../types';
import { earcut as Earcut } from './earcut';
import { Impl, Point } from './impl';
const MAX_VERTEX = 65535;
const MAX_INDICE = MAX_VERTEX * 2;
const PI = Math.PI;
const min = Math.min;
const max = Math.max;
const ceil = Math.ceil;
const acos = Math.acos;
const cos = Math.cos;
const sin = Math.sin;
const atan2 = Math.atan2;
const abs = Math.abs;
const attrBytes = 9;
let _renderData: IARenderData | null = null;
let _impl: Impl | null = null;
const _curColor = new Color();
const _currMatrix: Mat4 = new Mat4();
const _tempVec3 = new Vec3();
const vec3_temps: Vec3[] = [];
for (let i = 0; i < 4; i++) {
vec3_temps.push(new Vec3());
}
function curveDivs (r: number, arc: number, tol: number) {
const da = acos(r / (r + tol)) * 2.0;
return max(2, ceil(arc / da));
}
function clamp (v: number, minNum: number, maxNum: number) {
if (v < minNum) {
return minNum;
}
else if (v > maxNum) {
return maxNum;
}
return v;
}
export const graphicsAssembler: IAssembler = {
useModel: true,
createImpl (graphics: GraphicsComponent) {
return new Impl();
},
updateRenderData (graphics: GraphicsComponent) {
const datas = graphics.impl ? graphics.impl.getRenderDatas() : [];
for (let i = 0, l = datas.length; i < l; i++) {
datas[i].material = graphics.material;
}
},
fillBuffers (graphics: GraphicsComponent, renderer: UI) {
this.renderIA!(graphics, renderer);
},
renderIA (graphics: GraphicsComponent, renderer: UI) {
const impl = graphics.impl;
let renderDatas = impl && impl.getRenderDatas();
if (!renderDatas) {
renderDatas = [];
}
let bufferBatch = renderer.currBufferBatch!;
let vertexId = 0;
let byteoffset = 0;
let indicesOffset = 0;
for (const renderData of renderDatas) {
if (!graphics.material || renderData.byteCount <= 0 || renderData.indiceCount <= 0) {
continue;
}
vertexId = bufferBatch.vertexOffset;
byteoffset = bufferBatch.byteOffset;
indicesOffset = bufferBatch.indiceOffset;
bufferBatch.request(renderData.vertexCount, renderData.indiceCount);
bufferBatch = renderer.currBufferBatch!;
const vData = bufferBatch.vData!;
const iData = bufferBatch.iData!;
// the data format is strictly in accordance with pos uv color
const vDataCopy = renderData.vData.slice(0, renderData.byteCount >> 2);
vData.set(vDataCopy, byteoffset >> 2);
let iDataCopy = renderData.iData.slice(0, renderData.indiceCount);
iDataCopy = iDataCopy.map((v) => {
return v + vertexId;
});
iData.set(iDataCopy, indicesOffset);
renderer.forceMergeBatches(graphics.material, null);
}
},
getRenderData (graphics: GraphicsComponent, cverts: number) {
if (!_impl) {
return null;
}
const renderDatas = _impl.getRenderDatas();
let renderData = renderDatas[_impl.dataOffset];
if (!renderData) {
return null;
}
let meshbuffer = renderData;
const maxVertsCount = meshbuffer ? meshbuffer.vertexCount + cverts : 0;
if (maxVertsCount > MAX_VERTEX || maxVertsCount * 3 > MAX_INDICE) {
++_impl.dataOffset;
// maxVertsCount = cverts;
if (_impl.dataOffset < renderDatas.length) {
renderData = renderDatas[_impl.dataOffset];
}
else {
renderData = _impl.requestRenderData();
renderDatas[_impl.dataOffset] = renderData;
}
renderData.material = graphics.material;
meshbuffer = renderData;
}
if (meshbuffer && meshbuffer.vertexCount < maxVertsCount) {
meshbuffer.request(cverts, cverts * 3);
}
return renderData;
},
stroke (graphics: GraphicsComponent) {
color4.copy(_curColor, graphics.strokeColor);
graphics.node.getWorldMatrix(_currMatrix);
if (!graphics.impl) {
return;
}
this._flattenPaths!(graphics.impl);
this._expandStroke!(graphics);
graphics.impl.updatePathOffset = true;
},
fill (graphics: GraphicsComponent) {
color4.copy(_curColor, graphics.fillColor);
graphics.node.getWorldMatrix(_currMatrix);
this._expandFill!(graphics);
if (graphics.impl) {
graphics.impl.updatePathOffset = true;
}
},
_expandStroke (graphics: GraphicsComponent) {
const w = graphics.lineWidth * 0.5;
const lineCap = graphics.lineCap;
const lineJoin = graphics.lineJoin;
const miterLimit = graphics.miterLimit;
_impl = graphics.impl;
if (!_impl) {
return;
}
const ncap = curveDivs(w, PI, _impl.tessTol);
this._calculateJoins(_impl, w, lineJoin, miterLimit);
const paths = _impl.paths;
// Calculate max vertex usage.
let cverts = 0;
for (let i = _impl.pathOffset, l = _impl.pathLength; i < l; i++) {
const path = paths[i];
const pointsLength = path.points.length;
if (lineJoin === LineJoin.ROUND) {
cverts += (pointsLength + path.nbevel * (ncap + 2) + 1) * 2;
} // plus one for loop
else {
cverts += (pointsLength + path.nbevel * 5 + 1) * 2;
} // plus one for loop
if (!path.closed) {
// space for caps
if (lineCap === LineCap.ROUND) {
cverts += (ncap * 2 + 2) * 2;
} else {
cverts += (3 + 3) * 2;
}
}
}
const meshbuffer: IARenderData | null = _renderData = this.getRenderData!(graphics, cverts);
if (!meshbuffer) {
return;
}
const vData = meshbuffer.vData!;
const iData = meshbuffer.iData!;
for (let i = _impl.pathOffset, l = _impl.pathLength; i < l; i++) {
const path = paths[i];
const pts = path.points;
const pointsLength = pts.length;
const offset = meshbuffer.vertexStart;
let p0: Point;
let p1: Point;
let start = 0;
let end = 0;
const loop = path.closed;
if (loop) {
// Looping
p0 = pts[pointsLength - 1];
p1 = pts[0];
start = 0;
end = pointsLength;
} else {
// Add cap
p0 = pts[0];
p1 = pts[1];
start = 1;
end = pointsLength - 1;
}
if (!loop) {
// Add cap
const dPos = p1.sub(p0);
dPos.normalizeSelf();
const dx = dPos.x;
const dy = dPos.y;
if (lineCap === LineCap.BUTT) {
this._buttCap!(p0, dx, dy, w, 0);
}
else if (lineCap === LineCap.SQUARE) {
this._buttCap!(p0, dx, dy, w, w);
}
else if (lineCap === LineCap.ROUND) {
this._roundCapStart!(p0, dx, dy, w, ncap);
}
}
for (let j = start; j < end; ++j) {
if (lineJoin === LineJoin.ROUND) {
this._roundJoin(p0, p1, w, w, ncap);
}
else if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) {
this._bevelJoin(p0, p1, w, w);
}
else {
this._vset!(p1.x + p1.dmx * w, p1.y + p1.dmy * w);
this._vset!(p1.x - p1.dmx * w, p1.y - p1.dmy * w);
}
p0 = p1;
p1 = pts[j + 1];
}
if (loop) {
// Loop it
let vDataoOfset = offset * attrBytes;
let data = vData.slice(vDataoOfset, vDataoOfset + attrBytes);
vData.set(data, meshbuffer.vertexStart * attrBytes);
vDataoOfset += attrBytes;
meshbuffer.vertexStart++;
data = vData.slice(vDataoOfset, vDataoOfset + attrBytes);
vData.set(data, meshbuffer.vertexStart * attrBytes);
meshbuffer.vertexStart++;
} else {
// Add cap
const dPos = p1.sub(p0);
dPos.normalizeSelf();
const dx = dPos.x;
const dy = dPos.y;
if (lineCap === LineCap.BUTT) {
this._buttCap!(p1, dx, dy, w, 0);
}
else if (lineCap === LineCap.SQUARE) {
this._buttCap!(p1, dx, dy, w, w);
}
else if (lineCap === LineCap.ROUND) {
this._roundCapEnd!(p1, dx, dy, w, ncap);
}
}
// stroke indices
let indicesOffset = meshbuffer.indiceStart;
for (let begin = offset + 2, over = meshbuffer.vertexStart; begin < over; begin++) {
iData[indicesOffset++] = begin - 2;
iData[indicesOffset++] = begin - 1;
iData[indicesOffset++] = begin;
}
meshbuffer.indiceStart = indicesOffset;
if (indicesOffset !== meshbuffer.indiceCount) {
const arr = new Array(meshbuffer.indiceCount - indicesOffset);
meshbuffer.iData.set(arr, indicesOffset);
}
}
_renderData = null;
_impl = null;
},
_expandFill (graphics: GraphicsComponent) {
_impl = graphics.impl;
if (!_impl) {
return;
}
const paths = _impl.paths;
// Calculate max vertex usage.
let cverts = 0;
for (let i = _impl.pathOffset, l = _impl.pathLength; i < l; i++) {
const path = paths[i];
const pointsLength = path.points.length;
cverts += pointsLength;
}
const renderData = _renderData = this.getRenderData!(graphics, cverts);
if (!renderData) {
return;
}
const meshbuffer = renderData;
const vData = meshbuffer.vData!;
const iData = meshbuffer.iData!;
for (let i = _impl.pathOffset, l = _impl.pathLength; i < l; i++) {
const path = paths[i];
const pts = path.points;
const pointsLength = pts.length;
if (pointsLength === 0) {
continue;
}
// Calculate shape vertices.
const vertexOffset = renderData.vertexStart;
for (let j = 0; j < pointsLength; ++j) {
this._vset!(pts[j].x, pts[j].y);
}
let indicesOffset = renderData.indiceStart;
if (path.complex) {
const earcutData: number[] = [];
for (let j = vertexOffset, end = renderData.vertexStart; j < end; j++) {
let vDataOffset = j * attrBytes;
earcutData.push(vData[vDataOffset++]);
earcutData.push(vData[vDataOffset++]);
earcutData.push(vData[vDataOffset++]);
}
const newIndices = Earcut(earcutData, null, 3);
if (!newIndices || newIndices.length === 0) {
continue;
}
for (let j = 0, nIndices = newIndices.length; j < nIndices; j++) {
iData[indicesOffset++] = newIndices[j] + vertexOffset;
}
}
else {
const first = vertexOffset;
for (let start = vertexOffset + 2, end = meshbuffer.vertexStart; start < end; start++) {
iData[indicesOffset++] = first;
iData[indicesOffset++] = start - 1;
iData[indicesOffset++] = start;
}
}
meshbuffer.indiceStart = indicesOffset;
if (indicesOffset !== meshbuffer.indiceCount) {
const arr = new Array(meshbuffer.indiceCount - indicesOffset);
meshbuffer.iData.set(arr, indicesOffset);
}
}
_renderData = null;
_impl = null;
},
_calculateJoins (impl: Impl, w: number, lineJoin: LineJoin, miterLimit: number) {
let iw = 0.0;
if (w > 0.0) {
iw = 1 / w;
}
// Calculate which joins needs extra vertices to append, and gather vertex count.
const paths = impl.paths;
for (let i = impl.pathOffset, l = impl.pathLength; i < l; i++) {
const path = paths[i];
const pts = path.points;
const ptsLength = pts.length;
let p0 = pts[ptsLength - 1];
let p1 = pts[0];
let nleft = 0;
path.nbevel = 0;
for (let j = 0; j < ptsLength; j++) {
let dmr2 = 0;
let cross = 0;
let limit = 0;
// perp normals
const dlx0 = p0.dy;
const dly0 = -p0.dx;
const dlx1 = p1.dy;
const dly1 = -p1.dx;
// Calculate extrusions
p1.dmx = (dlx0 + dlx1) * 0.5;
p1.dmy = (dly0 + dly1) * 0.5;
dmr2 = p1.dmx * p1.dmx + p1.dmy * p1.dmy;
if (dmr2 > 0.000001) {
let scale = 1 / dmr2;
if (scale > 600) {
scale = 600;
}
p1.dmx *= scale;
p1.dmy *= scale;
}
// Keep track of left turns.
cross = p1.dx * p0.dy - p0.dx * p1.dy;
if (cross > 0) {
nleft++;
p1.flags |= PointFlags.PT_LEFT;
}
// Calculate if we should use bevel or miter for inner join.
limit = max(11, min(p0.len, p1.len) * iw);
if (dmr2 * limit * limit < 1) {
p1.flags |= PointFlags.PT_INNERBEVEL;
}
// Check to see if the corner needs to be beveled.
if (p1.flags & PointFlags.PT_CORNER) {
if (dmr2 * miterLimit * miterLimit < 1 ||
lineJoin === LineJoin.BEVEL ||
lineJoin === LineJoin.ROUND) {
p1.flags |= PointFlags.PT_BEVEL;
}
}
if ((p1.flags & (PointFlags.PT_BEVEL | PointFlags.PT_INNERBEVEL)) !== 0) {
path.nbevel++;
}
p0 = p1;
p1 = pts[j + 1];
}
}
},
_flattenPaths (impl: Impl) {
const paths = impl.paths;
for (let i = impl.pathOffset, l = impl.pathLength; i < l; i++) {
const path = paths[i];
const pts = path.points;
let p0 = pts[pts.length - 1];
let p1 = pts[0];
if (p0.equals(p1)) {
path.closed = true;
pts.pop();
p0 = pts[pts.length - 1];
}
for (let j = 0, size = pts.length; j < size; j++) {
// Calculate segment direction and length
const dPos = p1.sub(p0);
p0.len = dPos.mag();
if (dPos.x || dPos.y) {
dPos.normalizeSelf();
}
p0.dx = dPos.x;
p0.dy = dPos.y;
// Advance
p0 = p1;
p1 = pts[j + 1];
}
}
},
_chooseBevel (bevel: number, p0: Point, p1: Point, w: number) {
const x = p1.x;
const y = p1.y;
let x0 = 0;
let y0 = 0;
let x1 = 0;
let y1 = 0;
if (bevel !== 0) {
x0 = x + p0.dy * w;
y0 = y - p0.dx * w;
x1 = x + p1.dy * w;
y1 = y - p1.dx * w;
} else {
x0 = x1 = x + p1.dmx * w;
y0 = y1 = y + p1.dmy * w;
}
return [x0, y0, x1, y1];
},
_buttCap (p: Point, dx: number, dy: number, w: number, d: number) {
const px = p.x - dx * d;
const py = p.y - dy * d;
const dlx = dy;
const dly = -dx;
this._vset!(px + dlx * w, py + dly * w);
this._vset!(px - dlx * w, py - dly * w);
},
_roundCapStart (p: Point, dx: number, dy: number, w: number, ncap: number) {
const px = p.x;
const py = p.y;
const dlx = dy;
const dly = -dx;
for (let i = 0; i < ncap; i++) {
const a = i / (ncap - 1) * PI;
const ax = cos(a) * w;
const ay = sin(a) * w;
this._vset!(px - dlx * ax - dx * ay, py - dly * ax - dy * ay);
this._vset!(px, py);
}
this._vset!(px + dlx * w, py + dly * w);
this._vset!(px - dlx * w, py - dly * w);
},
_roundCapEnd (p: Point, dx: number, dy: number, w: number, ncap: number) {
const px = p.x;
const py = p.y;
const dlx = dy;
const dly = -dx;
this._vset!(px + dlx * w, py + dly * w);
this._vset!(px - dlx * w, py - dly * w);
for (let i = 0; i < ncap; i++) {
const a = i / (ncap - 1) * PI;
const ax = cos(a) * w;
const ay = sin(a) * w;
this._vset!(px, py);
this._vset!(px - dlx * ax + dx * ay, py - dly * ax + dy * ay);
}
},
_roundJoin (p0: Point, p1: Point, lw: number, rw: number, ncap: number) {
const dlx0 = p0.dy;
const dly0 = -p0.dx;
const dlx1 = p1.dy;
const dly1 = -p1.dx;
const p1x = p1.x;
const p1y = p1.y;
if ((p1.flags & PointFlags.PT_LEFT) !== 0) {
const out = this._chooseBevel!(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw);
const lx0 = out[0];
const ly0 = out[1];
const lx1 = out[2];
const ly1 = out[3];
const a0 = atan2(-dly0, -dlx0);
let a1 = atan2(-dly1, -dlx1);
if (a1 > a0) { a1 -= PI * 2; }
this._vset!(lx0, ly0);
this._vset!(p1x - dlx0 * rw, p1.y - dly0 * rw);
const n = clamp(ceil((a0 - a1) / PI) * ncap, 2, ncap);
for (let i = 0; i < n; i++) {
const u = i / (n - 1);
const a = a0 + u * (a1 - a0);
const rx = p1x + cos(a) * rw;
const ry = p1y + sin(a) * rw;
this._vset!(p1x, p1y);
this._vset!(rx, ry);
}
this._vset!(lx1, ly1);
this._vset!(p1x - dlx1 * rw, p1y - dly1 * rw);
} else {
const out = this._chooseBevel!(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw);
const rx0 = out[0];
const ry0 = out[1];
const rx1 = out[2];
const ry1 = out[3];
const a0 = atan2(dly0, dlx0);
let a1 = atan2(dly1, dlx1);
if (a1 < a0) { a1 += PI * 2; }
this._vset!(p1x + dlx0 * rw, p1y + dly0 * rw, 0);
this._vset!(rx0, ry0, 0);
const n = clamp(ceil((a1 - a0) / PI) * ncap, 2, ncap);
for (let i = 0; i < n; i++) {
const u = i / (n - 1);
const a = a0 + u * (a1 - a0);
const lx = p1x + cos(a) * lw;
const ly = p1y + sin(a) * lw;
this._vset!(lx, ly, 0);
this._vset!(p1x, p1y, 0);
}
this._vset!(p1x + dlx1 * rw, p1y + dly1 * rw);
this._vset!(rx1, ry1);
}
},
_bevelJoin (p0: Point, p1: Point, lw: number, rw: number) {
let rx0 = 0;
let ry0 = 0;
let rx1 = 0;
let ry1 = 0;
let lx0 = 0;
let ly0 = 0;
let lx1 = 0;
let ly1 = 0;
const dlx0 = p0.dy;
const dly0 = -p0.dx;
const dlx1 = p1.dy;
const dly1 = -p1.dx;
if (p1.flags & PointFlags.PT_LEFT) {
const out = this._chooseBevel!(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, lw);
lx0 = out[0];
ly0 = out[1];
lx1 = out[2];
ly1 = out[3];
this._vset!(lx0, ly0, 0);
this._vset!(p1.x - dlx0 * rw, p1.y - dly0 * rw, 0);
this._vset!(lx1, ly1, 0);
this._vset!(p1.x - dlx1 * rw, p1.y - dly1 * rw, 0);
} else {
const out = this._chooseBevel!(p1.flags & PointFlags.PT_INNERBEVEL, p0, p1, -rw);
rx0 = out[0];
ry0 = out[1];
rx1 = out[2];
ry1 = out[3];
this._vset!(p1.x + dlx0 * lw, p1.y + dly0 * lw, 0);
this._vset!(rx0, ry0);
this._vset!(p1.x + dlx1 * lw, p1.y + dly1 * lw, 0);
this._vset!(rx1, ry1);
}
},
_vset (x: number, y: number) {
if (!_renderData) {
return;
}
const meshbuffer = _renderData;
let dataOffset = meshbuffer.vertexStart * attrBytes;
const vData = meshbuffer.vData!;
vec3.set(_tempVec3, x, y, 0);
vec3.transformMat4(_tempVec3, _tempVec3, _currMatrix);
vData[dataOffset++] = _tempVec3.x;
vData[dataOffset++] = _tempVec3.y;
vData[dataOffset++] = _tempVec3.z;
vData[dataOffset++] = 1;
vData[dataOffset++] = 1;
color4.array(vData!, _curColor, dataOffset);
meshbuffer.vertexStart ++;
},
};
@@ -0,0 +1,246 @@
// import { ccclass } from '../../../../../core/data/class-decorator';
import { Color, Vec2 } from '../../../../../core/value-types';
import { IARenderData } from '../../../../../renderer/ui/renderData';
import RecyclePool from '../../../../memop/recycle-pool';
import { arc, ellipse, roundRect, tesselateBezier } from '../helper';
import { LineCap, LineJoin, PointFlags} from '../types';
// const renderer = require('../../../index');
// const renderEngine = renderer.renderEngine;
// const IARenderData = renderEngine.IARenderData;
// const InputAssembler = renderEngine.InputAssembler;
export class Point extends Vec2 {
public dx = 0;
public dy = 0;
public dmx = 0;
public dmy = 0;
public flags = 0;
public len = 0;
constructor (x: number, y: number) {
super(x, y);
this.reset();
}
public reset () {
this.dx = 0;
this.dy = 0;
this.dmx = 0;
this.dmy = 0;
this.flags = 0;
this.len = 0;
}
}
export class Path {
public closed = false;
public nbevel = 0;
public complex = true;
public points: Point[] = [];
constructor () {
this.reset();
}
public reset () {
this.closed = false;
this.nbevel = 0;
this.complex = true;
if (this.points) {
this.points.length = 0;
}
else {
this.points = [];
}
}
}
export class Impl {
public dataOffset = 0;
public updatePathOffset = false;
public pathLength = 0;
public pathOffset = 0;
public paths: Path[] = [];
// inner properties
public tessTol = 0.25;
public distTol = 0.01;
public fillColor = Color.WHITE;
public lineCap = LineCap.BUTT;
public strokeColor = Color.BLACK;
public lineJoin = LineJoin.MITER;
public lineWidth = 0;
public pointsOffset = 0;
private _commandx = 0;
private _commandy = 0;
private _points: Point[] = [];
private _renderDatasPool: RecyclePool<IARenderData> = new RecyclePool(() => {
return new IARenderData();
}, 16);
private _renderDatas: IARenderData[] = [];
private _curPath: Path | null = null;
public moveTo (x: number, y: number) {
if (this.updatePathOffset) {
this.pathOffset = this.pathLength;
this.updatePathOffset = false;
}
this._addPath();
this.addPoint(x, y, PointFlags.PT_CORNER);
this._commandx = x;
this._commandy = y;
}
public lineTo (x: number, y: number) {
this.addPoint(x, y, PointFlags.PT_CORNER);
this._commandx = x;
this._commandy = y;
}
public bezierCurveTo (c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number) {
const path = this._curPath!;
const last = path.points[path.points.length - 1];
if (!last) {
return;
}
if (last.x === c1x && last.y === c1y && c2x === x && c2y === y) {
this.lineTo(x, y);
return;
}
tesselateBezier(this, last.x, last.y, c1x, c1y, c2x, c2y, x, y, 0, PointFlags.PT_CORNER);
this._commandx = x;
this._commandy = y;
}
public quadraticCurveTo (cx: number, cy: number, x: number, y: number) {
const x0 = this._commandx;
const y0 = this._commandy;
this.bezierCurveTo(x0 + 2.0 / 3.0 * (cx - x0), y0 + 2.0 / 3.0 * (cy - y0), x + 2.0 / 3.0 * (cx - x), y + 2.0 / 3.0 * (cy - y), x, y);
}
public arc (cx: number, cy: number, r: number, startAngle: number, endAngle: number, counterclockwise: boolean) {
arc(this, cx, cy, r, startAngle, endAngle, counterclockwise);
}
public ellipse (cx: number, cy: number, rx: number, ry: number) {
ellipse(this, cx, cy, rx, ry);
this._curPath!.complex = false;
}
public circle (cx: number, cy: number, r: number) {
ellipse(this, cx, cy, r, r);
this._curPath!.complex = false;
}
public rect (x: number, y: number, w: number, h: number) {
this.moveTo(x, y);
this.lineTo(x + w, y);
this.lineTo(x + w, y + h);
this.lineTo(x, y + h);
this.close();
this._curPath!.complex = false;
}
public roundRect (x: number, y: number, w: number, h: number, r: number) {
roundRect(this, x, y, w, h, r);
this._curPath!.complex = false;
}
public clear (clean: boolean = false) {
this.pathLength = 0;
this.pathOffset = 0;
this.pointsOffset = 0;
this.dataOffset = 0;
this._curPath = null;
this.paths.length = 0;
this._points.length = 0;
this._renderDatasPool.reset();
const datas = this._renderDatas;
for (let i = 0, l = datas.length; i < l; i++) {
const data = datas[i];
if (!data) {
continue;
}
data.reset();
}
}
public close () {
this._curPath!.closed = true;
}
public requestRenderData () {
const renderData = this._renderDatasPool.add();
this._renderDatas.push(renderData);
return renderData;
}
public getRenderDatas () {
if (this._renderDatas.length === 0) {
this.requestRenderData();
}
return this._renderDatas;
}
public addPoint (x: number, y: number, flags: PointFlags) {
const path = this._curPath;
if (!path) {
return;
}
const points = this._points;
const pathPoints = path.points;
const offset = this.pointsOffset++;
let pt: Point = points[offset];
if (!pt) {
pt = new Point(x, y);
points.push(pt);
} else {
pt.x = x;
pt.y = y;
}
pt.flags = flags;
pathPoints.push(pt);
}
private _addPath () {
const offset = this.pathLength;
let path = this.paths[offset];
if (!path) {
path = new Path();
this.paths.push(path);
} else {
path.reset();
}
this.pathLength++;
this._curPath = path;
return path;
}
}
@@ -0,0 +1,37 @@
/****************************************************************************
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 { GraphicsComponent } from '../../../components/graphics-component';
import { UIRenderComponent } from '../../../components/ui-render-component';
import { IAssemblerManager } from '../../assembler';
import { graphicsAssembler } from './graphics-assembler';
const graphicsAssemblerManager: IAssemblerManager = {
getAssembler (sprite: UIRenderComponent) {
return graphicsAssembler;
},
};
GraphicsComponent.Assembler = graphicsAssemblerManager;
+1
View File
@@ -24,6 +24,7 @@
****************************************************************************/
// require('./graphics');
import './graphics/webgl/index';
import './label/index';
import './mask/index';
import './sprite/index';
+2 -56
View File
@@ -122,7 +122,6 @@ export const maskAssembler: IAssembler = {
// commit last data
renderer.autoMergeBatches();
// const clearGeometry = mask.getClearGeometry();
const clearMaterial = mask.getClearMaterial()!;
cw = screen.width;
ch = screen.height;
@@ -136,8 +135,6 @@ export const maskAssembler: IAssembler = {
vec3.set(vec3_temps[1], data3.x, data0.y, 0);
vec3.set(vec3_temps[2], data0.x, data3.y, 0);
vec3.set(vec3_temps[3], data3.x, data3.y, 0);
// const meshBuffer = createMeshBuffer(ui, clearGeometry);
// const nVert = Math.floor(clearGeometry.positions.length / 3);
screen.getWorldMatrix(_worldMatrix);
let buffer = renderer.currBufferBatch!;
@@ -155,10 +152,6 @@ export const maskAssembler: IAssembler = {
let vbuf = buffer.vData;
let iData = buffer.iData!;
for (let i = 0; i < 4; ++i) {
// vec3.set(v,
// clearGeometry.positions[3 * i + 0],
// clearGeometry.positions[3 * i + 1],
// clearGeometry.positions[3 * i + 2]);
vec3.copy(v, vec3_temps[i]);
vec3.transformMat4(v, v, _worldMatrix);
vbuf![vertexOffset++] = v.x;
@@ -178,7 +171,7 @@ export const maskAssembler: IAssembler = {
iData[indiceOffset++] = vertexId + 2;
_stencilManager.clear();
renderer.forceMergeBatches(clearMaterial, cc.builtinResMgr._resources['default-spriteframe']);
renderer.forceMergeBatches(clearMaterial, null);
const maskMaterial = mask.getMaskMaterial()!;
const datas = mask.renderData!.datas;
@@ -196,10 +189,6 @@ export const maskAssembler: IAssembler = {
iData = buffer.iData!;
mask.node.getWorldMatrix(_worldMatrix);
for (let i = 0; i < 4; ++i) {
// vec3.set(v,
// clearGeometry.positions[3 * i + 0],
// clearGeometry.positions[3 * i + 1],
// clearGeometry.positions[3 * i + 2]);
vec3.copy(v, vec3_temps[i]);
vec3.transformMat4(v, v, _worldMatrix);
vbuf![vertexOffset++] = v.x;
@@ -219,61 +208,18 @@ export const maskAssembler: IAssembler = {
iData[indiceOffset++] = vertexId + 2;
_stencilManager.enterLevel();
renderer.forceMergeBatches(maskMaterial, cc.builtinResMgr._resources['default-spriteframe']);
renderer.forceMergeBatches(maskMaterial, null);
_stencilManager.enableMask();
// const maskGeometry = mask.getMaskGeometry();
// const maskMaterial = mask.getMaskMaterial();
// if (maskGeometry && maskMaterial) {
// const meshBuffer = createMeshBuffer(ui, maskGeometry);
// const nVert = Math.floor(maskGeometry.positions.length / 3);
// const v = new vec3();
// const worldMatrix = mask.node.getWorldMatrix();
// for (let i = 0; i < nVert; ++i) {
// vec3.set(v,
// maskGeometry.positions[3 * i + 0],
// maskGeometry.positions[3 * i + 1],
// maskGeometry.positions[3 * i + 2]);
// vec3.transformMat4(v, v, worldMatrix);
// meshBuffer.vData![3 * i + 0] = v.x;
// meshBuffer.vData![3 * i + 1] = v.y;
// meshBuffer.vData![3 * i + 2] = v.z;
// }
// const maskRenderData = ui.createUIRenderData() as IUIRenderData;
// maskRenderData.meshBuffer = meshBuffer;
// maskRenderData.material = maskMaterial;
// ui.flushBatches(maskRenderData);
// }
},
};
export const maskEndAssembler: IAssembler = {
fillBuffers (mask: MaskComponent, ui: UI) {
_stencilManager.exitMask();
// const clearGeometry = mask.getClearGeometry();
// const clearMaterial = mask.getClearMaterial();
// if (clearGeometry && clearMaterial) {
// const meshBuffer = createMeshBuffer(ui, clearGeometry);
// meshBuffer.vData!.set(clearGeometry.positions);
// const clearMaskRenderData = ui.createUIRenderData() as IUIRenderData;
// clearMaskRenderData.meshBuffer = meshBuffer;
// clearMaskRenderData.material = clearMaterial;
// }
},
};
// function createMeshBuffer (ui: UI, geometry: IGeometry) {
// const nVert = Math.floor(geometry.positions.length / 3);
// const meshBuffer = ui.createBuffer(nVert, geometry.indices ? geometry.indices.length : 0);
// if (geometry.indices) {
// meshBuffer.iData!.set(geometry.indices);
// }
// // geometry.primitiveMode === undefined ? GFXPrimitiveMode.TRIANGLE_LIST : geometry.primitiveMode;
// return meshBuffer;
// }
const StartAssembler: IAssemblerManager = {
getAssembler () {
return maskAssembler;
-3
View File
@@ -38,9 +38,6 @@ for (let i = 0; i < 4; i++) {
}
export const simple: IAssembler = {
useModel: false,
createData (sprite: SpriteComponent) {
const renderData = sprite.requestRenderData();
renderData!.dataLength = 4;
@@ -0,0 +1,489 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator';
import { Color } from '../../../core/value-types';
import { UI } from '../../../renderer/ui/ui';
// import { IGraphicAssembler } from '../assembler/assembler';
// const SpriteMaterial = require('../renderer/render-engine').SpriteMaterial;
import { LineCap, LineJoin } from '../assembler/graphics/types';
import { Impl } from '../assembler/graphics/webgl/impl';
import { UIRenderComponent } from '../components/ui-render-component';
import { IAssembler } from '../assembler/assembler';
import { Material } from '../../assets';
import { RenderableComponent } from '../../framework/renderable-component';
/**
* @class Graphics
* @extends Component
*/
@ccclass('cc.GraphicsComponent')
@executionOrder(100)
@menu('UI/Graphics')
export class GraphicsComponent extends UIRenderComponent {
/**
* !#en
* Current line width.
* !#zh
* 当前线条宽度
* @property {Number} lineWidth
* @default 1
*/
get lineWidth () {
return this._lineWidth;
}
set lineWidth (value) {
this._lineWidth = value;
if (!this.impl){
return;
}
this.impl.lineWidth = value;
}
/**
* !#en
* lineJoin determines how two connecting segments (of lines, arcs or curves) with non-zero lengths in a shape are joined together.
* !#zh
* lineJoin 用来设置2个长度不为0的相连部分(线段,圆弧,曲线)如何连接在一起的属性。
* @property {Graphics.LineJoin} lineJoin
* @default LineJoin.MITER
*/
@property({
type: LineJoin,
})
get lineJoin () {
return this._lineJoin;
}
set lineJoin (value: LineJoin) {
this._lineJoin = value;
if (!this.impl) {
return;
}
this.impl.lineJoin = value;
}
/**
* !#en
* lineCap determines how the end points of every line are drawn.
* !#zh
* lineCap 指定如何绘制每一条线段末端。
* @property {Graphics.LineCap} lineCap
* @default LineCap.BUTT
*/
@property({
type: LineCap,
})
get lineCap () {
return this._lineCap;
}
set lineCap (value: LineCap) {
this._lineCap = value;
if (!this.impl) {
return;
}
this.impl.lineCap = value;
}
/**
* !#en
* stroke color
* !#zh
* 线段颜色
* @property {Color} strokeColor
* @default Color.BLACK
*/
@property
get strokeColor () {
return this._strokeColor;
}
set strokeColor (value: Color) {
if (!this.impl) {
return;
}
this.impl.strokeColor = this._strokeColor = new Color(value);
}
/**
* !#en
* fill color
* !#zh
* 填充颜色
* @property {Color} fillColor
* @default Color.WHITE
*/
@property
get fillColor () {
return this._fillColor;
}
set fillColor (value) {
if (!this.impl){
return;
}
this.impl.fillColor = this._fillColor = new Color(value);
}
/**
* !#en
* Sets the miter limit ratio
* !#zh
* 设置斜接面限制比例
* @property {Number} miterLimit
* @default 10
*/
@property
get miterLimit () {
return this._miterLimit;
}
set miterLimit (value) {
this._miterLimit = value;
// this.impl.miterLimit = value;
}
@property({
visible: false,
})
get color (){
return super.color;
}
public static LineJoin = LineJoin;
public static LineCap = LineCap;
public impl: Impl | null = null;
@property
private _lineWidth = 1;
@property
private _strokeColor = Color.BLACK;
@property
private _lineJoin = LineJoin.MITER;
@property
private _lineCap = LineCap.BUTT;
@property
private _fillColor = Color.WHITE;
@property
private _miterLimit = 10;
public __preload (){
if (super.__preload){
super.__preload();
}
this._flushAssembler();
}
public onRestore () {
if (!this.impl) {
this._flushAssembler();
}
}
public onEnable () {
if (super.onEnable) {
super.onEnable();
}
this._activateMaterial();
}
public onDestroy () {
if (super.onDestroy) {
super.onDestroy();
}
if (!this.impl) {
return;
}
this.impl.clear();
this.impl = null;
}
public _activateMaterial () {
if (!this._material) {
return;
}
this._updateMaterial(this._material);
}
/**
* !#en Move path start point to (x,y).
* !#zh 移动路径起点到坐标(x, y)
* @method moveTo
* @param {Number} [x] The x axis of the coordinate for the end point.
* @param {Number} [y] The y axis of the coordinate for the end point.
*/
public moveTo (x: number, y: number) {
if (!this.impl) {
return;
}
this.impl.moveTo(x, y);
}
/**
* !#en Adds a straight line to the path
* !#zh 绘制直线路径
* @method lineTo
* @param {Number} [x] The x axis of the coordinate for the end point.
* @param {Number} [y] The y axis of the coordinate for the end point.
*/
public lineTo (x: number, y: number) {
if (!this.impl) {
return;
}
this.impl.lineTo(x, y);
}
/**
* !#en Adds a cubic Bézier curve to the path
* !#zh 绘制三次贝赛尔曲线路径
* @method bezierCurveTo
* @param {Number} [c1x] The x axis of the coordinate for the first control point.
* @param {Number} [c1y] The y axis of the coordinate for first control point.
* @param {Number} [c2x] The x axis of the coordinate for the second control point.
* @param {Number} [c2y] The y axis of the coordinate for the second control point.
* @param {Number} [x] The x axis of the coordinate for the end point.
* @param {Number} [y] The y axis of the coordinate for the end point.
*/
public bezierCurveTo (c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number) {
if (!this.impl) {
return;
}
this.impl.bezierCurveTo(c1x, c1y, c2x, c2y, x, y);
}
/**
* !#en Adds a quadratic Bézier curve to the path
* !#zh 绘制二次贝赛尔曲线路径
* @method quadraticCurveTo
* @param {Number} [cx] The x axis of the coordinate for the control point.
* @param {Number} [cy] The y axis of the coordinate for the control point.
* @param {Number} [x] The x axis of the coordinate for the end point.
* @param {Number} [y] The y axis of the coordinate for the end point.
*/
public quadraticCurveTo (cx: number, cy: number, x: number, y: number) {
if (!this.impl) {
return;
}
this.impl.quadraticCurveTo(cx, cy, x, y);
}
/**
* !#en Adds an arc to the path which is centered at (cx, cy) position with radius r starting at startAngle and ending at endAngle going in the given direction by counterclockwise (defaulting to false).
* !#zh 绘制圆弧路径。圆弧路径的圆心在 (cx, cy) 位置,半径为 r ,根据 counterclockwise (默认为false)指定的方向从 startAngle 开始绘制,到 endAngle 结束。
* @method arc
* @param {Number} [cx] The x axis of the coordinate for the center point.
* @param {Number} [cy] The y axis of the coordinate for the center point.
* @param {Number} [r] The arc's radius.
* @param {Number} [startAngle] The angle at which the arc starts, measured clockwise from the positive x axis and expressed in radians.
* @param {Number} [endAngle] The angle at which the arc ends, measured clockwise from the positive x axis and expressed in radians.
* @param {Boolean} [counterclockwise] An optional Boolean which, if true, causes the arc to be drawn counter-clockwise between the two angles. By default it is drawn clockwise.
*/
public arc (cx: number, cy: number, r: number, startAngle: number, endAngle: number, counterclockwise: boolean) {
if (!this.impl) {
return;
}
this.impl.arc(cx, cy, r, startAngle, endAngle, counterclockwise);
}
/**
* !#en Adds an ellipse to the path.
* !#zh 绘制椭圆路径。
* @method ellipse
* @param {Number} [cx] The x axis of the coordinate for the center point.
* @param {Number} [cy] The y axis of the coordinate for the center point.
* @param {Number} [rx] The ellipse's x-axis radius.
* @param {Number} [ry] The ellipse's y-axis radius.
*/
public ellipse (cx: number, cy: number, rx: number, ry: number) {
if (!this.impl) {
return;
}
this.impl.ellipse(cx, cy, rx, ry);
}
/**
* !#en Adds an circle to the path.
* !#zh 绘制圆形路径。
* @method circle
* @param {Number} [cx] The x axis of the coordinate for the center point.
* @param {Number} [cy] The y axis of the coordinate for the center point.
* @param {Number} [r] The circle's radius.
*/
public circle (cx: number, cy: number, r: number) {
if (!this.impl) {
return;
}
this.impl.circle(cx, cy, r);
}
/**
* !#en Adds an rectangle to the path.
* !#zh 绘制矩形路径。
* @method rect
* @param {Number} [x] The x axis of the coordinate for the rectangle starting point.
* @param {Number} [y] The y axis of the coordinate for the rectangle starting point.
* @param {Number} [w] The rectangle's width.
* @param {Number} [h] The rectangle's height.
*/
public rect (x: number, y: number, w: number, h: number) {
if (!this.impl) {
return;
}
this.impl.rect(x, y, w, h);
}
/**
* !#en Adds an round corner rectangle to the path.
* !#zh 绘制圆角矩形路径。
* @method roundRect
* @param {Number} [x] The x axis of the coordinate for the rectangle starting point.
* @param {Number} [y] The y axis of the coordinate for the rectangle starting point.
* @param {Number} [w] The rectangles width.
* @param {Number} [h] The rectangle's height.
* @param {Number} [r] The radius of the rectangle.
*/
public roundRect (x: number, y: number, w: number, h: number, r: number) {
if (!this.impl) {
return;
}
this.impl.roundRect(x, y, w, h, r);
}
/**
* !#en Draws a filled rectangle.
* !#zh 绘制填充矩形。
* @method fillRect
* @param {Number} [x] The x axis of the coordinate for the rectangle starting point.
* @param {Number} [y] The y axis of the coordinate for the rectangle starting point.
* @param {Number} [w] The rectangle's width.
* @param {Number} [h] The rectangle's height.
*/
public fillRect (x, y, w, h) {
this.rect(x, y, w, h);
this.fill();
}
/**
* !#en Erasing any previously drawn content.
* !#zh 擦除之前绘制的所有内容的方法。
* @method clear
* @param {Boolean} [clean] Whether to clean the graphics inner cache.
*/
public clear (/*clean: boolean*/) {
if (!this.impl) {
return;
}
this.impl.clear();
}
/**
* !#en Causes the point of the pen to move back to the start of the current path. It tries to add a straight line from the current point to the start.
* !#zh 将笔点返回到当前路径起始点的。它尝试从当前点到起始点绘制一条直线。
* @method close
*/
public close () {
if (!this.impl) {
return;
}
this.impl.close();
}
/**
* !#en Strokes the current or given path with the current stroke style.
* !#zh 根据当前的画线样式,绘制当前或已经存在的路径。
* @method stroke
*/
public stroke () {
(this._assembler as IAssembler).stroke!(this);
}
/**
* !#en Fills the current or given path with the current fill style.
* !#zh 根据当前的画线样式,填充当前或已经存在的路径。
* @method fill
*/
public fill () {
(this._assembler as IAssembler).fill!(this);
}
public updateAssembler (render: UI) {
if (super.updateAssembler(render)) {
render.commitComp(this, null, this._assembler!);
return true;
}
return false;
}
protected _instanceMaterial () {
if (this._sharedMaterial) {
this._updateMaterial(
Material.getInstantiatedMaterial(this._sharedMaterial,
new RenderableComponent(),
CC_EDITOR ? true : false,
));
} else {
this._updateMaterial(
Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-base-material'),
new RenderableComponent(),
CC_EDITOR ? true : false,
));
}
}
private _flushAssembler (){
const assembler = GraphicsComponent.Assembler!.getAssembler(this);
if (this._assembler !== assembler) {
this._assembler = assembler;
this.impl = (assembler as IAssembler).createImpl!(this);
}
}
}
cc.GraphicsComponent = GraphicsComponent;
+1 -1
View File
@@ -637,7 +637,7 @@ export class LabelComponent extends UIRenderComponent {
));
} else {
this._updateMaterial(
Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-material'),
Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-material'),
new RenderableComponent(),
CC_EDITOR ? true : false,
));
+21 -11
View File
@@ -271,19 +271,17 @@ export class MaskComponent extends UIRenderComponent {
}
protected _instanceMaterial () {
let useMat: Material | null = null;
if (this._sharedMaterial) {
this._updateMaterial(
Material.getInstantiatedMaterial(this._sharedMaterial,
new RenderableComponent(),
CC_EDITOR ? true : false,
));
useMat = this._sharedMaterial;
this._updateMaterial(Material.getInstantiatedMaterial(useMat, new RenderableComponent(), CC_EDITOR ? true : false));
} else {
this._updateMaterial(
Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-base'),
new RenderableComponent(),
CC_EDITOR ? true : false,
));
useMat = cc.builtinResMgr.get('ui-base-material');
this._updateMaterial(Material.getInstantiatedMaterial(useMat!, new RenderableComponent(), CC_EDITOR ? true : false));
}
this._clearMaskMaterial = Material.getInstantiatedMaterial(useMat!, new RenderableComponent(), CC_EDITOR ? true : false);
this._maskMaterial = Material.getInstantiatedMaterial(useMat!, new RenderableComponent(), CC_EDITOR ? true : false);
}
// _resizeNodeToTargetNode: CC_EDITOR && function () {
@@ -347,6 +345,18 @@ export class MaskComponent extends UIRenderComponent {
this._clearMaskMaterial = Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false);
// setupClearMaskMaterial(this._maskMaterial);
}
}else{
if (!this._maskMaterial) {
this._maskMaterial = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-base-material'),
new RenderableComponent(), CC_EDITOR ? true : false);
// setupMaskMaterial(this._maskMaterial);
}
if (!this._clearMaskMaterial) {
this._clearMaskMaterial = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-base-material'),
new RenderableComponent(), CC_EDITOR ? true : false);
// setupClearMaskMaterial(this._maskMaterial);
}
}
}
@@ -404,7 +414,7 @@ export class MaskComponent extends UIRenderComponent {
if (!this._renderData) {
if (this._assembler && this._assembler.createData) {
this._renderData = this._assembler.createData(this);
this._renderData.material = this.sharedMaterial;
this._renderData!.material = this.sharedMaterial;
this.markForUpdateRenderData();
}
}
+1 -1
View File
@@ -527,7 +527,7 @@ export class SpriteComponent extends UIRenderComponent {
));
} else {
this._updateMaterial(
Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-material'),
Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-material'),
new RenderableComponent(),
CC_EDITOR ? true : false,
));
+1 -3
View File
@@ -82,10 +82,8 @@ export class MeshBuffer {
if (vertexCount + this.vertexOffset > 65535) {
// merge last state
this.batcher.autoMergeBatches();
const vCount = vertexCount;
const iCount = indiceCount;
if (this._outofCallback) {
this._outofCallback.call(this.batcher, vCount, iCount);
this._outofCallback.call(this.batcher, vertexCount, indiceCount);
}
return false;
}
+56 -1
View File
@@ -12,7 +12,7 @@ export class IRenderData {
public color: Color = Color.WHITE;
}
class BaseRenderData {
export class BaseRenderData {
public material: Material | null = null;
public vertexCount: number = 0;
public indiceCount: number = 0;
@@ -94,6 +94,61 @@ export class RenderData extends BaseRenderData {
}
}
export class IARenderData extends BaseRenderData {
public vData: Float32Array = new Float32Array(256 * 9 * 4);
public iData: Uint16Array = new Uint16Array(256 * 6);
public vertexStart = 0;
public indiceStart = 0;
public byteStart = 0;
public byteCount = 0;
private _formatByte = 9 * 4;
public request (vertexCount: number, indiceCount: number) {
const byteOffset = this.byteCount + vertexCount * this._formatByte;
const indiceOffset = this.indiceCount + indiceCount;
if (vertexCount + this.vertexCount > 65535) {
return false;
}
let byteLength = this.vData!.byteLength;
let indiceLength = this.iData!.length;
let vCount = this.vData.length;
let iCount = this.iData.length;
if (byteOffset > byteLength || indiceOffset > indiceLength) {
while (byteLength < byteOffset || indiceLength < indiceOffset) {
vCount *= 2;
iCount *= 2;
byteLength = vCount * 4;
indiceLength = iCount;
}
// copy old data
const oldvData = new Float32Array(this.vData.buffer);
this.vData = new Float32Array(vCount);
this.vData.set(oldvData, 0);
const oldiData = new Uint16Array(this.iData.buffer);
this.iData = new Uint16Array(iCount);
this.iData.set(oldiData, 0);
}
this.vertexCount += vertexCount; // vertexOffset
this.indiceCount += indiceCount; // indiceOffset
this.byteCount = byteOffset; // byteOffset
return true;
}
public reset () {
this.vertexCount = 0;
this.indiceCount = 0;
this.byteCount = 0;
this.vertexStart = 0;
this.indiceStart = 0;
this.byteStart = 0;
}
}
const _dataPool = new RecyclePool(() => {
return new IRenderData();
}, 128);
+2 -1
View File
@@ -332,6 +332,7 @@ export class UI {
buffer.vertexStart = buffer.vertexOffset;
buffer.indiceStart = buffer.indiceOffset;
buffer.byteStart = buffer.byteOffset;
}
public forceMergeBatches (material: Material, sprite: SpriteFrame | null) {
@@ -433,7 +434,7 @@ export class UI {
private _createMeshBuffer (): MeshBuffer {
const batch = this._bufferBatchPool.add();
batch.initialize(this._attributes, this._requireBufferBatch);
batch.initialize(this._attributes, this._requireBufferBatch.bind(this));
this._meshBuffers.push(batch);
return batch;
}