This commit is contained in:
jerrywwl
2019-03-06 09:28:42 +08:00
29 changed files with 539 additions and 478 deletions
+3 -2
View File
@@ -29,6 +29,7 @@ import { GFXBindingType } from '../../gfx/define';
import { GFXTextureView } from '../../gfx/texture-view';
import { Effect, IDefineMap } from '../../renderer/core/effect';
import { Pass, PassOverrides } from '../../renderer/core/pass';
import { builtinResMgr } from '../builtin';
import { RenderableComponent } from '../framework/renderable-component';
import { EffectAsset } from './effect-asset';
@@ -198,9 +199,9 @@ export class Material extends Asset {
protected _update (asset: EffectAsset | null = this._effectAsset, keepProps: boolean = true) {
// get effect asset
this._effectAsset = asset;
if (!this._effectAsset) { return; }
asset = asset || builtinResMgr.get<Material>('default-material').effectAsset!;
// create passes
this._passes = Effect.parseEffect(this._effectAsset, {
this._passes = Effect.parseEffect(asset, {
techIdx: this._techIdx,
defines: this._defines,
});
+3 -2
View File
@@ -80,8 +80,9 @@ export class TextureCube extends TextureBase {
}
/**
* @param textures
* @deprecated Manually assign to mipmaps property instead.
* convenient util for cubemap creation (even with custom mipmaps)
* @param texture - texture asset array containing six faces in a row
* @param out - the resulting texture cube asset
*/
public static fromTexture2DArray (textures: Texture2D[], out?: TextureCube) {
const mipmaps: ITextureCubeMipmap[] = [];
@@ -3,7 +3,7 @@ import { Enum } from "../../../../core/value-types";
import CurveRange from "./curve-range";
import { CCClass } from "../../../../core/data";
import { property, ccclass } from "../../../../core/data/class-decorator";
import ParticleSystemComponent from "../particle-system-component";
import { ParticleSystemComponent } from "../particle-system-component";
import Particle from "../particle";
// tslint:disable: max-line-length
+1 -1
View File
@@ -55,7 +55,7 @@ export default class Burst {
}
public update (psys, dt: number) {
if (psys.loop && this._remainingCount === 0) {
if (this._remainingCount === 0) {
this._remainingCount = this._repeatCount;
this._curTime = this._time;
}
@@ -4,7 +4,7 @@ import { Enum, Vec3 } from '../../../../core/value-types';
import CurveRange from '../animator/curve-range';
import { CCClass } from '../../../../core/data';
import { property, ccclass } from '../../../../core/data/class-decorator';
import ParticleSystemComponent from '../particle-system-component';
import { ParticleSystemComponent } from '../particle-system-component';
// tslint:disable: max-line-length
const _intermediVec = vec3.create(0, 0, 0);
+1 -1
View File
@@ -1,6 +1,6 @@
import { vec3, color4 } from '../../../core/vmath';
import { Color } from '../../../core/value-types';
import ParticleSystemComponent from './particle-system-component';
import { ParticleSystemComponent } from './particle-system-component';
export default class Particle {
public particleSystem: ParticleSystemComponent;
@@ -4,7 +4,6 @@ import { mat4, vec2, vec3, vec4 } from '../../../../core/vmath';
import { GFXAttributeName, GFXFormat } from '../../../../gfx/define';
import { IGFXInputAttribute } from '../../../../gfx/input-assembler';
import * as renderer from '../../../../renderer';
import gfx from '../../../../renderer/gfx';
import ParticleBatchModel from '../../../../renderer/models/particle-batch-model';
import { Material } from '../../../assets/material';
import RecyclePool from '../../../memop/recycle-pool';
@@ -0,0 +1,11 @@
import { PhysicsMaterial } from '../../assets/physics/material';
export const DefaultPhysicsMaterial: PhysicsMaterial = (() => {
const result = new PhysicsMaterial();
result.friction = 0.3;
result.restitution = 0.3;
return result;
})();
cc.DefaultPhysicsMaterial = DefaultPhysicsMaterial;
@@ -5,6 +5,7 @@ import { Quat, Vec3 } from '../../../../core/value-types';
import { quat, vec3 } from '../../../../core/vmath';
import { Node } from '../../../../scene-graph/node';
import { BoxColliderComponent, ColliderComponentBase, SphereColliderComponent } from '../collider-component';
import { DefaultPhysicsMaterial } from '../default-material';
import { getWrap, setWrap } from '../util';
import { PhysicsWorld } from '../world';
@@ -103,7 +104,9 @@ class SharedRigidBody {
private _worldScale: Vec3 = new Vec3(1, 1, 1);
constructor (node: Node, world: PhysicsWorld) {
this._body = new CANNON.Body();
this._body = new CANNON.Body({
material: DefaultPhysicsMaterial._getImpl(),
});
this._node = node;
setWrap<Node>(this._body, this._node);
this._world = world;
@@ -10,6 +10,7 @@ import {
import { Quat, Vec3 } from '../../../core/value-types';
import { vec3 } from '../../../core/vmath';
import { PhysicsMaterial } from '../../assets/physics/material';
import { DefaultPhysicsMaterial as DefaultPhysicsMaterial } from './default-material';
import { PhysicsBasedComponent, TransformSource } from './detail/physics-based-component';
import { toCannonVec3 } from './util';
@@ -62,12 +63,16 @@ export class RigidBodyComponent extends PhysicsBasedComponent {
this.mass = this._mass;
this.linearDamping = this._linearDamping;
this.angularDamping = this._angularDamping;
this.material = this._material;
this.useGravity = this._useGravity;
}
public onDisable () {
this.mass = NonRigidBodyProperties.mass;
this.linearDamping = NonRigidBodyProperties.linearDamping;
this.angularDamping = NonRigidBodyProperties.angularDamping;
this.material = DefaultPhysicsMaterial;
this.useGravity = true;
}
@property({
@@ -80,7 +85,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent {
set material (value) {
this._material = value;
if (this._body) {
this._body.material = this._material ? this._material._getImpl() : null;
this._body.material = (this._material || DefaultPhysicsMaterial)._getImpl();
}
}
+3 -7
View File
@@ -5,6 +5,7 @@ import { Node } from '../../../scene-graph/node';
import { PhysicsMaterial } from '../../assets/physics/material';
import { Constraint } from './constraints';
import { ContactMaterial } from './contact-material';
import { DefaultPhysicsMaterial } from './default-material';
import { getWrap, setWrap, toCannonOptions } from './util';
export interface IRaycastOptions {
@@ -40,24 +41,19 @@ cc.RaycastResult = RaycastResult;
export class PhysicsWorld {
private _cannonWorld: CANNON.World;
private _defaultMaterial: PhysicsMaterial;
private _defaultContactMaterial: ContactMaterial;
private _beforeStepEvent: CANNON.IEvent = {
type: 'beforeStep',
};
constructor () {
this._defaultMaterial = new PhysicsMaterial();
const mtl = new PhysicsMaterial();
mtl.friction = 0.3;
mtl.restitution = 0;
this._defaultContactMaterial = new ContactMaterial(this._defaultMaterial, mtl);
this._defaultContactMaterial = new ContactMaterial(DefaultPhysicsMaterial, DefaultPhysicsMaterial);
this._cannonWorld = new CANNON.World();
setWrap<PhysicsWorld>(this._cannonWorld, this);
this._cannonWorld.gravity.set(0, -9.81, 0);
this._cannonWorld.broadphase = new CANNON.NaiveBroadphase();
this._cannonWorld.defaultMaterial = this._defaultMaterial._getImpl();
this._cannonWorld.defaultMaterial = DefaultPhysicsMaterial._getImpl();
this._cannonWorld.defaultContactMaterial = this._defaultContactMaterial._getImpl();
}
+71 -83
View File
@@ -1,6 +1,8 @@
import { GFXComparisonFunc, GFXStencilOp } from '../../../../gfx/define';
import { Material } from '../../../assets/material';
import { MaskComponent } from '../../components/mask-component';
import { Pass, Effect } from '../../../../renderer';
import { IPassInfo } from '../../../assets/effect-asset';
// import { GFXStencilOp } from '../../../../gfx/define';
// import { MaskComponent } from '../../components/mask-component';
@@ -65,29 +67,6 @@ function updateDynamicStencilStates (material: Material, state: IStencilStateUpd
}
function overrideStencilState (material: Material, state: IStencilState) {
material.overridePipelineStates({
depthStencilState: {
stencilTestFront: state.stencilTest,
stencilFuncFront: state.func,
stencilReadMaskFront: state.stencilMask,
stencilWriteMaskFront: state.writeMask,
stencilFailOpFront: state.failOp,
stencilZFailOpFront: state.zFailOp,
stencilPassOpFront: state.passOp,
stencilRefFront: state.ref,
stencilTestBack: state.stencilTest,
stencilFuncBack: state.func,
stencilReadMaskBack: state.stencilMask,
stencilWriteMaskBack: state.writeMask,
stencilFailOpBack: state.failOp,
stencilZFailOpBack: state.zFailOp,
stencilPassOpBack: state.passOp,
stencilRefBack: state.ref,
},
});
}
export class StencilManager {
public static sharedManager: StencilManager | null = null;
public stage = Stage.DISABLED;
@@ -134,58 +113,52 @@ export class StencilManager {
}
public handleMaterial (mat: Material){
const pattern = this._stencilPattern;
if (this.stage === Stage.DISABLED) {
pattern.stencilTest = false;
} else {
pattern.stencilTest = true;
if (this.stage === Stage.ENABLED) {
pattern.func = GFXComparisonFunc.EQUAL;
pattern.failOp = GFXStencilOp.KEEP;
pattern.stencilMask = pattern.ref = this.getStencilRef();
pattern.writeMask = this.getWriteMask();
} else if (this.stage === Stage.CLEAR) {
pattern.func = GFXComparisonFunc.NEVER;
pattern.failOp = GFXStencilOp.ZERO;
pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
} else if (this.stage === Stage.ENTER_LEVEL) {
pattern.func = GFXComparisonFunc.NEVER;
pattern.failOp = GFXStencilOp.REPLACE;
pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
}
}
} else if (this.stage === Stage.ENABLED) {
this.updateMaskTargetMaterial(mat);
} else if (this.stage === Stage.CLEAR) {
this.updateClearMaskMaterial(mat);
} else if (this.stage === Stage.ENTER_LEVEL){
this.updateMaskMaterial(mat);
const state = this._stencilPattern;
if (this._changed(mat.passes[0])){
mat.overridePipelineStates({
depthStencilState: {
stencilTestFront: state.stencilTest,
stencilFuncFront: state.func,
stencilReadMaskFront: state.stencilMask,
stencilWriteMaskFront: state.writeMask,
stencilFailOpFront: state.failOp,
stencilZFailOpFront: state.zFailOp,
stencilPassOpFront: state.passOp,
stencilRefFront: state.ref,
stencilTestBack: state.stencilTest,
stencilFuncBack: state.func,
stencilReadMaskBack: state.stencilMask,
stencilWriteMaskBack: state.writeMask,
stencilFailOpBack: state.failOp,
stencilZFailOpBack: state.zFailOp,
stencilPassOpBack: state.passOp,
stencilRefBack: state.ref,
},
});
}
}
public updateMaskMaterial (material: Material) {
const pattern = this._stencilPattern;
pattern.func = GFXComparisonFunc.NEVER;
pattern.failOp = GFXStencilOp.REPLACE;
pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
overrideStencilState(material, pattern);
}
public updateClearMaskMaterial (material: Material) {
const pattern = this._stencilPattern;
pattern.func = GFXComparisonFunc.NEVER;
pattern.failOp = GFXStencilOp.ZERO;
pattern.writeMask = pattern.stencilMask = pattern.ref = this.getWriteMask();
overrideStencilState(material, pattern);
}
public updateMaskTargetMaterial (material: Material) {
const pattern = this._stencilPattern;
pattern.func = GFXComparisonFunc.EQUAL;
pattern.failOp = GFXStencilOp.KEEP;
pattern.stencilMask = pattern.ref = this.getStencilRef();
pattern.writeMask = this.getWriteMask();
overrideStencilState(material, pattern);
}
// public updateMaskMaterial (material: Material) {
// updateDynamicStencilStates (material, {
// func: GFXComparisonFunc.ALWAYS,
// writeMask: this._protectAncestorMasks(),
// ref: this._getWriteMaskForTopMask(),
// });
// }
// public updateClearMaskMaterial (material: Material) {
// updateDynamicStencilStates(material, {
// func: GFXComparisonFunc.NEVER,
// writeMask: this._protectAncestorMasks(),
// ref: 0,
// });
// }
public getWriteMask () {
return 0x00000001 << (this._maskStack.length - 1);
}
@@ -202,21 +175,36 @@ export class StencilManager {
return result;
}
// private _readAncestorMasks (): number {
// let result = 0;
// this._maskStack.forEach((mask, iBit) => {
// result |= (1 << iBit);
// });
// return result;
// }
public getInvertedRef () {
let result = 0;
for (let i = 0; i < this._maskStack.length - 1; ++i) {
result += (0x01 << i);
}
return result;
}
// private _protectAncestorMasks (): number {
// return ~this._readAncestorMasks();
// }
public reset () {
// reset stack and stage
this._maskStack.length = 0;
this.stage = Stage.DISABLED;
}
// private _getWriteMaskForTopMask (): number {
// return 1 << this._maskStack.length;
// }
private _changed (pass: Pass) {
const stencilState = pass.depthStencilState;
const pattern = this._stencilPattern;
if (pattern.stencilTest !== stencilState.stencilTestFront ||
pattern.func !== stencilState.stencilFuncFront ||
pattern.failOp !== stencilState.stencilFailOpFront ||
pattern.zFailOp !== stencilState.stencilZFailOpFront ||
pattern.passOp !== stencilState.stencilPassOpFront ||
pattern.stencilMask !== stencilState.stencilReadMaskFront ||
pattern.writeMask !== stencilState.stencilWriteMaskFront ||
pattern.ref !== stencilState.stencilRefFront) {
return true;
}
return false;
}
}
StencilManager.sharedManager = new StencilManager();
+2 -2
View File
@@ -31,10 +31,10 @@ import { ImageAsset } from '../../../assets/image-asset';
import { ccclass, executionOrder, menu, property } from '../../../core/data/class-decorator';
import macro from '../../../core/platform/CCMacro';
import { ccenum } from '../../../core/value-types/enum';
import { UI } from '../../../renderer/ui/ui';
import { FontAtlas } from '../assembler/label/bmfontUtils';
import { ISharedLabelData } from '../assembler/label/ttfUtils';
import { UIRenderComponent } from './ui-render-component';
import { UI } from '../../../renderer/ui/ui';
/**
* !#en Enum for text alignment.
@@ -539,7 +539,7 @@ export class LabelComponent extends UIRenderComponent {
private _texture: SpriteFrame | null = null;
private _ttfTexture: SpriteFrame | null = null;
private _userDefinedFont: Font | null = null;
private _assemblerData: ISharedLabelData|null = null;
private _assemblerData: ISharedLabelData | null = null;
private _fontAtlas: FontAtlas | null = null;
constructor () {
+2 -2
View File
@@ -501,7 +501,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.sharedMaterial;
this._renderData.material = this._material;
this.markForUpdateRenderData();
}
}
@@ -509,7 +509,7 @@ export class SpriteComponent extends UIRenderComponent {
private _activateMaterial () {
const spriteFrame = this._spriteFrame;
const material = this.sharedMaterial;
const material = this._material;
// WebGL
if (cc.game.renderType !== cc.game.RENDER_TYPE_CANVAS) {
// if (!material) {
+7 -15
View File
@@ -150,6 +150,10 @@ export class UIRenderComponent extends Component {
this._instanceMaterial();
}
get material () {
return this._material;
}
/**
* !#en find the rendered camera
* !#zh 查找被渲染相机
@@ -162,18 +166,6 @@ export class UIRenderComponent extends Component {
return this._renderData;
}
get material () {
return this._material;
}
set material (value: Material | null) {
if (this._material === value) {
return;
}
this._updateMaterial(value);
}
public static Assembler: IAssemblerManager | null = null;
public static PostAssembler: IAssemblerManager | null = null;
@@ -255,7 +247,7 @@ export class UIRenderComponent extends Component {
// }
// this._allocedDatas.length = 0;
this.destroyRenderData();
this.material = null;
this._updateMaterial(null);
this._renderData = null;
}
@@ -338,7 +330,7 @@ export class UIRenderComponent extends Component {
}
protected _updateColor () {
const material = this.material;
const material = this._material;
if (material) {
material.setProperty('color', this._color);
// material.updateHash();
@@ -387,7 +379,7 @@ export class UIRenderComponent extends Component {
private _instanceMaterial (){
if (this._sharedMaterial) {
this.material = Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false);
this._updateMaterial(Material.getInstantiatedMaterial(this._sharedMaterial, new RenderableComponent(), CC_EDITOR ? true : false));
}
}
}
@@ -1,5 +1,6 @@
import { Component} from '../../../components/component';
import { ccclass, executeInEditMode, executionOrder, menu, property } from '../../../core/data/class-decorator';
import { EventListener } from '../../../core/platform/event-manager/CCEventListener';
import { Mat4, Rect, Size, Vec2, Vec3 } from '../../../core/value-types';
import * as math from '../../../core/vmath/index';
import { EventType } from '../../../scene-graph/node-event-enum';
@@ -225,22 +226,20 @@ export class UITransformComponent extends Component {
testPt.y += this._anchorPoint.y * h;
if (testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h) {
// console.log('wpos '+this.node.getWorldPosition().toString());
// console.log('click '+this.node.name);
// if (listener && listener.mask) {
// const mask = listener.mask;
// const parent = this;
// // find mask parent, should hit test it
// if (parent === mask.node) {
// const comp = parent.getComponent(MaskComponent);
// return (comp && comp.enabledInHierarchy) ? comp.node.uiTransfromComp!.isHit(cameraPt) : true;
// } else {
// listener.mask = null;
// return true;
// }
// } else {
if (listener && listener.mask) {
const mask = listener.mask;
const parent = this.node;
// find mask parent, should hit test it
if (parent === mask.node) {
const comp = parent.getComponent(cc.MaskComponent);
return (comp && comp.enabledInHierarchy) ? comp.node.uiTransfromComp!.isHit(cameraPt) : true;
} else {
listener.mask = null;
return true;
}
} else {
return true;
// }
}
} else {
return false;
}
+3 -5
View File
@@ -235,7 +235,7 @@ function align (node: Node, widget: WidgetComponent) {
}
function visitNode (node: Node) {
const widget = node.uiWidgetComp;
const widget = node.getComponent(WidgetComponent);
if (widget) {
if (CC_DEV) {
// widget._validateTargetInDEV();
@@ -448,7 +448,7 @@ function updateAlignment (node: Node) {
}
// node._widget will be null when widget is disabled
const widget = node.uiWidgetComp;
const widget = node.getComponent(WidgetComponent);
if (widget && parent) {
align(node, widget);
}
@@ -483,7 +483,6 @@ export const widgetManager = cc._widgetManager = {
}
},
add (widget: WidgetComponent) {
widget.node.uiWidgetComp = widget;
this._nodesOrderDirty = true;
if (CC_EDITOR /*&& !cc.engine.isPlaying*/) {
const renderComp = widget.node.getComponent(UIRenderComponent);
@@ -499,7 +498,6 @@ export const widgetManager = cc._widgetManager = {
}
},
remove (widget: WidgetComponent) {
widget.node.uiWidgetComp = null;
this._activeWidgetsIterator.remove(widget);
if (CC_EDITOR && !cc.engine.isPlaying) {
widget.node.off(Event.POSITION_PART, adjustWidgetToAllowMovingInEditor, widget);
@@ -514,7 +512,7 @@ export const widgetManager = cc._widgetManager = {
},
refreshWidgetOnResized (node: Node) {
if (Node.isNode(node)){
const widget = node.uiWidgetComp;
const widget = node.getComponent(WidgetComponent);
// const widget: WidgetComponent | null = null;
if (widget) {
if (widget!.alignMode === AlignMode.ON_WINDOW_RESIZE) {
+37 -21
View File
@@ -26,15 +26,12 @@
****************************************************************************/
import { ccclass } from '../core/data/class-decorator';
import EventTarget from '../core/event/event-target';
import { EventTargetFactory } from '../core/event/event-target-factory';
import { addon } from '../core/utils/js';
import Rect, { rect } from '../core/value-types/rect';
import Size, { size } from '../core/value-types/size';
import Vec2, { v2 } from '../core/value-types/vec2';
import { Rect, Size, Vec2 } from '../core/value-types';
import { vec2 } from '../core/vmath';
import { ImageAsset } from './image-asset';
import { Texture2D } from './texture-2d';
import textureUtil from './texture-util';
import { ImageAsset } from './image-asset';
const INSET_LEFT = 0;
const INSET_TOP = 1;
@@ -121,6 +118,7 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) {
get insetTop () {
return this._capInsets[INSET_TOP];
}
set insetTop (value) {
this._capInsets[INSET_TOP] = value;
// if (this._texture) {
@@ -138,6 +136,7 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) {
get insetBottom () {
return this._capInsets[INSET_BOTTOM];
}
set insetBottom (value) {
this._capInsets[INSET_BOTTOM] = value;
// if (this._texture) {
@@ -155,6 +154,7 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) {
get insetLeft () {
return this._capInsets[INSET_LEFT];
}
set insetLeft (value) {
this._capInsets[INSET_LEFT] = value;
// if (this._texture) {
@@ -172,6 +172,7 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) {
get insetRight () {
return this._capInsets[INSET_RIGHT];
}
set insetRight (value) {
this._capInsets[INSET_RIGHT] = value;
// if (this._texture) {
@@ -183,7 +184,7 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) {
return this._atlasUuid;
}
set atlasUuid (value) {
set atlasUuid (value: string) {
this._atlasUuid = value;
}
@@ -217,7 +218,7 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) {
// store original info before packed to dynamic atlas
private _original = null;
private _atlasUuid?: string;
private _atlasUuid: string = '';
private _atlasSize = new Size();
@@ -291,8 +292,13 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) {
* !#en Returns the rect of the sprite frame in the texture.
* !#zh 获取 SpriteFrame 的纹理矩形区域
*/
public getRect () {
return rect(this._rect);
public getRect (out?: Rect) {
if (out) {
out.set(this._rect);
return out;
}
return this._rect.clone();
}
/**
@@ -307,8 +313,13 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) {
* !#en Returns the original size of the trimmed image.
* !#zh 获取修剪前的原始大小
*/
public getOriginalSize () {
return size(this._originalSize);
public getOriginalSize (out?: Size) {
if (out) {
out.set(this._originalSize);
return out;
}
return this._originalSize.clone();
}
/**
@@ -345,8 +356,8 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) {
// return;
// }
// let w = texture.width, h = texture.height;
let w = self.width;
let h = self.height;
const w = self.width;
const h = self.height;
// if (self._rotated && cc.game.renderType === cc.game.RENDER_TYPE_CANVAS) {
// // TODO: rotate texture for canvas
@@ -362,15 +373,15 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) {
if (self._rect) {
self.checkRect(this.image!);
} else {
self.setRect(cc.rect(0, 0, w, h));
self.setRect(new Rect(0, 0, w, h));
}
if (!self._originalSize) {
self.setOriginalSize(cc.size(w, h));
self.setOriginalSize(new Size(w, h));
}
if (!self._offset) {
self.setOffset(cc.v2(0, 0));
self.setOffset(new Vec2(0, 0));
}
self._calculateUV();
@@ -401,8 +412,13 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) {
* !#en Returns the offset of the frame in the texture.
* !#zh 获取偏移量
*/
public getOffset () {
return v2(this._offset);
public getOffset (out?: Vec2) {
if (out) {
out.set(this._offset);
return out;
}
return this._offset.clone();
}
/**
@@ -411,7 +427,7 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) {
* @param offsets
*/
public setOffset (offsets: Vec2) {
this._offset = new Vec2(offsets);
vec2.set(this._offset, offsets.x, offsets.y);
}
/**
@@ -536,7 +552,7 @@ export class SpriteFrame extends EventTargetFactory(Texture2D) {
// this._texture = null; // TODO - release texture
// }
public checkRect(texture: ImageAsset) {
public checkRect (texture: ImageAsset) {
const rect = this._rect;
let maxX = rect.x;
let maxY = rect.y;
+2
View File
@@ -30,6 +30,7 @@ import IDGenerator from '../core/utils/id-generator';
import { ccclass, property } from '../core/data/class-decorator';
import { Node } from '../scene-graph/node';
import { RenderScene } from '../renderer/scene/render-scene';
import { EventTarget } from '../core/event/event-target';
export class Component extends CCObject {
node: Node;
@@ -53,4 +54,5 @@ export class Component extends CCObject {
// friend to class BaseNode
public _id: string;
public _enabled: boolean;
public _eventTargets: Array<Node | EventTarget>;
}
+3 -3
View File
@@ -215,10 +215,10 @@ class Component extends CCObject {
/**
* Register all related EventTargets,
* all event callbacks will be removed in _onPreDestroy
* @property {Array} __eventTargets
* @property {Array} _eventTargets
* @private
*/
this.__eventTargets = [];
this._eventTargets = [];
}
// PUBLIC
@@ -341,7 +341,7 @@ class Component extends CCObject {
this.unscheduleAllCallbacks();
// Remove all listeners
var eventTargets = this.__eventTargets;
var eventTargets = this._eventTargets;
for (var i = 0, l = eventTargets.length; i < l; ++i) {
var target = eventTargets[i];
target && target.targetOff(this);
@@ -1,3 +1,5 @@
import { MaskComponent } from "../../../3d/ui/components/mask-component";
/****************************************************************************
Copyright (c) 2013-2016 Chukong Technologies Inc.
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
@@ -137,6 +139,12 @@ export class EventListener {
return listener!;
}
// hack: How to solve the problem of uncertain attribute
// callback's this object
public owner: Object | null = null;
public mask: MaskComponent | null = null;
public _previousIn?: boolean = false;
public _target: any = null;
// Event callback function
+4
View File
@@ -1,3 +1,5 @@
import { ccenum } from '../core/value-types/enum';
// Extensions
export enum WebGLEXT {
COMPRESSED_RGB_S3TC_DXT1_EXT = 0x83F0,
@@ -358,6 +360,8 @@ export enum GFXBlendFactor {
ONE_MINUS_CONSTANT_ALPHA,
}
ccenum(GFXBlendFactor);
export enum GFXColorMask {
NONE = 0x0,
R = 0x1,
+1 -2
View File
@@ -93,8 +93,7 @@ export class RenderScene {
constructor (root: Root) {
this._root = root;
this._ambient = new Ambient (this);
this._mainLight = new DirectionalLight(this, 'Main Light');
this._mainLight.node = new Node('Main Light');
this._mainLight = new DirectionalLight(this, 'Main Light', new Node('Main Light'));
this._skybox = new Skybox(this);
}
+7 -3
View File
@@ -11,9 +11,7 @@ export class Skybox extends Model {
set cubemap (val: TextureCube | null) {
this._cubemap = val || this._default;
this._material.setProperty('cubeMap', this._cubemap);
for (const pso of this._matPSORecord.get(this._material)!) {
pso.pipelineLayout.layouts[0].update();
}
this._updateBindingLayout();
}
get cubemap () {
return this._cubemap;
@@ -25,6 +23,7 @@ export class Skybox extends Model {
this._material.destroy();
this._material.initialize({ defines: { USE_RGBE_CUBEMAP: val } });
this.setSubModelMaterial(0, this._material);
this._updateBindingLayout();
}
get isRGBE () {
return this._isRGBE;
@@ -50,5 +49,10 @@ export class Skybox extends Model {
const mesh = createMesh(box({ width: 2, height: 2, length: 2 }));
const subMeshData = mesh.renderingMesh!.getSubmesh(0)!;
this.initSubModel(0, subMeshData, this._material);
this._updateBindingLayout();
}
protected _updateBindingLayout () {
this._matPSORecord.get(this._material)![0].pipelineLayout.layouts[0].update();
}
}
+1
View File
@@ -654,6 +654,7 @@ export class UI {
this._currTexView = null;
this._meshBufferUseCount = 0;
this._requireBufferBatch();
StencilManager.sharedManager!.reset();
// this._commitUIRenderDataPool.reset();
// this._commitUICanvas.length = 0;
}
+339 -292
View File
@@ -1,13 +1,14 @@
import { Node } from "./node";
import { eventManager } from '../core/platform/event-manager';
import { Component } from '../components/component';
import EventTarget from '../core/event/event-target';
import { EventListener } from "../core/platform/event-manager/CCEventListener";
import { eventManager } from '../core/platform/event-manager';
import { EventListener } from '../core/platform/event-manager/CCEventListener';
import Touch from '../core/platform/event-manager/CCTouch';
import { EventMouse, EventTouch} from '../core/platform/event-manager/index';
import { array } from '../core/utils/js';
import { EventMouse, EventTouch} from "../core/platform/event-manager/index";
import { EventType } from "./node-event-enum";
import { Node } from './node';
import { EventType } from './node-event-enum';
const _cachedArray = new Array(16);
_cachedArray.length = 0;
let _currentHovered: Node | null = null;
const _touchEvents = [
@@ -26,7 +27,8 @@ const _mouseEvents = [
EventType.MOUSE_WHEEL.toString(),
];
const _touchStartHandler = function (touch, event: EventTouch) {
// TODO: rearrange event
function _touchStartHandler (this: EventListener, touch: Touch, event: EventTouch) {
const pos = touch.getLocation();
const node = this.owner;
@@ -38,17 +40,26 @@ const _touchStartHandler = function (touch, event: EventTouch) {
return true;
}
return false;
};
const _touchMoveHandler = function (touch, event: EventTouch) {
const node = this.owner;
}
function _touchMoveHandler (this: EventListener, touch: Touch, event: EventTouch) {
const node = this.owner as Node;
if (!node || !node.uiTransfromComp) {
return;
}
event.type = EventType.TOUCH_MOVE.toString();
event.touch = touch;
event.bubbles = true;
node.dispatchEvent(event);
};
const _touchEndHandler = function (touch, event: EventTouch) {
}
function _touchEndHandler (this: EventListener, touch: Touch, event: EventTouch) {
const pos = touch.getLocation();
const node = this.owner;
const node = this.owner as Node;
if (!node || !node.uiTransfromComp) {
return;
}
if (node.uiTransfromComp.isHit(pos, this)) {
event.type = EventType.TOUCH_END.toString();
@@ -58,29 +69,41 @@ const _touchEndHandler = function (touch, event: EventTouch) {
event.touch = touch;
event.bubbles = true;
node.dispatchEvent(event);
};
const _touchCancelHandler = function (touch, event: EventTouch) {
const node = this.owner;
}
function _touchCancelHandler (this: EventListener, touch: Touch, event: EventTouch) {
const node = this.owner as Node;
if (!node || !node.uiTransfromComp) {
return;
}
event.type = EventType.TOUCH_CANCEL.toString();
event.touch = touch;
event.bubbles = true;
node.dispatchEvent(event);
};
}
const _mouseDownHandler = function (event: EventMouse) {
function _mouseDownHandler (this: EventListener, event: EventMouse) {
const pos = event.getLocation();
const node = this.owner;
const node = this.owner as Node;
if (!node || !node.uiTransfromComp) {
return;
}
if (node.uiTransfromComp.isHit(pos, this)) {
event.type = EventType.MOUSE_DOWN.toString();
event.bubbles = true;
node.dispatchEvent(event);
}
};
const _mouseMoveHandler = function (event: EventMouse) {
}
function _mouseMoveHandler (this: EventListener, event: EventMouse) {
const pos = event.getLocation();
const node = this.owner;
const node = this.owner as Node;
if (!node || !node.uiTransfromComp){
return;
}
const hit = node.uiTransfromComp.isHit(pos, this);
if (hit) {
if (!this._previousIn) {
@@ -92,7 +115,7 @@ const _mouseMoveHandler = function (event: EventMouse) {
_currentHovered!.eventProcessor.mouseListener!._previousIn = false;
}
}
_currentHovered = this.owner;
_currentHovered = node;
event.type = EventType.MOUSE_ENTER.toString();
node.dispatchEvent(event);
this._previousIn = true;
@@ -113,34 +136,43 @@ const _mouseMoveHandler = function (event: EventMouse) {
// Event processed, cleanup
// event.propagationStopped = true;
event.propagationStopped = true;
};
const _mouseUpHandler = function (event: EventMouse) {
}
function _mouseUpHandler (this: EventListener, event: EventMouse) {
const pos = event.getLocation();
const node = this.owner;
const node = this.owner as Node;
if (!node || !node.uiTransfromComp) {
return;
}
if (node.uiTransfromComp.isHit(pos, this)) {
event.type = EventType.MOUSE_UP.toString();
event.bubbles = true;
node.dispatchEvent(event);
// event.propagationStopped = true;
event.propagationStopped=true;
event.propagationStopped = true;
}
};
const _mouseWheelHandler = function (event: EventTouch) {
}
function _mouseWheelHandler (this: EventListener, event: EventTouch) {
const pos = event.getLocation();
const node = this.owner;
const node = this.owner as Node;
if (!node || !node.uiTransfromComp) {
return;
}
if (node.uiTransfromComp!.isHit(pos, this)) {
event.type = EventType.MOUSE_WHEEL.toString();
event.bubbles = true;
node.dispatchEvent(event);
// event.propagationStopped = true;
event.propagationStopped=true;
event.propagationStopped = true;
}
};
}
function _doDispatchEvent(owner: Node, event: EventTouch) {
let target, i;
function _doDispatchEvent (owner: Node, event: EventTouch) {
let target;
let i = 0;
event.target = owner;
// Event.CAPTURING_PHASE
@@ -150,10 +182,10 @@ function _doDispatchEvent(owner: Node, event: EventTouch) {
event.eventPhase = 1;
for (i = _cachedArray.length - 1; i >= 0; --i) {
target = _cachedArray[i];
if (target._capturingListeners) {
if (target._capturingTargets) {
event.currentTarget = target;
// fire event
target._capturingListeners.emit(event.type, event, _cachedArray);
target._capturingTargets.emit(event.type, event, _cachedArray);
// check if propagation stopped
if (event.propagationStopped) {
_cachedArray.length = 0;
@@ -167,11 +199,11 @@ function _doDispatchEvent(owner: Node, event: EventTouch) {
// checks if destroyed in capturing callbacks
event.eventPhase = 2;
event.currentTarget = owner;
if (owner.eventProcessor.capturingListeners) {
owner.eventProcessor.capturingListeners.emit(event.type, event);
if (owner.eventProcessor.capturingTargets) {
owner.eventProcessor.capturingTargets.emit(event.type, event);
}
if (!event.propagationImmediateStopped && owner.eventProcessor.bubblingListeners) {
owner.eventProcessor.bubblingListeners.emit(event.type, event);
if (!event.propagationImmediateStopped && owner.eventProcessor.bubblingTargets) {
owner.eventProcessor.bubblingTargets.emit(event.type, event);
}
if (!event.propagationStopped && event.bubbles) {
@@ -181,10 +213,10 @@ function _doDispatchEvent(owner: Node, event: EventTouch) {
event.eventPhase = 3;
for (i = 0; i < _cachedArray.length; ++i) {
target = _cachedArray[i];
if (target._bubblingListeners) {
if (target._bubblingTargets) {
event.currentTarget = target;
// fire event
target._bubblingListeners.emit(event.type, event);
target._bubblingTargets.emit(event.type, event);
// check if propagation stopped
if (event.propagationStopped) {
_cachedArray.length = 0;
@@ -196,15 +228,15 @@ function _doDispatchEvent(owner: Node, event: EventTouch) {
_cachedArray.length = 0;
}
function _searchMaskInParent(node: Node | null) {
var Mask = cc.MaskComponent;
function _searchMaskInParent (node: Node | null) {
const Mask = cc.MaskComponent;
if (Mask) {
let index = 0;
for (let curr = node; curr && Node.isNode(curr); curr = curr.parent, ++index) {
if (curr.getComponent(Mask)) {
return {
index: index,
node: curr
index,
node: curr,
};
}
}
@@ -212,25 +244,35 @@ function _searchMaskInParent(node: Node | null) {
return null;
}
function _checkListeners(listeners: EventTarget, events) {
if (listeners) {
for (let i = 0; i < events.length; ++i) {
if (listeners.hasEventListener(events[i])) {
return true;
function _checkListeners (node: Node, events: string[]) {
if (!node._persistNode) {
let i = 0;
if (node.eventProcessor.bubblingTargets) {
for (; i < events.length; ++i) {
if (node.eventProcessor.bubblingTargets.hasEventListener(events[i])) {
return true;
}
}
}
if (node.eventProcessor.capturingTargets) {
for (; i < events.length; ++i) {
if (node.eventProcessor.capturingTargets.hasEventListener(events[i])) {
return true;
}
}
}
return false;
}
return false;
return true;
}
export class NodeEventProcessor {
public get node(): Node {
public get node (): Node {
return this._node;
}
// Event listeners
public bubblingListeners: EventTarget | null = null;
public capturingListeners: EventTarget | null = null;
public bubblingTargets: EventTarget | null = null;
public capturingTargets: EventTarget | null = null;
// Touch event listener
public touchListener: EventListener | null = null;
// Mouse event listener
@@ -238,13 +280,228 @@ export class NodeEventProcessor {
private _node: Node;
constructor(node: Node) {
constructor (node: Node) {
this._node = node;
}
/**
* !#en
* Register a callback of a specific event type on Node.<br/>
* Use this method to register touch or mouse event permit propagation based on scene graph,<br/>
* These kinds of event are triggered with dispatchEvent, the dispatch process has three steps:<br/>
* 1. Capturing phase: dispatch in capture targets (`_getCapturingTargets`), e.g. parents in node tree, from root to the real target<br/>
* 2. At target phase: dispatch to the listeners of the real target<br/>
* 3. Bubbling phase: dispatch in bubble targets (`_getBubblingTargets`), e.g. parents in node tree, from the real target to root<br/>
* In any moment of the dispatching process, it can be stopped via `event.propagationStopped = true` or `event.stopPropagationImmidiate()`.<br/>
* It's the recommended way to register touch/mouse event for Node,<br/>
* please do not use cc.eventManager directly for Node.<br/>
* You can also register custom event and use `emit` to trigger custom event on Node.<br/>
* For such events, there won't be capturing and bubbling phase, your event will be dispatched directly to its listeners registered on the same node.<br/>
* You can also pass event callback parameters with `emit` by passing parameters after `type`.
* !#zh
* 在节点上注册指定类型的回调函数,也可以设置 target 用于绑定响应函数的 this 对象。<br/>
* 鼠标或触摸事件会被系统调用 dispatchEvent 方法触发,触发的过程包含三个阶段:<br/>
* 1. 捕获阶段:派发事件给捕获目标(通过 `_getCapturingTargets` 获取),比如,节点树中注册了捕获阶段的父节点,从根节点开始派发直到目标节点。<br/>
* 2. 目标阶段:派发给目标节点的监听器。<br/>
* 3. 冒泡阶段:派发事件给冒泡目标(通过 `_getBubblingTargets` 获取),比如,节点树中注册了冒泡阶段的父节点,从目标节点开始派发知道根节点。<br/>
* 同时您可以将事件派发到父节点或者通过调用 stopPropagation 拦截它。<br/>
* 推荐使用这种方式来监听节点上的触摸或鼠标事件,请不要在节点上直接使用 cc.eventManager。<br/>
* 你也可以注册自定义事件到节点上,并通过 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 {Event|any} [callback.event] event or first argument when emit
* @param {any} [callback.arg2] arg2
* @param {any} [callback.arg3] arg3
* @param {any} [callback.arg4] arg4
* @param {any} [callback.arg5] arg5
* @param {Object} [target] - The target (this object) to invoke the callback, can be null
* @param {Boolean} [useCapture=false] - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase.
* @return {Function} - Just returns the incoming callback so you can save the anonymous function easier.
* @typescript
* on<T extends Function>(type: string, callback: T, target?: any, useCapture?: boolean): T
* @example
* this.node.on(cc.Node.EventType.TOUCH_START, this.memberFunction, this); // if "this" is component and the "memberFunction" declared in CCClass.
* this.node.on(cc.Node.EventType.TOUCH_START, callback, this);
* this.node.on(cc.Node.EventType.ANCHOR_CHANGED, callback);
*/
public on (type: string, callback: Function, target?: Object, useCapture?: Object) {
const forDispatch = this._checknSetupSysEvent(type);
if (forDispatch) {
return this._onDispatch(type, callback, target, useCapture);
} else {
// switch (type) {
// case EventType.POSITION_CHANGED:
// this._eventMask |= POSITION_ON;
// break;
// case EventType.SCALE_CHANGED:
// this._eventMask |= SCALE_ON;
// break;
// case EventType.ROTATION_CHANGED:
// this._eventMask |= ROTATION_ON;
// break;
// case EventType.SIZE_CHANGED:
// this._eventMask |= SIZE_ON;
// break;
// case EventType.ANCHOR_CHANGED:
// this._eventMask |= ANCHOR_ON;
// break;
// }
if (!this.bubblingTargets) {
this.bubblingTargets = new EventTarget();
}
return this.bubblingTargets.on(type, callback, target);
}
}
/**
* !#en
* Register an callback of a specific event type on the Node,
* the callback will remove itself after the first time it is triggered.
* !#zh
* 注册节点的特定事件类型回调,回调会在第一时间被触发后删除自身。
*
* @method once
* @param {String} type - A string representing the event type to listen for.
* @param {Function} callback - The callback that will be invoked when the event is dispatched.
* The callback is ignored if it is a duplicate (the callbacks are unique).
* @param {Event|any} [callback.event] event or first argument when emit
* @param {any} [callback.arg2] arg2
* @param {any} [callback.arg3] arg3
* @param {any} [callback.arg4] arg4
* @param {any} [callback.arg5] arg5
* @param {Object} [target] - The target (this object) to invoke the callback, can be null
* @typescript
* once<T extends Function>(type: string, callback: T, target?: any, useCapture?: boolean): T
* @example
* node.once(cc.Node.EventType.ANCHOR_CHANGED, callback);
*/
public once (type: string, callback: Function, target?: Object, useCapture?: Object) {
const forDispatch = this._checknSetupSysEvent(type);
const eventType_hasOnceListener = '__ONCE_FLAG:' + type;
let listeners: EventTarget;
if (forDispatch && useCapture) {
listeners = this.capturingTargets = this.capturingTargets || new EventTarget();
}
else {
listeners = this.bubblingTargets = this.bubblingTargets || new EventTarget();
}
const hasOnceListener = listeners!.hasEventListener(eventType_hasOnceListener, callback, target);
if (!hasOnceListener) {
const self = this;
const onceWrapper = (...args) => {
self.off(type, onceWrapper, target);
listeners.remove(eventType_hasOnceListener, callback, target);
callback.call(self._node, ...args);
};
this.on(type, onceWrapper, target);
listeners.add(eventType_hasOnceListener, callback, target);
}
}
/**
* !#en
* Removes the callback previously registered with the same type, callback, target and or useCapture.
* This method is merely an alias to removeEventListener.
* !#zh 删除之前与同类型,回调,目标或 useCapture 注册的回调。
* @method off
* @param {String} type - A string representing the event type being removed.
* @param {Function} [callback] - The callback to remove.
* @param {Object} [target] - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed
* @param {Boolean} [useCapture=false] - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase.
* @example
* this.node.off(cc.Node.EventType.TOUCH_START, this.memberFunction, this);
* node.off(cc.Node.EventType.TOUCH_START, callback, this.node);
* node.off(cc.Node.EventType.ANCHOR_CHANGED, callback, this);
*/
public off (type: string, callback?: Function, target?: Object, useCapture?: Object) {
const touchEvent = _touchEvents.indexOf(type) !== -1;
const mouseEvent = !touchEvent && _mouseEvents.indexOf(type) !== -1;
if (touchEvent || mouseEvent) {
this._offDispatch(type, callback, target, useCapture);
if (touchEvent) {
if (this.touchListener && !_checkListeners(this._node, _touchEvents)) {
eventManager.removeListener(this.touchListener);
this.touchListener = null;
}
} else if (mouseEvent) {
if (this.mouseListener && !_checkListeners(this._node, _mouseEvents)) {
eventManager.removeListener(this.mouseListener);
this.mouseListener = null;
}
}
} else if (this.bubblingTargets) {
this.bubblingTargets.off(type, callback, target);
// const hasListeners = this.bubblingTargets.hasEventListener(type);
// All listener removed
// if (!hasListeners) {
// switch (type) {
// case EventType.POSITION_CHANGED:
// this._eventMask &= ~POSITION_ON;
// break;
// case EventType.SCALE_CHANGED:
// this._eventMask &= ~SCALE_ON;
// break;
// case EventType.ROTATION_CHANGED:
// this._eventMask &= ~ROTATION_ON;
// break;
// case EventType.SIZE_CHANGED:
// this._eventMask &= ~SIZE_ON;
// break;
// case EventType.ANCHOR_CHANGED:
// this._eventMask &= ~ANCHOR_ON;
// break;
// }
// }
}
}
/**
* !#en
* Trigger an event directly with the event name and necessary arguments.
* !#zh
* 通过事件名发送自定义事件
*
* @method emit
* @param {String} type - event type
* @param {*} [arg1] - First argument in callback
* @param {*} [arg2] - Second argument in callback
* @param {*} [arg3] - Third argument in callback
* @param {*} [arg4] - Fourth argument in callback
* @param {*} [arg5] - Fifth argument in callback
* @example
*
* eventTarget.emit('fire', event);
* eventTarget.emit('fire', message, emitter);
*/
public emit (type, ...args: any[]) {
if (this.bubblingTargets) {
this.bubblingTargets.emit(type, ...args);
}
}
/**
* !#en
* Dispatches an event into the event flow.
* The event target is the EventTarget object upon which the dispatchEvent() method is called.
* !#zh 分发事件到事件流中。
*
* @method dispatchEvent
* @param {Event} event - The Event object that is dispatched into the event flow
*/
public dispatchEvent (event: EventTouch) {
_doDispatchEvent(this._node, event);
_cachedArray.length = 0;
}
// EVENT TARGET
public _checknSetupSysEvent(type) {
private _checknSetupSysEvent (type: string) {
let newAdded = false;
let forDispatch = false;
if (_touchEvents.indexOf(type) !== -1) {
@@ -290,125 +547,7 @@ export class NodeEventProcessor {
return forDispatch;
}
/**
* !#en
* Register a callback of a specific event type on Node.<br/>
* Use this method to register touch or mouse event permit propagation based on scene graph,<br/>
* These kinds of event are triggered with dispatchEvent, the dispatch process has three steps:<br/>
* 1. Capturing phase: dispatch in capture targets (`_getCapturingTargets`), e.g. parents in node tree, from root to the real target<br/>
* 2. At target phase: dispatch to the listeners of the real target<br/>
* 3. Bubbling phase: dispatch in bubble targets (`_getBubblingTargets`), e.g. parents in node tree, from the real target to root<br/>
* In any moment of the dispatching process, it can be stopped via `event.propagationStopped = true` or `event.stopPropagationImmidiate()`.<br/>
* It's the recommended way to register touch/mouse event for Node,<br/>
* please do not use cc.eventManager directly for Node.<br/>
* You can also register custom event and use `emit` to trigger custom event on Node.<br/>
* For such events, there won't be capturing and bubbling phase, your event will be dispatched directly to its listeners registered on the same node.<br/>
* You can also pass event callback parameters with `emit` by passing parameters after `type`.
* !#zh
* 在节点上注册指定类型的回调函数,也可以设置 target 用于绑定响应函数的 this 对象。<br/>
* 鼠标或触摸事件会被系统调用 dispatchEvent 方法触发,触发的过程包含三个阶段:<br/>
* 1. 捕获阶段:派发事件给捕获目标(通过 `_getCapturingTargets` 获取),比如,节点树中注册了捕获阶段的父节点,从根节点开始派发直到目标节点。<br/>
* 2. 目标阶段:派发给目标节点的监听器。<br/>
* 3. 冒泡阶段:派发事件给冒泡目标(通过 `_getBubblingTargets` 获取),比如,节点树中注册了冒泡阶段的父节点,从目标节点开始派发知道根节点。<br/>
* 同时您可以将事件派发到父节点或者通过调用 stopPropagation 拦截它。<br/>
* 推荐使用这种方式来监听节点上的触摸或鼠标事件,请不要在节点上直接使用 cc.eventManager。<br/>
* 你也可以注册自定义事件到节点上,并通过 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 {Event|any} [callback.event] event or first argument when emit
* @param {any} [callback.arg2] arg2
* @param {any} [callback.arg3] arg3
* @param {any} [callback.arg4] arg4
* @param {any} [callback.arg5] arg5
* @param {Object} [target] - The target (this object) to invoke the callback, can be null
* @param {Boolean} [useCapture=false] - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase.
* @return {Function} - Just returns the incoming callback so you can save the anonymous function easier.
* @typescript
* on<T extends Function>(type: string, callback: T, target?: any, useCapture?: boolean): T
* @example
* this.node.on(cc.Node.EventType.TOUCH_START, this.memberFunction, this); // if "this" is component and the "memberFunction" declared in CCClass.
* this.node.on(cc.Node.EventType.TOUCH_START, callback, this);
* this.node.on(cc.Node.EventType.ANCHOR_CHANGED, callback);
*/
public on(type: string, callback: Function, target?: Object, useCapture?: Object) {
const forDispatch = this._checknSetupSysEvent(type);
if (forDispatch) {
return this._onDispatch(type, callback, target, useCapture);
} else {
// switch (type) {
// case EventType.POSITION_CHANGED:
// this._eventMask |= POSITION_ON;
// break;
// case EventType.SCALE_CHANGED:
// this._eventMask |= SCALE_ON;
// break;
// case EventType.ROTATION_CHANGED:
// this._eventMask |= ROTATION_ON;
// break;
// case EventType.SIZE_CHANGED:
// this._eventMask |= SIZE_ON;
// break;
// case EventType.ANCHOR_CHANGED:
// this._eventMask |= ANCHOR_ON;
// break;
// }
if (!this.bubblingListeners) {
this.bubblingListeners = new EventTarget();
}
return this.bubblingListeners.on(type, callback, target);
}
}
/**
* !#en
* Register an callback of a specific event type on the Node,
* the callback will remove itself after the first time it is triggered.
* !#zh
* 注册节点的特定事件类型回调,回调会在第一时间被触发后删除自身。
*
* @method once
* @param {String} type - A string representing the event type to listen for.
* @param {Function} callback - The callback that will be invoked when the event is dispatched.
* The callback is ignored if it is a duplicate (the callbacks are unique).
* @param {Event|any} [callback.event] event or first argument when emit
* @param {any} [callback.arg2] arg2
* @param {any} [callback.arg3] arg3
* @param {any} [callback.arg4] arg4
* @param {any} [callback.arg5] arg5
* @param {Object} [target] - The target (this object) to invoke the callback, can be null
* @typescript
* once<T extends Function>(type: string, callback: T, target?: any, useCapture?: boolean): T
* @example
* node.once(cc.Node.EventType.ANCHOR_CHANGED, callback);
*/
once(type: string, callback: Function, target: Object, useCapture?: Object) {
let forDispatch = this._checknSetupSysEvent(type);
let eventType_hasOnceListener = '__ONCE_FLAG:' + type;
let listeners: EventTarget | null = null;
if (forDispatch && useCapture) {
listeners = this.capturingListeners = this.capturingListeners || new EventTarget();
}
else {
listeners = this.bubblingListeners = this.bubblingListeners || new EventTarget();
}
let hasOnceListener = listeners!.hasEventListener(eventType_hasOnceListener, callback, target);
if (!hasOnceListener) {
let self = this;
let onceWrapper = function (arg1, arg2, arg3, arg4, arg5) {
self.off(type, onceWrapper, target);
listeners.remove(eventType_hasOnceListener, callback, target);
callback.call(this._node, arg1, arg2, arg3, arg4, arg5);
};
this.on(type, onceWrapper, target);
listeners.add(eventType_hasOnceListener, callback, target);
}
}
public _onDispatch(type: string, callback: Function, target?: Object, useCapture?: Object) {
private _onDispatch (type: string, callback: Function, target?: Object, useCapture?: Object) {
// Accept also patameters like: (type, callback, useCapture)
if (typeof target === 'boolean') {
useCapture = target;
@@ -421,141 +560,49 @@ export class NodeEventProcessor {
let listeners: EventTarget | null = null;
if (useCapture) {
listeners = this.capturingListeners = this.capturingListeners || new EventTarget();
listeners = this.capturingTargets = this.capturingTargets || new EventTarget();
} else {
listeners = this.bubblingListeners = this.bubblingListeners || new EventTarget();
listeners = this.bubblingTargets = this.bubblingTargets || new EventTarget();
}
if (!listeners.hasEventListener(type, callback, target)) {
listeners.add(type, callback, target);
if (target && target.__eventTargets) {
target.__eventTargets.push(this);
if (target && (target as Component)._eventTargets) {
(target as Component)._eventTargets.push(this._node);
}
}
return callback;
}
/**
* !#en
* Removes the callback previously registered with the same type, callback, target and or useCapture.
* This method is merely an alias to removeEventListener.
* !#zh 删除之前与同类型,回调,目标或 useCapture 注册的回调。
* @method off
* @param {String} type - A string representing the event type being removed.
* @param {Function} [callback] - The callback to remove.
* @param {Object} [target] - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed
* @param {Boolean} [useCapture=false] - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase.
* @example
* this.node.off(cc.Node.EventType.TOUCH_START, this.memberFunction, this);
* node.off(cc.Node.EventType.TOUCH_START, callback, this.node);
* node.off(cc.Node.EventType.ANCHOR_CHANGED, callback, this);
*/
public off(type: string, callback?: Function, target?: Object, useCapture?: Object) {
const touchEvent = _touchEvents.indexOf(type) !== -1;
const mouseEvent = !touchEvent && _mouseEvents.indexOf(type) !== -1;
if (touchEvent || mouseEvent) {
this._offDispatch(type, callback, target, useCapture);
if (touchEvent) {
if (this.touchListener && !_checkListeners(this.touchListener, _touchEvents)) {
eventManager.removeListener(this.touchListener);
this.touchListener = null;
}
} else if (mouseEvent) {
if (this.mouseListener && !_checkListeners(this.mouseListener, _mouseEvents)) {
eventManager.removeListener(this.mouseListener);
this.mouseListener = null;
}
}
} else if (this.bubblingListeners) {
this.bubblingListeners.off(type, callback, target);
const hasListeners = this.bubblingListeners.hasEventListener(type);
// All listener removed
// if (!hasListeners) {
// switch (type) {
// case EventType.POSITION_CHANGED:
// this._eventMask &= ~POSITION_ON;
// break;
// case EventType.SCALE_CHANGED:
// this._eventMask &= ~SCALE_ON;
// break;
// case EventType.ROTATION_CHANGED:
// this._eventMask &= ~ROTATION_ON;
// break;
// case EventType.SIZE_CHANGED:
// this._eventMask &= ~SIZE_ON;
// break;
// case EventType.ANCHOR_CHANGED:
// this._eventMask &= ~ANCHOR_ON;
// break;
// }
// }
}
}
public _offDispatch(type: string, callback: Function, target?: Object, useCapture?: Object) {
private _offDispatch (type: string, callback?: Function, target?: Object, useCapture?: Object) {
// Accept also patameters like: (type, callback, useCapture)
if (typeof target === 'boolean') {
useCapture = target;
target = undefined;
} else { useCapture = !!useCapture; }
if (!callback) {
this.capturingListeners && this.capturingListeners.removeAll(type);
this.bubblingListeners && this.bubblingListeners.removeAll(type);
if (this.capturingTargets){
this.capturingTargets.removeAll(type);
}
if (this.bubblingTargets){
this.bubblingTargets.removeAll(type);
}
} else {
const listeners = useCapture ? this.capturingListeners : this.bubblingListeners;
const listeners = useCapture ? this.capturingTargets : this.bubblingTargets;
if (listeners) {
listeners.remove(type, callback, target);
if (target && target.__eventTargets) {
array.fastRemove(target.__eventTargets, this);
if (target && (target as Component)._eventTargets) {
array.fastRemove((target as Component)._eventTargets, this);
}
}
}
}
/**
* !#en
* Trigger an event directly with the event name and necessary arguments.
* !#zh
* 通过事件名发送自定义事件
*
* @method emit
* @param {String} type - event type
* @param {*} [arg1] - First argument in callback
* @param {*} [arg2] - Second argument in callback
* @param {*} [arg3] - Third argument in callback
* @param {*} [arg4] - Fourth argument in callback
* @param {*} [arg5] - Fifth argument in callback
* @example
*
* eventTarget.emit('fire', event);
* eventTarget.emit('fire', message, emitter);
*/
public emit(type, ...args: any[]) {
if (this.bubblingListeners) {
this.bubblingListeners.emit(type, ...args);
}
}
/**
* !#en
* Dispatches an event into the event flow.
* The event target is the EventTarget object upon which the dispatchEvent() method is called.
* !#zh 分发事件到事件流中。
*
* @method dispatchEvent
* @param {Event} event - The Event object that is dispatched into the event flow
*/
public dispatchEvent(event: EventTouch) {
_doDispatchEvent(this._node, event);
_cachedArray.length = 0;
}
/**
* Get all the targets listening to the supplied type of event in the target's capturing phase.
* The capturing phase comprises the journey from the root to the last node BEFORE the event target's node.
@@ -568,11 +615,11 @@ export class NodeEventProcessor {
* @param {Array} array - the array to receive targets
* @example {@link cocos2d/core/event/_getCapturingTargets.js}
*/
_getCapturingTargets(type, array) {
var parent = this._node.parent;
private _getCapturingTargets (type: string, targets: Node[]) {
let parent = this._node.parent;
while (parent) {
if (parent.eventProcessor.capturingListeners && parent.eventProcessor.capturingListeners.hasEventListener(type)) {
array.push(parent);
if (parent.eventProcessor.capturingTargets && parent.eventProcessor.capturingTargets.hasEventListener(type)) {
targets.push(parent);
}
parent = parent.parent;
}
@@ -589,11 +636,11 @@ export class NodeEventProcessor {
* @param {String} type - the event type
* @param {Array} array - the array to receive targets
*/
_getBubblingTargets(type, array) {
var parent = this._node.parent;
private _getBubblingTargets (type: string, targets: Node[]) {
let parent = this._node.parent;
while (parent) {
if (parent.eventProcessor.bubblingListeners && parent.eventProcessor.bubblingListeners.hasEventListener(type)) {
array.push(parent);
if (parent.eventProcessor.bubblingTargets && parent.eventProcessor.bubblingTargets.hasEventListener(type)) {
targets.push(parent);
}
parent = parent.parent;
}
-14
View File
@@ -1,5 +1,4 @@
import { UITransformComponent } from '../3d/ui/components/ui-transfrom-component';
import { WidgetComponent } from '../3d/ui/components/widget-component';
import { ccclass, property } from '../core/data/class-decorator';
import { Mat4, Quat, Vec3 } from '../core/value-types';
import Size from '../core/value-types/size';
@@ -56,7 +55,6 @@ class Node extends BaseNode {
protected _eventProcessor;
private _uiTransfromComp: UITransformComponent | null = null;
private _uiWidgetComp: WidgetComponent | null = null;
@property({
type: Vec3,
@@ -97,18 +95,6 @@ class Node extends BaseNode {
this._uiTransfromComp = value;
}
get uiWidgetComp () {
if (!this._uiWidgetComp) {
this._uiWidgetComp = this.getComponent(WidgetComponent);
}
return this._uiWidgetComp;
}
set uiWidgetComp (value: WidgetComponent | null) {
this._uiWidgetComp = value;
}
get width () {
return this.uiTransfromComp!.width;
}
+2 -1
View File
@@ -118,8 +118,9 @@ export class SkyboxInfo {
set renderScene (val: RenderScene) {
this._resource = val.skybox;
this.cubemap = this._cubemap;
this.isRGBE = this._isRGBE;
this.cubemap = this._cubemap;
this.enabled = this._enabled;
}
}
cc.SkyboxInfo = SkyboxInfo;
+2 -2
View File
@@ -64,8 +64,7 @@ export class Scene extends Node {
super(name);
this._activeInHierarchy = false;
if (cc.director && cc.director.root) {
const rs = this._renderScene = cc.director.root.createScene({});
this._globals.renderScene = rs;
this._renderScene = cc.director.root.createScene({});
}
}
@@ -95,6 +94,7 @@ export class Scene extends Node {
this._inited = true;
}
this.walk(BaseNode._setScene);
this._globals.renderScene = this._renderScene!;
}
protected _activate (active: boolean) {