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", diff --git a/.vscode/cSpell.json b/.vscode/cSpell.json index 8e23ac8199..12508101b6 100644 --- a/.vscode/cSpell.json +++ b/.vscode/cSpell.json @@ -9,12 +9,15 @@ "deinterleave", "deserialize", "earcut", + "eventify", + "eventified", "forin", "glsl", "grayscale", "IGFX", "lerp", "lerpable", + "lightmap", "mipmaps", "octree", "OPENGL", diff --git a/@types/globals.d.ts b/@types/globals.d.ts index bc4251f3f5..558d2101c1 100644 --- a/@types/globals.d.ts +++ b/@types/globals.d.ts @@ -91,3 +91,5 @@ declare type Getter = () => any; declare type Setter = (value: any) => void; declare const Buffer: any; + +declare type EnumAlias = EnumT[keyof EnumT]; diff --git a/EngineErrorMap.md b/EngineErrorMap.md index d6b6038ac1..c48d8f9220 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -2012,3 +2012,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/audio/assets/player-dom.ts b/cocos/audio/assets/player-dom.ts index 1af89b8b54..a3fd447c6b 100644 --- a/cocos/audio/assets/player-dom.ts +++ b/cocos/audio/assets/player-dom.ts @@ -34,7 +34,7 @@ import { legacyCC } from '../../core/global-exports'; export class AudioPlayerDOM extends AudioPlayer { protected _volume = 1; protected _loop = false; - protected _oneShoting = false; + protected _oneShotOngoing = false; protected _audio: HTMLAudioElement; protected _cbRegistered = false; @@ -82,7 +82,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'); @@ -111,7 +111,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 () { @@ -120,7 +120,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) { @@ -130,17 +130,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/builtin/effects.ts b/cocos/core/3d/builtin/effects.ts index c08107d6fc..9f6201d915 100644 --- a/cocos/core/3d/builtin/effects.ts +++ b/cocos/core/3d/builtin/effects.ts @@ -167,7 +167,7 @@ export default [ "locals": { "blocks": [{ "name": "CCLocal", "defines": [] }], "samplers": [] } }, "defines": [ - { "name": "CC_RENDER_MODE", "type": "number", "dummyDependency": true, "range": [0, 4] }, + { "name": "CC_RENDER_MODE", "type": "number", "range": [0, 4] }, { "name": "CC_DRAW_WIRE_FRAME", "type": "boolean" }, { "name": "CC_USE_WORLD_SPACE", "type": "boolean" }, { "name": "CC_USE_HDR", "type": "boolean" } @@ -257,14 +257,14 @@ export default [ "shaders": [ { "name": "builtin-sprite|sprite-vs:vert|sprite-fs:frag", - "hash": 543960898, + "hash": 2999916052, "glsl3": { - "vert": `\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 mediump vec4 cc_fogColor;\n mediump vec4 cc_fogBase;\n mediump vec4 cc_fogAdd;\n};\n#if USE_LOCAL\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n highp vec4 cc_lightingMapUVParam;\n};\n#endif\nin vec3 a_position;\nin vec4 a_color;\nout vec4 color;\nin vec2 a_texCoord;\nout vec2 uv0;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if USE_LOCAL\n pos = cc_matViewProj * cc_matWorld * pos;\n #else\n pos = cc_matViewProj * pos;\n #endif\n uv0 = a_texCoord;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }`, - "frag": `\nprecision mediump float;\nin vec4 color;\n#if USE_TEXTURE\n in vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture(mainTexture, uv0);\n #if IS_GRAY\n float gray = 0.2126 * o.r + 0.7152 * o.g + 0.0722 * o.b;\n o.r = o.g = o.b = gray;\n #endif\n #endif\n o *= color;\n return o;\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` + "vert": `\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 mediump vec4 cc_fogColor;\n mediump vec4 cc_fogBase;\n mediump vec4 cc_fogAdd;\n};\n#if USE_LOCAL\nuniform CCLocal {\n highp mat4 cc_matWorld;\n highp mat4 cc_matWorldIT;\n highp vec4 cc_lightingMapUVParam;\n};\n#endif\nin vec3 a_position;\nin vec2 a_texCoord;\nin vec4 a_color;\nout vec4 color;\nout vec2 uv0;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if USE_LOCAL\n pos = cc_matViewProj * cc_matWorld * pos;\n #else\n pos = cc_matViewProj * pos;\n #endif\n uv0 = a_texCoord;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }`, + "frag": `\nprecision mediump float;\nvec4 CCSampleTexture(sampler2D tex, vec2 uv) {\n#if CC_ALPHA_SEPARATED\n return vec4(texture(tex, uv).rgb, texture(tex, uv + vec2(0.0, 0.5)).r);\n#else\n return texture(tex, uv);\n#endif\n}\nin vec4 color;\n#if USE_TEXTURE\n in vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= CCSampleTexture(mainTexture, uv0);\n #if IS_GRAY\n float gray = 0.2126 * o.r + 0.7152 * o.g + 0.0722 * o.b;\n o.r = o.g = o.b = gray;\n #endif\n #endif\n o *= color;\n return o;\n}\nout vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }` }, "glsl1": { - "vert": `\nprecision mediump float;\nuniform highp mat4 cc_matViewProj;\n#if USE_LOCAL\nuniform highp mat4 cc_matWorld;\n#endif\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying vec4 color;\nattribute vec2 a_texCoord;\nvarying vec2 uv0;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if USE_LOCAL\n pos = cc_matViewProj * cc_matWorld * pos;\n #else\n pos = cc_matViewProj * pos;\n #endif\n uv0 = a_texCoord;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }`, - "frag": `\nprecision mediump float;\nvarying vec4 color;\n#if USE_TEXTURE\n varying vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= texture2D(mainTexture, uv0);\n #if IS_GRAY\n float gray = 0.2126 * o.r + 0.7152 * o.g + 0.0722 * o.b;\n o.r = o.g = o.b = gray;\n #endif\n #endif\n o *= color;\n return o;\n}\nvoid main() { gl_FragColor = frag(); }` + "vert": `\nprecision mediump float;\nuniform highp mat4 cc_matViewProj;\n#if USE_LOCAL\nuniform highp mat4 cc_matWorld;\n#endif\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nvarying vec4 color;\nvarying vec2 uv0;\nvec4 vert () {\n vec4 pos = vec4(a_position, 1);\n #if USE_LOCAL\n pos = cc_matViewProj * cc_matWorld * pos;\n #else\n pos = cc_matViewProj * pos;\n #endif\n uv0 = a_texCoord;\n color = a_color;\n return pos;\n}\nvoid main() { gl_Position = vert(); }`, + "frag": `\nprecision mediump float;\nvec4 CCSampleTexture(sampler2D tex, vec2 uv) {\n#if CC_ALPHA_SEPARATED\n return vec4(texture2D(tex, uv).rgb, texture2D(tex, uv + vec2(0.0, 0.5)).r);\n#else\n return texture2D(tex, uv);\n#endif\n}\nvarying vec4 color;\n#if USE_TEXTURE\n varying vec2 uv0;\n uniform sampler2D mainTexture;\n#endif\nvec4 frag () {\n vec4 o = vec4(1, 1, 1, 1);\n #if USE_TEXTURE\n o *= CCSampleTexture(mainTexture, uv0);\n #if IS_GRAY\n float gray = 0.2126 * o.r + 0.7152 * o.g + 0.0722 * o.b;\n o.r = o.g = o.b = gray;\n #endif\n #endif\n o *= color;\n return o;\n}\nvoid main() { gl_FragColor = frag(); }` }, "builtins": { "globals": { "blocks": [{ "name": "CCGlobal", "defines": [] }], "samplers": [] }, @@ -272,6 +272,7 @@ export default [ }, "defines": [ { "name": "USE_LOCAL", "type": "boolean" }, + { "name": "CC_ALPHA_SEPARATED", "type": "boolean" }, { "name": "USE_TEXTURE", "type": "boolean" }, { "name": "IS_GRAY", "type": "boolean" } ], @@ -281,8 +282,8 @@ export default [ ], "attributes": [ { "name": "a_position", "type": 15, "count": 1, "defines": [], "format": 32, "location": 0 }, - { "name": "a_color", "type": 16, "count": 1, "defines": [], "format": 43, "location": 1 }, - { "name": "a_texCoord", "type": 14, "count": 1, "defines": [], "format": 21, "location": 2 } + { "name": "a_texCoord", "type": 14, "count": 1, "defines": [], "format": 21, "location": 1 }, + { "name": "a_color", "type": 16, "count": 1, "defines": [], "format": 43, "location": 2 } ] } ] @@ -296,31 +297,31 @@ export default [ "shaders": [ { "name": "builtin-standard|standard-vs:vert|standard-fs:frag", - "hash": 2109082843, + "hash": 792061870, "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 mediump vec4 cc_fogColor;\n mediump vec4 cc_fogBase;\n mediump vec4 cc_fogAdd;\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 highp vec4 cc_lightingMapUVParam;\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};\nfloat LinearFog(vec4 pos) {\n vec4 wPos = pos;\n float cam_dis = distance(cc_cameraPos, wPos);\n float fogStart = cc_fogBase.x;\n float fogEnd = cc_fogBase.y;\n return clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float fogDensity = cc_fogBase.z;\n float cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\n float f = exp(-cam_dis * fogDensity);\n return f;\n}\nfloat ExpSquaredFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float fogDensity = cc_fogBase.z;\n float cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\n float f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\n return f;\n}\nfloat LayeredFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float _FogTop = cc_fogAdd.x;\n float _FogRange = cc_fogAdd.y;\n vec3 camWorldProj = cc_cameraPos.xyz;\n camWorldProj.y = 0.;\n vec3 worldPosProj = wPos.xyz;\n worldPosProj.y = 0.;\n float fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\n float fDeltaY, fDensityIntegral;\n if (cc_cameraPos.y > _FogTop) {\n if (wPos.y < _FogTop) {\n fDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\n fDensityIntegral = fDeltaY * fDeltaY * 0.5;\n } else {\n fDeltaY = 0.;\n fDensityIntegral = 0.;\n }\n } else {\n if (wPos.y < _FogTop) {\n float fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\n float fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\n fDeltaY = abs(fDeltaA - fDeltaB);\n fDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n } else {\n fDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\n fDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n }\n }\n float fDensity;\n if (fDeltaY != 0.) {\n fDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n } else {\n fDensity = 0.;\n }\n float f = exp(-fDensity);\n return f;\n}\nfloat CC_TRANSFER_FOG(vec4 pos) {\n #if CC_USE_FOG == 1\n return LinearFog(pos);\n #elif CC_USE_FOG == 2\n return ExpFog(pos);\n #elif CC_USE_FOG == 3\n return ExpSquaredFog(pos);\n #elif CC_USE_FOG == 4\n return LayeredFog(pos);\n #endif\n return 1.;\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;\nout float factor_fog;\n#if USE_LIGHTMAP && !USE_BATCHING && !USE_INSTANCING\n out vec2 v_luv;\n#endif\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 factor_fog = CC_TRANSFER_FOG(matWorld * In.position);\n #if USE_LIGHTMAP && HAS_SECOND_UV && !USE_BATCHING && !USE_INSTANCING\n v_luv = cc_lightingMapUVParam.xy + a_texCoord1 * cc_lightingMapUVParam.zw;\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 mediump vec4 cc_fogColor;\n mediump vec4 cc_fogBase;\n mediump vec4 cc_fogAdd;\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 highp vec4 cc_lightingMapUVParam;\n};\n#endif\nuniform Constants {\n vec4 tilingOffset;\n vec4 albedo;\n vec4 albedoScaleAndCutoff;\n vec4 pbrParams;\n vec4 emissive;\n vec4 emissiveScaleParam;\n};\nfloat LinearFog(vec4 pos) {\n vec4 wPos = pos;\n float cam_dis = distance(cc_cameraPos, wPos);\n float fogStart = cc_fogBase.x;\n float fogEnd = cc_fogBase.y;\n return clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float fogDensity = cc_fogBase.z;\n float cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\n float f = exp(-cam_dis * fogDensity);\n return f;\n}\nfloat ExpSquaredFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float fogDensity = cc_fogBase.z;\n float cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\n float f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\n return f;\n}\nfloat LayeredFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float _FogTop = cc_fogAdd.x;\n float _FogRange = cc_fogAdd.y;\n vec3 camWorldProj = cc_cameraPos.xyz;\n camWorldProj.y = 0.;\n vec3 worldPosProj = wPos.xyz;\n worldPosProj.y = 0.;\n float fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\n float fDeltaY, fDensityIntegral;\n if (cc_cameraPos.y > _FogTop) {\n if (wPos.y < _FogTop) {\n fDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\n fDensityIntegral = fDeltaY * fDeltaY * 0.5;\n } else {\n fDeltaY = 0.;\n fDensityIntegral = 0.;\n }\n } else {\n if (wPos.y < _FogTop) {\n float fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\n float fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\n fDeltaY = abs(fDeltaA - fDeltaB);\n fDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n } else {\n fDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\n fDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n }\n }\n float fDensity;\n if (fDeltaY != 0.) {\n fDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n } else {\n fDensity = 0.;\n }\n float f = exp(-fDensity);\n return f;\n}\nfloat CC_TRANSFER_FOG(vec4 pos) {\n #if CC_USE_FOG == 1\n return LinearFog(pos);\n #elif CC_USE_FOG == 2\n return ExpFog(pos);\n #elif CC_USE_FOG == 3\n return ExpSquaredFog(pos);\n #elif CC_USE_FOG == 4\n return LayeredFog(pos);\n #endif\n return 1.;\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;\nout float factor_fog;\n#if USE_LIGHTMAP && !USE_BATCHING && !USE_INSTANCING\n out vec2 v_luv;\n#endif\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 factor_fog = CC_TRANSFER_FOG(matWorld * In.position);\n #if USE_LIGHTMAP && HAS_SECOND_UV && !USE_BATCHING && !USE_INSTANCING\n v_luv = cc_lightingMapUVParam.xy + a_texCoord1 * cc_lightingMapUVParam.zw;\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 mediump vec4 cc_fogColor;\n mediump vec4 cc_fogBase;\n mediump vec4 cc_fogAdd;\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}\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}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\n#if CC_FOWARD_ADD\nuniform CCForwardLight {\n highp vec4 cc_lightPos[1];\n vec4 cc_lightColor[1];\n vec4 cc_lightSizeRangeAngle[1];\n vec4 cc_lightDir[1];\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}\n vec4 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 diffuseContrib = diffuse / 3.14159265359;\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n float NV = max(abs(dot(N, V)), 0.001);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 finalColor = vec3(0.0);\n for (int i = 0; i < 1; i++) {\n vec3 SLU = cc_lightPos[i].xyz - s.position;\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_lightSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_lightSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\n #if CC_SPOTLIGHT\n float cosInner = max(dot(-cc_lightDir[i].xyz, SL), 0.01);\n float cosOuter = cc_lightSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n att *= GetAngleAtt(SL, -cc_lightDir[i].xyz, litAngleScale, litAngleOffset);\n #endif\n finalColor += SNL * cc_lightColor[i].rgb * cc_lightColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return vec4(finalColor, 0.0);\n }\n#else\n vec4 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 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 }\n#endif\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_LIGHTMAP\n in vec2 v_luv;\n uniform sampler2D cc_lightingMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nin float factor_fog;\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 #if USE_LIGHTMAP && !USE_BATCHING && !USE_INSTANCING && CC_FOWARD_ADD == 0\n vec4 lighting = texture(cc_lightingMap, v_luv);\n float fAmb = 0.5 - s.normal.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n vec3 finalColor = (ambDiff.rgb * s.albedo.rgb);\n finalColor += lighting.rgb * s.albedo.rgb;\n finalColor = finalColor * s.occlusion;\n finalColor += s.emissive;\n color.rgb = lighting.a * finalColor + (1.0 - lighting.a) * color.rgb;\n #endif\n color = mix(cc_fogColor, color, factor_fog);\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;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_fogBase;\nuniform mediump vec4 cc_fogAdd;\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;\nuniform highp vec4 cc_lightingMapUVParam;\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;\nfloat LinearFog(vec4 pos) {\n vec4 wPos = pos;\n float cam_dis = distance(cc_cameraPos, wPos);\n float fogStart = cc_fogBase.x;\n float fogEnd = cc_fogBase.y;\n return clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float fogDensity = cc_fogBase.z;\n float cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\n float f = exp(-cam_dis * fogDensity);\n return f;\n}\nfloat ExpSquaredFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float fogDensity = cc_fogBase.z;\n float cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\n float f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\n return f;\n}\nfloat LayeredFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float _FogTop = cc_fogAdd.x;\n float _FogRange = cc_fogAdd.y;\n vec3 camWorldProj = cc_cameraPos.xyz;\n camWorldProj.y = 0.;\n vec3 worldPosProj = wPos.xyz;\n worldPosProj.y = 0.;\n float fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\n float fDeltaY, fDensityIntegral;\n if (cc_cameraPos.y > _FogTop) {\n if (wPos.y < _FogTop) {\n fDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\n fDensityIntegral = fDeltaY * fDeltaY * 0.5;\n } else {\n fDeltaY = 0.;\n fDensityIntegral = 0.;\n }\n } else {\n if (wPos.y < _FogTop) {\n float fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\n float fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\n fDeltaY = abs(fDeltaA - fDeltaB);\n fDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n } else {\n fDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\n fDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n }\n }\n float fDensity;\n if (fDeltaY != 0.) {\n fDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n } else {\n fDensity = 0.;\n }\n float f = exp(-fDensity);\n return f;\n}\nfloat CC_TRANSFER_FOG(vec4 pos) {\n #if CC_USE_FOG == 1\n return LinearFog(pos);\n #elif CC_USE_FOG == 2\n return ExpFog(pos);\n #elif CC_USE_FOG == 3\n return ExpSquaredFog(pos);\n #elif CC_USE_FOG == 4\n return LayeredFog(pos);\n #endif\n return 1.;\n}\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;\nvarying float factor_fog;\n#if USE_LIGHTMAP && !USE_BATCHING && !USE_INSTANCING\n varying vec2 v_luv;\n#endif\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 factor_fog = CC_TRANSFER_FOG(matWorld * In.position);\n #if USE_LIGHTMAP && HAS_SECOND_UV && !USE_BATCHING && !USE_INSTANCING\n v_luv = cc_lightingMapUVParam.xy + a_texCoord1 * cc_lightingMapUVParam.zw;\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;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_fogBase;\nuniform mediump vec4 cc_fogAdd;\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;\nuniform highp vec4 cc_lightingMapUVParam;\n#endif\nuniform vec4 tilingOffset;\nfloat LinearFog(vec4 pos) {\n vec4 wPos = pos;\n float cam_dis = distance(cc_cameraPos, wPos);\n float fogStart = cc_fogBase.x;\n float fogEnd = cc_fogBase.y;\n return clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float fogDensity = cc_fogBase.z;\n float cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\n float f = exp(-cam_dis * fogDensity);\n return f;\n}\nfloat ExpSquaredFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float fogDensity = cc_fogBase.z;\n float cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\n float f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\n return f;\n}\nfloat LayeredFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float _FogTop = cc_fogAdd.x;\n float _FogRange = cc_fogAdd.y;\n vec3 camWorldProj = cc_cameraPos.xyz;\n camWorldProj.y = 0.;\n vec3 worldPosProj = wPos.xyz;\n worldPosProj.y = 0.;\n float fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\n float fDeltaY, fDensityIntegral;\n if (cc_cameraPos.y > _FogTop) {\n if (wPos.y < _FogTop) {\n fDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\n fDensityIntegral = fDeltaY * fDeltaY * 0.5;\n } else {\n fDeltaY = 0.;\n fDensityIntegral = 0.;\n }\n } else {\n if (wPos.y < _FogTop) {\n float fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\n float fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\n fDeltaY = abs(fDeltaA - fDeltaB);\n fDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n } else {\n fDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\n fDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n }\n }\n float fDensity;\n if (fDeltaY != 0.) {\n fDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n } else {\n fDensity = 0.;\n }\n float f = exp(-fDensity);\n return f;\n}\nfloat CC_TRANSFER_FOG(vec4 pos) {\n #if CC_USE_FOG == 1\n return LinearFog(pos);\n #elif CC_USE_FOG == 2\n return ExpFog(pos);\n #elif CC_USE_FOG == 3\n return ExpSquaredFog(pos);\n #elif CC_USE_FOG == 4\n return LayeredFog(pos);\n #endif\n return 1.;\n}\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;\nvarying float factor_fog;\n#if USE_LIGHTMAP && !USE_BATCHING && !USE_INSTANCING\n varying vec2 v_luv;\n#endif\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 factor_fog = CC_TRANSFER_FOG(matWorld * In.position);\n #if USE_LIGHTMAP && HAS_SECOND_UV && !USE_BATCHING && !USE_INSTANCING\n v_luv = cc_lightingMapUVParam.xy + a_texCoord1 * cc_lightingMapUVParam.zw;\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;\nuniform mediump vec4 cc_fogColor;\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}\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}\nstruct StandardSurface {\n vec4 albedo;\n vec3 position;\n vec3 normal;\n vec3 emissive;\n float roughness;\n float metallic;\n float occlusion;\n};\n#if CC_FOWARD_ADD\nuniform highp vec4 cc_lightPos[1];\nuniform vec4 cc_lightColor[1];\nuniform vec4 cc_lightSizeRangeAngle[1];\nuniform vec4 cc_lightDir[1];\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}\n vec4 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 diffuseContrib = diffuse / 3.14159265359;\n vec3 N = normalize(s.normal);\n vec3 V = normalize(cc_cameraPos.xyz - s.position);\n float NV = max(abs(dot(N, V)), 0.001);\n specular = BRDFApprox(specular, s.roughness, NV);\n vec3 finalColor = vec3(0.0);\n for (int i = 0; i < 1; i++) {\n vec3 SLU = cc_lightPos[i].xyz - s.position;\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_lightSizeRangeAngle[i].x;\n float litRadiusSqr = litRadius * litRadius;\n float illum = 3.14159265359 * (litRadiusSqr / max(litRadiusSqr , distSqr));\n float attRadiusSqrInv = 1.0 / max(cc_lightSizeRangeAngle[i].y, 0.01);\n attRadiusSqrInv *= attRadiusSqrInv;\n float att = GetDistAtt(distSqr, attRadiusSqrInv);\n vec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\n #if CC_SPOTLIGHT\n float cosInner = max(dot(-cc_lightDir[i].xyz, SL), 0.01);\n float cosOuter = cc_lightSizeRangeAngle[i].z;\n float litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\n float litAngleOffset = -cosOuter * litAngleScale;\n att *= GetAngleAtt(SL, -cc_lightDir[i].xyz, litAngleScale, litAngleOffset);\n #endif\n finalColor += SNL * cc_lightColor[i].rgb * cc_lightColor[i].w * illum * att * (diffuseContrib + lspec);\n }\n return vec4(finalColor, 0.0);\n }\n#else\n vec4 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 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 }\n#endif\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_LIGHTMAP\n varying vec2 v_luv;\n uniform sampler2D cc_lightingMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvarying float factor_fog;\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 #if USE_LIGHTMAP && !USE_BATCHING && !USE_INSTANCING && CC_FOWARD_ADD == 0\n vec4 lighting = texture2D(cc_lightingMap, v_luv);\n float fAmb = 0.5 - s.normal.y * 0.5;\n vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb) * cc_ambientSky.w;\n vec3 finalColor = (ambDiff.rgb * s.albedo.rgb);\n finalColor += lighting.rgb * s.albedo.rgb;\n finalColor = finalColor * s.occlusion;\n finalColor += s.emissive;\n color.rgb = lighting.a * finalColor + (1.0 - lighting.a) * color.rgb;\n #endif\n color = mix(cc_fogColor, color, factor_fog);\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": ["CC_FOWARD_ADD"] }], "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"] }, { "name": "cc_lightingMap", "defines": ["USE_LIGHTMAP"] }] } + "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": ["CC_FOWARD_ADD"] }], "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"] }, { "name": "cc_lightingMap", "defines": ["USE_LIGHTMAP"] }] } }, "defines": [ - { "name": "USE_INSTANCING", "type": "boolean" }, - { "name": "USE_BATCHING", "type": "boolean" }, { "name": "CC_USE_MORPH", "type": "boolean" }, - { "name": "CC_MORPH_TARGET_COUNT", "type": "number", "dummyDependency": true, "range": [2, 8] }, + { "name": "CC_MORPH_TARGET_COUNT", "type": "number", "range": [2, 8] }, { "name": "CC_MORPH_PRECOMPUTED", "type": "boolean" }, { "name": "CC_MORPH_TARGET_HAS_POSITION", "type": "boolean" }, { "name": "CC_MORPH_TARGET_HAS_NORMAL", "type": "boolean" }, { "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_FOG", "type": "number", "range": [0, 4] }, { "name": "USE_VERTEX_COLOR", "type": "boolean" }, { "name": "USE_NORMAL_MAP", "type": "boolean" }, @@ -331,21 +332,21 @@ export default [ { "name": "CC_SPOTLIGHT", "type": "boolean" }, { "name": "CC_USE_HDR", "type": "boolean" }, { "name": "USE_ALBEDO_MAP", "type": "boolean" }, - { "name": "ALBEDO_UV", "type": "string", "dummyDependency": true, "options": ["v_uv", "v_uv1"] }, - { "name": "NORMAL_UV", "type": "string", "dummyDependency": true, "options": ["v_uv", "v_uv1"] }, + { "name": "ALBEDO_UV", "type": "string", "options": ["v_uv", "v_uv1"] }, + { "name": "NORMAL_UV", "type": "string", "options": ["v_uv", "v_uv1"] }, { "name": "USE_PBR_MAP", "type": "boolean" }, - { "name": "PBR_UV", "type": "string", "dummyDependency": true, "options": ["v_uv", "v_uv1"] }, + { "name": "PBR_UV", "type": "string", "options": ["v_uv", "v_uv1"] }, { "name": "USE_METALLIC_ROUGHNESS_MAP", "type": "boolean" }, - { "name": "METALLIC_ROUGHNESS_UV", "type": "string", "dummyDependency": true, "options": ["v_uv", "v_uv1"] }, + { "name": "METALLIC_ROUGHNESS_UV", "type": "string", "options": ["v_uv", "v_uv1"] }, { "name": "USE_OCCLUSION_MAP", "type": "boolean" }, - { "name": "OCCLUSION_UV", "type": "string", "dummyDependency": true, "options": ["v_uv", "v_uv1"] }, + { "name": "OCCLUSION_UV", "type": "string", "options": ["v_uv", "v_uv1"] }, { "name": "USE_EMISSIVE_MAP", "type": "boolean" }, - { "name": "EMISSIVE_UV", "type": "string", "dummyDependency": true, "options": ["v_uv", "v_uv1"] }, - { "name": "OCCLUSION_CHANNEL", "type": "string", "dummyDependency": true, "options": ["r", "g", "b"] }, - { "name": "ROUGHNESS_CHANNEL", "type": "string", "dummyDependency": true, "options": ["g", "b", "r"] }, - { "name": "METALLIC_CHANNEL", "type": "string", "dummyDependency": true, "options": ["b", "r", "g"] }, + { "name": "EMISSIVE_UV", "type": "string", "options": ["v_uv", "v_uv1"] }, + { "name": "OCCLUSION_CHANNEL", "type": "string", "options": ["r", "g", "b"] }, + { "name": "ROUGHNESS_CHANNEL", "type": "string", "options": ["g", "b", "r"] }, + { "name": "METALLIC_CHANNEL", "type": "string", "options": ["b", "r", "g"] }, { "name": "USE_ALPHA_TEST", "type": "boolean" }, - { "name": "ALPHA_TEST_CHANNEL", "type": "string", "dummyDependency": true, "options": ["a", "r"] } + { "name": "ALPHA_TEST_CHANNEL", "type": "string", "options": ["a", "r"] } ], "blocks": [ {"name": "Constants", "defines": [], "binding": 0, "members": [ @@ -366,17 +367,17 @@ export default [ { "name": "emissiveMap", "type": 28, "count": 1, "defines": ["USE_EMISSIVE_MAP"], "binding": 36 } ], "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, "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 }, + { "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 } @@ -443,38 +444,38 @@ export default [ "shaders": [ { "name": "builtin-unlit|unlit-vs:vert|unlit-fs:frag", - "hash": 211923169, + "hash": 3346882623, "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 mediump vec4 cc_fogColor;\n mediump vec4 cc_fogBase;\n mediump vec4 cc_fogAdd;\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 highp vec4 cc_lightingMapUVParam;\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\nfloat LinearFog(vec4 pos) {\n vec4 wPos = pos;\n float cam_dis = distance(cc_cameraPos, wPos);\n float fogStart = cc_fogBase.x;\n float fogEnd = cc_fogBase.y;\n return clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float fogDensity = cc_fogBase.z;\n float cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\n float f = exp(-cam_dis * fogDensity);\n return f;\n}\nfloat ExpSquaredFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float fogDensity = cc_fogBase.z;\n float cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\n float f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\n return f;\n}\nfloat LayeredFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float _FogTop = cc_fogAdd.x;\n float _FogRange = cc_fogAdd.y;\n vec3 camWorldProj = cc_cameraPos.xyz;\n camWorldProj.y = 0.;\n vec3 worldPosProj = wPos.xyz;\n worldPosProj.y = 0.;\n float fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\n float fDeltaY, fDensityIntegral;\n if (cc_cameraPos.y > _FogTop) {\n if (wPos.y < _FogTop) {\n fDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\n fDensityIntegral = fDeltaY * fDeltaY * 0.5;\n } else {\n fDeltaY = 0.;\n fDensityIntegral = 0.;\n }\n } else {\n if (wPos.y < _FogTop) {\n float fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\n float fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\n fDeltaY = abs(fDeltaA - fDeltaB);\n fDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n } else {\n fDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\n fDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n }\n }\n float fDensity;\n if (fDeltaY != 0.) {\n fDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n } else {\n fDensity = 0.;\n }\n float f = exp(-fDensity);\n return f;\n}\nfloat CC_TRANSFER_FOG(vec4 pos) {\n #if CC_USE_FOG == 1\n return LinearFog(pos);\n #elif CC_USE_FOG == 2\n return ExpFog(pos);\n #elif CC_USE_FOG == 3\n return ExpSquaredFog(pos);\n #elif CC_USE_FOG == 4\n return LayeredFog(pos);\n #endif\n return 1.;\n}\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\nout float factor_fog;\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 factor_fog = CC_TRANSFER_FOG(matWorld * position);\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 mediump vec4 cc_fogColor;\n mediump vec4 cc_fogBase;\n mediump vec4 cc_fogAdd;\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 highp vec4 cc_lightingMapUVParam;\n};\n#endif\nfloat LinearFog(vec4 pos) {\n vec4 wPos = pos;\n float cam_dis = distance(cc_cameraPos, wPos);\n float fogStart = cc_fogBase.x;\n float fogEnd = cc_fogBase.y;\n return clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float fogDensity = cc_fogBase.z;\n float cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\n float f = exp(-cam_dis * fogDensity);\n return f;\n}\nfloat ExpSquaredFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float fogDensity = cc_fogBase.z;\n float cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\n float f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\n return f;\n}\nfloat LayeredFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float _FogTop = cc_fogAdd.x;\n float _FogRange = cc_fogAdd.y;\n vec3 camWorldProj = cc_cameraPos.xyz;\n camWorldProj.y = 0.;\n vec3 worldPosProj = wPos.xyz;\n worldPosProj.y = 0.;\n float fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\n float fDeltaY, fDensityIntegral;\n if (cc_cameraPos.y > _FogTop) {\n if (wPos.y < _FogTop) {\n fDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\n fDensityIntegral = fDeltaY * fDeltaY * 0.5;\n } else {\n fDeltaY = 0.;\n fDensityIntegral = 0.;\n }\n } else {\n if (wPos.y < _FogTop) {\n float fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\n float fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\n fDeltaY = abs(fDeltaA - fDeltaB);\n fDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n } else {\n fDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\n fDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n }\n }\n float fDensity;\n if (fDeltaY != 0.) {\n fDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n } else {\n fDensity = 0.;\n }\n float f = exp(-fDensity);\n return f;\n}\nfloat CC_TRANSFER_FOG(vec4 pos) {\n #if CC_USE_FOG == 1\n return LinearFog(pos);\n #elif CC_USE_FOG == 2\n return ExpFog(pos);\n #elif CC_USE_FOG == 3\n return ExpSquaredFog(pos);\n #elif CC_USE_FOG == 4\n return LayeredFog(pos);\n #endif\n return 1.;\n}\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\nout float factor_fog;\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 factor_fog = CC_TRANSFER_FOG(matWorld * position);\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 mediump vec4 cc_fogColor;\n mediump vec4 cc_fogBase;\n mediump vec4 cc_fogAdd;\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\nin float factor_fog;\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 o = mix(cc_fogColor, o, factor_fog);\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;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_fogBase;\nuniform mediump vec4 cc_fogAdd;\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\nfloat LinearFog(vec4 pos) {\n vec4 wPos = pos;\n float cam_dis = distance(cc_cameraPos, wPos);\n float fogStart = cc_fogBase.x;\n float fogEnd = cc_fogBase.y;\n return clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float fogDensity = cc_fogBase.z;\n float cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\n float f = exp(-cam_dis * fogDensity);\n return f;\n}\nfloat ExpSquaredFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float fogDensity = cc_fogBase.z;\n float cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\n float f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\n return f;\n}\nfloat LayeredFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float _FogTop = cc_fogAdd.x;\n float _FogRange = cc_fogAdd.y;\n vec3 camWorldProj = cc_cameraPos.xyz;\n camWorldProj.y = 0.;\n vec3 worldPosProj = wPos.xyz;\n worldPosProj.y = 0.;\n float fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\n float fDeltaY, fDensityIntegral;\n if (cc_cameraPos.y > _FogTop) {\n if (wPos.y < _FogTop) {\n fDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\n fDensityIntegral = fDeltaY * fDeltaY * 0.5;\n } else {\n fDeltaY = 0.;\n fDensityIntegral = 0.;\n }\n } else {\n if (wPos.y < _FogTop) {\n float fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\n float fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\n fDeltaY = abs(fDeltaA - fDeltaB);\n fDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n } else {\n fDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\n fDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n }\n }\n float fDensity;\n if (fDeltaY != 0.) {\n fDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n } else {\n fDensity = 0.;\n }\n float f = exp(-fDensity);\n return f;\n}\nfloat CC_TRANSFER_FOG(vec4 pos) {\n #if CC_USE_FOG == 1\n return LinearFog(pos);\n #elif CC_USE_FOG == 2\n return ExpFog(pos);\n #elif CC_USE_FOG == 3\n return ExpSquaredFog(pos);\n #elif CC_USE_FOG == 4\n return LayeredFog(pos);\n #endif\n return 1.;\n}\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\nvarying float factor_fog;\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 factor_fog = CC_TRANSFER_FOG(matWorld * position);\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;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_fogBase;\nuniform mediump vec4 cc_fogAdd;\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\nfloat LinearFog(vec4 pos) {\n vec4 wPos = pos;\n float cam_dis = distance(cc_cameraPos, wPos);\n float fogStart = cc_fogBase.x;\n float fogEnd = cc_fogBase.y;\n return clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float fogDensity = cc_fogBase.z;\n float cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\n float f = exp(-cam_dis * fogDensity);\n return f;\n}\nfloat ExpSquaredFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float fogDensity = cc_fogBase.z;\n float cam_dis = distance(cc_cameraPos, wPos) / fogAtten * 4.;\n float f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\n return f;\n}\nfloat LayeredFog(vec4 pos) {\n vec4 wPos = pos;\n float fogAtten = cc_fogAdd.z;\n float _FogTop = cc_fogAdd.x;\n float _FogRange = cc_fogAdd.y;\n vec3 camWorldProj = cc_cameraPos.xyz;\n camWorldProj.y = 0.;\n vec3 worldPosProj = wPos.xyz;\n worldPosProj.y = 0.;\n float fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\n float fDeltaY, fDensityIntegral;\n if (cc_cameraPos.y > _FogTop) {\n if (wPos.y < _FogTop) {\n fDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\n fDensityIntegral = fDeltaY * fDeltaY * 0.5;\n } else {\n fDeltaY = 0.;\n fDensityIntegral = 0.;\n }\n } else {\n if (wPos.y < _FogTop) {\n float fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\n float fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\n fDeltaY = abs(fDeltaA - fDeltaB);\n fDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n } else {\n fDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\n fDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n }\n }\n float fDensity;\n if (fDeltaY != 0.) {\n fDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n } else {\n fDensity = 0.;\n }\n float f = exp(-fDensity);\n return f;\n}\nfloat CC_TRANSFER_FOG(vec4 pos) {\n #if CC_USE_FOG == 1\n return LinearFog(pos);\n #elif CC_USE_FOG == 2\n return ExpFog(pos);\n #elif CC_USE_FOG == 3\n return ExpSquaredFog(pos);\n #elif CC_USE_FOG == 4\n return LayeredFog(pos);\n #endif\n return 1.;\n}\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\nvarying float factor_fog;\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 factor_fog = CC_TRANSFER_FOG(matWorld * position);\n return cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }`, "frag": `\nprecision mediump float;\nuniform mediump vec4 cc_exposure;\nuniform mediump vec4 cc_fogColor;\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\nvarying float factor_fog;\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 o = mix(cc_fogColor, o, factor_fog);\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", "dummyDependency": true, "range": [2, 8] }, + { "name": "CC_MORPH_TARGET_COUNT", "type": "number", "range": [2, 8] }, { "name": "CC_MORPH_PRECOMPUTED", "type": "boolean" }, { "name": "CC_MORPH_TARGET_HAS_POSITION", "type": "boolean" }, { "name": "CC_MORPH_TARGET_HAS_NORMAL", "type": "boolean" }, { "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_FOG", "type": "number", "range": [0, 4] }, { "name": "USE_VERTEX_COLOR", "type": "boolean" }, { "name": "USE_TEXTURE", "type": "boolean" }, { "name": "FLIP_UV", "type": "boolean" }, { "name": "CC_USE_HDR", "type": "boolean" }, { "name": "USE_ALPHA_TEST", "type": "boolean" }, - { "name": "ALPHA_TEST_CHANNEL", "type": "string", "dummyDependency": true, "options": ["a", "r", "g", "b"] } + { "name": "ALPHA_TEST_CHANNEL", "type": "string", "options": ["a", "r", "g", "b"] } ], "blocks": [ {"name": "TexCoords", "defines": ["USE_TEXTURE"], "binding": 0, "members": [ @@ -489,15 +490,15 @@ export default [ { "name": "mainTexture", "type": 28, "count": 1, "defines": ["USE_TEXTURE"], "binding": 31 } ], "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, "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 }, + { "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 } ] @@ -513,45 +514,45 @@ export default [ "shaders": [ { "name": "pipeline/planar-shadow|planar-shadow-vs:vert|planar-shadow-fs:frag", - "hash": 2467023454, + "hash": 2011749318, "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 mediump vec4 cc_fogColor;\n mediump vec4 cc_fogBase;\n mediump vec4 cc_fogAdd;\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 highp vec4 cc_lightingMapUVParam;\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 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 mediump vec4 cc_fogColor;\n mediump vec4 cc_fogBase;\n mediump vec4 cc_fogAdd;\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 highp vec4 cc_lightingMapUVParam;\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 mediump vec4 cc_fogColor;\n mediump vec4 cc_fogBase;\n mediump vec4 cc_fogAdd;\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 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": { "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", "dummyDependency": true, "range": [2, 8] }, + { "name": "CC_MORPH_TARGET_COUNT", "type": "number", "range": [2, 8] }, { "name": "CC_MORPH_PRECOMPUTED", "type": "boolean" }, { "name": "CC_MORPH_TARGET_HAS_POSITION", "type": "boolean" }, { "name": "CC_MORPH_TARGET_HAS_NORMAL", "type": "boolean" }, { "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, "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 }, + { "name": "a_dyn_batch_id", "type": 13, "count": 1, "defines": ["!USE_INSTANCING", "USE_BATCHING"], "format": 11, "location": 8 } ] } ] @@ -579,7 +580,7 @@ export default [ "locals": { "blocks": [], "samplers": [] } }, "defines": [ - { "name": "CC_USE_IBL", "type": "number", "dummyDependency": true, "range": [0, 2] }, + { "name": "CC_USE_IBL", "type": "number", "range": [0, 2] }, { "name": "CC_USE_HDR", "type": "boolean" }, { "name": "USE_RGBE_CUBEMAP", "type": "boolean" } ], diff --git a/cocos/core/3d/framework/batched-skinning-model-component.ts b/cocos/core/3d/framework/batched-skinning-model-component.ts index 8058a17c60..c27d5ab272 100644 --- a/cocos/core/3d/framework/batched-skinning-model-component.ts +++ b/cocos/core/3d/framework/batched-skinning-model-component.ts @@ -105,7 +105,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 }) @@ -206,7 +206,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 () { @@ -219,7 +219,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; } @@ -303,16 +303,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; @@ -503,74 +503,90 @@ export class BatchedSkinningModelComponent extends SkinningModelComponent { private _createUnitMesh (unitIdx: number, mesh: Mesh) { // add batch ID to this temp mesh - // first, update bookkeepping - 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; } - } + // first, update bookkeeping 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, legacyCC.sys.isLittleEndian); - // insert batch UV - dataView.setFloat32(newOffset + oldStride + 4, uvs[j * 2], legacyCC.sys.isLittleEndian); - dataView.setFloat32(newOffset + oldStride + 8, uvs[j * 2 + 1], legacyCC.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 = legacyCC.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/3d/framework/camera-component.ts b/cocos/core/3d/framework/camera-component.ts index f2eb9da5e8..98c5cafee2 100644 --- a/cocos/core/3d/framework/camera-component.ts +++ b/cocos/core/3d/framework/camera-component.ts @@ -650,3 +650,12 @@ export class CameraComponent extends Component { } } } + +export namespace CameraComponent { + 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/editor-camera-component.ts b/cocos/core/3d/framework/editor-camera-component.ts deleted file mode 100644 index dec5c7a837..0000000000 --- a/cocos/core/3d/framework/editor-camera-component.ts +++ /dev/null @@ -1,155 +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'; -import { legacyCC } from '../../global-exports'; - -@ccclass('cc.EditorCameraComponent') -export class EditorCameraComponent extends CameraComponent { - - private _uiEditorCamera: Camera | null = null; - - set projection (val) { - super.projection = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.projectionType = val; - } - } - - set fov (val) { - super.fov = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.fov = toRadian(val); - } - } - - set orthoHeight (val) { - super.orthoHeight = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.orthoHeight = val; - } - } - - set near (val) { - super.near = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.nearClip = val; - } - } - - set far (val) { - super.far = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.farClip = val; - } - } - - set clearColor (val) { - super.clearColor = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.clearColor = val; - } - } - - set clearDepth (val) { - super.clearDepth = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.clearDepth = val; - } - } - - set clearStencil (val) { - super.clearStencil = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.clearStencil = val; - } - } - - set clearFlags (val) { - super.clearFlags = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.clearFlag = val; - } - } - - set rect (val) { - super.rect = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.viewport = val; - } - } - - set screenScale (val) { - super.screenScale = val; - if (this._uiEditorCamera) { - this._uiEditorCamera.screenScale = val; - } - } - - public onLoad () { - super.onLoad(); - - this._inEditorMode = true; - } - - public onEnable () { - super.onEnable(); - if (this._uiEditorCamera) { - legacyCC.director.root!.ui.renderScene.addCamera(this._uiEditorCamera); - this._uiEditorCamera.enabled = true; - } - } - - public onDisable () { - super.onDisable(); - if (this._uiEditorCamera) { - legacyCC.director.root!.ui.renderScene.removeCamera(this._uiEditorCamera); - } - } - - public onDestroy () { - super.onDestroy(); - if (this._uiEditorCamera) { - legacyCC.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) { - legacyCC.director.root!.destroyCamera(this._uiEditorCamera); - this._uiEditorCamera = null; - } - this._uiEditorCamera = legacyCC.director.root!.createCamera(); - this._uiEditorCamera!.initialize({ - name: 'Editor UICamera', - node: this._camera.node, - projection: this._projection, - window: legacyCC.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 812d8764b2..fded2b8f12 100644 --- a/cocos/core/3d/framework/index.ts +++ b/cocos/core/3d/framework/index.ts @@ -31,7 +31,6 @@ import { legacyCC } from '../../global-exports'; 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,7 @@ export { // cc.AnimationComponent = AnimationComponent; legacyCC.CameraComponent = CameraComponent; -legacyCC.EditorComponent = EditorCameraComponent; +// legacyCC.EditorComponent = EditorCameraComponent; legacyCC.RenderableComponent = RenderableComponent; legacyCC.ModelComponent = ModelComponent; legacyCC.SkinningModelComponent = SkinningModelComponent; diff --git a/cocos/core/3d/framework/light-component.ts b/cocos/core/3d/framework/light-component.ts index 2b6b6d53c2..efcc44b7fd 100644 --- a/cocos/core/3d/framework/light-component.ts +++ b/cocos/core/3d/framework/light-component.ts @@ -271,3 +271,8 @@ export class LightComponent extends Component { } } } + +export namespace LightComponent { + 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 454252f06a..b2047e050d 100644 --- a/cocos/core/3d/framework/model-component.ts +++ b/cocos/core/3d/framework/model-component.ts @@ -41,6 +41,7 @@ import { builtinResMgr } from '../builtin'; import { RenderableComponent } from './renderable-component'; import { MorphRenderingInstance } from '../../assets/morph'; import { legacyCC } from '../../global-exports'; +import { assertIsTrue } from '../../data/utils/asserts'; /** * @en Shadow projection mode. @@ -77,8 +78,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 +112,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; } /** @@ -202,7 +205,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; } @@ -211,8 +222,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; @@ -221,7 +233,7 @@ export class ModelComponent extends RenderableComponent { constructor () { super(); - this._modelType = MorphModel; + this._modelType = Model; } public onLoad () { @@ -272,12 +284,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; if (this.model !== null) { this.model.updateLightingmap(this.lightmapSettings.texture, this.lightmapSettings.uvParam); @@ -304,12 +316,21 @@ export class ModelComponent extends RenderableComponent { } protected _createModel () { - this._model = (legacyCC.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 = (legacyCC.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); } } @@ -319,10 +340,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 () { @@ -377,7 +398,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; } @@ -386,10 +407,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; } } @@ -436,7 +459,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) { @@ -450,3 +475,7 @@ export class ModelComponent extends RenderableComponent { subMeshMorphInstance.renderResources.setWeights(subMeshMorphInstance.weights); } } + +export namespace ModelComponent { + export type ShadowCastingMode = EnumAlias; +} 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/core/animation/animation-component.ts b/cocos/core/animation/animation-component.ts index 6a92c57eef..aeebf15bc6 100644 --- a/cocos/core/animation/animation-component.ts +++ b/cocos/core/animation/animation-component.ts @@ -28,58 +28,17 @@ */ 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 { 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'; 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'; import { legacyCC } from '../global-exports'; -/** - * @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); - /** * 动画组件管理动画状态来控制动画的播放。 * 它提供了方便的接口用来预创建指定动画剪辑的动画状态,并提供了一系列事件: @@ -95,7 +54,7 @@ ccenum(EventType); @executionOrder(99) @executeInEditMode @menu('Components/Animation') -export class AnimationComponent extends Component implements IEventTarget { +export class AnimationComponent extends Eventify(Component) { /** * 获取此动画组件的自有动画剪辑。 * 动画组件开始运行时会为每个自有动画剪辑创建动画状态。 @@ -181,14 +140,12 @@ 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); + protected _nameToState: Record = createMap(true); @property({ type: [AnimationClip] }) - protected _clips: Array<(AnimationClip | null)> = []; + protected _clips: (AnimationClip | null)[] = []; @property protected _defaultClip: AnimationClip | null = null; @@ -322,6 +279,7 @@ export class AnimationComponent extends Component implements IEventTarget { public removeState (name: string) { const state = this._nameToState[name]; if (state) { + state.allowLastFrameEvent(false); state.stop(); delete this._nameToState[name]; } @@ -354,11 +312,12 @@ export class AnimationComponent extends Component implements IEventTarget { * @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; } } @@ -371,8 +330,8 @@ export class AnimationComponent extends Component implements IEventTarget { } } - if (state && state.isPlaying) { - if (force) { state.stop(); } + if (removalState && removalState.isPlaying) { + if (force) { removalState.stop(); } else { if (!TEST) { warnID(3903); } return; @@ -381,8 +340,8 @@ export class AnimationComponent extends Component implements IEventTarget { this._clips = this._clips.filter((item) => item !== clip); - if (state) { - delete this._nameToState[state.name]; + if (removalState) { + delete this._nameToState[removalState.name]; } } @@ -411,12 +370,18 @@ 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); - if (type === 'lastframe') { - for (const stateName of Object.keys(this._nameToState)) { - this._nameToState[stateName]!._lastframeEventOn = true; - } + public on (type: EventType, callback: TFunction, thisArg?: any) { + const ret = super.on(type, callback, thisArg); + 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; } @@ -435,33 +400,13 @@ export class AnimationComponent extends Component implements IEventTarget { * animation.off('play', this.onPlay, this); * ``` */ - public off (type: string, callback: Function, target?: Object) { - if (type === 'lastframe') { - const nameToState = this._nameToState; - for (const name of Object.keys(nameToState)) { - const state = nameToState[name]!; - state._lastframeEventOn = false; - } + public off (type: EventType, callback?: Function, thisArg?: any) { + super.off(type, callback, thisArg); + if (type === EventType.LASTFRAME) { + this._syncDisallowLastFrameEvent(); } - - EventTarget.prototype.off.call(this, type, callback, target); } - /** - * @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); } @@ -469,6 +414,7 @@ export class AnimationComponent extends Component implements IEventTarget { 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); } @@ -502,14 +448,27 @@ export class AnimationComponent extends Component implements IEventTarget { } } } + + 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); + } + } + } } -// for restore on and off -const {on, off} = AnimationComponent.prototype; -applyMixins(AnimationComponent, [CallbacksInvoker, EventTarget]); -// restore -AnimationComponent.prototype.on = on; -AnimationComponent.prototype.off = off; +export namespace AnimationComponent { + export type EventType = EnumAlias; +} legacyCC.AnimationComponent = AnimationComponent; diff --git a/cocos/core/animation/animation-manager.ts b/cocos/core/animation/animation-manager.ts index ee6e9b29e1..98e2a18088 100644 --- a/cocos/core/animation/animation-manager.ts +++ b/cocos/core/animation/animation-manager.ts @@ -13,6 +13,13 @@ import { BlendStateBuffer } from './skeletal-animation-blending'; import { AnimationState } from './animation-state'; import { CrossFade } from './cross-fade'; import { legacyCC } from '../global-exports'; +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 { @@ -23,9 +30,14 @@ export class AnimationManager extends System { public static ID = 'animation'; private _anims = new MutableForwardIterator([]); - private _delayEvents: Array<{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[] = []; public addCrossFade (crossFade: CrossFade) { this._crossFades.push(crossFade); @@ -36,8 +48,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; @@ -49,12 +63,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]; - event.target[event.func].apply(event.target, event.args); + 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); } - events.length = 0; + + for (let i = 0, l = _delayEvents.length; i < l; i++) { + const event = _delayEvents[i]; + event.fn.apply(event.thisArg, event.args); + } + _delayEvents.length = 0; } public destruct () { @@ -77,13 +96,40 @@ 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, }); } + + 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 16ec44b025..ea024d371e 100644 --- a/cocos/core/animation/animation-state.ts +++ b/cocos/core/animation/animation-state.ts @@ -27,35 +27,64 @@ * @category animation */ -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'; import { legacyCC } from '../global-exports'; +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 ( @@ -66,7 +95,6 @@ export class ICurveInstance { this._curveDetail = runtimeCurve; this._boundTarget = boundTarget; - this._rootTarget = target; } public applySample (ratio: number, index: number, lerpRequired: boolean, samplerResultCache, weight: number) { @@ -127,15 +155,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. @@ -242,12 +261,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 /** @@ -278,8 +291,6 @@ export class AnimationState extends Playable { public frameRate = 0; - public _lastframeEventOn = false; - protected _wrapMode = WrapMode.Normal; protected _repeatCount = 1; @@ -305,15 +316,16 @@ 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; private _blendStateWriters: IBlendStateWriter[] = []; private _isBlendStateWriterInitialized = false; + private _allowLastFrame = false; constructor (clip: AnimationClip, name = '') { super(); @@ -368,7 +380,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 { @@ -416,64 +428,59 @@ export class AnimationState extends Playable { this._destroyBlendStateWriters(); } - public _emit (type, state) { - if (this._target && this._target.isValid) { - this._target.emit(type, type, state); - } + /** + * @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[]) { + legacyCC.director.getAnimationManager().pushDelayEvent(this._emit, this, args); } - 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]; - } - legacyCC.director.getAnimationManager().pushDelayEvent(this, '_emit', 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._lastframeEventOn = 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._lastframeEventOn = true; - } - return this._target.once(type, (event) => { - callback.call(target, event); - this._lastframeEventOn = 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._lastframeEventOn = 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; } @@ -613,7 +620,7 @@ export class AnimationState extends Playable { // sample const info = this.sample(); - if (this._lastframeEventOn) { + if (this._allowLastFrame) { let lastInfo; if (!this._lastWrapInfo) { lastInfo = this._lastWrapInfo = new WrappedInfo(info); @@ -622,7 +629,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); @@ -630,7 +637,7 @@ export class AnimationState extends Playable { if (info.stopped) { this.stop(); - this.emit('finished', this); + this.emit(EventType.FINISHED, this); } } @@ -647,13 +654,13 @@ export class AnimationState extends Playable { } } - if (this._lastframeEventOn) { + 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; @@ -667,24 +674,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) { @@ -818,13 +825,19 @@ export class AnimationState extends Playable { lastIndex += direction; - legacyCC.director.getAnimationManager().pushDelayEvent(this, '_fireEvent', [lastIndex]); + legacyCC.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/cocos/core/animation/cross-fade.ts b/cocos/core/animation/cross-fade.ts index b1dd9307a6..399f1609b6 100644 --- a/cocos/core/animation/cross-fade.ts +++ b/cocos/core/animation/cross-fade.ts @@ -44,10 +44,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); @@ -56,6 +52,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. 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 b8c8efc516..f787e7b0b1 100644 --- a/cocos/core/animation/skeletal-animation-component.ts +++ b/cocos/core/animation/skeletal-animation-component.ts @@ -38,6 +38,7 @@ import { SkelAnimDataHub } from './skeletal-animation-data-hub'; import { SkeletalAnimationState } from './skeletal-animation-state'; import { getWorldTransformUntilRoot } from './transform-utils'; import { legacyCC } from '../global-exports'; +import { AnimationManager } from './animation-manager'; @ccclass('cc.SkeletalAnimationComponent.Socket') export class Socket { @@ -78,7 +79,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. @@ -111,6 +112,11 @@ export class SkeletalAnimationComponent extends AnimationComponent { return this._sockets; } set sockets (val) { + if (!this._useBakedAnimation) { + const animMgr = legacyCC.director.getAnimationManager() as AnimationManager; + animMgr.removeSockets(this.node, this._sockets); + animMgr.addSockets(this.node, val); + } this._sockets = val; this.rebuildSocketAnimations(); } @@ -139,6 +145,8 @@ export class SkeletalAnimationComponent extends AnimationComponent { comp.setUseBakedAnimation(this._useBakedAnimation); } } + if (this._useBakedAnimation) { (legacyCC.director.getAnimationManager() as AnimationManager).removeSockets(this.node, this._sockets); } + else { (legacyCC.director.getAnimationManager() as AnimationManager).addSockets(this.node, this._sockets); } } @property @@ -150,6 +158,7 @@ export class SkeletalAnimationComponent extends AnimationComponent { public onDestroy () { super.onDestroy(); (legacyCC.director.root.dataPoolManager as DataPoolManager).jointAnimationInfo.destroy(this.node.uuid); + (legacyCC.director.getAnimationManager() as AnimationManager).removeSockets(this.node, this._sockets); } public start () { diff --git a/cocos/core/animation/skeletal-animation-data-hub.ts b/cocos/core/animation/skeletal-animation-data-hub.ts index 37168f23e1..fdb4ebb85d 100644 --- a/cocos/core/animation/skeletal-animation-data-hub.ts +++ b/cocos/core/animation/skeletal-animation-data-hub.ts @@ -33,12 +33,12 @@ import { AnimationClip, IObjectCurveData } from './animation-clip'; import { HierarchyPath, isCustomPath, isPropertyPath } from './target-path'; import { legacyCC } from '../global-exports'; -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; @@ -115,20 +115,27 @@ 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 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 { + (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 c057d2f5cd..8617e42673 100644 --- a/cocos/core/animation/skeletal-animation-state.ts +++ b/cocos/core/animation/skeletal-animation-state.ts @@ -30,13 +30,11 @@ 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'; import { SkeletalAnimationComponent, Socket } from './skeletal-animation-component'; import { SkelAnimDataHub } from './skeletal-animation-data-hub'; -import { getWorldTransformUntilRoot } from './transform-utils'; import { legacyCC } from '../global-exports'; const m4_1 = new Mat4(); @@ -50,7 +48,6 @@ interface ITransform { interface ISocketData { target: Node; - transform: IJointTransform; frames: ITransform[]; } @@ -103,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; @@ -114,44 +111,52 @@ 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; } - const sourceData = SkelAnimDataHub.getOrExtract(this.clip).data; - // find lowest joint animation + if (!socket.target) { continue; } + 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!; + source = clipData.data[animPath]; + if (animNode) { + 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; } } - // create animation data - const socketData: ISocketData = { - target: socket.target, transform, - frames: source.worldMatrix.values.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]; - Mat4.toRTS(Mat4.multiply(m4_2, m, m4_1), dst.rot, dst.pos, dst.scale); + const curveData: Mat4[] | undefined = source && source.worldMatrix.values as Mat4[]; + const frames = clipData.info.frames; + const transforms: ITransform[] = []; + for (let f = 0; f < frames; f++) { + let mat: Mat4; + 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; + } + 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(socketData); + this._sockets.push({ + target: socket.target, + frames: transforms, + }); } } @@ -167,13 +172,4 @@ export class SkeletalAnimationState extends AnimationState { target.setRTS(rot, pos, scale); } } - - private _sampleCurvesRealTime (ratio: number) { - super._sampleCurves(ratio); - const stamp = legacyCC.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/assets/asset.ts b/cocos/core/assets/asset.ts index ceecc10e2c..f7277a6bf1 100644 --- a/cocos/core/assets/asset.ts +++ b/cocos/core/assets/asset.ts @@ -28,12 +28,8 @@ * @category asset */ -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 { ccclass, property } from '../data/class-decorator'; +import { Eventify } from '../event'; import { RawAsset } from './raw-asset'; import { Node } from '../scene-graph'; import { legacyCC } from '../global-exports'; @@ -60,7 +56,7 @@ import { legacyCC } from '../global-exports'; * @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`. @@ -112,33 +108,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. @@ -265,8 +234,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/image-asset.ts b/cocos/core/assets/image-asset.ts index 23d7f84473..7def7a8f4e 100644 --- a/cocos/core/assets/image-asset.ts +++ b/cocos/core/assets/image-asset.ts @@ -78,7 +78,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); } @@ -200,14 +200,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 = ""; + legacyCC.loader.removeItem(this.data.id); + } + return super.destroy(); + } // SERIALIZATION diff --git a/cocos/core/assets/mesh.ts b/cocos/core/assets/mesh.ts index 136e2da74d..51e8ed05ec 100644 --- a/cocos/core/assets/mesh.ts +++ b/cocos/core/assets/mesh.ts @@ -132,7 +132,9 @@ export class RenderingSubMesh { * (用于射线检测的)几何信息。 */ get geometricInfo () { - if (this._geometricInfo) { return this._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 } }; } @@ -747,7 +749,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/morph-rendering.ts b/cocos/core/assets/morph-rendering.ts index d97f57506f..0b24a2bec0 100644 --- a/cocos/core/assets/morph-rendering.ts +++ b/cocos/core/assets/morph-rendering.ts @@ -8,7 +8,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'; @@ -43,6 +43,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, diff --git a/cocos/core/assets/simple-texture.ts b/cocos/core/assets/simple-texture.ts index e32da7ddeb..8fe25ef710 100644 --- a/cocos/core/assets/simple-texture.ts +++ b/cocos/core/assets/simple-texture.ts @@ -13,6 +13,7 @@ import { ImageAsset } from './image-asset'; import { TextureBase } from './texture-base'; import { DEV } from 'internal:constants'; import { legacyCC } from '../global-exports'; +import { macro } from '../platform/macro'; const _regions: GFXBufferTextureCopy[] = [{ buffStride: 0, @@ -151,6 +152,10 @@ export class SimpleTexture extends TextureBase { } this.uploadData(data, level, arrayIndex); this._checkTextureLoaded(); + + if (macro.CLEANUP_IMAGE_CACHE) { + image.destroy(); + } }; if (image.loaded) { upload(); diff --git a/cocos/core/assets/skeleton.ts b/cocos/core/assets/skeleton.ts index c65f7c050a..699d9843f3 100644 --- a/cocos/core/assets/skeleton.ts +++ b/cocos/core/assets/skeleton.ts @@ -51,6 +51,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` 的长度相同。 */ @@ -62,15 +75,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/assets/sprite-frame.ts b/cocos/core/assets/sprite-frame.ts index e5195aabf3..97f53728e4 100644 --- a/cocos/core/assets/sprite-frame.ts +++ b/cocos/core/assets/sprite-frame.ts @@ -38,6 +38,8 @@ import { RenderTexture } from './render-texture'; import { TextureBase } from './texture-base'; import { EDITOR } from 'internal:constants'; import { legacyCC } from '../global-exports'; +import { ImageAsset, ImageSource } from './image-asset'; +import { Texture2D } from './texture-2d'; const INSET_LEFT = 0; const INSET_TOP = 1; @@ -182,6 +184,23 @@ 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 or an native image asset + * @zh + * 通过 Image 资源或者原始 image 资源创建一个 SpriteFrame 对象 + * @param imageSourceOrImageAsset ImageAsset or ImageSource, ImageSource support HTMLCanvasElement HTMLImageElement IMemoryImageSource + */ + 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(); + spf.texture = tex; + return spf; + } + /** * @en * Top border of the sprite. diff --git a/cocos/core/assets/texture-util.ts b/cocos/core/assets/texture-util.ts index 366b7a40c2..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, @@ -46,7 +47,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); @@ -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/components/ui-base/canvas-component.ts b/cocos/core/components/ui-base/canvas-component.ts index f679d9f891..fd38e13141 100644 --- a/cocos/core/components/ui-base/canvas-component.ts +++ b/cocos/core/components/ui-base/canvas-component.ts @@ -50,8 +50,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({ @@ -232,7 +232,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/core/components/ui-base/ui-transform-component.ts b/cocos/core/components/ui-base/ui-transform-component.ts index 7fbd12db42..a5235f024f 100644 --- a/cocos/core/components/ui-base/ui-transform-component.ts +++ b/cocos/core/components/ui-base/ui-transform-component.ts @@ -43,6 +43,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 @@ -397,6 +398,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; diff --git a/cocos/core/data/class-decorator.ts b/cocos/core/data/class-decorator.ts index 8dfe15166f..4595dcb1a9 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'; @@ -56,6 +48,7 @@ import { CCString, CCInteger, CCFloat, CCBoolean, PrimitiveType } from './utils/ import { error, errorID, warnID } from '../platform/debug'; import { DEV } from 'internal:constants'; import { legacyCC } from '../global-exports'; +import { Component } from '../components/component'; // caches for class construction const CACHE_KEY = '__ccclassCache__'; @@ -243,10 +236,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; @@ -264,8 +256,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(){};}'); // } @@ -315,25 +306,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()`。 */ @@ -382,13 +377,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; @@ -403,47 +396,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; @@ -455,18 +447,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 { * // ... * } @@ -475,16 +466,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 { * // ... * } @@ -493,28 +483,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 @@ -527,117 +515,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 d1aed3d3cd..5d1d18ed75 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 @@ -895,95 +895,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 e1ab04325a..9d2642c3c8 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 159c7b9160..ff4fa53a55 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 7f8447522a..0b79483505 100644 --- a/cocos/core/data/instantiate.ts +++ b/cocos/core/data/instantiate.ts @@ -35,6 +35,8 @@ import { js } from '../utils'; import { errorID, warn } from '../platform/debug'; import { DEV } from 'internal:constants'; import { legacyCC } from '../global-exports'; +import Prefab from '../assets/prefab'; +import { Node } from '../scene-graph/node'; // @ts-ignore const Destroyed = CCObject.Flags.Destroyed; @@ -46,12 +48,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 @@ -64,7 +63,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) { @@ -98,8 +97,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) { legacyCC.game._isCloning = true; + // @ts-ignore clone = original._instantiate(); legacyCC.game._isCloning = false; return clone; @@ -119,16 +120,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 1d739a9cb1..64375e894a 100644 --- a/cocos/core/data/object.ts +++ b/cocos/core/data/object.ts @@ -156,9 +156,6 @@ function compileDestruct (obj, ctor) { * The base class of most of all the objects in Fireball. * @zh * 大部分对象的基类。 - * @class Object - * - * @main * @private */ class CCObject { @@ -236,8 +233,6 @@ class CCObject { * 当一个对象的 `destroy` 调用以后,会在这一帧结束后才真正销毁。
* 因此从下一帧开始 `isValid` 就会返回 false,而当前帧内 `isValid` 仍然会是 true。
* 如果希望判断当前帧是否调用过 `destroy`,请使用 `cc.isValid(obj, true)`,不过这往往是特殊的业务需求引起的,通常情况下不需要这样。 - * - * @property {Boolean} isValid * @default true * @readOnly * @example @@ -251,7 +246,7 @@ class CCObject { * cc.log(node.isValid); // false, destroyed in the end of last frame * ``` */ - get isValid () { + get isValid (): boolean { return !(this._objFlags & Destroyed); } @@ -265,7 +260,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(); @@ -381,7 +376,7 @@ if (EDITOR) { } }); - /** + /* * The customized serialization for this object. (Editor Only) * @method _serialize * @param {Boolean} exporting @@ -392,7 +387,7 @@ if (EDITOR) { prototype._serialize = null; } -/** +/* * Init this object from the custom serialized data. * @method _deserialize * @param {Object} data - the serialized json data @@ -401,7 +396,7 @@ if (EDITOR) { */ // @ts-ignore prototype._deserialize = null; -/** +/* * Called before the object being destroyed. * @method _onPreDestroy * @private @@ -414,7 +409,6 @@ CCClass.fastDefine('cc.Object', CCObject, { _name: '', _objFlags: 0 }); /** * Bit mask that controls object states. * @enum Object.Flags - * @static * @private */ js.value(CCObject, 'Flags', { @@ -425,14 +419,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, @@ -455,7 +447,6 @@ js.value(CCObject, 'Flags', { /** * @en The node is deactivating. * @zh 节点正在反激活的过程中。 - * @property Deactivating * @private */ Deactivating, @@ -463,8 +454,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, @@ -485,7 +474,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, @@ -496,7 +484,6 @@ js.value(CCObject, 'Flags', { // * @zh // * 在游戏视图,层级,场景视图等等...中隐藏该对象。 // * 该标记只读,它只能被用作 scene.addEntity()的一个参数。 - // * @property {Number} Hide // */ // Hide: Hide, @@ -519,11 +506,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 cd26cef5c4..0a47811ca1 100644 --- a/cocos/core/event/callbacks-invoker.ts +++ b/cocos/core/event/callbacks-invoker.ts @@ -227,7 +227,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]; @@ -298,9 +298,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; @@ -317,10 +321,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); } } } @@ -333,6 +337,13 @@ export class CallbacksInvoker { } } } + + /** + * 移除所有回调。 + */ + public clear () { + this._callbackTable = createMap(true); + } } if (TEST) { diff --git a/cocos/core/event/event-target.ts b/cocos/core/event/event-target.ts index b125036545..ee592da36a 100644 --- a/cocos/core/event/event-target.ts +++ b/cocos/core/event/event-target.ts @@ -31,168 +31,24 @@ import * as js from '../utils/js'; import { CallbacksInvoker } from './callbacks-invoker'; import { legacyCC } from '../global-exports'; +import { Eventify } from './eventify'; -const fastRemove = js.array.fastRemove; - -export interface ITargetImpl extends Object { - __eventTargets?: Object[]; - node?: ITargetImpl; -} +// eslint-disable-next-line @typescript-eslint/no-extraneous-class +class Empty {}; /** - * !#en + * @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. + * [[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]]. * - * 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 是最常见的事件目标, + * @zh + * 事件目标是具有注册监听器、派发事件能力的类,[[Node]] 是最常见的事件目标, * 但是其他类也可以继承自事件目标以获得管理监听器和派发事件的能力。 - * 如果无法继承自 EventTarget,也可以考虑自实现 IEventTarget + * 如果无法继承自 EventTarget,也可以使用 [[Eventify]] */ -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) { - legacyCC.errorID(6800); - return; - } +export const EventTarget = Eventify(Empty); - 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) { - legacyCC.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; legacyCC.EventTarget = EventTarget; diff --git a/cocos/core/event/eventify.ts b/cocos/core/event/eventify.ts new file mode 100644 index 0000000000..cc1d880eb0 --- /dev/null +++ b/cocos/core/event/eventify.ts @@ -0,0 +1,207 @@ +/** + * @category event + */ + +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 + * 实现该接口的对象具有处理事件的能力。 + * @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, arg0?: any, arg1?: any, arg2?: any, arg3?: any, arg4?: any): void; +} + +/** + * @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: Extend from `Base` + * o.emit('sing', 'The ghost'); // Ok: `MyClass` implements IEventified + * } + * ``` + */ +export function Eventify (base: Constructor): Constructor { + 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)) { + callbacksInvokerOn.call(this, type, callback, target); + if (target) { + this._registerThisIntoTarget(target); + } + } + return callback; + } + + public once (type: EventType, callback: Callback, target?: object) { + if (!this.hasEventListener(type, callback, target)) { + callbacksInvokerOn.call(this, 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 { + callbacksInvokerOff.call(this, type, callback, target); + if (target) { + this._unregisterThisIntoTarget(target); + } + } + } + + public targetOff (typeOrTarget: string | object) { + this.removeAll(typeOrTarget); + } + + 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); + } + } + }; + + // Mixin with `CallbacksInvokers`'s prototype + const propertyDescriptors = Object.getOwnPropertyDescriptors(CallbacksInvoker.prototype); + for (const propertyName in propertyDescriptors) { + if (!(propertyName in Eventified.prototype)) { + Object.defineProperty(Eventified.prototype, propertyName, propertyDescriptors[propertyName]); + } + } + + return Eventified as unknown as any; +} + +interface ITargetImpl extends Object { + __eventTargets?: any[]; + 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/core/game.ts b/cocos/core/game.ts index fc3fbe1c48..d1b50f9e1f 100644 --- a/cocos/core/game.ts +++ b/cocos/core/game.ts @@ -434,7 +434,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, @@ -443,12 +443,12 @@ export class Game extends EventTarget { let swapbuffers = 3; const cb = () => { if (--swapbuffers > 1) { - window.requestAnimationFrame(cb); + window.rAF(cb); } const root = legacyCC.director.root; root.frameMove(0); root.device.present(); }; - window.requestAnimationFrame(cb); + window.rAF(cb); } } @@ -633,7 +633,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; } @@ -643,7 +643,7 @@ export class Game extends EventTarget { }); } else { - this.emit(Game.EVENT_GAME_INITED); + this._safeEmit(Game.EVENT_GAME_INITED); if (useSplash) { splashScreen.loadFinish = true; } @@ -735,20 +735,27 @@ export class Game extends EventTarget { if (JSB) { jsb.setPreferredFramesPerSecond(frameRate); + window.rAF = window.requestAnimationFrame; + window.cAF = window.cancelAnimationFrame; } - 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 || @@ -784,7 +791,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) { @@ -795,11 +802,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; } @@ -1015,7 +1022,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/geometry/intersect.ts b/cocos/core/geometry/intersect.ts index d2ea594b9d..3787ae1afb 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 / 3, vertexIndex1: i1 / 3, vertexIndex2: i2 / 3 }); + } else { + 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 / 3, vertexIndex1: i1 / 3, vertexIndex2: i2 / 3 }); + } } + 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 diff --git a/cocos/core/gfx/define.ts b/cocos/core/gfx/define.ts index 36750d73d3..bbe0ee4539 100644 --- a/cocos/core/gfx/define.ts +++ b/cocos/core/gfx/define.ts @@ -757,6 +757,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; @@ -796,7 +797,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-commands.ts b/cocos/core/gfx/webgl/webgl-commands.ts index cd7971a003..3766c6466d 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; @@ -178,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; @@ -1504,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; @@ -2566,8 +2580,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]; @@ -2703,8 +2715,14 @@ export function WebGLCmdFuncCopyBuffersToTexture ( region.texOffset.x, region.texOffset.y, w, h, gpuTexture.glFormat, pixels); } else { - gl.compressedTexImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, - gpuTexture.glInternelFmt, w, h, 0, pixels); + if (gpuTexture.glInternelFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL && !WECHAT) { + gl.compressedTexSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, pixels); + } else { + gl.compressedTexImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, + gpuTexture.glInternelFmt, w, h, 0, pixels); + } } } } @@ -2731,8 +2749,14 @@ export function WebGLCmdFuncCopyBuffersToTexture ( region.texOffset.x, region.texOffset.y, w, h, gpuTexture.glFormat, pixels); } else { - gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, - gpuTexture.glInternelFmt, w, h, 0, pixels); + if (gpuTexture.glInternelFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL && !WECHAT) { + gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, + region.texOffset.x, region.texOffset.y, w, h, + gpuTexture.glFormat, pixels); + } else { + gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, + gpuTexture.glInternelFmt, w, h, 0, pixels); + } } } } 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/gfx/webgl2/webgl2-commands.ts b/cocos/core/gfx/webgl2/webgl2-commands.ts index d8c12524a1..beb5d0830a 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; @@ -807,8 +817,34 @@ 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: + 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; + case gl.UNIFORM_BUFFER: + gl.bindBuffer(gl.UNIFORM_BUFFER, null); + device.stateCache.glUniformBuffer = null; + break; + } + + gl.deleteBuffer(gpuBuffer.glBuffer); gpuBuffer.glBuffer = null; } } @@ -1739,6 +1775,9 @@ export function WebGL2CmdFuncBeginRenderPass ( clearDepth: number, clearStencil: number) { + gfxStateCache.gpuInputAssembler = null; + gfxStateCache.gpuShader = null; + const gl = device.gl; const cache = device.stateCache; @@ -2575,8 +2614,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]; diff --git a/cocos/core/gfx/webgl2/webgl2-device.ts b/cocos/core/gfx/webgl2/webgl2-device.ts index 9a35f8e296..351a82fb40 100644 --- a/cocos/core/gfx/webgl2/webgl2-device.ts +++ b/cocos/core/gfx/webgl2/webgl2-device.ts @@ -256,7 +256,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; diff --git a/cocos/core/load-pipeline/CCLoader.ts b/cocos/core/load-pipeline/CCLoader.ts index 0924d2564f..c65f468bca 100644 --- a/cocos/core/load-pipeline/CCLoader.ts +++ b/cocos/core/load-pipeline/CCLoader.ts @@ -28,7 +28,9 @@ * @category loader */ -import { Asset, RawAsset } from '../assets'; +import { SpriteAtlas } from '../assets/sprite-atlas'; +import { Asset } from '../assets/asset'; +import { RawAsset } from '../assets/raw-asset' import { SpriteFrame } from '../assets/sprite-frame'; import { Texture2D } from '../assets/texture-2d'; import { TextureCube } from '../assets/texture-cube'; @@ -45,6 +47,8 @@ import { Pipeline } from './pipeline'; import ReleasedAssetChecker from './released-asset-checker'; import { DEBUG, EDITOR, DEV } from 'internal:constants'; import { legacyCC } from '../global-exports'; +import { warnID, errorID, error } from '../platform/debug'; +import * as path from '../utils/path'; const assetTables = Object.create(null); assetTables.assets = new AssetTable(); @@ -56,12 +60,10 @@ function getXMLHttpRequest () { const _info = { url: null, raw: false }; -/** - * @en - * Convert a resources by finding its real url with uuid, otherwise we will use the uuid or raw url as its url
+/* + * @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 */ @@ -99,48 +101,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 来添加自己的下载函数 */ @@ -148,23 +142,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 @@ -176,14 +174,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; @@ -197,6 +192,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; @@ -207,46 +207,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.
@@ -260,19 +253,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])); @@ -282,17 +275,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 legacyCC.error('[cc.loader.load] resources must be non-nil.'); + return error('[loader.load] resources must be non-nil.'); } if (completeCallback === undefined) { @@ -302,23 +294,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) { - legacyCC.warnID(4920, resource.id); + warnID(4920, resource.id); if (!resource.uuid && !resource.url) { resource.url = resource.id; } @@ -353,10 +349,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; @@ -421,39 +415,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; @@ -462,7 +446,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; @@ -471,7 +455,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; @@ -505,14 +489,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.
@@ -522,25 +498,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; @@ -550,19 +524,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; @@ -583,7 +557,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 legacyCC.SpriteAtlas) { + if (assetRes[i] instanceof SpriteAtlas) { const spriteFrames = assetRes[i].getSpriteFrames(); // tslint:disable: forin for (const k in spriteFrames) { @@ -601,28 +575,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. @@ -632,7 +595,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; @@ -642,7 +605,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; @@ -681,10 +644,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]; @@ -705,10 +666,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; @@ -731,23 +690,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); @@ -762,14 +719,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 错误。
@@ -778,25 +735,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]; @@ -809,7 +765,7 @@ export class CCLoader extends Pipeline { if (item) { const removed = this.removeItem(id); asset = item.content; - if (asset instanceof legacyCC.Asset) { + if (asset instanceof Asset) { const nativeUrl = asset.nativeUrl; if (nativeUrl) { this.release(nativeUrl); // uncache loading item of native asset @@ -824,11 +780,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; @@ -838,36 +792,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 { - legacyCC.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; } @@ -879,10 +825,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) { @@ -904,39 +848,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) { - legacyCC.warnID(4902); + warnID(4902); } } @@ -945,33 +888,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) { @@ -984,25 +926,21 @@ export class CCLoader extends Pipeline { } } else if (DEV) { - legacyCC.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]; @@ -1011,10 +949,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) { @@ -1031,13 +969,13 @@ export class CCLoader extends Pipeline { } uuid = assetTable.getUuid(url, type); if (!uuid) { - const extname = legacyCC.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) { - legacyCC.warnID(4901, url, extname); + warnID(4901, url, extname); } } } @@ -1045,17 +983,15 @@ export class CCLoader extends Pipeline { } if (!uuid && type) { if (isChildClassOf(type, SpriteFrame) || isChildClassOf(type, Texture2D) || isChildClassOf(type, TextureCube)) { - legacyCC.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; @@ -1063,20 +999,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) { - legacyCC.warnID(4800, assetOrUrlOrUuid); + warnID(4800, assetOrUrlOrUuid); return key; } legacyCC.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 = legacyCC.url.normalize(url); @@ -1087,15 +1020,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, legacyCC.RawAsset); @@ -1122,10 +1046,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; @@ -1176,6 +1097,9 @@ export class CCLoader extends Pipeline { } } +/** + * Singleton object of CCLoader + */ export const loader = legacyCC.loader = new CCLoader(); if (EDITOR) { diff --git a/cocos/core/load-pipeline/asset-loader.ts b/cocos/core/load-pipeline/asset-loader.ts index bdea7e0104..4d20cece95 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 */ @@ -37,6 +38,10 @@ import { legacyCC } from '../global-exports'; 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; @@ -76,7 +81,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 f87fe927ef..ca945383bb 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 18f5fa1b01..f9ef7edf46 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 */ import { legacyCC } from '../global-exports'; @@ -42,14 +42,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 00de864965..bf0e3f7170 100644 --- a/cocos/core/load-pipeline/downloader.ts +++ b/cocos/core/load-pipeline/downloader.ts @@ -186,45 +186,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; } @@ -232,10 +230,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); } @@ -289,16 +286,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 426c22859d..247ce46e7a 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'; @@ -43,7 +43,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; @@ -201,7 +201,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 6c4aee5de5..1e9ffe99b2 100644 --- a/cocos/core/load-pipeline/loader.ts +++ b/cocos/core/load-pipeline/loader.ts @@ -266,28 +266,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; @@ -295,16 +292,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 4d0698463b..f4825f38f9 100644 --- a/cocos/core/load-pipeline/loading-items.ts +++ b/cocos/core/load-pipeline/loading-items.ts @@ -35,27 +35,36 @@ import { legacyCC } from '../global-exports'; 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 }; @@ -113,8 +122,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; } @@ -175,27 +184,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 legacyCC.Enum(ItemState); @@ -203,10 +196,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) { @@ -215,15 +207,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) { @@ -234,53 +225,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(); @@ -315,8 +296,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]] @@ -382,22 +361,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)); @@ -458,12 +434,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 []; } @@ -472,7 +447,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]; @@ -543,7 +518,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; @@ -555,43 +529,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) { @@ -609,11 +575,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) { @@ -630,9 +594,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; @@ -652,10 +616,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; @@ -692,7 +655,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; @@ -709,8 +671,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]) { @@ -725,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); } @@ -742,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); } @@ -759,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 dfd2b4f3d4..f2120b0b53 100644 --- a/cocos/core/load-pipeline/md5-pipe.ts +++ b/cocos/core/load-pipeline/md5-pipe.ts @@ -43,6 +43,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; @@ -72,7 +76,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 df1d39b58e..1e97cca1e5 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 8c65ef662d..4875c6f819 100644 --- a/cocos/core/load-pipeline/pipeline.ts +++ b/cocos/core/load-pipeline/pipeline.ts @@ -35,10 +35,11 @@ import { legacyCC } from '../global-exports'; 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) { @@ -117,20 +118,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([ @@ -143,7 +149,7 @@ export class Pipeline { * ]); * ``` */ - constructor (pipes) { + constructor (pipes: IPipe[]) { this._pipes = pipes; for (let i = 0; i < pipes.length; ++i) { @@ -159,17 +165,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) { legacyCC.warnID(4921); @@ -183,12 +186,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]; } @@ -202,15 +205,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; @@ -219,16 +219,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; @@ -257,7 +254,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([ @@ -271,7 +268,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 @@ -303,12 +300,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(); @@ -316,7 +313,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]; } @@ -342,11 +344,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; @@ -359,11 +360,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) @@ -380,15 +379,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 d3b5478979..29ff8152ae 100644 --- a/cocos/core/load-pipeline/plist-parser.ts +++ b/cocos/core/load-pipeline/plist-parser.ts @@ -26,11 +26,11 @@ */ /** - * @category loader + * @hidden */ import { EDITOR } from 'internal:constants'; -import { legacyCC } from '../global-exports'; +import { warnID } from '../platform/debug'; /** * A SAX Parser @@ -75,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 */ @@ -90,7 +90,7 @@ class PlistParser extends SAXParser { let xmlDoc = this._parseXML(xmlTxt); let plist = xmlDoc.documentElement; if (plist.tagName !== 'plist') { - legacyCC.warnID(5100); + warnID(5100); return {}; } @@ -107,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"){ @@ -134,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) diff --git a/cocos/core/load-pipeline/released-asset-checker.ts b/cocos/core/load-pipeline/released-asset-checker.ts index 87ddb35fcc..2e60930cad 100644 --- a/cocos/core/load-pipeline/released-asset-checker.ts +++ b/cocos/core/load-pipeline/released-asset-checker.ts @@ -25,13 +25,13 @@ */ /** - * @category loader + * @hidden */ import {createMap, getClassName, clear} from '../utils/js'; import { legacyCC } from '../global-exports'; -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 95d6c554b3..bb9448c4db 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'; @@ -44,18 +44,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 76d56a707c..d87967ce62 100644 --- a/cocos/core/load-pipeline/unpackers.ts +++ b/cocos/core/load-pipeline/unpackers.ts @@ -24,12 +24,14 @@ THE SOFTWARE. */ -import { legacyCC } from '../global-exports'; - /** - * @category loader + * @hidden */ +import { errorID } from "../platform/debug"; +import { js } from "../utils/js"; +import { Texture2D } from "../assets/texture-2d"; + export class JsonUnpacker { public jsons = {}; @@ -39,7 +41,7 @@ export class JsonUnpacker { */ load (indices, packedJson) { if (packedJson.length !== indices.length) { - legacyCC.errorID(4915); + errorID(4915); } for (let i = 0; i < indices.length; i++) { let key = indices[i]; @@ -64,7 +66,7 @@ export class TextureUnpacker { load (indices, packedJson) { let datas = packedJson.data; if (datas.length !== indices.length) { - legacyCC.errorID(4915); + errorID(4915); } for (let i = 0; i < indices.length; i++) { this.contents[indices[i]] = {base: datas[i][0], mipmaps: datas[i][1]}; @@ -75,7 +77,7 @@ export class TextureUnpacker { let content = this.contents[key]; if (content) { return { - __type__: legacyCC.js._getClassId(legacyCC.Texture2D), + __type__: js._getClassId(Texture2D), content: content }; } diff --git a/cocos/core/load-pipeline/url.ts b/cocos/core/load-pipeline/url.ts index 401910ffb4..6ff41055bc 100644 --- a/cocos/core/load-pipeline/url.ts +++ b/cocos/core/load-pipeline/url.ts @@ -25,12 +25,13 @@ */ /** - * 加载相关模块 * @category loader */ import { EDITOR } from 'internal:constants'; import { legacyCC } from '../global-exports'; +import { errorID } from '../platform/debug'; +import { extname, stripSep } from '../utils/path'; /** * @class url @@ -70,20 +71,20 @@ let url = { */ raw: function (url) { if (EDITOR && !this._rawAssets) { - legacyCC.errorID(7000); + errorID(7000); return ''; } url = this.normalize(url); if ( !url.startsWith('resources/') ) { - legacyCC.errorID(EDITOR ? 7001 : 7002, url); + errorID(EDITOR ? 7001 : 7002, url); } else { // Compatible with versions lower than 1.10 var uuid = legacyCC.loader._getResUuid(url.slice(10), legacyCC.Asset, null, true); if (uuid) { - return legacyCC.AssetLibrary.getLibUrlNoExt(uuid, true) + legacyCC.path.extname(url); + return legacyCC.AssetLibrary.getLibUrlNoExt(uuid, true) + extname(url); } } @@ -91,7 +92,7 @@ let url = { }, _init: function (assets) { - this._rawAssets = legacyCC.path.stripSep(assets) + '/'; + this._rawAssets = stripSep(assets) + '/'; } } diff --git a/cocos/core/load-pipeline/utils.ts b/cocos/core/load-pipeline/utils.ts index 8d4b2e507c..80ef27598a 100644 --- a/cocos/core/load-pipeline/utils.ts +++ b/cocos/core/load-pipeline/utils.ts @@ -26,7 +26,7 @@ import { legacyCC } from '../global-exports'; /** - * @category loader + * @hidden */ let _noCacheRex = /\?/; diff --git a/cocos/core/load-pipeline/uuid-loader.ts b/cocos/core/load-pipeline/uuid-loader.ts index ac31a9eeec..57074116ed 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'; @@ -54,7 +54,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 = []; @@ -169,12 +169,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/math/deprecated.ts b/cocos/core/math/deprecated.ts index 4192c19bc0..1bb6c2efa1 100644 --- a/cocos/core/math/deprecated.ts +++ b/cocos/core/math/deprecated.ts @@ -361,8 +361,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 legacyCC.Color.fromHEX(args[0], arg1); }, }, diff --git a/cocos/core/math/quat.ts b/cocos/core/math/quat.ts index 96e0340f74..56f06a2f76 100644 --- a/cocos/core/math/quat.ts +++ b/cocos/core/math/quat.ts @@ -45,14 +45,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; @@ -63,7 +63,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; @@ -74,7 +74,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; @@ -85,7 +85,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); @@ -117,7 +117,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) { @@ -136,7 +136,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; @@ -151,7 +151,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; @@ -162,7 +162,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; @@ -174,7 +174,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); @@ -192,7 +192,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); @@ -210,7 +210,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); @@ -229,7 +229,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); @@ -244,7 +244,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; @@ -253,7 +253,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; @@ -265,14 +265,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); @@ -283,23 +283,27 @@ 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 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) { @@ -315,10 +319,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; } @@ -326,7 +330,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)); @@ -336,7 +340,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; @@ -352,7 +356,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; @@ -363,21 +367,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); @@ -392,7 +396,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, @@ -406,7 +410,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)); } @@ -414,7 +418,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; @@ -427,7 +431,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, @@ -475,7 +479,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; @@ -498,7 +502,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; @@ -511,7 +515,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; @@ -525,7 +529,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; @@ -540,7 +544,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; @@ -575,7 +579,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; @@ -587,7 +591,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]; @@ -598,14 +602,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)) && @@ -636,7 +640,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; @@ -721,46 +725,27 @@ export class Quat extends ValueType { } /** - * @zh 根据指定的插值比率,从当前四元数到目标四元数之间做插值。 + * @zh 根据指定的插值比率,从当前四元数到目标四元数之间做线性插值。 * @param to 目标四元数。 * @param ratio 插值比率,范围为 [0,1]。 */ public lerp (to: Quat, ratio: number) { - let scale0 = 0; - let scale1 = 0; - - // 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; - } - // 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 * 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 = 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) { + return Quat.slerp(this, this, to, ratio); + } + /** * @zh 求四元数长度 */ diff --git a/cocos/core/math/vec3.ts b/cocos/core/math/vec3.ts index d02407ac7d..812a353a79 100644 --- a/cocos/core/math/vec3.ts +++ b/cocos/core/math/vec3.ts @@ -358,7 +358,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; @@ -373,7 +373,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; @@ -400,9 +400,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/pipeline/forward/forward-stage.ts b/cocos/core/pipeline/forward/forward-stage.ts index 5c17ef20ec..1a4951e783 100644 --- a/cocos/core/pipeline/forward/forward-stage.ts +++ b/cocos/core/pipeline/forward/forward-stage.ts @@ -196,7 +196,7 @@ export class ForwardStage extends RenderStage { this._pipeline.lightBatchQueue.recordCommandBuffer(cmdBuff); if (camera.visibility & Layers.BitMask.DEFAULT) { - cmdBuff.execute(planarShadow.cmdBuffs.array, planarShadow.cmdBuffCount); + planarShadow.recordCommandBuffer(cmdBuff); } this._renderQueues[1].recordCommandBuffer(this._device!, this._framebuffer.renderPass!, cmdBuff); cmdBuff.endRenderPass(); 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'; diff --git a/cocos/core/pipeline/instanced-buffer.ts b/cocos/core/pipeline/instanced-buffer.ts index 9530e6a37d..f864fed2d9 100644 --- a/cocos/core/pipeline/instanced-buffer.ts +++ b/cocos/core/pipeline/instanced-buffer.ts @@ -16,6 +16,7 @@ export interface IInstancedItem { vb: GFXBuffer; data: Uint8Array; ia: GFXInputAssembler; + stride: number; } const INITIAL_CAPACITY = 32; @@ -40,21 +41,26 @@ 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}`); + 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; } @@ -86,7 +92,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 () { 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(); } diff --git a/cocos/core/platform/event-manager/event-listener.ts b/cocos/core/platform/event-manager/event-listener.ts index ef02b68e82..9a2e44a2c3 100644 --- a/cocos/core/platform/event-manager/event-listener.ts +++ b/cocos/core/platform/event-manager/event-listener.ts @@ -187,8 +187,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/renderer/core/pass-instance.ts b/cocos/core/renderer/core/pass-instance.ts index 5168232b93..a261caaec5 100644 --- a/cocos/core/renderer/core/pass-instance.ts +++ b/cocos/core/renderer/core/pass-instance.ts @@ -43,7 +43,7 @@ export class PassInstance extends Pass { private _dontNotify = false; constructor (parent: Pass, owner: MaterialInstance) { - super(parent.device); + super(parent.root); this._parent = parent; this._owner = owner; this._doInit(this._parent, true); // defines may change now diff --git a/cocos/core/renderer/core/pass.ts b/cocos/core/renderer/core/pass.ts index 32e2ed9a40..651a44d328 100644 --- a/cocos/core/renderer/core/pass.ts +++ b/cocos/core/renderer/core/pass.ts @@ -35,7 +35,7 @@ import { GFXBindingLayout, IGFXBinding, IGFXBindingLayoutInfo } from '../../gfx/ import { GFXBuffer, IGFXBufferInfo } from '../../gfx/buffer'; import { GFXBindingType, GFXBufferUsageBit, GFXDynamicState, GFXGetTypeSize, GFXMemoryUsageBit, GFXPrimitiveMode, GFXType } from '../../gfx/define'; -import { GFXFeature } from '../../gfx/device'; +import { GFXFeature, GFXDevice } from '../../gfx/device'; import { GFXBlendState, GFXBlendTarget, GFXDepthStencilState, GFXRasterizerState } from '../../gfx/pipeline-state'; import { GFXSampler } from '../../gfx/sampler'; @@ -187,6 +187,7 @@ export class Pass { protected _hash = 0; // external references protected _root: Root; + protected _device: GFXDevice; protected _shader: GFXShader | null = null; // for dynamic batching protected _batchedBuffer: BatchedBuffer | null = null; @@ -194,6 +195,7 @@ export class Pass { public constructor (root: Root) { this._root = root; + this._device = root.device; } /** @@ -438,7 +440,7 @@ export class Pass { const texture = builtinResMgr.get(texName); const textureView = texture && texture.getGFXTextureView()!; const samplerHash = info && (info.samplerHash !== undefined) ? info.samplerHash : texture.getSamplerHash(); - const sampler = samplerLib.getSampler(this._root.device, samplerHash); + const sampler = samplerLib.getSampler(this._device, samplerHash); this._textureViews[binding] = textureView; this._samplers[binding] = sampler; for (let i = 0; i < this._resources.length; i++) { @@ -491,7 +493,7 @@ export class Pass { const pipeline = this._root.pipeline; if (!pipeline) { return null; } this._dynamicBatchingSync(); - const res = programLib.getGFXShader(this._root.device, this._programName, this._defines, pipeline); + const res = programLib.getGFXShader(this._device, this._programName, this._defines, pipeline); if (!res.shader) { console.warn(`create shader ${this._programName} failed`); return false; } this._shader = res.shader; this._bindings = res.bindings; return true; @@ -513,7 +515,7 @@ export class Pass { const shader = res && res.shader || this._shader!; _blInfo.bindings = res && res.bindings || this._bindings; // bind resources - const bindingLayout = this._root.device.createBindingLayout(_blInfo); + const bindingLayout = this._device.createBindingLayout(_blInfo); for (const b in this._buffers) { bindingLayout.bindBuffer(parseInt(b), this._buffers[b]); } @@ -562,7 +564,7 @@ export class Pass { this._shaderInfo = programLib.getTemplate(info.program); this._properties = info.properties || this._properties; // pipeline state - const device = this._root.device; + const device = this._device; Pass.fillinPipelineInfo(this, info); if (info.stateOverrides) { Pass.fillinPipelineInfo(this, info.stateOverrides); } this._hash = Pass.getPassHash(this); @@ -593,7 +595,7 @@ export class Pass { protected _dynamicBatchingSync () { if (this._defines.USE_INSTANCING) { - if (!this._root.device.hasFeature(GFXFeature.INSTANCED_ARRAYS)) { + if (!this._device.hasFeature(GFXFeature.INSTANCED_ARRAYS)) { this._defines.USE_INSTANCING = false; } else if (!this._instancedBuffer) { this._instancedBuffer = new InstancedBuffer(this); @@ -628,7 +630,7 @@ export class Pass { const patch = patches[i]; this._defines[patch.name] = patch.value; } - const res = programLib.getGFXShader(this._root.device, this._programName, this._defines, pipeline); + const res = programLib.getGFXShader(this._device, this._programName, this._defines, pipeline); for (let i = 0; i < patches.length; i++) { const patch = patches[i]; delete this._defines[patch.name]; @@ -647,7 +649,8 @@ export class Pass { get customizations () { return this._customizations; } get phase () { return this._phase; } // infos - get device () { return this._root.device; } + get root () { return this._root; } + get device () { return this._device; } get shaderInfo () { return this._shaderInfo; } get program () { return this._programName; } get properties () { return this._properties; } diff --git a/cocos/core/renderer/models/baked-skinning-model.ts b/cocos/core/renderer/models/baked-skinning-model.ts index 971aa3794e..b9987d587d 100644 --- a/cocos/core/renderer/models/baked-skinning-model.ts +++ b/cocos/core/renderer/models/baked-skinning-model.ts @@ -44,6 +44,7 @@ import { IAnimInfo, IJointTextureHandle, jointTextureSamplerHash } from './skele import { MorphModel } from './morph-model'; import { IPSOCreateInfo } from '../scene/submodel'; import { legacyCC } from '../../global-exports'; +import { IGFXAttribute } from '../../gfx'; interface IJointsInfo { buffer: GFXBuffer | null; @@ -131,9 +132,8 @@ 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]; - } - if (info.dirty) { + view[0] = info.data[0]; + } else if (info.dirty) { info.buffer.update(info.data); info.dirty = false; } @@ -167,20 +167,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; @@ -220,8 +212,20 @@ export class BakedSkinningModel extends MorphModel { } } - protected updateInstancedAttributeList (psoCreateInfo: IPSOCreateInfo, pass: Pass) { - // super.updateInstancedAttributeList(psoCreateInfo, pass); - // this._instAnimInfoIdx = this.getInstancedAttributeIndex(INST_JOINT_ANIM_INFO); + protected updateInstancedAttributeList (attributes: IGFXAttribute[], pass: Pass) { + super.updateInstancedAttributeList(attributes, 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; + view[0] = animInfo.data[0]; + view[1] = jointTextureInfo[1]; + view[2] = jointTextureInfo[2]; + } } } diff --git a/cocos/core/renderer/models/morph-model.ts b/cocos/core/renderer/models/morph-model.ts index fd6ece9ce1..f9ffc3a23b 100644 --- a/cocos/core/renderer/models/morph-model.ts +++ b/cocos/core/renderer/models/morph-model.ts @@ -45,17 +45,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 +} diff --git a/cocos/core/renderer/models/skeletal-animation-utils.ts b/cocos/core/renderer/models/skeletal-animation-utils.ts index e5a7f2f5da..f089e74a15 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 @@ -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 { @@ -207,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) : @@ -221,23 +231,19 @@ 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]; - 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); + 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, 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 (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); @@ -263,47 +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)); } - 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]]; - if (!nodeData) { // don't skip null `boneSpaceBounds` here, or it becomes mesh-specific - 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; + 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 = skeleton.inverseBindposes[bindposeIdx]; + transformValid = false; } - const matrix = nodeData.worldMatrix.values as Mat4[]; - const m = matrix[frame]; - const boneSpaceBound = boneSpaceBounds[i]; + const boneSpaceBound = boneSpaceBounds[j]; if (boneSpaceBound) { - aabb.transform(ab_1, boneSpaceBound, m); + 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) { - const bindpose = bindposes[i]; - Mat4.multiply(m4_1, m, bindpose); - uploadJointData(textureBuffer, offset, m4_1, 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); @@ -318,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); + } } } @@ -359,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/models/skinning-model.ts b/cocos/core/renderer/models/skinning-model.ts index 3978e014af..4492a13967 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; @@ -111,7 +112,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 +153,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 +193,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 +229,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; } @@ -269,8 +270,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/camera.ts b/cocos/core/renderer/scene/camera.ts index 9ff2567730..3d82367b7b 100644 --- a/cocos/core/renderer/scene/camera.ts +++ b/cocos/core/renderer/scene/camera.ts @@ -605,6 +605,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; diff --git a/cocos/core/renderer/scene/model.ts b/cocos/core/renderer/scene/model.ts index 7f8da7833b..730cd6711c 100644 --- a/cocos/core/renderer/scene/model.ts +++ b/cocos/core/renderer/scene/model.ts @@ -4,21 +4,22 @@ import { Material } from '../../assets/material'; import { RenderingSubMesh } from '../../assets/mesh'; import { aabb } from '../../geometry'; import { GFXBuffer } from '../../gfx/buffer'; -import { GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit, GFXFilter, GFXAddress } from '../../gfx/define'; -import { GFXDevice } from '../../gfx/device'; +import { getTypedArrayConstructor, GFXBufferUsageBit, GFXFormat, GFXFormatInfos, GFXMemoryUsageBit, GFXFilter, GFXAddress } from '../../gfx/define'; +import { GFXDevice, GFXFeature } from '../../gfx/device'; import { GFXPipelineState } from '../../gfx/pipeline-state'; -import { Mat4, Vec3, Vec4} from '../../math'; +import { Mat4, Vec3, Vec4 } from '../../math'; import { Pool } from '../../memop'; -import { UBOForwardLight, UBOLocal, UniformLightingMapSampler } from '../../pipeline/define'; +import { UBOForwardLight, UBOLocal, UniformLightingMapSampler, INST_MAT_WORLD } from '../../pipeline/define'; import { Node } from '../../scene-graph'; import { Layers } from '../../scene-graph/layers'; import { RenderScene } from './render-scene'; import { Texture2D } from '../..'; -import { genSamplerHash, samplerLib} from '../../renderer/core/sampler-lib'; -import { GFXSampler } from '../../gfx'; +import { genSamplerHash, samplerLib } from '../../renderer/core/sampler-lib'; +import { GFXSampler, IGFXAttribute } from '../../gfx'; import { SubModel, IPSOCreateInfo } from './submodel'; import { Pass } from '../core/pass'; import { legacyCC } from '../../global-exports'; +import { programLib } from '../core/program-lib'; const m4_1 = new Mat4(); @@ -85,6 +86,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!; @@ -217,11 +222,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); } /** @@ -294,7 +300,7 @@ export class Model { if (this._localBuffer) { bindingLayout.bindBuffer(UBOLocal.BLOCK.binding, this._localBuffer); } } - this.updateInstancedAttributeList(psoCreateInfos[0], subModel.passes[0]); + this.updateInstancedAttributeList(subModel.subMeshData.attributes, subModel.passes[0]); } protected getMacroPatches (subModelIndex: number) : any { @@ -302,32 +308,29 @@ export class Model { } // for now no submodel level instancing attributes - protected updateInstancedAttributeList (psoCreateInfo: IPSOCreateInfo, pass: Pass) { - // if (!pass || !psoCreateInfo) { - // return; - // } - // const attributes = pso.inputState.attributes; - // let size = 0; - // for (let j = 0; j < attributes.length; j++) { - // const attribute = attributes[j]; - // if (!attribute.isInstanced) { continue; } - // size += GFXFormatInfos[attribute.format].size; - // } - // const attrs = this.instancedAttributes; - // attrs.buffer = new Uint8Array(size); attrs.list.length = 0; - // let offset = 0; const buffer = attrs.buffer.buffer; - // for (let j = 0; j < attributes.length; j++) { - // const attribute = attributes[j]; - // if (!attribute.isInstanced) { continue; } - // const format = attribute.format; - // const info = GFXFormatInfos[format]; - // const view = new (getTypedArrayConstructor(info))(buffer, offset, info.count); - // const isNormalized = attribute.isNormalized; - // offset += info.size; attrs.list.push({ name: attribute.name, format, isNormalized, view }); - // } - // if (pass.instancedBuffer) { pass.instancedBuffer.destroy(); } // instancing IA changed - // this._instMatWorldIdx = this.getInstancedAttributeIndex(INST_MAT_WORLD); - // this._transformUpdated = true; + protected updateInstancedAttributeList (attributes: IGFXAttribute[], pass: Pass) { + if (!pass.device.hasFeature(GFXFeature.INSTANCED_ARRAYS)) { return; } + let size = 0; + for (let j = 0; j < attributes.length; j++) { + const attribute = attributes[j]; + if (!attribute.isInstanced) { continue; } + size += GFXFormatInfos[attribute.format].size; + } + const attrs = this.instancedAttributes; + attrs.buffer = new Uint8Array(size); attrs.list.length = 0; + let offset = 0; const buffer = attrs.buffer.buffer; + for (let j = 0; j < attributes.length; j++) { + const attribute = attributes[j]; + if (!attribute.isInstanced) { continue; } + const format = attribute.format; + const info = GFXFormatInfos[format]; + const view = new (getTypedArrayConstructor(info))(buffer, offset, info.count); + const isNormalized = attribute.isNormalized; + offset += info.size; attrs.list.push({ name: attribute.name, format, isNormalized, view }); + } + if (pass.instancedBuffer) { pass.instancedBuffer.destroy(); } // instancing IA changed + this._instMatWorldIdx = this.getInstancedAttributeIndex(INST_MAT_WORLD); + this._transformUpdated = true; } protected getInstancedAttributeIndex (name: string) { @@ -350,7 +353,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 496f1d3aac..6bb004b5b7 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,44 +153,68 @@ 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; + 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++) { + 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 && 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); - 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); + // 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.end(); - return { psos, cmdBuffer }; + return { model, psos, instancedBuffer: material.passes[0].instancedBuffer }; } public destroyShadowData (model: Model) { - //todo: minggo - // const data = this._record.get(model); - // if (!data) { return; } - // data.cmdBuffer.destroy(); - // for (let i = 0; i < data.psos.length; i++) { - // const pso = data.psos[i]; - // model.removeImplantPSO(pso); - // this._material.passes[0].destroyPipelineState(pso); - // } - // this._record.delete(model); + const data = this._record.get(model); + if (!data) { return; } + 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); + // material.passes[0].destroyPipelineState(pso); + } + this._record.delete(model); } public onGlobalPipelineStateChanged () { diff --git a/cocos/core/renderer/scene/render-scene.ts b/cocos/core/renderer/scene/render-scene.ts index 4de93042a1..84e538d100 100644 --- a/cocos/core/renderer/scene/render-scene.ts +++ b/cocos/core/renderer/scene/render-scene.ts @@ -427,9 +427,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) { @@ -464,7 +464,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 }; diff --git a/cocos/core/renderer/scene/skybox.ts b/cocos/core/renderer/scene/skybox.ts index 6aec8ca651..a8753b1c6a 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; diff --git a/cocos/core/renderer/ui/ui-material.ts b/cocos/core/renderer/ui/ui-material.ts index 9a6b9c7e88..22036894e9 100644 --- a/cocos/core/renderer/ui/ui-material.ts +++ b/cocos/core/renderer/ui/ui-material.ts @@ -64,7 +64,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._psoCreateInfo = new Pool(() => { diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 1109639185..d22cdf60af 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -487,7 +487,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 0240bd6f4b..89242d7126 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 c35f012328..36fab4552f 100644 --- a/cocos/core/scene-graph/base-node.ts +++ b/cocos/core/scene-graph/base-node.ts @@ -40,10 +40,9 @@ import { baseNodePolyfill } from './base-node-dev'; import { NodeEventProcessor } from './node-event-processor'; import { DEV, DEBUG, EDITOR } from 'internal:constants'; import { legacyCC } from '../global-exports'; +import { Node } from './node'; +import { Scene } from './scene'; -/** - * - */ type Constructor = new (...args: any[]) => T; // @ts-ignore @@ -78,21 +77,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. @@ -103,17 +99,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) { @@ -129,16 +123,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) { @@ -150,15 +137,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 () { @@ -168,16 +149,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 () { @@ -186,21 +158,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 () { @@ -222,18 +188,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; @@ -243,14 +207,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; } @@ -349,42 +318,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; @@ -416,10 +370,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'; @@ -427,15 +377,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); * ``` */ @@ -448,10 +398,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; @@ -460,23 +406,20 @@ 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) { + 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; @@ -486,14 +429,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) { @@ -514,14 +457,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) { @@ -539,7 +478,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 @@ -564,13 +503,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,58 +528,48 @@ export class BaseNode extends CCObject implements ISchedulable { } return lastNode; } - - public addChild (child: this): void { - + /** + * @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 | Node): void { if (DEV && !(child instanceof legacyCC._BaseNode)) { return errorID(1634, legacyCC.js.getClassName(child)); } legacyCC.assertID(child, 1606); - legacyCC.assertID(child._parent === null, 1605); + legacyCC.assertID((child as this)._parent === null, 1605); // invokes the parent setter - child.setParent(this); - + (child as this).setParent(this); } /** - * @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); * ``` */ - public insertChild (child: this, siblingIndex: number) { + public insertChild (child: this | Node, siblingIndex: number) { child.parent = this; child.setSiblingIndex(siblingIndex); } /** - * @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) { @@ -674,11 +603,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) { @@ -688,7 +617,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; @@ -711,12 +640,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 @@ -774,16 +703,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) { @@ -792,33 +716,20 @@ 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) { + public removeChild (child: this | Node) { + if (this._children.indexOf(child as this) > -1) { // invoke the parent setter child.parent = null; } } /** - * @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 @@ -836,13 +747,8 @@ 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 { + public isChildOf (parent: this | Scene | null): boolean { let child: BaseNode | null = this; do { if (child === parent) { @@ -858,29 +764,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"); * ``` */ @@ -895,22 +803,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[]; @@ -924,18 +826,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"); @@ -952,18 +856,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"); @@ -984,9 +890,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; @@ -994,6 +901,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"); @@ -1086,11 +994,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; @@ -1102,6 +1010,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 * ``` @@ -1132,7 +1041,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; @@ -1141,7 +1087,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); @@ -1155,22 +1116,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 @@ -1194,15 +1202,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; @@ -1341,6 +1345,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) { @@ -1356,15 +1370,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) { legacyCC.game.removePersistRootNode(this); diff --git a/cocos/core/scene-graph/component-scheduler.ts b/cocos/core/scene-graph/component-scheduler.ts index ea7e88f356..0e59418dfb 100644 --- a/cocos/core/scene-graph/component-scheduler.ts +++ b/cocos/core/scene-graph/component-scheduler.ts @@ -216,7 +216,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) { @@ -333,11 +333,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[] = []; @@ -347,6 +362,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); @@ -393,6 +412,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) { @@ -413,6 +438,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) { @@ -422,6 +452,10 @@ export class ComponentScheduler { } } + /** + * @en Process start phase for registered components + * @zh 为当前注册的组件执行 start 阶段任务 + */ public startPhase () { // Start of this frame this._updating = true; @@ -447,11 +481,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 df7c9f2c3e..0a177ada0b 100644 --- a/cocos/core/scene-graph/find.ts +++ b/cocos/core/scene-graph/find.ts @@ -33,10 +33,14 @@ import { DEV } from 'internal:constants'; import { legacyCC } from '../global-exports'; /** - * 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 3172716379..3d05044de4 100644 --- a/cocos/core/scene-graph/layers.ts +++ b/cocos/core/scene-graph/layers.ts @@ -46,12 +46,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)); /** @@ -59,8 +70,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; @@ -75,8 +86,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); @@ -84,10 +95,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; @@ -103,9 +115,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 0daccc601a..514d1c012a 100644 --- a/cocos/core/scene-graph/node-activator.ts +++ b/cocos/core/scene-graph/node-activator.ts @@ -163,7 +163,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; @@ -173,11 +173,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(); @@ -206,6 +216,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; @@ -242,6 +260,11 @@ export default class NodeActivator { } } + /** + * @en Destroy a component + * @zh 销毁一个组件 + * @param comp Target component + */ public destroyComp (comp) { // ensure onDisable called legacyCC.director._compScheduler.disableComp(comp); diff --git a/cocos/core/scene-graph/node-enum.ts b/cocos/core/scene-graph/node-enum.ts index 2287dbc4f9..9bb3f0b15b 100644 --- a/cocos/core/scene-graph/node-enum.ts +++ b/cocos/core/scene-graph/node-enum.ts @@ -23,17 +23,25 @@ THE SOFTWARE. */ +import { legacyCC } from '../global-exports'; + /** * @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 @@ -67,3 +75,5 @@ export enum TransformBit { TRS = TransformBit.POSITION | TransformBit.ROTATION | TransformBit.SCALE, TRS_MASK = ~TransformBit.TRS, } + +legacyCC.internal.TransformBit = TransformBit; diff --git a/cocos/core/scene-graph/node-event-processor.ts b/cocos/core/scene-graph/node-event-processor.ts index a8d623b93a..1e011cf270 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 23198e50bb..14af4e820e 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'; @@ -55,36 +54,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 legacyCC.Scene)); @@ -118,8 +131,8 @@ export class Node extends BaseNode { protected _eulerDirty = false; /** - * @zh - * 本地坐标 + * @en Position in local coordinate system + * @zh 本地坐标系下的坐标 */ // @constget public get position (): Readonly { @@ -130,8 +143,8 @@ export class Node extends BaseNode { } /** - * @zh - * 世界坐标 + * @en Position in world coordinate system + * @zh 世界坐标系下的坐标 */ // @constget public get worldPosition (): Readonly { @@ -143,8 +156,8 @@ export class Node extends BaseNode { } /** - * @zh - * 本地旋转 + * @en Rotation in local coordinate system, represented by a quaternion + * @zh 本地坐标系下的旋转,用四元数表示 */ // @constget public get rotation (): Readonly { @@ -155,8 +168,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) { @@ -171,8 +184,8 @@ export class Node extends BaseNode { } /** - * @zh - * 世界旋转 + * @en Rotation in world coordinate system, represented by a quaternion + * @zh 世界坐标系下的旋转,用四元数表示 */ // @constget public get worldRotation (): Readonly { @@ -184,8 +197,8 @@ export class Node extends BaseNode { } /** - * @zh - * 本地缩放 + * @en Scale in local coordinate system + * @zh 本地坐标系下的缩放 */ // @constget public get scale (): Readonly { @@ -196,8 +209,8 @@ export class Node extends BaseNode { } /** - * @zh - * 世界缩放 + * @en Scale in world coordinate system + * @zh 世界坐标系下的缩放 */ // @constget public get worldScale (): Readonly { @@ -209,8 +222,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); @@ -222,8 +235,8 @@ export class Node extends BaseNode { } /** - * @zh - * 世界变换矩阵 + * @en World transformation matrix + * @zh 世界坐标系变换矩阵 */ // @constget public get worldMatrix (): Readonly { @@ -232,8 +245,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); @@ -246,8 +259,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) { @@ -258,8 +271,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; @@ -305,10 +318,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(); } @@ -358,10 +371,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; @@ -392,10 +405,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; @@ -419,10 +432,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); @@ -437,11 +450,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; } @@ -450,15 +462,14 @@ 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); } } /** - * @en - * update the world transform information if outdated - * @zh - * 更新节点的世界变换信息 + * @en Update the world transform information if outdated + * @zh 更新节点的世界变换信息 */ public updateWorldTransform () { if (!this._dirtyFlags) { return; } @@ -502,7 +513,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); @@ -518,19 +530,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; @@ -548,9 +559,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) { @@ -561,19 +573,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; @@ -592,11 +604,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); @@ -610,9 +622,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) { @@ -623,18 +636,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; @@ -652,9 +665,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) { @@ -664,6 +678,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; @@ -679,19 +699,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; @@ -722,9 +741,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(); @@ -736,19 +756,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; @@ -773,11 +793,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); @@ -796,9 +816,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(); @@ -810,18 +831,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; @@ -854,9 +875,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(); @@ -868,9 +890,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(); @@ -879,9 +902,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(); @@ -892,9 +916,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(); @@ -903,8 +928,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); } @@ -945,12 +973,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 268c9ea971..8b8737a0ec 100644 --- a/cocos/core/scene-graph/private-node.ts +++ b/cocos/core/scene-graph/private-node.ts @@ -49,16 +49,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 { @@ -100,9 +97,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 26bf793c4c..5a15b1a29d 100644 --- a/cocos/core/scene-graph/scene-globals.ts +++ b/cocos/core/scene-graph/scene-globals.ts @@ -44,6 +44,7 @@ const _v3 = new Vec3(); const _qt = new Quat(); /** + * @en Environment lighting information in the Scene * @zh 场景的环境光照相关信息 */ @ccclass('cc.AmbientInfo') @@ -58,6 +59,7 @@ export class AmbientInfo { protected _resource: Ambient | null = null; /** + * @en Sky color * @zh 天空颜色 */ @property({ type: Color }) @@ -70,6 +72,7 @@ export class AmbientInfo { } /** + * @en Sky illuminance * @zh 天空亮度 */ @float @@ -82,6 +85,7 @@ export class AmbientInfo { } /** + * @en Ground color * @zh 地面颜色 */ @property({ type: Color }) @@ -104,6 +108,7 @@ export class AmbientInfo { legacyCC.AmbientInfo = AmbientInfo; /** + * @en Skybox related information * @zh 天空盒相关信息 */ @ccclass('cc.SkyboxInfo') @@ -120,6 +125,7 @@ export class SkyboxInfo { protected _resource: Skybox | null = null; /** + * @en Whether activate skybox in the scene * @zh 是否启用天空盒? */ @property({ type: CCBoolean }) @@ -132,6 +138,7 @@ export class SkyboxInfo { } /** + * @en Whether use environment lighting * @zh 是否启用环境光照? */ @property({ type: CCBoolean }) @@ -144,6 +151,7 @@ export class SkyboxInfo { } /** + * @en The texture cube used for the skybox * @zh 使用的立方体贴图 */ @property({ type: TextureCube }) @@ -156,6 +164,7 @@ export class SkyboxInfo { } /** + * @en Whether enable RGBE data support in skybox shader * @zh 是否需要开启 shader 内的 RGBE 数据支持? */ @property({ type: CCBoolean }) @@ -384,6 +393,7 @@ export class FogInfo { } /** + * @en Scene level planar shadow related information * @zh 平面阴影相关信息 */ @ccclass('cc.PlanarShadowInfo') @@ -400,6 +410,7 @@ export class PlanarShadowInfo { protected _resource: PlanarShadows | null = null; /** + * @en Whether activate planar shadow * @zh 是否启用平面阴影? */ @property({ type: CCBoolean }) @@ -412,6 +423,7 @@ export class PlanarShadowInfo { } /** + * @en The normal of the plane which receives shadow * @zh 阴影接收平面的法线 */ @property({ type: Vec3 }) @@ -424,6 +436,7 @@ export class PlanarShadowInfo { } /** + * @en The distance from coordinate origin to the receiving plane. * @zh 阴影接收平面与原点的距离 */ @property({ type: CCFloat }) @@ -436,6 +449,7 @@ export class PlanarShadowInfo { } /** + * @en Shadow color * @zh 阴影颜色 */ @property({ type: Color }) @@ -448,8 +462,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); @@ -469,24 +484,36 @@ export class PlanarShadowInfo { legacyCC.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(); @property public fog = new FogInfo(); - + + /** + * @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 319db78a2e..a0aaf5d94b 100644 --- a/cocos/core/scene-graph/scene.ts +++ b/cocos/core/scene-graph/scene.ts @@ -38,20 +38,27 @@ import { legacyCC } from '../global-exports'; /** * @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; } @@ -62,16 +69,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; @@ -91,6 +94,10 @@ export class Scene extends BaseNode { this._inited = legacyCC.game ? !legacyCC.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(); legacyCC.director.root.destroyScene(this._renderScene); @@ -98,6 +105,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; @@ -119,23 +130,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/array.ts b/cocos/core/utils/array.ts index ff7f6d32c3..383580530c 100644 --- a/cocos/core/utils/array.ts +++ b/cocos/core/utils/array.ts @@ -115,24 +115,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. */ diff --git a/cocos/core/utils/misc.ts b/cocos/core/utils/misc.ts index 515ee015b5..15d5c6cd05 100644 --- a/cocos/core/utils/misc.ts +++ b/cocos/core/utils/misc.ts @@ -155,7 +155,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/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'; 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.'); diff --git a/cocos/particle/particle-system-component.ts b/cocos/particle/particle-system-component.ts index aa25bfb01d..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 @@ -297,14 +298,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, @@ -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; + } - // shpae 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,37 +652,37 @@ 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: 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) { // } @@ -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,18 +785,18 @@ 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; if (this._isPlaying) { this._time += scaledDeltaTime; - // excute emission + // Execute emission this._emit(scaledDeltaTime); // simulation, update particles. @@ -665,13 +808,13 @@ 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(); } } } - protected _onVisiblityChange (val) { + protected _onVisibilityChange (val) { // @ts-ignore if (this.processor._model) { // @ts-ignore @@ -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-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(); 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 4590c9350a..9db610724c 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!); diff --git a/cocos/physics/ammo/ammo-rigid-body.ts b/cocos/physics/ammo/ammo-rigid-body.ts index 9496d6c517..305d4bf006 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.isAwake) this.impl.activate(); } setLinearFactor (value: IVec3Like) { this.impl.setLinearFactor(cocos2AmmoVec3(this._btVec3_0, value)); + if (!this.isAwake) this.impl.activate(); } setAngularFactor (value: IVec3Like) { this.impl.setAngularFactor(cocos2AmmoVec3(this._btVec3_0, value)); + if (!this.isAwake) 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.isAwake) this.impl.activate(); } get isEnabled () { return this._isEnabled; } @@ -183,6 +183,7 @@ export class AmmoRigidBody implements IRigidBody { } setLinearVelocity (value: Vec3): void { + if (!this.isAwake) this.impl.activate(); cocos2AmmoVec3(this.impl.getLinearVelocity(), value); } @@ -191,12 +192,15 @@ export class AmmoRigidBody implements IRigidBody { } setAngularVelocity (value: Vec3): void { + if (!this.isAwake) this.impl.activate(); cocos2AmmoVec3(this.impl.getAngularVelocity(), value); } /** dynamic */ applyLocalForce (force: Vec3, rel_pos?: Vec3): void { + this._sharedBody.syncSceneToPhysics(); + 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; @@ -207,11 +211,15 @@ export class AmmoRigidBody implements IRigidBody { } applyLocalTorque (torque: Vec3): void { + this._sharedBody.syncSceneToPhysics(); + 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.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; @@ -222,6 +230,8 @@ export class AmmoRigidBody implements IRigidBody { } applyForce (force: Vec3, rel_pos?: Vec3): void { + this._sharedBody.syncSceneToPhysics(); + if (!this.isAwake) 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.isAwake) this.impl.activate(); this.impl.applyTorque(cocos2AmmoVec3(this._btVec3_0, torque)); } applyImpulse (impulse: Vec3, rel_pos?: Vec3): void { + this._sharedBody.syncSceneToPhysics(); + 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/ammo/ammo-shared-body.ts b/cocos/physics/ammo/ammo-shared-body.ts index 5eb4aaf6a9..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++) { @@ -244,10 +244,10 @@ export class AmmoSharedBody { } /** - * TODO: use motionstate + * 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..c55ea78522 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 { @@ -269,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); @@ -337,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); diff --git a/cocos/physics/cannon/cannon-rigid-body.ts b/cocos/physics/cannon/cannon-rigid-body.ts index b64f568fbf..d875e3650b 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 */ @@ -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.isAwake()) 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.isAwake()) 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.isAwake()) 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.isAwake()) this.impl.wakeUp(); } setLinearFactor (value: IVec3Like) { - - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } - Vec3.copy(this.impl.linearFactor, value); + if (!this.impl.isAwake()) this.impl.wakeUp(); } setAngularFactor (value: IVec3Like) { - - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } - Vec3.copy(this.impl.angularFactor, value); + if (!this.impl.isAwake()) 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.isAwake()) 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.isAwake()) 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.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) { - if (worldPoint == null) { - worldPoint = Vec3.ZERO; - } - - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } - + this._sharedBody.syncSceneToPhysics(); + 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 { - if (localPoint == null) { - localPoint = Vec3.ZERO; - } - - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } - + this._sharedBody.syncSceneToPhysics(); + 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 { - if (localPoint == null) { - localPoint = Vec3.ZERO; - } - - if (this.impl.isSleeping()) { - this.impl.wakeUp(); - } - + this._sharedBody.syncSceneToPhysics(); + 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 { - 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.isAwake()) 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.isAwake()) 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 07304f4f79..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,11 +18,11 @@ const CollisionEventObject = { type: 'onCollisionEnter' as CollisionEventType, selfCollider: null as ColliderComponent | null, otherCollider: null as ColliderComponent | null, - contacts: [] as any, + contacts: [] as IContactEquation[], }; /** - * sharedbody, node : sharedbody = 1 : 1 + * node : shared-body = 1 : 1 * static */ export class CannonSharedBody { @@ -130,10 +130,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,7 +164,6 @@ export class CannonSharedBody { CollisionEventObject.type = event.event; const self = getWrap(event.selfShape); const other = getWrap(event.otherShape); - if (self) { CollisionEventObject.selfCollider = self.collider; CollisionEventObject.otherCollider = other ? other.collider : null; 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/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/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/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..edc18eae3e 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 /// @@ -146,17 +135,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 * 获取封装对象,通过此对象可以访问到底层实例。 */ @@ -187,58 +176,43 @@ export class ColliderComponent extends Component implements IEventTarget { constructor () { super() } - /// EVENT INTERFACE /// - /** + * @en + * Registers callbacks associated with triggered or collision events. * @zh - * 注册触发事件或碰撞事件相关的回调。 - * @param type - 触发或碰撞事件的类型,可为 'onTriggerEnter','onTriggerStay','onTriggerExit' 或 'onCollisionEnter','onCollisionStay','onCollisionExit'; - * @param callback - 注册的回调函数 - * @param target - 可选参数,执行回调函数的目标 - * @param useCapture - 可选参数,当设置为 true,监听器将在捕获阶段触发,否则将在冒泡阶段触发。默认为 false。 + * 注册触发或碰撞事件相关的回调。 + * @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: TriggerCallback | CollisionCallback, target?: Object, useCapture?: any): any { + 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 - 触发或碰撞事件的类型,可为 'onTriggerEnter','onTriggerStay','onTriggerExit' 或 'onCollisionEnter','onCollisionStay','onCollisionExit'; - * @param callback - 注册的回调函数 - * @param target - 可选参数,执行回调函数的目标 - * @param useCapture - 可选参数,当设置为 true,监听器将在捕获阶段触发,否则将在冒泡阶段触发。默认为 false。 + * 取消已经注册的触发或碰撞事件相关的回调。 + * @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: TriggerCallback | CollisionCallback, target?: Object, useCapture?: any) { + 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 - 触发或碰撞事件的类型,可为 'onTriggerEnter','onTriggerStay','onTriggerExit' 或 'onCollisionEnter','onCollisionStay','onCollisionExit'; - * @param callback - 注册的回调函数 - * @param target - 可选参数,执行回调函数的目标 - * @param useCapture - 可选参数,当设置为 true,监听器将在捕获阶段触发,否则将在冒泡阶段触发。默认为 false。 + * 注册触发或碰撞事件相关的回调,执行一次后会自动取消注册。 + * @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: 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 { + public once (type: TriggerEventType | CollisionEventType, callback: Function, target?: Object): any { + super.once(type, callback, target); } /// GROUP MASK /// @@ -363,6 +337,9 @@ export class ColliderComponent extends Component implements IEventTarget { protected onDestroy () { if (!EDITOR) { + if (this._material) { + this._material.off('physics_material_update', this._updateMaterial, this); + } this._shape.onDestroy!(); } } @@ -374,5 +351,3 @@ export class ColliderComponent extends Component implements IEventTarget { } } - -applyMixins(ColliderComponent, [CallbacksInvoker, EventTarget]); 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..1a8bb5024d 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 * 获取封装对象,通过此对象可以访问到底层实例。 */ @@ -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/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/physics-interface.ts b/cocos/physics/framework/physics-interface.ts index 208068d625..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. @@ -123,6 +124,7 @@ export interface ICollisionEvent { * 碰撞中的所有碰撞点的信息。 */ readonly contacts: IContactEquation[]; + } /** diff --git a/cocos/physics/framework/physics-system.ts b/cocos/physics/framework/physics-system.ts index 1ceda5dda7..e2e8b29345 100644 --- a/cocos/physics/framework/physics-system.ts +++ b/cocos/physics/framework/physics-system.ts @@ -215,7 +215,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(); @@ -224,6 +230,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); } 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..d8b0907a6c 100644 --- a/cocos/physics/spec/i-physics-world.ts +++ b/cocos/physics/spec/i-physics-world.ts @@ -20,8 +20,8 @@ export interface IPhysicsWorld { setGravity: (v: IVec3Like) => void; setAllowSleep: (v: boolean) => void; setDefaultMaterial: (v: PhysicMaterial) => void; - step (deltaTime: number, ...args: any): void; - raycast (worldRay: ray, options: IRaycastOptions, pool: RecyclePool, resultes: PhysicsRayResult[]): boolean + 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; syncSceneToPhysics (): void; diff --git a/cocos/terrain/terrain-asset.ts b/cocos/terrain/terrain-asset.ts index d6c24ab483..b79386361e 100644 --- a/cocos/terrain/terrain-asset.ts +++ b/cocos/terrain/terrain-asset.ts @@ -10,154 +10,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]; @@ -193,6 +201,10 @@ export class TerrainAsset extends Asset{ this.emit('load'); } + /** + * @en tile size + * @zh 栅格大小 + */ set tileSize (value: number) { this._tileSize = value; } @@ -201,6 +213,10 @@ export class TerrainAsset extends Asset{ return this._tileSize; } + /** + * @en block count + * @zh 块数量 + */ set blockCount (value: number[]) { this._blockCount = value; } @@ -209,6 +225,10 @@ export class TerrainAsset extends Asset{ return this._blockCount; } + /** + * @en light map size + * @zh 光照图大小 + */ set lightMapSize (value: number) { this._lightMapSize = value; } @@ -217,6 +237,10 @@ export class TerrainAsset extends Asset{ return this._lightMapSize; } + /** + * @en weight map size + * @zh 权重图大小 + */ set weightMapSize (value: number) { this._weightMapSize = value; } @@ -225,6 +249,10 @@ export class TerrainAsset extends Asset{ return this._weightMapSize; } + /** + * @en height buffer + * @zh 高度缓存 + */ set heights (value: Uint16Array) { this._heights = value; } @@ -233,6 +261,10 @@ export class TerrainAsset extends Asset{ return this._heights; } + /** + * @en weight buffer + * @zh 权重缓存 + */ set weights (value: Uint8Array) { this._weights = value; } @@ -241,6 +273,10 @@ export class TerrainAsset extends Asset{ return this._weights; } + /** + * @en layer buffer + * @zh 纹理索引缓存 + */ set layerBuffer (value: number[]) { this._layerBuffer = value; } @@ -249,6 +285,10 @@ export class TerrainAsset extends Asset{ return this._layerBuffer; } + /** + * @en layer info + * @zh 纹理信息 + */ set layerInfos (value: TerrainLayerInfo[]) { this._layerInfos = value; } @@ -257,11 +297,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]; } @@ -274,10 +324,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; } @@ -288,43 +338,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(); } } @@ -336,49 +386,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 1161642ee3..ddb02c3cee 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, property } from '../core/data/class-decorator'; +import { ccclass, disallowMultiple, executeInEditMode, help, 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'; @@ -38,21 +38,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; @@ -61,6 +83,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; @@ -69,6 +95,10 @@ export class TerrainInfo { return _tileCount; } + /** + * @en vertex count + * @zh 顶点数量 + */ public get vertexCount () { const _vertexCount = this.tileCount; _vertexCount[0] += 1; @@ -78,25 +108,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; @@ -105,7 +142,7 @@ export class TerrainRenderable extends RenderableComponent { public _currentMaterialLayers: number = 0; public destroy () { - this._invalidMaterial(); + // this._invalidMaterial(); if (this._model != null) { legacyCC.director.root.destroyModel(this._model); this._model = null; @@ -132,13 +169,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: legacyCC.EffectAsset.get('builtin-terrain'), - defines: block._getMaterialDefines(nlayers), + defines: block._getMaterialDefines(nLayers), }); if (this._brushMaterial !== null) { @@ -152,7 +189,7 @@ export class TerrainRenderable extends RenderableComponent { } this.setMaterial(this._currentMaterial, 0); - this._currentMaterialLayers = nlayers; + this._currentMaterialLayers = nLayers; this._model.enabled = true; } } @@ -183,12 +220,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 @@ -203,6 +248,10 @@ export class TerrainBlockLightmapInfo { public VScale: number = 0; } +/** + * @en Terrain block + * @zh 地形块 + */ export class TerrainBlock { private _terrain: Terrain; private _info: TerrainBlockInfo; @@ -269,7 +318,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 = (legacyCC.director.root as Root).createModel(Model); this._renderable._model.initialize(this._node); @@ -401,14 +450,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); @@ -418,14 +479,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; @@ -436,6 +509,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; @@ -444,10 +521,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; @@ -580,8 +665,12 @@ export class TerrainBlock { } } +/** + * @en Terrain + * @zh 地形组件 + */ @ccclass('cc.Terrain') -// @menu('Components/Terrain') +@help('i18n:cc.TerrainComponent') @executeInEditMode @disallowMultiple export class Terrain extends Component { @@ -597,7 +686,7 @@ export class Terrain extends Component { visible: true, animatable: false, }) - protected _layers: Array = []; + protected _layers: (TerrainLayer|null)[] = []; @property({ visible: false, @@ -653,6 +742,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; @@ -660,14 +753,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; @@ -676,30 +781,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, @@ -715,6 +848,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]; @@ -725,6 +862,10 @@ export class Terrain extends Component { return this._buildImp(); } + /** + * @en rebuild + * @zh 重建地形 + */ public rebuild (info: TerrainInfo) { // build block info const blockInfos: TerrainBlockInfo[] = []; @@ -777,6 +918,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) { @@ -798,6 +943,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) { @@ -835,13 +984,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); } } @@ -912,12 +1061,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) { @@ -929,14 +1082,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; @@ -946,6 +1111,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; @@ -958,14 +1127,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); @@ -973,6 +1154,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; @@ -1022,6 +1207,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; @@ -1033,6 +1222,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; @@ -1083,6 +1276,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; @@ -1092,6 +1289,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; @@ -1104,6 +1305,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; @@ -1150,56 +1355,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; @@ -1236,14 +1438,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; @@ -1281,7 +1510,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; @@ -1330,12 +1559,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; @@ -1343,7 +1572,7 @@ export class Terrain extends Component { } } else { - this._normals = new Array(vcount * 3); + this._normals = new Array(vertexCount * 3); this._buildNormals(); } @@ -1468,7 +1697,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; @@ -1476,10 +1705,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); @@ -1507,20 +1736,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; diff --git a/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts b/cocos/ui/assembler/graphics/webgl/graphics-assembler.ts index 7e4d9c617c..1646a1b59d 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/button-component.ts b/cocos/ui/components/button-component.ts index 5cdbba558e..d7e356304c 100644 --- a/cocos/ui/components/button-component.ts +++ b/cocos/ui/components/button-component.ts @@ -151,6 +151,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. @@ -457,39 +490,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; /** @@ -501,7 +501,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 3076e1677e..9f8e2d2320 100644 --- a/cocos/ui/components/editbox/edit-box-component.ts +++ b/cocos/ui/components/editbox/edit-box-component.ts @@ -88,6 +88,7 @@ export class EditBoxComponent extends Component { */ @property({ tooltip: '输入框的初始输入内容,如果为空则会显示占位符的文本', + displayOrder: 1, }) get string () { return this._string; @@ -104,52 +105,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. @@ -160,6 +275,7 @@ export class EditBoxComponent extends Component { @property({ type: SpriteFrame, tooltip: '输入框的背景图片', + displayOrder: 10, }) get backgroundImage () { return this._backgroundImage; @@ -176,135 +292,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(); + } } } @@ -317,6 +350,7 @@ export class EditBoxComponent extends Component { */ @property({ tooltip: '输入框占位符的文本内容', + displayOrder: 13, }) get placeholder () { if (!this._placeholderLabel) { @@ -340,6 +374,7 @@ export class EditBoxComponent extends Component { */ @property({ tooltip: '输入框占位符的字体大小', + displayOrder: 14, }) get placeholderFontSize () { if (!this._placeholderLabel){ @@ -362,6 +397,7 @@ export class EditBoxComponent extends Component { */ @property({ tooltip: '输入框占位符的字体颜色', + displayOrder: 15, }) get placeholderFontColor () { if (!this._placeholderLabel) { @@ -374,28 +410,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; } /** @@ -410,6 +424,7 @@ export class EditBoxComponent extends Component { */ @property({ tooltip: '输入框总是可见,并且永远在游戏视图的上面(这个属性只有在 Web 上面修改有意义)', + displayOrder: 21, }) get stayOnTop () { return; @@ -428,6 +443,7 @@ export class EditBoxComponent extends Component { */ @property({ tooltip: '修改 DOM 输入元素的 tabIndex(这个属性只有在 Web 上面修改有意义)', + displayOrder: 22, }) get tabIndex () { return this._tabIndex; @@ -457,6 +473,7 @@ export class EditBoxComponent extends Component { @property({ type: [ComponentEventHandler], tooltip: '该事件在用户点击输入框获取焦点的时候被触发', + displayOrder: 31, }) public editingDidBegan: ComponentEventHandler[] = []; @@ -470,6 +487,7 @@ export class EditBoxComponent extends Component { @property({ type: [ComponentEventHandler], tooltip: '编辑文本输入框时触发的事件回调', + displayOrder: 32, }) public textChanged: ComponentEventHandler[] = []; @@ -483,6 +501,7 @@ export class EditBoxComponent extends Component { @property({ type: [ComponentEventHandler], tooltip: '在单行模式下面,一般是在用户按下回车或者点击屏幕输入框以外的地方调用该函数。 如果是多行输入,一般是在用户点击屏幕输入框以外的地方调用该函数', + displayOrder: 33, }) public editingDidEnded: ComponentEventHandler[] = []; @@ -496,6 +515,7 @@ export class EditBoxComponent extends Component { @property({ type: [ComponentEventHandler], tooltip: '该事件在用户按下回车键的时候被触发, 如果是单行输入框,按回车键还会使输入框失去焦点', + displayOrder: 34, }) public editingReturn: ComponentEventHandler[] = []; diff --git a/cocos/ui/components/graphics-component.ts b/cocos/ui/components/graphics-component.ts index ffc7a19f6f..cbfee79559 100644 --- a/cocos/ui/components/graphics-component.ts +++ b/cocos/ui/components/graphics-component.ts @@ -67,6 +67,7 @@ export class GraphicsComponent extends UIRenderComponent { * @zh * 当前线条宽度。 */ + @property get lineWidth () { return this._lineWidth; } @@ -505,10 +506,10 @@ export class GraphicsComponent extends UIRenderComponent { } this.impl.clear(clean); - if (this.model) { + this._detachFromScene(); + if(this.model){ this.model.destroy(); } - this.markForUpdateRenderData(); } @@ -536,6 +537,7 @@ export class GraphicsComponent extends UIRenderComponent { * 根据当前的画线样式,绘制当前或已经存在的路径。 */ public stroke () { + this._attachToScene(); (this._assembler as IAssembler).stroke!(this); } @@ -547,6 +549,7 @@ export class GraphicsComponent extends UIRenderComponent { * 根据当前的画线样式,填充当前或已经存在的路径。 */ public fill () { + this._attachToScene(); (this._assembler as IAssembler).fill!(this); } @@ -602,10 +605,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!); @@ -614,6 +618,7 @@ export class GraphicsComponent extends UIRenderComponent { protected _detachFromScene () { if (this.model && this.model.scene) { this.model.scene.removeModel(this.model); + this.model.scene = null; } } } diff --git a/cocos/ui/components/label-component.ts b/cocos/ui/components/label-component.ts index 82122efd80..a8728b58af 100644 --- a/cocos/ui/components/label-component.ts +++ b/cocos/ui/components/label-component.ts @@ -153,7 +153,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 自适应文本尺寸(后续完善))。 diff --git a/cocos/ui/components/page-view-component.ts b/cocos/ui/components/page-view-component.ts index 44f96e24cc..baceb5ba2b 100644 --- a/cocos/ui/components/page-view-component.ts +++ b/cocos/ui/components/page-view-component.ts @@ -254,14 +254,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({ @@ -269,8 +272,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({ diff --git a/cocos/ui/components/scroll-bar-component.ts b/cocos/ui/components/scroll-bar-component.ts index 3e1c58c699..5f91cc8fbc 100644 --- a/cocos/ui/components/scroll-bar-component.ts +++ b/cocos/ui/components/scroll-bar-component.ts @@ -98,7 +98,8 @@ export class ScrollBarComponent extends Component { */ @property({ type: SpriteComponent, - tooltip:'作为当前滚动区域位置显示的滑块 Sprite', + tooltip: '作为当前滚动区域位置显示的滑块 Sprite', + displayOrder: 0, }) get handle () { return this._handle; @@ -121,7 +122,8 @@ export class ScrollBarComponent extends Component { */ @property({ type: Direction, - tooltip:'ScrollBar 的滚动方向', + tooltip: 'ScrollBar 的滚动方向', + displayOrder: 1, }) get direction () { return this._direction; @@ -144,7 +146,8 @@ export class ScrollBarComponent extends Component { * 是否在没有滚动动作时自动隐藏 ScrollBar。 */ @property({ - tooltip:'是否在没有滚动动作时自动隐藏 ScrollBar', + tooltip: '是否在没有滚动动作时自动隐藏 ScrollBar', + displayOrder: 2, }) get enableAutoHide () { return this._enableAutoHide; @@ -171,7 +174,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 e91d68395f..6779f4acc6 100644 --- a/cocos/ui/components/scroll-view-component.ts +++ b/cocos/ui/components/scroll-view-component.ts @@ -207,6 +207,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 @@ -218,6 +274,7 @@ export class ScrollViewComponent extends ViewGroupComponent { @property({ type: Node, tooltip: '可滚动展示内容的节点', + displayOrder: 4, }) get content () { return this._content; @@ -231,6 +288,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. @@ -240,6 +310,7 @@ export class ScrollViewComponent extends ViewGroupComponent { @property({ type: ScrollBarComponent, tooltip: '水平滚动的 ScrollBar', + displayOrder: 6, }) get horizontalScrollBar () { return this._horizontalScrollBar; @@ -258,6 +329,19 @@ export class ScrollViewComponent extends ViewGroupComponent { } } + /** + * @en + * Enable vertical scroll. + * + * @zh + * 是否开启垂直滚动。 + */ + @property({ + tooltip: '是否开启垂直滚动', + displayOrder: 7, + }) + public vertical = true; + /** * @en * The vertical scrollbar reference. @@ -268,6 +352,7 @@ export class ScrollViewComponent extends ViewGroupComponent { @property({ type: ScrollBarComponent, tooltip: '垂直滚动的 ScrollBar', + displayOrder: 8, }) get verticalScrollBar () { return this._verticalScrollBar; @@ -286,103 +371,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 @@ -394,9 +382,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 05b8dbc05d..80e9a3a70a 100644 --- a/cocos/ui/components/toggle-component.ts +++ b/cocos/ui/components/toggle-component.ts @@ -66,7 +66,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; @@ -81,6 +82,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. @@ -91,7 +116,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; @@ -111,29 +137,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(); @@ -160,7 +163,7 @@ export class ToggleComponent extends ButtonComponent { */ @property({ type: [ComponentEventHandler], - tooltip:'列表类型,默认为空,用户添加的每一个事件由节点引用,组件名称和一个响应函数组成', + tooltip: '列表类型,默认为空,用户添加的每一个事件由节点引用,组件名称和一个响应函数组成', }) public checkEvents: ComponentEventHandler[] = []; @property diff --git a/cocos/ui/components/widget-component.ts b/cocos/ui/components/widget-component.ts index 5d86a21987..8559566f4c 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'; @@ -224,7 +224,7 @@ export class WidgetComponent extends Component { } set target (value) { - if (this._target === value){ + if (this._target === value) { return; } @@ -574,7 +574,7 @@ export class WidgetComponent extends Component { return this._isAbsTop; } set isAbsoluteTop (value) { - if (this._isAbsTop === value){ + if (this._isAbsTop === value) { return; } @@ -594,7 +594,7 @@ export class WidgetComponent extends Component { return this._isAbsBottom; } set isAbsoluteBottom (value) { - if (this._isAbsBottom === value){ + if (this._isAbsBottom === value) { return; } @@ -634,7 +634,7 @@ export class WidgetComponent extends Component { return this._isAbsRight; } set isAbsoluteRight (value) { - if (this._isAbsRight === value){ + if (this._isAbsRight === value) { return; } @@ -642,31 +642,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. @@ -678,7 +653,6 @@ export class WidgetComponent extends Component { get isAbsoluteHorizontalCenter () { return this._isAbsHorizontalCenter; } - set isAbsoluteHorizontalCenter (value) { if (this._isAbsHorizontalCenter === value) { return; @@ -700,7 +674,7 @@ export class WidgetComponent extends Component { return this._isAbsVerticalCenter; } set isAbsoluteVerticalCenter (value) { - if (this._isAbsVerticalCenter === value){ + if (this._isAbsVerticalCenter === value) { return; } @@ -708,6 +682,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 组成 @@ -716,7 +714,6 @@ export class WidgetComponent extends Component { get alignFlags () { return this._alignFlags; } - set alignFlags (value) { if (this._alignFlags === value) { return; @@ -767,6 +764,10 @@ export class WidgetComponent extends Component { private _originalHeight = 0; @property private _alignMode = AlignMode.ON_WINDOW_RESIZE; + @property({ + editorOnly: true, + }) + private _lockFlags = 0; /** * @en @@ -805,7 +806,7 @@ export class WidgetComponent extends Component { } - public setDirty (){ + public setDirty () { this._recursiveDirty(); } @@ -909,7 +910,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(); @@ -959,9 +960,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; } @@ -1003,7 +1004,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); @@ -1011,7 +1012,7 @@ export class WidgetComponent extends Component { } } - protected _targetChangedOperation (){ + protected _targetChangedOperation () { this._recursiveDirty(); } @@ -1070,7 +1071,7 @@ export class WidgetComponent extends Component { } private _recursiveDirty () { - if (this._dirty){ + if (this._dirty) { return; } @@ -1078,7 +1079,13 @@ export class WidgetComponent extends Component { } } +export namespace WidgetComponent { + export type AlignMode = EnumAlias; +} + // @ts-ignore legacyCC.WidgetComponent = WidgetComponent; // cc.Widget = module.exports = Widget; +legacyCC.internal.computeInverseTransForTarget = computeInverseTransForTarget; +legacyCC.internal.getReadonlyNodeSize = getReadonlyNodeSize; diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index b569f52c1c..5ecd91cc61 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: '', - BlockInputEventsComponent: '', + SubContextView: 'https://docs.cocos.com/creator3d/manual/en/editor/publish/publish-wechatgame-subcontext.html', + 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', - 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', @@ -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', @@ -49,10 +48,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..5390e61447 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: '', - BlockInputEventsComponent: '', + SubContextView: 'https://docs.cocos.com/creator3d/manual/zh/editor/publish/publish-wechatgame-subcontext.html', + 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', - 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', @@ -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', @@ -49,10 +48,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', } }, 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..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", @@ -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", diff --git a/tests/animation/animation-events.test.ts b/tests/animation/animation-events.test.ts new file mode 100644 index 0000000000..ce36e32b70 --- /dev/null +++ b/tests/animation/animation-events.test.ts @@ -0,0 +1,158 @@ +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: (fn: Function, thisArg: any, args: any[]) => { + fn.apply(thisArg, 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)', () => { + 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 = () => {}; + + 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(isLastFrameEventAllowed)).toBeTruthy(); + + animationComponent.on(AnimationComponent.EventType.LASTFRAME, handler2); + // Should no problem. + expect(initialStates.every(isLastFrameEventAllowed)).toBeTruthy(); + + animationComponent.off(AnimationComponent.EventType.LASTFRAME, handler2); + // Now we unsubscribe one, but this should still true. + 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 => !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(isLastFrameEventAllowed(newState)).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 diff --git a/tests/core/eventify.test.ts b/tests/core/eventify.test.ts new file mode 100644 index 0000000000..7883016548 --- /dev/null +++ b/tests/core/eventify.test.ts @@ -0,0 +1,38 @@ +import { Eventify } from '../../cocos/core'; + +test('Eventify', () => { + 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