implementing mask with graphics(#4138) (#4138)

exclude image_stencil
This commit is contained in:
JoneLau
2019-04-03 18:24:13 +08:00
committed by Weiliang Wang
parent 36402bc1ea
commit 4edd2a6ead
14 changed files with 572 additions and 569 deletions
+1 -8
View File
@@ -159,16 +159,9 @@ class BuiltinResMgr {
// sprite material
const spriteMtl = new cc.Material();
spriteMtl._uuid = 'ui-sprite-material';
spriteMtl.initialize({ effectName: 'builtin-sprite' });
spriteMtl.setProperty('mainTexture', defaultTexture);
spriteMtl.initialize({ defines: { USE_TEXTURE: true }, effectName: 'builtin-sprite' });
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';
+4 -2
View File
@@ -70,14 +70,16 @@ export enum LineJoin {
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.
* !#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,
/**
* !#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.
* !#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
*/
+3 -120
View File
@@ -23,32 +23,15 @@
THE SOFTWARE.
****************************************************************************/
import { Color, Mat4, Vec3 } from '../../../../core/value-types';
import { color4, vec3 } from '../../../../core/vmath';
import { Color, Mat4 } from '../../../../core/value-types';
import { IRenderData, RenderData } from '../../../../renderer/ui/renderData';
import { UI } from '../../../../renderer/ui/ui';
import { Node } from '../../../../scene-graph/node';
// import { IGeometry } from '../../../primitive/define';
import { MaskComponent } from '../../components/mask-component';
import { IAssembler, IAssemblerManager } from '../assembler';
import { StencilManager } from './stencil-manager';
const _stencilManager = StencilManager.sharedManager!;
const _worldMatrix = new Mat4();
const WHITE = Color.WHITE;
function getScreen (comp: MaskComponent){
let parent: Node | null = comp.node;
while (parent){
if (parent.getComponent(cc.CanvasComponent)){
return parent;
}
parent = parent.parent;
}
return parent;
}
export const maskAssembler: IAssembler = {
createData (mask: MaskComponent) {
@@ -100,115 +83,15 @@ export const maskAssembler: IAssembler = {
},
fillBuffers (mask: MaskComponent, renderer: UI) {
let cw = 0;
let ch = 0;
let appx = 0;
let appy = 0;
const data0 = new Vec3();
const data3 = new Vec3();
const vec3_temps: Vec3[] = [new Vec3(), new Vec3(), new Vec3(), new Vec3()];
const v = new vec3();
let screen: Node | null = null;
if (CC_EDITOR){
screen = getScreen(mask);
}else{
const comp = renderer.getScreen(mask.visibility);
screen = comp ? comp.node : null;
}
if (!screen) {
return;
}
_stencilManager.pushMask(mask);
// commit last data
renderer.autoMergeBatches();
const clearMaterial = mask.getClearMaterial()!;
cw = screen.width;
ch = screen.height;
appx = screen.anchorX * cw;
appy = screen.anchorY * ch;
data0.x = -appx;
data0.y = -appy;
data3.x = cw - appx;
data3.y = ch - appy;
vec3.set(vec3_temps[0], data0.x, data0.y, 0);
vec3.set(vec3_temps[1], data3.x, data0.y, 0);
vec3.set(vec3_temps[2], data0.x, data3.y, 0);
vec3.set(vec3_temps[3], data3.x, data3.y, 0);
screen.getWorldMatrix(_worldMatrix);
let buffer = renderer.currBufferBatch!;
let vertexOffset = buffer.byteOffset >> 2;
let indiceOffset = buffer.indiceOffset;
let vertexId = buffer.vertexOffset;
const isRecreate = buffer.request(4, 6);
if (!isRecreate) {
buffer = renderer.currBufferBatch!;
vertexOffset = 0;
indiceOffset = 0;
vertexId = 0;
}
let vbuf = buffer.vData;
let iData = buffer.iData!;
for (let i = 0; i < 4; ++i) {
vec3.copy(v, vec3_temps[i]);
vec3.transformMat4(v, v, _worldMatrix);
vbuf![vertexOffset++] = v.x;
vbuf![vertexOffset++] = v.y;
vbuf![vertexOffset++] = v.z;
vbuf![vertexOffset++] = 1;
vbuf![vertexOffset++] = 1;
color4.array(vbuf!, WHITE, vertexOffset);
vertexOffset += 4;
}
iData[indiceOffset++] = vertexId;
iData[indiceOffset++] = vertexId + 1;
iData[indiceOffset++] = vertexId + 2;
iData[indiceOffset++] = vertexId + 1;
iData[indiceOffset++] = vertexId + 3;
iData[indiceOffset++] = vertexId + 2;
_stencilManager.clear();
renderer.forceMergeBatches(clearMaterial, null);
const maskMaterial = mask.getMaskMaterial()!;
const datas = mask.renderData!.datas;
vec3.set(vec3_temps[0], datas[0].x, datas[0].y, 0);
vec3.set(vec3_temps[1], datas[3].x, datas[0].y, 0);
vec3.set(vec3_temps[2], datas[0].x, datas[3].y, 0);
vec3.set(vec3_temps[3], datas[3].x, datas[3].y, 0);
vertexOffset = buffer.byteOffset >> 2;
indiceOffset = buffer.indiceOffset;
vertexId = buffer.vertexOffset;
buffer.request(mask.renderData!.vertexCount, mask.renderData!.indiceCount);
vbuf = buffer.vData;
iData = buffer.iData!;
mask.node.getWorldMatrix(_worldMatrix);
for (let i = 0; i < 4; ++i) {
vec3.copy(v, vec3_temps[i]);
vec3.transformMat4(v, v, _worldMatrix);
vbuf![vertexOffset++] = v.x;
vbuf![vertexOffset++] = v.y;
vbuf![vertexOffset++] = v.z;
vbuf![vertexOffset++] = 1;
vbuf![vertexOffset++] = 1;
color4.array(vbuf!, mask.color, vertexOffset);
vertexOffset += 4;
}
iData[indiceOffset++] = vertexId;
iData[indiceOffset++] = vertexId + 1;
iData[indiceOffset++] = vertexId + 2;
iData[indiceOffset++] = vertexId + 1;
iData[indiceOffset++] = vertexId + 3;
iData[indiceOffset++] = vertexId + 2;
mask.clearGraphics!.updateAssembler(renderer);
_stencilManager.enterLevel();
renderer.forceMergeBatches(maskMaterial, null);
mask.graphics!.updateAssembler(renderer);
_stencilManager.enableMask();
},
+21 -22
View File
@@ -27,14 +27,12 @@
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 { Material } from '../../assets';
import { RenderableComponent } from '../../framework/renderable-component';
import { IAssembler } from '../assembler/assembler';
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
@@ -197,11 +195,8 @@ export class GraphicsComponent extends UIRenderComponent {
@property
private _miterLimit = 10;
public __preload (){
if (super.__preload){
super.__preload();
}
constructor (){
super();
this._flushAssembler();
}
@@ -306,7 +301,8 @@ export class GraphicsComponent extends UIRenderComponent {
}
/**
* !#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).
* !#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.
@@ -314,7 +310,8 @@ export class GraphicsComponent extends UIRenderComponent {
* @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.
* @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) {
@@ -461,19 +458,21 @@ export class GraphicsComponent extends UIRenderComponent {
}
protected _instanceMaterial () {
let mat: Material | null = null;
if (this._sharedMaterial) {
this._updateMaterial(
Material.getInstantiatedMaterial(this._sharedMaterial,
new RenderableComponent(),
CC_EDITOR ? true : false,
));
mat = 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,
));
if (UIRenderComponent.addColorMat) {
mat = new Material();
mat.copy(UIRenderComponent.addColorMat);
} else {
mat = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-material'), new RenderableComponent(), CC_EDITOR ? true : false);
mat.initialize({ defines: { USE_TEXTURE: false } });
UIRenderComponent.addColorMat = mat;
}
}
this._updateMaterial(mat);
}
private _flushAssembler (){
+23 -20
View File
@@ -613,35 +613,38 @@ export class LabelComponent extends UIRenderComponent {
}
protected _canRender () {
let result = super._canRender();
if (result) {
const font = this._font;
if (font && font instanceof BitmapFont) {
const spriteFrame = font.spriteFrame;
// cannot be activated if texture not loaded yet
if (!spriteFrame || !spriteFrame.textureLoaded()) {
result = false;
}
if (!super._canRender){
return false;
}
const font = this._font;
if (font && font instanceof BitmapFont) {
const spriteFrame = font.spriteFrame;
// cannot be activated if texture not loaded yet
if (!spriteFrame || !spriteFrame.textureLoaded()) {
return false;
}
}
return result;
return true;
}
protected _instanceMaterial () {
let mat: Material | null = null;
if (this._sharedMaterial) {
this._updateMaterial(
Material.getInstantiatedMaterial(this._sharedMaterial,
new RenderableComponent(),
CC_EDITOR ? true : false,
));
mat = Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false);
} else {
this._updateMaterial(
Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-material'),
new RenderableComponent(),
CC_EDITOR ? true : false,
));
if (UIRenderComponent.addColorMat) {
mat = new Material();
mat.copy(UIRenderComponent.addColorMat);
} else {
mat = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-material'), new RenderableComponent(), CC_EDITOR ? true : false);
mat.initialize({ defines: { USE_TEXTURE: false } });
UIRenderComponent.addColorMat = mat;
}
}
this._updateMaterial(mat);
}
private _checkStringEmpty () {
+337 -233
View File
@@ -23,47 +23,59 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
// import {SpriteFrame} from '../../../assets/CCSpriteFrame';
import { ccclass/*, executeInEditMode*/, executionOrder,
menu/*, property*/ } from '../../../core/data/class-decorator';
// import { ccenum } from '../../../core/value-types/enum';
// import { clamp } from '../../../core/vmath';
import { SpriteFrame } from '../../../assets/CCSpriteFrame';
import { Mat4, Vec2, Vec3 } from '../../../core';
import { ccclass, executionOrder, menu, property} from '../../../core/data/class-decorator';
import { EventType } from '../../../core/platform/event-manager/event-enum';
import { ccenum } from '../../../core/value-types/enum';
import * as vmath from '../../../core/vmath';
import { UI } from '../../../renderer/ui/ui';
import { Node } from '../../../scene-graph';
import { Material } from '../../assets/material';
import { RenderableComponent } from '../../framework/renderable-component';
// import circle from '../../primitive/circle';
import { IGeometry } from '../../primitive/define';
import quad from '../../primitive/quad';
import { scale, translate } from '../../primitive/transform';
import { GraphicsComponent } from './graphics-component';
import { UIRenderComponent } from './ui-render-component';
import { UITransformComponent } from './ui-transfrom-component';
// /**
// * !#en the type for mask.
// * !#zh 遮罩组件类型
// */
// export enum MaskType {
// /**
// * !#en Rect mask.
// * !#zh 使用矩形作为遮罩
// */
// RECT = 0,
const _worldMatrix = new Mat4();
const _vec2_temp = new Vec2();
const _mat4_temp = new Mat4();
// /**
// * !#en Ellipse Mask.
// * !#zh 使用椭圆作为遮罩
// */
// ELLIPSE = 1,
const _circlepoints: Vec3[] = [];
function _calculateCircle (center: Vec3, radius: Vec3, segements: number) {
_circlepoints.length = 0;
const anglePerStep = Math.PI * 2 / segements;
for (let step = 0; step < segements; ++step) {
_circlepoints.push(cc.v3(radius.x * Math.cos(anglePerStep * step) + center.x,
radius.y * Math.sin(anglePerStep * step) + center.y, 0));
}
// /**
// * !#en Image Stencil Mask.
// * !#zh 使用图像模版作为遮罩
// */
// IMAGE_STENCIL = 2,
// }
return _circlepoints;
}
/**
* !#en the type for mask.
* !#zh 遮罩组件类型
*/
export enum MaskType {
/**
* !#en Rect mask.
* !#zh 使用矩形作为遮罩
*/
RECT = 0,
// ccenum(MaskType);
/**
* !#en Ellipse Mask.
* !#zh 使用椭圆作为遮罩
*/
ELLIPSE = 1,
/**
* !#en Image Stencil Mask.
* !#zh 使用图像模版作为遮罩
*/
// IMAGE_STENCIL = 2,
}
ccenum(MaskType);
const SEGEMENTS_MIN = 3;
const SEGEMENTS_MAX = 10000;
@@ -76,39 +88,41 @@ const SEGEMENTS_MAX = 10000;
@executionOrder(100)
@menu('UI/Mask')
export class MaskComponent extends UIRenderComponent {
// public static Type = MaskType;
/**
* !#en The mask type.
* !#zh 遮罩类型。
*/
@property({
type: MaskType,
})
get type () {
return this._type;
}
// /**
// * !#en The mask type.
// * !#zh 遮罩类型。
// */
set type (value: MaskType) {
if (this._type === value){
return;
}
this._type = value;
// if (this._type !== MaskType.IMAGE_STENCIL) {
// this.spriteFrame = null;
// this.alphaThreshold = 0;
this._updateGraphics();
// }
if (this._renderData) {
this.destroyRenderData();
this._renderData = null;
}
this._activateMaterial();
}
/**
* !#en The mask image
* !#zh 遮罩所需要的贴图
*/
// @property({
// type: MaskType
// })
// get type () {
// return this._type;
// }
// set type(value: MaskType) {
// this._type = value;
// if (this._type !== MaskType.IMAGE_STENCIL) {
// this.spriteFrame = null;
// this.alphaThreshold = 0;
// this._updateGraphics();
// }
// if (this._renderData) {
// this.destroyRenderData();
// this._renderData = null;
// }
// this._activateMaterial();
// }
// /**
// * !#en The mask image
// * !#zh 遮罩所需要的贴图
// */
// @property({
// type: SpriteFrame
// type: SpriteFrame,
// })
// get spriteFrame () {
// return this._spriteFrame;
@@ -118,6 +132,8 @@ export class MaskComponent extends UIRenderComponent {
// if (this._spriteFrame === value) {
// return;
// }
// this._spriteFrame = value;
// this._applySpriteFrame(value);
// }
@@ -135,11 +151,9 @@ export class MaskComponent extends UIRenderComponent {
* 该数值 0 ~ 1 之间的浮点数,默认值为 0(因此禁用 alpha 测试)
* 当被设置为 1 时,会丢弃所有蒙版像素,所以不会显示任何内容,在之前的版本中,设置为 1 等同于 0,这种效果其实是不正确的
*/
// // @range: [0, 1, 0.1],
// // slide: true,
// @property({
// slide: true,
// range:[0, 1, 0.1]
// range: [0, 1, 0.1],
// })
// get alphaThreshold () {
// return this._alphaThreshold;
@@ -149,10 +163,10 @@ export class MaskComponent extends UIRenderComponent {
// this._alphaThreshold = value;
// }
// /**
// * !#en Reverse mask(Not supported in Canvas Mode).
// * !#zh 反向遮罩(不支持 Canvas 模式)。
// */
/**
* !#en Reverse mask(Not supported in Canvas Mode).
* !#zh 反向遮罩(不支持 Canvas 模式)。
*/
// @property()
// get inverted () {
// return this._inverted;
@@ -166,25 +180,60 @@ export class MaskComponent extends UIRenderComponent {
// }
// }
// /**
// * TODO: remove segments, not supported by graphics
// * !#en The segements for ellipse mask.
// * !#zh 椭圆遮罩的曲线细分数
// */
// @property
// get segments () {
// return this._segments;
// }
/**
* TODO: remove segments, not supported by graphics
* !#en The segements for ellipse mask.
* !#zh 椭圆遮罩的曲线细分数
*/
@property
get segments () {
return this._segments;
}
// set segments (value) {
// this._segments = clamp(value, SEGEMENTS_MIN, SEGEMENTS_MAX);
// }
set segments (value) {
this._segments = vmath.clamp(value, SEGEMENTS_MIN, SEGEMENTS_MAX);
this._updateGraphics();
}
get graphics (){
return this._graphics;
}
get clearGraphics (){
return this._clearGraphics;
}
@property({
visible: false,
override: true,
})
get dstBlendFactor (){
return this._dstBlendFactor;
}
@property({
visible: false,
override: true,
})
get srcBlendFactor () {
return this._srcBlendFactor;
}
@property({
visible: false,
override: true,
})
get color () {
return super.color;
}
public static Type = MaskType;
// @property
// private _spriteFrame: SpriteFrame | null = null;
// @property
// private _type = MaskType.RECT;
@property
private _type = MaskType.RECT;
// @property
// private _alphaThreshold = 0;
@@ -192,22 +241,47 @@ export class MaskComponent extends UIRenderComponent {
// @property
// private _inverted = false;
// @property
// private _segments = 64;
@property
private _segments = 64;
private _maskMaterial: Material | null = null;
private _graphics: GraphicsComponent | null = null;
private _clearGraphics: GraphicsComponent | null = null;
private _clearMaskMaterial: Material | null = null;
constructor (){
super();
this._flushAssembler();
}
private _maskGeometry: IGeometry | null = null;
public onLoad (){
this._createGraphics();
}
private _clearGeometry: IGeometry | null = null;
public onRestore () {
this._createGraphics();
// if (this._type !== MaskType.IMAGE_STENCIL) {
this._updateGraphics();
// }
// else {
// this._applySpriteFrame(null);
// }
}
public onEnable () {
super.onEnable();
this._flushAssembler();
// if (this._type === MaskType.IMAGE_STENCIL) {
// if (!this._spriteFrame || !this._spriteFrame.textureLoaded()) {
// if (this._spriteFrame) {
// this.markForUpdateRenderData(false);
// this._spriteFrame.once('load', this._onTextureLoaded, this);
// this._spriteFrame.ensureLoadTexture();
// }
// }
// }
// else {
this._updateGraphics();
// }
this._activateMaterial();
this._updateGeometry();
this.node.on(EventType.ROTATION_PART, this._nodeStateChange, this);
this.node.on(EventType.SCALE_PART, this._nodeStateChange, this);
@@ -222,22 +296,7 @@ export class MaskComponent extends UIRenderComponent {
public onDestroy () {
super.onDestroy();
}
public getMaskGeometry () {
return this._maskGeometry;
}
public getClearGeometry () {
return this._clearGeometry;
}
public getMaskMaterial (): Material | null {
return this._maskMaterial;
}
public getClearMaterial (): Material | null {
return this._clearMaskMaterial;
this._removeGraphics();
}
public updateAssembler (render: UI) {
@@ -251,15 +310,55 @@ export class MaskComponent extends UIRenderComponent {
public postUpdateAssembler (render: UI) {
if (!this._canRender() || !this._postAssembler) {
return null;
return;
}
render.commitComp(this, null, this._postAssembler!);
}
public isHit (cameraPt: Vec2){
const node = this.node;
const size = node.getContentSize();
const w = size.width;
const h = size.height;
const testPt = _vec2_temp;
this.node.getWorldMatrix(_worldMatrix);
vmath.mat4.invert(_mat4_temp, _worldMatrix);
vmath.vec2.transformMat4(testPt, cameraPt, _mat4_temp);
const ap = node.getAnchorPoint();
testPt.x += ap.x * w;
testPt.y += ap.y * h;
let result = false;
if (this.type === MaskType.RECT /*|| this.type === MaskType.IMAGE_STENCIL*/) {
result = testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h;
}
else if (this.type === MaskType.ELLIPSE) {
const rx = w / 2;
const ry = h / 2;
const px = testPt.x - 0.5 * w;
const py = testPt.y - 0.5 * h;
result = px * px / (rx * rx) + py * py / (ry * ry) < 1;
}
if (this.inverted) {
result = !result;
}
return result;
}
public _resizeNodeToTargetNode () {
// if (!CC_EDITOR){
// return;
// }
// if (this.spriteFrame) {
// const rect = this.spriteFrame.getRect();
// this.node.setContentSize(rect.width, rect.height);
// }
}
protected _nodeStateChange () {
super._nodeStateChange();
this._updateGeometry();
}
protected _canRender () {
@@ -267,138 +366,39 @@ export class MaskComponent extends UIRenderComponent {
return false;
}
return this._maskMaterial !== null && this._clearMaskMaterial !== null && this._renderPermit;
return this._clearGraphics !== null && this._graphics !== null && this._renderPermit;
}
protected _instanceMaterial () {
let useMat: Material | null = null;
let mat: Material | null = null;
if (this._sharedMaterial) {
useMat = this._sharedMaterial;
this._updateMaterial(Material.getInstantiatedMaterial(useMat, new RenderableComponent(), CC_EDITOR ? true : false));
mat = Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false);
} else {
useMat = cc.builtinResMgr.get('ui-base-material');
this._updateMaterial(Material.getInstantiatedMaterial(useMat!, new RenderableComponent(), CC_EDITOR ? true : false));
// if (this._type === MaskType.IMAGE_STENCIL) {
// if (UIRenderComponent.addTextureMat) {
// mat = new Material();
// mat.copy(UIRenderComponent.addTextureMat);
// } else {
// mat = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-material'), new RenderableComponent(), CC_EDITOR ? true : false);
// mat.initialize({ defines: { USE_TEXTURE: true } });
// UIRenderComponent.addTextureMat = mat;
// }
// } else {
if (UIRenderComponent.addColorMat) {
mat = new Material();
mat.copy(UIRenderComponent.addColorMat);
} else {
mat = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-material'), new RenderableComponent(), CC_EDITOR ? true : false);
mat.initialize({ defines: { USE_TEXTURE: false } });
UIRenderComponent.addColorMat = mat;
}
// }
}
this._clearMaskMaterial = Material.getInstantiatedMaterial(useMat!, new RenderableComponent(), CC_EDITOR ? true : false);
this._maskMaterial = Material.getInstantiatedMaterial(useMat!, new RenderableComponent(), CC_EDITOR ? true : false);
this._updateMaterial(mat);
}
// _resizeNodeToTargetNode: CC_EDITOR && function () {
// if (this.spriteFrame) {
// const rect = this.spriteFrame.getRect();
// this.node.setContentSize(rect.width, rect.height);
// }
// }
// private _onTextureLoaded () {
// // Mark render data dirty
// if (this._renderData) {
// this._renderData.uvDirty = true;
// this._renderData.vertDirty = true;
// }
// // Reactivate material
// if (this.enabledInHierarchy) {
// this._activateMaterial();
// }
// }
// private _applySpriteFrame (oldFrame) {
// if (oldFrame && oldFrame.off) {
// oldFrame.off('load', this._onTextureLoaded, this);
// }
// const spriteFrame = this._spriteFrame;
// if (spriteFrame) {
// if (spriteFrame.textureLoaded()) {
// this._onTextureLoaded();
// } else {
// spriteFrame.once('load', this._onTextureLoaded, this);
// spriteFrame.ensureLoadTexture();
// }
// }
// }
private _updateGeometry (){
this._maskGeometry = this._getGraphics();
this._clearGeometry = this._drawRect(
0, 0, cc.visibleRect.width, cc.visibleRect.height);
}
private _activateMaterial () {
// if (!this._maskMaterial) {
// this._maskMaterial = Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-material'), this, CC_EDITOR ? true : false);
// setupMaskMaterial(this._maskMaterial);
// }
// if (!this._clearMaskMaterial) {
// this._clearMaskMaterial = Material.getInstantiatedMaterial(cc.builtinResMgr.get('sprite-material'), this, CC_EDITOR ? true : false);
// setupClearMaskMaterial(this._clearMaskMaterial);
// }
if (this._sharedMaterial) {
if (!this._maskMaterial) {
this._maskMaterial = Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false);
// setupMaskMaterial(this._maskMaterial);
}
if (!this._clearMaskMaterial) {
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);
}
}
}
private _getGraphics () {
const uiTransform = this.node.getComponent(UITransformComponent);
if (!uiTransform) {
return null;
}
const width = uiTransform.width;
const height = uiTransform.height;
const x = -width * uiTransform.anchorPoint.x;
const y = -height * uiTransform.anchorPoint.y;
return this._drawRect(x, y, width, height);
// switch (this._type) {
// case MaskType.RECT:
// case MaskType.IMAGE_STENCIL:
// return this._drawRect(x, y, width, height);
// case MaskType.ELLIPSE:
// const cx = x + width / 2;
// const cy = y + height / 2;
// const rx = width / 2;
// const ry = height / 2;
// return this._drawEllipse(cx, cy, rx, ry);
// }
// return null;
}
private _drawRect (x: number, y: number, width: number, height: number) {
const geometry = quad({ includeNormal: false, includeUV: false });
scale(geometry, { x: width, y: height });
translate(geometry, { x: x + width / 2, y: y + height / 2 });
return geometry;
}
// private _drawEllipse (cx, cy, rx, ry) {
// const geometry = circle({ includeNormal: false, includeUV: false });
// scale(geometry, { x: rx, y: ry });
// translate(geometry, { x: cx, y: cy });
// return geometry;
// }
private _flushAssembler (){
protected _flushAssembler (){
const assembler = MaskComponent.Assembler!.getAssembler(this);
const posAssembler = MaskComponent.PostAssembler!.getAssembler(this);
@@ -419,6 +419,110 @@ export class MaskComponent extends UIRenderComponent {
}
}
}
private _onTextureLoaded () {
// Mark render data dirty
if (this._renderData) {
this._renderData.uvDirty = true;
this._renderData.vertDirty = true;
}
// Reactivate material
if (this.enabledInHierarchy) {
this._activateMaterial();
}
}
private _applySpriteFrame (oldFrame: SpriteFrame | null) {
// if (oldFrame && oldFrame.off) {
// oldFrame.off('load', this._onTextureLoaded, this);
// }
// const spriteFrame = this._spriteFrame;
// if (spriteFrame) {
// if (spriteFrame.textureLoaded()) {
// this._onTextureLoaded();
// } else {
// spriteFrame.once('load', this._onTextureLoaded, this);
// spriteFrame.ensureLoadTexture();
// }
// }
}
private _createGraphics () {
if (!this._clearGraphics) {
this._clearGraphics = new GraphicsComponent();
this._clearGraphics.node = new Node('clear-graphics');
this._clearGraphics._activateMaterial();
this._clearGraphics.lineWidth = 0;
this._clearGraphics.rect(0, 0, cc.visibleRect.width, cc.visibleRect.height);
this._clearGraphics.fill();
}
if (!this._graphics) {
this._graphics = new GraphicsComponent();
this._graphics.node = this.node;
this._graphics.lineWidth = 0;
this._graphics.strokeColor = cc.color(0, 0, 0, 0);
}
}
private _updateGraphics () {
if (!this._graphics){
return;
}
const node = this.node;
const graphics = this._graphics;
// Share render data with graphics content
graphics.clear();
const size = node.getContentSize();
const width = size.width;
const height = size.height;
const ap = node.getAnchorPoint();
const x = -width * ap.x;
const y = -height * ap.y;
if (this._type === MaskType.RECT) {
graphics.rect(x, y, width, height);
} else if (this._type === MaskType.ELLIPSE) {
const center = cc.v3(x + width / 2, y + height / 2, 0);
const radius = cc.v3(width / 2, height / 2, 0,
);
const points = _calculateCircle(center, radius, this._segments);
for (let i = 0; i < points.length; ++i) {
const point = points[i];
if (i === 0) {
graphics.moveTo(point.x, point.y);
} else {
graphics.lineTo(point.x, point.y);
}
}
graphics.close();
}
graphics.fill();
}
private _removeGraphics () {
if (this._graphics) {
this._graphics.destroy();
}
if (this._clearGraphics) {
this._clearGraphics.destroy();
}
}
private _activateMaterial () {
// if (this._type === MaskType.IMAGE_STENCIL && (!this.spriteFrame || !this.spriteFrame.textureLoaded())) {
// this._renderPermit = false;
// return;
// }
// if (this._sharedMaterial){
// return;
// }
// this._instanceMaterial();
}
}
// tslint:disable-next-line
+21 -19
View File
@@ -506,32 +506,34 @@ export class SpriteComponent extends UIRenderComponent {
// return false;
// }
// return true;
let canRender = super._canRender();
if (canRender) {
const spriteFrame = this._spriteFrame;
if (!spriteFrame || !spriteFrame.textureLoaded()) {
canRender = false;
}
canRender = true;
if (!super._canRender()){
return false;
}
return canRender;
const spriteFrame = this._spriteFrame;
if (!spriteFrame || !spriteFrame.textureLoaded()) {
return false;
}
return true;
}
protected _instanceMaterial () {
let mat: Material | null = null;
if (this._sharedMaterial) {
this._updateMaterial(
Material.getInstantiatedMaterial(this._sharedMaterial,
new RenderableComponent(),
CC_EDITOR ? true : false,
));
mat = Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false);
} else {
this._updateMaterial(
Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-material'),
new RenderableComponent(),
CC_EDITOR ? true : false,
));
if (UIRenderComponent.addTextureMat) {
mat = new Material();
mat.copy(UIRenderComponent.addTextureMat);
} else {
mat = Material.getInstantiatedMaterial(cc.builtinResMgr.get('ui-sprite-material'), new RenderableComponent(), CC_EDITOR ? true : false);
mat.initialize({ defines: { USE_TEXTURE: true}});
UIRenderComponent.addTextureMat = mat;
}
}
this._updateMaterial(mat);
}
private _flushAssembler () {
@@ -545,7 +547,7 @@ export class SpriteComponent extends UIRenderComponent {
if (!this._renderData) {
if (this._assembler && this._assembler.createData) {
this._renderData = this._assembler.createData(this);
this._renderData.material = this._material;
this._renderData!.material = this._material;
this.markForUpdateRenderData();
}
}
+14 -22
View File
@@ -23,7 +23,6 @@
THE SOFTWARE.
****************************************************************************/
import { Component } from '../../../components/component';
import {
ccclass,
executeInEditMode,
@@ -61,8 +60,6 @@ ccenum(GFXBlendFactor);
@executeInEditMode
export class UIRenderComponent extends UIComponent {
public static BlendState = GFXBlendFactor;
/**
* !#en specify the source Blend Factor, this will generate a custom material object
* please pay attention to the memory cost.
@@ -153,6 +150,12 @@ export class UIRenderComponent extends UIComponent {
}
get material () {
if (!this._material){
if (this._instanceMaterial) {
this._instanceMaterial();
}
}
return this._material;
}
@@ -160,9 +163,15 @@ export class UIRenderComponent extends UIComponent {
return this._renderData;
}
public static BlendState = GFXBlendFactor;
public static Assembler: IAssemblerManager | null = null;
public static PostAssembler: IAssemblerManager | null = null;
// 预先定制两份 UI 常用材质,也许之后需要修改
public static addColorMat: Material | null = null;
public static addTextureMat: Material | null = null;
@property
protected _srcBlendFactor = GFXBlendFactor.SRC_ALPHA;
@property
@@ -193,16 +202,6 @@ export class UIRenderComponent extends UIComponent {
rasterizerState: {},
};
// _allocedDatas = [];
// _vertexFormat = null;
// _toPostHandle = false;
constructor () {
super();
// this._assembler = this.constructor._assembler;
// this._postAssembler = this.constructor._postAssembler;
}
public __preload (){
if (this._instanceMaterial) {
this._instanceMaterial();
@@ -306,13 +305,6 @@ export class UIRenderComponent extends UIComponent {
return true;
}
public postUpdateAssembler (render: UI) {
}
public updateRenderData (force = false) {
}
protected _checkAndUpdateRenderData (){
if (this._renderDataDirty) {
this._assembler!.updateRenderData!(this);
@@ -321,7 +313,7 @@ export class UIRenderComponent extends UIComponent {
}
protected _canRender () {
return this._material !== null && this._renderPermit;
return this.material !== null && this._renderPermit;
}
protected _updateColor () {
@@ -361,7 +353,7 @@ export class UIRenderComponent extends UIComponent {
for (const child of this.node.children) {
const renderComp = child.getComponent(UIRenderComponent);
if (renderComp) {
renderComp.updateRenderData();
renderComp.markForUpdateRenderData();
}
}
}
@@ -1,7 +1,7 @@
import { Component} from '../../../components/component';
import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator';
import { EventType } from '../../../core/platform/event-manager/event-enum';
import { EventListener } from '../../../core/platform/event-manager/event-listener';
import { EventListener, ILinstenerMask } from '../../../core/platform/event-manager/event-listener';
import { Mat4, Rect, Size, Vec2, Vec3 } from '../../../core/value-types';
import * as vmath from '../../../core/vmath';
import { CanvasComponent } from './canvas-component';
@@ -233,12 +233,14 @@ export class UITransformComponent extends Component {
if (testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h) {
if (listener && listener.mask) {
const mask = listener.mask;
const parent = this.node;
const mask = listener.mask as ILinstenerMask;
let parent: any = this.node;
// find mask parent, should hit test it
for (let i = 0; parent && i < mask.index; ++i, parent = parent.parent) {
}
if (parent === mask.node) {
const comp = parent.getComponent(cc.MaskComponent);
return (comp && comp.enabledInHierarchy) ? comp.node.uiTransfromComp!.isHit(cameraPt) : true;
return (comp && comp.enabledInHierarchy) ? comp.isHit(cameraPt) : true;
} else {
listener.mask = null;
return true;
+1 -1
View File
@@ -31,7 +31,7 @@ import { Rect, Size, Vec2 } from '../core/value-types';
import { vec2 } from '../core/vmath';
import { ImageAsset } from './image-asset';
import { ITexture2DSerializeData, Texture2D } from './texture-2d';
import textureUtil from './texture-util';
import * as textureUtil from './texture-util';
const INSET_LEFT = 0;
const INSET_TOP = 1;
-112
View File
@@ -1,112 +0,0 @@
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
import { ImageAsset } from './image-asset';
import { Texture2D } from './texture-2d';
/**
* cc.textureUtil is a singleton object, it can load cc.Texture2D asynchronously
* @class textureUtil
* @static
*/
let textureUtil = {
loadImage (url, cb, target) {
cc.assertID(url, 3103);
var tex = cc.loader.getRes(url);
if (tex) {
if (tex.loaded) {
cb && cb.call(target, tex);
return tex;
}
else
{
tex.once("load", function(){
cb && cb.call(target, tex);
}, target);
return tex;
}
}
else {
tex = new Texture2D();
tex.url = url;
cc.loader.load({url: url, texture: tex}, function (err, texture) {
if (err) {
return cb && cb.call(target, err || new Error('Unknown error'));
}
texture.handleLoadedTexture();
cb && cb.call(target, null, texture);
});
return tex;
}
},
cacheImage (url, image) {
if (url && image) {
var tex = new Texture2D();
tex.image = new ImageAsset(image);
var item = {
id: url,
url: url, // real download url, maybe changed
error: null,
content: tex,
complete: false
}
cc.loader.flowOut(item);
return tex;
}
},
postLoadTexture (texture, callback) {
if (texture.loaded) {
callback && callback();
return;
}
if (!texture.url) {
callback && callback();
return;
}
// load image
cc.loader.load({
url: texture.url,
// For image, we should skip loader otherwise it will load a new texture
skips: ['Loader'],
}, function (err, image) {
if (image) {
if (CC_DEBUG && image instanceof cc.Texture2D) {
return cc.error('internal error: loader handle pipe must be skipped');
}
if (!texture.loaded) {
texture._nativeAsset = image;
}
}
callback && callback(err);
});
}
};
cc.textureUtil = textureUtil;
export default textureUtil;
+126
View File
@@ -0,0 +1,126 @@
/****************************************************************************
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 { ImageAsset, ImageSource } from './image-asset';
import { Texture2D } from './texture-2d';
/**
* cc.textureUtil is a singleton object, it can load cc.Texture2D asynchronously
* @class textureUtil
* @static
*/
export function loadImage (url: string, cb, target) {
cc.assertID(url, 3103);
let tex = cc.loader.getRes(url);
if (tex) {
if (tex.loaded) {
if (cb){
cb.call(target, tex);
}
return tex;
}
else {
tex.once('load', () => {
if (cb) {
cb.call(target, tex);
}
}, target);
return tex;
}
}
else {
tex = new Texture2D();
tex.url = url;
cc.loader.load({ url, texture: tex }, (err, texture) => {
if (err) {
return cb && cb.call(target, err || new Error('Unknown error'));
}
texture.handleLoadedTexture();
if (cb) {
cb.call(target, null, texture);
}
});
return tex;
}
}
export function cacheImage (url: string, image: ImageSource) {
if (url && image) {
const tex = new Texture2D();
tex.image = new ImageAsset(image);
const item = {
id: url,
url, // real download url, maybe changed
error: null,
content: tex,
complete: false,
};
cc.loader.flowOut(item);
return tex;
}
}
// TODO:
export function postLoadTexture (texture: Texture2D, callback: Function) {
if (texture.loaded) {
if (callback){
callback();
}
return;
}
if (!texture.nativeUrl) {
if (callback) {
callback();
}
return;
}
// load image
cc.loader.load({
url: texture.nativeUrl,
// For image, we should skip loader otherwise it will load a new texture
skips: ['Loader'],
}, (err, image) => {
if (image) {
if (CC_DEBUG && image instanceof cc.Texture2D) {
return cc.error('internal error: loader handle pipe must be skipped');
}
if (!texture.loaded) {
texture._nativeAsset = image;
}
}
if (callback) {
callback(err);
}
});
}
cc.textureUtil = {
loadImage,
cacheImage,
postLoadTexture,
};
@@ -1,4 +1,3 @@
import { MaskComponent } from "../../../3d/ui/components/mask-component";
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
@@ -25,6 +24,7 @@ import { MaskComponent } from "../../../3d/ui/components/mask-component";
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
import { Node } from '../../../scene-graph';
export interface IEventListenerCreateInfo {
event?: number;
@@ -32,6 +32,11 @@ export interface IEventListenerCreateInfo {
[x: string]: any;
}
export interface ILinstenerMask {
index: number;
node: Node;
}
/**
* !#en
* <p>
@@ -142,7 +147,7 @@ export class EventListener {
// hack: How to solve the problem of uncertain attribute
// callback's this object
public owner: Object | null = null;
public mask: MaskComponent | null = null;
public mask: ILinstenerMask | null = null;
public _previousIn?: boolean = false;
public _target: any = null;
+8 -4
View File
@@ -323,15 +323,18 @@ export class NodeEventProcessor {
* 你也可以注册自定义事件到节点上,并通过 emit 方法触发此类事件,对于这类事件,不会发生捕获冒泡阶段,只会直接派发给注册在该节点上的监听器<br/>
* 你可以通过在 emit 方法调用时在 type 之后传递额外的参数作为事件回调的参数列表
* @method on
* @param {String|Node.EventType} type - A string representing the event type to listen for.<br>See {{#crossLink "Node/EventTyupe/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events.
* @param {Function} callback - The callback that will be invoked when the event is dispatched. The callback is ignored if it is a duplicate (the callbacks are unique).
* @param {String|Node.EventType} type - A string representing the event type to listen for.
* <br>See {{#crossLink "Node/EventTyupe/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events.
* @param {Function} callback - The callback that will be invoked when the event is dispatched.
* The callback is ignored if it is a duplicate (the callbacks are unique).
* @param {Event|any} [callback.event] event or first argument when emit
* @param {any} [callback.arg2] arg2
* @param {any} [callback.arg3] arg3
* @param {any} [callback.arg4] arg4
* @param {any} [callback.arg5] arg5
* @param {Object} [target] - The target (this object) to invoke the callback, can be null
* @param {Boolean} [useCapture=false] - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase.
* @param {Boolean} [useCapture=false] - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit,
* otherwise it will be triggered during bubbling phase.
* @return {Function} - Just returns the incoming callback so you can save the anonymous function easier.
* @typescript
* on<T extends Function>(type: string, callback: T, target?: any, useCapture?: boolean): T
@@ -425,7 +428,8 @@ export class NodeEventProcessor {
* @param {String} type - A string representing the event type being removed.
* @param {Function} [callback] - The callback to remove.
* @param {Object} [target] - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed
* @param {Boolean} [useCapture=false] - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase.
* @param {Boolean} [useCapture=false] - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit,
* otherwise it will be triggered during bubbling phase.
* @example
* this.node.off(cc.Node.EventType.TOUCH_START, this.memberFunction, this);
* node.off(cc.Node.EventType.TOUCH_START, callback, this.node);