From 6ce01cd0beffdfbae5352425a62133090d45e9b7 Mon Sep 17 00:00:00 2001 From: Leslie Leigh Date: Sun, 14 Apr 2019 00:59:19 +0800 Subject: [PATCH 1/7] remove animation-animator; remove pause, resume, stop, setTime, sample API of animation-component (#4212) * remove animation-animator; remove pause, resume, stop, setTime, sample API of animation-component * anim preview --- cocos/animation/animation-animator.ts | 180 --------------- cocos/animation/animation-manager.ts | 6 +- cocos/animation/animation-state.ts | 11 +- cocos/animation/cross-fade.ts | 54 ++++- cocos/animation/index.ts | 1 - cocos/components/animation-component.ts | 279 +++++------------------- 6 files changed, 109 insertions(+), 422 deletions(-) delete mode 100644 cocos/animation/animation-animator.ts diff --git a/cocos/animation/animation-animator.ts b/cocos/animation/animation-animator.ts deleted file mode 100644 index 6147ddca0d..0000000000 --- a/cocos/animation/animation-animator.ts +++ /dev/null @@ -1,180 +0,0 @@ -import { AnimationComponent } from '../components/animation-component'; -import { binarySearchEpsilon as binarySearch } from '../core/data/utils/binary-search'; -import { errorID } from '../core/platform/CCDebug'; -import { MutableForwardIterator } from '../core/utils/array'; -import { Node } from '../scene-graph'; -import { AnimationBlendState } from './animation-blend-state'; -import { EventAnimCurve, EventInfo } from './animation-curve'; -import { AnimationState } from './animation-state'; -import { Playable } from './playable'; -import { WrapModeMask } from './types'; - -/** - * The actual animator for Animation Component. - */ -export class AnimationAnimator extends Playable { - public _anims = new MutableForwardIterator([]); - - constructor (public target: Node, public animation: AnimationComponent) { - super(); - } - - public playState (state: AnimationState, startTime?: number) { - if (!state.clip) { - return; - } - - if (!state.curveLoaded) { - state.initialize(this.target); - } - - state.animator = this; - state.play(); - - if (typeof startTime === 'number') { - state.setTime(startTime); - } - - this.play(); - } - - public stopStatesExcept (state: AnimationState) { - const iterator = this._anims; - const array = iterator.array; - for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { - const anim = array[iterator.i]; - if (anim === state) { - continue; - } - - this.stopState(anim); - } - } - - public addAnimation (anim: AnimationState) { - const index = this._anims.array.indexOf(anim); - if (index === -1) { - this._anims.push(anim); - } - - anim._setEventTarget(this.animation); - } - - public removeAnimation (anim: AnimationState) { - const index = this._anims.array.indexOf(anim); - if (index >= 0) { - this._anims.fastRemoveAt(index); - - if (this._anims.array.length === 0) { - this.stop(); - } - } - else { - errorID(3908); - } - - anim.animator = null; - } - - public sample () { - const iterator = this._anims; - const array = iterator.array; - for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { - const anim = array[iterator.i]; - anim.sample(); - } - } - - public stopState (state?: AnimationState) { - if (state) { - state.stop(); - } - } - - public pauseState (state?: AnimationState) { - if (state) { - state.pause(); - } - } - - public resumeState (state?: AnimationState) { - if (state) { - state.resume(); - } - - if (this.isPaused) { - this.resume(); - } - } - - public setStateTime (state: AnimationState, time: number): void; - - public setStateTime (time: number): void; - - public setStateTime (state: AnimationState | number, time?: number) { - if (time !== undefined) { - (state as AnimationState).setTime(time); - (state as AnimationState).sample(); - } - else { - for (const anim of this._anims.array) { - anim.setTime(state as number); - anim.sample(); - } - } - } - - public onStop () { - const iterator = this._anims; - const array = iterator.array; - for (iterator.i = 0; iterator.i < array.length; ++iterator.i) { - const anim = array[iterator.i]; - anim.stop(); - } - } - - public onPause () { - for (const anim of this._anims.array) { - anim.pause(); - // need to unbind animator to anim, or it maybe cannot be gc. - anim.animator = null; - } - } - - public onResume () { - for (const anim of this._anims.array) { - // rebind animator to anim - anim.animator = this; - - anim.resume(); - } - } - - public _reloadClip (state: AnimationState) { - state.initialize(this.target); - } -} - -// 这个方法应该是 SampledAnimCurve 才能用 -function createBatchedProperty (propPath, firstDotIndex, mainValue, animValue) { - mainValue = mainValue.clone(); - let nextValue = mainValue; - let leftIndex = firstDotIndex + 1; - let rightIndex = propPath.indexOf('.', leftIndex); - - // scan property path - while (rightIndex !== -1) { - const nextName = propPath.slice(leftIndex, rightIndex); - nextValue = nextValue[nextName]; - leftIndex = rightIndex + 1; - rightIndex = propPath.indexOf('.', leftIndex); - } - const lastPropName = propPath.slice(leftIndex); - nextValue[lastPropName] = animValue; - - return mainValue; -} - -if (CC_TEST) { - cc._Test.createBatchedProperty = createBatchedProperty; -} diff --git a/cocos/animation/animation-manager.ts b/cocos/animation/animation-manager.ts index 9e17433a77..10d13cc976 100644 --- a/cocos/animation/animation-manager.ts +++ b/cocos/animation/animation-manager.ts @@ -1,6 +1,6 @@ import { ccclass } from '../core/data/class-decorator'; import { errorID } from '../core/platform/CCDebug'; -import { MutableForwardIterator } from '../core/utils/array'; +import { MutableForwardIterator, remove } from '../core/utils/array'; import { Node } from '../scene-graph'; import { AnimationBlendState } from './animation-blend-state'; import { AnimationState } from './animation-state'; @@ -27,6 +27,10 @@ export class AnimationManager { this._crossFades.push(crossFade); } + public removeCrossFade (crossFade: CrossFade) { + remove(this._crossFades, crossFade); + } + public update (dt: number) { for (const crossFade of this._crossFades) { crossFade.update(dt); diff --git a/cocos/animation/animation-state.ts b/cocos/animation/animation-state.ts index 6d37159de3..fa339a7ebf 100644 --- a/cocos/animation/animation-state.ts +++ b/cocos/animation/animation-state.ts @@ -1,6 +1,5 @@ import { binarySearchEpsilon as binarySearch } from '../core/data/utils/binary-search'; import { Node } from '../scene-graph'; -import { AnimationAnimator } from './animation-animator'; import { AnimationBlendState } from './animation-blend-state'; import { AnimationClip } from './animation-clip'; import { AnimCurve, EventAnimCurve, EventInfo } from './animation-curve'; @@ -120,7 +119,7 @@ export class AnimationState extends Playable { set delay (value: number) { this._delayTime = this._delay = value; } - public animator: AnimationAnimator | null = null; + /** * !#en The curves list. * !#zh 曲线列表。 @@ -487,10 +486,6 @@ export class AnimationState extends Playable { cc.director.getAnimationManager().addAnimation(this); - if (this.animator) { - this.animator.addAnimation(this); - } - this.emit('play', this); } @@ -499,10 +494,6 @@ export class AnimationState extends Playable { cc.director.getAnimationManager().removeAnimation(this); } - if (this.animator) { - this.animator.removeAnimation(this); - } - this.emit('stop', this); } diff --git a/cocos/animation/cross-fade.ts b/cocos/animation/cross-fade.ts index 82f8fd482e..338e7e4d64 100644 --- a/cocos/animation/cross-fade.ts +++ b/cocos/animation/cross-fade.ts @@ -15,22 +15,20 @@ export class CrossFade extends Playable { constructor (public target: Node) { super(); - this._fadings.push({ - state: null, - easeDuration: Number.POSITIVE_INFINITY, - easeTime: 0, - }); + this._unshiftDefault(); } public update (deltaTime: number) { + if (!this.isPlaying || this.isPaused) { + return; + } let absoluteWeight = 1.0; for (let i = 0; i < this._fadings.length; ++i) { if (absoluteWeight === 0) { for (let j = i; j < this._fadings.length; ++j) { const fading = this._fadings[j]; if (fading.state) { - fading.state.weight = 0; - fading.state.stop(); + this._directStopState(fading.state); } } this._fadings.splice(i); @@ -65,6 +63,48 @@ export class CrossFade extends Playable { } } + public onPause () { + super.onPause(); + for (const fading of this._fadings) { + if (fading.state) { + fading.state.pause(); + } + } + } + + public onResume () { + super.onResume(); + for (const fading of this._fadings) { + if (fading.state) { + fading.state.resume(); + } + } + } + + public onStop () { + super.onStop(); + for (const fading of this._fadings) { + if (fading.state) { + this._directStopState(fading.state); + } + } + this._fadings.length = 0; + this._unshiftDefault(); + } + + private _unshiftDefault () { + this._fadings.unshift({ + state: null, + easeDuration: Number.POSITIVE_INFINITY, + easeTime: 0, + }); + } + + private _directStopState (state: AnimationState) { + state.weight = 0; + state.stop(); + } + private _directPlayState (state: AnimationState) { if (!state.clip) { return; diff --git a/cocos/animation/index.ts b/cocos/animation/index.ts index 244b1893c0..6c660dd93f 100644 --- a/cocos/animation/index.ts +++ b/cocos/animation/index.ts @@ -7,4 +7,3 @@ export * from './animation-curve'; export * from './animation-clip'; export * from './animation-manager'; export * from './animation-state'; -export * from './animation-animator'; diff --git a/cocos/components/animation-component.ts b/cocos/components/animation-component.ts index 611a9692b7..94123526da 100644 --- a/cocos/components/animation-component.ts +++ b/cocos/components/animation-component.ts @@ -1,5 +1,5 @@ -import { AnimationAnimator, AnimationClip, AnimationState } from '../animation'; +import { AnimationClip, AnimationState } from '../animation'; import { CrossFade } from '../animation/cross-fade'; import { ccclass, executeInEditMode, executionOrder, menu, property } from '../core/data/class-decorator'; import { EventTargetFactory, IEventTargetCallback } from '../core/event/event-target-factory'; @@ -81,12 +81,16 @@ export class AnimationComponent extends EventTargetFactory(Component) { set preview (value) { this._preview = value; + if (!this._defaultClip) { + return; + } if (value) { cc.engine.animatingInEditMode = true; - this.play(); + this.crossFade(this._defaultClip.name); + this._crossFade!.resume(); } else { cc.engine.animatingInEditMode = false; - this.stop(); + this._crossFade!.pause(); } } @@ -152,9 +156,8 @@ export class AnimationComponent extends EventTargetFactory(Component) { public playOnLoad = false; private _preview = false; - private _animator: AnimationAnimator | null = null; private _crossFade: CrossFade | null = null; - private _nameToState: Partial<{ [name: string]: AnimationState; }> = createMap(true); + private _nameToState: { [name: string]: AnimationState; } = createMap(true); private _didInit = false; private _currentClip: AnimationClip | null = null; @@ -163,7 +166,7 @@ export class AnimationComponent extends EventTargetFactory(Component) { * !#zh 通过脚本可以访问并播放的 AnimationClip 列表。 */ @property({ type: [AnimationClip] }) - private _clips: AnimationClip[] = []; + private _clips: Array<(AnimationClip | null)> = []; @property private _defaultClip: AnimationClip | null = null; @@ -172,37 +175,33 @@ export class AnimationComponent extends EventTargetFactory(Component) { super(); } - public update (deltaTime: number) { - if (this._animator) { - this._animator.update(deltaTime); - } - } - public start () { + this._init(); + this._startCrossFade(); if (!CC_EDITOR && this.playOnLoad && this._defaultClip) { - const isPlaying = this._animator && this._animator.isPlaying; - if (!isPlaying) { - const state = this.getAnimationState(this._defaultClip.name); - // this._animator!.playState(state); - this._crossFade.crossFade(state, 0); - } + this.crossFade(this._defaultClip.name, 0); } } public onEnable () { - if (this._animator) { - this._animator.resume(); + if (this._crossFade) { + this._crossFade.resume(); } } public onDisable () { - if (this._animator) { - this._animator.pause(); + if (this._crossFade) { + this._crossFade.pause(); } } public onDestroy () { - this.stop(); + if (this._crossFade) { + this._crossFade.stop(); + cc.director.getAnimationManager().removeCrossFade(this._crossFade); + this._crossFade.stop(); + this._crossFade = null; + } } /** @@ -224,146 +223,18 @@ export class AnimationComponent extends EventTargetFactory(Component) { * var animCtrl = this.node.getComponent(cc.Animation); * animCtrl.play("linear"); */ - public play (name?: string, startTime?: number) { - const state = this.playAdditive(name, startTime); - this._animator!.stopStatesExcept(state); - return state; - } - - public crossFade (name: string, duration = 0.3) { - const state = this.getAnimationState(name || (this._defaultClip && this._defaultClip.name) || ''); - this._crossFade.crossFade(state, duration); - return state; - } - - /** - * !#en - * Plays an additive animation, it will not stop other animations. - * If there are other animations playing, then will play several animations at the same time. - * !#zh 播放指定的动画(将不会停止当前播放的动画)。如果没有指定动画,则播放默认动画。 - * @param [name] - The name of animation to play. If no name is supplied then the default animation will be played. - * @param [startTime] - play an animation from startTime - * @return The AnimationState of playing animation. In cases where the animation can't be played - * (ie, there is no default animation or no animation with the specified name), the function will return null. - * @example - * // linear_1 and linear_2 at the same time playing. - * var animCtrl = this.node.getComponent(cc.Animation); - * animCtrl.playAdditive("linear_1"); - * animCtrl.playAdditive("linear_2"); - */ - public playAdditive (name?: string, startTime?: number) { - this._init(); - const state = this.getAnimationState(name || (this._defaultClip && this._defaultClip.name) || ''); - + public play (name?: string, startTime = 0) { + const state = this.crossFade(name); if (state) { - this.enabled = true; - - const animator = this._animator; - if (animator!.isPlaying && state.isPlaying) { - if (state.isPaused) { - animator!.resumeState(state); - } - else { - animator!.stopState(state); - animator!.playState(state, startTime); - } - } - else { - animator!.playState(state, startTime); - } - - // Animation cannot be played when the component is not enabledInHierarchy. - // That would cause an error for the animation lost the reference after destroying the node. - // If users play the animation when the component is not enabledInHierarchy, - // we pause the animator here so that it will automatically resume the animation when users enable the component. - if (!this.enabledInHierarchy) { - animator!.pause(); - } - - this.currentClip = state.clip; + state.time = startTime; } return state; } - /** - * !#en Stops an animation named name. If no name is supplied then stops all playing animations that were started with this Animation.
- * Stopping an animation also Rewinds it to the Start. - * !#zh 停止指定的动画。如果没有指定名字,则停止当前正在播放的动画。 - * @param [name] - The animation to stop, if not supplied then stops all playing animations. - */ - public stop (name?: string) { - if (!this._didInit) { - return; - } - if (name) { - const state = this._nameToState[name]; - if (state) { - this._animator!.stopState(state); - } - } - else { - this._animator!.stop(); - } - } - - /** - * !#en Pauses an animation named name. If no name is supplied then pauses all playing animations that were started with this Animation. - * !#zh 暂停当前或者指定的动画。如果没有指定名字,则暂停当前正在播放的动画。 - * @param [name] - The animation to pauses, if not supplied then pauses all playing animations. - */ - public pause (name?: string) { - if (!this._didInit) { - return; - } - if (name) { - const state = this._nameToState[name]; - if (state) { - this._animator!.pauseState(state); - } - } - else { - this.enabled = false; - } - } - - /** - * !#en Resumes an animation named name. If no name is supplied then resumes all paused animations that were started with this Animation. - * !#zh 重新播放指定的动画,如果没有指定名字,则重新播放当前正在播放的动画。 - * @method resume - * @param {String} [name] - The animation to resumes, if not supplied then resumes all paused animations. - */ - public resume (name?: string) { - if (!this._didInit) { - return; - } - if (name) { - const state = this._nameToState[name]; - if (state) { - this._animator!.resumeState(state); - } - } - else { - this.enabled = true; - } - } - - /** - * !#en Make an animation named name go to the specified time. If no name is supplied then make all animations go to the specified time. - * !#zh 设置指定动画的播放时间。如果没有指定名字,则设置当前播放动画的播放时间。 - * @param [time] - The time to go to - * @param [name] - Specified animation name, if not supplied then make all animations go to the time. - */ - public setCurrentTime (time: number, name?: string) { - this._init(); - if (name) { - const state = this._nameToState[name]; - if (state) { - this._animator!.setStateTime(state, time); - } - } - else { - this._animator!.setStateTime(time); - } + public crossFade (name?: string, duration = 0.3) { + const state = this.getAnimationState(name || (this._defaultClip && this._defaultClip.name) || ''); + this._crossFade!.crossFade(state, duration); + return state; } /** @@ -372,23 +243,10 @@ export class AnimationComponent extends EventTargetFactory(Component) { */ public getAnimationState (name: string) { this._init(); - let state = this._nameToState[name]; - - if (CC_EDITOR && (!state || !ArrayUtils.contains(this._clips, state.clip))) { - this._didInit = false; - - if (this._animator) { - this._animator!.stop(); - } - - this._init(); - state = this._nameToState[name]; - } - + const state = this._nameToState[name]; if (state && !state.curveLoaded) { - this._animator!._reloadClip(state); + state.initialize(this.node); } - return state || null; } @@ -449,7 +307,7 @@ export class AnimationComponent extends EventTargetFactory(Component) { } this._init(); - let state; + let state: AnimationState | undefined; for (const name of Object.keys(this._nameToState)) { state = this._nameToState[name]; const stateClip = state.clip; @@ -467,7 +325,7 @@ export class AnimationComponent extends EventTargetFactory(Component) { } if (state && state.isPlaying) { - if (force) { this.stop(state.name); } + if (force) { state.stop(); } else { if (!CC_TEST) { warnID(3903); } return; @@ -481,26 +339,6 @@ export class AnimationComponent extends EventTargetFactory(Component) { } } - /** - * !#en - * Samples animations at the current state.
- * This is useful when you explicitly want to set up some animation state, and sample it once. - * !#zh 对指定或当前动画进行采样。你可以手动将动画设置到某一个状态,然后采样一次。 - */ - public sample (name: string) { - this._init(); - - if (name) { - const state = this._nameToState[name]; - if (state) { - state.sample(); - } - } - else { - this._animator!.sample(); - } - } - /** * !#en * Register animation event callback. @@ -534,15 +372,12 @@ export class AnimationComponent extends EventTargetFactory(Component) { */ public on (type: string, callback: (state: AnimationState) => void, target?: Object | null, useCapture?: boolean) { this._init(); - const ret = super.on(type, callback, target, useCapture); - if (type === 'lastframe') { - for (const state of this._animator!._anims.array) { - state._lastframeEventOn = true; + for (const stateName of Object.keys(this._nameToState)) { + this._nameToState[stateName]!._lastframeEventOn = true; } } - return ret; } @@ -590,42 +425,41 @@ export class AnimationComponent extends EventTargetFactory(Component) { return; } this._didInit = true; - this._animator = new AnimationAnimator(this.node, this); - this._createStates(); this._crossFade = new CrossFade(this.node); - cc.director.getAnimationManager().addCrossFade(this._crossFade); + this._createStates(); + } + + private _startCrossFade () { + cc.director.getAnimationManager().addCrossFade(this._crossFade!); + this._crossFade!.play(); } private _createStates () { this._nameToState = createMap(true); - - // create animation states - let state: AnimationState | null = null; - let defaultClipState: AnimationState | undefined; + // Create animation states. for (const clip of this._clips) { if (clip) { - state = new AnimationState(clip); - + const state = this._createState(clip); if (CC_EDITOR) { - this._animator!._reloadClip(state); - } - - this._nameToState[state.name] = state; - if (equalClips(this._defaultClip, clip)) { - defaultClipState = state; + state.initialize(this.node); } } } - if (this._defaultClip && !defaultClipState) { - state = new AnimationState(this._defaultClip); - + const isDefaultClipBounded = this._clips.findIndex((clip) => equalClips(clip, this._defaultClip)) >= 0; + if (this._defaultClip && !isDefaultClipBounded) { + const state = this._createState(this._defaultClip); if (CC_EDITOR) { - this._animator!._reloadClip(state); + state.initialize(this.node); } - - this._nameToState[state.name] = state; } } + + private _createState (clip: AnimationClip, name?: string) { + const state = new AnimationState(clip, name); + state._setEventTarget(this); + this._nameToState[state.name] = state; + return state; + } } cc.AnimationComponent = AnimationComponent; @@ -634,6 +468,5 @@ function equalClips (clip1: AnimationClip | null, clip2: AnimationClip | null) { if (clip1 === clip2) { return true; } - - return clip1 && clip2 && (clip1.name === clip2.name || clip1._uuid === clip2._uuid); + return !!clip1 && !!clip2 && (clip1.name === clip2.name || clip1._uuid === clip2._uuid); } From 156cb10b895ef4092638277e2c987b2bbdb97789 Mon Sep 17 00:00:00 2001 From: zxg0622 <247274249@qq.com> Date: Sun, 14 Apr 2019 00:59:47 +0800 Subject: [PATCH 2/7] fix shadow culling near clip bias error (#4213) --- cocos/pipeline/culling.ts | 9 +++++---- cocos/pipeline/forward/forward-stage.ts | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/cocos/pipeline/culling.ts b/cocos/pipeline/culling.ts index d8fa1f230e..b699321278 100644 --- a/cocos/pipeline/culling.ts +++ b/cocos/pipeline/culling.ts @@ -25,8 +25,8 @@ export function cullSpotLight (light: SpotLight, model: Model) { export const cullSceneWithDirectionalLight = (() => { const lightFrustum: frustum = new frustum(); lightFrustum.accurate = true; - return (out: Model[], modelToCull: Model[], sceneCamera: Camera, light: DirectionalLight, near: number, far: number) => { - calcDirectionalLightCullFrustum(lightFrustum, sceneCamera, light, near, far); + return (out: Model[], modelToCull: Model[], sceneCamera: Camera, light: DirectionalLight, near: number, far: number, nearBias: number) => { + calcDirectionalLightCullFrustum(lightFrustum, sceneCamera, light, near, far, nearBias); for (const m of modelToCull) { if (!m.enabled || !m.worldBounds) { continue; @@ -51,7 +51,7 @@ export const calcDirectionalLightCullFrustum = (() => { const lightVeiwMatInv = cc.mat4(); const minBoxCorner = cc.v3(); const maxBoxCorner = cc.v3(); - return (out: frustum, sceneCamera: Camera, light: DirectionalLight, near: number, far: number) => { + return (out: frustum, sceneCamera: Camera, light: DirectionalLight, near: number, far: number, nearBias: number) => { mat4.fromRT(lightViewMat, light.node.getWorldRotation(lightRot), sceneCamera.node.getWorldPosition(lightPos)); mat4.invert(lightVeiwMatInv, lightViewMat); sceneCamera.getSplitFrustum(camFrustum, near, far); @@ -70,9 +70,10 @@ export const calcDirectionalLightCullFrustum = (() => { } // calc the light world transform ,suppose that the light's position is at the camera's location. vec3.set(lightViewCenter, (minBoxCorner.x + maxBoxCorner.x) / 2, (minBoxCorner.y + maxBoxCorner.y) / 2, maxBoxCorner.z); + lightViewCenter.z += nearBias; vec3.transformMat4(lightPos, lightViewCenter, lightViewMat); mat4.fromRT(lightViewMat, light.node.getWorldRotation(lightRot), lightPos); // calc the light's frustum - frustum.createOrtho(out, maxBoxCorner.x - minBoxCorner.x, maxBoxCorner.y - minBoxCorner.y, 0, minBoxCorner.z - maxBoxCorner.z, lightViewMat); + frustum.createOrtho(out, maxBoxCorner.x - minBoxCorner.x, maxBoxCorner.y - minBoxCorner.y, 0, minBoxCorner.z - nearBias - maxBoxCorner.z, lightViewMat); }; })(); diff --git a/cocos/pipeline/forward/forward-stage.ts b/cocos/pipeline/forward/forward-stage.ts index 3af25e9211..e1013b447c 100644 --- a/cocos/pipeline/forward/forward-stage.ts +++ b/cocos/pipeline/forward/forward-stage.ts @@ -89,7 +89,7 @@ export class ForwardStage extends RenderStage { this._castShadowObjects.splice(0); const camera = view.camera; const scene = camera.scene; - cullSceneWithDirectionalLight(this._castShadowObjects, scene.models, camera, scene.mainLight, camera.nearClip, camera.farClip); + cullSceneWithDirectionalLight(this._castShadowObjects, scene.models, camera, scene.mainLight, camera.nearClip, camera.farClip, 10); for (const m of this._castShadowObjects) { for (let i = 0; i < m.subModelNum; i++) { for (let j = 0; j < m.getSubModel(i).passes.length; j++) { From 2c77e6ce8a050e6455403ed8a850c296aa35f114 Mon Sep 17 00:00:00 2001 From: JoneLau <32630749+JoneLau@users.noreply.github.com> Date: Mon, 15 Apr 2019 13:44:47 +0800 Subject: [PATCH 3/7] fix event bug (#4216) --- cocos/core/event/callbacks-invoker.ts | 4 ++-- cocos/scene-graph/node-event-processor.ts | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/cocos/core/event/callbacks-invoker.ts b/cocos/core/event/callbacks-invoker.ts index 39760b9e7a..db895a0419 100644 --- a/cocos/core/event/callbacks-invoker.ts +++ b/cocos/core/event/callbacks-invoker.ts @@ -94,7 +94,7 @@ export class CallbacksHandler{ * @param {Function} callback * @param {Object} [target] - can be null */ - public add (key, callback, target) { + public add (key: string, callback: Function, target?: Object) { let list = this._callbackTable[key]; if (!list) { list = this._callbackTable[key] = callbackListPool.get(); @@ -230,7 +230,7 @@ export class CallbacksInvoker extends CallbacksHandler{ * @param {any} [p5] */ public emit (key: string, ...args: any[]) { - const list = this._callbackTable[key]; + const list: CallbackList = this._callbackTable[key]; if (list) { const rootInvoker = !list.isInvoking; list.isInvoking = true; diff --git a/cocos/scene-graph/node-event-processor.ts b/cocos/scene-graph/node-event-processor.ts index 985a7349e1..e63ef31eb5 100644 --- a/cocos/scene-graph/node-event-processor.ts +++ b/cocos/scene-graph/node-event-processor.ts @@ -409,10 +409,10 @@ export class NodeEventProcessor { const hasOnceListener = listeners!.hasEventListener(eventType_hasOnceListener, callback, target); if (!hasOnceListener) { const self = this; - const onceWrapper = (...args) => { + const onceWrapper = function (this: Object, ...args: any[]) { self.off(type, onceWrapper, target); listeners.remove(eventType_hasOnceListener, callback, target); - callback.call(self._node, ...args); + callback.call(this, ...args); }; this.on(type, onceWrapper, target); listeners.add(eventType_hasOnceListener, callback, target); @@ -497,7 +497,7 @@ export class NodeEventProcessor { * eventTarget.emit('fire', event); * eventTarget.emit('fire', message, emitter); */ - public emit (type, ...args: any[]) { + public emit (type: string, ...args: any[]) { if (this.bubblingTargets) { this.bubblingTargets.emit(type, ...args); } From 48e50a25321459012039499240b671ca45d89d97 Mon Sep 17 00:00:00 2001 From: Leslie Leigh Date: Mon, 15 Apr 2019 13:45:48 +0800 Subject: [PATCH 4/7] Generate declarations(for temp) (#4218) --- .gitignore | 1 + .vscode/launch.json | 6 ++ scripts/embedded-cocos-3d.d.ts | 6 -- scripts/generate-declaration-cli.js | 8 -- scripts/generate-declaration.js | 59 -------------- .../embedded-cocos-3d.d.ts | 3 + .../generate-declarations-cli.js | 10 +++ .../generate-declarations.js | 79 +++++++++++++++++++ tsconfig-gendecls.json | 69 ---------------- tsconfig.json | 1 + 10 files changed, 100 insertions(+), 142 deletions(-) delete mode 100644 scripts/embedded-cocos-3d.d.ts delete mode 100644 scripts/generate-declaration-cli.js delete mode 100644 scripts/generate-declaration.js create mode 100644 scripts/generate-declarations/embedded-cocos-3d.d.ts create mode 100644 scripts/generate-declarations/generate-declarations-cli.js create mode 100644 scripts/generate-declarations/generate-declarations.js delete mode 100644 tsconfig-gendecls.json diff --git a/.gitignore b/.gitignore index 6360e267d8..1a131fbb24 100644 --- a/.gitignore +++ b/.gitignore @@ -16,3 +16,4 @@ DebugInfos.json /rollup/out /package-lock.json playground/library +/declarations diff --git a/.vscode/launch.json b/.vscode/launch.json index 0d7b47731b..354a0daf9e 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,6 +1,12 @@ { "version": "0.2.0", "configurations": [ + { + "type": "node", + "request": "launch", + "name": "Generate declaraions", + "program": "${workspaceFolder}/scripts/generate-declarations/generate-declarations-cli.js" + }, { "type": "chrome", "request": "launch", diff --git a/scripts/embedded-cocos-3d.d.ts b/scripts/embedded-cocos-3d.d.ts deleted file mode 100644 index 52131c2cd8..0000000000 --- a/scripts/embedded-cocos-3d.d.ts +++ /dev/null @@ -1,6 +0,0 @@ - -import _ = require("index"); - -declare global { - const cc: typeof _; -} \ No newline at end of file diff --git a/scripts/generate-declaration-cli.js b/scripts/generate-declaration-cli.js deleted file mode 100644 index 6f1d739b1d..0000000000 --- a/scripts/generate-declaration-cli.js +++ /dev/null @@ -1,8 +0,0 @@ -const { generate } = require('./generate-declaration'); -const { existsSync } = require('fs'); -const outputFiles = generate(); -if (!outputFiles || outputFiles.some((outputFile) => !existsSync(outputFile))) { - console.error(`Failed to generate declaration files.`); -} else { - console.log(`Generate successed. Files:\n${outputFiles.join('\n')}\n`); -} \ No newline at end of file diff --git a/scripts/generate-declaration.js b/scripts/generate-declaration.js deleted file mode 100644 index 452ea5c36c..0000000000 --- a/scripts/generate-declaration.js +++ /dev/null @@ -1,59 +0,0 @@ -const { spawnSync } = require('child_process'); -const { join, extname, basename, dirname } = require('path'); -const { readFileSync, existsSync, unlinkSync } = require('fs'); -const ts = require('typescript'); - -const tscExecutableName = process.platform === 'win32' ? 'tsc.cmd' : 'tsc'; -const tscExecutablePath = join(__dirname, '..', 'node_modules', '.bin', tscExecutableName); -const tssConfigDir = join(__dirname, '..'); -const tscConfigPath = join(tssConfigDir, 'tsconfig-gendecls.json'); -const extraDestFiles = [ - join(__dirname, './embedded-cocos-3d.d.ts'), -]; - -function generate () { - const tscConfig = ts.readConfigFile(tscConfigPath, (path) => readFileSync(path).toString()); - if (tscConfig.error) { - console.error(`Bad tsconfig.json: ${tscConfig.error.messageText}`); - return undefined; - } - - const outputJSPath = join(tssConfigDir, tscConfig.config.compilerOptions.outFile); - console.log(outputJSPath); - - const extName = extname(outputJSPath); - if (extName !== '.js') { - console.error(`Unexpected output extension ${extName}, please check it.`); - return undefined; - } - - const dirName = dirname(outputJSPath); - const baseName = basename(outputJSPath, extName); - const destExtensions = [ - '.d.ts', - '.d.ts.map', - ]; - - const destFiles = destExtensions.map((destExtension) => { - const destFile = join(dirName, baseName + destExtension); - if (existsSync(destFile)) { - console.log(`Delete old ${destFile}.`); - unlinkSync(destFile); - } - - return destFile; - }); - - console.log(`Generating...`); - - spawnSync(tscExecutablePath, [ - '-p', - tscConfigPath, - ], { - stdio: [ null, process.stdout, process.stderr ] - }); - - return destFiles.concat(extraDestFiles); -} - -module.exports = { generate }; diff --git a/scripts/generate-declarations/embedded-cocos-3d.d.ts b/scripts/generate-declarations/embedded-cocos-3d.d.ts new file mode 100644 index 0000000000..9cf52f369d --- /dev/null +++ b/scripts/generate-declarations/embedded-cocos-3d.d.ts @@ -0,0 +1,3 @@ + +export * from 'index'; +export as namespace cc; diff --git a/scripts/generate-declarations/generate-declarations-cli.js b/scripts/generate-declarations/generate-declarations-cli.js new file mode 100644 index 0000000000..6a252750fd --- /dev/null +++ b/scripts/generate-declarations/generate-declarations-cli.js @@ -0,0 +1,10 @@ +const { generate } = require('./generate-declarations'); + +const successed = generate({ + outDir: './declarations', +}); +if (successed) { + console.log(`Successed.`); +} else { + console.error(`Failed to generate declaration files.`); +} \ No newline at end of file diff --git a/scripts/generate-declarations/generate-declarations.js b/scripts/generate-declarations/generate-declarations.js new file mode 100644 index 0000000000..e82b5f15a3 --- /dev/null +++ b/scripts/generate-declarations/generate-declarations.js @@ -0,0 +1,79 @@ +const { spawnSync } = require('child_process'); +const { join, extname, basename, dirname } = require('path'); +const { copyFileSync, existsSync, readFileSync, unlinkSync, writeFileSync, ensureDirSync } = require('fs-extra'); +const ts = require('typescript'); + +const tscExecutableName = process.platform === 'win32' ? 'tsc.cmd' : 'tsc'; +const tscExecutablePath = join(__dirname, '..', '..', 'node_modules', '.bin', tscExecutableName); +const tsConfigDir = join(__dirname, '..', '..'); +const tsConfigPath = join(tsConfigDir, 'tsconfig.json'); +const tempTsConfigPath = join(tsConfigDir, '__tsconfig-gendecls.json'); +const extraDestFiles = [ + join(__dirname, 'embedded-cocos-3d.d.ts'), +]; + +function generate (options) { + const tsConfig = ts.readConfigFile(tsConfigPath, (path) => readFileSync(path).toString()); + if (tsConfig.error) { + console.error(`Bad tsconfig.json: ${tsConfig.error.messageText}`); + return undefined; + } + + const { outDir } = options; + ensureDirSync(outDir); + + tsConfig.config.compilerOptions.declaration = true; + tsConfig.config.compilerOptions.emitDeclarationOnly = true; + tsConfig.config.compilerOptions.outFile = join(outDir, `index.js`); + + const outputJSPath = join(tsConfigDir, tsConfig.config.compilerOptions.outFile); + console.log(outputJSPath); + + const extName = extname(outputJSPath); + if (extName !== '.js') { + console.error(`Unexpected output extension ${extName}, please check it.`); + return undefined; + } + const dirName = dirname(outputJSPath); + const baseName = basename(outputJSPath, extName); + const destExtensions = [ + '.d.ts', + '.d.ts.map', + ]; + for (const destExtension of destExtensions) { + const destFile = join(dirName, baseName + destExtension); + if (existsSync(destFile)) { + console.log(`Delete old ${destFile}.`); + unlinkSync(destFile); + } + } + + console.log(`Make temp config file ${tempTsConfigPath}.`); + + writeFileSync(tempTsConfigPath, JSON.stringify(tsConfig.config, undefined, 4)); + + console.log(`Generating...`); + + const tscResult = spawnSync(tscExecutablePath, [ + '-p', + tempTsConfigPath, + ], { + stdio: [process.stdin, process.stdout, process.stderr], + }); + if (tscResult.error) { + console.error(`Failed to compile engine: \n${tscResult.error}.`); + return false; + } + + console.log(`Delete temp config file ${tempTsConfigPath}.`); + + unlinkSync(tempTsConfigPath); + + const types = tsConfig.config.compilerOptions.types.map((typeFile) => `${typeFile}.d.ts`); + (types.concat(extraDestFiles)).forEach((file) => { + copyFileSync(file, join(outDir, basename(file))); + }); + return true; +} + +module.exports = { generate }; diff --git a/tsconfig-gendecls.json b/tsconfig-gendecls.json deleted file mode 100644 index 3b37444dcc..0000000000 --- a/tsconfig-gendecls.json +++ /dev/null @@ -1,69 +0,0 @@ -{ - "compilerOptions": { - /* Basic Options */ - "target": "es6", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017','ES2018' or 'ESNEXT'. */ - "lib": ["es2015", "es2017", "dom"], - "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */ - // "lib": [], /* Specify library files to be included in the compilation. */ - "allowJs": false, /* Allow javascript files to be compiled. */ - // "checkJs": true, /* Report errors in .js files. */ - // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ - "declaration": true, /* Generates corresponding '.d.ts' file. */ - "emitDeclarationOnly": true, - // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ - "sourceMap": true, /* Generates corresponding '.map' file. */ - "outFile": "index.js", /* Concatenate and emit output to single file. */ - "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ - // "composite": true, /* Enable project compilation */ - // "removeComments": true, /* Do not emit comments to output. */ - // "noEmit": true, /* Do not emit outputs. */ - // "importHelpers": true, /* Import emit helpers from 'tslib'. */ - // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ - // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ - - /* Strict Type-Checking Options */ - "strict": true, /* Enable all strict type-checking options. */ - "noImplicitAny": false, /* Raise error on expressions and declarations with an implied 'any' type. */ - // "strictNullChecks": true, /* Enable strict null checks. */ - // "strictFunctionTypes": true, /* Enable strict checking of function types. */ - // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ - // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ - // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ - // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ - - /* Additional Checks */ - // "noUnusedLocals": true, /* Report errors on unused locals. */ - // "noUnusedParameters": true, /* Report errors on unused parameters. */ - // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ - // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ - - /* Module Resolution Options */ - // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ - // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ - // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ - // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ - // "typeRoots": [], /* List of folders to include type definitions from. */ - "types": [ - "./@types/globals", - "./@types/ammo.js", - "./@types/wx", - "./cocos/gfx/webgl2/WebGL2", - ], /* Type declaration files to be included in compilation. */ - // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ - "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ - // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ - - /* Source Map Options */ - // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ - // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ - // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ - // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ - - /* Experimental Options */ - "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ - // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ - }, - "files": [ - "index.ts", - ], - } diff --git a/tsconfig.json b/tsconfig.json index dee4bcf66a..08f005c97e 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -47,6 +47,7 @@ "./@types/globals", "./@types/ammo.js", "./@types/wx", + "./cocos/gfx/webgl/WebGL", "./cocos/gfx/webgl2/WebGL2", ], /* Type declaration files to be included in compilation. */ // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ From 87dee1bbe255453425f14a633e3a4c861073b3c4 Mon Sep 17 00:00:00 2001 From: Leslie Leigh Date: Mon, 15 Apr 2019 14:04:54 +0800 Subject: [PATCH 5/7] fix (#4219) --- scripts/generate-declarations/generate-declarations.js | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/scripts/generate-declarations/generate-declarations.js b/scripts/generate-declarations/generate-declarations.js index e82b5f15a3..e47553f5a9 100644 --- a/scripts/generate-declarations/generate-declarations.js +++ b/scripts/generate-declarations/generate-declarations.js @@ -1,5 +1,5 @@ const { spawnSync } = require('child_process'); -const { join, extname, basename, dirname } = require('path'); +const { join, extname, basename, dirname, isAbsolute } = require('path'); const { copyFileSync, existsSync, readFileSync, unlinkSync, writeFileSync, ensureDirSync } = require('fs-extra'); const ts = require('typescript'); @@ -71,7 +71,9 @@ function generate (options) { const types = tsConfig.config.compilerOptions.types.map((typeFile) => `${typeFile}.d.ts`); (types.concat(extraDestFiles)).forEach((file) => { - copyFileSync(file, join(outDir, basename(file))); + const destPath = join(outDir, isAbsolute(file) ? basename(file) : file); + ensureDirSync(dirname(destPath)); + copyFileSync(file, destPath); }); return true; } From 74310477c24acc8fd1939fbab2482b8824a82dd0 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 15 Apr 2019 16:49:57 +0800 Subject: [PATCH 6/7] Use standard rAF name (#4222) --- cocos/core/game.js | 18 ++++++++---------- 1 file changed, 8 insertions(+), 10 deletions(-) diff --git a/cocos/core/game.js b/cocos/core/game.js index 55e07f8fec..872aa6922b 100644 --- a/cocos/core/game.js +++ b/cocos/core/game.js @@ -182,7 +182,7 @@ class Game extends EventTarget { } config.frameRate = frameRate; if (this._intervalId) - window.cancelAnimFrame(this._intervalId); + window.cancelAnimationFrame(this._intervalId); this._intervalId = 0; this._paused = true; this._setAnimFrame(); @@ -220,7 +220,7 @@ class Game extends EventTarget { this._paused = true; // Pause main loop if (this._intervalId) - window.cancelAnimFrame(this._intervalId); + window.cancelAnimationFrame(this._intervalId); this._intervalId = 0; } @@ -485,22 +485,20 @@ class Game extends EventTarget { if (CC_JSB) { jsb.setPreferredFramesPerSecond(frameRate); - window.requestAnimFrame = window.requestAnimationFrame; - window.cancelAnimFrame = window.cancelAnimationFrame; } else { if (frameRate !== 60 && frameRate !== 30) { - window.requestAnimFrame = this._stTime; - window.cancelAnimFrame = this._ctTime; + window.requestAnimationFrame = this._stTime; + window.cancelAnimationFrame = this._ctTime; } else { - window.requestAnimFrame = window.requestAnimationFrame || + window.requestAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || this._stTime; - window.cancelAnimFrame = window.cancelAnimationFrame || + window.cancelAnimationFrame = window.cancelAnimationFrame || window.cancelRequestAnimationFrame || window.msCancelRequestAnimationFrame || window.mozCancelRequestAnimationFrame || @@ -535,7 +533,7 @@ class Game extends EventTarget { callback = function () { if (!self._paused) { - self._intervalId = window.requestAnimFrame(callback); + self._intervalId = window.requestAnimationFrame(callback); if (!CC_JSB && frameRate === 30) { if (skip = !skip) { return; @@ -545,7 +543,7 @@ class Game extends EventTarget { } }; - self._intervalId = window.requestAnimFrame(callback); + self._intervalId = window.requestAnimationFrame(callback); self._paused = false; } From 0609c58a9dd0381ceabc3392d40450ed270511d8 Mon Sep 17 00:00:00 2001 From: "jiaxin.lai" Date: Mon, 15 Apr 2019 20:25:26 +0800 Subject: [PATCH 7/7] Fix problems where physics and scene synchronization are different (#4224) --- .../framework/physics/collider-component.ts | 63 +++++++++---------- .../physics/detail/physics-based-component.ts | 57 ++++++++++------- .../framework/physics/rigid-body-component.ts | 30 +++++---- cocos/3d/physics/cannon-impl.ts | 26 ++++---- cocos/3d/physics/instance.ts | 5 ++ 5 files changed, 98 insertions(+), 83 deletions(-) diff --git a/cocos/3d/framework/physics/collider-component.ts b/cocos/3d/framework/physics/collider-component.ts index ed6c563814..4c1ba24b92 100644 --- a/cocos/3d/framework/physics/collider-component.ts +++ b/cocos/3d/framework/physics/collider-component.ts @@ -8,7 +8,7 @@ import { import Vec3 from '../../../core/value-types/vec3'; import { vec3 } from '../../../core/vmath'; import { BoxShapeBase, ShapeBase, SphereShapeBase } from '../../physics/api'; -import { createBoxShape, createSphereShape, ERigidBodyType } from '../../physics/instance'; +import { createBoxShape, createSphereShape, ERigidBodyType, ETransformSource } from '../../physics/instance'; import { PhysicsBasedComponent } from './detail/physics-based-component'; export class ColliderComponentBase extends PhysicsBasedComponent { @@ -23,13 +23,18 @@ export class ColliderComponentBase extends PhysicsBasedComponent { set isTrigger (value) { this._triggered = value; - const type = this._triggered ? ERigidBodyType.DYNAMIC : ERigidBodyType.STATIC; - if (this._body) { - this._body.setType(type); + const type = this._triggered ? ERigidBodyType.DYNAMIC : ERigidBodyType.KINEMATIC; + if (this.sharedBody) { + this.sharedBody.body.setType(type); + } + if (this._shapeBase) { + this._shapeBase.setCollisionResponse(!this._triggered); } - this._shapeBase.setCollisionResponse(!this._triggered); } + @property + private _center: Vec3 = new cc.Vec3(0, 0, 0); + /** * The center of the collider, in local space. */ @@ -40,19 +45,21 @@ export class ColliderComponentBase extends PhysicsBasedComponent { set center (value: Vec3) { vec3.copy(this._center, value); - this._shapeBase.setCenter(this._center); + if (this._shapeBase) { + this._shapeBase.setCenter(this._center); + } } - @property - private _center: Vec3 = new cc.Vec3(0, 0, 0); - constructor () { super(); } public __preload () { super.__preload(); - + if (this.sharedBody) { + this.sharedBody.transfromSource = ETransformSource.SCENE; + this.sharedBody.body.setUseGravity(false); + } this.center = this._center; this.isTrigger = this._triggered; @@ -61,19 +68,12 @@ export class ColliderComponentBase extends PhysicsBasedComponent { } } - public onLoad () { - super.onLoad(); - } - - public start () { - super.start(); - } - - public lateUpdate () { - if (this.node.hasChanged) { - this._shapeBase.setScale(this.node._scale); - } - } + // public lateUpdate () { + // TODO : 根据node的scale dirty标记去缩放shape + // if (this.node.hasChanged) { + // this._shapeBase.setScale(this.node._scale); + // } + // } public onEnable () { if (this.sharedBody) { @@ -120,10 +120,6 @@ export class BoxColliderComponent extends ColliderComponentBase { this._shape.setScale(this.node._scale); } - public onLoad () { - super.onLoad(); - } - /** * The size of the box, in local space. * @note Shall not specify size with component 0. @@ -135,7 +131,9 @@ export class BoxColliderComponent extends ColliderComponentBase { set size (value) { vec3.copy(this._size, value); - this._shape!.setSize(this._size); + if (this._shape) { + this._shape.setSize(this._size); + } if (this.sharedBody) { this.sharedBody.body.commitShapeUpdates(); } @@ -157,7 +155,6 @@ export class SphereColliderComponent extends ColliderComponentBase { } public __preload () { - // const scale = this.node._scale; // const max = Math.abs(Math.max(scale.x, Math.max(scale.y, scale.z))); this._shape = createSphereShape(this._radius); @@ -169,10 +166,6 @@ export class SphereColliderComponent extends ColliderComponentBase { this._shape.setScale(this.node._scale); } - public onLoad () { - super.onLoad(); - } - /** * The radius of the sphere. */ @@ -183,7 +176,9 @@ export class SphereColliderComponent extends ColliderComponentBase { set radius (value) { this._radius = value; - this._shape.setRadius(value); + if (this._shape) { + this._shape.setRadius(value); + } if (this.sharedBody) { this.sharedBody.body.commitShapeUpdates(); } diff --git a/cocos/3d/framework/physics/detail/physics-based-component.ts b/cocos/3d/framework/physics/detail/physics-based-component.ts index 6eb20448c1..0b5d97105d 100644 --- a/cocos/3d/framework/physics/detail/physics-based-component.ts +++ b/cocos/3d/framework/physics/detail/physics-based-component.ts @@ -4,13 +4,13 @@ import { Quat, Vec3 } from '../../../../core/value-types'; import { quat, vec3 } from '../../../../core/vmath'; import { Node } from '../../../../scene-graph/node'; import { AfterStepCallback, BeforeStepCallback, ICollisionCallback, ICollisionEvent, PhysicsWorldBase, RigidBodyBase } from '../../../physics/api'; -import { createRigidBody } from '../../../physics/instance'; +import { createRigidBody, ERigidBodyType, ETransformSource } from '../../../physics/instance'; import { stringfyQuat, stringfyVec3 } from '../../../physics/util'; export class PhysicsBasedComponent extends Component { protected get _body () { - return this._sharedBody!.body; + return this._sharedBody ? this._sharedBody.body : null; } protected get sharedBody () { @@ -26,12 +26,6 @@ export class PhysicsBasedComponent extends Component { this._refSharedBody(); } - public onLoad () { - } - - public start () { - } - public destroy () { if (this._sharedBody) { this._sharedBody.deref(); @@ -39,12 +33,6 @@ export class PhysicsBasedComponent extends Component { } } - // public syncPhysWithScene () { - // if (this.sharedBody) { - // this.sharedBody.syncPhysWithScene(this.node); - // } - // } - private _refSharedBody () { if (this._sharedBody) { return; @@ -86,6 +74,8 @@ class SharedRigidBody { private _transformInitialized: boolean = false; + private _isShapeOnly: boolean = true; + constructor (node: Node, world: PhysicsWorldBase) { this._body = createRigidBody({ name: node.name, @@ -104,6 +94,15 @@ class SharedRigidBody { return this._body; } + /** 设置场景与物理之间的同步关系 */ + public set transfromSource (v: ETransformSource) { + if (v === ETransformSource.SCENE) { + this._isShapeOnly = true; + } else { + this._isShapeOnly = false; + } + } + public ref () { if (!this._refCount) { this._activeBody(); @@ -134,7 +133,7 @@ class SharedRigidBody { this.body.setPosition(p); this.body.setRotation(r); - // remove to shape, scale belong to shape + // scale property should handle by shape, scale belong to shape // node.getWorldScale(this._worldScale); // // Because we sync the scale, we should update shape parameters. // this.body.scaleAllShapes(this._worldScale); @@ -203,18 +202,34 @@ class SharedRigidBody { this._transformInitialized = true; this.syncPhysWithScene(this._node); this._activeBody(); + } else { + // 开始物理计算之前,用户脚本或引擎功能有可能改变节点的Transform,所以需要判断并进行更新 + if (this._node.hasChanged) { + this.syncPhysWithScene(this._node); + } } - if (!this.body.isPhysicsManagedTransform() && this._node.hasChanged) { - // d(`Synchronize`); - this.syncPhysWithScene(this._node); - this._activeBody(); - } + // if (!this.body.isPhysicsManagedTransform() && this._node.hasChanged) { + // // d(`Synchronize`); + // this.syncPhysWithScene(this._node); + // this._activeBody(); + // } } private _afterStep () { - if (this.body.isPhysicsManagedTransform()) { + // if (this.body.isPhysicsManagedTransform()) { + // this._syncSceneWithPhys(); + // } + + // 物理计算之后,除了只有形状组件的节点,其它有刚体组件的节点,并且刚体类型为DYNAMIC的,需要将计算结果同步到Scene中 + if (!this._isShapeOnly && this.body.getType() === ERigidBodyType.DYNAMIC) { this._syncSceneWithPhys(); + } else { + // 对于只有形状组件的节点,需要将Scene中节点的Transform同步到Phyisc。 + // 这是因为物理计算后可能会改变一些节点,这会导致这些子节点的Transform也发生改变。 + if (this._node.hasChanged) { + this.syncPhysWithScene(this._node); + } } } } diff --git a/cocos/3d/framework/physics/rigid-body-component.ts b/cocos/3d/framework/physics/rigid-body-component.ts index 0399c28f3e..e1151a48c4 100644 --- a/cocos/3d/framework/physics/rigid-body-component.ts +++ b/cocos/3d/framework/physics/rigid-body-component.ts @@ -9,11 +9,12 @@ import { import { Quat, Vec3 } from '../../../core/value-types'; import { vec3 } from '../../../core/vmath'; import { PhysicsMaterial } from '../../assets/physics/material'; +import { ETransformSource } from '../../physics/instance'; import { DefaultPhysicsMaterial as DefaultPhysicsMaterial } from './default-material'; import { PhysicsBasedComponent } from './detail/physics-based-component'; const NonRigidBodyProperties = { - mass: 0, + mass: 10, linearDamping: 0, angularDamping: 0, }; @@ -36,10 +37,10 @@ export class RigidBodyComponent extends PhysicsBasedComponent { private _angularDamping: number = NonRigidBodyProperties.angularDamping; @property - private _fixedRotation: boolean = true; + private _fixedRotation: boolean = false; @property - private _triggered: boolean = true; + private _triggered: boolean = false; @property private _isKinematic: boolean = false; @@ -53,11 +54,9 @@ export class RigidBodyComponent extends PhysicsBasedComponent { super(); } - public onLoad () { - super.onLoad(); - } - - public onEnable () { + public __preload () { + super.__preload(); + this.sharedBody!.transfromSource = ETransformSource.PHYSIC; if (this.sharedBody) { this.mass = this._mass; this.linearDamping = this._linearDamping; @@ -65,7 +64,12 @@ export class RigidBodyComponent extends PhysicsBasedComponent { this.material = this._material; this.useGravity = this._useGravity; this.velocity = this._velocity; + this.isKinematic = this._isKinematic; + this.fixedRotation = this._fixedRotation; } + } + + public onEnable () { // if (this.sharedBody) { // this.sharedBody.body.wakeUp(); // } @@ -77,13 +81,6 @@ export class RigidBodyComponent extends PhysicsBasedComponent { // } } - public start () { - super.start(); - if (this._enabled) { - this.onEnable(); - } - } - @property({ type: PhysicsMaterial, }) @@ -158,6 +155,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent { } } + @property get fixedRotation () { return this._fixedRotation; } @@ -165,7 +163,7 @@ export class RigidBodyComponent extends PhysicsBasedComponent { set fixedRotation (value) { this._fixedRotation = value; if (this._body) { - this._body.setFreezeRotation(!value); + this._body.setFreezeRotation(value); } } diff --git a/cocos/3d/physics/cannon-impl.ts b/cocos/3d/physics/cannon-impl.ts index 68f2176922..36d093ef98 100644 --- a/cocos/3d/physics/cannon-impl.ts +++ b/cocos/3d/physics/cannon-impl.ts @@ -166,9 +166,9 @@ function fillRaycastResult (result: RaycastResult, cannonResult: CANNON.RaycastR ); } -enum TransformSource { +enum ETransformSource { Scene, - Phycis, + Physics, } export class CannonRigidBody implements RigidBodyBase { @@ -185,7 +185,7 @@ export class CannonRigidBody implements RigidBodyBase { private _onWorldPostStepListener: (event: CANNON.ICollisionEvent) => any; private _collisionCallbacks: ICollisionCallback[] = []; private _shapes: CannonShape[] = []; - private _transformSource: TransformSource = TransformSource.Scene; + private _transformSource: ETransformSource = ETransformSource.Scene; private _userData: any; private _world: CannonWorld | null = null; private _name: string; @@ -196,6 +196,7 @@ export class CannonRigidBody implements RigidBodyBase { this._cannonMaterial = defaultCannonMaterial; this._cannonBody = new CANNON.Body({ material: this._cannonMaterial, + type: ERigidBodyType.DYNAMIC, }); setWrap(this._cannonBody, this); this._cannonBody.allowSleep = true; @@ -259,10 +260,10 @@ export class CannonRigidBody implements RigidBodyBase { public setMass (value: number) { this._cannonBody.mass = value; this._cannonBody.updateMassProperties(); - if (this._cannonBody.type !== CANNON.Body.KINEMATIC) { - this._resetBodyTypeAccordingMess(); - this._onBodyTypeUpdated(); - } + // if (this._cannonBody.type !== CANNON.Body.KINEMATIC) { + // // this._resetBodyTypeAccordingMess(); + // // this._onBodyTypeUpdated(); + // } } public getIsKinematic () { @@ -273,9 +274,10 @@ export class CannonRigidBody implements RigidBodyBase { if (value) { this._cannonBody.type = CANNON.Body.KINEMATIC; } else { - this._resetBodyTypeAccordingMess(); + this._cannonBody.type = CANNON.Body.DYNAMIC; + // this._resetBodyTypeAccordingMess(); } - this._onBodyTypeUpdated(); + // this._onBodyTypeUpdated(); } public getLinearDamping () { @@ -369,7 +371,7 @@ export class CannonRigidBody implements RigidBodyBase { } public isPhysicsManagedTransform (): boolean { - return this._transformSource === TransformSource.Phycis; + return this._transformSource === ETransformSource.Physics; } public getPosition (out: Vec3) { @@ -435,9 +437,9 @@ export class CannonRigidBody implements RigidBodyBase { private _onBodyTypeUpdated () { if (this._cannonBody) { if (this._cannonBody.type === CANNON.Body.STATIC) { - this._transformSource = TransformSource.Scene; + this._transformSource = ETransformSource.Scene; } else { - this._transformSource = TransformSource.Phycis; + this._transformSource = ETransformSource.Physics; } } } diff --git a/cocos/3d/physics/instance.ts b/cocos/3d/physics/instance.ts index 114463b22f..1137a0b445 100644 --- a/cocos/3d/physics/instance.ts +++ b/cocos/3d/physics/instance.ts @@ -9,6 +9,11 @@ export enum ERigidBodyType { KINEMATIC = 4, } +export enum ETransformSource { + SCENE = 0, + PHYSIC = 1, +} + export function createPhysicsWorld (): PhysicsWorldBase { return new PhysicsWorld(); }