From fdf26192db14d86ba36fe1a116e853a33cc12222 Mon Sep 17 00:00:00 2001 From: zhangyiwenzyw <543260203@qq.com> Date: Sun, 26 Apr 2020 13:45:43 +0800 Subject: [PATCH 01/74] move EditorCameraComponent to editor project (#6619) --- .../3d/framework/editor-camera-component.ts | 165 ------------------ cocos/core/3d/framework/index.ts | 2 - 2 files changed, 167 deletions(-) delete mode 100644 cocos/core/3d/framework/editor-camera-component.ts diff --git a/cocos/core/3d/framework/editor-camera-component.ts b/cocos/core/3d/framework/editor-camera-component.ts deleted file mode 100644 index c1c509924e..0000000000 --- a/cocos/core/3d/framework/editor-camera-component.ts +++ /dev/null @@ -1,165 +0,0 @@ -/** - * @hidden - */ - -import { ccclass } from '../../data/class-decorator'; -import { GFXClearFlag } from '../../gfx/define'; -import { toRadian } from '../../math'; -import { Camera } from '../../renderer'; -import { CameraComponent } from './camera-component'; -import { CAMERA_EDITOR_MASK } from '../../pipeline/define'; - -@ccclass('cc.EditorCameraComponent') -export class EditorCameraComponent extends CameraComponent { - - private _uiEditorCamera: Camera | null = null; - - set projection (val) { - // @ts-ignore - super.projection = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.projectionType = val; - } - } - - set fov (val) { - // @ts-ignore - super.fov = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.fov = toRadian(val); - } - } - - set orthoHeight (val) { - // @ts-ignore - super.orthoHeight = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.orthoHeight = val; - } - } - - set near (val) { - // @ts-ignore - super.near = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.nearClip = val; - } - } - - set far (val) { - // @ts-ignore - super.far = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.farClip = val; - } - } - - set clearColor (val) { - // @ts-ignore - super.clearColor = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.clearColor = val; - } - } - - set clearDepth (val) { - // @ts-ignore - super.clearDepth = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.clearDepth = val; - } - } - - set clearStencil (val) { - // @ts-ignore - super.clearStencil = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.clearStencil = val; - } - } - - set clearFlags (val) { - // @ts-ignore - super.clearFlags = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.clearFlag = val; - } - } - - set rect (val) { - // @ts-ignore - super.rect = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.viewport = val; - } - } - - set screenScale (val) { - // @ts-ignore - super.screenScale = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.screenScale = val; - } - } - - public onLoad () { - super.onLoad(); - - this._inEditorMode = true; - } - - public onEnable () { - super.onEnable(); - if (this._uiEditorCamera) { - cc.director.root!.ui.renderScene.addCamera(this._uiEditorCamera); - this._uiEditorCamera.enabled = true; - } - } - - public onDisable () { - super.onDisable(); - if (this._uiEditorCamera) { - cc.director.root!.ui.renderScene.removeCamera(this._uiEditorCamera); - } - } - - public onDestroy () { - super.onDestroy(); - if (this._uiEditorCamera) { - cc.director.root!.destroyCamera(this._uiEditorCamera); - this._uiEditorCamera = null; - } - } - - protected _createCamera () { - const priorCamera = this._camera; - super._createCamera(); - - if (this._camera !== priorCamera && this._camera) { - if (this._uiEditorCamera) { - cc.director.root!.destroyCamera(this._uiEditorCamera); - this._uiEditorCamera = null; - } - this._uiEditorCamera = cc.director.root!.createCamera(); - this._uiEditorCamera!.initialize({ - name: 'Editor UICamera', - node: this._camera.node, - projection: this._projection, - window: cc.director.root!.mainWindow, - priority: this._priority + 1, - flows: ['UIFlow'], - }); - this._uiEditorCamera!.enabled = true; - - this._uiEditorCamera!.visibility = CAMERA_EDITOR_MASK; - this._uiEditorCamera!.viewport = this._camera.viewport; - this._uiEditorCamera!.fov = this._camera.fov; - this._uiEditorCamera!.nearClip = this._camera.nearClip; - this._uiEditorCamera!.farClip = this._camera.farClip; - this._uiEditorCamera!.clearColor = this._camera.clearColor; - this._uiEditorCamera!.clearDepth = this._camera.clearDepth; - this._uiEditorCamera!.clearStencil = this._camera.clearStencil; - this._uiEditorCamera!.clearFlag = GFXClearFlag.DEPTH_STENCIL; - } - } -} diff --git a/cocos/core/3d/framework/index.ts b/cocos/core/3d/framework/index.ts index 8fcfda568a..17ff9fe225 100644 --- a/cocos/core/3d/framework/index.ts +++ b/cocos/core/3d/framework/index.ts @@ -31,7 +31,6 @@ import { BatchedSkinningModelComponent, SkinningModelUnit } from './batched-skinning-model-component'; import { CameraComponent } from './camera-component'; import { DirectionalLightComponent } from './directional-light-component'; -import { EditorCameraComponent } from './editor-camera-component'; import { LightComponent } from './light-component'; import { ModelComponent } from './model-component'; import { RenderableComponent } from './renderable-component'; @@ -56,7 +55,6 @@ export { // cc.AnimationComponent = AnimationComponent; cc.CameraComponent = CameraComponent; -cc.EditorComponent = EditorCameraComponent; cc.RenderableComponent = RenderableComponent; cc.ModelComponent = ModelComponent; cc.SkinningModelComponent = SkinningModelComponent; From f534c9d516300cc6ee91713d34b208ace45bc1e3 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 27 Apr 2020 18:49:23 +0800 Subject: [PATCH 02/74] fix typo (#6625) --- cocos/audio/assets/player-dom.ts | 16 ++++++++-------- .../batched-skinning-model-component.ts | 4 ++-- .../animation/skeletal-animation-component.ts | 2 +- cocos/core/renderer/models/skinning-model.ts | 14 +++++++------- cocos/core/renderer/scene/render-scene.ts | 8 ++++---- 5 files changed, 22 insertions(+), 22 deletions(-) diff --git a/cocos/audio/assets/player-dom.ts b/cocos/audio/assets/player-dom.ts index a8dc1007ef..7adbb24647 100644 --- a/cocos/audio/assets/player-dom.ts +++ b/cocos/audio/assets/player-dom.ts @@ -33,7 +33,7 @@ import { AudioPlayer, IAudioInfo, PlayingState } from './player'; export class AudioPlayerDOM extends AudioPlayer { protected _volume = 1; protected _loop = false; - protected _oneShoting = false; + protected _oneShotOngoing = false; protected _audio: HTMLAudioElement; protected _cbRegistered = false; @@ -81,7 +81,7 @@ export class AudioPlayerDOM extends AudioPlayer { this._audio.loop = this._loop; // callback on audio ended this._audio.addEventListener('ended', () => { - if (this._oneShoting) { return; } + if (this._oneShotOngoing) { return; } this._state = PlayingState.STOPPED; this._audio!.currentTime = 0; this._eventTarget.emit('ended'); @@ -110,7 +110,7 @@ export class AudioPlayerDOM extends AudioPlayer { if (!this._audio || this._state !== PlayingState.PLAYING) { return; } this._audio.pause(); this._state = PlayingState.STOPPED; - this._oneShoting = false; + this._oneShotOngoing = false; } public stop () { @@ -119,7 +119,7 @@ export class AudioPlayerDOM extends AudioPlayer { if (this._state !== PlayingState.PLAYING) { return; } this._audio.pause(); this._state = PlayingState.STOPPED; - this._oneShoting = false; + this._oneShotOngoing = false; } public playOneShot (volume = 1) { @@ -129,17 +129,17 @@ export class AudioPlayerDOM extends AudioPlayer { if (!clip) { return; } clip.currentTime = 0; clip.volume = volume; - if (this._oneShoting) { return; } + if (this._oneShotOngoing) { return; } clip.loop = false; - this._oneShoting = true; + this._oneShotOngoing = true; clip.play().then(() => { clip.addEventListener('ended', () => { clip.currentTime = 0; clip.volume = this._volume; clip.loop = this._loop; - this._oneShoting = false; + this._oneShotOngoing = false; }, { once: true }); - }).catch(() => { this._oneShoting = false; }); + }).catch(() => { this._oneShotOngoing = false; }); } public setCurrentTime (val: number) { diff --git a/cocos/core/3d/framework/batched-skinning-model-component.ts b/cocos/core/3d/framework/batched-skinning-model-component.ts index 526a582108..78c6a710b0 100644 --- a/cocos/core/3d/framework/batched-skinning-model-component.ts +++ b/cocos/core/3d/framework/batched-skinning-model-component.ts @@ -104,7 +104,7 @@ export class SkinningModelUnit { } /** - * @en Convevient setter, copying all necessary information from target skinning model component. + * @en Convenient setter, copying all necessary information from target skinning model component. * @zh 复制目标 SkinningModelComponent 的所有属性到本单元,方便快速配置。 */ @property({ type: SkinningModelComponent }) @@ -504,7 +504,7 @@ export class BatchedSkinningModelComponent extends SkinningModelComponent { private _createUnitMesh (unitIdx: number, mesh: Mesh) { // add batch ID to this temp mesh - // first, update bookkeepping + // first, update bookkeeping let uvOffset = 0; let uvFormat = GFXFormat.UNKNOWN; let bundleIdx = 0; diff --git a/cocos/core/animation/skeletal-animation-component.ts b/cocos/core/animation/skeletal-animation-component.ts index cfd9ef6a05..ae54822ef9 100644 --- a/cocos/core/animation/skeletal-animation-component.ts +++ b/cocos/core/animation/skeletal-animation-component.ts @@ -77,7 +77,7 @@ function collectRecursively (node: Node, prefix = '', out: string[] = []) { /** * @en - * Skeletal animaiton component, offers the following features on top of [[AnimationComponent]]: + * Skeletal animation component, offers the following features on top of [[AnimationComponent]]: * * Choice between baked animation and real-time calculation, to leverage efficiency and expressiveness. * * Joint socket system: Create any socket node directly under the animation component root node, * find your target joint and register both to the socket list, so that the socket node would be in-sync with the joint. diff --git a/cocos/core/renderer/models/skinning-model.ts b/cocos/core/renderer/models/skinning-model.ts index 6d10cc0d4b..a88ab1a860 100644 --- a/cocos/core/renderer/models/skinning-model.ts +++ b/cocos/core/renderer/models/skinning-model.ts @@ -111,7 +111,7 @@ export function deleteTransform (node: Node) { } } -function getRevelantBuffers (outIndices: number[], outBuffers: number[], jointMaps: number[][], targetJoint: number) { +function getRelevantBuffers (outIndices: number[], outBuffers: number[], jointMaps: number[][], targetJoint: number) { for (let i = 0; i < jointMaps.length; i++) { const idxMap = jointMaps[i]; let index = -1; @@ -152,7 +152,7 @@ export class SkinningModel extends MorphModel { public uploadAnimation = null; private _buffers: GFXBuffer[] = []; - private _datas: Float32Array[] = []; + private _dataArray: Float32Array[] = []; private _joints: IJointInfo[] = []; private _bufferIndices: number[] | null = null; @@ -192,7 +192,7 @@ export class SkinningModel extends MorphModel { const indices: number[] = []; const buffers: number[] = []; if (!jointMaps) { indices.push(index); buffers.push(0); } - else { getRevelantBuffers(indices, buffers, jointMaps, index); } + else { getRelevantBuffers(indices, buffers, jointMaps, index); } this._joints.push({ indices, buffers, bound, target, bindpose, transform }); } } @@ -228,11 +228,11 @@ export class SkinningModel extends MorphModel { const { indices, buffers, transform, bindpose } = this._joints[i]; Mat4.multiply(m4_1, transform.world, bindpose); for (let b = 0; b < buffers.length; b++) { - uploadJointData(this._datas[buffers[b]], indices[b] * 12, m4_1, i === 0); + uploadJointData(this._dataArray[buffers[b]], indices[b] * 12, m4_1, i === 0); } } for (let b = 0; b < this._buffers.length; b++) { - this._buffers[b].update(this._datas[b]); + this._buffers[b].update(this._dataArray[b]); } return true; } @@ -265,8 +265,8 @@ export class SkinningModel extends MorphModel { stride: UBOSkinning.SIZE, }); } - if (!this._datas[i]) { - this._datas[i] = new Float32Array(UBOSkinning.COUNT); + if (!this._dataArray[i]) { + this._dataArray[i] = new Float32Array(UBOSkinning.COUNT); } } } diff --git a/cocos/core/renderer/scene/render-scene.ts b/cocos/core/renderer/scene/render-scene.ts index 40af8f5ae9..4aff4a5a46 100644 --- a/cocos/core/renderer/scene/render-scene.ts +++ b/cocos/core/renderer/scene/render-scene.ts @@ -419,9 +419,9 @@ export class RenderScene { if (PREVIEW) { if (ui2dNode == null) { console.error('make sure UINode is not null'); } } - const uiTransfrom = ui2dNode._uiProps.uiTransformComp; - if (uiTransfrom == null || ui2dNode.layer & Layers.Enum.IGNORE_RAYCAST || !(ui2dNode.layer & mask)) { return; } - uiTransfrom.getComputeAABB(aabbUI); + const uiTransform = ui2dNode._uiProps.uiTransformComp; + if (uiTransform == null || ui2dNode.layer & Layers.Enum.IGNORE_RAYCAST || !(ui2dNode.layer & mask)) { return; } + uiTransform.getComputeAABB(aabbUI); const d = intersect.ray_aabb(worldRay, aabbUI); if (d <= 0) { @@ -456,7 +456,7 @@ const pool = new RecyclePool(() => { return { node: null!, distance: Infinity }; }, 8); const resultModels: IRaycastResult[] = []; -/** Canavas raycast result pool */ +/** Canvas raycast result pool */ const aabbUI = new aabb(); const poolUI = new RecyclePool(() => { return { node: null!, distance: Infinity }; From 1e876bcd2a0337ff60451ddd6de0c49f3127a8bd Mon Sep 17 00:00:00 2001 From: "jiaxin.lai" Date: Tue, 28 Apr 2020 14:37:12 +0800 Subject: [PATCH 03/74] fix spell for physics module (#6624) --- cocos/physics/ammo/ammo-shared-body.ts | 2 +- cocos/physics/cannon/cannon-rigid-body.ts | 2 +- cocos/physics/cannon/cannon-shared-body.ts | 2 +- cocos/physics/cannon/instantiate.ts | 4 ++-- .../physics/cannon/shapes/cannon-cylinder-shape.ts | 2 +- cocos/physics/cocos/builtin-shared-body.ts | 4 ++-- cocos/physics/cocos/builtin-world.ts | 2 +- .../components/collider/box-collider-component.ts | 2 +- .../collider/capsule-collider-component.ts | 2 +- .../components/collider/collider-component.ts | 6 +++--- .../components/collider/mesh-collider-component.ts | 2 +- .../collider/sphere-collider-component.ts | 2 +- .../physics/framework/components/constant-force.ts | 14 +++++++------- .../framework/components/rigid-body-component.ts | 2 +- cocos/physics/framework/deprecated.ts | 8 ++++++++ cocos/physics/framework/util.ts | 8 -------- cocos/physics/spec/i-physics-world.ts | 2 +- 17 files changed, 33 insertions(+), 33 deletions(-) diff --git a/cocos/physics/ammo/ammo-shared-body.ts b/cocos/physics/ammo/ammo-shared-body.ts index 5eb4aaf6a9..94e85a2ce5 100644 --- a/cocos/physics/ammo/ammo-shared-body.ts +++ b/cocos/physics/ammo/ammo-shared-body.ts @@ -244,7 +244,7 @@ export class AmmoSharedBody { } /** - * TODO: use motionstate + * TODO: use motion state */ syncPhysicsToScene () { if (this.body.isStaticObject() || !this.body.isActive()) { diff --git a/cocos/physics/cannon/cannon-rigid-body.ts b/cocos/physics/cannon/cannon-rigid-body.ts index b64f568fbf..1a248ba3ea 100644 --- a/cocos/physics/cannon/cannon-rigid-body.ts +++ b/cocos/physics/cannon/cannon-rigid-body.ts @@ -12,7 +12,7 @@ const v3_cannon0 = new CANNON.Vec3(); const v3_cannon1 = new CANNON.Vec3(); /** - * wraped shared body + * wrapped shared body * dynamic * kinematic */ diff --git a/cocos/physics/cannon/cannon-shared-body.ts b/cocos/physics/cannon/cannon-shared-body.ts index 07304f4f79..51cc191407 100644 --- a/cocos/physics/cannon/cannon-shared-body.ts +++ b/cocos/physics/cannon/cannon-shared-body.ts @@ -22,7 +22,7 @@ const CollisionEventObject = { }; /** - * sharedbody, node : sharedbody = 1 : 1 + * node : shared-body = 1 : 1 * static */ export class CannonSharedBody { diff --git a/cocos/physics/cannon/instantiate.ts b/cocos/physics/cannon/instantiate.ts index 5a12ea2154..8c56ba60ea 100644 --- a/cocos/physics/cannon/instantiate.ts +++ b/cocos/physics/cannon/instantiate.ts @@ -6,7 +6,7 @@ import { CannonWorld } from './cannon-world'; import { CannonBoxShape } from './shapes/cannon-box-shape'; import { CannonSphereShape } from './shapes/cannon-sphere-shape'; import { CannonTrimeshShape } from './shapes/cannon-trimesh-shape'; -import { CannonCyliderShape } from './shapes/cannon-cylinder-shape'; +import { CannonCylinderShape } from './shapes/cannon-cylinder-shape'; if (PHYSICS_CANNON) { instantiate({ @@ -15,6 +15,6 @@ if (PHYSICS_CANNON) { body: CannonRigidBody, world: CannonWorld, trimesh: CannonTrimeshShape, - cylinder: CannonCyliderShape + cylinder: CannonCylinderShape }); } diff --git a/cocos/physics/cannon/shapes/cannon-cylinder-shape.ts b/cocos/physics/cannon/shapes/cannon-cylinder-shape.ts index d55445e39d..078987fa5e 100644 --- a/cocos/physics/cannon/shapes/cannon-cylinder-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-cylinder-shape.ts @@ -7,7 +7,7 @@ import { EAxisDirection } from '../../framework/physics-enum'; import { IVec3Like } from '../../../core/math/type-define'; import { commitShapeUpdates } from '../cannon-util'; -export class CannonCyliderShape extends CannonShape implements ICylinderShape { +export class CannonCylinderShape extends CannonShape implements ICylinderShape { get collider () { return this._collider as CylinderColliderComponent; diff --git a/cocos/physics/cocos/builtin-shared-body.ts b/cocos/physics/cocos/builtin-shared-body.ts index 6e3a525884..dd3d122aa4 100644 --- a/cocos/physics/cocos/builtin-shared-body.ts +++ b/cocos/physics/cocos/builtin-shared-body.ts @@ -63,7 +63,7 @@ export class BuiltinSharedBody extends BuiltinObject { set reference (v: boolean) { v ? this.ref++ : this.ref--; - if (this.ref == 0) { this.destory(); } + if (this.ref == 0) { this.destroy(); } } /** id generator */ @@ -132,7 +132,7 @@ export class BuiltinSharedBody extends BuiltinObject { } } - private destory () { + private destroy () { BuiltinSharedBody.sharedBodesMap.delete(this.node.uuid); (this.node as any) = null; (this.world as any) = null; diff --git a/cocos/physics/cocos/builtin-world.ts b/cocos/physics/cocos/builtin-world.ts index 19917a65c0..9c6fb7098a 100644 --- a/cocos/physics/cocos/builtin-world.ts +++ b/cocos/physics/cocos/builtin-world.ts @@ -40,7 +40,7 @@ export class BuiltInWorld implements IPhysicsWorld { private _collisionMatrixPrev: ArrayCollisionMatrix = new ArrayCollisionMatrix(); step (deltaTime: number): void { - // store and reset collsion array + // store and reset collision array const tmp = this._shapeArrPrev; this._shapeArrPrev = this.shapeArr; this.shapeArr = tmp; diff --git a/cocos/physics/framework/components/collider/box-collider-component.ts b/cocos/physics/framework/components/collider/box-collider-component.ts index 41ee4edec3..0a1f60ccf7 100644 --- a/cocos/physics/framework/components/collider/box-collider-component.ts +++ b/cocos/physics/framework/components/collider/box-collider-component.ts @@ -54,7 +54,7 @@ export class BoxColliderComponent extends ColliderComponent { /** * @en - * Gets the wrapper object, through which the lowlevel instance can be accessed. + * Gets the wrapper object, through which the lowLevel instance can be accessed. * @zh * 获取封装对象,通过此对象可以访问到底层实例。 */ diff --git a/cocos/physics/framework/components/collider/capsule-collider-component.ts b/cocos/physics/framework/components/collider/capsule-collider-component.ts index 6b6aea702c..eec4688734 100644 --- a/cocos/physics/framework/components/collider/capsule-collider-component.ts +++ b/cocos/physics/framework/components/collider/capsule-collider-component.ts @@ -117,7 +117,7 @@ export class CapsuleColliderComponent extends ColliderComponent { /** * @en - * Gets the wrapper object, through which the lowlevel instance can be accessed. + * Gets the wrapper object, through which the lowLevel instance can be accessed. * @zh * 获取封装对象,通过此对象可以访问到底层实例。 */ diff --git a/cocos/physics/framework/components/collider/collider-component.ts b/cocos/physics/framework/components/collider/collider-component.ts index f696b316e4..6ef307050d 100644 --- a/cocos/physics/framework/components/collider/collider-component.ts +++ b/cocos/physics/framework/components/collider/collider-component.ts @@ -146,17 +146,17 @@ export class ColliderComponent extends Component implements IEventTarget { /** * @en - * Gets the collider attached rigidbody, this may be null + * Gets the collider attached rigid-body, this may be null * @zh * 获取碰撞器所绑定的刚体组件,可能为 null */ - public get attachedRigidbody (): RigidBodyComponent | null { + public get attachedRigidBody (): RigidBodyComponent | null { return this.shape.attachedRigidBody; } /** * @en - * Gets the wrapper object, through which the lowlevel instance can be accessed. + * Gets the wrapper object, through which the lowLevel instance can be accessed. * @zh * 获取封装对象,通过此对象可以访问到底层实例。 */ diff --git a/cocos/physics/framework/components/collider/mesh-collider-component.ts b/cocos/physics/framework/components/collider/mesh-collider-component.ts index 5c7f317013..9146bbc8c7 100644 --- a/cocos/physics/framework/components/collider/mesh-collider-component.ts +++ b/cocos/physics/framework/components/collider/mesh-collider-component.ts @@ -60,7 +60,7 @@ export class MeshColliderComponent extends ColliderComponent { /** * @en - * Gets the wrapper object, through which the lowlevel instance can be accessed. + * Gets the wrapper object, through which the lowLevel instance can be accessed. * @zh * 获取封装对象,通过此对象可以访问到底层实例。 */ diff --git a/cocos/physics/framework/components/collider/sphere-collider-component.ts b/cocos/physics/framework/components/collider/sphere-collider-component.ts index ec0d646c87..26789c8694 100644 --- a/cocos/physics/framework/components/collider/sphere-collider-component.ts +++ b/cocos/physics/framework/components/collider/sphere-collider-component.ts @@ -52,7 +52,7 @@ export class SphereColliderComponent extends ColliderComponent { /** * @en - * Gets the wrapper object, through which the lowlevel instance can be accessed. + * Gets the wrapper object, through which the lowLevel instance can be accessed. * @zh * 获取封装对象,通过此对象可以访问到底层实例。 */ diff --git a/cocos/physics/framework/components/constant-force.ts b/cocos/physics/framework/components/constant-force.ts index e951fb14aa..3f5b389ed9 100644 --- a/cocos/physics/framework/components/constant-force.ts +++ b/cocos/physics/framework/components/constant-force.ts @@ -32,7 +32,7 @@ import { PHYSICS_BUILTIN } from 'internal:constants'; @executeInEditMode export class ConstantForce extends Component { - private _rigidbody: RigidBodyComponent | null = null; + private _rigidBody: RigidBodyComponent | null = null; @property private readonly _force: Vec3 = new Vec3(); @@ -126,7 +126,7 @@ export class ConstantForce extends Component { public onLoad () { if (!PHYSICS_BUILTIN) { - this._rigidbody = this.node.getComponent(RigidBodyComponent); + this._rigidBody = this.node.getComponent(RigidBodyComponent); this._maskUpdate(this._force, 1); this._maskUpdate(this._localForce, 2); this._maskUpdate(this._torque, 4); @@ -136,22 +136,22 @@ export class ConstantForce extends Component { public lateUpdate (dt: number) { if (!PHYSICS_BUILTIN) { - if (this._rigidbody != null && this._mask != 0) { + if (this._rigidBody != null && this._mask != 0) { if (this._mask & 1) { - this._rigidbody.applyForce(this._force); + this._rigidBody.applyForce(this._force); } if (this._mask & 2) { - this._rigidbody.applyLocalForce(this.localForce); + this._rigidBody.applyLocalForce(this.localForce); } if (this._mask & 4) { - this._rigidbody.applyTorque(this._torque); + this._rigidBody.applyTorque(this._torque); } if (this._mask & 8) { - this._rigidbody.applyLocalTorque(this._localTorque); + this._rigidBody.applyLocalTorque(this._localTorque); } } diff --git a/cocos/physics/framework/components/rigid-body-component.ts b/cocos/physics/framework/components/rigid-body-component.ts index 30e7444e9d..2d4e5eb681 100644 --- a/cocos/physics/framework/components/rigid-body-component.ts +++ b/cocos/physics/framework/components/rigid-body-component.ts @@ -264,7 +264,7 @@ export class RigidBodyComponent extends Component { /** * @en - * Gets the wrapper object, through which the lowlevel instance can be accessed. + * Gets the wrapper object, through which the lowLevel instance can be accessed. * @zh * 获取封装对象,通过此对象可以访问到底层实例。 */ diff --git a/cocos/physics/framework/deprecated.ts b/cocos/physics/framework/deprecated.ts index 26c9cb8ca6..50d3a18143 100644 --- a/cocos/physics/framework/deprecated.ts +++ b/cocos/physics/framework/deprecated.ts @@ -8,6 +8,7 @@ import { BoxColliderComponent } from "./components/collider/box-collider-compone import { SphereColliderComponent } from "./components/collider/sphere-collider-component"; import { CapsuleColliderComponent } from "./components/collider/capsule-collider-component"; import { RigidBodyComponent } from "./components/rigid-body-component"; +import { ColliderComponent } from "./components/collider/collider-component"; replaceProperty(PhysicsSystem, 'PhysicsSystem', [ { @@ -16,6 +17,13 @@ replaceProperty(PhysicsSystem, 'PhysicsSystem', [ } ]); +replaceProperty(ColliderComponent.prototype, 'ColliderComponent.prototype', [ + { + "name": "attachedRigidbody", + "newName": "attachedRigidBody" + } +]); + replaceProperty(BoxColliderComponent.prototype, 'BoxColliderComponent.prototype', [ { "name": "boxShape", diff --git a/cocos/physics/framework/util.ts b/cocos/physics/framework/util.ts index 77f811f04b..82991f8e73 100644 --- a/cocos/physics/framework/util.ts +++ b/cocos/physics/framework/util.ts @@ -5,14 +5,6 @@ import { Vec3 } from '../../core/math'; import { IVec3Like, IQuatLike } from '../../core/math/type-define'; -export function stringfyVec3 (value: IVec3Like): string { - return `(x: ${value.x}, y: ${value.y}, z: ${value.z})`; -} - -export function stringfyQuat (value: IQuatLike): string { - return `(x: ${value.x}, y: ${value.y}, z: ${value.z}, w: ${value.w})`; -} - interface IWrapped { __cc_wrapper__: T; } diff --git a/cocos/physics/spec/i-physics-world.ts b/cocos/physics/spec/i-physics-world.ts index 7bf2520d8d..d66b404dd5 100644 --- a/cocos/physics/spec/i-physics-world.ts +++ b/cocos/physics/spec/i-physics-world.ts @@ -21,7 +21,7 @@ export interface IPhysicsWorld { setAllowSleep: (v: boolean) => void; setDefaultMaterial: (v: PhysicMaterial) => void; step (deltaTime: number, ...args: any): void; - raycast (worldRay: ray, options: IRaycastOptions, pool: RecyclePool, resultes: PhysicsRayResult[]): boolean + raycast (worldRay: ray, options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean raycastClosest (worldRay: ray, options: IRaycastOptions, out: PhysicsRayResult): boolean; emitEvents (): void; syncSceneToPhysics (): void; From db885e32d1fbd4b876358ea4a5d23bf0ba8567ce Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Tue, 28 Apr 2020 14:48:01 +0800 Subject: [PATCH 04/74] Warn if morph target count is overflow (#6622) --- EngineErrorMap.md | 4 ++++ cocos/core/assets/morph-rendering.ts | 7 ++++++- 2 files changed, 10 insertions(+), 1 deletion(-) diff --git a/EngineErrorMap.md b/EngineErrorMap.md index ceb0523c83..259e7e2624 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -2008,3 +2008,7 @@ Can't getGFXSampler with out device ### 10001 The sub-mesh contains %d vertices, which beyonds the capability (%d vertices most) of renderer of your platform. + +### 10002 + +Sub-mesh may include at most %d morph targets, but you specified %d. diff --git a/cocos/core/assets/morph-rendering.ts b/cocos/core/assets/morph-rendering.ts index 5d739193ce..18acde5ec0 100644 --- a/cocos/core/assets/morph-rendering.ts +++ b/cocos/core/assets/morph-rendering.ts @@ -4,7 +4,7 @@ import { Texture2D } from './texture-2d'; import { ImageAsset } from './image-asset'; import { samplerLib } from '../renderer/core/sampler-lib'; import { UBOMorph, UniformPositionMorphTexture, UniformNormalMorphTexture, UniformTangentMorphTexture } from '../pipeline/define'; -import { warn } from '../platform/debug'; +import { warn, warnID } from '../platform/debug'; import { MorphRendering, SubMeshMorph, Morph, MorphRenderingInstance } from './morph'; import { assertIsNonNullable, assertIsTrue } from '../data/utils/asserts'; import { nextPow2 } from '../math/bits'; @@ -38,6 +38,11 @@ export class StdMorphRendering implements MorphRendering { continue; } + if (subMeshMorph.targets.length > UBOMorph.MAX_MORPH_TARGET_COUNT) { + warnID(10002, UBOMorph.MAX_MORPH_TARGET_COUNT, subMeshMorph.targets.length); + continue; + } + if (preferCpuComputing) { this._subMeshRenderings[iSubMesh] = new CpuComputing( this._mesh, From c9462d94a57c6efc67d27a509385942a62a7740c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Tue, 28 Apr 2020 14:48:48 +0800 Subject: [PATCH 05/74] Typo (#6621) --- .vscode/cSpell.json | 1 + cocos/core/3d/framework/model-component.ts | 2 +- cocos/core/3d/framework/renderable-component.ts | 4 ++-- cocos/particle/particle-system-component.ts | 12 ++++++------ 4 files changed, 10 insertions(+), 9 deletions(-) diff --git a/.vscode/cSpell.json b/.vscode/cSpell.json index 8e23ac8199..d7cb4436d7 100644 --- a/.vscode/cSpell.json +++ b/.vscode/cSpell.json @@ -15,6 +15,7 @@ "IGFX", "lerp", "lerpable", + "lightmap", "mipmaps", "octree", "OPENGL", diff --git a/cocos/core/3d/framework/model-component.ts b/cocos/core/3d/framework/model-component.ts index d18f18d9b4..d203eae35a 100644 --- a/cocos/core/3d/framework/model-component.ts +++ b/cocos/core/3d/framework/model-component.ts @@ -366,7 +366,7 @@ export class ModelComponent extends RenderableComponent { return builtinResMgr.get('missing-material'); } - protected _onVisiblityChange (val: number) { + protected _onVisibilityChange (val: number) { if (!this._model) { return; } this._model.visFlags = val; } diff --git a/cocos/core/3d/framework/renderable-component.ts b/cocos/core/3d/framework/renderable-component.ts index a4a4822690..8fe29c3582 100644 --- a/cocos/core/3d/framework/renderable-component.ts +++ b/cocos/core/3d/framework/renderable-component.ts @@ -34,7 +34,7 @@ export class RenderableComponent extends Component { set visibility (val) { this._visFlags = val; - this._onVisiblityChange(val); + this._onVisibilityChange(val); } @property({ @@ -204,6 +204,6 @@ export class RenderableComponent extends Component { protected _clearMaterials () { } - protected _onVisiblityChange (val) { + protected _onVisibilityChange (val) { } } diff --git a/cocos/particle/particle-system-component.ts b/cocos/particle/particle-system-component.ts index aa25bfb01d..7d8d6099ca 100644 --- a/cocos/particle/particle-system-component.ts +++ b/cocos/particle/particle-system-component.ts @@ -297,14 +297,14 @@ export class ParticleSystemComponent extends RenderableComponent { public rateOverDistance = new CurveRange(); /** - * @zh 设定在指定时间发射指定数量的粒子的 Brust 的数量。 + * @zh 设定在指定时间发射指定数量的粒子的 burst 的数量。 */ @property({ type: [Burst], displayOrder: 16, tooltip:'在某个时间点发射给定数量的粒子' }) - public bursts = new Array(); + public bursts: Burst[] = new Array(); @property({ type: Material, @@ -334,7 +334,7 @@ export class ParticleSystemComponent extends RenderableComponent { }) public colorOverLifetimeModule = new ColorOverLifetimeModule(); - // shpae module + // Shape module /** * @zh 粒子发射器模块。 */ @@ -539,7 +539,7 @@ export class ParticleSystemComponent extends RenderableComponent { this.textureAnimationModule.bindTarget(this.processor!); } - // TODO: fastforward current particle system by simulating particles over given period of time, then pause it. + // TODO: Fast forward current particle system by simulating particles over given period of time, then pause it. // simulate(time, withChildren, restart, fixedTimeStep) { // } @@ -653,7 +653,7 @@ export class ParticleSystemComponent extends RenderableComponent { if (this._isPlaying) { this._time += scaledDeltaTime; - // excute emission + // Execute emission this._emit(scaledDeltaTime); // simulation, update particles. @@ -671,7 +671,7 @@ export class ParticleSystemComponent extends RenderableComponent { } } - protected _onVisiblityChange (val) { + protected _onVisibilityChange (val) { // @ts-ignore if (this.processor._model) { // @ts-ignore From 944f9c7d8161181e3109d22ac5ab30d5f7686ad8 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Wed, 6 May 2020 18:42:26 +0800 Subject: [PATCH 06/74] fix batched skinning model init (#6649) --- .../core/3d/framework/batched-skinning-model-component.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/cocos/core/3d/framework/batched-skinning-model-component.ts b/cocos/core/3d/framework/batched-skinning-model-component.ts index 78c6a710b0..2fc7100b11 100644 --- a/cocos/core/3d/framework/batched-skinning-model-component.ts +++ b/cocos/core/3d/framework/batched-skinning-model-component.ts @@ -304,16 +304,16 @@ export class BatchedSkinningModelComponent extends SkinningModelComponent { } } + if (!isValid || !this._skinningRoot) { + return; + } + if (this._mesh) { this._mesh.destroyRenderingMesh(); } else { this._mesh = new Mesh(); } - if (!isValid || !this._skinningRoot) { - return; - } - let posOffset = 0; let posFormat = GFXFormat.UNKNOWN; let normalOffset = 0; From e39395b88c28e61971a57bf08299c36e3157596d Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Thu, 7 May 2020 15:16:46 +0800 Subject: [PATCH 07/74] firefox bug workaround (#6651) --- cocos/core/gfx/webgl2/webgl2-commands.ts | 20 +++++++++++++++++++- cocos/core/renderer/models/morph-model.ts | 18 +++++++++--------- 2 files changed, 28 insertions(+), 10 deletions(-) diff --git a/cocos/core/gfx/webgl2/webgl2-commands.ts b/cocos/core/gfx/webgl2/webgl2-commands.ts index a040cacd8f..497e84eb1b 100644 --- a/cocos/core/gfx/webgl2/webgl2-commands.ts +++ b/cocos/core/gfx/webgl2/webgl2-commands.ts @@ -807,8 +807,26 @@ export function WebGL2CmdFuncCreateBuffer (device: WebGL2GFXDevice, gpuBuffer: W } export function WebGL2CmdFuncDestroyBuffer (device: WebGL2GFXDevice, gpuBuffer: WebGL2GPUBuffer) { + const gl = device.gl; if (gpuBuffer.glBuffer) { - device.gl.deleteBuffer(gpuBuffer.glBuffer); + // Firefox 75+ implicitly unbind whatever buffer there was on the slot sometimes + // can be reproduced in the static batching scene at https://github.com/cocos-creator/test-cases-3d + switch (gpuBuffer.glTarget) { + case gl.ARRAY_BUFFER: + gl.bindBuffer(gl.ARRAY_BUFFER, null); + device.stateCache.glArrayBuffer = null; + break; + case gl.ELEMENT_ARRAY_BUFFER: + gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); + device.stateCache.glElementArrayBuffer = null; + break; + case gl.UNIFORM_BUFFER: + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + device.stateCache.glUniformBuffer = null; + break; + } + + gl.deleteBuffer(gpuBuffer.glBuffer); gpuBuffer.glBuffer = null; } } diff --git a/cocos/core/renderer/models/morph-model.ts b/cocos/core/renderer/models/morph-model.ts index 9e54a943f5..ec59534c10 100644 --- a/cocos/core/renderer/models/morph-model.ts +++ b/cocos/core/renderer/models/morph-model.ts @@ -44,17 +44,17 @@ export class MorphModel extends Model { private _launderMaterial (material: Material) { return material; - if (this._usedMaterials.has(material)) { - return new MaterialInstance({ - parent: material, - }); - } else { - this._usedMaterials.add(material); - return material; - } + // if (this._usedMaterials.has(material)) { + // return new MaterialInstance({ + // parent: material, + // }); + // } else { + // this._usedMaterials.add(material); + // return material; + // } } public setMorphRendering (morphRendering: MorphRenderingInstance) { this._morphRenderingInstance = morphRendering; } -} \ No newline at end of file +} From 9cf4b50f416d32672ac56efb0b3d3c5f681c69e1 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Thu, 7 May 2020 15:32:42 +0800 Subject: [PATCH 08/74] ui-stencil bug fix (#6635) --- cocos/core/renderer/ui/ui-material.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/core/renderer/ui/ui-material.ts b/cocos/core/renderer/ui/ui-material.ts index bfa490d0bb..f54751f4cc 100644 --- a/cocos/core/renderer/ui/ui-material.ts +++ b/cocos/core/renderer/ui/ui-material.ts @@ -65,7 +65,7 @@ export class UIMaterial { this._material.copy(info.material); - this._pass = this._material.passes[0]; + this._pass = info.material.passes[0]; this._pass.update(); this._psos = new Pool(() => { From 91b6178c808e80353d30d547b7c804b8b8de47f6 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 11 May 2020 15:56:32 +0800 Subject: [PATCH 09/74] fix socket animation in real-time mode (#6671) --- cocos/core/animation/animation-component.ts | 2 +- cocos/core/animation/animation-manager.ts | 56 ++++++++++++++++--- cocos/core/animation/animation-state.ts | 6 +- .../animation/skeletal-animation-blending.ts | 10 ++-- .../animation/skeletal-animation-component.ts | 9 +++ .../animation/skeletal-animation-state.ts | 22 +------- cocos/core/animation/target-path.ts | 16 +++--- cocos/core/renderer/models/skinning-model.ts | 1 + 8 files changed, 79 insertions(+), 43 deletions(-) diff --git a/cocos/core/animation/animation-component.ts b/cocos/core/animation/animation-component.ts index aaae3869e4..d8f3849a84 100644 --- a/cocos/core/animation/animation-component.ts +++ b/cocos/core/animation/animation-component.ts @@ -187,7 +187,7 @@ export class AnimationComponent extends Component implements IEventTarget { protected _nameToState: { [name: string]: AnimationState; } = createMap(true); @property({ type: [AnimationClip] }) - protected _clips: Array<(AnimationClip | null)> = []; + protected _clips: (AnimationClip | null)[] = []; @property protected _defaultClip: AnimationClip | null = null; diff --git a/cocos/core/animation/animation-manager.ts b/cocos/core/animation/animation-manager.ts index 0f5fe9a151..74bc328d90 100644 --- a/cocos/core/animation/animation-manager.ts +++ b/cocos/core/animation/animation-manager.ts @@ -12,6 +12,13 @@ import { MutableForwardIterator, remove } from '../utils/array'; import { BlendStateBuffer } from './skeletal-animation-blending'; import { AnimationState } from './animation-state'; import { CrossFade } from './cross-fade'; +import { IJointTransform, deleteTransform, getTransform, getWorldMatrix } from '../renderer/models/skinning-model'; +import { Socket } from './skeletal-animation-component'; + +interface ISocketData { + target: Node; + transform: IJointTransform; +} @ccclass export class AnimationManager extends System { @@ -22,9 +29,10 @@ export class AnimationManager extends System { public static ID = 'animation'; private _anims = new MutableForwardIterator([]); - private _delayEvents: Array<{target: Node; func: string; args: any[]}> = []; + private _delayEvents: {target: Node; func: string; args: any[]}[] = []; private _blendStateBuffer: BlendStateBuffer = new BlendStateBuffer(); private _crossFades: CrossFade[] = []; + private _sockets: ISocketData[] = []; public addCrossFade (crossFade: CrossFade) { this._crossFades.push(crossFade); @@ -35,8 +43,10 @@ export class AnimationManager extends System { } public update (dt: number) { - for (const crossFade of this._crossFades) { - crossFade.update(dt); + const { _delayEvents, _crossFades, _sockets } = this; + + for (let i = 0, l = _crossFades.length; i < l; i++) { + _crossFades[i].update(dt); } const iterator = this._anims; const array = iterator.array; @@ -48,12 +58,17 @@ export class AnimationManager extends System { } this._blendStateBuffer.apply(); - const events = this._delayEvents; - for (let i = 0, l = events.length; i < l; i++) { - const event = events[i]; + const stamp = cc.director.getTotalFrames(); + for (let i = 0, l = _sockets.length; i < l; i++) { + const { target, transform } = _sockets[i]; + target.matrix = getWorldMatrix(transform, stamp); + } + + for (let i = 0, l = _delayEvents.length; i < l; i++) { + const event = _delayEvents[i]; event.target[event.func].apply(event.target, event.args); } - events.length = 0; + _delayEvents.length = 0; } public destruct () { @@ -83,6 +98,33 @@ export class AnimationManager extends System { args, }); } + + public addSockets (root: Node, sockets: Socket[]) { + for (let i = 0; i < sockets.length; ++i) { + const socket = sockets[i]; + if (this._sockets.find((s) => s.target === socket.target)) { continue; } + const targetNode = root.getChildByPath(socket.path); + const transform = socket.target && targetNode && getTransform(targetNode, root); + if (transform) { + this._sockets.push({ target: socket.target!, transform }); + } + } + } + + public removeSockets (root: Node, sockets: Socket[]) { + for (let i = 0; i < sockets.length; ++i) { + const socketToRemove = sockets[i]; + for (let j = 0; j < this._sockets.length; ++j) { + const socket = this._sockets[j]; + if (socket.target === socketToRemove.target) { + deleteTransform(socket.transform.node); + this._sockets[j] = this._sockets[this._sockets.length - 1]; + this._sockets.length--; + break; + } + } + } + } } director.on(Director.EVENT_INIT, () => { diff --git a/cocos/core/animation/animation-state.ts b/cocos/core/animation/animation-state.ts index 90547208b6..1e17d140cb 100644 --- a/cocos/core/animation/animation-state.ts +++ b/cocos/core/animation/animation-state.ts @@ -304,10 +304,10 @@ export class AnimationState extends Playable { /** * May be `null` due to failed to initialize. */ - protected _commonTargetStatuses: Array = []; + })[] = []; protected _curveLoaded = false; protected _ignoreIndex = InvalidIndex; private _blendStateBuffer: BlendStateBuffer | null = null; @@ -367,7 +367,7 @@ export class AnimationState extends Playable { this._samplerSharedGroups.push(samplerSharedGroup); } - let rootTarget: any = undefined; + let rootTarget: any; if (typeof propertyCurve.commonTarget === 'undefined') { rootTarget = root; } else { diff --git a/cocos/core/animation/skeletal-animation-blending.ts b/cocos/core/animation/skeletal-animation-blending.ts index 9639d1ab10..c160ec6c8f 100644 --- a/cocos/core/animation/skeletal-animation-blending.ts +++ b/cocos/core/animation/skeletal-animation-blending.ts @@ -80,7 +80,7 @@ export type IBlendStateWriter = IValueProxyFactory & { destroy: () => void; }; -export function createBlendStateWriter

( +export function createBlendStateWriter

( blendState: BlendStateBuffer, node: Node, property: P, @@ -98,18 +98,18 @@ export function createBlendStateWriter

( let isConstCacheValid = false; let lastWeight = -1; return { - initialize: function () { + initialize () { if (!propertyBlendState) { propertyBlendState = blendState.ref(node, property); } }, - destroy: function () { + destroy () { if (propertyBlendState) { blendState.deRef(node, property); propertyBlendState = null; } }, - forTarget: (_) => { + forTarget: () => { return { set: (value: BlendingPropertyValue

) => { if (!propertyBlendState) { @@ -120,7 +120,7 @@ export function createBlendStateWriter

( if (weight !== 1 || weight !== lastWeight) { // If there are multi writer for this property at this time, - // or if the weight has been changed since last write, + // or if the weight has been changed since last write, // we should invalidate the cache. isConstCacheValid = false; } else if (isConstCacheValid) { diff --git a/cocos/core/animation/skeletal-animation-component.ts b/cocos/core/animation/skeletal-animation-component.ts index ae54822ef9..d6ffaf352c 100644 --- a/cocos/core/animation/skeletal-animation-component.ts +++ b/cocos/core/animation/skeletal-animation-component.ts @@ -37,6 +37,7 @@ import { AnimationComponent } from './animation-component'; import { SkelAnimDataHub } from './skeletal-animation-data-hub'; import { SkeletalAnimationState } from './skeletal-animation-state'; import { getWorldTransformUntilRoot } from './transform-utils'; +import { AnimationManager } from './animation-manager'; @ccclass('cc.SkeletalAnimationComponent.Socket') export class Socket { @@ -110,6 +111,11 @@ export class SkeletalAnimationComponent extends AnimationComponent { return this._sockets; } set sockets (val) { + if (!this._useBakedAnimation) { + const animMgr = cc.director.getAnimationManager() as AnimationManager; + animMgr.removeSockets(this.node, this._sockets); + animMgr.addSockets(this.node, val); + } this._sockets = val; this.rebuildSocketAnimations(); } @@ -138,6 +144,8 @@ export class SkeletalAnimationComponent extends AnimationComponent { comp.setUseBakedAnimation(this._useBakedAnimation); } } + if (this._useBakedAnimation) { (cc.director.getAnimationManager() as AnimationManager).removeSockets(this.node, this._sockets); } + else { (cc.director.getAnimationManager() as AnimationManager).addSockets(this.node, this._sockets); } } @property @@ -149,6 +157,7 @@ export class SkeletalAnimationComponent extends AnimationComponent { public onDestroy () { super.onDestroy(); (cc.director.root.dataPoolManager as DataPoolManager).jointAnimationInfo.destroy(this.node.uuid); + (cc.director.getAnimationManager() as AnimationManager).removeSockets(this.node, this._sockets); } public start () { diff --git a/cocos/core/animation/skeletal-animation-state.ts b/cocos/core/animation/skeletal-animation-state.ts index 273a354b41..6bba178477 100644 --- a/cocos/core/animation/skeletal-animation-state.ts +++ b/cocos/core/animation/skeletal-animation-state.ts @@ -30,7 +30,6 @@ import { SkinningModelComponent } from '../3d/framework/skinning-model-component'; import { Mat4, Quat, Vec3 } from '../math'; import { IAnimInfo, JointAnimationInfo } from '../renderer/models/skeletal-animation-utils'; -import { deleteTransform, getTransform, getWorldMatrix, IJointTransform } from '../renderer/models/skinning-model'; import { Node } from '../scene-graph/node'; import { AnimationClip, IRuntimeCurve } from './animation-clip'; import { AnimationState } from './animation-state'; @@ -49,7 +48,6 @@ interface ITransform { interface ISocketData { target: Node; - transform: IJointTransform; frames: ITransform[]; } @@ -102,7 +100,7 @@ export class SkeletalAnimationState extends AnimationState { this._comps[i].uploadAnimation(this.clip); } } else { - this._sampleCurves = this._sampleCurvesRealTime; + this._sampleCurves = super._sampleCurves; this.duration = this._clip.duration; if (!this._curvesInited) { this._curveLoaded = false; @@ -113,18 +111,13 @@ export class SkeletalAnimationState extends AnimationState { } public rebuildSocketCurves (sockets: Socket[]) { - for (let i = 0; i < this._sockets.length; ++i) { - const socket = this._sockets[i]; - deleteTransform(socket.transform.node); - } this._sockets.length = 0; if (!this._targetNode) { return null; } const root = this._targetNode; for (let i = 0; i < sockets.length; ++i) { const socket = sockets[i]; const targetNode = root.getChildByPath(socket.path); - const transform = targetNode && getTransform(targetNode, root); - if (!transform || !socket.target) { continue; } + if (!socket.target) { continue; } const sourceData = SkelAnimDataHub.getOrExtract(this.clip).data; // find lowest joint animation let animPath = socket.path; @@ -139,7 +132,7 @@ export class SkeletalAnimationState extends AnimationState { } // create animation data const socketData: ISocketData = { - target: socket.target, transform, + target: socket.target, frames: source.worldMatrix.values.map(() => ({ pos: new Vec3(), rot: new Quat(), scale: new Vec3() })), }; const frames = source.worldMatrix.values as Mat4[]; @@ -166,13 +159,4 @@ export class SkeletalAnimationState extends AnimationState { target.setRTS(rot, pos, scale); } } - - private _sampleCurvesRealTime (ratio: number) { - super._sampleCurves(ratio); - const stamp = cc.director.getTotalFrames(); - for (let i = 0; i < this._sockets.length; ++i) { - const { target, transform } = this._sockets[i]; - target.matrix = getWorldMatrix(transform, stamp); - } - } } diff --git a/cocos/core/animation/target-path.ts b/cocos/core/animation/target-path.ts index 50dc05a3b0..7f405254ff 100644 --- a/cocos/core/animation/target-path.ts +++ b/cocos/core/animation/target-path.ts @@ -4,14 +4,14 @@ import { ccclass, property } from '../data/class-decorator'; import { Node } from '../scene-graph/node'; -import { error } from '../platform/debug'; +import { warn } from '../platform/debug'; export type PropertyPath = string | number; export interface ICustomTargetPath { /** * If errors are encountered, `null` should be returned. - * @param target + * @param target */ get(target: any): any; } @@ -37,12 +37,12 @@ export class HierarchyPath implements ICustomTargetPath { public get (target: Node) { if (!(target instanceof Node)) { - error(`Target of hierarchy path shall be Node.`); + warn(`Target of hierarchy path should be of type Node.`); return null; } const result = target.getChildByPath(this.path); if (!result) { - error(`Node "${target.name}" has no path "${this.path}"`); + warn(`Node "${target.name}" has no path "${this.path}"`); return null; } return result; @@ -60,12 +60,12 @@ export class ComponentPath implements ICustomTargetPath { public get (target: Node) { if (!(target instanceof Node)) { - error(`Target of component path shall be Node.`); + warn(`Target of component path should be of type Node.`); return null; } const result = target.getComponent(this.component); if (!result) { - error(`Node "${target.name}" has no component "${this.component}"`); + warn(`Node "${target.name}" has no component "${this.component}"`); return null; } return result; @@ -83,7 +83,7 @@ export function evaluatePath (root: any, ...paths: TargetPath[]) { const path = paths[iPath]; if (isPropertyPath(path)) { if (!(path in result)) { - error(`Target object has no property "${path}"`); + warn(`Target object has no property "${path}"`); return null; } else { result = result[path]; @@ -96,4 +96,4 @@ export function evaluatePath (root: any, ...paths: TargetPath[]) { } } return result; -} \ No newline at end of file +} diff --git a/cocos/core/renderer/models/skinning-model.ts b/cocos/core/renderer/models/skinning-model.ts index a88ab1a860..daa1e57d5a 100644 --- a/cocos/core/renderer/models/skinning-model.ts +++ b/cocos/core/renderer/models/skinning-model.ts @@ -63,6 +63,7 @@ export function getWorldMatrix (transform: IJointTransform | null, stamp: number while (transform) { if (transform.stamp === stamp || transform.stamp + 1 === stamp && !transform.node.hasChangedFlags) { res = transform.world; + transform.stamp = stamp; break; } transform.stamp = stamp; From 8738be2de3dc74bd39de1e0e3a3f0721a637e0c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Mon, 11 May 2020 16:00:16 +0800 Subject: [PATCH 10/74] Optimize an edge case in cross fade (#6581) * Optimize an edge case * Let's be careful --- cocos/core/animation/cross-fade.ts | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/cocos/core/animation/cross-fade.ts b/cocos/core/animation/cross-fade.ts index 59ddb133da..4c7fd27ae0 100644 --- a/cocos/core/animation/cross-fade.ts +++ b/cocos/core/animation/cross-fade.ts @@ -43,10 +43,6 @@ export class CrossFade extends Playable { let absoluteWeight = 1.0; let deadFadingBegin = this._fadings.length; for (let iFading = 0; iFading < this._fadings.length; ++iFading) { - if (absoluteWeight === 0) { - deadFadingBegin = iFading; - break; - } const fading = this._fadings[iFading]; fading.easeTime += deltaTime; const relativeWeight = clamp01(fading.easeTime / fading.easeDuration); @@ -55,6 +51,11 @@ export class CrossFade extends Playable { if (fading.target.state) { fading.target.state.weight += weight; } + if (fading.easeTime >= fading.easeDuration) { + deadFadingBegin = iFading + 1; + fading.easeTime = fading.easeDuration; + break; + } } // Kill fadings having no lifetime. From 2776cad23067cb7e13337a93762d176fe400f307 Mon Sep 17 00:00:00 2001 From: cary <39078800+caryliu1999@users.noreply.github.com> Date: Mon, 11 May 2020 16:02:35 +0800 Subject: [PATCH 11/74] Add normalization processing in shell mode of particle. (#6599) --- cocos/particle/emitter/shape-module.ts | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/cocos/particle/emitter/shape-module.ts b/cocos/particle/emitter/shape-module.ts index 5e28466f83..81738d2318 100644 --- a/cocos/particle/emitter/shape-module.ts +++ b/cocos/particle/emitter/shape-module.ts @@ -362,13 +362,12 @@ function sphereEmit (emitFrom, radius, radiusThickness, pos, dir) { switch (emitFrom) { case EmitLocation.Volume: randomPointBetweenSphere(pos, radius * (1 - radiusThickness), radius); - Vec3.copy(dir, pos); - Vec3.normalize(dir, dir); + Vec3.normalize(dir, pos); break; case EmitLocation.Shell: randomUnitVector(pos); Vec3.multiplyScalar(pos, pos, radius); - Vec3.copy(dir, pos); + Vec3.normalize(dir, pos); break; default: console.warn(emitFrom + ' is not supported for sphere emitter.'); @@ -382,8 +381,7 @@ function hemisphereEmit (emitFrom, radius, radiusThickness, pos, dir) { if (pos.z > 0) { pos.z *= -1; } - Vec3.copy(dir, pos); - Vec3.normalize(dir, dir); + Vec3.normalize(dir, pos); break; case EmitLocation.Shell: randomUnitVector(pos); @@ -391,7 +389,7 @@ function hemisphereEmit (emitFrom, radius, radiusThickness, pos, dir) { if (pos.z > 0) { pos.z *= -1; } - Vec3.copy(dir, pos); + Vec3.normalize(dir, pos); break; default: console.warn(emitFrom + ' is not supported for hemisphere emitter.'); From 86cb960edc9206e34a919674918ef272dbcd63a1 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Mon, 11 May 2020 17:09:14 +0800 Subject: [PATCH 12/74] components help document url update (#6669) --- editor/i18n/en/localization.js | 10 +++++----- editor/i18n/zh/localization.js | 10 +++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index b569f52c1c..45c0ff6c85 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -8,12 +8,12 @@ module.exports = { ModelComponent: 'https://docs.cocos.com/creator3d/manual/en/engine/renderable/model-component.html', UITransformComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/ui-transform.html', SpriteComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/sprite.html', - SubContextView: '', + SubContextView: 'https://docs.cocos.com/creator3d/manual/en/editor/publish/publish-wechatgame-subcontext.html', BlockInputEventsComponent: '', CameraComponent: 'https://docs.cocos.com/creator3d/manual/en/editor/components/camera-component.html', CanvasComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/canvas.html', SkinningModelComponent: 'https://docs.cocos.com/creator3d/manual/en/engine/animation/skeletal-animation.html', - BatchedSkinningModel: '', + BatchedSkinningModel: 'https://docs.cocos.com/creator3d/manual/en/engine/animation/skeletal-animation.html', DirectionalLightComponent: 'https://docs.cocos.com/creator3d/manual/en/concepts/scene/light/dir-light.html', SphereLightComponent: 'https://docs.cocos.com/creator3d/manual/en/concepts/scene/light/sphere-light.html', SpotLightComponent: 'https://docs.cocos.com/creator3d/manual/en/concepts/scene/light/spot-light.html', @@ -49,10 +49,10 @@ module.exports = { BoxColliderComponent: 'https://docs.cocos.com/creator3d/manual/en/physics/physics-collider.html', SphereColliderComponent: 'https://docs.cocos.com/creator3d/manual/en/physics/physics-component.html', CapsuleColliderComponent: 'https://docs.cocos.com/creator3d/manual/en/physics/physics-component.html', - CylinderColliderComponent: '', - MeshColliderComponent: '', + CylinderColliderComponent: 'https://docs.cocos.com/creator3d/manual/en/physics/physics-component.html', + MeshColliderComponent: 'https://docs.cocos.com/creator3d/manual/en/physics/physics-component.html', RigidBodyComponent: 'https://docs.cocos.com/creator3d/manual/en/physics/physics-rigidbody.html', - ConstantForce: '', + ConstantForce: 'https://docs.cocos.com/creator3d/manual/en/physics/physics-component.html', } }, diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index 263ad71bd9..4348581a74 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -8,12 +8,12 @@ module.exports = { ModelComponent: 'https://docs.cocos.com/creator3d/manual/zh/engine/renderable/model-component.html', UITransformComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/ui-transform.html', SpriteComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/sprite.html', - SubContextView: '', + SubContextView: 'https://docs.cocos.com/creator3d/manual/zh/editor/publish/publish-wechatgame-subcontext.html', BlockInputEventsComponent: '', CameraComponent: 'https://docs.cocos.com/creator3d/manual/zh/editor/components/camera-component.html', CanvasComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/canvas.html', SkinningModelComponent: 'https://docs.cocos.com/creator3d/manual/zh/engine/animation/skeletal-animation.html', - BatchedSkinningModel: '', + BatchedSkinningModel: 'https://docs.cocos.com/creator3d/manual/zh/engine/animation/skeletal-animation.html', DirectionalLightComponent: 'https://docs.cocos.com/creator3d/manual/zh/concepts/scene/light/dir-light.html', SphereLightComponent: 'https://docs.cocos.com/creator3d/manual/zh/concepts/scene/light/sphere-light.html', SpotLightComponent: 'https://docs.cocos.com/creator3d/manual/zh/concepts/scene/light/spot-light.html', @@ -49,10 +49,10 @@ module.exports = { BoxColliderComponent: 'https://docs.cocos.com/creator3d/manual/zh/physics/physics-collider.html', SphereColliderComponent: 'https://docs.cocos.com/creator3d/manual/zh/physics/physics-component.html', CapsuleColliderComponent: 'https://docs.cocos.com/creator3d/manual/zh/physics/physics-component.html', - CylinderColliderComponent: '', - MeshColliderComponent: '', + CylinderColliderComponent: 'https://docs.cocos.com/creator3d/manual/zh/physics/physics-component.html', + MeshColliderComponent: 'https://docs.cocos.com/creator3d/manual/zh/physics/physics-component.html', RigidBodyComponent: 'https://docs.cocos.com/creator3d/manual/zh/physics/physics-rigidbody.html', - ConstantForce: '', + ConstantForce: 'https://docs.cocos.com/creator3d/manual/zh/physics/physics-component.html', } }, From e6b0c0a738be6fbc8305a63edc6e8cf1ec6ea8b3 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Mon, 11 May 2020 17:11:10 +0800 Subject: [PATCH 13/74] ui-transform isHit bug fix (#6670) --- cocos/core/components/ui-base/ui-transform-component.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/cocos/core/components/ui-base/ui-transform-component.ts b/cocos/core/components/ui-base/ui-transform-component.ts index 9eba2f7c31..e0f86bca74 100644 --- a/cocos/core/components/ui-base/ui-transform-component.ts +++ b/cocos/core/components/ui-base/ui-transform-component.ts @@ -42,6 +42,7 @@ const _vec2b = new Vec2(); const _mat4_temp = new Mat4(); const _matrix = new Mat4(); const _worldMatrix = new Mat4(); +const _zeroMatrix = new Mat4(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); const _rect = new Rect(); /** * @en @@ -396,6 +397,9 @@ export class UITransformComponent extends Component { this.node.getWorldMatrix(_worldMatrix); Mat4.invert(_mat4_temp, _worldMatrix); + if (Mat4.strictEquals(_mat4_temp, _zeroMatrix)) { + return false; + } Vec2.transformMat4(testPt, cameraPt, _mat4_temp); testPt.x += this._anchorPoint.x * w; testPt.y += this._anchorPoint.y * h; From 718eeff2bc46afbd2078140c0913ada8437d5a7b Mon Sep 17 00:00:00 2001 From: "jiaxin.lai" Date: Mon, 11 May 2020 17:20:54 +0800 Subject: [PATCH 14/74] fix trigger sync of node chian (#6665) * fix trigger sync of node chian * docs --- cocos/physics/framework/physics-system.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/cocos/physics/framework/physics-system.ts b/cocos/physics/framework/physics-system.ts index 5c11e27b1f..e54c0a29cd 100644 --- a/cocos/physics/framework/physics-system.ts +++ b/cocos/physics/framework/physics-system.ts @@ -223,6 +223,8 @@ export class PhysicsSystem extends System { } else { this.physicsWorld.step(this._deltaTime, this._timeSinceLastUpdate, this._maxSubStep); } + // TODO: nesting the dirty flag reset between the syncScenetoPhysics and the simulation to reduce calling syncScenetoPhysics. + this.physicsWorld.syncSceneToPhysics(); director.emit(Director.EVENT_AFTER_PHYSICS); } From 759bdbac51e1428355446411669ac236c8492fa5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Mon, 11 May 2020 17:22:30 +0800 Subject: [PATCH 15/74] Optimize non-morph plain ModelComponent (#6620) * Optimize non-morph plain ModelComponent * Do optimize also when every sub mesh morph is null --- cocos/core/3d/framework/model-component.ts | 47 ++++++++++++++++------ 1 file changed, 35 insertions(+), 12 deletions(-) diff --git a/cocos/core/3d/framework/model-component.ts b/cocos/core/3d/framework/model-component.ts index d203eae35a..d2a0190e83 100644 --- a/cocos/core/3d/framework/model-component.ts +++ b/cocos/core/3d/framework/model-component.ts @@ -40,6 +40,7 @@ import { Enum } from '../../value-types'; import { builtinResMgr } from '../builtin'; import { RenderableComponent } from './renderable-component'; import { MorphRenderingInstance } from '../../assets/morph'; +import { assertIsTrue } from '../../data/utils/asserts'; /** * @en Shadow projection mode. @@ -200,7 +201,15 @@ export class ModelComponent extends RenderableComponent { return this._model; } - @property + @property({ + visible: function (this: ModelComponent) { + return !!( + this.mesh && + this.mesh.struct.morph && + this.mesh.struct.morph.subMeshMorphs.some((subMeshMorph) => !!subMeshMorph) + ); + }, + }) get enableMorph () { return this._enableMorph; } @@ -209,8 +218,9 @@ export class ModelComponent extends RenderableComponent { this._enableMorph = value; } - protected _modelType: typeof MorphModel; - protected _model: MorphModel | null = null; + protected _modelType: typeof Model; + + protected _model: Model | null = null; private _morphInstance: MorphRenderingInstance | null = null; @@ -219,7 +229,7 @@ export class ModelComponent extends RenderableComponent { constructor () { super(); - this._modelType = MorphModel; + this._modelType = Model; } public onLoad () { @@ -294,12 +304,21 @@ export class ModelComponent extends RenderableComponent { } protected _createModel () { - this._model = (cc.director.root as Root).createModel(this._modelType); + const preferMorphOverPlain = !!this._morphInstance; + // Note we only change to use `MorphModel` if + // we are required to render morph and the `this._modelType` is exactly the basic `Model`. + // We do this since the `this._modelType` might be changed in classes derived from `ModelComponent`. + // We shall not overwrite it. + // Please notice that we do not enforce that + // derived classes should use a morph-able model type(i.e. model type derived from `MorphModel`). + // So we should take care of the edge case. + const modelType = (preferMorphOverPlain && this._modelType === Model) ? MorphModel : this._modelType; + this._model = (cc.director.root as Root).createModel(modelType); this._model.visFlags = this.visibility; this._model.initialize(this.node); this._models.length = 0; this._models.push(this._model); - if (this._morphInstance) { + if (this._morphInstance && this._model instanceof MorphModel) { this._model.setMorphRendering(this._morphInstance); } } @@ -309,10 +328,10 @@ export class ModelComponent extends RenderableComponent { return; } const scene = this._getRenderScene(); - if (this._model!.scene != null) { + if (this._model.scene != null) { this._detachFromScene(); } - scene.addModel(this._model!); + scene.addModel(this._model); } protected _detachFromScene () { @@ -375,10 +394,12 @@ export class ModelComponent extends RenderableComponent { if (!this._model) { return; } if (this._shadowCastingMode === ModelShadowCastingMode.OFF) { this._model.castShadow = false; - } else if (this._shadowCastingMode === ModelShadowCastingMode.ON) { - this._model.castShadow = true; } else { - console.warn(`ShadowCastingMode ${this._shadowCastingMode} is not supported.`); + assertIsTrue( + this._shadowCastingMode === ModelShadowCastingMode.ON, + `ShadowCastingMode ${this._shadowCastingMode} is not supported.`, + ); + this._model.castShadow = true; } } @@ -425,7 +446,9 @@ export class ModelComponent extends RenderableComponent { this._morphInstance.setWeights(iSubMesh, weights); } - this._model?.setMorphRendering(this._morphInstance); + if (this._model && this._model instanceof MorphModel) { + this._model.setMorphRendering(this._morphInstance); + } } private _syncMorphWeights (subMeshIndex: number) { From 826d53d9b0234d8dc20939ed6ef3d9b362a0b392 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Thu, 14 May 2020 15:34:18 +0800 Subject: [PATCH 16/74] compressedTexImage2D function change for compress texture (#6685) * compressedTexImage2D function change for compress texture * update --- cocos/core/gfx/webgl/webgl-commands.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/cocos/core/gfx/webgl/webgl-commands.ts b/cocos/core/gfx/webgl/webgl-commands.ts index 712f0966a8..39f69576c7 100644 --- a/cocos/core/gfx/webgl/webgl-commands.ts +++ b/cocos/core/gfx/webgl/webgl-commands.ts @@ -38,6 +38,7 @@ import { WebGLGFXDevice } from './webgl-device'; import { IWebGLGPUInputAssembler, IWebGLGPUUniform, WebGLAttrib, WebGLGPUBindingLayout, WebGLGPUBuffer, WebGLGPUFramebuffer, WebGLGPUInput, WebGLGPUPipelineState, WebGLGPUShader, WebGLGPUTexture, WebGLGPUUniformBlock, WebGLGPUUniformSampler } from './webgl-gpu-objects'; +import { WECHAT } from 'internal:constants'; function CmpF32NotEuqal (a: number, b: number): boolean { const c = a - b; @@ -2709,7 +2710,7 @@ export function WebGLCmdFuncCopyBuffersToTexture ( region.texOffset.x, region.texOffset.y, w, h, gpuTexture.glFormat, gpuTexture.glType, pixels); } else { - if (gpuTexture.glInternelFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { + if (gpuTexture.glInternelFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL && !WECHAT) { gl.compressedTexSubImage2D(gl.TEXTURE_2D, m, region.texOffset.x, region.texOffset.y, w, h, gpuTexture.glFormat, pixels); @@ -2743,7 +2744,7 @@ export function WebGLCmdFuncCopyBuffersToTexture ( region.texOffset.x, region.texOffset.y, w, h, gpuTexture.glFormat, gpuTexture.glType, pixels); } else { - if (gpuTexture.glInternelFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL) { + if (gpuTexture.glInternelFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL && !WECHAT) { gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, m, region.texOffset.x, region.texOffset.y, w, h, gpuTexture.glFormat, pixels); From a1512a099a3b84202d972e450e826236b6e91284 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Thu, 14 May 2020 17:45:19 +0800 Subject: [PATCH 17/74] widget lock value add (#6655) * widget value lock * remove change to editor * editorOnly add --- cocos/core/scene-graph/node-enum.ts | 2 + cocos/ui/components/widget-component.ts | 83 +++++++++++++------------ 2 files changed, 45 insertions(+), 40 deletions(-) diff --git a/cocos/core/scene-graph/node-enum.ts b/cocos/core/scene-graph/node-enum.ts index 2287dbc4f9..4262fd9747 100644 --- a/cocos/core/scene-graph/node-enum.ts +++ b/cocos/core/scene-graph/node-enum.ts @@ -67,3 +67,5 @@ export enum TransformBit { TRS = TransformBit.POSITION | TransformBit.ROTATION | TransformBit.SCALE, TRS_MASK = ~TransformBit.TRS, } + +cc.internal.TransformBit = TransformBit; diff --git a/cocos/ui/components/widget-component.ts b/cocos/ui/components/widget-component.ts index 2de090fa05..0a68b47e8a 100644 --- a/cocos/ui/components/widget-component.ts +++ b/cocos/ui/components/widget-component.ts @@ -28,7 +28,7 @@ * @category ui */ -import { Component} from '../../core/components'; +import { Component } from '../../core/components'; import { UITransformComponent } from '../../core/components/ui-base/ui-transform-component'; import { ccclass, help, executeInEditMode, executionOrder, menu, property, requireComponent } from '../../core/data/class-decorator'; import { Size, Vec3 } from '../../core/math'; @@ -223,7 +223,7 @@ export class WidgetComponent extends Component { } set target (value) { - if (this._target === value){ + if (this._target === value) { return; } @@ -573,7 +573,7 @@ export class WidgetComponent extends Component { return this._isAbsTop; } set isAbsoluteTop (value) { - if (this._isAbsTop === value){ + if (this._isAbsTop === value) { return; } @@ -593,7 +593,7 @@ export class WidgetComponent extends Component { return this._isAbsBottom; } set isAbsoluteBottom (value) { - if (this._isAbsBottom === value){ + if (this._isAbsBottom === value) { return; } @@ -633,7 +633,7 @@ export class WidgetComponent extends Component { return this._isAbsRight; } set isAbsoluteRight (value) { - if (this._isAbsRight === value){ + if (this._isAbsRight === value) { return; } @@ -641,31 +641,6 @@ export class WidgetComponent extends Component { this._autoChangedValue(AlignFlags.RIGHT, this._isAbsRight); } - /** - * @en - * Specifies the alignment mode of the Widget, which determines when the widget should refresh. - * - * @zh - * 指定 Widget 的对齐模式,用于决定 Widget 应该何时刷新。 - * - * @example - * ``` - * widget.alignMode = cc.Widget.AlignMode.ON_WINDOW_RESIZE; - * ``` - */ - @property({ - type: AlignMode, - tooltip:'指定 widget 的对齐方式,用于决定运行时 widget 应何时更新', - }) - get alignMode () { - return this._alignMode; - } - - set alignMode (value) { - this._alignMode = value; - this._recursiveDirty(); - } - /** * @en * If true, horizontalCenter is pixel margin, otherwise is percentage (0 - 1) margin. @@ -677,7 +652,6 @@ export class WidgetComponent extends Component { get isAbsoluteHorizontalCenter () { return this._isAbsHorizontalCenter; } - set isAbsoluteHorizontalCenter (value) { if (this._isAbsHorizontalCenter === value) { return; @@ -699,7 +673,7 @@ export class WidgetComponent extends Component { return this._isAbsVerticalCenter; } set isAbsoluteVerticalCenter (value) { - if (this._isAbsVerticalCenter === value){ + if (this._isAbsVerticalCenter === value) { return; } @@ -707,6 +681,30 @@ export class WidgetComponent extends Component { this._autoChangedValue(AlignFlags.MID, this._isAbsVerticalCenter); } + /** + * @en + * Specifies the alignment mode of the Widget, which determines when the widget should refresh. + * + * @zh + * 指定 Widget 的对齐模式,用于决定 Widget 应该何时刷新。 + * + * @example + * ``` + * widget.alignMode = cc.Widget.AlignMode.ON_WINDOW_RESIZE; + * ``` + */ + @property({ + type: AlignMode, + tooltip:'指定 widget 的对齐方式,用于决定运行时 widget 应何时更新', + }) + get alignMode () { + return this._alignMode; + } + set alignMode (value) { + this._alignMode = value; + this._recursiveDirty(); + } + /** * @zh * 对齐开关,由 AlignFlags 组成 @@ -715,7 +713,6 @@ export class WidgetComponent extends Component { get alignFlags () { return this._alignFlags; } - set alignFlags (value) { if (this._alignFlags === value) { return; @@ -766,6 +763,10 @@ export class WidgetComponent extends Component { private _originalHeight = 0; @property private _alignMode = AlignMode.ON_WINDOW_RESIZE; + @property({ + editorOnly: true, + }) + private _lockFlags = 0; /** * @en @@ -804,7 +805,7 @@ export class WidgetComponent extends Component { } - public setDirty (){ + public setDirty () { this._recursiveDirty(); } @@ -908,7 +909,7 @@ export class WidgetComponent extends Component { const targetSize = getReadonlyNodeSize(target); const deltaInPercent = new Vec3(); if (targetSize.width !== 0 && targetSize.height !== 0) { - Vec3.set(deltaInPercent, delta.x / targetSize.width , delta.y / targetSize.height, deltaInPercent.z); + Vec3.set(deltaInPercent, delta.x / targetSize.width, delta.y / targetSize.height, deltaInPercent.z); } const anchor = self.node.getAnchorPoint(); @@ -958,9 +959,9 @@ export class WidgetComponent extends Component { this.node.off(SystemEventType.PARENT_CHANGED, this._adjustTargetToParentChanged, this); } - protected _autoChangedValue (flag: AlignFlags, isAbs: boolean){ + protected _autoChangedValue (flag: AlignFlags, isAbs: boolean) { const current = (this._alignFlags & flag) > 0; - if (!current || !this.node.parent || !this.node.parent._uiProps.uiTransformComp){ + if (!current || !this.node.parent || !this.node.parent._uiProps.uiTransformComp) { return; } @@ -1002,7 +1003,7 @@ export class WidgetComponent extends Component { } } - protected _unregisterOldParentEvents ( oldParent: Node ) { + protected _unregisterOldParentEvents (oldParent: Node) { const target = this._target || oldParent; if (target) { target.off(SystemEventType.TRANSFORM_CHANGED, this._targetChangedOperation, this); @@ -1010,7 +1011,7 @@ export class WidgetComponent extends Component { } } - protected _targetChangedOperation (){ + protected _targetChangedOperation () { this._recursiveDirty(); } @@ -1069,7 +1070,7 @@ export class WidgetComponent extends Component { } private _recursiveDirty () { - if (this._dirty){ + if (this._dirty) { return; } @@ -1081,3 +1082,5 @@ export class WidgetComponent extends Component { cc.WidgetComponent = WidgetComponent; // cc.Widget = module.exports = Widget; +cc.internal.computeInverseTransForTarget = computeInverseTransForTarget; +cc.internal.getReadonlyNodeSize = getReadonlyNodeSize; From 2044c6a8daa86dd9e2536a941ab078ace2aa8ac2 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Fri, 15 May 2020 11:15:27 +0800 Subject: [PATCH 18/74] create spriteframe function add (#6687) * create spriteframe function add * name change --- cocos/core/assets/sprite-frame.ts | 33 +++++++++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/cocos/core/assets/sprite-frame.ts b/cocos/core/assets/sprite-frame.ts index 33b592102f..e915bd1f50 100644 --- a/cocos/core/assets/sprite-frame.ts +++ b/cocos/core/assets/sprite-frame.ts @@ -37,6 +37,8 @@ import { Asset } from './asset'; import { RenderTexture } from './render-texture'; import { TextureBase } from './texture-base'; import { EDITOR } from 'internal:constants'; +import { ImageAsset, ImageSource } from './image-asset'; +import { Texture2D } from './texture-2d'; const INSET_LEFT = 0; const INSET_TOP = 1; @@ -181,6 +183,37 @@ const temp_uvs: IUV[] = [{ u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, v: 0 }, { u: 0, */ @ccclass('cc.SpriteFrame') export class SpriteFrame extends Asset { + + /** + * @en + * Create a SpriteFrame object by an image asset + * @zh + * 通过 Image 资源创建一个 SpriteFrame 对象 + */ + public static createWithImage (image: ImageAsset) { + const spf = new SpriteFrame(); + const tex = new Texture2D(); + tex.image = image; + spf.texture = tex; + return spf; + } + + /** + * @en + * Create a SpriteFrame object by an native image asset + * @zh + * 通过原始 image 资源来创建一个 SpriteFrame 对象 + * @param imageSource support HTMLCanvasElement HTMLImageElement IMemoryImageSource + */ + public static createWithImageSource (imageSource: ImageSource) { + const img = new ImageAsset(imageSource); + const tex = new Texture2D(); + tex.image = img; + const spf = new SpriteFrame(); + spf.texture = tex; + return spf; + } + /** * @en * Top border of the sprite. From 65ab2b9bf462731c45efb9971b9b1f036aec1cf7 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Fri, 15 May 2020 14:04:44 +0800 Subject: [PATCH 19/74] Create spriteframe function change (#6693) * create spriteframe function change * name change --- cocos/core/assets/sprite-frame.ts | 24 +++++------------------- 1 file changed, 5 insertions(+), 19 deletions(-) diff --git a/cocos/core/assets/sprite-frame.ts b/cocos/core/assets/sprite-frame.ts index e915bd1f50..a52b126c71 100644 --- a/cocos/core/assets/sprite-frame.ts +++ b/cocos/core/assets/sprite-frame.ts @@ -186,27 +186,13 @@ export class SpriteFrame extends Asset { /** * @en - * Create a SpriteFrame object by an image asset + * Create a SpriteFrame object by an image asset or an native image asset * @zh - * 通过 Image 资源创建一个 SpriteFrame 对象 + * 通过 Image 资源或者原始 image 资源创建一个 SpriteFrame 对象 + * @param imageSourceOrImageAsset ImageAsset or ImageSource, ImageSource support HTMLCanvasElement HTMLImageElement IMemoryImageSource */ - public static createWithImage (image: ImageAsset) { - const spf = new SpriteFrame(); - const tex = new Texture2D(); - tex.image = image; - spf.texture = tex; - return spf; - } - - /** - * @en - * Create a SpriteFrame object by an native image asset - * @zh - * 通过原始 image 资源来创建一个 SpriteFrame 对象 - * @param imageSource support HTMLCanvasElement HTMLImageElement IMemoryImageSource - */ - public static createWithImageSource (imageSource: ImageSource) { - const img = new ImageAsset(imageSource); + public static createWithImage (imageSourceOrImageAsset: ImageSource | ImageAsset) { + const img = imageSourceOrImageAsset instanceof ImageAsset ? imageSourceOrImageAsset : new ImageAsset(imageSourceOrImageAsset); const tex = new Texture2D(); tex.image = img; const spf = new SpriteFrame(); From dfaf43d7324329ab7ba5d92a035e2989cf4e7b87 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Sun, 17 May 2020 12:48:31 +0800 Subject: [PATCH 20/74] planar shadow instancing support (#6692) * refresh instanced attr on material update * fix local binding check for builtin materials * planar shadow instancing support --- cocos/core/gfx/define.ts | 1 - cocos/core/gfx/webgl/webgl-window.ts | 4 +- cocos/core/pipeline/forward/forward-stage.ts | 2 +- .../renderer/models/baked-skinning-model.ts | 25 +++--- cocos/core/renderer/scene/model.ts | 8 +- cocos/core/renderer/scene/planar-shadows.ts | 86 +++++++++++-------- 6 files changed, 75 insertions(+), 51 deletions(-) diff --git a/cocos/core/gfx/define.ts b/cocos/core/gfx/define.ts index d2e4f44e96..74e5106f27 100644 --- a/cocos/core/gfx/define.ts +++ b/cocos/core/gfx/define.ts @@ -794,7 +794,6 @@ export function GFXFormatSurfaceSize ( size += GFXFormatSize(format, width, height, depth); width = Math.max(width >> 1, 1); height = Math.max(height >> 1, 1); - depth = Math.max(depth >> 1, 1); } return size; diff --git a/cocos/core/gfx/webgl/webgl-window.ts b/cocos/core/gfx/webgl/webgl-window.ts index 9a4a8c0b03..c04748bec5 100644 --- a/cocos/core/gfx/webgl/webgl-window.ts +++ b/cocos/core/gfx/webgl/webgl-window.ts @@ -46,7 +46,7 @@ export class WebGLGFXWindow extends GFXWindow { storeOp: GFXStoreOp.STORE, sampleCount: 1, beginLayout: GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL, - endLayout: GFXTextureLayout.COLOR_ATTACHMENT_OPTIMAL, + endLayout: GFXTextureLayout.PRESENT_SRC, }], depthStencilAttachment: { format : this._depthStencilFmt, @@ -56,7 +56,7 @@ export class WebGLGFXWindow extends GFXWindow { stencilStoreOp : GFXStoreOp.STORE, sampleCount : 1, beginLayout : GFXTextureLayout.DEPTH_STENCIL_ATTACHMENT_OPTIMAL, - endLayout : GFXTextureLayout.DEPTH_STENCIL_ATTACHMENT_OPTIMAL, + endLayout : GFXTextureLayout.PRESENT_SRC, }, }); diff --git a/cocos/core/pipeline/forward/forward-stage.ts b/cocos/core/pipeline/forward/forward-stage.ts index abb24c5b5e..ca9c0ebb61 100644 --- a/cocos/core/pipeline/forward/forward-stage.ts +++ b/cocos/core/pipeline/forward/forward-stage.ts @@ -181,7 +181,7 @@ export class ForwardStage extends RenderStage { this._opaqueBatchedQueue.recordCommandBuffer(cmdBuff); if (camera.visibility & Layers.BitMask.DEFAULT) { - cmdBuff.execute(planarShadow.cmdBuffs.array, planarShadow.cmdBuffCount); + planarShadow.recordCommandBuffer(cmdBuff); } cmdBuff.execute(this._renderQueues[1].cmdBuffs.array, this._renderQueues[1].cmdBuffCount); diff --git a/cocos/core/renderer/models/baked-skinning-model.ts b/cocos/core/renderer/models/baked-skinning-model.ts index 1470204b3f..8e8e4bd6d3 100644 --- a/cocos/core/renderer/models/baked-skinning-model.ts +++ b/cocos/core/renderer/models/baked-skinning-model.ts @@ -166,20 +166,12 @@ export class BakedSkinningModel extends MorphModel { if (oldTex && oldTex !== texture) { this._dataPoolManager.jointTexturePool.releaseHandle(oldTex); } this._jointsMedium.texture = texture; if (!texture) { return; } - const { buffer, jointTextureInfo: jointTextureInfo } = this._jointsMedium; + const { buffer, jointTextureInfo } = this._jointsMedium; jointTextureInfo[0] = texture.handle.texture.width; jointTextureInfo[1] = this._skeleton!.joints.length; jointTextureInfo[2] = texture.pixelOffset + 0.1; // guard against floor() underflow jointTextureInfo[3] = 1 / jointTextureInfo[0]; - const idx = this._instAnimInfoIdx; - if (idx >= 0) { // update instancing data too - const info = this._jointsMedium.animInfo; - const view = this.instancedAttributes.list[idx].view; - const pixelsPerJoint = this._dataPoolManager.jointTexturePool.pixelsPerJoint; - view[1] = pixelsPerJoint * jointTextureInfo[1]; - view[2] = jointTextureInfo[2]; - view[0] = view[1] * info.data[0] + view[2]; - } + this.updateInstancedJointTextureInfo(); if (buffer) { buffer.update(jointTextureInfo); } const tv = texture.handle.texView; const it = this._matPSORecord.values(); let res = it.next(); @@ -215,5 +207,18 @@ export class BakedSkinningModel extends MorphModel { protected updateInstancedAttributeList (pso: GFXPipelineState, pass: Pass) { super.updateInstancedAttributeList(pso, pass); this._instAnimInfoIdx = this.getInstancedAttributeIndex(INST_JOINT_ANIM_INFO); + this.updateInstancedJointTextureInfo(); + } + + private updateInstancedJointTextureInfo () { + const { jointTextureInfo, animInfo } = this._jointsMedium; + const idx = this._instAnimInfoIdx; + if (idx >= 0) { // update instancing data too + const view = this.instancedAttributes.list[idx].view; + const pixelsPerJoint = this._dataPoolManager.jointTexturePool.pixelsPerJoint; + view[1] = pixelsPerJoint * jointTextureInfo[1]; + view[2] = jointTextureInfo[2]; + view[0] = view[1] * animInfo.data[0] + view[2]; + } } } diff --git a/cocos/core/renderer/scene/model.ts b/cocos/core/renderer/scene/model.ts index 1dcfad1c58..f7dacd9ae1 100644 --- a/cocos/core/renderer/scene/model.ts +++ b/cocos/core/renderer/scene/model.ts @@ -14,6 +14,7 @@ import { Layers } from '../../scene-graph/layers'; import { IMacroPatch, Pass } from '../core/pass'; import { RenderScene } from './render-scene'; import { SubModel } from './submodel'; +import { programLib } from '../core/program-lib'; const m4_1 = new Mat4(); @@ -84,6 +85,10 @@ export class Model { return this._updateStamp; } + get isInstancingEnabled () { + return this._instMatWorldIdx >= 0; + } + public type = ModelType.DEFAULT; public scene: RenderScene | null = null; public node: Node = null!; @@ -344,7 +349,8 @@ export class Model { if (!mat) { return; } let hasForwardLight = false; for (const p of mat.passes) { - if (p.bindings.find((b) => b.name === UBOForwardLight.BLOCK.name)) { + const blocks = programLib.getTemplate(p.program).builtins.locals.blocks; + if (blocks.find((b) => b.name === UBOForwardLight.BLOCK.name)) { hasForwardLight = true; break; } diff --git a/cocos/core/renderer/scene/planar-shadows.ts b/cocos/core/renderer/scene/planar-shadows.ts index dc9b0a2b50..534ec34c04 100644 --- a/cocos/core/renderer/scene/planar-shadows.ts +++ b/cocos/core/renderer/scene/planar-shadows.ts @@ -1,29 +1,25 @@ import { Material } from '../../assets/material'; import { aabb, frustum, intersect } from '../../geometry'; -import { GFXCommandBuffer, IGFXCommandBufferInfo } from '../../gfx/command-buffer'; -import { GFXCommandBufferType } from '../../gfx/define'; import { GFXPipelineState } from '../../gfx/pipeline-state'; import { Color, Mat4, Quat, Vec3 } from '../../math'; -import { CachedArray } from '../../memop/cached-array'; import { IInternalBindingInst, UBOShadow } from '../../pipeline/define'; import { DirectionalLight } from './directional-light'; import { Model } from './model'; import { RenderScene } from './render-scene'; import { SphereLight } from './sphere-light'; +import { GFXCommandBuffer } from '../../gfx'; +import { InstancedBuffer } from '../../pipeline/instanced-buffer'; const _forward = new Vec3(0, 0, -1); const _v3 = new Vec3(); const _ab = new aabb(); const _qt = new Quat(); -const _info: IGFXCommandBufferInfo = { - allocator: null!, - type: GFXCommandBufferType.SECONDARY, -}; interface IShadowRenderData { + model: Model; psos: GFXPipelineState[]; - cmdBuffer: GFXCommandBuffer; + instancedBuffer: InstancedBuffer | null; } export class PlanarShadows { @@ -31,7 +27,6 @@ export class PlanarShadows { set enabled (enable: boolean) { this._enabled = enable; if (this._scene.mainLight) { this.updateDirLight(this._scene.mainLight); } - this._cmdBuffs.clear(); } get enabled (): boolean { @@ -67,14 +62,6 @@ export class PlanarShadows { return this._data; } - get cmdBuffs () { - return this._cmdBuffs; - } - - get cmdBuffCount () { - return this._cmdBuffs.length; - } - protected _scene: RenderScene; protected _enabled: boolean = false; protected _normal = new Vec3(0, 1, 0); @@ -85,17 +72,18 @@ export class PlanarShadows { 0.0, 0.0, 0.0, 0.3, // shadowColor ]); protected _globalBindings: IInternalBindingInst; - protected _cmdBuffs: CachedArray; - protected _cmdBuffCount = 0; protected _record = new Map(); + protected _pendingModels: IShadowRenderData[] = []; protected _material: Material; + protected _instancingMaterial: Material; constructor (scene: RenderScene) { this._scene = scene; this._globalBindings = scene.root.pipeline.globalBindings.get(UBOShadow.BLOCK.name)!; - this._cmdBuffs = new CachedArray(64); this._material = new Material(); this._material.initialize({ effectName: 'pipeline/planar-shadow' }); + this._instancingMaterial = new Material(); + this._instancingMaterial.initialize({ effectName: 'pipeline/planar-shadow', defines: { USE_INSTANCING: true } }); } public updateSphereLight (light: SphereLight) { @@ -154,7 +142,7 @@ export class PlanarShadows { } public updateCommandBuffers (frstm: frustum, stamp: number) { - this._cmdBuffs.clear(); + this._pendingModels.length = 0; if (!this._scene.mainLight) { return; } const models = this._scene.models; for (let i = 0; i < models.length; i++) { @@ -165,41 +153,67 @@ export class PlanarShadows { if (!intersect.aabb_frustum(_ab, frstm)) { continue; } } let data = this._record.get(model); + if (data && (!!data.instancedBuffer !== model.isInstancingEnabled)) { this.destroyShadowData(model); data = undefined; } if (!data) { data = this.createShadowData(model); this._record.set(model, data); } if (model.updateStamp !== stamp) { model.updateUBOs(stamp); } // for those outside the frustum - this.cmdBuffs.push(data.cmdBuffer); + this._pendingModels.push(data); + } + } + + public recordCommandBuffer (cmdBuff: GFXCommandBuffer) { + const models = this._pendingModels; + const modelLen = models.length; + const buffer = this._instancingMaterial.passes[0].instancedBuffer!; + buffer.clear(); + for (let i = 0; i < modelLen; i++) { + const { model, psos, instancedBuffer } = models[i]; + for (let j = 0; j < psos.length; j++) { + const submodel = model.getSubModel(j); + const pso = psos[j]; + if (instancedBuffer) { + instancedBuffer.merge(submodel, model.instancedAttributes, pso); + } else { + const ia = submodel.inputAssembler!; + cmdBuff.bindPipelineState(pso); + cmdBuff.bindBindingLayout(pso.pipelineLayout.layouts[0]); + cmdBuff.bindInputAssembler(ia); + cmdBuff.draw(ia); + } + } + } + if (buffer.pso) { + buffer.uploadBuffers(); + cmdBuff.bindPipelineState(buffer.pso!); + cmdBuff.bindBindingLayout(buffer.pso!.pipelineLayout.layouts[0]); + for (let b = 0; b < buffer.instances.length; ++b) { + const instance = buffer.instances[b]; + if (!instance.count) { continue; } + cmdBuff.bindInputAssembler(instance.ia); + cmdBuff.draw(instance.ia); + } } } public createShadowData (model: Model): IShadowRenderData { - const device = this._scene.root.device; - _info.allocator = device.commandAllocator; - const cmdBuffer = device.createCommandBuffer(_info); const psos: GFXPipelineState[] = []; - cmdBuffer.begin(); + const material = model.isInstancingEnabled ? this._instancingMaterial : this._material; for (let i = 0; i < model.subModelNum; i++) { - const ia = model.getSubModel(i).inputAssembler!; // @ts-ignore TS2445 - const pso = model.createPipelineState(this._material.passes[0], i); + const pso = model.createPipelineState(material.passes[0], i); model.insertImplantPSO(pso); // add back to model to sync binding layouts pso.pipelineLayout.layouts[0].update(); psos.push(pso); - cmdBuffer.bindPipelineState(pso); - cmdBuffer.bindBindingLayout(pso.pipelineLayout.layouts[0]); - cmdBuffer.bindInputAssembler(ia); - cmdBuffer.draw(ia); } - cmdBuffer.end(); - return { psos, cmdBuffer }; + return { model, psos, instancedBuffer: material.passes[0].instancedBuffer }; } public destroyShadowData (model: Model) { const data = this._record.get(model); if (!data) { return; } - data.cmdBuffer.destroy(); + const material = data.instancedBuffer ? this._instancingMaterial : this._material; for (let i = 0; i < data.psos.length; i++) { const pso = data.psos[i]; model.removeImplantPSO(pso); - this._material.passes[0].destroyPipelineState(pso); + material.passes[0].destroyPipelineState(pso); } this._record.delete(model); } From 1ff503bbf6e8df984d787232166796cfd3587056 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Sun, 17 May 2020 12:50:52 +0800 Subject: [PATCH 21/74] components help doc update (#6690) * components help doc update * webview remove --- editor/i18n/en/localization.js | 3 +-- editor/i18n/zh/localization.js | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index 45c0ff6c85..5ecd91cc61 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -9,7 +9,7 @@ module.exports = { UITransformComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/ui-transform.html', SpriteComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/sprite.html', SubContextView: 'https://docs.cocos.com/creator3d/manual/en/editor/publish/publish-wechatgame-subcontext.html', - BlockInputEventsComponent: '', + BlockInputEventsComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/block-input-enents.html', CameraComponent: 'https://docs.cocos.com/creator3d/manual/en/editor/components/camera-component.html', CanvasComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/canvas.html', SkinningModelComponent: 'https://docs.cocos.com/creator3d/manual/en/engine/animation/skeletal-animation.html', @@ -39,7 +39,6 @@ module.exports = { ToggleContainerComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/toggleContainer.html', ToggleComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/toggle.html', UIModelComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/ui-model.html', - WebviewComponent: '', WidgetComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/widget.html', UIReorderComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/ui-reorder-component.html', PageViewIndicatorComponent: 'https://docs.cocos.com/creator3d/manual/en/ui-system/components/editor/pageviewindicator.html', diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index 4348581a74..5390e61447 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -9,7 +9,7 @@ module.exports = { UITransformComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/ui-transform.html', SpriteComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/sprite.html', SubContextView: 'https://docs.cocos.com/creator3d/manual/zh/editor/publish/publish-wechatgame-subcontext.html', - BlockInputEventsComponent: '', + BlockInputEventsComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/block-input-enents.html', CameraComponent: 'https://docs.cocos.com/creator3d/manual/zh/editor/components/camera-component.html', CanvasComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/canvas.html', SkinningModelComponent: 'https://docs.cocos.com/creator3d/manual/zh/engine/animation/skeletal-animation.html', @@ -39,7 +39,6 @@ module.exports = { ToggleContainerComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/toggleContainer.html', ToggleComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/toggle.html', UIModelComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/ui-model.html', - WebviewComponent: '', WidgetComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/widget.html', UIReorderComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/ui-reorder-component.html', PageViewIndicatorComponent: 'https://docs.cocos.com/creator3d/manual/zh/ui-system/components/editor/pageviewindicator.html', From 3fb6490a64e21dcddeccdb516df23a4f34dffb56 Mon Sep 17 00:00:00 2001 From: JoneLau <32630749+JoneLau@users.noreply.github.com> Date: Sun, 17 May 2020 12:55:16 +0800 Subject: [PATCH 22/74] fixed the error in the clear operation (#6683) --- .../assembler/graphics/webgl/graphics-assembler.ts | 2 +- cocos/ui/components/graphics-component.ts | 12 ++++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts b/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts index faab508acd..f0e5d67540 100644 --- a/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts +++ b/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts @@ -173,7 +173,7 @@ export const graphicsAssembler: IAssembler = { }, end (graphics: GraphicsComponent) { - if (graphics.model) { + if (graphics.model && graphics.model.inited) { graphics.model.destroy(); } const impl = graphics.impl; diff --git a/cocos/ui/components/graphics-component.ts b/cocos/ui/components/graphics-component.ts index 909786a8fc..8dded75e73 100644 --- a/cocos/ui/components/graphics-component.ts +++ b/cocos/ui/components/graphics-component.ts @@ -504,10 +504,10 @@ export class GraphicsComponent extends UIRenderComponent { } this.impl.clear(clean); - if (this.model) { + this._detachFromScene(); + if(this.model){ this.model.destroy(); } - this.markForUpdateRenderData(); } @@ -535,6 +535,7 @@ export class GraphicsComponent extends UIRenderComponent { * 根据当前的画线样式,绘制当前或已经存在的路径。 */ public stroke () { + this._attachToScene(); (this._assembler as IAssembler).stroke!(this); } @@ -546,6 +547,7 @@ export class GraphicsComponent extends UIRenderComponent { * 根据当前的画线样式,填充当前或已经存在的路径。 */ public fill () { + this._attachToScene(); (this._assembler as IAssembler).fill!(this); } @@ -601,10 +603,11 @@ export class GraphicsComponent extends UIRenderComponent { protected _attachToScene () { const scene = director.root!.ui.renderScene; - if (!this.model) { + if (!this.model || this.model!.scene === scene) { return; } - if (this.model!.scene != null) { + + if (this.model!.scene !== null) { this._detachFromScene(); } scene.addModel(this.model!); @@ -613,6 +616,7 @@ export class GraphicsComponent extends UIRenderComponent { protected _detachFromScene () { if (this.model && this.model.scene) { this.model.scene.removeModel(this.model); + this.model.scene = null; } } } From 4a1e9c14e7245974464d7b259db0bdb367a474fb Mon Sep 17 00:00:00 2001 From: cary <39078800+caryliu1999@users.noreply.github.com> Date: Sun, 17 May 2020 13:23:28 +0800 Subject: [PATCH 23/74] Optimize the creation and memory of the runtime particle system. (#6660) --- cocos/particle/particle-system-component.ts | 218 +++++++++++++++--- cocos/particle/particle.ts | 18 +- .../renderer/particle-system-renderer-cpu.ts | 53 +++-- .../renderer/particle-system-renderer-gpu.ts | 50 ++-- 4 files changed, 246 insertions(+), 93 deletions(-) diff --git a/cocos/particle/particle-system-component.ts b/cocos/particle/particle-system-component.ts index 7d8d6099ca..545f3096ee 100644 --- a/cocos/particle/particle-system-component.ts +++ b/cocos/particle/particle-system-component.ts @@ -29,6 +29,7 @@ import ParticleSystemRenderer from './renderer/particle-system-renderer-data'; import TrailModule from './renderer/trail'; import { IParticleSystemRenderer } from './renderer/particle-system-renderer-base'; import { PARTICLE_MODULE_PROPERTY } from './particle'; +import { EDITOR } from 'internal:constants'; const _world_mat = new Mat4(); const _world_rol = new Quat(); @@ -52,7 +53,7 @@ export class ParticleSystemComponent extends RenderableComponent { } public set capacity (val) { - this._capacity = val; + this._capacity = Math.floor(val); // @ts-ignore if (this.processor && this.processor._model) { // @ts-ignore @@ -324,6 +325,8 @@ export class ParticleSystemComponent extends RenderableComponent { } // color over lifetime module + @property({type: ColorOverLifetimeModule}) + _colorOverLifetimeModule:ColorOverLifetimeModule | null = null; /** * @zh 颜色控制模块。 */ @@ -332,9 +335,24 @@ export class ParticleSystemComponent extends RenderableComponent { displayOrder: 23, tooltip:'颜色模块', }) - public colorOverLifetimeModule = new ColorOverLifetimeModule(); + public get colorOverLifetimeModule () { + if (EDITOR) { + if (!this._colorOverLifetimeModule) { + this._colorOverLifetimeModule = new ColorOverLifetimeModule(); + this._colorOverLifetimeModule.bindTarget(this.processor!); + } + } + return this._colorOverLifetimeModule; + } - // Shape module + public set colorOverLifetimeModule (val) { + if (!val) return; + this._colorOverLifetimeModule = val; + } + + // shape module + @property({type: ShapeModule}) + _shapeModule:ShapeModule | null = null; /** * @zh 粒子发射器模块。 */ @@ -343,9 +361,24 @@ export class ParticleSystemComponent extends RenderableComponent { displayOrder: 17, tooltip:'发射器模块', }) - public shapeModule = new ShapeModule(); + public get shapeModule () { + if (EDITOR) { + if (!this._shapeModule) { + this._shapeModule = new ShapeModule(); + this._shapeModule.onInit(this); + } + } + return this._shapeModule; + } + + public set shapeModule (val) { + if (!val) return; + this._shapeModule = val; + } // size over lifetime module + @property({type: SizeOvertimeModule}) + _sizeOvertimeModule:SizeOvertimeModule | null = null; /** * @zh 粒子大小模块。 */ @@ -354,8 +387,24 @@ export class ParticleSystemComponent extends RenderableComponent { displayOrder: 21, tooltip:'大小模块', }) - public sizeOvertimeModule = new SizeOvertimeModule(); + public get sizeOvertimeModule () { + if (EDITOR) { + if (!this._sizeOvertimeModule) { + this._sizeOvertimeModule = new SizeOvertimeModule(); + this._sizeOvertimeModule.bindTarget(this.processor!); + } + } + return this._sizeOvertimeModule; + } + public set sizeOvertimeModule (val) { + if (!val) return; + this._sizeOvertimeModule = val; + } + + // velocity overtime module + @property({type: VelocityOvertimeModule}) + _velocityOvertimeModule:VelocityOvertimeModule | null = null; /** * @zh 粒子速度模块。 */ @@ -364,8 +413,24 @@ export class ParticleSystemComponent extends RenderableComponent { displayOrder: 18, tooltip:'速度模块', }) - public velocityOvertimeModule = new VelocityOvertimeModule(); + public get velocityOvertimeModule () { + if (EDITOR) { + if (!this._velocityOvertimeModule) { + this._velocityOvertimeModule = new VelocityOvertimeModule(); + this._velocityOvertimeModule.bindTarget(this.processor!); + } + } + return this._velocityOvertimeModule; + } + public set velocityOvertimeModule (val) { + if (!val) return; + this._velocityOvertimeModule = val; + } + + // force overTime module + @property({type: ForceOvertimeModule}) + _forceOvertimeModule:ForceOvertimeModule | null = null; /** * @zh 粒子加速度模块。 */ @@ -374,8 +439,24 @@ export class ParticleSystemComponent extends RenderableComponent { displayOrder: 19, tooltip:'加速度模块', }) - public forceOvertimeModule = new ForceOvertimeModule(); + public get forceOvertimeModule () { + if (EDITOR) { + if (!this._forceOvertimeModule) { + this._forceOvertimeModule = new ForceOvertimeModule(); + this._forceOvertimeModule.bindTarget(this.processor!); + } + } + return this._forceOvertimeModule; + } + public set forceOvertimeModule (val) { + if (!val) return; + this._forceOvertimeModule = val; + } + + // limit velocity overtime module + @property({type: LimitVelocityOvertimeModule}) + _limitVelocityOvertimeModule:LimitVelocityOvertimeModule | null = null; /** * @zh 粒子限制速度模块(只支持 CPU 粒子)。 */ @@ -384,8 +465,24 @@ export class ParticleSystemComponent extends RenderableComponent { displayOrder: 20, tooltip:'限速模块', }) - public limitVelocityOvertimeModule = new LimitVelocityOvertimeModule(); + public get limitVelocityOvertimeModule () { + if (EDITOR) { + if (!this._limitVelocityOvertimeModule) { + this._limitVelocityOvertimeModule = new LimitVelocityOvertimeModule(); + this._limitVelocityOvertimeModule.bindTarget(this.processor!); + } + } + return this._limitVelocityOvertimeModule; + } + public set limitVelocityOvertimeModule (val) { + if (!val) return; + this._limitVelocityOvertimeModule = val; + } + + // rotation overtime module + @property({type: RotationOvertimeModule}) + _rotationOvertimeModule:RotationOvertimeModule | null = null; /** * @zh 粒子旋转模块。 */ @@ -394,8 +491,24 @@ export class ParticleSystemComponent extends RenderableComponent { displayOrder: 22, tooltip:'旋转模块', }) - public rotationOvertimeModule = new RotationOvertimeModule(); + public get rotationOvertimeModule () { + if (EDITOR) { + if (!this._rotationOvertimeModule) { + this._rotationOvertimeModule = new RotationOvertimeModule(); + this._rotationOvertimeModule.bindTarget(this.processor!); + } + } + return this._rotationOvertimeModule; + } + public set rotationOvertimeModule (val) { + if (!val) return; + this._rotationOvertimeModule = val; + } + + // texture animation module + @property({type: TextureAnimationModule}) + _textureAnimationModule:TextureAnimationModule | null = null; /** * @zh 贴图动画模块。 */ @@ -404,8 +517,24 @@ export class ParticleSystemComponent extends RenderableComponent { displayOrder: 24, tooltip:'贴图动画模块', }) - public textureAnimationModule = new TextureAnimationModule(); + public get textureAnimationModule () { + if (EDITOR) { + if (!this._textureAnimationModule) { + this._textureAnimationModule = new TextureAnimationModule(); + this._textureAnimationModule.bindTarget(this.processor!); + } + } + return this._textureAnimationModule; + } + public set textureAnimationModule (val) { + if (!val) return; + this._textureAnimationModule = val; + } + + // trail module + @property({type: TrailModule}) + _trailModule:TrailModule | null = null; /** * @zh 粒子轨迹模块。 */ @@ -414,7 +543,21 @@ export class ParticleSystemComponent extends RenderableComponent { displayOrder: 25, tooltip:'拖尾模块', }) - public trailModule = new TrailModule(); + public get trailModule () { + if (EDITOR) { + if (!this._trailModule) { + this._trailModule = new TrailModule(); + this._trailModule.onInit(this); + this._trailModule.onEnable(); + } + } + return this._trailModule; + } + + public set trailModule (val) { + if (!val) return; + this._trailModule = val; + } // particle system renderer @property({ @@ -490,8 +633,8 @@ export class ParticleSystemComponent extends RenderableComponent { public onLoad () { // HACK, TODO this.renderer.onInit(this); - this.shapeModule.onInit(this); - this.trailModule.onInit(this); + this._shapeModule && this._shapeModule.onInit(this); + this._trailModule && this._trailModule.onInit(this); this.bindModule(); this._resetPosition(); @@ -509,34 +652,34 @@ export class ParticleSystemComponent extends RenderableComponent { public _collectModels (): Model[] { this._models.length = 0; this._models.push((this.processor as any)._model); - if (this.trailModule.enable && (this.trailModule as any)._trailModel) { - this._models.push((this.trailModule as any)._trailModel); + if (this._trailModule && this._trailModule.enable && (this._trailModule as any)._trailModel) { + this._models.push((this._trailModule as any)._trailModel); } return this._models; } protected _attachToScene () { this.processor!.attachToScene(); - if (this.trailModule.enable) { - this.trailModule._attachToScene(); + if (this._trailModule && this._trailModule.enable) { + this._trailModule._attachToScene(); } } protected _detachFromScene () { this.processor!.detachFromScene(); - if (this.trailModule.enable) { - this.trailModule._detachFromScene(); + if (this._trailModule && this._trailModule.enable) { + this._trailModule._detachFromScene(); } } public bindModule () { - this.colorOverLifetimeModule.bindTarget(this.processor!); - this.sizeOvertimeModule.bindTarget(this.processor!); - this.rotationOvertimeModule.bindTarget(this.processor!); - this.forceOvertimeModule.bindTarget(this.processor!); - this.limitVelocityOvertimeModule.bindTarget(this.processor!); - this.velocityOvertimeModule.bindTarget(this.processor!); - this.textureAnimationModule.bindTarget(this.processor!); + this._colorOverLifetimeModule && this._colorOverLifetimeModule.bindTarget(this.processor!); + this._sizeOvertimeModule && this._sizeOvertimeModule.bindTarget(this.processor!); + this._rotationOvertimeModule && this._rotationOvertimeModule.bindTarget(this.processor!); + this._forceOvertimeModule && this._forceOvertimeModule.bindTarget(this.processor!); + this._limitVelocityOvertimeModule && this._limitVelocityOvertimeModule.bindTarget(this.processor!); + this._velocityOvertimeModule && this._velocityOvertimeModule.bindTarget(this.processor!); + this._textureAnimationModule && this._textureAnimationModule.bindTarget(this.processor!); } // TODO: Fast forward current particle system by simulating particles over given period of time, then pause it. @@ -609,7 +752,7 @@ export class ParticleSystemComponent extends RenderableComponent { public clear () { if (this.enabledInHierarchy) { this.processor!.clear(); - this.trailModule.clear(); + this._trailModule && this._trailModule.clear(); } } @@ -634,7 +777,7 @@ export class ParticleSystemComponent extends RenderableComponent { protected onDestroy () { // this._system.remove(this); this.processor!.onDestroy(); - this.trailModule.destroy(); + this._trailModule && this._trailModule.destroy(); } protected onEnable () { @@ -642,11 +785,11 @@ export class ParticleSystemComponent extends RenderableComponent { this.play(); } this.processor!.onEnable(); - this.trailModule.onEnable(); + this._trailModule && this._trailModule.onEnable(); } protected onDisable () { this.processor!.onDisable(); - this.trailModule.onDisable(); + this._trailModule && this._trailModule.onDisable(); } protected update (dt) { const scaledDeltaTime = dt * this.simulationSpeed; @@ -665,8 +808,8 @@ export class ParticleSystemComponent extends RenderableComponent { this.processor!.updateRenderData(); // update trail - if (this.trailModule.enable) { - this.trailModule.updateRenderData(); + if (this._trailModule && this._trailModule.enable) { + this._trailModule.updateRenderData(); } } } @@ -694,16 +837,15 @@ export class ParticleSystemComponent extends RenderableComponent { } const rand = pseudoRandom(randomRangeInt(0, INT_MAX)); - if (this.shapeModule.enable) { - this.shapeModule.emit(particle); - } - else { + if (this._shapeModule && this._shapeModule.enable) { + this._shapeModule.emit(particle); + } else { Vec3.set(particle.position, 0, 0, 0); Vec3.copy(particle.velocity, particleEmitZAxis); } - if (this.textureAnimationModule.enable) { - this.textureAnimationModule.init(particle); + if (this._textureAnimationModule && this._textureAnimationModule.enable) { + this._textureAnimationModule.init(particle); } Vec3.multiplyScalar(particle.velocity, particle.velocity, this.startSpeed.evaluate(delta, rand)!); diff --git a/cocos/particle/particle.ts b/cocos/particle/particle.ts index b416150f0c..6ed3b8528d 100644 --- a/cocos/particle/particle.ts +++ b/cocos/particle/particle.ts @@ -71,15 +71,15 @@ export const PARTICLE_MODULE_ORDER = [ ]; export const PARTICLE_MODULE_PROPERTY = [ - 'colorOverLifetimeModule', - 'shapeModule', - 'sizeOvertimeModule', - 'velocityOvertimeModule', - 'forceOvertimeModule', - 'limitVelocityOvertimeModule', - 'rotationOvertimeModule', - 'textureAnimationModule', - 'trailModule' + '_colorOverLifetimeModule', + '_shapeModule', + '_sizeOvertimeModule', + '_velocityOvertimeModule', + '_forceOvertimeModule', + '_limitVelocityOvertimeModule', + '_rotationOvertimeModule', + '_textureAnimationModule', + '_trailModule' ]; export interface IParticleModule { diff --git a/cocos/particle/renderer/particle-system-renderer-cpu.ts b/cocos/particle/renderer/particle-system-renderer-cpu.ts index a7ea727848..778394b5a5 100644 --- a/cocos/particle/renderer/particle-system-renderer-cpu.ts +++ b/cocos/particle/renderer/particle-system-renderer-cpu.ts @@ -14,13 +14,13 @@ const _tempAttribUV = new Vec3(); const _tempWorldTrans = new Mat4(); const _anim_module = [ - 'colorOverLifetimeModule', - 'sizeOvertimeModule', - 'velocityOvertimeModule', - 'forceOvertimeModule', - 'limitVelocityOvertimeModule', - 'rotationOvertimeModule', - 'textureAnimationModule' + '_colorOverLifetimeModule', + '_sizeOvertimeModule', + '_velocityOvertimeModule', + '_forceOvertimeModule', + '_limitVelocityOvertimeModule', + '_rotationOvertimeModule', + '_textureAnimationModule' ]; const _uvs = [ @@ -126,7 +126,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas public clear () { this._particles!.reset(); - this._particleSystem!.trailModule.clear(); + this._particleSystem!._trailModule && this._particleSystem!._trailModule.clear(); this.updateRenderData(); } @@ -154,7 +154,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas private _initModuleList () { _anim_module.forEach(val => { const pm = this._particleSystem[val]; - if (pm.enable) { + if (pm && pm.enable) { if (pm.needUpdate) { this._updateList[pm.name] = pm; } @@ -220,8 +220,10 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas value.update(ps._simulationSpace, _tempWorldTrans); }); - if (ps.trailModule.enable) { - ps.trailModule.update(); + const trailModule = ps._trailModule; + const trailEnable = trailModule && trailModule.enable; + if (trailEnable) { + trailModule.update(); } for (let i = 0; i < this._particles!.length; ++i) { @@ -230,8 +232,8 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas Vec3.set(p.animatedVelocity, 0, 0, 0); if (p.remainingLifetime < 0.0) { - if (ps.trailModule.enable) { - ps.trailModule.removeParticle(p); + if (trailEnable) { + trailModule.removeParticle(p); } this._particles!.removeAt(i); --i; @@ -248,8 +250,8 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas }); Vec3.scaleAndAdd(p.position, p.position, p.ultimateVelocity, dt); // apply velocity. - if (ps.trailModule.enable) { - ps.trailModule.animate(p, dt); + if (trailEnable) { + trailModule.animate(p, dt); } } return this._particles!.length; @@ -262,7 +264,8 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas for (let i = 0; i < this._particles!.length; ++i) { const p = this._particles!.data[i]; let fi = 0; - if (this._particleSystem!.textureAnimationModule.enable) { + const textureModule = this._particleSystem!._textureAnimationModule; + if (textureModule && textureModule.enable) { fi = p.frameIndex; } idx = i * 4; @@ -289,8 +292,9 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas if (this._model && index === 0) { this._model.setSubModelMaterial(0, material); } - if (this._particleSystem!.trailModule._trailModel && index === 1) { - this._particleSystem!.trailModule._trailModel.setSubModelMaterial(0, material); + const trailModule = this._particleSystem!._trailModule; + if (trailModule && trailModule._trailModel && index === 1) { + trailModule._trailModel.setSubModelMaterial(0, material); } } @@ -413,9 +417,9 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } else { console.warn(`particle system renderMode ${renderMode} not support.`); } - - if (ps.textureAnimationModule.enable) { - Vec2.set(vlenScale, ps.textureAnimationModule.numTilesX, ps.textureAnimationModule.numTilesY); + const textureModule = ps._textureAnimationModule; + if (textureModule && textureModule.enable) { + Vec2.set(vlenScale, textureModule.numTilesX, textureModule.numTilesY); pass.setUniform(this._uLenHandle, vlenScale); } else { pass.setUniform(this._uLenHandle, vlenScale); @@ -431,8 +435,9 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas return; } const ps = this._particleSystem; - if (ps.trailModule.enable) { - if (ps.simulationSpace === Space.World || ps.trailModule.space === Space.World) { + const trailModule = ps._trailModule; + if (trailModule && trailModule.enable) { + if (ps.simulationSpace === Space.World || trailModule.space === Space.World) { this._trailDefines[CC_USE_WORLD_SPACE] = true; } else { this._trailDefines[CC_USE_WORLD_SPACE] = false; @@ -446,7 +451,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } mat = mat || this._defaultTrailMat; mat!.recompileShaders(this._trailDefines); - ps.trailModule._updateMaterial(); + trailModule._updateMaterial(); } } } diff --git a/cocos/particle/renderer/particle-system-renderer-gpu.ts b/cocos/particle/renderer/particle-system-renderer-gpu.ts index 8aa57aee48..401f659e33 100644 --- a/cocos/particle/renderer/particle-system-renderer-gpu.ts +++ b/cocos/particle/renderer/particle-system-renderer-gpu.ts @@ -218,10 +218,12 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas _tempVec4.y = _sample_interval; pass.setUniform(pass.getHandle('u_sampleInfo')!, _tempVec4); + let enable = false; // force - const forceModule = this._particleSystem.forceOvertimeModule; - this._defines[FORCE_OVER_TIME_MODULE_ENABLE] = forceModule.enable; - if (forceModule.enable) { + const forceModule = this._particleSystem._forceOvertimeModule; + enable = forceModule && forceModule.enable; + this._defines[FORCE_OVER_TIME_MODULE_ENABLE] = enable; + if (enable) { this._forceTexture && this._forceTexture.destroy(); this._forceTexture = packCurveRangeXYZ(_sample_num, forceModule.x, forceModule.y, forceModule.z); const handle = pass.getHandle('force_over_time_tex0'); @@ -235,9 +237,10 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } // velocity - const velocityModule = this._particleSystem.velocityOvertimeModule; - this._defines[VELOCITY_OVER_TIME_MODULE_ENABLE] = velocityModule.enable; - if (velocityModule.enable) { + const velocityModule = this._particleSystem._velocityOvertimeModule; + enable = velocityModule && velocityModule.enable; + this._defines[VELOCITY_OVER_TIME_MODULE_ENABLE] = enable; + if (enable) { this._velocityTexture && this._velocityTexture.destroy(); this._velocityTexture = packCurveRangeXYZW(_sample_num, velocityModule.x, velocityModule.y, velocityModule.z, velocityModule.speedModifier); const handle = pass.getHandle('velocity_over_time_tex0'); @@ -251,9 +254,10 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } // color module - const colorModule = this._particleSystem.colorOverLifetimeModule; - this._defines[COLOR_OVER_TIME_MODULE_ENABLE] = colorModule.enable; - if (colorModule.enable) { + const colorModule = this._particleSystem._colorOverLifetimeModule; + enable = colorModule && colorModule.enable; + this._defines[COLOR_OVER_TIME_MODULE_ENABLE] = enable; + if (enable) { this._colorTexture && this._colorTexture.destroy(); this._colorTexture = packGradientRange(_sample_num, colorModule.color); const handle = pass.getHandle('color_over_time_tex0'); @@ -265,9 +269,10 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } // rotation module - const roationModule = this._particleSystem.rotationOvertimeModule; - this._defines[ROTATION_OVER_TIME_MODULE_ENABLE] = roationModule.enable; - if (roationModule.enable) { + const roationModule = this._particleSystem._rotationOvertimeModule; + enable = roationModule && roationModule.enable; + this._defines[ROTATION_OVER_TIME_MODULE_ENABLE] = enable; + if (enable) { this._rotationTexture && this._rotationTexture.destroy(); if (roationModule.separateAxes) { this._rotationTexture = packCurveRangeXYZ(_sample_num, roationModule.x, roationModule.y, roationModule.z); @@ -283,9 +288,10 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } // size module - const sizeModule = this._particleSystem.sizeOvertimeModule; - this._defines[SIZE_OVER_TIME_MODULE_ENABLE] = sizeModule.enable; - if (sizeModule.enable) { + const sizeModule = this._particleSystem._sizeOvertimeModule; + enable = sizeModule && sizeModule.enable; + this._defines[SIZE_OVER_TIME_MODULE_ENABLE] = enable; + if (enable) { this._sizeTexture && this._sizeTexture.destroy(); if (sizeModule.separateAxes) { this._sizeTexture = packCurveRangeXYZ(_sample_num, sizeModule.x, sizeModule.y, sizeModule.z, true); @@ -301,12 +307,12 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } // texture module - const textureModule = this._particleSystem.textureAnimationModule; - this._defines[TEXTURE_ANIMATION_MODULE_ENABLE] = textureModule.enable; - if (textureModule.enable) { + const textureModule = this._particleSystem._textureAnimationModule; + enable = textureModule && textureModule.enable; + this._defines[TEXTURE_ANIMATION_MODULE_ENABLE] = enable; + if (enable) { this._animTexture && this._animTexture.destroy(); this._animTexture = packCurveRangeXY(_sample_num, textureModule.startFrame, textureModule.frameOverTime); - const handle = pass.getHandle('texture_animation_tex0'); const binding = Pass.getBindingFromHandle(handle!); pass.bindSampler(binding, this._animTexture.getGFXSampler()!); @@ -394,9 +400,9 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } else { console.warn(`particle system renderMode ${renderMode} not support.`); } - - if (this._particleSystem.textureAnimationModule.enable) { - Vec2.set(this._frameTile_velLenScale, this._particleSystem.textureAnimationModule.numTilesX, this._particleSystem.textureAnimationModule.numTilesY); + const textureModule = this._particleSystem._textureAnimationModule; + if (textureModule && textureModule.enable) { + Vec2.set(this._frameTile_velLenScale, textureModule.numTilesX, textureModule.numTilesY); } this.initShaderUniform(mat!); From 3e1752d485b296fc402665ef6a51565ae1eec4d0 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 18 May 2020 10:30:53 +0800 Subject: [PATCH 24/74] no need to maintain both buffers when instancing (#6703) --- cocos/core/renderer/models/baked-skinning-model.ts | 3 +-- cocos/core/renderer/scene/model.ts | 9 +++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/cocos/core/renderer/models/baked-skinning-model.ts b/cocos/core/renderer/models/baked-skinning-model.ts index 8e8e4bd6d3..d06f664855 100644 --- a/cocos/core/renderer/models/baked-skinning-model.ts +++ b/cocos/core/renderer/models/baked-skinning-model.ts @@ -131,8 +131,7 @@ export class BakedSkinningModel extends MorphModel { if (idx >= 0) { const view = this.instancedAttributes.list[idx].view; view[0] = view[1] * info.data[0] + view[2]; - } - if (info.dirty) { + } else if (info.dirty) { info.buffer.update(info.data); info.dirty = false; } diff --git a/cocos/core/renderer/scene/model.ts b/cocos/core/renderer/scene/model.ts index f7dacd9ae1..ff60b3e2be 100644 --- a/cocos/core/renderer/scene/model.ts +++ b/cocos/core/renderer/scene/model.ts @@ -185,11 +185,12 @@ export class Model { if (idx >= 0) { const attrs = this.instancedAttributes!.list; uploadMat4AsVec4x3(worldMatrix, attrs[idx].view, attrs[idx + 1].view, attrs[idx + 2].view); + } else { + Mat4.toArray(this._localData, worldMatrix, UBOLocal.MAT_WORLD_OFFSET); + Mat4.inverseTranspose(m4_1, worldMatrix); + Mat4.toArray(this._localData, m4_1, UBOLocal.MAT_WORLD_IT_OFFSET); + this._localBuffer!.update(this._localData); } - Mat4.toArray(this._localData, worldMatrix, UBOLocal.MAT_WORLD_OFFSET); - Mat4.inverseTranspose(m4_1, worldMatrix); - Mat4.toArray(this._localData, m4_1, UBOLocal.MAT_WORLD_IT_OFFSET); - this._localBuffer!.update(this._localData); } /** From 53e758356a60786a90c11da30a38a477796caae6 Mon Sep 17 00:00:00 2001 From: JoneLau <32630749+JoneLau@users.noreply.github.com> Date: Mon, 18 May 2020 17:55:33 +0800 Subject: [PATCH 25/74] property name synchronization (#6681) --- cocos/core/components/ui-base/canvas-component.ts | 6 +++--- cocos/ui/components/graphics-component.ts | 1 + cocos/ui/components/label-component.ts | 2 +- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/cocos/core/components/ui-base/canvas-component.ts b/cocos/core/components/ui-base/canvas-component.ts index 037db36f26..d3e7aceb3a 100644 --- a/cocos/core/components/ui-base/canvas-component.ts +++ b/cocos/core/components/ui-base/canvas-component.ts @@ -49,8 +49,8 @@ const _worldPos = new Vec3(); const CanvasClearFlag = Enum({ SOLID_COLOR: GFXClearFlag.ALL, - DEPTH_STENCIL: GFXClearFlag.DEPTH_STENCIL, - NONE: GFXClearFlag.NONE, + DEPTH_ONLY: GFXClearFlag.DEPTH_STENCIL, + DONT_CLEAR: GFXClearFlag.NONE, }); const RenderMode = Enum({ @@ -231,7 +231,7 @@ export class CanvasComponent extends Component { @property({ type: CanvasClearFlag, }) - protected _clearFlag = CanvasClearFlag.NONE; + protected _clearFlag = CanvasClearFlag.DONT_CLEAR; @property protected _color = new Color(0, 0, 0, 0); @property({ diff --git a/cocos/ui/components/graphics-component.ts b/cocos/ui/components/graphics-component.ts index 8dded75e73..6b5a7c7592 100644 --- a/cocos/ui/components/graphics-component.ts +++ b/cocos/ui/components/graphics-component.ts @@ -66,6 +66,7 @@ export class GraphicsComponent extends UIRenderComponent { * @zh * 当前线条宽度。 */ + @property get lineWidth () { return this._lineWidth; } diff --git a/cocos/ui/components/label-component.ts b/cocos/ui/components/label-component.ts index a1f449c91d..cf8e39fade 100644 --- a/cocos/ui/components/label-component.ts +++ b/cocos/ui/components/label-component.ts @@ -152,7 +152,7 @@ enum CacheMode { */ BITMAP = 1, /** - * @en In CHAR mode, split text into characters and cache characters into a dynamic atlas which the size of 2048*2048. + * @en In CHAR mode, split text into characters and cache characters into a dynamic atlas which the size of 1024 * 1024. * * @zh CHAR 模式,将文本拆分为字符,并将字符缓存到一张单独的大小为 1024 * 1024 的图集中进行重复使用,不再使用动态图集。 * (注:当图集满时将不再进行缓存,暂时不支持 SHRINK 自适应文本尺寸(后续完善))。 From dc16ecfbd80c72a9d41909343807b6ab8e9a21f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Mon, 18 May 2020 19:11:14 +0800 Subject: [PATCH 26/74] Lint: @typescript-eslint/array-type (#6695) --- .eslintrc.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.eslintrc.json b/.eslintrc.json index 2a52396db2..a741540142 100644 --- a/.eslintrc.json +++ b/.eslintrc.json @@ -41,7 +41,7 @@ "@typescript-eslint/adjacent-overload-signatures": "off", "@typescript-eslint/array-type": ["warn", { - "default": "array-simple" + "default": "array" }], "@typescript-eslint/await-thenable": "off", "@typescript-eslint/ban-ts-ignore": "warn", From cc722a6ae053559764654a83fa854e6cb7cfc1ca Mon Sep 17 00:00:00 2001 From: JoneLau <32630749+JoneLau@users.noreply.github.com> Date: Wed, 20 May 2020 10:52:14 +0800 Subject: [PATCH 27/74] fix warning about super.xxx = xxx (#6701) (#6718) cherry pick branch 3d, link #6701 --- .../batched-skinning-model-component.ts | 6 +- tsconfig.json | 62 +++++++++---------- 2 files changed, 33 insertions(+), 35 deletions(-) diff --git a/cocos/core/3d/framework/batched-skinning-model-component.ts b/cocos/core/3d/framework/batched-skinning-model-component.ts index 2fc7100b11..a3d2b0b48b 100644 --- a/cocos/core/3d/framework/batched-skinning-model-component.ts +++ b/cocos/core/3d/framework/batched-skinning-model-component.ts @@ -172,19 +172,17 @@ export class BatchedSkinningModelComponent extends SkinningModelComponent { @property({ override: true, visible: false }) get mesh () { - return this._mesh; + return super.mesh; } set mesh (val) { - // @ts-ignore super.mesh = val; } @property({ override: true, visible: false }) get skeleton () { - return this._skeleton; + return super.skeleton; } set skeleton (val) { - // @ts-ignore super.skeleton = val; } diff --git a/tsconfig.json b/tsconfig.json index 38951b02e8..853810ef25 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,31 +1,31 @@ -{ - "compilerOptions": { - "target": "es5", - "lib": ["es2015", "es2017", "dom"], - "module": "commonjs", - "sourceMap": true, - "outDir": "./bin/.ts", - "rootDir": "./", - "strict": true, - "noImplicitAny": false, - "downlevelIteration": true, - "esModuleInterop": true, - "experimentalDecorators": true, - "isolatedModules": true, - "types": [ - "./@types/globals", - "./@types/consts", - "./@types/editor-extends", - "./@types/wx", - "./@types/webGL.extras", - "./@types/webGL2.extras", - "./node_modules/@cocos/cannon/CANNON", - "./node_modules/@cocos/ammo/Ammo", - "./node_modules/@types/jest/index" - ] - }, - "include": [ - "exports/**/*.ts", - "index.ts" - ] - } +{ + "compilerOptions": { + "target": "es6", + "lib": ["es2015", "es2017", "dom"], + "module": "commonjs", + "sourceMap": true, + "outDir": "./bin/.ts", + "rootDir": "./", + "strict": true, + "noImplicitAny": false, + "downlevelIteration": true, + "esModuleInterop": true, + "experimentalDecorators": true, + "isolatedModules": true, + "types": [ + "./@types/globals", + "./@types/consts", + "./@types/editor-extends", + "./@types/wx", + "./@types/webGL.extras", + "./@types/webGL2.extras", + "./node_modules/@cocos/cannon/CANNON", + "./node_modules/@cocos/ammo/Ammo", + "./node_modules/@types/jest/index" + ] + }, + "include": [ + "exports/**/*.ts", + "index.ts" + ] + } From e91bbfef448c024cb1af217cf9897451e52b7528 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Thu, 21 May 2020 16:05:52 +0800 Subject: [PATCH 28/74] gfx define bug fix for ETC2 (#6729) --- cocos/core/gfx/define.ts | 1 + cocos/core/gfx/webgl/webgl-commands.ts | 10 ++++++++++ cocos/core/gfx/webgl2/webgl2-commands.ts | 10 ++++++++++ cocos/core/gfx/webgl2/webgl2-device.ts | 1 - 4 files changed, 21 insertions(+), 1 deletion(-) diff --git a/cocos/core/gfx/define.ts b/cocos/core/gfx/define.ts index 74e5106f27..73a7538aed 100644 --- a/cocos/core/gfx/define.ts +++ b/cocos/core/gfx/define.ts @@ -755,6 +755,7 @@ export function GFXFormatSize (format: GFXFormat, width: number, height: number, case GFXFormat.EAC_R11: case GFXFormat.EAC_R11SN: return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; + case GFXFormat.ETC2_RGBA8: case GFXFormat.EAC_RG11: case GFXFormat.EAC_RG11SN: return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; diff --git a/cocos/core/gfx/webgl/webgl-commands.ts b/cocos/core/gfx/webgl/webgl-commands.ts index 39f69576c7..53c6389382 100644 --- a/cocos/core/gfx/webgl/webgl-commands.ts +++ b/cocos/core/gfx/webgl/webgl-commands.ts @@ -179,6 +179,16 @@ export function GFXFormatToWebGLInternalFormat (format: GFXFormat, gl: WebGLRend case GFXFormat.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; case GFXFormat.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL; + case GFXFormat.ETC2_RGB8: return WebGLEXT.COMPRESSED_RGB8_ETC2; + case GFXFormat.ETC2_SRGB8: return WebGLEXT.COMPRESSED_SRGB8_ETC2; + case GFXFormat.ETC2_RGB8_A1: return WebGLEXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2; + case GFXFormat.ETC2_SRGB8_A1: return WebGLEXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2; + case GFXFormat.ETC2_RGBA8: return WebGLEXT.COMPRESSED_RGBA8_ETC2_EAC; + case GFXFormat.ETC2_SRGB8_A8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC; + case GFXFormat.EAC_R11: return WebGLEXT.COMPRESSED_R11_EAC; + case GFXFormat.EAC_R11SN: return WebGLEXT.COMPRESSED_SIGNED_R11_EAC; + case GFXFormat.EAC_RG11: return WebGLEXT.COMPRESSED_RG11_EAC; + case GFXFormat.EAC_RG11SN: return WebGLEXT.COMPRESSED_SIGNED_RG11_EAC; case GFXFormat.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; case GFXFormat.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; diff --git a/cocos/core/gfx/webgl2/webgl2-commands.ts b/cocos/core/gfx/webgl2/webgl2-commands.ts index 497e84eb1b..9fa3410223 100644 --- a/cocos/core/gfx/webgl2/webgl2-commands.ts +++ b/cocos/core/gfx/webgl2/webgl2-commands.ts @@ -339,6 +339,16 @@ export function GFXFormatToWebGLFormat (format: GFXFormat, gl: WebGL2RenderingCo case GFXFormat.BC3_SRGB: return WebGLEXT.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; case GFXFormat.ETC_RGB8: return WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL; + case GFXFormat.ETC2_RGB8: return WebGLEXT.COMPRESSED_RGB8_ETC2; + case GFXFormat.ETC2_SRGB8: return WebGLEXT.COMPRESSED_SRGB8_ETC2; + case GFXFormat.ETC2_RGB8_A1: return WebGLEXT.COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2; + case GFXFormat.ETC2_SRGB8_A1: return WebGLEXT.COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2; + case GFXFormat.ETC2_RGBA8: return WebGLEXT.COMPRESSED_RGBA8_ETC2_EAC; + case GFXFormat.ETC2_SRGB8_A8: return WebGLEXT.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC; + case GFXFormat.EAC_R11: return WebGLEXT.COMPRESSED_R11_EAC; + case GFXFormat.EAC_R11SN: return WebGLEXT.COMPRESSED_SIGNED_R11_EAC; + case GFXFormat.EAC_RG11: return WebGLEXT.COMPRESSED_RG11_EAC; + case GFXFormat.EAC_RG11SN: return WebGLEXT.COMPRESSED_SIGNED_RG11_EAC; case GFXFormat.PVRTC_RGB2: return WebGLEXT.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; case GFXFormat.PVRTC_RGBA2: return WebGLEXT.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; diff --git a/cocos/core/gfx/webgl2/webgl2-device.ts b/cocos/core/gfx/webgl2/webgl2-device.ts index 5a4aad76fd..5402ffd8c3 100644 --- a/cocos/core/gfx/webgl2/webgl2-device.ts +++ b/cocos/core/gfx/webgl2/webgl2-device.ts @@ -255,7 +255,6 @@ export class WebGL2GFXDevice extends GFXDevice { this._features[GFXFeature.TEXTURE_HALF_FLOAT] = true; this._features[GFXFeature.FORMAT_R11G11B10F] = true; this._features[GFXFeature.FORMAT_D24S8] = true; - this._features[GFXFeature.FORMAT_ETC2] = true; this._features[GFXFeature.MSAA] = true; this._features[GFXFeature.ELEMENT_INDEX_UINT] = true; this._features[GFXFeature.INSTANCED_ARRAYS] = true; From ac3406082fca749e181f1cfe5cbfadb9637e57db Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Thu, 21 May 2020 16:48:17 +0800 Subject: [PATCH 29/74] Implements EventTarget in a better way (#6571) * Implements EventTarget in a better way * Fix * Update * Use Object instead of empty class * Comment * Revert "Use Object instead of empty class" This reverts commit 3d41c70064d74c10a7b5ece2da5593ca9e8ac877. * Eventful -> Eventify --- .vscode/cSpell.json | 2 + cocos/core/animation/animation-component.ts | 41 +--- cocos/core/assets/asset.ts | 37 +--- cocos/core/assets/texture-util.ts | 2 +- cocos/core/event/event-target.ts | 167 +-------------- cocos/core/event/eventify.ts | 201 ++++++++++++++++++ cocos/core/event/index.ts | 1 + .../components/collider/collider-component.ts | 71 +------ 8 files changed, 222 insertions(+), 300 deletions(-) create mode 100644 cocos/core/event/eventify.ts diff --git a/.vscode/cSpell.json b/.vscode/cSpell.json index d7cb4436d7..12508101b6 100644 --- a/.vscode/cSpell.json +++ b/.vscode/cSpell.json @@ -9,6 +9,8 @@ "deinterleave", "deserialize", "earcut", + "eventify", + "eventified", "forin", "glsl", "grayscale", diff --git a/cocos/core/animation/animation-component.ts b/cocos/core/animation/animation-component.ts index d8f3849a84..18b0651337 100644 --- a/cocos/core/animation/animation-component.ts +++ b/cocos/core/animation/animation-component.ts @@ -29,9 +29,7 @@ import { Component } from '../components/component'; import { ccclass, help, executeInEditMode, executionOrder, menu, property } from '../data/class-decorator'; -import { Event, EventTarget } from '../event'; -import { CallbacksInvoker, ICallbackTable } from '../event/callbacks-invoker'; -import { applyMixins, IEventTarget } from '../event/event-target-factory'; +import { Eventify } from '../event/eventify'; import { warnID } from '../platform/debug'; import * as ArrayUtils from '../utils/array'; import { createMap } from '../utils/js-typed'; @@ -79,6 +77,8 @@ export enum EventType { } ccenum(EventType); +type AnimationEventCallback = (this: ThisType, type: EventType, state: AnimationState) => void; + /** * 动画组件管理动画状态来控制动画的播放。 * 它提供了方便的接口用来预创建指定动画剪辑的动画状态,并提供了一系列事件: @@ -94,7 +94,7 @@ ccenum(EventType); @executionOrder(99) @executeInEditMode @menu('Components/Animation') -export class AnimationComponent extends Component implements IEventTarget { +export class AnimationComponent extends Eventify(Component) { /** * 获取此动画组件的自有动画剪辑。 * 动画组件开始运行时会为每个自有动画剪辑创建动画状态。 @@ -180,8 +180,6 @@ export class AnimationComponent extends Component implements IEventTarget { }) public playOnLoad = false; - public _callbackTable: ICallbackTable = createMap(true); - protected _crossFade = new CrossFade(); protected _nameToState: { [name: string]: AnimationState; } = createMap(true); @@ -410,8 +408,8 @@ export class AnimationComponent extends Component implements IEventTarget { * animation.on('play', this.onPlay, this); * ``` */ - public on (type: string, callback: (type: string, state: AnimationState) => void, target?: Object) { - const ret = EventTarget.prototype.on.call(this, type, callback, target); + public on (type: EventType, callback: TFunction, thisArg?: any) { + const ret = super.on(type, callback, thisArg); if (type === 'lastframe') { for (const stateName of Object.keys(this._nameToState)) { this._nameToState[stateName]!._lastframeEventOn = true; @@ -434,7 +432,7 @@ export class AnimationComponent extends Component implements IEventTarget { * animation.off('play', this.onPlay, this); * ``` */ - public off (type: string, callback: Function, target?: Object) { + public off (type: EventType, callback?: TFunction, thisArg?: any) { if (type === 'lastframe') { const nameToState = this._nameToState; for (const name of Object.keys(nameToState)) { @@ -442,25 +440,9 @@ export class AnimationComponent extends Component implements IEventTarget { state._lastframeEventOn = false; } } - - EventTarget.prototype.off.call(this, type, callback, target); + super.off(type, callback, thisArg); } - /** - * @en IEventTarget implementations, they will be overwrote with the same implementation in EventTarget by applyMixins - * @zh IEventTarget 实现,它们将被 applyMixins 在 EventTarget 中用相同的实现覆盖。 - */ - public targetOff (keyOrTarget?: string | Object | undefined): void {} - public once (type: string, callback: Function, target?: Object | undefined): Function | undefined { - return; - } - public dispatchEvent (event: Event): void {} - public hasEventListener (key: string, callback?: Function | undefined, target?: Object | undefined): boolean { - return false; - } - public removeAll (keyOrTarget?: string | Object | undefined): void {} - public emit (key: string, ...args: any[]): void {} - protected _createState (clip: AnimationClip, name?: string) { return new AnimationState(clip, name); } @@ -503,13 +485,6 @@ export class AnimationComponent extends Component implements IEventTarget { } } -// for restore on and off -const {on, off} = AnimationComponent.prototype; -applyMixins(AnimationComponent, [CallbacksInvoker, EventTarget]); -// restore -AnimationComponent.prototype.on = on; -AnimationComponent.prototype.off = off; - cc.AnimationComponent = AnimationComponent; function equalClips (clip1: AnimationClip | null, clip2: AnimationClip | null) { diff --git a/cocos/core/assets/asset.ts b/cocos/core/assets/asset.ts index 0f0cc992e6..a0c54b1031 100644 --- a/cocos/core/assets/asset.ts +++ b/cocos/core/assets/asset.ts @@ -29,11 +29,7 @@ */ import { ccclass, property, string } from '../data/class-decorator'; -import { Event } from '../event'; -import { CallbacksInvoker } from '../event/callbacks-invoker'; -import { EventTarget } from '../event/event-target'; -import { applyMixins, IEventTarget } from '../event/event-target-factory'; -import { createMap } from '../utils/js-typed'; +import { Eventify } from '../event'; import { RawAsset } from './raw-asset'; import { Node } from '../scene-graph'; @@ -59,7 +55,7 @@ import { Node } from '../scene-graph'; * @extends RawAsset */ @ccclass('cc.Asset') -export class Asset extends RawAsset implements IEventTarget { +export class Asset extends Eventify(RawAsset) { /** * @en Indicates whether its dependent raw assets can support deferred load if the owner scene (or prefab) is marked as `asyncLoadAssets`. @@ -111,33 +107,6 @@ export class Asset extends RawAsset implements IEventTarget { private _file: any = null; - constructor (...args: ConstructorParameters) { - super(...args); - } - - /** - * @en - * IEventTarget implementations, they will be overwrote with the same implementation in EventTarget by applyMixins - * @zh - * IEventTarget 实现,它们将被 applyMixins 在 EventTarget 中用相同的实现覆盖 - */ - // tslint:disable-next-line: member-ordering - public _callbackTable = createMap(true); - public on (type: string, callback: Function, target?: Object | undefined): Function | undefined { - return; - } - public off (type: string, callback?: Function | undefined, target?: Object | undefined): void {} - public targetOff (keyOrTarget?: string | Object | undefined): void {} - public once (type: string, callback: Function, target?: Object | undefined): Function | undefined { - return; - } - public dispatchEvent (event: Event): void {} - public hasEventListener (key: string, callback?: Function | undefined, target?: Object | undefined): boolean { - return false; - } - public removeAll (keyOrTarget?: string | Object | undefined): void {} - public emit (key: string, ...args: any[]): void {} - /** * @en * Returns the url of this asset's native object, if none it will returns an empty string. @@ -264,8 +233,6 @@ export class Asset extends RawAsset implements IEventTarget { public createNode? (callback: CreateNodeCallback): void; } -applyMixins(Asset, [CallbacksInvoker, EventTarget]); - /** * @param error - null or the error info * @param node - the created node or null diff --git a/cocos/core/assets/texture-util.ts b/cocos/core/assets/texture-util.ts index 366b7a40c2..9b00b9c9e5 100644 --- a/cocos/core/assets/texture-util.ts +++ b/cocos/core/assets/texture-util.ts @@ -46,7 +46,7 @@ export type LoadImageCallback = ( * @param target 回调函数的 `this` 参数。 * @returns 图像资源,返回时可能还未完成加载;加载完成或失败时会调用回调函数。 */ -export function loadImage (url: string, callback?: LoadImageCallback, target?: T) { +export function loadImage (url: string, callback?: LoadImageCallback, target?: T) { assertID(!!url, 3103); let imageAsset = loader.getRes(url); diff --git a/cocos/core/event/event-target.ts b/cocos/core/event/event-target.ts index 2294d63bf5..c133311362 100644 --- a/cocos/core/event/event-target.ts +++ b/cocos/core/event/event-target.ts @@ -28,170 +28,13 @@ * @category event */ -import * as js from '../utils/js'; -import { CallbacksInvoker } from './callbacks-invoker'; +import { Eventify } from './eventify'; -const fastRemove = js.array.fastRemove; +// eslint-disable-next-line @typescript-eslint/no-extraneous-class +class Empty {}; -export interface ITargetImpl extends Object { - __eventTargets?: Object[]; - node?: ITargetImpl; -} +export const EventTarget = Eventify(Empty); -/** - * !#en - * EventTarget is an object to which an event is dispatched when something has occurred. - * Entity are the most common event targets, but other objects can be event targets too. - * - * Event targets are an important part of the Fireball event model. - * The event target serves as the focal point for how events flow through the scene graph. - * When an event such as a mouse click or a keypress occurs, Fireball dispatches an event object - * into the event flow from the root of the hierarchy. The event object then makes its way through - * the scene graph until it reaches the event target, at which point it begins its return trip through - * the scene graph. This round-trip journey to the event target is conceptually divided into three phases: - * - The capture phase comprises the journey from the root to the last node before the event target's node - * - The target phase comprises only the event target node - * - The bubbling phase comprises any subsequent nodes encountered on the return trip to the root of the tree - * See also: http://www.w3.org/TR/DOM-Level-3-Events/#event-flow - * - * Event targets can implement the following methods: - * - _getCapturingTargets - * - _getBubblingTargets - * - * If a class cannot extend from EventTarget, it can consider implements IEventTarget interface. - * - * !#zh - * 事件目标是具有注册监听器、派发事件能力的类,Node 是最常见的事件目标, - * 但是其他类也可以继承自事件目标以获得管理监听器和派发事件的能力。 - * 如果无法继承自 EventTarget,也可以考虑自实现 IEventTarget - */ -export class EventTarget extends CallbacksInvoker { - /** - * @en - * Register an callback of a specific event type on the EventTarget. - * This type of event should be triggered via `emit`. - * @zh - * 注册事件目标的特定事件类型回调。这种类型的事件应该被 `emit` 触发。 - * - * @param type - A string representing the event type to listen for. - * @param 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 target - The target (this object) to invoke the callback, can be null - * @return - Just returns the incoming callback so you can save the anonymous function easier. - * @example - * eventTarget.on('fire', function () { - * cc.log("fire in the hole"); - * }, node); - */ - public on (type: string, callback: Function, target?: Object) { - if (!callback) { - cc.errorID(6800); - return; - } - - if (!this.hasEventListener(type, callback, target)) { - super.on(type, callback, target); - - const targetImpl = target as ITargetImpl; - if (target) { - if (targetImpl.__eventTargets) { - targetImpl.__eventTargets.push(this); - } else if (targetImpl.node && targetImpl.node.__eventTargets) { - targetImpl.node.__eventTargets.push(this); - } - } - } - return callback; - } - - /** - * @en - * Removes the listeners previously registered with the same type, callback, target and or useCapture, - * if only type is passed as parameter, all listeners registered with that type will be removed. - * @zh - * 删除之前用同类型,回调,目标或 useCapture 注册的事件监听器,如果只传递 type,将会删除 type 类型的所有事件监听器。 - * - * @param type - A string representing the event type being removed. - * @param callback - The callback to remove. - * @param target - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed - * @example - * // register fire eventListener - * var callback = eventTarget.on('fire', function () { - * cc.log("fire in the hole"); - * }, target); - * // remove fire event listener - * eventTarget.off('fire', callback, target); - * // remove all fire event listeners - * eventTarget.off('fire'); - */ - public off (type: string, callback?: Function, target?: Object) { - if (!callback) { - this.removeAll(type); - } - else { - super.off(type, callback, target); - - const targetImpl = target as ITargetImpl; - if (target) { - if (targetImpl.__eventTargets) { - fastRemove(targetImpl.__eventTargets, this); - } else if (targetImpl.node && targetImpl.node.__eventTargets) { - fastRemove(targetImpl.node.__eventTargets, this); - } - } - } - } - - /** - * @en Removes all callbacks previously registered with the same target (passed as parameter). - * This is not for removing all listeners in the current event target, - * and this is not for removing all listeners the target parameter have registered. - * It's only for removing all listeners (callback and target couple) registered on the current event target by the target parameter. - * @zh 在当前 EventTarget 上删除指定目标(target 参数)注册的所有事件监听器。 - * 这个函数无法删除当前 EventTarget 的所有事件监听器,也无法删除 target 参数所注册的所有事件监听器。 - * 这个函数只能删除 target 参数在当前 EventTarget 上注册的所有事件监听器。 - * @param target - The target to be searched for all related listeners - */ - public targetOff (keyOrTarget?: string | Object) { - this.removeAll(keyOrTarget); - } - - /** - * @en - * Register an callback of a specific event type on the EventTarget, - * the callback will remove itself after the first time it is triggered. - * @zh - * 注册事件目标的特定事件类型回调,回调会在第一时间被触发后删除自身。 - * - * @param type - A string representing the event type to listen for. - * @param 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 target - The target (this object) to invoke the callback, can be null - * @example - * eventTarget.once('fire', function () { - * cc.log("this is the callback and will be invoked only once"); - * }, node); - */ - public once (type: string, callback: Function, target?: Object) { - if (!callback) { - cc.errorID(6800); - return; - } - - if (!this.hasEventListener(type, callback, target)) { - super.on(type, callback, target, true); - - const targetImpl = target as ITargetImpl; - if (target) { - if (targetImpl.__eventTargets) { - targetImpl.__eventTargets.push(this); - } else if (targetImpl.node && targetImpl.node.__eventTargets) { - targetImpl.node.__eventTargets.push(this); - } - } - } - return callback; - } -} +export type EventTarget = InstanceType; cc.EventTarget = EventTarget; diff --git a/cocos/core/event/eventify.ts b/cocos/core/event/eventify.ts new file mode 100644 index 0000000000..ed78d59b7c --- /dev/null +++ b/cocos/core/event/eventify.ts @@ -0,0 +1,201 @@ +import { fastRemove } from '../utils/array'; +import { CallbacksInvoker } from './callbacks-invoker'; + +type Constructor = new (...args: any[]) => T; + +type EventType = string; + +/** + * @zh + * 实现该接口的对象具有处理事件的能力。 + * @en + * Objects those implement this interface have essentially the capability to process events. + */ +export interface IEventified { + /** + * @zh 检查指定事件是否已注册回调。 + * @en Checks whether there is correspond event listener registered on the given event. + * @param type - Event type. + * @param callback - Callback function when event triggered. + * @param target - Callback callee. + */ + hasEventListener (type: string, callback?: Function, target?: object): boolean; + + /** + * @en + * Register an callback of a specific event type on the EventTarget. + * This type of event should be triggered via `emit`. + * @zh + * 注册事件目标的特定事件类型回调。这种类型的事件应该被 `emit` 触发。 + * + * @param type - A string representing the event type to listen for. + * @param 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 thisArg - The target (this object) to invoke the callback, can be null + * @return - Just returns the incoming callback so you can save the anonymous function easier. + * @example + * eventTarget.on('fire', function () { + * cc.log("fire in the hole"); + * }, node); + */ + on (type: EventType, callback: TFunction, thisArg?: any): typeof callback; + + /** + * @en + * Register an callback of a specific event type on the EventTarget, + * the callback will remove itself after the first time it is triggered. + * @zh + * 注册事件目标的特定事件类型回调,回调会在第一时间被触发后删除自身。 + * + * @param type - A string representing the event type to listen for. + * @param 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 target - The target (this object) to invoke the callback, can be null + * @example + * eventTarget.once('fire', function () { + * cc.log("this is the callback and will be invoked only once"); + * }, node); + */ + once (type: EventType, callback: TFunction, thisArg?: any): typeof callback; + + /** + * @en + * Removes the listeners previously registered with the same type, callback, target and or useCapture, + * if only type is passed as parameter, all listeners registered with that type will be removed. + * @zh + * 删除之前用同类型,回调,目标或 useCapture 注册的事件监听器,如果只传递 type,将会删除 type 类型的所有事件监听器。 + * + * @param type - A string representing the event type being removed. + * @param callback - The callback to remove. + * @param target - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed + * @example + * // register fire eventListener + * var callback = eventTarget.on('fire', function () { + * cc.log("fire in the hole"); + * }, target); + * // remove fire event listener + * eventTarget.off('fire', callback, target); + * // remove all fire event listeners + * eventTarget.off('fire'); + */ + off (type: EventType, callback?: TFunction, thisArg?: any): void; + + /** + * @en Removes all callbacks previously registered with the same target (passed as parameter). + * This is not for removing all listeners in the current event target, + * and this is not for removing all listeners the target parameter have registered. + * It's only for removing all listeners (callback and target couple) registered on the current event target by the target parameter. + * @zh 在当前 EventTarget 上删除指定目标(target 参数)注册的所有事件监听器。 + * 这个函数无法删除当前 EventTarget 的所有事件监听器,也无法删除 target 参数所注册的所有事件监听器。 + * 这个函数只能删除 target 参数在当前 EventTarget 上注册的所有事件监听器。 + * @param typeOrTarget - The target to be searched for all related listeners + */ + targetOff (typeOrTarget: string | object): void; + + /** + * @zh 移除在特定事件类型中注册的所有回调或在某个目标中注册的所有回调。 + * @en Removes all callbacks registered in a certain event type or all callbacks registered with a certain target + * @param typeOrTarget - The event type or target with which the listeners will be removed + */ + removeAll (typeOrTarget: string | object): void; + + /** + * @zh 派发一个指定事件,并传递需要的参数 + * @en Trigger an event directly with the event name and necessary arguments. + * @param type - event type + * @param args - Arguments when the event triggered + */ + emit (type: EventType, ...args: any[]): void; +} + +/** + * 生成一个类,该类继承自指定的基类,并实现了 `IEventified` 的所有接口。 + * @param base 基类。 + * @example + * ```ts + * class Base { say() { console.log('Hello!'); } } + * class MyClass extends Eventify(Base) { } + * function (o: MyClass) { + * o.say(); // Ok: 继承自 `Base` + * o.emit('sing', 'The ghost'); // Ok: `MyClass`类的对象实现了 IEventified + * } + * ``` + */ +export function Eventify (base: Constructor): Constructor { + return class extends (base as unknown as any) implements IEventified { + private _callbacksInvoker: CallbacksInvoker = new CallbacksInvoker(); + + constructor (...args: any[]) { + super(...args); + } + + public hasEventListener (type: string, callback?: Function, target?: object): boolean { + return this._callbacksInvoker.hasEventListener(type, callback, target); + } + + public on (type: EventType, callback: Callback, target?: object) { + if (!this.hasEventListener(type, callback, target)) { + this._callbacksInvoker.on(type, callback, target); + if (target) { + this._registerThisIntoTarget(target); + } + } + return callback; + } + + public once (type: EventType, callback: Callback, target?: object) { + if (!this.hasEventListener(type, callback, target)) { + this._callbacksInvoker.on(type, callback, target, true); + if (target) { + this._registerThisIntoTarget(target); + } + } + return callback; + } + + public off (type: EventType, callback?: Function, target?: object) { + if (!callback) { + this.removeAll(type); + } else { + this._callbacksInvoker.off(type, callback, target); + if (target) { + this._unregisterThisIntoTarget(target); + } + } + } + + public targetOff (typeOrTarget: string | object) { + this.removeAll(typeOrTarget); + } + + public removeAll (typeOrTarget: string | object) { + this._callbacksInvoker.removeAll(typeOrTarget); + } + + public emit (type: EventType, ...args: any[]) { + return this._callbacksInvoker.emit(type, ...args); + } + + private _registerThisIntoTarget (target: ITargetImpl) { + if (target.__eventTargets) { + target.__eventTargets.push(this); + } else if (target.node && target.node.__eventTargets) { + target.node.__eventTargets.push(this); + } + } + + private _unregisterThisIntoTarget (target: ITargetImpl) { + if (target.__eventTargets) { + fastRemove(target.__eventTargets, this); + } else if (target.node && target.node.__eventTargets) { + fastRemove(target.node.__eventTargets, this); + } + } + + } as unknown as any; +} + +interface ITargetImpl extends Object { + __eventTargets?: IEventified[]; + node?: ITargetImpl; +} diff --git a/cocos/core/event/index.ts b/cocos/core/event/index.ts index adde5595ed..2846cc5296 100644 --- a/cocos/core/event/index.ts +++ b/cocos/core/event/index.ts @@ -30,3 +30,4 @@ export { default as Event } from './event'; export { EventTarget } from './event-target'; +export { Eventify } from './eventify'; diff --git a/cocos/physics/framework/components/collider/collider-component.ts b/cocos/physics/framework/components/collider/collider-component.ts index 6ef307050d..615aa68db9 100644 --- a/cocos/physics/framework/components/collider/collider-component.ts +++ b/cocos/physics/framework/components/collider/collider-component.ts @@ -3,10 +3,7 @@ */ import { ccclass, property } from '../../../../core/data/class-decorator'; -import { EventTarget } from '../../../../core/event'; -import { CallbacksInvoker, ICallbackTable } from '../../../../core/event/callbacks-invoker'; -import { applyMixins, IEventTarget } from '../../../../core/event/event-target-factory'; -import { createMap } from '../../../../core/utils/js'; +import { Eventify } from '../../../../core/event'; import { Vec3 } from '../../../../core/math'; import { CollisionCallback, CollisionEventType, TriggerCallback, TriggerEventType } from '../../physics-interface'; import { RigidBodyComponent } from '../rigid-body-component'; @@ -23,15 +20,7 @@ import { EDITOR, PHYSICS_BUILTIN } from 'internal:constants'; * 碰撞器的基类。 */ @ccclass('cc.ColliderComponent') -export class ColliderComponent extends Component implements IEventTarget { - - /** - * @en - * Stores a list of callbacks to the registration event, not directly modified. - * @zh - * 存储注册事件的回调列表,请不要直接修改。 - */ - public _callbackTable: ICallbackTable = createMap(true); +export class ColliderComponent extends Eventify(Component) { /// PUBLIC PROPERTY GETTER\SETTER /// @@ -187,60 +176,6 @@ export class ColliderComponent extends Component implements IEventTarget { constructor () { super() } - /// EVENT INTERFACE /// - - /** - * @zh - * 注册触发事件或碰撞事件相关的回调。 - * @param type - 触发或碰撞事件的类型,可为 'onTriggerEnter','onTriggerStay','onTriggerExit' 或 'onCollisionEnter','onCollisionStay','onCollisionExit'; - * @param callback - 注册的回调函数 - * @param target - 可选参数,执行回调函数的目标 - * @param useCapture - 可选参数,当设置为 true,监听器将在捕获阶段触发,否则将在冒泡阶段触发。默认为 false。 - */ - public on (type: TriggerEventType | CollisionEventType, callback: TriggerCallback | CollisionCallback, target?: Object, useCapture?: any): any { - } - - /** - * @zh - * 取消已经注册的触发事件或碰撞事件相关的回调。 - * @param type - 触发或碰撞事件的类型,可为 'onTriggerEnter','onTriggerStay','onTriggerExit' 或 'onCollisionEnter','onCollisionStay','onCollisionExit'; - * @param callback - 注册的回调函数 - * @param target - 可选参数,执行回调函数的目标 - * @param useCapture - 可选参数,当设置为 true,监听器将在捕获阶段触发,否则将在冒泡阶段触发。默认为 false。 - */ - public off (type: TriggerEventType | CollisionEventType, callback: TriggerCallback | CollisionCallback, target?: Object, useCapture?: any) { - } - - /** - * @zh - * 注册触发事件或碰撞事件相关的回调,但只会执行一次。 - * @param type - 触发或碰撞事件的类型,可为 'onTriggerEnter','onTriggerStay','onTriggerExit' 或 'onCollisionEnter','onCollisionStay','onCollisionExit'; - * @param callback - 注册的回调函数 - * @param target - 可选参数,执行回调函数的目标 - * @param useCapture - 可选参数,当设置为 true,监听器将在捕获阶段触发,否则将在冒泡阶段触发。默认为 false。 - */ - public once (type: TriggerEventType | CollisionEventType, callback: TriggerCallback | CollisionCallback, target?: Object, useCapture?: any): any { - } - - /** - * IEventTarget implementations, they will be overwrote with the same implementation in EventTarget by applyMixins - */ - public targetOff (keyOrTarget?: TriggerEventType | CollisionEventType | Object): void { - } - - public dispatchEvent (event: Event): void { - } - - public hasEventListener (key: TriggerEventType | CollisionEventType, callback?: TriggerCallback | CollisionCallback, target?: Object): boolean { - return false; - } - - public removeAll (keyOrTarget?: TriggerEventType | CollisionEventType | Object): void { - } - - public emit (key: TriggerEventType | CollisionEventType, ...args: any[]): void { - } - /// GROUP MASK /// /** @@ -374,5 +309,3 @@ export class ColliderComponent extends Component implements IEventTarget { } } - -applyMixins(ColliderComponent, [CallbacksInvoker, EventTarget]); From 9306b0ba8f2b0c75abcf7cb46ffdc262a67171c3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Fri, 22 May 2020 18:03:05 +0800 Subject: [PATCH 30/74] Allow some static member of class to be type (#6724) --- cocos/audio/assets/clip.ts | 5 +++++ cocos/core/3d/framework/camera-component.ts | 9 +++++++++ cocos/core/3d/framework/light-component.ts | 5 +++++ cocos/core/3d/framework/model-component.ts | 4 ++++ cocos/core/animation/animation-clip.ts | 4 ++++ cocos/core/animation/animation-component.ts | 4 ++++ cocos/core/assets/texture-base.ts | 6 ++++++ cocos/ui/components/widget-component.ts | 4 ++++ 8 files changed, 41 insertions(+) diff --git a/cocos/audio/assets/clip.ts b/cocos/audio/assets/clip.ts index bb21d52e9c..f069009d93 100644 --- a/cocos/audio/assets/clip.ts +++ b/cocos/audio/assets/clip.ts @@ -131,4 +131,9 @@ export class AudioClip extends Asset { } } +export namespace AudioClip { + export type PlayingState = typeof PlayingState; + export type AudioType = typeof AudioType; +} + cc.AudioClip = AudioClip; diff --git a/cocos/core/3d/framework/camera-component.ts b/cocos/core/3d/framework/camera-component.ts index d8ed97c7a1..11d4f22213 100644 --- a/cocos/core/3d/framework/camera-component.ts +++ b/cocos/core/3d/framework/camera-component.ts @@ -649,3 +649,12 @@ export class CameraComponent extends Component { } } } + +export namespace CameraComponent { + export type ProjectionType = typeof ProjectionType; + export type FOVAxis = typeof FOVAxis; + export type ClearFlag = typeof ClearFlag; + export type Aperture = typeof Aperture; + export type Shutter = typeof Shutter; + export type ISO = typeof ISO; +} diff --git a/cocos/core/3d/framework/light-component.ts b/cocos/core/3d/framework/light-component.ts index f6704f0eaf..3c41975f9e 100644 --- a/cocos/core/3d/framework/light-component.ts +++ b/cocos/core/3d/framework/light-component.ts @@ -225,3 +225,8 @@ export class LightComponent extends Component { } } } + +export namespace LightComponent { + export type Type = typeof LightType; + export type PhotometricTerm = typeof PhotometricTerm; +} diff --git a/cocos/core/3d/framework/model-component.ts b/cocos/core/3d/framework/model-component.ts index d2a0190e83..416a0ece08 100644 --- a/cocos/core/3d/framework/model-component.ts +++ b/cocos/core/3d/framework/model-component.ts @@ -462,3 +462,7 @@ export class ModelComponent extends RenderableComponent { subMeshMorphInstance.renderResources.setWeights(subMeshMorphInstance.weights); } } + +export namespace ModelComponent { + export type ShadowCastingMode = typeof ModelShadowCastingMode; +} diff --git a/cocos/core/animation/animation-clip.ts b/cocos/core/animation/animation-clip.ts index 7deab6b873..14b013b24f 100644 --- a/cocos/core/animation/animation-clip.ts +++ b/cocos/core/animation/animation-clip.ts @@ -394,4 +394,8 @@ export class AnimationClip extends Asset { } } +export namespace AnimationClip { + export type WrapMode = typeof AnimationWrapMode; +} + cc.AnimationClip = AnimationClip; diff --git a/cocos/core/animation/animation-component.ts b/cocos/core/animation/animation-component.ts index 18b0651337..4970943888 100644 --- a/cocos/core/animation/animation-component.ts +++ b/cocos/core/animation/animation-component.ts @@ -485,6 +485,10 @@ export class AnimationComponent extends Eventify(Component) { } } +export namespace AnimationComponent { + export type EventType = typeof EventType; +} + cc.AnimationComponent = AnimationComponent; function equalClips (clip1: AnimationClip | null, clip2: AnimationClip | null) { diff --git a/cocos/core/assets/texture-base.ts b/cocos/core/assets/texture-base.ts index 3770fcbfbb..8e0d2c8d37 100644 --- a/cocos/core/assets/texture-base.ts +++ b/cocos/core/assets/texture-base.ts @@ -326,4 +326,10 @@ export class TextureBase extends Asset { } } +export namespace TextureBase { + export type PixelFormat = typeof PixelFormat; + export type WrapMode = typeof WrapMode; + export type Filter = typeof Filter; +} + cc.TextureBase = TextureBase; diff --git a/cocos/ui/components/widget-component.ts b/cocos/ui/components/widget-component.ts index 0a68b47e8a..9c0c70e44d 100644 --- a/cocos/ui/components/widget-component.ts +++ b/cocos/ui/components/widget-component.ts @@ -1078,6 +1078,10 @@ export class WidgetComponent extends Component { } } +export namespace WidgetComponent { + export type AlignMode = typeof AlignMode; +} + // @ts-ignore cc.WidgetComponent = WidgetComponent; From a5c238dabb9c39c0b9dddb642a3169b624f32c5c Mon Sep 17 00:00:00 2001 From: pandamicro Date: Mon, 25 May 2020 15:26:02 +0800 Subject: [PATCH 31/74] API translations in core (#6726) * Add API translation for load pipeline * Add API translation for core/data * Fix decorator declarations * API translation for scene graph * Fix ci * Fix ci * Improve Eventify for event emit performance * Fix ci * improve format --- cocos/core/animation/animation-component.ts | 2 +- cocos/core/animation/animation-state.ts | 4 +- cocos/core/assets/asset.ts | 2 +- cocos/core/assets/texture-util.ts | 3 +- cocos/core/components/system.ts | 2 +- cocos/core/data/class-decorator.ts | 226 ++++------ cocos/core/data/class.ts | 91 +--- cocos/core/data/deserialize.ts | 2 +- cocos/core/data/instantiate-jit.ts | 2 +- cocos/core/data/instantiate.ts | 20 +- cocos/core/data/object.ts | 29 +- cocos/core/event/callbacks-invoker.ts | 12 +- cocos/core/event/event-target.ts | 11 + cocos/core/event/eventify.ts | 23 +- cocos/core/load-pipeline/CCLoader.ts | 416 +++++++----------- cocos/core/load-pipeline/asset-loader.ts | 7 +- cocos/core/load-pipeline/asset-table.ts | 36 +- .../core/load-pipeline/auto-release-utils.ts | 2 +- cocos/core/load-pipeline/binary-downloader.ts | 8 +- cocos/core/load-pipeline/callback-params.ts | 3 +- cocos/core/load-pipeline/downloader.ts | 60 ++- cocos/core/load-pipeline/font-loader.ts | 6 +- cocos/core/load-pipeline/index.ts | 2 +- cocos/core/load-pipeline/loader.ts | 39 +- cocos/core/load-pipeline/loading-items.ts | 187 +++----- cocos/core/load-pipeline/md5-pipe.ts | 12 +- cocos/core/load-pipeline/pack-downloader.ts | 2 +- cocos/core/load-pipeline/pipeline.ts | 112 +++-- cocos/core/load-pipeline/plist-parser.ts | 13 +- .../load-pipeline/released-asset-checker.ts | 4 +- cocos/core/load-pipeline/text-downloader.ts | 10 +- cocos/core/load-pipeline/unpackers.ts | 12 +- cocos/core/load-pipeline/url.ts | 11 +- cocos/core/load-pipeline/utils.ts | 2 +- cocos/core/load-pipeline/uuid-loader.ts | 11 +- .../platform/event-manager/event-listener.ts | 4 +- cocos/core/root.ts | 2 +- cocos/core/scene-graph/base-node-dev.ts | 2 +- cocos/core/scene-graph/base-node.ts | 406 ++++++++--------- cocos/core/scene-graph/component-scheduler.ts | 52 ++- cocos/core/scene-graph/find.ts | 6 +- cocos/core/scene-graph/layers.ts | 34 +- cocos/core/scene-graph/node-activator.ts | 25 +- cocos/core/scene-graph/node-enum.ts | 10 +- .../core/scene-graph/node-event-processor.ts | 2 +- cocos/core/scene-graph/node-ui-properties.ts | 17 +- cocos/core/scene-graph/node.ts | 341 +++++++------- cocos/core/scene-graph/private-node.ts | 8 +- cocos/core/scene-graph/scene-globals.ts | 31 +- cocos/core/scene-graph/scene.ts | 91 +++- cocos/core/utils/misc.ts | 2 +- cocos/particle/particle-utils.ts | 2 +- 52 files changed, 1186 insertions(+), 1233 deletions(-) diff --git a/cocos/core/animation/animation-component.ts b/cocos/core/animation/animation-component.ts index 4970943888..ebe526e51a 100644 --- a/cocos/core/animation/animation-component.ts +++ b/cocos/core/animation/animation-component.ts @@ -432,7 +432,7 @@ export class AnimationComponent extends Eventify(Component) { * animation.off('play', this.onPlay, this); * ``` */ - public off (type: EventType, callback?: TFunction, thisArg?: any) { + public off (type: EventType, callback?: Function, thisArg?: any) { if (type === 'lastframe') { const nameToState = this._nameToState; for (const name of Object.keys(nameToState)) { diff --git a/cocos/core/animation/animation-state.ts b/cocos/core/animation/animation-state.ts index 1e17d140cb..76f7b54e3d 100644 --- a/cocos/core/animation/animation-state.ts +++ b/cocos/core/animation/animation-state.ts @@ -30,14 +30,12 @@ import { EventArgumentsOf, EventCallbackOf } from '../event/defines'; import { Node } from '../scene-graph/node'; import { AnimationClip, IRuntimeCurve } from './animation-clip'; -import { AnimationComponent } from './animation-component'; import { AnimCurve, RatioSampler } from './animation-curve'; import { createBoundTarget, createBufferedTarget, IBufferedTarget, IBoundTarget } from './bound-target'; import { Playable } from './playable'; import { WrapMode, WrapModeMask, WrappedInfo } from './types'; -import { error } from '../platform/debug'; import { EDITOR } from 'internal:constants'; -import { HierarchyPath, TargetPath, evaluatePath } from './target-path'; +import { HierarchyPath, evaluatePath } from './target-path'; import { BlendStateBuffer, createBlendStateWriter, IBlendStateWriter } from './skeletal-animation-blending'; enum PropertySpecialization { diff --git a/cocos/core/assets/asset.ts b/cocos/core/assets/asset.ts index a0c54b1031..419230f7d2 100644 --- a/cocos/core/assets/asset.ts +++ b/cocos/core/assets/asset.ts @@ -28,7 +28,7 @@ * @category asset */ -import { ccclass, property, string } from '../data/class-decorator'; +import { ccclass, property } from '../data/class-decorator'; import { Eventify } from '../event'; import { RawAsset } from './raw-asset'; import { Node } from '../scene-graph'; diff --git a/cocos/core/assets/texture-util.ts b/cocos/core/assets/texture-util.ts index 9b00b9c9e5..d294be80c8 100644 --- a/cocos/core/assets/texture-util.ts +++ b/cocos/core/assets/texture-util.ts @@ -32,6 +32,7 @@ import { assertID, error } from '../platform/debug'; import { loader } from '../load-pipeline/CCLoader'; import { ImageAsset, ImageSource } from './image-asset'; import { DEBUG } from 'internal:constants'; +import { IItem } from '../load-pipeline/loading-items'; export type LoadImageCallback = ( this: T | undefined, @@ -96,7 +97,7 @@ export function cacheImage (url: string, image: ImageSource) { content: imageAsset, complete: false, }; - loader.flowOut(item); + loader.flowOut(item as IItem); return imageAsset; } } diff --git a/cocos/core/components/system.ts b/cocos/core/components/system.ts index 9da54b769a..33ae1e4600 100644 --- a/cocos/core/components/system.ts +++ b/cocos/core/components/system.ts @@ -48,7 +48,7 @@ export default class System implements ISchedulable { return this._id; } - public static sortByPriority (a:System, b:System) { + public static sortByPriority (a: System, b: System) { if (a._priority < b._priority) { return 1; } diff --git a/cocos/core/data/class-decorator.ts b/cocos/core/data/class-decorator.ts index a7a10fa0f1..d58aa0914b 100644 --- a/cocos/core/data/class-decorator.ts +++ b/cocos/core/data/class-decorator.ts @@ -25,7 +25,9 @@ */ /** - * @category core/data + * @category core/_decorator + * @en Some TypeScript decorators for class and data definition + * @zh 一些用来定义类和数据的 TypeScript 装饰器 */ // const FIX_BABEL6 = true; @@ -36,17 +38,7 @@ // tslint:disable:max-line-length // tslint:disable:no-empty-interface -/** - * Some JavaScript decorators which can be accessed with "cc._decorator". - * 一些 JavaScript 装饰器,目前可以通过 "cc._decorator" 来访问。 - * (这些 API 仍不完全稳定,有可能随着 JavaScript 装饰器的标准实现而调整) - * - * @submodule _decorator - * @module _decorator - * @main - */ - -// inspired by toddlxt (https://github.com/toddlxt/Creator-TypeScript-Boilerplate) +// inspired by @toddlxt (https://github.com/toddlxt/Creator-TypeScript-Boilerplate) import * as js from '../utils/js'; import './class'; @@ -55,6 +47,7 @@ import { doValidateMethodWithProps_DEV, getFullFormOfProperty } from './utils/pr import { CCString, CCInteger, CCFloat, CCBoolean, PrimitiveType } from './utils/attribute'; import { error, errorID, warnID } from '../platform/debug'; import { DEV } from 'internal:constants'; +import { Component } from '../components/component'; // caches for class construction const CACHE_KEY = '__ccclassCache__'; @@ -242,10 +235,9 @@ function genProperty (ctor, properties, propName, options, desc, cache) { } /** - * 将标准写法的 [ES6 Class](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) 声明为 CCClass,具体用法请参阅[类型定义](/docs/creator/scripting/class/)。 - * - * @method ccclass - * @param {String} [name] - The class name used for serialization. + * @en Declare a standard ES6 or TS Class as a CCClass, please refer to the [document](https://docs.cocos.com/creator3d/manual/zh/scripting/ccclass.html) + * @zh 将标准写法的 ES6 或者 TS Class 声明为 CCClass,具体用法请参阅[类型定义](https://docs.cocos.com/creator3d/manual/zh/scripting/ccclass.html)。 + * @param name - The class name used for serialization. * @example * ```typescript * const {ccclass} = cc._decorator; @@ -263,8 +255,7 @@ function genProperty (ctor, properties, propName, options, desc, cache) { * } * ``` */ - -export const ccclass = checkCtorArgument(function (ctor, name) { +export const ccclass: any | ((name?: string) => Function) = checkCtorArgument(function (ctor, name) { // if (FIX_BABEL6) { // eval('if(typeof _classCallCheck==="function"){_classCallCheck=function(){};}'); // } @@ -314,25 +305,29 @@ export type SimplePropertyType = Function | string | typeof CCString | typeof CC export type PropertyType = SimplePropertyType | SimplePropertyType[]; /** - * @zh cc 属性选项。 + * @zh CCClass 属性选项。 + * @en CCClass property options */ export interface IPropertyOptions extends IExposedAttributes { } /** - * @zh 标注属性为 cc 属性。 - * @param options 选项。 + * @en Declare as a CCClass property with options + * @zh 声明属性为 CCClass 属性。 + * @param options property options */ export function property (options?: IPropertyOptions): PropertyDecorator; /** + * @en Declare as a CCClass property with the property type * @zh 标注属性为 cc 属性。
* 等价于`@property({type})`。 - * @param type cc 属性的类型。 + * @param type A {{ccclass}} type or a {{ValueType}} */ export function property (type: PropertyType): PropertyDecorator; /** + * @en Declare as a CCClass property * @zh 标注属性为 cc 属性。
* 等价于`@property()`。 */ @@ -381,13 +376,11 @@ function createDummyDecorator (argCheckFunc) { } /** - * Makes a CCClass that inherit from component execute in edit mode.
+ * @en Makes a CCClass that inherit from component execute in edit mode.
* By default, all components are only executed in play mode,
* which means they will not have their callback functions executed while the Editor is in edit mode.
- * 允许继承自 Component 的 CCClass 在编辑器里执行。
+ * @zh 允许继承自 Component 的 CCClass 在编辑器里执行。
* 默认情况下,所有 Component 都只会在运行时才会执行,也就是说它们的生命周期回调不会在编辑器里触发。 - * - * @method executeInEditMode * @example * ```typescript * const {ccclass, executeInEditMode} = cc._decorator; @@ -402,47 +395,46 @@ function createDummyDecorator (argCheckFunc) { export const executeInEditMode = (DEV ? createEditorDecorator : createDummyDecorator)(checkCtorArgument, 'executeInEditMode', true); /** - * 为声明为 CCClass 的组件添加依赖的其它组件。当组件添加到节点上时,如果依赖的组件不存在,引擎将会自动将依赖组件添加到同一个节点,防止脚本出错。该设置在运行时同样有效。 - * - * @method requireComponent - * @param {Component} requiredComponent + * @en Declare that the current component relies on another type of component. + * If the required component doesn't exist, the engine will create a new empty instance of the required component and add to the node. + * @zh 为声明为 CCClass 的组件添加依赖的其它组件。当组件添加到节点上时,如果依赖的组件不存在,引擎将会自动将依赖组件添加到同一个节点,防止脚本出错。该设置在运行时同样有效。 + * @param requiredComponent The required component type * @example * ```typescript - * const {ccclass, requireComponent} = cc._decorator; + * import {_decorator, SpriteComponent, Component} from cc; + * import {ccclass, requireComponent} from _decorator; * - * @ccclass - * @requireComponent(cc.SpriteComponent) - * class SpriteCtrl extends cc.Component { + * @ccclass + * @requireComponent(SpriteComponent) + * class SpriteCtrl extends Component { * // ... * } * ``` */ -export const requireComponent = createEditorDecorator(checkCompArgument, 'requireComponent'); +export const requireComponent: (requiredComponent: Function) => Function = createEditorDecorator(checkCompArgument, 'requireComponent'); /** - * 将当前组件添加到组件菜单中,方便用户查找。例如 "Rendering/CameraCtrl"。 - * - * @method menu - * @param {String} path - The path is the menu represented like a pathname. - * For example the menu could be "Rendering/CameraCtrl". + * @en Add the current component to the specific menu path in `Add Component` selector of the inspector panel + * @zh 将当前组件添加到组件菜单中,方便用户查找。例如 "Rendering/CameraCtrl"。 + * @param path - The path is the menu represented like a pathname. For example the menu could be "Rendering/CameraCtrl". * @example * ```typescript * const {ccclass, menu} = cc._decorator; * - * @ccclass - * @menu("Rendering/CameraCtrl") + * @ccclass + * @menu("Rendering/CameraCtrl") * class NewScript extends cc.Component { * // ... * } * ``` */ -export const menu = (DEV ? createEditorDecorator : createDummyDecorator)(checkStringArgument, 'menu'); +export const menu: (path: string) => Function = (DEV ? createEditorDecorator : createDummyDecorator)(checkStringArgument, 'menu'); /** - * 设置脚本生命周期方法调用的优先级。优先级小于 0 的组件将会优先执行,优先级大于 0 的组件将会延后执行。优先级仅会影响 onLoad, onEnable, start, update 和 lateUpdate,而 onDisable 和 onDestroy 不受影响。 - * - * @method executionOrder - * @param {Number} order - The execution order of lifecycle methods for Component. Those less than 0 will execute before while those greater than 0 will execute after. + * @en Set the component priority, it decides at which order the life cycle functions of components will be invoked. Smaller priority get invoked before larger priority. + * This will affect `onLoad`, `onEnable`, `start`, `update` and `lateUpdate`, but `onDisable` and `onDestroy` won't be affected. + * @zh 设置脚本生命周期方法调用的优先级。优先级小于 0 的组件将会优先执行,优先级大于 0 的组件将会延后执行。优先级仅会影响 onLoad, onEnable, start, update 和 lateUpdate,而 onDisable 和 onDestroy 不受影响。 + * @param priority - The execution order of life cycle methods for Component. Smaller priority get invoked before larger priority. * @example * ```typescript * const {ccclass, executionOrder} = cc._decorator; @@ -454,18 +446,17 @@ export const menu = (DEV ? createEditorDecorator : createDummyDecorator)(checkSt * } * ``` */ -export const executionOrder = createEditorDecorator(checkNumberArgument, 'executionOrder'); +export const executionOrder: (priority: number) => Function = createEditorDecorator(checkNumberArgument, 'executionOrder'); /** - * 防止多个相同类型(或子类型)的组件被添加到同一个节点。 - * - * @method disallowMultiple + * @en Forbid add multiple instances of the component to the same node. + * @zh 防止多个相同类型(或子类型)的组件被添加到同一个节点。 * @example * ```typescript * const {ccclass, disallowMultiple} = cc._decorator; * - * @ccclass - * @disallowMultiple + * @ccclass + * @disallowMultiple * class CameraCtrl extends cc.Component { * // ... * } @@ -474,16 +465,15 @@ export const executionOrder = createEditorDecorator(checkNumberArgument, 'execut export const disallowMultiple = (DEV ? createEditorDecorator : createDummyDecorator)(checkCtorArgument, 'disallowMultiple'); /** - * 当指定了 "executeInEditMode" 以后,playOnFocus 可以在选中当前组件所在的节点时,提高编辑器的场景刷新频率到 60 FPS,否则场景就只会在必要的时候进行重绘。 - * - * @method playOnFocus + * @en When {{executeInEditMode}} is set, this decorator will decide when a node with the component is on focus whether the editor should running in high FPS mode. + * @zh 当指定了 "executeInEditMode" 以后,playOnFocus 可以在选中当前组件所在的节点时,提高编辑器的场景刷新频率到 60 FPS,否则场景就只会在必要的时候进行重绘。 * @example * ```typescript * const {ccclass, playOnFocus, executeInEditMode} = cc._decorator; * - * @ccclass - * @executeInEditMode - * @playOnFocus + * @ccclass + * @executeInEditMode + * @playOnFocus * class CameraCtrl extends cc.Component { * // ... * } @@ -492,28 +482,26 @@ export const disallowMultiple = (DEV ? createEditorDecorator : createDummyDecora export const playOnFocus = (DEV ? createEditorDecorator : createDummyDecorator)(checkCtorArgument, 'playOnFocus'); /** - * 自定义当前组件在 **属性检查器** 中渲染时所用的网页 url。 - * - * @method inspector - * @param {String} url + * @en Use a customized inspector page in the **inspector** + * @zh 自定义当前组件在 **属性检查器** 中渲染时所用的 UI 页面描述。 + * @param url The url of the page definition in js * @example * ```typescript * const {ccclass, inspector} = cc._decorator; * - * @ccclass - * @inspector("packages://inspector/inspectors/comps/camera-ctrl.js") + * @ccclass + * @inspector("packages://inspector/inspectors/comps/camera-ctrl.js") * class NewScript extends cc.Component { * // ... * } * ``` */ -export const inspector = (DEV ? createEditorDecorator : createDummyDecorator)(checkStringArgument, 'inspector'); +export const inspector: (url: string) => Function = (DEV ? createEditorDecorator : createDummyDecorator)(checkStringArgument, 'inspector'); /** - * 自定义当前组件在编辑器中显示的图标 url。 - * - * @method icon - * @param {String} url + * @en Define the icon of the component. + * @zh 自定义当前组件在编辑器中显示的图标 url。 + * @param url * @private * @example * ```typescript @@ -526,117 +514,55 @@ export const inspector = (DEV ? createEditorDecorator : createDummyDecorator)(ch * } * ``` */ -export const icon = (DEV ? createEditorDecorator : createDummyDecorator)(checkStringArgument, 'icon'); +export const icon: (url: string) => Function = (DEV ? createEditorDecorator : createDummyDecorator)(checkStringArgument, 'icon'); /** - * 指定当前组件的帮助文档的 url,设置过后,在 **属性检查器** 中就会出现一个帮助图标,用户点击将打开指定的网页。 - * - * @method help - * @param {String} url + * @en Define the help documentation url, if given, the component section in the **inspector** will have a help documentation icon reference to the web page given. + * @zh 指定当前组件的帮助文档的 url,设置过后,在 **属性检查器** 中就会出现一个帮助图标,用户点击将打开指定的网页。 + * @param url The url of the help documentation * @example * ```typescript * const {ccclass, help} = cc._decorator; * - * @ccclass - * @help("app://docs/html/components/spine.html") + * @ccclass + * @help("app://docs/html/components/spine.html") * class NewScript extends cc.Component { * // ... * } * ``` */ -export const help = (DEV ? createEditorDecorator : createDummyDecorator)(checkStringArgument, 'help'); +export const help: (url: string) => Function = (DEV ? createEditorDecorator : createDummyDecorator)(checkStringArgument, 'help'); // Other Decorators /** - * @en - * NOTE:
- * The old mixins implemented in cc.Class(ES5) behaves exact the same as multiple inheritance. - * But since ES6, class constructor can't be function-called and class methods become non-enumerable, - * so we can not mix in ES6 Classes.
- * See:
- * [https://esdiscuss.org/topic/traits-are-now-impossible-in-es6-until-es7-since-rev32](https://esdiscuss.org/topic/traits-are-now-impossible-in-es6-until-es7-since-rev32)
- * One possible solution (but IDE unfriendly):
- * [http://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes](http://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes/)
- *
- * NOTE:
- * You must manually call mixins constructor, this is different from cc.Class(ES5). - * @zh - * *注意:
- * 在cc.Class(ES5)中实现的旧mixin的行为与多重继承完全相同。 - * 但是从ES6开始,类构造函数不能被函数调用,类方法变得不可枚举, - * 所以我们不能混合使用ES6类。
- * 参看:
- * [https://esdiscuss.org/topic/traits-are-now-impossible-in-es6-until-es7-since-rev32](https://esdiscuss.org/topic/traits-are-now-impossible-in-ES6-直到-ES7,因为-rev32)点击 - * 一种可能的解决方案(但对 IDE 不友好):
- * [http://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes](http://justinfagnani.com/2015/12/21/real-mixins-with-javascript-classes/)结果 - *
- * 注意:
- * 您必须手动调用mixins构造函数,这与cc.Class(ES5)不同。 - * - * @method mixins - * @param {Function} ...ctor - constructors to mix, only support ES5 constructors or classes defined by using `cc.Class`, - * not support ES6 Classes. - * @example - * ```typescript - * const {ccclass, mixins} = cc._decorator; - * - * class Animal { ... } - * - * const Fly = cc.Class({ - * constructor () { ... } - * }); - * - * @ccclass - * @mixins(cc.EventTarget, Fly) - * class Bird extends Animal { - * constructor () { - * super(); - * - * // You must manually call mixins constructor, this is different from cc.Class(ES5) - * cc.EventTarget.call(this); - * Fly.call(this); - * } - * // ... - * } - * ``` - */ -export function mixins (...constructors: Function[]) { - const mixins: Function[] = []; - for (let i = 0; i < constructors.length; i++) { - mixins[i] = constructors[i]; - } - return function (ctor) { - const cache = getClassCache(ctor, 'mixins'); - if (cache) { - getSubDict(cache, 'proto').mixins = mixins; - } - }; -} - -/** - * 将该属性标记为 cc 整数。 + * @en Declare the property as integer + * @zh 将该属性标记为整数。 */ export const integer = type(CCInteger); /** - * 将该属性标记为 cc 浮点数。 + * @en Declare the property as float + * @zh 将该属性标记为浮点数。 */ export const float = type(CCFloat); /** - * 将该属性标记为 cc 布尔值。 + * @en Declare the property as boolean + * @zh 将该属性标记为布尔值。 */ export const boolean = type(CCBoolean); /** - * 将该属性标记为 cc 字符串。 + * @en Declare the property as string + * @zh 将该属性标记为字符串。 */ export const string = type(CCString); /** - * 标记该属性的类型。 - * @param type 指定类型。 + * @en Declare the property as the given type + * @zh 标记该属性的类型。 + * @param type */ export function type (type: Function): PropertyDecorator; diff --git a/cocos/core/data/class.ts b/cocos/core/data/class.ts index b38995b213..47fae59b93 100644 --- a/cocos/core/data/class.ts +++ b/cocos/core/data/class.ts @@ -25,7 +25,7 @@ */ /** - * @category core/data + * @hidden */ // tslint:disable:only-arrow-functions @@ -894,95 +894,6 @@ function declareProperties (cls, className, properties, baseClass, mixins, es6?: }); } -/** - * @en Defines a CCClass using the given specification - * @zh 定义一个 CCClass,传入参数必须是一个包含类型参数的字面量对象 - * - * @method Class - * - * @param {Object} [options] - * @param {String} [options.name] - The class name used for serialization. - * @param {Function} [options.extends] - The base class. - * @param {Function} [options.ctor] - The constructor. - * @param {Function} [options.__ctor__] - The same as ctor, but less encapsulated. - * @param {Object} [options.properties] - The property definitions. - * @param {Object} [options.statics] - The static members. - * @param {Function[]} [options.mixins] - * - * @param {Object} [options.editor] - attributes for Component listed below. - * @param {Boolean} [options.editor.executeInEditMode=false] - Allows the current component to run in edit mode. By default, all components are executed only at runtime, meaning that they will not have their callback functions executed while the Editor is in edit mode. - * @param {Function} [options.editor.requireComponent] - Automatically add required component as a dependency. - * @param {String} [options.editor.menu] - The menu path to register a component to the editors "Component" menu. Eg. "Rendering/Camera". - * @param {Number} [options.editor.executionOrder=0] - The execution order of lifecycle methods for Component. Those less than 0 will execute before while those greater than 0 will execute after. The order will only affect onLoad, onEnable, start, update and lateUpdate while onDisable and onDestroy will not be affected. - * @param {Boolean} [options.editor.disallowMultiple] - If specified to a type, prevents Component of the same type (or subtype) to be added more than once to a Node. - * @param {Boolean} [options.editor.playOnFocus=false] - This property is only available when executeInEditMode is set. If specified, the editor's scene view will keep updating this node in 60 fps when it is selected, otherwise, it will update only if necessary. - * @param {String} [options.editor.inspector] - Customize the page url used by the current component to render in the Properties. - * @param {String} [options.editor.icon] - Customize the icon that the current component displays in the editor. - * @param {String} [options.editor.help] - The custom documentation URL - * - * @param {Function} [options.update] - lifecycle method for Component, see {{#crossLink "Component/update:method"}}{{/crossLink}} - * @param {Function} [options.lateUpdate] - lifecycle method for Component, see {{#crossLink "Component/lateUpdate:method"}}{{/crossLink}} - * @param {Function} [options.onLoad] - lifecycle method for Component, see {{#crossLink "Component/onLoad:method"}}{{/crossLink}} - * @param {Function} [options.start] - lifecycle method for Component, see {{#crossLink "Component/start:method"}}{{/crossLink}} - * @param {Function} [options.onEnable] - lifecycle method for Component, see {{#crossLink "Component/onEnable:method"}}{{/crossLink}} - * @param {Function} [options.onDisable] - lifecycle method for Component, see {{#crossLink "Component/onDisable:method"}}{{/crossLink}} - * @param {Function} [options.onDestroy] - lifecycle method for Component, see {{#crossLink "Component/onDestroy:method"}}{{/crossLink}} - * @param {Function} [options.onFocusInEditor] - lifecycle method for Component, see {{#crossLink "Component/onFocusInEditor:method"}}{{/crossLink}} - * @param {Function} [options.onLostFocusInEditor] - lifecycle method for Component, see {{#crossLink "Component/onLostFocusInEditor:method"}}{{/crossLink}} - * @param {Function} [options.resetInEditor] - lifecycle method for Component, see {{#crossLink "Component/resetInEditor:method"}}{{/crossLink}} - * @param {Function} [options.onRestore] - for Component only, see {{#crossLink "Component/onRestore:method"}}{{/crossLink}} - * @param {Function} [options._getLocalBounds] - for Component only, see {{#crossLink "Component/_getLocalBounds:method"}}{{/crossLink}} - * - * @return {Function} - the created class - * - * @example - * ```typescript - * // define base class - * var Node = cc.Class(); - * // define sub class - * var Sprite = cc.Class({ - * name: 'Sprite', - * extends: Node, - * - * ctor: function () { - * this.url = ""; - * this.id = 0; - * }, - * - * statics: { - * // define static members - * count: 0, - * getBounds: function (spriteList) { - * // compute bounds... - * } - * }, - * - * properties { - * width: { - * default: 128, - * type: 'Integer', - * tooltip: 'The width of sprite' - * }, - * height: 128, - * size: { - * get: function () { - * return cc.v2(this.width, this.height); - * } - * } - * }, - * - * load: function () { - * // load this.url... - * }; - * }); - * - * // instantiate - * - * var obj = new Sprite(); - * obj.url = 'sprite.png'; - * obj.load(); - * ``` - */ function CCClass (options) { options = options || {}; diff --git a/cocos/core/data/deserialize.ts b/cocos/core/data/deserialize.ts index 33599c57ec..57f0836836 100644 --- a/cocos/core/data/deserialize.ts +++ b/cocos/core/data/deserialize.ts @@ -25,7 +25,7 @@ */ /** - * @category core/data + * @hidden */ import { warnID } from '../platform/debug'; diff --git a/cocos/core/data/instantiate-jit.ts b/cocos/core/data/instantiate-jit.ts index ccfc743293..454caca621 100644 --- a/cocos/core/data/instantiate-jit.ts +++ b/cocos/core/data/instantiate-jit.ts @@ -25,7 +25,7 @@ */ /** - * @category core/data + * @hidden */ // Some helper methods for compile instantiation code diff --git a/cocos/core/data/instantiate.ts b/cocos/core/data/instantiate.ts index c3baee2f2c..9d32386bfe 100644 --- a/cocos/core/data/instantiate.ts +++ b/cocos/core/data/instantiate.ts @@ -34,6 +34,8 @@ import { CCObject } from './object'; import { js } from '../utils'; import { errorID, warn } from '../platform/debug'; import { DEV } from 'internal:constants'; +import Prefab from '../assets/prefab'; +import { Node } from '../scene-graph/node'; // @ts-ignore const Destroyed = CCObject.Flags.Destroyed; @@ -45,12 +47,9 @@ const objsToClearTmpVar: any = []; // used to reset _iN$t variable /** * @en Clones the object `original` and returns the clone, or instantiate a node from the Prefab. * @zh 克隆指定的任意类型的对象,或者从 Prefab 实例化出新节点。 - * * (Instantiate 时,function 和 dom 等非可序列化对象会直接保留原有引用,Asset 会直接进行浅拷贝,可序列化类型会进行深拷贝。) - * - * @method instantiate - * @param {Prefab|Node|Object} original - An existing object that you want to make a copy of. - * @return {Node|Object} the newly instantiated object + * @param original - An existing object that you want to make a copy of. + * @return {} the newly instantiated object * @example * ```typescript * // instantiate node from prefab @@ -63,7 +62,7 @@ const objsToClearTmpVar: any = []; // used to reset _iN$t variable * node.parent = scene; * ``` */ -function instantiate (original, internal_force?) { +function instantiate (original: Prefab|Node|Object, internal_force?: Node|Object): Node | null { if (!internal_force) { if (typeof original !== 'object' || Array.isArray(original)) { if (DEV) { @@ -97,8 +96,10 @@ function instantiate (original, internal_force?) { // @param {Object} [instantiated] - If supplied, _instantiate just need to initialize the instantiated object, // no need to create new object by itself. // @returns {Object} - the instantiated object + // @ts-ignore if (original._instantiate) { cc.game._isCloning = true; + // @ts-ignore clone = original._instantiate(); cc.game._isCloning = false; return clone; @@ -118,16 +119,15 @@ function instantiate (original, internal_force?) { return clone; } -/** +/* * @en * Do instantiate object, the object to instantiate must be non-nil. * @zh * 这是一个通用的 instantiate 方法,可能效率比较低。 * 之后可以给各种类型重写快速实例化的特殊实现,但应该在单元测试中将结果和这个方法的结果进行对比。 * 值得注意的是,这个方法不可重入。 - * - * @param {Object} obj - 该方法仅供内部使用,用户需负责保证参数合法。什么参数是合法的请参考 cc.instantiate 的实现。 - * @param {Node} [parent] - 只有在该对象下的场景物体会被克隆。 + * @param obj - 该方法仅供内部使用,用户需负责保证参数合法。什么参数是合法的请参考 cc.instantiate 的实现。 + * @param parent - 只有在该对象下的场景物体会被克隆。 * @return {Object} * @private */ diff --git a/cocos/core/data/object.ts b/cocos/core/data/object.ts index 4fb055f3fc..2abd9f68d0 100644 --- a/cocos/core/data/object.ts +++ b/cocos/core/data/object.ts @@ -155,9 +155,6 @@ function compileDestruct (obj, ctor) { * The base class of most of all the objects in Fireball. * @zh * 大部分对象的基类。 - * @class Object - * - * @main * @private */ class CCObject { @@ -235,8 +232,6 @@ class CCObject { * 当一个对象的 `destroy` 调用以后,会在这一帧结束后才真正销毁。
* 因此从下一帧开始 `isValid` 就会返回 false,而当前帧内 `isValid` 仍然会是 true。
* 如果希望判断当前帧是否调用过 `destroy`,请使用 `cc.isValid(obj, true)`,不过这往往是特殊的业务需求引起的,通常情况下不需要这样。 - * - * @property {Boolean} isValid * @default true * @readOnly * @example @@ -250,7 +245,7 @@ class CCObject { * cc.log(node.isValid); // false, destroyed in the end of last frame * ``` */ - get isValid () { + get isValid (): boolean { return !(this._objFlags & Destroyed); } @@ -264,7 +259,7 @@ class CCObject { * 销毁该对象,并释放所有它对其它对象的引用。
* 实际销毁操作会延迟到当前帧渲染前执行。从下一帧开始,该对象将不再可用。 * 您可以在访问对象之前使用 cc.isValid(obj) 来检查对象是否已被销毁。 - * @return {Boolean} whether it is the first time the destroy being called + * @return whether it is the first time the destroy being called * @example * ``` * obj.destroy(); @@ -380,7 +375,7 @@ if (EDITOR) { } }); - /** + /* * The customized serialization for this object. (Editor Only) * @method _serialize * @param {Boolean} exporting @@ -391,7 +386,7 @@ if (EDITOR) { prototype._serialize = null; } -/** +/* * Init this object from the custom serialized data. * @method _deserialize * @param {Object} data - the serialized json data @@ -400,7 +395,7 @@ if (EDITOR) { */ // @ts-ignore prototype._deserialize = null; -/** +/* * Called before the object being destroyed. * @method _onPreDestroy * @private @@ -413,7 +408,6 @@ CCClass.fastDefine('cc.Object', CCObject, { _name: '', _objFlags: 0 }); /** * Bit mask that controls object states. * @enum Object.Flags - * @static * @private */ js.value(CCObject, 'Flags', { @@ -424,14 +418,12 @@ js.value(CCObject, 'Flags', { /** * @en The object will not be saved. * @zh 该对象将不会被保存。 - * @property {Number} DontSave */ DontSave, /** * @en The object will not be saved when building a player. * @zh 构建项目时,该对象将不会被保存。 - * @property {Number} EditorOnly */ EditorOnly, @@ -454,7 +446,6 @@ js.value(CCObject, 'Flags', { /** * @en The node is deactivating. * @zh 节点正在反激活的过程中。 - * @property Deactivating * @private */ Deactivating, @@ -462,8 +453,6 @@ js.value(CCObject, 'Flags', { /** * @en The lock node, when the node is locked, cannot be clicked in the scene. * @zh 锁定节点,锁定后场景内不能点击 - * - * @property LockedInEditor * @private */ LockedInEditor, @@ -484,7 +473,6 @@ js.value(CCObject, 'Flags', { /// ** // * @en This flag is readonly, it can only be used as an argument of scene.addEntity() or Entity.createWithFlags(). // * @zh 该标记只读,它只能被用作 scene.addEntity()的一个参数。 - // * @property {Number} HideInEditor // */ HideInHierarchy, @@ -495,7 +483,6 @@ js.value(CCObject, 'Flags', { // * @zh // * 在游戏视图,层级,场景视图等等...中隐藏该对象。 // * 该标记只读,它只能被用作 scene.addEntity()的一个参数。 - // * @property {Number} Hide // */ // Hide: Hide, @@ -518,11 +505,7 @@ js.value(CCObject, 'Flags', { IsSizeLocked, }); -/** - * @module cc - */ - -/** +/* * @en * Checks whether the object is non-nil and not yet destroyed.
* When an object's `destroy` is called, it is actually destroyed after the end of this frame. diff --git a/cocos/core/event/callbacks-invoker.ts b/cocos/core/event/callbacks-invoker.ts index d8bab4b836..50f5de5526 100644 --- a/cocos/core/event/callbacks-invoker.ts +++ b/cocos/core/event/callbacks-invoker.ts @@ -297,9 +297,13 @@ export class CallbacksInvoker { * @zh 派发一个指定事件,并传递需要的参数 * @en Trigger an event directly with the event name and necessary arguments. * @param key - event type - * @param args - Arguments when the event triggered + * @param arg0 - The first argument to be passed to the callback + * @param arg1 - The second argument to be passed to the callback + * @param arg2 - The third argument to be passed to the callback + * @param arg3 - The fourth argument to be passed to the callback + * @param arg4 - The fifth argument to be passed to the callback */ - public emit (key: string, ...args: any[]) { + public emit (key: string, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any) { const list: CallbackList = this._callbackTable[key]!; if (list) { const rootInvoker = !list.isInvoking; @@ -316,10 +320,10 @@ export class CallbacksInvoker { this.off(key, callback, target); } if (target) { - callback.call(target, ...args); + callback.call(target, arg0, arg1, arg2, arg3, arg4); } else { - callback(...args); + callback(arg0, arg1, arg2, arg3, arg4); } } } diff --git a/cocos/core/event/event-target.ts b/cocos/core/event/event-target.ts index c133311362..3da7a79821 100644 --- a/cocos/core/event/event-target.ts +++ b/cocos/core/event/event-target.ts @@ -33,6 +33,17 @@ import { Eventify } from './eventify'; // eslint-disable-next-line @typescript-eslint/no-extraneous-class class Empty {}; +/** + * @en + * EventTarget is an object to which an event is dispatched when something has occurred. + * [[Node]]s are the most common event targets, but other objects can be event targets too. + * If a class cannot extend from EventTarget, it can consider using [[Eventify]]. + * + * @zh + * 事件目标是具有注册监听器、派发事件能力的类,[[Node]] 是最常见的事件目标, + * 但是其他类也可以继承自事件目标以获得管理监听器和派发事件的能力。 + * 如果无法继承自 EventTarget,也可以使用 [[Eventify]] + */ export const EventTarget = Eventify(Empty); export type EventTarget = InstanceType; diff --git a/cocos/core/event/eventify.ts b/cocos/core/event/eventify.ts index ed78d59b7c..90b3bd3c7f 100644 --- a/cocos/core/event/eventify.ts +++ b/cocos/core/event/eventify.ts @@ -1,3 +1,7 @@ +/** + * @category event + */ + import { fastRemove } from '../utils/array'; import { CallbacksInvoker } from './callbacks-invoker'; @@ -105,19 +109,20 @@ export interface IEventified { * @param type - event type * @param args - Arguments when the event triggered */ - emit (type: EventType, ...args: any[]): void; + emit (type: EventType, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any): void; } /** - * 生成一个类,该类继承自指定的基类,并实现了 `IEventified` 的所有接口。 - * @param base 基类。 + * @en Generate a new class from the given base class, after polyfill all functionalities in [[IEventified]] as if it's extended from [[EventTarget]] + * @zh 生成一个类,该类继承自指定的基类,并以和 [[EventTarget]] 等同的方式实现了 [[IEventified]] 的所有接口。 + * @param base The base class * @example * ```ts * class Base { say() { console.log('Hello!'); } } * class MyClass extends Eventify(Base) { } * function (o: MyClass) { - * o.say(); // Ok: 继承自 `Base` - * o.emit('sing', 'The ghost'); // Ok: `MyClass`类的对象实现了 IEventified + * o.say(); // Ok: Extend from `Base` + * o.emit('sing', 'The ghost'); // Ok: `MyClass` implements IEventified * } * ``` */ @@ -125,10 +130,6 @@ export function Eventify (base: Constructor): Constructor (base: Constructor): Constructor +/* + * @en Convert a resources by finding its real url with uuid, otherwise we will use the uuid or raw url as its url
* So we gurantee there will be url in result - * @zh - * 通过使用 uuid 查找资源的真实 url 来转换资源,否则将使用 uuid 或原始 url 作为其 url
+ * @zh 通过使用 uuid 查找资源的真实 url 来转换资源,否则将使用 uuid 或原始 url 作为其 url
* 所以可以保证结果中会有 url * @param res */ @@ -98,48 +100,40 @@ const _sharedResources: any = []; const _sharedList: any = []; /** - * @en - * Loader for resource loading process. It's a singleton object. - * @zh - * 资源加载程序,这是一个单例对象。 + * @en Loader for resource loading process. The engine automatically initialize its singleton object {{loader}}. + * @zh 资源加载管理器,引擎会自动创建一个单例对象 {{loader}}。 */ export class CCLoader extends Pipeline { /** - * @en - * Gets a new XMLHttpRequest instance. - * @zh - * 获取一个新的 XMLHttpRequest 的实例。 + * @en Gets a new XMLHttpRequest instance. + * @zh 获取一个新的 XMLHttpRequest 的实例。 */ public getXMLHttpRequest: Function; /** - * @en - * The asset loader in cc.loader's pipeline, it's by default the first pipe.
+ * @en The asset loader in loader's pipeline, it's by default the first pipe.
* It's used to identify an asset's type, and determine how to download it. - * @zh - * cc.loader 中的资源加载器,默认情况下是最先加载的。
+ * @zh loader 中的资源加载器,默认情况下是最先加载的。
* 用于标识资源的类型,并确定如何加载此资源。 */ public assetLoader: AssetLoader; /** - * @en - * The md5 pipe in cc.loader's pipeline, it could be absent if the project isn't build with md5 option.
+ * @en The md5 pipe in loader's pipeline, it could be absent if the project isn't build with md5 option.
* It's used to modify the url to the real downloadable url with md5 suffix. - * @zh - * cc.loader 中的 md5 加载管道,如果项目没有使用 md5 构建,则此项可能不存在。
+ * @zh loader 中的 md5 加载管道,如果项目没有使用 md5 构建,则此项可能不存在。
* 用于修改带有 md5 后缀的真实可下载的 URL 。 */ public md5Pipe: null; /** * @en - * The downloader in cc.loader's pipeline, it's by default the second pipe.
+ * The downloader in loader's pipeline, it's by default the second pipe.
* It's used to download files with several handlers: pure text, image, script, audio, font, uuid.
* You can add your own download function with addDownloadHandlers * @zh - * cc.loader 中的资源下载程序,默认情况下是第二个加载的。
+ * loader 中的资源下载程序,默认情况下是第二个加载的。
* 它用于下载带有多个处理程序的文件:纯文本,图像,脚本,音频,字体,uuid。
* 您可以使用 addDownloadHandlers 来添加自己的下载函数 */ @@ -147,23 +141,27 @@ export class CCLoader extends Pipeline { /** * @en - * The loader in cc.loader's pipeline, it's by default the third pipe.
+ * The loader in loader's pipeline, it's by default the third pipe.
* It's used to parse downloaded content with several handlers: JSON, image, plist, fnt, uuid.
* You can add your own download function with addLoadHandlers * @zh - * cc.loader 中的资源下载程序,默认情况下是第三个加载的。
+ * loader 中的资源下载程序,默认情况下是第三个加载的。
* 它用于解析下载的内容及多个处理程序的文件:纯文本,图像,脚本,音频,字体,uuid。
* 您可以使用 addLoadHandlers 来添加自己的下载函数 */ public loader: Loader; - public onProgress: null; - public _assetTables: any; + /** + * @en The default progression callback during the loading process, + * if no progression callback is passed to {{load}} function, then this default callback will be used. + * @zh Loader 默认的进度回调函数,如果在调用 {{load}} 函数时没有指定进度回调函数的话,会调用默认进度回调函数。 + */ + public onProgress: Function | null; + public _assetTables: any; private _autoReleaseSetting: any; private _releasedAssetChecker_DEBUG: any; constructor () { - const assetLoader = new AssetLoader(); const downloader = new Downloader(); // tslint:disable-next-line: no-shadowed-letiable @@ -175,14 +173,11 @@ export class CCLoader extends Pipeline { loader, ]); - this.getXMLHttpRequest = getXMLHttpRequest; + this.getXMLHttpRequest = getXMLHttpRequest; this.assetLoader = assetLoader; - this.md5Pipe = null; - this.downloader = downloader; - this.loader = loader; this.onProgress = null; @@ -196,6 +191,11 @@ export class CCLoader extends Pipeline { } } + /** + * @en Initialize with director + * @zh 使用 {{director}} 初始化 + * @param director The director instance of engine + */ public init (director) { if (DEBUG) { const self = this; @@ -206,46 +206,39 @@ export class CCLoader extends Pipeline { } /** - * @en - * Add custom supported types handler or modify existing type handler for download process. - * @zh - * 为下载程序添加自定义支持的类型处理程序或修改现有的类型处理程序。 + * @en Add custom supported types handler or modify existing type handler for download process. + * @zh 为下载程序添加自定义支持的类型处理程序或修改现有的类型处理程序。 * @example * ```typescript - * cc.loader.addDownloadHandlers({ + * loader.addDownloadHandlers({ * // This will match all url with `.scene` extension or all url with `scene` type * 'scene' : function (url, callback) {} * }); * ``` - * @param extMap 具有相应处理程序的自定义支持类型 + * @param extMap Handlers for corresponding type in a map */ - public addDownloadHandlers (extMap: Object) { + public addDownloadHandlers (extMap: Map) { this.downloader.addHandlers(extMap); } /** - * @en - * Add custom supported types handler or modify existing type handler for load process. - * @zh - * 为加载程序添加自定义支持的类型处理程序或修改现有的类型处理程序。 + * @en Add custom supported types handler or modify existing type handler for load process. + * @zh 为加载程序添加自定义支持的类型处理程序或修改现有的类型处理程序。 * @example * ```typescript - * cc.loader.addLoadHandlers({ + * loader.addLoadHandlers({ * // This will match all url with `.scene` extension or all url with `scene` type * 'scene' : function (url, callback) {} * }); * ``` - * @method addLoadHandlers - * @param extMap 具有相应处理程序的自定义支持类型 + * @param extMap Handlers for corresponding type in a map */ - public addLoadHandlers (extMap: Object) { + public addLoadHandlers (extMap: Map) { this.loader.addHandlers(extMap); } // tslint:disable: max-line-length - // load(resources: string|string[]|{uuid?: string, url?: string, type?: string}, completeCallback?: Function): void - // load(resources: string|string[]|{uuid?: string, url?: string, type?: string}, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: Function|null): void /** * @en * Load resources with a progression callback and a complete callback.
@@ -259,19 +252,19 @@ export class CCLoader extends Pipeline {      * 唯一的区别是当用户将单个 URL 作为资源传递时,完整的回调将其结果直接设置为第二个参数。 * @example * ```TypeScript - * cc.loader.load('a.png', function (err, tex) { + * loader.load('a.png', function (err, tex) { * cc.log('Result should be a texture: ' + (tex instanceof cc.Texture2D)); * }); * - * cc.loader.load('http://example.com/a.png', function (err, tex) { + * loader.load('http://example.com/a.png', function (err, tex) { * cc.log('Should load a texture from external url: ' + (tex instanceof cc.Texture2D)); * }); * - * cc.loader.load({url: 'http://example.com/getImageREST?file=a.png', type: 'png'}, function (err, tex) { + * loader.load({url: 'http://example.com/getImageREST?file=a.png', type: 'png'}, function (err, tex) { * cc.log('Should load a texture from RESTful API by specify the type: ' + (tex instanceof cc.Texture2D)); * }); * - * cc.loader.load(['a.png', 'b.json'], function (errors, results) { + * loader.load(['a.png', 'b.json'], function (errors, results) { * if (errors) { * for (let i = 0; i < errors.length; i++) { * cc.log('Error url [' + errors[i] + ']: ' + results.getError(errors[i])); @@ -281,17 +274,16 @@ export class CCLoader extends Pipeline { * let bJsonObj = results.getContent('b.json'); * }); * ``` - * @method load - * @param {String|String[]|Object} resources - Url 列表数组 - * @param {Function} progressCallback - 当进度改变时调用的回调函数 + * @param resources - Url list or load request list + * @param progressCallback - Progression callback * @param {Number} progressCallback.completedCount - The number of the items that are already completed * @param {Number} progressCallback.totalCount - The total number of the items * @param {Object} progressCallback.item - The latest item which flow out the pipeline - * @param {Function} completeCallback - 当所有资源加载完毕后调用的回调函数 + * @param completeCallback - Completion callback */ - public load (resources, progressCallback, completeCallback?) { + public load (resources: string|string[]|Object, progressCallback?: Function|null, completeCallback?: Function|null) { if (DEV && !resources) { - return cc.error('[cc.loader.load] resources must be non-nil.'); + return error('[loader.load] resources must be non-nil.'); } if (completeCallback === undefined) { @@ -301,23 +293,27 @@ export class CCLoader extends Pipeline { const self = this; let singleRes: Boolean = false; + let resList: Array; let res; - if (!(resources instanceof Array)) { + if (resources instanceof Array) { + resList = resources; + } + else { if (resources) { singleRes = true; - resources = [resources]; + resList = [resources]; } else { - resources = []; + resList = []; } } _sharedResources.length = 0; // tslint:disable-next-line: prefer-for-of - for (let i = 0; i < resources.length; ++i) { - const resource = resources[i]; + for (let i = 0; i < resList.length; ++i) { + const resource: any = resList[i]; // Backward compatibility if (resource && resource.id) { - cc.warnID(4920, resource.id); + warnID(4920, resource.id); if (!resource.uuid && !resource.url) { resource.url = resource.id; } @@ -352,10 +348,8 @@ export class CCLoader extends Pipeline { } /** - * @en - * See: [[Pipeline.flowInDeps]] - * @zh - * 参考:[[Pipeline.flowInDeps]] + * @en See: {{Pipeline.flowInDeps}} + * @zh 参考:{{Pipeline.flowInDeps}} */ public flowInDeps (owner, urlList, callback) { _sharedList.length = 0; @@ -420,39 +414,29 @@ export class CCLoader extends Pipeline { completeCallback: LoadCompleteCallback, ); - // @typescript - // loadRes(url: string, type: typeof cc.Asset, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any) => void)|null): void - // loadRes(url: string, type: typeof cc.Asset, completeCallback: (error: Error, resource: any) => void): void - // loadRes(url: string, type: typeof cc.Asset): void - // loadRes(url: string, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any) => void)|null): void - // loadRes(url: string, completeCallback: (error: Error, resource: any) => void): void - // loadRes(url: string): void - /** * @en - * Load resources from the "resources" folder inside the "assets" folder of your project.
+ * Load assets from the "resources" folder inside the "assets" folder of your project.
*
* Note: All asset URLs in Creator use forward slashes, URLs using backslashes will not work. * @zh * 从项目的 “assets” 文件夹下的 “resources” 文件夹中加载资源
*
* 注意:Creator 中的所有资源 URL 都使用正斜杠,使用反斜杠的 URL 将不起作用。 - * @method loadRes - * @param {String} url - 目标资源的 URL
- * URl 相对于 “resources” 文件夹,必须省略文件扩展名。 - * @param {Function} type - 如果提供此参数,则将仅加载此类型的资源。 - * @param {Function} progressCallback - 当进度改变时调用的回调函数 + * @param url - The url of the asset to be loaded, this url should be related path without file extension to the `resources` folder. + * @param type - If type is provided, only asset for correspond type will be loaded + * @param progressCallback - Progression callback * @param {Number} progressCallback.completedCount - The number of the items that are already completed. * @param {Number} progressCallback.totalCount - The total number of the items. * @param {Object} progressCallback.item - The latest item which flow out the pipeline. - * @param {Function} completeCallback - 当所有资源加载完毕后调用的回调函数 + * @param completeCallback - Completion callback * @param {Error} completeCallback.error - The error info or null if loaded successfully. * @param {Object} completeCallback.resource - The loaded resource if it can be found otherwise returns null. * * @example * ```typescript * // load the prefab (project/assets/resources/misc/character/cocos) from resources folder - * cc.loader.loadRes('misc/character/cocos', function (err, prefab) { + * loader.loadRes('misc/character/cocos', function (err, prefab) { * if (err) { * cc.error(err.message || err); * return; @@ -461,7 +445,7 @@ export class CCLoader extends Pipeline { * }); * * // load the sprite frame of (project/assets/resources/imgs/cocos.png) from resources folder - * cc.loader.loadRes('imgs/cocos', cc.SpriteFrame, function (err, spriteFrame) { + * loader.loadRes('imgs/cocos', cc.SpriteFrame, function (err, spriteFrame) { * if (err) { * cc.error(err.message || err); * return; @@ -470,7 +454,7 @@ export class CCLoader extends Pipeline { * }); * ``` */ - public loadRes (url: String, type: Function, mount: string | Function, progressCallback?: Function, completeCallback?: Function) { + public loadRes (url: string, type: Function, mount: string | Function, progressCallback?: Function, completeCallback?: Function) { if (arguments.length !== 5) { completeCallback = progressCallback; progressCallback = mount as Function; @@ -504,14 +488,6 @@ export class CCLoader extends Pipeline { } } - // @typescript - // loadResDir(url: string, type: typeof cc.Asset, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any[], urls: string[]) => void)|null): void - // loadResDir(url: string, type: typeof cc.Asset, completeCallback: (error: Error, resource: any[], urls: string[]) => void): void - // loadResDir(url: string, type: typeof cc.Asset): void - // loadResDir(url: string, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any[], urls: string[]) => void)|null): void - // loadResDir(url: string, completeCallback: (error: Error, resource: any[], urls: string[]) => void): void - // loadResDir(url: string): void - /** * @en * Load all assets in a folder inside the "assets/resources" folder of your project.
@@ -521,25 +497,23 @@ export class CCLoader extends Pipeline { * 将所有资产加载到项目 “assets / resources” 文件夹中      *
* 注意:Creator 中的所有资源 URL 都使用正斜杠,使用反斜杠的 URL 将不起作用。 - * @method loadResDir - * @param {String} url - 目标文件夹的 URL
- * URl 相对于 “resources” 文件夹,必须省略文件扩展名。 - * @param {Function} type - 如果提供此参数,则将仅加载此类型的资源。 - * @param {Function} progressCallback - 当进度改变时调用的回调函数 + * @param url The url of the directory to be loaded, this url should be related path to the `resources` folder. + * @param type - If type is provided, only assets for correspond type will be loaded + * @param progressCallback - Progression callback * @param {Number} progressCallback.completedCount - The number of the items that are already completed. * @param {Number} progressCallback.totalCount - The total number of the items. * @param {Object} progressCallback.item - The latest item which flow out the pipeline. - * @param {Function} completeCallback - 当所有资源加载完毕后或者发生错误时调用的回调函数 + * @param completeCallback - Completion callback * @param {Error} completeCallback.error - If one of the asset failed, the complete callback is immediately called * with the error. If all assets are loaded successfully, error will be null. * @param {Asset[]|Array} completeCallback.assets - An array of all loaded assets. * If nothing to load, assets will be an empty array. - * @param {String[]} completeCallback.urls - An array that lists all the URLs of loaded assets. + * @param {string[]} completeCallback.urls - An array that lists all the URLs of loaded assets. * * @example * ```typescript * // load the texture (resources/imgs/cocos.png) and the corresponding sprite frame - * cc.loader.loadResDir('imgs/cocos', function (err, assets) { + * loader.loadResDir('imgs/cocos', function (err, assets) { * if (err) { * cc.error(err); * return; @@ -549,19 +523,19 @@ export class CCLoader extends Pipeline { * }); * * // load all textures in "resources/imgs/" - * cc.loader.loadResDir('imgs', cc.Texture2D, function (err, textures) { + * loader.loadResDir('imgs', cc.Texture2D, function (err, textures) { * let texture1 = textures[0]; * let texture2 = textures[1]; * }); * * // load all JSONs in "resources/data/" - * cc.loader.loadResDir('data', function (err, objects, urls) { + * loader.loadResDir('data', function (err, objects, urls) { * let data = objects[0]; * let url = urls[0]; * }); * ``` */ - public loadResDir (url: String, type?: Function, mount?, progressCallback?: Function, completeCallback?: Function) { + public loadResDir (url: string, type?: Function, mount?, progressCallback?: Function, completeCallback?: Function) { if (arguments.length !== 5) { completeCallback = progressCallback; progressCallback = mount; @@ -582,7 +556,7 @@ export class CCLoader extends Pipeline { // To show users the exact structure in asset panel, we need to return the spriteFrame assets in spriteAtlas const assetResLength = assetRes.length; for (let i = 0; i < assetResLength; ++i) { - if (assetRes[i] instanceof cc.SpriteAtlas) { + if (assetRes[i] instanceof SpriteAtlas) { const spriteFrames = assetRes[i].getSpriteFrames(); // tslint:disable: forin for (const k in spriteFrames) { @@ -600,28 +574,17 @@ export class CCLoader extends Pipeline { }, urls); } - // * @typescript - // * loadResArray(url: string[], type: typeof cc.Asset, progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any[]) => void)|null): void - // * loadResArray(url: string[], type: typeof cc.Asset, completeCallback: (error: Error, resource: any[]) => void): void - // * loadResArray(url: string[], type: typeof cc.Asset): void - // * loadResArray(url: string[], progressCallback: (completedCount: number, totalCount: number, item: any) => void, completeCallback: ((error: Error, resource: any[]) => void)|null): void - // * loadResArray(url: string[], completeCallback: (error: Error, resource: any[]) => void): void - // * loadResArray(url: string[]): void /** - * @en - * This method is like [[loadRes]] except that it accepts array of url. - * @zh - * 此方法除了接受 URL 数组参数外,与 [[loadRes]] 方法相同。 + * @en This method is like [[loadRes]] except that it accepts array of url. + * @zh 此方法除了接受 URL 数组参数外,与 [[loadRes]] 方法相同。 * - * @method loadResArray - * @param {String[]} urls - 目标资源的 URL 数组。 - * URl 为相对于 “resources” 文件夹的,且必须省略文件扩展名。 - * @param {Function} type - 如果提供此参数,则将仅加载此类型的资源。 - * @param {Function} progressCallback - 当进度改变时调用的回调函数 + * @param url The url array of assets to be loaded, this url should be related path without extension to the `resources` folder. + * @param type - If type is provided, only assets for correspond type will be loaded + * @param progressCallback - Progression callback * @param {Number} progressCallback.completedCount - The number of the items that are already completed. * @param {Number} progressCallback.totalCount - The total number of the items. * @param {Object} progressCallback.item - The latest item which flow out the pipeline. - * @param {Function} completeCallback - 当所有资源加载完毕后或者发生错误时调用的回调函数 + * @param completeCallback - Completion callback * @param {Error} completeCallback.error - If one of the asset failed, the complete callback is immediately called * with the error. If all assets are loaded successfully, error will be null. * @param {Asset[]|Array} completeCallback.assets - An array of all loaded assets. @@ -631,7 +594,7 @@ export class CCLoader extends Pipeline { * // load the SpriteFrames from resources folder * let spriteFrames; * let urls = ['misc/characters/character_01', 'misc/weapons/weapons_01']; - * cc.loader.loadResArray(urls, cc.SpriteFrame, function (err, assets) { + * loader.loadResArray(urls, cc.SpriteFrame, function (err, assets) { * if (err) { * cc.error(err); * return; @@ -641,7 +604,7 @@ export class CCLoader extends Pipeline { * }); * ``` */ - public loadResArray (urls: String[], type?: Function, mount?, progressCallback?: Function, completeCallback?: Function) { + public loadResArray (urls: string[], type?: Function, mount?, progressCallback?: Function, completeCallback?: Function) { if (arguments.length !== 5) { completeCallback = progressCallback; progressCallback = mount; @@ -680,10 +643,8 @@ export class CCLoader extends Pipeline { * 当使用 [[load]] 或 [[loadRes]] 来加载资源时,
* URL 将是资源的唯一标识。
* 在完成加载之后,你可以通过将 URL 传递给此 API 来获取它们。 - * @method getRes - * @param {String} url - * @param {Function} type - 如果提供此参数,则将仅返回此类型的资源。 - * @returns {*} + * @param url The asset url, it should be related path without extension to the `resources` folder. + * @param type If type is provided, the asset for correspond type will be returned */ public getRes (url: string, type?: Function): T | null { let item = this._cache[url]; @@ -704,10 +665,8 @@ export class CCLoader extends Pipeline { } /** - * @en - * Get total resources count in loader. - * @zh - * 获取加载的总资源数量 + * @en Get total resources count in loader. + * @zh 获取加载的总资源数量 */ public getResCount (): Number { return Object.keys(this._cache).length; @@ -730,23 +689,21 @@ export class CCLoader extends Pipeline { * @example * ```typescript * // Release all dependencies of a loaded prefab - * let deps = cc.loader.getDependsRecursively(prefab); - * cc.loader.release(deps); + * let deps = loader.getDependsRecursively(prefab); + * loader.release(deps); * // Retrieve all dependent textures - * let deps = cc.loader.getDependsRecursively('prefabs/sample'); + * let deps = loader.getDependsRecursively('prefabs/sample'); * let textures = []; * for (let i = 0; i < deps.length; ++i) { - * let item = cc.loader.getRes(deps[i]); + * let item = loader.getRes(deps[i]); * if (item instanceof cc.Texture2D) { * textures.push(item); * } * } * ``` - * @method getDependsRecursively - * @param {Asset|RawAsset|String} owner - 资源本身或者是资源的 url 或者是资源的 uuid - * @return {Array} + * @param owner - The asset itself or the asset url or the asset uuid */ - public getDependsRecursively (owner: Asset|RawAsset|String) { + public getDependsRecursively (owner: Asset|RawAsset|string): Array { if (owner) { const key = this._getReferenceKey(owner); const assets = getDependsRecursively(key); @@ -761,14 +718,14 @@ export class CCLoader extends Pipeline { /** * @en * Release the content of an asset or an array of assets by uuid.
- * Start from v1.3, this method will not only remove the cache of the asset in loader, but also clean up its content.
+ * This method will not only remove the cache of the asset in loader, but also clean up its content.
* For example, if you release a texture, the texture asset and its gl texture data will be freed up.
* In complexe project, you can use this function with [[getDependsRecursively]] to free up memory in critical circumstances.
* Notice, this method may cause the texture to be unusable, if there are still other nodes use the same texture, they may turn to black and report gl errors.
* If you only want to remove the cache of an asset, please use [[Pipeline.removeItem]] * @zh * 通过 id(通常是资源 url)来释放一个资源或者一个资源数组。
- * 从 v1.3 开始,这个方法不仅会从 loader 中删除资源的缓存引用,还会清理它的资源内容。
+ * 这个方法不仅会从 loader 中删除资源的缓存引用,还会清理它的资源内容。
* 比如说,当你释放一个 texture 资源,这个 texture 和它的 gl 贴图数据都会被释放。
* 在复杂项目中,我们建议你结合 [[getDependsRecursively]] 来使用,便于在设备内存告急的情况下更快地释放不再需要的资源的内存。
* 注意,这个函数可能会导致资源贴图或资源所依赖的贴图不可用,如果场景中存在节点仍然依赖同样的贴图,它们可能会变黑并报 GL 错误。
@@ -777,25 +734,24 @@ export class CCLoader extends Pipeline { * @example * ```typescript * // Release a texture which is no longer need - * cc.loader.release(texture); + * loader.release(texture); * // Release all dependencies of a loaded prefab - * let deps = cc.loader.getDependsRecursively('prefabs/sample'); - * cc.loader.release(deps); + * let deps = loader.getDependsRecursively('prefabs/sample'); + * loader.release(deps); * // If there is no instance of this prefab in the scene, the prefab and its dependencies like textures, sprite frames, etc, will be freed up. * // If you have some other nodes share a texture in this prefab, you can skip it in two ways: * // 1. Forbid auto release a texture before release - * cc.loader.setAutoRelease(texture2d, false); + * loader.setAutoRelease(texture2d, false); * // 2. Remove it from the dependencies array - * let deps = cc.loader.getDependsRecursively('prefabs/sample'); + * let deps = loader.getDependsRecursively('prefabs/sample'); * let index = deps.indexOf(texture2d._uuid); * if (index !== -1) * deps.splice(index, 1); - * cc.loader.release(deps); + * loader.release(deps); * ``` - * @method release - * @param {Asset|RawAsset|String|Array} asset + * @param asset Asset or assets to be released */ - public release (asset) { + public release (asset: Asset|RawAsset|string|Array) { if (Array.isArray(asset)) { for (let i = 0; i < asset.length; i++) { const key = asset[i]; @@ -808,7 +764,7 @@ export class CCLoader extends Pipeline { if (item) { const removed = this.removeItem(id); asset = item.content; - if (asset instanceof cc.Asset) { + if (asset instanceof Asset) { const nativeUrl = asset.nativeUrl; if (nativeUrl) { this.release(nativeUrl); // uncache loading item of native asset @@ -823,11 +779,9 @@ export class CCLoader extends Pipeline { } /** - * @en Release the asset by its object. Refer to [[release]] for detailed informations. - * @zh 通过资源对象自身来释放资源。详细信息请参考 [[release]] - * - * @method releaseAsset - * @param {Asset} asset + * @en Release the asset by its object. Refer to {{release}} for detailed informations. + * @zh 通过资源对象自身来释放资源。详细信息请参考 {{release}} + * @param asset The asset to be released */ public releaseAsset (asset: Asset) { const uuid = asset._uuid; @@ -837,36 +791,28 @@ export class CCLoader extends Pipeline { } /** - * @en - * Release the asset loaded by [[loadRes]]. Refer to [[release]] for detailed informations. - * @zh - * 释放通过 [[loadRes]] 加载的资源。详细信息请参考 [[release]] - * - * @method releaseRes - * @param {String} url - * @param {Function} type - 如果提供此参数,则将仅释放此类型的资源。 + * @en Release the asset loaded by {{loadRes}}. Refer to {{release}} for detailed informations. + * @zh 释放通过 {{loadRes}} 加载的资源。详细信息请参考 {{release}} + * @param url The asset url, it should be related path without extension to the `resources` folder. + * @param type If type is provided, the asset for correspond type will be returned */ - public releaseRes (url: String, type?: Function, mount?) { + public releaseRes (url: string, type?: Function, mount?) { const uuid = this._getResUuid(url, type, mount, true); if (uuid) { this.release(uuid); } else { - cc.errorID(4914, url); + errorID(4914, url); } } /** - * @en - * Release the all assets loaded by [[loadResDir]]. Refer to [[release]] for detailed informations. - * @zh - * 释放通过 [[loadResDir]] 加载的资源。详细信息请参考 [[release]] - * - * @method releaseResDir - * @param {String} url - * @param {Function} type - 如果提供此参数,则将仅释放此类型的资源。 + * @en Release the all assets loaded by {{loadResDir}}. Refer to {{release}} for detailed informations. + * @zh 释放通过 {{loadResDir}} 加载的资源。详细信息请参考 {{release}} + * @param url The url of the directory to release, it should be related path to the `resources` folder. + * @param type If type is provided, the asset for correspond type will be returned */ - public releaseResDir (url: String, type?: Function, mount?) { + public releaseResDir (url: string, type?: Function, mount?) { mount = mount || 'assets'; if (!assetTables[mount]) { return; } @@ -878,10 +824,8 @@ export class CCLoader extends Pipeline { } /** - * @en Resource all assets. Refer to [[release]] for detailed informations. - * @zh 释放所有资源。详细信息请参考 [[release]] - * - * @method releaseAll + * @en Resource all assets. Refer to {{release}} for detailed informations. + * @zh 释放所有资源。详细信息请参考 {{release}} */ public releaseAll () { for (const id in this._cache) { @@ -903,39 +847,38 @@ export class CCLoader extends Pipeline { * Indicates whether to release the asset when loading a new scene.
* By default, when loading a new scene, all assets in the previous scene will be released or preserved
* according to whether the previous scene checked the "Auto Release Assets" option.
- * On the other hand, assets dynamically loaded by using `cc.loader.loadRes` or `cc.loader.loadResDir`
+ * On the other hand, assets dynamically loaded by using `loader.loadRes` or `loader.loadResDir`
* will not be affected by that option, remain not released by default.
* Use this API to change the default behavior on a single asset, to force preserve or release specified asset when scene switching.
*
- * See: [[setAutoReleaseRecursively]], [[isAutoRelease]] + * See: {{setAutoReleaseRecursively}}, {{isAutoRelease}} * @zh * 设置当场景切换时是否自动释放资源。
* 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。
- * 而使用 `cc.loader.loadRes` 或 `cc.loader.loadResDir` 动态加载的资源,则不受场景设置的影响,默认不自动释放。
+ * 而使用 `loader.loadRes` 或 `loader.loadResDir` 动态加载的资源,则不受场景设置的影响,默认不自动释放。
* 使用这个 API 可以在单个资源上改变这个默认行为,强制在切换场景时保留或者释放指定资源。
*
- * 参考:[[setAutoReleaseRecursively]],[[isAutoRelease]] + * 参考:{{setAutoReleaseRecursively}},{{isAutoRelease}} * * @example * ```typescript * // auto release the texture event if "Auto Release Assets" disabled in current scene - * cc.loader.setAutoRelease(texture2d, true); + * loader.setAutoRelease(texture2d, true); * // don't release the texture even if "Auto Release Assets" enabled in current scene - * cc.loader.setAutoRelease(texture2d, false); + * loader.setAutoRelease(texture2d, false); * // first parameter can be url - * cc.loader.setAutoRelease(audioUrl, false); + * loader.setAutoRelease(audioUrl, false); * ``` - * @method setAutoRelease - * @param {Asset|String} assetOrUrlOrUuid - 资源对象或原始资源的 URL 或是 UUID - * @param {Boolean} autoRelease - 表示是否自动释放 + * @param assetOrUrlOrUuid - The asset or its url or its uuid + * @param autoRelease - Whether to release automatically during scene switch */ - public setAutoRelease (assetOrUrlOrUuid: Asset|String, autoRelease: Boolean) { + public setAutoRelease (assetOrUrlOrUuid: Asset|string, autoRelease: Boolean) { const key = this._getReferenceKey(assetOrUrlOrUuid); if (key) { this._autoReleaseSetting[key] = !!autoRelease; } else if (DEV) { - cc.warnID(4902); + warnID(4902); } } @@ -944,33 +887,32 @@ export class CCLoader extends Pipeline { * Indicates whether to release the asset and its referenced other assets when loading a new scene.
* By default, when loading a new scene, all assets in the previous scene will be released or preserved
* according to whether the previous scene checked the "Auto Release Assets" option.
- * On the other hand, assets dynamically loaded by using `cc.loader.loadRes` or `cc.loader.loadResDir`
+ * On the other hand, assets dynamically loaded by using `loader.loadRes` or `loader.loadResDir`
* will not be affected by that option, remain not released by default.
* Use this API to change the default behavior on the specified asset and its recursively referenced assets, to force preserve or release specified asset when scene switching.
*
- * See: [[setAutoRelease]], [[isAutoRelease]] + * See: {{setAutoRelease}}, {{isAutoRelease}} * @zh * 设置当场景切换时是否自动释放资源及资源引用的其它资源。
* 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。
- * 而使用 `cc.loader.loadRes` 或 `cc.loader.loadResDir` 动态加载的资源,则不受场景设置的影响,默认不自动释放。
+ * 而使用 `loader.loadRes` 或 `loader.loadResDir` 动态加载的资源,则不受场景设置的影响,默认不自动释放。
* 使用这个 API 可以在指定资源及资源递归引用到的所有资源上改变这个默认行为,强制在切换场景时保留或者释放指定资源。
*
- * 参考:[[setAutoRelease]],[[isAutoRelease]] + * 参考:{{setAutoRelease}},{{isAutoRelease}} * * @example * ```typescript * // auto release the SpriteFrame and its Texture event if "Auto Release Assets" disabled in current scene - * cc.loader.setAutoReleaseRecursively(spriteFrame, true); + * loader.setAutoReleaseRecursively(spriteFrame, true); * // don't release the SpriteFrame and its Texture even if "Auto Release Assets" enabled in current scene - * cc.loader.setAutoReleaseRecursively(spriteFrame, false); + * loader.setAutoReleaseRecursively(spriteFrame, false); * // don't release the Prefab and all the referenced assets - * cc.loader.setAutoReleaseRecursively(prefab, false); + * loader.setAutoReleaseRecursively(prefab, false); * ``` - * @method setAutoReleaseRecursively - * @param {Asset|String} assetOrUrlOrUuid - 资源对象或原始资源的 URL 或是 UUID - * @param {Boolean} autoRelease - 表示是否自动释放 + * @param assetOrUrlOrUuid - The asset or its url or its uuid + * @param autoRelease - Whether to release automatically during scene switch */ - public setAutoReleaseRecursively (assetOrUrlOrUuid: Asset|String, autoRelease: Boolean) { + public setAutoReleaseRecursively (assetOrUrlOrUuid: Asset|string, autoRelease: Boolean) { autoRelease = !!autoRelease; const key = this._getReferenceKey(assetOrUrlOrUuid); if (key) { @@ -983,25 +925,21 @@ export class CCLoader extends Pipeline { } } else if (DEV) { - cc.warnID(4902); + warnID(4902); } } /** - * @en - * Returns whether the asset is configured as auto released, despite how "Auto Release Assets" property is set on scene asset.
+ * @en Returns whether the asset is configured as auto released, despite how "Auto Release Assets" property is set on scene asset.
*
- * See: [[setAutoRelease]], [[setAutoReleaseRecursively]] - * - * @zh - * 返回指定的资源是否有被设置为自动释放,不论场景的“Auto Release Assets”如何设置。
+ * See: {{setAutoRelease}}, {{setAutoReleaseRecursively}} + * @zh 返回指定的资源是否有被设置为自动释放,不论场景的“Auto Release Assets”如何设置。
*
- * 参考:[[setAutoRelease]],[[setAutoReleaseRecursively]] - * @method isAutoRelease - * @param {Asset|String} assetOrUrl - asset object or the raw asset's url + * 参考:{{setAutoRelease}},{{setAutoReleaseRecursively}} + * @param {Asset|string} assetOrUrl - asset object or the raw asset's url * @returns {Boolean} */ - public isAutoRelease (assetOrUrl: Asset|String): Boolean{ + public isAutoRelease (assetOrUrl: Asset|string): Boolean{ const key = this._getReferenceKey(assetOrUrl); if (key) { return !!this._autoReleaseSetting[key]; @@ -1010,10 +948,10 @@ export class CCLoader extends Pipeline { } /** - * @zh - * 获取资源的 uuid + * @en Retrieve asset's uuid + * @zh 获取资源的 uuid */ - public _getResUuid (url, type, mount, quiet) { + public _getResUuid (url: string, type?: Function, mount?, quiet?) { mount = mount || 'assets'; let uuid = ''; if (EDITOR) { @@ -1030,13 +968,13 @@ export class CCLoader extends Pipeline { } uuid = assetTable.getUuid(url, type); if (!uuid) { - const extname = cc.path.extname(url); + const extname = path.extname(url); if (extname) { // strip extname url = url.slice(0, - extname.length); uuid = assetTable.getUuid(url, type); if (uuid && !quiet) { - cc.warnID(4901, url, extname); + warnID(4901, url, extname); } } } @@ -1044,17 +982,15 @@ export class CCLoader extends Pipeline { } if (!uuid && type) { if (isChildClassOf(type, SpriteFrame) || isChildClassOf(type, Texture2D) || isChildClassOf(type, TextureCube)) { - cc.warnID(4934); + warnID(4934); } } return uuid; } /** - * @en - * Find the asset's reference id in loader, asset could be asset object, asset uuid or asset url - * @zh - * 在 laoder 中找到资源的引用 id ,参数可以是资源对象、资源的 uuid 或者是资源的 url + * @en Find the asset's reference id in loader, asset could be asset object, asset uuid or asset url + * @zh 在 laoder 中找到资源的引用 id ,参数可以是资源对象、资源的 uuid 或者是资源的 url */ public _getReferenceKey (assetOrUrlOrUuid) { let key; @@ -1062,20 +998,17 @@ export class CCLoader extends Pipeline { key = assetOrUrlOrUuid._uuid || null; } else if (typeof assetOrUrlOrUuid === 'string') { - key = this._getResUuid(assetOrUrlOrUuid, null, null, true) || assetOrUrlOrUuid; + key = this._getResUuid(assetOrUrlOrUuid, undefined, undefined, true) || assetOrUrlOrUuid; } if (!key) { - cc.warnID(4800, assetOrUrlOrUuid); + warnID(4800, assetOrUrlOrUuid); return key; } cc.AssetLibrary._getAssetInfoInRuntime(key, _info); return this._cache[_info.url!] ? _info.url : key; } - /** - * @zh - * 当 url 未找到时的操作 - */ + // Operation when complete the request without found any asset private _urlNotFound (url, type, completeCallback) { callInNextTick(() => { url = cc.url.normalize(url); @@ -1086,15 +1019,6 @@ export class CCLoader extends Pipeline { }); } - /** - * @param {Function} [type] - * @param {Function} [onProgress] - * @param {Function} onComplete - * @returns {Object} arguments - * @returns {Function} arguments.type - * @returns {Function} arguments.onProgress - * @returns {Function} arguments.onComplete - */ private _parseLoadResArgs (type, onProgress, onComplete) { if (onComplete === undefined) { const isValidType = isChildClassOf(type, cc.RawAsset); @@ -1121,10 +1045,7 @@ export class CCLoader extends Pipeline { }; } - /** - * @zh - * 通过uuids 加载资源 - */ + // Load assets with uuids private _loadResUuids (uuids, progressCallback, completeCallback, urls ?) { if (uuids.length > 0) { const self = this; @@ -1175,6 +1096,9 @@ export class CCLoader extends Pipeline { } } +/** + * Singleton object of CCLoader + */ export const loader = cc.loader = new CCLoader(); if (EDITOR) { diff --git a/cocos/core/load-pipeline/asset-loader.ts b/cocos/core/load-pipeline/asset-loader.ts index 9c96957a65..c8f75ba9c7 100644 --- a/cocos/core/load-pipeline/asset-loader.ts +++ b/cocos/core/load-pipeline/asset-loader.ts @@ -23,6 +23,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + /** * @category loader */ @@ -36,6 +37,10 @@ import { EDITOR } from 'internal:constants'; const ID = 'AssetLoader'; let reusedArray:Array = []; +/** + * @en The load pipe in {{loader}} to load an asset with its uuid, it will recursively load its dependencies. + * @zh {{loader}} 加载管线中的资源加载管道,用来通过 uuid 加载 asset 资源及其依赖 + */ export default class AssetLoader implements IPipe { static ID = ID; public id:string = ID; @@ -75,7 +80,7 @@ export default class AssetLoader implements IPipe { if (EDITOR && this.pipeline) { this.pipeline._cache[url] = reusedArray[0]; } - queue.append(reusedArray); + queue && queue.append(reusedArray); // Dispatch to other raw type downloader item.type = ext; callback(null, item.content); diff --git a/cocos/core/load-pipeline/asset-table.ts b/cocos/core/load-pipeline/asset-table.ts index b92cce6bd4..9f3d96c6a6 100644 --- a/cocos/core/load-pipeline/asset-table.ts +++ b/cocos/core/load-pipeline/asset-table.ts @@ -24,7 +24,7 @@ THE SOFTWARE. */ /** - * @category loader + * @hidden */ import {pushToMap} from '../utils/misc'; @@ -37,7 +37,7 @@ import { SpriteAtlas } from '../assets/sprite-atlas'; import { DEBUG } from 'internal:constants'; class Entry { - public uuid:string; + public uuid: string; public type; constructor (uuid, type) { this.uuid = uuid; @@ -56,17 +56,17 @@ function isMatchByWord (path, test) { /* * @en AssetTable is used to find asset's uuid by url. * @zh AssetTable 用于查找资源的 uuid 和 url。 - * @class AssetTable - * */ - export class AssetTable { - private _pathToUuid:Map | Map>; + private _pathToUuid: Map | Map>; constructor () { this._pathToUuid = createMap(true); } - getUuid (path, type) { + /** + * Retrieve the asset uuid with the asset path and type + */ + getUuid (path: string, type: Function) { path = url.normalize(path); let item = this._pathToUuid[path]; if (item) { @@ -105,13 +105,16 @@ export class AssetTable { return ''; } - getUuidArray (path, type, out_urls) { + /** + * Retrieve an uuid array with the asset path and type + */ + getUuidArray (path: string, type: Function, out_urls: string[]) { path = url.normalize(path); if (path[path.length - 1] === '/') { path = path.slice(0, -1); } let path2uuid = this._pathToUuid; - let uuids:Array = []; + let uuids: Array = []; let _foundAtlasUrl; for (let p in path2uuid) { if ((p.startsWith(path) && isMatchByWord(p, path)) || !path) { @@ -161,16 +164,15 @@ export class AssetTable { // } /** - * @en TODO - * @zh 以路径为 key,uuid 为值添加到表中。 - * @method add - * @param {String} path - the path to load, should NOT include filename extensions. - * @param {String} uuid - * @param {Function} type - * @param {Boolean} isMainAsset + * @en Add an asset entry with path as key and asset uuid & type as value to the table + * @zh 以路径为 key,uuid 和资源类型为值添加到表中。 + * @param path - the path of the asset, should NOT include filename extensions. + * @param uuid - The uuid of the asset + * @param type - Constructor of the asset + * @param isMainAsset * @private */ - add (path, uuid, type, isMainAsset) { + add (path: string, uuid: string, type: Function, isMainAsset: boolean) { // remove extname // (can not use path.slice because length of extname maybe 0) isMainAsset && (path = path.substring(0, path.length - extname(path).length)); diff --git a/cocos/core/load-pipeline/auto-release-utils.ts b/cocos/core/load-pipeline/auto-release-utils.ts index c2e55241be..a4406e9705 100644 --- a/cocos/core/load-pipeline/auto-release-utils.ts +++ b/cocos/core/load-pipeline/auto-release-utils.ts @@ -24,7 +24,7 @@ THE SOFTWARE. */ /** - * @category loader + * @hidden */ import {createMap} from '../utils/js'; diff --git a/cocos/core/load-pipeline/binary-downloader.ts b/cocos/core/load-pipeline/binary-downloader.ts index a04bcf3260..8e6e517643 100644 --- a/cocos/core/load-pipeline/binary-downloader.ts +++ b/cocos/core/load-pipeline/binary-downloader.ts @@ -24,7 +24,7 @@ THE SOFTWARE. */ /** - * @category loader + * @hidden */ export default function downloadBinary (item, callback) { @@ -40,14 +40,14 @@ export default function downloadBinary (item, callback) { callback(null, arrayBuffer); } else { - callback({status:xhr.status, errorMessage:errInfo + '(no response)'}); + callback({status: xhr.status, errorMessage: errInfo + '(no response)'}); } }; xhr.onerror = function(){ - callback({status:xhr.status, errorMessage:errInfo + '(error)'}); + callback({status: xhr.status, errorMessage: errInfo + '(error)'}); }; xhr.ontimeout = function(){ - callback({status:xhr.status, errorMessage:errInfo + '(time out)'}); + callback({status: xhr.status, errorMessage: errInfo + '(time out)'}); }; xhr.send(null); } \ No newline at end of file diff --git a/cocos/core/load-pipeline/callback-params.ts b/cocos/core/load-pipeline/callback-params.ts index c86378a349..66e56e59a8 100644 --- a/cocos/core/load-pipeline/callback-params.ts +++ b/cocos/core/load-pipeline/callback-params.ts @@ -1,6 +1,7 @@ /** - * @category loader + * @hidden */ + export type LoadCompleteCallback = (error: Error | null | undefined, asset?: T) => void; export type LoadProgressCallback = (completedCount: number, totalCount: number, item: any) => void; diff --git a/cocos/core/load-pipeline/downloader.ts b/cocos/core/load-pipeline/downloader.ts index 9d636fd58f..2bcafe145f 100644 --- a/cocos/core/load-pipeline/downloader.ts +++ b/cocos/core/load-pipeline/downloader.ts @@ -185,45 +185,43 @@ interface IDownloadItem { } /** - * The downloader pipe, it can download several types of files: + * @en The downloader pipe in {{loader}}, it can download several types of files: * 1. Text * 2. Image * 3. Script * 4. Audio - * 5. Assets + * 5. Binary * All unknown type will be downloaded as plain text. - * You can pass custom supported types in the constructor. - * @class Pipeline.Downloader - */ -/** - * Constructor of Downloader, you can pass custom supported types. - * - * @method constructor - * @param {Object} extMap Custom supported types with corresponded handler - * @example - * ``` - * let downloader = new Downloader({ - * // This will match all url with `.scene` extension or all url with `scene` type - * 'scene' : function (url, callback) {} - * }); - * ``` + * You can pass custom supported types in the {{loader.addDownloadHandlers}}. + * @zh {{loader}} 中的下载管线,可以下载下列类型的文件: + * 1. Text + * 2. Image + * 3. Script + * 4. Audio + * 5. Binary + * 所有未知类型会被当做文本来下载,也可以通过 {{loader.addDownloadHandlers}} 来定制下载行为 */ export default class Downloader implements IPipe { static ID = ID; static PackDownloader = PackDownloader; - public id:string = ID; - public async:boolean = true; - public pipeline:Pipeline | null = null; - private extMap:object; + public id: string = ID; + public async: boolean = true; + public pipeline: Pipeline | null = null; + private extMap: object; private _curConcurrent = 0; - private _loadQueue:Array = []; + private _loadQueue: Array = []; private _subPackages = {}; constructor (extMap?) { this.extMap = mixin(extMap, defaultMap); } + /** + * @en Set sub package configurations, only available in certain platforms + * @zh 设置子包配置,只在部分平台支持 + * @param subPackages + */ setSubPackages (subPackages) { this._subPackages = subPackages; } @@ -231,10 +229,9 @@ export default class Downloader implements IPipe { /** * @en Add custom supported types handler or modify existing type handler. * @zh 添加自定义支持的类型处理程序或修改现有的类型处理程序。 - * @method addHandlers - * @param {Object} extMap Custom supported types with corresponded handler + * @param extMap Custom supported types with corresponded handler */ - addHandlers (extMap) { + addHandlers (extMap: Map) { mixin(this.extMap, extMap); } @@ -288,16 +285,13 @@ export default class Downloader implements IPipe { } /** - * @en - * Load subpackage with name. - * @zh - * 通过子包名加载子包代码。 - * @method loadSubpackage - * @param {String} name - Subpackage name - * @param {Function} [completeCallback] - Callback invoked when subpackage loaded + * @en Load sub package with name. + * @zh 通过子包名加载子包代码。 + * @param name - Sub package name + * @param completeCallback - Callback invoked when sub package loaded * @param {Error} completeCallback.error - error information */ - loadSubpackage (name, completeCallback) { + loadSubpackage (name: string, completeCallback?: Function) { let pac = this._subPackages[name]; if (pac) { if (pac.loaded) { diff --git a/cocos/core/load-pipeline/font-loader.ts b/cocos/core/load-pipeline/font-loader.ts index 188ae69023..0ef0bed6b4 100644 --- a/cocos/core/load-pipeline/font-loader.ts +++ b/cocos/core/load-pipeline/font-loader.ts @@ -24,7 +24,7 @@ */ /** - * @category loader + * @hidden */ import {safeMeasureText} from '../utils/text-utils'; @@ -42,7 +42,7 @@ const _testString = "BES bswy:->@123\u4E01\u3041\u1101"; let _fontFaces = {}; let _intervalId = -1; -let _loadingFonts:Array = []; +let _loadingFonts: Array = []; // 3 seconds timeout let _timeout = 3000; @@ -200,7 +200,7 @@ export function loadFont (item, callback) { } else { // Save loading font - let fontLoadHandle:IFontLoadHandle = { + let fontLoadHandle: IFontLoadHandle = { fontFamilyName, refWidth, callback, diff --git a/cocos/core/load-pipeline/index.ts b/cocos/core/load-pipeline/index.ts index fe057eb09e..60745f84b4 100644 --- a/cocos/core/load-pipeline/index.ts +++ b/cocos/core/load-pipeline/index.ts @@ -25,7 +25,7 @@ */ /** - * @category loader + * @hidden */ export {default as url} from './url'; diff --git a/cocos/core/load-pipeline/loader.ts b/cocos/core/load-pipeline/loader.ts index fc1aafc30b..c55ed479e1 100644 --- a/cocos/core/load-pipeline/loader.ts +++ b/cocos/core/load-pipeline/loader.ts @@ -265,28 +265,25 @@ let defaultMap = { let ID = 'Loader'; /** - * The loader pipe, it can load several types of files: + * @en The loader pipe in {{loader}}, it can load several types of files: * 1. Images * 2. JSON * 3. Plist * 4. Audio * 5. Font - * 6. Cocos Creator scene + * 6. Binary + * 7. Cocos Assets * It will not interfere with items of unknown type. - * You can pass custom supported types in the constructor. - * @class Pipeline.Loader - */ -/** - * Constructor of Loader, you can pass custom supported types. - * - * @param {Object} extMap Custom supported types with corresponded handler - * @example - * ``` - * let loader = new Loader({ - * // This will match all url with `.scene` extension or all url with `scene` type - * 'scene' : function (url, callback) {} - * }); - * ``` + * You can pass custom supported types in the {{loader.addLoadHandlers}}. + * @zh {{loader}} 中的解析加载管线,可以解析加载下列类型的资源: + * 1. Images + * 2. JSON + * 3. Plist + * 4. Audio + * 5. Font + * 6. Binary + * 7. Cocos Assets + * 所有未知类型不会被处理,也可以通过 {{loader.addLoadHandlers}} 来定制加载行为 */ export default class Loader implements IPipe { static ID = ID; @@ -294,16 +291,18 @@ export default class Loader implements IPipe { public id = ID; public async = true; public pipeline: Pipeline | null = null; - private extMap:object; + private extMap: object; constructor (extMap?) { this.extMap = mixin(extMap, defaultMap); } /** - * Add custom supported types handler or modify existing type handler. - * @param {Object} extMap Custom supported types with corresponded handler + * @en Add custom supported types handler or modify existing type handler. + * @zh 添加自定义支持的类型处理程序或修改现有的类型处理程序。 + * @param extMap Custom supported types with corresponded handler + * @param extMap Custom supported types with corresponded handler */ - addHandlers (extMap?) { + addHandlers (extMap: Map) { this.extMap = mixin(this.extMap, extMap); } diff --git a/cocos/core/load-pipeline/loading-items.ts b/cocos/core/load-pipeline/loading-items.ts index 1c44453502..e811eec341 100644 --- a/cocos/core/load-pipeline/loading-items.ts +++ b/cocos/core/load-pipeline/loading-items.ts @@ -34,27 +34,36 @@ import {createMap, mixin} from '../utils/js'; let _qid = (0|(Math.random()*998)); let _queues = createMap(true); -let _pool:Array = []; +let _pool: Array = []; const _POOL_MAX_LENGTH = 10; export interface IItem { queueId; - id:string; + id: string; url; // real download url, maybe changed rawUrl; // url used in scripts urlParam; - type:string; - error:Error|null; - content:any; - complete:boolean; - states:object; + type: string; + error: Error|null; + content: any; + complete: boolean; + states: object; deps; - isScene:boolean; + isScene: boolean; } enum ItemState { + /** + * @property {Number} WORKING + */ WORKING, + /** + * @property {Number} COMPLETE + */ COMPLETE, + /** + * @property {Number} ERROR + */ ERROR }; @@ -112,8 +121,8 @@ function createItem (id, queueId) { return result; } -let _checkedIds:Array = []; -function checkCircleReference(owner, item:IItem, recursiveCall?) { +let _checkedIds: Array = []; +function checkCircleReference(owner, item: IItem, recursiveCall?) { if (!owner || !item) { return false; } @@ -174,27 +183,11 @@ function checkCircleReference(owner, item:IItem, recursiveCall?) { *
* 对象可容纳其他自定义属性。
* 每个 LoadingItems 对象都会在 onComplete 回调之后被销毁,所以请不要持有它的引用并在结束回调之后依赖它的内容执行任何逻辑,有这种需求的话你可以提前复制它的内容。 - * - * @class LoadingItems - * @extends CallbacksInvoker */ export class LoadingItems extends CallbacksInvoker { /** - * @en The item states of the LoadingItems, its value could be LoadingItems.ItemState.WORKING | LoadingItems.ItemState.COMPLETET | LoadingItems.ItemState.ERROR - * @zh LoadingItems 队列中的加载项状态,状态的值可能是 LoadingItems.ItemState.WORKING | LoadingItems.ItemState.COMPLETET | LoadingItems.ItemState.ERROR - * @enum LoadingItems.ItemState - */ - - /** - * @property {Number} WORKING - */ - - /** - * @property {Number} COMPLETET - */ - - /** - * @property {Number} ERROR + * @en The item states of the LoadingItems, its value could be {{ItemState.WORKING}} | {{ItemState.COMPLETE}} | {{ItemState.ERROR}} + * @zh LoadingItems 队列中的加载项状态,状态的值可能是 {{ItemState.WORKING}} | {{ItemState.COMPLETE}} | {{ItemState.ERROR}} */ static ItemState = new cc.Enum(ItemState); @@ -202,10 +195,9 @@ export class LoadingItems extends CallbacksInvoker { * @en This is a callback which will be invoked while an item flow out the pipeline. * You can pass the callback function in LoadingItems.create or set it later. * @zh 这个回调函数将在 item 加载结束后被调用。你可以在构造时传递这个回调函数或者是在构造之后直接设置。 - * @method onProgress - * @param {Number} completedCount The number of the items that are already completed. - * @param {Number} totalCount The total number of the items. - * @param {Object} item The latest item which flow out the pipeline. + * @param completedCount The number of the items that are already completed. + * @param totalCount The total number of the items. + * @param item The latest item which flow out the pipeline. * @example * ``` * loadingItems.onProgress (completedCount, totalCount, item) { @@ -214,15 +206,14 @@ export class LoadingItems extends CallbacksInvoker { * } * ``` */ - public onProgress:Function|undefined; + public onProgress:((completedCount: number, totalCount: number, IItem) => void) | undefined; /** * @en This is a callback which will be invoked while all items is completed, * You can pass the callback function in LoadingItems.create or set it later. * @zh 该函数将在加载队列全部完成时被调用。你可以在构造时传递这个回调函数或者是在构造之后直接设置。 - * @method onComplete - * @param {Array} errors All errored urls will be stored in this array, if no error happened, then it will be null - * @param {LoadingItems} items All items. + * @param errors All errored urls will be stored in this array, if no error happened, then it will be null + * @param items All items. * @example * ``` * loadingItems.onComplete (errors, items) { @@ -233,53 +224,43 @@ export class LoadingItems extends CallbacksInvoker { * } * ``` */ - public onComplete:Function|undefined; + public onComplete:((errors: string[]|null, items: LoadingItems) => void) | undefined; /** * @en The map of all items. * @zh 存储所有加载项的对象。 - * @property map - * @type {Object} */ - public map = createMap(true); + public map: Map = createMap(true); /** * @en The map of completed items. * @zh 存储已经完成的加载项。 - * @property completed - * @type {Object} */ public completed = {}; /** * @en Total count of all items. * @zh 所有加载项的总数。 - * @property totalCount - * @type {Number} */ public totalCount = 0; /** * @en Total count of completed items. * @zh 所有完成加载项的总数。 - * @property completedCount - * @type {Number} */ public completedCount = 0; /** * @en Activated or not. * @zh 是否启用。 - * @property active - * @type {Boolean} */ - public active:boolean; + public active: boolean; - private _id:number; + private _id: number; private _pipeline; - private _errorUrls:Array = []; + private _errorUrls: Array = []; private _appending = false; - public _ownerQueue = null; + public _ownerQueue: LoadingItems|null = null; constructor (pipeline, urlList, onProgress, onComplete) { super(); @@ -314,8 +295,6 @@ export class LoadingItems extends CallbacksInvoker { * You can pass onProgress and onComplete callbacks to visualize the loading process. * @zh LoadingItems 的构造函数,这种构造方式会重用内部对象缓冲池中的 LoadingItems 队列,以尽量避免对象创建。 * 你可以传递 onProgress 和 onComplete 回调函数来获知加载进度信息。 - * @method create - * @static * @param {Pipeline} pipeline The pipeline to process the queue. * @param {Array} urlList The items array. * @param {Function} [onProgress] The progression callback, refer to [[onProgress]] @@ -381,22 +360,19 @@ export class LoadingItems extends CallbacksInvoker { /** * @en Retrieve the LoadingItems queue object for an item. * @zh 通过 item 对象获取它的 LoadingItems 队列。 - * @method getQueue - * @static - * @param {Object} item The item to query - * @return {LoadingItems} The LoadingItems queue object + * @param item The item to query + * @return The LoadingItems queue object */ - static getQueue (item) { + static getQueue (item: IItem): LoadingItems | null { return item.queueId ? _queues[item.queueId] : null; } /** * @en Complete an item in the LoadingItems queue, please do not call this method unless you know what's happening. * @zh 通知 LoadingItems 队列一个 item 对象已完成,请不要调用这个函数,除非你知道自己在做什么。 - * @method itemComplete - * @param {Object} item The item which has completed + * @param item The item which has completed */ - static itemComplete (item) { + static itemComplete (item: IItem) { let queue = _queues[item.queueId]; if (queue) { // console.log('----- Completed by pipeline ' + item.id + ', rest: ' + (queue.totalCount - queue.completedCount-1)); @@ -457,12 +433,11 @@ export class LoadingItems extends CallbacksInvoker { /** * @en Add urls to the LoadingItems queue. * @zh 向一个 LoadingItems 队列添加加载项。 - * @method append - * @param {Array} urlList 要追加的url列表,url可以是对象或字符串 - * @param {any} [owner] - * @return {Array} 在已接受的url列表中,可以拒绝某些无效项 + * @param urlList 要追加的url列表,url可以是对象或字符串 + * @param owner + * @return 在已接受的url列表中,可以拒绝某些无效项 */ - append (urlList, owner?) { + append (urlList: object[], owner?): IItem[] { if (!this.active) { return []; } @@ -471,7 +446,7 @@ export class LoadingItems extends CallbacksInvoker { } this._appending = true; - let accepted:Array = [], i, url, item; + let accepted: Array = [], i, url, item; for (i = 0; i < urlList.length; ++i) { url = urlList[i]; @@ -542,7 +517,6 @@ export class LoadingItems extends CallbacksInvoker { /** * @en Complete a LoadingItems queue, please do not call this method unless you know what's happening. * @zh 完成一个 LoadingItems 队列,请不要调用这个函数,除非你知道自己在做什么。 - * @method allComplete */ allComplete () { let errors = this._errorUrls.length === 0 ? null : this._errorUrls; @@ -554,43 +528,35 @@ export class LoadingItems extends CallbacksInvoker { /** * @en Check whether all items are completed. * @zh 检查是否所有加载项都已经完成。 - * @method isCompleted - * @return {Boolean} */ - isCompleted () { + isCompleted (): boolean { return this.completedCount >= this.totalCount; } /** * @en Check whether an item is completed. * @zh 通过 id 检查指定加载项是否已经加载完成。 - * @method isItemCompleted - * @param {String} id The item's id. - * @return {Boolean} + * @param id The item's id. */ - isItemCompleted (id) { + isItemCompleted (id: string): boolean { return !!this.completed[id]; } /** * @en Check whether an item exists. * @zh 通过 id 检查加载项是否存在。 - * @method exists - * @param {String} id The item's id. - * @return {Boolean} + * @param id The item's id. */ - exists (id) { + exists (id: string): boolean { return !!this.map[id]; } /** * @en Returns the content of an internal item. * @zh 通过 id 获取指定对象的内容。 - * @method getContent - * @param {String} id The item's id. - * @return {Object} + * @param id The item's id. */ - getContent (id) { + getContent (id: string): any { let item = this.map[id]; let ret = null; if (item) { @@ -608,11 +574,9 @@ export class LoadingItems extends CallbacksInvoker { /** * @en Returns the error of an internal item. * @zh 通过 id 获取指定对象的错误信息。 - * @method getError - * @param {String} id The item's id. - * @return {Object} + * @param id The item's id. */ - getError (id) { + getError (id: string): any { let item = this.map[id]; let ret = null; if (item) { @@ -629,9 +593,9 @@ export class LoadingItems extends CallbacksInvoker { /** * @en Remove an item, can only remove completed item, ongoing item can not be removed. * @zh 移除加载项,这里只会移除已经完成的加载项,正在进行的加载项将不能被删除。 - * @param {String} url + * @param url */ - removeItem (url) { + removeItem (url: string) { let item = this.map[url]; if (!item) return; @@ -651,10 +615,9 @@ export class LoadingItems extends CallbacksInvoker { /** * @en Complete an item in the LoadingItems queue, please do not call this method unless you know what's happening. * @zh 通知 LoadingItems 队列一个 item 对象已完成,请不要调用这个函数,除非你知道自己在做什么。 - * @method itemComplete - * @param {String} id The item url + * @param id The item url */ - itemComplete (id) { + itemComplete (id: string) { let item = this.map[id]; if (!item) { return; @@ -691,7 +654,6 @@ export class LoadingItems extends CallbacksInvoker { /** * @en Destroy the LoadingItems queue, the queue object won't be garbage collected, it will be recycled, so every after destroy is not reliable. * @zh 销毁一个 LoadingItems 队列,这个队列对象会被内部缓冲池回收,所以销毁后的所有内部信息都是不可依赖的。 - * @method destroy */ destroy () { this.active = false; @@ -724,13 +686,11 @@ export class LoadingItems extends CallbacksInvoker { /** * @en Add a listener for an item, the callback will be invoked when the item is completed. * @zh 监听加载项(通过 key 指定)的完成事件。 - * @method addListener - * @param {String} key - * @param {Function} callback - can be null - * @param {Object} target - can be null - * @return {Boolean} whether the key is new + * @param key - The item key + * @param callback - Callback function when item loaded + * @param target - Callback callee */ - addListener (key, callback, target) { + addListener (key: string, callback: Function, target?: any) { return super.on(key, callback, target); } @@ -741,13 +701,12 @@ export class LoadingItems extends CallbacksInvoker { * @zh * 检查指定的加载项是否有完成事件监听器。 * 如果同时还指定了一个回调方法,并且回调有注册,它只会返回 true。 - * @method hasListener - * @param {String} key - * @param {Function} [callback] - * @param {Object} [target] - * @return {Boolean} + * @param key - The item key + * @param callback - Callback function when item loaded + * @param target - Callback callee + * @return Whether the corresponding listener for the item is registered */ - hasListener (key, callback?, target?) { + hasListener (key: string, callback?: Function, target?: any): boolean { return super.hasEventListener(key, callback, target); } @@ -758,23 +717,19 @@ export class LoadingItems extends CallbacksInvoker { * @zh * 移除指定加载项已经注册的完成事件监听器。 * 只会删除 key, callback, target 均匹配的监听器。 - * @method remove - * @param {String} key - * @param {Function} callback - * @param {Object} target - * @return {Boolean} removed + * @param key - The item key + * @param callback - Callback function when item loaded + * @param target - Callback callee */ - removeListener (key, callback?, target?) { + removeListener (key: string, callback?: Function, target?: any) { return super.off(key, callback, target); } /** - * @en - * Removes all callbacks registered in a certain event + * @en Removes all callbacks registered in a certain event * type or all callbacks registered with a certain target. * @zh 删除指定目标的所有完成事件监听器。 - * @method removeAllListeners - * @param {String|Object} key - The event key to be removed or the target to be removed + * @param {String|Object} key - The item key to be removed or the target to be removed */ removeAllListeners (key) { super.removeAll(key); diff --git a/cocos/core/load-pipeline/md5-pipe.ts b/cocos/core/load-pipeline/md5-pipe.ts index 380b509445..9484b2b873 100644 --- a/cocos/core/load-pipeline/md5-pipe.ts +++ b/cocos/core/load-pipeline/md5-pipe.ts @@ -42,6 +42,10 @@ function getUuidFromURL (url) { return ""; } +/** + * @en The md5 pipe in {{loader}}, it can transform the url to the real url with md5 suffix + * @zh {{loader}} 中的 md5 管道,可以将资源 url 转换到包含 md5 后缀版本 + */ export default class MD5Pipe implements IPipe { static ID = ID; @@ -71,7 +75,13 @@ export default class MD5Pipe implements IPipe { return item; } - transformURL (url, hashPatchInFolder) { + /** + * @en Transform an url to the real url with md5 suffix + * @zh 将一个 url 转换到包含 md5 后缀版本 + * @param url The url to be parsed + * @param hashPatchInFolder NA + */ + transformURL (url, hashPatchInFolder?: boolean) { let uuid = getUuidFromURL(url); if (uuid) { let isNativeAsset = !url.match(this.libraryBase); diff --git a/cocos/core/load-pipeline/pack-downloader.ts b/cocos/core/load-pipeline/pack-downloader.ts index 86f67bed0b..46dc780671 100644 --- a/cocos/core/load-pipeline/pack-downloader.ts +++ b/cocos/core/load-pipeline/pack-downloader.ts @@ -25,7 +25,7 @@ */ /** - * @category loader + * @hidden */ import {pushToMap} from '../utils/misc'; diff --git a/cocos/core/load-pipeline/pipeline.ts b/cocos/core/load-pipeline/pipeline.ts index 0e6a118465..9d6e9e553a 100644 --- a/cocos/core/load-pipeline/pipeline.ts +++ b/cocos/core/load-pipeline/pipeline.ts @@ -34,10 +34,11 @@ import { EDITOR } from 'internal:constants'; const ItemState = LoadingItems.ItemState; export interface IPipe { - id:string; - async:boolean; - handle (item:IItem, callback); - next?:IPipe; + id: string; + async: boolean; + handle (item: IItem, callback); + next?: IPipe|null; + pipeline?: Pipeline|null; } function flow (pipe, item) { @@ -116,20 +117,25 @@ function flow (pipe, item) { * 一个 item 列表可以在 pipeline 中流动,它将输出加载项经过所有 pipe 之后的结果。
* 它们穿过 pipeline 就像水在管子里流动,将会按顺序流过每个 pipe。
* 最后当所有加载项都流出 pipeline 时,整个加载流程就结束了。 - * @class Pipeline */ export class Pipeline { + /** + * @en The item states of the LoadingItems, its value could be {{ItemState.WORKING}} | {{ItemState.COMPLETE}} | {{ItemState.ERROR}} + * @zh LoadingItems 队列中的加载项状态,状态的值可能是 {{ItemState.WORKING}} | {{ItemState.COMPLETE}} | {{ItemState.ERROR}} + */ static ItemState = ItemState; - protected _pipes:Array; + protected _pipes: Array; public _cache = createMap(true); /** - * 构造函数,通过一系列的 pipe 来构造一个新的 pipeline,pipes 将会在给定的顺序中被锁定。
+ * @en The constructor of the Pipeline, the order of pipes will remain as given. + * A pipe is an {{IPipe}} object which must have an `id` and a `handle` function, the `id` must be unique. + * It should also include an `async` property to identify whether the pipe's `handle` function is asynchronous. + * @zh 构造函数,通过一系列的 pipe 来构造一个新的 pipeline,pipes 将会在给定的顺序中被锁定。
* 一个 pipe 就是一个对象,它包含了字符串类型的 ‘id’ 和 ‘handle’ 函数,在 pipeline 中 id 必须是唯一的。
* 它还可以包括 ‘async’ 属性以确定它是否是一个异步过程。 - * - * @param {Array} pipes + * @param pipes All pipes for constructing the pipeline * @example * ``` * let pipeline = new Pipeline([ @@ -142,7 +148,7 @@ export class Pipeline { * ]); * ``` */ - constructor (pipes) { + constructor (pipes: IPipe[]) { this._pipes = pipes; for (let i = 0; i < pipes.length; ++i) { @@ -158,17 +164,14 @@ export class Pipeline { } /** - * @en - * Insert a new pipe at the given index of the pipeline.
+ * @en Insert a new pipe at the given index of the pipeline.
* A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline. - * @zh - * 在给定的索引位置插入一个新的 pipe。
+ * @zh 在给定的索引位置插入一个新的 pipe。
* 一个 pipe 必须包含一个字符串类型的 ‘id’ 和 ‘handle’ 函数,该 id 在 pipeline 必须是唯一标识。 - * @method insertPipe - * @param {Object} pipe The pipe to be inserted - * @param {Number} index The index to insert + * @param pipe The pipe to be inserted + * @param index The index to insert */ - insertPipe (pipe, index) { + insertPipe (pipe: IPipe, index: number) { // Must have handle and id, handle for flow, id for state flag if (!pipe.handle || !pipe.id || index > this._pipes.length) { cc.warnID(4921); @@ -182,12 +185,12 @@ export class Pipeline { pipe.pipeline = this; - let nextPipe:IPipe|null = null; + let nextPipe: IPipe|null = null; if (index < this._pipes.length) { nextPipe = this._pipes[index]; } - let previousPipe:IPipe|null = null; + let previousPipe: IPipe|null = null; if (index > 0) { previousPipe = this._pipes[index-1]; } @@ -201,15 +204,12 @@ export class Pipeline { } /** - * @en - * Insert a pipe to the end of an existing pipe. The existing pipe must be a valid pipe in the pipeline. - * @zh - * 在当前 pipeline 的一个已知 pipe 后面插入一个新的 pipe。 - * @method insertPipeAfter - * @param {Object} refPipe An existing pipe in the pipeline. - * @param {Object} newPipe The pipe to be inserted. + * @en Insert a pipe to the end of an existing pipe. The existing pipe must be a valid pipe in the pipeline. + * @zh 在当前 pipeline 的一个已知 pipe 后面插入一个新的 pipe。 + * @param refPipe An existing pipe in the pipeline. + * @param newPipe The pipe to be inserted. */ - insertPipeAfter (refPipe, newPipe) { + insertPipeAfter (refPipe: IPipe, newPipe: IPipe) { let index = this._pipes.indexOf(refPipe); if (index < 0) { return; @@ -218,16 +218,13 @@ export class Pipeline { } /** - * @en - * Add a new pipe at the end of the pipeline.
+ * @en Add a new pipe at the end of the pipeline.
* A pipe must contain an `id` in string and a `handle` function, the id must be unique in the pipeline. - * @zh - * 添加一个新的 pipe 到 pipeline 尾部。
+ * @zh 添加一个新的 pipe 到 pipeline 尾部。
* 该 pipe 必须包含一个字符串类型 ‘id’ 和 ‘handle’ 函数,该 id 在 pipeline 必须是唯一标识。 - * @method appendPipe - * @param {Object} pipe The pipe to be appended + * @param pipe The pipe to be appended */ - appendPipe (pipe) { + appendPipe (pipe: IPipe) { // Must have handle and id, handle for flow, id for state flag if (!pipe.handle || !pipe.id) { return; @@ -256,7 +253,7 @@ export class Pipeline { * 你也可以指定它的 ‘type’ 属性类型,默认情况下,该类型是 ‘url’ 的后缀名。
* 也通过添加一个 包含 ‘skips’ 属性的 item 对象,你就可以跳过 skips 中包含的 pipe。
* 该对象可以包含任何附加属性。 - * @param {Array} items + * @param items The {{IItem}} to be appended to the current pipeline * @example * ``` * pipeline.flowIn([ @@ -270,7 +267,7 @@ export class Pipeline { * ]); * ``` */ - flowIn (items) { + flowIn (items: Array) { let i, pipe = this._pipes[0], item; if (pipe) { // Cache all items first, in case synchronous loading flow same item repeatly @@ -302,12 +299,12 @@ export class Pipeline { * 这个 API 的使用通常是为了加载依赖项。
* 例如:
* 我们需要加载一个场景配置的 JSON 文件,该场景会将所有的依赖项全部都加载完毕以后,进行回调表示加载完毕。 - * @deprecated since v1.3 - * @param {Array} urlList - * @param {Function} callback - * @return {Array} Items accepted by the pipeline + * @param owner The owner item + * @param urlList The list of urls to be appended as dependencies of the owner. + * @param callback The callback to be invoked when all dependencies are completed. + * @return Items accepted by the pipeline */ - flowInDeps (owner, urlList, callback) { + flowInDeps (owner: IItem, urlList: object[], callback: Function): IItem[] { let deps = LoadingItems.create(this, function (errors, items) { callback(errors, items); items.destroy(); @@ -315,7 +312,12 @@ export class Pipeline { return deps.append(urlList, owner); } - flowOut (item) { + /** + * @en This function is invoked when an item has completed all pipes, it will flow out of the pipeline. + * @zh 这个函数会在 `item` 完成了所有管道,它会被标记为 `complete` 并流出管线。 + * @param item The item which is completed + */ + flowOut (item: IItem) { if (item.error) { delete this._cache[item.id]; } @@ -341,11 +343,10 @@ export class Pipeline { * 你希望让这些新的依赖项进入 pipeline,但是又不希望它们通过源 item 已经经过的 pipe,
* 但是你可能希望他们源 item 已经通过并跳过所有 pipes,
* 这个时候就可以使用这个 API。 - * @method copyItemStates - * @param {Object} srcItem The source item - * @param {Array|Object} dstItems A single destination item or an array of destination items + * @param srcItem The source item + * @param dstItems A single destination item or an array of destination items */ - copyItemStates (srcItem, dstItems) { + copyItemStates (srcItem: IItem, dstItems: IItem|Array) { if (!(dstItems instanceof Array)) { dstItems.states = srcItem.states; return; @@ -358,11 +359,9 @@ export class Pipeline { /** * @en Returns an item in pipeline. * @zh 根据 id 获取一个 item - * @method getItem - * @param {Object} id The id of the item - * @return {Object} + * @param id The id of the item */ - getItem (id) { + getItem (id: string): IItem|null { let item = this._cache[id]; if (!item) @@ -379,15 +378,14 @@ export class Pipeline { * @en Removes an completed item in pipeline. * It will only remove the cache in the pipeline or loader, its dependencies won't be released. * cc.loader provided another method to completely cleanup the resource and its dependencies, - * please refer to [[CCLoader.release]] + * please refer to {{Loader.release}} * @zh 移除指定的已完成 item。 * 这将仅仅从 pipeline 或者 loader 中删除其缓存,并不会释放它所依赖的资源。 - * cc.loader 中提供了另一种删除资源及其依赖的清理方法,请参考 [[CCLoader.release]] - * @method removeItem - * @param {Object} id The id of the item - * @return {Boolean} succeed or not + * cc.loader 中提供了另一种删除资源及其依赖的清理方法,请参考 {{Loader.release}} + * @param id The id of the item + * @return succeed or not */ - removeItem (id) { + removeItem (id: string): boolean { let removed = this._cache[id]; if (removed && removed.complete) { delete this._cache[id]; diff --git a/cocos/core/load-pipeline/plist-parser.ts b/cocos/core/load-pipeline/plist-parser.ts index ab6aee0806..29ff8152ae 100644 --- a/cocos/core/load-pipeline/plist-parser.ts +++ b/cocos/core/load-pipeline/plist-parser.ts @@ -26,10 +26,11 @@ */ /** - * @category loader + * @hidden */ import { EDITOR } from 'internal:constants'; +import { warnID } from '../platform/debug'; /** * A SAX Parser @@ -74,7 +75,7 @@ class SAXParser { /** * - * cc.plistParser is a singleton object for parsing plist files + * plistParser is a singleton object for parsing plist files * @class plistParser * @extends SAXParser */ @@ -89,7 +90,7 @@ class PlistParser extends SAXParser { let xmlDoc = this._parseXML(xmlTxt); let plist = xmlDoc.documentElement; if (plist.tagName !== 'plist') { - cc.warnID(5100); + warnID(5100); return {}; } @@ -106,7 +107,7 @@ class PlistParser extends SAXParser { } _parseNode (node) { - let data:any = null, tagName = node.tagName; + let data: any = null, tagName = node.tagName; if(tagName === "dict"){ data = this._parseDict(node); }else if(tagName === "array"){ @@ -133,7 +134,7 @@ class PlistParser extends SAXParser { } _parseArray (node) { - let data:Array = []; + let data: Array = []; for (let i = 0, len = node.childNodes.length; i < len; i++) { let child = node.childNodes[i]; if (child.nodeType !== 1) @@ -169,4 +170,4 @@ class PlistParser extends SAXParser { */ let plistParser = new PlistParser(); -export default plistParser; \ No newline at end of file +export default plistParser; diff --git a/cocos/core/load-pipeline/released-asset-checker.ts b/cocos/core/load-pipeline/released-asset-checker.ts index 87a66a546a..cd5f17466b 100644 --- a/cocos/core/load-pipeline/released-asset-checker.ts +++ b/cocos/core/load-pipeline/released-asset-checker.ts @@ -25,12 +25,12 @@ */ /** - * @category loader + * @hidden */ import {createMap, getClassName, clear} from '../utils/js'; -let _tmpInfo:any = null; +let _tmpInfo: any = null; function getItemDesc (item) { if (item.uuid) { diff --git a/cocos/core/load-pipeline/text-downloader.ts b/cocos/core/load-pipeline/text-downloader.ts index f251b776ba..ffd3e6941d 100644 --- a/cocos/core/load-pipeline/text-downloader.ts +++ b/cocos/core/load-pipeline/text-downloader.ts @@ -24,7 +24,7 @@ */ /** - * @category loader + * @hidden */ import {urlAppendTimestamp} from './utils'; @@ -43,18 +43,18 @@ export default function (item, callback) { callback(null, xhr.responseText); } else { - callback({status:xhr.status, errorMessage:errInfo + '(wrong status)'}); + callback({status: xhr.status, errorMessage: errInfo + '(wrong status)'}); } } else { - callback({status:xhr.status, errorMessage:errInfo + '(wrong readyState)'}); + callback({status: xhr.status, errorMessage: errInfo + '(wrong readyState)'}); } }; xhr.onerror = function(){ - callback({status:xhr.status, errorMessage:errInfo + '(error)'}); + callback({status: xhr.status, errorMessage: errInfo + '(error)'}); }; xhr.ontimeout = function(){ - callback({status:xhr.status, errorMessage:errInfo + '(time out)'}); + callback({status: xhr.status, errorMessage: errInfo + '(time out)'}); }; xhr.send(null); } \ No newline at end of file diff --git a/cocos/core/load-pipeline/unpackers.ts b/cocos/core/load-pipeline/unpackers.ts index 9b898953d8..d87967ce62 100644 --- a/cocos/core/load-pipeline/unpackers.ts +++ b/cocos/core/load-pipeline/unpackers.ts @@ -25,9 +25,13 @@ */ /** - * @category loader + * @hidden */ +import { errorID } from "../platform/debug"; +import { js } from "../utils/js"; +import { Texture2D } from "../assets/texture-2d"; + export class JsonUnpacker { public jsons = {}; @@ -37,7 +41,7 @@ export class JsonUnpacker { */ load (indices, packedJson) { if (packedJson.length !== indices.length) { - cc.errorID(4915); + errorID(4915); } for (let i = 0; i < indices.length; i++) { let key = indices[i]; @@ -62,7 +66,7 @@ export class TextureUnpacker { load (indices, packedJson) { let datas = packedJson.data; if (datas.length !== indices.length) { - cc.errorID(4915); + errorID(4915); } for (let i = 0; i < indices.length; i++) { this.contents[indices[i]] = {base: datas[i][0], mipmaps: datas[i][1]}; @@ -73,7 +77,7 @@ export class TextureUnpacker { let content = this.contents[key]; if (content) { return { - __type__: cc.js._getClassId(cc.Texture2D), + __type__: js._getClassId(Texture2D), content: content }; } diff --git a/cocos/core/load-pipeline/url.ts b/cocos/core/load-pipeline/url.ts index c953930962..fd437c8640 100644 --- a/cocos/core/load-pipeline/url.ts +++ b/cocos/core/load-pipeline/url.ts @@ -25,11 +25,12 @@ */ /** - * 加载相关模块 * @category loader */ import { EDITOR } from 'internal:constants'; +import { errorID } from '../platform/debug'; +import { extname, stripSep } from '../utils/path'; /** * @class url @@ -69,20 +70,20 @@ let url = { */ raw: function (url) { if (EDITOR && !this._rawAssets) { - cc.errorID(7000); + errorID(7000); return ''; } url = this.normalize(url); if ( !url.startsWith('resources/') ) { - cc.errorID(EDITOR ? 7001 : 7002, url); + errorID(EDITOR ? 7001 : 7002, url); } else { // Compatible with versions lower than 1.10 var uuid = cc.loader._getResUuid(url.slice(10), cc.Asset, null, true); if (uuid) { - return cc.AssetLibrary.getLibUrlNoExt(uuid, true) + cc.path.extname(url); + return cc.AssetLibrary.getLibUrlNoExt(uuid, true) + extname(url); } } @@ -90,7 +91,7 @@ let url = { }, _init: function (assets) { - this._rawAssets = cc.path.stripSep(assets) + '/'; + this._rawAssets = stripSep(assets) + '/'; } } diff --git a/cocos/core/load-pipeline/utils.ts b/cocos/core/load-pipeline/utils.ts index 9957fa5370..91a8976dde 100644 --- a/cocos/core/load-pipeline/utils.ts +++ b/cocos/core/load-pipeline/utils.ts @@ -24,7 +24,7 @@ */ /** - * @category loader + * @hidden */ let _noCacheRex = /\?/; diff --git a/cocos/core/load-pipeline/uuid-loader.ts b/cocos/core/load-pipeline/uuid-loader.ts index 3d445e644f..0d4fa1f4f5 100644 --- a/cocos/core/load-pipeline/uuid-loader.ts +++ b/cocos/core/load-pipeline/uuid-loader.ts @@ -25,7 +25,7 @@ */ /** - * @category loader + * @hidden */ import * as js from '../utils/js'; @@ -53,7 +53,7 @@ function parseDepends (item, asset, tdInfo, deferredLoadRawAssetsInRuntime) { let depends; let i, dependUuid; // cache dependencies for auto release - let dependKeys:Array = item.dependKeys = []; + let dependKeys: Array = item.dependKeys = []; if (deferredLoadRawAssetsInRuntime) { depends = []; @@ -168,12 +168,7 @@ function loadDepends (pipeline, item, asset, depends, callback) { else { // item was removed from cache, but ready in pipeline actually let queue = LoadingItems.getQueue(item); - // Hack to get a better behavior - let list = queue._callbackTable[dependSrc]; - if (list) { - list.unshift(loadCallback, loadCallbackCtx); - } - else { + if (queue) { queue.addListener(dependSrc, loadCallback, loadCallbackCtx); } } diff --git a/cocos/core/platform/event-manager/event-listener.ts b/cocos/core/platform/event-manager/event-listener.ts index fb4c5ec240..b98b5768b5 100644 --- a/cocos/core/platform/event-manager/event-listener.ts +++ b/cocos/core/platform/event-manager/event-listener.ts @@ -186,8 +186,8 @@ export class EventListener { *


* Sets paused state for the listener
* The paused state is only used for scene graph priority listeners.
- * `EventDispatcher::resumeAllEventListenersForTarget(node)` will set the paused state to `true`,
- * while `EventDispatcher::pauseAllEventListenersForTarget(node)` will set it to `false`.
+ * `EventDispatcher.resumeAllEventListenersForTarget(node)` will set the paused state to `true`,
+ * while `EventDispatcher.pauseAllEventListenersForTarget(node)` will set it to `false`.
* @note 1) Fixed priority listeners will never get paused. If a fixed priority doesn't want to receive events,
* call `setEnabled(false)` instead.
* 2) In `Node`'s onEnter and onExit, the `paused state` of the listeners
diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 0d3c6bd80c..879387d0c0 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -484,7 +484,7 @@ export class Root { this._views = []; } - public createModel (mClass: new () => T): T { + public createModel (mClass: typeof Model): T { let p = this._modelPools.get(mClass); if (!p) { this._modelPools.set(mClass, new Pool(() => new mClass(), 10)); diff --git a/cocos/core/scene-graph/base-node-dev.ts b/cocos/core/scene-graph/base-node-dev.ts index 49d23ecb5d..e65f4544cc 100644 --- a/cocos/core/scene-graph/base-node-dev.ts +++ b/cocos/core/scene-graph/base-node-dev.ts @@ -24,7 +24,7 @@ */ /** - * @category scene-graph + * @hidden */ import { CCObject } from '../data/object'; diff --git a/cocos/core/scene-graph/base-node.ts b/cocos/core/scene-graph/base-node.ts index a2408a0e8c..944df3a365 100644 --- a/cocos/core/scene-graph/base-node.ts +++ b/cocos/core/scene-graph/base-node.ts @@ -40,9 +40,6 @@ import { baseNodePolyfill } from './base-node-dev'; import { NodeEventProcessor } from './node-event-processor'; import { DEV, DEBUG, EDITOR } from 'internal:constants'; -/** - * - */ type Constructor = new (...args: any[]) => T; // @ts-ignore @@ -77,21 +74,18 @@ function getConstructor (typeOrClassName: string | Function): Function | null { } /** - * A base node for CCNode, it will: - * - maintain scene hierarchy and active logic - * - notifications if some properties changed - * - define some interfaces shares between CCNode - * - define machanisms for Enity Component Systems - * - define prefab and serialize functions - * - * @class _BaseNode - * @extends Object - * @uses EventTarget - * @method constructor - * @param {String} [name] - * @protected + * @en The base class for [[Node]], it: + * - maintains scene hierarchy and life cycle logic + * - provides EventTarget ability + * - emits events if some properties changed, ref: [[SystemEventType]] + * - manages components + * @zh [[Node]] 的基类,他会负责: + * - 维护场景树以及节点生命周期管理 + * - 提供 EventTarget 的事件管理和注册能力 + * - 派发节点状态相关的事件,参考:[[SystemEventType]] + * - 管理组件 */ -@ccclass('cc._BaseNode') +@ccclass('cc.BaseNode') export class BaseNode extends CCObject implements ISchedulable { /** * @en Gets all components attached to this node. @@ -102,17 +96,15 @@ export class BaseNode extends CCObject implements ISchedulable { } /** - * @en If true, the node is an persist node which won't be destroyed during scene transition.
+ * @en If true, the node is an persist node which won't be destroyed during scene transition. * If false, the node will be destroyed automatically when loading a new scene. Default is false. - * @zh 如果为true,则该节点是一个常驻节点,不会在场景转换期间被销毁。
- * 如果为false,节点将在加载新场景时自动销毁。默认为false。 - * @property _persistNode - * @type {Boolean} + * @zh 如果为true,则该节点是一个常驻节点,不会在场景转换期间被销毁。 + * 如果为false,节点将在加载新场景时自动销毁。默认为 false。 * @default false * @protected */ @property - get _persistNode () { + get _persistNode (): boolean { return (this._objFlags & DontDestroy) > 0; } set _persistNode (value) { @@ -128,16 +120,9 @@ export class BaseNode extends CCObject implements ISchedulable { /** * @en Name of node. * @zh 该节点名称。 - * @property name - * @type {String} - * @example - * ``` - * node.name = "New Node"; - * cc.log("Node Name: " + node.name); - * ``` */ @property - get name () { + get name (): string { return this._name; } set name (value) { @@ -149,15 +134,9 @@ export class BaseNode extends CCObject implements ISchedulable { } /** - * @en The uuid for editor, will be stripped before building project. + * @en The uuid for editor, will be stripped after building project. * @zh 主要用于编辑器的 uuid,在编辑器下可用于持久化存储,在项目构建之后将变成自增的 id。 - * @property uuid - * @type {String} * @readOnly - * @example - * ``` - * cc.log("Node Uuid: " + node.uuid); - * ``` */ @property get uuid () { @@ -167,16 +146,7 @@ export class BaseNode extends CCObject implements ISchedulable { /** * @en All children nodes. * @zh 节点的所有子节点。 - * @property children - * @type {Node[]} * @readOnly - * @example - * ``` - * var children = node.children; - * for (var i = 0; i < children.length; ++i) { - * cc.log("Node: " + children[i]); - * } - * ``` */ @property get children () { @@ -185,21 +155,15 @@ export class BaseNode extends CCObject implements ISchedulable { /** * @en - * The local active state of this node.
- * Note that a Node may be inactive because a parent is not active, even if this returns true.
+ * The local active state of this node. + * Note that a Node may be inactive because a parent is not active, even if this returns true. * Use [[activeInHierarchy]] * if you want to check if the Node is actually treated as active in the scene. * @zh - * 当前节点的自身激活状态。
- * 值得注意的是,一个节点的父节点如果不被激活,那么即使它自身设为激活,它仍然无法激活。
+ * 当前节点的自身激活状态。 + * 值得注意的是,一个节点的父节点如果不被激活,那么即使它自身设为激活,它仍然无法激活。 * 如果你想检查节点在场景中实际的激活状态可以使用 [[activeInHierarchy]] - * @property active - * @type {Boolean} * @default true - * @example - * ``` - * node.active = false; - * ``` */ @property get active () { @@ -221,18 +185,16 @@ export class BaseNode extends CCObject implements ISchedulable { /** * @en Indicates whether this node is active in the scene. * @zh 表示此节点是否在场景中激活。 - * @property activeInHierarchy - * @type {Boolean} - * @example - * ``` - * cc.log("activeInHierarchy: " + node.activeInHierarchy); - * ``` */ @property get activeInHierarchy () { return this._activeInHierarchy; } + /** + * @en The parent node + * @zh 父节点 + */ @property get parent () { return this._parent; @@ -242,14 +204,19 @@ export class BaseNode extends CCObject implements ISchedulable { } /** - * @en which scene this node belongs to. + * @en Which scene this node belongs to. * @zh 此节点属于哪个场景。 - * @type {cc.Scene}} + * @readonly */ get scene () { return this._scene; } + /** + * @en The event processor of the current node, it provides EventTarget ability. + * @zh 当前节点的事件处理器,提供 EventTarget 能力。 + * @readonly + */ get eventProcessor () { return this._eventProcessor; } @@ -348,42 +315,27 @@ export class BaseNode extends CCObject implements ISchedulable { @property protected _active = true; - /** - * @default [] - * @readOnly - */ @property protected _components: Component[] = []; - /** - * The PrefabInfo object - * @type {PrefabInfo} - */ + // The PrefabInfo object @property protected _prefab: any = null; - /** - * @en which scene this node belongs to. - * @zh 此节点属于哪个场景。 - * @type {cc.Scene}} - */ protected _scene: any = NullScene; protected _activeInHierarchy = false; - // TO DO - // @ts-ignore protected _id: string = idGenerator.getNewId(); protected _name: string; protected _eventProcessor: NodeEventProcessor = new NodeEventProcessor(this); protected _eventMask = 0; - /** - * Register all related EventTargets, - * all event callbacks will be removed in _onPreDestroy - * protected __eventTargets: EventTarget[] = []; - */ + + // Register all related EventTargets, + // all event callbacks will be removed in _onPreDestroy + // protected __eventTargets: EventTarget[] = []; protected __eventTargets: any[] = []; protected _siblingIndex: number = 0; @@ -415,10 +367,6 @@ export class BaseNode extends CCObject implements ISchedulable { } }; - /** - * @method constructor - * @param {String} [name] - */ constructor (name?: string) { super(name); this._name = name !== undefined ? name : 'New Node'; @@ -426,15 +374,15 @@ export class BaseNode extends CCObject implements ISchedulable { /** * @en - * Properties configuration function
- * All properties in attrs will be set to the node,
- * when the setter of the node is available,
- * the property will be set via setter function.
+ * Properties configuration function. + * All properties in attrs will be set to the node, + * when the setter of the node is available, + * the property will be set via setter function. * @zh 属性配置函数。在 attrs 的所有属性将被设置为节点属性。 * @param attrs - Properties to be set to node * @example * ``` - * var attrs = { key: 0, num: 100 }; + * var attrs = { name: 'New Name', active: false }; * node.attr(attrs); * ``` */ @@ -447,10 +395,6 @@ export class BaseNode extends CCObject implements ISchedulable { /** * @en Get parent of the node. * @zh 获取该节点的父节点。 - * @example - * ``` - * var parent = this.node.getParent(); - * ``` */ public getParent () { return this._parent; @@ -459,10 +403,6 @@ export class BaseNode extends CCObject implements ISchedulable { /** * @en Set parent of the node. * @zh 设置该节点的父节点。 - * @example - * ``` - * node.setParent(newNode); - * ``` */ public setParent (value: this | null, keepWorldTransform: boolean = false) { if (this._parent === value) { @@ -513,14 +453,10 @@ export class BaseNode extends CCObject implements ISchedulable { } /** - * @en Returns a child from the container given its uuid. + * @en Returns a child with the same uuid. * @zh 通过 uuid 获取节点的子节点。 * @param uuid - The uuid to find the child node. * @return a Node whose uuid equals to the input parameter - * @example - * ``` - * var child = node.getChildByUuid(uuid); - * ``` */ public getChildByUuid (uuid: string) { if (!uuid) { @@ -538,7 +474,7 @@ export class BaseNode extends CCObject implements ISchedulable { } /** - * @en Returns a child from the container given its name. + * @en Returns a child with the same name. * @zh 通过名称获取节点的子节点。 * @param name - A name to find the child node. * @return a CCNode object whose name equals to the input parameter @@ -563,13 +499,13 @@ export class BaseNode extends CCObject implements ISchedulable { } /** - * @en Returns a child from the container given its path. + * @en Returns a child with the given path. * @zh 通过路径获取节点的子节点。 * @param path - A path to find the child node. - * @return a CCNode object whose name equals to the input parameter + * @return a Node object whose path equals to the input parameter * @example * ``` - * var child = node.getChildByPath("Test Node"); + * var child = node.getChildByPath("subNode/Test Node"); * ``` */ public getChildByPath (path: string) { @@ -589,6 +525,11 @@ export class BaseNode extends CCObject implements ISchedulable { return lastNode; } + /** + * @en Add a child to the current node, it will be pushed to the end of [[children]] array. + * @zh 添加一个子节点,它会被添加到 [[children]] 数组的末尾。 + * @param child - the child node to be added + */ public addChild (child: this): void { if (DEV && !(child instanceof cc._BaseNode)) { @@ -603,14 +544,10 @@ export class BaseNode extends CCObject implements ISchedulable { } /** - * @en - * Inserts a child to the node at a specified index. - * @zh - * 插入子节点到指定位置 + * @en Inserts a child to the node at a specified index. + * @zh 插入子节点到指定位置 * @param child - the child node to be inserted - * 要插入的子节点 * @param siblingIndex - the sibling index to place the child in - * 用于放置子节点的同级索引 * @example * ``` * node.insertChild(child, 2); @@ -622,24 +559,16 @@ export class BaseNode extends CCObject implements ISchedulable { } /** - * @en Get the sibling index. - * @zh 获取同级索引。 - * @example - * ``` - * var index = node.getSiblingIndex(); - * ``` + * @en Get the sibling index of the current node in its parent's children array. + * @zh 获取当前节点在父节点的 children 数组中的位置。 */ public getSiblingIndex () { return this._siblingIndex; } /** - * @en Set the sibling index of this node. - * @zh 设置节点同级索引。 - * @example - * ``` - * node.setSiblingIndex(1); - * ``` + * @en Set the sibling index of the current node in its parent's children array. + * @zh 设置当前节点在父节点的 children 数组中的位置。 */ public setSiblingIndex (index: number) { if (!this._parent) { @@ -673,11 +602,11 @@ export class BaseNode extends CCObject implements ISchedulable { * This function call is not recursive, it's based on stack. * Please don't walk any other node inside the walk process. * @zh 遍历该节点的子树里的所有节点并按规则执行回调函数。 - * 对子树中的所有节点,包含当前节点,会执行两次回调,prefunc 会在访问它的子节点之前调用,postfunc 会在访问所有子节点之后调用。 + * 对子树中的所有节点,包含当前节点,会执行两次回调,preFunc 会在访问它的子节点之前调用,postFunc 会在访问所有子节点之后调用。 * 这个函数的实现不是基于递归的,而是基于栈展开递归的方式。 * 请不要在 walk 过程中对任何其他的节点嵌套执行 walk。 - * @param prefunc The callback to process node when reach the node for the first time - * @param postfunc The callback to process node when re-visit the node after walked all children in its sub tree + * @param preFunc The callback to process node when reach the node for the first time + * @param postFunc The callback to process node when re-visit the node after walked all children in its sub tree * @example * ``` * node.walk(function (target) { @@ -687,7 +616,7 @@ export class BaseNode extends CCObject implements ISchedulable { * }); * ``` */ - public walk (prefunc: (target: this) => void, postfunc?: (target: this) => void) { + public walk (preFunc: (target: this) => void, postFunc?: (target: this) => void) { // const BaseNode = cc._BaseNode; let index = 1; let children: this[] | null = null; @@ -710,12 +639,12 @@ export class BaseNode extends CCObject implements ISchedulable { if (!curr) { continue; } - if (!afterChildren && prefunc) { + if (!afterChildren && preFunc) { // pre call - prefunc(curr); - } else if (afterChildren && postfunc) { + preFunc(curr); + } else if (afterChildren && postFunc) { // post call - postfunc(curr); + postFunc(curr); } // Avoid memory leak @@ -773,16 +702,11 @@ export class BaseNode extends CCObject implements ISchedulable { /** * @en - * Remove itself from its parent node.
- * If the node orphan, then nothing happens. + * Remove itself from its parent node. + * If the node have no parent, then nothing happens. * @zh - * 从父节点中删除该节点。
- * 如果这个节点是一个孤节点,那么什么都不会发生。 - * @see cc.Node#removeFromParentAndCleanup - * @example - * ``` - * node.removeFromParent(); - * ``` + * 从父节点中删除该节点。 + * 如果这个节点是一个孤立节点,那么什么都不会发生。 */ public removeFromParent () { if (this._parent) { @@ -791,16 +715,9 @@ export class BaseNode extends CCObject implements ISchedulable { } /** - * @en - * Removes a child from the container. - * @zh - * 移除节点中指定的子节点。 + * @en Removes a child from the container. + * @zh 移除节点中指定的子节点。 * @param child - The child node which will be removed. - * 将被移除的子节点 - * @example - * ``` - * node.removeChild(newNode); - * ``` */ public removeChild (child: this) { if (this._children.indexOf(child) > -1) { @@ -810,14 +727,8 @@ export class BaseNode extends CCObject implements ISchedulable { } /** - * @en - * Removes all children from the container. - * @zh - * 移除节点所有的子节点。 - * @example - * ``` - * node.removeAllChildren(); - * ``` + * @en Removes all children from the container. + * @zh 移除节点所有的子节点。 */ public removeAllChildren () { // not using detachChild improves speed here @@ -835,11 +746,6 @@ export class BaseNode extends CCObject implements ISchedulable { * @en Is this node a child of the given node? * @zh 是否是指定节点的子节点? * @return True if this node is a child, deep child or identical to the given node. - * @return 如果此节点是子节点、深度子节点或与给定节点相同,则为True。 - * @example - * ``` - * node.isChildOf(newNode); - * ``` */ public isChildOf (parent: this | null): boolean { let child: BaseNode | null = this; @@ -857,29 +763,31 @@ export class BaseNode extends CCObject implements ISchedulable { /** * @en - * Returns the component of supplied type if the node has one attached, null if it doesn't.
+ * Returns the component of supplied type if the node has one attached, null if it doesn't. * You can also get component in the node by passing in the name of the script. * @zh - * 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。
+ * 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。 * 传入参数也可以是脚本的名称。 + * @param classConstructor The class of the target component * @example * ``` * // get sprite component. - * var sprite = node.getComponent(cc.SpriteComponent); + * var sprite = node.getComponent(SpriteComponent); * ``` */ public getComponent (classConstructor: Constructor): T | null; /** * @en - * Returns the component of supplied type if the node has one attached, null if it doesn't.
+ * Returns the component of supplied type if the node has one attached, null if it doesn't. * You can also get component in the node by passing in the name of the script. * @zh - * 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。
+ * 获取节点上指定类型的组件,如果节点有附加指定类型的组件,则返回,如果没有则为空。 * 传入参数也可以是脚本的名称。 + * @param className The class name of the target component * @example * ``` - * // get custom test calss. + * // get custom test class. * var test = node.getComponent("Test"); * ``` */ @@ -894,22 +802,16 @@ export class BaseNode extends CCObject implements ISchedulable { } /** - * @en Returns all components of supplied type in the node. + * @en Returns all components of given type in the node. * @zh 返回节点上指定类型的所有组件。 - * @example - * ``` - * var sprites = node.getComponents(cc.SpriteComponent); - * ``` + * @param classConstructor The class of the target component */ public getComponents (classConstructor: Constructor): T[]; /** - * @en Returns all components of supplied type in the node. + * @en Returns all components of given type in the node. * @zh 返回节点上指定类型的所有组件。 - * @example - * ``` - * var tests = node.getComponents("Test"); - * ``` + * @param className The class name of the target component */ public getComponents (className: string): Component[]; @@ -923,18 +825,20 @@ export class BaseNode extends CCObject implements ISchedulable { } /** - * @en Returns the component of supplied type in any of its children using depth first search. + * @en Returns the component of given type in any of its children using depth first search. * @zh 递归查找所有子节点中第一个匹配指定类型的组件。 + * @param classConstructor The class of the target component * @example * ``` - * var sprite = node.getComponentInChildren(cc.SpriteComponent); + * var sprite = node.getComponentInChildren(SpriteComponent); * ``` */ public getComponentInChildren (classConstructor: Constructor): T | null; /** - * @en Returns the component of supplied type in any of its children using depth first search. + * @en Returns the component of given type in any of its children using depth first search. * @zh 递归查找所有子节点中第一个匹配指定类型的组件。 + * @param className The class name of the target component * @example * ``` * var Test = node.getComponentInChildren("Test"); @@ -951,18 +855,20 @@ export class BaseNode extends CCObject implements ISchedulable { } /** - * @en Returns all components of supplied type in self or any of its children. + * @en Returns all components of given type in self or any of its children. * @zh 递归查找自身或所有子节点中指定类型的组件 + * @param classConstructor The class of the target component * @example * ``` - * var sprites = node.getComponentsInChildren(cc.SpriteComponent); + * var sprites = node.getComponentsInChildren(SpriteComponent); * ``` */ public getComponentsInChildren (classConstructor: Constructor): T[]; /** - * @en Returns all components of supplied type in self or any of its children. + * @en Returns all components of given type in self or any of its children. * @zh 递归查找自身或所有子节点中指定类型的组件 + * @param className The class name of the target component * @example * ``` * var tests = node.getComponentsInChildren("Test"); @@ -983,9 +889,10 @@ export class BaseNode extends CCObject implements ISchedulable { /** * @en Adds a component class to the node. You can also add component to node by passing in the name of the script. * @zh 向节点添加一个指定类型的组件类,你还可以通过传入脚本的名称来添加组件。 + * @param classConstructor The class of the component to add * @example * ``` - * var sprite = node.addComponent(cc.SpriteComponent); + * var sprite = node.addComponent(SpriteComponent); * ``` */ public addComponent (classConstructor: Constructor): T | null; @@ -993,6 +900,7 @@ export class BaseNode extends CCObject implements ISchedulable { /** * @en Adds a component class to the node. You can also add component to node by passing in the name of the script. * @zh 向节点添加一个指定类型的组件类,你还可以通过传入脚本的名称来添加组件。 + * @param className The class name of the component to add * @example * ``` * var test = node.addComponent("Test"); @@ -1085,11 +993,11 @@ export class BaseNode extends CCObject implements ISchedulable { * @zh * 删除节点上的指定组件,传入参数可以是一个组件构造函数或组件名,也可以是已经获得的组件引用。 * 如果你已经获得组件引用,你也可以直接调用 component.destroy() + * @param classConstructor The class of the component to remove * @deprecated please destroy the component to remove it. - * 请销毁组件以移除它。 * @example * ``` - * node.removeComponent(cc.SpriteComponent); + * node.removeComponent(SpriteComponent); * ``` */ public removeComponent (classConstructor: Constructor): void; @@ -1101,6 +1009,7 @@ export class BaseNode extends CCObject implements ISchedulable { * @zh * 删除节点上的指定组件,传入参数可以是一个组件构造函数或组件名,也可以是已经获得的组件引用。 * 如果你已经获得组件引用,你也可以直接调用 component.destroy() + * @param classNameOrInstance The class name of the component to remove or the component instance to be removed * @deprecated please destroy the component to remove it. * @example * ``` @@ -1131,7 +1040,44 @@ export class BaseNode extends CCObject implements ISchedulable { // EVENT PROCESSING - public on (type: string | SystemEventType, callback: Function, target?: Object, useCapture?: any) { + /** + * @en + * Register a callback of a specific event type on Node. + * Use this method to register touch or mouse event permit propagation based on scene graph, + * These kinds of event are triggered with dispatchEvent, the dispatch process has three steps: + * 1. Capturing phase: dispatch in capture targets (`_getCapturingTargets`), e.g. parents in node tree, from root to the real target + * 2. At target phase: dispatch to the listeners of the real target + * 3. Bubbling phase: dispatch in bubble targets (`_getBubblingTargets`), e.g. parents in node tree, from the real target to root + * In any moment of the dispatching process, it can be stopped via `event.stopPropagation()` or `event.stopPropagationImmidiate()`. + * It's the recommended way to register touch/mouse event for Node, + * please do not use cc.eventManager directly for Node. + * You can also register custom event and use `emit` to trigger custom event on Node. + * 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. + * You can also pass event callback parameters with `emit` by passing parameters after `type`. + * @zh + * 在节点上注册指定类型的回调函数,也可以设置 target 用于绑定响应函数的 this 对象。 + * 鼠标或触摸事件会被系统调用 dispatchEvent 方法触发,触发的过程包含三个阶段: + * 1. 捕获阶段:派发事件给捕获目标(通过 `_getCapturingTargets` 获取),比如,节点树中注册了捕获阶段的父节点,从根节点开始派发直到目标节点。 + * 2. 目标阶段:派发给目标节点的监听器。 + * 3. 冒泡阶段:派发事件给冒泡目标(通过 `_getBubblingTargets` 获取),比如,节点树中注册了冒泡阶段的父节点,从目标节点开始派发直到根节点。 + * 同时您可以将事件派发到父节点或者通过调用 stopPropagation 拦截它。 + * 推荐使用这种方式来监听节点上的触摸或鼠标事件,请不要在节点上直接使用 cc.eventManager。 + * 你也可以注册自定义事件到节点上,并通过 emit 方法触发此类事件,对于这类事件,不会发生捕获冒泡阶段,只会直接派发给注册在该节点上的监听器 + * 你可以通过在 emit 方法调用时在 type 之后传递额外的参数作为事件回调的参数列表 + * @param type - A string representing the event type to listen for.
See {{#crossLink "Node/EventTyupe/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events. + * @param 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 target - The target (this object) to invoke the callback, can be null + * @param useCapture - 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 - Just returns the incoming callback so you can save the anonymous function easier. + * @example + * ```typescript + * this.node.on(SystemEventType.TOUCH_START, this.memberFunction, this); // if "this" is component and the "memberFunction" declared in CCClass. + * node.on(SystemEventType.TOUCH_START, callback, this); + * node.on(SystemEventType.TOUCH_MOVE, callback, this); + * node.on(SystemEventType.TOUCH_END, callback, this); + * ``` + */ + public on (type: string | SystemEventType, callback: Function, target?: Object, useCapture: any = false) { switch (type) { case SystemEventType.TRANSFORM_CHANGED: this._eventMask |= TRANSFORM_ON; @@ -1140,7 +1086,22 @@ export class BaseNode extends CCObject implements ISchedulable { this._eventProcessor.on(type, callback, target, useCapture); } - public off (type: string, callback?: Function, target?: Object, useCapture?: any) { + /** + * @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 注册的回调。 + * @param type - A string representing the event type being removed. + * @param callback - The callback to remove. + * @param target - The target (this object) to invoke the callback, if it's not given, only callback without target will be removed + * @param useCapture - 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 + * ```typescript + * this.node.off(SystemEventType.TOUCH_START, this.memberFunction, this); + * node.off(SystemEventType.TOUCH_START, callback, this.node); + * ``` + */ + public off (type: string, callback?: Function, target?: Object, useCapture: any = false) { this._eventProcessor.off(type, callback, target, useCapture); const hasListeners = this._eventProcessor.hasEventListener(type); @@ -1154,22 +1115,69 @@ export class BaseNode extends CCObject implements ISchedulable { } } + /** + * @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 + * 注册节点的特定事件类型回调,回调会在第一时间被触发后删除自身。 + * + * @param type - A string representing the event type to listen for. + * @param 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 target - The target (this object) to invoke the callback, can be null + */ public once (type: string, callback: Function, target?: Object, useCapture?: any) { this._eventProcessor.once(type, callback, target, useCapture); } + /** + * @en + * Trigger an event directly with the event name and necessary arguments. + * @zh + * 通过事件名发送自定义事件 + * @param 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 + * ```typescript + * eventTarget.emit('fire', event); + * eventTarget.emit('fire', message, emitter); + * ``` + */ public emit (type: string, ...args: any[]) { this._eventProcessor.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 分发事件到事件流中。 + * @param event - The Event object that is dispatched into the event flow + */ public dispatchEvent (event: Event) { this._eventProcessor.dispatchEvent(event); } + /** + * @en Checks whether the EventTarget object has any callback registered for a specific type of event. + * @zh 检查事件目标对象是否有为特定类型的事件注册的回调。 + * @param type - The type of event. + * @return True if a callback of the specified type is registered; false otherwise. + */ public hasEventListener (type: string) { return this._eventProcessor.hasEventListener(type); } + /** + * @en Removes all callbacks previously registered with the same target. + * @zh 移除目标上的所有注册事件。 + * @param target - The target to be searched for all related callbacks + */ public targetOff (target: string | Object) { this._eventProcessor.targetOff(target); // Check for event mask reset @@ -1193,15 +1201,11 @@ export class BaseNode extends CCObject implements ISchedulable { /** * @en - * Destroy all children from the node, and release all their own references to other objects.
+ * Destroy all children from the node, and release all their own references to other objects. * Actual destruct operation will delayed until before rendering. * @zh - * 销毁所有子节点,并释放所有它们对其它对象的引用。
+ * 销毁所有子节点,并释放所有它们对其它对象的引用。 * 实际销毁操作会延迟到当前帧渲染前执行。 - * @example - * ``` - * node.destroyAllChildren(); - * ``` */ public destroyAllChildren () { const children = this._children; diff --git a/cocos/core/scene-graph/component-scheduler.ts b/cocos/core/scene-graph/component-scheduler.ts index d5541441dc..5fa3b8c1a4 100644 --- a/cocos/core/scene-graph/component-scheduler.ts +++ b/cocos/core/scene-graph/component-scheduler.ts @@ -215,7 +215,7 @@ function enableInEditor (comp) { } // return function to simply call each component with try catch protection -export function createInvokeImplJit (code:string, useDt?, ensureFlag?) { +export function createInvokeImplJit (code: string, useDt?, ensureFlag?) { // function (it) { // let a = it.array; // for (it.i = 0; it.i < a.length; ++it.i) { @@ -332,11 +332,26 @@ export const invokeOnEnable = EDITOR ? (iterator) => { }; /** - * The Manager for Component's life-cycle methods. + * @en The Manager for Component's life-cycle methods. + * It collaborates with [[NodeActivator]] to schedule and invoke life cycle methods for components + * @zh 组件生命周期函数的调度器。 + * 它和 [[NodeActivator]] 一起调度并执行组件的生命周期函数。 */ export class ComponentScheduler { + /** + * @en The invoker of `start` callback + * @zh `start` 回调的调度器 + */ public startInvoker!: OneOffInvoker; + /** + * @en The invoker of `update` callback + * @zh `update` 回调的调度器 + */ public updateInvoker!: ReusableInvoker; + /** + * @en The invoker of `lateUpdate` callback + * @zh `lateUpdate` 回调的调度器 + */ public lateUpdateInvoker!: ReusableInvoker; // components deferred to schedule private _deferredComps: any[] = []; @@ -346,6 +361,10 @@ export class ComponentScheduler { this.unscheduleAll(); } + /** + * @en Cancel all future callbacks, including `start`, `update` and `lateUpdate` + * @zh 取消所有未来的函数调度,包括 `start`,`update` 和 `lateUpdate` + */ public unscheduleAll () { // invokers this.startInvoker = new OneOffInvoker(invokeStart); @@ -392,6 +411,12 @@ export class ComponentScheduler { } } + /** + * @en Enable a component + * @zh 启用一个组件 + * @param comp The component to be enabled + * @param invoker The invoker which is responsible to schedule the `onEnable` call + */ public enableComp (comp, invoker?) { if (!(comp._objFlags & IsOnEnableCalled)) { if (comp.onEnable) { @@ -412,6 +437,11 @@ export class ComponentScheduler { } } + /** + * @en Disable a component + * @zh 禁用一个组件 + * @param comp The component to be disabled + */ public disableComp (comp) { if (comp._objFlags & IsOnEnableCalled) { if (comp.onDisable) { @@ -421,6 +451,10 @@ export class ComponentScheduler { } } + /** + * @en Process start phase for registered components + * @zh 为当前注册的组件执行 start 阶段任务 + */ public startPhase () { // Start of this frame this._updating = true; @@ -446,11 +480,21 @@ export class ComponentScheduler { // } } - public updatePhase (dt) { + /** + * @en Process update phase for registered components + * @zh 为当前注册的组件执行 update 阶段任务 + * @param dt 距离上一帧的时间 + */ + public updatePhase (dt:number) { this.updateInvoker.invoke(dt); } - public lateUpdatePhase (dt) { + /** + * @en Process late update phase for registered components + * @zh 为当前注册的组件执行 late update 阶段任务 + * @param dt 距离上一帧的时间 + */ + public lateUpdatePhase (dt:number) { this.lateUpdateInvoker.invoke(dt); // End of this frame diff --git a/cocos/core/scene-graph/find.ts b/cocos/core/scene-graph/find.ts index e98c677ebb..df1dc132dd 100644 --- a/cocos/core/scene-graph/find.ts +++ b/cocos/core/scene-graph/find.ts @@ -32,10 +32,14 @@ import { Node } from './node'; import { DEV } from 'internal:constants'; /** - * Finds a node by hierarchy path, the path is case-sensitive. + * @en Finds a node by hierarchy path, the path is case-sensitive. * It will traverse the hierarchy by splitting the path using '/' character. * This function will still returns the node even if it is inactive. * It is recommended to not use this function every frame instead cache the result at startup. + * @zh 通过路径从节点树中查找节点的方法,路径是大小写敏感的,并且通过 `/` 来分隔节点层级。 + * 即使节点的状态是未启用的也可以找到,建议将结果缓存,而不是每次需要都去查找。 + * @param path The path of the target node + * @param referenceNode If given, the search will be limited in the sub node tree of the reference node */ export function find (path: string, referenceNode?: Node): Node | null { if (!referenceNode) { diff --git a/cocos/core/scene-graph/layers.ts b/cocos/core/scene-graph/layers.ts index d6740d0e9d..f0f11f5a56 100644 --- a/cocos/core/scene-graph/layers.ts +++ b/cocos/core/scene-graph/layers.ts @@ -45,12 +45,23 @@ const layerList = { }; /** - * 场景节点层管理器,用于射线检测、物理碰撞和用户自定义脚本逻辑。 + * @zh 节点层管理器,层数据是以掩码数据方式存储在 [[Node.layer]] 中,用于射线检测、物理碰撞和用户自定义脚本逻辑。 * 每个节点可属于一个或多个层,可通过 “包含式” 或 “排除式” 两种检测器进行层检测。 + * @en Node's layer manager, it's stored as bit mask data in [[Node.layer]]. + * Layer information is widely used in raycast, physics and user logic. + * Every node can be assigned to multiple layers with different bit masks, you can setup layer with inclusive or exclusive operation. */ export class Layers { + /** + * @en All layers in an Enum + * @zh 以 Enum 形式存在的所有层列表 + */ public static Enum = Enum(layerList); + /** + * @en All layers in [[BitMask]] type + * @zh 包含所有层的 [[BitMask]] + */ public static BitMask = BitMask(Object.assign({}, layerList)); /** @@ -58,8 +69,8 @@ export class Layers { * Make a layer mask accepting nothing but the listed layers * @zh * 创建一个包含式层检测器,只接受列表中的层 - * @param includes 可接受的层数组 - * @return 指定功能的层检测器 + * @param includes All accepted layers + * @return A filter which can detect all accepted layers */ public static makeMaskInclude (includes: number[]): number { let mask = 0; @@ -74,8 +85,8 @@ export class Layers { * Make a layer mask accepting everything but the listed layers * @zh * 创建一个排除式层检测器,只拒绝列表中的层 - * @param excludes 将拒绝的层数组 - * @return 指定功能的层检测器 + * @param excludes All excluded layers + * @return A filter which can detect for excluded layers */ public static makeMaskExclude (excludes: number[]): number { return ~Layers.makeMaskInclude(excludes); @@ -83,10 +94,11 @@ export class Layers { /** * @zh 添加一个新层,用户可编辑 0 - 19 位为用户自定义层 - * @param name 层名字 - * @param bitNum 层序号 + * @en Add a new layer, user can use layers from bit position 0 to 19, other bits are reserved. + * @param name Layer's name + * @param bitNum Layer's bit position */ - public static addLayer ( name: string, bitNum: number) { + public static addLayer (name: string, bitNum: number) { if ( bitNum === undefined ) { console.warn('bitNum can\'t be undefined'); return; @@ -102,9 +114,9 @@ export class Layers { } /** - * @zh - * 移除一个层,用户可编辑 0 - 19 位为用户自定义层 - * @param bitNum 层序号 + * @en Remove a layer, user can remove layers from bit position 0 to 19, other bits are reserved. + * @zh 移除一个层,用户可编辑 0 - 19 位为用户自定义层 + * @param bitNum Layer's bit position */ public static deleteLayer (bitNum: number) { if ( bitNum > 19 || bitNum < 0) { diff --git a/cocos/core/scene-graph/node-activator.ts b/cocos/core/scene-graph/node-activator.ts index 86c41ab564..92902f4f9d 100644 --- a/cocos/core/scene-graph/node-activator.ts +++ b/cocos/core/scene-graph/node-activator.ts @@ -162,7 +162,7 @@ function _onLoadInEditor (comp) { /** * @en The class used to perform activating and deactivating operations of node and component. - * @zh 用于执行节点和组件的激活和停用操作的类。 + * @zh 用于执行节点和组件的激活和停用操作的管理器。 */ export default class NodeActivator { public resetComp: any; @@ -172,11 +172,21 @@ export default class NodeActivator { this.reset(); } + /** + * @en Reset all activation or des-activation tasks + * @zh 重置所有激活或非激活任务 + */ public reset () { // a stack of node's activating tasks this._activatingStack = []; } + /** + * @en Activate or des-activate a node + * @zh 激活或者停用某个节点 + * @param node Target node + * @param active Which state to set the node to + */ public activateNode (node, active) { if (active) { const task: any = activateTasksPool.get(); @@ -205,6 +215,14 @@ export default class NodeActivator { node.emit('active-in-hierarchy-changed', node); } + /** + * @en Activate or des-activate a component + * @zh 激活或者停用某个组件 + * @param comp Target component + * @param preloadInvoker The invoker for `_preload` method, normally from [[ComponentScheduler]] + * @param onLoadInvoker The invoker for `onLoad` method, normally from [[ComponentScheduler]] + * @param onEnableInvoker The invoker for `onEnable` method, normally from [[ComponentScheduler]] + */ public activateComp (comp, preloadInvoker?, onLoadInvoker?, onEnableInvoker?) { if (!(comp._objFlags & IsPreloadStarted)) { comp._objFlags |= IsPreloadStarted; @@ -241,6 +259,11 @@ export default class NodeActivator { } } + /** + * @en Destroy a component + * @zh 销毁一个组件 + * @param comp Target component + */ public destroyComp (comp) { // ensure onDisable called cc.director._compScheduler.disableComp(comp); diff --git a/cocos/core/scene-graph/node-enum.ts b/cocos/core/scene-graph/node-enum.ts index 4262fd9747..445832d001 100644 --- a/cocos/core/scene-graph/node-enum.ts +++ b/cocos/core/scene-graph/node-enum.ts @@ -27,13 +27,19 @@ * @category scene-graph */ -import { ccenum } from '../value-types/enum'; - +/** + * @en Node's coordinate space + * @zh 节点的坐标空间 + */ export enum NodeSpace { LOCAL, WORLD, } +/** + * @en Bit masks for node's transformation + * @zh 节点的空间变换位标记 + */ export enum TransformBit { /** * @zh diff --git a/cocos/core/scene-graph/node-event-processor.ts b/cocos/core/scene-graph/node-event-processor.ts index fed183a1b2..d9e4a3259d 100644 --- a/cocos/core/scene-graph/node-event-processor.ts +++ b/cocos/core/scene-graph/node-event-processor.ts @@ -24,7 +24,7 @@ */ /** - * @category scene-graph + * @hidden */ import Event from '../event/event'; diff --git a/cocos/core/scene-graph/node-ui-properties.ts b/cocos/core/scene-graph/node-ui-properties.ts index 008b3e7fa4..713e75753f 100644 --- a/cocos/core/scene-graph/node-ui-properties.ts +++ b/cocos/core/scene-graph/node-ui-properties.ts @@ -30,7 +30,15 @@ import { UIComponent } from '../components/ui-base/ui-component'; import { UITransformComponent } from '../components/ui-base/ui-transform-component'; +/** + * @en Node's UI properties abstraction + * @zh 节点上 UI 相关的属性抽象类 + */ export class NodeUIProperties { + /** + * @en The UI transform component + * @zh UI 变换组件 + */ get uiTransformComp () { if (!this._uiTransformComp) { this._uiTransformComp = this._node.getComponent(UITransformComponent); @@ -38,12 +46,19 @@ export class NodeUIProperties { return this._uiTransformComp; } - set uiTransformComp (value) { this._uiTransformComp = value; } + /** + * @en The base UI component + * @zh UI 基类组件 + */ public uiComp: UIComponent | null = null; + /** + * @en The opacity of the UI node + * @zh UI 透明度 + */ public opacity = 1; protected _uiTransformComp: UITransformComponent | null = null; private _node: any; diff --git a/cocos/core/scene-graph/node.ts b/cocos/core/scene-graph/node.ts index fed25379a2..653c425f31 100644 --- a/cocos/core/scene-graph/node.ts +++ b/cocos/core/scene-graph/node.ts @@ -27,7 +27,6 @@ * @category scene-graph */ -import { UIComponent, UITransformComponent } from '../components/ui-base'; import { ccclass, property } from '../data/class-decorator'; import { Mat3, Mat4, Quat, Size, Vec2, Vec3 } from '../math'; import { SystemEventType } from '../platform/event-manager/event-enum'; @@ -54,36 +53,50 @@ const bookOfChange = new Map(); * * 持有各类组件 * * 维护空间变换(坐标、旋转、缩放)信息 */ + +/** + * !#en + * Class of all entities in Cocos Creator scenes. + * Basic functionalities include: + * * Hierarchy management with parent and children + * * Components management + * * Coordinate system with position, scale, rotation in 3d space + * !#zh + * Cocos Creator 场景中的所有节点类。 + * 基本特性有: + * * 具有层级关系 + * * 持有各类组件 + * * 维护 3D 空间左边变换(坐标、旋转、缩放)信息 + */ @ccclass('cc.Node') export class Node extends BaseNode { public static bookOfChange = bookOfChange; /** - * @zh - * 节点可能发出的事件类型 + * @en Event types emitted by Node + * @zh 节点可能发出的事件类型 */ public static EventType = SystemEventType; /** - * @zh - * 空间变换操作的坐标系 + * @en Coordinates space + * @zh 空间变换操作的坐标系 */ public static NodeSpace = NodeSpace; /** - * @zh - * 节点变换更新的具体部分 - * @deprecated 请使用 [Node.TransformBit] + * @en Bit masks for Node transformation parts + * @zh 节点变换更新的具体部分 + * @deprecated please use [[Node.TransformBit]] */ public static TransformDirtyBit = TransformBit; /** - * @zh - * 节点变换更新的具体部分,可用于判断 TRANSFORM_CHANGED 事件的具体类型 + * @en Bit masks for Node transformation parts, can be used to determine which part changed in [[SystemEventType.TRANSFORM_CHANGED]] event + * @zh 节点变换更新的具体部分,可用于判断 [[SystemEventType.TRANSFORM_CHANGED]] 事件的具体类型 */ public static TransformBit = TransformBit; /** - * @zh - * 指定对象是否是普通的场景节点? - * @param obj 待测试的节点 + * @en Determine whether the given object is a normal Node. Will return false if [[Scene]] given. + * @zh 指定对象是否是普通的节点?如果传入 [[Scene]] 会返回 false。 */ public static isNode (obj: object | null): obj is Node { return obj instanceof Node && (obj.constructor === Node || !(obj instanceof cc.Scene)); @@ -117,8 +130,8 @@ export class Node extends BaseNode { protected _eulerDirty = false; /** - * @zh - * 本地坐标 + * @en Position in local coordinate system + * @zh 本地坐标系下的坐标 */ // @constget public get position (): Readonly { @@ -129,8 +142,8 @@ export class Node extends BaseNode { } /** - * @zh - * 世界坐标 + * @en Position in world coordinate system + * @zh 世界坐标系下的坐标 */ // @constget public get worldPosition (): Readonly { @@ -142,8 +155,8 @@ export class Node extends BaseNode { } /** - * @zh - * 本地旋转 + * @en Rotation in local coordinate system, represented by a quaternion + * @zh 本地坐标系下的旋转,用四元数表示 */ // @constget public get rotation (): Readonly { @@ -154,8 +167,8 @@ export class Node extends BaseNode { } /** - * @zh - * 以欧拉角表示的本地旋转值 + * @en Rotation in local coordinate system, represented by euler angles + * @zh 本地坐标系下的旋转,用欧拉角表示 */ @property({ type: Vec3 }) set eulerAngles (val: Readonly) { @@ -170,8 +183,8 @@ export class Node extends BaseNode { } /** - * @zh - * 世界旋转 + * @en Rotation in world coordinate system, represented by a quaternion + * @zh 世界坐标系下的旋转,用四元数表示 */ // @constget public get worldRotation (): Readonly { @@ -183,8 +196,8 @@ export class Node extends BaseNode { } /** - * @zh - * 本地缩放 + * @en Scale in local coordinate system + * @zh 本地坐标系下的缩放 */ // @constget public get scale (): Readonly { @@ -195,8 +208,8 @@ export class Node extends BaseNode { } /** - * @zh - * 世界缩放 + * @en Scale in world coordinate system + * @zh 世界坐标系下的缩放 */ // @constget public get worldScale (): Readonly { @@ -208,8 +221,8 @@ export class Node extends BaseNode { } /** - * @zh - * 本地变换矩阵 + * @en Local transformation matrix + * @zh 本地坐标系变换矩阵 */ public set matrix (val: Readonly) { Mat4.toRTS(val, this._lrot, this._lpos, this._lscale); @@ -221,8 +234,8 @@ export class Node extends BaseNode { } /** - * @zh - * 世界变换矩阵 + * @en World transformation matrix + * @zh 世界坐标系变换矩阵 */ // @constget public get worldMatrix (): Readonly { @@ -231,8 +244,8 @@ export class Node extends BaseNode { } /** - * @zh - * 当前节点面向的前方方向,默认前方为 -z 方向 + * @en The vector representing forward direction in local coordinate system, it's the minus z direction by default + * @zh 当前节点面向的前方方向,默认前方为 -z 方向 */ get forward (): Vec3 { return Vec3.transformQuat(new Vec3(), Vec3.FORWARD, this.worldRotation); @@ -245,8 +258,8 @@ export class Node extends BaseNode { } /** - * @zh - * 节点所属层,主要影响射线检测、物理碰撞等,参考 [[Layers]] + * @en Layer of the current Node, it affects raycast, physics etc, refer to [[Layers]] + * @zh 节点所属层,主要影响射线检测、物理碰撞等,参考 [[Layers]] */ @property set layer (l) { @@ -257,8 +270,8 @@ export class Node extends BaseNode { } /** - * @zh - * 这个节点的空间变换信息在当前帧内是否有变过? + * @en Whether the node's transformation have changed during the current frame. + * @zh 这个节点的空间变换信息在当前帧内是否有变过? */ get hasChangedFlags () { return bookOfChange.get(this._id) || 0; @@ -304,10 +317,10 @@ export class Node extends BaseNode { // =============================== /** - * @zh - * 设置父节点 - * @param value 父节点 - * @param keepWorldTransform 是否保留当前世界变换 + * @en Set parent of the node. + * @zh 设置该节点的父节点。 + * @param value Parent node + * @param keepWorldTransform Whether keep node's current world transform unchanged after this operation */ public setParent (value: this | null, keepWorldTransform: boolean = false) { if (keepWorldTransform) { this.updateWorldTransform(); } @@ -357,10 +370,10 @@ export class Node extends BaseNode { // =============================== /** - * @zh - * 移动节点 - * @param trans 位置增量 - * @param ns 操作空间 + * @en Perform a translation on the node + * @zh 移动节点 + * @param trans The increment on position + * @param ns The operation coordinate space */ public translate (trans: Vec3, ns?: NodeSpace): void { const space = ns || NodeSpace.LOCAL; @@ -391,10 +404,10 @@ export class Node extends BaseNode { } /** - * @zh - * 旋转节点 - * @param trans 旋转增量 - * @param ns 操作空间 + * @en Perform a rotation on the node + * @zh 旋转节点 + * @param trans The increment on position + * @param ns The operation coordinate space */ public rotate (rot: Quat, ns?: NodeSpace): void { const space = ns || NodeSpace.LOCAL; @@ -418,10 +431,10 @@ export class Node extends BaseNode { } /** - * @zh - * 设置当前节点旋转为面向目标位置,默认前方为 -z 方向 - * @param pos 目标位置 - * @param up 坐标系的上方向 + * @en Set the orientation of the node to face the target position, the node is facing minus z direction by default + * @zh 设置当前节点旋转为面向目标位置,默认前方为 -z 方向 + * @param pos Target position + * @param up Up direction */ public lookAt (pos: Vec3, up?: Vec3): void { this.getWorldPosition(v3_a); @@ -436,11 +449,10 @@ export class Node extends BaseNode { // =============================== /** - * @en - * invalidate the world transform information + * @en Invalidate the world transform information * for this node and all its children recursively - * @zh - * 递归标记节点世界变换为 dirty + * @zh 递归标记节点世界变换为 dirty + * @param dirtyBit The dirty bits to setup to children, can be composed with multiple dirty bits */ public invalidateChildren (dirtyBit: TransformBit) { if ((this._dirtyFlags & this.hasChangedFlags & dirtyBit) === dirtyBit) { return; } @@ -454,10 +466,8 @@ export class Node extends BaseNode { } /** - * @en - * update the world transform information if outdated - * @zh - * 更新节点的世界变换信息 + * @en Update the world transform information if outdated + * @zh 更新节点的世界变换信息 */ public updateWorldTransform () { if (!this._dirtyFlags) { return; } @@ -517,19 +527,18 @@ export class Node extends BaseNode { // =============================== /** - * @zh - * 设置本地坐标 - * @param position 目标本地坐标 + * @en Set position in local coordinate system + * @zh 设置本地坐标 + * @param position Target position */ public setPosition (position: Vec3): void; /** - * @zh - * 设置本地坐标 - * @param x 目标本地坐标的 X 分量 - * @param y 目标本地坐标的 Y 分量 - * @param z 目标本地坐标的 Z 分量 - * @param w 目标本地坐标的 W 分量 + * @en Set position in local coordinate system + * @zh 设置本地坐标 + * @param x X axis position + * @param y Y axis position + * @param z Z axis position */ public setPosition (x: number, y: number, z: number): void; @@ -547,9 +556,10 @@ export class Node extends BaseNode { } /** - * @zh - * 获取本地坐标 - * @param out 输出到此目标 vector + * @en Get position in local coordinate system, please try to pass `out` vector and reuse it to avoid garbage. + * @zh 获取本地坐标,注意,尽可能传递复用的 [[Vec3]] 以避免产生垃圾。 + * @param out Set the result to out vector + * @return If `out` given, the return value equals to `out`, otherwise a new vector will be generated and return */ public getPosition (out?: Vec3): Vec3 { if (out) { @@ -560,19 +570,19 @@ export class Node extends BaseNode { } /** - * @zh - * 设置本地旋转 - * @param rotation 目标本地旋转 + * @en Set rotation in local coordinate system with a quaternion representing the rotation + * @zh 用四元数设置本地旋转 + * @param rotation Rotation in quaternion */ public setRotation (rotation: Quat): void; /** - * @zh - * 设置本地旋转 - * @param x 目标本地旋转的 X 分量 - * @param y 目标本地旋转的 Y 分量 - * @param z 目标本地旋转的 Z 分量 - * @param w 目标本地旋转的 W 分量 + * @en Set rotation in local coordinate system with a quaternion representing the rotation + * @zh 用四元数设置本地旋转 + * @param x X value in quaternion + * @param y Y value in quaternion + * @param z Z value in quaternion + * @param w W value in quaternion */ public setRotation (x: number, y: number, z: number, w: number): void; @@ -591,11 +601,11 @@ export class Node extends BaseNode { } /** - * @zh - * 通过欧拉角设置本地旋转 - * @param x - 目标欧拉角的 X 分量 - * @param y - 目标欧拉角的 Y 分量 - * @param z - 目标欧拉角的 Z 分量 + * @en Set rotation in local coordinate system with euler angles + * @zh 用欧拉角设置本地旋转 + * @param x X axis rotation + * @param y Y axis rotation + * @param z Z axis rotation */ public setRotationFromEuler (x: number, y: number, z: number): void { Vec3.set(this._euler, x, y, z); @@ -609,9 +619,10 @@ export class Node extends BaseNode { } /** - * @zh - * 获取本地旋转 - * @param out 输出到此目标 quaternion + * @en Get rotation as quaternion in local coordinate system, please try to pass `out` quaternion and reuse it to avoid garbage. + * @zh 获取本地旋转,注意,尽可能传递复用的 [[Quat]] 以避免产生垃圾。 + * @param out Set the result to out quaternion + * @return If `out` given, the return value equals to `out`, otherwise a new quaternion will be generated and return */ public getRotation (out?: Quat): Quat { if (out) { @@ -622,18 +633,18 @@ export class Node extends BaseNode { } /** - * @zh - * 设置本地缩放 - * @param scale 目标本地缩放 + * @en Set scale in local coordinate system + * @zh 设置本地缩放 + * @param scale Target scale */ public setScale (scale: Vec3): void; /** - * @zh - * 设置本地缩放 - * @param x 目标本地缩放的 X 分量 - * @param y 目标本地缩放的 Y 分量 - * @param z 目标本地缩放的 Z 分量 + * @en Set scale in local coordinate system + * @zh 设置本地缩放 + * @param x X axis scale + * @param y Y axis scale + * @param z Z axis scale */ public setScale (x: number, y: number, z: number): void; @@ -651,9 +662,10 @@ export class Node extends BaseNode { } /** - * @zh - * 获取本地缩放 - * @param out 输出到此目标 vector + * @en Get scale in local coordinate system, please try to pass `out` vector and reuse it to avoid garbage. + * @zh 获取本地缩放,注意,尽可能传递复用的 [[Vec3]] 以避免产生垃圾。 + * @param out Set the result to out vector + * @return If `out` given, the return value equals to `out`, otherwise a new vector will be generated and return */ public getScale (out?: Vec3): Vec3 { if (out) { @@ -663,6 +675,12 @@ export class Node extends BaseNode { } } + /** + * @en Inversely transform a point from world coordinate system to local coordinate system. + * @zh 逆向变换一个空间点,一般用于将世界坐标转换到本地坐标系中。 + * @param out The result point in local coordinate system will be stored in this vector + * @param p A position in world coordinate system + */ public inverseTransformPoint (out: Vec3, p: Vec3) { Vec3.copy(out, p); let cur = this; let i = 0; @@ -678,19 +696,18 @@ export class Node extends BaseNode { } /** - * @zh - * 设置世界坐标 - * @param position 目标世界坐标 + * @en Set position in world coordinate system + * @zh 设置世界坐标 + * @param position Target position */ public setWorldPosition (position: Vec3): void; /** - * @zh - * 设置世界坐标 - * @param x 目标世界坐标的 X 分量 - * @param y 目标世界坐标的 Y 分量 - * @param z 目标世界坐标的 Z 分量 - * @param w 目标世界坐标的 W 分量 + * @en Set position in world coordinate system + * @zh 设置世界坐标 + * @param x X axis position + * @param y Y axis position + * @param z Z axis position */ public setWorldPosition (x: number, y: number, z: number): void; @@ -721,9 +738,10 @@ export class Node extends BaseNode { } /** - * @zh - * 获取世界坐标 - * @param out 输出到此目标 vector + * @en Get position in world coordinate system, please try to pass `out` vector and reuse it to avoid garbage. + * @zh 获取世界坐标,注意,尽可能传递复用的 [[Vec3]] 以避免产生垃圾。 + * @param out Set the result to out vector + * @return If `out` given, the return value equals to `out`, otherwise a new vector will be generated and return */ public getWorldPosition (out?: Vec3): Vec3 { this.updateWorldTransform(); @@ -735,19 +753,19 @@ export class Node extends BaseNode { } /** - * @zh - * 设置世界旋转 - * @param rotation 目标世界旋转 + * @en Set rotation in world coordinate system with a quaternion representing the rotation + * @zh 用四元数设置世界坐标系下的旋转 + * @param rotation Rotation in quaternion */ public setWorldRotation (rotation: Quat): void; /** - * @zh - * 设置世界旋转 - * @param x 目标世界旋转的 X 分量 - * @param y 目标世界旋转的 Y 分量 - * @param z 目标世界旋转的 Z 分量 - * @param w 目标世界旋转的 W 分量 + * @en Set rotation in world coordinate system with a quaternion representing the rotation + * @zh 用四元数设置世界坐标系下的旋转 + * @param x X value in quaternion + * @param y Y value in quaternion + * @param z Z value in quaternion + * @param w W value in quaternion */ public setWorldRotation (x: number, y: number, z: number, w: number): void; @@ -772,11 +790,11 @@ export class Node extends BaseNode { } /** - * @zh - * 通过欧拉角设置世界旋转 - * @param x - 目标欧拉角的 X 分量 - * @param y - 目标欧拉角的 Y 分量 - * @param z - 目标欧拉角的 Z 分量 + * @en Set rotation in world coordinate system with euler angles + * @zh 用欧拉角设置世界坐标系下的旋转 + * @param x X axis rotation + * @param y Y axis rotation + * @param z Z axis rotation */ public setWorldRotationFromEuler (x: number, y: number, z: number): void { Quat.fromEuler(this._rot, x, y, z); @@ -795,9 +813,10 @@ export class Node extends BaseNode { } /** - * @zh - * 获取世界旋转 - * @param out 输出到此目标 quaternion + * @en Get rotation as quaternion in world coordinate system, please try to pass `out` quaternion and reuse it to avoid garbage. + * @zh 获取世界坐标系下的旋转,注意,尽可能传递复用的 [[Quat]] 以避免产生垃圾。 + * @param out Set the result to out quaternion + * @return If `out` given, the return value equals to `out`, otherwise a new quaternion will be generated and return */ public getWorldRotation (out?: Quat): Quat { this.updateWorldTransform(); @@ -809,18 +828,18 @@ export class Node extends BaseNode { } /** - * @zh - * 设置世界缩放 - * @param scale 目标世界缩放 + * @en Set scale in world coordinate system + * @zh 设置世界坐标系下的缩放 + * @param scale Target scale */ public setWorldScale (scale: Vec3): void; /** - * @zh - * 设置世界缩放 - * @param x 目标世界缩放的 X 分量 - * @param y 目标世界缩放的 Y 分量 - * @param z 目标世界缩放的 Z 分量 + * @en Set scale in world coordinate system + * @zh 设置世界坐标系下的缩放 + * @param x X axis scale + * @param y Y axis scale + * @param z Z axis scale */ public setWorldScale (x: number, y: number, z: number): void; @@ -853,9 +872,10 @@ export class Node extends BaseNode { } /** - * @zh - * 获取世界缩放 - * @param out 输出到此目标 vector + * @en Get scale in world coordinate system, please try to pass `out` vector and reuse it to avoid garbage. + * @zh 获取世界缩放,注意,尽可能传递复用的 [[Vec3]] 以避免产生垃圾。 + * @param out Set the result to out vector + * @return If `out` given, the return value equals to `out`, otherwise a new vector will be generated and return */ public getWorldScale (out?: Vec3): Vec3 { this.updateWorldTransform(); @@ -867,9 +887,10 @@ export class Node extends BaseNode { } /** - * @zh - * 获取世界变换矩阵 - * @param out 输出到此目标矩阵 + * @en Get a world transform matrix + * @zh 获取世界变换矩阵 + * @param out Set the result to out matrix + * @return If `out` given, the return value equals to `out`, otherwise a new matrix will be generated and return */ public getWorldMatrix (out?: Mat4): Mat4 { this.updateWorldTransform(); @@ -878,9 +899,10 @@ export class Node extends BaseNode { } /** - * @zh - * 获取只包含旋转和缩放的世界变换矩阵 - * @param out 输出到此目标矩阵 + * @en Get a world transform matrix with only rotation and scale + * @zh 获取只包含旋转和缩放的世界变换矩阵 + * @param out Set the result to out matrix + * @return If `out` given, the return value equals to `out`, otherwise a new matrix will be generated and return */ public getWorldRS (out?: Mat4): Mat4 { this.updateWorldTransform(); @@ -891,9 +913,10 @@ export class Node extends BaseNode { } /** - * @zh - * 获取只包含旋转和位移的世界变换矩阵 - * @param out 输出到此目标矩阵 + * @en Get a world transform matrix with only rotation and translation + * @zh 获取只包含旋转和位移的世界变换矩阵 + * @param out Set the result to out matrix + * @return If `out` given, the return value equals to `out`, otherwise a new matrix will be generated and return */ public getWorldRT (out?: Mat4): Mat4 { this.updateWorldTransform(); @@ -902,8 +925,11 @@ export class Node extends BaseNode { } /** - * @zh - * 一次性设置所有局部变换(平移、旋转、缩放)信息 + * @en Set local transformation with rotation, position and scale separately. + * @zh 一次性设置所有局部变换(平移、旋转、缩放)信息 + * @param rot The rotation + * @param pos The position + * @param scale The scale */ public setRTS (rot?: Quat, pos?: Vec3, scale?: Vec3) { if (rot) { Quat.copy(this._lrot, rot); } @@ -944,12 +970,21 @@ export class Node extends BaseNode { public setContentSize (size: Size | number, height?: number) { this._uiProps.uiTransformComp!.setContentSize(size, height); } - + /** + * @en Pause all system events which is dispatched by [[SystemEvent]] + * @zh 暂停所有 [[SystemEvent]] 派发的系统事件 + * @param recursive Whether pause system events recursively for the child node tree + */ public pauseSystemEvents (recursive: boolean): void { // @ts-ignore eventManager.pauseTarget(this, recursive); } + /** + * @en Resume all paused system events which is dispatched by [[SystemEvent]] + * @zh 恢复所有 [[SystemEvent]] 派发的系统事件 + * @param recursive Whether resume system events recursively for the child node tree + */ public resumeSystemEvents (recursive: boolean): void { // @ts-ignore eventManager.resumeTarget(this, recursive); diff --git a/cocos/core/scene-graph/private-node.ts b/cocos/core/scene-graph/private-node.ts index d246187b93..8b466d4c84 100644 --- a/cocos/core/scene-graph/private-node.ts +++ b/cocos/core/scene-graph/private-node.ts @@ -48,16 +48,13 @@ const HideInHierarchy = CCObject.Flags.HideInHierarchy; * In this way, they can be easily kept inside the bounding box.
* Currently, it's used by RichText component and TileMap component. * @zh - * Cocos Creator 3d场景中的私有节点类。
+ * Cocos Creator 3d 场景中的私有节点类。
* 私有节点在编辑器中不可见,对用户透明。
* 通常私有节点是被一些特殊的组件创建出来作为父节点的一部分而存在的,理论上来说,它们不是子节点,而是父节点的组成部分。
* 私有节点有两个非常重要的特性:
* 1. 它有着最小的渲染排序的 Z 轴深度,并且无法被更改,因为它们不能被显示在其他正常子节点之上。
* 2. 它的定位也是特殊的,对于私有节点来说,父节点包围盒的左下角是它的局部坐标系原点,这个原点相当于父节点的位置减去它锚点的偏移。这样私有节点可以比较容易被控制在包围盒之中。
* 目前在引擎中,RichText 和 TileMap 都有可能生成私有节点。 - * @class PrivateNode - * @param {String} name - * @extends Node */ @ccclass('cc.PrivateNode') export class PrivateNode extends Node { @@ -99,9 +96,6 @@ export class PrivateNode extends Node { // cc.warnID(1638); // } - /** - * @param {String} [name] - */ constructor (name: string) { super(name); // this._originPos = cc.v2(); diff --git a/cocos/core/scene-graph/scene-globals.ts b/cocos/core/scene-graph/scene-globals.ts index 7129b65c00..59a973c10d 100644 --- a/cocos/core/scene-graph/scene-globals.ts +++ b/cocos/core/scene-graph/scene-globals.ts @@ -42,6 +42,7 @@ const _v3 = new Vec3(); const _qt = new Quat(); /** + * @en Environment lighting information in the Scene * @zh 场景的环境光照相关信息 */ @ccclass('cc.AmbientInfo') @@ -56,6 +57,7 @@ export class AmbientInfo { protected _resource: Ambient | null = null; /** + * @en Sky color * @zh 天空颜色 */ @property({ type: Color }) @@ -68,6 +70,7 @@ export class AmbientInfo { } /** + * @en Sky illuminance * @zh 天空亮度 */ @float @@ -80,6 +83,7 @@ export class AmbientInfo { } /** + * @en Ground color * @zh 地面颜色 */ @property({ type: Color }) @@ -102,6 +106,7 @@ export class AmbientInfo { cc.AmbientInfo = AmbientInfo; /** + * @en Skybox related information * @zh 天空盒相关信息 */ @ccclass('cc.SkyboxInfo') @@ -118,6 +123,7 @@ export class SkyboxInfo { protected _resource: Skybox | null = null; /** + * @en Whether activate skybox in the scene * @zh 是否启用天空盒? */ @property({ type: CCBoolean }) @@ -130,6 +136,7 @@ export class SkyboxInfo { } /** + * @en Whether use environment lighting * @zh 是否启用环境光照? */ @property({ type: CCBoolean }) @@ -142,6 +149,7 @@ export class SkyboxInfo { } /** + * @en The texture cube used for the skybox * @zh 使用的立方体贴图 */ @property({ type: TextureCube }) @@ -154,6 +162,7 @@ export class SkyboxInfo { } /** + * @en Whether enable RGBE data support in skybox shader * @zh 是否需要开启 shader 内的 RGBE 数据支持? */ @property({ type: CCBoolean }) @@ -176,6 +185,7 @@ export class SkyboxInfo { cc.SkyboxInfo = SkyboxInfo; /** + * @en Scene level planar shadow related information * @zh 平面阴影相关信息 */ @ccclass('cc.PlanarShadowInfo') @@ -192,6 +202,7 @@ export class PlanarShadowInfo { protected _resource: PlanarShadows | null = null; /** + * @en Whether activate planar shadow * @zh 是否启用平面阴影? */ @property({ type: CCBoolean }) @@ -204,6 +215,7 @@ export class PlanarShadowInfo { } /** + * @en The normal of the plane which receives shadow * @zh 阴影接收平面的法线 */ @property({ type: Vec3 }) @@ -216,6 +228,7 @@ export class PlanarShadowInfo { } /** + * @en The distance from coordinate origin to the receiving plane. * @zh 阴影接收平面与原点的距离 */ @property({ type: CCFloat }) @@ -228,6 +241,7 @@ export class PlanarShadowInfo { } /** + * @en Shadow color * @zh 阴影颜色 */ @property({ type: Color }) @@ -240,8 +254,9 @@ export class PlanarShadowInfo { } /** + * @en Set plane which receives shadow with the given node's world transformation * @zh 根据指定节点的世界变换设置阴影接收平面的信息 - * @param node 阴影接收平面的世界变换 + * @param node The node for setting up the plane */ public setPlaneFromNode (node: Node) { node.getWorldRotation(_qt); @@ -261,22 +276,34 @@ export class PlanarShadowInfo { cc.PlanarShadowInfo = PlanarShadowInfo; /** + * @en All scene related global parameters, it affects all content in the corresponding scene * @zh 各类场景级别的渲染参数,将影响全场景的所有物体 */ @ccclass('cc.SceneGlobals') export class SceneGlobals { + /** + * @en The environment light information + * @zh 场景的环境光照相关信息 + */ @property public ambient = new AmbientInfo(); + /** + * @en Scene level planar shadow related information + * @zh 平面阴影相关信息 + */ @property public planarShadows = new PlanarShadowInfo(); @property private _skybox = new SkyboxInfo(); + /** + * @en Skybox related information + * @zh 天空盒相关信息 + */ @property({ type: SkyboxInfo }) get skybox () { return this._skybox; } - set skybox (value) { this._skybox = value; } diff --git a/cocos/core/scene-graph/scene.ts b/cocos/core/scene-graph/scene.ts index 8efe1da88e..dfe1a102c5 100644 --- a/cocos/core/scene-graph/scene.ts +++ b/cocos/core/scene-graph/scene.ts @@ -37,20 +37,27 @@ import { EDITOR, TEST } from 'internal:constants'; /** * @en - * cc.Scene is a subclass of cc.Node that is used only as an abstract concept.
- * cc.Scene and cc.Node are almost identical with the difference that users can not modify cc.Scene manually. + * Scene is a subclass of [[BaseNode]], composed by nodes, representing the root of a runnable environment in the game. + * It's managed by [[Director]] and user can switch from a scene to another using [[Director.loadScene]] * @zh - * cc.Scene 是 cc._BaseNode 的子类,仅作为一个抽象的概念。
- * cc.Scene 和 cc._BaseNode 有点不同,用户不应直接修改 cc.Scene。 + * Scene 是 [[BaseNode]] 的子类,由节点所构成,代表着游戏中可运行的某一个整体环境。 + * 它由 [[Director]] 管理,用户可以使用 [[Director.loadScene]] 来切换场景 */ @ccclass('cc.Scene') export class Scene extends BaseNode { - + /** + * @en The renderer scene, normally user don't need to use it + * @zh 渲染层场景,一般情况下用户不需要关心它 + */ get renderScene () { return this._renderScene; } - get globals () { + /** + * @en All scene related global parameters, it affects all content in the scene + * @zh 各类场景级别的渲染参数,将影响全场景的所有物体 + */ + get globals (): SceneGlobals { return this._globals; } @@ -61,16 +68,12 @@ export class Scene extends BaseNode { @property public autoReleaseAssets = false; - /** - * @en Per-scene level rendering info - * @zh 场景级别的渲染信息 - */ - @property - public _globals = new SceneGlobals(); - public _renderScene: RenderScene | null = null; public dependAssets = null; // cache all depend assets for auto release + @property + protected _globals = new SceneGlobals(); + protected _inited: boolean; protected _prefabSyncedInLiveReload = false; @@ -90,6 +93,10 @@ export class Scene extends BaseNode { this._inited = cc.game ? !cc.game._isCloning : true; } + /** + * @en Destroy the current scene and all its nodes, this action won't destroy related assets + * @zh 销毁当前场景中的所有节点,这个操作不会销毁资源 + */ public destroy () { const success = super.destroy(); cc.director.root.destroyScene(this._renderScene); @@ -97,6 +104,10 @@ export class Scene extends BaseNode { return success; } + /** + * @en Only for compatibility purpose, user should not add any component to the scene + * @zh 仅为兼容性保留,用户不应该在场景上直接添加任何组件 + */ public addComponent (typeOrClassName: string | Function) { warnID(3822); return null; @@ -118,23 +129,77 @@ export class Scene extends BaseNode { // transform helpers + /** + * Refer to [[Node.getPosition]] + */ public getPosition (out?: Vec3): Vec3 { return Vec3.copy(out || new Vec3(), Vec3.ZERO); } + /** + * Refer to [[Node.getRotation]] + */ public getRotation (out?: Quat): Quat { return Quat.copy(out || new Quat(), Quat.IDENTITY); } + /** + * Refer to [[Node.getScale]] + */ public getScale (out?: Vec3): Vec3 { return Vec3.copy(out || new Vec3(), Vec3.ONE); } + /** + * Refer to [[Node.getWorldPosition]] + */ public getWorldPosition (out?: Vec3) { return Vec3.copy(out || new Vec3(), Vec3.ZERO); } + /** + * Refer to [[Node.getWorldRotation]] + */ public getWorldRotation (out?: Quat) { return Quat.copy(out || new Quat(), Quat.IDENTITY); } + /** + * Refer to [[Node.getWorldScale]] + */ public getWorldScale (out?: Vec3) { return Vec3.copy(out || new Vec3(), Vec3.ONE); } + /** + * Refer to [[Node.getWorldMatrix]] + */ public getWorldMatrix (out?: Mat4): Mat4 { return Mat4.copy(out || new Mat4(), Mat4.IDENTITY); } + /** + * Refer to [[Node.getWorldRS]] + */ public getWorldRS (out?: Mat4): Mat4 { return Mat4.copy(out || new Mat4(), Mat4.IDENTITY); } + /** + * Refer to [[Node.getWorldRT]] + */ public getWorldRT (out?: Mat4): Mat4 { return Mat4.copy(out || new Mat4(), Mat4.IDENTITY); } + /** + * Refer to [[Node.position]] + */ public get position (): Readonly { return Vec3.ZERO; } + /** + * Refer to [[Node.worldPosition]] + */ public get worldPosition (): Readonly { return Vec3.ZERO; } + /** + * Refer to [[Node.rotation]] + */ public get rotation (): Readonly { return Quat.IDENTITY; } + /** + * Refer to [[Node.worldRotation]] + */ public get worldRotation (): Readonly { return Quat.IDENTITY; } + /** + * Refer to [[Node.scale]] + */ public get scale (): Readonly { return Vec3.ONE; } + /** + * Refer to [[Node.worldScale]] + */ public get worldScale (): Readonly { return Vec3.ONE; } + /** + * Refer to [[Node.eulerAngles]] + */ public get eulerAngles (): Readonly { return Vec3.ZERO; } + /** + * Refer to [[Node.worldMatrix]] + */ public get worldMatrix (): Readonly { return Mat4.IDENTITY; } + /** + * Refer to [[Node.updateWorldTransform]] + */ public updateWorldTransform () {} // life-cycle call backs diff --git a/cocos/core/utils/misc.ts b/cocos/core/utils/misc.ts index 727fe66072..cfc1d37785 100644 --- a/cocos/core/utils/misc.ts +++ b/cocos/core/utils/misc.ts @@ -154,7 +154,7 @@ export function isDomNode (obj) { } } -export function callInNextTick (callback, p1?:any, p2?:any) { +export function callInNextTick (callback, p1?: any, p2?: any) { if (EDITOR) { if (callback) { // @ts-ignore diff --git a/cocos/particle/particle-utils.ts b/cocos/particle/particle-utils.ts index b08a74a874..f14f0e6932 100644 --- a/cocos/particle/particle-utils.ts +++ b/cocos/particle/particle-utils.ts @@ -21,7 +21,7 @@ export class ParticleUtils { } if (!this.particleSystemPool.has(prefab._uuid)) { this.particleSystemPool.set(prefab._uuid, new Pool(() => { - return instantiate(prefab); + return instantiate(prefab) || new Node(); }, 1)); } return this.particleSystemPool.get(prefab._uuid)!.alloc(); From b531f781487e422a1bf14563672978bffc35a335 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Mon, 25 May 2020 17:35:48 +0800 Subject: [PATCH 32/74] Fix a language semantic violation (#6674) --- cocos/core/event/callbacks-invoker.ts | 7 +++++++ cocos/core/load-pipeline/loading-items.ts | 3 +-- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/cocos/core/event/callbacks-invoker.ts b/cocos/core/event/callbacks-invoker.ts index 50f5de5526..fa92f1393d 100644 --- a/cocos/core/event/callbacks-invoker.ts +++ b/cocos/core/event/callbacks-invoker.ts @@ -336,6 +336,13 @@ export class CallbacksInvoker { } } } + + /** + * 移除所有回调。 + */ + public clear () { + this._callbackTable = createMap(true); + } } if (TEST) { diff --git a/cocos/core/load-pipeline/loading-items.ts b/cocos/core/load-pipeline/loading-items.ts index e811eec341..4830254068 100644 --- a/cocos/core/load-pipeline/loading-items.ts +++ b/cocos/core/load-pipeline/loading-items.ts @@ -670,8 +670,7 @@ export class LoadingItems extends CallbacksInvoker { this.totalCount = 0; this.completedCount = 0; - // Reinitialize CallbacksInvoker, generate three new objects, could be improved - CallbacksInvoker.call(this); + this.clear(); _queues[this._id] = null; if (_queueDeps[this._id]) { From 39ff4fa132a5e5efcb8d03835ad94e706967aca2 Mon Sep 17 00:00:00 2001 From: JoneLau <32630749+JoneLau@users.noreply.github.com> Date: Mon, 25 May 2020 17:38:07 +0800 Subject: [PATCH 33/74] fix undo bug for pageview (#6682) --- cocos/ui/components/page-view-component.ts | 17 ++++++++++++----- 1 file changed, 12 insertions(+), 5 deletions(-) diff --git a/cocos/ui/components/page-view-component.ts b/cocos/ui/components/page-view-component.ts index e4a8c6b318..bcac158144 100644 --- a/cocos/ui/components/page-view-component.ts +++ b/cocos/ui/components/page-view-component.ts @@ -253,14 +253,17 @@ export class PageViewComponent extends ScrollViewComponent { }) public autoPageTurningThreshold = 100; - // override visible false @property({ type: ScrollBarComponent, visible: false, override: true, }) - get verticalScrollBar() { - return this._verticalScrollBar; + get verticalScrollBar () { + return super.verticalScrollBar; + } + + set verticalScrollBar (value) { + super.verticalScrollBar = value; } @property({ @@ -268,8 +271,12 @@ export class PageViewComponent extends ScrollViewComponent { visible: false, override: true, }) - get horizontalScrollBar() { - return this._horizontalScrollBar; + get horizontalScrollBar () { + return super.horizontalScrollBar; + } + + set horizontalScrollBar (value) { + super.horizontalScrollBar = value; } @property({ From c801a4e3a6c272bf07a4897d6cdf8fc1e71ec4ea Mon Sep 17 00:00:00 2001 From: zheng han Date: Mon, 25 May 2020 17:59:34 +0800 Subject: [PATCH 34/74] export ccenum (#6714) --- cocos/core/value-types/index.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/cocos/core/value-types/index.ts b/cocos/core/value-types/index.ts index 9f382a6616..5972d0b3ee 100644 --- a/cocos/core/value-types/index.ts +++ b/cocos/core/value-types/index.ts @@ -29,5 +29,5 @@ */ export { BitMask } from './bitmask'; -export { Enum } from './enum'; +export { Enum, ccenum } from './enum'; export { ValueType } from './value-type'; From b42de567af331c4fbc7bb7e0f7f301e802d4de60 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 25 May 2020 18:05:52 +0800 Subject: [PATCH 35/74] fix skinning model pose calc when missing joint nodes (#6721) * fix skinning model pose calc when missing joint nodes * fix camera.worldToScreen when world pos is behind near plane * fix batched skinning model material instantiation --- .../batched-skinning-model-component.ts | 4 +-- cocos/core/math/vec3.ts | 10 +++---- .../models/skeletal-animation-utils.ts | 29 +++++++------------ cocos/core/renderer/scene/camera.ts | 1 + 4 files changed, 19 insertions(+), 25 deletions(-) diff --git a/cocos/core/3d/framework/batched-skinning-model-component.ts b/cocos/core/3d/framework/batched-skinning-model-component.ts index a3d2b0b48b..a942c1e239 100644 --- a/cocos/core/3d/framework/batched-skinning-model-component.ts +++ b/cocos/core/3d/framework/batched-skinning-model-component.ts @@ -205,7 +205,7 @@ export class BatchedSkinningModelComponent extends SkinningModelComponent { public _onMaterialModified (idx: number, material: Material | null) { this.cookMaterials(); - super._onMaterialModified(idx, this.getMaterial(idx)); + super._onMaterialModified(idx, this.getMaterialInstance(idx)); } public cook () { @@ -218,7 +218,7 @@ export class BatchedSkinningModelComponent extends SkinningModelComponent { if (!this._batchMaterial) { this._batchMaterial = this.getMaterial(0); } - const mat = this.getMaterial(0); + const mat = this.getMaterialInstance(0); if (!mat || !this._batchMaterial || !this._batchMaterial.effectAsset) { console.warn('incomplete batch material!'); return; } diff --git a/cocos/core/math/vec3.ts b/cocos/core/math/vec3.ts index b8fce62da7..7f64d5845d 100644 --- a/cocos/core/math/vec3.ts +++ b/cocos/core/math/vec3.ts @@ -357,7 +357,7 @@ export class Vec3 extends ValueType { const y = a.y; const z = a.z; let rhw = m.m03 * x + m.m07 * y + m.m11 * z + m.m15; - rhw = rhw ? 1 / rhw : 1; + rhw = rhw ? Math.abs(1 / rhw) : 1; out.x = (m.m00 * x + m.m04 * y + m.m08 * z + m.m12) * rhw; out.y = (m.m01 * x + m.m05 * y + m.m09 * z + m.m13) * rhw; out.z = (m.m02 * x + m.m06 * y + m.m10 * z + m.m14) * rhw; @@ -372,7 +372,7 @@ export class Vec3 extends ValueType { const y = a.y; const z = a.z; let rhw = m.m03 * x + m.m07 * y + m.m11 * z; - rhw = rhw ? 1 / rhw : 1; + rhw = rhw ? Math.abs(1 / rhw) : 1; out.x = (m.m00 * x + m.m04 * y + m.m08 * z) * rhw; out.y = (m.m01 * x + m.m05 * y + m.m09 * z) * rhw; out.z = (m.m02 * x + m.m06 * y + m.m10 * z) * rhw; @@ -399,9 +399,9 @@ export class Vec3 extends ValueType { const x = v.x; const y = v.y; const z = v.z; - out.x = m.m00 * x + m.m01 * y + m.m02 * z + m.m03; - out.y = m.m04 * x + m.m05 * y + m.m06 * z + m.m07; - out.x = m.m08 * x + m.m09 * y + m.m10 * z + m.m11; + out.x = m.m00 * x + m.m04 * y + m.m08 * z + m.m12; + out.y = m.m01 * x + m.m05 * y + m.m09 * z + m.m13; + out.x = m.m02 * x + m.m06 * y + m.m10 * z + m.m14; return out; } diff --git a/cocos/core/renderer/models/skeletal-animation-utils.ts b/cocos/core/renderer/models/skeletal-animation-utils.ts index e5a7f2f5da..63e4ab19b4 100644 --- a/cocos/core/renderer/models/skeletal-animation-utils.ts +++ b/cocos/core/renderer/models/skeletal-animation-utils.ts @@ -56,7 +56,7 @@ export function selectJointsMediumFormat (device: GFXDevice): GFXFormat { } // negative zeros cannot be decoded correctly at GLSL 100 minimum highp float precision, 1/1024 -// and it has a significant effect on the final transformation +// and it has a significant impact on the final transformation function makeStable (n: number) { return n ? n : 0; } // Linear Blending Skinning @@ -224,20 +224,16 @@ export class JointTexturePool { for (let i = 0; i < joints.length; i++) { const node = skinningRoot.getChildByPath(joints[i]); const bound = boneSpaceBounds[i]; - if (!node) { // don't skip null `bound` here, or it becomes mesh-specific - if (buildTexture) { uploadJointData(textureBuffer, 12 * i, Mat4.IDENTITY, i === 0); } - continue; - } - getWorldTransformUntilRoot(node, skinningRoot, m4_1); + const mat = node ? getWorldTransformUntilRoot(node, skinningRoot, m4_1) : Mat4.IDENTITY; if (bound) { - aabb.transform(ab_1, bound, m4_1); + aabb.transform(ab_1, bound, mat); ab_1.getBoundary(v3_3, v3_4); Vec3.min(v3_min, v3_min, v3_3); Vec3.max(v3_max, v3_max, v3_4); } if (buildTexture) { - Mat4.multiply(m4_1, m4_1, bindposes[i]); - uploadJointData(textureBuffer, 12 * i, m4_1, i === 0); + if (mat !== Mat4.IDENTITY) { Mat4.multiply(mat, mat, bindposes[i]); } + uploadJointData(textureBuffer, 12 * i, mat, i === 0); } } const bounds = [new aabb()]; texture.bounds.set(mesh.hash, bounds); @@ -285,24 +281,21 @@ export class JointTexturePool { const bound = bounds[frame]; for (let i = 0; i < totalJoints; i++, offset += 12) { const nodeData = clipData.data[joints[i]]; - if (!nodeData) { // don't skip null `boneSpaceBounds` here, or it becomes mesh-specific + let mat = Mat4.IDENTITY; + if (nodeData) { mat = nodeData.worldMatrix.values[frame] as Mat4; } + else { const node = skinningRoot.getChildByPath(joints[i]); // fallback to default pose - const mat = node ? getWorldTransformUntilRoot(node, skinningRoot, m4_1) : Mat4.IDENTITY; - if (buildTexture) { uploadJointData(textureBuffer, offset, mat, i === 0); } - continue; + mat = node ? getWorldTransformUntilRoot(node, skinningRoot, m4_1) : Mat4.IDENTITY; } - const matrix = nodeData.worldMatrix.values as Mat4[]; - const m = matrix[frame]; const boneSpaceBound = boneSpaceBounds[i]; if (boneSpaceBound) { - aabb.transform(ab_1, boneSpaceBound, m); + aabb.transform(ab_1, boneSpaceBound, mat); ab_1.getBoundary(v3_3, v3_4); Vec3.min(bound.center, bound.center, v3_3); Vec3.max(bound.halfExtents, bound.halfExtents, v3_4); } if (buildTexture) { - const bindpose = bindposes[i]; - Mat4.multiply(m4_1, m, bindpose); + if (mat !== Mat4.IDENTITY) { Mat4.multiply(m4_1, mat, bindposes[i]); } uploadJointData(textureBuffer, offset, m4_1, i === 0); } } diff --git a/cocos/core/renderer/scene/camera.ts b/cocos/core/renderer/scene/camera.ts index 5b97287179..3fbda67814 100644 --- a/cocos/core/renderer/scene/camera.ts +++ b/cocos/core/renderer/scene/camera.ts @@ -597,6 +597,7 @@ export class Camera { const ch = this.viewport.height * this._height; Vec3.transformMat4(out, worldPos, this.matViewProj); + out.x = cx + (out.x + 1) * 0.5 * cw; out.y = cy + (out.y + 1) * 0.5 * ch; out.z = out.z * 0.5 + 0.5; From 5c1d3fa37016a1fadf986f8cd2b4781650db52cf Mon Sep 17 00:00:00 2001 From: Myway Date: Mon, 25 May 2020 20:53:12 +0800 Subject: [PATCH 36/74] fix typo (#6740) * fix typo * fixed serialize decorator * fix serialize formerly --- cocos/core/3d/framework/model-component.ts | 26 +- cocos/terrain/terrain-asset.ts | 248 +++++++------ cocos/terrain/terrain-lod.ts | 164 ++++----- cocos/terrain/terrain.ts | 395 ++++++++++++++++----- 4 files changed, 556 insertions(+), 277 deletions(-) diff --git a/cocos/core/3d/framework/model-component.ts b/cocos/core/3d/framework/model-component.ts index 416a0ece08..c10b1ae8c7 100644 --- a/cocos/core/3d/framework/model-component.ts +++ b/cocos/core/3d/framework/model-component.ts @@ -77,8 +77,10 @@ class ModelLightmapSettings { protected _bakeable: boolean = false; @property protected _castShadow: boolean = false; - @property - protected _recieveShadow: boolean = false; + @property({ + formerlySerializedAs: '_recieveShadow', + }) + protected _receiveShadow: boolean = false; @property protected _lightmapSize: number = 64; @@ -109,16 +111,16 @@ class ModelLightmapSettings { } /** - * @en recieve shadow. + * @en receive shadow. * @zh 是否接受阴影。 */ @property - get recieveShadow () { - return this._recieveShadow; + get receiveShadow () { + return this._receiveShadow; } - set recieveShadow (val) { - this._recieveShadow = val; + set receiveShadow (val) { + this._receiveShadow = val; } /** @@ -280,12 +282,12 @@ export class ModelComponent extends RenderableComponent { } } - public _updateLightmap (lightmap: Texture2D|null, uoff: number, voff: number, uscale: number, vscale: number) { + public _updateLightmap (lightmap: Texture2D|null, uOff: number, vOff: number, uScale: number, vScale: number) { this.lightmapSettings.texture = lightmap; - this.lightmapSettings.uvParam.x = uoff; - this.lightmapSettings.uvParam.y = voff; - this.lightmapSettings.uvParam.z = uscale; - this.lightmapSettings.uvParam.w = vscale; + this.lightmapSettings.uvParam.x = uOff; + this.lightmapSettings.uvParam.y = vOff; + this.lightmapSettings.uvParam.z = uScale; + this.lightmapSettings.uvParam.w = vScale; } protected _updateModels () { diff --git a/cocos/terrain/terrain-asset.ts b/cocos/terrain/terrain-asset.ts index 4e9231f206..160ee42a3c 100644 --- a/cocos/terrain/terrain-asset.ts +++ b/cocos/terrain/terrain-asset.ts @@ -9,154 +9,162 @@ export const TERRAIN_DATA_VERSION2 = 0x01010002; export const TERRAIN_DATA_VERSION3 = 0x01010003; export const TERRAIN_DATA_VERSION_DEFAULT = 0x01010111; -export class TerrainBuffer { - public Length: number = 0; - public Buffer: Uint8Array = new Uint8Array(2048); - private _dview: DataView = new DataView(this.Buffer.buffer); +class TerrainBuffer { + public length: number = 0; + public buffer: Uint8Array = new Uint8Array(2048); + private _buffView: DataView = new DataView(this.buffer.buffer); private _seekPos: number = 0; - public Reserve (size: number) { - if (this.Buffer.byteLength > size) { + public reserve (size: number) { + if (this.buffer.byteLength > size) { return; } - let capacity = this.Buffer.byteLength; + let capacity = this.buffer.byteLength; while (capacity < size) { capacity += capacity; } const temp = new Uint8Array(capacity); - for (let i = 0; i < this.Length; ++i) { - temp[i] = this.Buffer[i]; + for (let i = 0; i < this.length; ++i) { + temp[i] = this.buffer[i]; } - this.Buffer = temp; - this._dview = new DataView(this.Buffer.buffer); + this.buffer = temp; + this._buffView = new DataView(this.buffer.buffer); } - public Assign (buff: Uint8Array) { - this.Buffer = buff; - this.Length = buff.length; + public assign (buff: Uint8Array) { + this.buffer = buff; + this.length = buff.length; this._seekPos = buff.byteOffset; - this._dview = new DataView(buff.buffer); + this._buffView = new DataView(buff.buffer); } - public WriteInt8 (value: number) { - this.Reserve(this.Length + 1); + public writeInt8 (value: number) { + this.reserve(this.length + 1); - this._dview.setInt8(this.Length, value); - this.Length += 1; + this._buffView.setInt8(this.length, value); + this.length += 1; } - public WriteInt16 (value: number) { - this.Reserve(this.Length + 2); + public writeInt16 (value: number) { + this.reserve(this.length + 2); - this._dview.setInt16(this.Length, value, true); - this.Length += 2; + this._buffView.setInt16(this.length, value, true); + this.length += 2; } - public WriteInt32 (value: number) { - this.Reserve(this.Length + 4); + public writeInt32 (value: number) { + this.reserve(this.length + 4); - this._dview.setInt32(this.Length, value, true); - this.Length += 4; + this._buffView.setInt32(this.length, value, true); + this.length += 4; } - public WriteIntArray (value: number[]) { - this.Reserve(this.Length + 4 * value.length); + public writeIntArray (value: number[]) { + this.reserve(this.length + 4 * value.length); for (let i = 0; i < value.length; ++i) { - this._dview.setInt32(this.Length + i * 4, value[i], true); + this._buffView.setInt32(this.length + i * 4, value[i], true); } - this.Length += 4 * value.length; + this.length += 4 * value.length; } - public WriteFloat (value: number) { - this.Reserve(this.Length + 4); + public writeFloat (value: number) { + this.reserve(this.length + 4); - this._dview.setFloat32(this.Length, value, true); - this.Length += 4; + this._buffView.setFloat32(this.length, value, true); + this.length += 4; } - public WriteFloatArray (value: number[]) { - this.Reserve(this.Length + 4 * value.length); + public writeFloatArray (value: number[]) { + this.reserve(this.length + 4 * value.length); for (let i = 0; i < value.length; ++i) { - this._dview.setFloat32(this.Length + i * 4, value[i], true); + this._buffView.setFloat32(this.length + i * 4, value[i], true); } - this.Length += 4 * value.length; + this.length += 4 * value.length; } - public WriteString (value: string) { - this.Reserve(this.Length + value.length + 4); + public writeString (value: string) { + this.reserve(this.length + value.length + 4); - this._dview.setInt32(this.Length, value.length, true); + this._buffView.setInt32(this.length, value.length, true); for (let i = 0; i < value.length; ++i) { - this._dview.setInt8(this.Length + 4 + i, value.charCodeAt(i)); + this._buffView.setInt8(this.length + 4 + i, value.charCodeAt(i)); } - this.Length += value.length + 4; + this.length += value.length + 4; } - public ReadInt8 () { - const value = this._dview.getInt8(this._seekPos); + public readInt8 () { + const value = this._buffView.getInt8(this._seekPos); this._seekPos += 1; return value; } - public ReadInt16 () { - const value = this._dview.getInt16(this._seekPos, true); + public readInt16 () { + const value = this._buffView.getInt16(this._seekPos, true); this._seekPos += 2; return value; } - public ReadInt () { - const value = this._dview.getInt32(this._seekPos, true); + public readInt () { + const value = this._buffView.getInt32(this._seekPos, true); this._seekPos += 4; return value; } - public ReadIntArray (value: number[]) { + public readIntArray (value: number[]) { for (let i = 0; i < value.length; ++i) { - value[i] = this._dview.getInt32(this._seekPos + i * 4, true); + value[i] = this._buffView.getInt32(this._seekPos + i * 4, true); } this._seekPos += 4 * value.length; return value; } - public ReadFloat () { - const value = this._dview.getFloat32(this._seekPos, true); + public readFloat () { + const value = this._buffView.getFloat32(this._seekPos, true); this._seekPos += 4; return value; } - public ReadFloatArray (value: number[]) { + public readFloatArray (value: number[]) { for (let i = 0; i < value.length; ++i) { - value[i] = this._dview.getFloat32(this._seekPos + i * 4, true); + value[i] = this._buffView.getFloat32(this._seekPos + i * 4, true); } this._seekPos += 4 * value.length; return value; } - public ReadString () { - const length = this.ReadInt(); + public readString () { + const length = this.readInt(); let value = ''; for (let i = 0; i < length; ++i) { - value += String.fromCharCode(this.ReadInt8()); + value += String.fromCharCode(this.readInt8()); } return value; } } -export class TerrainLayerInfo{ +/** + * @en terrain layer info + * @zh 地形纹理信息 + */ +export class TerrainLayerInfo { public slot: number = 0; public tileSize: number = 1; public detailMap: string = ''; } +/** + * @en terrain asset + * @zh 地形资源 + */ @ccclass('cc.TerrainAsset') -export class TerrainAsset extends Asset{ +export class TerrainAsset extends Asset { protected _data: Uint8Array|null = null; protected _tileSize: number = 1; protected _blockCount: number[] = [1, 1]; @@ -192,6 +200,10 @@ export class TerrainAsset extends Asset{ this.emit('load'); } + /** + * @en tile size + * @zh 栅格大小 + */ set tileSize (value: number) { this._tileSize = value; } @@ -200,6 +212,10 @@ export class TerrainAsset extends Asset{ return this._tileSize; } + /** + * @en block count + * @zh 块数量 + */ set blockCount (value: number[]) { this._blockCount = value; } @@ -208,6 +224,10 @@ export class TerrainAsset extends Asset{ return this._blockCount; } + /** + * @en light map size + * @zh 光照图大小 + */ set lightMapSize (value: number) { this._lightMapSize = value; } @@ -216,6 +236,10 @@ export class TerrainAsset extends Asset{ return this._lightMapSize; } + /** + * @en weight map size + * @zh 权重图大小 + */ set weightMapSize (value: number) { this._weightMapSize = value; } @@ -224,6 +248,10 @@ export class TerrainAsset extends Asset{ return this._weightMapSize; } + /** + * @en height buffer + * @zh 高度缓存 + */ set heights (value: Uint16Array) { this._heights = value; } @@ -232,6 +260,10 @@ export class TerrainAsset extends Asset{ return this._heights; } + /** + * @en weight buffer + * @zh 权重缓存 + */ set weights (value: Uint8Array) { this._weights = value; } @@ -240,6 +272,10 @@ export class TerrainAsset extends Asset{ return this._weights; } + /** + * @en layer buffer + * @zh 纹理索引缓存 + */ set layerBuffer (value: number[]) { this._layerBuffer = value; } @@ -248,6 +284,10 @@ export class TerrainAsset extends Asset{ return this._layerBuffer; } + /** + * @en layer info + * @zh 纹理信息 + */ set layerInfos (value: TerrainLayerInfo[]) { this._layerInfos = value; } @@ -256,11 +296,21 @@ export class TerrainAsset extends Asset{ return this._layerInfos; } - public getLayer (xblock: number, yblock: number, layerId: number) { - const blockId = yblock * this.blockCount[0] + xblock; + /** + * @en get layer + * @param xBlock block index x + * @param yBlock block index y + * @param layerId layer id + * @zh 获得纹理索引 + * @param xBlock 地形块索引x + * @param yBlock 地形块索引y + * @param layerId 层Id + */ + public getLayer (xBlock: number, yBlock: number, layerId: number) { + const blockId = yBlock * this.blockCount[0] + xBlock; const index = blockId * 4 + layerId; - if (xblock < this.blockCount[0] && yblock < this.blockCount[1] && index < this._layerBuffer.length) { + if (xBlock < this.blockCount[0] && yBlock < this.blockCount[1] && index < this._layerBuffer.length) { return this._layerBuffer[index]; } @@ -273,10 +323,10 @@ export class TerrainAsset extends Asset{ public _loadNativeData (_nativeData: Uint8Array) { const stream = new TerrainBuffer(); - stream.Assign(_nativeData); + stream.assign(_nativeData); // version - const version = stream.ReadInt(); + const version = stream.readInt(); if (version === TERRAIN_DATA_VERSION_DEFAULT) { return true; } @@ -287,43 +337,43 @@ export class TerrainAsset extends Asset{ } // geometry info - this.tileSize = stream.ReadFloat(); - stream.ReadIntArray(this._blockCount); - this.weightMapSize = stream.ReadInt16(); - this.lightMapSize = stream.ReadInt16(); + this.tileSize = stream.readFloat(); + stream.readIntArray(this._blockCount); + this.weightMapSize = stream.readInt16(); + this.lightMapSize = stream.readInt16(); // heights - const heightBufferSize = stream.ReadInt(); + const heightBufferSize = stream.readInt(); this.heights = new Uint16Array(heightBufferSize); for (let i = 0; i < this.heights.length; ++i) { - this.heights[i] = stream.ReadInt16(); + this.heights[i] = stream.readInt16(); } // weights - const WeightBufferSize = stream.ReadInt(); + const WeightBufferSize = stream.readInt(); this.weights = new Uint8Array(WeightBufferSize); for (let i = 0; i < this.weights.length; ++i) { - this.weights[i] = stream.ReadInt8(); + this.weights[i] = stream.readInt8(); } // layer buffer if (version >= TERRAIN_DATA_VERSION2) { - const layerBufferSize = stream.ReadInt(); + const layerBufferSize = stream.readInt(); this.layerBuffer = new Array(layerBufferSize); for (let i = 0; i < this.layerBuffer.length; ++i) { - this.layerBuffer[i] = stream.ReadInt16(); + this.layerBuffer[i] = stream.readInt16(); } } // layer infos if (version >= TERRAIN_DATA_VERSION3) { - const layerInfoSize = stream.ReadInt(); + const layerInfoSize = stream.readInt(); this.layerInfos = new Array(layerInfoSize); for (let i = 0; i < this.layerInfos.length; ++i) { this.layerInfos[i] = new TerrainLayerInfo(); - this.layerInfos[i].slot = stream.ReadInt(); - this.layerInfos[i].tileSize = stream.ReadFloat(); - this.layerInfos[i].detailMap = stream.ReadString(); + this.layerInfos[i].slot = stream.readInt(); + this.layerInfos[i].tileSize = stream.readFloat(); + this.layerInfos[i].detailMap = stream.readString(); } } @@ -335,49 +385,47 @@ export class TerrainAsset extends Asset{ const stream = new TerrainBuffer(); // version - stream.WriteInt32(TERRAIN_DATA_VERSION3); + stream.writeInt32(TERRAIN_DATA_VERSION3); // geometry info - stream.WriteFloat(this.tileSize); - stream.WriteIntArray(this._blockCount); - stream.WriteInt16(this.weightMapSize); - stream.WriteInt16(this.lightMapSize); + stream.writeFloat(this.tileSize); + stream.writeIntArray(this._blockCount); + stream.writeInt16(this.weightMapSize); + stream.writeInt16(this.lightMapSize); // heights - stream.WriteInt32(this.heights.length); + stream.writeInt32(this.heights.length); for (let i = 0; i < this.heights.length; ++i) { - stream.WriteInt16(this.heights[i]); + stream.writeInt16(this.heights[i]); } // weights - stream.WriteInt32(this.weights.length); + stream.writeInt32(this.weights.length); for (let i = 0; i < this.weights.length; ++i) { - stream.WriteInt8(this.weights[i]); + stream.writeInt8(this.weights[i]); } // layer buffer - stream.WriteInt32(this.layerBuffer.length); + stream.writeInt32(this.layerBuffer.length); for (let i = 0; i < this.layerBuffer.length; ++i) { - stream.WriteInt16(this.layerBuffer[i]); + stream.writeInt16(this.layerBuffer[i]); } // layer infos - stream.WriteInt32(this.layerInfos.length); + stream.writeInt32(this.layerInfos.length); for (let i = 0; i < this.layerInfos.length; ++i) { - stream.WriteInt32(this.layerInfos[i].slot); - stream.WriteFloat(this.layerInfos[i].tileSize); - stream.WriteString(this.layerInfos[i].detailMap); + stream.writeInt32(this.layerInfos[i].slot); + stream.writeFloat(this.layerInfos[i].tileSize); + stream.writeString(this.layerInfos[i].detailMap); } - return stream.Buffer; + return stream.buffer; } public _exportDefaultNativeData (): Uint8Array { const stream = new TerrainBuffer(); - - stream.WriteInt32(TERRAIN_DATA_VERSION_DEFAULT); - - return stream.Buffer; + stream.writeInt32(TERRAIN_DATA_VERSION_DEFAULT); + return stream.buffer; } } diff --git a/cocos/terrain/terrain-lod.ts b/cocos/terrain/terrain-lod.ts index f36808ac33..007843d2f8 100644 --- a/cocos/terrain/terrain-lod.ts +++ b/cocos/terrain/terrain-lod.ts @@ -32,7 +32,7 @@ export class TerrainLodKey { export class TerrainLod { public mBodyIndex: TerrainIndexPool[] = TerrainIndexPool[TERRAIN_LOD_LEVELS]; - public mConecterIndex: TerrainIndexPool[][][] = TerrainIndexPool[TERRAIN_LOD_LEVELS][TERRAIN_LOD_LEVELS][4]; + public mConnecterIndex: TerrainIndexPool[][][] = TerrainIndexPool[TERRAIN_LOD_LEVELS][TERRAIN_LOD_LEVELS][4]; constructor () { for (let i = 0; i < TERRAIN_LOD_LEVELS; ++i) { @@ -42,13 +42,13 @@ export class TerrainLod { for (let i = 0; i < TERRAIN_LOD_LEVELS; ++i) { for (let j = 0; j < TERRAIN_LOD_LEVELS; ++j) { for (let k = 0; k < 4; ++k) { - this.mConecterIndex[i][j][k] = new TerrainIndexPool(); + this.mConnecterIndex[i][j][k] = new TerrainIndexPool(); } } } this.genBodyIndex(); - this.genConecterIndex(); + this.genConnecterIndex(); /* for (let l = 0; l < TERRAIN_LOD_LEVELS; ++l) { @@ -111,7 +111,7 @@ export class TerrainLod { this.mBodyIndex[level].indices = new Uint16Array(count); let index = 0; - const indeces = new Uint16Array(count); + const indices = new Uint16Array(count); // generate triangle list cw // @@ -120,22 +120,22 @@ export class TerrainLod { for (let y = 0; y < tiles; ++y) { for (let x = 0; x < tiles; ++x) { /* - indeces[index++] = row_n + x * step; - indeces[index++] = row_c + x * step; - indeces[index++] = row_n + (x + 1) * step; + indices[index++] = row_n + x * step; + indices[index++] = row_c + x * step; + indices[index++] = row_n + (x + 1) * step; - indeces[index++] = row_n + (x + 1) * step; - indeces[index++] = row_c + x * step; - indeces[index++] = row_c + (x + 1) * step; + indices[index++] = row_n + (x + 1) * step; + indices[index++] = row_c + x * step; + indices[index++] = row_c + (x + 1) * step; */ - indeces[index++] = row_n + x * step; - indeces[index++] = row_n + (x + 1) * step; - indeces[index++] = row_c + x * step; + indices[index++] = row_n + x * step; + indices[index++] = row_n + (x + 1) * step; + indices[index++] = row_c + x * step; - indeces[index++] = row_n + (x + 1) * step; - indeces[index++] = row_c + (x + 1) * step; - indeces[index++] = row_c + x * step; + indices[index++] = row_n + (x + 1) * step; + indices[index++] = row_c + (x + 1) * step; + indices[index++] = row_c + x * step; } row_c += TERRAIN_LOD_VERTS * step; @@ -143,41 +143,41 @@ export class TerrainLod { } this.mBodyIndex[level].size = index; - this.mBodyIndex[level].indices = indeces; + this.mBodyIndex[level].indices = indices; } - private genConecterIndex () { + private genConnecterIndex () { for (let i = 0; i < TERRAIN_LOD_VERTS; ++i) { for (let j = 0; j < TERRAIN_LOD_VERTS; ++j) { - this._genConecterIndexNorth(i, j); - this._genConecterIndexSouth(i, j); - this._genConecterIndexWest(i, j); - this._genConecterIndexEast(i, j); + this._genConnecterIndexNorth(i, j); + this._genConnecterIndexSouth(i, j); + this._genConnecterIndexWest(i, j); + this._genConnecterIndexEast(i, j); } } } - private _genConecterIndexNorth (level: number, conecter: number) { + private _genConnecterIndexNorth (level: number, connecter: number) { const TN_NorthIndex = TERRAIN_LOD_NORTH_INDEX; - if (conecter < level || level === TERRAIN_LOD_LEVELS - 1) { - this.mConecterIndex[level][conecter][TN_NorthIndex].size = 0; - this.mConecterIndex[level][conecter][TN_NorthIndex].indices = null; + if (connecter < level || level === TERRAIN_LOD_LEVELS - 1) { + this.mConnecterIndex[level][connecter][TN_NorthIndex].size = 0; + this.mConnecterIndex[level][connecter][TN_NorthIndex].indices = null; return; } const self_step = 1 << level; - const neighbor_step = 1 << conecter; + const neighbor_step = 1 << connecter; const self_tile = TERRAIN_LOD_TILES >> level; - const neighbor_tile = TERRAIN_LOD_TILES >> conecter; + const neighbor_tile = TERRAIN_LOD_TILES >> connecter; const count = self_tile * 2 + 2; let index = 0; - const indeces = new Uint16Array(count); + const indices = new Uint16Array(count); // starter - indeces[index++] = 0; - indeces[index++] = 0; + indices[index++] = 0; + indices[index++] = 0; // middler for (let i = 1; i < self_tile; ++i) { @@ -189,39 +189,39 @@ export class TerrainLod { const index0 = y1 * TERRAIN_LOD_VERTS + x1; const index1 = y0 * TERRAIN_LOD_VERTS + x0; - indeces[index++] = index0; - indeces[index++] = index1; + indices[index++] = index0; + indices[index++] = index1; } // ender - indeces[index++] = TERRAIN_LOD_VERTS - 1; - indeces[index++] = TERRAIN_LOD_VERTS - 1; + indices[index++] = TERRAIN_LOD_VERTS - 1; + indices[index++] = TERRAIN_LOD_VERTS - 1; - this.mConecterIndex[level][conecter][TN_NorthIndex].size = index; - this.mConecterIndex[level][conecter][TN_NorthIndex].indices = indeces; + this.mConnecterIndex[level][connecter][TN_NorthIndex].size = index; + this.mConnecterIndex[level][connecter][TN_NorthIndex].indices = indices; } - private _genConecterIndexSouth (level: number, conecter: number) { + private _genConnecterIndexSouth (level: number, connecter: number) { const TN_SouthIndex = TERRAIN_LOD_SOUTH_INDEX; - if (conecter < level || level === TERRAIN_LOD_LEVELS - 1) { - this.mConecterIndex[level][conecter][TN_SouthIndex].size = 0; - this.mConecterIndex[level][conecter][TN_SouthIndex].indices = null; + if (connecter < level || level === TERRAIN_LOD_LEVELS - 1) { + this.mConnecterIndex[level][connecter][TN_SouthIndex].size = 0; + this.mConnecterIndex[level][connecter][TN_SouthIndex].indices = null; return; } const self_step = 1 << level; - const neighbor_step = 1 << conecter; + const neighbor_step = 1 << connecter; const self_tile = TERRAIN_LOD_TILES >> level; - const neighbor_tile = TERRAIN_LOD_TILES >> conecter; + const neighbor_tile = TERRAIN_LOD_TILES >> connecter; const count = self_tile * 2 + 2; let index = 0; - const indeces = new Uint16Array(count); + const indices = new Uint16Array(count); // starter - indeces[index++] = TERRAIN_LOD_TILES * TERRAIN_LOD_VERTS; - indeces[index++] = TERRAIN_LOD_TILES * TERRAIN_LOD_VERTS; + indices[index++] = TERRAIN_LOD_TILES * TERRAIN_LOD_VERTS; + indices[index++] = TERRAIN_LOD_TILES * TERRAIN_LOD_VERTS; // middler for (let i = 1; i < self_tile; ++i) { @@ -233,39 +233,39 @@ export class TerrainLod { const index0 = y1 * TERRAIN_LOD_VERTS + x1; const index1 = y0 * TERRAIN_LOD_VERTS + x0; - indeces[index++] = index0; - indeces[index++] = index1; + indices[index++] = index0; + indices[index++] = index1; } // ender - indeces[index++] = TERRAIN_LOD_VERTS * TERRAIN_LOD_VERTS - 1; - indeces[index++] = TERRAIN_LOD_VERTS * TERRAIN_LOD_VERTS - 1; + indices[index++] = TERRAIN_LOD_VERTS * TERRAIN_LOD_VERTS - 1; + indices[index++] = TERRAIN_LOD_VERTS * TERRAIN_LOD_VERTS - 1; - this.mConecterIndex[level][conecter][TN_SouthIndex].size = index; - this.mConecterIndex[level][conecter][TN_SouthIndex].indices = indeces; + this.mConnecterIndex[level][connecter][TN_SouthIndex].size = index; + this.mConnecterIndex[level][connecter][TN_SouthIndex].indices = indices; } - private _genConecterIndexWest (level: number, conecter: number) { + private _genConnecterIndexWest (level: number, connecter: number) { const TN_WestIndex = TERRAIN_LOD_WEST_INDEX; - if (conecter < level || level === TERRAIN_LOD_LEVELS - 1) { - this.mConecterIndex[level][conecter][TN_WestIndex].size = 0; - this.mConecterIndex[level][conecter][TN_WestIndex].indices = null; + if (connecter < level || level === TERRAIN_LOD_LEVELS - 1) { + this.mConnecterIndex[level][connecter][TN_WestIndex].size = 0; + this.mConnecterIndex[level][connecter][TN_WestIndex].indices = null; return; } const self_step = 1 << level; - const neighbor_step = 1 << conecter; + const neighbor_step = 1 << connecter; const self_tile = TERRAIN_LOD_TILES >> level; - const neighbor_tile = TERRAIN_LOD_TILES >> conecter; + const neighbor_tile = TERRAIN_LOD_TILES >> connecter; const count = self_tile * 2 + 2; let index = 0; - const indeces = new Uint16Array(count); + const indices = new Uint16Array(count); // starter - indeces[index++] = 0; - indeces[index++] = 0; + indices[index++] = 0; + indices[index++] = 0; // middler for (let i = 1; i < self_tile; ++i) { @@ -277,39 +277,39 @@ export class TerrainLod { const index0 = y0 * TERRAIN_LOD_VERTS + x0; const index1 = y1 * TERRAIN_LOD_VERTS + x1; - indeces[index++] = index0; - indeces[index++] = index1; + indices[index++] = index0; + indices[index++] = index1; } // ender - indeces[index++] = TERRAIN_LOD_TILES * TERRAIN_LOD_VERTS; - indeces[index++] = TERRAIN_LOD_TILES * TERRAIN_LOD_VERTS; + indices[index++] = TERRAIN_LOD_TILES * TERRAIN_LOD_VERTS; + indices[index++] = TERRAIN_LOD_TILES * TERRAIN_LOD_VERTS; - this.mConecterIndex[level][conecter][TN_WestIndex].size = index; - this.mConecterIndex[level][conecter][TN_WestIndex].indices = indeces; + this.mConnecterIndex[level][connecter][TN_WestIndex].size = index; + this.mConnecterIndex[level][connecter][TN_WestIndex].indices = indices; } - private _genConecterIndexEast (level: number, conecter: number) { + private _genConnecterIndexEast (level: number, connecter: number) { const TN_EastIndex = TERRAIN_LOD_EAST_INDEX; - if (conecter < level || level === TERRAIN_LOD_LEVELS - 1) { - this.mConecterIndex[level][conecter][TN_EastIndex].size = 0; - this.mConecterIndex[level][conecter][TN_EastIndex].indices = null; + if (connecter < level || level === TERRAIN_LOD_LEVELS - 1) { + this.mConnecterIndex[level][connecter][TN_EastIndex].size = 0; + this.mConnecterIndex[level][connecter][TN_EastIndex].indices = null; return; } const self_step = 1 << level; - const neighbor_step = 1 << conecter; + const neighbor_step = 1 << connecter; const self_tile = TERRAIN_LOD_TILES >> level; - const neighbor_tile = TERRAIN_LOD_TILES >> conecter; + const neighbor_tile = TERRAIN_LOD_TILES >> connecter; const count = self_tile * 2 + 2; let index = 0; - const indeces = new Uint16Array(count); + const indices = new Uint16Array(count); // starter - indeces[index++] = TERRAIN_LOD_VERTS - 1; - indeces[index++] = TERRAIN_LOD_VERTS - 1; + indices[index++] = TERRAIN_LOD_VERTS - 1; + indices[index++] = TERRAIN_LOD_VERTS - 1; // middler for (let i = 1; i < self_tile; ++i) { @@ -321,15 +321,15 @@ export class TerrainLod { const index0 = y0 * TERRAIN_LOD_VERTS + x0; const index1 = y1 * TERRAIN_LOD_VERTS + x1; - indeces[index++] = index0; - indeces[index++] = index1; + indices[index++] = index0; + indices[index++] = index1; } // ender - indeces[index++] = TERRAIN_LOD_VERTS * TERRAIN_LOD_VERTS - 1; - indeces[index++] = TERRAIN_LOD_VERTS * TERRAIN_LOD_VERTS - 1; + indices[index++] = TERRAIN_LOD_VERTS * TERRAIN_LOD_VERTS - 1; + indices[index++] = TERRAIN_LOD_VERTS * TERRAIN_LOD_VERTS - 1; - this.mConecterIndex[level][conecter][TN_EastIndex].size = index; - this.mConecterIndex[level][conecter][TN_EastIndex].indices = indeces; + this.mConnecterIndex[level][connecter][TN_EastIndex].size = index; + this.mConnecterIndex[level][connecter][TN_EastIndex].indices = indices; } } diff --git a/cocos/terrain/terrain.ts b/cocos/terrain/terrain.ts index 6418a88eee..62d91045ef 100644 --- a/cocos/terrain/terrain.ts +++ b/cocos/terrain/terrain.ts @@ -9,7 +9,7 @@ import { Filter, PixelFormat, WrapMode } from '../core/assets/asset-enum'; import { Material } from '../core/assets/material'; import { RenderingSubMesh } from '../core/assets/mesh'; import { Component } from '../core/components'; -import { ccclass, disallowMultiple, executeInEditMode, menu, property } from '../core/data/class-decorator'; +import { ccclass, disallowMultiple, executeInEditMode, help, menu, property } from '../core/data/class-decorator'; import { director } from '../core/director'; import { GFXBuffer } from '../core/gfx/buffer'; import { GFXAttributeName, GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit, GFXPrimitiveMode } from '../core/gfx/define'; @@ -37,21 +37,43 @@ export const TERRAIN_WEST_INDEX = 2; export const TERRAIN_EAST_INDEX = 3; /** - * 地形信息。 + * @en Terrain info + * @zh 地形信息 */ @ccclass('cc.TerrainInfo') export class TerrainInfo { - @property({ - tooltip: '地形Tile的大小', - }) + /** + * @en tile size + * @zh 栅格大小 + */ + @property public tileSize: number = 1; + + /** + * @en block count + * @zh 地形块的数量 + */ @property public blockCount: number[] = [1, 1]; + + /** + * @en weight map size + * @zh 权重图大小 + */ @property public weightMapSize: number = 128; + + /** + * @en light map size + * @zh 光照图大小 + */ @property public lightMapSize: number = 128; + /** + * @en terrain size + * @zh 地形大小 + */ public get size () { const sz = new Size(0, 0); sz.width = this.blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY * this.tileSize; @@ -60,6 +82,10 @@ export class TerrainInfo { return sz; } + /** + * @en tile count + * @zh 栅格数量 + */ public get tileCount () { const _tileCount = [0, 0]; _tileCount[0] = this.blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY; @@ -68,6 +94,10 @@ export class TerrainInfo { return _tileCount; } + /** + * @en vertex count + * @zh 顶点数量 + */ public get vertexCount () { const _vertexCount = this.tileCount; _vertexCount[0] += 1; @@ -77,25 +107,32 @@ export class TerrainInfo { } } +/** + * @en Terrain layer + * @zh 地形纹理层 + */ @ccclass('cc.TerrainLayer') export class TerrainLayer { - @property({ - tooltip: '当前Layer的纹理', - }) + /** + * @en detail texture + * @zh 细节纹理 + */ + @property public detailMap: Texture2D|null = null; - @property({ - tooltip: '纹理的平铺大小,值越小会在同样大小的区域内进行更多次的平铺', - }) + + /** + * @en tile size + * @zh 平铺大小 + */ + @property public tileSize: number = 1; } -export class TerrainVertex { - public position: Vec3 = new Vec3(0, 0, 0); - public normal: Vec3 = new Vec3(0, 1, 0); - public uv: Vec2 = new Vec2(0, 0); -} - -export class TerrainRenderable extends RenderableComponent { +/** + * @en Terrain renderable + * @zh 地形渲染组件 + */ +class TerrainRenderable extends RenderableComponent { public _model: Model | null = null; public _meshData: RenderingSubMesh | null = null; @@ -104,7 +141,7 @@ export class TerrainRenderable extends RenderableComponent { public _currentMaterialLayers: number = 0; public destroy () { - this._invalidMaterial(); + // this._invalidMaterial(); if (this._model != null) { cc.director.root.destroyModel(this._model); this._model = null; @@ -131,13 +168,13 @@ export class TerrainRenderable extends RenderableComponent { return; } - const nlayers = block.getMaxLayer(); - if (this._currentMaterial == null || nlayers !== this._currentMaterialLayers) { + const nLayers = block.getMaxLayer(); + if (this._currentMaterial == null || nLayers !== this._currentMaterialLayers) { this._currentMaterial = new Material(); this._currentMaterial.initialize({ effectAsset: cc.EffectAsset.get('builtin-terrain'), - defines: block._getMaterialDefines(nlayers), + defines: block._getMaterialDefines(nLayers), }); if (this._brushMaterial !== null) { @@ -151,7 +188,7 @@ export class TerrainRenderable extends RenderableComponent { } this.setMaterial(this._currentMaterial, 0); - this._currentMaterialLayers = nlayers; + this._currentMaterialLayers = nLayers; this._model.enabled = true; } } @@ -182,12 +219,20 @@ export class TerrainRenderable extends RenderableComponent { } } +/** + * @en Terrain block info + * @zh 地形块信息 + */ @ccclass('cc.TerrainBlockInfo') export class TerrainBlockInfo { @property public layers: number[] = [-1, -1, -1, -1]; } +/** + * @en Terrain block light map info + * @zh 地形块光照图信息 + */ @ccclass('cc.TerrainBlockLightmapInfo') export class TerrainBlockLightmapInfo { @property @@ -202,6 +247,10 @@ export class TerrainBlockLightmapInfo { public VScale: number = 0; } +/** + * @en Terrain block + * @zh 地形块 + */ export class TerrainBlock { private _terrain: Terrain; private _info: TerrainBlockInfo; @@ -268,7 +317,7 @@ export class TerrainBlock { ]; const subMesh = this._renderable._meshData = new RenderingSubMesh([vertexBuffer], gfxAttributes, GFXPrimitiveMode.TRIANGLE_LIST); - subMesh.indexBuffer = this._terrain.getSharedIndexBuffer() || undefined; + subMesh.indexBuffer = this._terrain._getSharedIndexBuffer() || undefined; this._renderable._model = (cc.director.root as Root).createModel(Model); this._renderable._model.initialize(this._node); @@ -400,14 +449,26 @@ export class TerrainBlock { } } + /** + * @en get layers + * @zh 获得纹理层索引 + */ get layers () { return this._info.layers; } + /** + * @en get light map + * @zh 获得光照图 + */ get lightmap () { return this._lightmapInfo ? this._lightmapInfo.texture : null; } + /** + * @en get light map uv parameter + * @zh 获得光照图纹理坐标参数 + */ get lightmapUVParam () { if (this._lightmapInfo != null) { return new Vec4(this._lightmapInfo.UOff, this._lightmapInfo.VOff, this._lightmapInfo.UScale, this._lightmapInfo.VScale); @@ -417,14 +478,26 @@ export class TerrainBlock { } } + /** + * @en get terrain owner + * @zh 获得地形对象 + */ public getTerrain () { return this._terrain; } + /** + * @en get index + * @zh 获得地形索引 + */ public getIndex () { return this._index; } + /** + * @en get rect bound + * @zh 获得地形矩形包围体 + */ public getRect () { const rect = new Rect(); rect.x = this._index[0] * TERRAIN_BLOCK_TILE_COMPLEXITY; @@ -435,6 +508,10 @@ export class TerrainBlock { return rect; } + /** + * @en set layer + * @zh 设置纹理层 + */ public setLayer (index: number, layerId: number) { if (this.layers[index] !== layerId) { this.layers[index] = layerId; @@ -443,10 +520,18 @@ export class TerrainBlock { } } + /** + * @en get layer + * @zh 获得纹理层 + */ public getLayer (index: number) { return this.layers[index]; } + /** + * @en get max layer index + * @zh 获得最大纹理索引 + */ public getMaxLayer () { if (this.layers[3] >= 0) { return 3; @@ -579,8 +664,12 @@ export class TerrainBlock { } } +/** + * @en Terrain + * @zh 地形组件 + */ @ccclass('cc.Terrain') -// @menu('Components/Terrain') +@help('i18n:cc.TerrainComponent') @executeInEditMode @disallowMultiple export class Terrain extends Component { @@ -652,6 +741,10 @@ export class Terrain extends Component { return this.__asset; } + /** + * @en get terrain size + * @zh 获得地形大小 + */ public get size () { const sz = new Size(0, 0); sz.width = this.blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY * this.tileSize; @@ -659,14 +752,26 @@ export class Terrain extends Component { return sz; } + /** + * @en get tile size + * @zh 获得栅格大小 + */ get tileSize () { return this._tileSize; } + /** + * @en get tile count + * @zh 获得栅格数量 + */ public get tileCount () { return [this.blockCount[0] * TERRAIN_BLOCK_TILE_COMPLEXITY, this.blockCount[1] * TERRAIN_BLOCK_TILE_COMPLEXITY]; } + /** + * @en get vertex count + * @zh 获得顶点数量 + */ public get vertexCount () { const _vertexCount = this.tileCount; _vertexCount[0] += 1; @@ -675,30 +780,58 @@ export class Terrain extends Component { return _vertexCount; } + /** + * @en get block count + * @zh 获得地形块数量 + */ get blockCount () { return this._blockCount; } + /** + * @en get light map size + * @zh 获得光照图大小 + */ get lightMapSize () { return this._lightMapSize; } + /** + * @en get weight map size + * @zh 获得权重图大小 + */ get weightMapSize () { return this._weightMapSize; } + /** + * @en get height buffer + * @zh 获得高度缓存 + */ get heights () { return this._heights; } + /** + * @en get weight buffer + * @zh 获得权重缓存 + */ get weights () { return this._weights; } + /** + * @en check valid + * @zh 检测是否有效 + */ get valid () { return this._blocks.length > 0; } + /** + * @en get terrain info + * @zh 获得地形信息 + */ @property({ type: TerrainInfo, visible: true, @@ -714,6 +847,10 @@ export class Terrain extends Component { return ti; } + /** + * @en build + * @zh 构建地形 + */ public build (info: TerrainInfo) { this._tileSize = info.tileSize; this._blockCount[0] = info.blockCount[0]; @@ -724,6 +861,10 @@ export class Terrain extends Component { return this._buildImp(); } + /** + * @en rebuild + * @zh 重建地形 + */ public rebuild (info: TerrainInfo) { // build block info const blockInfos: TerrainBlockInfo[] = []; @@ -776,6 +917,10 @@ export class Terrain extends Component { } } + /** + * @en import height field + * @zh 导入高度图 + */ public importHeightField (hf: HeightField, heightScale: number) { let index = 0; for (let j = 0; j < this.vertexCount[1]; ++j) { @@ -797,6 +942,10 @@ export class Terrain extends Component { } } + /** + * @en export height field + * @zh 导出高度图 + */ public exportHeightField (hf: HeightField, heightScale: number) { let index = 0; for (let j = 0; j < hf.h; ++j) { @@ -834,13 +983,13 @@ export class Terrain extends Component { } for (let i = 0; i < this._layers.length; ++i) { - const tlayer = this._layers[i]; - if (tlayer != null && tlayer.detailMap != null) { - const ilayer = new TerrainLayerInfo(); - ilayer.slot = i; - ilayer.tileSize = tlayer.tileSize; - ilayer.detailMap = tlayer.detailMap._uuid; - asset.layerInfos.push(ilayer); + const temp = this._layers[i]; + if (temp != null && temp.detailMap != null) { + const layer = new TerrainLayerInfo(); + layer.slot = i; + layer.tileSize = temp.tileSize; + layer.detailMap = temp.detailMap._uuid; + asset.layerInfos.push(layer); } } @@ -911,12 +1060,16 @@ export class Terrain extends Component { this._buildImp(true); } - public update (dtime: number) { + public update (deltaTime: number) { for (const i of this._blocks) { i.update(); } } + /** + * @en add layer + * @zh 添加纹理层 + */ public addLayer (layer: TerrainLayer) { for (let i = 0; i < this._layers.length; ++i) { if (this._layers[i] == null) { @@ -928,14 +1081,26 @@ export class Terrain extends Component { return -1; } + /** + * @en set layer + * @zh 设置纹理层 + */ public setLayer (i: number, layer: TerrainLayer) { this._layers[i] = layer; } + /** + * @en remove layer + * @zh 移除纹理层 + */ public removeLayer (id: number) { this._layers[id] = null; } + /** + * @en get layer + * @zh 获得纹理层 + */ public getLayer (id: number) { if (id === -1) { return null; @@ -945,6 +1110,10 @@ export class Terrain extends Component { } + /** + * @en get position + * @zh 获得地形上的位置 + */ public getPosition (i: number, j: number) { const x = i * this._tileSize; const z = j * this._tileSize; @@ -957,14 +1126,26 @@ export class Terrain extends Component { return this._heights; } + /** + * @en set height + * @zh 设置地形上的高度 + */ public setHeight (i: number, j: number, h: number) { this._heights[j * this.vertexCount[0] + i] = TERRAIN_HEIGHT_BASE + h / TERRAIN_HEIGHT_FACTORY; } + /** + * @en get height + * @zh 获得地形上的高度 + */ public getHeight (i: number, j: number) { return (this._heights[j * this.vertexCount[0] + i] - TERRAIN_HEIGHT_BASE) * TERRAIN_HEIGHT_FACTORY; } + /** + * @en set height + * @zh 设置高度 + */ public getHeightClamp (i: number, j: number) { i = clamp(i, 0, this.vertexCount[0] - 1); j = clamp(j, 0, this.vertexCount[1] - 1); @@ -972,6 +1153,10 @@ export class Terrain extends Component { return this.getHeight(i, j); } + /** + * @en get height by point + * @zh 根据点的坐标获得高度 + */ public getHeightAt (x: number, y: number) { const fx = x / this.tileSize; const fy = y / this.tileSize; @@ -1021,6 +1206,10 @@ export class Terrain extends Component { this._normals[index * 3 + 2] = n.z; } + /** + * @en get normal + * @zh 获得法线 + */ public getNormal (i: number, j: number) { const index = j * this.vertexCount[0] + i; @@ -1032,6 +1221,10 @@ export class Terrain extends Component { return n; } + /** + * @en get normal by point + * @zh 根据点的坐标获得法线 + */ public getNormalAt (x: number, y: number) { const fx = x / this.tileSize; const fy = y / this.tileSize; @@ -1082,6 +1275,10 @@ export class Terrain extends Component { return n; } + /** + * @en set weight + * @zh 设置权重 + */ public setWeight (i: number, j: number, w: Vec4) { const index = j * this._weightMapSize * this._blockCount[0] + i; @@ -1091,6 +1288,10 @@ export class Terrain extends Component { this._weights[index * 4 + 3] = w.w * 255; } + /** + * @en get weight + * @zh 获得权重 + */ public getWeight (i: number, j: number) { const index = j * this._weightMapSize * this._blockCount[0] + i; @@ -1103,6 +1304,10 @@ export class Terrain extends Component { return w; } + /** + * @en get normal by point + * @zh 根据点的坐标获得权重 + */ public getWeightAt (x: number, y: number) { const fx = x / this.tileSize; const fy = y / this.tileSize; @@ -1149,56 +1354,53 @@ export class Terrain extends Component { return n; } + /** + * @en get block info + * @zh 获得地形块信息 + */ public getBlockInfo (i: number, j: number) { return this._blockInfos[j * this._blockCount[0] + i]; } + /** + * @en get block + * @zh 获得地形块对象 + */ public getBlock (i: number, j: number) { return this._blocks[j * this._blockCount[0] + i]; } + /** + * @en get all blocks + * @zh 获得地形块缓存 + */ public getBlocks () { return this._blocks; } - public getSharedIndexBuffer () { - return this._sharedIndexBuffer; - } - - public _resetLightmap (enble: boolean) { - this._lightmapInfos.length = 0; - if (enble) { - for (let i = 0; i < this._blockCount[0] * this._blockCount[1]; ++i) { - this._lightmapInfos.push(new TerrainBlockLightmapInfo()); - } - } - } - - public _updateLightmap (blockId: number, tex: Texture2D|null, uoff: number, voff: number, uscale: number, vscale: number) { - this._lightmapInfos[blockId].texture = tex; - this._lightmapInfos[blockId].UOff = uoff; - this._lightmapInfos[blockId].VOff = voff; - this._lightmapInfos[blockId].UScale = uscale; - this._lightmapInfos[blockId].VScale = vscale; - this._blocks[blockId]._updateLightmap(this._lightmapInfos[blockId]); - } - - public _getLightmapInfo (i: number, j: number) { - const index = j * this._blockCount[0] + i; - return index < this._lightmapInfos.length ? this._lightmapInfos[index] : null; - } - - public rayCheck (start: Vec3, dir: Vec3, step: number, worldspace: boolean = true) { + /** + * @en ray check + * @param start ray start + * @param dir ray direction + * @param step ray step + * @param worldSpace is world space + * @zh 射线检测 + * @param start 射线原点 + * @param dir 射线方向 + * @param step 射线步长 + * @param worldSpace 是否在世界空间 + */ + public rayCheck (start: Vec3, dir: Vec3, step: number, worldSpace: boolean = true) { const MAX_COUNT = 2000; const trace = start; - if (worldspace) { + if (worldSpace) { Vec3.subtract(trace, start, this.node.getWorldPosition()); } - const dstep = new Vec3(); - dstep.set(dir); - dstep.multiplyScalar(step); + const delta = new Vec3(); + delta.set(dir); + delta.multiplyScalar(step); let position: Vec3|null = null; @@ -1235,14 +1437,41 @@ export class Terrain extends Component { break; } - trace.add(dstep); + trace.add(delta); } } return position; } - public _calcuNormal (x: number, z: number) { + public _getSharedIndexBuffer () { + return this._sharedIndexBuffer; + } + + public _resetLightmap (enble: boolean) { + this._lightmapInfos.length = 0; + if (enble) { + for (let i = 0; i < this._blockCount[0] * this._blockCount[1]; ++i) { + this._lightmapInfos.push(new TerrainBlockLightmapInfo()); + } + } + } + + public _updateLightmap (blockId: number, tex: Texture2D|null, uOff: number, vOff: number, uScale: number, vScale: number) { + this._lightmapInfos[blockId].texture = tex; + this._lightmapInfos[blockId].UOff = uOff; + this._lightmapInfos[blockId].VOff = vOff; + this._lightmapInfos[blockId].UScale = uScale; + this._lightmapInfos[blockId].VScale = vScale; + this._blocks[blockId]._updateLightmap(this._lightmapInfos[blockId]); + } + + public _getLightmapInfo (i: number, j: number) { + const index = j * this._blockCount[0] + i; + return index < this._lightmapInfos.length ? this._lightmapInfos[index] : null; + } + + public _calcNormal (x: number, z: number) { let flip = 1; const here = this.getPosition(x, z); let right: Vec3; @@ -1280,7 +1509,7 @@ export class Terrain extends Component { let index = 0; for (let y = 0; y < this.vertexCount[1]; ++y) { for (let x = 0; x < this.vertexCount[0]; ++x) { - const n = this._calcuNormal(x, y); + const n = this._calcNormal(x, y); this._normals[index * 3 + 0] = n.x; this._normals[index * 3 + 1] = n.y; @@ -1329,12 +1558,12 @@ export class Terrain extends Component { } // build heights & normals - const vcount = this.vertexCount[0] * this.vertexCount[1]; - if (this._heights === null || this._heights.length !== vcount) { - this._heights = new Uint16Array(vcount); - this._normals = new Array(vcount * 3); + const vertexCount = this.vertexCount[0] * this.vertexCount[1]; + if (this._heights === null || this._heights.length !== vertexCount) { + this._heights = new Uint16Array(vertexCount); + this._normals = new Array(vertexCount * 3); - for (let i = 0; i < vcount; ++i) { + for (let i = 0; i < vertexCount; ++i) { this._heights[i] = TERRAIN_HEIGHT_BASE; this._normals[i * 3 + 0] = 0; this._normals[i * 3 + 1] = 1; @@ -1342,7 +1571,7 @@ export class Terrain extends Component { } } else { - this._normals = new Array(vcount * 3); + this._normals = new Array(vertexCount * 3); this._buildNormals(); } @@ -1467,7 +1696,7 @@ export class Terrain extends Component { }; // sample weight - const sampleOldWeight = (_x: number, _y: number, _xoff: number, _yoff: number, _weights: Uint8Array) => { + const sampleOldWeight = (_x: number, _y: number, _xOff: number, _yOff: number, _weights: Uint8Array) => { const ix0 = Math.floor(_x); const iz0 = Math.floor(_y); const ix1 = ix0 + 1; @@ -1475,10 +1704,10 @@ export class Terrain extends Component { const dx = _x - ix0; const dz = _y - iz0; - const a = getOldWeight(ix0 + _xoff, iz0 + _yoff, this._weights); - const b = getOldWeight(ix1 + _xoff, iz0 + _yoff, this._weights); - const c = getOldWeight(ix0 + _xoff, iz1 + _yoff, this._weights); - const d = getOldWeight(ix1 + _xoff, iz1 + _yoff, this._weights); + const a = getOldWeight(ix0 + _xOff, iz0 + _yOff, this._weights); + const b = getOldWeight(ix1 + _xOff, iz0 + _yOff, this._weights); + const c = getOldWeight(ix0 + _xOff, iz1 + _yOff, this._weights); + const d = getOldWeight(ix1 + _xOff, iz1 + _yOff, this._weights); const m = new Vec4(); Vec4.add(m, b, c).multiplyScalar(0.5); @@ -1506,20 +1735,20 @@ export class Terrain extends Component { // fill new weights for (let j = 0; j < h; ++j) { for (let i = 0; i < w; ++i) { - const uoff = i * oldWeightMapSize; - const voff = j * oldWeightMapSize; + const uOff = i * oldWeightMapSize; + const vOff = j * oldWeightMapSize; for (let v = 0; v < info.weightMapSize; ++v) { for (let u = 0; u < info.weightMapSize; ++u) { // tslint:disable-next-line: no-shadowed-variable let w: Vec4; if (info.weightMapSize === oldWeightMapSize) { - w = getOldWeight(u + uoff, v + voff, this._weights); + w = getOldWeight(u + uOff, v + vOff, this._weights); } else { const x = u / (info.weightMapSize - 1) * (oldWeightMapSize - 1); const y = v / (info.weightMapSize - 1) * (oldWeightMapSize - 1); - w = sampleOldWeight(x, y, uoff, voff, this._weights); + w = sampleOldWeight(x, y, uOff, vOff, this._weights); } const du = i * info.weightMapSize + u; From ae097582cd47c3765cb58c82bab5af6156282d51 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Tue, 26 May 2020 11:19:03 +0800 Subject: [PATCH 37/74] Bump tfig@1.2.4 (#6742) --- package-lock.json | 56 +++++++++++++++++++++++------------------------ package.json | 2 +- 2 files changed, 29 insertions(+), 29 deletions(-) diff --git a/package-lock.json b/package-lock.json index c278d218da..17c1e66a1b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10661,9 +10661,9 @@ "dev": true }, "tfig": { - "version": "1.2.3", - "resolved": "https://registry.npmjs.org/tfig/-/tfig-1.2.3.tgz", - "integrity": "sha512-dNOGoeUy7sx8DdY9AkY7pq5KNZ1jqHCgvdfPEEnUPl53oW76fqUA4o87glIkPkv0Tg3NxqlBxSLYgmvFzQBOLQ==", + "version": "1.2.4", + "resolved": "https://registry.npm.taobao.org/tfig/download/tfig-1.2.4.tgz?cache=0&sync_timestamp=1590462801724&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Ftfig%2Fdownload%2Ftfig-1.2.4.tgz", + "integrity": "sha1-JsX47k1zgqMy1GVfjKpo3p0mV4E=", "dev": true, "requires": { "fs-extra": "^7.0.1", @@ -10673,14 +10673,14 @@ "dependencies": { "ansi-regex": { "version": "4.1.0", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-4.1.0.tgz", - "integrity": "sha512-1apePfXM1UOSqw0o9IiFAovVz9M5S1Dg+4TrDwfMewQ6p/rmMueb7tWZjQ1rx4Loy1ArBggoqGpfqqdI4rondg==", + "resolved": "https://registry.npm.taobao.org/ansi-regex/download/ansi-regex-4.1.0.tgz?cache=0&sync_timestamp=1570188663907&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fansi-regex%2Fdownload%2Fansi-regex-4.1.0.tgz", + "integrity": "sha1-i5+PCM8ay4Q3Vqg5yox+MWjFGZc=", "dev": true }, "cliui": { "version": "5.0.0", - "resolved": "https://registry.npmjs.org/cliui/-/cliui-5.0.0.tgz", - "integrity": "sha512-PYeGSEmmHM6zvoef2w8TPzlrnNpXIjTipYK780YswmIP9vjxmd6Y2a3CB2Ks6/AU8NHjZugXvo8w3oWM2qnwXA==", + "resolved": "https://registry.npm.taobao.org/cliui/download/cliui-5.0.0.tgz?cache=0&sync_timestamp=1573943292170&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fcliui%2Fdownload%2Fcliui-5.0.0.tgz", + "integrity": "sha1-3u/P2y6AB4SqNPRvoI4GhRx7u8U=", "dev": true, "requires": { "string-width": "^3.1.0", @@ -10690,8 +10690,8 @@ }, "find-up": { "version": "3.0.0", - "resolved": "https://registry.npmjs.org/find-up/-/find-up-3.0.0.tgz", - "integrity": "sha512-1yD6RmLI1XBfxugvORwlck6f75tYL+iR0jqwsOrOxMZyGYqUuDhJ0l4AXdO1iX/FTs9cBAMEk1gWSEx1kSbylg==", + "resolved": "https://registry.npm.taobao.org/find-up/download/find-up-3.0.0.tgz", + "integrity": "sha1-SRafHXmTQwZG2mHsxa41XCHJe3M=", "dev": true, "requires": { "locate-path": "^3.0.0" @@ -10699,20 +10699,20 @@ }, "get-caller-file": { "version": "2.0.5", - "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", - "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "resolved": "https://registry.npm.taobao.org/get-caller-file/download/get-caller-file-2.0.5.tgz", + "integrity": "sha1-T5RBKoLbMvNuOwuXQfipf+sDH34=", "dev": true }, "require-main-filename": { "version": "2.0.0", - "resolved": "https://registry.npmjs.org/require-main-filename/-/require-main-filename-2.0.0.tgz", - "integrity": "sha512-NKN5kMDylKuldxYLSUfrbo5Tuzh4hd+2E8NPPX02mZtn1VuREQToYe/ZdlJy+J3uCpfaiGF05e7B8W0iXbQHmg==", + "resolved": "https://registry.npm.taobao.org/require-main-filename/download/require-main-filename-2.0.0.tgz", + "integrity": "sha1-0LMp7MfMD2Fkn2IhW+aa9UqomJs=", "dev": true }, "string-width": { "version": "3.1.0", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-3.1.0.tgz", - "integrity": "sha512-vafcv6KjVZKSgz06oM/H6GDBrAtz8vdhQakGjFIvNrHA6y3HCF1CInLy+QLq8dTJPQ1b+KDUqDFctkdRW44e1w==", + "resolved": "https://registry.npm.taobao.org/string-width/download/string-width-3.1.0.tgz?cache=0&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fstring-width%2Fdownload%2Fstring-width-3.1.0.tgz", + "integrity": "sha1-InZ74htirxCBV0MG9prFG2IgOWE=", "dev": true, "requires": { "emoji-regex": "^7.0.1", @@ -10722,8 +10722,8 @@ }, "strip-ansi": { "version": "5.2.0", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-5.2.0.tgz", - "integrity": "sha512-DuRs1gKbBqsMKIZlrffwlug8MHkcnpjs5VPmL1PAh+mA30U0DTotfDZ0d2UUsXpPmPmMMJ6W773MaA3J+lbiWA==", + "resolved": "https://registry.npm.taobao.org/strip-ansi/download/strip-ansi-5.2.0.tgz?cache=0&sync_timestamp=1573280518303&other_urls=https%3A%2F%2Fregistry.npm.taobao.org%2Fstrip-ansi%2Fdownload%2Fstrip-ansi-5.2.0.tgz", + "integrity": "sha1-jJpTb+tq/JYr36WxBKUJHBrZwK4=", "dev": true, "requires": { "ansi-regex": "^4.1.0" @@ -10737,8 +10737,8 @@ }, "wrap-ansi": { "version": "5.1.0", - "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-5.1.0.tgz", - "integrity": "sha512-QC1/iN/2/RPVJ5jYK8BGttj5z83LmSKmvbvrXPNCLZSEb32KKVDJDl/MOt2N01qU2H/FkzEa9PKto1BqDjtd7Q==", + "resolved": "https://registry.npm.taobao.org/wrap-ansi/download/wrap-ansi-5.1.0.tgz", + "integrity": "sha1-H9H2cjXVttD+54EFYAG/tpTAOwk=", "dev": true, "requires": { "ansi-styles": "^3.2.0", @@ -10748,14 +10748,14 @@ }, "y18n": { "version": "4.0.0", - "resolved": "https://registry.npmjs.org/y18n/-/y18n-4.0.0.tgz", - "integrity": "sha512-r9S/ZyXu/Xu9q1tYlpsLIsa3EeLXXk0VwlxqTcFRfg9EhMW+17kbt9G0NrgCmhGb5vT2hyhJZLfDGx+7+5Uj/w==", + "resolved": "https://registry.npm.taobao.org/y18n/download/y18n-4.0.0.tgz", + "integrity": "sha1-le+U+F7MgdAHwmThkKEg8KPIVms=", "dev": true }, "yargs": { - "version": "13.3.0", - "resolved": "https://registry.npmjs.org/yargs/-/yargs-13.3.0.tgz", - "integrity": "sha512-2eehun/8ALW8TLoIl7MVaRUrg+yCnenu8B4kBlRxj3GJGDKU1Og7sMXPNm1BYyM1DOJmTZ4YeN/Nwxv+8XJsUA==", + "version": "13.3.2", + "resolved": "https://registry.npm.taobao.org/yargs/download/yargs-13.3.2.tgz", + "integrity": "sha1-rX/+/sGqWVZayRX4Lcyzipwxot0=", "dev": true, "requires": { "cliui": "^5.0.0", @@ -10767,13 +10767,13 @@ "string-width": "^3.0.0", "which-module": "^2.0.0", "y18n": "^4.0.0", - "yargs-parser": "^13.1.1" + "yargs-parser": "^13.1.2" } }, "yargs-parser": { - "version": "13.1.1", - "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-13.1.1.tgz", - "integrity": "sha512-oVAVsHz6uFrg3XQheFII8ESO2ssAf9luWuAd6Wexsu4F3OtIW0o8IribPXYrD4WC24LWtPrJlGy87y5udK+dxQ==", + "version": "13.1.2", + "resolved": "https://registry.npm.taobao.org/yargs-parser/download/yargs-parser-13.1.2.tgz", + "integrity": "sha1-Ew8JcC667vJlDVTObj5XBvek+zg=", "dev": true, "requires": { "camelcase": "^5.0.0", diff --git a/package.json b/package.json index 90b6376eab..433b7639a8 100644 --- a/package.json +++ b/package.json @@ -41,7 +41,7 @@ "jest": "^24.8.0", "spectorjs": "^0.9.15", "stats.js": "^0.17.0", - "tfig": "^1.2.3", + "tfig": "^1.2.4", "ts-jest": "^24.3.0", "typedoc": "^0.14.2", "typedoc-plugin-external-module-name": "github:cocos-creator/typedoc-plugin-external-module-name#master", From b4580ecfbf60f446b80545051da37ce4e9f0b8b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Tue, 26 May 2020 15:50:22 +0800 Subject: [PATCH 38/74] Animation events (#6737) --- cocos/core/animation/animation-component.ts | 63 ++++++++++++++------- cocos/core/animation/animation-state.ts | 26 +++++---- tests/animation/animation-events.test.ts | 59 +++++++++++++++++++ 3 files changed, 114 insertions(+), 34 deletions(-) create mode 100644 tests/animation/animation-events.test.ts diff --git a/cocos/core/animation/animation-component.ts b/cocos/core/animation/animation-component.ts index ebe526e51a..179f2f7ab7 100644 --- a/cocos/core/animation/animation-component.ts +++ b/cocos/core/animation/animation-component.ts @@ -28,7 +28,7 @@ */ import { Component } from '../components/component'; -import { ccclass, help, executeInEditMode, executionOrder, menu, property } from '../data/class-decorator'; +import { ccclass, executeInEditMode, executionOrder, help, menu, property } from '../data/class-decorator'; import { Eventify } from '../event/eventify'; import { warnID } from '../platform/debug'; import * as ArrayUtils from '../utils/array'; @@ -77,8 +77,6 @@ export enum EventType { } ccenum(EventType); -type AnimationEventCallback = (this: ThisType, type: EventType, state: AnimationState) => void; - /** * 动画组件管理动画状态来控制动画的播放。 * 它提供了方便的接口用来预创建指定动画剪辑的动画状态,并提供了一系列事件: @@ -182,7 +180,7 @@ export class AnimationComponent extends Eventify(Component) { protected _crossFade = new CrossFade(); - protected _nameToState: { [name: string]: AnimationState; } = createMap(true); + protected _nameToState: Record = createMap(true); @property({ type: [AnimationClip] }) protected _clips: (AnimationClip | null)[] = []; @@ -319,6 +317,7 @@ export class AnimationComponent extends Eventify(Component) { public removeState (name: string) { const state = this._nameToState[name]; if (state) { + state.allowLastFrameEvent = false; state.stop(); delete this._nameToState[name]; } @@ -351,11 +350,12 @@ export class AnimationComponent extends Eventify(Component) { * @param {Boolean} [force=false] - If force is true, then will always remove the clip and any animation states based on it. */ public removeClip (clip: AnimationClip, force?: boolean) { - let state: AnimationState | undefined; - for (const name of Object.keys(this._nameToState)) { - state = this._nameToState[name]; + let removalState: AnimationState | undefined; + for (const name in this._nameToState) { + const state = this._nameToState[name]; const stateClip = state.clip; if (stateClip === clip) { + removalState = state; break; } } @@ -368,8 +368,8 @@ export class AnimationComponent extends Eventify(Component) { } } - if (state && state.isPlaying) { - if (force) { state.stop(); } + if (removalState && removalState.isPlaying) { + if (force) { removalState.stop(); } else { if (!TEST) { warnID(3903); } return; @@ -378,8 +378,8 @@ export class AnimationComponent extends Eventify(Component) { this._clips = this._clips.filter((item) => item !== clip); - if (state) { - delete this._nameToState[state.name]; + if (removalState) { + delete this._nameToState[removalState.name]; } } @@ -410,10 +410,16 @@ export class AnimationComponent extends Eventify(Component) { */ public on (type: EventType, callback: TFunction, thisArg?: any) { const ret = super.on(type, callback, thisArg); - if (type === 'lastframe') { - for (const stateName of Object.keys(this._nameToState)) { - this._nameToState[stateName]!._lastframeEventOn = true; - } + if (type === EventType.LASTFRAME) { + this._syncAllowLastFrameEvent(); + } + return ret; + } + + public once (type: EventType, callback: TFunction, thisArg?: any) { + const ret = super.once(type, callback, thisArg); + if (type === EventType.LASTFRAME) { + this._syncAllowLastFrameEvent(); } return ret; } @@ -433,14 +439,10 @@ export class AnimationComponent extends Eventify(Component) { * ``` */ public off (type: EventType, callback?: Function, thisArg?: any) { - if (type === 'lastframe') { - const nameToState = this._nameToState; - for (const name of Object.keys(nameToState)) { - const state = nameToState[name]!; - state._lastframeEventOn = false; - } - } super.off(type, callback, thisArg); + if (type === EventType.LASTFRAME) { + this._syncDisallowLastFrameEvent(); + } } protected _createState (clip: AnimationClip, name?: string) { @@ -450,6 +452,7 @@ export class AnimationComponent extends Eventify(Component) { protected _doCreateState (clip: AnimationClip, name: string) { const state = this._createState(clip, name); state._setEventTarget(this); + state.allowLastFrameEvent = this.hasEventListener(EventType.LASTFRAME); if (this.node) { state.initialize(this.node); } @@ -483,6 +486,22 @@ export class AnimationComponent extends Eventify(Component) { } } } + + private _syncAllowLastFrameEvent () { + if (this.hasEventListener(EventType.LASTFRAME)) { + for (const stateName in this._nameToState) { + this._nameToState[stateName].allowLastFrameEvent = true; + } + } + } + + private _syncDisallowLastFrameEvent () { + if (!this.hasEventListener(EventType.LASTFRAME)) { + for (const stateName in this._nameToState) { + this._nameToState[stateName].allowLastFrameEvent = false; + } + } + } } export namespace AnimationComponent { diff --git a/cocos/core/animation/animation-state.ts b/cocos/core/animation/animation-state.ts index 76f7b54e3d..e0ff6ef7d5 100644 --- a/cocos/core/animation/animation-state.ts +++ b/cocos/core/animation/animation-state.ts @@ -275,7 +275,13 @@ export class AnimationState extends Playable { public frameRate = 0; - public _lastframeEventOn = false; + /** + * @zh + * 是否允许触发 `LastFrame` 事件。 + * @en + * Whether `LastFrame` should be triggered. + */ + public allowLastFrameEvent = false; protected _wrapMode = WrapMode.Normal; @@ -421,11 +427,7 @@ export class AnimationState extends Playable { public emit (type: K, ...args: EventArgumentsOf): void; - public emit (...restargs: any[]) { - const args = new Array(restargs.length); - for (let i = 0, l = args.length; i < l; i++) { - args[i] = restargs[i]; - } + public emit (...args: any[]) { cc.director.getAnimationManager().pushDelayEvent(this, '_emit', args); } @@ -434,7 +436,7 @@ export class AnimationState extends Playable { public on (type: string, callback: Function, target?: any) { if (this._target && this._target.isValid) { if (type === 'lastframe') { - this._lastframeEventOn = true; + this.allowLastFrameEvent = true; } return this._target.on(type, callback, target); } @@ -448,11 +450,11 @@ export class AnimationState extends Playable { public once (type: string, callback: Function, target?: any) { if (this._target && this._target.isValid) { if (type === 'lastframe') { - this._lastframeEventOn = true; + this.allowLastFrameEvent = true; } return this._target.once(type, (event) => { callback.call(target, event); - this._lastframeEventOn = false; + this.allowLastFrameEvent = false; }); } else { @@ -464,7 +466,7 @@ export class AnimationState extends Playable { if (this._target && this._target.isValid) { if (type === 'lastframe') { if (!this._target.hasEventListener(type)) { - this._lastframeEventOn = false; + this.allowLastFrameEvent = false; } } this._target.off(type, callback, target); @@ -610,7 +612,7 @@ export class AnimationState extends Playable { // sample const info = this.sample(); - if (this._lastframeEventOn) { + if (this.allowLastFrameEvent) { let lastInfo; if (!this._lastWrapInfo) { lastInfo = this._lastWrapInfo = new WrappedInfo(info); @@ -644,7 +646,7 @@ export class AnimationState extends Playable { } } - if (this._lastframeEventOn) { + if (this.allowLastFrameEvent) { if (this._lastIterations === undefined) { this._lastIterations = ratio; } diff --git a/tests/animation/animation-events.test.ts b/tests/animation/animation-events.test.ts new file mode 100644 index 0000000000..14014ac427 --- /dev/null +++ b/tests/animation/animation-events.test.ts @@ -0,0 +1,59 @@ +import { Node, AnimationComponent, director, AnimationClip, math } from '../../cocos/core'; + + +test('Animation events(general)', () => { + +}); + +test('Animation event(last-frame event optimization)', () => { + const animationComponent = createTestAnimationComponent(); + + const clip0 = createTestClip('clip0'); + const clip1 = createTestClip('clip1'); + const initialClips = [ clip0, clip1 ]; + const defaultClip = initialClips[0]; + animationComponent.clips = initialClips; + animationComponent.defaultClip = defaultClip; + const initialStates = [clip0, clip0].map((clip) => animationComponent.getState(clip.name)); + + const handler1 = () => {}; + const handler2 = () => {}; + + expect(initialStates.every((state) => !state.allowLastFrameEvent)).toBeTruthy(); + + animationComponent.on(AnimationComponent.EventType.LASTFRAME, handler1); + // After subscribe the last-frame event, all states should have `allowLastFrameEvent` set to `true`. + expect(initialStates.every((state) => state.allowLastFrameEvent)).toBeTruthy(); + + animationComponent.on(AnimationComponent.EventType.LASTFRAME, handler2); + // Should no problem. + expect(initialStates.every((state) => state.allowLastFrameEvent)).toBeTruthy(); + + animationComponent.off(AnimationComponent.EventType.LASTFRAME, handler2); + // Now we unsubscribe one, but this should still true. + expect(initialStates.every((state) => state.allowLastFrameEvent)).toBeTruthy(); + + animationComponent.off(AnimationComponent.EventType.LASTFRAME, handler1); + // All states should have `allowLastFrameEvent` set to `false` + // if no any subscribe on 'last-frame' event. + expect(initialStates.every((state) => !state.allowLastFrameEvent)).toBeTruthy(); + + animationComponent.on(AnimationComponent.EventType.LASTFRAME, handler1); + // The newly added state should automatically have `allowLastFrameEvent` set to `true`. + const newState = animationComponent.createState(createTestClip('clip-new')); + // The newly added state should also have `allowLastFrameEvent` set to `true`. + expect(newState.allowLastFrameEvent).toBeTruthy(); +}); + +function createTestAnimationComponent() { + const node = new Node(); + const animationComponent = node.addComponent(AnimationComponent); + return animationComponent; +} + +function createTestClip(name: string, duration: number = math.randomRange(0, 1)) { + const clip = new AnimationClip(); + clip.name = name; + clip.duration = 0; + return clip; +} \ No newline at end of file From 2c1ef7941ffc8038ee1699b98265975d0f850058 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Wed, 27 May 2020 11:03:56 +0800 Subject: [PATCH 39/74] Improve typing (#6751) --- @types/globals.d.ts | 2 ++ cocos/audio/assets/clip.ts | 4 ++-- cocos/core/3d/framework/camera-component.ts | 12 ++++++------ cocos/core/3d/framework/light-component.ts | 4 ++-- cocos/core/3d/framework/model-component.ts | 2 +- cocos/core/animation/animation-clip.ts | 2 +- cocos/core/animation/animation-component.ts | 2 +- cocos/core/assets/texture-base.ts | 6 +++--- cocos/ui/components/widget-component.ts | 2 +- 9 files changed, 19 insertions(+), 17 deletions(-) diff --git a/@types/globals.d.ts b/@types/globals.d.ts index ec88be1fea..d727b0de5b 100644 --- a/@types/globals.d.ts +++ b/@types/globals.d.ts @@ -97,3 +97,5 @@ declare type Getter = () => any; declare type Setter = (value: any) => void; declare const Buffer: any; + +declare type EnumAlias = EnumT[keyof EnumT]; diff --git a/cocos/audio/assets/clip.ts b/cocos/audio/assets/clip.ts index f069009d93..1370be51b1 100644 --- a/cocos/audio/assets/clip.ts +++ b/cocos/audio/assets/clip.ts @@ -132,8 +132,8 @@ export class AudioClip extends Asset { } export namespace AudioClip { - export type PlayingState = typeof PlayingState; - export type AudioType = typeof AudioType; + export type PlayingState = EnumAlias; + export type AudioType = EnumAlias; } cc.AudioClip = AudioClip; diff --git a/cocos/core/3d/framework/camera-component.ts b/cocos/core/3d/framework/camera-component.ts index 11d4f22213..532ed4df89 100644 --- a/cocos/core/3d/framework/camera-component.ts +++ b/cocos/core/3d/framework/camera-component.ts @@ -651,10 +651,10 @@ export class CameraComponent extends Component { } export namespace CameraComponent { - export type ProjectionType = typeof ProjectionType; - export type FOVAxis = typeof FOVAxis; - export type ClearFlag = typeof ClearFlag; - export type Aperture = typeof Aperture; - export type Shutter = typeof Shutter; - export type ISO = typeof ISO; + export type ProjectionType = EnumAlias; + export type FOVAxis = EnumAlias; + export type ClearFlag = EnumAlias; + export type Aperture = EnumAlias; + export type Shutter = EnumAlias; + export type ISO = EnumAlias; } diff --git a/cocos/core/3d/framework/light-component.ts b/cocos/core/3d/framework/light-component.ts index 3c41975f9e..6ff416ca78 100644 --- a/cocos/core/3d/framework/light-component.ts +++ b/cocos/core/3d/framework/light-component.ts @@ -227,6 +227,6 @@ export class LightComponent extends Component { } export namespace LightComponent { - export type Type = typeof LightType; - export type PhotometricTerm = typeof PhotometricTerm; + export type Type = EnumAlias; + export type PhotometricTerm = EnumAlias; } diff --git a/cocos/core/3d/framework/model-component.ts b/cocos/core/3d/framework/model-component.ts index c10b1ae8c7..deedb858d0 100644 --- a/cocos/core/3d/framework/model-component.ts +++ b/cocos/core/3d/framework/model-component.ts @@ -466,5 +466,5 @@ export class ModelComponent extends RenderableComponent { } export namespace ModelComponent { - export type ShadowCastingMode = typeof ModelShadowCastingMode; + export type ShadowCastingMode = EnumAlias; } diff --git a/cocos/core/animation/animation-clip.ts b/cocos/core/animation/animation-clip.ts index 14b013b24f..d6b2ca52a1 100644 --- a/cocos/core/animation/animation-clip.ts +++ b/cocos/core/animation/animation-clip.ts @@ -395,7 +395,7 @@ export class AnimationClip extends Asset { } export namespace AnimationClip { - export type WrapMode = typeof AnimationWrapMode; + export type WrapMode = EnumAlias; } cc.AnimationClip = AnimationClip; diff --git a/cocos/core/animation/animation-component.ts b/cocos/core/animation/animation-component.ts index 179f2f7ab7..9cc4b3790d 100644 --- a/cocos/core/animation/animation-component.ts +++ b/cocos/core/animation/animation-component.ts @@ -505,7 +505,7 @@ export class AnimationComponent extends Eventify(Component) { } export namespace AnimationComponent { - export type EventType = typeof EventType; + export type EventType = EnumAlias; } cc.AnimationComponent = AnimationComponent; diff --git a/cocos/core/assets/texture-base.ts b/cocos/core/assets/texture-base.ts index 8e0d2c8d37..75b511485c 100644 --- a/cocos/core/assets/texture-base.ts +++ b/cocos/core/assets/texture-base.ts @@ -327,9 +327,9 @@ export class TextureBase extends Asset { } export namespace TextureBase { - export type PixelFormat = typeof PixelFormat; - export type WrapMode = typeof WrapMode; - export type Filter = typeof Filter; + export type PixelFormat = EnumAlias; + export type WrapMode = EnumAlias; + export type Filter = EnumAlias; } cc.TextureBase = TextureBase; diff --git a/cocos/ui/components/widget-component.ts b/cocos/ui/components/widget-component.ts index 9c0c70e44d..4e124b693b 100644 --- a/cocos/ui/components/widget-component.ts +++ b/cocos/ui/components/widget-component.ts @@ -1079,7 +1079,7 @@ export class WidgetComponent extends Component { } export namespace WidgetComponent { - export type AlignMode = typeof AlignMode; + export type AlignMode = EnumAlias; } // @ts-ignore From 569e8fdf702a13f446a823455dc645498c6a5a74 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Wed, 27 May 2020 14:05:10 +0800 Subject: [PATCH 40/74] instanced buffer: explicit stride check (#6757) --- cocos/core/pipeline/instanced-buffer.ts | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) diff --git a/cocos/core/pipeline/instanced-buffer.ts b/cocos/core/pipeline/instanced-buffer.ts index 9548f9f53f..d371a5ffcc 100644 --- a/cocos/core/pipeline/instanced-buffer.ts +++ b/cocos/core/pipeline/instanced-buffer.ts @@ -15,6 +15,7 @@ export interface IInstancedItem { vb: GFXBuffer; data: Uint8Array; ia: GFXInputAssembler; + stride: number; } const INITIAL_CAPACITY = 32; @@ -45,15 +46,19 @@ export class InstancedBuffer { for (let i = 0; i < this.instances.length; ++i) { const instance = this.instances[i]; if (instance.ia.indexBuffer !== sourceIA.indexBuffer || instance.count >= MAX_CAPACITY) { continue; } + if (instance.stride !== stride) { + console.error(`instanced buffer stride mismatch! ${stride}/${instance.stride}`); + return; + } if (instance.count >= instance.capacity) { // resize buffers instance.capacity <<= 1; - const newSize = stride * instance.capacity; + const newSize = instance.stride * instance.capacity; const oldData = instance.data; instance.data = new Uint8Array(newSize); instance.data.set(oldData); instance.vb.resize(newSize); } - instance.data.set(attrs.buffer, stride * instance.count++); + instance.data.set(attrs.buffer, instance.stride * instance.count++); return; } @@ -85,7 +90,7 @@ export class InstancedBuffer { vertexBuffers.push(vb); const ia = device.createInputAssembler({ attributes, vertexBuffers, indexBuffer }); - this.instances.push({ count: 1, capacity: INITIAL_CAPACITY, vb, data, ia }); + this.instances.push({ count: 1, capacity: INITIAL_CAPACITY, vb, data, ia, stride }); } public uploadBuffers () { From 4bed4fb6d18ce2eeadd6b4d8c3bce0c8cf29ac10 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Wed, 27 May 2020 14:48:35 +0800 Subject: [PATCH 41/74] fix quat.slerp (#6760) --- cocos/core/math/quat.ts | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/cocos/core/math/quat.ts b/cocos/core/math/quat.ts index e24e2693e9..17515699c9 100644 --- a/cocos/core/math/quat.ts +++ b/cocos/core/math/quat.ts @@ -289,16 +289,20 @@ export class Quat extends ValueType { let scale0 = 0; let scale1 = 0; + let bx = b.x; + let by = b.y; + let bz = b.z; + let bw = b.w; // calc cosine let cosom = a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; // adjust signs (if necessary) if (cosom < 0.0) { cosom = -cosom; - b.x = -b.x; - b.y = -b.y; - b.z = -b.z; - b.w = -b.w; + bx = -bx; + by = -by; + bz = -bz; + bw = -bw; } // calculate coefficients if ((1.0 - cosom) > 0.000001) { @@ -314,10 +318,10 @@ export class Quat extends ValueType { scale1 = t; } // calculate final values - out.x = scale0 * a.x + scale1 * b.x; - out.y = scale0 * a.y + scale1 * b.y; - out.z = scale0 * a.z + scale1 * b.z; - out.w = scale0 * a.w + scale1 * b.w; + out.x = scale0 * a.x + scale1 * bx; + out.y = scale0 * a.y + scale1 * by; + out.z = scale0 * a.z + scale1 * bz; + out.w = scale0 * a.w + scale1 * bw; return out; } From 6df0bb538859aea46aca3eb016b5d12d4af4b28b Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Wed, 27 May 2020 15:19:37 +0800 Subject: [PATCH 42/74] instance buffer: skip empty buffers (#6761) --- cocos/core/math/quat.ts | 20 ++++++++++++-------- cocos/core/pipeline/instanced-buffer.ts | 5 +++-- 2 files changed, 15 insertions(+), 10 deletions(-) diff --git a/cocos/core/math/quat.ts b/cocos/core/math/quat.ts index 17515699c9..8cedba78ce 100644 --- a/cocos/core/math/quat.ts +++ b/cocos/core/math/quat.ts @@ -731,16 +731,20 @@ export class Quat extends ValueType { public lerp (to: Quat, ratio: number) { let scale0 = 0; let scale1 = 0; + let bx = to.x; + let by = to.y; + let bz = to.z; + let bw = to.w; // calc cosine let cosom = this.x * to.x + this.y * to.y + this.z * to.z + this.w * to.w; // adjust signs (if necessary) if (cosom < 0.0) { cosom = -cosom; - to.x = -to.x; - to.y = -to.y; - to.z = -to.z; - to.w = -to.w; + bx = -bx; + by = -by; + bz = -bz; + bw = -bw; } // calculate coefficients if ((1.0 - cosom) > 0.000001) { @@ -756,10 +760,10 @@ export class Quat extends ValueType { scale1 = ratio; } // calculate final values - this.x = scale0 * this.x + scale1 * to.x; - this.y = scale0 * this.y + scale1 * to.y; - this.z = scale0 * this.z + scale1 * to.z; - this.w = scale0 * this.w + scale1 * to.w; + this.x = scale0 * this.x + scale1 * bx; + this.y = scale0 * this.y + scale1 * by; + this.z = scale0 * this.z + scale1 * bz; + this.w = scale0 * this.w + scale1 * bw; return this; } diff --git a/cocos/core/pipeline/instanced-buffer.ts b/cocos/core/pipeline/instanced-buffer.ts index d371a5ffcc..416b92c1e1 100644 --- a/cocos/core/pipeline/instanced-buffer.ts +++ b/cocos/core/pipeline/instanced-buffer.ts @@ -40,14 +40,15 @@ export class InstancedBuffer { } public merge (subModel: SubModel, attrs: IInstancedAttributeBlock, pso: GFXPipelineState) { - if (!this.pso) { this.pso = pso; } const stride = attrs.buffer.length; + if (!stride) { return; } // we assume per-instance attributes are always present + if (!this.pso) { this.pso = pso; } const sourceIA = subModel.inputAssembler!; for (let i = 0; i < this.instances.length; ++i) { const instance = this.instances[i]; if (instance.ia.indexBuffer !== sourceIA.indexBuffer || instance.count >= MAX_CAPACITY) { continue; } if (instance.stride !== stride) { - console.error(`instanced buffer stride mismatch! ${stride}/${instance.stride}`); + // console.error(`instanced buffer stride mismatch! ${stride}/${instance.stride}`); return; } if (instance.count >= instance.capacity) { // resize buffers From 21e2712bf4e99af81a5e5c152e775919d1e6bc88 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Wed, 27 May 2020 16:23:22 +0800 Subject: [PATCH 43/74] Add animation component event unit test (#6750) * Add animation component event unit test * CI --- tests/animation/animation-events.test.ts | 101 ++++++++++++++++++++++- 1 file changed, 99 insertions(+), 2 deletions(-) diff --git a/tests/animation/animation-events.test.ts b/tests/animation/animation-events.test.ts index 14014ac427..31d07a536c 100644 --- a/tests/animation/animation-events.test.ts +++ b/tests/animation/animation-events.test.ts @@ -1,8 +1,105 @@ -import { Node, AnimationComponent, director, AnimationClip, math } from '../../cocos/core'; - +import { Node, AnimationComponent, director, AnimationClip, math, AnimationState } from '../../cocos/core'; test('Animation events(general)', () => { + jest.spyOn((global as any).cc.director, 'getAnimationManager').mockImplementation(() => { + return { + addAnimation: () => { }, + removeAnimation: () => { }, + addCrossFade: () => { }, + removeCrossFade: () => { }, + pushDelayEvent: (target: Node, func: string, args: any[]) => { + target[func].apply(target, args); + }, + }; + }); + const clip = new AnimationClip('default'); + clip.duration = 2.0; + const node = new Node(); + const animationComponent = node.addComponent(AnimationComponent); + animationComponent.defaultClip = clip; + const state = animationComponent.getState(clip.name); + + const testMagic = (() => { + const bitMaskMap: Record = { + [AnimationComponent.EventType.PLAY]: 1 << 1, + [AnimationComponent.EventType.RESUME]: 1 << 2, + [AnimationComponent.EventType.PAUSE]: 1 << 3, + [AnimationComponent.EventType.STOP]: 1 << 4, + [AnimationComponent.EventType.LASTFRAME]: 1 << 5, + [AnimationComponent.EventType.FINISHED]: 1 << 6, + }; + let actual = 0; + return { + makeMockFunction(eventType: AnimationComponent.EventType) { + const mask = bitMaskMap[eventType]; + return jest.fn(() => { + actual |= mask; + }); + }, + + clear() { + actual = 0; + }, + + expectAndClear(eventTypes: AnimationComponent.EventType | AnimationComponent.EventType[]) { + let expected = 0; + if (Array.isArray(eventTypes)) { + for (const eventType of eventTypes) { + expected |= bitMaskMap[eventType]; + } + } else { + expected |= bitMaskMap[eventTypes] + } + expect(expected === actual).toBeTruthy(); + this.clear(); + }, + }; + })(); + + [ + AnimationComponent.EventType.PLAY, + AnimationComponent.EventType.RESUME, + AnimationComponent.EventType.PAUSE, + AnimationComponent.EventType.STOP, + AnimationComponent.EventType.LASTFRAME, + AnimationComponent.EventType.FINISHED, + ].forEach((eventType) => { + animationComponent.on(eventType, testMagic.makeMockFunction(eventType)); + }); + + animationComponent.play(); + testMagic.expectAndClear(AnimationComponent.EventType.PLAY); + + animationComponent.pause(); + testMagic.expectAndClear(AnimationComponent.EventType.PAUSE); + + animationComponent.resume(); + testMagic.expectAndClear(AnimationComponent.EventType.RESUME); + + animationComponent.stop(); + testMagic.expectAndClear(AnimationComponent.EventType.STOP); + + // Naturally end-of-life should trigger finished event + // and stopped. + animationComponent.play(); + state.update(0); + testMagic.clear(); + state.update(clip.duration); + testMagic.expectAndClear([ + AnimationComponent.EventType.FINISHED, + AnimationComponent.EventType.STOP, + ]); + + // But in loop mode they won't be triggered. + // Instead, the last frame event should be triggered. + state.wrapMode = AnimationClip.WrapMode.Loop; + animationComponent.play(); + state.update(0); + state.update(clip.duration / 2); + testMagic.clear(); + state.update(clip.duration / 2 + clip.duration / 4); + testMagic.expectAndClear(AnimationComponent.EventType.LASTFRAME); }); test('Animation event(last-frame event optimization)', () => { From c16393974fe094b86bf7be1c8c1bcb20fcd49aee Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Wed, 27 May 2020 17:47:57 +0800 Subject: [PATCH 44/74] quat.prototype.slerp (#6764) --- .../animation/skeletal-animation-data-hub.ts | 26 ++++++++----- .../animation/skeletal-animation-state.ts | 7 ++-- cocos/core/math/deprecated.ts | 4 +- cocos/core/math/quat.ts | 39 ++++++++++++------- cocos/core/pipeline/render-instanced-queue.ts | 18 +++++---- 5 files changed, 57 insertions(+), 37 deletions(-) diff --git a/cocos/core/animation/skeletal-animation-data-hub.ts b/cocos/core/animation/skeletal-animation-data-hub.ts index d4319b06aa..d40edb9a5b 100644 --- a/cocos/core/animation/skeletal-animation-data-hub.ts +++ b/cocos/core/animation/skeletal-animation-data-hub.ts @@ -32,12 +32,12 @@ import { DataPoolManager } from '../renderer/data-pool-manager'; import { AnimationClip, IObjectCurveData } from './animation-clip'; import { HierarchyPath, isCustomPath, isPropertyPath } from './target-path'; -type CurveData = Vec3 | Quat | Mat4; +type CurveData = Vec3[] | Quat[] | Mat4[]; type ConvertedProps = Record; interface IPropertyCurve { keys: number; - values: CurveData[]; + values: CurveData; } interface ISkeletalCurveInfo { frames: number; @@ -114,20 +114,26 @@ function convertToSkeletalCurves (clip: AnimationClip): IConvertedData { function convertToUniformSample (clip: AnimationClip, curve: IPropertyCurve, frames: number) { const keys = clip.keys[curve.keys]; - const values: CurveData[] = []; + const values: CurveData = []; if (!keys || keys.length === 1) { for (let i = 0; i < frames; i++) { values[i] = curve.values[0].clone(); // never forget to clone } } else { + const isQuat = curve.values[0] instanceof Quat; for (let i = 0, idx = 0; i < frames; i++) { - let time = i / clip.sample; - while (keys[idx] <= time) { idx++; } - if (idx > keys.length - 1) { idx = keys.length - 1; time = keys[idx]; } - else if (idx === 0) { idx = 1; } - const from = curve.values[idx - 1].clone() as any; - from.lerp(curve.values[idx], clamp01((time - keys[idx - 1]) / (keys[idx] - keys[idx - 1]))); - values[i] = from; + let time = i / clip.sample; + while (keys[idx] <= time) { idx++; } + if (idx > keys.length - 1) { idx = keys.length - 1; time = keys[idx]; } + else if (idx === 0) { idx = 1; } + const from = curve.values[idx - 1].clone(); + const ratio = clamp01((time - keys[idx - 1]) / (keys[idx] - keys[idx - 1])); + if (isQuat) { + (from as Quat).slerp(curve.values[idx] as Quat, ratio); + } else { + (from as Vec3).lerp(curve.values[idx] as Vec3, ratio); + } + values[i] = from; } } curve.values = values; diff --git a/cocos/core/animation/skeletal-animation-state.ts b/cocos/core/animation/skeletal-animation-state.ts index 6bba178477..e3e85bbc4e 100644 --- a/cocos/core/animation/skeletal-animation-state.ts +++ b/cocos/core/animation/skeletal-animation-state.ts @@ -131,16 +131,15 @@ export class SkeletalAnimationState extends AnimationState { if (idx < 0) { break; } } // create animation data + const frames = source.worldMatrix.values as Mat4[]; const socketData: ISocketData = { target: socket.target, - frames: source.worldMatrix.values.map(() => ({ pos: new Vec3(), rot: new Quat(), scale: new Vec3() })), + frames: frames.map(() => ({ pos: new Vec3(), rot: new Quat(), scale: new Vec3() })), }; - const frames = source.worldMatrix.values as Mat4[]; - const data = socketData.frames; // apply downstream default pose getWorldTransformUntilRoot(targetNode!, animNode, m4_1); for (let j = 0; j < socketData.frames.length; j++) { - const m = frames[j]; const dst = data[j]; + const m = frames[j]; const dst = socketData.frames[j]; Mat4.toRTS(Mat4.multiply(m4_2, m, m4_1), dst.rot, dst.pos, dst.scale); } this._sockets.push(socketData); diff --git a/cocos/core/math/deprecated.ts b/cocos/core/math/deprecated.ts index b1db27e6d9..4cdbd4e931 100644 --- a/cocos/core/math/deprecated.ts +++ b/cocos/core/math/deprecated.ts @@ -360,8 +360,8 @@ replaceProperty(Color, 'Color', [ { name: 'fromHex', newName: 'fromHEX', - customFunction: function (...args: any) { - let arg1 = args[1].toString(16); + customFunction (...args: any) { + const arg1 = args[1].toString(16); return cc.Color.fromHEX(args[0], arg1); }, }, diff --git a/cocos/core/math/quat.ts b/cocos/core/math/quat.ts index 8cedba78ce..3f70d6c4d5 100644 --- a/cocos/core/math/quat.ts +++ b/cocos/core/math/quat.ts @@ -724,27 +724,40 @@ export class Quat extends ValueType { } /** - * @zh 根据指定的插值比率,从当前四元数到目标四元数之间做插值。 + * @zh 根据指定的插值比率,从当前四元数到目标四元数之间做线性插值。 * @param to 目标四元数。 * @param ratio 插值比率,范围为 [0,1]。 */ public lerp (to: Quat, ratio: number) { + this.x = this.x + ratio * (to.x - this.x); + this.y = this.y + ratio * (to.y - this.y); + this.z = this.z + ratio * (to.z - this.z); + this.w = this.w + ratio * (to.w - this.w); + return this; + } + + /** + * @zh 根据指定的插值比率,从当前四元数到目标四元数之间做球面插值。 + * @param to 目标四元数。 + * @param ratio 插值比率,范围为 [0,1]。 + */ + public slerp (to: Quat, ratio: number) { let scale0 = 0; let scale1 = 0; - let bx = to.x; - let by = to.y; - let bz = to.z; - let bw = to.w; + let tox = to.x; + let toy = to.y; + let toz = to.z; + let tow = to.w; // calc cosine let cosom = this.x * to.x + this.y * to.y + this.z * to.z + this.w * to.w; // adjust signs (if necessary) if (cosom < 0.0) { cosom = -cosom; - bx = -bx; - by = -by; - bz = -bz; - bw = -bw; + tox = -tox; + toy = -toy; + toz = -toz; + tow = -tow; } // calculate coefficients if ((1.0 - cosom) > 0.000001) { @@ -760,10 +773,10 @@ export class Quat extends ValueType { scale1 = ratio; } // calculate final values - this.x = scale0 * this.x + scale1 * bx; - this.y = scale0 * this.y + scale1 * by; - this.z = scale0 * this.z + scale1 * bz; - this.w = scale0 * this.w + scale1 * bw; + this.x = scale0 * this.x + scale1 * tox; + this.y = scale0 * this.y + scale1 * toy; + this.z = scale0 * this.z + scale1 * toz; + this.w = scale0 * this.w + scale1 * tow; return this; } diff --git a/cocos/core/pipeline/render-instanced-queue.ts b/cocos/core/pipeline/render-instanced-queue.ts index f829d2fcb4..f314e3a984 100644 --- a/cocos/core/pipeline/render-instanced-queue.ts +++ b/cocos/core/pipeline/render-instanced-queue.ts @@ -45,14 +45,16 @@ export class RenderInstancedQueue { const it = this.queue.values(); let res = it.next(); while (!res.done) { const { instances, pso } = res.value; - res.value.uploadBuffers(); - cmdBuff.bindPipelineState(pso!); - cmdBuff.bindBindingLayout(pso!.pipelineLayout.layouts[0]); - for (let b = 0; b < instances.length; ++b) { - const instance = instances[b]; - if (!instance.count) { continue; } - cmdBuff.bindInputAssembler(instance.ia); - cmdBuff.draw(instance.ia); + if (pso) { + res.value.uploadBuffers(); + cmdBuff.bindPipelineState(pso); + cmdBuff.bindBindingLayout(pso.pipelineLayout.layouts[0]); + for (let b = 0; b < instances.length; ++b) { + const instance = instances[b]; + if (!instance.count) { continue; } + cmdBuff.bindInputAssembler(instance.ia); + cmdBuff.draw(instance.ia); + } } res = it.next(); } From 462944865913ec2790867e388070dec524c670b2 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Wed, 27 May 2020 18:34:54 +0800 Subject: [PATCH 45/74] skeletal animation: handle duplicated keys (#6769) --- .../animation/skeletal-animation-data-hub.ts | 3 +- cocos/core/math/quat.ts | 38 +------------------ 2 files changed, 3 insertions(+), 38 deletions(-) diff --git a/cocos/core/animation/skeletal-animation-data-hub.ts b/cocos/core/animation/skeletal-animation-data-hub.ts index d40edb9a5b..85f7245278 100644 --- a/cocos/core/animation/skeletal-animation-data-hub.ts +++ b/cocos/core/animation/skeletal-animation-data-hub.ts @@ -127,7 +127,8 @@ function convertToUniformSample (clip: AnimationClip, curve: IPropertyCurve, fra if (idx > keys.length - 1) { idx = keys.length - 1; time = keys[idx]; } else if (idx === 0) { idx = 1; } const from = curve.values[idx - 1].clone(); - const ratio = clamp01((time - keys[idx - 1]) / (keys[idx] - keys[idx - 1])); + const denom = keys[idx] - keys[idx - 1]; + const ratio = denom ? clamp01((time - keys[idx - 1]) / denom) : 1; if (isQuat) { (from as Quat).slerp(curve.values[idx] as Quat, ratio); } else { diff --git a/cocos/core/math/quat.ts b/cocos/core/math/quat.ts index 3f70d6c4d5..07fe577f15 100644 --- a/cocos/core/math/quat.ts +++ b/cocos/core/math/quat.ts @@ -742,43 +742,7 @@ export class Quat extends ValueType { * @param ratio 插值比率,范围为 [0,1]。 */ public slerp (to: Quat, ratio: number) { - let scale0 = 0; - let scale1 = 0; - let tox = to.x; - let toy = to.y; - let toz = to.z; - let tow = to.w; - - // calc cosine - let cosom = this.x * to.x + this.y * to.y + this.z * to.z + this.w * to.w; - // adjust signs (if necessary) - if (cosom < 0.0) { - cosom = -cosom; - tox = -tox; - toy = -toy; - toz = -toz; - tow = -tow; - } - // calculate coefficients - if ((1.0 - cosom) > 0.000001) { - // standard case (slerp) - const omega = Math.acos(cosom); - const sinom = Math.sin(omega); - scale0 = Math.sin((1.0 - ratio) * omega) / sinom; - scale1 = Math.sin(ratio * omega) / sinom; - } else { - // "from" and "to" quaternions are very close - // ... so we can do a linear interpolation - scale0 = 1.0 - ratio; - scale1 = ratio; - } - // calculate final values - this.x = scale0 * this.x + scale1 * tox; - this.y = scale0 * this.y + scale1 * toy; - this.z = scale0 * this.z + scale1 * toz; - this.w = scale0 * this.w + scale1 * tow; - - return this; + return Quat.slerp(this, this, to, ratio); } /** From 93802dae26199170dad56912e62c05c9703a0428 Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Thu, 28 May 2020 10:59:22 +0800 Subject: [PATCH 46/74] fixed scale not word (#6770) --- cocos/core/scene-graph/node.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos/core/scene-graph/node.ts b/cocos/core/scene-graph/node.ts index 653c425f31..6ea55170a3 100644 --- a/cocos/core/scene-graph/node.ts +++ b/cocos/core/scene-graph/node.ts @@ -511,7 +511,8 @@ export class Node extends BaseNode { if (dirtyBits & TransformBit.RS) { if (dirtyBits & TransformBit.ROTATION) { Quat.copy(child._rot, child._lrot); - } else { + } + if (dirtyBits & TransformBit.SCALE) { Vec3.copy(child._scale, child._lscale); } Mat4.fromRTS(child._mat, child._rot, child._pos, child._scale); From 48ce4949268d43e293d6a30d5cd3255eead4ca86 Mon Sep 17 00:00:00 2001 From: "jiaxin.lai" Date: Thu, 28 May 2020 13:39:15 +0800 Subject: [PATCH 47/74] physics optimization (#6768) * fix cannon shape center update * add isA to differentiate the contact data * sync optimize * quat typing * fix body sleeping state * remove event after destroy * typing * fix time reset * set mass default to 1 * skipBackFaces by default * tweaks for ammo world step * continue if sleeping * checking before wake up * Annotation specifications * tweaks * rename isA to isBodyA * renaming --- cocos/core/math/quat.ts | 78 ++++++------- cocos/physics/ammo/ammo-const.ts | 1 + cocos/physics/ammo/ammo-rigid-body.ts | 26 ++++- cocos/physics/ammo/ammo-shared-body.ts | 19 +-- cocos/physics/ammo/ammo-world.ts | 18 ++- cocos/physics/cannon/cannon-rigid-body.ts | 109 +++++------------- cocos/physics/cannon/cannon-shared-body.ts | 13 ++- cocos/physics/cannon/cannon-util.ts | 3 +- cocos/physics/cannon/shapes/cannon-shape.ts | 8 +- .../components/collider/collider-component.ts | 42 +++++++ .../components/rigid-body-component.ts | 2 +- cocos/physics/framework/physics-interface.ts | 8 ++ cocos/physics/framework/physics-system.ts | 8 +- cocos/physics/spec/i-physics-world.ts | 2 +- 14 files changed, 183 insertions(+), 154 deletions(-) diff --git a/cocos/core/math/quat.ts b/cocos/core/math/quat.ts index 07fe577f15..2ee6608a59 100644 --- a/cocos/core/math/quat.ts +++ b/cocos/core/math/quat.ts @@ -44,14 +44,14 @@ export class Quat extends ValueType { /** * @zh 获得指定四元数的拷贝 */ - public static clone (a: Out) { + public static clone (a: Out) { return new Quat(a.x, a.y, a.z, a.w); } /** * @zh 复制目标四元数 */ - public static copy (out: Out, a: QuatLike) { + public static copy (out: Out, a: QuatLike) { out.x = a.x; out.y = a.y; out.z = a.z; @@ -62,7 +62,7 @@ export class Quat extends ValueType { /** * @zh 设置四元数值 */ - public static set (out: Out, x: number, y: number, z: number, w: number) { + public static set (out: Out, x: number, y: number, z: number, w: number) { out.x = x; out.y = y; out.z = z; @@ -73,7 +73,7 @@ export class Quat extends ValueType { /** * @zh 将目标赋值为单位四元数 */ - public static identity (out: Out) { + public static identity (out: Out) { out.x = 0; out.y = 0; out.z = 0; @@ -84,7 +84,7 @@ export class Quat extends ValueType { /** * @zh 设置四元数为两向量间的最短路径旋转,默认两向量都已归一化 */ - public static rotationTo (out: Out, a: VecLike, b: VecLike) { + public static rotationTo (out: Out, a: VecLike, b: VecLike) { const dot = Vec3.dot(a, b); if (dot < -0.999999) { Vec3.cross(v3_1, Vec3.UNIT_X, a); @@ -116,7 +116,7 @@ export class Quat extends ValueType { * @param q 源四元数 * @return 旋转弧度 */ - public static getAxisAngle (outAxis: VecLike, q: Out) { + public static getAxisAngle (outAxis: VecLike, q: Out) { const rad = Math.acos(q.w) * 2.0; const s = Math.sin(rad / 2.0); if (s !== 0.0) { @@ -135,7 +135,7 @@ export class Quat extends ValueType { /** * @zh 四元数乘法 */ - public static multiply (out: Out, a: QuatLike_1, b: QuatLike_2) { + public static multiply (out: Out, a: QuatLike_1, b: QuatLike_2) { const x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y; const y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z; const z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x; @@ -150,7 +150,7 @@ export class Quat extends ValueType { /** * @zh 四元数标量乘法 */ - public static multiplyScalar (out: Out, a: Out, b: number) { + public static multiplyScalar (out: Out, a: Out, b: number) { out.x = a.x * b; out.y = a.y * b; out.z = a.z * b; @@ -161,7 +161,7 @@ export class Quat extends ValueType { /** * @zh 四元数乘加:A + B * scale */ - public static scaleAndAdd (out: Out, a: Out, b: Out, scale: number) { + public static scaleAndAdd (out: Out, a: Out, b: Out, scale: number) { out.x = a.x + b.x * scale; out.y = a.y + b.y * scale; out.z = a.z + b.z * scale; @@ -173,7 +173,7 @@ export class Quat extends ValueType { * @zh 绕 X 轴旋转指定四元数 * @param rad 旋转弧度 */ - public static rotateX (out: Out, a: Out, rad: number) { + public static rotateX (out: Out, a: Out, rad: number) { rad *= 0.5; const bx = Math.sin(rad); @@ -191,7 +191,7 @@ export class Quat extends ValueType { * @zh 绕 Y 轴旋转指定四元数 * @param rad 旋转弧度 */ - public static rotateY (out: Out, a: Out, rad: number) { + public static rotateY (out: Out, a: Out, rad: number) { rad *= 0.5; const by = Math.sin(rad); @@ -209,7 +209,7 @@ export class Quat extends ValueType { * @zh 绕 Z 轴旋转指定四元数 * @param rad 旋转弧度 */ - public static rotateZ (out: Out, a: Out, rad: number) { + public static rotateZ (out: Out, a: Out, rad: number) { rad *= 0.5; const bz = Math.sin(rad); @@ -228,7 +228,7 @@ export class Quat extends ValueType { * @param axis 旋转轴,默认已归一化 * @param rad 旋转弧度 */ - public static rotateAround (out: Out, rot: Out, axis: VecLike, rad: number) { + public static rotateAround (out: Out, rot: Out, axis: VecLike, rad: number) { // get inv-axis (local to rot) Quat.invert(qt_1, rot); Vec3.transformQuat(v3_1, axis, qt_1); @@ -243,7 +243,7 @@ export class Quat extends ValueType { * @param axis 旋转轴 * @param rad 旋转弧度 */ - public static rotateAroundLocal (out: Out, rot: Out, axis: VecLike, rad: number) { + public static rotateAroundLocal (out: Out, rot: Out, axis: VecLike, rad: number) { Quat.fromAxisAngle(qt_1, axis, rad); Quat.multiply(out, rot, qt_1); return out; @@ -252,7 +252,7 @@ export class Quat extends ValueType { /** * @zh 根据 xyz 分量计算 w 分量,默认已归一化 */ - public static calculateW (out: Out, a: Out) { + public static calculateW (out: Out, a: Out) { out.x = a.x; out.y = a.y; @@ -264,14 +264,14 @@ export class Quat extends ValueType { /** * @zh 四元数点积(数量积) */ - public static dot (a: Out, b: Out) { + public static dot (a: Out, b: Out) { return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w; } /** * @zh 逐元素线性插值: A + t * (B - A) */ - public static lerp (out: Out, a: Out, b: Out, t: number) { + public static lerp (out: Out, a: Out, b: Out, t: number) { out.x = a.x + t * (b.x - a.x); out.y = a.y + t * (b.y - a.y); out.z = a.z + t * (b.z - a.z); @@ -282,8 +282,8 @@ export class Quat extends ValueType { /** * @zh 四元数球面插值 */ - public static slerp - (out: Out, a: QuatLike_1, b: QuatLike_2, t: number) { + public static slerp + (out: Out, a: QuatLike_1, b: QuatLike_2, t: number) { // benchmarks: // http://jsperf.com/quaternion-slerp-implementations @@ -329,7 +329,7 @@ export class Quat extends ValueType { /** * @zh 带两个控制点的四元数球面插值 */ - public static sqlerp (out: Out, a: Out, b: Out, c: Out, d: Out, t: number) { + public static sqlerp (out: Out, a: Out, b: Out, c: Out, d: Out, t: number) { Quat.slerp(qt_1, a, d, t); Quat.slerp(qt_2, b, c, t); Quat.slerp(out, qt_1, qt_2, 2 * t * (1 - t)); @@ -339,7 +339,7 @@ export class Quat extends ValueType { /** * @zh 四元数求逆 */ - public static invert (out: Out, a: QuatLike) { + public static invert (out: Out, a: QuatLike) { const dot = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w; const invDot = dot ? 1.0 / dot : 0; @@ -355,7 +355,7 @@ export class Quat extends ValueType { /** * @zh 求共轭四元数,对单位四元数与求逆等价,但更高效 */ - public static conjugate (out: Out, a: Out) { + public static conjugate (out: Out, a: Out) { out.x = -a.x; out.y = -a.y; out.z = -a.z; @@ -366,21 +366,21 @@ export class Quat extends ValueType { /** * @zh 求四元数长度 */ - public static len (a: Out) { + public static len (a: Out) { return Math.sqrt(a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w); } /** * @zh 求四元数长度平方 */ - public static lengthSqr (a: Out) { + public static lengthSqr (a: Out) { return a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w; } /** * @zh 归一化四元数 */ - public static normalize (out: Out, a: Out) { + public static normalize (out: Out, a: Out) { let len = a.x * a.x + a.y * a.y + a.z * a.z + a.w * a.w; if (len > 0) { len = 1 / Math.sqrt(len); @@ -395,7 +395,7 @@ export class Quat extends ValueType { /** * @zh 根据本地坐标轴朝向计算四元数,默认三向量都已归一化且相互垂直 */ - public static fromAxes (out: Out, xAxis: VecLike, yAxis: VecLike, zAxis: VecLike) { + public static fromAxes (out: Out, xAxis: VecLike, yAxis: VecLike, zAxis: VecLike) { Mat3.set(m3_1, xAxis.x, xAxis.y, xAxis.z, yAxis.x, yAxis.y, yAxis.z, @@ -409,7 +409,7 @@ export class Quat extends ValueType { * @param view 视口面向的前方向,必须归一化 * @param up 视口的上方向,必须归一化,默认为 (0, 1, 0) */ - public static fromViewUp (out: Out, view: VecLike, up?: Vec3) { + public static fromViewUp (out: Out, view: VecLike, up?: Vec3) { Mat3.fromViewUp(m3_1, view, up); return Quat.normalize(out, Quat.fromMat3(out, m3_1)); } @@ -417,7 +417,7 @@ export class Quat extends ValueType { /** * @zh 根据旋转轴和旋转弧度计算四元数 */ - public static fromAxisAngle (out: Out, axis: VecLike, rad: number) { + public static fromAxisAngle (out: Out, axis: VecLike, rad: number) { rad = rad * 0.5; const s = Math.sin(rad); out.x = s * axis.x; @@ -430,7 +430,7 @@ export class Quat extends ValueType { /** * @zh 根据三维矩阵信息计算四元数,默认输入矩阵不含有缩放信息 */ - public static fromMat3 (out: Out, m: Mat3) { + public static fromMat3 (out: Out, m: Mat3) { const { m00: m00, m03: m01, m06: m02, m01: m10, m04: m11, m07: m12, @@ -478,7 +478,7 @@ export class Quat extends ValueType { /** * @zh 根据欧拉角信息计算四元数,旋转顺序为 YZX */ - public static fromEuler (out: Out, x: number, y: number, z: number) { + public static fromEuler (out: Out, x: number, y: number, z: number) { x *= halfToRad; y *= halfToRad; z *= halfToRad; @@ -501,7 +501,7 @@ export class Quat extends ValueType { /** * @zh 返回定义此四元数的坐标系 X 轴向量 */ - public static toAxisX (out: VecLike, q: Out) { + public static toAxisX (out: IVec3Like, q: IQuatLike) { const fy = 2.0 * q.y; const fz = 2.0 * q.z; out.x = 1.0 - fy * q.y - fz * q.z; @@ -514,7 +514,7 @@ export class Quat extends ValueType { /** * @zh 返回定义此四元数的坐标系 Y 轴向量 */ - public static toAxisY (out: VecLike, q: Out) { + public static toAxisY (out: IVec3Like, q: IQuatLike) { const fx = 2.0 * q.x; const fy = 2.0 * q.y; const fz = 2.0 * q.z; @@ -528,7 +528,7 @@ export class Quat extends ValueType { /** * @zh 返回定义此四元数的坐标系 Z 轴向量 */ - public static toAxisZ (out: VecLike, q: Out) { + public static toAxisZ (out: IVec3Like, q: IQuatLike) { const fx = 2.0 * q.x; const fy = 2.0 * q.y; const fz = 2.0 * q.z; @@ -543,7 +543,7 @@ export class Quat extends ValueType { * @zh 根据四元数计算欧拉角,返回角度 x, y 在 [-180, 180] 区间内, z 默认在 [-90, 90] 区间内,旋转顺序为 YZX * @param outerZ z 取值范围区间改为 [-180, -90] U [90, 180] */ - public static toEuler (out: Out, q: IQuatLike, outerZ?: boolean) { + public static toEuler (out: IVec3Like, q: IQuatLike, outerZ?: boolean) { const { x, y, z, w } = q; let bank = 0; let heading = 0; @@ -578,7 +578,7 @@ export class Quat extends ValueType { * @zh 四元数转数组 * @param ofs 数组内的起始偏移量 */ - public static toArray > (out: Out, q: IQuatLike, ofs = 0) { + public static toArray> (out: Out, q: IQuatLike, ofs = 0) { out[ofs + 0] = q.x; out[ofs + 1] = q.y; out[ofs + 2] = q.z; @@ -590,7 +590,7 @@ export class Quat extends ValueType { * @zh 数组转四元数 * @param ofs 数组起始偏移量 */ - public static fromArray (out: Out, arr: IWritableArrayLike, ofs = 0) { + public static fromArray (out: IQuatLike, arr: IWritableArrayLike, ofs = 0) { out.x = arr[ofs + 0]; out.y = arr[ofs + 1]; out.z = arr[ofs + 2]; @@ -601,14 +601,14 @@ export class Quat extends ValueType { /** * @zh 四元数等价判断 */ - public static strictEquals (a: Out, b: Out) { + public static strictEquals (a: IQuatLike, b: IQuatLike) { return a.x === b.x && a.y === b.y && a.z === b.z && a.w === b.w; } /** * @zh 排除浮点数误差的四元数近似等价判断 */ - public static equals (a: Out, b: Out, epsilon = EPSILON) { + public static equals (a: IQuatLike, b: IQuatLike, epsilon = EPSILON) { return (Math.abs(a.x - b.x) <= epsilon * Math.max(1.0, Math.abs(a.x), Math.abs(b.x)) && Math.abs(a.y - b.y) <= epsilon * Math.max(1.0, Math.abs(a.y), Math.abs(b.y)) && Math.abs(a.z - b.z) <= epsilon * Math.max(1.0, Math.abs(a.z), Math.abs(b.z)) && @@ -639,7 +639,7 @@ export class Quat extends ValueType { constructor (x?: number, y?: number, z?: number, w?: number); - constructor (x?: number | Quat, y?: number, z?: number, w?: number) { + constructor (x?: number | IQuatLike, y?: number, z?: number, w?: number) { super(); if (x && typeof x === 'object') { this.x = x.x; diff --git a/cocos/physics/ammo/ammo-const.ts b/cocos/physics/ammo/ammo-const.ts index 6436c6ea6f..b0d55852d2 100644 --- a/cocos/physics/ammo/ammo-const.ts +++ b/cocos/physics/ammo/ammo-const.ts @@ -12,6 +12,7 @@ export const CollisionEventObject = { selfCollider: null as unknown as ColliderComponent, otherCollider: null as unknown as ColliderComponent, contacts: [] as IContactEquation[], + isBodyA: false, }; export class AmmoConstant { diff --git a/cocos/physics/ammo/ammo-rigid-body.ts b/cocos/physics/ammo/ammo-rigid-body.ts index 9496d6c517..c6f35205c7 100644 --- a/cocos/physics/ammo/ammo-rigid-body.ts +++ b/cocos/physics/ammo/ammo-rigid-body.ts @@ -74,30 +74,30 @@ export class AmmoRigidBody implements IRigidBody { fixRotation (value: boolean) { if (value) { /** TODO : should i reset angular velocity & torque ? */ - this.impl.setAngularFactor(cocos2AmmoVec3(this._btVec3_0, Vec3.ZERO)); } else { this.impl.setAngularFactor(cocos2AmmoVec3(this._btVec3_0, this._rigidBody.angularFactor)); } + if (this.isSleeping) this.impl.activate(); } setLinearFactor (value: IVec3Like) { this.impl.setLinearFactor(cocos2AmmoVec3(this._btVec3_0, value)); + if (this.isSleeping) this.impl.activate(); } setAngularFactor (value: IVec3Like) { this.impl.setAngularFactor(cocos2AmmoVec3(this._btVec3_0, value)); + if (this.isSleeping) this.impl.activate(); } setAllowSleep (v: boolean) { if (v) { - const state = this.impl.getActivationState(); - if (state == AmmoCollisionObjectStates.DISABLE_DEACTIVATION) { - this.impl.setActivationState(AmmoCollisionObjectStates.ACTIVE_TAG); - } + this.impl.forceActivationState(AmmoCollisionObjectStates.ACTIVE_TAG); } else { - this.impl.setActivationState(AmmoCollisionObjectStates.DISABLE_DEACTIVATION); + this.impl.forceActivationState(AmmoCollisionObjectStates.DISABLE_DEACTIVATION); } + if (this.isSleeping) this.impl.activate(); } get isEnabled () { return this._isEnabled; } @@ -183,6 +183,7 @@ export class AmmoRigidBody implements IRigidBody { } setLinearVelocity (value: Vec3): void { + if (this.isSleeping) this.impl.activate(); cocos2AmmoVec3(this.impl.getLinearVelocity(), value); } @@ -191,12 +192,15 @@ export class AmmoRigidBody implements IRigidBody { } setAngularVelocity (value: Vec3): void { + if (this.isSleeping) this.impl.activate(); cocos2AmmoVec3(this.impl.getAngularVelocity(), value); } /** dynamic */ applyLocalForce (force: Vec3, rel_pos?: Vec3): void { + this._sharedBody.syncSceneToPhysics(); + if (this.isSleeping) this.impl.activate(); const quat = this._sharedBody.node.worldRotation; const v = Vec3.transformQuat(v3_0, force, quat); const rp = rel_pos ? Vec3.transformQuat(v3_1, rel_pos, quat) : Vec3.ZERO; @@ -207,11 +211,15 @@ export class AmmoRigidBody implements IRigidBody { } applyLocalTorque (torque: Vec3): void { + this._sharedBody.syncSceneToPhysics(); + if (this.isSleeping) this.impl.activate(); Vec3.transformQuat(v3_0, torque, this._sharedBody.node.worldRotation); this.impl.applyTorque(cocos2AmmoVec3(this._btVec3_0, v3_0)); } applyLocalImpulse (impulse: Vec3, rel_pos?: Vec3): void { + this._sharedBody.syncSceneToPhysics(); + if (this.isSleeping) this.impl.activate(); const quat = this._sharedBody.node.worldRotation; const v = Vec3.transformQuat(v3_0, impulse, quat); const rp = rel_pos ? Vec3.transformQuat(v3_1, rel_pos, quat) : Vec3.ZERO; @@ -222,6 +230,8 @@ export class AmmoRigidBody implements IRigidBody { } applyForce (force: Vec3, rel_pos?: Vec3): void { + this._sharedBody.syncSceneToPhysics(); + if (this.isSleeping) this.impl.activate(); const rp = rel_pos ? rel_pos : Vec3.ZERO; this.impl.applyForce( cocos2AmmoVec3(this._btVec3_0, force), @@ -230,10 +240,14 @@ export class AmmoRigidBody implements IRigidBody { } applyTorque (torque: Vec3): void { + this._sharedBody.syncSceneToPhysics(); + if (this.isSleeping) this.impl.activate(); this.impl.applyTorque(cocos2AmmoVec3(this._btVec3_0, torque)); } applyImpulse (impulse: Vec3, rel_pos?: Vec3): void { + this._sharedBody.syncSceneToPhysics(); + if (this.isSleeping) this.impl.activate(); const rp = rel_pos ? rel_pos : Vec3.ZERO; this.impl.applyImpulse( cocos2AmmoVec3(this._btVec3_0, impulse), diff --git a/cocos/physics/ammo/ammo-shared-body.ts b/cocos/physics/ammo/ammo-shared-body.ts index 94e85a2ce5..34cefcc982 100644 --- a/cocos/physics/ammo/ammo-shared-body.ts +++ b/cocos/physics/ammo/ammo-shared-body.ts @@ -233,7 +233,7 @@ export class AmmoSharedBody { cocos2AmmoVec3(wt.getOrigin(), this.node.worldPosition) cocos2AmmoQuat(this.bodyStruct.worldQuat, this.node.worldRotation); wt.setRotation(this.bodyStruct.worldQuat); - this.body.activate(); + if (this.isBodySleeping()) this.body.activate(); if (this.node.hasChangedFlags & TransformBit.SCALE) { for (let i = 0; i < this.bodyStruct.wrappedShapes.length; i++) { @@ -247,7 +247,7 @@ export class AmmoSharedBody { * TODO: use motion state */ syncPhysicsToScene () { - if (this.body.isStaticObject() || !this.body.isActive()) { + if (this.body.isStaticObject() || this.isBodySleeping()) { return; } @@ -302,17 +302,6 @@ export class AmmoSharedBody { this.ghost.activate(); } - // private updateGroupMask () { - // const body = this.bodyStruct.body; - // const bodyProxy = body.getBroadphaseHandle(); - // bodyProxy.m_collisionFilterGroup = this.collisionFilterGroup; - // bodyProxy.m_collisionFilterMask = this.collisionFilterMask; - // const ghost = this.ghostStruct.ghost; - // const ghostProxy = ghost.getBroadphaseHandle(); - // ghostProxy.m_collisionFilterGroup = this.collisionFilterGroup; - // ghostProxy.m_collisionFilterMask = this.collisionFilterMask; - // } - updateByReAdd () { /** * see: https://pybullet.org/Bullet/phpBB3/viewtopic.php?f=9&t=5312&p=19094&hilit=how+to+change+group+mask#p19097 @@ -367,4 +356,8 @@ export class AmmoSharedBody { (this.ghostStruct as any) = null; } + private isBodySleeping () { + const state = this.body.getActivationState(); + return state == AmmoCollisionObjectStates.ISLAND_SLEEPING; + } } diff --git a/cocos/physics/ammo/ammo-world.ts b/cocos/physics/ammo/ammo-world.ts index afc24d61a0..6b4bf3a7b7 100644 --- a/cocos/physics/ammo/ammo-world.ts +++ b/cocos/physics/ammo/ammo-world.ts @@ -59,9 +59,10 @@ export class AmmoWorld implements IPhysicsWorld { this._btWorld.setGravity(this._btGravity); } - step (timeStep: number, fixTimeStep?: number, maxSubStep?: number) { + step (deltaTime: number, timeSinceLastCalled?: number, maxSubStep: number = 0) { if (this.bodies.length == 0 && this.ghosts.length == 0) return; - this._btWorld.stepSimulation(timeStep, maxSubStep, fixTimeStep); + if (timeSinceLastCalled == undefined) timeSinceLastCalled = deltaTime; + this._btWorld.stepSimulation(timeSinceLastCalled, maxSubStep, deltaTime); for (let i = 0; i < this.bodies.length; i++) { this.bodies[i].syncPhysicsToScene(); @@ -258,6 +259,15 @@ export class AmmoWorld implements IPhysicsWorld { TriggerEventObject.otherCollider = collider0; collider1.emit(TriggerEventObject.type, TriggerEventObject); } else { + const body0 = collider0.attachedRigidBody; + const body1 = collider1.attachedRigidBody; + if (body0 && body1) { + if (body0.isSleeping && body1.isSleeping) continue; + } else if (body0 == null && body1) { + if (body1.isSleeping) continue; + } else if (body1 == null && body0) { + if (body0.isSleeping) continue; + } if (this.collisionArrayMat.get(shape0.id, shape1.id)) { CollisionEventObject.type = 'onCollisionStay'; } else { @@ -285,10 +295,12 @@ export class AmmoWorld implements IPhysicsWorld { CollisionEventObject.selfCollider = collider0; CollisionEventObject.otherCollider = collider1; + CollisionEventObject.isBodyA = true; collider0.emit(CollisionEventObject.type, CollisionEventObject); CollisionEventObject.selfCollider = collider1; CollisionEventObject.otherCollider = collider0; + CollisionEventObject.isBodyA = false; collider1.emit(CollisionEventObject.type, CollisionEventObject); } @@ -354,10 +366,12 @@ export class AmmoWorld implements IPhysicsWorld { CollisionEventObject.type = 'onCollisionExit'; CollisionEventObject.selfCollider = collider0; CollisionEventObject.otherCollider = collider1; + CollisionEventObject.isBodyA = true; collider0.emit(CollisionEventObject.type, CollisionEventObject); CollisionEventObject.selfCollider = collider1; CollisionEventObject.otherCollider = collider0; + CollisionEventObject.isBodyA = false; collider1.emit(CollisionEventObject.type, CollisionEventObject); this.collisionArrayMat.set(shape0.id, shape1.id, false); diff --git a/cocos/physics/cannon/cannon-rigid-body.ts b/cocos/physics/cannon/cannon-rigid-body.ts index 1a248ba3ea..aff71b6deb 100644 --- a/cocos/physics/cannon/cannon-rigid-body.ts +++ b/cocos/physics/cannon/cannon-rigid-body.ts @@ -31,23 +31,20 @@ export class CannonRigidBody implements IRigidBody { } setAllowSleep (v: boolean) { - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } this.impl.allowSleep = v; + if (this.impl.isSleeping()) this.impl.wakeUp(); } setMass (value: number) { this.impl.mass = value; if (this.impl.mass == 0) { this.impl.type = CANNON.Body.STATIC; + } else { + this.impl.type = this._rigidBody.isKinematic ? CANNON.Body.KINEMATIC : CANNON.Body.DYNAMIC; } this.impl.updateMassProperties(); - - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } + if (this.impl.isSleeping()) this.impl.wakeUp(); } setIsKinematic (value: boolean) { @@ -63,13 +60,9 @@ export class CannonRigidBody implements IRigidBody { } fixRotation (value: boolean) { - - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } - this.impl.fixedRotation = value; this.impl.updateMassProperties(); + if (this.impl.isSleeping()) this.impl.wakeUp(); } setLinearDamping (value: number) { @@ -81,30 +74,18 @@ export class CannonRigidBody implements IRigidBody { } useGravity (value: boolean) { - - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } - this.impl.useGravity = value; + if (this.impl.isSleeping()) this.impl.wakeUp(); } setLinearFactor (value: IVec3Like) { - - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } - Vec3.copy(this.impl.linearFactor, value); + if (this.impl.isSleeping()) this.impl.wakeUp(); } setAngularFactor (value: IVec3Like) { - - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } - Vec3.copy(this.impl.angularFactor, value); + if (this.impl.isSleeping()) this.impl.wakeUp(); } get impl () { @@ -182,11 +163,7 @@ export class CannonRigidBody implements IRigidBody { } setLinearVelocity (value: Vec3): void { - - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } - + if (this.impl.isSleeping()) this.impl.wakeUp(); Vec3.copy(this.impl.velocity, value); } @@ -196,80 +173,50 @@ export class CannonRigidBody implements IRigidBody { } setAngularVelocity (value: Vec3): void { - - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } - + if (this.impl.isSleeping()) this.impl.wakeUp(); Vec3.copy(this.impl.angularVelocity, value); } applyForce (force: Vec3, worldPoint?: Vec3) { - if (worldPoint == null) { - worldPoint = Vec3.ZERO; - } - - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } - + this._sharedBody.syncSceneToPhysics(); + if (this.impl.isSleeping()) this.impl.wakeUp(); + if (worldPoint == null) worldPoint = Vec3.ZERO; this.impl.applyForce(Vec3.copy(v3_cannon0, force), Vec3.copy(v3_cannon1, worldPoint)); } applyImpulse (impulse: Vec3, worldPoint?: Vec3) { - if (worldPoint == null) { - worldPoint = Vec3.ZERO; - } - - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } - + this._sharedBody.syncSceneToPhysics(); + if (this.impl.isSleeping()) this.impl.wakeUp(); + if (worldPoint == null) worldPoint = Vec3.ZERO; this.impl.applyImpulse(Vec3.copy(v3_cannon0, impulse), Vec3.copy(v3_cannon1, worldPoint)); } applyLocalForce (force: Vec3, localPoint?: Vec3): void { - if (localPoint == null) { - localPoint = Vec3.ZERO; - } - - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } - + this._sharedBody.syncSceneToPhysics(); + if (this.impl.isSleeping()) this.impl.wakeUp(); + if (localPoint == null) localPoint = Vec3.ZERO; this.impl.applyLocalForce(Vec3.copy(v3_cannon0, force), Vec3.copy(v3_cannon1, localPoint)); } applyLocalImpulse (impulse: Vec3, localPoint?: Vec3): void { - if (localPoint == null) { - localPoint = Vec3.ZERO; - } - - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } - + this._sharedBody.syncSceneToPhysics(); + if (this.impl.isSleeping()) this.impl.wakeUp(); + if (localPoint == null) localPoint = Vec3.ZERO; this.impl.applyLocalImpulse(Vec3.copy(v3_cannon0, impulse), Vec3.copy(v3_cannon1, localPoint)); } applyTorque (torque: Vec3): void { - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } - this.impl.torque.x += torque.x; - this.impl.torque.y += torque.y; - this.impl.torque.z += torque.z; + this._sharedBody.syncSceneToPhysics(); + if (this.impl.isSleeping()) this.impl.wakeUp(); + Vec3.add(this.impl.torque, this.impl.torque, torque); } applyLocalTorque (torque: Vec3): void { - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } + this._sharedBody.syncSceneToPhysics(); + if (this.impl.isSleeping()) this.impl.wakeUp(); Vec3.copy(v3_cannon0, torque); this.impl.vectorToWorldFrame(v3_cannon0, v3_cannon0); - this.impl.torque.x += v3_cannon0.x; - this.impl.torque.y += v3_cannon0.y; - this.impl.torque.z += v3_cannon0.z; + Vec3.add(this.impl.torque, this.impl.torque, v3_cannon0); } /** group */ diff --git a/cocos/physics/cannon/cannon-shared-body.ts b/cocos/physics/cannon/cannon-shared-body.ts index 51cc191407..c759f39a77 100644 --- a/cocos/physics/cannon/cannon-shared-body.ts +++ b/cocos/physics/cannon/cannon-shared-body.ts @@ -19,6 +19,7 @@ const CollisionEventObject = { selfCollider: null as ColliderComponent | null, otherCollider: null as ColliderComponent | null, contacts: [] as any, + isBodyA: false, }; /** @@ -130,10 +131,12 @@ export class CannonSharedBody { syncPhysicsToScene () { if (this.body.type != ERigidBodyType.STATIC) { - Vec3.copy(v3_0, this.body.position); - Quat.copy(quat_0, this.body.quaternion); - this.node.worldPosition = v3_0; - this.node.worldRotation = quat_0; + if (!this.body.isSleeping()) { + Vec3.copy(v3_0, this.body.position); + Quat.copy(quat_0, this.body.quaternion); + this.node.worldPosition = v3_0; + this.node.worldRotation = quat_0; + } } } @@ -162,8 +165,8 @@ export class CannonSharedBody { CollisionEventObject.type = event.event; const self = getWrap(event.selfShape); const other = getWrap(event.otherShape); - if (self) { + CollisionEventObject.isBodyA = event['bi'] == event.selfShape.body; CollisionEventObject.selfCollider = self.collider; CollisionEventObject.otherCollider = other ? other.collider : null; let i = 0; diff --git a/cocos/physics/cannon/cannon-util.ts b/cocos/physics/cannon/cannon-util.ts index 725b71c6cb..fe4ee8da79 100644 --- a/cocos/physics/cannon/cannon-util.ts +++ b/cocos/physics/cannon/cannon-util.ts @@ -1,6 +1,5 @@ import CANNON from '@cocos/cannon'; import { getWrap } from '../framework/util'; -import { Vec3 } from '../../core'; import { IBaseShape } from '../spec/i-physics-shape'; import { PhysicsRayResult } from '../framework'; import { IRaycastOptions } from '../spec/i-physics-world'; @@ -9,7 +8,7 @@ export function toCannonRaycastOptions (out: CANNON.IRaycastOptions, options: IR out.checkCollisionResponse = !options.queryTrigger; out.collisionFilterGroup = -1; out.collisionFilterMask = options.mask; - out.skipBackFaces = false; + // out.skipBackFaces = true; } export function fillRaycastResult (result: PhysicsRayResult, cannonResult: CANNON.RaycastResult) { diff --git a/cocos/physics/cannon/shapes/cannon-shape.ts b/cocos/physics/cannon/shapes/cannon-shape.ts index 1ff2f26f43..bff7134198 100644 --- a/cocos/physics/cannon/shapes/cannon-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-shape.ts @@ -1,5 +1,5 @@ import CANNON from '@cocos/cannon'; -import { Vec3 } from '../../../core/math'; +import { Vec3, Quat } from '../../../core/math'; import { getWrap, setWrap } from '../../framework/util'; import { commitShapeUpdates } from '../cannon-util'; import { PhysicMaterial } from '../../framework/assets/physic-material'; @@ -163,9 +163,11 @@ export class CannonShape implements IBaseShape { this._index = index; } - setOffsetAndOrient (offset: CANNON.Vec3, Orient: CANNON.Quaternion) { + setOffsetAndOrient (offset: CANNON.Vec3, orient: CANNON.Quaternion) { + Vec3.copy(offset, this._offset); + Quat.copy(orient, this._orient); this._offset = offset; - this._orient = Orient; + this._orient = orient; } protected _setCenter (v: IVec3Like) { diff --git a/cocos/physics/framework/components/collider/collider-component.ts b/cocos/physics/framework/components/collider/collider-component.ts index 615aa68db9..edc18eae3e 100644 --- a/cocos/physics/framework/components/collider/collider-component.ts +++ b/cocos/physics/framework/components/collider/collider-component.ts @@ -176,6 +176,45 @@ export class ColliderComponent extends Eventify(Component) { constructor () { super() } + /** + * @en + * Registers callbacks associated with triggered or collision events. + * @zh + * 注册触发或碰撞事件相关的回调。 + * @param type - The event type, onTriggerEnter|onTriggerStay|onTriggerExit|onCollisionEnter|onCollisionStay|onCollisionExit; + * @param callback - The event callback, signature:`(event?:ICollisionEvent|ITriggerEvent)=>void`. + * @param target - The event callback target. + */ + public on (type: TriggerEventType | CollisionEventType, callback: Function, target?: Object): any { + super.on(type, callback, target); + } + + /** + * @en + * Unregisters callbacks associated with trigger or collision events that have been registered. + * @zh + * 取消已经注册的触发或碰撞事件相关的回调。 + * @param type - The event type, onTriggerEnter|onTriggerStay|onTriggerExit|onCollisionEnter|onCollisionStay|onCollisionExit; + * @param callback - The event callback, signature:`(event?:ICollisionEvent|ITriggerEvent)=>void`. + * @param target - The event callback target. + */ + public off (type: TriggerEventType | CollisionEventType, callback?: Function, target?: Object) { + super.off(type, callback, target); + } + + /** + * @en + * Registers a callback associated with a trigger or collision event, which is automatically unregistered once executed. + * @zh + * 注册触发或碰撞事件相关的回调,执行一次后会自动取消注册。 + * @param type - The event type, onTriggerEnter|onTriggerStay|onTriggerExit|onCollisionEnter|onCollisionStay|onCollisionExit; + * @param callback - The event callback, signature:`(event?:ICollisionEvent|ITriggerEvent)=>void`. + * @param target - The event callback target. + */ + public once (type: TriggerEventType | CollisionEventType, callback: Function, target?: Object): any { + super.once(type, callback, target); + } + /// GROUP MASK /// /** @@ -298,6 +337,9 @@ export class ColliderComponent extends Eventify(Component) { protected onDestroy () { if (!EDITOR) { + if (this._material) { + this._material.off('physics_material_update', this._updateMaterial, this); + } this._shape.onDestroy!(); } } diff --git a/cocos/physics/framework/components/rigid-body-component.ts b/cocos/physics/framework/components/rigid-body-component.ts index 2d4e5eb681..1a8bb5024d 100644 --- a/cocos/physics/framework/components/rigid-body-component.ts +++ b/cocos/physics/framework/components/rigid-body-component.ts @@ -280,7 +280,7 @@ export class RigidBodyComponent extends Component { private _allowSleep: boolean = true; @property - private _mass: number = 10; + private _mass: number = 1; @property private _linearDamping: number = 0.1; diff --git a/cocos/physics/framework/physics-interface.ts b/cocos/physics/framework/physics-interface.ts index 208068d625..8bab3e7a30 100644 --- a/cocos/physics/framework/physics-interface.ts +++ b/cocos/physics/framework/physics-interface.ts @@ -123,6 +123,14 @@ export interface ICollisionEvent { * 碰撞中的所有碰撞点的信息。 */ readonly contacts: IContactEquation[]; + + /** + * @en + * Used to marks the selfCollider is `A` or not. + * @zh + * 用于标记自身碰撞器是否为`A`. + */ + readonly isBodyA: boolean; } /** diff --git a/cocos/physics/framework/physics-system.ts b/cocos/physics/framework/physics-system.ts index e54c0a29cd..4fb2556bfb 100644 --- a/cocos/physics/framework/physics-system.ts +++ b/cocos/physics/framework/physics-system.ts @@ -214,7 +214,13 @@ export class PhysicsSystem extends System { return; } - this._timeSinceLastUpdate = this._timeReset ? 0 : deltaTime; + if (this._timeReset) { + this._timeSinceLastUpdate = 0; + this._timeReset = false; + } else { + this._timeSinceLastUpdate = deltaTime; + } + this.physicsWorld.emitEvents(); director.emit(Director.EVENT_BEFORE_PHYSICS); this.physicsWorld.syncSceneToPhysics(); diff --git a/cocos/physics/spec/i-physics-world.ts b/cocos/physics/spec/i-physics-world.ts index d66b404dd5..d8b0907a6c 100644 --- a/cocos/physics/spec/i-physics-world.ts +++ b/cocos/physics/spec/i-physics-world.ts @@ -20,7 +20,7 @@ export interface IPhysicsWorld { setGravity: (v: IVec3Like) => void; setAllowSleep: (v: boolean) => void; setDefaultMaterial: (v: PhysicMaterial) => void; - step (deltaTime: number, ...args: any): void; + step (deltaTime: number, timeSinceLastCalled?: number, maxSubSteps?: number): void; raycast (worldRay: ray, options: IRaycastOptions, pool: RecyclePool, results: PhysicsRayResult[]): boolean raycastClosest (worldRay: ray, options: IRaycastOptions, out: PhysicsRayResult): boolean; emitEvents (): void; From 7f4e9a4a41eb83aace3c7325249e7b8b38b65611 Mon Sep 17 00:00:00 2001 From: ChiaNing Date: Thu, 28 May 2020 17:52:00 +0800 Subject: [PATCH 48/74] invalidateChildren protect (#6775) * invalidateChildren protect * update --- cocos/core/scene-graph/node.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos/core/scene-graph/node.ts b/cocos/core/scene-graph/node.ts index 6ea55170a3..b90e372e6f 100644 --- a/cocos/core/scene-graph/node.ts +++ b/cocos/core/scene-graph/node.ts @@ -461,7 +461,8 @@ export class Node extends BaseNode { dirtyBit |= TransformBit.POSITION; const len = this._children.length; for (let i = 0; i < len; ++i) { - this._children[i].invalidateChildren(dirtyBit); + const child = this._children[i]; + child.isValid && child.invalidateChildren(dirtyBit); } } From d32896450108e7b990865c585d06198c35563a86 Mon Sep 17 00:00:00 2001 From: "jiaxin.lai" Date: Thu, 28 May 2020 19:02:23 +0800 Subject: [PATCH 49/74] revert 'optimize contact data' (#6776) --- cocos/physics/ammo/ammo-const.ts | 1 - cocos/physics/ammo/ammo-world.ts | 20 ++++++++------------ cocos/physics/cannon/cannon-shared-body.ts | 6 ++---- cocos/physics/framework/physics-interface.ts | 8 +------- 4 files changed, 11 insertions(+), 24 deletions(-) diff --git a/cocos/physics/ammo/ammo-const.ts b/cocos/physics/ammo/ammo-const.ts index b0d55852d2..6436c6ea6f 100644 --- a/cocos/physics/ammo/ammo-const.ts +++ b/cocos/physics/ammo/ammo-const.ts @@ -12,7 +12,6 @@ export const CollisionEventObject = { selfCollider: null as unknown as ColliderComponent, otherCollider: null as unknown as ColliderComponent, contacts: [] as IContactEquation[], - isBodyA: false, }; export class AmmoConstant { diff --git a/cocos/physics/ammo/ammo-world.ts b/cocos/physics/ammo/ammo-world.ts index 6b4bf3a7b7..c55ea78522 100644 --- a/cocos/physics/ammo/ammo-world.ts +++ b/cocos/physics/ammo/ammo-world.ts @@ -279,14 +279,14 @@ export class AmmoWorld implements IPhysicsWorld { const cq = data.contacts[i] as Ammo.btManifoldPoint; if (contactsPool.length > 0) { const c = contactsPool.pop(); - ammo2CocosVec3(c.contactA, cq.m_positionWorldOnA); - ammo2CocosVec3(c.contactB, cq.m_positionWorldOnB); + ammo2CocosVec3(c.contactA, cq.m_localPointA); + ammo2CocosVec3(c.contactB, cq.m_localPointB); ammo2CocosVec3(c.normal, cq.m_normalWorldOnB); CollisionEventObject.contacts.push(c); } else { const c = { - contactA: ammo2CocosVec3(new Vec3(), cq.m_positionWorldOnA), - contactB: ammo2CocosVec3(new Vec3(), cq.m_positionWorldOnB), + contactA: ammo2CocosVec3(new Vec3(), cq.m_localPointA), + contactB: ammo2CocosVec3(new Vec3(), cq.m_localPointB), normal: ammo2CocosVec3(new Vec3(), cq.m_normalWorldOnB), }; CollisionEventObject.contacts.push(c); @@ -295,12 +295,10 @@ export class AmmoWorld implements IPhysicsWorld { CollisionEventObject.selfCollider = collider0; CollisionEventObject.otherCollider = collider1; - CollisionEventObject.isBodyA = true; collider0.emit(CollisionEventObject.type, CollisionEventObject); CollisionEventObject.selfCollider = collider1; CollisionEventObject.otherCollider = collider0; - CollisionEventObject.isBodyA = false; collider1.emit(CollisionEventObject.type, CollisionEventObject); } @@ -349,14 +347,14 @@ export class AmmoWorld implements IPhysicsWorld { const cq = data.contacts[i] as Ammo.btManifoldPoint; if (contactsPool.length > 0) { const c = contactsPool.pop(); - ammo2CocosVec3(c.contactA, cq.m_positionWorldOnA); - ammo2CocosVec3(c.contactB, cq.m_positionWorldOnB); + ammo2CocosVec3(c.contactA, cq.m_localPointA); + ammo2CocosVec3(c.contactB, cq.m_localPointB); ammo2CocosVec3(c.normal, cq.m_normalWorldOnB); CollisionEventObject.contacts.push(c); } else { const c = { - contactA: ammo2CocosVec3(new Vec3(), cq.m_positionWorldOnA), - contactB: ammo2CocosVec3(new Vec3(), cq.m_positionWorldOnB), + contactA: ammo2CocosVec3(new Vec3(), cq.m_localPointA), + contactB: ammo2CocosVec3(new Vec3(), cq.m_localPointB), normal: ammo2CocosVec3(new Vec3(), cq.m_normalWorldOnB), }; CollisionEventObject.contacts.push(c); @@ -366,12 +364,10 @@ export class AmmoWorld implements IPhysicsWorld { CollisionEventObject.type = 'onCollisionExit'; CollisionEventObject.selfCollider = collider0; CollisionEventObject.otherCollider = collider1; - CollisionEventObject.isBodyA = true; collider0.emit(CollisionEventObject.type, CollisionEventObject); CollisionEventObject.selfCollider = collider1; CollisionEventObject.otherCollider = collider0; - CollisionEventObject.isBodyA = false; collider1.emit(CollisionEventObject.type, CollisionEventObject); this.collisionArrayMat.set(shape0.id, shape1.id, false); diff --git a/cocos/physics/cannon/cannon-shared-body.ts b/cocos/physics/cannon/cannon-shared-body.ts index c759f39a77..7efd1aef5b 100644 --- a/cocos/physics/cannon/cannon-shared-body.ts +++ b/cocos/physics/cannon/cannon-shared-body.ts @@ -7,7 +7,7 @@ import { CannonShape } from './shapes/cannon-shape'; import { ColliderComponent } from '../../../exports/physics-framework'; import { TransformBit } from '../../core/scene-graph/node-enum'; import { Node } from '../../core'; -import { CollisionEventType } from '../framework/physics-interface'; +import { CollisionEventType, IContactEquation } from '../framework/physics-interface'; import { CannonRigidBody } from './cannon-rigid-body'; import { commitShapeUpdates } from './cannon-util'; @@ -18,8 +18,7 @@ const CollisionEventObject = { type: 'onCollisionEnter' as CollisionEventType, selfCollider: null as ColliderComponent | null, otherCollider: null as ColliderComponent | null, - contacts: [] as any, - isBodyA: false, + contacts: [] as IContactEquation[], }; /** @@ -166,7 +165,6 @@ export class CannonSharedBody { const self = getWrap(event.selfShape); const other = getWrap(event.otherShape); if (self) { - CollisionEventObject.isBodyA = event['bi'] == event.selfShape.body; CollisionEventObject.selfCollider = self.collider; CollisionEventObject.otherCollider = other ? other.collider : null; let i = 0; diff --git a/cocos/physics/framework/physics-interface.ts b/cocos/physics/framework/physics-interface.ts index 8bab3e7a30..56cb458659 100644 --- a/cocos/physics/framework/physics-interface.ts +++ b/cocos/physics/framework/physics-interface.ts @@ -116,6 +116,7 @@ export interface ICollisionEvent { */ readonly otherCollider: ColliderComponent; + // TODO: Provide interface to dynamic instantiate instead static data /** * @en * Information about all points of impact in a collision event. @@ -124,13 +125,6 @@ export interface ICollisionEvent { */ readonly contacts: IContactEquation[]; - /** - * @en - * Used to marks the selfCollider is `A` or not. - * @zh - * 用于标记自身碰撞器是否为`A`. - */ - readonly isBodyA: boolean; } /** From 1a389cecbbdb13a151e98d295f76bc869f480a27 Mon Sep 17 00:00:00 2001 From: JoneLau <32630749+JoneLau@users.noreply.github.com> Date: Thu, 28 May 2020 19:49:59 +0800 Subject: [PATCH 50/74] Sorting UI components (#6739) --- cocos/ui/components/button-component.ts | 68 ++-- .../components/editbox/edit-box-component.ts | 336 ++++++++++-------- cocos/ui/components/scroll-bar-component.ts | 12 +- cocos/ui/components/scroll-view-component.ts | 205 ++++++----- cocos/ui/components/toggle-component.ts | 55 +-- 5 files changed, 357 insertions(+), 319 deletions(-) diff --git a/cocos/ui/components/button-component.ts b/cocos/ui/components/button-component.ts index 52d3f9f07b..5a3bddba3a 100644 --- a/cocos/ui/components/button-component.ts +++ b/cocos/ui/components/button-component.ts @@ -150,6 +150,39 @@ export enum EventType { @requireComponent(UITransformComponent) export class ButtonComponent extends Component { + /** + * @en + * Transition target. + * When Button state changed: + * - If Transition type is Button.Transition.NONE, Button will do nothing. + * - If Transition type is Button.Transition.COLOR, Button will change target's color. + * - If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite. + * + * @zh + * 需要过渡的目标。
+ * 当前按钮状态改变规则:
+ * - 如果 Transition type 选择 Button.Transition.NONE,按钮不做任何过渡。 + * - 如果 Transition type 选择 Button.Transition.COLOR,按钮会对目标颜色进行颜色之间的过渡。 + * - 如果 Transition type 选择 Button.Transition.Sprite,按钮会对目标 Sprite 进行 Sprite 之间的过渡。 + */ + @property({ + type: Node, + displayOrder: 0, + tooltip: '指定 Button 背景节点,Button 状态改变时会修改此节点的 Color 或 Sprite 属性', + }) + get target () { + return this._target; + } + + set target (value) { + if (this._target === value) { + return; + } + + this._target = value; + this._applyTarget(); + } + /** * @en * Whether the Button is disabled. @@ -456,39 +489,6 @@ export class ButtonComponent extends Component { this._updateState(); } - /** - * @en - * Transition target. - * When Button state changed: - * - If Transition type is Button.Transition.NONE, Button will do nothing. - * - If Transition type is Button.Transition.COLOR, Button will change target's color. - * - If Transition type is Button.Transition.SPRITE, Button will change target Sprite's sprite. - * - * @zh - * 需要过渡的目标。
- * 当前按钮状态改变规则:
- * - 如果 Transition type 选择 Button.Transition.NONE,按钮不做任何过渡。 - * - 如果 Transition type 选择 Button.Transition.COLOR,按钮会对目标颜色进行颜色之间的过渡。 - * - 如果 Transition type 选择 Button.Transition.Sprite,按钮会对目标 Sprite 进行 Sprite 之间的过渡。 - */ - @property({ - type: Node, - displayOrder: 0, - tooltip:'指定 Button 背景节点,Button 状态改变时会修改此节点的 Color 或 Sprite 属性', - }) - get target () { - return this._target; - } - - set target (value) { - if (this._target === value) { - return; - } - - this._target = value; - this._applyTarget(); - } - public static Transition = Transition; public static EventType = EventType; /** @@ -500,7 +500,7 @@ export class ButtonComponent extends Component { */ @property({ type: [ComponentEventHandler], - displayOrder: 3, + displayOrder: 20, tooltip:'按钮点击事件的列表。先将数量改为1或更多,就可以为每个点击事件设置接受者和处理方法', }) public clickEvents: ComponentEventHandler[] = []; diff --git a/cocos/ui/components/editbox/edit-box-component.ts b/cocos/ui/components/editbox/edit-box-component.ts index 138583292d..97b1270b9f 100644 --- a/cocos/ui/components/editbox/edit-box-component.ts +++ b/cocos/ui/components/editbox/edit-box-component.ts @@ -87,6 +87,7 @@ export class EditBoxComponent extends Component { */ @property({ tooltip: '输入框的初始输入内容,如果为空则会显示占位符的文本', + displayOrder: 1, }) get string () { return this._string; @@ -103,52 +104,166 @@ export class EditBoxComponent extends Component { /** * @en - * The Label component attached to the node for EditBox's input text label + * Font size of the input text. * * @zh - * 输入框输入文本节点上挂载的 Label 组件对象 + * 输入框文本的字体大小。该属性会在将来的版本中移除,请使用 editBox.textLabel.fontSize。 */ @property({ - tooltip: '输入框输入文本节点上挂载的 Label 组件对象', - type: LabelComponent, + tooltip: '输入框文本的字体大小', + displayOrder: 2, }) - get textLabel () { - return this._textLabel; + get fontSize () { + if (!this._textLabel) { + return 20; + } + return this._textLabel!.fontSize; } - set textLabel (oldValue) { - if (this._textLabel !== oldValue) { - this._textLabel = oldValue; - if (this._textLabel){ - this._updateTextLabel(); - this._updateLabels(); - } + set fontSize (value) { + if (this._textLabel) { + this._textLabel.fontSize = value; } } + /** * @en - * The Label component attached to the node for EditBox's placeholder text label. + * Font color of the input text. * * @zh - * 输入框占位符节点上挂载的 Label 组件对象。 + * 输入框文本的颜色。该属性会在将来的版本中移除,请使用 editBox.textLabel.color */ @property({ - tooltip: '输入框占位符节点上挂载的 Label 组件对象', - type: LabelComponent, + type: Color, + tooltip: '输入框文本的颜色', + displayOrder: 3, }) - get placeholderLabel () { - return this._placeholderLabel; + get fontColor () { + if (!this._textLabel) { + return math.Color.WHITE.clone(); + } + return this._textLabel!.color; } - set placeholderLabel (oldValue) { - if (this._placeholderLabel !== oldValue) { - this._placeholderLabel = oldValue; - if (this._placeholderLabel){ - this._updatePlaceholderLabel(); - this._updateLabels(); - } + set fontColor (value) { + if (this._textLabel) { + this._textLabel.color = value; } } + + /** + * @en + * Set the input flags that are to be applied to the EditBox. + * + * @zh + * 指定输入标志位,可以指定输入方式为密码或者单词首字母大写。 + */ + @property({ + type: InputFlag, + tooltip: '指定输入标志位,可以指定输入方式为密码或者单词首字母大写', + displayOrder: 4, + }) + get inputFlag () { + return this._inputFlag; + } + + set inputFlag (value) { + this._inputFlag = value; + this._updateString(this._string); + } + + /** + * @en + * Set the input mode of the edit box. + * If you pass ANY, it will create a multiline EditBox. + * + * @zh + * 指定输入模式: ANY表示多行输入,其它都是单行输入,移动平台上还可以指定键盘样式。 + */ + @property({ + type: InputMode, + tooltip: '指定输入模式: ANY 表示多行输入,其它都是单行输入,移动平台上还可以指定键盘样式', + displayOrder: 5, + }) + get inputMode () { + return this._inputMode; + } + + set inputMode (oldValue) { + if (this._inputMode !== oldValue) { + this._inputMode = oldValue; + this._updateTextLabel(); + this._updatePlaceholderLabel(); + } + } + + /** + * @en + * The return key type of EditBox. + * Note: it is meaningless for web platforms and desktop platforms. + * + * @zh + * 指定移动设备上面回车按钮的样式。 + * 注意:这个选项对 web 平台与 desktop 平台无效。 + */ + @property({ + type: KeyboardReturnType, + tooltip: '指定移动设备上面回车按钮的样式', + displayOrder: 6, + }) + get returnType () { + return this._returnType; + } + + set returnType (value: KeyboardReturnType) { + this._returnType = value; + } + + /** + * @en + * The maximize input length of EditBox. + * - If pass a value less than 0, it won't limit the input number of characters. + * - If pass 0, it doesn't allow input any characters. + * + * @zh + * 输入框最大允许输入的字符个数。 + * - 如果值为小于 0 的值,则不会限制输入字符个数。 + * - 如果值为 0,则不允许用户进行任何输入。 + */ + @property({ + tooltip: '输入框最大允许输入的字符个数', + displayOrder: 7, + }) + get maxLength () { + return this._maxLength; + } + set maxLength (value: number) { + this._maxLength = value; + } + + /** + * @en + * Change the lineHeight of displayed text. + * + * @zh + * 输入框文本的行高。 + */ + @property({ + tooltip: '输入框文本的行高', + displayOrder: 8, + }) + get lineHeight () { + if (!this._textLabel) { + return 40; + } + return this._textLabel!.lineHeight; + } + set lineHeight (value: number) { + if (this._textLabel) { + this._textLabel.lineHeight = value; + } + } + /** * @en * The background image of EditBox. @@ -159,6 +274,7 @@ export class EditBoxComponent extends Component { @property({ type: SpriteFrame, tooltip: '输入框的背景图片', + displayOrder: 10, }) get backgroundImage () { return this._backgroundImage; @@ -175,135 +291,52 @@ export class EditBoxComponent extends Component { /** * @en - * The return key type of EditBox. - * Note: it is meaningless for web platforms and desktop platforms. + * The Label component attached to the node for EditBox's input text label * * @zh - * 指定移动设备上面回车按钮的样式。 - * 注意:这个选项对 web 平台与 desktop 平台无效。 + * 输入框输入文本节点上挂载的 Label 组件对象 */ @property({ - type: KeyboardReturnType, - tooltip: '指定移动设备上面回车按钮的样式', + tooltip: '输入框输入文本节点上挂载的 Label 组件对象', + type: LabelComponent, + displayOrder: 11, }) - get returnType () { - return this._returnType; + get textLabel () { + return this._textLabel; } - set returnType (value: KeyboardReturnType) { - this._returnType = value; - } - - /** - * @en - * Set the input flags that are to be applied to the EditBox. - * - * @zh - * 指定输入标志位,可以指定输入方式为密码或者单词首字母大写。 - */ - @property({ - type: InputFlag, - tooltip: '指定输入标志位,可以指定输入方式为密码或者单词首字母大写', - }) - get inputFlag () { - return this._inputFlag; - } - - set inputFlag (value) { - this._inputFlag = value; - this._updateString(this._string); - } - /** - * @en - * Set the input mode of the edit box. - * If you pass ANY, it will create a multiline EditBox. - * - * @zh - * 指定输入模式: ANY表示多行输入,其它都是单行输入,移动平台上还可以指定键盘样式。 - */ - @property({ - type: InputMode, - tooltip: '指定输入模式: ANY 表示多行输入,其它都是单行输入,移动平台上还可以指定键盘样式', - }) - get inputMode () { - return this._inputMode; - } - - set inputMode (oldValue) { - if (this._inputMode !== oldValue) { - this._inputMode = oldValue; - this._updateTextLabel(); - this._updatePlaceholderLabel(); - } - - } - - /** - * @en - * Font size of the input text. - * - * @zh - * 输入框文本的字体大小。该属性会在将来的版本中移除,请使用 editBox.textLabel.fontSize。 - */ - @property({ - tooltip: '输入框文本的字体大小', - }) - get fontSize () { - if (!this._textLabel){ - return 20; + set textLabel (oldValue) { + if (this._textLabel !== oldValue) { + this._textLabel = oldValue; + if (this._textLabel) { + this._updateTextLabel(); + this._updateLabels(); } - return this._textLabel!.fontSize; - } - - set fontSize (value) { - if (this._textLabel) { - this._textLabel.fontSize = value; } } - /** * @en - * Change the lineHeight of displayed text. + * The Label component attached to the node for EditBox's placeholder text label. * * @zh - * 输入框文本的行高。 + * 输入框占位符节点上挂载的 Label 组件对象。 */ @property({ - tooltip: '输入框文本的行高', + tooltip: '输入框占位符节点上挂载的 Label 组件对象', + type: LabelComponent, + displayOrder: 12, }) - get lineHeight () { - if (!this._textLabel){ - return 40; - } - return this._textLabel!.lineHeight; - } - set lineHeight (value: number) { - if (this._textLabel) { - this._textLabel.lineHeight = value; - } + get placeholderLabel () { + return this._placeholderLabel; } - /** - * @en - * Font color of the input text. - * - * @zh - * 输入框文本的颜色。该属性会在将来的版本中移除,请使用 editBox.textLabel.color - */ - @property({ - type: Color, - tooltip: '输入框文本的颜色', - }) - get fontColor () { - if (!this._textLabel){ - return math.Color.WHITE.clone(); - } - return this._textLabel!.color; - } - - set fontColor (value) { - if (this._textLabel) { - this._textLabel.color = value; + set placeholderLabel (oldValue) { + if (this._placeholderLabel !== oldValue) { + this._placeholderLabel = oldValue; + if (this._placeholderLabel) { + this._updatePlaceholderLabel(); + this._updateLabels(); + } } } @@ -316,6 +349,7 @@ export class EditBoxComponent extends Component { */ @property({ tooltip: '输入框占位符的文本内容', + displayOrder: 13, }) get placeholder () { if (!this._placeholderLabel) { @@ -339,6 +373,7 @@ export class EditBoxComponent extends Component { */ @property({ tooltip: '输入框占位符的字体大小', + displayOrder: 14, }) get placeholderFontSize () { if (!this._placeholderLabel){ @@ -361,6 +396,7 @@ export class EditBoxComponent extends Component { */ @property({ tooltip: '输入框占位符的字体颜色', + displayOrder: 15, }) get placeholderFontColor () { if (!this._placeholderLabel) { @@ -373,28 +409,6 @@ export class EditBoxComponent extends Component { if (this._placeholderLabel) { this._placeholderLabel.color = value; } - - } - - /** - * @en - * The maximize input length of EditBox. - * - If pass a value less than 0, it won't limit the input number of characters. - * - If pass 0, it doesn't allow input any characters. - * - * @zh - * 输入框最大允许输入的字符个数。 - * - 如果值为小于 0 的值,则不会限制输入字符个数。 - * - 如果值为 0,则不允许用户进行任何输入。 - */ - @property({ - tooltip: '输入框最大允许输入的字符个数', - }) - get maxLength () { - return this._maxLength; - } - set maxLength (value: number) { - this._maxLength = value; } /** @@ -409,6 +423,7 @@ export class EditBoxComponent extends Component { */ @property({ tooltip: '输入框总是可见,并且永远在游戏视图的上面(这个属性只有在 Web 上面修改有意义)', + displayOrder: 21, }) get stayOnTop () { return; @@ -427,6 +442,7 @@ export class EditBoxComponent extends Component { */ @property({ tooltip: '修改 DOM 输入元素的 tabIndex(这个属性只有在 Web 上面修改有意义)', + displayOrder: 22, }) get tabIndex () { return this._tabIndex; @@ -456,6 +472,7 @@ export class EditBoxComponent extends Component { @property({ type: [ComponentEventHandler], tooltip: '该事件在用户点击输入框获取焦点的时候被触发', + displayOrder: 31, }) public editingDidBegan: ComponentEventHandler[] = []; @@ -469,6 +486,7 @@ export class EditBoxComponent extends Component { @property({ type: [ComponentEventHandler], tooltip: '编辑文本输入框时触发的事件回调', + displayOrder: 32, }) public textChanged: ComponentEventHandler[] = []; @@ -482,6 +500,7 @@ export class EditBoxComponent extends Component { @property({ type: [ComponentEventHandler], tooltip: '在单行模式下面,一般是在用户按下回车或者点击屏幕输入框以外的地方调用该函数。 如果是多行输入,一般是在用户点击屏幕输入框以外的地方调用该函数', + displayOrder: 33, }) public editingDidEnded: ComponentEventHandler[] = []; @@ -495,6 +514,7 @@ export class EditBoxComponent extends Component { @property({ type: [ComponentEventHandler], tooltip: '该事件在用户按下回车键的时候被触发, 如果是单行输入框,按回车键还会使输入框失去焦点', + displayOrder: 34, }) public editingReturn: ComponentEventHandler[] = []; diff --git a/cocos/ui/components/scroll-bar-component.ts b/cocos/ui/components/scroll-bar-component.ts index 4fa713b924..e6ac453a94 100644 --- a/cocos/ui/components/scroll-bar-component.ts +++ b/cocos/ui/components/scroll-bar-component.ts @@ -97,7 +97,8 @@ export class ScrollBarComponent extends Component { */ @property({ type: SpriteComponent, - tooltip:'作为当前滚动区域位置显示的滑块 Sprite', + tooltip: '作为当前滚动区域位置显示的滑块 Sprite', + displayOrder: 0, }) get handle () { return this._handle; @@ -120,7 +121,8 @@ export class ScrollBarComponent extends Component { */ @property({ type: Direction, - tooltip:'ScrollBar 的滚动方向', + tooltip: 'ScrollBar 的滚动方向', + displayOrder: 1, }) get direction () { return this._direction; @@ -143,7 +145,8 @@ export class ScrollBarComponent extends Component { * 是否在没有滚动动作时自动隐藏 ScrollBar。 */ @property({ - tooltip:'是否在没有滚动动作时自动隐藏 ScrollBar', + tooltip: '是否在没有滚动动作时自动隐藏 ScrollBar', + displayOrder: 2, }) get enableAutoHide () { return this._enableAutoHide; @@ -170,7 +173,8 @@ export class ScrollBarComponent extends Component { * 注意:只要当 “enableAutoHide” 为 true 时,才有效。 */ @property({ - tooltip:'没有滚动动作后经过多久会自动隐藏。\n注意:只要当 “enableAutoHide” 为 true 时,才有效。', + tooltip: '没有滚动动作后经过多久会自动隐藏。\n注意:只要当 “enableAutoHide” 为 true 时,才有效。', + displayOrder: 3, }) get autoHideTime () { return this._autoHideTime; diff --git a/cocos/ui/components/scroll-view-component.ts b/cocos/ui/components/scroll-view-component.ts index b84a872834..1a81fa0412 100644 --- a/cocos/ui/components/scroll-view-component.ts +++ b/cocos/ui/components/scroll-view-component.ts @@ -206,6 +206,62 @@ export enum EventType { @executionOrder(110) @menu('UI/ScrollView') export class ScrollViewComponent extends ViewGroupComponent { + public static EventType = EventType; + + /** + * @en + * The elapse time of bouncing back. A value of 0 will bounce back immediately. + * + * @zh + * 回弹持续的时间,0 表示将立即反弹。 + */ + @property({ + range: [0, 10], + tooltip: '回弹持续的时间,0 表示将立即反弹', + displayOrder: 0, + }) + public bounceDuration = 1; + + /** + * @en + * It determines how quickly the content stop moving. A value of 1 will stop the movement immediately. + * A value of 0 will never stop the movement until it reaches to the boundary of scrollview. + * + * @zh + * 开启惯性后,在用户停止触摸后滚动多快停止,0表示永不停止,1表示立刻停止。 + */ + @property({ + range: [0, 1, 0.1], + tooltip: '开启惯性后,在用户停止触摸后滚动多快停止,0 表示永不停止,1 表示立刻停止', + displayOrder: 1, + }) + public brake = 0.5; + + /** + * @en + * When elastic is set, the content will be bounce back when move out of boundary. + * + * @zh + * 是否允许滚动内容超过边界,并在停止触摸后回弹。 + */ + @property({ + tooltip: '是否允许滚动内容超过边界,并在停止触摸后回弹', + displayOrder: 2, + }) + public elastic = true; + + /** + * @en + * When inertia is set, the content will continue to move when touch ended. + * + * @zh + * 是否开启滚动惯性。 + */ + @property({ + tooltip: '是否开启滚动惯性', + displayOrder: 3, + }) + public inertia = true; /** * @en @@ -217,6 +273,7 @@ export class ScrollViewComponent extends ViewGroupComponent { @property({ type: Node, tooltip: '可滚动展示内容的节点', + displayOrder: 4, }) get content () { return this._content; @@ -230,6 +287,19 @@ export class ScrollViewComponent extends ViewGroupComponent { this._calculateBoundary(); } + /** + * @en + * Enable horizontal scroll. + * + * @zh + * 是否开启水平滚动。 + */ + @property({ + tooltip: '是否开启水平滚动', + displayOrder: 5, + }) + public horizontal = true; + /** * @en * The horizontal scrollbar reference. @@ -239,6 +309,7 @@ export class ScrollViewComponent extends ViewGroupComponent { @property({ type: ScrollBarComponent, tooltip: '水平滚动的 ScrollBar', + displayOrder: 6, }) get horizontalScrollBar () { return this._horizontalScrollBar; @@ -257,6 +328,19 @@ export class ScrollViewComponent extends ViewGroupComponent { } } + /** + * @en + * Enable vertical scroll. + * + * @zh + * 是否开启垂直滚动。 + */ + @property({ + tooltip: '是否开启垂直滚动', + displayOrder: 7, + }) + public vertical = true; + /** * @en * The vertical scrollbar reference. @@ -267,6 +351,7 @@ export class ScrollViewComponent extends ViewGroupComponent { @property({ type: ScrollBarComponent, tooltip: '垂直滚动的 ScrollBar', + displayOrder: 8, }) get verticalScrollBar () { return this._verticalScrollBar; @@ -285,103 +370,6 @@ export class ScrollViewComponent extends ViewGroupComponent { } } - get view () { - if (!this._content) { - return null; - } - - return this._content.parent; - } - - public static EventType = EventType; - /** - * @en - * Enable horizontal scroll. - * - * @zh - * 是否开启水平滚动。 - */ - @property({ - tooltip: '是否开启水平滚动', - }) - public horizontal = true; - - /** - * @en - * Enable vertical scroll. - * - * @zh - * 是否开启垂直滚动。 - */ - @property({ - tooltip: '是否开启垂直滚动', - }) - public vertical = true; - - /** - * @en - * When inertia is set, the content will continue to move when touch ended. - * - * @zh - * 是否开启滚动惯性。 - */ - @property({ - tooltip: '是否开启滚动惯性', - }) - public inertia = true; - - /** - * @en - * It determines how quickly the content stop moving. A value of 1 will stop the movement immediately. - * A value of 0 will never stop the movement until it reaches to the boundary of scrollview. - * - * @zh - * 开启惯性后,在用户停止触摸后滚动多快停止,0表示永不停止,1表示立刻停止。 - */ - @property({ - range: [0, 1, 0.1], - tooltip: '开启惯性后,在用户停止触摸后滚动多快停止,0 表示永不停止,1 表示立刻停止', - }) - public brake = 0.5; - - /** - * @en - * When elastic is set, the content will be bounce back when move out of boundary. - * - * @zh - * 是否允许滚动内容超过边界,并在停止触摸后回弹。 - */ - @property({ - tooltip: '是否允许滚动内容超过边界,并在停止触摸后回弹', - }) - public elastic = true; - - /** - * @en - * The elapse time of bouncing back. A value of 0 will bounce back immediately. - * - * @zh - * 回弹持续的时间,0 表示将立即反弹。 - */ - @property({ - range: [0, 10], - tooltip: '回弹持续的时间,0 表示将立即反弹', - }) - public bounceDuration = 1; - - /** - * @en - * Scrollview events callback. - * - * @zh - * 滚动视图的事件回调函数。 - */ - @property({ - type: [ComponentEventHandler], - tooltip: '滚动视图的事件回调函数', - }) - public scrollEvents: ComponentEventHandler[] = []; - /** * @en * If cancelInnerEvents is set to true, the scroll behavior will cancel touch events on inner content nodes @@ -393,9 +381,32 @@ export class ScrollViewComponent extends ViewGroupComponent { */ @property({ tooltip: '滚动行为是否会取消子节点上注册的触摸事件', + displayOrder: 9, }) public cancelInnerEvents = true; + /** + * @en + * Scrollview events callback. + * + * @zh + * 滚动视图的事件回调函数。 + */ + @property({ + type: [ComponentEventHandler], + tooltip: '滚动视图的事件回调函数', + displayOrder: 10, + }) + public scrollEvents: ComponentEventHandler[] = []; + + get view () { + if (!this._content) { + return null; + } + + return this._content.parent; + } + protected _autoScrolling = false; protected _scrolling = false; @property diff --git a/cocos/ui/components/toggle-component.ts b/cocos/ui/components/toggle-component.ts index f51ce4041c..4941fda246 100644 --- a/cocos/ui/components/toggle-component.ts +++ b/cocos/ui/components/toggle-component.ts @@ -65,7 +65,8 @@ export class ToggleComponent extends ButtonComponent { * 如果这个设置为 true,则 check mark 组件会处于 enabled 状态,否则处于 disabled 状态。 */ @property({ - tooltip:'如果这个设置为 true,则 check mark 组件会处于 enabled 状态,否则处于 disabled 状态。', + tooltip: '如果这个设置为 true,则 check mark 组件会处于 enabled 状态,否则处于 disabled 状态。', + displayOrder: 2, }) get isChecked () { return this._isChecked; @@ -80,6 +81,30 @@ export class ToggleComponent extends ButtonComponent { this._updateCheckMark(); } + /** + * @en + * The image used for the checkmark. + * + * @zh + * Toggle 处于选中状态时显示的图片。 + */ + @property({ + type: SpriteComponent, + tooltip: 'Toggle 处于选中状态时显示的精灵图片', + displayOrder: 3, + }) + get checkMark () { + return this._checkMark; + } + + set checkMark (value) { + if (this._checkMark === value) { + return; + } + + this._checkMark = value; + } + /** * @en * The toggle group which the toggle belongs to, when it is null, the toggle is a CheckBox. @@ -90,7 +115,8 @@ export class ToggleComponent extends ButtonComponent { */ @property({ type: ToggleContainerComponent, - tooltip:'Toggle 所属的 ToggleGroup,这个属性是可选的。如果这个属性为 null,则 Toggle 是一个 CheckBox,否则,Toggle 是一个 RadioButton。' + tooltip: 'Toggle 所属的 ToggleGroup,这个属性是可选的。如果这个属性为 null,则 Toggle 是一个 CheckBox,否则,Toggle 是一个 RadioButton。', + displayOrder: 4, }) get toggleGroup () { return this._toggleGroup; @@ -110,29 +136,6 @@ export class ToggleComponent extends ButtonComponent { } } - /** - * @en - * The image used for the checkmark. - * - * @zh - * Toggle 处于选中状态时显示的图片。 - */ - @property({ - type: SpriteComponent, - tooltip:'Toggle 处于选中状态时显示的精灵图片', - }) - get checkMark () { - return this._checkMark; - } - - set checkMark (value: SpriteComponent | null) { - if (this._checkMark === value) { - return; - } - - this._checkMark = value; - } - set _resizeToTarget (value: boolean) { if (value) { this._resizeNodeToTargetNode(); @@ -159,7 +162,7 @@ export class ToggleComponent extends ButtonComponent { */ @property({ type: [ComponentEventHandler], - tooltip:'列表类型,默认为空,用户添加的每一个事件由节点引用,组件名称和一个响应函数组成', + tooltip: '列表类型,默认为空,用户添加的每一个事件由节点引用,组件名称和一个响应函数组成', }) public checkEvents: ComponentEventHandler[] = []; @property From b108494b38a1eaf8674f230e26650ad9fe28a91a Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Thu, 28 May 2020 19:51:57 +0800 Subject: [PATCH 51/74] skeletal animation: handle indirect anim curve influence (#6774) --- cocos/core/3d/builtin/effects.ts | 84 +++++++++---------- .../animation/skeletal-animation-state.ts | 52 +++++++----- .../models/skeletal-animation-utils.ts | 67 +++++++++++++-- cocos/core/scene-graph/node.ts | 2 +- 4 files changed, 135 insertions(+), 70 deletions(-) diff --git a/cocos/core/3d/builtin/effects.ts b/cocos/core/3d/builtin/effects.ts index 71b09105f1..05f4f949ae 100644 --- a/cocos/core/3d/builtin/effects.ts +++ b/cocos/core/3d/builtin/effects.ts @@ -296,22 +296,20 @@ export default [ "shaders": [ { "name": "builtin-standard|standard-vs:vert|standard-fs:frag", - "hash": 1960762747, + "hash": 1635302204, "glsl3": { - "vert": `\nprecision highp float;\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec4 a_tangent;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScaleParam;\n};\n#if USE_VERTEX_COLOR\n in vec3 a_color;\n out vec3 v_color;\n#endif\nout vec3 v_position;\nout vec3 v_normal;\n#if USE_NORMAL_MAP\n out vec3 v_tangent;\n out vec3 v_bitangent;\n#endif\nin vec2 a_texCoord;\nout vec2 v_uv;\nin vec2 a_texCoord1;\nout vec2 v_uv1;\nvec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_MORPH\n applyMorph(In);\n #endif\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n mat4 matWorld, matWorldIT;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n matWorldIT = matWorld;\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #if HAS_SECOND_UV\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec4 a_tangent;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScaleParam;\n};\n#if USE_VERTEX_COLOR\n in vec3 a_color;\n out vec3 v_color;\n#endif\nout vec3 v_position;\nout vec3 v_normal;\n#if USE_NORMAL_MAP\n out vec3 v_tangent;\n out vec3 v_bitangent;\n#endif\nin vec2 a_texCoord;\nout vec2 v_uv;\nin vec2 a_texCoord1;\nout vec2 v_uv1;\nvec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_MORPH\n applyMorph(In);\n #endif\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n mat4 matWorld, matWorldIT;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n matWorldIT = matWorld;\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #if HAS_SECOND_UV\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision highp float;\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\n return textureLod(tex, coord, lod);\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\n return textureLod(tex, coord, lod);\n}\n#endif\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nuniform CCForwardLight {\n highp vec4 cc_sphereLitPos[2];\n vec4 cc_sphereLitSizeRange[2];\n vec4 cc_sphereLitColor[2];\n highp vec4 cc_spotLitPos[2];\n vec4 cc_spotLitSizeRangeAngle[2];\n vec4 cc_spotLitDir[2];\n vec4 cc_spotLitColor[2];\n};\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting (vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb);\n #endif\n finalColor += env * cc_ambientSky.w * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\n color = min(color, vec3(8.0));\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScaleParam;\n};\nin vec3 v_position;\nin vec2 v_uv;\nin vec2 v_uv1;\nin vec3 v_normal;\n#if USE_VERTEX_COLOR\n in vec3 v_color;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n in vec3 v_tangent;\n in vec3 v_bitangent;\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_VERTEX_COLOR\n baseColor.rgb *= v_color;\n #endif\n #if USE_ALBEDO_MAP\n vec4 texColor = texture(albedoMap, ALBEDO_UV);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScaleAndCutoff.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture(normalMap, NORMAL_UV).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrParams.w) * normalize(v_tangent) +\n (nmmp.y * pbrParams.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n vec4 res = texture(pbrMap, PBR_UV);\n pbr.x *= res.OCCLUSION_CHANNEL;\n pbr.y *= res.ROUGHNESS_CHANNEL;\n pbr.z *= res.METALLIC_CHANNEL;\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture(metallicRoughnessMap, METALLIC_ROUGHNESS_UV);\n pbr.z *= metallicRoughness.METALLIC_CHANNEL;\n pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.x *= texture(occlusionMap, OCCLUSION_UV).OCCLUSION_CHANNEL;\n #endif\n s.occlusion = clamp(pbr.x, 0.0, 0.96);\n s.roughness = clamp(pbr.y, 0.04, 1.0);\n s.metallic = pbr.z;\n s.emissive = emissive.rgb * emissiveScaleParam.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture(emissiveMap, EMISSIVE_UV).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision highp float;\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matWorldIT;\n#endif\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec4 a_tangent;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform vec4 tilingOffset;\n#if USE_VERTEX_COLOR\n attribute vec3 a_color;\n varying vec3 v_color;\n#endif\nvarying vec3 v_position;\nvarying vec3 v_normal;\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n#endif\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nattribute vec2 a_texCoord1;\nvarying vec2 v_uv1;\nvec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_MORPH\n applyMorph(In);\n #endif\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n mat4 matWorld, matWorldIT;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n matWorldIT = matWorld;\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #if HAS_SECOND_UV\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec4 a_tangent;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matWorldIT;\n#endif\nuniform vec4 tilingOffset;\n#if USE_VERTEX_COLOR\n attribute vec3 a_color;\n varying vec3 v_color;\n#endif\nvarying vec3 v_position;\nvarying vec3 v_normal;\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n#endif\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nattribute vec2 a_texCoord1;\nvarying vec2 v_uv1;\nvec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_MORPH\n applyMorph(In);\n #endif\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n mat4 matWorld, matWorldIT;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n matWorldIT = matWorld;\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #if HAS_SECOND_UV\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\n #ifdef GL_EXT_shader_texture_lod\n #extension GL_EXT_shader_texture_lod : enable\n #endif\nprecision highp float;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_exposure;\nuniform mediump vec4 cc_mainLitDir;\nuniform mediump vec4 cc_mainLitColor;\nuniform mediump vec4 cc_ambientSky;\nuniform mediump vec4 cc_ambientGround;\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\n #ifdef GL_EXT_shader_texture_lod\n return texture2DLodEXT(tex, coord, lod);\n #else\n return texture2D(tex, coord, lod);\n #endif\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\n #ifdef GL_EXT_shader_texture_lod\n return textureCubeLodEXT(tex, coord, lod);\n #else\n return textureCube(tex, coord, lod);\n #endif\n}\n#endif\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nuniform highp vec4 cc_sphereLitPos[2];\nuniform vec4 cc_sphereLitSizeRange[2];\nuniform vec4 cc_sphereLitColor[2];\nuniform highp vec4 cc_spotLitPos[2];\nuniform vec4 cc_spotLitSizeRangeAngle[2];\nuniform vec4 cc_spotLitDir[2];\nuniform vec4 cc_spotLitColor[2];\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting (vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb);\n #endif\n finalColor += env * cc_ambientSky.w * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\n color = min(color, vec3(8.0));\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nuniform vec4 albedo;\nuniform vec4 albedoScaleAndCutoff;\nuniform vec4 pbrParams;\nuniform vec4 emissive;\nuniform vec4 emissiveScaleParam;\nvarying vec3 v_position;\nvarying vec2 v_uv;\nvarying vec2 v_uv1;\nvarying vec3 v_normal;\n#if USE_VERTEX_COLOR\n varying vec3 v_color;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_VERTEX_COLOR\n baseColor.rgb *= v_color;\n #endif\n #if USE_ALBEDO_MAP\n vec4 texColor = texture2D(albedoMap, ALBEDO_UV);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScaleAndCutoff.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture2D(normalMap, NORMAL_UV).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrParams.w) * normalize(v_tangent) +\n (nmmp.y * pbrParams.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n vec4 res = texture2D(pbrMap, PBR_UV);\n pbr.x *= res.OCCLUSION_CHANNEL;\n pbr.y *= res.ROUGHNESS_CHANNEL;\n pbr.z *= res.METALLIC_CHANNEL;\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture2D(metallicRoughnessMap, METALLIC_ROUGHNESS_UV);\n pbr.z *= metallicRoughness.METALLIC_CHANNEL;\n pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.x *= texture2D(occlusionMap, OCCLUSION_UV).OCCLUSION_CHANNEL;\n #endif\n s.occlusion = clamp(pbr.x, 0.0, 0.96);\n s.roughness = clamp(pbr.y, 0.04, 1.0);\n s.metallic = pbr.z;\n s.emissive = emissive.rgb * emissiveScaleParam.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture2D(emissiveMap, EMISSIVE_UV).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": { "globals": { "blocks": [{ "name": "CCGlobal", "defines": [] }], "samplers": [{ "name": "cc_environment", "defines": ["CC_USE_IBL"] }] }, - "locals": { "blocks": [{ "name": "CCLocalBatched", "defines": ["!USE_INSTANCING", "USE_BATCHING"] }, { "name": "CCLocal", "defines": ["!USE_INSTANCING", "!USE_BATCHING"] }, { "name": "CCMorph", "defines": ["CC_USE_MORPH"] }, { "name": "CCSkinningTexture", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"] }, { "name": "CCSkinningAnimation", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"] }, { "name": "CCSkinning", "defines": ["CC_USE_SKINNING", "!CC_USE_BAKED_ANIMATION"] }, { "name": "CCForwardLight", "defines": [] }], "samplers": [{ "name": "cc_PositionDisplacements", "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_POSITION"] }, { "name": "cc_NormalDisplacements", "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_NORMAL"] }, { "name": "cc_TangentDisplacements", "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_TANGENT"] }, { "name": "cc_jointTexture", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"] }] } + "locals": { "blocks": [{ "name": "CCMorph", "defines": ["CC_USE_MORPH"] }, { "name": "CCSkinningTexture", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"] }, { "name": "CCSkinningAnimation", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"] }, { "name": "CCSkinning", "defines": ["CC_USE_SKINNING", "!CC_USE_BAKED_ANIMATION"] }, { "name": "CCLocalBatched", "defines": ["!USE_INSTANCING", "USE_BATCHING"] }, { "name": "CCLocal", "defines": ["!USE_INSTANCING", "!USE_BATCHING"] }, { "name": "CCForwardLight", "defines": [] }], "samplers": [{ "name": "cc_PositionDisplacements", "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_POSITION"] }, { "name": "cc_NormalDisplacements", "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_NORMAL"] }, { "name": "cc_TangentDisplacements", "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_TANGENT"] }, { "name": "cc_jointTexture", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"] }] } }, "defines": [ - { "name": "USE_INSTANCING", "type": "boolean" }, - { "name": "USE_BATCHING", "type": "boolean" }, { "name": "CC_USE_MORPH", "type": "boolean" }, { "name": "CC_MORPH_TARGET_COUNT", "type": "number", "range": [2, 8] }, { "name": "CC_MORPH_PRECOMPUTED", "type": "boolean" }, @@ -320,7 +318,9 @@ export default [ { "name": "CC_MORPH_TARGET_HAS_TANGENT", "type": "boolean" }, { "name": "CC_USE_SKINNING", "type": "boolean" }, { "name": "CC_USE_BAKED_ANIMATION", "type": "boolean" }, + { "name": "USE_INSTANCING", "type": "boolean" }, { "name": "CC_SUPPORT_FLOAT_TEXTURE", "type": "boolean" }, + { "name": "USE_BATCHING", "type": "boolean" }, { "name": "USE_VERTEX_COLOR", "type": "boolean" }, { "name": "USE_NORMAL_MAP", "type": "boolean" }, { "name": "HAS_SECOND_UV", "type": "boolean" }, @@ -362,17 +362,17 @@ export default [ { "name": "emissiveMap", "type": 28, "count": 1, "defines": ["USE_EMISSIVE_MAP"], "binding": 35 } ], "attributes": [ - { "name": "a_matWorld0", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 4 }, - { "name": "a_matWorld1", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 5 }, - { "name": "a_matWorld2", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 6 }, - { "name": "a_dyn_batch_id", "type": 13, "count": 1, "defines": ["!USE_INSTANCING", "USE_BATCHING"], "format": 11, "location": 3 }, { "name": "a_position", "type": 15, "count": 1, "defines": [], "format": 32, "location": 0 }, { "name": "a_normal", "type": 15, "count": 1, "defines": [], "format": 32, "location": 1 }, { "name": "a_tangent", "type": 16, "count": 1, "defines": [], "format": 43, "location": 2 }, - { "name": "a_vertexId", "type": 13, "count": 1, "defines": ["CC_USE_MORPH"], "format": 11, "location": 7 }, - { "name": "a_weights", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING"], "format": 43, "location": 8 }, - { "name": "a_joints", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING"], "format": 43, "location": 9 }, - { "name": "a_jointAnimInfo", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION", "USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 10 }, + { "name": "a_vertexId", "type": 13, "count": 1, "defines": ["CC_USE_MORPH"], "format": 11, "location": 3 }, + { "name": "a_weights", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING"], "format": 43, "location": 4 }, + { "name": "a_joints", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING"], "format": 43, "location": 5 }, + { "name": "a_jointAnimInfo", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION", "USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 6 }, + { "name": "a_matWorld0", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 7 }, + { "name": "a_matWorld1", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 8 }, + { "name": "a_matWorld2", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 9 }, + { "name": "a_dyn_batch_id", "type": 13, "count": 1, "defines": ["!USE_INSTANCING", "USE_BATCHING"], "format": 11, "location": 10 }, { "name": "a_color", "type": 15, "count": 1, "defines": ["USE_VERTEX_COLOR"], "format": 32, "location": 11 }, { "name": "a_texCoord", "type": 14, "count": 1, "defines": [], "format": 21, "location": 12 }, { "name": "a_texCoord1", "type": 14, "count": 1, "defines": [], "format": 21, "location": 13 } @@ -438,22 +438,20 @@ export default [ "shaders": [ { "name": "builtin-unlit|unlit-vs:vert|unlit-fs:frag", - "hash": 2123471034, + "hash": 1851195889, "glsl3": { - "vert": `\nprecision highp float;\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\n#if USE_VERTEX_COLOR\n in vec4 a_color;\n out vec4 v_color;\n#endif\n#if USE_TEXTURE\n in vec2 a_texCoord;\n out vec2 v_uv;\n uniform TexCoords {\n vec4 tilingOffset;\n };\n#endif\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\n#if USE_VERTEX_COLOR\n in vec4 a_color;\n out vec4 v_color;\n#endif\n#if USE_TEXTURE\n in vec2 a_texCoord;\n out vec2 v_uv;\n uniform TexCoords {\n vec4 tilingOffset;\n };\n#endif\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision mediump float;\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n#if USE_ALPHA_TEST\n#endif\n#if USE_TEXTURE\n in vec2 v_uv;\n uniform sampler2D mainTexture;\n#endif\nuniform Constant {\n vec4 mainColor;\n vec4 colorScaleAndCutoff;\n};\n#if USE_VERTEX_COLOR\n in vec4 v_color;\n#endif\nvec4 frag () {\n vec4 o = mainColor;\n o.rgb *= colorScaleAndCutoff.xyz;\n #if USE_VERTEX_COLOR\n o *= v_color;\n #endif\n #if USE_TEXTURE\n o *= texture(mainTexture, v_uv);\n #endif\n #if USE_ALPHA_TEST\n if (o.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard;\n #endif\n return CCFragOutput(o);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision highp float;\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\n#if USE_VERTEX_COLOR\n attribute vec4 a_color;\n varying vec4 v_color;\n#endif\n#if USE_TEXTURE\n attribute vec2 a_texCoord;\n varying vec2 v_uv;\n uniform vec4 tilingOffset;\n#endif\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\n#if USE_VERTEX_COLOR\n attribute vec4 a_color;\n varying vec4 v_color;\n#endif\n#if USE_TEXTURE\n attribute vec2 a_texCoord;\n varying vec2 v_uv;\n uniform vec4 tilingOffset;\n#endif\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision mediump float;\nuniform mediump vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n#if USE_ALPHA_TEST\n#endif\n#if USE_TEXTURE\n varying vec2 v_uv;\n uniform sampler2D mainTexture;\n#endif\nuniform vec4 mainColor;\nuniform vec4 colorScaleAndCutoff;\n#if USE_VERTEX_COLOR\n varying vec4 v_color;\n#endif\nvec4 frag () {\n vec4 o = mainColor;\n o.rgb *= colorScaleAndCutoff.xyz;\n #if USE_VERTEX_COLOR\n o *= v_color;\n #endif\n #if USE_TEXTURE\n o *= texture2D(mainTexture, v_uv);\n #endif\n #if USE_ALPHA_TEST\n if (o.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard;\n #endif\n return CCFragOutput(o);\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": { "globals": { "blocks": [{ "name": "CCGlobal", "defines": [] }], "samplers": [] }, - "locals": { "blocks": [{ "name": "CCLocalBatched", "defines": ["!USE_INSTANCING", "USE_BATCHING"] }, { "name": "CCLocal", "defines": ["!USE_INSTANCING", "!USE_BATCHING"] }, { "name": "CCMorph", "defines": ["CC_USE_MORPH"] }, { "name": "CCSkinningTexture", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"] }, { "name": "CCSkinningAnimation", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"] }, { "name": "CCSkinning", "defines": ["CC_USE_SKINNING", "!CC_USE_BAKED_ANIMATION"] }], "samplers": [{ "name": "cc_PositionDisplacements", "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_POSITION"] }, { "name": "cc_NormalDisplacements", "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_NORMAL"] }, { "name": "cc_TangentDisplacements", "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_TANGENT"] }, { "name": "cc_jointTexture", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"] }] } + "locals": { "blocks": [{ "name": "CCMorph", "defines": ["CC_USE_MORPH"] }, { "name": "CCSkinningTexture", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"] }, { "name": "CCSkinningAnimation", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"] }, { "name": "CCSkinning", "defines": ["CC_USE_SKINNING", "!CC_USE_BAKED_ANIMATION"] }, { "name": "CCLocalBatched", "defines": ["!USE_INSTANCING", "USE_BATCHING"] }, { "name": "CCLocal", "defines": ["!USE_INSTANCING", "!USE_BATCHING"] }], "samplers": [{ "name": "cc_PositionDisplacements", "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_POSITION"] }, { "name": "cc_NormalDisplacements", "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_NORMAL"] }, { "name": "cc_TangentDisplacements", "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_TANGENT"] }, { "name": "cc_jointTexture", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"] }] } }, "defines": [ - { "name": "USE_INSTANCING", "type": "boolean" }, - { "name": "USE_BATCHING", "type": "boolean" }, { "name": "CC_USE_MORPH", "type": "boolean" }, { "name": "CC_MORPH_TARGET_COUNT", "type": "number", "range": [2, 8] }, { "name": "CC_MORPH_PRECOMPUTED", "type": "boolean" }, @@ -462,7 +460,9 @@ export default [ { "name": "CC_MORPH_TARGET_HAS_TANGENT", "type": "boolean" }, { "name": "CC_USE_SKINNING", "type": "boolean" }, { "name": "CC_USE_BAKED_ANIMATION", "type": "boolean" }, + { "name": "USE_INSTANCING", "type": "boolean" }, { "name": "CC_SUPPORT_FLOAT_TEXTURE", "type": "boolean" }, + { "name": "USE_BATCHING", "type": "boolean" }, { "name": "USE_VERTEX_COLOR", "type": "boolean" }, { "name": "USE_TEXTURE", "type": "boolean" }, { "name": "FLIP_UV", "type": "boolean" }, @@ -483,15 +483,15 @@ export default [ { "name": "mainTexture", "type": 28, "count": 1, "defines": ["USE_TEXTURE"], "binding": 30 } ], "attributes": [ - { "name": "a_matWorld0", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 4 }, - { "name": "a_matWorld1", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 1 }, - { "name": "a_matWorld2", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 2 }, - { "name": "a_dyn_batch_id", "type": 13, "count": 1, "defines": ["!USE_INSTANCING", "USE_BATCHING"], "format": 11, "location": 3 }, { "name": "a_position", "type": 15, "count": 1, "defines": [], "format": 32, "location": 0 }, - { "name": "a_vertexId", "type": 13, "count": 1, "defines": ["CC_USE_MORPH"], "format": 11, "location": 5 }, - { "name": "a_weights", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING"], "format": 43, "location": 6 }, - { "name": "a_joints", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING"], "format": 43, "location": 7 }, - { "name": "a_jointAnimInfo", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION", "USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 8 }, + { "name": "a_vertexId", "type": 13, "count": 1, "defines": ["CC_USE_MORPH"], "format": 11, "location": 1 }, + { "name": "a_weights", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING"], "format": 43, "location": 2 }, + { "name": "a_joints", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING"], "format": 43, "location": 3 }, + { "name": "a_jointAnimInfo", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION", "USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 4 }, + { "name": "a_matWorld0", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 5 }, + { "name": "a_matWorld1", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 6 }, + { "name": "a_matWorld2", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 7 }, + { "name": "a_dyn_batch_id", "type": 13, "count": 1, "defines": ["!USE_INSTANCING", "USE_BATCHING"], "format": 11, "location": 8 }, { "name": "a_color", "type": 16, "count": 1, "defines": ["USE_VERTEX_COLOR"], "format": 43, "location": 9 }, { "name": "a_texCoord", "type": 14, "count": 1, "defines": ["USE_TEXTURE"], "format": 21, "location": 10 } ] @@ -507,22 +507,20 @@ export default [ "shaders": [ { "name": "pipeline/planar-shadow|planar-shadow-vs:vert|planar-shadow-fs:frag", - "hash": 2467023454, + "hash": 1445934484, "glsl3": { - "vert": `\nprecision highp float;\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nuniform CCShadow {\n highp mat4 cc_matLightPlaneProj;\n lowp vec4 cc_shadowColor;\n};\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n position = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nuniform CCShadow {\n highp mat4 cc_matLightPlaneProj;\n lowp vec4 cc_shadowColor;\n};\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n position = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision mediump float;\nuniform CCShadow {\n highp mat4 cc_matLightPlaneProj;\n lowp vec4 cc_shadowColor;\n};\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvec4 frag () {\n return CCFragOutput(cc_shadowColor);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision highp float;\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\nuniform highp mat4 cc_matLightPlaneProj;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n position = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\nuniform highp mat4 cc_matLightPlaneProj;\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n position = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision mediump float;\nuniform lowp vec4 cc_shadowColor;\nuniform mediump vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvec4 frag () {\n return CCFragOutput(cc_shadowColor);\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": { "globals": { "blocks": [{ "name": "CCGlobal", "defines": [] }, { "name": "CCShadow", "defines": [] }], "samplers": [] }, - "locals": { "blocks": [{ "name": "CCLocalBatched", "defines": ["!USE_INSTANCING", "USE_BATCHING"] }, { "name": "CCLocal", "defines": ["!USE_INSTANCING", "!USE_BATCHING"] }, { "name": "CCMorph", "defines": ["CC_USE_MORPH"] }, { "name": "CCSkinningTexture", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"] }, { "name": "CCSkinningAnimation", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"] }, { "name": "CCSkinning", "defines": ["CC_USE_SKINNING", "!CC_USE_BAKED_ANIMATION"] }], "samplers": [{ "name": "cc_PositionDisplacements", "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_POSITION"] }, { "name": "cc_NormalDisplacements", "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_NORMAL"] }, { "name": "cc_TangentDisplacements", "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_TANGENT"] }, { "name": "cc_jointTexture", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"] }] } + "locals": { "blocks": [{ "name": "CCMorph", "defines": ["CC_USE_MORPH"] }, { "name": "CCSkinningTexture", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"] }, { "name": "CCSkinningAnimation", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"] }, { "name": "CCSkinning", "defines": ["CC_USE_SKINNING", "!CC_USE_BAKED_ANIMATION"] }, { "name": "CCLocalBatched", "defines": ["!USE_INSTANCING", "USE_BATCHING"] }, { "name": "CCLocal", "defines": ["!USE_INSTANCING", "!USE_BATCHING"] }], "samplers": [{ "name": "cc_PositionDisplacements", "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_POSITION"] }, { "name": "cc_NormalDisplacements", "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_NORMAL"] }, { "name": "cc_TangentDisplacements", "defines": ["CC_USE_MORPH", "CC_MORPH_TARGET_HAS_TANGENT"] }, { "name": "cc_jointTexture", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION"] }] } }, "defines": [ - { "name": "USE_INSTANCING", "type": "boolean" }, - { "name": "USE_BATCHING", "type": "boolean" }, { "name": "CC_USE_MORPH", "type": "boolean" }, { "name": "CC_MORPH_TARGET_COUNT", "type": "number", "range": [2, 8] }, { "name": "CC_MORPH_PRECOMPUTED", "type": "boolean" }, @@ -531,21 +529,23 @@ export default [ { "name": "CC_MORPH_TARGET_HAS_TANGENT", "type": "boolean" }, { "name": "CC_USE_SKINNING", "type": "boolean" }, { "name": "CC_USE_BAKED_ANIMATION", "type": "boolean" }, + { "name": "USE_INSTANCING", "type": "boolean" }, { "name": "CC_SUPPORT_FLOAT_TEXTURE", "type": "boolean" }, + { "name": "USE_BATCHING", "type": "boolean" }, { "name": "CC_USE_HDR", "type": "boolean" } ], "blocks": [], "samplers": [], "attributes": [ - { "name": "a_matWorld0", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 4 }, - { "name": "a_matWorld1", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 1 }, - { "name": "a_matWorld2", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 2 }, - { "name": "a_dyn_batch_id", "type": 13, "count": 1, "defines": ["!USE_INSTANCING", "USE_BATCHING"], "format": 11, "location": 3 }, { "name": "a_position", "type": 15, "count": 1, "defines": [], "format": 32, "location": 0 }, - { "name": "a_vertexId", "type": 13, "count": 1, "defines": ["CC_USE_MORPH"], "format": 11, "location": 5 }, - { "name": "a_weights", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING"], "format": 43, "location": 6 }, - { "name": "a_joints", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING"], "format": 43, "location": 7 }, - { "name": "a_jointAnimInfo", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION", "USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 8 } + { "name": "a_vertexId", "type": 13, "count": 1, "defines": ["CC_USE_MORPH"], "format": 11, "location": 1 }, + { "name": "a_weights", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING"], "format": 43, "location": 2 }, + { "name": "a_joints", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING"], "format": 43, "location": 3 }, + { "name": "a_jointAnimInfo", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION", "USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 4 }, + { "name": "a_matWorld0", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 5 }, + { "name": "a_matWorld1", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 6 }, + { "name": "a_matWorld2", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 7 }, + { "name": "a_dyn_batch_id", "type": 13, "count": 1, "defines": ["!USE_INSTANCING", "USE_BATCHING"], "format": 11, "location": 8 } ] } ] diff --git a/cocos/core/animation/skeletal-animation-state.ts b/cocos/core/animation/skeletal-animation-state.ts index e3e85bbc4e..405388d92a 100644 --- a/cocos/core/animation/skeletal-animation-state.ts +++ b/cocos/core/animation/skeletal-animation-state.ts @@ -118,31 +118,45 @@ export class SkeletalAnimationState extends AnimationState { const socket = sockets[i]; const targetNode = root.getChildByPath(socket.path); if (!socket.target) { continue; } - const sourceData = SkelAnimDataHub.getOrExtract(this.clip).data; - // find lowest joint animation + const clipData = SkelAnimDataHub.getOrExtract(this.clip); let animPath = socket.path; - let source = sourceData[animPath]; - let animNode = targetNode!; + let source = clipData.data[animPath]; + let animNode = targetNode; + let downstream: Mat4 | undefined; while (!source) { const idx = animPath.lastIndexOf('/'); - animPath = animPath.substring(0, idx); - source = sourceData[animPath]; - animNode = animNode.parent!; if (idx < 0) { break; } + animPath = animPath.substring(0, idx); + source = clipData.data[animPath]; + if (animNode) { + if (!downstream) { downstream = m4_2; Mat4.identity(downstream); } + Mat4.fromRTS(m4_1, animNode.rotation, animNode.position, animNode.scale); + Mat4.multiply(downstream, m4_1, downstream); + animNode = animNode.parent; + } } - // create animation data - const frames = source.worldMatrix.values as Mat4[]; - const socketData: ISocketData = { + const curveData: Mat4[] | undefined = source && source.worldMatrix.values as Mat4[]; + const frames = clipData.info.frames; + const transforms: ITransform[] = []; + for (let frame = 0; frame < frames; frame++) { + let mat: Mat4; + if (curveData && downstream) { // curve & static two-way combination + mat = Mat4.multiply(m4_1, curveData[frame], downstream); + } else if (curveData) { // there is a curve directly controlling the joint + mat = curveData[frame]; + } else if (downstream) { // fallback to default pose if no animation curve can be found upstream + mat = downstream; + } else { // bottom line: render the original mesh as-is + mat = Mat4.IDENTITY; + } + const tfm = { pos: new Vec3(), rot: new Quat(), scale: new Vec3() }; + Mat4.toRTS(mat, tfm.rot, tfm.pos, tfm.scale); + transforms.push(tfm); + } + this._sockets.push({ target: socket.target, - frames: frames.map(() => ({ pos: new Vec3(), rot: new Quat(), scale: new Vec3() })), - }; - // apply downstream default pose - getWorldTransformUntilRoot(targetNode!, animNode, m4_1); - for (let j = 0; j < socketData.frames.length; j++) { - const m = frames[j]; const dst = socketData.frames[j]; - Mat4.toRTS(Mat4.multiply(m4_2, m, m4_1), dst.rot, dst.pos, dst.scale); - } - this._sockets.push(socketData); + frames: transforms, + }); } } diff --git a/cocos/core/renderer/models/skeletal-animation-utils.ts b/cocos/core/renderer/models/skeletal-animation-utils.ts index 63e4ab19b4..2e347462c0 100644 --- a/cocos/core/renderer/models/skeletal-animation-utils.ts +++ b/cocos/core/renderer/models/skeletal-animation-utils.ts @@ -144,6 +144,12 @@ export interface ICustomJointTextureLayout { contents: IChunkContent[]; } +interface IJointAnimInfo { + downstream?: Mat4; // downstream default pose, if present + curveData?: Mat4[]; // the nearest animation curve, if present + correctionPath?: string; // path of the nearest curve, if downstream pose does not exist +} + // Have to use some big number to replace the actual 'Infinity'. // For (Infinity - Infinity) evaluates to NaN const Inf = Number.MAX_SAFE_INTEGER; @@ -276,16 +282,43 @@ export class JointTexturePool { for (let fid = 0; fid < frames; fid++) { bounds.push(new aabb(Inf, Inf, Inf, -Inf, -Inf, -Inf)); } + const animInfos: IJointAnimInfo[] = []; + for (let i = 0; i < totalJoints; i++) { + let animPath = joints[i]; + let source = clipData.data[animPath]; + let animNode = skinningRoot.getChildByPath(animPath); + let downstream: Mat4 | undefined; + let correctionPath: string | undefined; + while (!source) { + const idx = animPath.lastIndexOf('/'); + if (idx < 0) { break; } + animPath = animPath.substring(0, idx); + source = clipData.data[animPath]; + if (animNode) { + if (!downstream) { downstream = new Mat4(); } + Mat4.fromRTS(m4_1, animNode.rotation, animNode.position, animNode.scale); + Mat4.multiply(downstream, m4_1, downstream); + animNode = animNode.parent; + } else { // record the nearest curve path if no downstream pose is present + correctionPath = animPath; + } + } + animInfos.push({ curveData: source && source.worldMatrix.values as Mat4[], downstream, correctionPath }); + } let offset = 0; for (let frame = 0; frame < frames; frame++) { const bound = bounds[frame]; for (let i = 0; i < totalJoints; i++, offset += 12) { - const nodeData = clipData.data[joints[i]]; - let mat = Mat4.IDENTITY; - if (nodeData) { mat = nodeData.worldMatrix.values[frame] as Mat4; } - else { - const node = skinningRoot.getChildByPath(joints[i]); // fallback to default pose - mat = node ? getWorldTransformUntilRoot(node, skinningRoot, m4_1) : Mat4.IDENTITY; + const animInfo = animInfos[i]; + let mat: Mat4; + if (animInfo.curveData && animInfo.downstream) { // curve & static two-way combination + mat = Mat4.multiply(m4_1, animInfo.curveData[frame], animInfo.downstream); + } else if (animInfo.curveData) { // there is a curve directly controlling the joint + mat = animInfo.curveData[frame]; + } else if (animInfo.downstream) { // fallback to default pose if no animation curve can be found upstream + mat = animInfo.downstream; + } else { // bottom line: render the original mesh as-is + mat = Mat4.IDENTITY; } const boneSpaceBound = boneSpaceBounds[i]; if (boneSpaceBound) { @@ -295,8 +328,26 @@ export class JointTexturePool { Vec3.max(bound.halfExtents, bound.halfExtents, v3_4); } if (buildTexture) { - if (mat !== Mat4.IDENTITY) { Mat4.multiply(m4_1, mat, bindposes[i]); } - uploadJointData(textureBuffer, offset, m4_1, i === 0); + let bindposeIdx = i; + // It is regularly observed that developers may choose to delete the whole skeleton node tree + // for skinning models that only use baked animations, to reduce prefab file size. + // This becomes troublesome in some cases during baking though, e.g. when a skeleton joint node + // is not directly controlled by any animation curve, but its parent nodes are. + // Due to the lack of proper downstream default pose, the joint transform can not be calculated accurately. + // We address this issue by employing some pragmatic approximation. + // Specifically, by multiplying the bindpose of the joint corresponding to the nearest curve, instead of the actual target joint. + // It gives more visually-plausible results compared to the naive approach for most cases we've covered. + if (animInfo.correctionPath !== undefined) { + bindposeIdx = i - 1; // just use the previous joint if the exact path is not found + for (let j = 0; j < totalJoints; j++) { + if (joints[j] === animInfo.correctionPath) { + bindposeIdx = j; break; + } + } + } + // no need to apply bindpose if we are rendering the mesh as-is + if (mat !== Mat4.IDENTITY) { mat = Mat4.multiply(m4_1, mat, bindposes[bindposeIdx]); } + uploadJointData(textureBuffer, offset, mat, i === 0); } } aabb.fromPoints(bound, bound.center, bound.halfExtents); diff --git a/cocos/core/scene-graph/node.ts b/cocos/core/scene-graph/node.ts index b90e372e6f..2569efc60d 100644 --- a/cocos/core/scene-graph/node.ts +++ b/cocos/core/scene-graph/node.ts @@ -512,7 +512,7 @@ export class Node extends BaseNode { if (dirtyBits & TransformBit.RS) { if (dirtyBits & TransformBit.ROTATION) { Quat.copy(child._rot, child._lrot); - } + } if (dirtyBits & TransformBit.SCALE) { Vec3.copy(child._scale, child._lscale); } From d84f5203d2ba1b373d88b668d41677ddcabe8bc4 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Fri, 29 May 2020 11:51:06 +0800 Subject: [PATCH 52/74] should reset cache when binding framebuffer (#6777) * move bindpose finding outside frame loop * should reset cache when binding framebuffer --- cocos/core/gfx/webgl/webgl-commands.ts | 2 + cocos/core/gfx/webgl2/webgl2-commands.ts | 2 + .../models/skeletal-animation-utils.ts | 40 +++++++++---------- 3 files changed, 24 insertions(+), 20 deletions(-) diff --git a/cocos/core/gfx/webgl/webgl-commands.ts b/cocos/core/gfx/webgl/webgl-commands.ts index 53c6389382..822a98bca0 100644 --- a/cocos/core/gfx/webgl/webgl-commands.ts +++ b/cocos/core/gfx/webgl/webgl-commands.ts @@ -1523,6 +1523,8 @@ export function WebGLCmdFuncBeginRenderPass ( if (cache.glFramebuffer !== gpuFramebuffer.glFramebuffer) { gl.bindFramebuffer(gl.FRAMEBUFFER, gpuFramebuffer.glFramebuffer); cache.glFramebuffer = gpuFramebuffer.glFramebuffer; + gfxStateCache.gpuInputAssembler = null; + gfxStateCache.gpuShader = null; } if (cache.viewport.left !== renderArea.x || diff --git a/cocos/core/gfx/webgl2/webgl2-commands.ts b/cocos/core/gfx/webgl2/webgl2-commands.ts index 9fa3410223..5b73099849 100644 --- a/cocos/core/gfx/webgl2/webgl2-commands.ts +++ b/cocos/core/gfx/webgl2/webgl2-commands.ts @@ -1776,6 +1776,8 @@ export function WebGL2CmdFuncBeginRenderPass ( if (cache.glFramebuffer !== gpuFramebuffer.glFramebuffer) { gl.bindFramebuffer(gl.FRAMEBUFFER, gpuFramebuffer.glFramebuffer); cache.glFramebuffer = gpuFramebuffer.glFramebuffer; + gfxStateCache.gpuInputAssembler = null; + gfxStateCache.gpuShader = null; } if (cache.viewport.left !== renderArea.x || diff --git a/cocos/core/renderer/models/skeletal-animation-utils.ts b/cocos/core/renderer/models/skeletal-animation-utils.ts index 2e347462c0..be6407887f 100644 --- a/cocos/core/renderer/models/skeletal-animation-utils.ts +++ b/cocos/core/renderer/models/skeletal-animation-utils.ts @@ -147,7 +147,7 @@ export interface ICustomJointTextureLayout { interface IJointAnimInfo { downstream?: Mat4; // downstream default pose, if present curveData?: Mat4[]; // the nearest animation curve, if present - correctionPath?: string; // path of the nearest curve, if downstream pose does not exist + bindpose: Mat4; // the actual bindpose to use } // Have to use some big number to replace the actual 'Infinity'. @@ -303,7 +303,24 @@ export class JointTexturePool { correctionPath = animPath; } } - animInfos.push({ curveData: source && source.worldMatrix.values as Mat4[], downstream, correctionPath }); + let bindposeIdx = i; + // It is regularly observed that developers may choose to delete the whole skeleton node tree + // for skinning models that only use baked animations, to reduce prefab file size. + // This becomes troublesome in some cases during baking though, e.g. when a skeleton joint node + // is not directly controlled by any animation curve, but its parent nodes are. + // Due to the lack of proper downstream default pose, the joint transform can not be calculated accurately. + // We address this issue by employing some pragmatic approximation. + // Specifically, by multiplying the bindpose of the joint corresponding to the nearest curve, instead of the actual target joint. + // It gives more visually-plausible results compared to the naive approach for most cases we've covered. + if (correctionPath !== undefined) { + bindposeIdx = i - 1; // just use the previous joint if the exact path is not found + for (let j = 0; j < totalJoints; j++) { + if (joints[j] === correctionPath) { + bindposeIdx = j; break; + } + } + } + animInfos.push({ curveData: source && source.worldMatrix.values as Mat4[], downstream, bindpose: bindposes[bindposeIdx] }); } let offset = 0; for (let frame = 0; frame < frames; frame++) { @@ -328,25 +345,8 @@ export class JointTexturePool { Vec3.max(bound.halfExtents, bound.halfExtents, v3_4); } if (buildTexture) { - let bindposeIdx = i; - // It is regularly observed that developers may choose to delete the whole skeleton node tree - // for skinning models that only use baked animations, to reduce prefab file size. - // This becomes troublesome in some cases during baking though, e.g. when a skeleton joint node - // is not directly controlled by any animation curve, but its parent nodes are. - // Due to the lack of proper downstream default pose, the joint transform can not be calculated accurately. - // We address this issue by employing some pragmatic approximation. - // Specifically, by multiplying the bindpose of the joint corresponding to the nearest curve, instead of the actual target joint. - // It gives more visually-plausible results compared to the naive approach for most cases we've covered. - if (animInfo.correctionPath !== undefined) { - bindposeIdx = i - 1; // just use the previous joint if the exact path is not found - for (let j = 0; j < totalJoints; j++) { - if (joints[j] === animInfo.correctionPath) { - bindposeIdx = j; break; - } - } - } // no need to apply bindpose if we are rendering the mesh as-is - if (mat !== Mat4.IDENTITY) { mat = Mat4.multiply(m4_1, mat, bindposes[bindposeIdx]); } + if (mat !== Mat4.IDENTITY) { mat = Mat4.multiply(m4_1, mat, animInfo.bindpose); } uploadJointData(textureBuffer, offset, mat, i === 0); } } From a0cc2585b611e91ee3513a5ba0e6d47ff076ac53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Fri, 29 May 2020 11:51:34 +0800 Subject: [PATCH 53/74] Solve once-off problem (#6773) --- cocos/core/event/callbacks-invoker.ts | 22 +++++++++++++++++++++- cocos/core/event/eventify.ts | 2 +- 2 files changed, 22 insertions(+), 2 deletions(-) diff --git a/cocos/core/event/callbacks-invoker.ts b/cocos/core/event/callbacks-invoker.ts index fa92f1393d..27f30ebb7b 100644 --- a/cocos/core/event/callbacks-invoker.ts +++ b/cocos/core/event/callbacks-invoker.ts @@ -164,6 +164,26 @@ export interface ICallbackTable { export class CallbacksInvoker { public _callbackTable: ICallbackTable = createMap(true); + /** + * After "once subscription" is triggered, + * the corresponding `CallbacksInvoker.prototype.off` was going to be called + * as a matter of course. + * But `Eventify(base).prototype.off` was not called though it should be. + * This is because `Eventify(base)` use `CallbacksInvoker` in a composition way. + * We do this HACK here to solve this problem temporarily. + */ + private _thisProxy: { + off: CallbacksInvoker['off']; + }; + + /** + * + * @param thisProxy Note, this is for special use case. DO NOT take to use this parameter. + */ + constructor (thisProxy?: CallbacksInvoker['_thisProxy']) { + this._thisProxy = thisProxy ?? this; + } + /** * @zh 向一个事件名注册一个新的事件监听器,包含回调函数和调用者 * @en Register an event listener to a given event key with callback and target. @@ -317,7 +337,7 @@ export class CallbacksInvoker { const target = info.target; // Pre off once callbacks to avoid influence on logic in callback if (info.once) { - this.off(key, callback, target); + this._thisProxy.off(key, callback, target); } if (target) { callback.call(target, arg0, arg1, arg2, arg3, arg4); diff --git a/cocos/core/event/eventify.ts b/cocos/core/event/eventify.ts index 90b3bd3c7f..3d8d09718e 100644 --- a/cocos/core/event/eventify.ts +++ b/cocos/core/event/eventify.ts @@ -128,7 +128,7 @@ export interface IEventified { */ export function Eventify (base: Constructor): Constructor { return class extends (base as unknown as any) implements IEventified { - private _callbacksInvoker: CallbacksInvoker = new CallbacksInvoker(); + private _callbacksInvoker: CallbacksInvoker = new CallbacksInvoker(this); public hasEventListener (type: string, callback?: Function, target?: object): boolean { return this._callbacksInvoker.hasEventListener(type, callback, target); From ec8450459d50834cc49ec161ba5710ad75672769 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Fri, 29 May 2020 14:06:52 +0800 Subject: [PATCH 54/74] Revert "Solve once-off problem (#6773)" (#6780) This reverts commit a0cc2585b611e91ee3513a5ba0e6d47ff076ac53. --- cocos/core/event/callbacks-invoker.ts | 22 +--------------------- cocos/core/event/eventify.ts | 2 +- 2 files changed, 2 insertions(+), 22 deletions(-) diff --git a/cocos/core/event/callbacks-invoker.ts b/cocos/core/event/callbacks-invoker.ts index 27f30ebb7b..fa92f1393d 100644 --- a/cocos/core/event/callbacks-invoker.ts +++ b/cocos/core/event/callbacks-invoker.ts @@ -164,26 +164,6 @@ export interface ICallbackTable { export class CallbacksInvoker { public _callbackTable: ICallbackTable = createMap(true); - /** - * After "once subscription" is triggered, - * the corresponding `CallbacksInvoker.prototype.off` was going to be called - * as a matter of course. - * But `Eventify(base).prototype.off` was not called though it should be. - * This is because `Eventify(base)` use `CallbacksInvoker` in a composition way. - * We do this HACK here to solve this problem temporarily. - */ - private _thisProxy: { - off: CallbacksInvoker['off']; - }; - - /** - * - * @param thisProxy Note, this is for special use case. DO NOT take to use this parameter. - */ - constructor (thisProxy?: CallbacksInvoker['_thisProxy']) { - this._thisProxy = thisProxy ?? this; - } - /** * @zh 向一个事件名注册一个新的事件监听器,包含回调函数和调用者 * @en Register an event listener to a given event key with callback and target. @@ -337,7 +317,7 @@ export class CallbacksInvoker { const target = info.target; // Pre off once callbacks to avoid influence on logic in callback if (info.once) { - this._thisProxy.off(key, callback, target); + this.off(key, callback, target); } if (target) { callback.call(target, arg0, arg1, arg2, arg3, arg4); diff --git a/cocos/core/event/eventify.ts b/cocos/core/event/eventify.ts index 3d8d09718e..90b3bd3c7f 100644 --- a/cocos/core/event/eventify.ts +++ b/cocos/core/event/eventify.ts @@ -128,7 +128,7 @@ export interface IEventified { */ export function Eventify (base: Constructor): Constructor { return class extends (base as unknown as any) implements IEventified { - private _callbacksInvoker: CallbacksInvoker = new CallbacksInvoker(this); + private _callbacksInvoker: CallbacksInvoker = new CallbacksInvoker(); public hasEventListener (type: string, callback?: Function, target?: object): boolean { return this._callbacksInvoker.hasEventListener(type, callback, target); From afa7f892bbd0b9aea2372fac751a963ed28e8d78 Mon Sep 17 00:00:00 2001 From: "jiaxin.lai" Date: Fri, 29 May 2020 14:26:34 +0800 Subject: [PATCH 55/74] activate when not awake (#6781) * activate when not awake * cannon too --- cocos/physics/ammo/ammo-rigid-body.ts | 24 +++++++++---------- cocos/physics/cannon/cannon-rigid-body.ts | 28 +++++++++++------------ 2 files changed, 26 insertions(+), 26 deletions(-) diff --git a/cocos/physics/ammo/ammo-rigid-body.ts b/cocos/physics/ammo/ammo-rigid-body.ts index c6f35205c7..305d4bf006 100644 --- a/cocos/physics/ammo/ammo-rigid-body.ts +++ b/cocos/physics/ammo/ammo-rigid-body.ts @@ -78,17 +78,17 @@ export class AmmoRigidBody implements IRigidBody { } else { this.impl.setAngularFactor(cocos2AmmoVec3(this._btVec3_0, this._rigidBody.angularFactor)); } - if (this.isSleeping) this.impl.activate(); + if (!this.isAwake) this.impl.activate(); } setLinearFactor (value: IVec3Like) { this.impl.setLinearFactor(cocos2AmmoVec3(this._btVec3_0, value)); - if (this.isSleeping) this.impl.activate(); + if (!this.isAwake) this.impl.activate(); } setAngularFactor (value: IVec3Like) { this.impl.setAngularFactor(cocos2AmmoVec3(this._btVec3_0, value)); - if (this.isSleeping) this.impl.activate(); + if (!this.isAwake) this.impl.activate(); } setAllowSleep (v: boolean) { @@ -97,7 +97,7 @@ export class AmmoRigidBody implements IRigidBody { } else { this.impl.forceActivationState(AmmoCollisionObjectStates.DISABLE_DEACTIVATION); } - if (this.isSleeping) this.impl.activate(); + if (!this.isAwake) this.impl.activate(); } get isEnabled () { return this._isEnabled; } @@ -183,7 +183,7 @@ export class AmmoRigidBody implements IRigidBody { } setLinearVelocity (value: Vec3): void { - if (this.isSleeping) this.impl.activate(); + if (!this.isAwake) this.impl.activate(); cocos2AmmoVec3(this.impl.getLinearVelocity(), value); } @@ -192,7 +192,7 @@ export class AmmoRigidBody implements IRigidBody { } setAngularVelocity (value: Vec3): void { - if (this.isSleeping) this.impl.activate(); + if (!this.isAwake) this.impl.activate(); cocos2AmmoVec3(this.impl.getAngularVelocity(), value); } @@ -200,7 +200,7 @@ export class AmmoRigidBody implements IRigidBody { applyLocalForce (force: Vec3, rel_pos?: Vec3): void { this._sharedBody.syncSceneToPhysics(); - if (this.isSleeping) this.impl.activate(); + if (!this.isAwake) this.impl.activate(); const quat = this._sharedBody.node.worldRotation; const v = Vec3.transformQuat(v3_0, force, quat); const rp = rel_pos ? Vec3.transformQuat(v3_1, rel_pos, quat) : Vec3.ZERO; @@ -212,14 +212,14 @@ export class AmmoRigidBody implements IRigidBody { applyLocalTorque (torque: Vec3): void { this._sharedBody.syncSceneToPhysics(); - if (this.isSleeping) this.impl.activate(); + if (!this.isAwake) this.impl.activate(); Vec3.transformQuat(v3_0, torque, this._sharedBody.node.worldRotation); this.impl.applyTorque(cocos2AmmoVec3(this._btVec3_0, v3_0)); } applyLocalImpulse (impulse: Vec3, rel_pos?: Vec3): void { this._sharedBody.syncSceneToPhysics(); - if (this.isSleeping) this.impl.activate(); + if (!this.isAwake) this.impl.activate(); const quat = this._sharedBody.node.worldRotation; const v = Vec3.transformQuat(v3_0, impulse, quat); const rp = rel_pos ? Vec3.transformQuat(v3_1, rel_pos, quat) : Vec3.ZERO; @@ -231,7 +231,7 @@ export class AmmoRigidBody implements IRigidBody { applyForce (force: Vec3, rel_pos?: Vec3): void { this._sharedBody.syncSceneToPhysics(); - if (this.isSleeping) this.impl.activate(); + if (!this.isAwake) this.impl.activate(); const rp = rel_pos ? rel_pos : Vec3.ZERO; this.impl.applyForce( cocos2AmmoVec3(this._btVec3_0, force), @@ -241,13 +241,13 @@ export class AmmoRigidBody implements IRigidBody { applyTorque (torque: Vec3): void { this._sharedBody.syncSceneToPhysics(); - if (this.isSleeping) this.impl.activate(); + if (!this.isAwake) this.impl.activate(); this.impl.applyTorque(cocos2AmmoVec3(this._btVec3_0, torque)); } applyImpulse (impulse: Vec3, rel_pos?: Vec3): void { this._sharedBody.syncSceneToPhysics(); - if (this.isSleeping) this.impl.activate(); + if (!this.isAwake) this.impl.activate(); const rp = rel_pos ? rel_pos : Vec3.ZERO; this.impl.applyImpulse( cocos2AmmoVec3(this._btVec3_0, impulse), diff --git a/cocos/physics/cannon/cannon-rigid-body.ts b/cocos/physics/cannon/cannon-rigid-body.ts index aff71b6deb..d875e3650b 100644 --- a/cocos/physics/cannon/cannon-rigid-body.ts +++ b/cocos/physics/cannon/cannon-rigid-body.ts @@ -32,7 +32,7 @@ export class CannonRigidBody implements IRigidBody { setAllowSleep (v: boolean) { this.impl.allowSleep = v; - if (this.impl.isSleeping()) this.impl.wakeUp(); + if (!this.impl.isAwake()) this.impl.wakeUp(); } setMass (value: number) { @@ -44,7 +44,7 @@ export class CannonRigidBody implements IRigidBody { } this.impl.updateMassProperties(); - if (this.impl.isSleeping()) this.impl.wakeUp(); + if (!this.impl.isAwake()) this.impl.wakeUp(); } setIsKinematic (value: boolean) { @@ -62,7 +62,7 @@ export class CannonRigidBody implements IRigidBody { fixRotation (value: boolean) { this.impl.fixedRotation = value; this.impl.updateMassProperties(); - if (this.impl.isSleeping()) this.impl.wakeUp(); + if (!this.impl.isAwake()) this.impl.wakeUp(); } setLinearDamping (value: number) { @@ -75,17 +75,17 @@ export class CannonRigidBody implements IRigidBody { useGravity (value: boolean) { this.impl.useGravity = value; - if (this.impl.isSleeping()) this.impl.wakeUp(); + if (!this.impl.isAwake()) this.impl.wakeUp(); } setLinearFactor (value: IVec3Like) { Vec3.copy(this.impl.linearFactor, value); - if (this.impl.isSleeping()) this.impl.wakeUp(); + if (!this.impl.isAwake()) this.impl.wakeUp(); } setAngularFactor (value: IVec3Like) { Vec3.copy(this.impl.angularFactor, value); - if (this.impl.isSleeping()) this.impl.wakeUp(); + if (!this.impl.isAwake()) this.impl.wakeUp(); } get impl () { @@ -163,7 +163,7 @@ export class CannonRigidBody implements IRigidBody { } setLinearVelocity (value: Vec3): void { - if (this.impl.isSleeping()) this.impl.wakeUp(); + if (!this.impl.isAwake()) this.impl.wakeUp(); Vec3.copy(this.impl.velocity, value); } @@ -173,47 +173,47 @@ export class CannonRigidBody implements IRigidBody { } setAngularVelocity (value: Vec3): void { - if (this.impl.isSleeping()) this.impl.wakeUp(); + if (!this.impl.isAwake()) this.impl.wakeUp(); Vec3.copy(this.impl.angularVelocity, value); } applyForce (force: Vec3, worldPoint?: Vec3) { this._sharedBody.syncSceneToPhysics(); - if (this.impl.isSleeping()) this.impl.wakeUp(); + if (!this.impl.isAwake()) this.impl.wakeUp(); if (worldPoint == null) worldPoint = Vec3.ZERO; this.impl.applyForce(Vec3.copy(v3_cannon0, force), Vec3.copy(v3_cannon1, worldPoint)); } applyImpulse (impulse: Vec3, worldPoint?: Vec3) { this._sharedBody.syncSceneToPhysics(); - if (this.impl.isSleeping()) this.impl.wakeUp(); + if (!this.impl.isAwake()) this.impl.wakeUp(); if (worldPoint == null) worldPoint = Vec3.ZERO; this.impl.applyImpulse(Vec3.copy(v3_cannon0, impulse), Vec3.copy(v3_cannon1, worldPoint)); } applyLocalForce (force: Vec3, localPoint?: Vec3): void { this._sharedBody.syncSceneToPhysics(); - if (this.impl.isSleeping()) this.impl.wakeUp(); + if (!this.impl.isAwake()) this.impl.wakeUp(); if (localPoint == null) localPoint = Vec3.ZERO; this.impl.applyLocalForce(Vec3.copy(v3_cannon0, force), Vec3.copy(v3_cannon1, localPoint)); } applyLocalImpulse (impulse: Vec3, localPoint?: Vec3): void { this._sharedBody.syncSceneToPhysics(); - if (this.impl.isSleeping()) this.impl.wakeUp(); + if (!this.impl.isAwake()) this.impl.wakeUp(); if (localPoint == null) localPoint = Vec3.ZERO; this.impl.applyLocalImpulse(Vec3.copy(v3_cannon0, impulse), Vec3.copy(v3_cannon1, localPoint)); } applyTorque (torque: Vec3): void { this._sharedBody.syncSceneToPhysics(); - if (this.impl.isSleeping()) this.impl.wakeUp(); + if (!this.impl.isAwake()) this.impl.wakeUp(); Vec3.add(this.impl.torque, this.impl.torque, torque); } applyLocalTorque (torque: Vec3): void { this._sharedBody.syncSceneToPhysics(); - if (this.impl.isSleeping()) this.impl.wakeUp(); + if (!this.impl.isAwake()) this.impl.wakeUp(); Vec3.copy(v3_cannon0, torque); this.impl.vectorToWorldFrame(v3_cannon0, v3_cannon0); Vec3.add(this.impl.torque, this.impl.torque, v3_cannon0); From 91a41a2c61b8e977a9ab843626d9e2048d36cb16 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 29 May 2020 14:26:50 +0800 Subject: [PATCH 56/74] Safe emit game events to avoid editor startup failure (#6779) * Safe emit game events so that it won't break editor startup * Correct API * remove useless indexof --- cocos/core/event/callbacks-invoker.ts | 2 +- cocos/core/game.ts | 22 ++++++++++++++++++---- cocos/core/utils/array.ts | 18 ------------------ 3 files changed, 19 insertions(+), 23 deletions(-) diff --git a/cocos/core/event/callbacks-invoker.ts b/cocos/core/event/callbacks-invoker.ts index fa92f1393d..8200e1a420 100644 --- a/cocos/core/event/callbacks-invoker.ts +++ b/cocos/core/event/callbacks-invoker.ts @@ -226,7 +226,7 @@ export class CallbacksInvoker { * @en Removes all callbacks registered in a certain event type or all callbacks registered with a certain target * @param keyOrTarget - The event type or target with which the listeners will be removed */ - public removeAll (keyOrTarget?: string | Object) { + public removeAll (keyOrTarget: string | Object) { if (typeof keyOrTarget === 'string') { // remove by key const list = this._callbackTable[keyOrTarget]; diff --git a/cocos/core/game.ts b/cocos/core/game.ts index a96eba919c..44fba1127c 100644 --- a/cocos/core/game.ts +++ b/cocos/core/game.ts @@ -631,7 +631,7 @@ export class Game extends EventTarget { else { this.setRenderPipeline(asset); } - this.emit(Game.EVENT_GAME_INITED); + this._safeEmit(Game.EVENT_GAME_INITED); if (useSplash) { splashScreen.loadFinish = true; } @@ -641,7 +641,7 @@ export class Game extends EventTarget { }); } else { - this.emit(Game.EVENT_GAME_INITED); + this._safeEmit(Game.EVENT_GAME_INITED); if (useSplash) { splashScreen.loadFinish = true; } @@ -719,7 +719,7 @@ export class Game extends EventTarget { // Log engine version console.log('Cocos Creator 3D v' + cc.ENGINE_VERSION); - this.emit(Game.EVENT_ENGINE_INITED); + this._safeEmit(Game.EVENT_ENGINE_INITED); this._inited = true; } @@ -1007,7 +1007,21 @@ export class Game extends EventTarget { } this._rendererInitialized = true; - this.emit(Game.EVENT_RENDERER_INITED); + this._safeEmit(Game.EVENT_RENDERER_INITED); + } + + private _safeEmit (event) { + if (EDITOR) { + try { + this.emit(event); + } + catch (e) { + console.warn(e); + } + } + else { + this.emit(event); + } } } diff --git a/cocos/core/utils/array.ts b/cocos/core/utils/array.ts index 4277ee56ae..acef5fa63f 100644 --- a/cocos/core/utils/array.ts +++ b/cocos/core/utils/array.ts @@ -113,24 +113,6 @@ export function appendObjectsAt (array: T[], addObjs: T[], index: number) { return array; } -/** - * Exact same function as Array.prototype.indexOf.
- * HACK: ugliy hack for Baidu mobile browser compatibility, - * stupid Baidu guys modify Array.prototype.indexOf for all pages loaded, - * their version changes strict comparison to non-strict comparison, - * it also ignores the second parameter of the original API, and this will cause event handler enter infinite loop.
- * Baidu developers, if you ever see this documentation, - * here is the standard: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf, Seriously! - * - * @method indexOf - * @param searchElement - Element to locate in the array. - * @param [fromIndex=0] - The index to start the search at - * @return the first index at which a given element can be found in the array, or -1 if it is not present. - */ -export function indexOf (array: T[], searchElement: T, fromIndex?: number) { - return Array.prototype.indexOf.call(array, [searchElement, fromIndex]); -} - /** * Determines whether the array contains a specific value. */ From 2a2a56ad2b9930c33e7301180a0be8798144f525 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Fri, 29 May 2020 15:20:49 +0800 Subject: [PATCH 57/74] Solve the "once-off" problem (#6782) * Solve the "once-off" problem * Revert CallbacksInvoker * Update * Optimize --- cocos/core/event/eventify.ts | 45 ++++++++++++++++++++---------------- tests/core/eventify.test.ts | 38 ++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+), 20 deletions(-) create mode 100644 tests/core/eventify.test.ts diff --git a/cocos/core/event/eventify.ts b/cocos/core/event/eventify.ts index 90b3bd3c7f..cc1d880eb0 100644 --- a/cocos/core/event/eventify.ts +++ b/cocos/core/event/eventify.ts @@ -4,11 +4,19 @@ import { fastRemove } from '../utils/array'; import { CallbacksInvoker } from './callbacks-invoker'; +import { createMap } from '../utils/js'; type Constructor = new (...args: any[]) => T; type EventType = string; +const { + prototype: { + on: callbacksInvokerOn, + off: callbacksInvokerOff, + }, +} = CallbacksInvoker; + /** * @zh * 实现该接口的对象具有处理事件的能力。 @@ -127,16 +135,12 @@ export interface IEventified { * ``` */ export function Eventify (base: Constructor): Constructor { - return class extends (base as unknown as any) implements IEventified { - private _callbacksInvoker: CallbacksInvoker = new CallbacksInvoker(); - - public hasEventListener (type: string, callback?: Function, target?: object): boolean { - return this._callbacksInvoker.hasEventListener(type, callback, target); - } - + class Eventified extends (base as unknown as any) { + private _callbackTable = createMap(true); + public on (type: EventType, callback: Callback, target?: object) { if (!this.hasEventListener(type, callback, target)) { - this._callbacksInvoker.on(type, callback, target); + callbacksInvokerOn.call(this, type, callback, target); if (target) { this._registerThisIntoTarget(target); } @@ -146,7 +150,7 @@ export function Eventify (base: Constructor): Constructor (type: EventType, callback: Callback, target?: object) { if (!this.hasEventListener(type, callback, target)) { - this._callbacksInvoker.on(type, callback, target, true); + callbacksInvokerOn.call(this, type, callback, target, true); if (target) { this._registerThisIntoTarget(target); } @@ -158,7 +162,7 @@ export function Eventify (base: Constructor): Constructor (base: Constructor): Constructor (base: Constructor): Constructor { + class Base { + public _nickName: string; + + constructor(nickName: string) { + this._nickName = nickName; + } + + public getNickName() { + return this._nickName; + } + } + + const hookOnOff = jest.fn(() => {}); + + class Derived extends Eventify(Base) { + public off(type: string, callback?: Function, target?: object) { + super.off(type, callback, target); + hookOnOff(); + } + } + + const nickName = 'Jack'; + const derived = new Derived(nickName); + expect(derived.getNickName()).toEqual(nickName); + + const eventName = 'test'; + const eventCallback = jest.fn(() => {}); + + derived.off(eventName, eventCallback); + expect(hookOnOff).toBeCalledTimes(1); + + derived.once(eventName, eventCallback); + derived.emit(eventName); + expect(hookOnOff).toBeCalledTimes(2); +}); \ No newline at end of file From 0d01f9867eebf89802d8855a370ce11adc62b88a Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 29 May 2020 15:26:11 +0800 Subject: [PATCH 58/74] Fix Node & Scene incompatible issue (#6786) --- cocos/core/scene-graph/base-node.ts | 36 ++++++++++++++--------------- 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/cocos/core/scene-graph/base-node.ts b/cocos/core/scene-graph/base-node.ts index 944df3a365..2031fb8d2e 100644 --- a/cocos/core/scene-graph/base-node.ts +++ b/cocos/core/scene-graph/base-node.ts @@ -39,6 +39,8 @@ import * as js from '../utils/js'; import { baseNodePolyfill } from './base-node-dev'; import { NodeEventProcessor } from './node-event-processor'; import { DEV, DEBUG, EDITOR } from 'internal:constants'; +import { Node } from './node'; +import { Scene } from './scene'; type Constructor = new (...args: any[]) => T; @@ -404,18 +406,19 @@ export class BaseNode extends CCObject implements ISchedulable { * @en Set parent of the node. * @zh 设置该节点的父节点。 */ - public setParent (value: this | null, keepWorldTransform: boolean = false) { + public setParent (value: this | Scene | null, keepWorldTransform: boolean = false) { if (this._parent === value) { return; } const oldParent = this._parent; + const newParent = value as this; if (DEBUG && oldParent && // Change parent when old parent desactivating or activating (oldParent._objFlags & ChangingState)) { errorID(3821); } - this._parent = value; + this._parent = newParent; // Reset sibling index this._siblingIndex = 0; @@ -425,14 +428,14 @@ export class BaseNode extends CCObject implements ISchedulable { this.emit(SystemEventType.PARENT_CHANGED, oldParent); } - if (value) { - if (DEBUG && (value._objFlags & Deactivating)) { + if (newParent) { + if (DEBUG && (newParent._objFlags & Deactivating)) { errorID(3821); } - value._children.push(this); - this._siblingIndex = value._children.length - 1; - if (value.emit) { - value.emit(SystemEventType.CHILD_ADDED, this); + newParent._children.push(this); + this._siblingIndex = newParent._children.length - 1; + if (newParent.emit) { + newParent.emit(SystemEventType.CHILD_ADDED, this); } } if (oldParent) { @@ -524,23 +527,20 @@ export class BaseNode extends CCObject implements ISchedulable { } return lastNode; } - /** * @en Add a child to the current node, it will be pushed to the end of [[children]] array. * @zh 添加一个子节点,它会被添加到 [[children]] 数组的末尾。 * @param child - the child node to be added */ - public addChild (child: this): void { - + public addChild (child: this | Node): void { if (DEV && !(child instanceof cc._BaseNode)) { return errorID(1634, cc.js.getClassName(child)); } cc.assertID(child, 1606); - cc.assertID(child._parent === null, 1605); + cc.assertID((child as this)._parent === null, 1605); // invokes the parent setter - child.setParent(this); - + (child as this).setParent(this); } /** @@ -553,7 +553,7 @@ export class BaseNode extends CCObject implements ISchedulable { * node.insertChild(child, 2); * ``` */ - public insertChild (child: this, siblingIndex: number) { + public insertChild (child: this | Node, siblingIndex: number) { child.parent = this; child.setSiblingIndex(siblingIndex); } @@ -719,8 +719,8 @@ export class BaseNode extends CCObject implements ISchedulable { * @zh 移除节点中指定的子节点。 * @param child - The child node which will be removed. */ - public removeChild (child: this) { - if (this._children.indexOf(child) > -1) { + public removeChild (child: this | Node) { + if (this._children.indexOf(child as this) > -1) { // invoke the parent setter child.parent = null; } @@ -747,7 +747,7 @@ export class BaseNode extends CCObject implements ISchedulable { * @zh 是否是指定节点的子节点? * @return True if this node is a child, deep child or identical to the given node. */ - public isChildOf (parent: this | null): boolean { + public isChildOf (parent: this | Scene | null): boolean { let child: BaseNode | null = this; do { if (child === parent) { From c7fb63b1ecaf8f78f1d0a2518908c2ee0b9f976d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leslie=20Leigh=20=28=E6=9D=8E=E7=9A=84=E5=BA=8F=29?= Date: Fri, 29 May 2020 18:38:51 +0800 Subject: [PATCH 59/74] Mark event-related API of AnimationState as deprecated (#6772) * Add 'last-frame-arrived' event; Optimize animation state events * Doc * Rename 'last-frame-arrived' -> 'iteration-end' * Revert refine * Doc * Revert `iteration-end` * CI --- cocos/core/animation/animation-component.ts | 49 +----- cocos/core/animation/animation-manager.ts | 14 +- cocos/core/animation/animation-state.ts | 161 +++++++++++--------- tests/animation/animation-events.test.ts | 18 ++- 4 files changed, 111 insertions(+), 131 deletions(-) diff --git a/cocos/core/animation/animation-component.ts b/cocos/core/animation/animation-component.ts index 9cc4b3790d..7fac4010d9 100644 --- a/cocos/core/animation/animation-component.ts +++ b/cocos/core/animation/animation-component.ts @@ -33,50 +33,11 @@ import { Eventify } from '../event/eventify'; import { warnID } from '../platform/debug'; import * as ArrayUtils from '../utils/array'; import { createMap } from '../utils/js-typed'; -import { ccenum } from '../value-types/enum'; import { AnimationClip } from './animation-clip'; -import { AnimationState } from './animation-state'; +import { AnimationState, EventType } from './animation-state'; import { CrossFade } from './cross-fade'; import { EDITOR, TEST } from 'internal:constants'; -/** - * @en The event type supported by Animation - * @zh Animation 支持的事件类型。 - */ -export enum EventType { - /** - * @en Emit when begin playing animation - * @zh 开始播放时触发。 - */ - PLAY = 'play', - /** - * @en Emit when stop playing animation - * @zh 停止播放时触发。 - */ - STOP = 'stop', - /** - * @en Emit when pause animation - * @zh 暂停播放时触发。 - */ - PAUSE = 'pause', - /** - * @en Emit when resume animation - * @zh 恢复播放时触发。 - */ - RESUME = 'resume', - /** - * @en If animation repeat count is larger than 1, emit when animation play to the last frame - * @zh 假如动画循环次数大于 1,当动画播放到最后一帧时触发。 - */ - LASTFRAME = 'lastframe', - /** - * @en Emit when finish playing animation - * @zh 动画播放完成时触发。 - */ - FINISHED = 'finished', -} -ccenum(EventType); - /** * 动画组件管理动画状态来控制动画的播放。 * 它提供了方便的接口用来预创建指定动画剪辑的动画状态,并提供了一系列事件: @@ -317,7 +278,7 @@ export class AnimationComponent extends Eventify(Component) { public removeState (name: string) { const state = this._nameToState[name]; if (state) { - state.allowLastFrameEvent = false; + state.allowLastFrameEvent(false); state.stop(); delete this._nameToState[name]; } @@ -452,7 +413,7 @@ export class AnimationComponent extends Eventify(Component) { protected _doCreateState (clip: AnimationClip, name: string) { const state = this._createState(clip, name); state._setEventTarget(this); - state.allowLastFrameEvent = this.hasEventListener(EventType.LASTFRAME); + state.allowLastFrameEvent(this.hasEventListener(EventType.LASTFRAME)); if (this.node) { state.initialize(this.node); } @@ -490,7 +451,7 @@ export class AnimationComponent extends Eventify(Component) { private _syncAllowLastFrameEvent () { if (this.hasEventListener(EventType.LASTFRAME)) { for (const stateName in this._nameToState) { - this._nameToState[stateName].allowLastFrameEvent = true; + this._nameToState[stateName].allowLastFrameEvent(true); } } } @@ -498,7 +459,7 @@ export class AnimationComponent extends Eventify(Component) { private _syncDisallowLastFrameEvent () { if (!this.hasEventListener(EventType.LASTFRAME)) { for (const stateName in this._nameToState) { - this._nameToState[stateName].allowLastFrameEvent = false; + this._nameToState[stateName].allowLastFrameEvent(false); } } } diff --git a/cocos/core/animation/animation-manager.ts b/cocos/core/animation/animation-manager.ts index 74bc328d90..2e71c8cdda 100644 --- a/cocos/core/animation/animation-manager.ts +++ b/cocos/core/animation/animation-manager.ts @@ -29,7 +29,11 @@ export class AnimationManager extends System { public static ID = 'animation'; private _anims = new MutableForwardIterator([]); - private _delayEvents: {target: Node; func: string; args: any[]}[] = []; + private _delayEvents: { + fn: Function; + thisArg: any; + args: any[]; + }[] = []; private _blendStateBuffer: BlendStateBuffer = new BlendStateBuffer(); private _crossFades: CrossFade[] = []; private _sockets: ISocketData[] = []; @@ -66,7 +70,7 @@ export class AnimationManager extends System { for (let i = 0, l = _delayEvents.length; i < l; i++) { const event = _delayEvents[i]; - event.target[event.func].apply(event.target, event.args); + event.fn.apply(event.thisArg, event.args); } _delayEvents.length = 0; } @@ -91,10 +95,10 @@ export class AnimationManager extends System { } } - public pushDelayEvent (target: Node, func: string, args: any[]) { + public pushDelayEvent (fn: Function, thisArg: any, args: any[]) { this._delayEvents.push({ - target, - func, + fn, + thisArg, args, }); } diff --git a/cocos/core/animation/animation-state.ts b/cocos/core/animation/animation-state.ts index e0ff6ef7d5..33c4a0fe3e 100644 --- a/cocos/core/animation/animation-state.ts +++ b/cocos/core/animation/animation-state.ts @@ -27,7 +27,6 @@ * @category animation */ -import { EventArgumentsOf, EventCallbackOf } from '../event/defines'; import { Node } from '../scene-graph/node'; import { AnimationClip, IRuntimeCurve } from './animation-clip'; import { AnimCurve, RatioSampler } from './animation-curve'; @@ -37,22 +36,54 @@ import { WrapMode, WrapModeMask, WrappedInfo } from './types'; import { EDITOR } from 'internal:constants'; import { HierarchyPath, evaluatePath } from './target-path'; import { BlendStateBuffer, createBlendStateWriter, IBlendStateWriter } from './skeletal-animation-blending'; +import { ccenum } from '../value-types/enum'; -enum PropertySpecialization { - NodePosition, - NodeScale, - NodeRotation, - None, +/** + * @en The event type supported by Animation + * @zh Animation 支持的事件类型。 + */ +export enum EventType { + /** + * @en Emit when begin playing animation + * @zh 开始播放时触发。 + */ + PLAY = 'play', + /** + * @en Emit when stop playing animation + * @zh 停止播放时触发。 + */ + STOP = 'stop', + /** + * @en Emit when pause animation + * @zh 暂停播放时触发。 + */ + PAUSE = 'pause', + /** + * @en Emit when resume animation + * @zh 恢复播放时触发。 + */ + RESUME = 'resume', + + /** + * @en If animation repeat count is larger than 1, emit when animation play to the last frame. + * @zh 假如动画循环次数大于 1,当动画播放到最后一帧时触发。 + */ + LASTFRAME = 'lastframe', + + /** + * @en Triggered when finish playing animation. + * @zh 动画完成播放时触发。 + */ + FINISHED = 'finished', } +ccenum(EventType); export class ICurveInstance { public commonTargetIndex?: number; private _curve: AnimCurve; private _boundTarget: IBoundTarget; - private _rootTarget: any; private _rootTargetProperty?: string; - private _cached?: any[]; private _curveDetail: Omit; constructor ( @@ -63,7 +94,6 @@ export class ICurveInstance { this._curveDetail = runtimeCurve; this._boundTarget = boundTarget; - this._rootTarget = target; } public applySample (ratio: number, index: number, lerpRequired: boolean, samplerResultCache, weight: number) { @@ -124,15 +154,6 @@ function makeSamplerSharedGroup (sampler: RatioSampler | null): ISamplerSharedGr const InvalidIndex = -1; -export interface IAnimationEventDefinitionMap { - 'finished': (animationState: AnimationState) => void; - 'lastframe': (animationState: AnimationState) => void; - 'play': (animationState: AnimationState) => void; - 'pause': (animationState: AnimationState) => void; - 'resume': (animationState: AnimationState) => void; - 'stop': (animationState: AnimationState) => void; -} - /** * @en * The AnimationState gives full control over animation playback process. @@ -239,12 +260,6 @@ export class AnimationState extends Playable { this._delayTime = this._delay = value; } - /** - * @en The curves list. - * @zh 曲线列表。 - */ - // public curves: AnimCurve[] = []; - // http://www.w3.org/TR/web-animations/#idl-def-AnimationTiming /** @@ -275,14 +290,6 @@ export class AnimationState extends Playable { public frameRate = 0; - /** - * @zh - * 是否允许触发 `LastFrame` 事件。 - * @en - * Whether `LastFrame` should be triggered. - */ - public allowLastFrameEvent = false; - protected _wrapMode = WrapMode.Normal; protected _repeatCount = 1; @@ -317,6 +324,7 @@ export class AnimationState extends Playable { private _blendStateBuffer: BlendStateBuffer | null = null; private _blendStateWriters: IBlendStateWriter[] = []; private _isBlendStateWriterInitialized = false; + private _allowLastFrame = false; constructor (clip: AnimationClip, name = '') { super(); @@ -419,60 +427,59 @@ export class AnimationState extends Playable { this._destroyBlendStateWriters(); } - public _emit (type, state) { - if (this._target && this._target.isValid) { - this._target.emit(type, type, state); - } - } - - public emit (type: K, ...args: EventArgumentsOf): void; - + /** + * @deprecated Since V1.1.1, animation states were no longer defined as event targets. + * To process animation events, use `AnimationComponent` instead. + */ public emit (...args: any[]) { - cc.director.getAnimationManager().pushDelayEvent(this, '_emit', args); + cc.director.getAnimationManager().pushDelayEvent(this._emit, this, args); } - public on (type: K, callback: EventCallbackOf, target?: any): void; - + /** + * @deprecated Since V1.1.1, animation states were no longer defined as event targets. + * To process animation events, use `AnimationComponent` instead. + */ public on (type: string, callback: Function, target?: any) { if (this._target && this._target.isValid) { - if (type === 'lastframe') { - this.allowLastFrameEvent = true; - } return this._target.on(type, callback, target); - } - else { + } else { return null; } } - public once (type: K, callback: EventCallbackOf, target?: any): void; - + /** + * @deprecated Since V1.1.1, animation states were no longer defined as event targets. + * To process animation events, use `AnimationComponent` instead. + */ public once (type: string, callback: Function, target?: any) { if (this._target && this._target.isValid) { - if (type === 'lastframe') { - this.allowLastFrameEvent = true; - } - return this._target.once(type, (event) => { - callback.call(target, event); - this.allowLastFrameEvent = false; - }); - } - else { + return this._target.once(type, callback, target); + } else { return null; } } + /** + * @deprecated Since V1.1.1, animation states were no longer defined as event targets. + * To process animation events, use `AnimationComponent` instead. + */ public off (type: string, callback: Function, target?: any) { if (this._target && this._target.isValid) { - if (type === 'lastframe') { - if (!this._target.hasEventListener(type)) { - this.allowLastFrameEvent = false; - } - } this._target.off(type, callback, target); } } + /** + * @zh + * 是否允许触发 `LastFrame` 事件。 + * @en + * Whether `LastFrame` should be triggered. + * @param allowed True if the last frame events may be triggered. + */ + public allowLastFrameEvent (allowed: boolean) { + this._allowLastFrame = allowed; + } + public _setEventTarget (target) { this._target = target; } @@ -612,7 +619,7 @@ export class AnimationState extends Playable { // sample const info = this.sample(); - if (this.allowLastFrameEvent) { + if (this._allowLastFrame) { let lastInfo; if (!this._lastWrapInfo) { lastInfo = this._lastWrapInfo = new WrappedInfo(info); @@ -621,7 +628,7 @@ export class AnimationState extends Playable { } if (this.repeatCount > 1 && ((info.iterations | 0) > (lastInfo.iterations | 0))) { - this.emit('lastframe', this); + this.emit(EventType.LASTFRAME, this); } lastInfo.set(info); @@ -629,7 +636,7 @@ export class AnimationState extends Playable { if (info.stopped) { this.stop(); - this.emit('finished', this); + this.emit(EventType.FINISHED, this); } } @@ -646,13 +653,13 @@ export class AnimationState extends Playable { } } - if (this.allowLastFrameEvent) { + if (this._allowLastFrame) { if (this._lastIterations === undefined) { this._lastIterations = ratio; } if ((this.time > 0 && this._lastIterations > ratio) || (this.time < 0 && this._lastIterations < ratio)) { - this.emit('lastframe', this); + this.emit(EventType.LASTFRAME, this); } this._lastIterations = ratio; @@ -666,24 +673,24 @@ export class AnimationState extends Playable { this.setTime(0); this._delayTime = this._delay; this._onReplayOrResume(); - this.emit('play', this); + this.emit(EventType.PLAY, this); } protected onStop () { if (!this.isPaused) { this._onPauseOrStop(); } - this.emit('stop', this); + this.emit(EventType.STOP, this); } protected onResume () { this._onReplayOrResume(); - this.emit('resume', this); + this.emit(EventType.RESUME, this); } protected onPause () { this._onPauseOrStop(); - this.emit('pause', this); + this.emit(EventType.PAUSE, this); } protected _sampleCurves (ratio: number) { @@ -817,13 +824,19 @@ export class AnimationState extends Playable { lastIndex += direction; - cc.director.getAnimationManager().pushDelayEvent(this, '_fireEvent', [lastIndex]); + cc.director.getAnimationManager().pushDelayEvent(this._fireEvent, this, [lastIndex]); } while (lastIndex !== eventIndex && lastIndex > -1 && lastIndex < length); } this._lastWrapInfoEvent.set(wrapInfo); } + private _emit (type, state) { + if (this._target && this._target.isValid) { + this._target.emit(type, type, state); + } + } + private _fireEvent (index: number) { if (!this._targetNode || !this._targetNode.isValid) { return; diff --git a/tests/animation/animation-events.test.ts b/tests/animation/animation-events.test.ts index 31d07a536c..ce36e32b70 100644 --- a/tests/animation/animation-events.test.ts +++ b/tests/animation/animation-events.test.ts @@ -7,8 +7,8 @@ test('Animation events(general)', () => { removeAnimation: () => { }, addCrossFade: () => { }, removeCrossFade: () => { }, - pushDelayEvent: (target: Node, func: string, args: any[]) => { - target[func].apply(target, args); + pushDelayEvent: (fn: Function, thisArg: any, args: any[]) => { + fn.apply(thisArg, args); }, }; }); @@ -116,30 +116,32 @@ test('Animation event(last-frame event optimization)', () => { const handler1 = () => {}; const handler2 = () => {}; - expect(initialStates.every((state) => !state.allowLastFrameEvent)).toBeTruthy(); + const isLastFrameEventAllowed = (state: AnimationState) => (state as any)['_allowLastFrame']; + + expect(initialStates.every(state => !isLastFrameEventAllowed(state))).toBeTruthy(); animationComponent.on(AnimationComponent.EventType.LASTFRAME, handler1); // After subscribe the last-frame event, all states should have `allowLastFrameEvent` set to `true`. - expect(initialStates.every((state) => state.allowLastFrameEvent)).toBeTruthy(); + expect(initialStates.every(isLastFrameEventAllowed)).toBeTruthy(); animationComponent.on(AnimationComponent.EventType.LASTFRAME, handler2); // Should no problem. - expect(initialStates.every((state) => state.allowLastFrameEvent)).toBeTruthy(); + expect(initialStates.every(isLastFrameEventAllowed)).toBeTruthy(); animationComponent.off(AnimationComponent.EventType.LASTFRAME, handler2); // Now we unsubscribe one, but this should still true. - expect(initialStates.every((state) => state.allowLastFrameEvent)).toBeTruthy(); + expect(initialStates.every(isLastFrameEventAllowed)).toBeTruthy(); animationComponent.off(AnimationComponent.EventType.LASTFRAME, handler1); // All states should have `allowLastFrameEvent` set to `false` // if no any subscribe on 'last-frame' event. - expect(initialStates.every((state) => !state.allowLastFrameEvent)).toBeTruthy(); + expect(initialStates.every(state => !isLastFrameEventAllowed(state))).toBeTruthy(); animationComponent.on(AnimationComponent.EventType.LASTFRAME, handler1); // The newly added state should automatically have `allowLastFrameEvent` set to `true`. const newState = animationComponent.createState(createTestClip('clip-new')); // The newly added state should also have `allowLastFrameEvent` set to `true`. - expect(newState.allowLastFrameEvent).toBeTruthy(); + expect(isLastFrameEventAllowed(newState)).toBeTruthy(); }); function createTestAnimationComponent() { From 2b05eac155a71d311668bbe44e212d271c1e0a97 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Fri, 29 May 2020 19:08:34 +0800 Subject: [PATCH 60/74] should unbind VAO before unbind VB/IBs (#6788) --- cocos/core/gfx/webgl/webgl-commands.ts | 7 +++---- cocos/core/gfx/webgl2/webgl2-commands.ts | 15 +++++++++++---- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/cocos/core/gfx/webgl/webgl-commands.ts b/cocos/core/gfx/webgl/webgl-commands.ts index 822a98bca0..3d9a0f0b3e 100644 --- a/cocos/core/gfx/webgl/webgl-commands.ts +++ b/cocos/core/gfx/webgl/webgl-commands.ts @@ -1515,6 +1515,9 @@ export function WebGLCmdFuncBeginRenderPass ( clearDepth: number, clearStencil: number) { + gfxStateCache.gpuInputAssembler = null; + gfxStateCache.gpuShader = null; + const gl = device.gl; const cache = device.stateCache; let clears: GLbitfield = 0; @@ -1523,8 +1526,6 @@ export function WebGLCmdFuncBeginRenderPass ( if (cache.glFramebuffer !== gpuFramebuffer.glFramebuffer) { gl.bindFramebuffer(gl.FRAMEBUFFER, gpuFramebuffer.glFramebuffer); cache.glFramebuffer = gpuFramebuffer.glFramebuffer; - gfxStateCache.gpuInputAssembler = null; - gfxStateCache.gpuShader = null; } if (cache.viewport.left !== renderArea.x || @@ -2582,8 +2583,6 @@ export function WebGLCmdFuncDraw (device: WebGLGFXDevice, drawInfo: IGFXDrawInfo const cmdIds = new Array(WebGLCmd.COUNT); export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: WebGLCmdPackage) { cmdIds.fill(0); - gfxStateCache.gpuShader = null; - gfxStateCache.gpuInputAssembler = null; for (let i = 0; i < cmdPackage.cmds.length; ++i) { const cmd = cmdPackage.cmds.array[i]; diff --git a/cocos/core/gfx/webgl2/webgl2-commands.ts b/cocos/core/gfx/webgl2/webgl2-commands.ts index 5b73099849..2b01b92d55 100644 --- a/cocos/core/gfx/webgl2/webgl2-commands.ts +++ b/cocos/core/gfx/webgl2/webgl2-commands.ts @@ -823,10 +823,18 @@ export function WebGL2CmdFuncDestroyBuffer (device: WebGL2GFXDevice, gpuBuffer: // can be reproduced in the static batching scene at https://github.com/cocos-creator/test-cases-3d switch (gpuBuffer.glTarget) { case gl.ARRAY_BUFFER: + if (device.useVAO && device.stateCache.glVAO) { + gl.bindVertexArray(null); + device.stateCache.glVAO = null; + } gl.bindBuffer(gl.ARRAY_BUFFER, null); device.stateCache.glArrayBuffer = null; break; case gl.ELEMENT_ARRAY_BUFFER: + if (device.useVAO && device.stateCache.glVAO) { + gl.bindVertexArray(null); + device.stateCache.glVAO = null; + } gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null); device.stateCache.glElementArrayBuffer = null; break; @@ -1767,6 +1775,9 @@ export function WebGL2CmdFuncBeginRenderPass ( clearDepth: number, clearStencil: number) { + gfxStateCache.gpuInputAssembler = null; + gfxStateCache.gpuShader = null; + const gl = device.gl; const cache = device.stateCache; @@ -1776,8 +1787,6 @@ export function WebGL2CmdFuncBeginRenderPass ( if (cache.glFramebuffer !== gpuFramebuffer.glFramebuffer) { gl.bindFramebuffer(gl.FRAMEBUFFER, gpuFramebuffer.glFramebuffer); cache.glFramebuffer = gpuFramebuffer.glFramebuffer; - gfxStateCache.gpuInputAssembler = null; - gfxStateCache.gpuShader = null; } if (cache.viewport.left !== renderArea.x || @@ -2608,8 +2617,6 @@ export function WebGL2CmdFuncDraw (device: WebGL2GFXDevice, drawInfo: IGFXDrawIn const cmdIds = new Array(WebGL2Cmd.COUNT); export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: WebGL2CmdPackage) { cmdIds.fill(0); - gfxStateCache.gpuShader = null; - gfxStateCache.gpuInputAssembler = null; for (let i = 0; i < cmdPackage.cmds.length; ++i) { const cmd = cmdPackage.cmds.array[i]; From 99a2269436c6b99a54cca3a1821e8ce7f18f5400 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 29 May 2020 19:22:39 +0800 Subject: [PATCH 61/74] Fix window default rAF replacing issue (#6789) * Fix window default rAF replacing issue * Clear rAF before change mode --- cocos/core/game.ts | 27 ++++++++++++++++----------- 1 file changed, 16 insertions(+), 11 deletions(-) diff --git a/cocos/core/game.ts b/cocos/core/game.ts index 44fba1127c..84c1951475 100644 --- a/cocos/core/game.ts +++ b/cocos/core/game.ts @@ -432,7 +432,7 @@ export class Game extends EventTarget { this._paused = true; // Pause main loop if (this._intervalId) { - window.cancelAnimationFrame(this._intervalId); + window.cAF(this._intervalId); this._intervalId = 0; } // Because JSB platforms never actually stops the swap chain, @@ -441,12 +441,12 @@ export class Game extends EventTarget { let swapbuffers = 3; const cb = () => { if (--swapbuffers > 1) { - window.requestAnimationFrame(cb); + window.rAF(cb); } const root = cc.director.root; root.frameMove(0); root.device.present(); }; - window.requestAnimationFrame(cb); + window.rAF(cb); } } @@ -734,19 +734,24 @@ export class Game extends EventTarget { if (JSB) { jsb.setPreferredFramesPerSecond(frameRate); } - else { + else { + if (this._intervalId) { + window.cAF(this._intervalId); + this._intervalId = 0; + } + if (frameRate !== 60 && frameRate !== 30) { - window.requestAnimationFrame = this._stTime; - window.cancelAnimationFrame = this._ctTime; + window.rAF = this._stTime; + window.cAF = this._ctTime; } else { - window.requestAnimationFrame = window.requestAnimationFrame || + window.rAF = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame || this._stTime; - window.cancelAnimationFrame = window.cancelAnimationFrame || + window.cAF = window.cancelAnimationFrame || window.cancelRequestAnimationFrame || window.msCancelRequestAnimationFrame || window.mozCancelRequestAnimationFrame || @@ -782,7 +787,7 @@ export class Game extends EventTarget { callback = (time: number) => { if (this._paused) { return; } - this._intervalId = window.requestAnimationFrame(callback); + this._intervalId = window.rAF(callback); if (!JSB && frameRate === 30) { skip = !skip; if (skip) { @@ -793,11 +798,11 @@ export class Game extends EventTarget { }; if (this._intervalId) { - window.cancelAnimationFrame(this._intervalId); + window.cAF(this._intervalId); this._intervalId = 0; } - this._intervalId = window.requestAnimationFrame(callback); + this._intervalId = window.rAF(callback); this._paused = false; } From 34eab244fcd77c1a1cb5a821ab924d803fd609be Mon Sep 17 00:00:00 2001 From: pandamicro Date: Fri, 29 May 2020 19:49:30 +0800 Subject: [PATCH 62/74] Fix crash caused by event target removal on destroyed component (#6790) --- cocos/core/scene-graph/base-node.ts | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/cocos/core/scene-graph/base-node.ts b/cocos/core/scene-graph/base-node.ts index 2031fb8d2e..8a4059f47c 100644 --- a/cocos/core/scene-graph/base-node.ts +++ b/cocos/core/scene-graph/base-node.ts @@ -1344,6 +1344,16 @@ export class BaseNode extends CCObject implements ISchedulable { this._registerIfAttached!(false); } + // Clear event targets + const eventTargets = this.__eventTargets; + for (let i = 0; i < eventTargets.length; ++i) { + const et = eventTargets[i]; + if (et) { + et.targetOff(this); + } + } + eventTargets.length = 0; + // destroy children const children = this._children; for (let i = 0; i < children.length; ++i) { @@ -1359,15 +1369,6 @@ export class BaseNode extends CCObject implements ISchedulable { comps[i]._destroyImmediate(); } - const eventTargets = this.__eventTargets; - for (let i = 0; i < eventTargets.length; ++i) { - const et = eventTargets[i]; - if (et) { - et.targetOff(this); - } - } - eventTargets.length = 0; - // remove from persist if (this._persistNode) { cc.game.removePersistRootNode(this); From 1cefb4e04ce243d1dccce832096b6598c2ace48f Mon Sep 17 00:00:00 2001 From: pandamicro Date: Sun, 31 May 2020 14:50:51 +0800 Subject: [PATCH 63/74] Fix native rAF and cAF (#6792) * Fix native rAF and cAF * Update version --- cocos/core/game.ts | 2 ++ package.json | 2 +- predefine.ts | 2 +- 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/cocos/core/game.ts b/cocos/core/game.ts index 84c1951475..a606ac5122 100644 --- a/cocos/core/game.ts +++ b/cocos/core/game.ts @@ -733,6 +733,8 @@ export class Game extends EventTarget { if (JSB) { jsb.setPreferredFramesPerSecond(frameRate); + window.rAF = window.requestAnimationFrame; + window.cAF = window.cancelAnimationFrame; } else { if (this._intervalId) { diff --git a/package.json b/package.json index 433b7639a8..45bcd03700 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "cocos-creator-3d", - "version": "1.0.2", + "version": "1.1.1", "description": "Cocos Creator 3D is a cross-platform 3D game engine written in Javascript, licensed under MIT.", "homepage": "http://www.cocos.com", "license": "MIT", diff --git a/predefine.ts b/predefine.ts index 869fdf5d39..8ec843e3c1 100644 --- a/predefine.ts +++ b/predefine.ts @@ -165,7 +165,7 @@ if (DEV) { * Please DO NOT remove this String, it is an important flag for bug tracking.
* If you post a bug to forum, please attach this flag. */ -const engineVersion = '1.1.0'; +const engineVersion = '1.1.1'; _global.CocosEngine = cc.ENGINE_VERSION = engineVersion; export default cc; From 7198381ed9ae2df180267136b222caf070530b3e Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Sun, 31 May 2020 21:58:08 +0800 Subject: [PATCH 64/74] update comments (#6793) --- .../models/skeletal-animation-utils.ts | 32 +++++++++++++------ 1 file changed, 22 insertions(+), 10 deletions(-) diff --git a/cocos/core/renderer/models/skeletal-animation-utils.ts b/cocos/core/renderer/models/skeletal-animation-utils.ts index be6407887f..cf18c582c3 100644 --- a/cocos/core/renderer/models/skeletal-animation-utils.ts +++ b/cocos/core/renderer/models/skeletal-animation-utils.ts @@ -303,17 +303,29 @@ export class JointTexturePool { correctionPath = animPath; } } + // the default behavior, just use the bindpose for current joint directly let bindposeIdx = i; - // It is regularly observed that developers may choose to delete the whole skeleton node tree - // for skinning models that only use baked animations, to reduce prefab file size. - // This becomes troublesome in some cases during baking though, e.g. when a skeleton joint node - // is not directly controlled by any animation curve, but its parent nodes are. - // Due to the lack of proper downstream default pose, the joint transform can not be calculated accurately. - // We address this issue by employing some pragmatic approximation. - // Specifically, by multiplying the bindpose of the joint corresponding to the nearest curve, instead of the actual target joint. - // It gives more visually-plausible results compared to the naive approach for most cases we've covered. + /** + * It is regularly observed that developers may choose to delete the whole + * skeleton node tree for skinning models that only use baked animations, + * to reduce prefab file size. + * + * This becomes troublesome in some cases during baking though, e.g. when a + * skeleton joint node is not directly controlled by any animation curve, + * but its parent nodes are. Due to lack of proper downstream default pose, + * the joint transform can not be calculated accurately. + * + * We address this issue by employing some pragmatic approximation. + * Specifically, by multiplying the bindpose of the joint corresponding to + * the nearest curve, instead of the actual target joint. This effectively + * merges the skinning influence of the 'incomplete' joint into its nearest + * parent with accurate transform data. + * It gives more visually-plausible results compared to the naive approach + * for most cases we've covered. + */ if (correctionPath !== undefined) { - bindposeIdx = i - 1; // just use the previous joint if the exact path is not found + // just use the previous joint if the exact path is not found + bindposeIdx = i - 1; for (let j = 0; j < totalJoints; j++) { if (joints[j] === correctionPath) { bindposeIdx = j; break; @@ -338,7 +350,7 @@ export class JointTexturePool { mat = Mat4.IDENTITY; } const boneSpaceBound = boneSpaceBounds[i]; - if (boneSpaceBound) { + if (boneSpaceBound && mat !== Mat4.IDENTITY) { aabb.transform(ab_1, boneSpaceBound, mat); ab_1.getBoundary(v3_3, v3_4); Vec3.min(bound.center, bound.center, v3_3); From 13ec9c08f8f7ebd93b56a27a6363832cd5f8b166 Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 1 Jun 2020 16:16:51 +0800 Subject: [PATCH 65/74] fix skinning model bounds (#6795) * fix skinning model bounds * fix instancing status query * fix batched skinning model mesh cook --- .../batched-skinning-model-component.ts | 123 ++++++----- .../animation/skeletal-animation-state.ts | 11 +- cocos/core/assets/mesh.ts | 26 ++- cocos/core/assets/skeleton.ts | 32 ++- .../models/skeletal-animation-utils.ts | 199 ++++++++++-------- cocos/core/renderer/scene/model.ts | 3 +- cocos/core/renderer/scene/planar-shadows.ts | 6 +- 7 files changed, 228 insertions(+), 172 deletions(-) diff --git a/cocos/core/3d/framework/batched-skinning-model-component.ts b/cocos/core/3d/framework/batched-skinning-model-component.ts index a942c1e239..fb15fff52c 100644 --- a/cocos/core/3d/framework/batched-skinning-model-component.ts +++ b/cocos/core/3d/framework/batched-skinning-model-component.ts @@ -42,6 +42,7 @@ import { IGFXAttribute } from '../../gfx/input-assembler'; import { Mat4, Vec2, Vec3 } from '../../math'; import { mapBuffer, readBuffer, writeBuffer } from '../misc/buffer'; import { SkinningModelComponent } from './skinning-model-component'; +import { sys } from '../../platform'; const repeat = (n: number) => n - Math.floor(n); const batch_id: IGFXAttribute = { name: GFXAttributeName.ATTR_BATCH_ID, format: GFXFormat.R32F, isNormalized: false }; @@ -503,73 +504,89 @@ export class BatchedSkinningModelComponent extends SkinningModelComponent { private _createUnitMesh (unitIdx: number, mesh: Mesh) { // add batch ID to this temp mesh // first, update bookkeeping - let uvOffset = 0; - let uvFormat = GFXFormat.UNKNOWN; - let bundleIdx = 0; - for (; bundleIdx < mesh.struct.vertexBundles.length; bundleIdx++) { - const bundle = mesh.struct.vertexBundles[bundleIdx]; - uvOffset = bundle.view.offset; - uvFormat = GFXFormat.UNKNOWN; - for (let a = 0; a < bundle.attributes.length; a++) { - const attr = bundle.attributes[a]; - if (attr.name === GFXAttributeName.ATTR_TEX_COORD) { - uvFormat = attr.format; - break; - } - uvOffset += GFXFormatInfos[attr.format].size; - } - if (uvFormat) { break; } - } const newMeshStruct: Mesh.IStruct = JSON.parse(JSON.stringify(mesh.struct)); - let newOffset = 0; - const oldBundle = mesh.struct.vertexBundles[bundleIdx]; - const newBundle = newMeshStruct.vertexBundles[bundleIdx]; // put the new UVs in the same bundle with original UVs - newBundle.attributes.push(batch_id); - newBundle.attributes.push(batch_uv); - newBundle.view.offset = newOffset; - newBundle.view.length += newBundle.view.count * batch_extras_size; - newBundle.view.stride += batch_extras_size; - newOffset += newBundle.view.length; + const modifiedBundles: Record = {}; + for (let p = 0; p < mesh.struct.primitives.length; p++) { + const primitive = mesh.struct.primitives[p]; + let uvOffset = 0; + let uvFormat = GFXFormat.UNKNOWN; + let bundleIdx = 0; + for (; bundleIdx < primitive.vertexBundelIndices.length; bundleIdx++) { + const bundle = mesh.struct.vertexBundles[primitive.vertexBundelIndices[bundleIdx]]; + uvOffset = bundle.view.offset; + uvFormat = GFXFormat.UNKNOWN; + for (let a = 0; a < bundle.attributes.length; a++) { + const attr = bundle.attributes[a]; + if (attr.name === GFXAttributeName.ATTR_TEX_COORD) { + uvFormat = attr.format; + break; + } + uvOffset += GFXFormatInfos[attr.format].size; + } + if (uvFormat) { break; } + } + if (modifiedBundles[bundleIdx] !== undefined) { continue; } + modifiedBundles[bundleIdx] = [ uvFormat, uvOffset ]; + const newBundle = newMeshStruct.vertexBundles[bundleIdx]; // put the new UVs in the same bundle with original UVs + newBundle.attributes.push(batch_id); + newBundle.attributes.push(batch_uv); + newBundle.view.offset = 0; + newBundle.view.length += newBundle.view.count * batch_extras_size; + newBundle.view.stride += batch_extras_size; + } + let totalLength = 0; + for (let b = 0; b < newMeshStruct.vertexBundles.length; b++) { + totalLength += newMeshStruct.vertexBundles[b].view.length; + } for (let p = 0; p < newMeshStruct.primitives.length; p++) { const pm = newMeshStruct.primitives[p]; if (pm.indexView) { - pm.indexView.offset = newOffset; - newOffset += pm.indexView.length; + pm.indexView.offset = totalLength; + totalLength += pm.indexView.length; } } // now, we ride! - const src = mesh.data!; let oldOffset = 0; - const newMeshData = new Uint8Array(newOffset); - const dataView = new DataView(newMeshData.buffer); - const uvs = readBuffer(new DataView(src.buffer), uvFormat, uvOffset, oldBundle.view.length, oldBundle.view.stride); - const oldView = oldBundle.view; - const newView = newBundle.view; - let oldStride = oldView.stride; - let newStride = newView.stride; - oldOffset = oldView.offset; - newOffset = newView.offset; - for (let j = 0; j < newView.count; j++) { - const srcVertex = src.subarray(oldOffset, oldOffset + oldStride); - newMeshData.set(srcVertex, newOffset); - // insert batch ID - dataView.setFloat32(newOffset + oldStride, unitIdx, cc.sys.isLittleEndian); - // insert batch UV - dataView.setFloat32(newOffset + oldStride + 4, uvs[j * 2], cc.sys.isLittleEndian); - dataView.setFloat32(newOffset + oldStride + 8, uvs[j * 2 + 1], cc.sys.isLittleEndian); - newOffset += newStride; oldOffset += oldStride; + const newMeshData = new Uint8Array(totalLength); + const oldMeshData = mesh.data!; + const newDataView = new DataView(newMeshData.buffer); + const oldDataView = new DataView(oldMeshData.buffer); + const isLittleEndian = sys.isLittleEndian; + for (const b in modifiedBundles) { + const newBundle = newMeshStruct.vertexBundles[b]; + const oldBundle = mesh.struct.vertexBundles[b]; + const [ uvFormat, uvOffset ] = modifiedBundles[b]; + const uvs = readBuffer(oldDataView, uvFormat, uvOffset, oldBundle.view.length, oldBundle.view.stride); + const oldView = oldBundle.view; + const newView = newBundle.view; + const oldStride = oldView.stride; + const newStride = newView.stride; + let oldOffset = oldView.offset; + let newOffset = newView.offset; + for (let j = 0; j < newView.count; j++) { + const srcVertex = oldMeshData.subarray(oldOffset, oldOffset + oldStride); + newMeshData.set(srcVertex, newOffset); + // insert batch ID + newDataView.setFloat32(newOffset + oldStride, unitIdx, ); + // insert batch UV + newDataView.setFloat32(newOffset + oldStride + 4, uvs[j * 2], isLittleEndian); + newDataView.setFloat32(newOffset + oldStride + 8, uvs[j * 2 + 1], isLittleEndian); + newOffset += newStride; + oldOffset += oldStride; + } } for (let k = 0; k < newMeshStruct.primitives.length; k++) { const oldPrimitive = mesh.struct.primitives[k]; const newPrimitive = newMeshStruct.primitives[k]; if (oldPrimitive.indexView && newPrimitive.indexView) { - oldStride = oldPrimitive.indexView.stride; - newStride = newPrimitive.indexView.stride; - oldOffset = oldPrimitive.indexView.offset; - newOffset = newPrimitive.indexView.offset; + const oldStride = oldPrimitive.indexView.stride; + const newStride = newPrimitive.indexView.stride; + let oldOffset = oldPrimitive.indexView.offset; + let newOffset = newPrimitive.indexView.offset; for (let j = 0; j < newPrimitive.indexView.count; j++) { - const srcIndices = src.subarray(oldOffset, oldOffset + oldStride); + const srcIndices = oldMeshData.subarray(oldOffset, oldOffset + oldStride); newMeshData.set(srcIndices, newOffset); - newOffset += newStride; oldOffset += oldStride; + newOffset += newStride; + oldOffset += oldStride; } } } diff --git a/cocos/core/animation/skeletal-animation-state.ts b/cocos/core/animation/skeletal-animation-state.ts index 405388d92a..b7a7e65ff7 100644 --- a/cocos/core/animation/skeletal-animation-state.ts +++ b/cocos/core/animation/skeletal-animation-state.ts @@ -35,7 +35,6 @@ import { AnimationClip, IRuntimeCurve } from './animation-clip'; import { AnimationState } from './animation-state'; import { SkeletalAnimationComponent, Socket } from './skeletal-animation-component'; import { SkelAnimDataHub } from './skeletal-animation-data-hub'; -import { getWorldTransformUntilRoot } from './transform-utils'; const m4_1 = new Mat4(); const m4_2 = new Mat4(); @@ -125,25 +124,25 @@ export class SkeletalAnimationState extends AnimationState { let downstream: Mat4 | undefined; while (!source) { const idx = animPath.lastIndexOf('/'); - if (idx < 0) { break; } animPath = animPath.substring(0, idx); source = clipData.data[animPath]; if (animNode) { - if (!downstream) { downstream = m4_2; Mat4.identity(downstream); } + if (!downstream) { downstream = Mat4.identity(m4_2); } Mat4.fromRTS(m4_1, animNode.rotation, animNode.position, animNode.scale); Mat4.multiply(downstream, m4_1, downstream); animNode = animNode.parent; } + if (idx < 0) { break; } } const curveData: Mat4[] | undefined = source && source.worldMatrix.values as Mat4[]; const frames = clipData.info.frames; const transforms: ITransform[] = []; - for (let frame = 0; frame < frames; frame++) { + for (let f = 0; f < frames; f++) { let mat: Mat4; if (curveData && downstream) { // curve & static two-way combination - mat = Mat4.multiply(m4_1, curveData[frame], downstream); + mat = Mat4.multiply(m4_1, curveData[f], downstream); } else if (curveData) { // there is a curve directly controlling the joint - mat = curveData[frame]; + mat = curveData[f]; } else if (downstream) { // fallback to default pose if no animation curve can be found upstream mat = downstream; } else { // bottom line: render the original mesh as-is diff --git a/cocos/core/assets/mesh.ts b/cocos/core/assets/mesh.ts index cc962b3689..c842f74c5c 100644 --- a/cocos/core/assets/mesh.ts +++ b/cocos/core/assets/mesh.ts @@ -131,18 +131,24 @@ export class RenderingSubMesh { * (用于射线检测的)几何信息。 */ get geometricInfo () { - if (this._geometricInfo) { return this._geometricInfo; } - if (this.mesh == undefined) { return { positions: new Float32Array(), indices: new Uint8Array(), boundingBox: { min: Vec3.ZERO, max: Vec3.ZERO } }; } - if (this.subMeshIdx == undefined) { return { positions: new Float32Array(), indices: new Uint8Array(), boundingBox: { min: Vec3.ZERO, max: Vec3.ZERO } }; } + if (this._geometricInfo) { + return this._geometricInfo; + } + if (this.mesh === undefined) { + return { positions: new Float32Array(), indices: new Uint8Array(), boundingBox: { min: Vec3.ZERO, max: Vec3.ZERO } }; + } + if (this.subMeshIdx === undefined) { + return { positions: new Float32Array(), indices: new Uint8Array(), boundingBox: { min: Vec3.ZERO, max: Vec3.ZERO } }; + } const mesh = this.mesh!; const index = this.subMeshIdx!; const positions = mesh.readAttribute(index, GFXAttributeName.ATTR_POSITION) as unknown as Float32Array; const indices = mesh.readIndices(index) as Uint16Array; const max = new Vec3(); const min = new Vec3(); - const pAttri = this.attributes.find(element => element.name == cc.GFXAttributeName.ATTR_POSITION); + const pAttri = this.attributes.find(element => element.name === cc.GFXAttributeName.ATTR_POSITION); if (pAttri) { const conut = GFXFormatInfos[pAttri.format].count; - if (conut == 2) { + if (conut === 2) { max.set(positions[0], positions[1], 0); min.set(positions[0], positions[1], 0); } else { @@ -150,7 +156,7 @@ export class RenderingSubMesh { min.set(positions[0], positions[1], positions[2]); } for (let i = 0; i < positions.length; i += conut) { - if (conut == 2) { + if (conut === 2) { max.x = positions[i] > max.x ? positions[i] : max.x; max.y = positions[i + 1] > max.y ? positions[i + 1] : max.y; min.x = positions[i] < min.x ? positions[i] : min.x; @@ -544,7 +550,7 @@ export class Mesh extends Asset { private _data: Uint8Array | null = null; private _initialized = false; private _renderingSubMeshes: RenderingSubMesh[] | null = null; - private _boneSpaceBounds = new Map>(); + private _boneSpaceBounds = new Map(); private _jointBufferIndices: number[] | null = null; constructor () { @@ -631,7 +637,7 @@ export class Mesh extends Asset { } this._renderingSubMeshes = subMeshes; - + if (this._struct.morph) { this.morphRendering = createMorphRendering(this, gfxDevice); } @@ -697,7 +703,7 @@ export class Mesh extends Asset { if (this._boneSpaceBounds.has(skeleton.hash)) { return this._boneSpaceBounds.get(skeleton.hash)!; } - const bounds: Array = []; + const bounds: (aabb | null)[] = []; this._boneSpaceBounds.set(skeleton.hash, bounds); const valid: boolean[] = []; const bindposes = skeleton.bindposes; @@ -742,7 +748,7 @@ export class Mesh extends Asset { * @returns 是否验证成功。若验证选项为 `true` 且验证未通过则返回 `false`,否则返回 `true`。 */ public merge (mesh: Mesh, worldMatrix?: Mat4, validate?: boolean): boolean { - if (validate !== undefined && validate) { + if (validate) { if (!this.loaded || !mesh.loaded || !this.validateMergingMesh(mesh)) { return false; } diff --git a/cocos/core/assets/skeleton.ts b/cocos/core/assets/skeleton.ts index 8d7a88bc4f..e139eeeebf 100644 --- a/cocos/core/assets/skeleton.ts +++ b/cocos/core/assets/skeleton.ts @@ -50,6 +50,19 @@ export class Skeleton extends Asset { @property private _hash = 0; + private _invBindposes: Mat4[] | null = null; + + /** + * 所有关节的路径。该数组的长度始终与 `this.bindposes` 的长度相同。 + */ + get joints () { + return this._joints; + } + + set joints (value) { + this._joints = value; + } + /** * 所有关节的绑定姿势矩阵。该数组的长度始终与 `this.joints` 的长度相同。 */ @@ -61,15 +74,16 @@ export class Skeleton extends Asset { this._bindposes = value; } - /** - * 所有关节的路径。该数组的长度始终与 `this.bindposes` 的长度相同。 - */ - get joints () { - return this._joints; - } - - set joints (value) { - this._joints = value; + get inverseBindposes () { + if (!this._invBindposes) { + this._invBindposes = []; + for (let i = 0; i < this._bindposes.length; i++) { + const inv = new Mat4(); + Mat4.invert(inv, this._bindposes[i]); + this._invBindposes.push(inv); + } + } + return this._invBindposes; } get hash () { diff --git a/cocos/core/renderer/models/skeletal-animation-utils.ts b/cocos/core/renderer/models/skeletal-animation-utils.ts index cf18c582c3..f089e74a15 100644 --- a/cocos/core/renderer/models/skeletal-animation-utils.ts +++ b/cocos/core/renderer/models/skeletal-animation-utils.ts @@ -118,6 +118,13 @@ export const jointTextureSamplerHash = genSamplerHash([ GFXAddress.CLAMP, ]); +interface IInternalJointAnimInfo { + downstream?: Mat4; // downstream default pose, if present + curveData?: Mat4[]; // the nearest animation curve, if present + bindposeIdx: number; // index of the actual bindpose to use + bindposeCorrection?: Mat4; // correction factor from the original bindpose +} + export interface IJointTextureHandle { pixelOffset: number; refCount: number; @@ -126,6 +133,7 @@ export interface IJointTextureHandle { readyToBeDeleted: boolean; handle: ITextureBufferHandle; bounds: Map; + animInfos?: IInternalJointAnimInfo[]; } const v3_3 = new Vec3(); @@ -133,6 +141,7 @@ const v3_4 = new Vec3(); const v3_min = new Vec3(); const v3_max = new Vec3(); const m4_1 = new Mat4(); +const m4_2 = new Mat4(); const ab_1 = new aabb(); export interface IChunkContent { @@ -144,12 +153,6 @@ export interface ICustomJointTextureLayout { contents: IChunkContent[]; } -interface IJointAnimInfo { - downstream?: Mat4; // downstream default pose, if present - curveData?: Mat4[]; // the nearest animation curve, if present - bindpose: Mat4; // the actual bindpose to use -} - // Have to use some big number to replace the actual 'Infinity'. // For (Infinity - Infinity) evaluates to NaN const Inf = Number.MAX_SAFE_INTEGER; @@ -213,8 +216,9 @@ export class JointTexturePool { if (texture && texture.bounds.has(mesh.hash)) { texture.refCount++; return texture; } const { joints, bindposes } = skeleton; let textureBuffer: Float32Array = null!; let buildTexture = false; + const jointCount = joints.length; if (!texture) { - const bufSize = joints.length * 12; + const bufSize = jointCount * 12; const customChunkIdx = this._chunkIdxMap.get(hash); const handle = customChunkIdx !== undefined ? this._customPool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT, customChunkIdx) : @@ -227,10 +231,10 @@ export class JointTexturePool { Vec3.set(v3_min, Inf, Inf, Inf); Vec3.set(v3_max, -Inf, -Inf, -Inf); const boneSpaceBounds = mesh.getBoneSpaceBounds(skeleton); - for (let i = 0; i < joints.length; i++) { - const node = skinningRoot.getChildByPath(joints[i]); - const bound = boneSpaceBounds[i]; - const mat = node ? getWorldTransformUntilRoot(node, skinningRoot, m4_1) : Mat4.IDENTITY; + for (let j = 0, offset = 0; j < jointCount; j++, offset += 12) { + const node = skinningRoot.getChildByPath(joints[j]); + const mat = node ? getWorldTransformUntilRoot(node, skinningRoot, m4_1) : skeleton.inverseBindposes[j]; + const bound = boneSpaceBounds[j]; if (bound) { aabb.transform(ab_1, bound, mat); ab_1.getBoundary(v3_3, v3_4); @@ -238,8 +242,8 @@ export class JointTexturePool { Vec3.max(v3_max, v3_max, v3_4); } if (buildTexture) { - if (mat !== Mat4.IDENTITY) { Mat4.multiply(mat, mat, bindposes[i]); } - uploadJointData(textureBuffer, 12 * i, mat, i === 0); + if (node) { Mat4.multiply(mat, mat, bindposes[j]); } + uploadJointData(textureBuffer, offset, node ? mat : Mat4.IDENTITY, j === 0); } } const bounds = [new aabb()]; texture.bounds.set(mesh.hash, bounds); @@ -265,101 +269,50 @@ export class JointTexturePool { const clipData = SkelAnimDataHub.getOrExtract(clip); const frames = clipData.info.frames; let textureBuffer: Float32Array = null!; let buildTexture = false; - const totalJoints = joints.length; + const jointCount = joints.length; if (!texture) { - const bufSize = totalJoints * 12 * frames; + const bufSize = jointCount * 12 * frames; const customChunkIdx = this._chunkIdxMap.get(hash); const handle = customChunkIdx !== undefined ? this._customPool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT, customChunkIdx) : this._pool.alloc(bufSize * Float32Array.BYTES_PER_ELEMENT); if (!handle) { return null; } + const animInfos = this._createAnimInfos(skeleton, clip, skinningRoot); texture = { pixelOffset: handle.start / this._formatSize, refCount: 1, bounds: new Map(), - skeletonHash: skeleton.hash, clipHash: clip.hash, readyToBeDeleted: false, handle }; + skeletonHash: skeleton.hash, clipHash: clip.hash, readyToBeDeleted: false, handle, animInfos }; textureBuffer = new Float32Array(bufSize); buildTexture = true; } else { texture.refCount++; } const boneSpaceBounds = mesh.getBoneSpaceBounds(skeleton); const bounds: aabb[] = []; texture.bounds.set(mesh.hash, bounds); - for (let fid = 0; fid < frames; fid++) { + for (let f = 0; f < frames; f++) { bounds.push(new aabb(Inf, Inf, Inf, -Inf, -Inf, -Inf)); } - const animInfos: IJointAnimInfo[] = []; - for (let i = 0; i < totalJoints; i++) { - let animPath = joints[i]; - let source = clipData.data[animPath]; - let animNode = skinningRoot.getChildByPath(animPath); - let downstream: Mat4 | undefined; - let correctionPath: string | undefined; - while (!source) { - const idx = animPath.lastIndexOf('/'); - if (idx < 0) { break; } - animPath = animPath.substring(0, idx); - source = clipData.data[animPath]; - if (animNode) { - if (!downstream) { downstream = new Mat4(); } - Mat4.fromRTS(m4_1, animNode.rotation, animNode.position, animNode.scale); - Mat4.multiply(downstream, m4_1, downstream); - animNode = animNode.parent; - } else { // record the nearest curve path if no downstream pose is present - correctionPath = animPath; - } - } - // the default behavior, just use the bindpose for current joint directly - let bindposeIdx = i; - /** - * It is regularly observed that developers may choose to delete the whole - * skeleton node tree for skinning models that only use baked animations, - * to reduce prefab file size. - * - * This becomes troublesome in some cases during baking though, e.g. when a - * skeleton joint node is not directly controlled by any animation curve, - * but its parent nodes are. Due to lack of proper downstream default pose, - * the joint transform can not be calculated accurately. - * - * We address this issue by employing some pragmatic approximation. - * Specifically, by multiplying the bindpose of the joint corresponding to - * the nearest curve, instead of the actual target joint. This effectively - * merges the skinning influence of the 'incomplete' joint into its nearest - * parent with accurate transform data. - * It gives more visually-plausible results compared to the naive approach - * for most cases we've covered. - */ - if (correctionPath !== undefined) { - // just use the previous joint if the exact path is not found - bindposeIdx = i - 1; - for (let j = 0; j < totalJoints; j++) { - if (joints[j] === correctionPath) { - bindposeIdx = j; break; - } - } - } - animInfos.push({ curveData: source && source.worldMatrix.values as Mat4[], downstream, bindpose: bindposes[bindposeIdx] }); - } - let offset = 0; - for (let frame = 0; frame < frames; frame++) { - const bound = bounds[frame]; - for (let i = 0; i < totalJoints; i++, offset += 12) { - const animInfo = animInfos[i]; - let mat: Mat4; - if (animInfo.curveData && animInfo.downstream) { // curve & static two-way combination - mat = Mat4.multiply(m4_1, animInfo.curveData[frame], animInfo.downstream); - } else if (animInfo.curveData) { // there is a curve directly controlling the joint - mat = animInfo.curveData[frame]; - } else if (animInfo.downstream) { // fallback to default pose if no animation curve can be found upstream - mat = animInfo.downstream; + for (let f = 0, offset = 0; f < frames; f++) { + const bound = bounds[f]; + for (let j = 0; j < jointCount; j++, offset += 12) { + const { curveData, downstream, bindposeIdx, bindposeCorrection } = texture.animInfos![j]; + let mat: Mat4; let transformValid = true; + if (curveData && downstream) { // curve & static two-way combination + mat = Mat4.multiply(m4_1, curveData[f], downstream); + } else if (curveData) { // there is a curve directly controlling the joint + mat = curveData[f]; + } else if (downstream) { // fallback to default pose if no animation curve can be found upstream + mat = downstream; } else { // bottom line: render the original mesh as-is - mat = Mat4.IDENTITY; + mat = skeleton.inverseBindposes[bindposeIdx]; + transformValid = false; } - const boneSpaceBound = boneSpaceBounds[i]; - if (boneSpaceBound && mat !== Mat4.IDENTITY) { - aabb.transform(ab_1, boneSpaceBound, mat); + const boneSpaceBound = boneSpaceBounds[j]; + if (boneSpaceBound) { + const transform = bindposeCorrection ? Mat4.multiply(m4_2, mat, bindposeCorrection) : mat; + aabb.transform(ab_1, boneSpaceBound, transform); ab_1.getBoundary(v3_3, v3_4); Vec3.min(bound.center, bound.center, v3_3); Vec3.max(bound.halfExtents, bound.halfExtents, v3_4); } if (buildTexture) { - // no need to apply bindpose if we are rendering the mesh as-is - if (mat !== Mat4.IDENTITY) { mat = Mat4.multiply(m4_1, mat, animInfo.bindpose); } - uploadJointData(textureBuffer, offset, mat, i === 0); + if (transformValid) { Mat4.multiply(m4_1, mat, bindposes[bindposeIdx]); } + uploadJointData(textureBuffer, offset, transformValid ? m4_1 : Mat4.IDENTITY, j === 0); } } aabb.fromPoints(bound, bound.center, bound.halfExtents); @@ -374,9 +327,12 @@ export class JointTexturePool { public releaseHandle (handle: IJointTextureHandle) { if (handle.refCount > 0) { handle.refCount--; } if (!handle.refCount && handle.readyToBeDeleted) { - const customChunkIdx = this._chunkIdxMap.get(handle.skeletonHash ^ handle.clipHash); + const hash = handle.skeletonHash ^ handle.clipHash; + const customChunkIdx = this._chunkIdxMap.get(hash); (customChunkIdx !== undefined ? this._customPool : this._pool).free(handle.handle); - this._textureBuffers.delete(handle.skeletonHash ^ handle.clipHash); + if (this._textureBuffers.get(hash) === handle) { + this._textureBuffers.delete(hash); + } } } @@ -415,6 +371,69 @@ export class JointTexturePool { res = it.next(); } } + + private _createAnimInfos (skeleton: Skeleton, clip: AnimationClip, skinningRoot: Node) { + const animInfos: IInternalJointAnimInfo[] = []; + const { joints, bindposes } = skeleton; + const jointCount = joints.length; + const clipData = SkelAnimDataHub.getOrExtract(clip); + for (let j = 0; j < jointCount; j++) { + let animPath = joints[j]; + let source = clipData.data[animPath]; + let animNode = skinningRoot.getChildByPath(animPath); + let downstream: Mat4 | undefined; + let correctionPath: string | undefined; + while (!source) { + const idx = animPath.lastIndexOf('/'); + animPath = animPath.substring(0, idx); + source = clipData.data[animPath]; + if (animNode) { + if (!downstream) { downstream = new Mat4(); } + Mat4.fromRTS(m4_1, animNode.rotation, animNode.position, animNode.scale); + Mat4.multiply(downstream, m4_1, downstream); + animNode = animNode.parent; + } else { // record the nearest curve path if no downstream pose is present + correctionPath = animPath; + } + if (idx < 0) { break; } + } + // the default behavior, just use the bindpose for current joint directly + let bindposeIdx = j; + let bindposeCorrection: Mat4 | undefined; + /** + * It is regularly observed that developers may choose to delete the whole + * skeleton node tree for skinning models that only use baked animations, + * to reduce prefab file size. + * + * This becomes troublesome in some cases during baking though, e.g. when a + * skeleton joint node is not directly controlled by any animation curve, + * but its parent nodes are. Due to lack of proper downstream default pose, + * the joint transform can not be calculated accurately. + * + * We address this issue by employing some pragmatic approximation. + * Specifically, by multiplying the bindpose of the joint corresponding to + * the nearest curve, instead of the actual target joint. This effectively + * merges the skinning influence of the 'incomplete' joint into its nearest + * parent with accurate transform data. + * It gives more visually-plausible results compared to the naive approach + * for most cases we've covered. + */ + if (correctionPath !== undefined && source) { + // just use the previous joint if the exact path is not found + bindposeIdx = j - 1; + for (let t = 0; t < jointCount; t++) { + if (joints[t] === correctionPath) { + bindposeIdx = t; + bindposeCorrection = new Mat4(); + Mat4.multiply(bindposeCorrection, bindposes[t], skeleton.inverseBindposes[j]); + break; + } + } + } + animInfos.push({ curveData: source && source.worldMatrix.values as Mat4[], downstream, bindposeIdx, bindposeCorrection }); + } + return animInfos; + } } export interface IAnimInfo { diff --git a/cocos/core/renderer/scene/model.ts b/cocos/core/renderer/scene/model.ts index ff60b3e2be..d9eb7d0257 100644 --- a/cocos/core/renderer/scene/model.ts +++ b/cocos/core/renderer/scene/model.ts @@ -4,7 +4,7 @@ import { RenderingSubMesh } from '../../assets/mesh'; import { aabb } from '../../geometry'; import { GFXBuffer } from '../../gfx/buffer'; import { getTypedArrayConstructor, GFXBufferUsageBit, GFXFormat, GFXFormatInfos, GFXMemoryUsageBit } from '../../gfx/define'; -import { GFXDevice } from '../../gfx/device'; +import { GFXDevice, GFXFeature } from '../../gfx/device'; import { GFXPipelineState } from '../../gfx/pipeline-state'; import { Mat4, Vec3 } from '../../math'; import { Pool } from '../../memop'; @@ -306,6 +306,7 @@ export class Model { // for now no submodel level instancing attributes protected updateInstancedAttributeList (pso: GFXPipelineState, pass: Pass) { + if (!pass.device.hasFeature(GFXFeature.INSTANCED_ARRAYS)) { return; } const attributes = pso.inputState.attributes; let size = 0; for (let j = 0; j < attributes.length; j++) { diff --git a/cocos/core/renderer/scene/planar-shadows.ts b/cocos/core/renderer/scene/planar-shadows.ts index 534ec34c04..0ad38dd656 100644 --- a/cocos/core/renderer/scene/planar-shadows.ts +++ b/cocos/core/renderer/scene/planar-shadows.ts @@ -163,8 +163,8 @@ export class PlanarShadows { public recordCommandBuffer (cmdBuff: GFXCommandBuffer) { const models = this._pendingModels; const modelLen = models.length; - const buffer = this._instancingMaterial.passes[0].instancedBuffer!; - buffer.clear(); + const buffer = this._instancingMaterial.passes[0].instancedBuffer; + if (buffer) { buffer.clear(); } for (let i = 0; i < modelLen; i++) { const { model, psos, instancedBuffer } = models[i]; for (let j = 0; j < psos.length; j++) { @@ -181,7 +181,7 @@ export class PlanarShadows { } } } - if (buffer.pso) { + if (buffer && buffer.pso) { buffer.uploadBuffers(); cmdBuff.bindPipelineState(buffer.pso!); cmdBuff.bindBindingLayout(buffer.pso!.pipelineLayout.layouts[0]); From af3ae070be926c447a5d02b64d10ab82e91c0408 Mon Sep 17 00:00:00 2001 From: yinkaile <501251991@qq.com> Date: Mon, 1 Jun 2020 16:31:59 +0800 Subject: [PATCH 66/74] export ubo defines (#6791) * export ubo defines * export pipeline define things to cc.pipeline --- cocos/core/pipeline/index.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/cocos/core/pipeline/index.ts b/cocos/core/pipeline/index.ts index 2d8bfd33a0..418f48ad3f 100644 --- a/cocos/core/pipeline/index.ts +++ b/cocos/core/pipeline/index.ts @@ -2,7 +2,8 @@ * @category pipeline */ -export { RenderPassStage, JOINT_UNIFORM_CAPACITY as JointUniformCapacity } from './define'; +import * as pipelineDefine from './define'; +export const pipeline = pipelineDefine; export { RenderPipeline } from './render-pipeline'; export { RenderFlow } from './render-flow'; From 8f9f09f119379687db8ec2a515912ba8490295bb Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 1 Jun 2020 18:57:57 +0800 Subject: [PATCH 67/74] fix skinning model instancing (#6799) Apparently pre-calculating final offsets on CPU then pass to shader requires more precision than what's actually provided on some devices. Never mind, just go with the old ways. --- cocos/core/3d/builtin/effects.ts | 18 +++++++++--------- .../renderer/models/baked-skinning-model.ts | 9 ++++----- 2 files changed, 13 insertions(+), 14 deletions(-) diff --git a/cocos/core/3d/builtin/effects.ts b/cocos/core/3d/builtin/effects.ts index 05f4f949ae..c5410786ec 100644 --- a/cocos/core/3d/builtin/effects.ts +++ b/cocos/core/3d/builtin/effects.ts @@ -296,13 +296,13 @@ export default [ "shaders": [ { "name": "builtin-standard|standard-vs:vert|standard-fs:frag", - "hash": 1635302204, + "hash": 3369013589, "glsl3": { - "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec4 a_tangent;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScaleParam;\n};\n#if USE_VERTEX_COLOR\n in vec3 a_color;\n out vec3 v_color;\n#endif\nout vec3 v_position;\nout vec3 v_normal;\n#if USE_NORMAL_MAP\n out vec3 v_tangent;\n out vec3 v_bitangent;\n#endif\nin vec2 a_texCoord;\nout vec2 v_uv;\nin vec2 a_texCoord1;\nout vec2 v_uv1;\nvec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_MORPH\n applyMorph(In);\n #endif\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n mat4 matWorld, matWorldIT;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n matWorldIT = matWorld;\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #if HAS_SECOND_UV\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec4 a_tangent;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScaleParam;\n};\n#if USE_VERTEX_COLOR\n in vec3 a_color;\n out vec3 v_color;\n#endif\nout vec3 v_position;\nout vec3 v_normal;\n#if USE_NORMAL_MAP\n out vec3 v_tangent;\n out vec3 v_bitangent;\n#endif\nin vec2 a_texCoord;\nout vec2 v_uv;\nin vec2 a_texCoord1;\nout vec2 v_uv1;\nvec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_MORPH\n applyMorph(In);\n #endif\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n mat4 matWorld, matWorldIT;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n matWorldIT = matWorld;\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #if HAS_SECOND_UV\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision highp float;\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\n return textureLod(tex, coord, lod);\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\n return textureLod(tex, coord, lod);\n}\n#endif\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nuniform CCForwardLight {\n highp vec4 cc_sphereLitPos[2];\n vec4 cc_sphereLitSizeRange[2];\n vec4 cc_sphereLitColor[2];\n highp vec4 cc_spotLitPos[2];\n vec4 cc_spotLitSizeRangeAngle[2];\n vec4 cc_spotLitDir[2];\n vec4 cc_spotLitColor[2];\n};\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting (vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb);\n #endif\n finalColor += env * cc_ambientSky.w * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\n color = min(color, vec3(8.0));\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScaleParam;\n};\nin vec3 v_position;\nin vec2 v_uv;\nin vec2 v_uv1;\nin vec3 v_normal;\n#if USE_VERTEX_COLOR\n in vec3 v_color;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n in vec3 v_tangent;\n in vec3 v_bitangent;\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_VERTEX_COLOR\n baseColor.rgb *= v_color;\n #endif\n #if USE_ALBEDO_MAP\n vec4 texColor = texture(albedoMap, ALBEDO_UV);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScaleAndCutoff.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture(normalMap, NORMAL_UV).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrParams.w) * normalize(v_tangent) +\n (nmmp.y * pbrParams.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n vec4 res = texture(pbrMap, PBR_UV);\n pbr.x *= res.OCCLUSION_CHANNEL;\n pbr.y *= res.ROUGHNESS_CHANNEL;\n pbr.z *= res.METALLIC_CHANNEL;\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture(metallicRoughnessMap, METALLIC_ROUGHNESS_UV);\n pbr.z *= metallicRoughness.METALLIC_CHANNEL;\n pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.x *= texture(occlusionMap, OCCLUSION_UV).OCCLUSION_CHANNEL;\n #endif\n s.occlusion = clamp(pbr.x, 0.0, 0.96);\n s.roughness = clamp(pbr.y, 0.04, 1.0);\n s.metallic = pbr.z;\n s.emissive = emissive.rgb * emissiveScaleParam.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture(emissiveMap, EMISSIVE_UV).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec4 a_tangent;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matWorldIT;\n#endif\nuniform vec4 tilingOffset;\n#if USE_VERTEX_COLOR\n attribute vec3 a_color;\n varying vec3 v_color;\n#endif\nvarying vec3 v_position;\nvarying vec3 v_normal;\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n#endif\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nattribute vec2 a_texCoord1;\nvarying vec2 v_uv1;\nvec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_MORPH\n applyMorph(In);\n #endif\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n mat4 matWorld, matWorldIT;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n matWorldIT = matWorld;\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #if HAS_SECOND_UV\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec4 a_tangent;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matWorldIT;\n#endif\nuniform vec4 tilingOffset;\n#if USE_VERTEX_COLOR\n attribute vec3 a_color;\n varying vec3 v_color;\n#endif\nvarying vec3 v_position;\nvarying vec3 v_normal;\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n#endif\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nattribute vec2 a_texCoord1;\nvarying vec2 v_uv1;\nvec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_MORPH\n applyMorph(In);\n #endif\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n mat4 matWorld, matWorldIT;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n matWorldIT = matWorld;\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #if HAS_SECOND_UV\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\n #ifdef GL_EXT_shader_texture_lod\n #extension GL_EXT_shader_texture_lod : enable\n #endif\nprecision highp float;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_exposure;\nuniform mediump vec4 cc_mainLitDir;\nuniform mediump vec4 cc_mainLitColor;\nuniform mediump vec4 cc_ambientSky;\nuniform mediump vec4 cc_ambientGround;\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\n #ifdef GL_EXT_shader_texture_lod\n return texture2DLodEXT(tex, coord, lod);\n #else\n return texture2D(tex, coord, lod);\n #endif\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\n #ifdef GL_EXT_shader_texture_lod\n return textureCubeLodEXT(tex, coord, lod);\n #else\n return textureCube(tex, coord, lod);\n #endif\n}\n#endif\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nuniform highp vec4 cc_sphereLitPos[2];\nuniform vec4 cc_sphereLitSizeRange[2];\nuniform vec4 cc_sphereLitColor[2];\nuniform highp vec4 cc_spotLitPos[2];\nuniform vec4 cc_spotLitSizeRangeAngle[2];\nuniform vec4 cc_spotLitDir[2];\nuniform vec4 cc_spotLitColor[2];\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting (vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb);\n #endif\n finalColor += env * cc_ambientSky.w * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\n color = min(color, vec3(8.0));\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nuniform vec4 albedo;\nuniform vec4 albedoScaleAndCutoff;\nuniform vec4 pbrParams;\nuniform vec4 emissive;\nuniform vec4 emissiveScaleParam;\nvarying vec3 v_position;\nvarying vec2 v_uv;\nvarying vec2 v_uv1;\nvarying vec3 v_normal;\n#if USE_VERTEX_COLOR\n varying vec3 v_color;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_VERTEX_COLOR\n baseColor.rgb *= v_color;\n #endif\n #if USE_ALBEDO_MAP\n vec4 texColor = texture2D(albedoMap, ALBEDO_UV);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScaleAndCutoff.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture2D(normalMap, NORMAL_UV).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrParams.w) * normalize(v_tangent) +\n (nmmp.y * pbrParams.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n vec4 res = texture2D(pbrMap, PBR_UV);\n pbr.x *= res.OCCLUSION_CHANNEL;\n pbr.y *= res.ROUGHNESS_CHANNEL;\n pbr.z *= res.METALLIC_CHANNEL;\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture2D(metallicRoughnessMap, METALLIC_ROUGHNESS_UV);\n pbr.z *= metallicRoughness.METALLIC_CHANNEL;\n pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.x *= texture2D(occlusionMap, OCCLUSION_UV).OCCLUSION_CHANNEL;\n #endif\n s.occlusion = clamp(pbr.x, 0.0, 0.96);\n s.roughness = clamp(pbr.y, 0.04, 1.0);\n s.metallic = pbr.z;\n s.emissive = emissive.rgb * emissiveScaleParam.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture2D(emissiveMap, EMISSIVE_UV).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": { @@ -438,13 +438,13 @@ export default [ "shaders": [ { "name": "builtin-unlit|unlit-vs:vert|unlit-fs:frag", - "hash": 1851195889, + "hash": 2908788487, "glsl3": { - "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\n#if USE_VERTEX_COLOR\n in vec4 a_color;\n out vec4 v_color;\n#endif\n#if USE_TEXTURE\n in vec2 a_texCoord;\n out vec2 v_uv;\n uniform TexCoords {\n vec4 tilingOffset;\n };\n#endif\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\n#if USE_VERTEX_COLOR\n in vec4 a_color;\n out vec4 v_color;\n#endif\n#if USE_TEXTURE\n in vec2 a_texCoord;\n out vec2 v_uv;\n uniform TexCoords {\n vec4 tilingOffset;\n };\n#endif\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision mediump float;\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n#if USE_ALPHA_TEST\n#endif\n#if USE_TEXTURE\n in vec2 v_uv;\n uniform sampler2D mainTexture;\n#endif\nuniform Constant {\n vec4 mainColor;\n vec4 colorScaleAndCutoff;\n};\n#if USE_VERTEX_COLOR\n in vec4 v_color;\n#endif\nvec4 frag () {\n vec4 o = mainColor;\n o.rgb *= colorScaleAndCutoff.xyz;\n #if USE_VERTEX_COLOR\n o *= v_color;\n #endif\n #if USE_TEXTURE\n o *= texture(mainTexture, v_uv);\n #endif\n #if USE_ALPHA_TEST\n if (o.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard;\n #endif\n return CCFragOutput(o);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\n#if USE_VERTEX_COLOR\n attribute vec4 a_color;\n varying vec4 v_color;\n#endif\n#if USE_TEXTURE\n attribute vec2 a_texCoord;\n varying vec2 v_uv;\n uniform vec4 tilingOffset;\n#endif\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\n#if USE_VERTEX_COLOR\n attribute vec4 a_color;\n varying vec4 v_color;\n#endif\n#if USE_TEXTURE\n attribute vec2 a_texCoord;\n varying vec2 v_uv;\n uniform vec4 tilingOffset;\n#endif\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision mediump float;\nuniform mediump vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n#if USE_ALPHA_TEST\n#endif\n#if USE_TEXTURE\n varying vec2 v_uv;\n uniform sampler2D mainTexture;\n#endif\nuniform vec4 mainColor;\nuniform vec4 colorScaleAndCutoff;\n#if USE_VERTEX_COLOR\n varying vec4 v_color;\n#endif\nvec4 frag () {\n vec4 o = mainColor;\n o.rgb *= colorScaleAndCutoff.xyz;\n #if USE_VERTEX_COLOR\n o *= v_color;\n #endif\n #if USE_TEXTURE\n o *= texture2D(mainTexture, v_uv);\n #endif\n #if USE_ALPHA_TEST\n if (o.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard;\n #endif\n return CCFragOutput(o);\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": { @@ -507,13 +507,13 @@ export default [ "shaders": [ { "name": "pipeline/planar-shadow|planar-shadow-vs:vert|planar-shadow-fs:frag", - "hash": 1445934484, + "hash": 915782623, "glsl3": { - "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nuniform CCShadow {\n highp mat4 cc_matLightPlaneProj;\n lowp vec4 cc_shadowColor;\n};\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n position = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nuniform CCShadow {\n highp mat4 cc_matLightPlaneProj;\n lowp vec4 cc_shadowColor;\n};\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n position = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision mediump float;\nuniform CCShadow {\n highp mat4 cc_matLightPlaneProj;\n lowp vec4 cc_shadowColor;\n};\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvec4 frag () {\n return CCFragOutput(cc_shadowColor);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * i + a_jointAnimInfo.x;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\nuniform highp mat4 cc_matLightPlaneProj;\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n position = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\nuniform highp mat4 cc_matLightPlaneProj;\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n position = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision mediump float;\nuniform lowp vec4 cc_shadowColor;\nuniform mediump vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvec4 frag () {\n return CCFragOutput(cc_shadowColor);\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": { diff --git a/cocos/core/renderer/models/baked-skinning-model.ts b/cocos/core/renderer/models/baked-skinning-model.ts index d06f664855..8bfb81f53a 100644 --- a/cocos/core/renderer/models/baked-skinning-model.ts +++ b/cocos/core/renderer/models/baked-skinning-model.ts @@ -40,7 +40,7 @@ import { Node } from '../../scene-graph'; import { Pass, IMacroPatch } from '../core/pass'; import { samplerLib } from '../core/sampler-lib'; import { DataPoolManager } from '../data-pool-manager'; -import { Model, ModelType } from '../scene/model'; +import { ModelType } from '../scene/model'; import { IAnimInfo, IJointTextureHandle, jointTextureSamplerHash } from './skeletal-animation-utils'; import { MorphModel } from './morph-model'; @@ -130,7 +130,7 @@ export class BakedSkinningModel extends MorphModel { const idx = this._instAnimInfoIdx; if (idx >= 0) { const view = this.instancedAttributes.list[idx].view; - view[0] = view[1] * info.data[0] + view[2]; + view[0] = info.data[0]; } else if (info.dirty) { info.buffer.update(info.data); info.dirty = false; @@ -214,10 +214,9 @@ export class BakedSkinningModel extends MorphModel { const idx = this._instAnimInfoIdx; if (idx >= 0) { // update instancing data too const view = this.instancedAttributes.list[idx].view; - const pixelsPerJoint = this._dataPoolManager.jointTexturePool.pixelsPerJoint; - view[1] = pixelsPerJoint * jointTextureInfo[1]; + view[0] = animInfo.data[0]; + view[1] = jointTextureInfo[1]; view[2] = jointTextureInfo[2]; - view[0] = view[1] * animInfo.data[0] + view[2]; } } } From 32efb3cf62a92ccc0e4d50322d29f9202d98b9fb Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Mon, 1 Jun 2020 19:26:41 +0800 Subject: [PATCH 68/74] fix skinning shader (#6800) --- cocos/core/3d/builtin/effects.ts | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/cocos/core/3d/builtin/effects.ts b/cocos/core/3d/builtin/effects.ts index c5410786ec..3d67432164 100644 --- a/cocos/core/3d/builtin/effects.ts +++ b/cocos/core/3d/builtin/effects.ts @@ -296,13 +296,13 @@ export default [ "shaders": [ { "name": "builtin-standard|standard-vs:vert|standard-fs:frag", - "hash": 3369013589, + "hash": 1377525096, "glsl3": { - "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec4 a_tangent;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScaleParam;\n};\n#if USE_VERTEX_COLOR\n in vec3 a_color;\n out vec3 v_color;\n#endif\nout vec3 v_position;\nout vec3 v_normal;\n#if USE_NORMAL_MAP\n out vec3 v_tangent;\n out vec3 v_bitangent;\n#endif\nin vec2 a_texCoord;\nout vec2 v_uv;\nin vec2 a_texCoord1;\nout vec2 v_uv1;\nvec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_MORPH\n applyMorph(In);\n #endif\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n mat4 matWorld, matWorldIT;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n matWorldIT = matWorld;\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #if HAS_SECOND_UV\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec4 a_tangent;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScaleParam;\n};\n#if USE_VERTEX_COLOR\n in vec3 a_color;\n out vec3 v_color;\n#endif\nout vec3 v_position;\nout vec3 v_normal;\n#if USE_NORMAL_MAP\n out vec3 v_tangent;\n out vec3 v_bitangent;\n#endif\nin vec2 a_texCoord;\nout vec2 v_uv;\nin vec2 a_texCoord1;\nout vec2 v_uv1;\nvec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_MORPH\n applyMorph(In);\n #endif\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n mat4 matWorld, matWorldIT;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n matWorldIT = matWorld;\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #if HAS_SECOND_UV\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision highp float;\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\n return textureLod(tex, coord, lod);\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\n return textureLod(tex, coord, lod);\n}\n#endif\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nuniform CCForwardLight {\n highp vec4 cc_sphereLitPos[2];\n vec4 cc_sphereLitSizeRange[2];\n vec4 cc_sphereLitColor[2];\n highp vec4 cc_spotLitPos[2];\n vec4 cc_spotLitSizeRangeAngle[2];\n vec4 cc_spotLitDir[2];\n vec4 cc_spotLitColor[2];\n};\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting (vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb);\n #endif\n finalColor += env * cc_ambientSky.w * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\n color = min(color, vec3(8.0));\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScaleParam;\n};\nin vec3 v_position;\nin vec2 v_uv;\nin vec2 v_uv1;\nin vec3 v_normal;\n#if USE_VERTEX_COLOR\n in vec3 v_color;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n in vec3 v_tangent;\n in vec3 v_bitangent;\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_VERTEX_COLOR\n baseColor.rgb *= v_color;\n #endif\n #if USE_ALBEDO_MAP\n vec4 texColor = texture(albedoMap, ALBEDO_UV);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScaleAndCutoff.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture(normalMap, NORMAL_UV).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrParams.w) * normalize(v_tangent) +\n (nmmp.y * pbrParams.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n vec4 res = texture(pbrMap, PBR_UV);\n pbr.x *= res.OCCLUSION_CHANNEL;\n pbr.y *= res.ROUGHNESS_CHANNEL;\n pbr.z *= res.METALLIC_CHANNEL;\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture(metallicRoughnessMap, METALLIC_ROUGHNESS_UV);\n pbr.z *= metallicRoughness.METALLIC_CHANNEL;\n pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.x *= texture(occlusionMap, OCCLUSION_UV).OCCLUSION_CHANNEL;\n #endif\n s.occlusion = clamp(pbr.x, 0.0, 0.96);\n s.roughness = clamp(pbr.y, 0.04, 1.0);\n s.metallic = pbr.z;\n s.emissive = emissive.rgb * emissiveScaleParam.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture(emissiveMap, EMISSIVE_UV).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec4 a_tangent;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matWorldIT;\n#endif\nuniform vec4 tilingOffset;\n#if USE_VERTEX_COLOR\n attribute vec3 a_color;\n varying vec3 v_color;\n#endif\nvarying vec3 v_position;\nvarying vec3 v_normal;\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n#endif\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nattribute vec2 a_texCoord1;\nvarying vec2 v_uv1;\nvec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_MORPH\n applyMorph(In);\n #endif\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n mat4 matWorld, matWorldIT;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n matWorldIT = matWorld;\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #if HAS_SECOND_UV\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec4 a_tangent;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matWorldIT;\n#endif\nuniform vec4 tilingOffset;\n#if USE_VERTEX_COLOR\n attribute vec3 a_color;\n varying vec3 v_color;\n#endif\nvarying vec3 v_position;\nvarying vec3 v_normal;\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n#endif\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nattribute vec2 a_texCoord1;\nvarying vec2 v_uv1;\nvec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_MORPH\n applyMorph(In);\n #endif\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n mat4 matWorld, matWorldIT;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n matWorldIT = matWorld;\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #if HAS_SECOND_UV\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\n #ifdef GL_EXT_shader_texture_lod\n #extension GL_EXT_shader_texture_lod : enable\n #endif\nprecision highp float;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_exposure;\nuniform mediump vec4 cc_mainLitDir;\nuniform mediump vec4 cc_mainLitColor;\nuniform mediump vec4 cc_ambientSky;\nuniform mediump vec4 cc_ambientGround;\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\n #ifdef GL_EXT_shader_texture_lod\n return texture2DLodEXT(tex, coord, lod);\n #else\n return texture2D(tex, coord, lod);\n #endif\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\n #ifdef GL_EXT_shader_texture_lod\n return textureCubeLodEXT(tex, coord, lod);\n #else\n return textureCube(tex, coord, lod);\n #endif\n}\n#endif\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nuniform highp vec4 cc_sphereLitPos[2];\nuniform vec4 cc_sphereLitSizeRange[2];\nuniform vec4 cc_sphereLitColor[2];\nuniform highp vec4 cc_spotLitPos[2];\nuniform vec4 cc_spotLitSizeRangeAngle[2];\nuniform vec4 cc_spotLitDir[2];\nuniform vec4 cc_spotLitColor[2];\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting (vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb);\n #endif\n finalColor += env * cc_ambientSky.w * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\n color = min(color, vec3(8.0));\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nuniform vec4 albedo;\nuniform vec4 albedoScaleAndCutoff;\nuniform vec4 pbrParams;\nuniform vec4 emissive;\nuniform vec4 emissiveScaleParam;\nvarying vec3 v_position;\nvarying vec2 v_uv;\nvarying vec2 v_uv1;\nvarying vec3 v_normal;\n#if USE_VERTEX_COLOR\n varying vec3 v_color;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_VERTEX_COLOR\n baseColor.rgb *= v_color;\n #endif\n #if USE_ALBEDO_MAP\n vec4 texColor = texture2D(albedoMap, ALBEDO_UV);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScaleAndCutoff.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture2D(normalMap, NORMAL_UV).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrParams.w) * normalize(v_tangent) +\n (nmmp.y * pbrParams.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n vec4 res = texture2D(pbrMap, PBR_UV);\n pbr.x *= res.OCCLUSION_CHANNEL;\n pbr.y *= res.ROUGHNESS_CHANNEL;\n pbr.z *= res.METALLIC_CHANNEL;\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture2D(metallicRoughnessMap, METALLIC_ROUGHNESS_UV);\n pbr.z *= metallicRoughness.METALLIC_CHANNEL;\n pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.x *= texture2D(occlusionMap, OCCLUSION_UV).OCCLUSION_CHANNEL;\n #endif\n s.occlusion = clamp(pbr.x, 0.0, 0.96);\n s.roughness = clamp(pbr.y, 0.04, 1.0);\n s.metallic = pbr.z;\n s.emissive = emissive.rgb * emissiveScaleParam.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture2D(emissiveMap, EMISSIVE_UV).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": { @@ -438,13 +438,13 @@ export default [ "shaders": [ { "name": "builtin-unlit|unlit-vs:vert|unlit-fs:frag", - "hash": 2908788487, + "hash": 3773155015, "glsl3": { - "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\n#if USE_VERTEX_COLOR\n in vec4 a_color;\n out vec4 v_color;\n#endif\n#if USE_TEXTURE\n in vec2 a_texCoord;\n out vec2 v_uv;\n uniform TexCoords {\n vec4 tilingOffset;\n };\n#endif\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\n#if USE_VERTEX_COLOR\n in vec4 a_color;\n out vec4 v_color;\n#endif\n#if USE_TEXTURE\n in vec2 a_texCoord;\n out vec2 v_uv;\n uniform TexCoords {\n vec4 tilingOffset;\n };\n#endif\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision mediump float;\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n#if USE_ALPHA_TEST\n#endif\n#if USE_TEXTURE\n in vec2 v_uv;\n uniform sampler2D mainTexture;\n#endif\nuniform Constant {\n vec4 mainColor;\n vec4 colorScaleAndCutoff;\n};\n#if USE_VERTEX_COLOR\n in vec4 v_color;\n#endif\nvec4 frag () {\n vec4 o = mainColor;\n o.rgb *= colorScaleAndCutoff.xyz;\n #if USE_VERTEX_COLOR\n o *= v_color;\n #endif\n #if USE_TEXTURE\n o *= texture(mainTexture, v_uv);\n #endif\n #if USE_ALPHA_TEST\n if (o.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard;\n #endif\n return CCFragOutput(o);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\n#if USE_VERTEX_COLOR\n attribute vec4 a_color;\n varying vec4 v_color;\n#endif\n#if USE_TEXTURE\n attribute vec2 a_texCoord;\n varying vec2 v_uv;\n uniform vec4 tilingOffset;\n#endif\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\n#if USE_VERTEX_COLOR\n attribute vec4 a_color;\n varying vec4 v_color;\n#endif\n#if USE_TEXTURE\n attribute vec2 a_texCoord;\n varying vec2 v_uv;\n uniform vec4 tilingOffset;\n#endif\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision mediump float;\nuniform mediump vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n#if USE_ALPHA_TEST\n#endif\n#if USE_TEXTURE\n varying vec2 v_uv;\n uniform sampler2D mainTexture;\n#endif\nuniform vec4 mainColor;\nuniform vec4 colorScaleAndCutoff;\n#if USE_VERTEX_COLOR\n varying vec4 v_color;\n#endif\nvec4 frag () {\n vec4 o = mainColor;\n o.rgb *= colorScaleAndCutoff.xyz;\n #if USE_VERTEX_COLOR\n o *= v_color;\n #endif\n #if USE_TEXTURE\n o *= texture2D(mainTexture, v_uv);\n #endif\n #if USE_ALPHA_TEST\n if (o.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard;\n #endif\n return CCFragOutput(o);\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": { @@ -507,13 +507,13 @@ export default [ "shaders": [ { "name": "pipeline/planar-shadow|planar-shadow-vs:vert|planar-shadow-fs:frag", - "hash": 915782623, + "hash": 333056161, "glsl3": { - "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nuniform CCShadow {\n highp mat4 cc_matLightPlaneProj;\n lowp vec4 cc_shadowColor;\n};\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n position = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nuniform CCShadow {\n highp mat4 cc_matLightPlaneProj;\n lowp vec4 cc_shadowColor;\n};\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n position = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision mediump float;\nuniform CCShadow {\n highp mat4 cc_matLightPlaneProj;\n lowp vec4 cc_shadowColor;\n};\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvec4 frag () {\n return CCFragOutput(cc_shadowColor);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (cc_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\nuniform highp mat4 cc_matLightPlaneProj;\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n position = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\nuniform highp mat4 cc_matLightPlaneProj;\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n position = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision mediump float;\nuniform lowp vec4 cc_shadowColor;\nuniform mediump vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvec4 frag () {\n return CCFragOutput(cc_shadowColor);\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": { From 51ecb2f1af80f91d33223dd8a5564a10b51f2f34 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 2 Jun 2020 11:25:40 +0800 Subject: [PATCH 69/74] Fix CLEANUP_IMAGE_CACHE not working issue (#6803) --- cocos/core/assets/simple-texture.ts | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/cocos/core/assets/simple-texture.ts b/cocos/core/assets/simple-texture.ts index 9e9baccec3..d463ae65a6 100644 --- a/cocos/core/assets/simple-texture.ts +++ b/cocos/core/assets/simple-texture.ts @@ -12,6 +12,7 @@ import { Filter } from './asset-enum'; import { ImageAsset } from './image-asset'; import { TextureBase } from './texture-base'; import { DEV } from 'internal:constants'; +import { macro } from '../platform/macro'; const _regions: GFXBufferTextureCopy[] = [{ buffOffset: 0, @@ -152,6 +153,12 @@ export class SimpleTexture extends TextureBase { } this.uploadData(data, level, arrayIndex); this._checkTextureLoaded(); + + if (macro.CLEANUP_IMAGE_CACHE) { + if (data instanceof HTMLImageElement) { + data.src = ""; + } + } }; if (image.loaded) { upload(); From 7079d5e1afefed21d12bbccbb7613d0969896910 Mon Sep 17 00:00:00 2001 From: "jiaxin.lai" Date: Tue, 2 Jun 2020 12:54:05 +0800 Subject: [PATCH 70/74] Fix ray_subMesh/mesh/model (#6801) * fix ray_subMesh/mesh/model * tweaks * tweaks * tweaks * fix ray_model * tweaks * tweaks * docs * tweaks --- cocos/core/geometry/intersect.ts | 165 +++++++++++++++++-------------- cocos/core/geometry/spec.ts | 114 ++++++++++++++++++++- 2 files changed, 201 insertions(+), 78 deletions(-) diff --git a/cocos/core/geometry/intersect.ts b/cocos/core/geometry/intersect.ts index d2ea594b9d..c8c6551728 100644 --- a/cocos/core/geometry/intersect.ts +++ b/cocos/core/geometry/intersect.ts @@ -324,17 +324,34 @@ const ray_capsule = (function () { * ray-subMesh intersect detect. * @zh * 射线和子三角网格的相交性检测。 + * @param {ray} ray + * @param {RenderingSubMesh} subMesh + * @param {IRaySubMeshOptions} options + * @return {number} 0 or !0 */ const ray_subMesh = (function () { const tri = triangle.create(); const deOpt: IRaySubMeshOptions = { distance: Infinity, doubleSided: false, mode: ERaycastMode.ANY }; - const tr: IRaySubMeshResult = { distance: 0, vertexIndex0: 0, vertexIndex1: 0, vertexIndex2: 0 }; let minDis = 0; - const broadphase = (ray: ray, submesh: RenderingSubMesh) => { - const min = submesh.geometricInfo.boundingBox.min; - const max = submesh.geometricInfo.boundingBox.max; - return ray_aabb2(ray, min, max); + + const fillResult = (m: ERaycastMode, d: number, i0: number, i1: number, i2: number, r?: IRaySubMeshResult[]) => { + if (m == ERaycastMode.CLOSEST) { + if (minDis > d || minDis == 0) { + minDis = d; + if (r) { + if (r.length == 0) { + r.push({ distance: d, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 }); + } else { + r[0].distance = d; r[0].vertexIndex0 = i0; r[0].vertexIndex1 = i1; r[0].vertexIndex2 = i2; + } + } + } + } else { + minDis = d; + if (r) r.push({ distance: d, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 }); + } } + const narrowphase = (vb: Float32Array, ib: IBArray, pm: GFXPrimitiveMode, ray: ray, opt: IRaySubMeshOptions) => { if (pm === GFXPrimitiveMode.TRIANGLE_LIST) { const cnt = ib.length; @@ -346,25 +363,9 @@ const ray_subMesh = (function () { Vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]); Vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]); const dist = intersect.ray_triangle(ray, tri, opt.doubleSided); - if (dist == 0 || dist > opt.distance!) continue; - if (opt.mode == ERaycastMode.CLOSEST) { - if (minDis > dist || minDis == 0) { - minDis = dist; - tr.distance = dist; - tr.vertexIndex0 = i0; - tr.vertexIndex1 = i1; - tr.vertexIndex2 = i2; - if (opt.result && j + 3 < cnt) - opt.result.push({ distance: tr.distance, vertexIndex0: tr.vertexIndex0, vertexIndex1: tr.vertexIndex1, vertexIndex2: tr.vertexIndex2 }); - } - } else if (opt.mode == ERaycastMode.ALL) { - minDis = dist; - if (opt.result) opt.result.push({ distance: dist, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 }); - } else { - minDis = dist; - if (opt.result) opt.result.push({ distance: dist, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 }); - return minDis; - } + if (dist == 0 || dist > opt.distance) continue; + fillResult(opt.mode, dist, i0, i1, i2, opt.result); + if (opt.mode == ERaycastMode.ANY) return dist; } } else if (pm === GFXPrimitiveMode.TRIANGLE_STRIP) { const cnt = ib.length - 2; @@ -378,18 +379,9 @@ const ray_subMesh = (function () { Vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]); rev = ~rev; const dist = intersect.ray_triangle(ray, tri, opt.doubleSided); - if (dist == 0 || dist > opt.distance!) continue; - if (opt.mode == ERaycastMode.CLOSEST) { - if (minDis < dist) continue; - if (opt.result) opt.result.push({ distance: dist, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 }); - } else if (opt.mode == ERaycastMode.ALL) { - minDis = dist; - if (opt.result) opt.result.push({ distance: dist, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 }); - } else { - minDis = dist; - if (opt.result) opt.result.push({ distance: dist, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 }); - return minDis; - } + if (dist == 0 || dist > opt.distance) continue; + fillResult(opt.mode, dist, i0, i1, i2, opt.result); + if (opt.mode == ERaycastMode.ANY) return dist; } } else if (pm === GFXPrimitiveMode.TRIANGLE_FAN) { const cnt = ib.length - 1; @@ -401,32 +393,25 @@ const ray_subMesh = (function () { Vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]); Vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]); const dist = intersect.ray_triangle(ray, tri, opt.doubleSided); - if (dist == 0 || dist > opt.distance!) continue; - if (opt.mode == ERaycastMode.CLOSEST) { - if (minDis < dist) continue; - if (opt.result) opt.result.push({ distance: dist, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 }); - } else if (opt.mode == ERaycastMode.ALL) { - minDis = dist; - if (opt.result) opt.result.push({ distance: dist, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 }); - } else { - minDis = dist; - if (opt.result) opt.result.push({ distance: dist, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 }); - return minDis; - } + if (dist == 0 || dist > opt.distance) continue; + fillResult(opt.mode, dist, i0, i1, i2, opt.result); + if (opt.mode == ERaycastMode.ANY) return dist; } } return minDis; }; return function (ray: ray, submesh: RenderingSubMesh, option?: IRaySubMeshOptions) { + minDis = 0; + if (submesh.geometricInfo.positions.length == 0) return minDis; const opt = option == undefined ? deOpt : option; - if (!opt.doNotZeroMin) minDis = 0; - if (submesh.geometricInfo.positions.length == 0) return; - if (broadphase(ray, submesh)) { + const min = submesh.geometricInfo.boundingBox.min; + const max = submesh.geometricInfo.boundingBox.max; + if (ray_aabb2(ray, min, max)) { const pm = submesh.primitiveMode; const { positions: vb, indices: ib } = submesh.geometricInfo!; narrowphase(vb, ib!, pm, ray, opt); } - return minDis != 0; + return minDis; } })(); @@ -435,27 +420,44 @@ const ray_subMesh = (function () { * ray-mesh intersect detect. * @zh * 射线和三角网格资源的相交性检测。 + * @param {ray} ray + * @param {Mesh} mesh + * @param {IRayMeshOptions} options + * @return {number} 0 or !0 */ const ray_mesh = (function () { - const deOpt: IRayMeshOptions = { distance: Infinity, doubleSided: false, mode: ERaycastMode.ANY, doNotZeroMin: true }; + let minDis = 0; + const deOpt: IRayMeshOptions = { distance: Infinity, doubleSided: false, mode: ERaycastMode.ANY }; return function (ray: ray, mesh: Mesh, option?: IRayMeshOptions) { + minDis = 0; const opt = option == undefined ? deOpt : option; const length = mesh.renderingSubMeshes.length; - let result = false; const min = mesh.struct.minPosition; const max = mesh.struct.maxPosition; - if (min && max && !ray_aabb2(ray, min, max)) return false; + if (min && max && !ray_aabb2(ray, min, max)) return minDis; for (let i = 0; i < length; i++) { const sm = mesh.renderingSubMeshes[i]; - if (ray_subMesh(ray, sm, opt)) { - result = true; - if (opt.subIndices) opt.subIndices.push(i); - if (opt.mode == ERaycastMode.ANY) { - return true; + const dis = ray_subMesh(ray, sm, opt); + if (dis) { + if (opt.mode == ERaycastMode.CLOSEST) { + if (minDis == 0 || minDis > dis) { + minDis = dis; + if (opt.subIndices) opt.subIndices[0] = i; + } + } else { + minDis = dis; + if (opt.subIndices) opt.subIndices.push(i); + if (opt.mode == ERaycastMode.ANY) { + return dis; + } } } } - return result; + if (minDis && opt.mode == ERaycastMode.CLOSEST) { + if (opt.result) opt.result.length = 1; + if (opt.subIndices) opt.subIndices.length = 1; + } + return minDis; } })(); @@ -464,34 +466,51 @@ const ray_mesh = (function () { * ray-model intersect detect. * @zh * 射线和渲染模型的相交性检测。 + * @param {ray} ray + * @param {Model} model + * @param {IRayModelOptions} options + * @return {number} 0 or !0 */ const ray_model = (function () { - const deOpt: IRayModelOptions = { distance: Infinity, doubleSided: false, mode: ERaycastMode.ANY, doNotZeroMin: true, doNotTransformRay: false }; + let minDis = 0; + const deOpt: IRayModelOptions = { distance: Infinity, doubleSided: false, mode: ERaycastMode.ANY }; const modelRay = new ray(); - const m4 = new Mat4; + const m4 = new Mat4(); return function (r: ray, model: Model, option?: IRayModelOptions) { + minDis = 0; const opt = option == undefined ? deOpt : option; const length = model.subModelNum; - let result = false; + const wb = model.worldBounds; + if (wb && !ray_aabb(r, wb)) return minDis; ray.copy(modelRay, r); - if (!opt.doNotTransformRay) { + if (model.node) { Mat4.invert(m4, model.node.getWorldMatrix(m4)); Vec3.transformMat4(modelRay.o, r.o, m4); Vec3.normalize(modelRay.d, Vec3.transformMat4Normal(modelRay.d, r.d, m4)); } - const box = model.modelBounds; - if (box && !ray_aabb(modelRay, box)) return false; for (let i = 0; i < length; i++) { const sm = model.getSubModel(i).subMeshData; - if (ray_subMesh(modelRay, sm, opt)) { - result = true; - if (opt.subIndices) opt.subIndices.push(i); - if (opt.mode == ERaycastMode.ANY) { - return true; + const dis = ray_subMesh(modelRay, sm, opt); + if (dis) { + if (opt.mode == ERaycastMode.CLOSEST) { + if (minDis == 0 || minDis > dis) { + minDis = dis; + if (opt.subIndices) opt.subIndices[0] = i; + } + } else { + minDis = dis; + if (opt.subIndices) opt.subIndices.push(i); + if (opt.mode == ERaycastMode.ANY) { + return dis; + } } } } - return result; + if (minDis && opt.mode == ERaycastMode.CLOSEST) { + if (opt.result) opt.result.length = 1; + if (opt.subIndices) opt.subIndices.length = 1; + } + return minDis; } })(); diff --git a/cocos/core/geometry/spec.ts b/cocos/core/geometry/spec.ts index d014f46a6b..6f875d2eac 100644 --- a/cocos/core/geometry/spec.ts +++ b/cocos/core/geometry/spec.ts @@ -2,39 +2,143 @@ * @category geometry */ -export enum ERaycastMode { +/** + * @en + * The raycast mode. + * @zh + * 射线检测模式。 + */ +export enum ERaycastMode { + + /** + * @en + * Detect and record all data. + * @zh + * 检测并记录所有的数据。 + */ ALL, + + /** + * @en + * Detect all, but record only the most recent data. + * @zh + * 检测所有,但只记录最近的数据。 + */ CLOSEST, + + /** + * @en + * Once the test is successful, the test is stopped and the data is recorded only once. + * @zh + * 一旦检测成功就停止检测,只会记录一次数据。 + */ ANY, } +/** + * @en + * The storage structure of the raycast results. + * @zh + * 射线检测结果的存储结构。 + */ export interface IRaySubMeshResult { + + /** + * @en + * The distance between the hit point and the ray. + * @zh + * 击中点和射线的距离。 + */ distance: number; + + /** + * @en + * The index of the triangle vertex 0。 + * @zh + * 三角形顶点0的索引。 + */ vertexIndex0: number; + + /** + * @en + * The index of the triangle vertex 1。 + * @zh + * 三角形顶点1的索引 + */ vertexIndex1: number; + + /** + * @en + * The index of the triangle vertex 2。 + * @zh + * 三角形顶点2的索引 + */ vertexIndex2: number; } +/** + * @en + * The optional param structure of the `ray_subMesh`. + * @zh + * `ray_subMesh`的可选参数结构。 + */ export interface IRaySubMeshOptions { + /** + * @en + * The raycast mode,`ANY` by default. * @zh - * 检测模式:[0,1,2]=>[ALL,CLOSEST,ANY] + * 射线检测模式:[0, 1, 2]=>[`ALL`, `CLOSEST`, `ANY`] */ mode: ERaycastMode; + /** + * @en + * The maximum distance of the raycast, `Infinity` by default. * @zh - * 检测的最大距离 + * 射线检测的最大距离,默认为`Infinity`。 */ distance: number; + + /** + * @en + * An array used to store the results of a ray detection. + * @zh + * 用于存储射线检测结果的数组。 + */ result?: IRaySubMeshResult[]; + + /** + * @en + * Whether to detect the double-sided or not,`false` by default. + * @zh + * 是否检测双面,默认为`false`。 + */ doubleSided?: boolean; - doNotZeroMin?: boolean; } +/** + * @en + * The optional param structure of the `ray_mesh`. + * @zh + * `ray_mesh`的可选参数结构。 + */ export interface IRayMeshOptions extends IRaySubMeshOptions { + + /** + * @en + * The index of the sub mesh. + * @zh + * 子网格的索引。 + */ subIndices?: number[]; } +/** + * @en + * The optional param structure of the `ray_model`. + * @zh + * `ray_model`的可选参数结构。 + */ export interface IRayModelOptions extends IRayMeshOptions { - doNotTransformRay?: boolean; } \ No newline at end of file From def53e4c748c1e2574bf1218d71faaff5b00efb6 Mon Sep 17 00:00:00 2001 From: pandamicro Date: Tue, 2 Jun 2020 13:52:55 +0800 Subject: [PATCH 71/74] Restore ImageAsset destroy logic to help destroy Image (#6804) --- cocos/core/assets/image-asset.ts | 17 ++++++++--------- cocos/core/assets/simple-texture.ts | 4 +--- 2 files changed, 9 insertions(+), 12 deletions(-) diff --git a/cocos/core/assets/image-asset.ts b/cocos/core/assets/image-asset.ts index b597415a06..6c66f18ee9 100644 --- a/cocos/core/assets/image-asset.ts +++ b/cocos/core/assets/image-asset.ts @@ -77,7 +77,7 @@ export class ImageAsset extends Asset { * 此图像资源的图像数据。 */ get data () { - const data = (this._nativeData as IMemoryImageSource)._data; + const data = this._nativeData && (this._nativeData as IMemoryImageSource)._data; return ArrayBuffer.isView(data) ? data : this._nativeData as (HTMLCanvasElement | HTMLImageElement); } @@ -199,14 +199,13 @@ export class ImageAsset extends Asset { } } - // destroy() { - // if (cc.macro.CLEANUP_IMAGE_CACHE) { - // if (this._data instanceof HTMLImageElement) { - // this._data.src = ""; - // cc.loader.removeItem(this._data.id); - // } - // } - // } + public destroy (): boolean { + if (this.data && this.data instanceof HTMLImageElement) { + this.data.src = ""; + cc.loader.removeItem(this.data.id); + } + return super.destroy(); + } // SERIALIZATION diff --git a/cocos/core/assets/simple-texture.ts b/cocos/core/assets/simple-texture.ts index d463ae65a6..7d819cc69e 100644 --- a/cocos/core/assets/simple-texture.ts +++ b/cocos/core/assets/simple-texture.ts @@ -155,9 +155,7 @@ export class SimpleTexture extends TextureBase { this._checkTextureLoaded(); if (macro.CLEANUP_IMAGE_CACHE) { - if (data instanceof HTMLImageElement) { - data.src = ""; - } + image.destroy(); } }; if (image.loaded) { From 8086fe64949aee7990ee811be76ae19b0a73070c Mon Sep 17 00:00:00 2001 From: Yun Hsiao Wu Date: Tue, 2 Jun 2020 16:32:35 +0800 Subject: [PATCH 72/74] fix skybox binding layout update (#6806) --- cocos/core/3d/builtin/effects.ts | 24 ++++++++++++------------ cocos/core/renderer/scene/skybox.ts | 7 +++++-- 2 files changed, 17 insertions(+), 14 deletions(-) diff --git a/cocos/core/3d/builtin/effects.ts b/cocos/core/3d/builtin/effects.ts index 3d67432164..e7a4403780 100644 --- a/cocos/core/3d/builtin/effects.ts +++ b/cocos/core/3d/builtin/effects.ts @@ -296,13 +296,13 @@ export default [ "shaders": [ { "name": "builtin-standard|standard-vs:vert|standard-fs:frag", - "hash": 1377525096, + "hash": 2048859965, "glsl3": { - "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec4 a_tangent;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScaleParam;\n};\n#if USE_VERTEX_COLOR\n in vec3 a_color;\n out vec3 v_color;\n#endif\nout vec3 v_position;\nout vec3 v_normal;\n#if USE_NORMAL_MAP\n out vec3 v_tangent;\n out vec3 v_bitangent;\n#endif\nin vec2 a_texCoord;\nout vec2 v_uv;\nin vec2 a_texCoord1;\nout vec2 v_uv1;\nvec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_MORPH\n applyMorph(In);\n #endif\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n mat4 matWorld, matWorldIT;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n matWorldIT = matWorld;\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #if HAS_SECOND_UV\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec4 a_tangent;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in highp vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScaleParam;\n};\n#if USE_VERTEX_COLOR\n in vec3 a_color;\n out vec3 v_color;\n#endif\nout vec3 v_position;\nout vec3 v_normal;\n#if USE_NORMAL_MAP\n out vec3 v_tangent;\n out vec3 v_bitangent;\n#endif\nin vec2 a_texCoord;\nout vec2 v_uv;\nin vec2 a_texCoord1;\nout vec2 v_uv1;\nvec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_MORPH\n applyMorph(In);\n #endif\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n mat4 matWorld, matWorldIT;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n matWorldIT = matWorld;\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #if HAS_SECOND_UV\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision highp float;\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\n return textureLod(tex, coord, lod);\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\n return textureLod(tex, coord, lod);\n}\n#endif\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nuniform CCForwardLight {\n highp vec4 cc_sphereLitPos[2];\n vec4 cc_sphereLitSizeRange[2];\n vec4 cc_sphereLitColor[2];\n highp vec4 cc_spotLitPos[2];\n vec4 cc_spotLitSizeRangeAngle[2];\n vec4 cc_spotLitDir[2];\n vec4 cc_spotLitColor[2];\n};\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting (vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb);\n #endif\n finalColor += env * cc_ambientSky.w * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\n color = min(color, vec3(8.0));\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScaleParam;\n};\nin vec3 v_position;\nin vec2 v_uv;\nin vec2 v_uv1;\nin vec3 v_normal;\n#if USE_VERTEX_COLOR\n in vec3 v_color;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n in vec3 v_tangent;\n in vec3 v_bitangent;\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_VERTEX_COLOR\n baseColor.rgb *= v_color;\n #endif\n #if USE_ALBEDO_MAP\n vec4 texColor = texture(albedoMap, ALBEDO_UV);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScaleAndCutoff.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture(normalMap, NORMAL_UV).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrParams.w) * normalize(v_tangent) +\n (nmmp.y * pbrParams.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n vec4 res = texture(pbrMap, PBR_UV);\n pbr.x *= res.OCCLUSION_CHANNEL;\n pbr.y *= res.ROUGHNESS_CHANNEL;\n pbr.z *= res.METALLIC_CHANNEL;\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture(metallicRoughnessMap, METALLIC_ROUGHNESS_UV);\n pbr.z *= metallicRoughness.METALLIC_CHANNEL;\n pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.x *= texture(occlusionMap, OCCLUSION_UV).OCCLUSION_CHANNEL;\n #endif\n s.occlusion = clamp(pbr.x, 0.0, 0.96);\n s.roughness = clamp(pbr.y, 0.04, 1.0);\n s.metallic = pbr.z;\n s.emissive = emissive.rgb * emissiveScaleParam.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture(emissiveMap, EMISSIVE_UV).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec4 a_tangent;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matWorldIT;\n#endif\nuniform vec4 tilingOffset;\n#if USE_VERTEX_COLOR\n attribute vec3 a_color;\n varying vec3 v_color;\n#endif\nvarying vec3 v_position;\nvarying vec3 v_normal;\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n#endif\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nattribute vec2 a_texCoord1;\nvarying vec2 v_uv1;\nvec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_MORPH\n applyMorph(In);\n #endif\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n mat4 matWorld, matWorldIT;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n matWorldIT = matWorld;\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #if HAS_SECOND_UV\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec4 a_tangent;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute highp vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matWorldIT;\n#endif\nuniform vec4 tilingOffset;\n#if USE_VERTEX_COLOR\n attribute vec3 a_color;\n varying vec3 v_color;\n#endif\nvarying vec3 v_position;\nvarying vec3 v_normal;\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n#endif\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nattribute vec2 a_texCoord1;\nvarying vec2 v_uv1;\nvec4 vert () {\n StandardVertInput In;\n In.position = vec4(a_position, 1.0);\n In.normal = a_normal;\n In.tangent = a_tangent;\n #if CC_USE_MORPH\n applyMorph(In);\n #endif\n #if CC_USE_SKINNING\n CCSkin(In);\n #endif\n mat4 matWorld, matWorldIT;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n matWorldIT = matWorld;\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n matWorldIT = matWorld;\n #else\n matWorld = cc_matWorld;\n matWorldIT = cc_matWorldIT;\n #endif\n vec4 pos = matWorld * In.position;\n v_position = pos.xyz;\n v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n #if USE_NORMAL_MAP\n v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\n v_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n #endif\n v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n #if HAS_SECOND_UV\n v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * In.position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\n #ifdef GL_EXT_shader_texture_lod\n #extension GL_EXT_shader_texture_lod : enable\n #endif\nprecision highp float;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_exposure;\nuniform mediump vec4 cc_mainLitDir;\nuniform mediump vec4 cc_mainLitColor;\nuniform mediump vec4 cc_ambientSky;\nuniform mediump vec4 cc_ambientGround;\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\n return rgbe.rgb * pow(2.0, rgbe.a * 255.0 - 128.0);\n}\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\n #ifdef GL_EXT_shader_texture_lod\n return texture2DLodEXT(tex, coord, lod);\n #else\n return texture2D(tex, coord, lod);\n #endif\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\n #ifdef GL_EXT_shader_texture_lod\n return textureCubeLodEXT(tex, coord, lod);\n #else\n return textureCube(tex, coord, lod);\n #endif\n}\n#endif\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nuniform highp vec4 cc_sphereLitPos[2];\nuniform vec4 cc_sphereLitSizeRange[2];\nuniform vec4 cc_sphereLitColor[2];\nuniform highp vec4 cc_spotLitPos[2];\nuniform vec4 cc_spotLitSizeRangeAngle[2];\nuniform vec4 cc_spotLitDir[2];\nuniform vec4 cc_spotLitColor[2];\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\n float factor = distSqr * invSqrAttRadius;\n float smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\n return smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\n float attenuation = 1.0 / max(distSqr, 0.01*0.01);\n attenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\n return attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\n float cd = dot(litDir, L);\n float attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\n return (attenuation * attenuation);\n}\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\n vec3 NxH = cross(N, H);\n float OneMinusNoHSqr = dot(NxH, NxH);\n float a = roughness * roughness;\n float n = NoH * a;\n float p = a / (OneMinusNoHSqr + n * n);\n return p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\n return (roughness*0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\n const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\n const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\n vec4 r = roughness * c0 + c1;\n float a004 = min( r.x * r.x, exp2( -9.28 * NoV ) ) * r.x + r.y;\n vec2 AB = vec2( -1.04, 1.04 ) * a004 + r.zw;\n AB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\n return specular * AB.x + AB.y;\n}\nvec3 CalcDynamicLighting (vec3 worldPos, vec3 N, vec3 V, vec3 diffuse, vec3 specular, float roughness) {\n vec3 lighting = vec3(0.0);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n for (int i = 0; i < 2; i++) {\n vec3 PLU = cc_sphereLitPos[i].xyz - worldPos;\n vec3 PL = normalize(PLU);\n vec3 PH = normalize(PL + V);\n float PNL = max(dot(N, PL), 0.001);\n float PNH = max(dot(N, PH), 0.0);\n float distSqr = dot(PLU, PLU);\n float litRadius = cc_sphereLitSizeRange[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_sphereLitSizeRange[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(roughness, PNH, PH, N);\n lighting += PNL * cc_sphereLitColor[i].rgb * cc_sphereLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n for (int i = 0; i < 2; i++) {\n vec3 SLU = cc_spotLitPos[i].xyz - worldPos;\n vec3 SL = normalize(SLU);\n vec3 SH = normalize(SL + V);\n float SNL = max(dot(N, SL), 0.001);\n float SNH = max(dot(N, SH), 0.0);\n float distSqr = dot(SLU, SLU);\n float litRadius = cc_spotLitSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_spotLitSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float cosInner = max(dot(-cc_spotLitDir[i].xyz, SL), 0.01);\n float cosOuter = cc_spotLitSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n att *= GetAngleAtt(SL, -cc_spotLitDir[i].xyz, litAngleScale, litAngleOffset);\n vec3 lspec = specular * CalcSpecular(roughness, SNH, SH, N);\n lighting += SNL * cc_spotLitColor[i].rgb * cc_spotLitColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return lighting;\n}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\nvec4 CCStandardShading (StandardSurface s) {\n vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\n vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n vec3 L = normalize(-cc_mainLitDir.xyz);\n vec3 H = normalize(L+V);\n float NV = max(abs(dot(N, V)), 0.001);\n float NL = max(dot(N, L), 0.001);\n float NH = max(dot(N, H), 0.0);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 diffuseContrib = diffuse / 3.14159265359;\n vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\n vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w * (diffuseContrib + specularContrib);\n finalColor += CalcDynamicLighting(s.position, N, V, diffuse, specular, s.roughness);\n float fAmb = 0.5 - N.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n finalColor += (ambDiff.rgb * diffuse);\n #if CC_USE_IBL\n vec3 R = normalize(reflect(-V, N));\n vec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n #if CC_USE_IBL == 2\n vec3 env = unpackRGBE(envmap);\n #else\n vec3 env = SRGBToLinear(envmap.rgb);\n #endif\n finalColor += env * cc_ambientSky.w * specular;\n #endif\n finalColor = finalColor * s.occlusion;\n #if CC_USE_HDR\n s.emissive *= cc_exposure.w;\n #endif\n finalColor += s.emissive;\n return vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\n color = min(color, vec3(8.0));\n const float A = 2.51;\n const float B = 0.03;\n const float C = 2.43;\n const float D = 0.59;\n const float E = 0.14;\n return (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n #if !CC_USE_HDR\n color.rgb = sqrt(ACESToneMap(color.rgb));\n #endif\n return color;\n}\nuniform vec4 albedo;\nuniform vec4 albedoScaleAndCutoff;\nuniform vec4 pbrParams;\nuniform vec4 emissive;\nuniform vec4 emissiveScaleParam;\nvarying vec3 v_position;\nvarying vec2 v_uv;\nvarying vec2 v_uv1;\nvarying vec3 v_normal;\n#if USE_VERTEX_COLOR\n varying vec3 v_color;\n#endif\n#if USE_ALBEDO_MAP\n uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\n varying vec3 v_tangent;\n varying vec3 v_bitangent;\n uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\n uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\n uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\n uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\n uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\n vec4 baseColor = albedo;\n #if USE_VERTEX_COLOR\n baseColor.rgb *= v_color;\n #endif\n #if USE_ALBEDO_MAP\n vec4 texColor = texture2D(albedoMap, ALBEDO_UV);\n texColor.rgb = SRGBToLinear(texColor.rgb);\n baseColor *= texColor;\n #endif\n s.albedo = baseColor;\n s.albedo.rgb *= albedoScaleAndCutoff.xyz;\n #if USE_ALPHA_TEST\n if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n #endif\n s.normal = v_normal;\n #if USE_NORMAL_MAP\n vec3 nmmp = texture2D(normalMap, NORMAL_UV).xyz - vec3(0.5);\n s.normal =\n (nmmp.x * pbrParams.w) * normalize(v_tangent) +\n (nmmp.y * pbrParams.w) * normalize(v_bitangent) +\n nmmp.z * normalize(s.normal);\n #endif\n s.position = v_position;\n vec4 pbr = pbrParams;\n #if USE_PBR_MAP\n vec4 res = texture2D(pbrMap, PBR_UV);\n pbr.x *= res.OCCLUSION_CHANNEL;\n pbr.y *= res.ROUGHNESS_CHANNEL;\n pbr.z *= res.METALLIC_CHANNEL;\n #endif\n #if USE_METALLIC_ROUGHNESS_MAP\n vec4 metallicRoughness = texture2D(metallicRoughnessMap, METALLIC_ROUGHNESS_UV);\n pbr.z *= metallicRoughness.METALLIC_CHANNEL;\n pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL;\n #endif\n #if USE_OCCLUSION_MAP\n pbr.x *= texture2D(occlusionMap, OCCLUSION_UV).OCCLUSION_CHANNEL;\n #endif\n s.occlusion = clamp(pbr.x, 0.0, 0.96);\n s.roughness = clamp(pbr.y, 0.04, 1.0);\n s.metallic = pbr.z;\n s.emissive = emissive.rgb * emissiveScaleParam.xyz;\n #if USE_EMISSIVE_MAP\n s.emissive *= SRGBToLinear(texture2D(emissiveMap, EMISSIVE_UV).rgb);\n #endif\n}\nvec4 frag () {\n StandardSurface s; surf(s);\n vec4 color = CCStandardShading(s);\n return CCFragOutput(color);\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": { @@ -368,7 +368,7 @@ export default [ { "name": "a_vertexId", "type": 13, "count": 1, "defines": ["CC_USE_MORPH"], "format": 11, "location": 3 }, { "name": "a_weights", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING"], "format": 43, "location": 4 }, { "name": "a_joints", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING"], "format": 43, "location": 5 }, - { "name": "a_jointAnimInfo", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION", "USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 6 }, + { "name": "a_jointAnimInfo", "type": 16, "count": 1, "precision": "highp ", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION", "USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 6 }, { "name": "a_matWorld0", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 7 }, { "name": "a_matWorld1", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 8 }, { "name": "a_matWorld2", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 9 }, @@ -438,13 +438,13 @@ export default [ "shaders": [ { "name": "builtin-unlit|unlit-vs:vert|unlit-fs:frag", - "hash": 3773155015, + "hash": 3753129449, "glsl3": { - "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\n#if USE_VERTEX_COLOR\n in vec4 a_color;\n out vec4 v_color;\n#endif\n#if USE_TEXTURE\n in vec2 a_texCoord;\n out vec2 v_uv;\n uniform TexCoords {\n vec4 tilingOffset;\n };\n#endif\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in highp vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\n#if USE_VERTEX_COLOR\n in vec4 a_color;\n out vec4 v_color;\n#endif\n#if USE_TEXTURE\n in vec2 a_texCoord;\n out vec2 v_uv;\n uniform TexCoords {\n vec4 tilingOffset;\n };\n#endif\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision mediump float;\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n#if USE_ALPHA_TEST\n#endif\n#if USE_TEXTURE\n in vec2 v_uv;\n uniform sampler2D mainTexture;\n#endif\nuniform Constant {\n vec4 mainColor;\n vec4 colorScaleAndCutoff;\n};\n#if USE_VERTEX_COLOR\n in vec4 v_color;\n#endif\nvec4 frag () {\n vec4 o = mainColor;\n o.rgb *= colorScaleAndCutoff.xyz;\n #if USE_VERTEX_COLOR\n o *= v_color;\n #endif\n #if USE_TEXTURE\n o *= texture(mainTexture, v_uv);\n #endif\n #if USE_ALPHA_TEST\n if (o.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard;\n #endif\n return CCFragOutput(o);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\n#if USE_VERTEX_COLOR\n attribute vec4 a_color;\n varying vec4 v_color;\n#endif\n#if USE_TEXTURE\n attribute vec2 a_texCoord;\n varying vec2 v_uv;\n uniform vec4 tilingOffset;\n#endif\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute highp vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\n#if USE_VERTEX_COLOR\n attribute vec4 a_color;\n varying vec4 v_color;\n#endif\n#if USE_TEXTURE\n attribute vec2 a_texCoord;\n varying vec2 v_uv;\n uniform vec4 tilingOffset;\n#endif\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n #if USE_TEXTURE\n v_uv = a_texCoord;\n #if FLIP_UV\n v_uv.y = 1.0 - v_uv.y;\n #endif\n v_uv = v_uv * tilingOffset.xy + tilingOffset.zw;\n #endif\n #if USE_VERTEX_COLOR\n v_color = a_color;\n #endif\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision mediump float;\nuniform mediump vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\n#if USE_ALPHA_TEST\n#endif\n#if USE_TEXTURE\n varying vec2 v_uv;\n uniform sampler2D mainTexture;\n#endif\nuniform vec4 mainColor;\nuniform vec4 colorScaleAndCutoff;\n#if USE_VERTEX_COLOR\n varying vec4 v_color;\n#endif\nvec4 frag () {\n vec4 o = mainColor;\n o.rgb *= colorScaleAndCutoff.xyz;\n #if USE_VERTEX_COLOR\n o *= v_color;\n #endif\n #if USE_TEXTURE\n o *= texture2D(mainTexture, v_uv);\n #endif\n #if USE_ALPHA_TEST\n if (o.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard;\n #endif\n return CCFragOutput(o);\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": { @@ -487,7 +487,7 @@ export default [ { "name": "a_vertexId", "type": 13, "count": 1, "defines": ["CC_USE_MORPH"], "format": 11, "location": 1 }, { "name": "a_weights", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING"], "format": 43, "location": 2 }, { "name": "a_joints", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING"], "format": 43, "location": 3 }, - { "name": "a_jointAnimInfo", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION", "USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 4 }, + { "name": "a_jointAnimInfo", "type": 16, "count": 1, "precision": "highp ", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION", "USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 4 }, { "name": "a_matWorld0", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 5 }, { "name": "a_matWorld1", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 6 }, { "name": "a_matWorld2", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 7 }, @@ -507,13 +507,13 @@ export default [ "shaders": [ { "name": "pipeline/planar-shadow|planar-shadow-vs:vert|planar-shadow-fs:frag", - "hash": 333056161, + "hash": 2011749318, "glsl3": { - "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nuniform CCShadow {\n highp mat4 cc_matLightPlaneProj;\n lowp vec4 cc_shadowColor;\n};\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n position = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nin vec3 a_position;\n#if CC_USE_MORPH\n in float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform CCMorph {\n vec4 cc_displacementWeights[15];\n vec4 cc_displacementTextureInfo;\n};\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_weights;\nin vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n in highp vec4 a_jointAnimInfo;\n #endif\n uniform CCSkinningTexture {\n highp vec4 cc_jointTextureInfo;\n };\n uniform CCSkinningAnimation {\n highp vec4 cc_jointAnimInfo;\n };\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform CCSkinning {\n highp vec4 cc_joints[30 * 3];\n };\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\n#if USE_INSTANCING\n in vec4 a_matWorld0;\n in vec4 a_matWorld1;\n in vec4 a_matWorld2;\n#elif USE_BATCHING\n in float a_dyn_batch_id;\n uniform CCLocalBatched {\n highp mat4 cc_matWorlds[10];\n };\n#else\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n};\n#endif\nuniform CCShadow {\n highp mat4 cc_matLightPlaneProj;\n lowp vec4 cc_shadowColor;\n};\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n position = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision mediump float;\nuniform CCShadow {\n highp mat4 cc_matLightPlaneProj;\n lowp vec4 cc_shadowColor;\n};\nuniform CCGlobal {\n highp vec4 cc_time;\n mediump vec4 cc_screenSize;\n mediump vec4 cc_screenScale;\n mediump vec4 cc_nativeSize;\n highp mat4 cc_matView;\n highp mat4 cc_matViewInv;\n highp mat4 cc_matProj;\n highp mat4 cc_matProjInv;\n highp mat4 cc_matViewProj;\n highp mat4 cc_matViewProjInv;\n highp vec4 cc_cameraPos;\n mediump vec4 cc_exposure;\n mediump vec4 cc_mainLitDir;\n mediump vec4 cc_mainLitColor;\n mediump vec4 cc_ambientSky;\n mediump vec4 cc_ambientGround;\n};\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvec4 frag () {\n return CCFragOutput(cc_shadowColor);\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\nuniform highp mat4 cc_matLightPlaneProj;\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n position = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }`, + "vert": `\nprecision highp float;\nstruct StandardVertInput {\n highp vec4 position;\n vec3 normal;\n vec4 tangent;\n};\nattribute vec3 a_position;\n#if CC_USE_MORPH\n attribute float a_vertexId;\n int getVertexId() {\n return int(a_vertexId);\n }\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\n vec4 fetchFlatPixel(sampler2D tex, int pixelIndex) {\n float pixelIndexF = float(pixelIndex);\n vec2 textureResolution = vec2(float(cc_displacementTextureInfo.x), float(cc_displacementTextureInfo.y));\n float pixelX = mod(pixelIndexF, textureResolution.x);\n float pixelY = floor(pixelIndexF / textureResolution.x);\n vec2 uv = (vec2(pixelX, pixelY) + .5) / textureResolution;\n return texture2D(tex, uv);\n }\nfloat getDisplacementWeight(int index) {\n float m = mod(float(index), 4.0);\n if (m < 1.0) {\n return cc_displacementWeights[index / 4].x;\n } else if (m < 2.0) {\n return cc_displacementWeights[index / 4].y;\n } else if (m < 3.0) {\n return cc_displacementWeights[index / 4].z;\n } else {\n return cc_displacementWeights[index / 4].w;\n }\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\n return fetchFlatPixel(tex, vertexIndex).rgb;\n#else\n vec3 result = vec3(0, 0, 0);\n for (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\n int dataPixelStart = int(fetchFlatPixel(tex, iTarget).r);\n result += (fetchFlatPixel(tex, dataPixelStart + vertexIndex).rgb * getDisplacementWeight(iTarget));\n }\n return result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\n uniform sampler2D cc_PositionDisplacements;\n vec3 getPositionDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n uniform sampler2D cc_NormalDisplacements;\n vec3 getNormalDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n }\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n uniform sampler2D cc_TangentDisplacements;\n vec3 getTangentDisplacement(int vertexId) {\n return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n }\n#endif\nvoid applyMorph (inout StandardVertInput attr) {\n int vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\n attr.position.xyz = attr.position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\n attr.normal.xyz = attr.normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\n attr.tangent.xyz = attr.tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\n position.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_weights;\nattribute vec4 a_joints;\n#if CC_USE_BAKED_ANIMATION\n #if USE_INSTANCING\n attribute highp vec4 a_jointAnimInfo;\n #endif\n uniform highp vec4 cc_jointTextureInfo;\n uniform highp vec4 cc_jointAnimInfo;\n uniform sampler2D cc_jointTexture;\n #if !CC_SUPPORT_FLOAT_TEXTURE\n highp float decode32 (highp vec4 rgba) {\n rgba = rgba * 255.0;\n highp float Sign = 1.0 - step(128.0, rgba[3]) * 2.0;\n highp float Exponent = 2.0 * mod(rgba[3], 128.0) + step(128.0, rgba[2]) - 127.0;\n highp float Mantissa = mod(rgba[2], 128.0) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\n return Sign * exp2(Exponent - 23.0) * Mantissa;\n }\n #endif\n#else\n uniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n #if CC_SUPPORT_FLOAT_TEXTURE\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 3.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 3.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\n vec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\n vec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #else\n mat4 getJointMatrix (float i) {\n #if USE_INSTANCING\n highp float j = 12.0 * (a_jointAnimInfo.x * a_jointAnimInfo.y + i) + a_jointAnimInfo.z;\n #else\n highp float j = 12.0 * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + i) + cc_jointTextureInfo.z;\n #endif\n highp float invSize = cc_jointTextureInfo.w;\n highp float y = floor(j * invSize);\n highp float x = j - y * cc_jointTextureInfo.x;\n y = (y + 0.5) * invSize;\n vec4 v1 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n );\n vec4 v2 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n );\n vec4 v3 = vec4(\n decode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\n decode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n );\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n #endif\n#else\n mat4 getJointMatrix (float i) {\n int idx = int(i);\n vec4 v1 = cc_joints[idx * 3];\n vec4 v2 = cc_joints[idx * 3 + 1];\n vec4 v3 = cc_joints[idx * 3 + 2];\n return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n }\n#endif\nmat4 skinMatrix () {\n return getJointMatrix(a_joints.x) * a_weights.x\n + getJointMatrix(a_joints.y) * a_weights.y;\n + getJointMatrix(a_joints.z) * a_weights.z;\n + getJointMatrix(a_joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\n mat4 m = skinMatrix();\n position = m * position;\n}\nvoid CCSkin (inout StandardVertInput attr) {\n mat4 m = skinMatrix();\n attr.position = m * attr.position;\n attr.normal = (m * vec4(attr.normal, 0.0)).xyz;\n attr.tangent.xyz = (m * vec4(attr.tangent.xyz, 0.0)).xyz;\n}\n#endif\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#if USE_INSTANCING\n attribute vec4 a_matWorld0;\n attribute vec4 a_matWorld1;\n attribute vec4 a_matWorld2;\n#elif USE_BATCHING\n attribute float a_dyn_batch_id;\n uniform highp mat4 cc_matWorlds[10];\n#else\nuniform highp mat4 cc_matWorld;\n#endif\nuniform highp mat4 cc_matLightPlaneProj;\nvec4 vert () {\n vec4 position;\n position = vec4(a_position, 1.0);\n #if CC_USE_MORPH\n applyMorph(position);\n #endif\n #if CC_USE_SKINNING\n CCSkin(position);\n #endif\n mat4 matWorld;\n #if USE_INSTANCING\n matWorld = mat4(\n vec4(a_matWorld0.xyz, 0.0),\n vec4(a_matWorld1.xyz, 0.0),\n vec4(a_matWorld2.xyz, 0.0),\n vec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n );\n #elif USE_BATCHING\n matWorld = cc_matWorlds[int(a_dyn_batch_id)];\n #else\n matWorld = cc_matWorld;\n #endif\n position = cc_matProj * (cc_matView * cc_matLightPlaneProj * matWorld) * position;\n position.z -= 0.0001;\n return position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision mediump float;\nuniform lowp vec4 cc_shadowColor;\nuniform mediump vec4 cc_exposure;\nvec3 SRGBToLinear (vec3 gamma) {\n return gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n #if CC_USE_HDR\n color.rgb = mix(color.rgb, SRGBToLinear(color.rgb) * cc_exposure.w, vec3(cc_exposure.z));\n #endif\n return color;\n}\nvec4 frag () {\n return CCFragOutput(cc_shadowColor);\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": { @@ -541,7 +541,7 @@ export default [ { "name": "a_vertexId", "type": 13, "count": 1, "defines": ["CC_USE_MORPH"], "format": 11, "location": 1 }, { "name": "a_weights", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING"], "format": 43, "location": 2 }, { "name": "a_joints", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING"], "format": 43, "location": 3 }, - { "name": "a_jointAnimInfo", "type": 16, "count": 1, "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION", "USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 4 }, + { "name": "a_jointAnimInfo", "type": 16, "count": 1, "precision": "highp ", "defines": ["CC_USE_SKINNING", "CC_USE_BAKED_ANIMATION", "USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 4 }, { "name": "a_matWorld0", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 5 }, { "name": "a_matWorld1", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 6 }, { "name": "a_matWorld2", "type": 16, "count": 1, "defines": ["USE_INSTANCING"], "format": 43, "isInstanced": true, "location": 7 }, diff --git a/cocos/core/renderer/scene/skybox.ts b/cocos/core/renderer/scene/skybox.ts index 139f0f8caa..b6876d3cde 100644 --- a/cocos/core/renderer/scene/skybox.ts +++ b/cocos/core/renderer/scene/skybox.ts @@ -18,7 +18,6 @@ export class Skybox extends Model { set useIBL (val) { this._useIBL = val; this._updatePipeline(); - this._updateGlobalBinding(); } get useIBL () { return this._useIBL; @@ -29,7 +28,6 @@ export class Skybox extends Model { skybox_material!.recompileShaders({ USE_RGBE_CUBEMAP: this._isRGBE }); this.setSubModelMaterial(0, skybox_material); this._updatePipeline(); - this._updateGlobalBinding(); } get isRGBE () { return this._isRGBE; @@ -65,6 +63,11 @@ export class Skybox extends Model { this.initSubModel(0, skybox_mesh.renderingSubMeshes[0], skybox_material); } + public onGlobalPipelineStateChanged () { + super.onGlobalPipelineStateChanged(); + this._updateGlobalBinding(); + } + protected _updatePipeline () { const value = this._useIBL ? this._isRGBE ? 2 : 1 : 0; const pipeline = this.scene!.root.pipeline; From a0a7cc2f0b423a0ce32f36c748b521a17c8bc76e Mon Sep 17 00:00:00 2001 From: "jiaxin.lai" Date: Tue, 2 Jun 2020 19:59:09 +0800 Subject: [PATCH 73/74] fix vertex index of ray model (#6809) * fix vertex index * tweaks --- cocos/core/geometry/intersect.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/cocos/core/geometry/intersect.ts b/cocos/core/geometry/intersect.ts index c8c6551728..3787ae1afb 100644 --- a/cocos/core/geometry/intersect.ts +++ b/cocos/core/geometry/intersect.ts @@ -340,15 +340,15 @@ const ray_subMesh = (function () { minDis = d; if (r) { if (r.length == 0) { - r.push({ distance: d, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 }); + r.push({ distance: d, vertexIndex0: i0 / 3, vertexIndex1: i1 / 3, vertexIndex2: i2 / 3 }); } else { - r[0].distance = d; r[0].vertexIndex0 = i0; r[0].vertexIndex1 = i1; r[0].vertexIndex2 = i2; + r[0].distance = d; r[0].vertexIndex0 = i0 / 3; r[0].vertexIndex1 = i1 / 3; r[0].vertexIndex2 = i2 / 3; } } } } else { minDis = d; - if (r) r.push({ distance: d, vertexIndex0: i0, vertexIndex1: i1, vertexIndex2: i2 }); + if (r) r.push({ distance: d, vertexIndex0: i0 / 3, vertexIndex1: i1 / 3, vertexIndex2: i2 / 3 }); } } From 83f6c572b5da9ae57b0a91d7248e83dba6a5a1a4 Mon Sep 17 00:00:00 2001 From: SijieWang Date: Wed, 3 Jun 2020 13:38:17 +0800 Subject: [PATCH 74/74] cc -> legacyCC --- cocos/core/animation/animation-manager.ts | 2 +- cocos/core/assets/image-asset.ts | 2 +- cocos/core/scene-graph/node-enum.ts | 4 +++- cocos/ui/components/widget-component.ts | 4 ++-- 4 files changed, 7 insertions(+), 5 deletions(-) diff --git a/cocos/core/animation/animation-manager.ts b/cocos/core/animation/animation-manager.ts index 15752cad36..98e2a18088 100644 --- a/cocos/core/animation/animation-manager.ts +++ b/cocos/core/animation/animation-manager.ts @@ -63,7 +63,7 @@ export class AnimationManager extends System { } this._blendStateBuffer.apply(); - const stamp = cc.director.getTotalFrames(); + const stamp = legacyCC.director.getTotalFrames(); for (let i = 0, l = _sockets.length; i < l; i++) { const { target, transform } = _sockets[i]; target.matrix = getWorldMatrix(transform, stamp); diff --git a/cocos/core/assets/image-asset.ts b/cocos/core/assets/image-asset.ts index 308979b0c0..7def7a8f4e 100644 --- a/cocos/core/assets/image-asset.ts +++ b/cocos/core/assets/image-asset.ts @@ -203,7 +203,7 @@ export class ImageAsset extends Asset { public destroy (): boolean { if (this.data && this.data instanceof HTMLImageElement) { this.data.src = ""; - cc.loader.removeItem(this.data.id); + legacyCC.loader.removeItem(this.data.id); } return super.destroy(); } diff --git a/cocos/core/scene-graph/node-enum.ts b/cocos/core/scene-graph/node-enum.ts index 445832d001..9bb3f0b15b 100644 --- a/cocos/core/scene-graph/node-enum.ts +++ b/cocos/core/scene-graph/node-enum.ts @@ -23,6 +23,8 @@ THE SOFTWARE. */ +import { legacyCC } from '../global-exports'; + /** * @category scene-graph */ @@ -74,4 +76,4 @@ export enum TransformBit { TRS_MASK = ~TransformBit.TRS, } -cc.internal.TransformBit = TransformBit; +legacyCC.internal.TransformBit = TransformBit; diff --git a/cocos/ui/components/widget-component.ts b/cocos/ui/components/widget-component.ts index e5cc95e9c3..8559566f4c 100644 --- a/cocos/ui/components/widget-component.ts +++ b/cocos/ui/components/widget-component.ts @@ -1087,5 +1087,5 @@ export namespace WidgetComponent { legacyCC.WidgetComponent = WidgetComponent; // cc.Widget = module.exports = Widget; -cc.internal.computeInverseTransForTarget = computeInverseTransForTarget; -cc.internal.getReadonlyNodeSize = getReadonlyNodeSize; +legacyCC.internal.computeInverseTransForTarget = computeInverseTransForTarget; +legacyCC.internal.getReadonlyNodeSize = getReadonlyNodeSize;