diff --git a/.github/workflows/native-compile-platforms.yml b/.github/workflows/native-compile-platforms.yml index 5d0d36e63c..1c1fcd25f9 100644 --- a/.github/workflows/native-compile-platforms.yml +++ b/.github/workflows/native-compile-platforms.yml @@ -68,6 +68,68 @@ jobs: cmake --build . --config Release echo "Compile Win64 Release Done!" + compile_android_minimal: + name: "Android Minimal" + if: + (! contains(github.event.pull_request.body, '[X] does not change any runtime related code or build configuration')) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v2 + - name: Download external libraries + shell: bash + run: | + EXT_VERSION=`node ./.github/workflows/get-native-external-version.js` + git clone --branch $EXT_VERSION --depth 1 https://github.com/cocos-creator/engine-native-external native/external + - uses: nttld/setup-ndk@v1 + id: setup-ndk + with: + ndk-version: r21e + add-to-path: false + - name: Generate bindings + env: + ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }} + run: | + python3 -m pip install PyYAML==5.4.1 Cheetah3 + python3 ./native/tools/tojs/genbindings.py + rm ./native/tools/tojs/userconf.ini + - name: Compile + env: + COCOS_ENGINE_DEV: 1 + run: | + NATIVE_ROOT=$GITHUB_WORKSPACE/native + ANDORID_NDK=$ANDROID_NDK_LATEST_HOME + NATIVE_DIR=$GITHUB_WORKSPACE/templates/android-template + echo "Compiling Android ... " + cd $GITHUB_WORKSPACE/templates/ + echo "message(STATUS \"hook before \${CC_TARGET_NAME}\")" >> android/template/Pre-Sample.cmake + echo "message(STATUS \"hook after \${CC_TARGET_NAME}\")" >> android/template/Post-Sample.cmake + if [ ! -d android-template ]; then + cp -r android/template android-template + fi + cd $GITHUB_WORKSPACE/templates/android/build + mkdir -p build-android/proj + touch build-android/proj/cfg.cmake + echo "set(CI_FORCE_MINIMAL_FEATURES ON)" >> build-android/proj/cfg.cmake + + mkdir -p build-android/assets + + ASSET_DIR=$GITHUB_WORKSPACE/templates/android/build/build-android/ + + sed -i "s@^PROP_NDK_PATH.*@PROP_NDK_PATH=$ANDORID_NDK@g" gradle.properties + sed -i "s@^APPLICATION_ID.*@APPLICATION_ID=com.cocos.android@g" gradle.properties + sed -i "s@^RES_PATH.*@RES_PATH=$ASSET_DIR@g" gradle.properties + sed -i "s@^COCOS_ENGINE_PATH.*@COCOS_ENGINE_PATH=$NATIVE_ROOT@g" gradle.properties + sed -i "s@^NATIVE_DIR.*@NATIVE_DIR=$NATIVE_DIR@g" gradle.properties + + # To speedup CI, compile arm64-v8a only + # sed -i "s@^PROP_APP_ABI.*@PROP_APP_ABI=armeabi-v7a:arm64-v8a:x86@g" gradle.properties + sed -i "s@^PROP_APP_ABI.*@PROP_APP_ABI=arm64-v8a@g" gradle.properties + + echo "Compile Android - cmake ..." + echo "ANDORID_NDK ${ANDROID_NDK} or ${ANDROID_NDK_HOME}" + ./gradlew :CocosGame:assembleDebug --quiet + echo "Compile Android Debug Done!" + compile_android: name: "Android" if: @@ -127,7 +189,7 @@ jobs: # To speedup CI, compile arm64-v8a only # sed -i "s@^PROP_APP_ABI.*@PROP_APP_ABI=armeabi-v7a:arm64-v8a:x86@g" gradle.properties - sed -i "s@^PROP_APP_ABI.*@PROP_APP_ABI=arm64-v8a@g" gradle.properties + sed -i "s@^PROP_APP_ABI.*@PROP_APP_ABI=armeabi-v7a:arm64-v8a@g" gradle.properties echo "Compile Android - cmake ..." echo "ANDORID_NDK ${ANDROID_NDK} or ${ANDROID_NDK_HOME}" diff --git a/.github/workflows/run_test_cases.yml b/.github/workflows/run_test_cases.yml index b65d9ebae8..df039d0b6e 100644 --- a/.github/workflows/run_test_cases.yml +++ b/.github/workflows/run_test_cases.yml @@ -82,6 +82,7 @@ jobs: run: | cd .. python3 -u ./python/main.py --workspace ${{github.workspace}} --pr_number ${{ steps.get_pr.outputs.pr_number }} --author ${{ steps.parse_pr.outputs.pr_author }} --base_ref ${{ steps.parse_pr.outputs.pr_base_ref }} --base_sha ${{ steps.parse_pr.outputs.pr_base_sha }} --head_ref ${{ steps.parse_pr.outputs.pr_head_ref }} --head_sha ${{ steps.parse_pr.outputs.pr_head_sha }} + - name: Update Comment uses: peter-evans/create-or-update-comment@v1 with: @@ -167,6 +168,7 @@ jobs: run: | cd .. python3 -u ./python/main.py --workspace ${{github.workspace}} --pr_number ${{ steps.get_pr.outputs.pr_number }} --author ${{ steps.parse_pr.outputs.pr_author }} --base_ref ${{ steps.parse_pr.outputs.pr_base_ref }} --base_sha ${{ steps.parse_pr.outputs.pr_base_sha }} --head_ref ${{ steps.parse_pr.outputs.pr_head_ref }} --head_sha ${{ steps.parse_pr.outputs.pr_head_sha }} + - name: Update Comment uses: peter-evans/create-or-update-comment@v1 with: diff --git a/@types/jsb.d.ts b/@types/jsb.d.ts index 588f5e757c..f8c0a5a4f5 100644 --- a/@types/jsb.d.ts +++ b/@types/jsb.d.ts @@ -148,57 +148,6 @@ declare namespace jsb { export function getOriginalPCMBuffer (url: string, channelID: number): ArrayBuffer | undefined; } - export namespace reflection{ - /** - * https://docs.cocos.com/creator/manual/zh/advanced-topics/java-reflection.html - * call OBJC/Java static methods - * - * @param className - * @param methodName - * @param methodSignature - * @param parameters - */ - export function callStaticMethod (className: string, methodName: string, methodSignature: string, ...parameters:any): any; - } - export namespace bridge{ - /** - * send to native with at least one argument. - */ - export function sendToNative(arg0: string, arg1?: string): void; - /** - * save your own callback controller with a js function, - * use jsb.bridge.onNative = (arg0: String, arg1: String)=>{...} - * @param args : received from native - */ - export function onNative(arg0: string, arg1?: string|null): void; - } - /** - * Listener for jsbBridgeWrapper's event. - * It takes one argument as string which is transferred by jsbBridge. - */ - export type OnNativeEventListener = (arg: string) => void; - export namespace jsbBridgeWrapper { - /** If there's no event registered, the wrapper will create one */ - export function addNativeEventListener(eventName: string, listener: OnNativeEventListener); - /** - * Dispatch the event registered on Objective-C, Java etc. - * No return value in JS to tell you if it works. - */ - export function dispatchEventToNative(eventName: string, arg?: string); - /** - * Remove all listeners relative. - */ - export function removeAllListenersForEvent(eventName: string); - /** - * Remove the listener specified - */ - export function removeNativeEventListener(eventName: string, listener: OnNativeEventListener); - /** - * Remove all events, use it carefully! - */ - export function removeAllListeners(); - } - export interface ManifestAsset { md5: string; path: string; diff --git a/EngineErrorMap.md b/EngineErrorMap.md index 3269cafad4..b707f1cf3d 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -3286,4 +3286,8 @@ The native folder may be generated from older versions, please refer https://doc ### 16003 -'%s' is removed since v%s, please use '%s' instead. \ No newline at end of file +'%s' is removed since v%s, please use '%s' instead. + +### 16101 + +The effect('%s') you are looking for does not exist, please confirm the effect name in the editor. NOTE: Since 3.6, the name of the built-in effect has been changed to its name in the editor, please check it out. More information please refer to https://docs.cocos.com/creator/manual/en/shader/effect-inspector.html \ No newline at end of file diff --git a/cc.config.json b/cc.config.json index 0abf04065e..412737ccc1 100644 --- a/cc.config.json +++ b/cc.config.json @@ -7,7 +7,8 @@ "970b0598-bcb0-4714-91fb-2e81440dccd8", "bcd64cc6-2dd9-43f6-abbe-66318d332032", "d930590d-bb92-4cc8-8bd1-23cd027f9edf", - "a3cd009f-0ab0-420d-9278-b9fdab939bbc" + "a3cd009f-0ab0-420d-9278-b9fdab939bbc", + "9361fd90-ba52-4f84-aa93-6e878fd576ca" ]}, "gfx-webgl": { "modules": [ "gfx-webgl" ] }, "gfx-webgl2": { "modules": [ "gfx-webgl2" ] }, @@ -15,7 +16,6 @@ "modules": [ "3d" ], "dependentAssets": [ "1baf0fc9-befa-459c-8bdd-af1a450a0319", - "9361fd90-ba52-4f84-aa93-6e878fd576ca", "511d2633-09a7-4bdd-ac42-f778032124b3", "5d45aa00-e064-4938-b314-4265f0c2258c", "28d6d6b8-3f66-4a73-9795-17a0852ba2d4", @@ -57,10 +57,14 @@ }, "particle-2d": { "modules": [ "particle-2d" ] }, "physics-framework": { "modules": [ "physics-framework" ] }, - "physics-cannon": { "modules": [ "physics-cannon", "physics-framework" ] }, - "physics-physx": { "modules": [ "physics-physx", "physics-framework" ] }, - "physics-ammo": { "modules": [ "physics-ammo", "physics-framework", "wait-for-ammo-instantiation" ] }, - "physics-builtin": { "modules": [ "physics-builtin", "physics-framework" ] }, + "physics-cannon": { "modules": [ "physics-cannon", "physics-framework" ] , + "dependentAssets": [ "ba21476f-2866-4f81-9c4d-6e359316e448" ]}, + "physics-physx": { "modules": [ "physics-physx", "physics-framework" ] , + "dependentAssets": [ "ba21476f-2866-4f81-9c4d-6e359316e448" ]}, + "physics-ammo": { "modules": [ "physics-ammo", "physics-framework", "wait-for-ammo-instantiation" ] , + "dependentAssets": [ "ba21476f-2866-4f81-9c4d-6e359316e448" ]}, + "physics-builtin": { "modules": [ "physics-builtin", "physics-framework" ] , + "dependentAssets": [ "ba21476f-2866-4f81-9c4d-6e359316e448" ]}, "physics-2d-framework": { "modules": [ "physics-2d-framework" ] }, "physics-2d-box2d": { "modules": [ "physics-2d-box2d", "physics-2d-framework" ] }, "physics-2d-builtin": { "modules": [ "physics-2d-builtin", "physics-2d-framework" ] }, @@ -264,78 +268,91 @@ "constants": { "HTML5": { "comment": "Running in Web platform", + "type": "boolean", "value": false, "internal": false, "dynamic": true }, "NATIVE": { "comment": "Running in native platform (mobile app, desktop app, or simulator).", + "type": "boolean", "value": false, "internal": false, "dynamic": true }, "WECHAT": { "comment": "Running in the Wechat's mini game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "BAIDU": { "comment": "Running in the baidu's mini game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "XIAOMI": { "comment": "Running in the xiaomi's quick game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "ALIPAY": { "comment": "Running in the alipay's mini game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "BYTEDANCE": { "comment": "Running in the ByteDance's mini game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "OPPO": { "comment": "Running in the oppo's quick game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "VIVO": { "comment": "Running in the vivo's quick game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "HUAWEI": { "comment": "Running in the huawei's quick game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "COCOSPLAY": { "comment": "Running in the cocosplay.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "QTT": { "comment": "Running in the qtt's quick game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "LINKSURE": { "comment": "Running in the linksure's quick game.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false @@ -343,6 +360,7 @@ "EDITOR": { "comment": "Running in the editor.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false, @@ -350,6 +368,7 @@ }, "PREVIEW": { "comment": "Preview in browser or simulator.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false, @@ -357,12 +376,14 @@ }, "BUILD": { "comment": "Running in published project.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false }, "TEST": { "comment": "Running in the engine's unit test.", + "type": "boolean", "value": false, "ccGlobal": true, "internal": false, @@ -372,19 +393,22 @@ "DEBUG": { "comment": "Running debug mode.", + "type": "boolean", "value": true, "ccGlobal": true, "internal": false }, "SERVER_MODE": { "comment": "Running in the server mode.", + "type": "boolean", "value": false, - "internal": false + "internal": true }, "DEV": { "comment": "Running in the editor or preview.", + "type": "boolean", "value": "$EDITOR || $PREVIEW || $TEST", "ccGlobal": true, "internal": false, @@ -392,25 +416,28 @@ }, "MINIGAME": { "comment": "Running in mini game.", + "type": "boolean", "value": "$WECHAT || $BAIDU || $XIAOMI || $ALIPAY || $BYTEDANCE", "ccGlobal": true, "internal": false }, "RUNTIME_BASED": { "comment": "Running in runtime based environment.", + "type": "boolean", "value": "$OPPO || $VIVO || $HUAWEI || $COCOSPLAY || $QTT || $LINKSURE", "ccGlobal": true, "internal": false }, "SUPPORT_JIT": { "comment": "Support JIT.", + "type": "boolean", "value": "!($MINIGAME || $RUNTIME_BASED)", "ccGlobal": true, - "internal": false, - "dynamic": true + "internal": false }, "JSB": { "comment": "Running in environment where using JSB as the JavaScript interface binding scheme.", + "type": "boolean", "value": "$NATIVE", "ccGlobal": true, "internal": false, @@ -418,8 +445,15 @@ }, "NOT_PACK_PHYSX_LIBS": { "comment": "This is an internal constant to determine whether pack physx libs.", + "type": "boolean", "value": false, "internal": true + }, + "NET_MODE": { + "comment": "The network access mode.\n- 0 Client\n- 1 ListenServer\n- 2 HostServer", + "type": "number", + "value": 0, + "internal": false } } } diff --git a/cc.config.schema.json b/cc.config.schema.json index e2f0b72edf..2446166f91 100644 --- a/cc.config.schema.json +++ b/cc.config.schema.json @@ -38,7 +38,6 @@ "additionalProperties": { "type": "string" }, - "description": "Construct a type with a set of properties K of type T", "type": "object" }, "test": { @@ -62,6 +61,13 @@ ], "type": "object" }, + "ConstantTypeName": { + "enum": [ + "boolean", + "number" + ], + "type": "string" + }, "Feature": { "additionalProperties": false, "description": "An engine feature.", @@ -111,16 +117,22 @@ "description": "Whether exported to developer. If true, it's only exported to engine.", "type": "boolean" }, + "type": { + "$ref": "#/definitions/ConstantTypeName", + "description": "The type of the constant for generating consts.d.ts file." + }, "value": { - "description": "The default value of the constant. It can be a boolean or string. When it's a string type, the value is the result of eval().", + "description": "The default value of the constant. It can be a boolean, number or string. When it's a string type, the value is the result of eval().", "type": [ "boolean", - "string" + "string", + "number" ] } }, "required": [ "comment", + "type", "value", "internal" ], @@ -144,7 +156,6 @@ }, "type": "object" }, - "description": "Construct a type with a set of properties K of type T", "type": "object" } }, diff --git a/cocos/2d/assembler/label/bmfontUtils.ts b/cocos/2d/assembler/label/bmfontUtils.ts index 13a58f4c1d..33f97c0e1d 100644 --- a/cocos/2d/assembler/label/bmfontUtils.ts +++ b/cocos/2d/assembler/label/bmfontUtils.ts @@ -24,13 +24,13 @@ */ import { JSB } from 'internal:constants'; -import { BitmapFont, IConfig, FontLetterDefinition } from '../../assets/bitmap-font'; +import { BitmapFont, IConfig, FontLetterDefinition, FontAtlas } from '../../assets/bitmap-font'; import { SpriteFrame } from '../../assets/sprite-frame'; import { isUnicodeCJK, isUnicodeSpace } from '../../utils/text-utils'; import { Rect, Size, Vec2 } from '../../../core/math'; -import { HorizontalTextAlignment, VerticalTextAlignment, Label, Overflow } from '../../components/label'; +import { HorizontalTextAlignment, VerticalTextAlignment, Label, Overflow, CacheMode } from '../../components/label'; import { UITransform } from '../../framework/ui-transform'; -import { shareLabelInfo } from './font-utils'; +import { LetterAtlas, shareLabelInfo } from './font-utils'; import { dynamicAtlasManager } from '../../utils/dynamic-atlas/atlas-manager'; class LetterInfo { @@ -43,6 +43,8 @@ class LetterInfo { } const _tmpRect = new Rect(); +const _defaultLetterAtlas = new LetterAtlas(64, 64); +const _defaultFontAtlas = new FontAtlas(null); let _comp: Label | null = null; let _uiTrans: UITransform | null = null; @@ -161,6 +163,13 @@ export const bmfontUtils = { _spriteFrame = fontAsset.spriteFrame; _fntConfig = fontAsset.fntConfig; shareLabelInfo.fontAtlas = fontAsset.fontDefDictionary; + if (!shareLabelInfo.fontAtlas) { + if (comp.cacheMode === CacheMode.CHAR) { + shareLabelInfo.fontAtlas = _defaultLetterAtlas; + } else { + shareLabelInfo.fontAtlas = _defaultFontAtlas; + } + } dynamicAtlasManager.packToDynamicAtlas(comp, _spriteFrame); // TODO update material and uv @@ -224,6 +233,10 @@ export const bmfontUtils = { const kerningDict = _fntConfig!.kerningDict; const horizontalKerning = _horizontalKerning; + if (!kerningDict) { + return; + } + let prev = -1; for (let i = 0; i < stringLen; ++i) { const key = string.charCodeAt(i); diff --git a/cocos/2d/assembler/label/font-utils.ts b/cocos/2d/assembler/label/font-utils.ts index cda68fea39..2208be9118 100644 --- a/cocos/2d/assembler/label/font-utils.ts +++ b/cocos/2d/assembler/label/font-utils.ts @@ -144,6 +144,7 @@ class LetterTexture { public destroy () { this.image = null; // Label._canvasPool.put(this._data); + CanvasPool.getInstance().put(this.data as ISharedLabelData); } private _updateProperties () { diff --git a/cocos/2d/assembler/mask/mask-assembler.ts b/cocos/2d/assembler/mask/mask-assembler.ts index 77eb48e9d8..a564f0bd99 100644 --- a/cocos/2d/assembler/mask/mask-assembler.ts +++ b/cocos/2d/assembler/mask/mask-assembler.ts @@ -27,6 +27,7 @@ import { IBatcher } from '../../renderer/i-batcher'; import { Mask, MaskType } from '../../components/mask'; import { IAssembler, IAssemblerManager } from '../../renderer/base'; import { StencilManager } from '../../renderer/stencil-manager'; +import { RenderDrawInfoType } from '../../renderer/render-draw-info'; const _stencilManager = StencilManager.sharedManager!; @@ -45,7 +46,7 @@ function applyAreaMask (mask: Mask, renderer: IBatcher) { export const maskAssembler: IAssembler = { createData (mask: Mask) { - const renderData = mask.requestRenderData(); + const renderData = mask.requestRenderData(RenderDrawInfoType.MODEL); return renderData; }, diff --git a/cocos/2d/components/mask.ts b/cocos/2d/components/mask.ts index fed0237cb2..d31ce3ad4d 100644 --- a/cocos/2d/components/mask.ts +++ b/cocos/2d/components/mask.ts @@ -44,7 +44,7 @@ import { Stage } from '../renderer/stencil-manager'; import { NodeEventProcessor } from '../../core/scene-graph/node-event-processor'; import { RenderingSubMesh } from '../../core/assets/rendering-sub-mesh'; import { IAssemblerManager } from '../renderer/base'; -import { RenderEntity, RenderEntityType } from '../renderer/render-entity'; +import { MaskMode, RenderEntity, RenderEntityType } from '../renderer/render-entity'; import { RenderDrawInfoType } from '../renderer/render-draw-info'; import { Sprite } from './sprite'; @@ -152,9 +152,7 @@ export class Mask extends UIRenderer { this._changeRenderType(); this._updateGraphics(); if (JSB) { - this.subComp!.renderEntity.setIsSubMask(true); - // subMask and mask should have the same inverted flag - this.subComp!.renderEntity.setIsMaskInverted(this._inverted); + this.subComp!.renderEntity.setMaskMode(this._inverted ? MaskMode.MASK_NODE_INVERTED : MaskMode.MASK_NODE); } } else { if (this._graphics) { @@ -164,9 +162,7 @@ export class Mask extends UIRenderer { this._maskNode!.parent = null; this._changeRenderType(); if (JSB) { - this.subComp!.renderEntity.setIsSubMask(true); - // subMask and mask should have the same inverted flag - this.subComp!.renderEntity.setIsMaskInverted(this._inverted); + this.subComp!.renderEntity.setMaskMode(this._inverted ? MaskMode.MASK_NODE_INVERTED : MaskMode.MASK_NODE); } } } @@ -194,7 +190,7 @@ export class Mask extends UIRenderer { } if (JSB) { - this._renderEntity.setIsMaskInverted(this._inverted); + this._renderEntity.setMaskMode(this._inverted ? MaskMode.MASK_INVERTED : MaskMode.MASK); } } @@ -355,11 +351,8 @@ export class Mask extends UIRenderer { if (JSB) { if (this.renderData && this.subComp) { - this._renderEntity.setIsMask(true); - this.subComp.renderEntity.setIsSubMask(true); - this._renderEntity.setIsMaskInverted(this._inverted); - // subMask and mask should have the same inverted flag - this.subComp.renderEntity.setIsMaskInverted(this._inverted); + this._renderEntity.setMaskMode(this._inverted ? MaskMode.MASK_INVERTED : MaskMode.MASK); + this.subComp.renderEntity.setMaskMode(this._inverted ? MaskMode.MASK_NODE_INVERTED : MaskMode.MASK_NODE); // hack for isMeshBuffer flag this.renderData.renderDrawInfo.setIsMeshBuffer(true); this.renderData.drawInfoType = RenderDrawInfoType.MODEL; @@ -656,7 +649,7 @@ export class Mask extends UIRenderer { } protected _updateBuiltinMaterial (): Material { - return this._clearStencilMtl!; + return builtinResMgr.get('default-clear-stencil'); } protected _updateMaterial () { diff --git a/cocos/2d/components/sprite.ts b/cocos/2d/components/sprite.ts index 3ed18783e3..50924edf6e 100644 --- a/cocos/2d/components/sprite.ts +++ b/cocos/2d/components/sprite.ts @@ -25,7 +25,7 @@ */ import { ccclass, help, executionOrder, menu, tooltip, displayOrder, type, range, editable, serializable, visible } from 'cc.decorator'; -import { EDITOR } from 'internal:constants'; +import { BUILD, EDITOR } from 'internal:constants'; import { SpriteAtlas } from '../assets/sprite-atlas'; import { SpriteFrame } from '../assets/sprite-frame'; import { Vec2 } from '../../core/math'; @@ -616,7 +616,7 @@ export class Sprite extends UIRenderer { private _applySpriteSize () { if (this._spriteFrame) { - if (!this._spriteFrame.isDefault) { + if (BUILD || !this._spriteFrame.isDefault) { if (SizeMode.RAW === this._sizeMode) { const size = this._spriteFrame.originalSize; this.node._uiProps.uiTransformComp!.setContentSize(size); diff --git a/cocos/2d/components/ui-mesh-renderer.ts b/cocos/2d/components/ui-mesh-renderer.ts index ca585daa8b..3bb3df2990 100644 --- a/cocos/2d/components/ui-mesh-renderer.ts +++ b/cocos/2d/components/ui-mesh-renderer.ts @@ -25,7 +25,7 @@ */ import { ccclass, help, executionOrder, menu, executeInEditMode } from 'cc.decorator'; -import { JSB } from 'internal:constants'; +import { DEBUG, JSB } from 'internal:constants'; import { ModelRenderer } from '../../core/components/model-renderer'; import { RenderPriority } from '../../core/pipeline/define'; import { IBatcher } from '../renderer/i-batcher'; @@ -241,7 +241,9 @@ export class UIMeshRenderer extends Component { } get renderEntity () { - assert(this._renderEntity); + if (DEBUG) { + assert(this._renderEntity, 'this._renderEntity should not be invalid'); + } return this._renderEntity; } diff --git a/cocos/2d/components/ui-opacity.ts b/cocos/2d/components/ui-opacity.ts index 3e1e11f2eb..a02016f1de 100644 --- a/cocos/2d/components/ui-opacity.ts +++ b/cocos/2d/components/ui-opacity.ts @@ -28,6 +28,7 @@ import { JSB } from 'internal:constants'; import { Component } from '../../core/components/component'; import { clampf } from '../../core/utils/misc'; import { UIRenderer } from '../framework/ui-renderer'; +import { Node } from '../../core/scene-graph'; /** * @en @@ -66,16 +67,44 @@ export class UIOpacity extends Component { this._opacity = value; this.node._uiProps.localOpacity = value / 255; - this.setEntityColorDirtyRecursively(true); + this.setEntityLocalOpacityDirtyRecursively(true); } - private setEntityColorDirtyRecursively (dirty: boolean) { + private setEntityLocalOpacityDirtyRecursively (dirty: boolean) { if (JSB) { - const render = this.node._uiProps.uiComp as UIRenderer; - if (render) { - render.setEntityOpacity(this.node._uiProps.localOpacity); + // const render = this.node._uiProps.uiComp as UIRenderer; + // if (render) { + // render.setEntityOpacity(this.node._uiProps.localOpacity); + // } + // UIRenderer.setEntityColorDirtyRecursively(this.node, dirty); + + UIOpacity.setEntityLocalOpacityDirtyRecursively(this.node, dirty, 1); + } + } + + // for UIOpacity + public static setEntityLocalOpacityDirtyRecursively (node: Node, dirty: boolean, interruptParentOpacity: number) { + const render = node._uiProps.uiComp as UIRenderer; + const uiOp = node.getComponent(UIOpacity); + let interruptOpacity = interruptParentOpacity;// if there is no UIOpacity component, it should always equal to 1. + + if (render && render.color) { // exclude UIMeshRenderer which has not color + render.renderEntity.colorDirty = dirty; + render.renderEntity.color = render.color;// necessity to be considering + if (uiOp) { + render.renderEntity.localOpacity = interruptOpacity * uiOp.opacity / 255; + } else { + // there is a just UIRenderer but no UIOpacity on the node, we should just transport the parentOpacity to the node. + render.renderEntity.localOpacity = interruptOpacity; } - UIRenderer.setEntityColorDirtyRecursively(this.node, dirty); + interruptOpacity = 1; + } else if (uiOp) { + // there is a just UIOpacity but no UIRenderer on the node. + interruptOpacity = uiOp.opacity / 255; + } + + for (let i = 0; i < node.children.length; i++) { + UIOpacity.setEntityLocalOpacityDirtyRecursively(node.children[i], dirty || (interruptOpacity < 1), interruptOpacity); } } @@ -84,11 +113,11 @@ export class UIOpacity extends Component { public onEnable () { this.node._uiProps.localOpacity = this._opacity / 255; - this.setEntityColorDirtyRecursively(true); + this.setEntityLocalOpacityDirtyRecursively(true); } public onDisable () { this.node._uiProps.localOpacity = 1; - this.setEntityColorDirtyRecursively(true); + this.setEntityLocalOpacityDirtyRecursively(true); } } diff --git a/cocos/2d/framework/ui-renderer.ts b/cocos/2d/framework/ui-renderer.ts index 059c48c5a0..54da6921c5 100644 --- a/cocos/2d/framework/ui-renderer.ts +++ b/cocos/2d/framework/ui-renderer.ts @@ -23,9 +23,9 @@ THE SOFTWARE. */ -import { EDITOR, JSB } from 'internal:constants'; +import { DEBUG, EDITOR, JSB } from 'internal:constants'; import { - ccclass, executeInEditMode, requireComponent, disallowMultiple, tooltip, + ccclass, executeInEditMode, requireComponent, tooltip, type, displayOrder, serializable, override, visible, displayName, disallowAnimation, } from 'cc.decorator'; import { Color } from '../../core/math'; @@ -46,6 +46,7 @@ import { Renderer } from '../../core/components/renderer'; import { RenderEntity, RenderEntityType } from '../renderer/render-entity'; import { uiRendererManager } from './ui-renderer-manager'; import { assert, director } from '../../core'; +import { RenderDrawInfoType } from '../renderer/render-draw-info'; // hack ccenum(BlendFactor); @@ -113,7 +114,6 @@ export enum InstanceMaterialType { */ @ccclass('cc.UIRenderer') @requireComponent(UITransform) -@disallowMultiple @executeInEditMode export class UIRenderer extends Renderer { /** @@ -285,7 +285,9 @@ export class UIRenderer extends Renderer { } get renderEntity () { - assert(this._renderEntity); + if (DEBUG) { + assert(this._renderEntity, 'this._renderEntity should not be invalid'); + } return this._renderEntity; } @@ -380,9 +382,9 @@ export class UIRenderer extends Renderer { * @zh 请求新的渲染数据对象。 * @return The new render data */ - public requestRenderData () { + public requestRenderData (drawInfoType = RenderDrawInfoType.COMP) { const data = RenderData.add(); - data.initRenderDrawInfo(this); + data.initRenderDrawInfo(this, drawInfoType); this._renderData = data; return data; } @@ -434,8 +436,10 @@ export class UIRenderer extends Renderer { protected _postRender (render: IBatcher) { } protected _canRender () { - return this.isValid - && this.getMaterial(0) !== null + if (DEBUG) { + assert(this.isValid, 'this component should not be invalid!'); + } + return this.getMaterial(0) !== null && this.enabled && (this._delegateSrc ? this._delegateSrc.activeInHierarchy : this.enabledInHierarchy) && this._color.a > 0; @@ -464,13 +468,14 @@ export class UIRenderer extends Renderer { this._assembler.updateColor(this); // Need update rendFlag when opacity changes from 0 to !0 or 0 to !0 this._renderFlag = this._canRender(); + this.setEntityEnabled(this._renderFlag); } } // for common public static setEntityColorDirtyRecursively (node: Node, dirty: boolean) { const render = node._uiProps.uiComp as UIRenderer; - if (render) { + if (render && render.color) { // exclude UIMeshRenderer which has not color render._renderEntity.colorDirty = dirty; render._renderEntity.color = render.color;// necessity to be considering } @@ -497,6 +502,12 @@ export class UIRenderer extends Renderer { } } + public setEntityEnabled (enabled: boolean) { + if (JSB) { + this._renderEntity.enabled = enabled; + } + } + /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ diff --git a/cocos/2d/renderer/draw-batch.ts b/cocos/2d/renderer/draw-batch.ts index 4f079da6ad..47f852b318 100644 --- a/cocos/2d/renderer/draw-batch.ts +++ b/cocos/2d/renderer/draw-batch.ts @@ -133,15 +133,8 @@ export class DrawBatch2D { if (bsHash === -1) { bsHash = 0; } hashFactor = (dssHash << 16) | bsHash; - if (JSB) { - const nativeDSS = dss._nativeObj ? dss._nativeObj : dss; - const nativeBS = bs._nativeObj ? bs._nativeObj : bs; - // @ts-expect-error hack for UI use pass object - passInUse._initPassFromTarget(mtlPass, nativeDSS, nativeBS, hashFactor); - } else { - // @ts-expect-error hack for UI use pass object - passInUse._initPassFromTarget(mtlPass, dss, bs, hashFactor); - } + // @ts-expect-error hack for UI use pass object + passInUse._initPassFromTarget(mtlPass, dss, bs, hashFactor); this._shaders[i] = passInUse.getShaderVariant(patches)!; diff --git a/cocos/2d/renderer/native-2d.ts b/cocos/2d/renderer/native-2d.ts index 59b219f318..dab487fb54 100644 --- a/cocos/2d/renderer/native-2d.ts +++ b/cocos/2d/renderer/native-2d.ts @@ -4,22 +4,7 @@ import { Node } from '../../core/scene-graph'; import { Model } from '../../core/renderer/scene'; export declare class NativeRenderDrawInfo { - constructor(batcher: NativeBatcher2d); - - // get batcher ():NativeBatcher2d { return new NativeBatcher2d(); } - // set batcher (batcher: NativeBatcher2d) {} - - get accId(): number; - set accId(accId: number); - - get bufferId(): number; - set bufferId(bufferId: number); - - get vertexOffset(): number; - set vertexOffset(vertexOffset: number); - - get indexOffset(): number; - set indexOffset(indexOffset: number); + constructor(); get vbBuffer(): ArrayBufferLike; set vbBuffer(vbBuffer: ArrayBufferLike); @@ -33,64 +18,35 @@ export declare class NativeRenderDrawInfo { get iDataBuffer(): ArrayBufferLike; set iDataBuffer(iDataBuffer: ArrayBufferLike); - get vbCount(): number; - set vbCount(vbCount: number); - - get ibCount(): number; - set ibCount(ibCount: number); - - get vertDirty(): boolean; - set vertDirty(val: boolean); - - get dataHash(): number; - set dataHash(dataHash: number); - - get isMeshBuffer(): boolean; - set isMeshBuffer(isMeshBuffer: boolean); - get material(): Material | null; set material(material: Material | null); get texture(): Texture | null; set texture(texture: Texture | null); - get textureHash(): number; - set textureHash(textureHash: number); - get sampler(): Sampler | null; set sampler(sampler: Sampler | null); - get blendHash(): number; - set blendHash(blendHash: number); - get model(): Model | null; set model(model: Model | null); - get drawInfoType(): number; - set drawInfoType(drawInfoType: number); + get subNode(): Node; + set subNode(node: Node); - setRender2dBufferToNative(data: TypedArray, stride: number, size: number); + changeMeshBuffer(); + setRender2dBufferToNative(data: TypedArray); syncSharedBufferToNative(data: TypedArray); getAttrSharedBufferForJS(): ArrayBufferLike; } export declare class NativeRenderEntity { - constructor(batcher: NativeBatcher2d); + constructor(type: number); addDynamicRenderDrawInfo(drawInfo: NativeRenderDrawInfo); setDynamicRenderDrawInfo(drawInfo: NativeRenderDrawInfo, index: number); removeDynamicRenderDrawInfo(); clearDynamicRenderDrawInfos(); - get isMask(): boolean; - set isMask(val: boolean); - - get isSubMask(): boolean; - set isSubMask(val: boolean); - - get isMaskInverted(): boolean; - set isMaskInverted(val: boolean); - get node(): Node | null; set node(node: Node | null); @@ -100,7 +56,6 @@ export declare class NativeRenderEntity { get staticDrawInfoSize(): number; set staticDrawInfoSize(size: number); - setRenderEntityType(type: number); getStaticRenderDrawInfo(index: number): NativeRenderDrawInfo; getEntitySharedBufferForJS(): ArrayBufferLike; } diff --git a/cocos/2d/renderer/render-data.ts b/cocos/2d/renderer/render-data.ts index 1a96a925fe..5afd0617ac 100644 --- a/cocos/2d/renderer/render-data.ts +++ b/cocos/2d/renderer/render-data.ts @@ -173,12 +173,13 @@ export class BaseRenderData { if (!this._renderDrawInfo) { this._renderDrawInfo = new RenderDrawInfo(); // for no resize() invoking components - this.setRenderDrawInfoAttributes(); + //this.setRenderDrawInfoAttributes(); renderEntity.addDynamicRenderDrawInfo(this._renderDrawInfo); } } this.drawInfoType = drawInfoType; + this.setRenderDrawInfoAttributes(); } } @@ -290,9 +291,6 @@ export class RenderData extends BaseRenderData { } set textureHash (val: number) { this._textureHash = val; - if (this._renderDrawInfo) { - this._renderDrawInfo.setTextureHash(val); - } } protected _blendHash = -1; @@ -301,9 +299,6 @@ export class RenderData extends BaseRenderData { } set blendHash (val: number) { this._blendHash = val; - if (this._renderDrawInfo) { - this._renderDrawInfo.setBlendHash(val); - } } public indices: Uint16Array | null = null; @@ -384,9 +379,7 @@ export class RenderData extends BaseRenderData { this._renderDrawInfo.setAccId(this._accessor.id); super.setRenderDrawInfoAttributes(); this._renderDrawInfo.setTexture(this.frame ? this.frame.getGFXTexture() : null); - this._renderDrawInfo.setTextureHash(this.textureHash); this._renderDrawInfo.setSampler(this.frame ? this.frame.getGFXSampler() : null); - this._renderDrawInfo.setBlendHash(this.blendHash); } } @@ -418,8 +411,9 @@ export class RenderData extends BaseRenderData { if (!this._renderDrawInfo) { return; } - this.renderDrawInfo.initRender2dBuffer(this.dataLength, this.floatStride); - this.renderDrawInfo.setRender2dBufferToNative(); + this.renderDrawInfo.setStride(this.floatStride); + this.renderDrawInfo.setVBCount(this.dataLength); + this.renderDrawInfo.initRender2dBuffer(); } } @@ -479,6 +473,10 @@ export class RenderData extends BaseRenderData { this.blendHash = comp.blendHash; this.passDirty = false; this.hashDirty = true; + + if (this._renderDrawInfo) { + this._renderDrawInfo.setMaterial(this.material); + } } if (this.nodeDirty) { const renderScene = comp.node.scene ? comp._getRenderScene() : null; @@ -494,15 +492,24 @@ export class RenderData extends BaseRenderData { this.textureHash = frame.getHash(); this.textureDirty = false; this.hashDirty = true; + + if (this._renderDrawInfo) { + this._renderDrawInfo.setTexture(this.frame ? this.frame.getGFXTexture() : null); + this._renderDrawInfo.setSampler(this.frame ? this.frame.getGFXSampler() : null); + } } if (this.hashDirty) { this.updateHash(); + + if (this._renderDrawInfo) { + this._renderDrawInfo.setDataHash(this.dataHash); + } } // Hack Do not update pre frame if (JSB && this.multiOwner === false) { // for sync vData and iData address to native - this.setRenderDrawInfoAttributes(); + //this.setRenderDrawInfoAttributes(); // sync shared buffer to native this.copyRenderDataToSharedBuffer(); } diff --git a/cocos/2d/renderer/render-draw-info.ts b/cocos/2d/renderer/render-draw-info.ts index 1e4d410f26..9bf2b185d2 100644 --- a/cocos/2d/renderer/render-draw-info.ts +++ b/cocos/2d/renderer/render-draw-info.ts @@ -6,63 +6,82 @@ import { director, Material, Node } from '../../core'; import { Sampler, Texture } from '../../core/gfx'; import { Model } from '../../core/renderer/scene'; -export enum RenderDrawInfoSharedBufferView { - enabled, - count, +export enum AttrUInt8ArrayView { + DrawInfoType, + VertDirty, + IsMeshBuffer, + Stride, + Count +} + +export enum AttrUInt16ArrayView { + BufferID, + AccessorID, + Count +} + +export enum AttrUInt32ArrayView { + VertexOffset, + IndexOffset, + VBCount, + IBCount, + DataHash, + Count } export enum RenderDrawInfoType { COMP, MODEL, IA, + SUB_NODE, } export class RenderDrawInfo { - public stencilStage: Stage = Stage.DISABLED; - protected _accId: number | undefined; - protected _bufferId: number | undefined; - protected _vertexOffset: number | undefined; - protected _indexOffset: number | undefined; - protected _vb: Float32Array | undefined; - protected _ib: Uint16Array | undefined; - protected _vData: Float32Array | undefined; - protected _iData: Uint16Array | undefined; - protected _vertDirty: boolean | undefined; - protected _vbCount: number | undefined; - protected _ibCount: number | undefined; - protected _dataHash: number | undefined; - protected _isMeshBuffer: boolean | undefined; - protected _material: Material | undefined; + protected _accId = -1; + protected _bufferId = -1; + protected _vertexOffset = 0; + protected _indexOffset = 0; + protected _vb: Float32Array | null = null; + protected _ib: Uint16Array | null = null; + protected _vData: Float32Array | null = null; + protected _iData: Uint16Array | null = null; + protected _vertDirty = false; + protected _vbCount = 0; + protected _ibCount = 0; + protected _dataHash = 0; + protected _isMeshBuffer = false; + protected _material: Material | null = null; protected _texture: Texture | null = null; - protected _textureHash: number | undefined; protected _sampler: Sampler | null = null; - protected _blendHash: number | undefined; - - protected _model: Model | undefined; + protected _stride = 0; + protected _useLocal = false; + protected _model: Model | null = null; protected _drawInfoType :RenderDrawInfoType = RenderDrawInfoType.COMP; + protected _subNode: Node | null = null; protected declare _nativeObj: NativeRenderDrawInfo; + protected _uint8SharedBuffer: Uint8Array; + protected _uint16SharedBuffer: Uint16Array; + protected _uint32SharedBuffer: Uint32Array; // SharedBuffer of pos/uv/color protected declare _render2dBuffer: Float32Array; - // SharedBuffer of extra attributes - protected declare _sharedBuffer: Int32Array; - - protected _vertexCount = 0; - protected _stride = 0; - constructor (nativeDrawInfo?: NativeRenderDrawInfo) { this.init(nativeDrawInfo); + const attrSharedBuffer = this._nativeObj.getAttrSharedBufferForJS(); + let offset = 0; + this._uint8SharedBuffer = new Uint8Array(attrSharedBuffer, offset, AttrUInt8ArrayView.Count); + offset += AttrUInt8ArrayView.Count * Uint8Array.BYTES_PER_ELEMENT; + this._uint16SharedBuffer = new Uint16Array(attrSharedBuffer, offset, AttrUInt16ArrayView.Count); + offset += AttrUInt16ArrayView.Count * Uint16Array.BYTES_PER_ELEMENT; + this._uint32SharedBuffer = new Uint32Array(attrSharedBuffer, offset, AttrUInt32ArrayView.Count); } get nativeObj () { return this._nativeObj; } - // set nativeObj (val:NativeRenderDrawInfo) { - // this._nativeObj = val; - // } get render2dBuffer () { return this._render2dBuffer; @@ -74,11 +93,9 @@ export class RenderDrawInfo { this._nativeObj = nativeDrawInfo; } if (!this._nativeObj) { - this._nativeObj = new NativeRenderDrawInfo(director.root!.batcher2D.nativeObj); + this._nativeObj = new NativeRenderDrawInfo(); } } - - this.initSharedBuffer(); } public clear () { @@ -91,28 +108,31 @@ export class RenderDrawInfo { public setAccId (accId) { this._accId = accId; if (JSB) { - this._nativeObj.accId = accId; + this._uint16SharedBuffer[AttrUInt16ArrayView.AccessorID] = accId; } } public setBufferId (bufferId) { - this._bufferId = bufferId; if (JSB) { - this._nativeObj.bufferId = bufferId; + if (this._bufferId !== bufferId) { + this._uint16SharedBuffer[AttrUInt16ArrayView.BufferID] = bufferId; + this._nativeObj.changeMeshBuffer(); + } } + this._bufferId = bufferId; } public setVertexOffset (vertexOffset) { this._vertexOffset = vertexOffset; if (JSB) { - this._nativeObj.vertexOffset = vertexOffset; + this._uint32SharedBuffer[AttrUInt32ArrayView.VertexOffset] = vertexOffset; } } public setIndexOffset (indexOffset) { this._indexOffset = indexOffset; if (JSB) { - this._nativeObj.indexOffset = indexOffset; + this._uint32SharedBuffer[AttrUInt32ArrayView.IndexOffset] = indexOffset; } } @@ -142,37 +162,34 @@ export class RenderDrawInfo { public setVBCount (vbCount) { if (JSB) { - this._nativeObj.vbCount = vbCount; + this._uint32SharedBuffer[AttrUInt32ArrayView.VBCount] = vbCount; } + this._vbCount = vbCount; } public setIBCount (ibCount) { if (JSB) { - this._nativeObj.ibCount = ibCount; + this._uint32SharedBuffer[AttrUInt32ArrayView.IBCount] = ibCount; } } public setVertDirty (val: boolean) { if (JSB) { - this._nativeObj.vertDirty = val; + this._uint8SharedBuffer[AttrUInt8ArrayView.VertDirty] = val ? 1 : 0; } this._vertDirty = val; } public setDataHash (dataHash: number) { if (JSB) { - if (this._dataHash !== dataHash) { - this._nativeObj.dataHash = dataHash; - } + this._uint32SharedBuffer[AttrUInt32ArrayView.DataHash] = dataHash; } this._dataHash = dataHash; } public setIsMeshBuffer (isMeshBuffer: boolean) { if (JSB) { - if (this._isMeshBuffer !== isMeshBuffer) { - this._nativeObj.isMeshBuffer = isMeshBuffer; - } + this._uint8SharedBuffer[AttrUInt8ArrayView.IsMeshBuffer] = isMeshBuffer ? 1 : 0; } this._isMeshBuffer = isMeshBuffer; } @@ -195,15 +212,6 @@ export class RenderDrawInfo { this._texture = texture; } - public setTextureHash (textureHash: number) { - if (JSB) { - if (this._textureHash !== textureHash) { - this._nativeObj.textureHash = textureHash; - } - } - this._textureHash = textureHash; - } - public setSampler (sampler: Sampler | null) { if (JSB) { if (this._sampler !== sampler) { @@ -213,15 +221,6 @@ export class RenderDrawInfo { this._sampler = sampler; } - public setBlendHash (blendHash: number) { - if (JSB) { - if (this._blendHash !== blendHash) { - this._nativeObj.blendHash = blendHash; - } - } - this._blendHash = blendHash; - } - public setModel (model: Model) { if (JSB) { if (this._model !== model) { @@ -233,23 +232,38 @@ export class RenderDrawInfo { public setDrawInfoType (drawInfoType: RenderDrawInfoType) { if (JSB) { if (this._drawInfoType !== drawInfoType) { - this._nativeObj.drawInfoType = drawInfoType; + this._uint8SharedBuffer[AttrUInt8ArrayView.DrawInfoType] = drawInfoType; } } this._drawInfoType = drawInfoType; } - public initRender2dBuffer (vertexCount: number, stride: number) { + public setSubNode (node : Node) { if (JSB) { - this._stride = stride; - this._vertexCount = vertexCount; - this._render2dBuffer = new Float32Array(vertexCount * stride); + if (this._subNode !== node) { + this._nativeObj.subNode = node; + } + } + this._subNode = node; + } + + public setStride (stride: number) { + if (JSB) { + this._uint8SharedBuffer[AttrUInt8ArrayView.Stride] = stride; + } + this._stride = stride; + } + + public initRender2dBuffer () { + if (JSB) { + this._render2dBuffer = new Float32Array(this._vbCount * this._stride); + this._nativeObj.setRender2dBufferToNative(this._render2dBuffer); } } public fillRender2dBuffer (vertexDataArr: IRenderData[]) { if (JSB) { - const fillLength = Math.min(this._vertexCount, vertexDataArr.length); + const fillLength = Math.min(this._vbCount, vertexDataArr.length); let bufferOffset = 0; for (let i = 0; i < fillLength; i++) { this.updateVertexBuffer(bufferOffset, vertexDataArr[i]); @@ -275,17 +289,4 @@ export class RenderDrawInfo { this._render2dBuffer[bufferOffset++] = temp.color.a; } } - - public setRender2dBufferToNative () { - if (JSB) { - this._nativeObj.setRender2dBufferToNative(this._render2dBuffer, this._stride, this._vertexCount * this._stride); - } - } - - private initSharedBuffer () { - if (JSB) { - //this._sharedBuffer = new Int32Array(RenderDrawInfoSharedBufferView.count); - this._sharedBuffer = new Int32Array(this._nativeObj.getAttrSharedBufferForJS()); - } - } } diff --git a/cocos/2d/renderer/render-entity.ts b/cocos/2d/renderer/render-entity.ts index 2faffde36b..2cfc5c0feb 100644 --- a/cocos/2d/renderer/render-entity.ts +++ b/cocos/2d/renderer/render-entity.ts @@ -1,6 +1,5 @@ import { JSB } from 'internal:constants'; import { NativeRenderEntity } from './native-2d'; -import { UIRenderer } from '../framework/ui-renderer'; import { Batcher2D } from './batcher-2d'; import { RenderData } from './render-data'; import { RenderDrawInfo } from './render-draw-info'; @@ -11,6 +10,7 @@ import { Stage } from './stencil-manager'; export enum RenderEntityType { STATIC, DYNAMIC, + CROSSED, } export enum RenderEntityFloatSharedBufferView { @@ -23,17 +23,25 @@ export enum RenderEntityUInt8SharedBufferView { colorG, colorB, colorA, + maskMode, count, } export enum RenderEntityBoolSharedBufferView{ colorDirty, enabled, - padding0, - padding1, + useLocal, count, } +export enum MaskMode { + NONE, + MASK, + MASK_INVERTED, + MASK_NODE, + MASK_NODE_INVERTED +} + export class RenderEntity { private _renderEntityType: RenderEntityType = RenderEntityType.STATIC; @@ -41,13 +49,8 @@ export class RenderEntity { protected _node: Node | null = null; protected _stencilStage: Stage = Stage.DISABLED; - - // is it entity a mask node - protected _isMask = false; - // is it entity a sub mask node - protected _isSubMask = false; - // is mask inverted - protected _isMaskInverted = false; + protected _useLocal = false; + protected _maskMode = MaskMode.NONE; protected declare _floatSharedBuffer: Float32Array; protected declare _uint8SharedBuffer: Uint8Array; @@ -119,10 +122,9 @@ export class RenderEntity { constructor (entityType: RenderEntityType) { if (JSB) { if (!this._nativeObj) { - this._nativeObj = new NativeRenderEntity(director.root!.batcher2D.nativeObj); + this._nativeObj = new NativeRenderEntity(entityType); } - this.setRenderEntityType(entityType); - + this._renderEntityType = entityType; this.initSharedBuffer(); } } @@ -164,6 +166,13 @@ export class RenderEntity { } } + public setMaskMode (mode: MaskMode) { + if (JSB) { + this._uint8SharedBuffer[RenderEntityUInt8SharedBufferView.maskMode] = mode; + } + this._maskMode = mode; + } + public getStaticRenderDrawInfo (): RenderDrawInfo | null { if (JSB) { const nativeDrawInfo = this._nativeObj.getStaticRenderDrawInfo(this._nativeObj.staticDrawInfoSize++); @@ -173,33 +182,6 @@ export class RenderEntity { return null; } - setIsMask (val:boolean) { - if (JSB) { - if (this._isMask !== val) { - this._nativeObj.isMask = val; - } - } - this._isMask = val; - } - - setIsSubMask (val:boolean) { - if (JSB) { - if (this._isSubMask !== val) { - this._nativeObj.isSubMask = val; - } - } - this._isSubMask = val; - } - - setIsMaskInverted (val:boolean) { - if (JSB) { - if (this._isMaskInverted !== val) { - this._nativeObj.isMaskInverted = val; - } - } - this._isMaskInverted = val; - } - setNode (node: Node | null) { if (JSB) { if (this._node !== node) { @@ -218,13 +200,11 @@ export class RenderEntity { this._stencilStage = stage; } - setRenderEntityType (type: RenderEntityType) { + setUseLocal (useLocal: boolean) { if (JSB) { - if (this._renderEntityType !== type) { - this._nativeObj.setRenderEntityType(type); - } + this._boolSharedBuffer[RenderEntityBoolSharedBufferView.useLocal] = useLocal ? 1 : 0; } - this._renderEntityType = type; + this._useLocal = useLocal; } private initSharedBuffer () { diff --git a/cocos/2d/utils/dynamic-atlas/atlas-manager.ts b/cocos/2d/utils/dynamic-atlas/atlas-manager.ts index 3c84eb9010..1a8d60d23c 100644 --- a/cocos/2d/utils/dynamic-atlas/atlas-manager.ts +++ b/cocos/2d/utils/dynamic-atlas/atlas-manager.ts @@ -240,7 +240,7 @@ export class DynamicAtlasManager extends System { * @param frame the sprite frame that will be packed in the dynamic atlas. */ public packToDynamicAtlas (comp, frame) { - if (EDITOR && !legacyCC.GAME_VIEW) return; + if ((EDITOR && !legacyCC.GAME_VIEW) || !this._enabled) return; if (frame && !frame._original && frame.packable && frame.texture && frame.texture.width > 0 && frame.texture.height > 0) { const packedFrame = this.insertSpriteFrame(frame); diff --git a/cocos/core/assets/asset.jsb.ts b/cocos/core/assets/asset.jsb.ts index fdda2fd2ac..5c34eda92b 100644 --- a/cocos/core/assets/asset.jsb.ts +++ b/cocos/core/assets/asset.jsb.ts @@ -31,6 +31,7 @@ import { createMap } from '../utils/js-typed'; import { property } from '../data/class-decorator'; import { getUrlWithUuid } from '../asset-manager/helper'; import { extname } from '../utils/path'; +import { ExtraEventMethods } from '../utils/jsb-utils' import '../data/object'; declare const jsb: any; @@ -41,7 +42,7 @@ declare const jsb: any; */ export type CreateNodeCallback = (error: Error | null, node: Node) => void; -applyMixins(jsb.Asset, [CallbacksInvoker]); +applyMixins(jsb.Asset, [CallbacksInvoker, ExtraEventMethods]); const assetProto: any = jsb.Asset.prototype; diff --git a/cocos/core/assets/effect-asset.ts b/cocos/core/assets/effect-asset.ts index 1f4438c0ce..4f020585f0 100644 --- a/cocos/core/assets/effect-asset.ts +++ b/cocos/core/assets/effect-asset.ts @@ -33,6 +33,7 @@ import { MacroRecord } from '../renderer/core/pass-utils'; import { programLib } from '../renderer/core/program-lib'; import { Asset } from './asset'; import { legacyCC } from '../global-exports'; +import { warnID } from '../platform/debug'; export declare namespace EffectAsset { export interface IPropertyInfo { @@ -163,6 +164,30 @@ export declare namespace EffectAsset { } } +const legacyBuiltinEffectNames = [ + 'planar-shadow', + 'skybox', + 'deferred-lighting', + 'bloom', + 'post-process', + 'profiler', + 'splash-screen', + 'standard', + 'unlit', + 'sprite', + 'particle', + 'particle-gpu', + 'particle-trail', + 'billboard', + 'terrain', + 'graphics', + 'clear-stencil', + 'spine', + 'occlusion-query', + 'geometry-renderer', + 'debug-renderer', +]; + /** * @en Effect asset is the base template for instantiating material, all effects should be unique globally. * All effects are managed in a static map of EffectAsset. @@ -211,6 +236,9 @@ export class EffectAsset extends Asset { return EffectAsset._effects[n]; } } + if (legacyBuiltinEffectNames.includes(name)) { + warnID(16101, name); + } return null; } diff --git a/cocos/core/assets/texture-cube.jsb.ts b/cocos/core/assets/texture-cube.jsb.ts index 4eed88162d..4b5f4d666a 100644 --- a/cocos/core/assets/texture-cube.jsb.ts +++ b/cocos/core/assets/texture-cube.jsb.ts @@ -27,6 +27,7 @@ import { legacyCC } from '../global-exports'; import { Filter, PixelFormat, WrapMode } from './asset-enum'; import { js } from '../utils/js'; import './simple-texture'; +import { EDITOR, TEST } from 'internal:constants'; const textureCubeProto: any = jsb.TextureCube.prototype; interface ITextureCubeSerializeData { @@ -67,6 +68,9 @@ enum MipmapMode { } textureCubeProto.createNode = null!; +declare const jsb: any; + +// @ts-expect-error jsb.TextureCube is exported from cpp export type TextureCube = jsb.TextureCube; export const TextureCube: any = jsb.TextureCube; @@ -80,15 +84,6 @@ textureCubeProto._ctor = function () { this._mipmapAtlas = null; }; -function _forEachFace (mipmap, callback: (face, faceIndex) => void) { - callback(mipmap.front, FaceIndex.front); - callback(mipmap.back, FaceIndex.back); - callback(mipmap.left, FaceIndex.left); - callback(mipmap.right, FaceIndex.right); - callback(mipmap.top, FaceIndex.top); - callback(mipmap.bottom, FaceIndex.bottom); -} - Object.defineProperty(textureCubeProto, 'mipmaps', { get () { return this._mipmaps; @@ -96,27 +91,6 @@ Object.defineProperty(textureCubeProto, 'mipmaps', { set (value) { this._mipmaps = value; this.setMipmaps(value); - this.mipmapLevel = this._mipmaps.length; - if (this._mipmaps.length > 0) { - const imageAsset = this._mipmaps[0].front; - this.reset({ - width: imageAsset.width, - height: imageAsset.height, - format: imageAsset.format, - mipmapLevel: this._mipmaps.length, - }); - this._mipmaps.forEach((mipmap, level) => { - _forEachFace(mipmap, (face, faceIndex) => { - this.assignImage(face, level, faceIndex); - }); - }); - } else { - this.reset({ - width: 0, - height: 0, - mipmapLevel: this._mipmaps.length, - }); - } } }); @@ -200,7 +174,9 @@ textureCubeProto._deserialize = function (serializedData: ITextureCubeSerializeD const data = serializedData; jsb.TextureBase.prototype._deserialize.call(this, data.base, handle); this.isRGBE = data.rgbe; - this._mipmapMode = parseInt(data.mipmapMode); + if (data.mipmapMode != undefined) { + this._mipmapMode = data.mipmapMode; + } if (this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP) { const mipmapAtlas = data.mipmapAtlas; const mipmapLayout = data.mipmapLayout; diff --git a/cocos/core/components/component.ts b/cocos/core/components/component.ts index ad0d2c63cb..6bd3d02b8a 100644 --- a/cocos/core/components/component.ts +++ b/cocos/core/components/component.ts @@ -748,7 +748,7 @@ value(Component, '_registerEditorProps', (cls, props) => { { const frame = RF.peek(); let menu = val; - if (frame) { + if (frame && !menu.includes('/')) { menu = `i18n:menu.custom_script/${menu}`; } diff --git a/cocos/core/components/renderer.ts b/cocos/core/components/renderer.ts index bee78aefd0..0d4f7c57eb 100644 --- a/cocos/core/components/renderer.ts +++ b/cocos/core/components/renderer.ts @@ -25,7 +25,7 @@ import { EDITOR } from 'internal:constants'; import { - ccclass, type, displayOrder, displayName, serializable, + ccclass, type, displayOrder, displayName, serializable, disallowMultiple, } from 'cc.decorator'; import { Material } from '../assets/material'; import { Component } from './component'; @@ -55,6 +55,7 @@ const _matInsInfo: IMaterialInstanceInfo = { * 默认情况下,渲染组件使用共享材质进行渲染,材质实例也不会被创建出来。仅在用户通过 [[material]],[[materials]] 和 [[getMaterialInstance]] 接口获取材质时才会创建材质实例。 */ @ccclass('cc.Renderer') +@disallowMultiple export class Renderer extends Component { /** * @en Get the default shared material diff --git a/cocos/core/data/class.ts b/cocos/core/data/class.ts index f5370ab9af..c5a9c32306 100644 --- a/cocos/core/data/class.ts +++ b/cocos/core/data/class.ts @@ -359,6 +359,8 @@ export function isCCClassOrFastDefined (constructor: Constructor) { return constructor?.hasOwnProperty?.('__values__'); } +CCClass.isCCClassOrFastDefined = isCCClassOrFastDefined; + /** * Return all super classes. * @param constructor The Constructor. diff --git a/cocos/core/game.ts b/cocos/core/game.ts index e7d7cd2684..56915eabff 100644 --- a/cocos/core/game.ts +++ b/cocos/core/game.ts @@ -24,7 +24,7 @@ THE SOFTWARE. */ -import { EDITOR, HTML5, JSB, NATIVE, PREVIEW, RUNTIME_BASED, TEST } from 'internal:constants'; +import { BUILD, DEBUG, EDITOR, HTML5, JSB, NATIVE, PREVIEW, RUNTIME_BASED, TEST } from 'internal:constants'; import { systemInfo } from 'pal/system-info'; import { findCanvas, loadJsFile } from 'pal/env'; import { Pacer } from 'pal/pacer'; @@ -673,6 +673,9 @@ export class Game extends EventTarget { return this.onPreBaseInitDelegate.dispatch(); }) .then(() => { + if (DEBUG) { + console.time('Init Base'); + } const debugMode = config.debugMode || debug.DebugMode.NONE; debug._resetDebugSetting(debugMode); sys.init(); @@ -680,6 +683,9 @@ export class Game extends EventTarget { }) .then(() => settings.init(config.settingsPath, config.overrideSettings)) .then(() => { + if (DEBUG) { + console.timeEnd('Init Base'); + } this.emit(Game.EVENT_POST_BASE_INIT); return this.onPostBaseInitDelegate.dispatch(); }) @@ -690,6 +696,9 @@ export class Game extends EventTarget { return this.onPreInfrastructureInitDelegate.dispatch(); }) .then(() => { + if (DEBUG) { + console.time('Init Infrastructure'); + } macro.init(); const adapter = findCanvas(); if (adapter) { @@ -704,6 +713,9 @@ export class Game extends EventTarget { builtinResMgr.init(); Layers.init(); this.initPacer(); + if (DEBUG) { + console.timeEnd('Init Infrastructure'); + } }) .then(() => { this.emit(Game.EVENT_POST_INFRASTRUCTURE_INIT); @@ -715,9 +727,17 @@ export class Game extends EventTarget { this.emit(Game.EVENT_PRE_SUBSYSTEM_INIT); return this.onPreSubsystemInitDelegate.dispatch(); }) - .then(() => director.init()) - .then(() => builtinResMgr.loadBuiltinAssets()) .then(() => { + if (DEBUG) { + console.time('Init SubSystem'); + } + director.init(); + return builtinResMgr.loadBuiltinAssets(); + }) + .then(() => { + if (DEBUG) { + console.timeEnd('Init SubSystem'); + } this.emit(Game.EVENT_POST_SUBSYSTEM_INIT); return this.onPostSubsystemInitDelegate.dispatch(); }) @@ -733,6 +753,9 @@ export class Game extends EventTarget { return this.onPreProjectInitDelegate.dispatch(); }) .then(() => { + if (DEBUG) { + console.time('Init Project'); + } const jsList = settings.querySettings(Settings.Category.PLUGINS, 'jsList'); let promise = Promise.resolve(); if (jsList) { @@ -753,9 +776,14 @@ export class Game extends EventTarget { .then(() => this._loadProjectBundles()) .then(() => this._setupRenderPipeline()) .then(() => this._loadPreloadAssets()) - .then(() => builtinResMgr.compileBuiltinMaterial()) - .then(() => SplashScreen.instance.init()) .then(() => { + builtinResMgr.compileBuiltinMaterial(); + return SplashScreen.instance.init(); + }) + .then(() => { + if (DEBUG) { + console.timeEnd('Init Project'); + } this.emit(Game.EVENT_POST_PROJECT_INIT); return this.onPostProjectInitDelegate.dispatch(); }) diff --git a/cocos/core/gfx/base/define.ts b/cocos/core/gfx/base/define.ts index 69d9da2964..5a6e18a55f 100644 --- a/cocos/core/gfx/base/define.ts +++ b/cocos/core/gfx/base/define.ts @@ -32,6 +32,8 @@ import { DescriptorSetLayout } from './descriptor-set-layout'; import { Sampler } from './states/sampler'; import { GeneralBarrier } from './states/general-barrier'; +import { TextureBarrier } from './states/texture-barrier'; +import { BufferBarrier } from './states/buffer-barrier'; import { GCObject } from '../../data/gc-object'; interface ICopyable { copy (info: ICopyable): ICopyable; } @@ -679,6 +681,15 @@ export enum BarrierType { SPLIT_END, } +export enum PassType { + RASTER, + COMPUTE, + COPY, + MOVE, + RAYTRACE, + PRESENT, +} + export type BufferUsage = BufferUsageBit; export type BufferFlags = BufferFlagBit; export type MemoryAccess = MemoryAccessBit; @@ -763,6 +774,19 @@ export class DeviceCaps { } } +export class DeviceOptions { + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + + constructor ( + public enableBarrierDeduce: boolean = true, + ) {} + + public copy (info: Readonly) { + this.enableBarrierDeduce = info.enableBarrierDeduce; + return this; + } +} + export class Offset { declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object @@ -1535,13 +1559,25 @@ export class SubpassDependency { constructor ( public srcSubpass: number = 0, public dstSubpass: number = 0, - public barrier: GeneralBarrier = null!, + public generalBarrier: GeneralBarrier = null!, + public bufferBarriers: BufferBarrier = null!, + public buffers: Buffer = null!, + public bufferBarrierCount: number = 0, + public textureBarriers: TextureBarrier = null!, + public textures: Texture = null!, + public textureBarrierCount: number = 0, ) {} public copy (info: Readonly) { this.srcSubpass = info.srcSubpass; this.dstSubpass = info.dstSubpass; - this.barrier = info.barrier; + this.generalBarrier = info.generalBarrier; + this.bufferBarriers = info.bufferBarriers; + this.buffers = info.buffers; + this.bufferBarrierCount = info.bufferBarrierCount; + this.textureBarriers = info.textureBarriers; + this.textures = info.textures; + this.textureBarrierCount = info.textureBarrierCount; return this; } } @@ -2086,95 +2122,95 @@ export function FormatSize (format: Format, width: number, height: number, depth return (width * height * depth * FormatInfos[format].size); } else { switch (format) { - case Format.BC1: - case Format.BC1_ALPHA: - case Format.BC1_SRGB: - case Format.BC1_SRGB_ALPHA: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; - case Format.BC2: - case Format.BC2_SRGB: - case Format.BC3: - case Format.BC3_SRGB: - case Format.BC4: - case Format.BC4_SNORM: - case Format.BC6H_SF16: - case Format.BC6H_UF16: - case Format.BC7: - case Format.BC7_SRGB: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; - case Format.BC5: - case Format.BC5_SNORM: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 32 * depth; + case Format.BC1: + case Format.BC1_ALPHA: + case Format.BC1_SRGB: + case Format.BC1_SRGB_ALPHA: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; + case Format.BC2: + case Format.BC2_SRGB: + case Format.BC3: + case Format.BC3_SRGB: + case Format.BC4: + case Format.BC4_SNORM: + case Format.BC6H_SF16: + case Format.BC6H_UF16: + case Format.BC7: + case Format.BC7_SRGB: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; + case Format.BC5: + case Format.BC5_SNORM: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 32 * depth; - case Format.ETC_RGB8: - case Format.ETC2_RGB8: - case Format.ETC2_SRGB8: - case Format.ETC2_RGB8_A1: - case Format.EAC_R11: - case Format.EAC_R11SN: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; - case Format.ETC2_RGBA8: - case Format.ETC2_SRGB8_A1: - case Format.EAC_RG11: - case Format.EAC_RG11SN: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; + case Format.ETC_RGB8: + case Format.ETC2_RGB8: + case Format.ETC2_SRGB8: + case Format.ETC2_RGB8_A1: + case Format.EAC_R11: + case Format.EAC_R11SN: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; + case Format.ETC2_RGBA8: + case Format.ETC2_SRGB8_A1: + case Format.EAC_RG11: + case Format.EAC_RG11SN: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; - case Format.PVRTC_RGB2: - case Format.PVRTC_RGBA2: - case Format.PVRTC2_2BPP: - return Math.ceil(width / 8) * Math.ceil(height / 4) * 8 * depth; + case Format.PVRTC_RGB2: + case Format.PVRTC_RGBA2: + case Format.PVRTC2_2BPP: + return Math.ceil(width / 8) * Math.ceil(height / 4) * 8 * depth; - case Format.PVRTC_RGB4: - case Format.PVRTC_RGBA4: - case Format.PVRTC2_4BPP: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; + case Format.PVRTC_RGB4: + case Format.PVRTC_RGBA4: + case Format.PVRTC2_4BPP: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; - case Format.ASTC_RGBA_4X4: - case Format.ASTC_SRGBA_4X4: - return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; - case Format.ASTC_RGBA_5X4: - case Format.ASTC_SRGBA_5X4: - return Math.ceil(width / 5) * Math.ceil(height / 4) * 16 * depth; - case Format.ASTC_RGBA_5X5: - case Format.ASTC_SRGBA_5X5: - return Math.ceil(width / 5) * Math.ceil(height / 5) * 16 * depth; - case Format.ASTC_RGBA_6X5: - case Format.ASTC_SRGBA_6X5: - return Math.ceil(width / 6) * Math.ceil(height / 5) * 16 * depth; - case Format.ASTC_RGBA_6X6: - case Format.ASTC_SRGBA_6X6: - return Math.ceil(width / 6) * Math.ceil(height / 6) * 16 * depth; - case Format.ASTC_RGBA_8X5: - case Format.ASTC_SRGBA_8X5: - return Math.ceil(width / 8) * Math.ceil(height / 5) * 16 * depth; - case Format.ASTC_RGBA_8X6: - case Format.ASTC_SRGBA_8X6: - return Math.ceil(width / 8) * Math.ceil(height / 6) * 16 * depth; - case Format.ASTC_RGBA_8X8: - case Format.ASTC_SRGBA_8X8: - return Math.ceil(width / 8) * Math.ceil(height / 8) * 16 * depth; - case Format.ASTC_RGBA_10X5: - case Format.ASTC_SRGBA_10X5: - return Math.ceil(width / 10) * Math.ceil(height / 5) * 16 * depth; - case Format.ASTC_RGBA_10X6: - case Format.ASTC_SRGBA_10X6: - return Math.ceil(width / 10) * Math.ceil(height / 6) * 16 * depth; - case Format.ASTC_RGBA_10X8: - case Format.ASTC_SRGBA_10X8: - return Math.ceil(width / 10) * Math.ceil(height / 8) * 16 * depth; - case Format.ASTC_RGBA_10X10: - case Format.ASTC_SRGBA_10X10: - return Math.ceil(width / 10) * Math.ceil(height / 10) * 16 * depth; - case Format.ASTC_RGBA_12X10: - case Format.ASTC_SRGBA_12X10: - return Math.ceil(width / 12) * Math.ceil(height / 10) * 16 * depth; - case Format.ASTC_RGBA_12X12: - case Format.ASTC_SRGBA_12X12: - return Math.ceil(width / 12) * Math.ceil(height / 12) * 16 * depth; + case Format.ASTC_RGBA_4X4: + case Format.ASTC_SRGBA_4X4: + return Math.ceil(width / 4) * Math.ceil(height / 4) * 16 * depth; + case Format.ASTC_RGBA_5X4: + case Format.ASTC_SRGBA_5X4: + return Math.ceil(width / 5) * Math.ceil(height / 4) * 16 * depth; + case Format.ASTC_RGBA_5X5: + case Format.ASTC_SRGBA_5X5: + return Math.ceil(width / 5) * Math.ceil(height / 5) * 16 * depth; + case Format.ASTC_RGBA_6X5: + case Format.ASTC_SRGBA_6X5: + return Math.ceil(width / 6) * Math.ceil(height / 5) * 16 * depth; + case Format.ASTC_RGBA_6X6: + case Format.ASTC_SRGBA_6X6: + return Math.ceil(width / 6) * Math.ceil(height / 6) * 16 * depth; + case Format.ASTC_RGBA_8X5: + case Format.ASTC_SRGBA_8X5: + return Math.ceil(width / 8) * Math.ceil(height / 5) * 16 * depth; + case Format.ASTC_RGBA_8X6: + case Format.ASTC_SRGBA_8X6: + return Math.ceil(width / 8) * Math.ceil(height / 6) * 16 * depth; + case Format.ASTC_RGBA_8X8: + case Format.ASTC_SRGBA_8X8: + return Math.ceil(width / 8) * Math.ceil(height / 8) * 16 * depth; + case Format.ASTC_RGBA_10X5: + case Format.ASTC_SRGBA_10X5: + return Math.ceil(width / 10) * Math.ceil(height / 5) * 16 * depth; + case Format.ASTC_RGBA_10X6: + case Format.ASTC_SRGBA_10X6: + return Math.ceil(width / 10) * Math.ceil(height / 6) * 16 * depth; + case Format.ASTC_RGBA_10X8: + case Format.ASTC_SRGBA_10X8: + return Math.ceil(width / 10) * Math.ceil(height / 8) * 16 * depth; + case Format.ASTC_RGBA_10X10: + case Format.ASTC_SRGBA_10X10: + return Math.ceil(width / 10) * Math.ceil(height / 10) * 16 * depth; + case Format.ASTC_RGBA_12X10: + case Format.ASTC_SRGBA_12X10: + return Math.ceil(width / 12) * Math.ceil(height / 10) * 16 * depth; + case Format.ASTC_RGBA_12X12: + case Format.ASTC_SRGBA_12X12: + return Math.ceil(width / 12) * Math.ceil(height / 12) * 16 * depth; - default: { - return 0; - } + default: { + return 0; + } } } } @@ -2253,30 +2289,30 @@ export function getTypedArrayConstructor (info: FormatInfo): TypedArrayConstruct } const stride = info.size / info.count; switch (info.type) { - case FormatType.UNORM: - case FormatType.UINT: { - switch (stride) { - case 1: return Uint8Array; - case 2: return Uint16Array; - case 4: return Uint32Array; - default: - return Uint8Array; + case FormatType.UNORM: + case FormatType.UINT: { + switch (stride) { + case 1: return Uint8Array; + case 2: return Uint16Array; + case 4: return Uint32Array; + default: + return Uint8Array; + } } - } - case FormatType.SNORM: - case FormatType.INT: { - switch (stride) { - case 1: return Int8Array; - case 2: return Int16Array; - case 4: return Int32Array; - default: - return Int8Array; + case FormatType.SNORM: + case FormatType.INT: { + switch (stride) { + case 1: return Int8Array; + case 2: return Int16Array; + case 4: return Int32Array; + default: + return Int8Array; + } } - } - case FormatType.FLOAT: { - return Float32Array; - } - default: + case FormatType.FLOAT: { + return Float32Array; + } + default: } return Float32Array; } @@ -2286,93 +2322,93 @@ export interface FormatAlignment { height: number, // default 1 } -export function formatAlignment (format: Format) : FormatAlignment { +export function formatAlignment (format: Format): FormatAlignment { switch (format) { - case Format.BC1: - case Format.BC1_ALPHA: - case Format.BC1_SRGB: - case Format.BC1_SRGB_ALPHA: - case Format.BC2: - case Format.BC2_SRGB: - case Format.BC3: - case Format.BC3_SRGB: - case Format.BC4: - case Format.BC4_SNORM: - case Format.BC6H_SF16: - case Format.BC6H_UF16: - case Format.BC7: - case Format.BC7_SRGB: - case Format.BC5: - case Format.BC5_SNORM: - case Format.ETC_RGB8: - case Format.ETC2_RGB8: - case Format.ETC2_SRGB8: - case Format.ETC2_RGB8_A1: - case Format.EAC_R11: - case Format.EAC_R11SN: - case Format.ETC2_RGBA8: - case Format.ETC2_SRGB8_A1: - case Format.EAC_RG11: - case Format.EAC_RG11SN: - return { width: 4, height: 4 }; + case Format.BC1: + case Format.BC1_ALPHA: + case Format.BC1_SRGB: + case Format.BC1_SRGB_ALPHA: + case Format.BC2: + case Format.BC2_SRGB: + case Format.BC3: + case Format.BC3_SRGB: + case Format.BC4: + case Format.BC4_SNORM: + case Format.BC6H_SF16: + case Format.BC6H_UF16: + case Format.BC7: + case Format.BC7_SRGB: + case Format.BC5: + case Format.BC5_SNORM: + case Format.ETC_RGB8: + case Format.ETC2_RGB8: + case Format.ETC2_SRGB8: + case Format.ETC2_RGB8_A1: + case Format.EAC_R11: + case Format.EAC_R11SN: + case Format.ETC2_RGBA8: + case Format.ETC2_SRGB8_A1: + case Format.EAC_RG11: + case Format.EAC_RG11SN: + return { width: 4, height: 4 }; - case Format.PVRTC_RGB2: - case Format.PVRTC_RGBA2: - case Format.PVRTC2_2BPP: - return { width: 8, height: 4 }; + case Format.PVRTC_RGB2: + case Format.PVRTC_RGBA2: + case Format.PVRTC2_2BPP: + return { width: 8, height: 4 }; - case Format.PVRTC_RGB4: - case Format.PVRTC_RGBA4: - case Format.PVRTC2_4BPP: - return { width: 4, height: 4 }; + case Format.PVRTC_RGB4: + case Format.PVRTC_RGBA4: + case Format.PVRTC2_4BPP: + return { width: 4, height: 4 }; - case Format.ASTC_RGBA_4X4: - case Format.ASTC_SRGBA_4X4: - return { width: 4, height: 4 }; - case Format.ASTC_RGBA_5X4: - case Format.ASTC_SRGBA_5X4: - return { width: 5, height: 4 }; - case Format.ASTC_RGBA_5X5: - case Format.ASTC_SRGBA_5X5: - return { width: 5, height: 5 }; - case Format.ASTC_RGBA_6X5: - case Format.ASTC_SRGBA_6X5: - return { width: 6, height: 5 }; - case Format.ASTC_RGBA_6X6: - case Format.ASTC_SRGBA_6X6: - return { width: 6, height: 6 }; - case Format.ASTC_RGBA_8X5: - case Format.ASTC_SRGBA_8X5: - return { width: 8, height: 5 }; - case Format.ASTC_RGBA_8X6: - case Format.ASTC_SRGBA_8X6: - return { width: 8, height: 6 }; - case Format.ASTC_RGBA_8X8: - case Format.ASTC_SRGBA_8X8: - return { width: 8, height: 8 }; - case Format.ASTC_RGBA_10X5: - case Format.ASTC_SRGBA_10X5: - return { width: 10, height: 5 }; - case Format.ASTC_RGBA_10X6: - case Format.ASTC_SRGBA_10X6: - return { width: 10, height: 6 }; - case Format.ASTC_RGBA_10X8: - case Format.ASTC_SRGBA_10X8: - return { width: 10, height: 8 }; - case Format.ASTC_RGBA_10X10: - case Format.ASTC_SRGBA_10X10: - return { width: 10, height: 10 }; - case Format.ASTC_RGBA_12X10: - case Format.ASTC_SRGBA_12X10: - return { width: 12, height: 10 }; - case Format.ASTC_RGBA_12X12: - case Format.ASTC_SRGBA_12X12: - return { width: 12, height: 12 }; - default: - return { width: 1, height: 1 }; + case Format.ASTC_RGBA_4X4: + case Format.ASTC_SRGBA_4X4: + return { width: 4, height: 4 }; + case Format.ASTC_RGBA_5X4: + case Format.ASTC_SRGBA_5X4: + return { width: 5, height: 4 }; + case Format.ASTC_RGBA_5X5: + case Format.ASTC_SRGBA_5X5: + return { width: 5, height: 5 }; + case Format.ASTC_RGBA_6X5: + case Format.ASTC_SRGBA_6X5: + return { width: 6, height: 5 }; + case Format.ASTC_RGBA_6X6: + case Format.ASTC_SRGBA_6X6: + return { width: 6, height: 6 }; + case Format.ASTC_RGBA_8X5: + case Format.ASTC_SRGBA_8X5: + return { width: 8, height: 5 }; + case Format.ASTC_RGBA_8X6: + case Format.ASTC_SRGBA_8X6: + return { width: 8, height: 6 }; + case Format.ASTC_RGBA_8X8: + case Format.ASTC_SRGBA_8X8: + return { width: 8, height: 8 }; + case Format.ASTC_RGBA_10X5: + case Format.ASTC_SRGBA_10X5: + return { width: 10, height: 5 }; + case Format.ASTC_RGBA_10X6: + case Format.ASTC_SRGBA_10X6: + return { width: 10, height: 6 }; + case Format.ASTC_RGBA_10X8: + case Format.ASTC_SRGBA_10X8: + return { width: 10, height: 8 }; + case Format.ASTC_RGBA_10X10: + case Format.ASTC_SRGBA_10X10: + return { width: 10, height: 10 }; + case Format.ASTC_RGBA_12X10: + case Format.ASTC_SRGBA_12X10: + return { width: 12, height: 10 }; + case Format.ASTC_RGBA_12X12: + case Format.ASTC_SRGBA_12X12: + return { width: 12, height: 12 }; + default: + return { width: 1, height: 1 }; } } -export function alignTo (size: number, alignment: number) : number { +export function alignTo (size: number, alignment: number): number { return Math.ceil(size / alignment) * alignment; } diff --git a/cocos/core/gfx/base/input-assembler.ts b/cocos/core/gfx/base/input-assembler.ts index 9f21f956e4..1d60f29b25 100644 --- a/cocos/core/gfx/base/input-assembler.ts +++ b/cocos/core/gfx/base/input-assembler.ts @@ -195,7 +195,7 @@ export abstract class InputAssembler extends GFXObject { let res = 'attrs'; for (let i = 0; i < this.attributes.length; ++i) { const at = this.attributes[i]; - res += `,${at.name},${at.format},${at.isNormalized},${at.stream},${at.isInstanced}`; + res += `,${at.name},${at.format},${at.isNormalized},${at.stream},${at.isInstanced},${at.location}`; } return murmurhash2_32_gc(res, 666); } diff --git a/cocos/core/index.ts b/cocos/core/index.ts index 308a71d09f..11604930e2 100644 --- a/cocos/core/index.ts +++ b/cocos/core/index.ts @@ -60,3 +60,5 @@ export * from './components'; export * from './builtin'; export * from './curves'; export * from './settings'; + +export * from './pipeline/custom/builtin-pipelines'; diff --git a/cocos/core/pipeline/custom/builtin-pipelines.ts b/cocos/core/pipeline/custom/builtin-pipelines.ts new file mode 100644 index 0000000000..bd06683baa --- /dev/null +++ b/cocos/core/pipeline/custom/builtin-pipelines.ts @@ -0,0 +1,453 @@ +import { Material } from '../../assets'; +import { intersect, Sphere } from '../../geometry'; +import { ClearFlagBit, Color, Format, LoadOp, Rect, StoreOp, Viewport } from '../../gfx'; +import { macro } from '../../platform'; +import { Camera, CSMLevel, DirectionalLight, Light, LightType, ShadowType, SKYBOX_FLAG, SpotLight } from '../../renderer/scene'; +import { supportsR32FloatTexture } from '../define'; +import { SRGBToLinear } from '../pipeline-funcs'; +import { AccessType, AttachmentType, ComputeView, LightInfo, QueueHint, RasterView, ResourceResidency, SceneFlags } from './types'; +import { Pipeline, PipelineBuilder } from './pipeline'; + +export function getRenderArea (camera: Camera, width: number, height: number, light: Light | null = null, level = 0): Rect { + const out = new Rect(); + const vp = camera.viewport; + const w = width; + const h = height; + out.x = vp.x * w; + out.y = vp.y * h; + out.width = vp.width * w; + out.height = vp.height * h; + if (light) { + switch (light.type) { + case LightType.DIRECTIONAL: { + const mainLight = light as DirectionalLight; + if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1) { + out.x = 0; + out.y = 0; + out.width = w; + out.height = h; + } else { + out.x = level % 2 * 0.5 * w; + out.y = (1 - Math.floor(level / 2)) * 0.5 * h; + out.width = 0.5 * w; + out.height = 0.5 * h; + } + break; + } + case LightType.SPOT: { + out.x = 0; + out.y = 0; + out.width = w; + out.height = h; + break; + } + default: + } + } + return out; +} + +export function buildShadowPass (passName: Readonly, + ppl: Pipeline, + camera: Camera, light: Light, level: number, + width: Readonly, height: Readonly) { + const device = ppl.device; + const shadowMapName = passName; + if (!ppl.containsResource(shadowMapName)) { + const format = supportsR32FloatTexture(device) ? Format.R32F : Format.RGBA8; + ppl.addRenderTarget(shadowMapName, format, width, height, ResourceResidency.MANAGED); + ppl.addDepthStencil(`${shadowMapName}Depth`, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); + } + const pass = ppl.addRasterPass(width, height, 'default', passName); + pass.addRasterView(shadowMapName, new RasterView('_', + AccessType.WRITE, AttachmentType.RENDER_TARGET, + LoadOp.CLEAR, StoreOp.STORE, + ClearFlagBit.COLOR, + new Color(1, 1, 1, camera.clearColor.w))); + pass.addRasterView(`${shadowMapName}Depth`, new RasterView('_', + AccessType.WRITE, AttachmentType.DEPTH_STENCIL, + LoadOp.CLEAR, StoreOp.DISCARD, + ClearFlagBit.DEPTH_STENCIL, + new Color(camera.clearDepth, camera.clearStencil, 0, 0))); + const rect = getRenderArea(camera, width, height, light, level); + pass.setViewport(new Viewport(rect.x, rect.y, rect.width, rect.height)); + const queue = pass.addQueue(QueueHint.RENDER_OPAQUE); + queue.addSceneOfCamera(camera, new LightInfo(light, level), + SceneFlags.SHADOW_CASTER); +} + +class CameraInfo { + shadowEnabled = false; + mainLightShadowNames = new Array(); + spotLightShadowNames = new Array(); +} + +export function buildShadowPasses (cameraName: string, camera: Camera, ppl: Pipeline): CameraInfo { + const pipeline = ppl; + const shadowInfo = pipeline.pipelineSceneData.shadows; + const validPunctualLights = ppl.pipelineSceneData.validPunctualLights; + const cameraInfo = new CameraInfo(); + const shadows = ppl.pipelineSceneData.shadows; + if (!shadowInfo.enabled || shadowInfo.type !== ShadowType.ShadowMap) { return cameraInfo; } + cameraInfo.shadowEnabled = true; + const _validLights: Light[] = []; + let n = 0; + let m = 0; + for (;n < shadowInfo.maxReceived && m < validPunctualLights.length;) { + const light = validPunctualLights[m]; + if (light.type === LightType.SPOT) { + const spotLight = light as SpotLight; + if (spotLight.shadowEnabled) { + _validLights.push(light); + n++; + } + } + m++; + } + + const { mainLight } = camera.scene!; + // build shadow map + const mapWidth = shadows.size.x; + const mapHeight = shadows.size.y; + if (mainLight && mainLight.shadowEnabled) { + cameraInfo.mainLightShadowNames[0] = `MainLightShadow${cameraName}`; + if (mainLight.shadowFixedArea) { + buildShadowPass(cameraInfo.mainLightShadowNames[0], ppl, + camera, mainLight, 0, mapWidth, mapHeight); + } else { + const csmLevel = pipeline.pipelineSceneData.csmSupported ? mainLight.csmLevel : 1; + for (let i = 0; i < csmLevel; i++) { + cameraInfo.mainLightShadowNames[i] = `MainLightShadow${cameraName}`; + buildShadowPass(cameraInfo.mainLightShadowNames[i], ppl, + camera, mainLight, i, mapWidth, mapHeight); + } + } + } + + for (let l = 0; l < _validLights.length; l++) { + const light = _validLights[l]; + const passName = `SpotLightShadow${l.toString()}${cameraName}`; + cameraInfo.spotLightShadowNames[l] = passName; + buildShadowPass(passName, ppl, + camera, light, 0, mapWidth, mapHeight); + } + return cameraInfo; +} + +const _cameras: Camera[] = []; + +export function getCameraUniqueID (camera: Camera) { + if (!_cameras.includes(camera)) { + _cameras.push(camera); + } + return _cameras.indexOf(camera); +} + +export function getLoadOpOfClearFlag (clearFlag: ClearFlagBit, attachment: AttachmentType): LoadOp { + let loadOp = LoadOp.CLEAR; + if (!(clearFlag & ClearFlagBit.COLOR) + && attachment === AttachmentType.RENDER_TARGET) { + if (clearFlag & SKYBOX_FLAG) { + loadOp = LoadOp.DISCARD; + } else { + loadOp = LoadOp.LOAD; + } + } + if ((clearFlag & ClearFlagBit.DEPTH_STENCIL) !== ClearFlagBit.DEPTH_STENCIL + && attachment === AttachmentType.DEPTH_STENCIL) { + if (!(clearFlag & ClearFlagBit.DEPTH)) loadOp = LoadOp.LOAD; + if (!(clearFlag & ClearFlagBit.STENCIL)) loadOp = LoadOp.LOAD; + } + return loadOp; +} + +export class ForwardPipelineBuilder extends PipelineBuilder { + public setup (cameras: Camera[], ppl: Pipeline): void { + for (let i = 0; i < cameras.length; i++) { + const camera = cameras[i]; + if (camera.scene === null) { + continue; + } + validPunctualLightsCulling(ppl, camera); + const cameraID = getCameraUniqueID(camera); + const cameraName = `Camera${cameraID}`; + const cameraInfo = buildShadowPasses(cameraName, camera, ppl); + const width = camera.window.width; + const height = camera.window.height; + + const forwardPassRTName = `dsForwardPassColor${cameraName}`; + const forwardPassDSName = `dsForwardPassDS${cameraName}`; + if (!ppl.containsResource(forwardPassRTName)) { + ppl.addRenderTexture(forwardPassRTName, Format.RGBA8, width, height, camera.window); + ppl.addDepthStencil(forwardPassDSName, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); + } + const forwardPass = ppl.addRasterPass(width, height, 'default', `CameraForwardPass${cameraID}`); + for (const dirShadowName of cameraInfo.mainLightShadowNames) { + if (ppl.containsResource(dirShadowName)) { + const computeView = new ComputeView(); + forwardPass.addComputeView(dirShadowName, computeView); + } + } + for (const spotShadowName of cameraInfo.spotLightShadowNames) { + if (ppl.containsResource(spotShadowName)) { + const computeView = new ComputeView(); + forwardPass.addComputeView(spotShadowName, computeView); + } + } + const passView = new RasterView('_', + AccessType.WRITE, AttachmentType.RENDER_TARGET, + getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), + StoreOp.STORE, + camera.clearFlag, + new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w)); + const passDSView = new RasterView('_', + AccessType.WRITE, AttachmentType.DEPTH_STENCIL, + getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), + StoreOp.STORE, + camera.clearFlag, + new Color(camera.clearDepth, camera.clearStencil, 0, 0)); + forwardPass.addRasterView(forwardPassRTName, passView); + forwardPass.addRasterView(forwardPassDSName, passDSView); + forwardPass + .addQueue(QueueHint.RENDER_OPAQUE) + .addSceneOfCamera(camera, new LightInfo(), + SceneFlags.OPAQUE_OBJECT | SceneFlags.PLANAR_SHADOW | SceneFlags.CUTOUT_OBJECT + | SceneFlags.PLANAR_SHADOW | SceneFlags.DEFAULT_LIGHTING); + forwardPass + .addQueue(QueueHint.RENDER_TRANSPARENT) + .addSceneOfCamera(camera, new LightInfo(), SceneFlags.TRANSPARENT_OBJECT | SceneFlags.UI | SceneFlags.GEOMETRY | SceneFlags.PROFILER); + } + } +} + +// Anti-aliasing type, other types will be gradually added in the future +export enum AntiAliasing { + NONE, + FXAA, +} + +class DeferredData { + constructor () { + this._deferredLightingMaterial = new Material(); + this._deferredLightingMaterial.name = 'builtin-deferred-material'; + this._deferredLightingMaterial.initialize({ + effectName: 'pipeline/deferred-lighting', + defines: { CC_RECEIVE_SHADOW: 1 }, + }); + for (let i = 0; i < this._deferredLightingMaterial.passes.length; ++i) { + this._deferredLightingMaterial.passes[i].tryCompile(); + } + + this._deferredPostMaterial = new Material(); + this._deferredPostMaterial.name = 'builtin-post-process-material'; + if (macro.ENABLE_ANTIALIAS_FXAA) { + this._antiAliasing = AntiAliasing.FXAA; + } + this._deferredPostMaterial.initialize({ + effectName: 'pipeline/post-process', + defines: { + // Anti-aliasing type, currently only fxaa, so 1 means fxaa + ANTIALIAS_TYPE: this._antiAliasing, + }, + }); + for (let i = 0; i < this._deferredPostMaterial.passes.length; ++i) { + this._deferredPostMaterial.passes[i].tryCompile(); + } + } + readonly _deferredLightingMaterial: Material; + readonly _deferredPostMaterial: Material; + _antiAliasing: AntiAliasing = AntiAliasing.NONE; +} + +export function validPunctualLightsCulling (pipeline: Pipeline, camera: Camera) { + const sceneData = pipeline.pipelineSceneData; + const validPunctualLights = sceneData.validPunctualLights; + validPunctualLights.length = 0; + const _sphere = Sphere.create(0, 0, 0, 1); + const { spotLights } = camera.scene!; + for (let i = 0; i < spotLights.length; i++) { + const light = spotLights[i]; + if (light.baked) { + continue; + } + + Sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); + if (intersect.sphereFrustum(_sphere, camera.frustum)) { + validPunctualLights.push(light); + } + } + + const { sphereLights } = camera.scene!; + for (let i = 0; i < sphereLights.length; i++) { + const light = sphereLights[i]; + if (light.baked) { + continue; + } + Sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); + if (intersect.sphereFrustum(_sphere, camera.frustum)) { + validPunctualLights.push(light); + } + } +} + +export class DeferredPipelineBuilder extends PipelineBuilder { + public setup (cameras: Camera[], ppl: Pipeline): void { + for (let i = 0; i < cameras.length; ++i) { + const camera = cameras[i]; + if (!camera.scene) { + continue; + } + validPunctualLightsCulling(ppl, camera); + const cameraID = getCameraUniqueID(camera); + const cameraName = `Camera${cameraID}`; + const cameraInfo = buildShadowPasses(cameraName, camera, ppl); + const width = camera.window.width; + const height = camera.window.height; + + const deferredGbufferPassRTName = `dsDeferredPassColorCamera`; + const deferredGbufferPassNormal = `deferredGbufferPassNormal`; + const deferredGbufferPassEmissive = `deferredGbufferPassEmissive`; + const deferredGbufferPassDSName = `dsDeferredPassDSCamera`; + if (!ppl.containsResource(deferredGbufferPassRTName)) { + const colFormat = Format.RGBA16F; + ppl.addRenderTarget(deferredGbufferPassRTName, colFormat, width, height, ResourceResidency.MANAGED); + ppl.addRenderTarget(deferredGbufferPassNormal, colFormat, width, height, ResourceResidency.MANAGED); + ppl.addRenderTarget(deferredGbufferPassEmissive, colFormat, width, height, ResourceResidency.MANAGED); + ppl.addDepthStencil(deferredGbufferPassDSName, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); + } + // gbuffer pass + const gbufferPass = ppl.addRasterPass(width, height, 'Geometry', `CameraGbufferPass${cameraID}`); + + const rtColor = new Color(0, 0, 0, 0); + if (camera.clearFlag & ClearFlagBit.COLOR) { + if (ppl.pipelineSceneData.isHDR) { + SRGBToLinear(rtColor, camera.clearColor); + } else { + rtColor.x = camera.clearColor.x; + rtColor.y = camera.clearColor.y; + rtColor.z = camera.clearColor.z; + } + } + const passColorView = new RasterView('_', + AccessType.WRITE, AttachmentType.RENDER_TARGET, + LoadOp.CLEAR, StoreOp.STORE, + camera.clearFlag, + rtColor); + const passNormalView = new RasterView('_', + AccessType.WRITE, AttachmentType.RENDER_TARGET, + LoadOp.CLEAR, StoreOp.STORE, + camera.clearFlag, + new Color(0, 0, 0, 0)); + const passEmissiveView = new RasterView('_', + AccessType.WRITE, AttachmentType.RENDER_TARGET, + LoadOp.CLEAR, StoreOp.STORE, + camera.clearFlag, + new Color(0, 0, 0, 0)); + const passDSView = new RasterView('_', + AccessType.WRITE, AttachmentType.DEPTH_STENCIL, + LoadOp.CLEAR, StoreOp.STORE, + camera.clearFlag, + new Color(camera.clearDepth, camera.clearStencil, 0, 0)); + gbufferPass.addRasterView(deferredGbufferPassRTName, passColorView); + gbufferPass.addRasterView(deferredGbufferPassNormal, passNormalView); + gbufferPass.addRasterView(deferredGbufferPassEmissive, passEmissiveView); + gbufferPass.addRasterView(deferredGbufferPassDSName, passDSView); + gbufferPass + .addQueue(QueueHint.RENDER_OPAQUE) + .addSceneOfCamera(camera, new LightInfo(), SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT); + const deferredLightingPassRTName = `deferredLightingPassRTName`; + const deferredLightingPassDS = `deferredLightingPassDS`; + if (!ppl.containsResource(deferredLightingPassRTName)) { + ppl.addRenderTarget(deferredLightingPassRTName, Format.RGBA8, width, height, ResourceResidency.MANAGED); + ppl.addDepthStencil(deferredLightingPassDS, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); + } + // lighting pass + const lightingPass = ppl.addRasterPass(width, height, 'Lighting', `CameraLightingPass${cameraID}`); + for (const dirShadowName of cameraInfo.mainLightShadowNames) { + if (ppl.containsResource(dirShadowName)) { + const computeView = new ComputeView(); + lightingPass.addComputeView(dirShadowName, computeView); + } + } + for (const spotShadowName of cameraInfo.spotLightShadowNames) { + if (ppl.containsResource(spotShadowName)) { + const computeView = new ComputeView(); + lightingPass.addComputeView(spotShadowName, computeView); + } + } + if (ppl.containsResource(deferredGbufferPassRTName)) { + const computeView = new ComputeView(); + computeView.name = 'gbuffer_albedoMap'; + lightingPass.addComputeView(deferredGbufferPassRTName, computeView); + + const computeNormalView = new ComputeView(); + computeNormalView.name = 'gbuffer_normalMap'; + lightingPass.addComputeView(deferredGbufferPassNormal, computeNormalView); + + const computeEmissiveView = new ComputeView(); + computeEmissiveView.name = 'gbuffer_emissiveMap'; + lightingPass.addComputeView(deferredGbufferPassEmissive, computeEmissiveView); + + const computeDepthView = new ComputeView(); + computeDepthView.name = 'depth_stencil'; + lightingPass.addComputeView(deferredGbufferPassDSName, computeDepthView); + } + const lightingClearColor = new Color(0, 0, 0, 0); + if (camera.clearFlag & ClearFlagBit.COLOR) { + lightingClearColor.x = camera.clearColor.x; + lightingClearColor.y = camera.clearColor.y; + lightingClearColor.z = camera.clearColor.z; + } + lightingClearColor.w = 0; + const lightingPassView = new RasterView('_', + AccessType.WRITE, AttachmentType.RENDER_TARGET, + LoadOp.CLEAR, StoreOp.STORE, + camera.clearFlag, + lightingClearColor); + lightingPass.addRasterView(deferredLightingPassRTName, lightingPassView); + lightingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addCameraQuad( + camera, this._deferredData._deferredLightingMaterial, + SceneFlags.VOLUMETRIC_LIGHTING, + ); + lightingPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), + SceneFlags.TRANSPARENT_OBJECT | SceneFlags.PLANAR_SHADOW | SceneFlags.GEOMETRY); + // Postprocess + const postprocessPassRTName = `postprocessPassRTName${cameraID}`; + const postprocessPassDS = `postprocessPassDS${cameraID}`; + if (!ppl.containsResource(postprocessPassRTName)) { + ppl.addRenderTexture(postprocessPassRTName, Format.RGBA8, width, height, camera.window); + ppl.addDepthStencil(postprocessPassDS, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); + } + const postprocessPass = ppl.addRasterPass(width, height, 'Postprocess', `CameraPostprocessPass${cameraID}`); + if (ppl.containsResource(deferredLightingPassRTName)) { + const computeView = new ComputeView(); + computeView.name = 'outputResultMap'; + postprocessPass.addComputeView(deferredLightingPassRTName, computeView); + } + const postClearColor = new Color(0, 0, 0, camera.clearColor.w); + if (camera.clearFlag & ClearFlagBit.COLOR) { + postClearColor.x = camera.clearColor.x; + postClearColor.y = camera.clearColor.y; + postClearColor.z = camera.clearColor.z; + } + const postprocessPassView = new RasterView('_', + AccessType.WRITE, AttachmentType.RENDER_TARGET, + getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.RENDER_TARGET), + StoreOp.STORE, + camera.clearFlag, + postClearColor); + const postprocessPassDSView = new RasterView('_', + AccessType.WRITE, AttachmentType.DEPTH_STENCIL, + getLoadOpOfClearFlag(camera.clearFlag, AttachmentType.DEPTH_STENCIL), + StoreOp.STORE, + camera.clearFlag, + new Color(camera.clearDepth, camera.clearStencil, 0, 0)); + postprocessPass.addRasterView(postprocessPassRTName, postprocessPassView); + postprocessPass.addRasterView(postprocessPassDS, postprocessPassDSView); + postprocessPass.addQueue(QueueHint.NONE).addFullscreenQuad(this._deferredData._deferredPostMaterial, SceneFlags.NONE); + postprocessPass.addQueue(QueueHint.RENDER_TRANSPARENT).addSceneOfCamera(camera, new LightInfo(), + SceneFlags.UI | SceneFlags.PROFILER); + } + } + readonly _deferredData = new DeferredData(); +} diff --git a/cocos/core/pipeline/custom/compiler.ts b/cocos/core/pipeline/custom/compiler.ts index 57c2a8b161..56e533f383 100644 --- a/cocos/core/pipeline/custom/compiler.ts +++ b/cocos/core/pipeline/custom/compiler.ts @@ -22,14 +22,14 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ -import { Buffer, Framebuffer, Texture } from '../../gfx'; +import { Buffer, Framebuffer, Texture, Viewport } from '../../gfx'; import { assert } from '../../platform/debug'; import { LayoutGraphData } from './layout-graph'; import { Pipeline } from './pipeline'; -import { AccessType, Blit, ComputePass, CopyPass, Dispatch, ManagedResource, MovePass, - PresentPass, RasterPass, RasterView, RaytracePass, RenderGraph, RenderGraphValue, RenderGraphVisitor, +import { Blit, ClearView, ComputePass, CopyPass, Dispatch, ManagedResource, MovePass, + PresentPass, RasterPass, RaytracePass, RenderGraph, RenderGraphValue, RenderGraphVisitor, RenderQueue, RenderSwapchain, ResourceGraph, ResourceGraphVisitor, SceneData } from './render-graph'; -import { ResourceResidency } from './types'; +import { AccessType, RasterView, ResourceResidency } from './types'; class PassVisitor implements RenderGraphVisitor { public passID = 0xFFFFFFFF; @@ -42,6 +42,12 @@ class PassVisitor implements RenderGraphVisitor { constructor (context: CompilerContext) { this._context = context; } + clear (value: ClearView[]): unknown { + throw new Error('Method not implemented.'); + } + viewport (value: Viewport): unknown { + throw new Error('Method not implemented.'); + } raster (pass: RasterPass) { // Since the pass is valid, there is no need to continue traversing. if (pass.isValid) { @@ -82,7 +88,7 @@ class PassVisitor implements RenderGraphVisitor { rg.visitVertex(this, sceneID); } } - scene (value: SceneData) { + private _fetchValidPass () { if (this._currPass!.isValid) { return; } @@ -90,31 +96,48 @@ class PassVisitor implements RenderGraphVisitor { const outputName = this._context.resourceGraph.vertexName(outputId); const readViews: Map = new Map(); const pass = this._currPass!; - for (const [name, raster] of pass.rasterViews) { + + for (const [readName, raster] of pass.rasterViews) { // find the pass - if (name === outputName + if (readName === outputName && raster.accessType !== AccessType.READ) { assert(!pass.isValid, 'The same pass cannot output multiple resources with the same name at the same time'); pass.isValid = true; continue; } if (raster.accessType !== AccessType.WRITE) { - readViews.set(name, raster); + readViews.set(readName, raster); } } if (pass.isValid) { - for (const [name, raster] of readViews) { - const resVisitor = new ResourceVisitor(this._context); - const resourceGraph = this._context.resourceGraph; - const vertID = resourceGraph.vertex(name); - if (vertID) { + let resVisitor; + let resourceGraph; + let vertID; + for (const [rasterName, raster] of readViews) { + resVisitor = new ResourceVisitor(this._context); + resourceGraph = this._context.resourceGraph; + vertID = resourceGraph.find(rasterName); + if (vertID !== 0xFFFFFFFF) { + resVisitor.resID = vertID; + resourceGraph.visitVertex(resVisitor, vertID); + } + } + for (const [computeName, cViews] of pass.computeViews) { + resVisitor = new ResourceVisitor(this._context); + resourceGraph = this._context.resourceGraph; + vertID = resourceGraph.find(computeName); + if (vertID !== 0xFFFFFFFF) { resVisitor.resID = vertID; resourceGraph.visitVertex(resVisitor, vertID); } } } } + scene (value: SceneData) { + this._fetchValidPass(); + } blit (value: Blit) { + this._fetchValidPass(); } dispatch (value: Dispatch) { } diff --git a/cocos/core/pipeline/custom/debug.ts b/cocos/core/pipeline/custom/debug.ts new file mode 100644 index 0000000000..0ee76dd397 --- /dev/null +++ b/cocos/core/pipeline/custom/debug.ts @@ -0,0 +1,200 @@ +/* eslint-disable max-len */ +import { Viewport } from '../../gfx'; +import { assert } from '../../platform'; +import { DefaultVisitor, ReferenceGraphView, ED, edge_descriptor, IncidenceGraph } from './graph'; +import { Blit, ClearView, ComputePass, CopyPass, Dispatch, getRenderGraphValueName, MovePass, PresentPass, RasterPass, RaytracePass, RenderGraph, RenderGraphValue, RenderGraphVisitor, RenderQueue, SceneData } from './render-graph'; +import { getQueueHintName } from './types'; + +export const enableDebug = true; + +let oss = ''; +let space = ''; + +class PrePrintVisitor implements RenderGraphVisitor { + constructor (g: RenderGraph) { + this.g = g; + } + clear (value: ClearView[]) { + // do nothing + } + viewport (value: Viewport) { + // do nothing + } + raster (value: RasterPass) { + oss += `${space}width = ${value.width}\n`; + oss += `${space}height = ${value.height}\n`; + for (const rasterView of value.rasterViews) { + oss += `${space}"${rasterView[0]}": RasterView\n`; + } + for (const computeView of value.computeViews) { + oss += `${space}"${computeView[0]}": ComputeView[]\n`; + } + } + compute (value: ComputePass) { + for (const computeView of value.computeViews) { + oss += `${space}"${computeView[0]}": ComputeView[]\n`; + } + } + copy (value: CopyPass) { + if (value.copyPairs.length === 1) { + const pair = value.copyPairs[0]; + oss += `${space}source = "${pair.source}"\n`; + oss += `${space}target = "${pair.target}"\n`; + } else { + let i = 0; + oss += `${space}sources = [`; + for (const pair of value.copyPairs) { + if (i++) { + oss += ', '; + } + oss += `"${pair.source}"`; + } + oss += ']\n'; + + oss += `${space}targets = [`; + for (const pair of value.copyPairs) { + if (i++) { + oss += ', '; + } + oss += `"${pair.target}"`; + } + oss += ']\n'; + } + } + move (value: MovePass) { + if (value.movePairs.length === 1) { + const pair = value.movePairs[0]; + oss += `${space}source = "${pair.source}"\n`; + oss += `${space}target = "${pair.target}"\n`; + } else { + let i = 0; + oss += `${space}sources = [`; + for (const pair of value.movePairs) { + if (i++) { + oss += ', '; + } + oss += `"${pair.source}"`; + } + oss += ']\n'; + + oss += `${space}targets = [`; + for (const pair of value.movePairs) { + if (i++) { + oss += ', '; + } + oss += `"${pair.target}"`; + } + oss += ']\n'; + } + } + present (value: PresentPass) { + for (const present of value.presents) { + oss += `${space}"${present[0]}": Present{ interval = ${present[1].syncInterval} }\n`; + } + } + raytrace (value: RaytracePass) { + for (const computeView of value.computeViews) { + oss += `${space}"${computeView[0]}": ComputeView[]\n`; + } + } + queue (value: RenderQueue) { + oss += `${space}hint = ${getQueueHintName(value.hint)}\n`; + } + scene (value: SceneData) { + oss += `${space}scenes = [`; + let i = 0; + for (const scene of value.scenes) { + if (i++) { + oss += ', '; + } + oss += `"${scene}"`; + } + oss += ']\n'; + } + blit (value: Blit) {} + dispatch (value: Dispatch) { + oss += `${space}shader = "${value.shader}"\n`; + oss += `${space}groupX = ${value.threadGroupCountX}\n`; + oss += `${space}groupY = ${value.threadGroupCountY}\n`; + oss += `${space}groupZ = ${value.threadGroupCountZ}\n`; + } + g: RenderGraph; +} + +class PostPrintVisitor implements RenderGraphVisitor { + constructor (g: RenderGraph) { + this.g = g; + } + clear (value: ClearView[]) { + // do nothing + } + viewport (value: Viewport) { + // do nothing + } + raster (value: RasterPass) { + // post raster pass + } + compute (value: ComputePass) {} + copy (value: CopyPass) {} + move (value: MovePass) {} + present (value: PresentPass) {} + raytrace (value: RaytracePass) {} + queue (value: RenderQueue) { + // collect scene results + } + scene (value: SceneData) { + // scene command list finished + } + blit (value: Blit) {} + dispatch (value: Dispatch) {} + g: RenderGraph; +} + +export class RenderGraphPrintVisitor extends DefaultVisitor { + constructor (g: RenderGraph) { + super(); + this.preVertexVisitor = new PrePrintVisitor(g); + this.postVertexVisitor = new PostPrintVisitor(g); + } + initializeVertex (v: number, gv: ReferenceGraphView): void { + // initialization + } + startVertex (v: number, gv: ReferenceGraphView): void { + const g = gv.g; + // passes begin + // assert(g.holds(RenderGraphValue.Raster, v) + // || g.holds(RenderGraphValue.Compute, v) + // || g.holds(RenderGraphValue.Copy, v) + // || g.holds(RenderGraphValue.Move, v) + // || g.holds(RenderGraphValue.Present, v) + // || g.holds(RenderGraphValue.Raytrace, v)); + } + discoverVertex (v: number, gv: ReferenceGraphView): void { + const g = gv.g; + oss += `${space}"${g.getName(v)}": ${getRenderGraphValueName(g.id(v))} {\n`; + space += ' '; + + g.visitVertex(this.preVertexVisitor, v); + } + backEdge (e: ED, gv: ReferenceGraphView): void { + assert(false); + } + forwardOrCrossEdge (e: ED, gv: ReferenceGraphView): void { + assert(false); + } + finishEdge (e: ED, gv: ReferenceGraphView): void { + const g = gv.g; + } + finishVertex (v: number, gv: ReferenceGraphView): void { + const g = gv.g; + g.visitVertex(this.postVertexVisitor, v); + + space = space.substring(0, space.length - 4); + oss += `${space}}\n`; + } + print (): string { + return oss; + } + readonly preVertexVisitor; + readonly postVertexVisitor; +} diff --git a/cocos/core/pipeline/custom/effect.ts b/cocos/core/pipeline/custom/effect.ts index d9d56a830d..bd0c748ae0 100644 --- a/cocos/core/pipeline/custom/effect.ts +++ b/cocos/core/pipeline/custom/effect.ts @@ -1,10 +1,12 @@ import { legacyCC } from '../../global-exports'; import { EffectAsset } from '../../assets'; -import { WebDescriptorHierarchy } from './web-descriptor-hierarchy'; +import { CollectVisitor, WebDescriptorHierarchy } from './web-descriptor-hierarchy'; // eslint-disable-next-line max-len -import { Descriptor, DescriptorBlock, DescriptorBlockFlattened, DescriptorBlockIndex, DescriptorDB, LayoutGraph, LayoutGraphValue } from './layout-graph'; -import { Pipeline } from './pipeline'; -import { UniformBlock } from '../../gfx'; +import { Descriptor, DescriptorBlock, DescriptorBlockFlattened, DescriptorBlockIndex, DescriptorDB, DescriptorTypeOrder, LayoutGraph, LayoutGraphData, LayoutGraphValue, RenderPhase } from './layout-graph'; +import { LayoutGraphBuilder, Pipeline } from './pipeline'; +import { DescriptorType, ShaderStageFlagBit, Type, UniformBlock } from '../../gfx'; +import { ParameterType, UpdateFrequency } from './types'; +import { depthFirstSearch, GraphColor, MutableVertexPropertyMap } from './graph'; function descriptorBlock2Flattened (block: DescriptorBlock, flattened: DescriptorBlockFlattened): void { block.descriptors.forEach((value, key) => { @@ -23,30 +25,7 @@ function descriptorBlock2Flattened (block: DescriptorBlock, flattened: Descripto flattened.capacity = block.capacity; } -export function rebuildLayoutGraph (): void { - const root = legacyCC.director.root; - if (!root.usesCustomPipeline) { - return; - } - if (EffectAsset.isLayoutValid()) { - return; - } - console.log('rebuildLayoutGraph begin'); - const ppl: Pipeline = root.customPipeline; - const effects = EffectAsset.getAll(); - const lg = new WebDescriptorHierarchy(); - const lgData = ppl.layoutGraphBuilder; - lgData.clear(); - - const defaultStage: number = lg.addGlobal('default', true, true, true, true, true, true, true); - - for (const n in effects) { - const e: EffectAsset = effects[n]; - lg.addEffect(e, defaultStage); - } - - const graph: LayoutGraph = lg.layoutGraph; - +export function buildLayoutGraphDataImpl (graph: LayoutGraph, lgData: LayoutGraphBuilder) { for (const v of graph.vertices()) { const db: DescriptorDB = graph.getDescriptors(v); let vid = 0; @@ -64,17 +43,242 @@ export function rebuildLayoutGraph (): void { db.blocks.forEach((value, key) => { const index: DescriptorBlockIndex = JSON.parse(key) as DescriptorBlockIndex; const block: DescriptorBlock = value; + const flattened = new DescriptorBlockFlattened(); + descriptorBlock2Flattened(block, flattened); if (block.capacity > 0) { - const flattened = new DescriptorBlockFlattened(); - descriptorBlock2Flattened(block, flattened); lgData.addDescriptorBlock(vid, index, flattened); } + for (let i = 0; i < flattened.uniformBlockNames.length; ++i) { + lgData.addUniformBlock(vid, index, flattened.uniformBlockNames[i], flattened.uniformBlocks[i]); + } }); } +} - lgData.compile(); - console.log(lgData.print()); +function rebuildLayoutGraph (): void { + const root = legacyCC.director.root; + if (!root.usesCustomPipeline) { + return; + } + if (EffectAsset.isLayoutValid()) { + return; + } + console.log('rebuildLayoutGraph begin'); + const ppl: Pipeline = root.customPipeline; + const effects = EffectAsset.getAll(); + const lg: WebDescriptorHierarchy = new WebDescriptorHierarchy(); + const lgData = ppl.layoutGraphBuilder; + lgData.clear(); + + const defaultStage: number = lg.addGlobal('default', true, true, true, true, true, true, true); + + for (const n in effects) { + const e: EffectAsset = effects[n]; + lg.addEffect(e, defaultStage); + } + + lg.mergeDescriptors(defaultStage); + + buildLayoutGraphDataImpl(lg.layoutGraph, lgData); EffectAsset.setLayoutValid(); console.log('rebuildLayoutGraph end'); } + +function buildForwardLayoutFromGlobal (ppl: Pipeline, lg: WebDescriptorHierarchy) { + const src = ppl.globalDSManager.descriptorSetLayout; + const passDB: DescriptorDB = new DescriptorDB(); + let count = 0; + for (const b of src.bindings) { + switch (b.descriptorType) { + case DescriptorType.UNIFORM_BUFFER: { + const block = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.UNIFORM_BUFFER, + b.stageFlags, passDB); + block.descriptors.set(`Descriptor${count}`, new Descriptor(Type.UNKNOWN)); + ++block.count; + ++block.capacity; + break; + } + case DescriptorType.DYNAMIC_UNIFORM_BUFFER: { + const block = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.DYNAMIC_UNIFORM_BUFFER, + b.stageFlags, passDB); + block.descriptors.set(`Descriptor${count}`, new Descriptor(Type.UNKNOWN)); + ++block.count; + ++block.capacity; + break; + } + case DescriptorType.STORAGE_BUFFER: { + const block = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.STORAGE_BUFFER, + b.stageFlags, passDB); + block.descriptors.set(`Descriptor${count}`, new Descriptor(Type.UNKNOWN)); + ++block.count; + ++block.capacity; + break; + } + case DescriptorType.DYNAMIC_STORAGE_BUFFER: { + const block = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.DYNAMIC_STORAGE_BUFFER, + b.stageFlags, passDB); + block.descriptors.set(`Descriptor${count}`, new Descriptor(Type.UNKNOWN)); + ++block.count; + ++block.capacity; + break; + } + case DescriptorType.SAMPLER_TEXTURE: { + const block = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.SAMPLER_TEXTURE, + b.stageFlags, passDB); + block.descriptors.set(`Descriptor${count}`, new Descriptor(Type.UNKNOWN)); + ++block.count; + ++block.capacity; + break; + } + case DescriptorType.SAMPLER: { + const block = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.SAMPLER, + b.stageFlags, passDB); + block.descriptors.set(`Descriptor${count}`, new Descriptor(Type.UNKNOWN)); + ++block.count; + ++block.capacity; + break; + } + case DescriptorType.TEXTURE: { + const block = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.TEXTURE, + b.stageFlags, passDB); + block.descriptors.set(`Descriptor${count}`, new Descriptor(Type.UNKNOWN)); + ++block.count; + ++block.capacity; + break; + } + case DescriptorType.STORAGE_IMAGE: { + const block = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.STORAGE_IMAGE, + b.stageFlags, passDB); + block.descriptors.set(`Descriptor${count}`, new Descriptor(Type.UNKNOWN)); + ++block.count; + ++block.capacity; + break; + } + case DescriptorType.INPUT_ATTACHMENT: { + const block = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.INPUT_ATTACHMENT, + b.stageFlags, passDB); + block.descriptors.set(`Descriptor${count}`, new Descriptor(Type.UNKNOWN)); + ++block.count; + ++block.capacity; + break; + } + case DescriptorType.UNKNOWN: + default: + break; + } + ++count; + } + const defaultID = lg._layoutGraph.addVertex( + LayoutGraphValue.RenderStage, + LayoutGraphValue.RenderStage, + 'default', passDB, + ); + + lg.mergeDescriptors(defaultID); +} + +export function buildForwardLayout (ppl: Pipeline) { + const lg = new WebDescriptorHierarchy(); + const bFromGlobalDescriptorSet = false; + + if (bFromGlobalDescriptorSet) { + buildForwardLayoutFromGlobal(ppl, lg); + } else { + const defaultID = lg.addGlobal('default', true, true, true, true, true, true, true); + lg.mergeDescriptors(defaultID); + } + + const builder = ppl.layoutGraphBuilder; + builder.clear(); + buildLayoutGraphDataImpl(lg.layoutGraph, builder); +} + +enum DeferredStage { + GEOMETRY, + LIGHTING, + POST +} + +export class VectorGraphColorMap implements MutableVertexPropertyMap { + constructor (sz: number) { + this.colors = new Array(sz); + } + get (u: number): GraphColor { + return this.colors[u]; + } + put (u: number, value: GraphColor): void { + this.colors[u] = value; + } + readonly colors: Array; +} + +export function buildDeferredLayout (ppl: Pipeline) { + const lg = new WebDescriptorHierarchy(); + const defaultID = lg.addGlobal('default', true, true, true, true, true, true, true); + lg.mergeDescriptors(defaultID); + const geometryPassID = lg.addRenderStage('Geometry', DeferredStage.GEOMETRY); + const lightingPassID = lg.addRenderStage('Lighting', DeferredStage.LIGHTING); + const postPassID = lg.addRenderStage('Postprocess', DeferredStage.POST); + + const geometryQueueID = lg.addRenderPhase('Queue', geometryPassID); + const lightingQueueID = lg.addRenderPhase('Queue', lightingPassID); + const postQueueID = lg.addRenderPhase('Queue', postPassID); + + const lightingDescriptors = lg.layoutGraph.getDescriptors(lightingQueueID); + + const lightingPassBlock = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.SAMPLER_TEXTURE, + ShaderStageFlagBit.FRAGMENT, + lightingDescriptors); + + lg.setDescriptor(lightingPassBlock, 'gbuffer_albedoMap', Type.FLOAT4); + lg.setDescriptor(lightingPassBlock, 'gbuffer_normalMap', Type.FLOAT4); + lg.setDescriptor(lightingPassBlock, 'gbuffer_emissiveMap', Type.FLOAT4); + lg.setDescriptor(lightingPassBlock, 'depth_stencil', Type.FLOAT4); + + const visitor = new CollectVisitor(); + const colorMap = new VectorGraphColorMap(lg.layoutGraph.numVertices()); + depthFirstSearch(lg.layoutGraph, visitor, colorMap); + + lg.mergeDescriptors(lightingPassID); + // Postprocess + const postDescriptors = lg.layoutGraph.getDescriptors(postPassID); + + const postPassBlock = lg.getLayoutBlock(UpdateFrequency.PER_PASS, + ParameterType.TABLE, + DescriptorTypeOrder.SAMPLER_TEXTURE, + ShaderStageFlagBit.FRAGMENT, + postDescriptors); + + lg.setDescriptor(postPassBlock, 'outputResultMap', Type.FLOAT4); + lg.merge(postDescriptors); + + lg.mergeDescriptors(postPassID); + if (visitor.error) { + console.log(visitor.error); + } + + const builder = ppl.layoutGraphBuilder; + builder.clear(); + buildLayoutGraphDataImpl(lg.layoutGraph, builder); +} diff --git a/cocos/core/pipeline/custom/executor.ts b/cocos/core/pipeline/custom/executor.ts index 57730554de..9d6867f1b9 100644 --- a/cocos/core/pipeline/custom/executor.ts +++ b/cocos/core/pipeline/custom/executor.ts @@ -30,24 +30,44 @@ */ /* eslint-disable max-len */ import { getPhaseID, InstancedBuffer, PipelineStateManager } from '..'; -import { AccessFlagBit, Buffer, ClearFlagBit, Color, ColorAttachment, CommandBuffer, DepthStencilAttachment, Device, deviceManager, Format, Framebuffer, - FramebufferInfo, GeneralBarrierInfo, LoadOp, PipelineState, Rect, RenderPass, RenderPassInfo, StoreOp, Swapchain, Texture, TextureInfo, +import { assert } from '../..'; +import { AABB } from '../../geometry/aabb'; +import intersect from '../../geometry/intersect'; +import { Sphere } from '../../geometry/sphere'; +import { AccessFlagBit, Attribute, Buffer, BufferInfo, BufferUsageBit, BufferViewInfo, ClearFlagBit, Color, ColorAttachment, CommandBuffer, DepthStencilAttachment, DescriptorSet, DescriptorSetInfo, Device, deviceManager, Format, Framebuffer, + FramebufferInfo, GeneralBarrierInfo, InputAssemblerInfo, LoadOp, MemoryUsageBit, PipelineState, Rect, RenderPass, RenderPassInfo, SamplerInfo, Shader, StoreOp, SurfaceTransform, Swapchain, Texture, TextureInfo, TextureType, TextureUsageBit, Viewport } from '../../gfx'; import { legacyCC } from '../../global-exports'; -import { BatchingSchemes } from '../../renderer'; +import { Mat4 } from '../../math/mat4'; +import { Vec3 } from '../../math/vec3'; +import { Vec4 } from '../../math/vec4'; +import { BatchingSchemes, Pass } from '../../renderer'; +import { DirectionalLight, SpotLight } from '../../renderer/scene'; import { Camera, SKYBOX_FLAG } from '../../renderer/scene/camera'; +import { Light, LightType } from '../../renderer/scene/light'; +import { Model } from '../../renderer/scene/model'; +import { CSMLevel, CSMOptimizationMode, ShadowType } from '../../renderer/scene/shadows'; +import { SubModel } from '../../renderer/scene/submodel'; import { Root } from '../../root'; import { BatchedBuffer } from '../batched-buffer'; -import { SetIndex } from '../define'; +import { RenderPassStage, SetIndex, UBODeferredLight, UBOForwardLight, UBOLocal } from '../define'; import { PipelineSceneData } from '../pipeline-scene-data'; +import { PipelineInputAssemblerData } from '../render-pipeline'; +import { ShadowLayerVolume } from '../shadow/csm-layers'; +import { LayoutGraph, LayoutGraphData, LayoutGraphDataVisitor, LayoutGraphVisitor, PipelineLayoutData, RenderPhase, RenderPhaseData, RenderStageData } from './layout-graph'; import { Pipeline, SceneVisitor } from './pipeline'; -import { AccessType, AttachmentType, Blit, ComputePass, CopyPass, Dispatch, ManagedResource, MovePass, PresentPass, - RasterPass, RaytracePass, RenderGraph, RenderGraphVisitor, RenderQueue, RenderSwapchain, ResourceDesc, +import { Blit, ClearView, ComputePass, CopyPass, Dispatch, ManagedResource, MovePass, PresentPass, + RasterPass, RaytracePass, RenderGraph, RenderGraphValue, RenderGraphVisitor, RenderQueue, RenderSwapchain, ResourceDesc, ResourceGraph, ResourceGraphVisitor, ResourceTraits, SceneData } from './render-graph'; -import { QueueHint, ResourceDimension, ResourceFlags } from './types'; -import { PipelineUBO } from './ubos'; +import { AttachmentType, ComputeView, QueueHint, ResourceDimension, ResourceFlags, SceneFlags, UpdateFrequency } from './types'; +import { PipelineUBO } from '../pipeline-ubo'; import { RenderInfo, RenderObject, WebSceneTask, WebSceneTransversal } from './web-scene'; import { WebSceneVisitor } from './web-scene-visitor'; +import { stringify, parse } from './utils'; +import { RenderAdditiveLightQueue } from '../render-additive-light-queue'; +import { RenderShadowMapBatchedQueue } from '../render-shadow-map-batched-queue'; +import { renderProfiler } from '../pipeline-funcs'; +import { PlanarShadowQueue } from '../planar-shadow-queue'; class DeviceResource { protected _context: ExecutorContext; @@ -119,6 +139,17 @@ class DeviceTexture extends DeviceResource { info.height, )); } + + release () { + if (this.framebuffer) { + this.framebuffer.destroy(); + this._framebuffer = null; + } + if (this.texture) { + this.texture.destroy(); + this._texture = null; + } + } } class DeviceBuffer extends DeviceResource { @@ -126,6 +157,230 @@ class DeviceBuffer extends DeviceResource { super(name, context); } } + +class BlitDesc { + private _blit: Blit; + private _screenQuad: PipelineInputAssemblerData | null = null; + private _queue: DeviceRenderQueue | null = null; + private _stageDesc: DescriptorSet | null = null; + // If VOLUMETRIC_LIGHTING is turned on, it needs to be assigned + private _lightVolumeBuffer: Buffer | null = null; + private _lightMeterScale = 10000.0; + private _lightBufferData!: Float32Array; + get screenQuad () { return this._screenQuad; } + get blit () { return this._blit; } + set blit (blit: Blit) { this._blit = blit; } + get stageDesc () { return this._stageDesc; } + constructor (blit: Blit, queue: DeviceRenderQueue) { + this._blit = blit; + this._queue = queue; + } + /** + * @zh + * 创建四边形输入汇集器。 + */ + protected _createQuadInputAssembler (): PipelineInputAssemblerData { + // create vertex buffer + const inputAssemblerData = new PipelineInputAssemblerData(); + + const vbStride = Float32Array.BYTES_PER_ELEMENT * 4; + const vbSize = vbStride * 4; + const device = this._queue!.devicePass.context.device; + const quadVB = device.createBuffer(new BufferInfo( + BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.DEVICE | MemoryUsageBit.HOST, + vbSize, + vbStride, + )); + + if (!quadVB) { + return inputAssemblerData; + } + + // create index buffer + const ibStride = Uint8Array.BYTES_PER_ELEMENT; + const ibSize = ibStride * 6; + + const quadIB = device.createBuffer(new BufferInfo( + BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.DEVICE, + ibSize, + ibStride, + )); + + if (!quadIB) { + return inputAssemblerData; + } + + const indices = new Uint8Array(6); + indices[0] = 0; indices[1] = 1; indices[2] = 2; + indices[3] = 1; indices[4] = 3; indices[5] = 2; + + quadIB.update(indices); + + // create input assembler + + const attributes = new Array(2); + attributes[0] = new Attribute('a_position', Format.RG32F); + attributes[1] = new Attribute('a_texCoord', Format.RG32F); + + const quadIA = device.createInputAssembler(new InputAssemblerInfo( + attributes, + [quadVB], + quadIB, + )); + + inputAssemblerData.quadIB = quadIB; + inputAssemblerData.quadVB = quadVB; + inputAssemblerData.quadIA = quadIA; + return inputAssemblerData; + } + createSreenQuad () { + if (!this._screenQuad) { + this._screenQuad = this._createQuadInputAssembler(); + } + } + private _updateScreenVB () { + const devicePass = this._queue!.devicePass; + const width = devicePass.context.width; + const height = devicePass.context.height; + const vb = devicePass.genQuadVertexData(SurfaceTransform.IDENTITY, new Rect(0, 0, width, height)); + this._screenQuad!.quadVB!.update(vb); + } + private _gatherVolumeLights (camera: Camera) { + if (!camera.scene) { return; } + const context = this._queue!.devicePass.context; + const pipeline = context.pipeline; + const cmdBuff = context.commandBuffer; + + const sphereLights = camera.scene.sphereLights; + const spotLights = camera.scene.spotLights; + const _sphere = Sphere.create(0, 0, 0, 1); + const _vec4Array = new Float32Array(4); + const exposure = camera.exposure; + + let idx = 0; + const maxLights = UBODeferredLight.LIGHTS_PER_PASS; + const elementLen = Vec4.length; // sizeof(vec4) / sizeof(float32) + const fieldLen = elementLen * maxLights; + + for (let i = 0; i < sphereLights.length && idx < maxLights; i++, ++idx) { + const light = sphereLights[i]; + Sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); + if (intersect.sphereFrustum(_sphere, camera.frustum)) { + // cc_lightPos + Vec3.toArray(_vec4Array, light.position); + _vec4Array[3] = 0; + this._lightBufferData.set(_vec4Array, idx * elementLen); + + // cc_lightColor + Vec3.toArray(_vec4Array, light.color); + if (light.useColorTemperature) { + const tempRGB = light.colorTemperatureRGB; + _vec4Array[0] *= tempRGB.x; + _vec4Array[1] *= tempRGB.y; + _vec4Array[2] *= tempRGB.z; + } + + if (pipeline.pipelineSceneData.isHDR) { + _vec4Array[3] = light.luminance * exposure * this._lightMeterScale; + } else { + _vec4Array[3] = light.luminance; + } + + this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 1); + + // cc_lightSizeRangeAngle + _vec4Array[0] = light.size; + _vec4Array[1] = light.range; + _vec4Array[2] = 0.0; + this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 2); + } + } + + for (let i = 0; i < spotLights.length && idx < maxLights; i++, ++idx) { + const light = spotLights[i]; + Sphere.set(_sphere, light.position.x, light.position.y, light.position.z, light.range); + if (intersect.sphereFrustum(_sphere, camera.frustum)) { + // cc_lightPos + Vec3.toArray(_vec4Array, light.position); + _vec4Array[3] = 1; + this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 0); + + // cc_lightColor + Vec3.toArray(_vec4Array, light.color); + if (light.useColorTemperature) { + const tempRGB = light.colorTemperatureRGB; + _vec4Array[0] *= tempRGB.x; + _vec4Array[1] *= tempRGB.y; + _vec4Array[2] *= tempRGB.z; + } + if (pipeline.pipelineSceneData.isHDR) { + _vec4Array[3] = light.luminance * exposure * this._lightMeterScale; + } else { + _vec4Array[3] = light.luminance; + } + this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 1); + + // cc_lightSizeRangeAngle + _vec4Array[0] = light.size; + _vec4Array[1] = light.range; + _vec4Array[2] = light.spotAngle; + this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 2); + + // cc_lightDir + Vec3.toArray(_vec4Array, light.direction); + this._lightBufferData.set(_vec4Array, idx * elementLen + fieldLen * 3); + } + } + + // the count of lights is set to cc_lightDir[0].w + const offset = fieldLen * 3 + 3; + this._lightBufferData.set([idx], offset); + + cmdBuff.updateBuffer(this._lightVolumeBuffer!, this._lightBufferData); + } + update () { + this._updateScreenVB(); + if (this.blit.sceneFlags & SceneFlags.VOLUMETRIC_LIGHTING + && this.blit.camera) { + this._gatherVolumeLights(this.blit.camera); + } + this._stageDesc!.update(); + } + + createStageDescriptor () { + if (this._stageDesc) { + return; + } + const pass = this.blit.material!.passes[0]; + const device = this._queue!.devicePass.context.device; + this._stageDesc = device.createDescriptorSet(new DescriptorSetInfo(pass.localSetLayout)); + if (this.blit.sceneFlags & SceneFlags.VOLUMETRIC_LIGHTING) { + let totalSize = Float32Array.BYTES_PER_ELEMENT * 4 * 4 * UBODeferredLight.LIGHTS_PER_PASS; + totalSize = Math.ceil(totalSize / device.capabilities.uboOffsetAlignment) * device.capabilities.uboOffsetAlignment; + + this._lightVolumeBuffer = device.createBuffer(new BufferInfo( + BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, + totalSize, + device.capabilities.uboOffsetAlignment, + )); + + const deferredLitsBufView = device.createBuffer(new BufferViewInfo(this._lightVolumeBuffer, 0, totalSize)); + this._lightBufferData = new Float32Array(totalSize / Float32Array.BYTES_PER_ELEMENT); + this._stageDesc.bindBuffer(UBOForwardLight.BINDING, deferredLitsBufView); + } + const _localUBO = device.createBuffer(new BufferInfo( + BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.DEVICE, + UBOLocal.SIZE, + UBOLocal.SIZE, + )); + this._stageDesc.bindBuffer(UBOLocal.BINDING, _localUBO); + } +} + class DeviceRenderQueue { private _preSceneTasks: DevicePreSceneTask[] = []; private _sceneTasks: DeviceSceneTask[] = []; @@ -133,18 +388,29 @@ class DeviceRenderQueue { private _devicePass: DeviceRenderPass; private _hint: QueueHint = QueueHint.NONE; private _phaseID = getPhaseID('default'); + private _renderPhase: RenderPhaseData | null = null; protected _transversal: DeviceSceneTransversal | null = null; get phaseID (): number { return this._phaseID; } - + get renderPhase (): RenderPhaseData | null { return this._renderPhase; } + set renderPhase (val) { this._renderPhase = val; } private _sceneVisitor: WebSceneVisitor; + private _blitDesc: BlitDesc | null = null; constructor (devicePass: DeviceRenderPass) { this._devicePass = devicePass; this._sceneVisitor = new WebSceneVisitor(this._devicePass.context.commandBuffer, this._devicePass.context.pipeline.pipelineSceneData); } - addSceneTask (scene: SceneData) { + createBlitDesc (blit: Blit) { + if (this._blitDesc) { + return; + } + this._blitDesc = new BlitDesc(blit, this); + this._blitDesc.createSreenQuad(); + this._blitDesc.createStageDescriptor(); + } + addSceneTask (scene: GraphScene): void { if (!this._transversal) { - this._transversal = new DeviceSceneTransversal(this, this.devicePass.context.pipelineSceneData, scene.camera!); + this._transversal = new DeviceSceneTransversal(this, this.devicePass.context.pipelineSceneData, scene); } this._preSceneTasks.push(this._transversal.preRenderPass(this._sceneVisitor)); this._sceneTasks.push(this._transversal.transverse(this._sceneVisitor)); @@ -152,6 +418,7 @@ class DeviceRenderQueue { clearTasks () { this._sceneTasks.length = 0; } + get blitDesc () { return this._blitDesc; } get sceneTasks () { return this._sceneTasks; } set queueHint (value: QueueHint) { this._hint = value; } get queueHint () { return this._hint; } @@ -186,6 +453,69 @@ class SubmitInfo { public batches = new Set(); public opaqueList: RenderInfo[] = []; public transparentList: RenderInfo[] = []; + public planarQueue: PlanarShadowQueue | null = null; + public shadowMap: RenderShadowMapBatchedQueue | null = null; + public additiveLight: RenderAdditiveLightQueue | null = null; +} + +class RenderPassLayoutInfo { + protected _layoutID = 0; + protected _stage: RenderStageData | null = null; + protected _layout: PipelineLayoutData; + protected _context: ExecutorContext; + protected _inputName: string; + protected _descriptorSet: DescriptorSet | null = null; + constructor (layoutId, input: [string, ComputeView[]], context: ExecutorContext) { + this._inputName = input[0]; + this._layoutID = layoutId; + const lg = context.layoutGraph; + this._stage = lg.getRenderStage(layoutId); + this._context = context; + this._layout = lg.getLayout(layoutId); + const layoutData = this._layout.descriptorSets.get(UpdateFrequency.PER_PASS); + if (layoutData) { + // find resource + const deviceTex = context.deviceTextures.get(this._inputName); + const gfxTex = deviceTex?.texture; + if (!gfxTex) { + throw Error(`Could not find texture with resource name ${this._inputName}`); + } + // bind descriptors + for (const descriptor of input[1]) { + const descriptorName = descriptor.name; + const descriptorID = lg.attributeIndex.get(descriptorName); + // find descriptor binding + for (const block of layoutData.descriptorSetLayoutData.descriptorBlocks) { + for (let i = 0; i !== block.descriptors.length; ++i) { + if (descriptorID === block.descriptors[i].descriptorID) { + layoutData.descriptorSet!.bindTexture(block.offset + i, gfxTex); + layoutData.descriptorSet!.bindSampler(block.offset + i, context.device.getSampler(new SamplerInfo())); + if (!this._descriptorSet) this._descriptorSet = layoutData.descriptorSet; + } + } + } + } + } + } + get descriptorSet () { return this._descriptorSet; } + get layoutID () { return this._layoutID; } + get stage () { return this._stage; } + get layout () { return this._layout; } +} + +class RasterPassInfo { + protected _id: number; + protected _pass: RasterPass; + constructor (id, pass) { + this._id = id; + this._pass = pass; + } + get id () { return this._id; } + get pass () { return this._pass; } + applyInfo (id: number, pass: RasterPass) { + this._id = id; + this._pass = pass; + } } class DeviceRenderPass { @@ -196,35 +526,42 @@ class DeviceRenderPass { protected _clearDepth = 1; protected _clearStencil = 0; protected _context: ExecutorContext; - private _rasterPass: RasterPass; + protected _viewport: Viewport | null = null; + private _rasterInfo: RasterPassInfo; + private _layout: RenderPassLayoutInfo | null = null; public submitMap: Map = new Map(); - constructor (context: ExecutorContext, rasterPass: RasterPass) { + constructor (context: ExecutorContext, passInfo: RasterPassInfo) { this._context = context; - this._rasterPass = rasterPass; + this._rasterInfo = passInfo; const device = context.device; const depthStencilAttachment = new DepthStencilAttachment(); depthStencilAttachment.format = Format.DEPTH_STENCIL; + depthStencilAttachment.depthLoadOp = LoadOp.DISCARD; + depthStencilAttachment.stencilLoadOp = LoadOp.DISCARD; depthStencilAttachment.stencilStoreOp = StoreOp.DISCARD; depthStencilAttachment.depthStoreOp = StoreOp.DISCARD; - depthStencilAttachment.barrier = device.getGeneralBarrier(new GeneralBarrierInfo( - AccessFlagBit.DEPTH_STENCIL_ATTACHMENT_WRITE, - AccessFlagBit.DEPTH_STENCIL_ATTACHMENT_WRITE, - )); + const colors: ColorAttachment[] = []; const colorTexs: Texture[] = []; let depthTex: Texture | null = null; let swapchain: Swapchain | null = null; let framebuffer: Framebuffer | null = null; - for (const [resName, rasterV] of rasterPass.rasterViews) { + for (const cv of passInfo.pass.computeViews) { + this._applyRenderLayout(cv); + } + // update the layout descriptorSet + if (this.renderLayout && this.renderLayout.descriptorSet) { + this.renderLayout.descriptorSet.update(); + } + for (const [resName, rasterV] of passInfo.pass.rasterViews) { let resTex = context.deviceTextures.get(resName); - if (rasterV.accessType === AccessType.READ || resTex) { - continue; + if (!resTex) { + const resourceGraph = context.resourceGraph; + const vertId = resourceGraph.vertex(resName); + const resourceVisitor = new ResourceVisitor(resName, context); + resourceGraph.visitVertex(resourceVisitor, vertId); + resTex = context.deviceTextures.get(resName)!; } - const resourceGraph = context.resourceGraph; - const vertId = resourceGraph.vertex(resName); - const resourceVisitor = new ResourceVisitor(resName, context); - resourceGraph.visitVertex(resourceVisitor, vertId); - resTex = context.deviceTextures.get(resName)!; if (!swapchain) swapchain = resTex.swapchain; if (!framebuffer) framebuffer = resTex.framebuffer; const clearFlag = rasterV.clearFlags & 0xffffffff; @@ -235,31 +572,26 @@ class DeviceRenderPass { const colorAttachment = new ColorAttachment(); colorAttachment.format = resTex.description!.format; colorAttachment.sampleCount = resTex.description!.sampleCount; - if (!(clearFlag & ClearFlagBit.COLOR)) { - rasterV.clearColor.x = 0; - rasterV.clearColor.y = 0; - rasterV.clearColor.z = 0; - rasterV.clearColor.w = 1; - if (clearFlag & SKYBOX_FLAG) { - colorAttachment.loadOp = LoadOp.DISCARD; - } else { - colorAttachment.loadOp = LoadOp.LOAD; - colorAttachment.barrier = device.getGeneralBarrier(new GeneralBarrierInfo( - AccessFlagBit.COLOR_ATTACHMENT_WRITE, - AccessFlagBit.COLOR_ATTACHMENT_WRITE, - )); - } - } + colorAttachment.loadOp = rasterV.loadOp; + colorAttachment.storeOp = rasterV.storeOp; + colorAttachment.barrier = device.getGeneralBarrier(new GeneralBarrierInfo( + rasterV.loadOp === LoadOp.LOAD ? AccessFlagBit.COLOR_ATTACHMENT_WRITE : AccessFlagBit.NONE, + rasterV.storeOp === StoreOp.STORE ? AccessFlagBit.COLOR_ATTACHMENT_WRITE : AccessFlagBit.NONE, + )); this._clearColor.push(rasterV.clearColor); colors.push(colorAttachment); } break; case AttachmentType.DEPTH_STENCIL: + depthStencilAttachment.depthStoreOp = rasterV.storeOp; + depthStencilAttachment.stencilStoreOp = rasterV.storeOp; + depthStencilAttachment.depthLoadOp = rasterV.loadOp; + depthStencilAttachment.stencilLoadOp = rasterV.loadOp; + depthStencilAttachment.barrier = device.getGeneralBarrier(new GeneralBarrierInfo( + rasterV.loadOp === LoadOp.LOAD ? AccessFlagBit.DEPTH_STENCIL_ATTACHMENT_WRITE : AccessFlagBit.NONE, + rasterV.storeOp === StoreOp.STORE ? AccessFlagBit.DEPTH_STENCIL_ATTACHMENT_WRITE : AccessFlagBit.NONE, + )); if (!resTex.swapchain && !resTex.framebuffer) depthTex = resTex.texture!; - if ((clearFlag & ClearFlagBit.DEPTH_STENCIL) !== ClearFlagBit.DEPTH_STENCIL) { - if (!(clearFlag & ClearFlagBit.DEPTH)) depthStencilAttachment.depthLoadOp = LoadOp.LOAD; - if (!(clearFlag & ClearFlagBit.STENCIL)) depthStencilAttachment.stencilLoadOp = LoadOp.LOAD; - } this._clearDepth = rasterV.clearColor.x; this._clearStencil = rasterV.clearColor.y; break; @@ -274,20 +606,21 @@ class DeviceRenderPass { const currTex = device.createTexture(new TextureInfo()); colorTexs.push(currTex); } - if (!depthTex && !swapchain && !framebuffer) { - depthTex = device.createTexture(new TextureInfo( - TextureType.TEX2D, - TextureUsageBit.DEPTH_STENCIL_ATTACHMENT | TextureUsageBit.SAMPLED, - Format.DEPTH_STENCIL, - colorTexs[0].width, - colorTexs[0].height, - )); - } + // if (!depthTex && !swapchain && !framebuffer) { + // depthTex = device.createTexture(new TextureInfo( + // TextureType.TEX2D, + // TextureUsageBit.DEPTH_STENCIL_ATTACHMENT | TextureUsageBit.SAMPLED, + // Format.DEPTH_STENCIL, + // colorTexs[0].width, + // colorTexs[0].height, + // )); + // } this._renderPass = device.createRenderPass(new RenderPassInfo(colors, depthStencilAttachment)); this._framebuffer = framebuffer || device.createFramebuffer(new FramebufferInfo(this._renderPass, swapchain ? [swapchain.colorTexture] : colorTexs, swapchain ? swapchain.depthStencilTexture : depthTex)); } + get renderLayout () { return this._layout; } get context () { return this._context; } get renderPass () { return this._renderPass; } get framebuffer () { return this._framebuffer; } @@ -295,18 +628,90 @@ class DeviceRenderPass { get clearDepth () { return this._clearDepth; } get clearStencil () { return this._clearStencil; } get deviceQueues () { return this._deviceQueues; } - get rasterPass () { return this._rasterPass; } + get rasterPassInfo () { return this._rasterInfo; } + get viewport () { return this._viewport; } addQueue (queue: DeviceRenderQueue) { this._deviceQueues.push(queue); } prePass () { for (const queue of this._deviceQueues) { queue.preRecord(); } } + protected _applyRenderLayout (input: [string, ComputeView[]]) { + const stageName = this._context.renderGraph.getLayout(this.rasterPassInfo.id); + if (stageName) { + const layoutGraph = this._context.layoutGraph; + const stageId = layoutGraph.locateChild(layoutGraph.nullVertex(), stageName); + if (stageId !== 0xFFFFFFFF) { + this._layout = new RenderPassLayoutInfo(stageId, input, this._context); + } + } + } + genQuadVertexData (surfaceTransform: SurfaceTransform, renderArea: Rect) : Float32Array { + const vbData = new Float32Array(4 * 4); + + const minX = renderArea.x / this._context.width; + const maxX = (renderArea.x + renderArea.width) / this._context.width; + let minY = renderArea.y / this._context.height; + let maxY = (renderArea.y + renderArea.height) / this._context.height; + if (this._context.root.device.capabilities.screenSpaceSignY > 0) { + const temp = maxY; + maxY = minY; + minY = temp; + } + let n = 0; + switch (surfaceTransform) { + case (SurfaceTransform.IDENTITY): + n = 0; + vbData[n++] = -1.0; vbData[n++] = -1.0; vbData[n++] = minX; vbData[n++] = maxY; + vbData[n++] = 1.0; vbData[n++] = -1.0; vbData[n++] = maxX; vbData[n++] = maxY; + vbData[n++] = -1.0; vbData[n++] = 1.0; vbData[n++] = minX; vbData[n++] = minY; + vbData[n++] = 1.0; vbData[n++] = 1.0; vbData[n++] = maxX; vbData[n++] = minY; + break; + case (SurfaceTransform.ROTATE_90): + n = 0; + vbData[n++] = -1.0; vbData[n++] = -1.0; vbData[n++] = maxX; vbData[n++] = maxY; + vbData[n++] = 1.0; vbData[n++] = -1.0; vbData[n++] = maxX; vbData[n++] = minY; + vbData[n++] = -1.0; vbData[n++] = 1.0; vbData[n++] = minX; vbData[n++] = maxY; + vbData[n++] = 1.0; vbData[n++] = 1.0; vbData[n++] = minX; vbData[n++] = minY; + break; + case (SurfaceTransform.ROTATE_180): + n = 0; + vbData[n++] = -1.0; vbData[n++] = -1.0; vbData[n++] = minX; vbData[n++] = minY; + vbData[n++] = 1.0; vbData[n++] = -1.0; vbData[n++] = maxX; vbData[n++] = minY; + vbData[n++] = -1.0; vbData[n++] = 1.0; vbData[n++] = minX; vbData[n++] = maxY; + vbData[n++] = 1.0; vbData[n++] = 1.0; vbData[n++] = maxX; vbData[n++] = maxY; + break; + case (SurfaceTransform.ROTATE_270): + n = 0; + vbData[n++] = -1.0; vbData[n++] = -1.0; vbData[n++] = minX; vbData[n++] = minY; + vbData[n++] = 1.0; vbData[n++] = -1.0; vbData[n++] = minX; vbData[n++] = maxY; + vbData[n++] = -1.0; vbData[n++] = 1.0; vbData[n++] = maxX; vbData[n++] = minY; + vbData[n++] = 1.0; vbData[n++] = 1.0; vbData[n++] = maxX; vbData[n++] = maxY; + break; + default: + break; + } + + return vbData; + } + + protected _applyViewport (frameTex: Texture) { + this._viewport = null; + const viewport = this._rasterInfo.pass.viewport; + if (viewport.left !== 0 || viewport.top !== 0 + || viewport.width !== frameTex.width + || viewport.height !== frameTex.height) { + this._viewport = viewport; + } + } // record common buffer record () { - const cmdBuff = this._context.commandBuffer; const tex = this.framebuffer.colorTextures[0]!; - cmdBuff.beginRenderPass(this.renderPass, this.framebuffer, new Rect(0, 0, tex.width, tex.height), + this._applyViewport(tex); + const cmdBuff = this._context.commandBuffer; + const renderArea = this._viewport ? new Rect(this._viewport.left, this._viewport.top, this._viewport.width, this._viewport.height) + : new Rect(0, 0, tex.width, tex.height); + cmdBuff.beginRenderPass(this.renderPass, this.framebuffer, renderArea, this.clearColor, this.clearDepth, this.clearStencil); cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, this._context.pipeline.globalDSManager.globalDescriptorSet); @@ -321,46 +726,79 @@ class DeviceRenderPass { queue.postRecord(); } } + resetQueues (id: number, pass: RasterPass) { + this._rasterInfo.applyInfo(id, pass); + this._deviceQueues.length = 0; + } } class DeviceSceneTransversal extends WebSceneTransversal { protected _currentQueue: DeviceRenderQueue; - constructor (quque: DeviceRenderQueue, sceneData: PipelineSceneData, camera: Camera) { - super(camera, sceneData); + protected _graphScene: GraphScene; + constructor (quque: DeviceRenderQueue, sceneData: PipelineSceneData, graphSceneData: GraphScene) { + const camera = graphSceneData.scene ? graphSceneData.scene.camera : null; + super(camera, sceneData, quque.devicePass.context.ubo); this._currentQueue = quque; + this._graphScene = graphSceneData; } + get graphScene () { return this._graphScene; } public preRenderPass (visitor: WebSceneVisitor): DevicePreSceneTask { - return new DevicePreSceneTask(this._currentQueue, this._camera, visitor); + return new DevicePreSceneTask(this._currentQueue, this._graphScene, visitor); } public transverse (visitor: WebSceneVisitor): DeviceSceneTask { - return new DeviceSceneTask(this._currentQueue, this._camera, visitor); + return new DeviceSceneTask(this._currentQueue, this._graphScene, visitor); } public postRenderPass (visitor: WebSceneVisitor): DevicePostSceneTask { - return new DevicePostSceneTask(this._sceneData, this._camera, visitor); + return new DevicePostSceneTask(this._sceneData, this._currentQueue.devicePass.context.ubo, this._camera, visitor); } } - +class GraphScene { + scene: SceneData | null = null; + blit: Blit | null = null; + dispatch: Dispatch | null = null; +} class DevicePreSceneTask extends WebSceneTask { protected _currentQueue: DeviceRenderQueue; protected _renderPass: RenderPass; protected _submitInfo: SubmitInfo | null = null; + protected _graphScene: GraphScene; private _cmdBuff: CommandBuffer; - constructor (queue: DeviceRenderQueue, camera: Camera, visitor: SceneVisitor) { - super(queue.devicePass.context.pipelineSceneData, camera, visitor); + constructor (queue: DeviceRenderQueue, graphScene: GraphScene, visitor: SceneVisitor) { + super(queue.devicePass.context.pipelineSceneData, queue.devicePass.context.ubo, + graphScene.scene && graphScene.scene.camera ? graphScene.scene.camera : null, visitor); this._currentQueue = queue; + this._graphScene = graphScene; this._renderPass = this._currentQueue.devicePass.renderPass; - this._cmdBuff = this._currentQueue.devicePass.context.commandBuffer; + this._cmdBuff = queue.devicePass.context.commandBuffer; } + get graphScene () { return this._graphScene; } public start () { + if (this.graphScene.blit) { + this._currentQueue.createBlitDesc(this.graphScene.blit); + return; + } + if (!this.camera) { + return; + } const submitMap = this._currentQueue.devicePass.submitMap; if (submitMap.has(this.camera)) { this._submitInfo = submitMap.get(this.camera)!; } else { // culling - super.start(); + if (!this._isShadowMap() || (this._isShadowMap() && this.graphScene.scene!.light.level === 0)) super.start(); this._submitInfo = new SubmitInfo(); + submitMap.set(this.camera, this._submitInfo); } + // shadowmap + if (this._isShadowMap() && !this._submitInfo.shadowMap) { + assert(this.graphScene.scene!.light.light); + this._submitInfo.shadowMap = new RenderShadowMapBatchedQueue(this._currentQueue.devicePass.context.pipeline); + this._submitInfo.shadowMap.gatherLightPasses(this.camera, this.graphScene.scene!.light.light, this._cmdBuff, this.graphScene.scene!.light.level); + this.sceneData.shadowFrameBufferMap.set(this.graphScene.scene!.light.light, this._currentQueue.devicePass.framebuffer); + return; + } + const sceneFlag = this._graphScene.scene!.flags; for (const ro of this.sceneData.renderObjects) { const subModels = ro.model.subModels; for (const submodel of subModels) { @@ -379,29 +817,29 @@ class DevicePreSceneTask extends WebSceneTask { const batchedBuffer = p.getBatchedBuffer(); batchedBuffer.merge(submodel, passes.indexOf(p), ro.model); this._submitInfo.batches.add(batchedBuffer); - } else { - switch (this._currentQueue.queueHint) { - case QueueHint.NONE: - this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p)); - this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p), true); - break; - case QueueHint.RENDER_CUTOUT: - case QueueHint.RENDER_OPAQUE: - this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p)); - break; - case QueueHint.RENDER_TRANSPARENT: - this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p), true); - break; - default: - } + } else if ((sceneFlag & SceneFlags.TRANSPARENT_OBJECT) + && (sceneFlag & SceneFlags.OPAQUE_OBJECT || sceneFlag & SceneFlags.OPAQUE_OBJECT)) { + this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p)); + this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p), true); + } else if ((sceneFlag & SceneFlags.CUTOUT_OBJECT) || (sceneFlag & SceneFlags.OPAQUE_OBJECT)) { + this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p)); + } else if (sceneFlag & SceneFlags.TRANSPARENT_OBJECT) { + this._insertRenderList(ro, subModels.indexOf(submodel), passes.indexOf(p), true); } } } } - + const pipeline = this._currentQueue.devicePass.context.pipeline; + if (sceneFlag & SceneFlags.DEFAULT_LIGHTING) { + this._submitInfo.additiveLight = new RenderAdditiveLightQueue(pipeline); + this._submitInfo.additiveLight.gatherLightPasses(this.camera, this._cmdBuff); + } + if (sceneFlag & SceneFlags.PLANAR_SHADOW) { + this._submitInfo.planarQueue = new PlanarShadowQueue(pipeline); + this._submitInfo.planarQueue.gatherShadowPasses(this.camera, this._cmdBuff); + } this._submitInfo.opaqueList.sort(this._opaqueCompareFn); this._submitInfo.transparentList.sort(this._transparentCompareFn); - if (!submitMap.has(this.camera)) submitMap.set(this.camera, this._submitInfo); } protected _insertRenderList (ro: RenderObject, subModelIdx: number, passIdx: number, isTransparent = false) { const subModel = ro.model.subModels[subModelIdx]; @@ -463,11 +901,34 @@ class DevicePreSceneTask extends WebSceneTask { } } - public submit () { + private _isShadowMap () { + return this.sceneData.shadows.enabled + && this.sceneData.shadows.type === ShadowType.ShadowMap + && this.graphScene.scene!.flags & SceneFlags.SHADOW_CASTER; + } + + protected _updateUbo (camera: Camera) { const ubo = this._currentQueue.devicePass.context.ubo; - ubo.updateGlobalUBO(this.camera.window); - ubo.updateCameraUBO(this.camera); - ubo.updateShadowUBO(this.camera); + ubo.updateGlobalUBO(camera.window); + ubo.updateCameraUBO(camera); + ubo.updateShadowUBO(camera); + } + + public submit () { + const context = this._currentQueue.devicePass.context; + const ubo = context.ubo; + if (this.graphScene.blit) { + const blitCam = this.graphScene.blit.camera; + if (blitCam) this._updateUbo(blitCam); + this._currentQueue.blitDesc!.update(); + return; + } + if (this._isShadowMap()) { + ubo.updateShadowUBOLight(context.pipeline.descriptorSet, + this.graphScene.scene!.light.light!, this.graphScene.scene!.light.level); + return; + } + this._updateUbo(this.camera!); this._uploadInstanceBuffers(); this._uploadBatchedBuffers(); @@ -477,15 +938,19 @@ class DevicePreSceneTask extends WebSceneTask { class DeviceSceneTask extends WebSceneTask { protected _currentQueue: DeviceRenderQueue; protected _renderPass: RenderPass; - constructor (queue: DeviceRenderQueue, camera: Camera, visitor: SceneVisitor) { - super(queue.devicePass.context.pipelineSceneData, camera, visitor); + protected _graphScene: GraphScene; + constructor (queue: DeviceRenderQueue, graphScene: GraphScene, visitor: SceneVisitor) { + super(queue.devicePass.context.pipelineSceneData, queue.devicePass.context.ubo, + graphScene.scene && graphScene.scene.camera ? graphScene.scene.camera : null, visitor); this._currentQueue = queue; this._renderPass = this._currentQueue.devicePass.renderPass; + this._graphScene = graphScene; } + get graphScene () { return this._graphScene; } public start () {} protected _recordRenderList (isTransparent: boolean) { const submitMap = this._currentQueue.devicePass.submitMap; - const renderList = isTransparent ? submitMap.get(this.camera)!.transparentList : submitMap.get(this.camera)!.opaqueList; + const renderList = isTransparent ? submitMap.get(this.camera!)!.transparentList : submitMap.get(this.camera!)!.opaqueList; for (let i = 0; i < renderList.length; ++i) { const { subModel, passIdx } = renderList[i]; const { inputAssembler } = subModel; @@ -505,7 +970,7 @@ class DeviceSceneTask extends WebSceneTask { } protected _recordInstences () { const submitMap = this._currentQueue.devicePass.submitMap; - const it = submitMap.get(this.camera)!.instances.values(); let res = it.next(); + const it = submitMap.get(this.camera!)!.instances.values(); let res = it.next(); while (!res.done) { const { instances, pass, hasPendingModels } = res.value; if (hasPendingModels) { @@ -532,7 +997,7 @@ class DeviceSceneTask extends WebSceneTask { } protected _recordBatches () { const submitMap = this._currentQueue.devicePass.submitMap; - const it = submitMap.get(this.camera)!.batches.values(); let res = it.next(); + const it = submitMap.get(this.camera!)!.batches.values(); let res = it.next(); while (!res.done) { let boundPSO = false; for (let b = 0; b < res.value.batches.length; ++b) { @@ -555,11 +1020,11 @@ class DeviceSceneTask extends WebSceneTask { } } protected _recordUI () { - const batches = this.camera.scene!.batches; + const batches = this.camera!.scene!.batches; for (let i = 0; i < batches.length; i++) { const batch = batches[i]; let visible = false; - if (this.camera.visibility & batch.visFlags) { + if (this.camera!.visibility & batch.visFlags) { visible = true; } @@ -584,26 +1049,134 @@ class DeviceSceneTask extends WebSceneTask { protected _recordTransparentList () { this._recordRenderList(true); } + protected _recordShadowMap () { + const context = this._currentQueue.devicePass.context; + const submitMap = this._currentQueue.devicePass.submitMap; + submitMap.get(this.camera!)?.shadowMap?.recordCommandBuffer(context.device, + this._renderPass, context.commandBuffer); + } protected _generateRenderArea (): Rect { const out = new Rect(); - const vp = this.camera.viewport; - const w = this.camera.window.width; - const h = this.camera.window.height; + const vp = this.camera ? this.camera.viewport : new Rect(0, 0, 1, 1); + const texture = this._currentQueue.devicePass.framebuffer.colorTextures[0]!; + const w = texture.width; + const h = texture.height; out.x = vp.x * w; out.y = vp.y * h; out.width = vp.width * w; out.height = vp.height * h; + if (this._isShadowMap() && this.graphScene.scene!.light.light) { + const light = this.graphScene.scene!.light.light; + const level = this.graphScene.scene!.light.level; + switch (light.type) { + case LightType.DIRECTIONAL: { + const mainLight = light as DirectionalLight; + if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1) { + out.x = 0; + out.y = 0; + out.width = w; + out.height = h; + } else { + out.x = level % 2 * 0.5 * w; + out.y = (1 - Math.floor(level / 2)) * 0.5 * h; + out.width = 0.5 * w; + out.height = 0.5 * h; + } + break; + } + case LightType.SPOT: { + out.x = 0; + out.y = 0; + out.width = w; + out.height = h; + break; + } + default: + } + } return out; } + private _isShadowMap () { + return this.sceneData.shadows.enabled + && this.sceneData.shadows.type === ShadowType.ShadowMap + && this.graphScene.scene + && this.graphScene.scene.flags & SceneFlags.SHADOW_CASTER; + } + private _recordBlit () { + if (!this.graphScene.blit) { return; } + const currMat = this.graphScene.blit.material; + const pass = currMat!.passes[0]; + const shader = pass.getShaderVariant(); + const devicePass = this._currentQueue.devicePass; + const screenIa: any = this._currentQueue.blitDesc!.screenQuad!.quadIA; + let pso; + if (pass !== null && shader !== null && screenIa !== null) { + pso = PipelineStateManager.getOrCreatePipelineState(devicePass.context.device, pass, shader, + devicePass.renderPass, screenIa); + } + if (pso) { + this.visitor.bindPipelineState(pso); + const layoutStage = devicePass.renderLayout; + // TODO: It will be changed to global later + this.visitor.bindDescriptorSet(SetIndex.MATERIAL, layoutStage!.descriptorSet!); + this.visitor.bindDescriptorSet(SetIndex.LOCAL, this._currentQueue.blitDesc!.stageDesc!); + this.visitor.bindInputAssembler(screenIa); + this.visitor.draw(screenIa); + } + } + private _recordAdditiveLights () { + const devicePass = this._currentQueue.devicePass; + const submitMap = devicePass.submitMap; + const context = devicePass.context; + submitMap.get(this.camera!)?.additiveLight?.recordCommandBuffer(context.device, + this._renderPass, + devicePass.context.commandBuffer); + } + + private _recordPlanarShadows () { + const devicePass = this._currentQueue.devicePass; + const submitMap = devicePass.submitMap; + const context = devicePass.context; + submitMap.get(this.camera!)?.planarQueue?.recordCommandBuffer(context.device, + this._renderPass, + devicePass.context.commandBuffer); + } + public submit () { const area = this._generateRenderArea(); - this.visitor.setViewport(new Viewport(area.x, area.y, area.width, area.height)); - this.visitor.setScissor(area); + const devicePass = this._currentQueue.devicePass; + const context = devicePass.context; + if (!this._currentQueue.devicePass.viewport) { + this.visitor.setViewport(new Viewport(area.x, area.y, area.width, area.height)); + this.visitor.setScissor(area); + } + // Currently processing blit and camera first + if (this.graphScene.blit) { + this._recordBlit(); + return; + } + if (this._isShadowMap()) { + this._recordShadowMap(); + return; + } + const graphSceneData = this.graphScene.scene!; this._recordOpaqueList(); this._recordInstences(); this._recordBatches(); + this._recordAdditiveLights(); + this._recordPlanarShadows(); this._recordTransparentList(); - this._recordUI(); + if (graphSceneData.flags & SceneFlags.GEOMETRY) { + this.camera!.geometryRenderer?.render(devicePass.renderPass, + context.commandBuffer, context.pipeline.pipelineSceneData); + } + if (graphSceneData.flags & SceneFlags.UI) { + this._recordUI(); + } + if (graphSceneData.flags & SceneFlags.PROFILER) { + renderProfiler(context.device, devicePass.renderPass, + context.commandBuffer, context.pipeline.profiler, this.camera!); + } } } @@ -614,7 +1187,10 @@ class ExecutorContext { ubo: PipelineUBO, device: Device, resourceGraph: ResourceGraph, - renderGraph: RenderGraph) { + renderGraph: RenderGraph, + layoutGraph: LayoutGraphData, + width: number, + height: number) { this.pipeline = pipeline; this.device = device; this.commandBuffer = device.commandBuffer; @@ -623,19 +1199,24 @@ class ExecutorContext { this.renderGraph = renderGraph; this.root = legacyCC.director.root; this.ubo = ubo; + this.layoutGraph = layoutGraph; + this.width = width; + this.height = height; } readonly device: Device; readonly pipeline: Pipeline; readonly commandBuffer: CommandBuffer; readonly pipelineSceneData: PipelineSceneData; readonly resourceGraph: ResourceGraph; - readonly devicePasses: Map = new Map(); + readonly devicePasses: Map = new Map(); readonly deviceTextures: Map = new Map(); - readonly renderGraph: RenderGraph; + readonly layoutGraph: LayoutGraphData; readonly root: Root; readonly ubo: PipelineUBO; + readonly width: number; + readonly height: number; + renderGraph: RenderGraph; } - class ResourceVisitor implements ResourceGraphVisitor { private _context: ExecutorContext; name: string; @@ -662,6 +1243,7 @@ class ResourceVisitor implements ResourceGraphVisitor { this.createDeviceTex(value); } } + class PassVisitor implements RenderGraphVisitor { public passID = 0xFFFFFFFF; private _queueID = 0xFFFFFFFF; @@ -672,21 +1254,31 @@ class PassVisitor implements RenderGraphVisitor { constructor (context: ExecutorContext) { this._context = context; } + clear (value: ClearView[]): unknown { + throw new Error('Method not implemented.'); + } + viewport (value: Viewport): unknown { + throw new Error('Method not implemented.'); + } raster (pass: RasterPass) { if (!pass.isValid) { return; } const rg = this._context.renderGraph; const devicePasses = this._context.devicePasses; - this._currPass = devicePasses.get(this.passID); + const layout = this._context.layoutGraph; + const passHash = stringify(pass); + this._currPass = devicePasses.get(passHash); if (!this._currPass) { - this._currPass = new DeviceRenderPass(this._context, pass); - devicePasses.set(this.passID, this._currPass); - for (const q of rg.children(this.passID)) { - const queueID = q.target as number; - this._queueID = queueID; - rg.visitVertex(this, queueID); - } + this._currPass = new DeviceRenderPass(this._context, new RasterPassInfo(this.passID, pass)); + devicePasses.set(passHash, this._currPass); + } else { + this._currPass.resetQueues(this.passID, pass); + } + for (const q of rg.children(this.passID)) { + const queueID = q.target as number; + this._queueID = queueID; + rg.visitVertex(this, queueID); } this._currPass.prePass(); this._currPass.record(); @@ -713,6 +1305,14 @@ class PassVisitor implements RenderGraphVisitor { this._currQueue = deviceQueue; this._currPass!.addQueue(deviceQueue); const rg = this._context.renderGraph; + const layoutName = this._context.renderGraph.getLayout(this._queueID); + if (layoutName) { + const layoutGraph = this._context.layoutGraph; + if (this._currPass!.renderLayout) { + const layoutId = layoutGraph.locateChild(this._currPass!.renderLayout.layoutID, layoutName); + deviceQueue.renderPhase = layoutGraph.tryGetRenderPhase(layoutId); + } + } for (const s of rg.children(this._queueID)) { const sceneID = s.target as number; this._sceneID = sceneID; @@ -720,9 +1320,14 @@ class PassVisitor implements RenderGraphVisitor { } } scene (value: SceneData) { - this._currQueue!.addSceneTask(value); + const graphScene = new GraphScene(); + graphScene.scene = value; + this._currQueue!.addSceneTask(graphScene); } blit (value: Blit) { + const graphScene = new GraphScene(); + graphScene.blit = value; + this._currQueue!.addSceneTask(graphScene); } dispatch (value: Dispatch) { } @@ -732,25 +1337,26 @@ export class Executor { constructor (pipeline: Pipeline, ubo: PipelineUBO, device: Device, - resourceGraph: ResourceGraph) { - this._pipeline = pipeline; - this._device = device; - this._ubo = ubo; - this._commandBuffer = device.commandBuffer; - this._resourceGraph = resourceGraph; + resourceGraph: ResourceGraph, + layoutGraph: LayoutGraphData, + width: number, height: number) { + this._context = new ExecutorContext( + pipeline, + ubo, + device, + resourceGraph, + new RenderGraph(), + layoutGraph, + width, + height, + ); } execute (rg: RenderGraph) { - const context = new ExecutorContext( - this._pipeline, - this._ubo, - this._device, - this._resourceGraph, - rg, - ); - const cmdBuff = context.commandBuffer; + this._context.renderGraph = rg; + const cmdBuff = this._context.commandBuffer; cmdBuff.begin(); - const passVisitor = new PassVisitor(context); + const passVisitor = new PassVisitor(this._context); for (const vertID of rg.vertices()) { if (rg.numParents(vertID) === 0) { // vertex has no parents, must be pass @@ -759,11 +1365,15 @@ export class Executor { } } cmdBuff.end(); - context.device.queue.submit([cmdBuff]); + this._context.device.queue.submit([cmdBuff]); } - private readonly _pipeline: Pipeline; - private readonly _device: Device; - private readonly _commandBuffer: CommandBuffer; - private readonly _resourceGraph: ResourceGraph; - private readonly _ubo: PipelineUBO; + + release () { + this._context.devicePasses.clear(); + for (const [k, v] of this._context.deviceTextures) { + v.release(); + } + this._context.deviceTextures.clear(); + } + private readonly _context: ExecutorContext; } diff --git a/cocos/core/pipeline/custom/graph.ts b/cocos/core/pipeline/custom/graph.ts index 89c9e7f28b..650d89d4e3 100644 --- a/cocos/core/pipeline/custom/graph.ts +++ b/cocos/core/pipeline/custom/graph.ts @@ -343,6 +343,10 @@ export interface PropertyMap { get (x: vertex_descriptor | edge_descriptor): unknown; } +export interface MutableVertexPropertyMap extends PropertyMap { + put (x: vertex_descriptor, value: T): void; +} + //-------------------------------------------------------------------------- // PropertyGraph //-------------------------------------------------------------------------- @@ -519,3 +523,259 @@ export function findRelative (g: ParentGraph, v: vertex_descriptor | null, path: } return curr; } + +//======================================================================= +// DFS +// Based on boost/graph/depth_first_search.hpp +//======================================================================= + +//======================================================================= +// Copyright 1997, 1998, 1999, 2000 University of Notre Dame. +// Copyright 2003 Bruce Barr +// Authors: Andrew Lumsdaine, Lie-Quan Lee, Jeremy G. Siek +// +// Distributed under the Boost Software License, Version 1.0. (See +// accompanying file LICENSE_1_0.txt or copy at +// http://www.boost.org/LICENSE_1_0.txt) +//======================================================================= + +export interface TerminatorFunc { + terminate (v: vertex_descriptor, g: IncidenceGraph): boolean; +} + +class NoTermination implements TerminatorFunc { + terminate (v: vertex_descriptor, g: IncidenceGraph): boolean { + return false; + } +} + +function getDefaultStartingVertex (g: IncidenceGraph & VertexListGraph): vertex_descriptor | null { + const iter = g.vertices(); + const v = iter.next(); + if (v.done) { + return g.nullVertex(); + } else { + return v.value; + } +} + +export interface GraphVisitor { + // 0. before dfs + initializeVertex (v: vertex_descriptor, g: IncidenceGraph): void; + // 1. dfs starting vertex (usually the root) + startVertex (v: vertex_descriptor, g: IncidenceGraph): void; + // 2. vertex discovered + discoverVertex (v: vertex_descriptor, g: IncidenceGraph): void; + // 3. edge discovered + examineEdge (e: edge_descriptor, g: IncidenceGraph): void; + // 4(a). is tree edge + treeEdge (e: edge_descriptor, g: IncidenceGraph): void; + // 4(b). is back edge + backEdge (e: edge_descriptor, g: IncidenceGraph): void; + // 4(c). is forward or cross edge + forwardOrCrossEdge (e: edge_descriptor, g: IncidenceGraph): void; + // 5. edge finished + finishEdge (e: edge_descriptor, g: IncidenceGraph): void; + // 6. vertex finished + finishVertex (v: vertex_descriptor, g: IncidenceGraph): void; +} + +export enum GraphColor { + WHITE, + GRAY, + GREEN, + RED, + BLACK, +} + +class VertexInfo { + constructor ( + v: vertex_descriptor, + e: edge_descriptor | null, + iter: out_edge_iterator | null, + ) { + this.v = v; + this.e = e; + this.iter = iter; + } + v: vertex_descriptor; + e: edge_descriptor | null; + iter: out_edge_iterator | null; +} + +function depthFirstVisitImpl ( + g: IncidenceGraph, + u: vertex_descriptor, + visitor: GraphVisitor, + color: MutableVertexPropertyMap, + func: TerminatorFunc, +): void { + let srcE: edge_descriptor | null = null; + let ei: out_edge_iterator | null = null; + const stack = new Array(); + + color.put(u, GraphColor.GRAY); + visitor.discoverVertex(u, g); + + ei = g.outEdges(u); + if (func.terminate(u, g)) { + // If this vertex terminates the search, we push empty range + stack.push(new VertexInfo(u, null, null)); + } else { + stack.push(new VertexInfo(u, null, ei)); + } + + while (stack.length) { + const back = stack.pop()!; + u = back.v; + srcE = back.e; + ei = back.iter; + // finish_edge has to be called here, not after the + // loop. Think of the pop as the return from a recursive call. + if (srcE !== null) { + visitor.finishEdge(srcE, g); + } + if (ei) { // has out edges + for (let ev = ei.next(); !ev.done; ev = ei.next()) { + const e = ev.value; + const v = e.target; + visitor.examineEdge(e, g); + const vColor = color.get(v); + if (vColor === GraphColor.WHITE) { + visitor.treeEdge(e, g); + srcE = e; + stack.push(new VertexInfo(u, srcE, ei)); + u = v; + color.put(u, GraphColor.GRAY); + visitor.discoverVertex(u, g); + ei = g.outEdges(u); + if (func.terminate(u, g)) { + break; + } + } else { + if (vColor === GraphColor.GRAY) { + visitor.backEdge(e, g); + } else { + visitor.forwardOrCrossEdge(e, g); + } + visitor.finishEdge(e, g); + } + } + } + color.put(u, GraphColor.BLACK); + visitor.finishVertex(u, g); + } +} + +export function depthFirstSearch ( + g: IncidenceGraph & VertexListGraph, + visitor: GraphVisitor, + color: MutableVertexPropertyMap, + startVertex: vertex_descriptor | null = null, +): void { + // get start vertex + startVertex = startVertex || getDefaultStartingVertex(g); + // graph is empty, do nothing + if (startVertex === null || g.numVertices() === 0) { + return; + } + // initialize vertex and color map + for (const u of g.vertices()) { + color.put(u, GraphColor.WHITE); + visitor.initializeVertex(u, g); + } + // start DFS + const terminator = new NoTermination(); + // try starting from startVertex + if (startVertex !== getDefaultStartingVertex(g)) { + visitor.startVertex(startVertex, g); + depthFirstVisitImpl(g, startVertex, visitor, color, terminator); + } + // try starting from each vertex + for (const u of g.vertices()) { + // if vertex is not visited, start DFS + if (color.get(u) === GraphColor.WHITE) { + visitor.startVertex(u, g); + depthFirstVisitImpl(g, u, visitor, color, terminator); + } + } +} + +export function depthFirstVisit ( + g: IncidenceGraph, + u: vertex_descriptor, + visitor: GraphVisitor, + color: MutableVertexPropertyMap, + func: TerminatorFunc = new NoTermination(), +): void { + visitor.startVertex(u, g); + depthFirstVisitImpl(g, u, visitor, color, func); +} + +export class DefaultVisitor implements GraphVisitor { + initializeVertex (v: vertex_descriptor, g: IncidenceGraph): void { + // do nothing + } + startVertex (v: vertex_descriptor, g: IncidenceGraph): void { + // do nothing + } + discoverVertex (v: vertex_descriptor, g: IncidenceGraph): void { + // do nothing + } + examineEdge (e: edge_descriptor, g: IncidenceGraph): void { + // do nothing + } + treeEdge (e: edge_descriptor, g: IncidenceGraph): void { + // do nothing + } + backEdge (e: edge_descriptor, g: IncidenceGraph): void { + // do nothing + } + forwardOrCrossEdge (e: edge_descriptor, g: IncidenceGraph): void { + // do nothing + } + finishEdge (e: edge_descriptor, g: IncidenceGraph): void { + // do nothing + } + finishVertex (v: vertex_descriptor, g: IncidenceGraph): void { + // do nothing + } +} + +export class ReferenceGraphView +implements IncidenceGraph, VertexListGraph { + constructor (g: BaseGraph) { + this.g = g; + this.directed_category = directional.directed; + this.edge_parallel_category = parallel.allow; + this.traversal_category = traversal.incidence | traversal.vertex_list; + } + nullVertex () { + return this.g.nullVertex(); + } + edge (u: vertex_descriptor, v: vertex_descriptor): boolean { + return this.g.reference(u, v); + } + source (e: edge_descriptor): vertex_descriptor { + return this.g.parent(e); + } + target (e: edge_descriptor): vertex_descriptor { + return this.g.child(e); + } + outEdges (v: vertex_descriptor): out_edge_iterator { + return this.g.children(v); + } + outDegree (v: vertex_descriptor): number { + return this.g.numChildren(v); + } + vertices (): IterableIterator { + return this.g.vertices(); + } + numVertices (): number { + return this.g.numVertices(); + } + readonly directed_category: directional; + readonly edge_parallel_category: parallel; + readonly traversal_category: traversal; + g: BaseGraph; +} diff --git a/cocos/core/pipeline/custom/index.jsb.ts b/cocos/core/pipeline/custom/index.jsb.ts index 7d82f809fc..3d7115c0ea 100644 --- a/cocos/core/pipeline/custom/index.jsb.ts +++ b/cocos/core/pipeline/custom/index.jsb.ts @@ -25,17 +25,21 @@ declare const render: any; -import { Pipeline } from './pipeline'; -import { rebuildLayoutGraph } from './effect'; import { legacyCC } from '../../global-exports'; +import { Pipeline, PipelineBuilder } from './pipeline'; +import { buildDeferredLayout, buildForwardLayout } from './effect'; export function createCustomPipeline (): Pipeline { - return render.Factory.createPipeline(); + const root = legacyCC.director.root; + const ppl = render.Factory.createPipeline(); + if (root.useDeferredPipeline) { + buildDeferredLayout(ppl); + } else { + buildForwardLayout(ppl); + } + return ppl; } -export function registerRebuildLayoutGraph() { - const director = legacyCC.director; - if (director.root.usesCustomPipeline) { - director.on(legacyCC.Director.EVENT_BEFORE_DRAW, rebuildLayoutGraph); - } +export function setCustomPipelineBuilder (builder: PipelineBuilder) { + // not implemented yet } diff --git a/cocos/core/pipeline/custom/index.ts b/cocos/core/pipeline/custom/index.ts index 26d09084e4..3028c2bc92 100644 --- a/cocos/core/pipeline/custom/index.ts +++ b/cocos/core/pipeline/custom/index.ts @@ -23,9 +23,28 @@ THE SOFTWARE. */ -import { Pipeline } from './pipeline'; +import { Pipeline, PipelineBuilder } from './pipeline'; import { WebPipeline } from './web-pipeline'; +import { buildDeferredLayout, buildForwardLayout } from './effect'; +import { macro } from '../../platform/macro'; + +let _pipeline: WebPipeline | null = null; export function createCustomPipeline (): Pipeline { - return new WebPipeline(); + const ppl = new WebPipeline(); + const pplName = macro.CUSTOM_PIPELINE_NAME; + ppl.setCustomPipelineName(pplName); + if (ppl.usesDeferredPipeline) { + buildDeferredLayout(ppl); + } else { + buildForwardLayout(ppl); + } + _pipeline = ppl; + return ppl; +} + +export function setCustomPipelineBuilder (builder: PipelineBuilder) { + if (_pipeline) { + _pipeline.builder = builder; + } } diff --git a/cocos/core/pipeline/custom/layout-graph.ts b/cocos/core/pipeline/custom/layout-graph.ts index e354b2f0c8..2f708b4924 100644 --- a/cocos/core/pipeline/custom/layout-graph.ts +++ b/cocos/core/pipeline/custom/layout-graph.ts @@ -124,6 +124,14 @@ export const enum LayoutGraphValue { RenderPhase, } +export function getLayoutGraphValueName (e: LayoutGraphValue): string { + switch (e) { + case LayoutGraphValue.RenderStage: return 'RenderStage'; + case LayoutGraphValue.RenderPhase: return 'RenderPhase'; + default: return ''; + } +} + interface LayoutGraphValueType { [LayoutGraphValue.RenderStage]: number [LayoutGraphValue.RenderPhase]: RenderPhase @@ -662,7 +670,7 @@ export class DescriptorSetLayoutData { slot: number; capacity: number; readonly descriptorBlocks: DescriptorBlockData[] = []; - readonly uniformBlocks: Map = new Map(); + readonly uniformBlocks: Map = new Map(); } export class DescriptorSetData { @@ -703,6 +711,14 @@ export const enum LayoutGraphDataValue { RenderPhase, } +export function getLayoutGraphDataValueName (e: LayoutGraphDataValue): string { + switch (e) { + case LayoutGraphDataValue.RenderStage: return 'RenderStage'; + case LayoutGraphDataValue.RenderPhase: return 'RenderPhase'; + default: return ''; + } +} + interface LayoutGraphDataValueType { [LayoutGraphDataValue.RenderStage]: RenderStageData [LayoutGraphDataValue.RenderPhase]: RenderPhaseData @@ -1043,6 +1059,9 @@ export class LayoutGraphData implements impl.BidirectionalGraph getUpdate (v: number): UpdateFrequency { return this._updateFrequencies[v]; } + setUpdate (v: number, value: UpdateFrequency) { + this._updateFrequencies[v] = value; + } getLayout (v: number): PipelineLayoutData { return this._layouts[v]; } diff --git a/cocos/core/pipeline/custom/pipeline.ts b/cocos/core/pipeline/custom/pipeline.ts index 09e6c7bf19..09800827c6 100644 --- a/cocos/core/pipeline/custom/pipeline.ts +++ b/cocos/core/pipeline/custom/pipeline.ts @@ -29,26 +29,30 @@ * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= */ /* eslint-disable max-len */ +import { Material } from '../../assets'; import { Camera } from '../../renderer/scene/camera'; import { GeometryRenderer } from '../geometry-renderer'; -import { Buffer, Color, DescriptorSet, DescriptorSetLayout, DrawInfo, Format, InputAssembler, PipelineState, Rect, Sampler, Swapchain, Texture, Viewport } from '../../gfx'; +import { Buffer, Color, CommandBuffer, DescriptorSet, DescriptorSetLayout, Device, DrawInfo, Format, InputAssembler, PipelineState, Rect, Sampler, Swapchain, Texture, UniformBlock, Viewport } from '../../gfx'; import { GlobalDSManager } from '../global-descriptor-set-manager'; import { DescriptorBlockFlattened, DescriptorBlockIndex } from './layout-graph'; import { Mat4, Quat, Vec2, Vec4 } from '../../math'; import { MacroRecord } from '../../renderer/core/pass-utils'; import { PipelineSceneData } from '../pipeline-scene-data'; -import { QueueHint, ResourceResidency, SceneFlags, TaskType, UpdateFrequency } from './types'; -import { ComputeView, CopyPair, MovePair, RasterView } from './render-graph'; +import { ComputeView, LightInfo, QueueHint, RasterView, ResourceResidency, SceneFlags, TaskType, UpdateFrequency } from './types'; +import { CopyPair, MovePair } from './render-graph'; import { RenderScene } from '../../renderer/core/render-scene'; import { RenderWindow } from '../../renderer/core/render-window'; -import { Light, Model } from '../../renderer/scene'; +import { Model } from '../../renderer/scene'; export abstract class PipelineRuntime { public abstract activate(swapchain: Swapchain): boolean; public abstract destroy(): boolean; public abstract render(cameras: Camera[]): void; + public abstract get device(): Device; public abstract get globalDSManager(): GlobalDSManager; public abstract get descriptorSetLayout(): DescriptorSetLayout; + public abstract get descriptorSet(): DescriptorSet; + public abstract get commandBuffers(): CommandBuffer[]; public abstract get pipelineSceneData(): PipelineSceneData; public abstract get constantMacros(): string; public abstract get profiler(): Model | null; @@ -56,6 +60,9 @@ export abstract class PipelineRuntime { public abstract get geometryRenderer(): GeometryRenderer | null; public abstract get shadingScale(): number; public abstract set shadingScale(scale: number); + public abstract getMacroString(name: string): string; + public abstract getMacroInt(name: string): number; + public abstract getMacroBool(name: string): boolean; public abstract setMacroString(name: string, value: string): void; public abstract setMacroInt(name: string, value: number): void; public abstract setMacroBool(name: string, value: boolean): void; @@ -79,37 +86,39 @@ export abstract class Setter { } export abstract class RasterQueueBuilder extends Setter { - public abstract addSceneOfCamera(camera: Camera, light: Light | null, sceneFlags: SceneFlags, name: string): void; - public abstract addSceneOfCamera(camera: Camera, light: Light | null, sceneFlags: SceneFlags): void; + public abstract addSceneOfCamera(camera: Camera, light: LightInfo, sceneFlags: SceneFlags, name: string): void; + public abstract addSceneOfCamera(camera: Camera, light: LightInfo, sceneFlags: SceneFlags): void; public abstract addScene(name: string, sceneFlags: SceneFlags): void; - public abstract addFullscreenQuad(shader: string, name: string): void; - public abstract addFullscreenQuad(shader: string): void; + public abstract addFullscreenQuad(material: Material, sceneFlags: SceneFlags, name: string): void; + public abstract addFullscreenQuad(material: Material, sceneFlags: SceneFlags): void; + public abstract addCameraQuad(camera: Camera, material: Material, sceneFlags: SceneFlags, name: string): void; + public abstract addCameraQuad(camera: Camera, material: Material, sceneFlags: SceneFlags): void; + public abstract clearRenderTarget(name: string, color: Color): void; + public abstract setViewport(viewport: Viewport): void; } export abstract class RasterPassBuilder extends Setter { public abstract addRasterView(name: string, view: RasterView): void; public abstract addComputeView(name: string, view: ComputeView): void; - public abstract addQueue(hint: QueueHint, layoutName: string, name: string): RasterQueueBuilder; - public abstract addQueue(hint: QueueHint, layoutName: string): RasterQueueBuilder; + public abstract addQueue(hint: QueueHint, name: string): RasterQueueBuilder; public abstract addQueue(hint: QueueHint): RasterQueueBuilder; - public abstract addFullscreenQuad(shader: string, layoutName: string, name: string): void; - public abstract addFullscreenQuad(shader: string, layoutName: string): void; - public abstract addFullscreenQuad(shader: string): void; + public abstract addFullscreenQuad(material: Material, sceneFlags: SceneFlags, name: string): void; + public abstract addFullscreenQuad(material: Material, sceneFlags: SceneFlags): void; + public abstract addCameraQuad(camera: Camera, material: Material, sceneFlags: SceneFlags, name: string): void; + public abstract addCameraQuad(camera: Camera, material: Material, sceneFlags: SceneFlags): void; + public abstract setViewport(viewport: Viewport): void; } export abstract class ComputeQueueBuilder extends Setter { - public abstract addDispatch(shader: string, threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number, layoutName: string, name: string): void; - public abstract addDispatch(shader: string, threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number, layoutName: string): void; + public abstract addDispatch(shader: string, threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number, name: string): void; public abstract addDispatch(shader: string, threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number): void; } export abstract class ComputePassBuilder extends Setter { public abstract addComputeView(name: string, view: ComputeView): void; - public abstract addQueue(layoutName: string, name: string): ComputeQueueBuilder; - public abstract addQueue(layoutName: string): ComputeQueueBuilder; + public abstract addQueue(name: string): ComputeQueueBuilder; public abstract addQueue(): ComputeQueueBuilder; - public abstract addDispatch(shader: string, threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number, layoutName: string, name: string): void; - public abstract addDispatch(shader: string, threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number, layoutName: string): void; + public abstract addDispatch(shader: string, threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number, name: string): void; public abstract addDispatch(shader: string, threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number): void; } @@ -150,12 +159,14 @@ export abstract class LayoutGraphBuilder { public abstract addRenderPhase(name: string, parentID: number): number; public abstract addShader(name: string, parentPhaseID: number): void; public abstract addDescriptorBlock(nodeID: number, index: DescriptorBlockIndex, block: DescriptorBlockFlattened): void; + public abstract addUniformBlock(nodeID: number, index: DescriptorBlockIndex, name: string, uniformBlock: UniformBlock): void; public abstract reserveDescriptorBlock(nodeID: number, index: DescriptorBlockIndex, block: DescriptorBlockFlattened): void; public abstract compile(): number; public abstract print(): string; } export abstract class Pipeline extends PipelineRuntime { + public abstract containsResource(name: string): boolean; public abstract addRenderTexture(name: string, format: Format, width: number, height: number, renderWindow: RenderWindow): number; public abstract addRenderTarget(name: string, format: Format, width: number, height: number, residency: ResourceResidency): number; public abstract addDepthStencil(name: string, format: Format, width: number, height: number, residency: ResourceResidency): number; @@ -173,5 +184,9 @@ export abstract class Pipeline extends PipelineRuntime { public abstract getDescriptorSetLayout(shaderName: string, freq: UpdateFrequency): DescriptorSetLayout | null; } +export abstract class PipelineBuilder { + public abstract setup(cameras: Camera[], pipeline: Pipeline): void; +} + export class Factory { } diff --git a/cocos/core/pipeline/custom/render-graph.ts b/cocos/core/pipeline/custom/render-graph.ts index b7e5a3dcaf..1f7a4146f2 100644 --- a/cocos/core/pipeline/custom/render-graph.ts +++ b/cocos/core/pipeline/custom/render-graph.ts @@ -30,10 +30,10 @@ */ /* eslint-disable max-len */ import * as impl from './graph'; +import { Material } from '../../assets'; import { Camera } from '../../renderer/scene/camera'; -import { AccessFlagBit, Buffer, ClearFlagBit, Color, Format, Framebuffer, LoadOp, SampleCount, Sampler, StoreOp, Swapchain, Texture, TextureFlagBit } from '../../gfx'; -import { QueueHint, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags } from './types'; -import { Light } from '../../renderer/scene'; +import { AccessFlagBit, Buffer, ClearFlagBit, Color, Format, Framebuffer, SampleCount, Sampler, Swapchain, Texture, TextureFlagBit, Viewport } from '../../gfx'; +import { ComputeView, LightInfo, QueueHint, RasterView, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags } from './types'; export class ResourceDesc { dimension: ResourceDimension = ResourceDimension.BUFFER; @@ -84,6 +84,17 @@ export const enum ResourceGraphValue { Swapchain, } +export function getResourceGraphValueName (e: ResourceGraphValue): string { + switch (e) { + case ResourceGraphValue.Managed: return 'Managed'; + case ResourceGraphValue.PersistentBuffer: return 'PersistentBuffer'; + case ResourceGraphValue.PersistentTexture: return 'PersistentTexture'; + case ResourceGraphValue.Framebuffer: return 'Framebuffer'; + case ResourceGraphValue.Swapchain: return 'Swapchain'; + default: return ''; + } +} + interface ResourceGraphValueType { [ResourceGraphValue.Managed]: ManagedResource [ResourceGraphValue.PersistentBuffer]: Buffer @@ -594,92 +605,6 @@ export class ResourceGraph implements impl.BidirectionalGraph readonly _valueIndex: Map = new Map(); } -export const enum AttachmentType { - RENDER_TARGET, - DEPTH_STENCIL, -} - -export function getAttachmentTypeName (e: AttachmentType): string { - switch (e) { - case AttachmentType.RENDER_TARGET: - return 'RENDER_TARGET'; - case AttachmentType.DEPTH_STENCIL: - return 'DEPTH_STENCIL'; - default: - return ''; - } -} - -export const enum AccessType { - READ, - READ_WRITE, - WRITE, -} - -export function getAccessTypeName (e: AccessType): string { - switch (e) { - case AccessType.READ: - return 'READ'; - case AccessType.READ_WRITE: - return 'READ_WRITE'; - case AccessType.WRITE: - return 'WRITE'; - default: - return ''; - } -} - -export class RasterView { - constructor ( - slotName = '', - accessType: AccessType = AccessType.WRITE, - attachmentType: AttachmentType = AttachmentType.RENDER_TARGET, - loadOp: LoadOp = LoadOp.LOAD, - storeOp: StoreOp = StoreOp.STORE, - clearFlags: ClearFlagBit = ClearFlagBit.ALL, - clearColor: Color = new Color(), - ) { - this.slotName = slotName; - this.accessType = accessType; - this.attachmentType = attachmentType; - this.loadOp = loadOp; - this.storeOp = storeOp; - this.clearFlags = clearFlags; - this.clearColor = clearColor; - } - slotName: string; - accessType: AccessType; - attachmentType: AttachmentType; - loadOp: LoadOp; - storeOp: StoreOp; - clearFlags: ClearFlagBit; - readonly clearColor: Color; -} - -export const enum ClearValueType { - FLOAT_TYPE, - INT_TYPE, -} - -export function getClearValueTypeName (e: ClearValueType): string { - switch (e) { - case ClearValueType.FLOAT_TYPE: - return 'FLOAT_TYPE'; - case ClearValueType.INT_TYPE: - return 'INT_TYPE'; - default: - return ''; - } -} - -export class ComputeView { - name = ''; - accessType: AccessType = AccessType.READ; - clearFlags: ClearFlagBit = ClearFlagBit.NONE; - readonly clearColor: Color = new Color(); - clearValueType: ClearValueType = ClearValueType.FLOAT_TYPE; -} - export class RasterSubpass { readonly rasterViews: Map = new Map(); readonly computeViews: Map = new Map(); @@ -980,6 +905,7 @@ export class RasterPass { readonly subpassGraph: SubpassGraph = new SubpassGraph(); width = 0; height = 0; + readonly viewport: Viewport = new Viewport(); } export class ComputePass { @@ -1061,6 +987,17 @@ export class RaytracePass { readonly computeViews: Map = new Map(); } +export class ClearView { + constructor (slotName = '', clearFlags: ClearFlagBit = gfx.ClearFlagBit.ALL, clearColor: Color = new Color()) { + this.slotName = slotName; + this.clearFlags = clearFlags; + this.clearColor = clearColor; + } + slotName: string; + clearFlags: ClearFlagBit; + readonly clearColor: Color; +} + export class RenderQueue { constructor (hint: QueueHint = QueueHint.RENDER_OPAQUE) { this.hint = hint; @@ -1069,13 +1006,14 @@ export class RenderQueue { } export class SceneData { - constructor (name = '', flags: SceneFlags = SceneFlags.NONE) { + constructor (name = '', flags: SceneFlags = SceneFlags.NONE, light: LightInfo = new LightInfo()) { this.name = name; + this.light = light; this.flags = flags; } name: string; camera: Camera | null = null; - light: Light | null = null; + readonly light: LightInfo; flags: SceneFlags; readonly scenes: string[] = []; } @@ -1094,10 +1032,14 @@ export class Dispatch { } export class Blit { - constructor (shader = '') { - this.shader = shader; + constructor (material: Material | null, sceneFlags: SceneFlags, camera: Camera | null) { + this.material = material; + this.sceneFlags = sceneFlags; + this.camera = camera; } - shader: string; + /*object*/ material: Material | null; + sceneFlags: SceneFlags; + camera: Camera | null; } export class Present { @@ -1135,6 +1077,26 @@ export const enum RenderGraphValue { Scene, Blit, Dispatch, + Clear, + Viewport, +} + +export function getRenderGraphValueName (e: RenderGraphValue): string { + switch (e) { + case RenderGraphValue.Raster: return 'Raster'; + case RenderGraphValue.Compute: return 'Compute'; + case RenderGraphValue.Copy: return 'Copy'; + case RenderGraphValue.Move: return 'Move'; + case RenderGraphValue.Present: return 'Present'; + case RenderGraphValue.Raytrace: return 'Raytrace'; + case RenderGraphValue.Queue: return 'Queue'; + case RenderGraphValue.Scene: return 'Scene'; + case RenderGraphValue.Blit: return 'Blit'; + case RenderGraphValue.Dispatch: return 'Dispatch'; + case RenderGraphValue.Clear: return 'Clear'; + case RenderGraphValue.Viewport: return 'Viewport'; + default: return ''; + } } interface RenderGraphValueType { @@ -1148,6 +1110,8 @@ interface RenderGraphValueType { [RenderGraphValue.Scene]: SceneData [RenderGraphValue.Blit]: Blit [RenderGraphValue.Dispatch]: Dispatch + [RenderGraphValue.Clear]: ClearView[] + [RenderGraphValue.Viewport]: Viewport } export interface RenderGraphVisitor { @@ -1161,6 +1125,8 @@ export interface RenderGraphVisitor { scene(value: SceneData): unknown; blit(value: Blit): unknown; dispatch(value: Dispatch): unknown; + clear(value: ClearView[]): unknown; + viewport(value: Viewport): unknown; } type RenderGraphObject = RasterPass @@ -1172,7 +1138,9 @@ type RenderGraphObject = RasterPass | RenderQueue | SceneData | Blit -| Dispatch; +| Dispatch +| ClearView[] +| Viewport; //----------------------------------------------------------------- // Graph Concept @@ -1553,12 +1521,18 @@ export class RenderGraph implements impl.BidirectionalGraph getLayout (v: number): string { return this._layoutNodes[v]; } + setLayout (v: number, value: string) { + this._layoutNodes[v] = value; + } getData (v: number): RenderData { return this._data[v]; } getValid (v: number): boolean { return this._valid[v]; } + setValid (v: number, value: boolean) { + this._valid[v] = value; + } //----------------------------------------------------------------- // PolymorphicGraph holds (id: RenderGraphValue, v: number): boolean { @@ -1607,6 +1581,10 @@ export class RenderGraph implements impl.BidirectionalGraph return visitor.blit(vert._object as Blit); case RenderGraphValue.Dispatch: return visitor.dispatch(vert._object as Dispatch); + case RenderGraphValue.Clear: + return visitor.clear(vert._object as ClearView[]); + case RenderGraphValue.Viewport: + return visitor.viewport(vert._object as Viewport); default: throw Error('polymorphic type not found'); } @@ -1681,6 +1659,20 @@ export class RenderGraph implements impl.BidirectionalGraph throw Error('value id not match'); } } + getClear (v: number): ClearView[] { + if (this._vertices[v]._id === RenderGraphValue.Clear) { + return this._vertices[v]._object as ClearView[]; + } else { + throw Error('value id not match'); + } + } + getViewport (v: number): Viewport { + if (this._vertices[v]._id === RenderGraphValue.Viewport) { + return this._vertices[v]._object as Viewport; + } else { + throw Error('value id not match'); + } + } tryGetRaster (v: number): RasterPass | null { if (this._vertices[v]._id === RenderGraphValue.Raster) { return this._vertices[v]._object as RasterPass; @@ -1751,6 +1743,20 @@ export class RenderGraph implements impl.BidirectionalGraph return null; } } + tryGetClear (v: number): ClearView[] | null { + if (this._vertices[v]._id === RenderGraphValue.Clear) { + return this._vertices[v]._object as ClearView[]; + } else { + return null; + } + } + tryGetViewport (v: number): Viewport | null { + if (this._vertices[v]._id === RenderGraphValue.Viewport) { + return this._vertices[v]._object as Viewport; + } else { + return null; + } + } //----------------------------------------------------------------- // ReferenceGraph // type reference_descriptor = impl.ED; diff --git a/cocos/core/pipeline/custom/types.ts b/cocos/core/pipeline/custom/types.ts index 571136effb..f891839276 100644 --- a/cocos/core/pipeline/custom/types.ts +++ b/cocos/core/pipeline/custom/types.ts @@ -29,6 +29,9 @@ * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= */ /* eslint-disable max-len */ +import { ClearFlagBit, Color, LoadOp, StoreOp } from '../../gfx'; +import { Light } from '../../renderer/scene'; + export const enum UpdateFrequency { PER_INSTANCE, PER_BATCH, @@ -180,9 +183,130 @@ export function getTaskTypeName (e: TaskType): string { export const enum SceneFlags { NONE = 0, - OPAQUE_OBJECT = 0x1, - CUTOUT_OBJECT = 0x2, - TRANSPARENT_OBJECT = 0x4, - SHADOW_CASTER = 0x8, + OPAQUE_OBJECT = 1, + CUTOUT_OBJECT = 2, + TRANSPARENT_OBJECT = 4, + SHADOW_CASTER = 8, + UI = 16, + DEFAULT_LIGHTING = 32, + VOLUMETRIC_LIGHTING = 64, + CLUSTERED_LIGHTING = 128, + PLANAR_SHADOW = 256, + GEOMETRY = 512, + PROFILER = 1024, ALL = 0xFFFFFFFF, } + +export const enum LightingMode { + NONE, + DEFAULT, + CLUSTERED, +} + +export function getLightingModeName (e: LightingMode): string { + switch (e) { + case LightingMode.NONE: + return 'NONE'; + case LightingMode.DEFAULT: + return 'DEFAULT'; + case LightingMode.CLUSTERED: + return 'CLUSTERED'; + default: + return ''; + } +} + +export const enum AttachmentType { + RENDER_TARGET, + DEPTH_STENCIL, +} + +export function getAttachmentTypeName (e: AttachmentType): string { + switch (e) { + case AttachmentType.RENDER_TARGET: + return 'RENDER_TARGET'; + case AttachmentType.DEPTH_STENCIL: + return 'DEPTH_STENCIL'; + default: + return ''; + } +} + +export const enum AccessType { + READ, + READ_WRITE, + WRITE, +} + +export function getAccessTypeName (e: AccessType): string { + switch (e) { + case AccessType.READ: + return 'READ'; + case AccessType.READ_WRITE: + return 'READ_WRITE'; + case AccessType.WRITE: + return 'WRITE'; + default: + return ''; + } +} + +export class RasterView { + constructor ( + slotName = '', + accessType: AccessType = AccessType.WRITE, + attachmentType: AttachmentType = AttachmentType.RENDER_TARGET, + loadOp: LoadOp = LoadOp.LOAD, + storeOp: StoreOp = StoreOp.STORE, + clearFlags: ClearFlagBit = ClearFlagBit.ALL, + clearColor: Color = new Color(), + ) { + this.slotName = slotName; + this.accessType = accessType; + this.attachmentType = attachmentType; + this.loadOp = loadOp; + this.storeOp = storeOp; + this.clearFlags = clearFlags; + this.clearColor = clearColor; + } + slotName: string; + accessType: AccessType; + attachmentType: AttachmentType; + loadOp: LoadOp; + storeOp: StoreOp; + clearFlags: ClearFlagBit; + readonly clearColor: Color; +} + +export const enum ClearValueType { + FLOAT_TYPE, + INT_TYPE, +} + +export function getClearValueTypeName (e: ClearValueType): string { + switch (e) { + case ClearValueType.FLOAT_TYPE: + return 'FLOAT_TYPE'; + case ClearValueType.INT_TYPE: + return 'INT_TYPE'; + default: + return ''; + } +} + +export class ComputeView { + name = ''; + accessType: AccessType = AccessType.READ; + clearFlags: ClearFlagBit = ClearFlagBit.NONE; + readonly clearColor: Color = new Color(); + clearValueType: ClearValueType = ClearValueType.FLOAT_TYPE; +} + +export class LightInfo { + constructor (light: Light | null = null, level = 0) { + this.light = light; + this.level = level; + } + /*object*/ light: Light | null; + level: number; +} diff --git a/cocos/core/pipeline/custom/ubos.ts b/cocos/core/pipeline/custom/ubos.ts deleted file mode 100644 index 840a2cb698..0000000000 --- a/cocos/core/pipeline/custom/ubos.ts +++ /dev/null @@ -1,500 +0,0 @@ -/* - Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - */ - -import { UBOGlobal, UBOShadow, UBOCamera, UNIFORM_SHADOWMAP_BINDING, - supportsR32FloatTexture, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING } from '../define'; -import { Device, BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet } from '../../gfx'; -import { Camera } from '../../renderer/scene/camera'; -import { Mat4, Vec3, Vec4, Color } from '../../math'; -import { WebPipeline } from './web-pipeline'; -import { legacyCC } from '../../global-exports'; -import { CSMLevel, PCFType, Shadows, ShadowType } from '../../renderer/scene/shadows'; -import { updatePlanarNormalAndDistance, updatePlanarPROJ } from '../scene-culling'; -import { Light, LightType } from '../../renderer/scene/light'; -import { DirectionalLight, SpotLight } from '../../renderer/scene'; -import { RenderWindow } from '../../renderer/core/render-window'; -import { builtinResMgr } from '../../builtin/builtin-res-mgr'; -import { Texture2D } from '../../assets'; -import { DebugView, DebugViewCompositeType } from '../debug-view'; - -const _matShadowView = new Mat4(); -const _matShadowProj = new Mat4(); -const _matShadowViewProj = new Mat4(); -const _vec4ShadowInfo = new Vec4(); -const _lightDir = new Vec4(0.0, 0.0, 1.0, 0.0); - -export class PipelineUBO { - public static updateGlobalUBOView (window: RenderWindow, bufferView: Float32Array) { - const director = legacyCC.director; - const root = director.root; - const fv = bufferView; - - const shadingWidth = Math.floor(window.width); - const shadingHeight = Math.floor(window.height); - - // update UBOGlobal - fv[UBOGlobal.TIME_OFFSET] = root.cumulativeTime; - fv[UBOGlobal.TIME_OFFSET + 1] = root.frameTime; - fv[UBOGlobal.TIME_OFFSET + 2] = director.getTotalFrames(); - - fv[UBOGlobal.SCREEN_SIZE_OFFSET] = shadingWidth; - fv[UBOGlobal.SCREEN_SIZE_OFFSET + 1] = shadingHeight; - fv[UBOGlobal.SCREEN_SIZE_OFFSET + 2] = 1.0 / shadingWidth; - fv[UBOGlobal.SCREEN_SIZE_OFFSET + 3] = 1.0 / shadingHeight; - - fv[UBOGlobal.NATIVE_SIZE_OFFSET] = shadingWidth; - fv[UBOGlobal.NATIVE_SIZE_OFFSET + 1] = shadingHeight; - fv[UBOGlobal.NATIVE_SIZE_OFFSET + 2] = 1.0 / fv[UBOGlobal.NATIVE_SIZE_OFFSET]; - fv[UBOGlobal.NATIVE_SIZE_OFFSET + 3] = 1.0 / fv[UBOGlobal.NATIVE_SIZE_OFFSET + 1]; - - const debugView = root.debugView; - if (debugView) { - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET] = debugView.singleMode as number; - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 1] = debugView.lightingWithAlbedo ? 1.0 : 0.0; - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 2] = debugView.csmLayerColoration ? 1.0 : 0.0; - for (let i = DebugViewCompositeType.DIRECT_DIFFUSE as number; i < DebugViewCompositeType.MAX_BIT_COUNT; i++) { - fv[UBOGlobal.DEBUG_VIEW_COMPOSITE_PACK_1_OFFSET + i] = debugView.isCompositeModeEnabled(i) ? 1.0 : 0.0; - } - } else { - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET] = 0.0; - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 1] = 1.0; - fv[UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 2] = 0.0; - for (let i = DebugViewCompositeType.DIRECT_DIFFUSE as number; i < DebugViewCompositeType.MAX_BIT_COUNT; i++) { - fv[UBOGlobal.DEBUG_VIEW_COMPOSITE_PACK_1_OFFSET + i] = 1.0; - } - } - } - - public static updateCameraUBOView (pipeline: WebPipeline, bufferView: Float32Array, - camera: Camera) { - const scene = camera.scene ? camera.scene : legacyCC.director.getScene().renderScene; - const mainLight = scene.mainLight; - const sceneData = pipeline.pipelineSceneData; - const ambient = sceneData.ambient; - const fog = sceneData.fog; - const shadowInfo = sceneData.shadows; - const cv = bufferView; - const exposure = camera.exposure; - const isHDR = sceneData.isHDR; - - // update camera ubo - cv[UBOCamera.SCREEN_SCALE_OFFSET] = sceneData.shadingScale; - cv[UBOCamera.SCREEN_SCALE_OFFSET + 1] = sceneData.shadingScale; - cv[UBOCamera.SCREEN_SCALE_OFFSET + 2] = 1.0 / cv[UBOCamera.SCREEN_SCALE_OFFSET]; - cv[UBOCamera.SCREEN_SCALE_OFFSET + 3] = 1.0 / cv[UBOCamera.SCREEN_SCALE_OFFSET + 1]; - - cv[UBOCamera.EXPOSURE_OFFSET] = exposure; - cv[UBOCamera.EXPOSURE_OFFSET + 1] = 1.0 / exposure; - cv[UBOCamera.EXPOSURE_OFFSET + 2] = isHDR ? 1.0 : 0.0; - cv[UBOCamera.EXPOSURE_OFFSET + 3] = 0.0; - - if (mainLight) { - const shadowEnable = (mainLight.shadowEnabled && shadowInfo.type === ShadowType.ShadowMap) ? 1.0 : 0.0; - const mainLightDir = mainLight.direction; - _lightDir.set(mainLightDir.x, mainLightDir.y, mainLightDir.z, shadowEnable); - Vec4.toArray(cv, _lightDir, UBOCamera.MAIN_LIT_DIR_OFFSET); - Vec3.toArray(cv, mainLight.color, UBOCamera.MAIN_LIT_COLOR_OFFSET); - if (mainLight.useColorTemperature) { - const colorTempRGB = mainLight.colorTemperatureRGB; - cv[UBOCamera.MAIN_LIT_COLOR_OFFSET] *= colorTempRGB.x; - cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 1] *= colorTempRGB.y; - cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 2] *= colorTempRGB.z; - } - - if (isHDR) { - cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance * exposure; - } else { - cv[UBOCamera.MAIN_LIT_COLOR_OFFSET + 3] = mainLight.illuminance; - } - } else { - _lightDir.set(0, 0, 1, 0); - Vec4.toArray(cv, _lightDir, UBOCamera.MAIN_LIT_DIR_OFFSET); - Vec4.toArray(cv, Vec4.ZERO, UBOCamera.MAIN_LIT_COLOR_OFFSET); - } - - const skyColor = ambient.skyColor; - if (isHDR) { - skyColor.w = ambient.skyIllum * exposure; - } else { - skyColor.w = ambient.skyIllum; - } - cv[UBOCamera.AMBIENT_SKY_OFFSET + 0] = skyColor.x; - cv[UBOCamera.AMBIENT_SKY_OFFSET + 1] = skyColor.y; - cv[UBOCamera.AMBIENT_SKY_OFFSET + 2] = skyColor.z; - cv[UBOCamera.AMBIENT_SKY_OFFSET + 3] = skyColor.w; - cv[UBOCamera.AMBIENT_GROUND_OFFSET + 0] = ambient.groundAlbedo.x; - cv[UBOCamera.AMBIENT_GROUND_OFFSET + 1] = ambient.groundAlbedo.y; - cv[UBOCamera.AMBIENT_GROUND_OFFSET + 2] = ambient.groundAlbedo.z; - const skybox = pipeline.pipelineSceneData.skybox; - cv[UBOCamera.AMBIENT_GROUND_OFFSET + 3] = skybox.envmap ? skybox.envmap?.mipmapLevel : 1.0; - - Mat4.toArray(cv, camera.matView, UBOCamera.MAT_VIEW_OFFSET); - Mat4.toArray(cv, camera.node.worldMatrix, UBOCamera.MAT_VIEW_INV_OFFSET); - Vec3.toArray(cv, camera.position, UBOCamera.CAMERA_POS_OFFSET); - - Mat4.toArray(cv, camera.matProj, UBOCamera.MAT_PROJ_OFFSET); - Mat4.toArray(cv, camera.matProjInv, UBOCamera.MAT_PROJ_INV_OFFSET); - Mat4.toArray(cv, camera.matViewProj, UBOCamera.MAT_VIEW_PROJ_OFFSET); - Mat4.toArray(cv, camera.matViewProjInv, UBOCamera.MAT_VIEW_PROJ_INV_OFFSET); - cv[UBOCamera.CAMERA_POS_OFFSET + 3] = this.getCombineSignY(); - - const colorTempRGB = fog.colorArray; - cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET] = colorTempRGB.x; - cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET + 1] = colorTempRGB.y; - cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET + 2] = colorTempRGB.z; - cv[UBOCamera.GLOBAL_FOG_COLOR_OFFSET + 3] = colorTempRGB.z; - - cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET] = fog.fogStart; - cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET + 1] = fog.fogEnd; - cv[UBOCamera.GLOBAL_FOG_BASE_OFFSET + 2] = fog.fogDensity; - - cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET] = fog.fogTop; - cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET + 1] = fog.fogRange; - cv[UBOCamera.GLOBAL_FOG_ADD_OFFSET + 2] = fog.fogAtten; - - cv[UBOCamera.NEAR_FAR_OFFSET] = camera.nearClip; - cv[UBOCamera.NEAR_FAR_OFFSET + 1] = camera.farClip; - - cv[UBOCamera.VIEW_PORT_OFFSET] = sceneData.shadingScale * camera.window.width * camera.viewport.x; - cv[UBOCamera.VIEW_PORT_OFFSET + 1] = sceneData.shadingScale * camera.window.height * camera.viewport.y; - cv[UBOCamera.VIEW_PORT_OFFSET + 2] = sceneData.shadingScale * camera.window.width * camera.viewport.z; - cv[UBOCamera.VIEW_PORT_OFFSET + 3] = sceneData.shadingScale * camera.window.height * camera.viewport.w; - } - - public static getPCFRadius (shadowInfo: Shadows, mainLight: DirectionalLight): number { - const shadowMapSize = shadowInfo.size.x; - switch (mainLight.shadowPcf) { - case PCFType.HARD: - return 0.0; - case PCFType.SOFT: - return 1.0 / (shadowMapSize * 0.5); - case PCFType.SOFT_2X: - return 2.0 / (shadowMapSize * 0.5); - case PCFType.SOFT_4X: - return 3.0 / (shadowMapSize * 0.5); - default: - } - return 0.0; - } - - public static updateShadowUBOView (pipeline: WebPipeline, shadowBufferView: Float32Array, camera: Camera) { - const device = pipeline.device; - const mainLight = camera.scene!.mainLight; - const sceneData = pipeline.pipelineSceneData; - const shadowInfo = sceneData.shadows; - const csmLayers = sceneData.csmLayers; - const sv = shadowBufferView; - const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; - - if (shadowInfo.enabled && mainLight) { - if (shadowInfo.type === ShadowType.ShadowMap) { - if (mainLight.shadowEnabled) { - if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1) { - const matShadowView = csmLayers.specialLayer.matShadowView; - const matShadowProj = csmLayers.specialLayer.matShadowProj; - const matShadowViewProj = csmLayers.specialLayer.matShadowViewProj; - const near = mainLight.shadowNear; - const far = mainLight.shadowFar; - - Mat4.toArray(sv, matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET); - - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowProj.m10; - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowProj.m14; - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowProj.m11; - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowProj.m15; - - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 0] = matShadowProj.m00; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 1] = matShadowProj.m05; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05; - - Mat4.toArray(sv, matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); - - _vec4ShadowInfo.set(near, far, 0, 1.0 - mainLight.shadowSaturation); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); - - _vec4ShadowInfo.set(0, packing, mainLight.shadowNormalBias, 0); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); - } else { - for (let i = 0; i < mainLight.csmLevel; i++) { - sv[UBOShadow.CSM_SPLITS_INFO_OFFSET + i] = csmLayers.layers[i].splitCameraFar / mainLight.shadowDistance; - - const matShadowView = csmLayers.layers[i].matShadowView; - Mat4.toArray(sv, matShadowView, UBOShadow.MAT_CSM_VIEW_OFFSET + 16 * i); - - const matShadowViewProj = csmLayers.layers[i].matShadowViewProj; - Mat4.toArray(sv, matShadowViewProj, UBOShadow.MAT_CSM_VIEW_PROJ_OFFSET + 16 * i); - - const matShadowViewProjAtlas = csmLayers.layers[i].matShadowViewProjAtlas; - Mat4.toArray(sv, matShadowViewProjAtlas, UBOShadow.MAT_CSM_VIEW_PROJ_ATLAS_OFFSET + 16 * i); - - const matShadowProj = csmLayers.layers[i].matShadowProj; - sv[UBOShadow.CSM_PROJ_DEPTH_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m10; - sv[UBOShadow.CSM_PROJ_DEPTH_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m14; - sv[UBOShadow.CSM_PROJ_DEPTH_INFO_OFFSET + 2 + 4 * i] = matShadowProj.m11; - sv[UBOShadow.CSM_PROJ_DEPTH_INFO_OFFSET + 3 + 4 * i] = matShadowProj.m15; - - sv[UBOShadow.CSM_PROJ_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m00; - sv[UBOShadow.CSM_PROJ_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m05; - sv[UBOShadow.CSM_PROJ_INFO_OFFSET + 2 + 4 * i] = 1.0 / matShadowProj.m00; - sv[UBOShadow.CSM_PROJ_INFO_OFFSET + 3 + 4 * i] = 1.0 / matShadowProj.m05; - } - - sv[UBOShadow.CSM_INFO_OFFSET + 0] = 0; - sv[UBOShadow.CSM_INFO_OFFSET + 1] = this.getPCFRadius(shadowInfo, mainLight); - sv[UBOShadow.CSM_INFO_OFFSET + 2] = 0; - sv[UBOShadow.CSM_INFO_OFFSET + 3] = 0; - - _vec4ShadowInfo.set(0, 0, 0, 1.0 - mainLight.shadowSaturation); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); - - _vec4ShadowInfo.set(0.0, packing, mainLight.shadowNormalBias, mainLight.csmLevel); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); - } - _vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, mainLight.shadowPcf, mainLight.shadowBias); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET); - } - } else { - updatePlanarPROJ(shadowInfo, mainLight, sv); - updatePlanarNormalAndDistance(shadowInfo, sv); - } - - Color.toArray(sv, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET); - } - } - - public static updateShadowUBOLightView (pipeline: WebPipeline, shadowBufferView: Float32Array, light: Light, level: number) { - const device = pipeline.device; - const sceneData = pipeline.pipelineSceneData; - const shadowInfo = sceneData.shadows; - const csmLayers = sceneData.csmLayers; - const sv = shadowBufferView; - const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; - switch (light.type) { - case LightType.DIRECTIONAL: { - const mainLight = light as DirectionalLight; - if (shadowInfo.enabled && mainLight && mainLight.shadowEnabled) { - if (shadowInfo.type === ShadowType.ShadowMap) { - let near = 0.1; - let far = 0; - let matShadowView; - let matShadowProj; - let matShadowViewProj; - let levelCount = 0; - if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1) { - matShadowView = csmLayers.specialLayer.matShadowView; - matShadowProj = csmLayers.specialLayer.matShadowProj; - matShadowViewProj = csmLayers.specialLayer.matShadowViewProj; - if (mainLight.shadowFixedArea) { - near = mainLight.shadowNear; - far = mainLight.shadowFar; - levelCount = 0; - } else { - near = 0.1; - far = csmLayers.specialLayer.shadowCameraFar; - levelCount = 1; - } - _vec4ShadowInfo.set(0.0, packing, mainLight.shadowNormalBias, 0); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); - } else { - const layer = csmLayers.layers[level]; - matShadowView = layer.matShadowView; - matShadowProj = layer.matShadowProj; - matShadowViewProj = layer.matShadowViewProj; - - near = layer.splitCameraNear; - far = layer.splitCameraFar; - levelCount = mainLight.csmLevel; - } - - Mat4.toArray(sv, matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET); - - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 0] = matShadowProj.m10; - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 1] = matShadowProj.m14; - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 2] = matShadowProj.m11; - sv[UBOShadow.SHADOW_PROJ_DEPTH_INFO_OFFSET + 3] = matShadowProj.m15; - - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 0] = matShadowProj.m00; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 1] = matShadowProj.m05; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00; - sv[UBOShadow.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05; - - Mat4.toArray(sv, matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); - - _vec4ShadowInfo.set(near, far, 0, 1.0 - mainLight.shadowSaturation); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); - - _vec4ShadowInfo.set(0.0, packing, mainLight.shadowNormalBias, levelCount); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); - - _vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, mainLight.shadowPcf, mainLight.shadowBias); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET); - } - } - break; - } - case LightType.SPOT: { - const spotLight = light as SpotLight; - Mat4.invert(_matShadowView, (light as any).node.getWorldMatrix()); - Mat4.toArray(sv, _matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET); - - Mat4.perspective(_matShadowProj, (light as any).angle, 1.0, 0.001, (light as any).range); - - Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); - Mat4.toArray(sv, _matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); - - _vec4ShadowInfo.set(0.01, (light as SpotLight).range, 0.0, 0.0); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); - - _vec4ShadowInfo.set(shadowInfo.size.x, shadowInfo.size.y, spotLight.shadowPcf, spotLight.shadowBias); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET); - - _vec4ShadowInfo.set(1.0, packing, spotLight.shadowNormalBias, 0.0); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); - break; - } - default: - } - - Color.toArray(sv, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET); - } - - protected _globalUBO = new Float32Array(UBOGlobal.COUNT); - protected _cameraUBO = new Float32Array(UBOCamera.COUNT); - protected _shadowUBO = new Float32Array(UBOShadow.COUNT); - static _combineSignY = 0; - protected declare _device: Device; - protected declare _pipeline: WebPipeline; - - /** - *|combinedSignY|clipSpaceSignY|screenSpaceSignY| Backends | - *| :--: | :--: | :--: | :--: | - *| 0 | -1 | -1 | Vulkan | - *| 1 | 1 | -1 | Metal | - *| 2 | -1 | 1 | | - *| 3 | 1 | 1 | GL-like | - */ - public static getCombineSignY () { - return PipelineUBO._combineSignY; - } - - private _initCombineSignY () { - const device = this._device; - PipelineUBO._combineSignY = (device.capabilities.screenSpaceSignY * 0.5 + 0.5) << 1 | (device.capabilities.clipSpaceSignY * 0.5 + 0.5); - } - - public activate (device: Device, pipeline: WebPipeline) { - this._device = device; - this._pipeline = pipeline; - const ds = this._pipeline.globalDSManager.globalDescriptorSet; - this._initCombineSignY(); - - const globalUBO = device.createBuffer(new BufferInfo( - BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, - MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, - UBOGlobal.SIZE, - UBOGlobal.SIZE, - )); - ds.bindBuffer(UBOGlobal.BINDING, globalUBO); - - const cameraUBO = device.createBuffer(new BufferInfo( - BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, - MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, - UBOCamera.SIZE, - UBOCamera.SIZE, - )); - ds.bindBuffer(UBOCamera.BINDING, cameraUBO); - const shadowUBO = device.createBuffer(new BufferInfo( - BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, - MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, - UBOShadow.SIZE, - UBOShadow.SIZE, - )); - ds.bindBuffer(UBOShadow.BINDING, shadowUBO); - } - - /** - * @en Update all UBOs - * @zh 更新全部 UBO。 - */ - public updateGlobalUBO (window: RenderWindow) { - const globalDSManager = this._pipeline.globalDSManager; - const ds = this._pipeline.globalDSManager.globalDescriptorSet; - const cmdBuffer = this._pipeline.device.commandBuffer; - ds.update(); - PipelineUBO.updateGlobalUBOView(window, this._globalUBO); - cmdBuffer.updateBuffer(ds.getBuffer(UBOGlobal.BINDING), this._globalUBO); - - globalDSManager.bindBuffer(UBOGlobal.BINDING, ds.getBuffer(UBOGlobal.BINDING)); - globalDSManager.update(); - } - - public updateCameraUBO (camera: Camera) { - const globalDSManager = this._pipeline.globalDSManager; - const ds = this._pipeline.globalDSManager.globalDescriptorSet; - const cmdBuffer = this._pipeline.device.commandBuffer; - PipelineUBO.updateCameraUBOView(this._pipeline, this._cameraUBO, camera); - cmdBuffer.updateBuffer(ds.getBuffer(UBOCamera.BINDING), this._cameraUBO); - - globalDSManager.bindBuffer(UBOCamera.BINDING, ds.getBuffer(UBOCamera.BINDING)); - globalDSManager.update(); - } - - public updateShadowUBO (camera: Camera) { - const sceneData = this._pipeline.pipelineSceneData; - const shadowInfo = sceneData.shadows; - if (!shadowInfo.enabled) return; - - const ds = this._pipeline.globalDSManager.globalDescriptorSet; - const cmdBuffer = this._pipeline.device.commandBuffer; - const shadowFrameBufferMap = sceneData.shadowFrameBufferMap; - const mainLight = camera.scene!.mainLight; - if (mainLight && shadowFrameBufferMap.has(mainLight)) { - ds.bindTexture(UNIFORM_SHADOWMAP_BINDING, shadowFrameBufferMap.get(mainLight)!.colorTextures[0]!); - } - PipelineUBO.updateShadowUBOView(this._pipeline, this._shadowUBO, camera); - ds.update(); - cmdBuffer.updateBuffer(ds.getBuffer(UBOShadow.BINDING), this._shadowUBO); - } - - public updateShadowUBOLight (globalDS: DescriptorSet, light: Light, level = 0) { - PipelineUBO.updateShadowUBOLightView(this._pipeline, this._shadowUBO, light, level); - globalDS.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); - globalDS.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); - globalDS.update(); - globalDS.getBuffer(UBOShadow.BINDING).update(this._shadowUBO); - } - - public updateShadowUBORange (offset: number, data: Mat4 | Color) { - if (data instanceof Mat4) { - Mat4.toArray(this._shadowUBO, data, offset); - } else if (data instanceof Color) { - Color.toArray(this._shadowUBO, data, offset); - } - } - - public destroy () { - } -} diff --git a/cocos/core/pipeline/custom/utils.ts b/cocos/core/pipeline/custom/utils.ts new file mode 100644 index 0000000000..ee00bad60a --- /dev/null +++ b/cocos/core/pipeline/custom/utils.ts @@ -0,0 +1,39 @@ +// https://stackoverflow.com/questions/56714318/how-to-disable-multiple-rules-for-eslint-nextline?msclkid=5d4c2298ba7911eca34d0ab30591752e + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export function replacer (key: unknown, value: unknown) { + if (value instanceof Map) { + return { + meta_t: 'Map', + value: Array.from(value.entries()).sort((a, b) => String(a[0]).localeCompare(b[0])), + }; + } else if (value instanceof Set) { + return { + meta_t: 'Set', + value: Array.from(value).sort(), + }; + } + return value; +} + +// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unused-vars +export function reviver (key: unknown, value: any) { + if (typeof value === 'object' && value !== null) { + if (value.meta_t === 'Map') { + return new Map(value.value); + } else if (value.meta_t === 'Set') { + return new Set(value.value); + } + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return value; +} + +export function stringify (data: unknown, space?: string | number | undefined) { + return JSON.stringify(data, replacer, space); +} + +export function parse (text: string) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return JSON.parse(text, reviver); +} diff --git a/cocos/core/pipeline/custom/web-descriptor-hierarchy.ts b/cocos/core/pipeline/custom/web-descriptor-hierarchy.ts index b587f56664..3ca6001025 100644 --- a/cocos/core/pipeline/custom/web-descriptor-hierarchy.ts +++ b/cocos/core/pipeline/custom/web-descriptor-hierarchy.ts @@ -25,58 +25,66 @@ ****************************************************************************/ import { EffectAsset } from '../../assets'; -import { Descriptor, DescriptorBlock, DescriptorBlockIndex, DescriptorDB, DescriptorTypeOrder, LayoutGraph, LayoutGraphValue, RenderPhase } from './layout-graph'; +import { Descriptor, DescriptorBlock, DescriptorBlockIndex, DescriptorDB, DescriptorTypeOrder, LayoutGraph, LayoutGraphValue, LayoutGraphVisitor, RenderPhase } from './layout-graph'; import { ShaderStageFlagBit, Type, Uniform, UniformBlock } from '../../gfx'; import { ParameterType, UpdateFrequency } from './types'; -import { JOINT_UNIFORM_CAPACITY, UBOForwardLight, UBOLocalBatched, UBOMorph } from '../define'; +import { JOINT_UNIFORM_CAPACITY, RenderPassStage, SetIndex, UBOCamera, UBOForwardLight, UBOGlobal, UBOLocal, UBOLocalBatched, UBOMorph, UBOShadow, UBOSkinning, UBOSkinningAnimation, UBOSkinningTexture, UBOUILocal, UBOWorldBound } from '../define'; +import { DefaultVisitor, edge_descriptor, IncidenceGraph, vertex_descriptor } from './graph'; export class WebDescriptorHierarchy { + public uniformBlockIndex: Map; + public blockMerged: Map>; + public dbsToMerge: Map; + constructor () { this._layoutGraph = new LayoutGraph(); + this.uniformBlockIndex = new Map(); + this.blockMerged = new Map>(); + this.dbsToMerge = new Map(); } - private getLayoutBlock (freq: UpdateFrequency, paraType: ParameterType, descType: DescriptorTypeOrder, vis: ShaderStageFlagBit, descriptorDB: DescriptorDB): DescriptorBlock { + public getLayoutBlock (freq: UpdateFrequency, paraType: ParameterType, descType: DescriptorTypeOrder, vis: ShaderStageFlagBit, descriptorDB: DescriptorDB): DescriptorBlock { const blockIndex: DescriptorBlockIndex = new DescriptorBlockIndex(freq, paraType, descType, vis); const key = JSON.stringify(blockIndex); if (descriptorDB.blocks.get(key) === undefined) { const uniformBlock: DescriptorBlock = new DescriptorBlock(); descriptorDB.blocks.set(key, uniformBlock); - // uniformBlock['blockIndex'] = blockIndex; + this.uniformBlockIndex.set(uniformBlock, blockIndex); } return descriptorDB.blocks.get(key) as DescriptorBlock; } - private getLayoutBlockByKey (key: string, descriptorDB: DescriptorDB): DescriptorBlock { + public getLayoutBlockByKey (key: string, descriptorDB: DescriptorDB): DescriptorBlock { if (descriptorDB.blocks.get(key) === undefined) { const uniformBlock: DescriptorBlock = new DescriptorBlock(); descriptorDB.blocks.set(key, uniformBlock); - // const blockIndedx: DescriptorBlockIndex = JSON.parse(key) as DescriptorBlockIndex; - // uniformBlock['blockIndex'] = blockIndedx; + const blockIndedx: DescriptorBlockIndex = JSON.parse(key) as DescriptorBlockIndex; + this.uniformBlockIndex.set(uniformBlock, blockIndedx); } return descriptorDB.blocks.get(key) as DescriptorBlock; } - private getUniformBlock (blockName: string, targetBlock: DescriptorBlock): UniformBlock { + public getUniformBlock (set: number, binding: number, blockName: string, targetBlock: DescriptorBlock): UniformBlock { if (targetBlock.uniformBlocks.get(blockName) === undefined) { - const uniformDB: UniformBlock = new UniformBlock(); + const uniformDB: UniformBlock = new UniformBlock(set, binding, blockName, [], 1); targetBlock.uniformBlocks.set(blockName, uniformDB); } return targetBlock.uniformBlocks.get(blockName) as UniformBlock; } - private setUniform (uniformDB: UniformBlock, name: string, type: Type, count: number) { + public setUniform (uniformDB: UniformBlock, name: string, type: Type, count: number) { const uniform: Uniform = new Uniform(name, type, count); - // uniformDB.values.set(uniform.name, uniform); + uniformDB.members.push(uniform); } - private setDescriptor (targetBlock: DescriptorBlock, name: string, type: Type) { + public setDescriptor (targetBlock: DescriptorBlock, name: string, type: Type) { const descriptor: Descriptor = new Descriptor(type); targetBlock.descriptors.set(name, descriptor); } - private merge (descriptorDB: DescriptorDB) { + public merge (descriptorDB: DescriptorDB) { for (const entry of descriptorDB.blocks) { const block: DescriptorBlock = entry[1]; const typeMap: Map = new Map(); @@ -97,31 +105,49 @@ export class WebDescriptorHierarchy { if (count > 0) { const mergedDescriptor: Descriptor = new Descriptor(type); mergedDescriptor.count = count; - // block.merged.set(type, mergedDescriptor); + let merged: Map; + if (this.blockMerged.get(block) === undefined) { + merged = new Map(); + this.blockMerged.set(block, merged); + } + this.blockMerged.get(block)?.set(type, mergedDescriptor); } } } } - private mergeDBs (descriptorDBs: DescriptorDB[], target: DescriptorDB) { - /* + public mergeDBs (descriptorDBs: DescriptorDB[], target: DescriptorDB) { for (let i = 0; i < descriptorDBs.length; ++i) { const db: DescriptorDB = descriptorDBs[i]; for (const e of db.blocks) { const key: string = e[0]; const block: DescriptorBlock = e[1]; - if (block.merged.size > 0) { + let merged: Map; + if (this.blockMerged.get(block) === undefined) { + merged = new Map(); + this.blockMerged.set(block, merged); + } else { + merged = this.blockMerged.get(block) as Map; + } + if (merged.size > 0) { const targetBlock: DescriptorBlock = this.getLayoutBlockByKey(key, target); - for (const ee of block.merged) { + let targetMerged: Map; + if (this.blockMerged.get(targetBlock) === undefined) { + targetMerged = new Map(); + this.blockMerged.set(targetBlock, targetMerged); + } else { + targetMerged = this.blockMerged.get(targetBlock) as Map; + } + for (const ee of merged) { const type: Type = ee[0]; const descriptor: Descriptor = ee[1]; - if (!targetBlock.merged.has(type)) { + if (!targetMerged.has(type)) { const ds: Descriptor = new Descriptor(descriptor.type); ds.count = descriptor.count; - targetBlock.merged.set(type, ds); + targetMerged.set(type, ds); } else { - const ds: Descriptor | undefined = targetBlock.merged.get(type); + const ds: Descriptor | undefined = targetMerged.get(type); if (ds !== undefined) { ds.count = ds.count > descriptor.count ? ds.count : descriptor.count; } @@ -131,10 +157,9 @@ export class WebDescriptorHierarchy { } } } - */ } - private sort (descriptorDB: DescriptorDB) { + public sort (descriptorDB: DescriptorDB) { const sortedMap: Map = new Map(Array.from(descriptorDB.blocks).sort((a, b) => String(a[0]).localeCompare(b[0]))); descriptorDB.blocks.clear(); for (const e of sortedMap) { @@ -145,8 +170,6 @@ export class WebDescriptorHierarchy { public addEffect (asset: EffectAsset, parent: number): void { const sz = asset.shaders.length; - const dbsToMerge: DescriptorDB[] = []; - for (let i = 0; i !== sz; ++i) { const shader: EffectAsset.IShaderInfo = asset.shaders[i]; @@ -156,10 +179,10 @@ export class WebDescriptorHierarchy { const blockInfo: EffectAsset.IBlockInfo = shader.blocks[k]; const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_INSTANCE, ParameterType.TABLE, DescriptorTypeOrder.UNIFORM_BUFFER, blockInfo.stageFlags, queueDB); - const uniformDB: UniformBlock = this.getUniformBlock(blockInfo.name, targetBlock); + const uniformDB: UniformBlock = this.getUniformBlock(SetIndex.MATERIAL, blockInfo.binding, blockInfo.name, targetBlock); for (let kk = 0; kk < blockInfo.members.length; ++kk) { const uniform: Uniform = blockInfo.members[kk]; - // uniformDB.values.set(uniform.name, uniform); + uniformDB.members.push(uniform); } } @@ -200,7 +223,7 @@ export class WebDescriptorHierarchy { for (let k = 0; k < shader.subpassInputs.length; ++k) { const subpassInfo: EffectAsset.IInputAttachmentInfo = shader.subpassInputs[k]; - const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_QUEUE, + const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, ParameterType.TABLE, DescriptorTypeOrder.INPUT_ATTACHMENT, subpassInfo.stageFlags, queueDB); this.setDescriptor(targetBlock, subpassInfo.name, Type.SUBPASS_INPUT); } @@ -224,37 +247,37 @@ export class WebDescriptorHierarchy { for (let k = 0; k < shader.builtins.locals.blocks.length; ++k) { const blockName: string = shader.builtins.locals.blocks[k].name; if (blockName === 'CCMorph') { - const morphDB: UniformBlock = this.getUniformBlock('CCMorph', localUniformTarget); + const morphDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOMorph.BINDING, 'CCMorph', localUniformTarget); this.setUniform(morphDB, 'cc_displacementWeights', Type.FLOAT4, UBOMorph.MAX_MORPH_TARGET_COUNT / 4); this.setUniform(morphDB, 'cc_displacementTextureInfo', Type.FLOAT4, 1); } else if (blockName === 'CCSkinningTexture') { - const skinningTexDB: UniformBlock = this.getUniformBlock('CCSkinningTexture', localUniformTarget); + const skinningTexDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOSkinningTexture.BINDING, 'CCSkinningTexture', localUniformTarget); this.setUniform(skinningTexDB, 'cc_jointTextureInfo', Type.FLOAT4, 1); } else if (blockName === 'CCSkinningAnimation') { - const skinningAnimDB: UniformBlock = this.getUniformBlock('CCSkinningAnimation', localUniformTarget); + const skinningAnimDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOSkinningAnimation.BINDING, 'CCSkinningAnimation', localUniformTarget); this.setUniform(skinningAnimDB, 'cc_jointAnimInfo', Type.FLOAT4, 1); } else if (blockName === 'CCSkinning') { - const skinningDB: UniformBlock = this.getUniformBlock('CCSkinning', localUniformTarget); + const skinningDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOSkinning.BINDING, 'CCSkinning', localUniformTarget); this.setUniform(skinningDB, 'cc_joints', Type.FLOAT4, JOINT_UNIFORM_CAPACITY * 3); } else if (blockName === 'CCUILocal') { - const uiDB: UniformBlock = this.getUniformBlock('CCUILocal', localUITarget); + const uiDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOUILocal.BINDING, 'CCUILocal', localUITarget); this.setUniform(uiDB, 'cc_local_data', Type.FLOAT4, 1); } else if (blockName === 'CCForwardLight') { - const lightDB: UniformBlock = this.getUniformBlock('CCForwardLight', localLightTarget); + const lightDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOForwardLight.BINDING, 'CCForwardLight', localLightTarget); this.setUniform(lightDB, 'cc_lightPos', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS); this.setUniform(lightDB, 'cc_lightColor', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS); this.setUniform(lightDB, 'cc_lightSizeRangeAngle', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS); this.setUniform(lightDB, 'cc_lightDir', Type.FLOAT4, UBOForwardLight.LIGHTS_PER_PASS); } else if (blockName === 'CCLocal') { - const localDB: UniformBlock = this.getUniformBlock('CCLocal', localModelTarget); + const localDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOLocal.BINDING, 'CCLocal', localModelTarget); this.setUniform(localDB, 'cc_matWorld', Type.MAT4, 1); this.setUniform(localDB, 'cc_matWorldIT', Type.MAT4, 1); this.setUniform(localDB, 'cc_lightingMapUVParam', Type.FLOAT4, 1); } else if (blockName === 'CCLocalBatched') { - const batchDB: UniformBlock = this.getUniformBlock('CCLocalBatched', localModelTarget); + const batchDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOLocalBatched.BINDING, 'CCLocalBatched', localModelTarget); this.setUniform(batchDB, 'cc_matWorlds', Type.MAT4, UBOLocalBatched.BATCHING_COUNT); } else if (blockName === 'CCWorldBound') { - const boundDB: UniformBlock = this.getUniformBlock('CCWorldBound', localModelTarget); + const boundDB: UniformBlock = this.getUniformBlock(SetIndex.LOCAL, UBOWorldBound.BINDING, 'CCWorldBound', localModelTarget); this.setUniform(boundDB, 'cc_worldBoundCenter', Type.FLOAT4, 1); this.setUniform(boundDB, 'cc_worldBoundHalfExtents', Type.FLOAT4, 1); } @@ -292,13 +315,16 @@ export class WebDescriptorHierarchy { this.merge(queueDB); this.sort(queueDB); - dbsToMerge.push(queueDB); + + const parentDB: DescriptorDB = this._layoutGraph.getDescriptors(parent); + if (this.dbsToMerge.get(parentDB) === undefined) { + this.dbsToMerge.set(parentDB, []); + } + this.dbsToMerge.get(parentDB)?.push(queueDB); } } public addGlobal (vName: string, hasCCGlobal, hasCCCamera, hasCCShadow, hasShadowmap, hasEnv, hasDiffuse, hasSpot): number { - const dbsToMerge: DescriptorDB[] = []; - const passDB: DescriptorDB = new DescriptorDB(); // Add pass layout from define.ts const globalUniformTarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_PASS, @@ -307,14 +333,18 @@ export class WebDescriptorHierarchy { ParameterType.TABLE, DescriptorTypeOrder.SAMPLER_TEXTURE, ShaderStageFlagBit.FRAGMENT, passDB); if (hasCCGlobal) { - const globalDB: UniformBlock = this.getUniformBlock('CCGlobal', globalUniformTarget); + const globalDB: UniformBlock = this.getUniformBlock(SetIndex.GLOBAL, + UBOGlobal.BINDING, 'CCGlobal', globalUniformTarget); this.setUniform(globalDB, 'cc_time', Type.FLOAT4, 1); this.setUniform(globalDB, 'cc_screenSize', Type.FLOAT4, 1); this.setUniform(globalDB, 'cc_nativeSize', Type.FLOAT4, 1); + + this.setDescriptor(globalUniformTarget, 'CCGlobal', Type.UNKNOWN); } if (hasCCCamera) { - const cameraDB: UniformBlock = this.getUniformBlock('CCCamera', globalUniformTarget); + const cameraDB: UniformBlock = this.getUniformBlock(SetIndex.GLOBAL, + UBOCamera.BINDING, 'CCCamera', globalUniformTarget); this.setUniform(cameraDB, 'cc_matView', Type.MAT4, 1); this.setUniform(cameraDB, 'cc_matViewInv', Type.MAT4, 1); this.setUniform(cameraDB, 'cc_matProj', Type.MAT4, 1); @@ -334,11 +364,13 @@ export class WebDescriptorHierarchy { this.setUniform(cameraDB, 'cc_fogAdd', Type.FLOAT4, 1); this.setUniform(cameraDB, 'cc_nearFar', Type.FLOAT4, 1); this.setUniform(cameraDB, 'cc_viewPort', Type.FLOAT4, 1); + + this.setDescriptor(globalUniformTarget, 'CCCamera', Type.UNKNOWN); } if (hasCCShadow) { - const shadowDB: UniformBlock = this.getUniformBlock('CCShadow', globalUniformTarget); - this.setUniform(shadowDB, 'cc_matLightPlaneProj', Type.MAT4, 1); + const shadowDB: UniformBlock = this.getUniformBlock(SetIndex.GLOBAL, + UBOShadow.BINDING, 'CCShadow', globalUniformTarget); this.setUniform(shadowDB, 'cc_matLightView', Type.MAT4, 1); this.setUniform(shadowDB, 'cc_matLightViewProj', Type.MAT4, 1); this.setUniform(shadowDB, 'cc_shadowInvProjDepthInfo', Type.FLOAT4, 1); @@ -348,6 +380,9 @@ export class WebDescriptorHierarchy { this.setUniform(shadowDB, 'cc_shadowWHPBInfo', Type.FLOAT4, 1); this.setUniform(shadowDB, 'cc_shadowLPNNInfo', Type.FLOAT4, 1); this.setUniform(shadowDB, 'cc_shadowColor', Type.FLOAT4, 1); + this.setUniform(shadowDB, 'cc_planarNDInfo', Type.FLOAT4, 1); + + this.setDescriptor(globalUniformTarget, 'CCShadow', Type.UNKNOWN); } if (hasShadowmap) { @@ -363,18 +398,141 @@ export class WebDescriptorHierarchy { this.setDescriptor(globalSamplerTexTarget, 'cc_spotShadowMap', Type.SAMPLER2D); } - const vid = this._layoutGraph.addVertex(LayoutGraphValue.RenderStage, LayoutGraphValue.RenderStage, vName, passDB); - - //this.mergeDBs(dbsToMerge, passDB); this.merge(passDB); - this.sort(passDB); + + const vid = this._layoutGraph.addVertex( + LayoutGraphValue.RenderStage, RenderPassStage.DEFAULT, vName, passDB, + ); return vid; } - private _layoutGraph: LayoutGraph; + public mergeDescriptors (vid: number) { + const target: DescriptorDB = this._layoutGraph.getDescriptors(vid); + const toMerge = this.dbsToMerge.get(target); + if (toMerge !== undefined) { + this.mergeDBs(toMerge, target); + this.sort(target); + } + } + + public addRenderStage (name: string, stageID: number): number { + const passDB: DescriptorDB = new DescriptorDB(); + return this._layoutGraph.addVertex(LayoutGraphValue.RenderStage, + stageID, name, passDB); + } + + public addRenderPhase (name: string, parentStageID: number): number { + const passDB: DescriptorDB = new DescriptorDB(); + return this._layoutGraph.addVertex(LayoutGraphValue.RenderPhase, + new RenderPhase(), name, passDB, parentStageID); + } + + public _layoutGraph: LayoutGraph; public get layoutGraph () { return this._layoutGraph; } } + +function getNumDescriptors (block: DescriptorBlock): number { + let count = 0; + for (const [, d] of block.descriptors) { + count += d.count; + } + return count; +} + +function checkDescriptorConsistency (lhs: Descriptor, rhs: Descriptor): boolean { + if (lhs.type !== rhs.type) { + return false; + } + if (lhs.count !== rhs.count) { + return false; + } + return true; +} + +export class CollectVisitor extends DefaultVisitor { + getFrequency (g: LayoutGraph, v: number): UpdateFrequency { + let freq: UpdateFrequency; + if (g.holds(LayoutGraphValue.RenderStage, v)) { + freq = UpdateFrequency.PER_PASS; + } else { + freq = UpdateFrequency.PER_QUEUE; + } + return freq; + } + + mergeDescriptors (srcBlock: DescriptorBlock, dstBlock: DescriptorBlock): string { + for (const [name, src] of srcBlock.descriptors) { + const dst = dstBlock.descriptors.get(name); + if (dst !== undefined) { + if (!checkDescriptorConsistency(src, dst)) { + return `Descriptor ${name} is inconsistent`; + } + } else { + dstBlock.descriptors.set(name, src); + } + } + return ''; + } + + mergeParent (freq: UpdateFrequency, src: DescriptorDB, dst: DescriptorDB): string { + for (const [key, srcBlock] of src.blocks) { + let dstBlock = dst.blocks.get(key); + if (dstBlock === undefined) { + dstBlock = new DescriptorBlock(); + dst.blocks.set(key, dstBlock); + } + const index = JSON.parse(key) as DescriptorBlockIndex; + if (index.updateFrequency > freq) { + const error = this.mergeDescriptors(srcBlock, dstBlock); + if (error) { + return error; + } + } + } + return ''; + } + + updateInfo (freq: UpdateFrequency, db: DescriptorDB) { + db.blocks.forEach((block: DescriptorBlock, key: string) => { + const index = JSON.parse(key) as DescriptorBlockIndex; + if (index.updateFrequency >= freq) { + block.count = getNumDescriptors(block); + block.capacity = block.count; + } + }); + } + + backEdge (e: edge_descriptor, g: LayoutGraph): void { + this._error = 'Cycle detected in graph'; + } + + finishEdge (e: edge_descriptor, g: LayoutGraph): void { + if (this._error !== '') { + return; + } + const parentID = g.source(e); + const v = g.target(e); + const dst = g.getDescriptors(parentID); + const src = g.getDescriptors(v); + const freq = this.getFrequency(g, v); + this.mergeParent(freq, src, dst); + } + + finishVertex (v: number, g: LayoutGraph): void { + if (this._error !== '') { + return; + } + const freq = this.getFrequency(g, v); + const db = g.getDescriptors(v); + this.updateInfo(freq, db); + } + + get error (): string { + return this._error; + } + private _error = ''; +} diff --git a/cocos/core/pipeline/custom/web-layout-graph.ts b/cocos/core/pipeline/custom/web-layout-graph.ts index 2c98b15234..7dc864e8b4 100644 --- a/cocos/core/pipeline/custom/web-layout-graph.ts +++ b/cocos/core/pipeline/custom/web-layout-graph.ts @@ -1,10 +1,188 @@ +import { DEBUG } from 'internal:constants'; // eslint-disable-next-line max-len -import { DescriptorSetInfo, DescriptorSetLayout, DescriptorSetLayoutBinding, DescriptorSetLayoutInfo, DescriptorType, Device, ShaderStageFlagBit } from '../../gfx'; +import { DescriptorSetInfo, DescriptorSetLayout, DescriptorSetLayoutBinding, DescriptorSetLayoutInfo, DescriptorType, Device, ShaderStageFlagBit, Type, Uniform, UniformBlock } from '../../gfx'; +import { VectorGraphColorMap } from './effect'; +import { DefaultVisitor, depthFirstSearch, GraphColor, MutableVertexPropertyMap } from './graph'; // eslint-disable-next-line max-len -import { DescriptorBlock, DescriptorBlockIndex, LayoutGraphData, PipelineLayoutData, LayoutGraphDataValue, RenderStageData, RenderPhaseData, DescriptorTypeOrder, DescriptorSetLayoutData, DescriptorSetData, DescriptorBlockData, Descriptor, DescriptorData, getDescriptorTypeOrderName, DescriptorBlockFlattened } from './layout-graph'; +import { DescriptorBlockIndex, LayoutGraphData, PipelineLayoutData, LayoutGraphDataValue, RenderStageData, RenderPhaseData, DescriptorTypeOrder, DescriptorSetLayoutData, DescriptorSetData, DescriptorBlockData, Descriptor, DescriptorData, getDescriptorTypeOrderName, DescriptorBlockFlattened } from './layout-graph'; import { LayoutGraphBuilder } from './pipeline'; import { getUpdateFrequencyName, UpdateFrequency } from './types'; +function getName (type: Type): string { + switch (type) { + case Type.UNKNOWN: return 'Unknown'; + case Type.BOOL: return 'Bool'; + case Type.BOOL2: return 'Bool2'; + case Type.BOOL3: return 'Bool3'; + case Type.BOOL4: return 'Bool4'; + case Type.INT: return 'Int'; + case Type.INT2: return 'Int2'; + case Type.INT3: return 'Int3'; + case Type.INT4: return 'Int4'; + case Type.UINT: return 'Uint'; + case Type.UINT2: return 'Uint2'; + case Type.UINT3: return 'Uint3'; + case Type.UINT4: return 'Uint4'; + case Type.FLOAT: return 'Float'; + case Type.FLOAT2: return 'Float2'; + case Type.FLOAT3: return 'Float3'; + case Type.FLOAT4: return 'Float4'; + case Type.MAT2: return 'Mat2'; + case Type.MAT2X3: return 'Mat2x3'; + case Type.MAT2X4: return 'Mat2x4'; + case Type.MAT3X2: return 'Mat3x2'; + case Type.MAT3: return 'Mat3'; + case Type.MAT3X4: return 'Mat3x4'; + case Type.MAT4X2: return 'Mat4x2'; + case Type.MAT4X3: return 'Mat4x3'; + case Type.MAT4: return 'Mat4'; + case Type.SAMPLER1D: return 'Sampler1D'; + case Type.SAMPLER1D_ARRAY: return 'Sampler1DArray'; + case Type.SAMPLER2D: return 'Sampler2D'; + case Type.SAMPLER2D_ARRAY: return 'Sampler2DArray'; + case Type.SAMPLER3D: return 'Sampler3D'; + case Type.SAMPLER_CUBE: return 'SamplerCube'; + case Type.SAMPLER: return 'Sampler'; + case Type.TEXTURE1D: return 'Texture1D'; + case Type.TEXTURE1D_ARRAY: return 'Texture1DArray'; + case Type.TEXTURE2D: return 'Texture2D'; + case Type.TEXTURE2D_ARRAY: return 'Texture2DArray'; + case Type.TEXTURE3D: return 'Texture3D'; + case Type.TEXTURE_CUBE: return 'TextureCube'; + case Type.IMAGE1D: return 'Image1D'; + case Type.IMAGE1D_ARRAY: return 'Image1DArray'; + case Type.IMAGE2D: return 'Image2D'; + case Type.IMAGE2D_ARRAY: return 'Image2DArray'; + case Type.IMAGE3D: return 'Image3D'; + case Type.IMAGE_CUBE: return 'ImageCube'; + case Type.SUBPASS_INPUT: return 'SubpassInput'; + case Type.COUNT: return 'Count'; + default: return 'Unknown'; + } +} + +function hasFlag (flags: ShaderStageFlagBit, flagToTest: ShaderStageFlagBit): boolean { + return (flags & flagToTest) !== 0; +} + +function getVisibilityName (stage: ShaderStageFlagBit): string { + let count = 0; + let str = ''; + if (hasFlag(stage, ShaderStageFlagBit.VERTEX)) { + if (count++) { + str += ' | '; + } + str += 'Vertex'; + } + if (hasFlag(stage, ShaderStageFlagBit.CONTROL)) { + if (count++) { + str += ' | '; + } + str += 'Control'; + } + if (hasFlag(stage, ShaderStageFlagBit.EVALUATION)) { + if (count++) { + str += ' | '; + } + str += 'Evaluation'; + } + if (hasFlag(stage, ShaderStageFlagBit.GEOMETRY)) { + if (count++) { + str += ' | '; + } + str += 'Geometry'; + } + if (hasFlag(stage, ShaderStageFlagBit.FRAGMENT)) { + if (count++) { + str += ' | '; + } + str += 'Fragment'; + } + if (hasFlag(stage, ShaderStageFlagBit.COMPUTE)) { + if (count++) { + str += ' | '; + } + str += 'Compute'; + } + if (stage === ShaderStageFlagBit.ALL) { + if (count++) { + str += ' | '; + } + str += 'All'; + } + return str; +} + +class PrintVisitor extends DefaultVisitor { + discoverVertex (u: number, g: LayoutGraphData) { + const ppl: PipelineLayoutData = g.getLayout(u); + const name: string = g._names[u]; + const freq: UpdateFrequency = g._updateFrequencies[u]; + this.oss += `${this.space}"${name}": `; + if (g.holds(LayoutGraphDataValue.RenderStage, u)) { + this.oss += `RenderStage {\n`; + } else { + this.oss += `RenderPhase {\n`; + } + this.space += ' '; + + // eslint-disable-next-line no-loop-func + ppl.descriptorSets.forEach((value, key) => { + this.oss += `${this.space}DescriptorSet<${getUpdateFrequencyName(key)}> {\n`; + this.space += ' '; + const uniformBlocks = value.descriptorSetLayoutData.uniformBlocks; + uniformBlocks.forEach((uniformBlock, attrNameID) => { + const name = g.valueNames[attrNameID]; + this.oss += `${this.space}UniformBlock "${name}" {\n`; + for (const u of uniformBlock.members) { + if (u.count > 1) { + this.oss += `${this.space} ${u.name}[${u.count}]: ${getName(u.type)}\n`; + } else { + this.oss += `${this.space} ${u.name}: ${getName(u.type)}\n`; + } + } + this.oss += `${this.space}}\n`; + }); + + const blocks = value.descriptorSetLayoutData.descriptorBlocks; + for (let j = 0; j < blocks.length; ++j) { + const block = blocks[j]; + this.oss += `${this.space}Block<${getDescriptorTypeOrderName(block.type)}, ${getVisibilityName(block.visibility)}> {\n`; + this.oss += `${this.space} capacity: ${block.capacity}\n`; + this.oss += `${this.space} count: ${block.descriptors.length}\n`; + if (block.descriptors.length > 0) { + this.oss += `${this.space} Descriptors{ \n`; + const count = 0; + for (let k = 0; k < block.descriptors.length; ++k) { + const d: DescriptorData = block.descriptors[k]; + // if (count++) { + this.oss += this.space; + this.oss += ' '; + const n: string = g.valueNames[d.descriptorID]; + this.oss += `"${n}`; + if (d.count !== 1) { + this.oss += `[${d.count}]`; + } + this.oss += '"'; + // } + this.oss += '\n'; + } + this.oss += `${this.space} }\n`; + } + this.oss += `${this.space}}\n`; + } + this.space = this.space.substring(0, this.space.length - 4); + this.oss += `${this.space}}\n`; + }); + } + finishVertex (v: number, g: LayoutGraphData) { + this.space = this.space.substring(0, this.space.length - 4); + this.oss += `${this.space}}\n`; + } + space = ''; + oss = ''; +} + export class WebLayoutGraphBuilder extends LayoutGraphBuilder { private _data: LayoutGraphData; private _device: Device; @@ -15,13 +193,6 @@ export class WebLayoutGraphBuilder extends LayoutGraphBuilder { this._data = dataIn; } - private add_vertex (g: LayoutGraphData, tag: T, object, name: string, parentID = 0xFFFFFFFF): number { - const layouts: PipelineLayoutData = new PipelineLayoutData(); - // eslint-disable-next-line max-len - layouts.descriptorSets.set(UpdateFrequency.PER_INSTANCE, new DescriptorSetData(new DescriptorSetLayoutData(), null, null)); - return g.addVertex(tag, object, name, UpdateFrequency.PER_INSTANCE, layouts, parentID); - } - private getGfxType (type: DescriptorTypeOrder): DescriptorType | null { switch (type) { case DescriptorTypeOrder.UNIFORM_BUFFER: @@ -48,58 +219,6 @@ export class WebLayoutGraphBuilder extends LayoutGraphBuilder { } } - private hasFlag (flags, flagToTest): boolean { - return (flags & flagToTest) !== 0; - } - - private getName (stage: ShaderStageFlagBit): string { - let count = 0; - let str = ''; - if (this.hasFlag(stage, ShaderStageFlagBit.VERTEX)) { - if (count++) { - str += ' | '; - } - str += 'Vertex'; - } - if (this.hasFlag(stage, ShaderStageFlagBit.CONTROL)) { - if (count++) { - str += ' | '; - } - str += 'Control'; - } - if (this.hasFlag(stage, ShaderStageFlagBit.EVALUATION)) { - if (count++) { - str += ' | '; - } - str += 'Evaluation'; - } - if (this.hasFlag(stage, ShaderStageFlagBit.GEOMETRY)) { - if (count++) { - str += ' | '; - } - str += 'Geometry'; - } - if (this.hasFlag(stage, ShaderStageFlagBit.FRAGMENT)) { - if (count++) { - str += ' | '; - } - str += 'Fragment'; - } - if (this.hasFlag(stage, ShaderStageFlagBit.COMPUTE)) { - if (count++) { - str += ' | '; - } - str += 'Compute'; - } - if (stage === ShaderStageFlagBit.ALL) { - if (count++) { - str += ' | '; - } - str += 'All'; - } - return str; - } - private createDescriptorSetLayout (layoutData: DescriptorSetLayoutData) { const info: DescriptorSetLayoutInfo = new DescriptorSetLayoutInfo(); for (let i = 0; i < layoutData.descriptorBlocks.length; ++i) { @@ -128,11 +247,16 @@ export class WebLayoutGraphBuilder extends LayoutGraphBuilder { } public addRenderStage (name: string): number { - return this.add_vertex(this._data, LayoutGraphDataValue.RenderStage, new RenderStageData(), name); + return this._data.addVertex(LayoutGraphDataValue.RenderStage, + new RenderStageData(), name, + UpdateFrequency.PER_PASS, new PipelineLayoutData()); } public addRenderPhase (name: string, parentID: number): number { - return this.add_vertex(this._data, LayoutGraphDataValue.RenderPhase, new RenderPhaseData(), name, parentID); + return this._data.addVertex(LayoutGraphDataValue.RenderPhase, + new RenderPhaseData(), name, + UpdateFrequency.PER_QUEUE, new PipelineLayoutData(), + parentID); } public addShader (name: string, parentPhaseID: number): void { @@ -154,30 +278,49 @@ export class WebLayoutGraphBuilder extends LayoutGraphBuilder { console.error('error uniform'); return; } + let data: DescriptorSetData | undefined = ppl.descriptorSets.get(index.updateFrequency); + if (!data) { + data = new DescriptorSetData(new DescriptorSetLayoutData(), null, null); + ppl.descriptorSets.set(index.updateFrequency, data); + } + const layout = data.descriptorSetLayoutData; + + const dstBlock = new DescriptorBlockData(index.descriptorType, index.visibility, block.capacity); + layout.descriptorBlocks.push(dstBlock); + dstBlock.offset = layout.capacity; + dstBlock.capacity = block.capacity; + for (let j = 0; j < block.descriptors.length; ++j) { + const name: string = block.descriptorNames[j]; + const d: Descriptor = block.descriptors[j]; + let nameID: number | undefined = g.attributeIndex.get(name); + if (nameID === undefined) { + const id = g.valueNames.length; + g.attributeIndex.set(name, id); + g.valueNames.push(name); + } + + nameID = g.attributeIndex.get(name); + const data: DescriptorData = new DescriptorData(nameID); + data.count = d.count; + dstBlock.descriptors.push(data); + } + layout.capacity += block.capacity; + } + + public addUniformBlock (nodeID: number, index: DescriptorBlockIndex, name: string, uniformBlock: UniformBlock): void { + const g: LayoutGraphData = this._data; + const ppl: PipelineLayoutData = g.getLayout(nodeID); const layout: DescriptorSetLayoutData | undefined = ppl.descriptorSets.get(index.updateFrequency)?.descriptorSetLayoutData; if (layout !== undefined) { - const dstBlock = new DescriptorBlockData(index.descriptorType, index.visibility, block.capacity); - layout.descriptorBlocks.push(dstBlock); - dstBlock.offset = layout.capacity; - dstBlock.capacity = block.capacity; - for (let j = 0; j < block.descriptors.length; ++j) { - const name: string = block.descriptorNames[j]; - const d: Descriptor = block.descriptors[j]; - let nameID: number | undefined = g.attributeIndex.get(name); - if (nameID === undefined) { - const id = g.valueNames.length; - g.attributeIndex.set(name, id); - g.valueNames.push(name); - } - - nameID = g.attributeIndex.get(name); - const data: DescriptorData = new DescriptorData(nameID); - data.count = d.count; - dstBlock.descriptors.push(data); + let nameID: number | undefined = g.attributeIndex.get(name); + if (nameID === undefined) { + const id = g.valueNames.length; + g.attributeIndex.set(name, id); + g.valueNames.push(name); } - layout.capacity += block.capacity; - } else { - console.error('no layout'); + + nameID = g.attributeIndex.get(name); + layout.uniformBlocks.set(nameID as number, uniformBlock); } } @@ -213,54 +356,18 @@ export class WebLayoutGraphBuilder extends LayoutGraphBuilder { level.descriptorSet = (this._device.createDescriptorSet(new DescriptorSetInfo(layout))); }); } - + if (DEBUG) { + console.log(this.print()); + } return 0; } public print (): string { - let oss = ''; const g: LayoutGraphData = this._data; - for (let i = 0; i < g._layouts.length; ++i) { - const ppl: PipelineLayoutData = g.getLayout(i); - const name: string = g._names[i]; - const freq: UpdateFrequency = g._updateFrequencies[i]; - - oss += `"${name}": `; - oss += `<${getUpdateFrequencyName(freq)}> {\n`; - - // eslint-disable-next-line no-loop-func - ppl.descriptorSets.forEach((value, key) => { - oss += `Set<${getUpdateFrequencyName(key)}> {\n`; - const blocks = value.descriptorSetLayoutData.descriptorBlocks; - for (let j = 0; j < blocks.length; ++j) { - const block = blocks[j]; - oss += `Block<${getDescriptorTypeOrderName(block.type)}, ${this.getName(block.visibility)}> {\n`; - oss += `capacity: ${block.capacity},\n`; - oss += `count: ${block.descriptors.length},\n`; - if (block.descriptors.length > 0) { - oss += 'Descriptors{ \n'; - const count = 0; - for (let k = 0; k < block.descriptors.length; ++k) { - const d: DescriptorData = block.descriptors[k]; - // if (count++) { - oss += ' '; - const n: string = g.valueNames[d.descriptorID]; - oss += `"${n}`; - if (d.count !== 1) { - oss += `[${d.count}]`; - } - oss += '"'; - // } - oss += '\n'; - } - oss += ' }\n'; - } - oss += '}\n'; - } - oss += '}\n'; - }); - } - return oss; + const visitor = new PrintVisitor(); + const colorMap = new VectorGraphColorMap(g.numVertices()); + depthFirstSearch(g, visitor, colorMap); + return visitor.oss; } public get data () { diff --git a/cocos/core/pipeline/custom/web-pipeline.ts b/cocos/core/pipeline/custom/web-pipeline.ts index 513867c09f..e3ef09902b 100644 --- a/cocos/core/pipeline/custom/web-pipeline.ts +++ b/cocos/core/pipeline/custom/web-pipeline.ts @@ -25,13 +25,13 @@ /* eslint-disable max-len */ import { systemInfo } from 'pal/system-info'; -import { Color, Buffer, DescriptorSetLayout, Device, Feature, Format, FormatFeatureBit, Sampler, Swapchain, Texture, StoreOp, LoadOp, ClearFlagBit, DescriptorSet, deviceManager } from '../../gfx/index'; +import { Color, Buffer, DescriptorSetLayout, Device, Feature, Format, FormatFeatureBit, Sampler, Swapchain, Texture, StoreOp, LoadOp, ClearFlagBit, DescriptorSet, deviceManager, Viewport, API, CommandBuffer } from '../../gfx/index'; import { Mat4, Quat, Vec2, Vec4 } from '../../math'; -import { QueueHint, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags, UpdateFrequency } from './types'; -import { AccessType, AttachmentType, Blit, ComputePass, ComputeView, CopyPair, CopyPass, Dispatch, ManagedResource, MovePair, MovePass, PresentPass, RasterPass, RasterView, RenderData, RenderGraph, RenderGraphValue, RenderQueue, RenderSwapchain, ResourceDesc, ResourceGraph, ResourceGraphValue, ResourceStates, ResourceTraits, SceneData } from './render-graph'; -import { ComputePassBuilder, ComputeQueueBuilder, CopyPassBuilder, LayoutGraphBuilder, MovePassBuilder, Pipeline, RasterPassBuilder, RasterQueueBuilder, SceneTask, SceneTransversal, SceneVisitor, Setter } from './pipeline'; +import { ComputeView, LightInfo, LightingMode, QueueHint, RasterView, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags, UpdateFrequency } from './types'; +import { Blit, ClearView, ComputePass, CopyPair, CopyPass, Dispatch, ManagedResource, MovePair, MovePass, PresentPass, RasterPass, RenderData, RenderGraph, RenderGraphComponent, RenderGraphValue, RenderQueue, RenderSwapchain, ResourceDesc, ResourceGraph, ResourceGraphValue, ResourceStates, ResourceTraits, SceneData } from './render-graph'; +import { ComputePassBuilder, ComputeQueueBuilder, CopyPassBuilder, LayoutGraphBuilder, MovePassBuilder, Pipeline, PipelineBuilder, RasterPassBuilder, RasterQueueBuilder, SceneTask, SceneTransversal, SceneVisitor, Setter } from './pipeline'; import { PipelineSceneData } from '../pipeline-scene-data'; -import { Model, Camera, SKYBOX_FLAG, Light, LightType, ShadowType, DirectionalLight, Shadows } from '../../renderer/scene'; +import { Model, Camera, Light } from '../../renderer/scene'; import { legacyCC } from '../../global-exports'; import { LayoutGraphData } from './layout-graph'; import { Executor } from './executor'; @@ -43,13 +43,16 @@ import { MacroRecord, RenderScene } from '../../renderer'; import { GlobalDSManager } from '../global-descriptor-set-manager'; import { supportsR32FloatTexture, UNIFORM_SHADOWMAP_BINDING, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING } from '../define'; import { OS } from '../../../../pal/system-info/enum-type'; -import { WebDescriptorHierarchy } from './web-descriptor-hierarchy'; import { Compiler } from './compiler'; -import { PipelineUBO } from './ubos'; +import { PipelineUBO } from '../pipeline-ubo'; import { builtinResMgr } from '../../builtin/builtin-res-mgr'; import { Texture2D } from '../../assets/texture-2d'; import { WebLayoutGraphBuilder } from './web-layout-graph'; import { GeometryRenderer } from '../geometry-renderer'; +import { Material } from '../../assets'; +import { DeferredPipelineBuilder, ForwardPipelineBuilder } from './builtin-pipelines'; +import { RenderGraphPrintVisitor } from './debug'; +import { decideProfilerCamera } from '../pipeline-funcs'; export class WebSetter { constructor (data: RenderData) { @@ -125,6 +128,17 @@ function setCameraValues (setter: Setter, setter.setVec4('cc_viewPort', new Vec4(camera.viewport.x, camera.viewport.y, camera.viewport.z, camera.viewport.w)); } +function getFirstChildLayoutName (lg: LayoutGraphData, parentID: number): string { + if (lg.numVertices() && parentID !== 0xFFFFFFFF && lg.numChildren(parentID)) { + const childNodes = lg.children(parentID); + if (childNodes.next().value && childNodes.next().value.target !== lg.nullVertex()) { + const ququeLayoutID = childNodes.next().value.target; + return lg.getName(ququeLayoutID); + } + } + return ''; +} + export class WebRasterQueueBuilder extends WebSetter implements RasterQueueBuilder { constructor (data: RenderData, renderGraph: RenderGraph, vertID: number, queue: RenderQueue, pipeline: PipelineSceneData) { super(data); @@ -133,10 +147,9 @@ export class WebRasterQueueBuilder extends WebSetter implements RasterQueueBuild this._queue = queue; this._pipeline = pipeline; } - addSceneOfCamera (camera: Camera, light: Light | null, sceneFlags: SceneFlags, name = 'Camera'): void { - const sceneData = new SceneData(name, sceneFlags); + addSceneOfCamera (camera: Camera, light: LightInfo, sceneFlags: SceneFlags, name = 'Camera'): void { + const sceneData = new SceneData(name, sceneFlags, light); sceneData.camera = camera; - sceneData.light = light; this._renderGraph.addVertex( RenderGraphValue.Scene, sceneData, name, '', new RenderData(), false, this._vertID, ); @@ -149,9 +162,28 @@ export class WebRasterQueueBuilder extends WebSetter implements RasterQueueBuild RenderGraphValue.Scene, sceneData, sceneName, '', new RenderData(), false, this._vertID, ); } - addFullscreenQuad (shader: string, layoutName = '', name = 'Quad'): void { + addFullscreenQuad (material: Material, sceneFlags = SceneFlags.NONE, name = 'Quad'): void { this._renderGraph.addVertex( - RenderGraphValue.Blit, new Blit(shader), name, '', new RenderData(), false, this._vertID, + RenderGraphValue.Blit, new Blit(material, sceneFlags, null), + name, '', new RenderData(), false, this._vertID, + ); + } + addCameraQuad (camera: Camera, material: Material, sceneFlags: SceneFlags) { + this._renderGraph.addVertex( + RenderGraphValue.Blit, new Blit(material, sceneFlags, camera), + 'CameraQuad', '', new RenderData(), false, this._vertID, + ); + } + clearRenderTarget (name: string, color: Color) { + this._renderGraph.addVertex( + RenderGraphValue.Clear, [new ClearView(name, ClearFlagBit.COLOR, color)], + 'ClearRenderTarget', '', new RenderData(), false, this._vertID, + ); + } + setViewport (viewport: Viewport) { + this._renderGraph.addVertex( + RenderGraphValue.Viewport, viewport, + 'Viewport', '', new RenderData(), false, this._vertID, ); } private readonly _renderGraph: RenderGraph; @@ -161,12 +193,18 @@ export class WebRasterQueueBuilder extends WebSetter implements RasterQueueBuild } export class WebRasterPassBuilder extends WebSetter implements RasterPassBuilder { - constructor (data: RenderData, renderGraph: RenderGraph, vertID: number, pass: RasterPass, pipeline: PipelineSceneData) { + constructor (data: RenderData, renderGraph: RenderGraph, layoutGraph: LayoutGraphData, vertID: number, pass: RasterPass, pipeline: PipelineSceneData) { super(data); this._renderGraph = renderGraph; + this._layoutGraph = layoutGraph; this._vertID = vertID; this._pass = pass; this._pipeline = pipeline; + + const layoutName = this._renderGraph.component( + RenderGraphComponent.Layout, this._vertID, + ); + this._layoutID = layoutGraph.locateChild(layoutGraph.nullVertex(), layoutName); } addRasterView (name: string, view: RasterView) { this._pass.rasterViews.set(name, view); @@ -178,40 +216,49 @@ export class WebRasterPassBuilder extends WebSetter implements RasterPassBuilder this._pass.computeViews.set(name, [view]); } } - addQueue (hint: QueueHint = QueueHint.RENDER_OPAQUE, layoutName = '', name = 'Queue') { - if (layoutName === '') { - switch (hint) { - case QueueHint.RENDER_OPAQUE: - layoutName = 'Opaque'; - break; - case QueueHint.RENDER_CUTOUT: - layoutName = 'Cutout'; - break; - case QueueHint.RENDER_TRANSPARENT: - layoutName = 'Transparent'; - break; - default: - throw Error('cannot infer layoutName from QueueHint'); - } - } + + addQueue (hint: QueueHint = QueueHint.RENDER_OPAQUE, name = 'Queue') { const queue = new RenderQueue(hint); const data = new RenderData(); const queueID = this._renderGraph.addVertex( - RenderGraphValue.Queue, queue, name, layoutName, data, false, this._vertID, + RenderGraphValue.Queue, queue, name, '', data, false, this._vertID, ); return new WebRasterQueueBuilder(data, this._renderGraph, queueID, queue, this._pipeline); } - addFullscreenQuad (shader: string, layoutName = '', name = 'Quad') { - this._renderGraph.addVertex( - RenderGraphValue.Blit, - new Blit(shader), - name, layoutName, new RenderData(), false, this._vertID, + + addFullscreenQuad (material: Material, sceneFlags = SceneFlags.NONE, name = 'FullscreenQuad') { + const queue = new RenderQueue(QueueHint.RENDER_TRANSPARENT); + const queueId = this._renderGraph.addVertex( + RenderGraphValue.Queue, queue, + 'Queue', '', new RenderData(), + false, this._vertID, ); + this._renderGraph.addVertex( + RenderGraphValue.Blit, new Blit(material, sceneFlags, null), + name, '', new RenderData(), false, queueId, + ); + } + + addCameraQuad (camera: Camera, material: Material, sceneFlags: SceneFlags, name = 'CameraQuad') { + const queue = new RenderQueue(QueueHint.RENDER_TRANSPARENT); + const queueId = this._renderGraph.addVertex( + RenderGraphValue.Queue, queue, + 'Queue', '', new RenderData(), false, this._vertID, + ); + this._renderGraph.addVertex( + RenderGraphValue.Blit, new Blit(material, sceneFlags, camera), + name, '', new RenderData(), false, queueId, + ); + } + setViewport (viewport: Viewport): void { + this._pass.viewport.copy(viewport); } private readonly _renderGraph: RenderGraph; private readonly _vertID: number; + private readonly _layoutID: number; private readonly _pass: RasterPass; private readonly _pipeline: PipelineSceneData; + private readonly _layoutGraph: LayoutGraphData; } export class WebComputeQueueBuilder extends WebSetter implements ComputeQueueBuilder { @@ -226,12 +273,11 @@ export class WebComputeQueueBuilder extends WebSetter implements ComputeQueueBui threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number, - layoutName = '', name = 'Dispatch') { this._renderGraph.addVertex( RenderGraphValue.Dispatch, new Dispatch(shader, threadGroupCountX, threadGroupCountY, threadGroupCountZ), - name, layoutName, new RenderData(), false, this._vertID, + name, '', new RenderData(), false, this._vertID, ); } private readonly _renderGraph: RenderGraph; @@ -241,12 +287,18 @@ export class WebComputeQueueBuilder extends WebSetter implements ComputeQueueBui } export class WebComputePassBuilder extends WebSetter implements ComputePassBuilder { - constructor (data: RenderData, renderGraph: RenderGraph, vertID: number, pass: ComputePass, pipeline: PipelineSceneData) { + constructor (data: RenderData, renderGraph: RenderGraph, layoutGraph: LayoutGraphData, vertID: number, pass: ComputePass, pipeline: PipelineSceneData) { super(data); this._renderGraph = renderGraph; + this._layoutGraph = layoutGraph; this._vertID = vertID; this._pass = pass; this._pipeline = pipeline; + + const layoutName = this._renderGraph.component( + RenderGraphComponent.Layout, this._vertID, + ); + this._layoutID = layoutGraph.locateChild(layoutGraph.nullVertex(), layoutName); } addComputeView (name: string, view: ComputeView) { if (this._pass.computeViews.has(name)) { @@ -255,11 +307,11 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild this._pass.computeViews.set(name, [view]); } } - addQueue (layoutName = '', name = 'Queue') { + addQueue (name = 'Queue') { const queue = new RenderQueue(); const data = new RenderData(); const queueID = this._renderGraph.addVertex( - RenderGraphValue.Queue, queue, name, layoutName, data, false, this._vertID, + RenderGraphValue.Queue, queue, name, '', data, false, this._vertID, ); return new WebComputeQueueBuilder(data, this._renderGraph, queueID, queue, this._pipeline); } @@ -267,16 +319,17 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild threadGroupCountX: number, threadGroupCountY: number, threadGroupCountZ: number, - layoutName = '', name = 'Dispatch') { this._renderGraph.addVertex( RenderGraphValue.Dispatch, new Dispatch(shader, threadGroupCountX, threadGroupCountY, threadGroupCountZ), - name, layoutName, new RenderData(), false, this._vertID, + name, '', new RenderData(), false, this._vertID, ); } private readonly _renderGraph: RenderGraph; + private readonly _layoutGraph: LayoutGraphData; private readonly _vertID: number; + private readonly _layoutID: number; private readonly _pass: ComputePass; private readonly _pipeline: PipelineSceneData; } @@ -317,6 +370,26 @@ function isManaged (residency: ResourceResidency): boolean { } export class WebPipeline extends Pipeline { + public containsResource (name: string): boolean { + return this._resourceGraph.contains(name); + } + public addComputePass(layoutName: string, name: string): ComputePassBuilder; + public addComputePass(layoutName: string): ComputePassBuilder; + public addComputePass (layoutName: any, name?: any): ComputePassBuilder { + throw new Error('Method not implemented.'); + } + public addMovePass (name: string): MovePassBuilder { + throw new Error('Method not implemented.'); + } + public addCopyPass (name: string): CopyPassBuilder { + throw new Error('Method not implemented.'); + } + public presentAll (): void { + throw new Error('Method not implemented.'); + } + public createSceneTransversal (camera: Camera, scene: RenderScene): SceneTransversal { + throw new Error('Method not implemented.'); + } protected _generateConstantMacros (clusterEnabled: boolean) { let str = ''; str += `#define CC_DEVICE_SUPPORT_FLOAT_TEXTURE ${this._device.getFormatFeatures(Format.RGBA32F) @@ -329,29 +402,68 @@ export class WebPipeline extends Pipeline { str += `#define CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES ${macro.ENABLE_WEBGL_HIGHP_STRUCT_VALUES ? 1 : 0}\n`; this._constantMacros = str; } - + public setCustomPipelineName (name: string) { + this._customPipelineName = name; + if (this._customPipelineName === 'Deferred') { + this._usesDeferredPipeline = true; + } + } public activate (swapchain: Swapchain): boolean { this._device = deviceManager.gfxDevice; this._globalDSManager = new GlobalDSManager(this._device); - this._macros.CC_USE_HDR = this._pipelineSceneData.isHDR; + this.setMacroBool('CC_USE_HDR', this._pipelineSceneData.isHDR); this._generateConstantMacros(false); this._pipelineSceneData.activate(this._device); - const descH = new WebDescriptorHierarchy(); - //descH.addEffect(new EffectAsset()); this._pipelineUBO.activate(this._device, this); + const isFloat = supportsR32FloatTexture(this._device) ? 0 : 1; + this.setMacroInt('CC_SHADOWMAP_FORMAT', isFloat); + // 0: SHADOWMAP_LINER_DEPTH_OFF, 1: SHADOWMAP_LINER_DEPTH_ON. + const isLinear = this._device.gfxAPI === API.WEBGL ? 1 : 0; + this.setMacroInt('CC_SHADOWMAP_USE_LINEAR_DEPTH', isLinear); + + // 0: UNIFORM_VECTORS_LESS_EQUAL_64, 1: UNIFORM_VECTORS_GREATER_EQUAL_125. + this.pipelineSceneData.csmSupported = this.device.capabilities.maxFragmentUniformVectors + >= (WebPipeline.CSM_UNIFORM_VECTORS + WebPipeline.GLOBAL_UNIFORM_VECTORS); + this.setMacroBool('CC_SUPPORT_CASCADED_SHADOW_MAP', this.pipelineSceneData.csmSupported); + + // enable the deferred pipeline + if (this.usesDeferredPipeline) { + this.setMacroInt('CC_PIPELINE_TYPE', 1); + } const shadowMapSampler = this._globalDSManager.pointSampler; this.descriptorSet.bindSampler(UNIFORM_SHADOWMAP_BINDING, shadowMapSampler); this.descriptorSet.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); this.descriptorSet.bindSampler(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, shadowMapSampler); this.descriptorSet.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); this.descriptorSet.update(); + this.layoutGraphBuilder.compile(); + + this._forward = new ForwardPipelineBuilder(); + this._deferred = new DeferredPipelineBuilder(); return true; } public destroy (): boolean { + this._globalDSManager?.globalDescriptorSet.destroy(); this._globalDSManager?.destroy(); this._pipelineSceneData?.destroy(); return true; } + public get device (): Device { + return this._device; + } + public get lightingMode (): LightingMode { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return this._lightingMode; + } + public set lightingMode (mode: LightingMode) { + this._lightingMode = mode; + } + public get layoutGraphBuilder (): LayoutGraphBuilder { + return new WebLayoutGraphBuilder(this._device, this._layoutGraph); + } + public get usesDeferredPipeline (): boolean { + return this._usesDeferredPipeline; + } public get macros (): MacroRecord { return this._macros; } @@ -364,6 +476,9 @@ export class WebPipeline extends Pipeline { public get descriptorSet (): DescriptorSet { return this._globalDSManager.globalDescriptorSet; } + public get commandBuffers (): CommandBuffer[] { + return [this._device.commandBuffer]; + } public get pipelineSceneData (): PipelineSceneData { return this._pipelineSceneData; } @@ -385,6 +500,27 @@ export class WebPipeline extends Pipeline { public set shadingScale (scale: number) { this._pipelineSceneData.shadingScale = scale; } + public getMacroString (name: string): string { + const str = this._macros[name]; + if (str === undefined) { + return ''; + } + return str as string; + } + public getMacroInt (name: string): number { + const value = this._macros[name]; + if (value === undefined) { + return 0; + } + return value as number; + } + public getMacroBool (name: string): boolean { + const value = this._macros[name]; + if (value === undefined) { + return false; + } + return value as boolean; + } public setMacroString (name: string, value: string): void { this._macros[name] = value; } @@ -394,9 +530,6 @@ export class WebPipeline extends Pipeline { public setMacroBool (name: string, value: boolean): void { this._macros[name] = value; } - public get device () { - return this._device; - } public onGlobalPipelineStateChanged (): void { // do nothing } @@ -438,7 +571,7 @@ export class WebPipeline extends Pipeline { desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = format; - desc.flags = ResourceFlags.COLOR_ATTACHMENT; + desc.flags = ResourceFlags.COLOR_ATTACHMENT | ResourceFlags.SAMPLED; assert(isManaged(residency)); return this._resourceGraph.addVertex( @@ -457,7 +590,7 @@ export class WebPipeline extends Pipeline { desc.depthOrArraySize = 1; desc.mipLevels = 1; desc.format = format; - desc.flags = ResourceFlags.DEPTH_STENCIL_ATTACHMENT; + desc.flags = ResourceFlags.DEPTH_STENCIL_ATTACHMENT | ResourceFlags.SAMPLED; return this._resourceGraph.addVertex( ResourceGraphValue.Managed, new ManagedResource(), @@ -488,134 +621,46 @@ export class WebPipeline extends Pipeline { throw new Error('Cannot run without creating rendergraph'); } if (!this._executor) { - this._executor = new Executor(this, this._pipelineUBO, this._device, this._resourceGraph); + this._executor = new Executor(this, this._pipelineUBO, this._device, + this._resourceGraph, this.layoutGraph, this.width, this.height); } this._executor.execute(this._renderGraph); } - protected _buildShadowPass (automata: WebPipeline, - light: Readonly, - shadows: Readonly, - passName: Readonly, - width: Readonly, - height: Readonly, - bCastShadow: Readonly) { - if (bCastShadow) { - if (!automata.resourceGraph.contains(this._dsShadowMap)) { - const format = supportsR32FloatTexture(this._device) ? Format.R32F : Format.RGBA8; - automata.addRenderTarget(this._dsShadowMap, format, width, height, ResourceResidency.PERSISTENT); - } - const pass = automata.addRasterPass(width, height, '_', passName); - pass.addRasterView(this._dsShadowMap, new RasterView('_', - AccessType.WRITE, AttachmentType.RENDER_TARGET, - LoadOp.CLEAR, StoreOp.STORE, - ClearFlagBit.COLOR, - new Color(0, 0, 0, 0))); - const queue = pass.addQueue(QueueHint.RENDER_OPAQUE); - queue.addScene(`${passName}_shadowScene`, - SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT | SceneFlags.SHADOW_CASTER); - // setCameraValues(queue, camera, light, shadows); - } - } - protected _buildShadowPasses (automata: WebPipeline, validLights: Light[], - mainLight: Readonly | null, - pplScene: Readonly, - name: Readonly): void { - const shadows = pplScene.shadows; - if (!shadows.enabled || shadows.type !== ShadowType.ShadowMap) { - return; - } - const castShadowObjects = pplScene.csmLayers.castShadowObjects; - const validPunctualLights = pplScene.validPunctualLights; - - // force clean up - validLights.length = 0; - - // pick spot lights - let numSpotLights = 0; - for (let i = 0; numSpotLights < shadows.maxReceived && i < validPunctualLights.length; ++i) { - const light = validPunctualLights[i]; - if (light.type === LightType.SPOT) { - validLights.push(light); - ++numSpotLights; - } - } - - // build shadow map - const bCastShadow = castShadowObjects.length !== 0; - const mapWidth = bCastShadow ? shadows.size.x : 1; - const mapHeight = bCastShadow ? shadows.size.y : 1; - - // main light - if (mainLight) { - const passName = `MainLightShadow${name}`; - this._buildShadowPass(automata, mainLight, shadows, - passName, mapWidth, mapHeight, bCastShadow); - } - // spot lights - for (let i = 0; i !== validLights.length; ++i) { - const passName = `SpotLight${i.toString()}Shadow${name}`; - this._buildShadowPass(automata, validLights[i], shadows, - passName, mapWidth, mapHeight, bCastShadow); - } - } - private readonly _validLights: Light[] = []; - private readonly _dsShadowMap = 'dsShadowMap'; - render (cameras: Camera[]) { - if (cameras.length === 0) { - return; - } + protected _applySize (cameras: Camera[]) { + let newWidth = this._width; + let newHeight = this._height; cameras.forEach((camera) => { + const window = camera.window; + newWidth = Math.max(window.width, newWidth); + newHeight = Math.max(window.height, newHeight); if (!this._cameras.includes(camera)) { this._cameras.push(camera); } }); + if (newWidth !== this._width || newHeight !== this._height) { + this._width = newWidth; + this._height = newHeight; + } + } + + private _width = 0; + private _height = 0; + get width () { return this._width; } + get height () { return this._height; } + render (cameras: Camera[]) { + if (cameras.length === 0) { + return; + } + this._applySize(cameras); + decideProfilerCamera(cameras); // build graph this.beginFrame(); - for (let i = 0; i < cameras.length; i++) { - const camera = cameras[i]; - if (camera.scene) { - const idx = this._cameras.indexOf(camera); - this._buildShadowPasses(this, this._validLights, - camera.scene.mainLight, - this._pipelineSceneData, - `Camera${idx}`); - - const window = camera.window; - const width = Math.floor(window.width); - const height = Math.floor(window.height); - const forwardPassRTName = `dsForwardPassColorCamera${idx}`; - const forwardPassDSName = `dsForwardPassDSCamera${idx}`; - if (!this.resourceGraph.contains(forwardPassRTName)) { - this.addRenderTexture(forwardPassRTName, Format.RGBA8, width, height, camera.window); - this.addDepthStencil(forwardPassDSName, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); - } - const forwardPass = this.addRasterPass(width, height, '_', `CameraForwardPass${idx}`); - if (this.resourceGraph.contains(this._dsShadowMap)) { - forwardPass.addRasterView(this._dsShadowMap, new RasterView('_', - AccessType.READ, AttachmentType.RENDER_TARGET, - LoadOp.CLEAR, StoreOp.DISCARD, - ClearFlagBit.NONE, - new Color(0, 0, 0, 1))); - } - const passView = new RasterView('_', - AccessType.WRITE, AttachmentType.RENDER_TARGET, - LoadOp.CLEAR, StoreOp.STORE, - camera.clearFlag, - new Color(camera.clearColor.x, camera.clearColor.y, camera.clearColor.z, camera.clearColor.w)); - const passDSView = new RasterView('_', - AccessType.WRITE, AttachmentType.DEPTH_STENCIL, - LoadOp.CLEAR, StoreOp.STORE, - camera.clearFlag, - new Color(1, 0, 0, 0)); - forwardPass.addRasterView(forwardPassRTName, passView); - forwardPass.addRasterView(forwardPassDSName, passDSView); - forwardPass - .addQueue(QueueHint.RENDER_OPAQUE) - .addSceneOfCamera(camera, null, SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT); - forwardPass - .addQueue(QueueHint.RENDER_TRANSPARENT) - .addSceneOfCamera(camera, null, SceneFlags.TRANSPARENT_OBJECT); - } + if (this.builder) { + this.builder.setup(cameras, this); + } else if (this.usesDeferredPipeline) { + this._deferred.setup(cameras, this); + } else { + this._forward.setup(cameras, this); } this.compile(); this.execute(); @@ -624,43 +669,17 @@ export class WebPipeline extends Pipeline { addRasterPass (width: number, height: number, layoutName: string, name = 'Raster'): RasterPassBuilder { const pass = new RasterPass(); + pass.viewport.width = width; + pass.viewport.height = height; + const data = new RenderData(); const vertID = this._renderGraph!.addVertex( RenderGraphValue.Raster, pass, name, layoutName, data, false, ); - const result = new WebRasterPassBuilder(data, this._renderGraph!, vertID, pass, this._pipelineSceneData); + const result = new WebRasterPassBuilder(data, this._renderGraph!, this._layoutGraph, vertID, pass, this._pipelineSceneData); this._updateRasterPassConstants(result, width, height); return result; } - addComputePass (layoutName: string, name = 'Compute'): ComputePassBuilder { - const pass = new ComputePass(); - const data = new RenderData(); - const vertID = this._renderGraph!.addVertex( - RenderGraphValue.Compute, pass, name, layoutName, new RenderData(), false, - ); - return new WebComputePassBuilder(data, this._renderGraph!, vertID, pass, this._pipelineSceneData); - } - addMovePass (name = 'Move'): MovePassBuilder { - const pass = new MovePass(); - const vertID = this._renderGraph!.addVertex(RenderGraphValue.Move, pass, name, '', new RenderData(), false); - return new WebMovePassBuilder(this._renderGraph!, vertID, pass); - } - addCopyPass (name = 'Copy'): CopyPassBuilder { - const pass = new CopyPass(); - const vertID = this._renderGraph!.addVertex(RenderGraphValue.Copy, pass, name, '', new RenderData(), false); - return new WebCopyPassBuilder(this._renderGraph!, vertID, pass); - } - presentAll (): void { - const pass = new PresentPass(); - // TODO: add swapchains to present pass - this._renderGraph!.addVertex(RenderGraphValue.Present, pass, '', '', new RenderData(), false); - } - createSceneTransversal (camera: Camera, scene: RenderScene): SceneTransversal { - return new WebSceneTransversal(camera, this.pipelineSceneData); - } - get layoutGraphBuilder (): LayoutGraphBuilder { - return new WebLayoutGraphBuilder(this._device, this._layoutGraph); - } public getDescriptorSetLayout (shaderName: string, freq: UpdateFrequency): DescriptorSetLayout { const lg = this._layoutGraph; const phaseID = lg.shaderLayoutIndex.get(shaderName)!; @@ -689,18 +708,29 @@ export class WebPipeline extends Pipeline { new Vec4(shadingWidth, shadingHeight, 1.0 / shadingWidth, 1.0 / shadingHeight)); } + public static MAX_BLOOM_FILTER_PASS_NUM = 6; + private _usesDeferredPipeline = false; private _device!: Device; private _globalDSManager!: GlobalDSManager; private readonly _macros: MacroRecord = {}; private readonly _pipelineSceneData: PipelineSceneData = new PipelineSceneData(); private _constantMacros = ''; + private _lightingMode = LightingMode.DEFAULT; private _profiler: Model | null = null; private _pipelineUBO: PipelineUBO = new PipelineUBO(); private _cameras: Camera[] = []; - private readonly _layoutGraph: LayoutGraphData = new LayoutGraphData(); + private _layoutGraph: LayoutGraphData = new LayoutGraphData(); private readonly _resourceGraph: ResourceGraph = new ResourceGraph(); private _renderGraph: RenderGraph | null = null; private _compiler: Compiler | null = null; private _executor: Executor | null = null; + private _customPipelineName = ''; + private _forward!: ForwardPipelineBuilder; + private _deferred!: DeferredPipelineBuilder; + public builder: PipelineBuilder | null = null; + // csm uniform used vectors count + public static CSM_UNIFORM_VECTORS = 61; + // all global uniform used vectors count + public static GLOBAL_UNIFORM_VECTORS = 64; } diff --git a/cocos/core/pipeline/custom/web-scene.ts b/cocos/core/pipeline/custom/web-scene.ts index 17877e73dc..12faee61ca 100644 --- a/cocos/core/pipeline/custom/web-scene.ts +++ b/cocos/core/pipeline/custom/web-scene.ts @@ -23,16 +23,15 @@ THE SOFTWARE. ****************************************************************************/ -import { intersect, Sphere } from '../../geometry'; -import { legacyCC } from '../../global-exports'; -import { Mat4, Vec3, Color } from '../../math'; +import { Frustum, intersect } from '../../geometry'; +import { Mat4, Vec3 } from '../../math'; import { RenderScene } from '../../renderer'; -import { Camera, SphereLight, DirectionalLight, Model, Shadows, ShadowType, SKYBOX_FLAG, SubModel } from '../../renderer/scene'; -import { IRenderObject, IRenderPass } from '../define'; +import { Camera, DirectionalLight, Model, Shadows, ShadowType, SKYBOX_FLAG, SubModel } from '../../renderer/scene'; +import { IRenderObject, IRenderPass, UBOShadow } from '../define'; import { PipelineSceneData } from '../pipeline-scene-data'; import { SceneTask, SceneTransversal, SceneVisitor } from './pipeline'; import { TaskType } from './types'; -import { ShadowLayerVolume } from '../shadow/csm-layers'; +import { PipelineUBO } from '../pipeline-ubo'; export class RenderObject implements IRenderObject { public model: Model; @@ -50,71 +49,22 @@ export class RenderInfo implements IRenderPass { public subModel; public passIdx = -1; } + export class WebSceneTask extends SceneTask { - constructor (scneData: PipelineSceneData, camera: Camera, visitor: SceneVisitor) { + constructor (scneData: PipelineSceneData, ubo: PipelineUBO, camera: Camera | null, visitor: SceneVisitor) { super(); - this._scene = camera.scene!; - this._camera = camera; + if (camera) { + this._scene = camera.scene!; + this._camera = camera; + } this._visitor = visitor; this._sceneData = scneData; + this._ubo = ubo; } get taskType (): TaskType { return TaskType.SYNC; } - public static shadowCulling (camera: Camera, sceneData: PipelineSceneData, layer: ShadowLayerVolume) { - const csmLayers = sceneData.csmLayers; - const castShadowObjects = csmLayers.castShadowObjects; - const dirLightFrustum = layer.validFrustum; - const dirShadowObjects = layer.shadowObjects; - dirShadowObjects.length = 0; - const visibility = camera.visibility; - for (let i = 0; i < castShadowObjects.length; i++) { - const castShadowObject = castShadowObjects[i]; - const model = castShadowObject.model; - // filter model by view visibility - if (model.enabled) { - if (model.node && ((visibility & model.node.layer) === model.node.layer)) { - // shadow render Object - if (dirShadowObjects != null && model.castShadow && model.worldBounds) { - // frustum culling - // eslint-disable-next-line no-lonely-if - if (intersect.aabbFrustum(model.worldBounds, dirLightFrustum)) { - dirShadowObjects.push(castShadowObject); - } - } - } - } - } - } - - protected _updateDirLight (light: DirectionalLight) { - const shadows = this._sceneData.shadows; - - const dir = light.direction; - const n = shadows.normal; const d = shadows.distance + 0.001; // avoid z-fighting - const NdL = Vec3.dot(n, dir); const scale = 1 / NdL; - const lx = dir.x * scale; const ly = dir.y * scale; const lz = dir.z * scale; - const nx = n.x; const ny = n.y; const nz = n.z; - const m = shadows.matLight; - m.m00 = 1 - nx * lx; - m.m01 = -nx * ly; - m.m02 = -nx * lz; - m.m03 = 0; - m.m04 = -ny * lx; - m.m05 = 1 - ny * ly; - m.m06 = -ny * lz; - m.m07 = 0; - m.m08 = -nz * lx; - m.m09 = -nz * ly; - m.m10 = 1 - nz * lz; - m.m11 = 0; - m.m12 = lx * d; - m.m13 = ly * d; - m.m14 = lz * d; - m.m15 = 1; - } - protected _getRenderObject (model: Model, camera: Camera) { let depth = 0; if (model.node) { @@ -127,30 +77,29 @@ export class WebSceneTask extends SceneTask { } protected _sceneCulling () { - const scene = this._scene; - const camera = this._camera; - const mainLight = scene.mainLight; + if (!this.camera) { return; } + const scene = this.renderScene; + const camera = this.camera; + const mainLight = scene!.mainLight; const sceneData = this._sceneData; const shadows = sceneData.shadows; const skybox = sceneData.skybox; const csmLayers = sceneData.csmLayers; - const renderObjects = sceneData.renderObjects; renderObjects.length = 0; const castShadowObjects = csmLayers.castShadowObjects; castShadowObjects.length = 0; + const csmLayerObjects = csmLayers.layerObjects; + csmLayerObjects.clear(); if (shadows.enabled) { + this._ubo.updateShadowUBORange(UBOShadow.SHADOW_COLOR_OFFSET, shadows.shadowColor); if (shadows.type === ShadowType.ShadowMap) { - // update lightFrustum - csmLayers.update(sceneData, camera); - } - } - - if (mainLight) { - if (shadows.type === ShadowType.Planar) { - this._updateDirLight(mainLight); + // update CSM layers + if (mainLight && mainLight.node) { + csmLayers.update(sceneData, camera); + } } } @@ -158,7 +107,7 @@ export class WebSceneTask extends SceneTask { renderObjects.push(this._getRenderObject(skybox.model, camera)); } - const models = scene.models; + const models = scene!.models; const visibility = camera.visibility; for (let i = 0; i < models.length; i++) { @@ -168,6 +117,7 @@ export class WebSceneTask extends SceneTask { if (model.enabled) { if (model.castShadow) { castShadowObjects.push(this._getRenderObject(model, camera)); + csmLayerObjects.push(this._getRenderObject(model, camera)); } if (model.node && ((visibility & model.node.layer) === model.node.layer) @@ -193,34 +143,39 @@ export class WebSceneTask extends SceneTask { } get camera () { return this._camera; } - get scene (): RenderScene { + get renderScene () { return this._scene; } get visitor () { return this._visitor; } + get dirLightFrustum () { return this._dirLightFrustum; } get sceneData (): PipelineSceneData { return this._sceneData; } - private _scene: RenderScene; - private _camera: Camera; + private _scene: RenderScene | null = null; + private _camera: Camera | null = null; private _visitor: SceneVisitor; private _sceneData: PipelineSceneData; + private _dirLightFrustum = new Frustum(); + protected _ubo: PipelineUBO; } export class WebSceneTransversal extends SceneTransversal { public preRenderPass (visitor: SceneVisitor): SceneTask { - return new WebSceneTask(this._sceneData, this._camera, visitor); + return new WebSceneTask(this._sceneData, this._ubo, this._camera, visitor); } public postRenderPass (visitor: SceneVisitor): SceneTask { - return new WebSceneTask(this._sceneData, this._camera, visitor); + return new WebSceneTask(this._sceneData, this._ubo, this._camera, visitor); } - constructor (camera: Camera, sceneData: PipelineSceneData) { + constructor (camera: Camera | null, sceneData: PipelineSceneData, ubo: PipelineUBO) { super(); this._camera = camera; - this._scene = camera.scene!; + if (camera) this._scene = camera.scene!; this._sceneData = sceneData; + this._ubo = ubo; } public transverse (visitor: SceneVisitor): SceneTask { - return new WebSceneTask(this._sceneData, this._camera, visitor); + return new WebSceneTask(this._sceneData, this._ubo, this._camera, visitor); } - protected _scene: RenderScene; - protected _camera: Camera; + protected _scene: RenderScene | null = null; + protected _camera: Camera | null = null; + protected _ubo: PipelineUBO; protected _sceneData: PipelineSceneData; } diff --git a/cocos/core/pipeline/define.ts b/cocos/core/pipeline/define.ts index d78b7b2b85..8f5ad4464d 100644 --- a/cocos/core/pipeline/define.ts +++ b/cocos/core/pipeline/define.ts @@ -114,6 +114,7 @@ export enum PipelineGlobalBindings { UBO_GLOBAL, UBO_CAMERA, UBO_SHADOW, + UBO_CSM, // should reserve slot for this optional ubo SAMPLER_SHADOWMAP, SAMPLER_ENVIRONMENT, // don't put this as the first sampler binding due to Mac GL driver issues: cubemap at texture unit 0 causes rendering issues @@ -256,13 +257,11 @@ globalDescriptorSetLayout.layouts[UBOCamera.NAME] = UBOCamera.LAYOUT; globalDescriptorSetLayout.bindings[UBOCamera.BINDING] = UBOCamera.DESCRIPTOR; /** - * @en The uniform buffer object for shadow - * @zh 给阴影对象使用的 UBO + * @en The uniform buffer object for 'cast shadow(fixed || csm)' && 'dir fixed area shadow' && 'spot shadow' && 'sphere shadow' && 'planar shadow' + * @zh 这个 UBO 仅仅只给 'cast shadow(fixed || csm)' && 'dir fixed area shadow' && 'spot shadow' && 'sphere shadow' && 'planar shadow' 使用 */ export class UBOShadow { - public static readonly CSM_LEVEL_COUNT = 4; - public static readonly MAT_LIGHT_PLANE_PROJ_OFFSET = 0; - public static readonly MAT_LIGHT_VIEW_OFFSET = UBOShadow.MAT_LIGHT_PLANE_PROJ_OFFSET + 16; + public static readonly MAT_LIGHT_VIEW_OFFSET = 0; public static readonly MAT_LIGHT_VIEW_PROJ_OFFSET = UBOShadow.MAT_LIGHT_VIEW_OFFSET + 16; public static readonly SHADOW_INV_PROJ_DEPTH_INFO_OFFSET = UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET + 16; public static readonly SHADOW_PROJ_DEPTH_INFO_OFFSET = UBOShadow.SHADOW_INV_PROJ_DEPTH_INFO_OFFSET + 4; @@ -272,20 +271,12 @@ export class UBOShadow { public static readonly SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET = UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 4; public static readonly SHADOW_COLOR_OFFSET = UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 4; public static readonly PLANAR_NORMAL_DISTANCE_INFO_OFFSET = UBOShadow.SHADOW_COLOR_OFFSET + 4; - public static readonly MAT_CSM_VIEW_OFFSET = UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 4; - public static readonly MAT_CSM_VIEW_PROJ_OFFSET = UBOShadow.MAT_CSM_VIEW_OFFSET + 16 * UBOShadow.CSM_LEVEL_COUNT; - public static readonly MAT_CSM_VIEW_PROJ_ATLAS_OFFSET = UBOShadow.MAT_CSM_VIEW_PROJ_OFFSET + 16 * UBOShadow.CSM_LEVEL_COUNT; - public static readonly CSM_PROJ_DEPTH_INFO_OFFSET = UBOShadow.MAT_CSM_VIEW_PROJ_ATLAS_OFFSET + 16 * UBOShadow.CSM_LEVEL_COUNT; - public static readonly CSM_PROJ_INFO_OFFSET = UBOShadow.CSM_PROJ_DEPTH_INFO_OFFSET + 4 * UBOShadow.CSM_LEVEL_COUNT; - public static readonly CSM_SPLITS_INFO_OFFSET = UBOShadow.CSM_PROJ_INFO_OFFSET + 4 * UBOShadow.CSM_LEVEL_COUNT; - public static readonly CSM_INFO_OFFSET = UBOShadow.CSM_SPLITS_INFO_OFFSET + 4; - public static readonly COUNT: number = UBOShadow.CSM_INFO_OFFSET + 4; + public static readonly COUNT: number = UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 4; public static readonly SIZE = UBOShadow.COUNT * 4; public static readonly NAME = 'CCShadow'; public static readonly BINDING = PipelineGlobalBindings.UBO_SHADOW; public static readonly DESCRIPTOR = new DescriptorSetLayoutBinding(UBOShadow.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.ALL); public static readonly LAYOUT = new UniformBlock(SetIndex.GLOBAL, UBOShadow.BINDING, UBOShadow.NAME, [ - new Uniform('cc_matLightPlaneProj', Type.MAT4, 1), new Uniform('cc_matLightView', Type.MAT4, 1), new Uniform('cc_matLightViewProj', Type.MAT4, 1), new Uniform('cc_shadowInvProjDepthInfo', Type.FLOAT4, 1), @@ -296,18 +287,45 @@ export class UBOShadow { new Uniform('cc_shadowLPNNInfo', Type.FLOAT4, 1), new Uniform('cc_shadowColor', Type.FLOAT4, 1), new Uniform('cc_planarNDInfo', Type.FLOAT4, 1), - new Uniform('cc_matCSMView', Type.MAT4, UBOShadow.CSM_LEVEL_COUNT), - new Uniform('cc_matCSMViewProj', Type.MAT4, UBOShadow.CSM_LEVEL_COUNT), - new Uniform('cc_matCSMViewProjAtlas', Type.MAT4, UBOShadow.CSM_LEVEL_COUNT), - new Uniform('cc_csmProjDepthInfo', Type.FLOAT4, UBOShadow.CSM_LEVEL_COUNT), - new Uniform('cc_csmProjInfo', Type.FLOAT4, UBOShadow.CSM_LEVEL_COUNT), - new Uniform('cc_csmSplitsInfo', Type.FLOAT4, 1), - new Uniform('cc_csmInfo', Type.FLOAT4, 1), ], 1); } globalDescriptorSetLayout.layouts[UBOShadow.NAME] = UBOShadow.LAYOUT; globalDescriptorSetLayout.bindings[UBOShadow.BINDING] = UBOShadow.DESCRIPTOR; +/** + * @en The uniform buffer object only for dir csm shadow(level: 1 ~ 4) + * @zh 级联阴影使用的UBO + */ +export class UBOCSM { + public static readonly CSM_LEVEL_COUNT = 4; + public static readonly CSM_VIEW_DIR_0_OFFSET = 0; + public static readonly CSM_VIEW_DIR_1_OFFSET = UBOCSM.CSM_VIEW_DIR_0_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; + public static readonly CSM_VIEW_DIR_2_OFFSET = UBOCSM.CSM_VIEW_DIR_1_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; + public static readonly CSM_ATLAS_OFFSET = UBOCSM.CSM_VIEW_DIR_2_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; + public static readonly MAT_CSM_VIEW_PROJ_OFFSET = UBOCSM.CSM_ATLAS_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; + public static readonly CSM_PROJ_DEPTH_INFO_OFFSET = UBOCSM.MAT_CSM_VIEW_PROJ_OFFSET + 16 * UBOCSM.CSM_LEVEL_COUNT; + public static readonly CSM_PROJ_INFO_OFFSET = UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; + public static readonly CSM_SPLITS_INFO_OFFSET = UBOCSM.CSM_PROJ_INFO_OFFSET + 4 * UBOCSM.CSM_LEVEL_COUNT; + public static readonly COUNT: number = UBOCSM.CSM_SPLITS_INFO_OFFSET + 4; + public static readonly SIZE = UBOCSM.COUNT * 4; + + public static readonly NAME = 'CCCSM'; + public static readonly BINDING = PipelineGlobalBindings.UBO_CSM; + public static readonly DESCRIPTOR = new DescriptorSetLayoutBinding(UBOCSM.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.ALL); + public static readonly LAYOUT = new UniformBlock(SetIndex.GLOBAL, UBOCSM.BINDING, UBOCSM.NAME, [ + new Uniform('cc_csmViewDir0', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT), + new Uniform('cc_csmViewDir1', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT), + new Uniform('cc_csmViewDir2', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT), + new Uniform('cc_csmAtlas', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT), + new Uniform('cc_matCSMViewProj', Type.MAT4, UBOCSM.CSM_LEVEL_COUNT), + new Uniform('cc_csmProjDepthInfo', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT), + new Uniform('cc_csmProjInfo', Type.FLOAT4, UBOCSM.CSM_LEVEL_COUNT), + new Uniform('cc_csmSplitsInfo', Type.FLOAT4, 1), + ], 1); +} +globalDescriptorSetLayout.layouts[UBOCSM.NAME] = UBOCSM.LAYOUT; +globalDescriptorSetLayout.bindings[UBOCSM.BINDING] = UBOCSM.DESCRIPTOR; + /* eslint-disable max-len */ /** diff --git a/cocos/core/pipeline/pipeline-scene-data.ts b/cocos/core/pipeline/pipeline-scene-data.ts index bc7a8f549f..27c3556410 100644 --- a/cocos/core/pipeline/pipeline-scene-data.ts +++ b/cocos/core/pipeline/pipeline-scene-data.ts @@ -55,6 +55,13 @@ export class PipelineSceneData { this._shadingScale = val; } + public get csmSupported () { + return this._csmSupported; + } + public set csmSupported (val: boolean) { + this._csmSupported = val; + } + public fog: Fog = new Fog(); public ambient: Ambient = new Ambient(); public skybox: Skybox = new Skybox(); @@ -85,6 +92,7 @@ export class PipelineSceneData { protected _occlusionQueryShader: Shader | null = null; protected _isHDR = true; protected _shadingScale = 1.0; + protected _csmSupported = true; constructor () { this._shadingScale = 1.0; diff --git a/cocos/core/pipeline/pipeline-ubo.ts b/cocos/core/pipeline/pipeline-ubo.ts index a36e2856b1..1a84ab35cb 100644 --- a/cocos/core/pipeline/pipeline-ubo.ts +++ b/cocos/core/pipeline/pipeline-ubo.ts @@ -24,26 +24,26 @@ */ import { UBOGlobal, UBOShadow, UBOCamera, UNIFORM_SHADOWMAP_BINDING, - supportsR32FloatTexture, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING } from './define'; -import { Device, BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet, API } from '../gfx'; + supportsR32FloatTexture, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, UBOCSM } from './define'; +import { Device, BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet } from '../gfx'; import { Camera } from '../renderer/scene/camera'; import { Mat4, Vec3, Vec4, Color } from '../math'; -import { RenderPipeline } from './render-pipeline'; +import { PipelineRuntime } from './custom/pipeline'; import { legacyCC } from '../global-exports'; import { CSMLevel, PCFType, Shadows, ShadowType } from '../renderer/scene/shadows'; -import { updatePlanarNormalAndDistance, updatePlanarPROJ } from './scene-culling'; import { Light, LightType } from '../renderer/scene/light'; import { DirectionalLight, SpotLight } from '../renderer/scene'; import { RenderWindow } from '../renderer/core/render-window'; import { builtinResMgr } from '../builtin/builtin-res-mgr'; import { Texture2D } from '../assets'; -import { DebugView, DebugViewCompositeType } from './debug-view'; +import { DebugViewCompositeType } from './debug-view'; const _matShadowView = new Mat4(); const _matShadowProj = new Mat4(); const _matShadowViewProj = new Mat4(); const _vec4ShadowInfo = new Vec4(); const _lightDir = new Vec4(0.0, 0.0, 1.0, 0.0); +const _tempVec3 = new Vec3(); export class PipelineUBO { public static updateGlobalUBOView (window: RenderWindow, bufferView: Float32Array) { @@ -87,7 +87,7 @@ export class PipelineUBO { } } - public static updateCameraUBOView (pipeline: RenderPipeline, bufferView: Float32Array, + public static updateCameraUBOView (pipeline: PipelineRuntime, bufferView: Float32Array, camera: Camera) { const scene = camera.scene ? camera.scene : legacyCC.director.getScene().renderScene; const mainLight = scene.mainLight; @@ -201,19 +201,30 @@ export class PipelineUBO { return 0.0; } - public static updateShadowUBOView (pipeline: RenderPipeline, shadowBufferView: Float32Array, camera: Camera) { + public static updatePlanarNormalAndDistance (shadowInfo: Shadows, shadowUBO: Float32Array) { + Vec3.normalize(_tempVec3, shadowInfo.normal); + shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 0] = _tempVec3.x; + shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 1] = _tempVec3.y; + shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 2] = _tempVec3.z; + shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 3] = -shadowInfo.distance; + } + + public static updateShadowUBOView (pipeline: PipelineRuntime, shadowBufferView: Float32Array, + csmBufferView: Float32Array, camera: Camera) { const device = pipeline.device; const mainLight = camera.scene!.mainLight; const sceneData = pipeline.pipelineSceneData; const shadowInfo = sceneData.shadows; const csmLayers = sceneData.csmLayers; const sv = shadowBufferView; + const cv = csmBufferView; + const csmSupported = sceneData.csmSupported; const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; if (mainLight && shadowInfo.enabled) { if (shadowInfo.type === ShadowType.ShadowMap) { if (mainLight.shadowEnabled) { - if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1) { + if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1 || !csmSupported) { const matShadowView = csmLayers.specialLayer.matShadowView; const matShadowProj = csmLayers.specialLayer.matShadowProj; const matShadowViewProj = csmLayers.specialLayer.matShadowViewProj; @@ -240,35 +251,36 @@ export class PipelineUBO { _vec4ShadowInfo.set(0, packing, mainLight.shadowNormalBias, 0); Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET); } else { + const layerThreshold = this.getPCFRadius(shadowInfo, mainLight); for (let i = 0; i < mainLight.csmLevel; i++) { - sv[UBOShadow.CSM_SPLITS_INFO_OFFSET + i] = csmLayers.layers[i].splitCameraFar / mainLight.shadowDistance; - const matShadowView = csmLayers.layers[i].matShadowView; - Mat4.toArray(sv, matShadowView, UBOShadow.MAT_CSM_VIEW_OFFSET + 16 * i); + _vec4ShadowInfo.set(matShadowView.m00, matShadowView.m04, matShadowView.m08, layerThreshold); + Vec4.toArray(cv, _vec4ShadowInfo, UBOCSM.CSM_VIEW_DIR_0_OFFSET + 4 * i); + _vec4ShadowInfo.set(matShadowView.m01, matShadowView.m05, matShadowView.m09, 0.0); + Vec4.toArray(cv, _vec4ShadowInfo, UBOCSM.CSM_VIEW_DIR_1_OFFSET + 4 * i); + _vec4ShadowInfo.set(matShadowView.m02, matShadowView.m06, matShadowView.m10, 0.0); + Vec4.toArray(cv, _vec4ShadowInfo, UBOCSM.CSM_VIEW_DIR_2_OFFSET + 4 * i); + + const csmAtlas = csmLayers.layers[i].csmAtlas; + Vec4.toArray(cv, csmAtlas, UBOCSM.CSM_ATLAS_OFFSET + 4 * i); + + cv[UBOCSM.CSM_SPLITS_INFO_OFFSET + i] = csmLayers.layers[i].splitCameraFar / mainLight.shadowDistance; const matShadowViewProj = csmLayers.layers[i].matShadowViewProj; - Mat4.toArray(sv, matShadowViewProj, UBOShadow.MAT_CSM_VIEW_PROJ_OFFSET + 16 * i); - - const matShadowViewProjAtlas = csmLayers.layers[i].matShadowViewProjAtlas; - Mat4.toArray(sv, matShadowViewProjAtlas, UBOShadow.MAT_CSM_VIEW_PROJ_ATLAS_OFFSET + 16 * i); + Mat4.toArray(cv, matShadowViewProj, UBOCSM.MAT_CSM_VIEW_PROJ_OFFSET + 16 * i); const matShadowProj = csmLayers.layers[i].matShadowProj; - sv[UBOShadow.CSM_PROJ_DEPTH_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m10; - sv[UBOShadow.CSM_PROJ_DEPTH_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m14; - sv[UBOShadow.CSM_PROJ_DEPTH_INFO_OFFSET + 2 + 4 * i] = matShadowProj.m11; - sv[UBOShadow.CSM_PROJ_DEPTH_INFO_OFFSET + 3 + 4 * i] = matShadowProj.m15; + cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m10; + cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m14; + cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 2 + 4 * i] = matShadowProj.m11; + cv[UBOCSM.CSM_PROJ_DEPTH_INFO_OFFSET + 3 + 4 * i] = matShadowProj.m15; - sv[UBOShadow.CSM_PROJ_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m00; - sv[UBOShadow.CSM_PROJ_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m05; - sv[UBOShadow.CSM_PROJ_INFO_OFFSET + 2 + 4 * i] = 1.0 / matShadowProj.m00; - sv[UBOShadow.CSM_PROJ_INFO_OFFSET + 3 + 4 * i] = 1.0 / matShadowProj.m05; + cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 0 + 4 * i] = matShadowProj.m00; + cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 1 + 4 * i] = matShadowProj.m05; + cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 2 + 4 * i] = 1.0 / matShadowProj.m00; + cv[UBOCSM.CSM_PROJ_INFO_OFFSET + 3 + 4 * i] = 1.0 / matShadowProj.m05; } - sv[UBOShadow.CSM_INFO_OFFSET + 0] = 0; - sv[UBOShadow.CSM_INFO_OFFSET + 1] = this.getPCFRadius(shadowInfo, mainLight); - sv[UBOShadow.CSM_INFO_OFFSET + 2] = 0; - sv[UBOShadow.CSM_INFO_OFFSET + 3] = 0; - _vec4ShadowInfo.set(0, 0, 0, 1.0 - mainLight.shadowSaturation); Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); @@ -279,21 +291,22 @@ export class PipelineUBO { Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET); } } else { - updatePlanarPROJ(shadowInfo, mainLight, sv); - updatePlanarNormalAndDistance(shadowInfo, sv); + PipelineUBO.updatePlanarNormalAndDistance(shadowInfo, sv); } Color.toArray(sv, shadowInfo.shadowColor, UBOShadow.SHADOW_COLOR_OFFSET); } } - public static updateShadowUBOLightView (pipeline: RenderPipeline, shadowBufferView: Float32Array, light: Light, level: number) { + public static updateShadowUBOLightView (pipeline: PipelineRuntime, shadowBufferView: Float32Array, light: Light, level: number) { const device = pipeline.device; const sceneData = pipeline.pipelineSceneData; const shadowInfo = sceneData.shadows; const csmLayers = sceneData.csmLayers; const sv = shadowBufferView; const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; + const cap = pipeline.device.capabilities; + switch (light.type) { case LightType.DIRECTIONAL: { const mainLight = light as DirectionalLight; @@ -363,7 +376,8 @@ export class PipelineUBO { Mat4.invert(_matShadowView, (light as any).node.getWorldMatrix()); Mat4.toArray(sv, _matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET); - Mat4.perspective(_matShadowProj, (light as any).angle, 1.0, 0.001, (light as any).range); + Mat4.perspective(_matShadowProj, (light as any).angle, 1.0, 0.001, (light as any).range, + true, cap.clipSpaceMinZ, cap.clipSpaceSignY, 0); Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); Mat4.toArray(sv, _matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); @@ -388,9 +402,10 @@ export class PipelineUBO { protected _globalUBO = new Float32Array(UBOGlobal.COUNT); protected _cameraUBO = new Float32Array(UBOCamera.COUNT); protected _shadowUBO = new Float32Array(UBOShadow.COUNT); + protected _csmUBO = new Float32Array(UBOCSM.COUNT); static _combineSignY = 0; protected declare _device: Device; - protected declare _pipeline: RenderPipeline; + protected declare _pipeline: PipelineRuntime; /** *|combinedSignY|clipSpaceSignY|screenSpaceSignY| Backends | @@ -409,7 +424,7 @@ export class PipelineUBO { PipelineUBO._combineSignY = (device.capabilities.screenSpaceSignY * 0.5 + 0.5) << 1 | (device.capabilities.clipSpaceSignY * 0.5 + 0.5); } - public activate (device: Device, pipeline: RenderPipeline) { + public activate (device: Device, pipeline: PipelineRuntime) { this._device = device; this._pipeline = pipeline; const ds = this._pipeline.descriptorSet; @@ -437,6 +452,13 @@ export class PipelineUBO { UBOShadow.SIZE, )); ds.bindBuffer(UBOShadow.BINDING, shadowUBO); + const csmUBO = device.createBuffer(new BufferInfo( + BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, + UBOCSM.SIZE, + UBOCSM.SIZE, + )); + ds.bindBuffer(UBOCSM.BINDING, csmUBO); } /** @@ -478,9 +500,10 @@ export class PipelineUBO { if (mainLight && shadowFrameBufferMap.has(mainLight)) { ds.bindTexture(UNIFORM_SHADOWMAP_BINDING, shadowFrameBufferMap.get(mainLight)!.colorTextures[0]!); } - PipelineUBO.updateShadowUBOView(this._pipeline, this._shadowUBO, camera); + PipelineUBO.updateShadowUBOView(this._pipeline, this._shadowUBO, this._csmUBO, camera); ds.update(); cmdBuffer[0].updateBuffer(ds.getBuffer(UBOShadow.BINDING), this._shadowUBO); + cmdBuffer[0].updateBuffer(ds.getBuffer(UBOCSM.BINDING), this._csmUBO); } public updateShadowUBOLight (globalDS: DescriptorSet, light: Light, level = 0) { diff --git a/cocos/core/pipeline/planar-shadow-queue.ts b/cocos/core/pipeline/planar-shadow-queue.ts index 5ec1517544..a0049614f8 100644 --- a/cocos/core/pipeline/planar-shadow-queue.ts +++ b/cocos/core/pipeline/planar-shadow-queue.ts @@ -32,7 +32,7 @@ import { Model, Camera } from '../renderer/scene'; import { RenderInstancedQueue } from './render-instanced-queue'; import { ShadowType } from '../renderer/scene/shadows'; import { Layers } from '../scene-graph/layers'; -import { RenderPipeline } from './render-pipeline'; +import { PipelineRuntime } from './custom/pipeline'; const _ab = new AABB(); @@ -40,15 +40,14 @@ export class PlanarShadowQueue { private _pendingModels: Model[] = []; private _castModels:Model[] = []; private _instancedQueue = new RenderInstancedQueue(); - private _pipeline: RenderPipeline; + private _pipeline: PipelineRuntime; - constructor (pipeline: RenderPipeline) { + constructor (pipeline: PipelineRuntime) { this._pipeline = pipeline; } public gatherShadowPasses (camera: Camera, cmdBuff: CommandBuffer) { const pipelineSceneData = this._pipeline.pipelineSceneData; - const pipelineUBO = this._pipeline.pipelineUBO; const shadows = pipelineSceneData.shadows; this._instancedQueue.clear(); this._pendingModels.length = 0; diff --git a/cocos/core/pipeline/render-additive-light-queue.ts b/cocos/core/pipeline/render-additive-light-queue.ts index 1416d82419..44487057e9 100644 --- a/cocos/core/pipeline/render-additive-light-queue.ts +++ b/cocos/core/pipeline/render-additive-light-queue.ts @@ -24,7 +24,6 @@ */ import { BatchingSchemes, Pass } from '../renderer/core/pass'; -import { RenderPipeline } from './render-pipeline'; import { Model } from '../renderer/scene/model'; import { PipelineStateManager } from './pipeline-state-manager'; import { Vec3, nextPow2, Mat4, Color } from '../math'; @@ -41,9 +40,10 @@ import { getPhaseID } from './pass-phase'; import { Light, LightType } from '../renderer/scene/light'; import { SetIndex, UBOForwardLight, UBOShadow, UNIFORM_SHADOWMAP_BINDING, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, supportsR32FloatTexture } from './define'; -import { updatePlanarNormalAndDistance, updatePlanarPROJ } from './scene-culling'; import { Camera, ShadowType } from '../renderer/scene'; import { GlobalDSManager } from './global-descriptor-set-manager'; +import { PipelineUBO } from './pipeline-ubo'; +import { PipelineRuntime } from './custom/pipeline'; interface IAdditiveLightPass { subModel: SubModel; @@ -111,7 +111,7 @@ function isInstancedOrBatched (model: Model) { * @zh 叠加光照队列。 */ export class RenderAdditiveLightQueue { - private _pipeline: RenderPipeline; + private _pipeline: PipelineRuntime; private _device: Device; private _lightPasses: IAdditiveLightPass[] = []; private _instancedLightPassPool = _lightPassPool.alloc(); @@ -127,7 +127,7 @@ export class RenderAdditiveLightQueue { private _batchedQueue: RenderBatchedQueue; private _lightMeterScale = 10000.0; - constructor (pipeline: RenderPipeline) { + constructor (pipeline: PipelineRuntime) { this._pipeline = pipeline; this._device = pipeline.device; this._instancedQueue = new RenderInstancedQueue(); @@ -333,6 +333,7 @@ export class RenderAdditiveLightQueue { const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; const globalDSManager: GlobalDSManager = this._pipeline.globalDSManager; const validPunctualLights = sceneData.validPunctualLights; + const cap = this._pipeline.device.capabilities; for (let i = 0; i < validPunctualLights.length; i++) { const light = validPunctualLights[i]; @@ -344,8 +345,7 @@ export class RenderAdditiveLightQueue { case LightType.SPHERE: { // planar PROJ if (mainLight) { - updatePlanarPROJ(shadowInfo, mainLight, this._shadowUBO); - updatePlanarNormalAndDistance(shadowInfo, this._shadowUBO); + PipelineUBO.updatePlanarNormalAndDistance(shadowInfo, this._shadowUBO); } this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x; @@ -367,15 +367,15 @@ export class RenderAdditiveLightQueue { // planar PROJ if (mainLight) { - updatePlanarPROJ(shadowInfo, mainLight, this._shadowUBO); - updatePlanarNormalAndDistance(shadowInfo, this._shadowUBO); + PipelineUBO.updatePlanarNormalAndDistance(shadowInfo, this._shadowUBO); } // light view Mat4.invert(_matShadowView, (light as SpotLight).node!.getWorldMatrix()); // light proj - Mat4.perspective(_matShadowViewProj, (light as SpotLight).angle, 1.0, 0.001, (light as SpotLight).range); + Mat4.perspective(_matShadowViewProj, (light as SpotLight).angle, 1.0, 0.001, (light as SpotLight).range, + true, cap.clipSpaceMinZ, cap.clipSpaceSignY, 0); matShadowProj = _matShadowViewProj.clone(); matShadowInvProj = _matShadowViewProj.clone().invert(); diff --git a/cocos/core/pipeline/render-pipeline.ts b/cocos/core/pipeline/render-pipeline.ts index ff07bf5052..360cce60a3 100644 --- a/cocos/core/pipeline/render-pipeline.ts +++ b/cocos/core/pipeline/render-pipeline.ts @@ -386,6 +386,30 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi } } + public getMacroString (name: string): string { + const str = this._macros[name]; + if (str === undefined) { + return ''; + } + return str as string; + } + + public getMacroInt (name: string): number { + const value = this._macros[name]; + if (value === undefined) { + return 0; + } + return value as number; + } + + public getMacroBool (name: string): boolean { + const value = this._macros[name]; + if (value === undefined) { + return false; + } + return value as boolean; + } + public setMacroString (name: string, value: string): void { this._macros[name] = value; } diff --git a/cocos/core/pipeline/render-shadow-map-batched-queue.ts b/cocos/core/pipeline/render-shadow-map-batched-queue.ts index 56febd8d64..a3e6c74aae 100644 --- a/cocos/core/pipeline/render-shadow-map-batched-queue.ts +++ b/cocos/core/pipeline/render-shadow-map-batched-queue.ts @@ -35,28 +35,19 @@ import { ShadowType } from '../renderer/scene/shadows'; import { Light, LightType } from '../renderer/scene/light'; import { intersect } from '../geometry'; import { Model } from '../renderer/scene/model'; -import { RenderPipeline } from './render-pipeline'; import { Camera, DirectionalLight, SpotLight } from '../renderer/scene'; import { shadowCulling } from './scene-culling'; +import { PipelineRuntime } from './custom/pipeline'; const _phaseID = getPhaseID('shadow-caster'); -const _shadowPassIndices: number[] = []; -function getShadowPassIndex (subModels: SubModel[], shadowPassIndices: number[]) { - shadowPassIndices.length = 0; - let hasShadowPass = false; - for (let j = 0; j < subModels.length; j++) { - const { passes } = subModels[j]; - let shadowPassIndex = -1; - for (let k = 0; k < passes.length; k++) { - if (passes[k].phase === _phaseID) { - shadowPassIndex = k; - hasShadowPass = true; - break; - } +function getShadowPassIndex (subModel: SubModel) : number { + const passes = subModel.passes; + for (let k = 0; k < passes.length; k++) { + if (passes[k].phase === _phaseID) { + return k; } - shadowPassIndices.push(shadowPassIndex); } - return hasShadowPass; + return -1; } /** @@ -64,14 +55,14 @@ function getShadowPassIndex (subModels: SubModel[], shadowPassIndices: number[]) * 阴影渲染队列 */ export class RenderShadowMapBatchedQueue { - private _pipeline: RenderPipeline; + private _pipeline: PipelineRuntime; private _subModelsArray: SubModel[] = []; private _passArray: Pass[] = []; private _shaderArray: Shader[] = []; private _instancedQueue: RenderInstancedQueue; private _batchedQueue: RenderBatchedQueue; - public constructor (pipeline: RenderPipeline) { + public constructor (pipeline: PipelineRuntime) { this._pipeline = pipeline; this._instancedQueue = new RenderInstancedQueue(); this._batchedQueue = new RenderBatchedQueue(); @@ -100,8 +91,7 @@ export class RenderShadowMapBatchedQueue { for (let i = 0; i < dirShadowObjects.length; i++) { const ro = dirShadowObjects[i]; const model = ro.model; - if (!getShadowPassIndex(model.subModels, _shadowPassIndices)) { continue; } - this.add(model, _shadowPassIndices); + this.add(model); } } @@ -114,12 +104,11 @@ export class RenderShadowMapBatchedQueue { for (let i = 0; i < castShadowObjects.length; i++) { const ro = castShadowObjects[i]; const model = ro.model; - if (!getShadowPassIndex(model.subModels, _shadowPassIndices)) { continue; } if (model.worldBounds) { if (!intersect.aabbFrustum(model.worldBounds, spotLight.frustum)) { continue; } } - this.add(model, _shadowPassIndices); + this.add(model); } } break; @@ -143,12 +132,12 @@ export class RenderShadowMapBatchedQueue { this._batchedQueue.clear(); } - public add (model: Model, _shadowPassIndices: number[]) { + public add (model: Model) { const subModels = model.subModels; for (let j = 0; j < subModels.length; j++) { const subModel = subModels[j]; - const shadowPassIdx = _shadowPassIndices[j]; - if (shadowPassIdx < 0) { return; } + const shadowPassIdx = getShadowPassIndex(subModel); + if (shadowPassIdx < 0) { continue; } const pass = subModel.passes[shadowPassIdx]; const batchingScheme = pass.batchingScheme; diff --git a/cocos/core/pipeline/scene-culling.ts b/cocos/core/pipeline/scene-culling.ts index b2b28f419a..52ca536887 100644 --- a/cocos/core/pipeline/scene-culling.ts +++ b/cocos/core/pipeline/scene-culling.ts @@ -23,15 +23,14 @@ THE SOFTWARE. */ -import { AABB, Frustum, intersect, Sphere } from '../geometry'; +import { intersect, Sphere } from '../geometry'; import { Model } from '../renderer/scene/model'; import { Camera, SKYBOX_FLAG } from '../renderer/scene/camera'; -import { Vec3, Mat4, Color } from '../math'; +import { Vec3 } from '../math'; import { RenderPipeline } from './render-pipeline'; import { Pool } from '../memop'; import { IRenderObject, UBOShadow } from './define'; -import { ShadowType, Shadows, CSMLevel, CSMOptimizationMode } from '../renderer/scene/shadows'; -import { SphereLight, DirectionalLight } from '../renderer/scene'; +import { ShadowType, Shadows, CSMOptimizationMode } from '../renderer/scene/shadows'; import { PipelineSceneData } from './pipeline-scene-data'; import { ShadowLayerVolume } from './shadow/csm-layers'; @@ -52,99 +51,6 @@ function getRenderObject (model: Model, camera: Camera) { return ro; } -function updateSphereLight (pipeline: RenderPipeline, light: SphereLight) { - const shadows = pipeline.pipelineSceneData.shadows; - - const pos = light.node!.worldPosition; - const n = shadows.normal; const d = shadows.distance + 0.001; // avoid z-fighting - const NdL = Vec3.dot(n, pos); - const lx = pos.x; const ly = pos.y; const lz = pos.z; - const nx = n.x; const ny = n.y; const nz = n.z; - const m = shadows.matLight; - m.m00 = NdL - d - lx * nx; - m.m01 = -ly * nx; - m.m02 = -lz * nx; - m.m03 = -nx; - m.m04 = -lx * ny; - m.m05 = NdL - d - ly * ny; - m.m06 = -lz * ny; - m.m07 = -ny; - m.m08 = -lx * nz; - m.m09 = -ly * nz; - m.m10 = NdL - d - lz * nz; - m.m11 = -nz; - m.m12 = lx * d; - m.m13 = ly * d; - m.m14 = lz * d; - m.m15 = NdL; - - pipeline.pipelineUBO.updateShadowUBORange(UBOShadow.MAT_LIGHT_PLANE_PROJ_OFFSET, shadows.matLight); -} - -function updateDirLight (pipeline: RenderPipeline, light: DirectionalLight) { - const shadows = pipeline.pipelineSceneData.shadows; - - const dir = light.direction; - const n = shadows.normal; const d = shadows.distance + 0.001; // avoid z-fighting - const NdL = Vec3.dot(n, dir); const scale = 1 / NdL; - const lx = dir.x * scale; const ly = dir.y * scale; const lz = dir.z * scale; - const nx = n.x; const ny = n.y; const nz = n.z; - const m = shadows.matLight; - m.m00 = 1 - nx * lx; - m.m01 = -nx * ly; - m.m02 = -nx * lz; - m.m03 = 0; - m.m04 = -ny * lx; - m.m05 = 1 - ny * ly; - m.m06 = -ny * lz; - m.m07 = 0; - m.m08 = -nz * lx; - m.m09 = -nz * ly; - m.m10 = 1 - nz * lz; - m.m11 = 0; - m.m12 = lx * d; - m.m13 = ly * d; - m.m14 = lz * d; - m.m15 = 1; - - pipeline.pipelineUBO.updateShadowUBORange(UBOShadow.MAT_LIGHT_PLANE_PROJ_OFFSET, shadows.matLight); -} - -export function updatePlanarPROJ (shadowInfo: Shadows, light: DirectionalLight, shadowUBO: Float32Array) { - const dir = light.direction; - const n = shadowInfo.normal; const d = shadowInfo.distance + 0.001; // avoid z-fighting - const NdL = Vec3.dot(n, dir); const scale = 1 / NdL; - const lx = dir.x * scale; const ly = dir.y * scale; const lz = dir.z * scale; - const nx = n.x; const ny = n.y; const nz = n.z; - const m = shadowInfo.matLight; - m.m00 = 1 - nx * lx; - m.m01 = -nx * ly; - m.m02 = -nx * lz; - m.m03 = 0; - m.m04 = -ny * lx; - m.m05 = 1 - ny * ly; - m.m06 = -ny * lz; - m.m07 = 0; - m.m08 = -nz * lx; - m.m09 = -nz * ly; - m.m10 = 1 - nz * lz; - m.m11 = 0; - m.m12 = lx * d; - m.m13 = ly * d; - m.m14 = lz * d; - m.m15 = 1; - - Mat4.toArray(shadowUBO, m, UBOShadow.MAT_LIGHT_PLANE_PROJ_OFFSET); -} - -export function updatePlanarNormalAndDistance (shadowInfo: Shadows, shadowUBO: Float32Array) { - Vec3.normalize(_tempVec3, shadowInfo.normal); - shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 0] = _tempVec3.x; - shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 1] = _tempVec3.y; - shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 2] = _tempVec3.z; - shadowUBO[UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_OFFSET + 3] = shadowInfo.distance; -} - export function validPunctualLightsCulling (pipeline: RenderPipeline, camera: Camera) { const sceneData = pipeline.pipelineSceneData; const validPunctualLights = sceneData.validPunctualLights; @@ -239,12 +145,6 @@ export function sceneCulling (pipeline: RenderPipeline, camera: Camera) { } } - if (mainLight) { - if (shadows.type === ShadowType.Planar) { - updateDirLight(pipeline, mainLight); - } - } - if (skybox.enabled && skybox.model && (camera.clearFlag & SKYBOX_FLAG)) { renderObjects.push(getRenderObject(skybox.model, camera)); } diff --git a/cocos/core/pipeline/shadow/csm-layers.ts b/cocos/core/pipeline/shadow/csm-layers.ts index ed024f4e10..5ca571e06a 100644 --- a/cocos/core/pipeline/shadow/csm-layers.ts +++ b/cocos/core/pipeline/shadow/csm-layers.ts @@ -20,7 +20,7 @@ */ import { DirectionalLight, Camera, Shadows, CSMLevel, CSMOptimizationMode } from '../../renderer/scene'; -import { Mat4, Vec3, Vec2, Quat } from '../../math'; +import { Mat4, Vec3, Vec2, Vec4 } from '../../math'; import { Frustum, AABB } from '../../geometry'; import { IRenderObject } from '../define'; import { legacyCC } from '../../global-exports'; @@ -43,8 +43,6 @@ const _snap = new Vec3(); const _maxVec3 = new Vec3(10000000, 10000000, 10000000); const _minVec3 = new Vec3(-10000000, -10000000, -10000000); const _shadowPos = new Vec3(); -const _bias = new Vec3(); -const _scale = new Vec3(); let _maxLayerPosz = 0.0; let _maxLayerFarPlane = 0.0; @@ -162,9 +160,10 @@ export class ShadowLayerVolume { orthoSizeWidth = orthoSizeHeight = Vec3.distance(this._lightViewFrustum.vertices[0], this._lightViewFrustum.vertices[6]); } - if (dirLight.csmLevel > 1 && dirLight.csmOptimizationMode + const csmLevel = legacyCC.director.root.pipeline.pipelineSceneData.csmSupported ? dirLight.csmLevel : 1; + if (csmLevel > 1 && dirLight.csmOptimizationMode === CSMOptimizationMode.RemoveDuplicates) { - if (this._level >= dirLight.csmLevel - 1) { + if (this._level >= csmLevel - 1) { _maxLayerFarPlane = this._castLightViewBoundingBox.halfExtents.z; _maxLayerPosz = this._castLightViewBoundingBox.center.z; } else { @@ -217,8 +216,7 @@ export class CSMShadowLayer extends ShadowLayerVolume { protected _splitCameraNear = 0; protected _splitCameraFar = 0; - protected _matShadowAtlas: Mat4 = new Mat4(); - protected _matShadowViewProjAtlas: Mat4 = new Mat4(); + protected _csmAtlas: Vec4 = new Vec4(); constructor (level: number) { super(level); @@ -239,18 +237,11 @@ export class CSMShadowLayer extends ShadowLayerVolume { this._splitCameraFar = val; } - get matShadowAtlas () { - return this._matShadowAtlas; + get csmAtlas () { + return this._csmAtlas; } - set matShadowViewAtlas (val) { - this._matShadowAtlas = val; - } - - get matShadowViewProjAtlas () { - return this._matShadowViewProjAtlas; - } - set matShadowViewProjAtlas (val) { - this._matShadowViewProjAtlas = val; + set csmAtlas (val) { + this._csmAtlas = val; } public destroy () { @@ -261,9 +252,7 @@ export class CSMShadowLayer extends ShadowLayerVolume { const clipSpaceSignY = legacyCC.director.root.device.capabilities.clipSpaceSignY; const x = level % 2 - 0.5; const y = (0.5 - Math.floor(level / 2)) * clipSpaceSignY; - _bias.set(x, y, 0); - _scale.set(0.5, 0.5, 1); - Mat4.fromRTS(this._matShadowAtlas, Quat.IDENTITY, _bias, _scale); + this._csmAtlas.set(0.5, 0.5, x, y); } } @@ -310,7 +299,7 @@ export class CSMLayers { if (dirLight === null) { return; } const shadowInfo = sceneData.shadows; - const levelCount = dirLight.csmLevel; + const levelCount = legacyCC.director.root.pipeline.pipelineSceneData.csmSupported ? dirLight.csmLevel : 1; const shadowDistance = dirLight.shadowDistance; if (!shadowInfo.enabled || !dirLight.shadowEnabled) { return; } @@ -359,7 +348,7 @@ export class CSMLayers { const nd = 0.1; const fd = dirLight.shadowDistance; const ratio = fd / nd; - const level = dirLight.csmLevel; + const level = legacyCC.director.root.pipeline.pipelineSceneData.csmSupported ? dirLight.csmLevel : 1; const lambda = dirLight.csmLayerLambda; this._layers[0].splitCameraNear = nd; for (let i = 1; i < level; i++) { @@ -379,7 +368,7 @@ export class CSMLayers { } private _calculateCSM (camera: Camera, dirLight: DirectionalLight, shadowInfo: Shadows) { - const level = dirLight.csmLevel; + const level = legacyCC.director.root.pipeline.pipelineSceneData.csmSupported ? dirLight.csmLevel : 1; const shadowMapWidth = level > 1 ? shadowInfo.size.x * 0.5 : shadowInfo.size.x; if (shadowMapWidth < 0.0) { return; } @@ -391,8 +380,6 @@ export class CSMLayers { const far = csmLayer.splitCameraFar; csmLayer.calculateSplitFrustum(camera, _mat4Trans, near, far); csmLayer.createMatrix(dirLight, shadowMapWidth, false); - - Mat4.multiply(csmLayer.matShadowViewProjAtlas, csmLayer.matShadowAtlas, csmLayer.matShadowViewProj); } if (level === CSMLevel.LEVEL_1) { diff --git a/cocos/core/pipeline/shadow/shadow-flow.ts b/cocos/core/pipeline/shadow/shadow-flow.ts index 562b4a531c..5444843e43 100644 --- a/cocos/core/pipeline/shadow/shadow-flow.ts +++ b/cocos/core/pipeline/shadow/shadow-flow.ts @@ -24,7 +24,7 @@ */ import { ccclass } from 'cc.decorator'; -import { PIPELINE_FLOW_SHADOW, supportsR32FloatTexture } from '../define'; +import { PIPELINE_FLOW_SHADOW, supportsR32FloatTexture, UBOCamera, UBOCSM, UBOGlobal, UBOShadow } from '../define'; import { IRenderFlowInfo, RenderFlow } from '../render-flow'; import { ForwardFlowPriority } from '../enum'; import { ShadowStage } from './shadow-stage'; @@ -83,6 +83,11 @@ export class ShadowFlow extends RenderFlow { const isLinear = pipeline.device.gfxAPI === API.WEBGL ? 1 : 0; pipeline.macros.CC_SHADOWMAP_USE_LINEAR_DEPTH = isLinear; + // 0: UNIFORM_VECTORS_LESS_EQUAL_64, 1: UNIFORM_VECTORS_GREATER_EQUAL_125. + pipeline.pipelineSceneData.csmSupported = pipeline.device.capabilities.maxFragmentUniformVectors + >= (UBOGlobal.COUNT + UBOCamera.COUNT + UBOShadow.COUNT + UBOCSM.COUNT) / 4; + pipeline.macros.CC_SUPPORT_CASCADED_SHADOW_MAP = pipeline.pipelineSceneData.csmSupported; + pipeline.onGlobalPipelineStateChanged(); } @@ -127,7 +132,8 @@ export class ShadowFlow extends RenderFlow { if (mainLight.shadowFixedArea) { this._renderStage(camera, mainLight, shadowFrameBuffer!, globalDS); } else { - for (let i = 0; i < mainLight.csmLevel; i++) { + const csmLevel = pipeline.pipelineSceneData.csmSupported ? mainLight.csmLevel : 1; + for (let i = 0; i < csmLevel; i++) { this._renderStage(camera, mainLight, shadowFrameBuffer!, globalDS, i); } } diff --git a/cocos/core/pipeline/shadow/shadow-stage.ts b/cocos/core/pipeline/shadow/shadow-stage.ts index 65770cd4ca..f4e768a0b0 100644 --- a/cocos/core/pipeline/shadow/shadow-stage.ts +++ b/cocos/core/pipeline/shadow/shadow-stage.ts @@ -119,7 +119,7 @@ export class ShadowStage extends RenderStage { switch (this._light.type) { case LightType.DIRECTIONAL: { const mainLight = this._light as DirectionalLight; - if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1) { + if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1 || !pipelineSceneData.csmSupported) { this._renderArea.x = 0; this._renderArea.y = 0; this._renderArea.width = shadowMapSize.x; diff --git a/cocos/core/platform/macro.ts b/cocos/core/platform/macro.ts index 9d3e319b92..cfb92e4550 100644 --- a/cocos/core/platform/macro.ts +++ b/cocos/core/platform/macro.ts @@ -1071,6 +1071,16 @@ interface Macro { */ BATCHER2D_MEM_INCREMENT: number; + /** + * @zh 自定义渲染管线的名字(实验性) + * 引擎会根据名字创建对应的渲染管线(仅限Web平台)。如果名字为空,则不启用自定义渲染管线。 + * 目前仅支持'Forward', 'Deferred'两种。 + * @en The name of custom rendering pipeline (experimental) + * Engine will use the name to create the custom pipeline (Web only). If the name is empty, custom pipeline will be disabled. + * Currently only 'Forward' and 'Deferred' are supported. + */ + CUSTOM_PIPELINE_NAME: string; + /** * @internal */ @@ -1104,6 +1114,7 @@ const macro: Macro = { MAX_LABEL_CANVAS_POOL_SIZE: 20, ENABLE_WEBGL_HIGHP_STRUCT_VALUES: false, BATCHER2D_MEM_INCREMENT: 144, + CUSTOM_PIPELINE_NAME: '', init () { if (NATIVE || MINIGAME || RUNTIME_BASED) { this.CLEANUP_IMAGE_CACHE = true; diff --git a/cocos/core/renderer/core/program-lib.ts b/cocos/core/renderer/core/program-lib.ts index fa4499856b..04d9231d07 100644 --- a/cocos/core/renderer/core/program-lib.ts +++ b/cocos/core/renderer/core/program-lib.ts @@ -443,28 +443,9 @@ class ProgramLib { const tmpl = this._templates[name]; const tmplInfo = this._templateInfos[tmpl.hash]; if (!tmplInfo.pipelineLayout) { - const director = legacyCC.director; - if (director.root.usesCustomPipeline) { - const root = legacyCC.director.root; - const ppl: Pipeline = root.customPipeline; - insertBuiltinBindings(tmpl, tmplInfo, globalDescriptorSetLayout, 'globals'); - const globalDS = ppl.getDescriptorSetLayout(name, UpdateFrequency.PER_PASS); - const materialDS = ppl.getDescriptorSetLayout(name, UpdateFrequency.PER_BATCH); - const localDS = ppl.getDescriptorSetLayout(name, UpdateFrequency.PER_INSTANCE); - if (globalDS) { - tmplInfo.setLayouts[SetIndex.GLOBAL] = globalDS; - } - if (materialDS) { - tmplInfo.setLayouts[SetIndex.MATERIAL] = materialDS; - } - if (localDS) { - tmplInfo.setLayouts[SetIndex.LOCAL] = localDS; - } - } else { - this.getDescriptorSetLayout(device, name); // ensure set layouts have been created - insertBuiltinBindings(tmpl, tmplInfo, globalDescriptorSetLayout, 'globals'); - tmplInfo.setLayouts[SetIndex.GLOBAL] = pipeline.descriptorSetLayout; - } + this.getDescriptorSetLayout(device, name); // ensure set layouts have been created + insertBuiltinBindings(tmpl, tmplInfo, globalDescriptorSetLayout, 'globals'); + tmplInfo.setLayouts[SetIndex.GLOBAL] = pipeline.descriptorSetLayout; tmplInfo.pipelineLayout = device.createPipelineLayout(new PipelineLayoutInfo(tmplInfo.setLayouts)); } diff --git a/cocos/core/renderer/scene/shadows.ts b/cocos/core/renderer/scene/shadows.ts index ec37aedbb4..7673f65793 100644 --- a/cocos/core/renderer/scene/shadows.ts +++ b/cocos/core/renderer/scene/shadows.ts @@ -23,6 +23,7 @@ THE SOFTWARE. */ +import { DEBUG } from 'internal:constants'; import { Material } from '../../assets/material'; import { Sphere } from '../../geometry'; import { Color, Mat4, Vec3, Vec2 } from '../../math'; @@ -31,6 +32,7 @@ import { Enum } from '../../value-types'; import type { ShadowsInfo } from '../../scene-graph/scene-globals'; import { IMacroPatch } from '../core/pass'; import { Shader } from '../../gfx'; +import { assert } from '../../platform/debug'; /** * @zh 阴影贴图分辨率。 @@ -346,7 +348,11 @@ export class Shadows { this._material.initialize({ effectName: 'pipeline/planar-shadow' }); } - return this._material.passes[0].getShaderVariant(patches); + const passes = this._material.passes; + if (DEBUG) { + assert(passes.length > 0, 'passes should not be empty!'); + } + return passes.length > 0 ? passes[0].getShaderVariant(patches) : null; } /** @@ -361,7 +367,11 @@ export class Shadows { this._instancingMaterial.initialize({ effectName: 'pipeline/planar-shadow', defines: { USE_INSTANCING: true } }); } - return this._instancingMaterial.passes[0].getShaderVariant(patches); + const passes = this._instancingMaterial.passes; + if (DEBUG) { + assert(passes.length > 0, 'passes should not be empty!'); + } + return passes.length > 0 ? passes[0].getShaderVariant(patches) : null; } public initialize (shadowsInfo: ShadowsInfo) { diff --git a/cocos/core/renderer/scene/skybox.ts b/cocos/core/renderer/scene/skybox.ts index cc684368da..4b23715426 100644 --- a/cocos/core/renderer/scene/skybox.ts +++ b/cocos/core/renderer/scene/skybox.ts @@ -150,11 +150,13 @@ export class Skybox { * @zh 是否使用离线烘焙的卷积图? */ get useConvolutionMap (): boolean { + if (this.reflectionMap) { + return this.reflectionMap.isUsingOfflineMipmaps(); + } if (this.envmap) { return this.envmap.isUsingOfflineMipmaps(); - } else { - return false; } + return false; } /** @@ -200,15 +202,15 @@ export class Skybox { } } - public setSkyboxMaterial (skyboxMat: Material | null) { - if (skyboxMat) { - this._editableMaterial = new MaterialInstance({ parent: skyboxMat }); - this._editableMaterial.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE }); + get reflectionMap (): TextureCube | null { + const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; + if (isHDR) { + return this._reflectionHDR; } else { - this._editableMaterial = null; + return this._reflectionLDR; } - this._updatePipeline(); } + protected _envmapLDR: TextureCube | null = null; protected _envmapHDR: TextureCube | null = null; protected _diffuseMapLDR: TextureCube | null = null; @@ -222,6 +224,8 @@ export class Skybox { protected _useDiffuseMap = false; protected _editableMaterial: MaterialInstance | null = null; protected _activated = false; + protected _reflectionHDR: TextureCube | null = null; + protected _reflectionLDR: TextureCube | null = null; public initialize (skyboxInfo: SkyboxInfo) { this._activated = false; @@ -258,6 +262,39 @@ export class Skybox { this._updatePipeline(); } + /** + * @en Set custom skybox material + * @zh 设置自定义的天空盒材质 + * @param skyboxMat @en Skybox material @zh 天空盒材质 + */ + public setSkyboxMaterial (skyboxMat: Material | null) { + if (skyboxMat) { + this._editableMaterial = new MaterialInstance({ parent: skyboxMat }); + this._editableMaterial.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE }); + } else { + this._editableMaterial = null; + } + this._updatePipeline(); + } + + /** + * @en Set the environment reflection convolution map + * @zh 设置环境反射卷积图 + * @param reflectionHDR @en Reflection convolution map for HDR mode @zh HDR 模式下的反射卷积图 + * @param reflectionLDR @en Reflection convolution map for LDR mode @zh LDR 模式下的反射卷积图 + */ + public setReflectionMaps (reflectionHDR: TextureCube | null, reflectionLDR: TextureCube | null) { + this._reflectionHDR = reflectionHDR; + this._reflectionLDR = reflectionLDR; + this._updateGlobalBinding(); + this._updatePipeline(); + } + + public updateMaterialRenderInfo () { + this._updateGlobalBinding(); + this._updatePipeline(); + } + public activate () { const pipeline = legacyCC.director.root.pipeline; this._globalDSManager = pipeline.globalDSManager; @@ -265,10 +302,9 @@ export class Skybox { if (!this._model) { this._model = legacyCC.director.root.createModel(legacyCC.renderer.scene.Model) as Model; - // @ts-expect-error private member access - this._model._initLocalDescriptors = () => {}; - // @ts-expect-error private member access - this._model._initWorldBoundDescriptors = () => {}; + //The skybox material has added properties of 'environmentMap' that need local ubo + //this._model._initLocalDescriptors = () => {}; + //this._model._initWorldBoundDescriptors = () => {}; } let isRGBE = this._default.isRGBE; let isUseConvolutionMap = this._default.isUsingOfflineMipmaps(); @@ -333,9 +369,19 @@ export class Skybox { if (this.enabled) { if (this._editableMaterial) { - this._editableMaterial.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE }); + if (this.reflectionMap) { + this._editableMaterial.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE, USE_REFLECTION_CUBEMAP: true }); + this._editableMaterial.setProperty('environmentMap', this.envmap); + } else { + this._editableMaterial.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE, USE_REFLECTION_CUBEMAP: false }); + } } else if (skybox_material) { - skybox_material.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE }); + if (this.reflectionMap) { + skybox_material.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE, USE_REFLECTION_CUBEMAP: true }); + skybox_material.setProperty('environmentMap', this.envmap); + } else { + skybox_material.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE, USE_REFLECTION_CUBEMAP: false }); + } } } @@ -345,19 +391,26 @@ export class Skybox { } else { this._model.setSubModelMaterial(0, skybox_material!); } + this._updateSubModes(); } } protected _updateGlobalBinding () { if (this._globalDSManager) { const device = deviceManager.gfxDevice; - - const envmap = this.envmap ? this.envmap : this._default; - if (envmap) { - const texture = envmap.getGFXTexture()!; - const sampler = device.getSampler(envmap.getSamplerInfo()); + if (this.reflectionMap) { + const texture = this.reflectionMap.getGFXTexture()!; + const sampler = device.getSampler(this.reflectionMap.getSamplerInfo()); this._globalDSManager.bindSampler(UNIFORM_ENVIRONMENT_BINDING, sampler); this._globalDSManager.bindTexture(UNIFORM_ENVIRONMENT_BINDING, texture); + } else { + const envmap = this.envmap ? this.envmap : this._default; + if (envmap) { + const texture = envmap.getGFXTexture()!; + const sampler = device.getSampler(envmap.getSamplerInfo()); + this._globalDSManager.bindSampler(UNIFORM_ENVIRONMENT_BINDING, sampler); + this._globalDSManager.bindTexture(UNIFORM_ENVIRONMENT_BINDING, texture); + } } const diffuseMap = this.diffuseMap ? this.diffuseMap : this._default; @@ -371,6 +424,15 @@ export class Skybox { this._globalDSManager.update(); } } + + protected _updateSubModes () { + if (this._model) { + const subModels = this._model.subModels; + for (let i = 0; i < subModels.length; i++) { + subModels[i].update(); + } + } + } } legacyCC.Skybox = Skybox; diff --git a/cocos/core/root.jsb.ts b/cocos/core/root.jsb.ts index af8290a8ec..9e1b3c32d5 100644 --- a/cocos/core/root.jsb.ts +++ b/cocos/core/root.jsb.ts @@ -3,8 +3,8 @@ import { warnID } from './platform/debug'; import legacyCC from '../../predefine'; import { DataPoolManager } from '../3d/skeletal-animation/data-pool-manager'; import { Device, deviceManager } from './gfx'; -import { registerRebuildLayoutGraph } from './pipeline/custom/index.jsb'; import { DebugView } from './pipeline/debug-view'; +import { buildDeferredLayout, buildForwardLayout } from './pipeline/custom/effect'; declare const nr: any; declare const jsb: any; @@ -188,9 +188,15 @@ const oldSetPipeline = rootProto.setRenderPipeline; rootProto.setRenderPipeline = function (pipeline) { let ppl; if (this.usesCustomPipeline) { - ppl = oldSetPipeline.call(this, null); - registerRebuildLayoutGraph(); - + const result = oldSetPipeline.call(this, null); + const ppl = this.customPipeline; + if (this.useDeferredPipeline) { + buildDeferredLayout(ppl); + } else { + buildForwardLayout(ppl); + } + ppl.layoutGraphBuilder.compile(); + return result; } else { if (!pipeline) { // pipeline should not be created in C++, ._ctor need to be triggered diff --git a/cocos/core/root.ts b/cocos/core/root.ts index 2e82d53f87..4a5e8a59bf 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -23,6 +23,7 @@ THE SOFTWARE. */ +import { DEV, HTML5, TEST } from 'internal:constants'; import { Pool } from './memop'; import { RenderPipeline, createDefaultPipeline, DeferredPipeline } from './pipeline'; import { DebugView } from './pipeline/debug-view'; @@ -42,6 +43,7 @@ import { Batcher2D } from '../2d/renderer/batcher-2d'; import { IPipelineEvent } from './pipeline/pipeline-event'; import { settings, Settings } from './settings'; import { localDescriptorSetLayout_ResizeMaxJoints } from './pipeline/define'; +import { macro } from './platform/macro'; /** * @en Initialization information for the Root @@ -118,7 +120,7 @@ export class Root { * 启用自定义渲染管线 */ public get usesCustomPipeline (): boolean { - return this._usesCustomPipeline; + return this._usesCustomPipeline && macro.CUSTOM_PIPELINE_NAME !== ''; } /** @@ -247,7 +249,7 @@ export class Root { private _mainWindow: RenderWindow | null = null; private _curWindow: RenderWindow | null = null; private _tempWindow: RenderWindow | null = null; - private _usesCustomPipeline = false; + private _usesCustomPipeline = true; private _pipeline: PipelineRuntime | null = null; private _pipelineEvent: IPipelineEvent | null = null; private _classicPipeline: RenderPipeline | null = null; diff --git a/cocos/core/scene-graph/base-node-dev.ts b/cocos/core/scene-graph/base-node-dev.ts index 0377b84386..4de4000e25 100644 --- a/cocos/core/scene-graph/base-node-dev.ts +++ b/cocos/core/scene-graph/base-node-dev.ts @@ -149,30 +149,40 @@ export function baseNodePolyfill (BaseNode) { if (EDITOR || TEST) { BaseNode.prototype._registerIfAttached = function (register) { - const attachedObjsForEditor = legacyCC.engine.attachedObjsForEditor; - if (register) { - attachedObjsForEditor[this._id] = this; - for (let i = this._components.length - 1; i >= 0; i--) { - const comp = this._components[i]; - if (!comp) { - this._components.splice(i, 1); - console.error(`component attached to node:${this.name} is invalid for some reason`); - continue; + if (!this._id) { + console.warn(`Node(${this && this.name}}) is invalid or its data is corrupted.`); + return; + } + if (EditorExtends.Node && EditorExtends.Component) { + if (register) { + EditorExtends.Node.add(this._id, this); + + for (let i = 0; i < this._components.length; i++) { + const comp = this._components[i]; + if (!comp || !comp._id) { + console.warn(`Component attached to node:${this.name} is corrupted`); + } else { + EditorExtends.Component.add(comp._id, comp); + } } - attachedObjsForEditor[comp._id] = comp; - } - legacyCC.engine.emit('node-attach-to-scene', this); - } else { - legacyCC.engine.emit('node-detach-from-scene', this); - delete attachedObjsForEditor[this._id]; - for (const comp of this._components) { - delete attachedObjsForEditor[comp._id]; + } else { + for (let i = 0; i < this._components.length; i++) { + const comp = this._components[i]; + if (!comp || !comp._id) { + console.warn(`Component attached to node:${this.name} is corrupted`); + } else { + EditorExtends.Component.remove(comp._id); + } + } + + EditorExtends.Node.remove(this._id); } } + const children = this._children; for (let i = 0, len = children.length; i < len; ++i) { const child = children[i]; - child._registerIfAttached(register); + child._registerIfAttached!(register); } }; } diff --git a/cocos/core/scene-graph/base-node.ts b/cocos/core/scene-graph/base-node.ts index 2627deaf18..c831d7c419 100644 --- a/cocos/core/scene-graph/base-node.ts +++ b/cocos/core/scene-graph/base-node.ts @@ -29,7 +29,7 @@ import { Component } from '../components/component'; import { property } from '../data/decorators/property'; import { CCObject } from '../data/object'; import { Event } from '../../input/types'; -import { errorID, warnID, error, log, getError } from '../platform/debug'; +import { errorID, warnID, error, warn, log, getError } from '../platform/debug'; import { ISchedulable } from '../scheduler'; import IdGenerator from '../utils/id-generator'; import * as js from '../utils/js'; @@ -361,32 +361,6 @@ export class BaseNode extends CCObject implements ISchedulable { } } - protected _registerIfAttached = !EDITOR ? undefined : function _registerIfAttached (this: BaseNode, register) { - if (EditorExtends.Node && EditorExtends.Component) { - if (register) { - EditorExtends.Node.add(this._id, this); - - for (let i = 0; i < this._components.length; i++) { - const comp = this._components[i]; - EditorExtends.Component.add(comp._id, comp); - } - } else { - for (let i = 0; i < this._components.length; i++) { - const comp = this._components[i]; - EditorExtends.Component.remove(comp._id); - } - - EditorExtends.Node.remove(this._id); - } - } - - const children = this._children; - for (let i = 0, len = children.length; i < len; ++i) { - const child = children[i]; - child._registerIfAttached!(register); - } - }; - constructor (name?: string) { super(name); this._name = name !== undefined ? name : 'New Node'; @@ -1345,9 +1319,11 @@ export class BaseNode extends CCObject implements ISchedulable { const inCurrentSceneNow = newParent && newParent.isChildOf(scene); if (!inCurrentSceneBefore && inCurrentSceneNow) { // attached + // @ts-expect-error Polyfilled functions in base-node-dev.ts this._registerIfAttached!(true); } else if (inCurrentSceneBefore && !inCurrentSceneNow) { // detached + // @ts-expect-error Polyfilled functions in base-node-dev.ts this._registerIfAttached!(false); } @@ -1369,6 +1345,7 @@ export class BaseNode extends CCObject implements ISchedulable { const parent = this._parent; const destroyByParent: boolean = (!!parent) && ((parent._objFlags & Destroying) !== 0); if (!destroyByParent && EDITOR) { + // @ts-expect-error Polyfilled functions in base-node-dev.ts this._registerIfAttached!(false); } diff --git a/cocos/core/scene-graph/scene-globals.jsb.ts b/cocos/core/scene-graph/scene-globals.jsb.ts index c2177c6920..d512665a21 100644 --- a/cocos/core/scene-graph/scene-globals.jsb.ts +++ b/cocos/core/scene-graph/scene-globals.jsb.ts @@ -402,6 +402,10 @@ serializable(SkyboxInfoProto, '_enabled'); serializable(SkyboxInfoProto, '_useHDR'); type(Material)(SkyboxInfoProto, '_editableMaterial'); serializable(SkyboxInfoProto, '_editableMaterial'); +type(TextureCube)(SkyboxInfoProto, '_reflectionHDR'); +serializable(SkyboxInfoProto, '_reflectionHDR'); +type(TextureCube)(SkyboxInfoProto, '_reflectionLDR'); +serializable(SkyboxInfoProto, '_reflectionLDR'); const skyboxEnabledDescriptor = Object.getOwnPropertyDescriptor(SkyboxInfoProto, 'enabled'); tooltip('i18n:skybox.enabled')(SkyboxInfoProto, 'enabled', skyboxEnabledDescriptor); editable(SkyboxInfoProto, 'enabled', skyboxEnabledDescriptor); diff --git a/cocos/core/scene-graph/scene-globals.ts b/cocos/core/scene-graph/scene-globals.ts index cfed18f5ed..ce702c8f45 100644 --- a/cocos/core/scene-graph/scene-globals.ts +++ b/cocos/core/scene-graph/scene-globals.ts @@ -1,3 +1,4 @@ +/* eslint-disable func-names */ /* Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. http://www.cocos.com @@ -343,9 +344,6 @@ export class SkyboxInfo { // Switch UI to and from LDR/HDR textures depends on HDR state if (this._resource) { - this.envmap = this._resource.envmap; - this.diffuseMap = this._resource.diffuseMap; - if (this.envLightingType === EnvironmentLightingType.DIFFUSEMAP_WITH_REFLECTION) { if (this.diffuseMap === null) { this.envLightingType = EnvironmentLightingType.AUTOGEN_HEMISPHERE_DIFFUSE_WITH_REFLECTION; @@ -356,7 +354,10 @@ export class SkyboxInfo { } } - if (this._resource) { this._resource.useHDR = this._useHDR; } + if (this._resource) { + this._resource.useHDR = this._useHDR; + this._resource.updateMaterialRenderInfo(); + } } get useHDR () { (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR = this._useHDR; @@ -374,8 +375,10 @@ export class SkyboxInfo { const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; if (isHDR) { this._envmapHDR = val; + this._reflectionHDR = null; } else { this._envmapLDR = val; + this._reflectionLDR = null; } if (!val) { if (isHDR) { @@ -392,6 +395,7 @@ export class SkyboxInfo { if (this._resource) { this._resource.setEnvMaps(this._envmapHDR, this._envmapLDR); this._resource.setDiffuseMaps(this._diffuseMapHDR, this._diffuseMapLDR); + this._resource.setReflectionMaps(this._reflectionHDR, this._reflectionLDR); this._resource.useDiffuseMap = this.applyDiffuseMap; this._resource.envmap = val; } @@ -440,6 +444,40 @@ export class SkyboxInfo { } } + /** + * @en Convolutional map using environmental reflections + * @zh 使用环境反射卷积图 + */ + @visible(function (this : SkyboxInfo) { + if (this._resource?.reflectionMap) { + return true; + } + return false; + }) + @editable + @readOnly + @type(TextureCube) + @displayOrder(100) + set reflectionMap (val: TextureCube | null) { + const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; + if (isHDR) { + this._reflectionHDR = val; + } else { + this._reflectionLDR = val; + } + if (this._resource) { + this._resource.setReflectionMaps(this._reflectionHDR, this._reflectionLDR); + } + } + get reflectionMap () { + const isHDR = (legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR; + if (isHDR) { + return this._reflectionHDR; + } else { + return this._reflectionLDR; + } + } + /** * @en Use custom skybox material * @zh 使用自定义的天空盒材质 @@ -479,6 +517,12 @@ export class SkyboxInfo { @serializable @type(Material) protected _editableMaterial: Material | null = null; + @serializable + @type(TextureCube) + protected _reflectionHDR: TextureCube | null = null; + @serializable + @type(TextureCube) + protected _reflectionLDR: TextureCube | null = null; protected _resource: Skybox | null = null; @@ -494,6 +538,7 @@ export class SkyboxInfo { this._resource.setEnvMaps(this._envmapHDR, this._envmapLDR); this._resource.setDiffuseMaps(this._diffuseMapHDR, this._diffuseMapLDR); this._resource.setSkyboxMaterial(this._editableMaterial); + this._resource.setReflectionMaps(this._reflectionHDR, this._reflectionLDR); this._resource.activate(); // update global DS first } } @@ -806,7 +851,7 @@ export class ShadowsInfo { @tooltip('i18n:shadow.planeHeight') set planeHeight (val: number) { this._distance = val; - if (this._resource) { this._resource.distance = -val; } + if (this._resource) { this._resource.distance = val; } } get planeHeight () { return this._distance; diff --git a/cocos/core/scene-graph/scene.ts b/cocos/core/scene-graph/scene.ts index 65be90ba01..9f0466292a 100644 --- a/cocos/core/scene-graph/scene.ts +++ b/cocos/core/scene-graph/scene.ts @@ -331,6 +331,7 @@ export class Scene extends BaseNode { active = (active !== false); if (EDITOR) { // register all nodes to editor + // @ts-expect-error Polyfilled functions in base-node-dev.ts this._registerIfAttached!(active); } legacyCC.director._nodeActivator.activateNode(this, active); diff --git a/cocos/core/splash-screen.ts b/cocos/core/splash-screen.ts index 8a8bd2e27c..f35faae6c9 100644 --- a/cocos/core/splash-screen.ts +++ b/cocos/core/splash-screen.ts @@ -100,7 +100,7 @@ export class SplashScreen { }; this._curTime = 0; - if (EDITOR || (PREVIEW && !NATIVE) || !this.settings.enabled || this.settings.base64src === '' || this.settings.totalTime <= 0) { + if (EDITOR || PREVIEW || !this.settings.enabled || this.settings.base64src === '' || this.settings.totalTime <= 0) { this.settings.totalTime = 0; } else { this.device = legacyCC.director.root!.device; diff --git a/cocos/core/utils/jsb-utils.ts b/cocos/core/utils/jsb-utils.ts index 4e013dc7e6..6ca9b0840a 100644 --- a/cocos/core/utils/jsb-utils.ts +++ b/cocos/core/utils/jsb-utils.ts @@ -158,3 +158,13 @@ export function updateChildrenForDeserialize (node: Node) { // }); // node._isChildrenRedefined = true; // } +type EventType = string | number; +export function ExtraEventMethods () {} + +ExtraEventMethods.prototype.once = function once void> (type: EventType, callback: Callback, target?: any) { + return this.on(type, callback, target, true) as Callback; +}; + +ExtraEventMethods.prototype.targetOff = function targetOff (typeOrTarget: any) { + this.removeAll(typeOrTarget); +}; diff --git a/cocos/dragon-bones/ArmatureDisplay.ts b/cocos/dragon-bones/ArmatureDisplay.ts index 90c378c13e..d7db2aceb4 100644 --- a/cocos/dragon-bones/ArmatureDisplay.ts +++ b/cocos/dragon-bones/ArmatureDisplay.ts @@ -516,7 +516,6 @@ export class ArmatureDisplay extends UIRenderer { private _drawInfoList : RenderDrawInfo[] = []; private requestDrawInfo (idx: number) { if (!this._drawInfoList[idx]) { - const batch2d = director.root!.batcher2D; this._drawInfoList[idx] = new RenderDrawInfo(); } return this._drawInfoList[idx]; @@ -586,11 +585,7 @@ export class ArmatureDisplay extends UIRenderer { owner: this, }; inst = new MaterialInstance(matInfo); - if (JSB) { - inst.recompileShaders({ USE_LOCAL: false }, 0); // TODO: not supported by ui - } else { - inst.recompileShaders({ USE_LOCAL: true }, 0); // TODO: not supported by ui - } + inst.recompileShaders({ USE_LOCAL: true }, 0); // TODO: not supported by ui this._materialCache[key] = inst; inst.overridePipelineStates({ blendState: { @@ -1348,7 +1343,9 @@ export class ArmatureDisplay extends UIRenderer { } protected createRenderEntity () { - return new RenderEntity(RenderEntityType.DYNAMIC); + const renderEntity = new RenderEntity(RenderEntityType.DYNAMIC); + renderEntity.setUseLocal(true); + return renderEntity; } } diff --git a/cocos/native-binding/impl.ts b/cocos/native-binding/impl.ts index 2e76019e99..b2ac5a301c 100644 --- a/cocos/native-binding/impl.ts +++ b/cocos/native-binding/impl.ts @@ -1,9 +1,136 @@ +/* + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ +import { sys } from "../core/platform/sys"; +import { NATIVE } from 'internal:constants'; const globalJsb = globalThis.jsb ?? {}; +if( NATIVE ){ + Object.defineProperty(globalJsb, 'reflection', { + get () { + if (globalJsb.__bridge !== undefined) return globalJsb.__bridge; + if (globalThis.JavascriptJavaBridge && (sys.os === sys.OS.ANDROID || sys.os === sys.OS.OHOS)) { + globalJsb.__bridge = new globalThis.JavascriptJavaBridge(); + } else if (globalThis.JavaScriptObjCBridge && (sys.os === sys.OS.IOS || sys.os === sys.OS.OSX)) { + globalJsb.__bridge = new globalThis.JavaScriptObjCBridge(); + } else { + globalJsb.__bridge = null; + } + return globalJsb.__bridge; + }, + enumerable: true, + configurable: true, + set (value) { + globalJsb.__bridge = value; + }, + }); + Object.defineProperty(globalJsb, 'bridge', { + get () { + if (globalJsb.__ccbridge !== undefined) return globalJsb.__ccbridge; + if (window.ScriptNativeBridge && sys.os === sys.OS.ANDROID || sys.os === sys.OS.IOS || sys.os === sys.OS.OSX || sys.os === sys.OS.OHOS) { + globalJsb.__ccbridge = new ScriptNativeBridge(); + } else { + globalJsb.__ccbridge = null; + } + return globalJsb.__ccbridge; + }, + enumerable: true, + configurable: true, + set (value) { + globalJsb.__ccbridge = value; + }, + }); + const JsbBridgeWrapper = { + eventMap: new Map(), + addNativeEventListener (eventName, listener) { + if (!this.eventMap.get(eventName)) { + this.eventMap.set(eventName, []); + } + const arr = this.eventMap.get(eventName); + if (!arr.find(listener)) { + arr.push(listener); + } + }, + dispatchEventToNative (eventName, arg) { + globalJsb.bridge.sendToNative(eventName, arg); + }, + removeAllListenersForEvent (eventName) { + return this.eventMap.delete(eventName); + }, + removeNativeEventListener (eventName, listener) { + const arr = this.eventMap.get(eventName); + if (!arr) { + return false; + } + for (let i = 0, l = arr.length; i < l; i++) { + if (arr[i] === listener) { + arr.splice(i, 1); + return true; + } + } + return true; + }, + removeAllListeners () { + this.eventMap.clear(); + }, + triggerEvent (eventName, arg) { + const arr = this.eventMap.get(eventName); + if (!arr) { + console.error(`${eventName} does not exist`); + return; + } + arr.map((listener) => listener.call(null, arg)); + }, + }; + + Object.defineProperty(globalJsb, 'jsbBridgeWrapper', { + get () { + if (globalJsb.__JsbBridgeWrapper !== undefined) return globalJsb.__JsbBridgeWrapper; + + if (window.ScriptNativeBridge && sys.os === sys.OS.ANDROID || sys.os === sys.OS.IOS || sys.os === sys.OS.OSX || sys.os === sys.OS.OHOS) { + globalJsb.__JsbBridgeWrapper = JsbBridgeWrapper; + globalJsb.bridge.onNative = (methodName, arg1) => { + console.log(`Trigger event: ${methodName} with argeter: ${arg1}`); + globalJsb.__JsbBridgeWrapper.triggerEvent(methodName, arg1); + }; + } else { + globalJsb.__JsbBridgeWrapper = null; + } + return globalJsb.__JsbBridgeWrapper; + }, + enumerable: true, + configurable: true, + set (value) { + globalJsb.__JsbBridgeWrapper = value; + }, + }); +} export const native = { DownloaderHints: globalJsb.DownloaderHints, Downloader: globalJsb.Downloader, - zipUtils: globalJsb.ZipUtils, + zipUtils: globalJsb.zipUtils, fileUtils: globalJsb.fileUtils, DebugRenderer: globalJsb.DebugRenderer, + copyTextToClipboard: globalJsb.copyTextToClipboard?.bind(globalJsb), }; diff --git a/cocos/native-binding/index.ts b/cocos/native-binding/index.ts index 629c15dec2..5a19c2764e 100644 --- a/cocos/native-binding/index.ts +++ b/cocos/native-binding/index.ts @@ -36,6 +36,12 @@ export declare namespace native { */ export type DownloaderTask = { requestURL: string, storagePath: string, identifier: string }; + /** + * @en Copy text to clipboard @zh 拷贝字符串到剪切板 + * @param text + */ + export function copyTextToClipboard(text:string): void; + /** * @en DownloaderHints @zh 下载任务的配置接口 * @param countOfMaxProcessingTasks @@ -61,6 +67,7 @@ export declare namespace native { * @example * ```ts * let downloader = new native.Downloader(); // create a Downloader object by default constructor + * ``` */ constructor(); @@ -75,6 +82,7 @@ export declare namespace native { * tempFileNameSuffix: ".tmp" * }; * let downloader = new native.Downloader(hints); // create a Downloader object with DownloaderHints + * ``` */ constructor (hints: DownloaderHints); @@ -88,6 +96,7 @@ export declare namespace native { * @example * ```ts * let task = downloader.createDownloadTask('https://example.com/exampleFile.zip', native.fileUtils.getWritablePath()); + * ``` */ createDownloadTask (requestURL:string, storagePath:string, identifier?:string): DownloaderTask; @@ -101,6 +110,7 @@ export declare namespace native { * downloader.onSuccess = (task) => { * console.log('Success!'); // call when task download success * }; + * ``` */ onSuccess: (task: DownloaderTask) => void | undefined; @@ -118,6 +128,7 @@ export declare namespace native { * console.log(bytesReceived, totalBytesReceived); // download data info * console.log(totalBytesReceived / totalBytesExpected * 100).toFixed(1) + '%'); // progress prompt * }; + * ``` */ onProgress: (task: DownloaderTask, bytesReceived: number, totalBytesReceived: number, totalBytesExpected: number) => void | undefined; @@ -148,6 +159,7 @@ export declare namespace native { * @example * ```ts * let task = downloader.createDownloadFileTask('https://example.com/exampleFile.zip', native.fileUtils.getWritablePath()); + * ``` */ createDownloadFileTask (requestURL:string, storagePath:string, identifier?:string): DownloaderTask; @@ -162,6 +174,7 @@ export declare namespace native { * downloader.setOnFileTaskSuccess((task)=>{ * console.log('Success!'); // call when task download success * }); + * ``` */ setOnFileTaskSuccess (onSucceed: (task: DownloaderTask) => void): void; @@ -177,6 +190,7 @@ export declare namespace native { * console.log(bytesReceived, totalBytesReceived); // download data info * console.log(totalBytesReceived / totalBytesExpected * 100).toFixed(1) + '%'); // progress prompt * }); + * ``` */ setOnTaskProgress (onProgress: (task: DownloaderTask, bytesReceived: number, totalBytesReceived: number, totalBytesExpected: number) => void): void; @@ -191,6 +205,7 @@ export declare namespace native { * downloader.setOnTaskError((task, errorCode, errorCodeInternal, errorStr)=>{ * console.log('Error:', errorStr); * }); + * ``` */ setOnTaskError (onError: (task: DownloaderTask, errorCode: number, errorCodeInternal: number, errorStr: string) => void): void; } @@ -838,7 +853,7 @@ export declare namespace native { * @en DebugRenderer class used to output debug text on screen * @zh 用于输出屏幕调试文字的调试渲染器类 */ - export class DebugRenderer { + export class DebugRenderer { /** * @en get DebugRenderer instance * @zh 获取调试渲染器实例 @@ -854,5 +869,132 @@ export declare namespace native { * @param info @en the output text information @zh 输出的文本属性 */ addText(text:string, screenPos: Vec2, info?: DebugTextInfo): void; - } + } + + export namespace reflection { + /** + * https://docs.cocos.com/creator/manual/zh/advanced-topics/java-reflection.html + * @en call Objective-C/Java static methods + * @zh 调用 Objective-C/Java 静态方法 + * + * @param className : @en the class name of the Objective-C/Java class @zh Objective-C/Java 类的类名 + * @param methodName : @en the method name of the Objective-C/Java class @zh Objective-C/Java 类的方法名 + * @param methodSignature : @en the method signature of the Objective-C/Java class @zh Objective-C/Java 方法签名 + * @param parameters : @en the parameters of the Objective-C/Java class to translate @zh 传递至该 Objective-C/Java 方法的参数 + */ + export function callStaticMethod (methodName: string, methodSignature: string, ...parameters:any): any; + } + + /** + * @en + * The API to listen and dispatch events on Objc/JAVA without reflection, + * Function onNative can only be overriden once by time. + * https://docs.cocos.com/creator/manual/en/advanced-topics/js-java-bridge.html + * Sample: + * ``` + * native.bridge.onNative = (event, data) => { + * if (event === 'send_message') { + * console.log(data); + * } + * } + * ``` + * ``` + * // Java codes + * JsbBridge.sendToScript('send_message', 'hello world'); + * ``` + * @zh + * 不使用反射机制来调用和监听Objc/JAVA事件的接口, + * 同一时间只能重载一个onNative函数 + * https://docs.cocos.com/creator/manual/zh/advanced-topics/js-java-bridge.html + * 示例: + * ``` + * native.bridge.onNative = (event, data) => { + * if (event === 'send_message') { + * console.log(data); + * } + * } + * ``` + * ```java + * JsbBridge.sendToScript('send_message', 'hello world'); + * ``` + */ + export namespace bridge { + /** + * @en send to native with maxmimum of 2 parameters + * @zh 向原生发送消息,可接受1到2个参数。 + * @param arg0 : @en the first parameter @zh 第一个参数 + * @param arg1 : @en the second parameter @zh 第二个参数 + */ + export function sendToNative(arg0: string, arg1?: string): void; + /** + * @en + * Define your own js callback function. When native scripts run sendToScript, this callback will be called. + * usage: jsb.bridge.onNative = (arg0: String, arg1: String) => {...} + * @zh + * 定义自己的js回调函数,当原生调用 sendToScript 时,该回调函数被触发。 + * 使用 jsb.bridge.onNative = (arg0: String, arg1: String) => {...} + * + * @param arg0 : @en the first parameter @zh 第一个参数 + * @param arg1 : @en the second parameter @zh 第二个参数 + */ + export function onNative(arg0: string, arg1?: string|null): void; + } + /** + * @en + * Listener for jsbBridgeWrapper's event. + * It takes one argument as data which is transferred by jsbBridge. + * @zh + * jsbBridgeWrapper 的事件监听器, + * 它接受一个字符串参数,这个参数是通过 jsbBridge 进行传递的数据 + * @param arg: @en the data transferred by jsbBridge @zh jsbBridge 进行传递的数据 + */ + export type OnNativeEventListener = (arg: string) => void; + /** + * @en + * A high level API to call Objc/JAVA methods. + * Use bridge to implement it. If use jsbBridgeWrapper, bridge should not be used. + * https://docs.cocos.com/creator/manual/en/advanced-topics/jsb-bridge-wrapper.html + * @zh + * 高级 API,用于调用 Objc/JAVA 方法。 + * 该方法封装在bridge之上,如果使用 jsbBridgeWrapper,bridge 不应该被使用。 + * https://docs.cocos.com/creator/manual/zh/advanced-topics/jsb-bridge-wrapper.html + */ + export namespace jsbBridgeWrapper { + /** + * @en + * Register one listener to the event + * @zh + * 给事件注册一个监听 + * @param event : @en the event name @zh 事件名称 + * @param listener : @en the listener @zh 监听器 + */ + export function addNativeEventListener(event: string, listener: OnNativeEventListener); + /** + * @en + * Dispatch the event registered on Objective-C, Java etc. + * @zh + * 调用 Objective-C、Java 等的注册的事件。 + * @param event : @en the event name @zh 事件名称 + * @param data : @en the data @zh 数据 + */ + export function dispatchEventToNative(event: string, arg?: string); + /** + * @en Remove all listeners listennig to event. + * @zh 移除指定事件的所有监听。 + * @param event : @en the event name @zh 事件名称 + */ + export function removeAllListenersForEvent(event: string); + /** + * @en Remove the listener specified. + * @zh 移除指定的事件监听器 + * @param event : @en the event name @zh 事件名称 + */ + export function removeNativeEventListener(event: string, listener: OnNativeEventListener); + /** + * @en Remove all events, use it carefully! + * @zh 移除所有事件,请小心使用! + * @param event : @en the event name @zh 事件名称 + */ + export function removeAllListeners(); + } } diff --git a/cocos/particle/animator/curve-range.ts b/cocos/particle/animator/curve-range.ts index 88b93bdd89..1aad3808d7 100644 --- a/cocos/particle/animator/curve-range.ts +++ b/cocos/particle/animator/curve-range.ts @@ -316,7 +316,7 @@ export function packCurveRangeXY (samples: number, x: CurveRange, y: CurveRange, sum += value; average = sum / (j + 1); } - data[j * 4 + i] = average; + data[((h * samples) + j) * 4 + i] = average; } } } @@ -342,7 +342,7 @@ export function packCurveRangeXYZ (samples: number, x: CurveRange, y: CurveRange sum += value; average = sum / (j + 1); } - data[j * 4 + i] = average; + data[((h * samples) + j) * 4 + i] = average; } } } @@ -368,7 +368,7 @@ export function packCurveRangeXYZW (samples: number, x: CurveRange, y: CurveRang sum += value; average = sum / (j + 1); } - data[j * 4 + i] = average; + data[((h * samples) + j) * 4 + i] = average; } } } diff --git a/cocos/particle/animator/gradient-range.ts b/cocos/particle/animator/gradient-range.ts index 0770f58186..a19c8dbe05 100644 --- a/cocos/particle/animator/gradient-range.ts +++ b/cocos/particle/animator/gradient-range.ts @@ -140,7 +140,7 @@ export default class GradientRange { /** * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - public _onBeforeSerialize (props: any): any { + public _onBeforeSerialize (props: any) { return SerializableTable[this._mode]; } } @@ -174,7 +174,7 @@ function evaluateHeight (gr: GradientRange) { export function packGradientRange (samples: number, gr: GradientRange) { const height = evaluateHeight(gr); const data = new Uint8Array(samples * height * 4); - const interval = 1.0 / (samples - 1); + const interval = 1.0 / (samples); let offset = 0; for (let h = 0; h < height; h++) { diff --git a/cocos/particle/particle-system.ts b/cocos/particle/particle-system.ts index 0111cd98c1..76cc6f685b 100644 --- a/cocos/particle/particle-system.ts +++ b/cocos/particle/particle-system.ts @@ -989,6 +989,14 @@ export class ParticleSystem extends ModelRenderer { } protected onDestroy () { + this.stop(); + if (this.processor.getModel()?.scene) { + this.processor.detachFromScene(); + if (this._trailModule && this._trailModule.enable) { + this._trailModule._detachFromScene(); + } + } + legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_COMMIT, this.beforeRender, this); // this._system.remove(this); this.processor.onDestroy(); diff --git a/cocos/particle/renderer/particle-system-renderer-gpu.ts b/cocos/particle/renderer/particle-system-renderer-gpu.ts index d8dd3d19fd..9255b25cd8 100644 --- a/cocos/particle/renderer/particle-system-renderer-gpu.ts +++ b/cocos/particle/renderer/particle-system-renderer-gpu.ts @@ -457,7 +457,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas this._defines[TEXTURE_ANIMATION_MODULE_ENABLE] = enable; if (enable) { if (this._animTexture) this._animTexture.destroy(); - this._animTexture = packCurveRangeXY(_sample_num, textureModule.startFrame, textureModule.frameOverTime); + this._animTexture = packCurveRangeXY(_sample_num, textureModule.startFrame, textureModule.frameOverTime, true); const handle = pass.getHandle('texture_animation_tex0'); const binding = Pass.getBindingFromHandle(handle); pass.bindSampler(binding, this._animTexture.getGFXSampler()!); diff --git a/cocos/physics/bullet/instantiated.ts b/cocos/physics/bullet/instantiated.ts index 133297500f..b638e265d7 100644 --- a/cocos/physics/bullet/instantiated.ts +++ b/cocos/physics/bullet/instantiated.ts @@ -37,8 +37,6 @@ if (globalThis.BULLET) { bulletLibs = globalThis.BULLET; } -if (!physics.selector.runInEditor) bulletLibs = () => ({}); - interface instanceExt extends Bullet.instance { CACHE: any, BODY_CACHE_NAME: string, diff --git a/cocos/physics/framework/physics-selector.ts b/cocos/physics/framework/physics-selector.ts index 284a98d27c..763c7145dc 100644 --- a/cocos/physics/framework/physics-selector.ts +++ b/cocos/physics/framework/physics-selector.ts @@ -156,7 +156,6 @@ function switchTo (id: IPhysicsEngineId) { const world = mutableSelector.physicsWorld; world.setGravity(worldInitData.gravity); world.setAllowSleep(worldInitData.allowSleep); - world.setDefaultMaterial(worldInitData.defaultMaterial); } } @@ -187,7 +186,6 @@ export function constructDefaultWorld (data: IWorldInitData) { const world = mutableSelector.physicsWorld = createPhysicsWorld(); world.setGravity(worldInitData.gravity); world.setAllowSleep(worldInitData.allowSleep); - world.setDefaultMaterial(worldInitData.defaultMaterial); } } diff --git a/cocos/physics/framework/physics-system.ts b/cocos/physics/framework/physics-system.ts index 1bf94dd628..595519fb00 100644 --- a/cocos/physics/framework/physics-system.ts +++ b/cocos/physics/framework/physics-system.ts @@ -24,15 +24,15 @@ */ import { EDITOR } from 'internal:constants'; -import { Vec3 } from '../../core/math'; +import { Vec3, builtinResMgr, RecyclePool, game, Enum } from '../../core'; import { IRaycastOptions } from '../spec/i-physics-world'; import { director, Director } from '../../core/director'; import { System } from '../../core/components'; import { PhysicsMaterial } from './assets/physics-material'; -import { RecyclePool, game, Enum } from '../../core'; + import { Ray } from '../../core/geometry'; import { PhysicsRayResult } from './physics-ray-result'; -import { IPhysicsConfig, ICollisionMatrix } from './physics-config'; +import { IPhysicsConfig, ICollisionMatrix, IPhysicsMaterial } from './physics-config'; import { CollisionMatrix } from './collision-matrix'; import { PhysicsGroup } from './physics-enum'; import { constructDefaultWorld, IWorldInitData, selector } from './physics-selector'; @@ -210,6 +210,25 @@ export class PhysicsSystem extends System implements IWorldInitData { return this._material; } + initDefaultMaterial () : void { + if (this._material != null) { + return; + } + + this._material = builtinResMgr.get('default-physics-material'); + if (this._material != null) { + //console.log('initDefaultMaterial'); + //console.log('this._materialConfig', this._materialConfig); + this.physicsWorld.setDefaultMaterial(this._material); + this._material.on(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this); + + //set default physics material using material config + this.setDefaultMaterial(this._materialConfig); + } else { + console.error('PhysicsSystem initDefaultMaterial failed'); + } + } + /** * @en * Gets the wrappered object of the physical world through which you can access the actual underlying object. @@ -263,9 +282,9 @@ export class PhysicsSystem extends System implements IWorldInitData { private _accumulator = 0; private _sleepThreshold = 0.1; private readonly _gravity = new Vec3(0, -10, 0); - private readonly _material = new PhysicsMaterial(); + private _material!: PhysicsMaterial; //default physics material + private _materialConfig: IPhysicsMaterial = new PhysicsMaterial(); private static readonly _instance: PhysicsSystem | null = null; - private readonly raycastOptions: IRaycastOptions = { group: -1, mask: -1, @@ -277,7 +296,6 @@ export class PhysicsSystem extends System implements IWorldInitData { private constructor () { super(); - this._material.on(PhysicsMaterial.EVENT_UPDATE, this._updateMaterial, this); } postUpdate (deltaTime: number) { @@ -332,15 +350,10 @@ export class PhysicsSystem extends System implements IWorldInitData { const gravity = config ? config.gravity : settings.querySettings(Settings.Category.PHYSICS, 'gravity'); if (gravity) Vec3.copy(this._gravity, gravity); - const defaultMaterial = config ? config.defaultMaterial : settings.querySettings(Settings.Category.PHYSICS, 'defaultMaterial'); - if (defaultMaterial) { - this._material.setValues( - defaultMaterial.friction, - defaultMaterial.rollingFriction, - defaultMaterial.spinningFriction, - defaultMaterial.restitution, - ); - } + const defaultMaterialConfig = config ? config.defaultMaterial : settings.querySettings(Settings.Category.PHYSICS, 'defaultMaterial'); + //console.log('resetConfiguration'); + //console.log('defaultMaterialConfig', defaultMaterialConfig); + this._materialConfig = defaultMaterialConfig; const collisionMatrix = config ? config.collisionMatrix : settings.querySettings(Settings.Category.PHYSICS, 'collisionMatrix'); if (collisionMatrix) { @@ -360,10 +373,27 @@ export class PhysicsSystem extends System implements IWorldInitData { if (this.physicsWorld) { this.physicsWorld.setGravity(this._gravity); this.physicsWorld.setAllowSleep(this._allowSleep); - this.physicsWorld.setDefaultMaterial(this._material); } } + /** + * @en + * Set the default physics material to given value. + * @zh + * 设置默认物理材质到指定的值。 + */ + setDefaultMaterial (materialConfig : IPhysicsMaterial):void { + if (!this._material) return; + if (!materialConfig) return; + + this._material.setValues( + materialConfig.friction, + materialConfig.rollingFriction, + materialConfig.spinningFriction, + materialConfig.restitution, + ); + } + /** * @en * Reset the accumulator of time to given value. @@ -468,6 +498,12 @@ export class PhysicsSystem extends System implements IWorldInitData { constructDefaultWorld(sys); (PhysicsSystem._instance as unknown as PhysicsSystem) = sys; director.registerSystem(PhysicsSystem.ID, sys, sys.priority); + + if (!builtinResMgr.get('default-physics-material')) { + game.onPostProjectInitDelegate.add(sys.initDefaultMaterial.bind(sys)); + } else { + sys.initDefaultMaterial(); + } } } } diff --git a/cocos/physics/physx/shapes/physx-terrain-shape.ts b/cocos/physics/physx/shapes/physx-terrain-shape.ts index 3a8fb9d4b4..aac0767c6a 100644 --- a/cocos/physics/physx/shapes/physx-terrain-shape.ts +++ b/cocos/physics/physx/shapes/physx-terrain-shape.ts @@ -32,7 +32,7 @@ import { PhysXInstance } from '../physx-instance'; import { EPhysXShapeType, PhysXShape } from './physx-shape'; export class PhysXTerrainShape extends PhysXShape implements ITerrainShape { - static heightScale = 1 / 5000; + static heightScale = 1 / 512; constructor () { super(EPhysXShapeType.TERRAIN); diff --git a/cocos/spine/skeleton.ts b/cocos/spine/skeleton.ts index 964e64a7ea..55fee777f0 100644 --- a/cocos/spine/skeleton.ts +++ b/cocos/spine/skeleton.ts @@ -624,7 +624,6 @@ export class Skeleton extends UIRenderer { private requestDrawInfo (idx: number) { if (!this._drawInfoList[idx]) { - const batch2d = director.root!.batcher2D; this._drawInfoList[idx] = new RenderDrawInfo(); } return this._drawInfoList[idx]; @@ -1378,11 +1377,7 @@ export class Skeleton extends UIRenderer { }], }, }); - if (JSB) { - inst.recompileShaders({ TWO_COLORED: useTwoColor, USE_LOCAL: false }); - } else { - inst.recompileShaders({ TWO_COLORED: useTwoColor, USE_LOCAL: true }); - } + inst.recompileShaders({ TWO_COLORED: useTwoColor, USE_LOCAL: true }); return inst; } @@ -1744,7 +1739,9 @@ export class Skeleton extends UIRenderer { } protected createRenderEntity () { - return new RenderEntity(RenderEntityType.DYNAMIC); + const renderEntity = new RenderEntity(RenderEntityType.DYNAMIC); + renderEntity.setUseLocal(true); + return renderEntity; } } diff --git a/cocos/tiledmap/assembler/simple.ts b/cocos/tiledmap/assembler/simple.ts index 05ae0ad5f3..94f97473cd 100644 --- a/cocos/tiledmap/assembler/simple.ts +++ b/cocos/tiledmap/assembler/simple.ts @@ -408,7 +408,7 @@ function traverseGrids (leftDown: { col: number, row: number }, rightTop: { col: const nodes = comp.requestSubNodesData(); const celData = comp.getNodesByRowCol(row, col); if (celData && celData.count > 0) { - (nodes as any).subNodes = comp.getNodesByRowCol(row, col)!.list as any; + (nodes as any).subNodes = celData.list as any; } } diff --git a/cocos/tiledmap/tiled-layer.ts b/cocos/tiledmap/tiled-layer.ts index df74c36afa..9640a93b51 100644 --- a/cocos/tiledmap/tiled-layer.ts +++ b/cocos/tiledmap/tiled-layer.ts @@ -226,7 +226,6 @@ export class TiledLayer extends UIRenderer { dataComp = node.addComponent(TiledUserNodeData); node.parent = this.node; - // node._renderFlag |= RenderFlow.FLAG_BREAK_FLOW; this._userNodeMap[node.uuid] = dataComp; dataComp._row = -1; @@ -1380,12 +1379,28 @@ export class TiledLayer extends UIRenderer { } public requestTiledRenderData () { + const arr = this._tiledDataArray as any[]; + while (arr.length > 0 && arr[arr.length - 1].subNodes && arr[arr.length - 1].subNodes.length === 0) { + arr.pop(); + } + if (arr.length > 0) { + const last = arr[arr.length - 1]; + if (last.renderData && last.renderData.vertexCount === 0) { + return last as TiledRenderData; + } + } const comb = { renderData: null, texture: null }; this._tiledDataArray.push(comb); return (comb as TiledRenderData); } public requestSubNodesData () { + const arr = this._tiledDataArray as any[]; + if (arr.length > 0) { + if (arr[arr.length - 1].subNodes && arr[arr.length - 1].subNodes.length === 0) { + return arr[arr.length - 1] as TiledSubNodeData; + } + } const renderData: (TiledUserNodeData | null)[] = []; const comb = { subNodes: renderData }; this._tiledDataArray.push(comb); @@ -1442,7 +1457,7 @@ export class TiledLayer extends UIRenderer { } protected createRenderEntity () { - return new RenderEntity(RenderEntityType.DYNAMIC); + return new RenderEntity(RenderEntityType.CROSSED); } private fillIndicesBuffer (renderData: RenderData, drawInfo: RenderDrawInfo) { @@ -1467,31 +1482,42 @@ export class TiledLayer extends UIRenderer { } public prepareDrawData () { + this._drawInfoList.length = 0; const entity = this.renderEntity; entity.clearDynamicRenderDrawInfos(); - for (let i = 0; i < this._tiledDataArray.length; i++) { - this._tiledDataArrayIdx = i; - const m = this._tiledDataArray[i]; - //const batch2d = director.root!.batcher2D; + const tiledDataArray = this._tiledDataArray; + let idx = 0; + tiledDataArray.forEach((m) => { if ((m as TiledSubNodeData).subNodes) { // 提前处理 User Nodes - // (m as TiledSubNodeData).subNodes.forEach((c) => { - // if (c) batch2d.walk(c.node); - // }); + (m as TiledSubNodeData).subNodes.forEach((c) => { + if (c) { + if (!this._drawInfoList[idx]) { + this._drawInfoList[idx] = new RenderDrawInfo(); + } + const drawInfo = this._drawInfoList[idx]; + drawInfo.setDrawInfoType(RenderDrawInfoType.SUB_NODE); + drawInfo.setSubNode(c.node); + entity.setDynamicRenderDrawInfo(drawInfo, idx); + idx++; + } + }); } else { const td = m as TiledRenderData; if (td.texture) { - const drawInfo = this.requestDrawInfo(i); + if (!this._drawInfoList[idx]) { + this._drawInfoList[idx] = new RenderDrawInfo(); + } + const drawInfo = this._drawInfoList[idx]; td.renderData!.fillDrawInfoAttributes(drawInfo); drawInfo.setTexture(td.texture.getGFXTexture()); - drawInfo.setTextureHash(td.texture.getHash()); drawInfo.setSampler(td.texture.getGFXSampler()); - drawInfo.setBlendHash(this.blendHash); drawInfo.setMaterial(this.getRenderMaterial(0)!); this.fillIndicesBuffer(td.renderData!, drawInfo); - entity.setDynamicRenderDrawInfo(drawInfo, i); + entity.setDynamicRenderDrawInfo(drawInfo, idx); + idx++; } } - } + }); } } diff --git a/editor/assets/chunks/builtin/functionalities/fog.chunk.meta b/editor/assets/chunks/builtin/functionalities/fog.chunk.meta index 58cb06b250..760dfe7d31 100644 --- a/editor/assets/chunks/builtin/functionalities/fog.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/fog.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "02a04bf3-4c27-4596-81fd-dfc35224f1d1", diff --git a/editor/assets/chunks/builtin/functionalities/morph-animation.chunk.meta b/editor/assets/chunks/builtin/functionalities/morph-animation.chunk.meta index 354b4ae4f8..3bc483a242 100644 --- a/editor/assets/chunks/builtin/functionalities/morph-animation.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/morph-animation.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "3adaa06a-e674-487c-9d49-42bc398c255b", diff --git a/editor/assets/chunks/builtin/functionalities/shadow-map.chunk b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk index 174a86c27e..137f3e6742 100644 --- a/editor/assets/chunks/builtin/functionalities/shadow-map.chunk +++ b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk @@ -1,5 +1,8 @@ // used for replacing cc-shadow-map-base.chunk #include +#if CC_SUPPORT_CASCADED_SHADOW_MAP + #include +#endif #include #include @@ -39,6 +42,18 @@ float CCGetLinearDepth(vec3 worldPos) { CC_HANDLE_NDC_SAMPLE_FLIP(shadowNDCPos.xy); return true; } + + vec4 ApplyShadowDepthBias_FaceNormal(vec4 shadowPos, vec3 worldNormal, float normalBias, vec3 matViewDir0, vec3 matViewDir1, vec3 matViewDir2, vec2 projScaleXY) + { + vec4 newShadowPos = shadowPos; + if (normalBias > EPSILON_LOWP) + { + vec3 viewNormal = vec3(dot(matViewDir0, worldNormal), dot(matViewDir1, worldNormal), dot(matViewDir2, worldNormal)); + if (viewNormal.z < 0.1) + newShadowPos.xy += viewNormal.xy * projScaleXY * normalBias * clamp(viewNormal.z, 0.001, 0.1); + } + return newShadowPos; + } vec4 ApplyShadowDepthBias_FaceNormal(vec4 shadowPos, vec3 worldNormal, float normalBias, mat4 matLightView, vec2 projScaleXY) { @@ -211,50 +226,62 @@ float CCGetLinearDepth(vec3 worldPos) { return mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w); } - - int CCGetCSMLevel(out vec4 csmPos, out vec4 shadowProjDepthInfo, out vec4 shadowProjInfo, out vec4 matShadowViewLine0, out vec4 matShadowViewLine1, out vec4 matShadowViewLine2, out vec4 matShadowViewLine3, vec3 worldPos) { - int layer = -1; - for (int i = 0; i < NUMCASCADES; i++) { - vec4 shadowPos = cc_matCSMViewProj[i] * vec4(worldPos.xyz, 1.0); - vec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5; - if (clipPos.x >= (0.0 + cc_csmInfo.y) && clipPos.x <= (1.0 - cc_csmInfo.y) && - clipPos.y >= (0.0 + cc_csmInfo.y) && clipPos.y <= (1.0 - cc_csmInfo.y) && - clipPos.z >= 0.0 && clipPos.z <= 1.0 && layer < 0) { - csmPos = cc_matCSMViewProjAtlas[i] * vec4(worldPos.xyz, 1.0); - shadowProjDepthInfo = cc_csmProjDepthInfo[i]; - shadowProjInfo = cc_csmProjInfo[i]; - matShadowViewLine0 = cc_matCSMView[i][0]; - matShadowViewLine1 = cc_matCSMView[i][1]; - matShadowViewLine2 = cc_matCSMView[i][2]; - matShadowViewLine3 = cc_matCSMView[i][3]; - layer = i; + #if CC_SUPPORT_CASCADED_SHADOW_MAP + int CCGetCSMLevel(out vec4 csmPos, out vec4 shadowProjDepthInfo, out vec4 shadowProjInfo, out vec3 shadowViewDir0, out vec3 shadowViewDir1, out vec3 shadowViewDir2, vec3 worldPos) { + int layer = -1; + highp float layerThreshold = cc_csmViewDir0[0].w; + for (int i = 0; i < NUMCASCADES; i++) { + vec4 shadowPos = cc_matCSMViewProj[i] * vec4(worldPos.xyz, 1.0); + vec3 clipPos = shadowPos.xyz / shadowPos.w * 0.5 + 0.5; + if (clipPos.x >= (0.0 + layerThreshold) && clipPos.x <= (1.0 - layerThreshold) && + clipPos.y >= (0.0 + layerThreshold) && clipPos.y <= (1.0 - layerThreshold) && + clipPos.z >= 0.0 && clipPos.z <= 1.0 && layer < 0) { + csmPos = cc_matCSMViewProj[i] * vec4(worldPos.xyz, 1.0); + csmPos.xy = csmPos.xy * cc_csmAtlas[i].xy + cc_csmAtlas[i].zw; + shadowProjDepthInfo = cc_csmProjDepthInfo[i]; + shadowProjInfo = cc_csmProjInfo[i]; + shadowViewDir0 = cc_csmViewDir0[i].xyz; + shadowViewDir1 = cc_csmViewDir1[i].xyz; + shadowViewDir2 = cc_csmViewDir2[i].xyz; + layer = i; + } } + return layer; } - return layer; - } - float CCCSMFactorBase(vec3 worldPos, vec3 N, vec2 shadowBias) - { - vec4 csmPos = vec4(1.0); - vec4 shadowProjDepthInfo, shadowProjInfo; - mat4 matLightView; - int level = CCGetCSMLevel(csmPos, shadowProjDepthInfo, shadowProjInfo, matLightView[0], matLightView[1], matLightView[2], matLightView[3], worldPos); - if (level < 0) { return 1.0; } - float realtimeShadow = 1.0; + float CCCSMFactorBase(vec3 worldPos, vec3 N, vec2 shadowBias) + { + vec4 csmPos = vec4(1.0); + vec4 shadowProjDepthInfo, shadowProjInfo; + vec3 shadowViewDir0, shadowViewDir1, shadowViewDir2; + int level = CCGetCSMLevel(csmPos, shadowProjDepthInfo, shadowProjInfo, shadowViewDir0, shadowViewDir1, shadowViewDir2, worldPos); + if (level < 0) { return 1.0; } + float realtimeShadow = 1.0; - vec4 pos = ApplyShadowDepthBias_FaceNormal(csmPos, N, shadowBias.y, matLightView, shadowProjInfo.xy); - pos = ApplyShadowDepthBias_Orthographic(pos, shadowBias.x, shadowProjDepthInfo.x, shadowProjDepthInfo.y); - - float pcf = cc_shadowWHPBInfo.z; - if (pcf > 2.9) { - realtimeShadow = CCGetDirLightShadowFactorSoft5X(pos); - } else if (pcf > 1.9) { - realtimeShadow = CCGetDirLightShadowFactorSoft3X(pos); - } else if (pcf > 0.9) { - realtimeShadow = CCGetDirLightShadowFactorSoft(pos); - }else { - realtimeShadow = CCGetDirLightShadowFactorHard(pos); + vec4 pos = ApplyShadowDepthBias_FaceNormal(csmPos, N, shadowBias.y, shadowViewDir0, shadowViewDir1, shadowViewDir2, shadowProjInfo.xy); + pos = ApplyShadowDepthBias_Orthographic(pos, shadowBias.x, shadowProjDepthInfo.x, shadowProjDepthInfo.y); + + float pcf = cc_shadowWHPBInfo.z; + if (pcf > 2.9) { + realtimeShadow = CCGetDirLightShadowFactorSoft5X(pos); + } else if (pcf > 1.9) { + realtimeShadow = CCGetDirLightShadowFactorSoft3X(pos); + } else if (pcf > 0.9) { + realtimeShadow = CCGetDirLightShadowFactorSoft(pos); + }else { + realtimeShadow = CCGetDirLightShadowFactorHard(pos); + } + return mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w); } - return mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w); - } + #else + int CCGetCSMLevel(out vec4 csmPos, out vec4 shadowProjDepthInfo, out vec4 shadowProjInfo, out vec3 shadowViewDir0, out vec3 shadowViewDir1, out vec3 shadowViewDir2, vec3 worldPos) { + return -1; + } + + float CCCSMFactorBase(vec3 worldPos, vec3 N, vec2 shadowBias) { + vec4 shadowPos = cc_matLightViewProj * vec4(worldPos, 1.0); + return CCShadowFactorBase(shadowPos, N, shadowBias); + } + #endif + #endif diff --git a/editor/assets/chunks/builtin/functionalities/shadow-map.chunk.meta b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk.meta index b10c803341..f10cec021f 100644 --- a/editor/assets/chunks/builtin/functionalities/shadow-map.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "d4c26490-0a2d-4b6a-9a52-55b5741f18a4", diff --git a/editor/assets/chunks/builtin/functionalities/skinning-animation-dqs.chunk.meta b/editor/assets/chunks/builtin/functionalities/skinning-animation-dqs.chunk.meta index 4daae2933a..b2af9f5561 100644 --- a/editor/assets/chunks/builtin/functionalities/skinning-animation-dqs.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/skinning-animation-dqs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "80908463-4566-4fdf-9744-775605cd7ab7", diff --git a/editor/assets/chunks/builtin/functionalities/skinning-animation-lbs.chunk.meta b/editor/assets/chunks/builtin/functionalities/skinning-animation-lbs.chunk.meta index fb212ed6dd..f0740c7d8e 100644 --- a/editor/assets/chunks/builtin/functionalities/skinning-animation-lbs.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/skinning-animation-lbs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "258a17ce-6c50-4e8a-92aa-8ecec1a6af24", diff --git a/editor/assets/chunks/builtin/functionalities/world-transform.chunk.meta b/editor/assets/chunks/builtin/functionalities/world-transform.chunk.meta index 6d7ea1fe6b..88f1d9961d 100644 --- a/editor/assets/chunks/builtin/functionalities/world-transform.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/world-transform.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "c2885f54-4ff2-4284-8bbc-b77bc71965b4", diff --git a/editor/assets/chunks/builtin/internal/alpha-test.chunk.meta b/editor/assets/chunks/builtin/internal/alpha-test.chunk.meta index 575c886b84..bac2e2d260 100644 --- a/editor/assets/chunks/builtin/internal/alpha-test.chunk.meta +++ b/editor/assets/chunks/builtin/internal/alpha-test.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "2c3da5b6-0202-470a-a915-59f1e2968853", diff --git a/editor/assets/chunks/builtin/internal/embedded-alpha.chunk.meta b/editor/assets/chunks/builtin/internal/embedded-alpha.chunk.meta index 10ddc4f29f..fb3ba3d851 100644 --- a/editor/assets/chunks/builtin/internal/embedded-alpha.chunk.meta +++ b/editor/assets/chunks/builtin/internal/embedded-alpha.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "ef4fb7de-9b39-4eeb-9ae8-d292ff94a452", diff --git a/editor/assets/chunks/builtin/internal/particle-common.chunk.meta b/editor/assets/chunks/builtin/internal/particle-common.chunk.meta index d1117e8fa3..452f0a8667 100644 --- a/editor/assets/chunks/builtin/internal/particle-common.chunk.meta +++ b/editor/assets/chunks/builtin/internal/particle-common.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "7a49db3a-930e-4ffc-8659-a82141dabebb", diff --git a/editor/assets/chunks/builtin/internal/particle-trail.chunk.meta b/editor/assets/chunks/builtin/internal/particle-trail.chunk.meta index c299ebfbca..90b911d7c9 100644 --- a/editor/assets/chunks/builtin/internal/particle-trail.chunk.meta +++ b/editor/assets/chunks/builtin/internal/particle-trail.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "df7d02d8-559a-4c02-9aac-3732cfc83d7a", diff --git a/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk.meta b/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk.meta index 814eb46b72..07624b6cb8 100644 --- a/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk.meta +++ b/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "b4b00c01-eca8-4ae4-a04d-e00bbeb6d0e0", diff --git a/editor/assets/chunks/builtin/internal/particle-vs-legacy.chunk.meta b/editor/assets/chunks/builtin/internal/particle-vs-legacy.chunk.meta index 3654188849..f2fc3d2483 100644 --- a/editor/assets/chunks/builtin/internal/particle-vs-legacy.chunk.meta +++ b/editor/assets/chunks/builtin/internal/particle-vs-legacy.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "6e1b48cb-69c8-448c-8055-69ab9793fbab", diff --git a/editor/assets/chunks/builtin/internal/sprite-common.chunk.meta b/editor/assets/chunks/builtin/internal/sprite-common.chunk.meta index 1b9639a9a5..19ab4b6952 100644 --- a/editor/assets/chunks/builtin/internal/sprite-common.chunk.meta +++ b/editor/assets/chunks/builtin/internal/sprite-common.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "35822e78-bb35-405f-87bd-d42af6ac9ede", diff --git a/editor/assets/chunks/builtin/internal/sprite-texture.chunk.meta b/editor/assets/chunks/builtin/internal/sprite-texture.chunk.meta index b99baf3b52..79d2474698 100644 --- a/editor/assets/chunks/builtin/internal/sprite-texture.chunk.meta +++ b/editor/assets/chunks/builtin/internal/sprite-texture.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "4b48672e-e044-4035-9029-13afb50c1aee", diff --git a/editor/assets/chunks/builtin/uniforms/cc-csm.chunk b/editor/assets/chunks/builtin/uniforms/cc-csm.chunk new file mode 100644 index 0000000000..809eb9691d --- /dev/null +++ b/editor/assets/chunks/builtin/uniforms/cc-csm.chunk @@ -0,0 +1,14 @@ +// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. + +#pragma define NUMCASCADES 4 +#pragma builtin(global) +layout(set = 0, binding = 3) uniform CCCSM { + highp vec4 cc_csmViewDir0[NUMCASCADES]; //[0].w->layer blank threshold + highp vec4 cc_csmViewDir1[NUMCASCADES]; + highp vec4 cc_csmViewDir2[NUMCASCADES]; + highp vec4 cc_csmAtlas[NUMCASCADES]; + highp mat4 cc_matCSMViewProj[NUMCASCADES]; + highp vec4 cc_csmProjDepthInfo[NUMCASCADES]; + highp vec4 cc_csmProjInfo[NUMCASCADES]; + highp vec4 cc_csmSplitsInfo; // x-> level_1 far, y-> level_2 far, z-> level_3 far, w-> level_4 far +}; diff --git a/editor/assets/chunks/builtin/uniforms/cc-csm.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-csm.chunk.meta new file mode 100644 index 0000000000..6511219a49 --- /dev/null +++ b/editor/assets/chunks/builtin/uniforms/cc-csm.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.6", + "importer": "effect-header", + "imported": true, + "uuid": "c3e3500f-370c-4da1-92f9-d0d9fd806bd8", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk b/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk index 482aa2034e..4b678a409c 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk @@ -3,4 +3,4 @@ #pragma define-meta CC_USE_DIFFUSEMAP range([0, 2]) #pragma builtin(global) -layout(set = 0, binding = 6) uniform samplerCube cc_diffuseMap; \ No newline at end of file +layout(set = 0, binding = 7) uniform samplerCube cc_diffuseMap; diff --git a/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk.meta index 785b080d44..8a554d4208 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "17e8e047-4c5e-412c-85c8-a76a98742f2a", diff --git a/editor/assets/chunks/builtin/uniforms/cc-environment.chunk b/editor/assets/chunks/builtin/uniforms/cc-environment.chunk index 6e4bd55ce0..6bc653525d 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-environment.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-environment.chunk @@ -5,4 +5,4 @@ #pragma define-meta CC_USE_IBL range([0, 2]) #pragma builtin(global) -layout(set = 0, binding = 4) uniform samplerCube cc_environment; +layout(set = 0, binding = 5) uniform samplerCube cc_environment; diff --git a/editor/assets/chunks/builtin/uniforms/cc-environment.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-environment.chunk.meta index af73e27c3c..9d0d0fad91 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-environment.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-environment.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "cd94308c-6959-4671-9dcb-6c58342273e2", diff --git a/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk.meta index c20ac85e4e..53dd5b0098 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "5e0f5e6e-5008-497f-b223-4e5f1801d8fd", diff --git a/editor/assets/chunks/builtin/uniforms/cc-global.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-global.chunk.meta index 78b4e93f32..73ede74a6f 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-global.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-global.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "1ea907a3-a36e-432a-ae38-af712c77aaad", diff --git a/editor/assets/chunks/builtin/uniforms/cc-light-map.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-light-map.chunk.meta index 42d24030dc..4f9e7f7efc 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-light-map.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-light-map.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "fa1c0cd1-03c6-45dd-8294-bf7a1e21aad4", diff --git a/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk.meta index 50f2d38f86..853ddc200a 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "21b24bc9-a158-488e-b27c-b98a461fb438", diff --git a/editor/assets/chunks/builtin/uniforms/cc-local.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-local.chunk.meta index b30beab87f..0686dc98f4 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-local.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-local.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "e835c2d5-a377-4197-bdb8-382037573494", diff --git a/editor/assets/chunks/builtin/uniforms/cc-morph.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-morph.chunk.meta index 003376ce0a..5ea9bba5c4 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-morph.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-morph.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "94d19070-32c6-4900-a288-2258fda37f29", diff --git a/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk b/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk index dc82842bec..b1ec0587ed 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk @@ -1,5 +1,5 @@ #pragma builtin(global) -layout(set = 0, binding = 3) uniform highp sampler2D cc_shadowMap; +layout(set = 0, binding = 4) uniform highp sampler2D cc_shadowMap; #pragma builtin(global) -layout(set = 0, binding = 5) uniform highp sampler2D cc_spotShadowMap; +layout(set = 0, binding = 6) uniform highp sampler2D cc_spotShadowMap; diff --git a/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk.meta index b8d0fb62b5..e20bf64968 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "e8411010-e411-43ab-8f2e-4f4865dca4cf", diff --git a/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk b/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk index 8a5f24f3ff..c26340e9e1 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk @@ -3,7 +3,6 @@ #pragma define NUMCASCADES 4 #pragma builtin(global) layout(set = 0, binding = 2) uniform CCShadow { - highp mat4 cc_matLightPlaneProj; highp mat4 cc_matLightView; highp mat4 cc_matLightViewProj; highp vec4 cc_shadowInvProjDepthInfo; // x -> cc_matLightInvProj[10]([2][2]); y -> cc_matLightInvProj[14]([2][3]); z -> cc_matLightInvProj[11]([3][2]); w -> cc_matLightInvProj[15]([3][3]); @@ -14,11 +13,4 @@ layout(set = 0, binding = 2) uniform CCShadow { mediump vec4 cc_shadowLPNNInfo; // x -> lightType(L); y -> isPacking(P); z -> normalBias(N); w -> CSM level(N); lowp vec4 cc_shadowColor; mediump vec4 cc_planarNDInfo; // xyz -> normalized plane (N); w -> plane (D); - highp mat4 cc_matCSMView[NUMCASCADES]; - highp mat4 cc_matCSMViewProj[NUMCASCADES]; - highp mat4 cc_matCSMViewProjAtlas[NUMCASCADES]; - highp vec4 cc_csmProjDepthInfo[NUMCASCADES]; - highp vec4 cc_csmProjInfo[NUMCASCADES]; - highp vec4 cc_csmSplitsInfo; // x-> level_1 far, y-> level_2 far, z-> level_3 far, w-> level_4 far - highp vec4 cc_csmInfo; // y-> radius }; diff --git a/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk.meta index a148f8d4bd..295624e6ff 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "69f8ecd8-cdc9-4655-a6ec-d39dacdffc2f", diff --git a/editor/assets/chunks/builtin/uniforms/cc-skinning.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-skinning.chunk.meta index a23d9b8235..d657b6681b 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-skinning.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-skinning.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "99488fd6-220b-4d13-9a41-8b9439cd3944", diff --git a/editor/assets/chunks/builtin/uniforms/cc-world-bound.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-world-bound.chunk.meta index f60c1335b6..cdb49e8e32 100644 --- a/editor/assets/chunks/builtin/uniforms/cc-world-bound.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-world-bound.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "669458fe-c428-40cd-8575-51607aa8edbc", diff --git a/editor/assets/chunks/common/color/aces.chunk.meta b/editor/assets/chunks/common/color/aces.chunk.meta index ed401b322f..faba7c9f8b 100644 --- a/editor/assets/chunks/common/color/aces.chunk.meta +++ b/editor/assets/chunks/common/color/aces.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "7efbe295-0202-4979-8cda-6cfe35e086cf", diff --git a/editor/assets/chunks/common/color/gamma.chunk.meta b/editor/assets/chunks/common/color/gamma.chunk.meta index 00ea376a9e..09cb52dbeb 100644 --- a/editor/assets/chunks/common/color/gamma.chunk.meta +++ b/editor/assets/chunks/common/color/gamma.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "bb213412-2e68-43b3-9de5-73ca332acace", diff --git a/editor/assets/chunks/common/common-define.chunk.meta b/editor/assets/chunks/common/common-define.chunk.meta index bcaeda1c0f..bc5f8672cc 100644 --- a/editor/assets/chunks/common/common-define.chunk.meta +++ b/editor/assets/chunks/common/common-define.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "9d86a3e4-ec06-4e51-ba68-45f2b7739fbb", diff --git a/editor/assets/chunks/common/data/packing.chunk.meta b/editor/assets/chunks/common/data/packing.chunk.meta index 5e7417f776..8c0ac60eb4 100644 --- a/editor/assets/chunks/common/data/packing.chunk.meta +++ b/editor/assets/chunks/common/data/packing.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "73866dd2-eaf5-40af-a061-1b9d38782204", diff --git a/editor/assets/chunks/common/data/unpack.chunk.meta b/editor/assets/chunks/common/data/unpack.chunk.meta index d22d3257f1..bcb9a88365 100644 --- a/editor/assets/chunks/common/data/unpack.chunk.meta +++ b/editor/assets/chunks/common/data/unpack.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "e3e5d086-acc9-4dd8-98e8-24ac02f547d5", diff --git a/editor/assets/chunks/common/debug/debug-view-define.chunk.meta b/editor/assets/chunks/common/debug/debug-view-define.chunk.meta index 81ea67f60a..ca074c5fbf 100644 --- a/editor/assets/chunks/common/debug/debug-view-define.chunk.meta +++ b/editor/assets/chunks/common/debug/debug-view-define.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "9c973ee8-952a-4ee3-a617-ba6397db6bac", diff --git a/editor/assets/chunks/common/effect/fog.chunk.meta b/editor/assets/chunks/common/effect/fog.chunk.meta index 9291399821..2e3a0ef339 100644 --- a/editor/assets/chunks/common/effect/fog.chunk.meta +++ b/editor/assets/chunks/common/effect/fog.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "399f5890-dde1-40de-9751-a7aa91a56b93", diff --git a/editor/assets/chunks/common/lighting/attenuation.chunk.meta b/editor/assets/chunks/common/lighting/attenuation.chunk.meta index 75f253af0f..6e0822a887 100644 --- a/editor/assets/chunks/common/lighting/attenuation.chunk.meta +++ b/editor/assets/chunks/common/lighting/attenuation.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "077cca29-6f66-4aad-a3a7-4f0a7ecd523f", diff --git a/editor/assets/chunks/common/lighting/brdf.chunk.meta b/editor/assets/chunks/common/lighting/brdf.chunk.meta index 14002851f1..27adcff968 100644 --- a/editor/assets/chunks/common/lighting/brdf.chunk.meta +++ b/editor/assets/chunks/common/lighting/brdf.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "3a85eafd-0fd0-468f-8a2e-0c81493230c7", diff --git a/editor/assets/chunks/common/lighting/functions.chunk.meta b/editor/assets/chunks/common/lighting/functions.chunk.meta index 650ec89532..0007383998 100644 --- a/editor/assets/chunks/common/lighting/functions.chunk.meta +++ b/editor/assets/chunks/common/lighting/functions.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "d360c347-a546-4967-bdd3-30cae323f123", diff --git a/editor/assets/chunks/common/lighting/light-map.chunk.meta b/editor/assets/chunks/common/lighting/light-map.chunk.meta index 6ba97ff7df..c408be98e3 100644 --- a/editor/assets/chunks/common/lighting/light-map.chunk.meta +++ b/editor/assets/chunks/common/lighting/light-map.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "00e591cd-469d-4611-adb9-a5ca965a0552", diff --git a/editor/assets/chunks/common/lighting/rect-area-light.chunk.meta b/editor/assets/chunks/common/lighting/rect-area-light.chunk.meta index 2960457ec7..414e0f636a 100644 --- a/editor/assets/chunks/common/lighting/rect-area-light.chunk.meta +++ b/editor/assets/chunks/common/lighting/rect-area-light.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "a24fb7a1-f7a5-430c-a8b2-e4c516131086", diff --git a/editor/assets/chunks/common/math/coordinates.chunk.meta b/editor/assets/chunks/common/math/coordinates.chunk.meta index 673d9ae7b7..356a11304d 100644 --- a/editor/assets/chunks/common/math/coordinates.chunk.meta +++ b/editor/assets/chunks/common/math/coordinates.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "e9d8b3bb-03e4-46b2-be29-ea58fac18c18", diff --git a/editor/assets/chunks/common/math/number.chunk.meta b/editor/assets/chunks/common/math/number.chunk.meta index 000a1f2345..8327256642 100644 --- a/editor/assets/chunks/common/math/number.chunk.meta +++ b/editor/assets/chunks/common/math/number.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "9f84c121-c61b-499f-b400-81a5448d6078", diff --git a/editor/assets/chunks/common/math/octahedron-transform.chunk.meta b/editor/assets/chunks/common/math/octahedron-transform.chunk.meta index db4b5cf3dc..e990809fa2 100644 --- a/editor/assets/chunks/common/math/octahedron-transform.chunk.meta +++ b/editor/assets/chunks/common/math/octahedron-transform.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "41f91fc1-5aec-45dd-91ca-39ab964f8054", diff --git a/editor/assets/chunks/common/math/transform.chunk.meta b/editor/assets/chunks/common/math/transform.chunk.meta index d3270470d9..1bd281d564 100644 --- a/editor/assets/chunks/common/math/transform.chunk.meta +++ b/editor/assets/chunks/common/math/transform.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "0de81d5f-2a3e-467e-bcf5-84f7828edab6", diff --git a/editor/assets/chunks/common/mesh/material.chunk.meta b/editor/assets/chunks/common/mesh/material.chunk.meta index 58551fa823..5186e23dab 100644 --- a/editor/assets/chunks/common/mesh/material.chunk.meta +++ b/editor/assets/chunks/common/mesh/material.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "f992af76-5145-4f8e-beae-6d88be403e8e", diff --git a/editor/assets/chunks/common/shadow/native-pcf.chunk.meta b/editor/assets/chunks/common/shadow/native-pcf.chunk.meta index 95779e1cc1..5e1e511993 100644 --- a/editor/assets/chunks/common/shadow/native-pcf.chunk.meta +++ b/editor/assets/chunks/common/shadow/native-pcf.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "cac4ba94-f412-4899-83b1-ce035b0c09e0", diff --git a/editor/assets/chunks/common/texture/cubemap.chunk b/editor/assets/chunks/common/texture/cubemap.chunk index 096cf8963f..87fd12895e 100644 --- a/editor/assets/chunks/common/texture/cubemap.chunk +++ b/editor/assets/chunks/common/texture/cubemap.chunk @@ -7,7 +7,7 @@ #endif //#todo: add GL400 calcmip - float mip = roughness * mipCount; + float mip = roughness * (mipCount - 1.0); float delta = (dot(dFdx(R), dFdy(R))) * 1000.0; float mipBias = mix(0.0, 5.0, clamp(delta, 0.0, 1.0)); @@ -35,7 +35,7 @@ roughness = pow(roughness, 0.5); #endif - vec4 envmap = fragTextureLod(cc_environment, R, roughness * mipCount); + vec4 envmap = fragTextureLod(cc_environment, R, roughness * (mipCount - 1.0)); #if CC_USE_IBL == IBL_RGBE return unpackRGBE(envmap); diff --git a/editor/assets/chunks/common/texture/cubemap.chunk.meta b/editor/assets/chunks/common/texture/cubemap.chunk.meta index 824fdc2036..a26916f2eb 100644 --- a/editor/assets/chunks/common/texture/cubemap.chunk.meta +++ b/editor/assets/chunks/common/texture/cubemap.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "3931bd87-0a7b-4d2d-a5f1-9544227343a8", diff --git a/editor/assets/chunks/common/texture/texture-lod.chunk.meta b/editor/assets/chunks/common/texture/texture-lod.chunk.meta index 6f3bad78d9..794063d21a 100644 --- a/editor/assets/chunks/common/texture/texture-lod.chunk.meta +++ b/editor/assets/chunks/common/texture/texture-lod.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "d26f7be9-ac7f-4dfd-88ee-6657dfe3426e", diff --git a/editor/assets/chunks/deprecated.chunk.meta b/editor/assets/chunks/deprecated.chunk.meta index 4c57b9fe65..8eab61fa91 100644 --- a/editor/assets/chunks/deprecated.chunk.meta +++ b/editor/assets/chunks/deprecated.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "355259fc-3a13-4fed-b553-a5e2caeb2e75", diff --git a/editor/assets/chunks/legacy/decode-base.chunk.meta b/editor/assets/chunks/legacy/decode-base.chunk.meta index badd50fc3d..5987d28c61 100644 --- a/editor/assets/chunks/legacy/decode-base.chunk.meta +++ b/editor/assets/chunks/legacy/decode-base.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "e05f440c-0ba5-4c83-a039-5644d248bb87", diff --git a/editor/assets/chunks/legacy/decode-standard.chunk.meta b/editor/assets/chunks/legacy/decode-standard.chunk.meta index 5f72be4425..76fa7d87af 100644 --- a/editor/assets/chunks/legacy/decode-standard.chunk.meta +++ b/editor/assets/chunks/legacy/decode-standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "8daa33da-9438-4294-aace-2a58d1b183ab", diff --git a/editor/assets/chunks/legacy/decode.chunk.meta b/editor/assets/chunks/legacy/decode.chunk.meta index c9784e1a4f..815fe18760 100644 --- a/editor/assets/chunks/legacy/decode.chunk.meta +++ b/editor/assets/chunks/legacy/decode.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "385a7ca1-9421-475c-aa02-38d52ef3ba7f", diff --git a/editor/assets/chunks/legacy/fog-base.chunk.meta b/editor/assets/chunks/legacy/fog-base.chunk.meta index 6a0164cf37..621bc94080 100644 --- a/editor/assets/chunks/legacy/fog-base.chunk.meta +++ b/editor/assets/chunks/legacy/fog-base.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "84b6c1d8-edf3-4d07-9151-8f7ec568fd69", diff --git a/editor/assets/chunks/legacy/fog-fs.chunk.meta b/editor/assets/chunks/legacy/fog-fs.chunk.meta index 254c62b66d..c63910a58e 100644 --- a/editor/assets/chunks/legacy/fog-fs.chunk.meta +++ b/editor/assets/chunks/legacy/fog-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "5915ee07-9b06-4383-9b98-5b292bd116e9", diff --git a/editor/assets/chunks/legacy/fog-vs.chunk.meta b/editor/assets/chunks/legacy/fog-vs.chunk.meta index 927934a2bc..cd31a3c843 100644 --- a/editor/assets/chunks/legacy/fog-vs.chunk.meta +++ b/editor/assets/chunks/legacy/fog-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "0bc1a9f5-9282-4192-a0d4-4818568f2b16", diff --git a/editor/assets/chunks/legacy/input-standard.chunk.meta b/editor/assets/chunks/legacy/input-standard.chunk.meta index e207992247..5251175db1 100644 --- a/editor/assets/chunks/legacy/input-standard.chunk.meta +++ b/editor/assets/chunks/legacy/input-standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "f957d7e0-a3eb-480c-b3c6-43a1a5273b71", diff --git a/editor/assets/chunks/legacy/input.chunk.meta b/editor/assets/chunks/legacy/input.chunk.meta index c42482bae0..27b99aeb1c 100644 --- a/editor/assets/chunks/legacy/input.chunk.meta +++ b/editor/assets/chunks/legacy/input.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "3b9a2995-9fa1-4862-9bcf-9b6fa2c64bd4", diff --git a/editor/assets/chunks/legacy/lighting.chunk.meta b/editor/assets/chunks/legacy/lighting.chunk.meta index 9441cbaf19..b7b414e28a 100644 --- a/editor/assets/chunks/legacy/lighting.chunk.meta +++ b/editor/assets/chunks/legacy/lighting.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "4b078b9b-ae79-4653-bc9d-d70e69b49f4b", diff --git a/editor/assets/chunks/legacy/lightingmap-fs.chunk.meta b/editor/assets/chunks/legacy/lightingmap-fs.chunk.meta index 1339518218..6e33014baa 100644 --- a/editor/assets/chunks/legacy/lightingmap-fs.chunk.meta +++ b/editor/assets/chunks/legacy/lightingmap-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "1cd3229a-63b6-438b-88e9-98afa7f1c69e", diff --git a/editor/assets/chunks/legacy/lightingmap-vs.chunk.meta b/editor/assets/chunks/legacy/lightingmap-vs.chunk.meta index ac4b38351c..da17d515ec 100644 --- a/editor/assets/chunks/legacy/lightingmap-vs.chunk.meta +++ b/editor/assets/chunks/legacy/lightingmap-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "d22a3ca1-78fe-442c-a604-0349f5c873f7", diff --git a/editor/assets/chunks/legacy/local-batch.chunk.meta b/editor/assets/chunks/legacy/local-batch.chunk.meta index cd7932b447..8556ca2c67 100644 --- a/editor/assets/chunks/legacy/local-batch.chunk.meta +++ b/editor/assets/chunks/legacy/local-batch.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "bcff50e8-1d1f-4aea-bd0c-6868a4f2a45b", diff --git a/editor/assets/chunks/legacy/main-functions/general-vs.chunk.meta b/editor/assets/chunks/legacy/main-functions/general-vs.chunk.meta index 522b83410b..874741a555 100644 --- a/editor/assets/chunks/legacy/main-functions/general-vs.chunk.meta +++ b/editor/assets/chunks/legacy/main-functions/general-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "2cdcf2a6-42f3-4142-a340-eabfe530ccbf", diff --git a/editor/assets/chunks/legacy/main-functions/outline-fs.chunk.meta b/editor/assets/chunks/legacy/main-functions/outline-fs.chunk.meta index 31abf0e7b0..5c736f4ad9 100644 --- a/editor/assets/chunks/legacy/main-functions/outline-fs.chunk.meta +++ b/editor/assets/chunks/legacy/main-functions/outline-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "4864e2f6-3eb5-4f08-a87a-5c98141cdef4", diff --git a/editor/assets/chunks/legacy/main-functions/outline-vs.chunk.meta b/editor/assets/chunks/legacy/main-functions/outline-vs.chunk.meta index 282d26c222..0984a95f92 100644 --- a/editor/assets/chunks/legacy/main-functions/outline-vs.chunk.meta +++ b/editor/assets/chunks/legacy/main-functions/outline-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "f71444cb-cecf-4692-a310-2a5fdb96b469", diff --git a/editor/assets/chunks/legacy/morph.chunk.meta b/editor/assets/chunks/legacy/morph.chunk.meta index 0cf4637e72..7c900ae6a5 100644 --- a/editor/assets/chunks/legacy/morph.chunk.meta +++ b/editor/assets/chunks/legacy/morph.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "48359533-f5f1-4346-b242-66597abd9838", diff --git a/editor/assets/chunks/legacy/output-standard.chunk.meta b/editor/assets/chunks/legacy/output-standard.chunk.meta index 963d8ad8c4..4e7271e7d8 100644 --- a/editor/assets/chunks/legacy/output-standard.chunk.meta +++ b/editor/assets/chunks/legacy/output-standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "a3c0cc1c-64de-4e52-9698-5f73f8db488e", diff --git a/editor/assets/chunks/legacy/output.chunk.meta b/editor/assets/chunks/legacy/output.chunk.meta index b8bc4f3744..3d594a4524 100644 --- a/editor/assets/chunks/legacy/output.chunk.meta +++ b/editor/assets/chunks/legacy/output.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "713f0582-5c82-484f-81f7-5006e5a4f48f", diff --git a/editor/assets/chunks/legacy/shading-cluster-additive.chunk.meta b/editor/assets/chunks/legacy/shading-cluster-additive.chunk.meta index 456dad04bc..f40e8cf466 100644 --- a/editor/assets/chunks/legacy/shading-cluster-additive.chunk.meta +++ b/editor/assets/chunks/legacy/shading-cluster-additive.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "b2d386c6-615b-4375-accd-574405611e35", diff --git a/editor/assets/chunks/legacy/shading-standard-additive.chunk.meta b/editor/assets/chunks/legacy/shading-standard-additive.chunk.meta index adb70f1e55..73c4783751 100644 --- a/editor/assets/chunks/legacy/shading-standard-additive.chunk.meta +++ b/editor/assets/chunks/legacy/shading-standard-additive.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "a70c48b7-cf69-4c97-a857-21149cd71200", diff --git a/editor/assets/chunks/legacy/shading-standard-base.chunk b/editor/assets/chunks/legacy/shading-standard-base.chunk index 336727e4e2..138f64223e 100644 --- a/editor/assets/chunks/legacy/shading-standard-base.chunk +++ b/editor/assets/chunks/legacy/shading-standard-base.chunk @@ -43,7 +43,7 @@ vec3 BRDFApprox (vec3 specular, float roughness, float NoV) { #pragma extension([GL_OES_standard_derivatives, __VERSION__ < 110]) vec3 GetEnvReflectionWithMipFiltering(vec3 R, float roughness, float mipCount, float denoiseIntensity) { #if CC_USE_IBL - float mip = roughness * mipCount; + float mip = roughness * (mipCount - 1.0); float delta = (dot(dFdx(R), dFdy(R))) * 1000.0; float mipBias = mix(0.0, 5.0, clamp(delta, 0.0, 1.0)); @@ -100,38 +100,36 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) { vec3 N = normalize(s.normal); vec3 V = normalize(cc_cameraPos.xyz - position); - float NV = max(abs(dot(N, V)), 0.0); - specular = BRDFApprox(specular, s.roughness, NV); - - vec3 L = normalize(-cc_mainLitDir.xyz); - vec3 H = normalize(L + V); - float NH = max(dot(N, H), 0.0); - float NL = max(dot(N, L), 0.0); - vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w; - vec3 diffuseContrib = diffuse / PI; - - // Cook-Torrance Microfacet Specular BRDF - vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N); - vec3 dirlightContrib = (diffuseContrib + specularContrib); - - float shadow = 1.0; - #if CC_RECEIVE_SHADOW - if (NL > 0.0 && cc_mainLitDir.w > 0.0) { - if (cc_shadowLPNNInfo.w > 0.0) { - shadow = CCCSMFactorBase(position, N, s.shadowBias); - } else { - shadow = CCShadowFactorBase(shadowPos, N, s.shadowBias); - } - } - #endif - - dirlightContrib *= shadow; - finalColor *= dirlightContrib; - #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD - if (s.lightmap_test > EPSILON_LOWP) { - finalColor = diffuse * s.lightmap.rgb * shadow; - } + vec3 finalColor = diffuse * s.lightmap.rgb; + #else + float NV = max(abs(dot(N, V)), 0.0); + specular = BRDFApprox(specular, s.roughness, NV); + + vec3 L = normalize(-cc_mainLitDir.xyz); + vec3 H = normalize(L + V); + float NH = max(dot(N, H), 0.0); + float NL = max(dot(N, L), 0.0); + vec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w; + vec3 diffuseContrib = diffuse / PI; + + // Cook-Torrance Microfacet Specular BRDF + vec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N); + vec3 dirlightContrib = (diffuseContrib + specularContrib); + + float shadow = 1.0; + #if CC_RECEIVE_SHADOW + if (NL > 0.0 && cc_mainLitDir.w > 0.0) { + if (cc_shadowLPNNInfo.w > 0.0) { + shadow = CCCSMFactorBase(position, N, s.shadowBias); + } else { + shadow = CCShadowFactorBase(shadowPos, N, s.shadowBias); + } + } + #endif + + dirlightContrib *= shadow; + finalColor *= dirlightContrib; #endif float fAmb = 0.5 - N.y * 0.5; @@ -151,10 +149,10 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) { vec3 R = normalize(reflect(-V, N)); - #if USE_REFLECTION_DENOISE + #if USE_REFLECTION_DENOISE && !CC_IBL_CONVOLUTED vec3 env = GetEnvReflectionWithMipFiltering(R, s.roughness, cc_ambientGround.w, 0.6); #else - vec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w); + vec4 envmap = fragTextureLod(cc_environment, R, s.roughness * (cc_ambientGround.w - 1.0)); #if CC_USE_IBL == IBL_RGBE vec3 env = unpackRGBE(envmap); diff --git a/editor/assets/chunks/legacy/shading-standard-base.chunk.meta b/editor/assets/chunks/legacy/shading-standard-base.chunk.meta index e2532ae168..adef3c3f57 100644 --- a/editor/assets/chunks/legacy/shading-standard-base.chunk.meta +++ b/editor/assets/chunks/legacy/shading-standard-base.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "9ae7cfaf-c5cc-4899-95a5-d6e1215c8964", diff --git a/editor/assets/chunks/legacy/shading-standard.chunk.meta b/editor/assets/chunks/legacy/shading-standard.chunk.meta index 872b5824cc..2753b8f39a 100644 --- a/editor/assets/chunks/legacy/shading-standard.chunk.meta +++ b/editor/assets/chunks/legacy/shading-standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "f9ba1729-bacf-4e62-8c97-0103d940c464", diff --git a/editor/assets/chunks/legacy/shading-toon.chunk.meta b/editor/assets/chunks/legacy/shading-toon.chunk.meta index ae89c4d64e..0a067a7499 100644 --- a/editor/assets/chunks/legacy/shading-toon.chunk.meta +++ b/editor/assets/chunks/legacy/shading-toon.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "bbfd1dfb-8f99-4b68-9aa6-817d5b67096d", diff --git a/editor/assets/chunks/legacy/shadow-map-base.chunk.meta b/editor/assets/chunks/legacy/shadow-map-base.chunk.meta index a076463160..48cb2d8d89 100644 --- a/editor/assets/chunks/legacy/shadow-map-base.chunk.meta +++ b/editor/assets/chunks/legacy/shadow-map-base.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "1d68b1b7-2f78-4c24-9f35-b215dc980207", diff --git a/editor/assets/chunks/legacy/shadow-map-fs.chunk.meta b/editor/assets/chunks/legacy/shadow-map-fs.chunk.meta index dac386137d..7737ba3c7c 100644 --- a/editor/assets/chunks/legacy/shadow-map-fs.chunk.meta +++ b/editor/assets/chunks/legacy/shadow-map-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "5716d893-2ecc-4110-9291-88b7e939d37d", diff --git a/editor/assets/chunks/legacy/shadow-map-vs.chunk.meta b/editor/assets/chunks/legacy/shadow-map-vs.chunk.meta index 8ca760831c..0564fce7dc 100644 --- a/editor/assets/chunks/legacy/shadow-map-vs.chunk.meta +++ b/editor/assets/chunks/legacy/shadow-map-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "b2e7c003-9c9f-40ee-82c6-32d920a759e8", diff --git a/editor/assets/chunks/legacy/skinning.chunk.meta b/editor/assets/chunks/legacy/skinning.chunk.meta index b2122b52e9..7c45a21b0c 100644 --- a/editor/assets/chunks/legacy/skinning.chunk.meta +++ b/editor/assets/chunks/legacy/skinning.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "f1e9de44-ca95-48c8-9233-d1b5406ab544", diff --git a/editor/assets/chunks/legacy/standard-surface-entry.chunk.meta b/editor/assets/chunks/legacy/standard-surface-entry.chunk.meta index 7aa2c5a7a1..4952255b79 100644 --- a/editor/assets/chunks/legacy/standard-surface-entry.chunk.meta +++ b/editor/assets/chunks/legacy/standard-surface-entry.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "31d0a199-05e2-422c-a019-8139a855841c", diff --git a/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk.meta b/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk.meta index a34b2330e0..47c4149611 100644 --- a/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk.meta +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "be2dc7d9-db45-4d0b-957b-aee1cb81bde0", diff --git a/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk.meta b/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk.meta index fdcb215751..ec12eb8e50 100644 --- a/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk.meta +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "7646cc74-5fcc-47c4-970b-5958505c17e5", diff --git a/editor/assets/chunks/lighting-models/default-functions/simple-skin.chunk.meta b/editor/assets/chunks/lighting-models/default-functions/simple-skin.chunk.meta index 2b899695c8..1c6eaafd8e 100644 --- a/editor/assets/chunks/lighting-models/default-functions/simple-skin.chunk.meta +++ b/editor/assets/chunks/lighting-models/default-functions/simple-skin.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "9ada82f2-4c4e-433f-8090-e8bfad31fcf2", diff --git a/editor/assets/chunks/lighting-models/includes/standard.chunk.meta b/editor/assets/chunks/lighting-models/includes/standard.chunk.meta index ad70678752..aed47b8c7d 100644 --- a/editor/assets/chunks/lighting-models/includes/standard.chunk.meta +++ b/editor/assets/chunks/lighting-models/includes/standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "cc12f5ac-3dcf-4455-aea9-b9be2dd9071e", diff --git a/editor/assets/chunks/lighting-models/includes/toon.chunk.meta b/editor/assets/chunks/lighting-models/includes/toon.chunk.meta index b8099d0120..e50c36cac6 100644 --- a/editor/assets/chunks/lighting-models/includes/toon.chunk.meta +++ b/editor/assets/chunks/lighting-models/includes/toon.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "2710ad01-b6c3-4048-b5d9-b3b69cec3e94", diff --git a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk index a6bf1324e4..2124986c01 100644 --- a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk +++ b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk @@ -61,23 +61,37 @@ CCSurfacesLightingInitializeColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData); CCSurfacesLightingCalculateIntermediateData_PerLight(lightingData, surfaceData, -cc_mainLitDir.xyz); - CCSurfacesLightingCalculateColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData); - CCSurfacesLightingCalculateDirect(lightingResult.directDiffuse, lightingResult.directSpecular, lightingData, cc_mainLitColor); - - // CCSurfacesLightingCalculateShadow: - lightingResult.shadow = 1.0; - #if CC_RECEIVE_SHADOW - if (cc_mainLitDir.w > 0.0) { - if (CCSurfacesLightingEnableShadow(lightingData.NoL)) { - if (cc_shadowLPNNInfo.w > 0.0) { - lightingResult.shadow = CCCSMFactorBase(surfaceData.worldPos, lightingData.N, shadowBias); - } else { - vec4 shadowPos = cc_matLightViewProj * vec4(surfaceData.worldPos, 1.0); - lightingResult.shadow = CCShadowFactorBase(shadowPos, lightingData.N, shadowBias); + // CCSurfacesLightingCalculateBaked: + lightingResult.lightmapColor = vec3(0.0); + #if CC_SURFACES_USE_LIGHT_MAP && !USE_BATCHING && !CC_FORWARD_ADD + vec4 lightmap = GetLightMapColor(cc_lightingMap, FSInput_lightMapUV.xy, FSInput_lightMapUV.z); + lightingResult.lightmapColor = lightmap.rgb; + // lightingResult.shadow/ao *= lightmap.a; + + // static dir light + lightingResult.directDiffuse = lightingResult.directSpecular = vec3(0.0); + lightingResult.shadow = lightingResult.ao = 1.0; + // dynamic & stationary dir light + #else + CCSurfacesLightingCalculateColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData); + + CCSurfacesLightingCalculateDirect(lightingResult.directDiffuse, lightingResult.directSpecular, lightingData, cc_mainLitColor); + + // CCSurfacesLightingCalculateShadow: + lightingResult.shadow = 1.0; + #if CC_RECEIVE_SHADOW + if (cc_mainLitDir.w > 0.0) { + if (CCSurfacesLightingEnableShadow(lightingData.NoL)) { + if (cc_shadowLPNNInfo.w > 0.0) { + lightingResult.shadow = CCCSMFactorBase(surfaceData.worldPos, lightingData.N, shadowBias); + } else { + vec4 shadowPos = cc_matLightViewProj * vec4(surfaceData.worldPos, 1.0); + lightingResult.shadow = CCShadowFactorBase(shadowPos, lightingData.N, shadowBias); + } } } - } + #endif #endif // apply SSR, local probe & global probe @@ -85,14 +99,6 @@ // CCSurfacesLightingCalculateTransmittence(lightingResult, lightingData, shadowPos); - // CCSurfacesLightingCalculateBaked: - lightingResult.lightmapColor = vec3(0.0); - #if CC_SURFACES_USE_LIGHT_MAP && !USE_BATCHING && !CC_FORWARD_ADD - vec4 lightmap = GetLightMapColor(cc_lightingMap, FSInput_lightMapUV.xy, FSInput_lightMapUV.z); - lightingResult.lightmapColor = lightmap.rgb; - // lightingResult.shadow/ao *= lightmap.a; - #endif - // apply screen-space shadow and ao // lightingResult.shadow/ao *= XXX; diff --git a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk.meta b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk.meta index 19fc3e1827..55ceff5cac 100644 --- a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk.meta +++ b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "41c84281-f2e7-43e2-88bd-6ffcaf1daf5a", diff --git a/editor/assets/chunks/lighting-models/model-functions/standard.chunk b/editor/assets/chunks/lighting-models/model-functions/standard.chunk index a05a4d09bc..9ee80346a5 100644 --- a/editor/assets/chunks/lighting-models/model-functions/standard.chunk +++ b/editor/assets/chunks/lighting-models/model-functions/standard.chunk @@ -101,7 +101,7 @@ void CCSurfacesLightingCalculateEnvironment(inout LightingResult lightingResult, #if CC_SURFACES_LIGHTING_ANISOTROPIC && CC_SURFACES_LIGHTING_ANISOTROPIC_ENVCONVOLUTION_COUNT envSpec = EnvAnisotropicReflection(R, roughness, cc_ambientGround.w, lightingData.anisotropyShape, lightingData.V, lightingData.N, lightingData.T, lightingData.B); #else - #if CC_SURFACES_USE_REFLECTION_DENOISE + #if CC_SURFACES_USE_REFLECTION_DENOISE && !CC_IBL_CONVOLUTED envSpec = EnvReflectionWithMipFiltering(normalize(R), roughness, cc_ambientGround.w, 0.6); #else envSpec = EnvReflection(R, roughness, cc_ambientGround.w); diff --git a/editor/assets/chunks/lighting-models/model-functions/standard.chunk.meta b/editor/assets/chunks/lighting-models/model-functions/standard.chunk.meta index cf93dfd88f..07695ab1b5 100644 --- a/editor/assets/chunks/lighting-models/model-functions/standard.chunk.meta +++ b/editor/assets/chunks/lighting-models/model-functions/standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "4c24618b-1e1d-40e4-883a-cd3fd2304233", diff --git a/editor/assets/chunks/lighting-models/model-functions/toon.chunk.meta b/editor/assets/chunks/lighting-models/model-functions/toon.chunk.meta index afbfaec417..f7999c03d4 100644 --- a/editor/assets/chunks/lighting-models/model-functions/toon.chunk.meta +++ b/editor/assets/chunks/lighting-models/model-functions/toon.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "9276cd2c-6001-4f89-b024-f53f63628527", diff --git a/editor/assets/chunks/post-process/anti-aliasing.chunk.meta b/editor/assets/chunks/post-process/anti-aliasing.chunk.meta index e75d0351e9..52e21fdbbe 100644 --- a/editor/assets/chunks/post-process/anti-aliasing.chunk.meta +++ b/editor/assets/chunks/post-process/anti-aliasing.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "60bb7684-4cd7-4d19-96c4-262e12e0b025", diff --git a/editor/assets/chunks/post-process/fxaa.chunk.meta b/editor/assets/chunks/post-process/fxaa.chunk.meta index c1801612d6..63f3a4284f 100644 --- a/editor/assets/chunks/post-process/fxaa.chunk.meta +++ b/editor/assets/chunks/post-process/fxaa.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "0afb4a28-945f-48ac-91e5-6f483345f8ab", diff --git a/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk.meta b/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk.meta index 42a257d04c..dfaf28401b 100644 --- a/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk.meta +++ b/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "ec870cfb-9c88-4f70-929a-ae540a33075b", diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk.meta b/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk.meta index 0397a96d5e..ae509452e5 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "f3454fd7-28d9-48dd-a761-ebc8e26834ed", diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk.meta b/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk.meta index 05258f96b8..1c0c4c3b8b 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk.meta +++ b/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "65084d4a-ae7c-4ca9-8448-f4cd405144b7", diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk.meta b/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk.meta index e8eca09b32..3429e4df33 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk.meta +++ b/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "45e6b403-a354-48de-a1e1-e59238bd30b1", diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk.meta b/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk.meta index bf692bfc58..bea46aabc9 100644 --- a/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk.meta +++ b/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "513eb9a6-0193-4ab1-a7da-2ab087936caa", diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-fs.chunk.meta index 0af09667a2..ffdd36b88d 100644 --- a/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "1d7d5670-83c4-4dab-acf3-edb7ae758881", diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-vs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-vs.chunk.meta index 1d6a31a520..786eff84ec 100644 --- a/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-vs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "e25e8368-0f16-4322-981e-8b7eebc97afb", diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk.meta index ddc4b7b01d..ad13a831b1 100644 --- a/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "6a27185f-415d-419c-95b0-85337e21eff9", diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/sky-vs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/misc/sky-vs.chunk.meta index ff1eeaeabb..8231fd5cdb 100644 --- a/editor/assets/chunks/shading-entries/main-functions/misc/sky-vs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/misc/sky-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "070d960d-b2b5-437c-99da-0aeb502f7273", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk.meta index 416f4df722..a2a0e6dd05 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "52b875e1-87c0-4dc5-a3f7-ce32cb4d93c6", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/deferred-fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/deferred-fs.chunk.meta index 282eca1aa7..2e7803fb24 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/deferred-fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/deferred-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "1101cf65-cc90-486b-b6a5-29ae060e01c7", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk index 9776b74e4b..f3f97bb6b9 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk @@ -20,8 +20,8 @@ void main() { { vec4 csmPos; vec4 shadowProjDepthInfo, shadowProjInfo; - mat4 matLightView; - int csmLayer = CCGetCSMLevel(csmPos, shadowProjDepthInfo, shadowProjInfo, matLightView[0], matLightView[1], matLightView[2], matLightView[3], surfaceData.worldPos); + vec3 shadowViewDir0, shadowViewDir1, shadowViewDir2; + int csmLayer = CCGetCSMLevel(csmPos, shadowProjDepthInfo, shadowProjInfo, shadowViewDir0, shadowViewDir1, shadowViewDir2, surfaceData.worldPos); bool OutOfRange = csmLayer < 0; if (OutOfRange) colDebugCSMLayer = vec3(1.0); diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk.meta index 01e57b893a..2184c1ffd7 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "349a2be0-c8d3-420c-9dd1-bf86e01a7055", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk.meta index cfe1d49566..8a665f9597 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "4306c0df-b6d6-4733-8a45-c85907f94d29", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk index 33614ecd79..e1824dc45d 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk @@ -3,8 +3,9 @@ in highp vec2 v_clip_depth; layout(location = 0) out vec4 fragColorX; void main () { - // for alpha clip - SurfacesFragmentModifyBaseColorAndTransparency(); + // better performance than SurfacesFragmentModifyBaseColorAndTransparency + SurfacesFragmentAlphaClipOnly(); + highp float clipDepth = v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5; // spot use linear diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk.meta index fa25ea61ea..2597a07791 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "a734c67a-3ce2-4978-bf57-080d1dfbbb43", diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk.meta index 942f03f737..9817d7fc3b 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk.meta +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "7a668e36-d75e-488d-b47a-52591e07151d", diff --git a/editor/assets/chunks/surfaces/data-structures/standard.chunk.meta b/editor/assets/chunks/surfaces/data-structures/standard.chunk.meta index 4c83acc676..59fc003fdb 100644 --- a/editor/assets/chunks/surfaces/data-structures/standard.chunk.meta +++ b/editor/assets/chunks/surfaces/data-structures/standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "29b8aed8-f4da-471e-a036-4fffc28868f3", diff --git a/editor/assets/chunks/surfaces/data-structures/toon.chunk.meta b/editor/assets/chunks/surfaces/data-structures/toon.chunk.meta index 4940e02b61..8c506a3bb1 100644 --- a/editor/assets/chunks/surfaces/data-structures/toon.chunk.meta +++ b/editor/assets/chunks/surfaces/data-structures/toon.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "7ac0dc35-81bc-4b7c-9701-a401747deccf", diff --git a/editor/assets/chunks/surfaces/default-functions/common-vs.chunk.meta b/editor/assets/chunks/surfaces/default-functions/common-vs.chunk.meta index 68e84b64df..8de04a9d76 100644 --- a/editor/assets/chunks/surfaces/default-functions/common-vs.chunk.meta +++ b/editor/assets/chunks/surfaces/default-functions/common-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "b3d7cc71-db0a-4f76-a2e1-c145c679180f", diff --git a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk index 16ba4c5344..10234ffc44 100644 --- a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk +++ b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk @@ -5,6 +5,13 @@ vec4 SurfacesFragmentModifyBaseColorAndTransparency() } #endif +#ifndef CC_SURFACES_FRAGMENT_ALPHA_CLIP_ONLY +// for base shape without color usage, such as render-to-shadow +void SurfacesFragmentAlphaClipOnly() +{ +} +#endif + #ifndef CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL vec3 SurfacesFragmentModifyWorldNormal() diff --git a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk.meta b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk.meta index e2a4ec4208..406d413813 100644 --- a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "57b9c877-9855-47c0-bb6f-da3a2c19414e", diff --git a/editor/assets/chunks/surfaces/default-functions/toon-fs.chunk.meta b/editor/assets/chunks/surfaces/default-functions/toon-fs.chunk.meta index bf7c495dba..d5675a8111 100644 --- a/editor/assets/chunks/surfaces/default-functions/toon-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/default-functions/toon-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "3804c73c-5c8d-42cf-8382-6b64ab2ea7bc", diff --git a/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk.meta index 5fb3edc435..5a1200e89a 100644 --- a/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk.meta +++ b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "5fb14bc4-12ef-4b8f-b2d2-e0a7df233e31", diff --git a/editor/assets/chunks/surfaces/effect-macros/render-to-shadowmap.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/render-to-shadowmap.chunk.meta index 2f27574999..f19174c1cc 100644 --- a/editor/assets/chunks/surfaces/effect-macros/render-to-shadowmap.chunk.meta +++ b/editor/assets/chunks/surfaces/effect-macros/render-to-shadowmap.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "f66020b7-1a8a-424a-abf4-a8cbe80e410f", diff --git a/editor/assets/chunks/surfaces/effect-macros/silhouette-edge.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/silhouette-edge.chunk.meta index 3886390638..71dd84019e 100644 --- a/editor/assets/chunks/surfaces/effect-macros/silhouette-edge.chunk.meta +++ b/editor/assets/chunks/surfaces/effect-macros/silhouette-edge.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "2f746ff4-a6d3-41ec-bcd7-52c8283f3a57", diff --git a/editor/assets/chunks/surfaces/effect-macros/sky.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/sky.chunk.meta index 48e61c6e3f..1e06271390 100644 --- a/editor/assets/chunks/surfaces/effect-macros/sky.chunk.meta +++ b/editor/assets/chunks/surfaces/effect-macros/sky.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "dc6e17a4-b3b4-4316-8f1e-c925b6fab67c", diff --git a/editor/assets/chunks/surfaces/effect-macros/terrain.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/terrain.chunk.meta index 1511825d54..a49c4e71ac 100644 --- a/editor/assets/chunks/surfaces/effect-macros/terrain.chunk.meta +++ b/editor/assets/chunks/surfaces/effect-macros/terrain.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "1de87047-07ab-491a-b418-588ff145eaec", diff --git a/editor/assets/chunks/surfaces/includes/common-fs.chunk b/editor/assets/chunks/surfaces/includes/common-fs.chunk index 59b8fe2a88..67497a14cf 100644 --- a/editor/assets/chunks/surfaces/includes/common-fs.chunk +++ b/editor/assets/chunks/surfaces/includes/common-fs.chunk @@ -23,6 +23,9 @@ // Uniforms--Tex #include +#if CC_SUPPORT_CASCADED_SHADOW_MAP + #include +#endif #if CC_USE_IBL #include #if CC_USE_DIFFUSEMAP diff --git a/editor/assets/chunks/surfaces/includes/common-fs.chunk.meta b/editor/assets/chunks/surfaces/includes/common-fs.chunk.meta index 8f7f46821d..7f9cb08c46 100644 --- a/editor/assets/chunks/surfaces/includes/common-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/includes/common-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "a6451dbc-fc4c-4a10-84f5-072c6e982fa5", diff --git a/editor/assets/chunks/surfaces/includes/common-vs.chunk.meta b/editor/assets/chunks/surfaces/includes/common-vs.chunk.meta index 8961da1726..4507a1b1df 100644 --- a/editor/assets/chunks/surfaces/includes/common-vs.chunk.meta +++ b/editor/assets/chunks/surfaces/includes/common-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "c66380b2-694f-40bd-afd8-91a2e58d904d", diff --git a/editor/assets/chunks/surfaces/includes/standard-fs.chunk.meta b/editor/assets/chunks/surfaces/includes/standard-fs.chunk.meta index db736e4f9a..82c32350c4 100644 --- a/editor/assets/chunks/surfaces/includes/standard-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/includes/standard-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "0d0afa06-80d6-45b8-9fa6-6f6ad947c00b", diff --git a/editor/assets/chunks/surfaces/includes/standard-vs.chunk.meta b/editor/assets/chunks/surfaces/includes/standard-vs.chunk.meta index ae8aeba766..abd2cec726 100644 --- a/editor/assets/chunks/surfaces/includes/standard-vs.chunk.meta +++ b/editor/assets/chunks/surfaces/includes/standard-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "698b9da6-3f0e-4113-8b1c-5ebc82e3ab3d", diff --git a/editor/assets/chunks/surfaces/includes/toon-fs.chunk.meta b/editor/assets/chunks/surfaces/includes/toon-fs.chunk.meta index 9e64e66c52..15d9e0d196 100644 --- a/editor/assets/chunks/surfaces/includes/toon-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/includes/toon-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "5a2c165c-7d8d-4ed5-9142-52f895dee13c", diff --git a/editor/assets/chunks/surfaces/includes/toon-vs.chunk.meta b/editor/assets/chunks/surfaces/includes/toon-vs.chunk.meta index c8212a7459..8df6b5aeac 100644 --- a/editor/assets/chunks/surfaces/includes/toon-vs.chunk.meta +++ b/editor/assets/chunks/surfaces/includes/toon-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "ef0e1f2a-454f-4613-959c-3d9da0cae4f8", diff --git a/editor/assets/chunks/surfaces/module-functions/common-vs.chunk.meta b/editor/assets/chunks/surfaces/module-functions/common-vs.chunk.meta index a949abc4ad..a3e2ec1a71 100644 --- a/editor/assets/chunks/surfaces/module-functions/common-vs.chunk.meta +++ b/editor/assets/chunks/surfaces/module-functions/common-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "e1feba3c-c7a2-4208-9c1f-732b7e46abd4", diff --git a/editor/assets/chunks/surfaces/module-functions/debug-view.chunk.meta b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk.meta index 49ff1d145f..8d793ce426 100644 --- a/editor/assets/chunks/surfaces/module-functions/debug-view.chunk.meta +++ b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "30961f82-b8ef-4d3b-a9e5-944bb5e103f1", diff --git a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk index b5917fb879..ab4ec5037e 100644 --- a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk +++ b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk @@ -113,15 +113,8 @@ vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult li color.xyz += lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting; color.xyz += lightingResult.directSpecular * lightingResult.specularColorWithLighting; #else - #if CC_SURFACES_USE_LIGHT_MAP && !USE_BATCHING && !CC_FORWARD_ADD - float lum = FSInput_lightMapUV.z; - float lightmapCoef = step(lum, EPSILON_LOWP); - #else - float lightmapCoef = 0.0; - #endif - - color.xyz += ( - mix(lightingResult.directDiffuse, lightingResult.lightmapColor, lightmapCoef) * lightingResult.diffuseColorWithLighting + color.xyz += lightingResult.lightmapColor * lightingResult.diffuseColorWithLighting + + (lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting + lightingResult.directSpecular * lightingResult.specularColorWithLighting) * lightingResult.shadow; diff --git a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk.meta b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk.meta index dcd7687993..eb9b75fcb7 100644 --- a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "6853f548-fd1c-4a96-94f3-ba6981fbefd4", diff --git a/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk.meta b/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk.meta index e73d37d4cd..436be700d3 100644 --- a/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk.meta +++ b/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.5", + "ver": "1.0.6", "importer": "effect-header", "imported": true, "uuid": "218130cc-7167-4535-b6b8-99807138bb39", diff --git a/editor/assets/effects/builtin-billboard.effect.meta b/editor/assets/effects/builtin-billboard.effect.meta index 0330371d48..b99edfc9ce 100644 --- a/editor/assets/effects/builtin-billboard.effect.meta +++ b/editor/assets/effects/builtin-billboard.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "711ebe11-f673-4cd9-9a83-63c60ba54c5b", diff --git a/editor/assets/effects/builtin-camera-texture.effect.meta b/editor/assets/effects/builtin-camera-texture.effect.meta index c1306a4724..963bb6e224 100644 --- a/editor/assets/effects/builtin-camera-texture.effect.meta +++ b/editor/assets/effects/builtin-camera-texture.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "bf4078d6-d2d7-4073-83bb-cd6f1802e880", diff --git a/editor/assets/effects/builtin-clear-stencil.effect.meta b/editor/assets/effects/builtin-clear-stencil.effect.meta index 3bad34afcb..7d8f0c60b4 100644 --- a/editor/assets/effects/builtin-clear-stencil.effect.meta +++ b/editor/assets/effects/builtin-clear-stencil.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "810e96e4-e456-4468-9b59-f4e8f39732c0", diff --git a/editor/assets/effects/builtin-debug-renderer.effect.meta b/editor/assets/effects/builtin-debug-renderer.effect.meta index 100aa99380..5716841b4d 100644 --- a/editor/assets/effects/builtin-debug-renderer.effect.meta +++ b/editor/assets/effects/builtin-debug-renderer.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "ff9be190-20a4-4e48-b68c-76e3c7cff085", diff --git a/editor/assets/effects/builtin-geometry-renderer.effect.meta b/editor/assets/effects/builtin-geometry-renderer.effect.meta index 229c4ccaec..003d482453 100644 --- a/editor/assets/effects/builtin-geometry-renderer.effect.meta +++ b/editor/assets/effects/builtin-geometry-renderer.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "4bb480dd-8384-4bc9-987f-de67cc53052a", diff --git a/editor/assets/effects/builtin-graphics.effect.meta b/editor/assets/effects/builtin-graphics.effect.meta index 7a96ca66ad..4359b7a619 100644 --- a/editor/assets/effects/builtin-graphics.effect.meta +++ b/editor/assets/effects/builtin-graphics.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "1c02ae6f-4492-4915-b8f8-7492a3b1e4cd", diff --git a/editor/assets/effects/builtin-occlusion-query.effect.meta b/editor/assets/effects/builtin-occlusion-query.effect.meta index ab0239f48d..9df4581862 100644 --- a/editor/assets/effects/builtin-occlusion-query.effect.meta +++ b/editor/assets/effects/builtin-occlusion-query.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "d9937e59-61fe-4ec6-92ab-7ac5a19c89b0", diff --git a/editor/assets/effects/builtin-particle-gpu.effect.meta b/editor/assets/effects/builtin-particle-gpu.effect.meta index 2c6c603fed..a2520b7436 100644 --- a/editor/assets/effects/builtin-particle-gpu.effect.meta +++ b/editor/assets/effects/builtin-particle-gpu.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "971bdb23-3ff6-43eb-b422-1c30165a3663", diff --git a/editor/assets/effects/builtin-particle-trail.effect.meta b/editor/assets/effects/builtin-particle-trail.effect.meta index a924478f5c..2229e8dadf 100644 --- a/editor/assets/effects/builtin-particle-trail.effect.meta +++ b/editor/assets/effects/builtin-particle-trail.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "17debcc3-0a6b-4b8a-b00b-dc58b885581e", diff --git a/editor/assets/effects/builtin-particle.effect.meta b/editor/assets/effects/builtin-particle.effect.meta index 9f33a7edef..c03b1229ae 100644 --- a/editor/assets/effects/builtin-particle.effect.meta +++ b/editor/assets/effects/builtin-particle.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "d1346436-ac96-4271-b863-1f4fdead95b0", diff --git a/editor/assets/effects/builtin-reflection-deferred.effect.meta b/editor/assets/effects/builtin-reflection-deferred.effect.meta index 372ca1464d..ca823d592a 100644 --- a/editor/assets/effects/builtin-reflection-deferred.effect.meta +++ b/editor/assets/effects/builtin-reflection-deferred.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "99498f84-efe6-43a6-a9a7-e6e93eb845c1", diff --git a/editor/assets/effects/builtin-spine.effect.meta b/editor/assets/effects/builtin-spine.effect.meta index 9af7395abb..0fe556b993 100644 --- a/editor/assets/effects/builtin-spine.effect.meta +++ b/editor/assets/effects/builtin-spine.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "c27215d8-6835-4b68-bfbb-bdeac6100c04", diff --git a/editor/assets/effects/builtin-sprite-renderer.effect.meta b/editor/assets/effects/builtin-sprite-renderer.effect.meta index b0163d210a..02784a96f0 100644 --- a/editor/assets/effects/builtin-sprite-renderer.effect.meta +++ b/editor/assets/effects/builtin-sprite-renderer.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "6ef1defe-7997-477a-9b35-c18859ff8066", diff --git a/editor/assets/effects/builtin-sprite.effect.meta b/editor/assets/effects/builtin-sprite.effect.meta index 29f28e1cc8..2d830603b1 100644 --- a/editor/assets/effects/builtin-sprite.effect.meta +++ b/editor/assets/effects/builtin-sprite.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "60f7195c-ec2a-45eb-ba94-8955f60e81d0", diff --git a/editor/assets/effects/builtin-standard.effect b/editor/assets/effects/builtin-standard.effect index 69fa82c50b..bf63e71f8a 100644 --- a/editor/assets/effects/builtin-standard.effect +++ b/editor/assets/effects/builtin-standard.effect @@ -368,11 +368,10 @@ CCProgram shadow-caster-fs %{ vec4 frag () { vec4 baseColor = albedo; - #if USE_ALBEDO_MAP - baseColor *= texture(albedoMap, ALBEDO_UV); - #endif - #if USE_ALPHA_TEST + #if USE_ALBEDO_MAP + baseColor *= texture(albedoMap, ALBEDO_UV); + #endif if (baseColor.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard; #endif diff --git a/editor/assets/effects/builtin-standard.effect.meta b/editor/assets/effects/builtin-standard.effect.meta index 14658ad55d..04f0c87578 100644 --- a/editor/assets/effects/builtin-standard.effect.meta +++ b/editor/assets/effects/builtin-standard.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "1baf0fc9-befa-459c-8bdd-af1a450a0319", diff --git a/editor/assets/effects/builtin-terrain.effect.meta b/editor/assets/effects/builtin-terrain.effect.meta index 28b87b72b6..410178cb44 100644 --- a/editor/assets/effects/builtin-terrain.effect.meta +++ b/editor/assets/effects/builtin-terrain.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "1d08ef62-a503-4ce2-8b9a-46c90873f7d3", diff --git a/editor/assets/effects/builtin-toon.effect b/editor/assets/effects/builtin-toon.effect index 7c9a6badec..a36b279efc 100644 --- a/editor/assets/effects/builtin-toon.effect +++ b/editor/assets/effects/builtin-toon.effect @@ -309,11 +309,11 @@ CCProgram shadow-caster-fs %{ vec4 frag () { vec4 baseColor = baseColor; - #if USE_BASE_COLOR_MAP - baseColor *= texture(baseColorMap, v_uv); - #endif #if USE_ALPHA_TEST + #if USE_BASE_COLOR_MAP + baseColor *= texture(baseColorMap, v_uv); + #endif if (baseColor.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard; #endif diff --git a/editor/assets/effects/builtin-toon.effect.meta b/editor/assets/effects/builtin-toon.effect.meta index afd69e1d7f..137aaed477 100644 --- a/editor/assets/effects/builtin-toon.effect.meta +++ b/editor/assets/effects/builtin-toon.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "a7612b54-35e3-4238-a1a9-4a7b54635839", diff --git a/editor/assets/effects/builtin-unlit.effect.meta b/editor/assets/effects/builtin-unlit.effect.meta index 460184af4a..a66c3e0920 100644 --- a/editor/assets/effects/builtin-unlit.effect.meta +++ b/editor/assets/effects/builtin-unlit.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "a3cd009f-0ab0-420d-9278-b9fdab939bbc", diff --git a/editor/assets/effects/builtin-wireframe.effect.meta b/editor/assets/effects/builtin-wireframe.effect.meta index 4dc7a7aa5a..8bc31eefbc 100644 --- a/editor/assets/effects/builtin-wireframe.effect.meta +++ b/editor/assets/effects/builtin-wireframe.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "81127eb0-7556-453c-b147-670782dd5e53", diff --git a/editor/assets/effects/dcc/imported-metallic-roughness.effect b/editor/assets/effects/dcc/imported-metallic-roughness.effect index cc26af5ded..57d9153dc4 100644 --- a/editor/assets/effects/dcc/imported-metallic-roughness.effect +++ b/editor/assets/effects/dcc/imported-metallic-roughness.effect @@ -57,6 +57,8 @@ CCEffect %{ albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } } mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + alphaSource: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + alphaSourceMap: { value: grey, editor: { parent: USE_OPACITY_MAP } } - name: transparent passes: - vert: standard-vs @@ -435,19 +437,33 @@ CCProgram shadow-caster-fs %{ #pragma define-meta ALBEDO_UV options([v_uv, v_uv1]) #endif - #if USE_ALPHA_TEST - #pragma define-meta ALPHA_TEST_CHANNEL options([a, r]) + #pragma define-meta TEXTURE_UV options([v_uv, v_uv1]) + + #if USE_OPACITY_MAP + #pragma define-meta ALPHA_SOURCE_CHANNEL options([r, g, b, a]) + uniform sampler2D alphaSourceMap; #endif vec4 frag () { - vec4 baseColor = albedo; - - #if USE_ALBEDO_MAP - baseColor *= texture(albedoMap, ALBEDO_UV); - #endif - #if USE_ALPHA_TEST - if (baseColor.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard; + float alpha = albedo.a; + #if USE_ALBEDO_MAP + alpha = texture(albedoMap, TEXTURE_UV).a; + #endif + #if ALPHA_SOURCE_IS_OPACITY + #if USE_OPACITY_MAP + alpha = 1.0 - texture(alphaSourceMap, TEXTURE_UV).ALPHA_SOURCE_CHANNEL; + #else + alpha = 1.0 - alphaSource; + #endif + #else + #if USE_OPACITY_MAP + alpha = texture(alphaSourceMap, TEXTURE_UV).ALPHA_SOURCE_CHANNEL; + #else + alpha = alphaSource; + #endif + #endif + if (alpha < albedoScaleAndCutoff.w) discard; #endif highp float clipDepth = v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5; diff --git a/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta b/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta index b0d0358205..eaa8359626 100644 --- a/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta +++ b/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "2ec11458-f855-4978-b14d-f3ed5cf697fa", diff --git a/editor/assets/effects/dcc/imported-specular-glossiness.effect b/editor/assets/effects/dcc/imported-specular-glossiness.effect index e7bbd5f9ed..05af1fb76c 100644 --- a/editor/assets/effects/dcc/imported-specular-glossiness.effect +++ b/editor/assets/effects/dcc/imported-specular-glossiness.effect @@ -10,7 +10,7 @@ CCEffect %{ mainTexture: { value: grey, target: albedoMap, editor: { displayName: DiffuseMap } } mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: diffuseColor, linear: true, editor: { displayName: DiffuseColor, type: color } } albedoScale: { value: 1.0, target: diffuseFactor, editor: { displayName: diffuseFactor } } - alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } + alphaThreshold: { value: 0.5, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } emissive: { value: [0.0, 0.0, 0.0, 1.0], linear: true, editor: { type: color } } emissiveMap: { value: grey } shininessExponentMap: { value: grey, editor: { parent: '!HAS_EXPORTED_GLOSSINESS' } } @@ -52,11 +52,13 @@ CCEffect %{ rasterizerState: cullMode: front properties: - tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } - mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, editor: { displayName: Albedo, type: color } } - albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } - alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } } - mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: diffuseColor, editor: { displayName: Albedo, type: color } } + albedoScale: { value: 1.0, target: diffuseFactor, editor: { displayName: diffuseFactor } } + alphaThreshold: { value: 0.5, editor: { parent: USE_ALPHA_TEST } } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + transparencyMap: { value: grey, editor: { displayName: TransparencyMap } } + transparencyFactor: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } - name: transparent passes: - vert: standard-vs @@ -78,10 +80,7 @@ CCEffect %{ CCProgram shared-ubos %{ uniform Constants { - vec4 tilingOffset; - vec4 albedo; - vec4 albedoScaleAndCutoff; - + vec4 tilingOffset; vec4 diffuseColor; vec4 specularColor; vec4 emissive; @@ -298,6 +297,7 @@ CCProgram standard-fs %{ #if USE_ALBEDO_MAP vec4 texColor = texture(albedoMap, TEXTURE_UV); texColor.rgb = SRGBToLinear(texColor.rgb); + texColor.a *= transparencyFactor; baseColor *= texColor; #else baseColor *= diffuseColor; @@ -305,11 +305,11 @@ CCProgram standard-fs %{ baseColor.rgb *= diffuseFactor; #if USE_TRANSPARENCY_MAP - baseColor.a = texture(transparencyMap, TEXTURE_UV).a * transparencyFactor; + baseColor.a = texture(transparencyMap, TEXTURE_UV).a; #endif #if USE_ALPHA_TEST - if (baseColor.a < albedoScaleAndCutoff.w) discard; + if (baseColor.a < alphaThreshold) discard; #endif #if CC_RECEIVE_SHADOW @@ -403,6 +403,11 @@ CCProgram shadow-caster-vs %{ out highp vec2 v_clip_depth; + #if USE_VERTEX_COLOR + in vec4 a_color; + out lowp vec4 v_color; + #endif + vec4 vert () { StandardVertInput In; CCVertInput(In); @@ -418,6 +423,10 @@ CCProgram shadow-caster-vs %{ v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw; #endif + #if USE_VERTEX_COLOR + v_color = a_color; + #endif + v_clip_depth = clipPos.zw; return clipPos; @@ -445,19 +454,23 @@ CCProgram shadow-caster-fs %{ uniform sampler2D transparencyMap; #endif - vec4 frag () { - vec4 baseColor = diffuseColor; - #if USE_ALBEDO_MAP - vec4 texColor = texture(albedoMap, TEXTURE_UV); - baseColor *= texColor; - #endif - - #if USE_TRANSPARENCY_MAP - baseColor.a = texture(transparencyMap, TEXTURE_UV).a * transparencyFactor; - #endif + #if USE_VERTEX_COLOR + in lowp vec4 v_color; + #endif + vec4 frag () { #if USE_ALPHA_TEST - if (baseColor.a < albedoScaleAndCutoff.w) discard; + float alpha = diffuseColor.a; + #if USE_VERTEX_COLOR + alpha *= v_color.a; + #endif + #if USE_ALBEDO_MAP + alpha *= texture(albedoMap, TEXTURE_UV).a * transparencyFactor; + #endif + #if USE_TRANSPARENCY_MAP + alpha = texture(transparencyMap, TEXTURE_UV).a; + #endif + if (alpha < alphaThreshold) discard; #endif highp float clipDepth = v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5; diff --git a/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta b/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta index a410f41320..36c2df10a9 100644 --- a/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta +++ b/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "f648964e-8d32-41fc-9ac9-7a1e714dd17b", diff --git a/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect b/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect index a7e51a0614..f0e0515a49 100644 --- a/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect +++ b/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect @@ -57,6 +57,8 @@ CCEffect %{ albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } } mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + alphaSource: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + alphaSourceMap: { value: grey, editor: { parent: USE_OPACITY_MAP } } - name: transparent passes: - vert: standard-vs @@ -225,6 +227,33 @@ CCProgram surface-fragment %{ return baseColor; } + #define CC_SURFACES_FRAGMENT_ALPHA_CLIP_ONLY + void SurfacesFragmentAlphaClipOnly() + { + #if USE_ALPHA_TEST + float alpha = albedo.a; + #if USE_ALBEDO_MAP + alpha = texture(albedoMap, TEXTURE_UV).a; + #endif + + #if ALPHA_SOURCE_IS_OPACITY + #if USE_OPACITY_MAP + alpha = 1.0 - texture(alphaSourceMap, TEXTURE_UV).ALPHA_SOURCE_CHANNEL; + #else + alpha = 1.0 - alphaSource; + #endif + #else + #if USE_OPACITY_MAP + alpha = texture(alphaSourceMap, TEXTURE_UV).ALPHA_SOURCE_CHANNEL; + #else + alpha = alphaSource; + #endif + #endif + + if (alpha < albedoScaleAndCutoff.w) discard; + #endif + } + #define CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL vec3 SurfacesFragmentModifyWorldNormal() { diff --git a/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta b/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta index 78dc909476..05e963698b 100644 --- a/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta +++ b/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "994bae8e-8bfc-4bc4-a32d-ad924f9917d0", diff --git a/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect index fff8749109..47c620cd7f 100644 --- a/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect +++ b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect @@ -10,7 +10,7 @@ CCEffect %{ mainTexture: { value: grey, target: albedoMap, editor: { displayName: DiffuseMap } } mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: diffuseColor, linear: true, editor: { displayName: DiffuseColor, type: color } } albedoScale: { value: 1.0, target: diffuseFactor, editor: { displayName: diffuseFactor } } - alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } + alphaThreshold: { value: 0.5, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } emissive: { value: [0.0, 0.0, 0.0, 1.0], linear: true, editor: { type: color } } emissiveMap: { value: grey } shininessExponentMap: { value: grey, editor: { parent: '!HAS_EXPORTED_GLOSSINESS' } } @@ -19,7 +19,7 @@ CCEffect %{ specularMap: { value: grey, editor: { parent: '!HAS_EXPORTED_METALLIC' } } specularFactor: { value: 1.0, editor: { parent: '!HAS_EXPORTED_METALLIC' } } transparencyMap: { value: grey, editor: { displayName: TransparencyMap } } - transparencyFactor: { value: 0.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + transparencyFactor: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } normalStrength: { value: 1.0, target: normalScale, editor: { displayName: bumpFactor, parent: USE_NORMAL_MAP, slide: true, range: [0, 5.0], step: 0.001 } } normalMap: { value: normal } @@ -52,11 +52,13 @@ CCEffect %{ rasterizerState: cullMode: front properties: - tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } - mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, editor: { displayName: Albedo, type: color } } - albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } - alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } } - mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: diffuseColor, editor: { displayName: Albedo, type: color } } + albedoScale: { value: 1.0, target: diffuseFactor, editor: { displayName: diffuseFactor } } + alphaThreshold: { value: 0.5, editor: { parent: USE_ALPHA_TEST } } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + transparencyMap: { value: grey, editor: { displayName: TransparencyMap } } + transparencyFactor: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } - name: transparent passes: - vert: standard-vs @@ -78,10 +80,7 @@ CCEffect %{ CCProgram shared-ubos %{ uniform Constants { - vec4 tilingOffset; - vec4 albedo; - vec4 albedoScaleAndCutoff; - + vec4 tilingOffset; vec4 diffuseColor; vec4 specularColor; vec4 emissive; @@ -221,21 +220,22 @@ CCProgram surface-fragment %{ return vec4(inSpecular, specularFactor); } - #define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY - vec4 SurfacesFragmentModifyBaseColorAndTransparency() + #define CC_SURFACES_FRAGMENT_ALPHA_CLIP_ONLY + void SurfacesFragmentAlphaClipOnly() { - //diffuse - vec4 baseColor = vec4(1.0); - - #if USE_TRANSPARENCY_MAP - baseColor.a = texture(transparencyMap, TEXTURE_UV).a * transparencyFactor; - #endif - - #if USE_ALPHA_TEST - if (baseColor.a < albedoScaleAndCutoff.w) discard; - #endif - - return baseColor; + #if USE_ALPHA_TEST + float alpha = diffuseColor.a; + #if USE_VERTEX_COLOR + alpha *= FSInput_vertexColor.a; + #endif + #if USE_ALBEDO_MAP + alpha *= texture(albedoMap, TEXTURE_UV).a * transparencyFactor; + #endif + #if USE_TRANSPARENCY_MAP + alpha = texture(transparencyMap, TEXTURE_UV).a; + #endif + if (alpha < alphaThreshold) discard; + #endif } #define CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL @@ -264,7 +264,7 @@ CCProgram surface-fragment %{ #include void SurfacesFragmentModifySharedData(inout SurfacesMaterialData surfaceData) { - vec4 baseColor = diffuseColor; + vec4 baseColor = vec4(1.0); #if USE_VERTEX_COLOR baseColor.rgb *= SRGBToLinear(FSInput_vertexColor.rgb); // use linear baseColor.a *= FSInput_vertexColor.a; @@ -272,9 +272,19 @@ CCProgram surface-fragment %{ #if USE_ALBEDO_MAP vec4 texColor = texture(albedoMap, TEXTURE_UV); texColor.rgb = SRGBToLinear(texColor.rgb); - baseColor = texColor; + texColor.a *= transparencyFactor; + baseColor *= texColor; #else - baseColor.rgb *= diffuseFactor; + baseColor *= diffuseColor; + #endif + baseColor.rgb *= diffuseFactor; + + #if USE_TRANSPARENCY_MAP + baseColor.a = texture(transparencyMap, TEXTURE_UV).a; + #endif + + #if USE_ALPHA_TEST + if (baseColor.a < alphaThreshold) discard; #endif vec4 specularColorAndFactor = getSpecularColorAndFactor(); @@ -311,7 +321,7 @@ CCProgram surface-fragment %{ #endif baseColor.rgb = albedo; - surfaceData.baseColor.rgb = baseColor.rgb; + surfaceData.baseColor = baseColor; surfaceData.specularIntensity = inSpecularIntensity * 0.5; surfaceData.roughness = 1.0 - inGlossiness; surfaceData.metallic = inMetallic; diff --git a/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta index 29279dae5d..36d84ac32b 100644 --- a/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta +++ b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "5b7d6814-90a6-4d9f-b7fd-410dca9de957", diff --git a/editor/assets/effects/editor/gizmo.effect.meta b/editor/assets/effects/editor/gizmo.effect.meta index d04dd02b1f..da110fe4b9 100644 --- a/editor/assets/effects/editor/gizmo.effect.meta +++ b/editor/assets/effects/editor/gizmo.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "9d6c6bde-2fe2-44ee-883b-909608948b04", diff --git a/editor/assets/effects/editor/grid-2d.effect.meta b/editor/assets/effects/editor/grid-2d.effect.meta index 0de78e4d9a..435d55ae85 100644 --- a/editor/assets/effects/editor/grid-2d.effect.meta +++ b/editor/assets/effects/editor/grid-2d.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "cb2c332a-fa5e-4235-a129-f011634bb7ad", diff --git a/editor/assets/effects/editor/grid-stroke.effect.meta b/editor/assets/effects/editor/grid-stroke.effect.meta index 29685ea2bb..a1571f491e 100644 --- a/editor/assets/effects/editor/grid-stroke.effect.meta +++ b/editor/assets/effects/editor/grid-stroke.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "4736e978-c8fa-449f-9cf6-fe0158ded9d7", diff --git a/editor/assets/effects/editor/grid.effect.meta b/editor/assets/effects/editor/grid.effect.meta index 78d9c604ea..ce5401dd4c 100644 --- a/editor/assets/effects/editor/grid.effect.meta +++ b/editor/assets/effects/editor/grid.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "ba35f02e-a81c-464c-bfc5-c788328da667", diff --git a/editor/assets/effects/editor/light.effect.meta b/editor/assets/effects/editor/light.effect.meta index 6d7e64d869..9a8c7639de 100644 --- a/editor/assets/effects/editor/light.effect.meta +++ b/editor/assets/effects/editor/light.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "e4e4cb19-8dd2-450d-ad20-1a818263b8d3", diff --git a/editor/assets/effects/editor/terrain-circle-brush.effect.meta b/editor/assets/effects/editor/terrain-circle-brush.effect.meta index 02be42bc8f..a777d57d97 100644 --- a/editor/assets/effects/editor/terrain-circle-brush.effect.meta +++ b/editor/assets/effects/editor/terrain-circle-brush.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "a3e72674-c38f-4336-a285-1826b1799cd7", diff --git a/editor/assets/effects/editor/terrain-image-brush.effect.meta b/editor/assets/effects/editor/terrain-image-brush.effect.meta index bdf635471b..5e5f19b091 100644 --- a/editor/assets/effects/editor/terrain-image-brush.effect.meta +++ b/editor/assets/effects/editor/terrain-image-brush.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "7a115de7-2d94-4620-8b89-766d7f8cbff9", diff --git a/editor/assets/effects/editor/terrain-select-brush.effect.meta b/editor/assets/effects/editor/terrain-select-brush.effect.meta index 63be517a0b..3509cb6b08 100644 --- a/editor/assets/effects/editor/terrain-select-brush.effect.meta +++ b/editor/assets/effects/editor/terrain-select-brush.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "9b4d3fa5-89bf-4715-b69a-dbbd1efaf6a5", diff --git a/editor/assets/effects/pipeline/bloom.effect.meta b/editor/assets/effects/pipeline/bloom.effect.meta index 4c2ea4ad1f..31ef120dd6 100644 --- a/editor/assets/effects/pipeline/bloom.effect.meta +++ b/editor/assets/effects/pipeline/bloom.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "28d6d6b8-3f66-4a73-9795-17a0852ba2d4", diff --git a/editor/assets/effects/pipeline/deferred-lighting.effect.meta b/editor/assets/effects/pipeline/deferred-lighting.effect.meta index 9b7398987d..d473a6e17d 100644 --- a/editor/assets/effects/pipeline/deferred-lighting.effect.meta +++ b/editor/assets/effects/pipeline/deferred-lighting.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "5d45aa00-e064-4938-b314-4265f0c2258c", diff --git a/editor/assets/effects/pipeline/planar-shadow.effect.meta b/editor/assets/effects/pipeline/planar-shadow.effect.meta index 602f81fcae..b41c449ee9 100644 --- a/editor/assets/effects/pipeline/planar-shadow.effect.meta +++ b/editor/assets/effects/pipeline/planar-shadow.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "9361fd90-ba52-4f84-aa93-6e878fd576ca", diff --git a/editor/assets/effects/pipeline/post-process.effect.meta b/editor/assets/effects/pipeline/post-process.effect.meta index 22332aa354..00fc08ae12 100644 --- a/editor/assets/effects/pipeline/post-process.effect.meta +++ b/editor/assets/effects/pipeline/post-process.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "ec8106fe-05bf-4e94-943c-e0d3b7bb5e45", diff --git a/editor/assets/effects/pipeline/skybox.effect b/editor/assets/effects/pipeline/skybox.effect index 0d74301934..239893f61c 100644 --- a/editor/assets/effects/pipeline/skybox.effect +++ b/editor/assets/effects/pipeline/skybox.effect @@ -3,6 +3,8 @@ CCEffect %{ - passes: - vert: sky-vs:vert frag: sky-fs:frag + properties: &props + environmentMap: { value: grey } priority: max - 10 rasterizerState: cullMode: none @@ -57,11 +59,21 @@ CCProgram sky-fs %{ in mediump vec4 viewDir; - vec4 frag () { + vec3 getEnvironment(samplerCube cubeMap) + { #if USE_RGBE_CUBEMAP - vec3 c = unpackRGBE(fragTextureLod(cc_environment, viewDir.xyz, 0.0)); + vec3 c = unpackRGBE(fragTextureLod(cubeMap, viewDir.xyz, 0.0)); #else - vec3 c = SRGBToLinear(fragTextureLod(cc_environment, viewDir.xyz, 0.0).rgb); + vec3 c = SRGBToLinear(fragTextureLod(cubeMap, viewDir.xyz, 0.0).rgb); + #endif + return c; + } + uniform samplerCube environmentMap; + vec4 frag () { + #if USE_REFLECTION_CUBEMAP + vec3 c = getEnvironment(environmentMap); + #else + vec3 c = getEnvironment(cc_environment); #endif return CCFragOutput(vec4(c * cc_ambientSky.w, 1.0)); } diff --git a/editor/assets/effects/pipeline/skybox.effect.meta b/editor/assets/effects/pipeline/skybox.effect.meta index 8772f85d25..bcfe4cc866 100644 --- a/editor/assets/effects/pipeline/skybox.effect.meta +++ b/editor/assets/effects/pipeline/skybox.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "511d2633-09a7-4bdd-ac42-f778032124b3", diff --git a/editor/assets/effects/pipeline/smaa.effect.meta b/editor/assets/effects/pipeline/smaa.effect.meta index 77044b5679..76f2381c99 100644 --- a/editor/assets/effects/pipeline/smaa.effect.meta +++ b/editor/assets/effects/pipeline/smaa.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "6624c63c-0e3d-4d5f-bd15-a7805b71c521", diff --git a/editor/assets/effects/pipeline/tonemap.effect.meta b/editor/assets/effects/pipeline/tonemap.effect.meta index 20ffa1b2d1..04ff4a614a 100644 --- a/editor/assets/effects/pipeline/tonemap.effect.meta +++ b/editor/assets/effects/pipeline/tonemap.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "31b152ff-f689-4082-a292-3eb5a0b33014", diff --git a/editor/assets/effects/surfaces/sky.effect b/editor/assets/effects/surfaces/sky.effect index 49e05e217d..aad126744a 100644 --- a/editor/assets/effects/surfaces/sky.effect +++ b/editor/assets/effects/surfaces/sky.effect @@ -6,6 +6,8 @@ CCEffect %{ passes: - vert: sky-vs frag: sky-fs + properties: &props + environmentMap: { value: grey } priority : max - 10 rasterizerState : cullMode : none @@ -25,18 +27,32 @@ CCProgram surface-vertex %{ }% CCProgram surface-fragment %{ + + uniform samplerCube environmentMap; + + vec3 getEnvironment(samplerCube cubeMap) + { + vec3 c = vec3(1.0); + vec3 normal = normalize(FSInput_worldNormal); + #if USE_RGBE_CUBEMAP + c *= unpackRGBE(fragTextureLod(cubeMap, normal.xyz, 0.0)); + #else + c *= SRGBToLinear(fragTextureLod(cubeMap, normal.xyz, 0.0).rgb); + #endif + return c; + } + #define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY vec4 SurfacesFragmentModifyBaseColorAndTransparency() { - vec3 c = vec3(1.0); - #if CC_USE_IBL - vec3 normal = normalize(FSInput_worldNormal); - #if USE_RGBE_CUBEMAP - c *= unpackRGBE(fragTextureLod(cc_environment, normal.xyz, 0.0)); - #else - c *= SRGBToLinear(fragTextureLod(cc_environment, normal.xyz, 0.0).rgb); + vec3 c = vec3(1.0); + #if CC_USE_IBL + #if USE_REFLECTION_CUBEMAP + c = getEnvironment(environmentMap); + #else + c = getEnvironment(cc_environment); + #endif #endif - #endif return vec4(c * cc_ambientSky.w, 1.0); } }% diff --git a/editor/assets/effects/surfaces/sky.effect.meta b/editor/assets/effects/surfaces/sky.effect.meta index e2aa6109bf..0178ca6f69 100644 --- a/editor/assets/effects/surfaces/sky.effect.meta +++ b/editor/assets/effects/surfaces/sky.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "6308c013-7d49-4160-9516-562dd205b480", diff --git a/editor/assets/effects/surfaces/standard.effect b/editor/assets/effects/surfaces/standard.effect index 54a73ad84b..3aa5030fe6 100644 --- a/editor/assets/effects/surfaces/standard.effect +++ b/editor/assets/effects/surfaces/standard.effect @@ -193,7 +193,7 @@ CCProgram surface-fragment %{ baseColor.rgb *= SRGBToLinear(FSInput_vertexColor.rgb); // use linear baseColor.a *= FSInput_vertexColor.a; #endif - + #if USE_ALBEDO_MAP vec4 texColor = texture(albedoMap, ALBEDO_UV); texColor.rgb = SRGBToLinear(texColor.rgb); @@ -208,10 +208,26 @@ CCProgram surface-fragment %{ return baseColor; } + #define CC_SURFACES_FRAGMENT_ALPHA_CLIP_ONLY + void SurfacesFragmentAlphaClipOnly() + { + #if USE_ALPHA_TEST + float alpha = albedo.ALPHA_TEST_CHANNEL; + #if USE_VERTEX_COLOR + alpha *= FSInput_vertexColor.a; + #endif + #if USE_ALBEDO_MAP + alpha = texture(albedoMap, ALBEDO_UV).ALPHA_TEST_CHANNEL; + #endif + + if (alpha < albedoScaleAndCutoff.w) discard; + #endif + } + #define CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL vec3 SurfacesFragmentModifyWorldNormal() { - vec3 normal = FSInput_worldNormal; + vec3 normal = FSInput_worldNormal; #if USE_NORMAL_MAP vec3 nmmp = texture(normalMap, NORMAL_UV).xyz - vec3(0.5); normal = CalculateNormalFromTangentSpace(nmmp, emissiveScaleParam.w, normal.xyz, FSInput_worldTangent, FSInput_mirrorNormal); @@ -223,8 +239,8 @@ CCProgram surface-fragment %{ #define CC_SURFACES_FRAGMENT_MODIFY_ANISOTROPY_PARAMS vec4 SurfacesFragmentModifyAnisotropyParams() { - float anisotropyRotation = anisotropyParam.y; - float anisotropyShape = anisotropyParam.x; + float anisotropyRotation = anisotropyParam.y; + float anisotropyShape = anisotropyParam.x; #if IS_ANISOTROPY && USE_ANISOTROPY_ROTATION_MAP anisotropyRotation = fract(anisotropyRotation + texture(anisotropyRotationMap, DEFAULT_UV).x); #endif diff --git a/editor/assets/effects/surfaces/standard.effect.meta b/editor/assets/effects/surfaces/standard.effect.meta index 466869b12f..d79f6cf3a5 100644 --- a/editor/assets/effects/surfaces/standard.effect.meta +++ b/editor/assets/effects/surfaces/standard.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "c8f66d17-351a-48da-a12c-0212d28575c4", diff --git a/editor/assets/effects/surfaces/toon.effect b/editor/assets/effects/surfaces/toon.effect index 380a66dbe8..5460bca9dd 100644 --- a/editor/assets/effects/surfaces/toon.effect +++ b/editor/assets/effects/surfaces/toon.effect @@ -171,28 +171,23 @@ CCProgram surface-fragment %{ #endif } - // only for render-to-shadow-map or misc usage - #define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY - vec4 SurfacesFragmentModifyBaseColorAndTransparency() + #define CC_SURFACES_FRAGMENT_ALPHA_CLIP_ONLY + void SurfacesFragmentAlphaClipOnly() { - vec4 color = baseColor; - #if USE_BASE_COLOR_MAP - vec4 texColor = texture(baseColorMap, FSInput_texcoord); - texColor.rgb = SRGBToLinear(texColor.rgb); - color *= texColor; - #endif - #if USE_ALPHA_TEST - if (color.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard; + float alpha = baseColor.ALPHA_TEST_CHANNEL; + #if USE_BASE_COLOR_MAP + alpha = texture(baseColorMap, FSInput_texcoord).ALPHA_TEST_CHANNEL; + #endif + + if (alpha < colorScaleAndCutoff.w) discard; #endif - - return color; } #define CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL vec3 SurfacesFragmentModifyWorldNormal() { - vec3 normal = FSInput_worldNormal; + vec3 normal = FSInput_worldNormal; #if USE_NORMAL_MAP vec3 nmmp = texture(normalMap, FSInput_texcoord).xyz - vec3(0.5); normal = CalculateNormalFromTangentSpace(nmmp, emissiveScaleAndStrenth.w, normal.xyz, FSInput_worldTangent, FSInput_mirrorNormal); diff --git a/editor/assets/effects/surfaces/toon.effect.meta b/editor/assets/effects/surfaces/toon.effect.meta index 1bdd20b5af..a40ba7fcb4 100644 --- a/editor/assets/effects/surfaces/toon.effect.meta +++ b/editor/assets/effects/surfaces/toon.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "9b20a514-6cc3-49de-b216-b6b863046249", diff --git a/editor/assets/effects/util/batched-unlit.effect.meta b/editor/assets/effects/util/batched-unlit.effect.meta index f6dbbb069e..5f0fe9590c 100644 --- a/editor/assets/effects/util/batched-unlit.effect.meta +++ b/editor/assets/effects/util/batched-unlit.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "f1556893-88b6-4c65-8c16-a5256ef3ad25", diff --git a/editor/assets/effects/util/profiler.effect.meta b/editor/assets/effects/util/profiler.effect.meta index 3673052970..a0bd1c8fd4 100644 --- a/editor/assets/effects/util/profiler.effect.meta +++ b/editor/assets/effects/util/profiler.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "871c3b6c-7379-419d-bda3-794b239ab90d", diff --git a/editor/assets/effects/util/sequence-anim.effect.meta b/editor/assets/effects/util/sequence-anim.effect.meta index 6c878d5975..2c4ed14748 100644 --- a/editor/assets/effects/util/sequence-anim.effect.meta +++ b/editor/assets/effects/util/sequence-anim.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "27cc5a0b-ec0b-4a67-98cf-b42d4fa971de", diff --git a/editor/assets/effects/util/splash-screen.effect.meta b/editor/assets/effects/util/splash-screen.effect.meta index 2b1b7c4e7d..02692371d7 100644 --- a/editor/assets/effects/util/splash-screen.effect.meta +++ b/editor/assets/effects/util/splash-screen.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.7", + "ver": "1.5.8", "importer": "effect", "imported": true, "uuid": "970b0598-bcb0-4714-91fb-2e81440dccd8", diff --git a/editor/assets/physics.meta b/editor/assets/physics.meta new file mode 100644 index 0000000000..030d815e47 --- /dev/null +++ b/editor/assets/physics.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "b80a0d17-b988-4ad3-b214-25df2694b0e7", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/physics/default-physics-material.pmtl b/editor/assets/physics/default-physics-material.pmtl new file mode 100644 index 0000000000..b50ff948b4 --- /dev/null +++ b/editor/assets/physics/default-physics-material.pmtl @@ -0,0 +1,10 @@ +{ + "__type__": "cc.PhysicMaterial", + "_name": "default-physics-material", + "_objFlags": 0, + "_native": "", + "_friction": 0.8, + "_rollingFriction": 0.1, + "_spinningFriction": 0.1, + "_restitution": 0.1 +} \ No newline at end of file diff --git a/editor/assets/physics/default-physics-material.pmtl.meta b/editor/assets/physics/default-physics-material.pmtl.meta new file mode 100644 index 0000000000..b47936b3f6 --- /dev/null +++ b/editor/assets/physics/default-physics-material.pmtl.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.0.1", + "importer": "physics-material", + "imported": true, + "uuid": "ba21476f-2866-4f81-9c4d-6e359316e448", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/engine-features/render-config.json b/editor/engine-features/render-config.json index 3f1b52bc1c..47c1977ee6 100644 --- a/editor/engine-features/render-config.json +++ b/editor/engine-features/render-config.json @@ -129,7 +129,7 @@ "wechatPlugin": true }, "occlusion-query": { - "default": ["occlusion-query"], + "default": [], "label": "i18n:ENGINE.features.occlusion_query.label", "description": "i18n:ENGINE.features.occlusion_query.description", "native": "USE_OCCLUSION_QUERY", @@ -137,7 +137,7 @@ "category": "3d" }, "geometry-renderer": { - "default": ["geometry-renderer"], + "default": [], "label": "i18n:ENGINE.features.geometry_renderer.label", "description": "i18n:ENGINE.features.geometry_renderer.description", "native": "USE_GEOMETRY_RENDERER", @@ -145,7 +145,7 @@ "category": "3d" }, "debug-renderer": { - "default": ["debug-renderer"], + "default": [], "label": "i18n:ENGINE.features.debug_renderer.label", "description": "i18n:ENGINE.features.debug_renderer.description", "native": "USE_DEBUG_RENDERER", @@ -222,6 +222,12 @@ "description": "i18n:ENGINE.features.marionette.description", "wechatPlugin": false, "category": "animation" + }, + "custom-pipeline": { + "default": [], + "label": "i18n:ENGINE.features.custom_pipeline.label", + "description": "i18n:ENGINE.features.custom_pipeline.description", + "wechatPlugin": false } }, "categories": { diff --git a/editor/i18n/en/assets.js b/editor/i18n/en/assets.js index ef48dcb1fe..a415a3a25a 100644 --- a/editor/i18n/en/assets.js +++ b/editor/i18n/en/assets.js @@ -15,12 +15,12 @@ module.exports = { save: 'Save', locate_asset: 'Locate in Assets Panel', 'label-atlas': { - SpriteFrameTip: 'SpriteFrame', + SpriteFrameTip: 'Sprite Frame', ItemWidthTip: 'Item Width', ItemHeightTip: 'Item Height', StartCharTip: 'Start Char', FontSizeTip: 'Font Size', - SpriteFrame: 'SpriteFrame', + SpriteFrame: 'Sprite Frame', ItemWidth: 'Item Width', ItemHeight: 'Item Height', StartChar: 'Start Char', @@ -32,17 +32,24 @@ module.exports = { }, erpTextureCube: { anisotropy: 'Anisotropy', + filterMode: 'Filter Mode', minFilter: 'Min Filter', magFilter: 'Mag Filter', + generateMipmaps: 'Generate Mipmaps', mipFilter: 'Mip Filter', + wrapMode: 'Wrap Mode', wrapModeS: 'Wrap Mode S', wrapModeT: 'Wrap Mode T', - anisotropyTip: 'Anisotropy', - minFilterTip: 'Min Filter', - magFilterTip: 'Mag Filter', - mipFilterTip: 'Mip Filter', - wrapModeSTip: 'Wrap Mode S', - wrapModeTTip: 'Wrap Mode T', + anisotropyTip: 'Maximum threshold for applying anisotropic filtering algorithms', + filterModeTip: 'Choose how Texture is filtered when apply 3d transformation', + minFilterTip: 'Minification filtering method', + magFilterTip: 'Magnification filtering method', + generateMipmapsTip: + 'Turn on this option to enable Mipmaps generation.Mipmaps are smaller versions of the original texture that are used to enhance performance and reduce rendering artifacts when objects are small in screen space', + mipFilterTip: 'Mip map filtering method', + wrapModeTip: 'Choose how Texture behaves when tiled. The default option is repeat', + wrapModeSTip: 'Texture addressing mode in S(U) direction', + wrapModeTTip: 'Texture addressing mode in T(V) direction', bakeReflectionConvolution: 'Bake Reflection Convolution', faceSize: { name: 'Face Size', @@ -58,9 +65,9 @@ module.exports = { loadPluginInWeb: 'Load In Web', loadPluginInEditor: 'Load In Editor', loadPluginInNative: 'Load In Native', - simulateGlobals: 'Simulate global variables', + simulateGlobals: 'Simulate Global Variables', executionScopeTip: 'Do not transpile or wrap this plugin script.', - executionScopeEnclosed: 'Simulate global variables', + executionScopeEnclosed: 'Simulate Global Variables', pluginTip: 'Import As Plugin', dependenciesTip: 'Dependencies', globalTip: 'Global', @@ -138,19 +145,26 @@ module.exports = { }, texture: { anisotropy: 'Anisotropy', - anisotropyTip: 'Anisotropy', + anisotropyTip: 'Maximum threshold for applying anisotropic filtering algorithms', + filterMode: 'Filter Mode', + filterModeTip: 'Choose how Texture is filtered when apply 3d transformation', minfilter: 'Min Filter', minfilterTip: 'Minification filtering method', magfilter: 'Mag Filter', magfilterTip: 'Magnification filtering method', + generateMipmaps: 'Generate Mipmaps', + generateMipmapsTip: + 'Turn on this option to enable Mipmaps generation.Mipmaps are smaller versions of the original texture that are used to enhance performance and reduce rendering artifacts when objects are small in screen space', mipfilter: 'Mip Filter', mipfilterTip: 'Mip map filtering method', + wrapMode: 'Wrap Mode', + wrapModeTip: 'Choose how Texture behaves when tiled. The default option is repeat', wrapModeS: 'Wrap Mode S', wrapModeSTip: 'Texture addressing mode in S(U) direction', wrapModeT: 'Wrap Mode T', wrapModeTTip: 'Texture addressing mode in T(V) direction', modeWarn: - "Warning: WebGL 1.0 platform doesn't support 'repeat' filter for non-power-of-two textures(runtime fallback to 'clamp-to-edge'), effectively disabling features like the 'tilingOffset' property in many materials.", + "Warning: WebGL 1.0 platform doesn't support 'Repeat' filter for non-power-of-two textures(runtime fallback to 'Clamp'), effectively disabling features like the 'tilingOffset' property in many materials.", }, fbx: { browse: 'Change Target', @@ -223,19 +237,19 @@ module.exports = { }, }, dumpMaterials: { - name: 'Dump materials', + name: 'Dump Materials', title: 'Whether to extract material assets out of embedded (sub)assets, so that the assets become editable.', }, materialDumpDir: { - name: 'Material dump directory', + name: 'Material Dump Directory', title: 'The directory to dump the materials.\nDefault to a direct sub-folder named `Materials_${model-file-base-name}` under current path.', }, useVertexColors: { - name: 'Use vertex colors', + name: 'Use Vertex Colors', title: 'Whether to use vertex colors. ', }, depthWriteInAlphaModeBlend: { - name: 'Depth-write if blending', + name: 'Depth-Write If Blending', title: 'Enable depth-write if the alpha mode is set to "BLEND". ', }, skipValidation: { @@ -248,7 +262,7 @@ module.exports = { ok: 'OK', }, ImageRemap: { - remapAs: 'Remap as', + remapAs: 'Remap As', original: 'Original', }, limitMaterialDumpDir: 'The extracted path needs to be scoped to the project path.', @@ -259,7 +273,7 @@ module.exports = { warn: 'Warning: Changing this property may break imported assets that have been using or referencing. ', }, disableMeshSplit: { - name: 'Disable mesh split', + name: 'Disable Mesh Split', title: 'Currently there is a joint-counting-based mesh splitting process during the
' + 'import pipeline to workaround the max uniform vector limit problem for real-time
' + @@ -283,36 +297,36 @@ module.exports = { name: 'Simplification', title: 'Simplification', si: { - name: 'Achieve the ratio R', - title: 'Achieve the ratio R', + name: 'Achieve The Ratio R', + title: 'Achieve The Ratio R', }, sa: { - name: 'Aggressively simplify', - title: 'Aggressively simplify', + name: 'Aggressively Simplify', + title: 'Aggressively Simplify', }, }, scene: { name: 'Scene', title: 'Scene', kn: { - name: 'Keep nodes transform', - title: 'Keep nodes transform', + name: 'Keep Nodes Transform', + title: 'Keep Nodes Transform', }, ke: { - name: 'Keep extras data', - title: 'Keep extras data', + name: 'Keep Extras Data', + title: 'Keep Extras Data', }, }, miscellaneous: { name: 'Miscellaneous', title: 'Miscellaneous', noq: { - name: 'Disable quantization', - title: 'Disable quantization', + name: 'Disable Quantization', + title: 'Disable Quantization', }, v: { - name: 'Verbose output', - title: 'Verbose output', + name: 'Verbose Output', + title: 'Verbose Output', }, }, // eslint-disable-next-line max-len @@ -406,7 +420,7 @@ module.exports = { paste_component_values: 'Paste Component Values', help_url: 'Help Document', - custom_script: 'Custom script', + custom_script: 'Custom Script', }, prefab: { diff --git a/editor/i18n/en/components.js b/editor/i18n/en/components.js index b4d0bcb53b..7b68a87dfc 100644 --- a/editor/i18n/en/components.js +++ b/editor/i18n/en/components.js @@ -22,7 +22,7 @@ module.exports = { 'When the new Prefab system is complete, it will be automatically migrated to the new Prefab system.', }, label: { - font_style_tooltip: "The style of the text, corresponding to the engine's isBold,isItalic,isUnderline", + font_style_tooltip: "The style of the text, corresponding to the engine's Bold, Italic, Underline", }, layer: { confirm_message: 'Do you want to set layer for all child objects as well?', diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index 1125566083..85d9a5c15c 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -170,7 +170,7 @@ module.exports = { }, sprite: { gray_scale: 'Whether turn on grayscale rendering mode', - sprite_frame: 'SpriteFrame image to use', + sprite_frame: 'Sprite Frame image to use', atlas: 'Atlas that the image belongs to', type: 'Rendering mode:\n - Simple: Modifying the size will stretch the image as a whole, which is suitable for sequence frame animation and normal images. \n' + @@ -224,7 +224,7 @@ module.exports = { hover_sprite: 'The sprite frame used when the button is in hovered over.', disabled_sprite: 'The sprite frame used when the button is in a disabled sate.', target: - "reference to the Sprite as target's background. When the state of the target changes the sprite's color or spriteFrame will be updated.", + "reference to the Sprite as target's background. When the state of the target changes the sprite's color or sprite frame will be updated.", click_events: 'By changing the number to 1 or more, you can set the receiver and the handler for each click event', }, canvas: { @@ -333,15 +333,15 @@ module.exports = { 'The turning velocity threshold for page turning\nWhen user swipes the PageView quickly, a velocity is calculated based on the swipe distance and time.\nIf the velocity is larger than the threshold, the page will be flipped', }, pageview_indicator: { - spriteFrame: 'The spriteFrame for each element', - direction: 'The location direction of PageViewIndicator', + spriteFrame: 'The sprite frame for each element', + direction: 'The location direction of page view indicator', cell_size: 'The cellSize for each element', spacing: 'The distance between each element', }, particleSystemRenderer: { renderMode: 'Particle render mode', - velocityScale: 'Lerp speed of particle along move direction when render mode is StrecthedBillboard', - lengthScale: 'Lerp length of particle along move direction when render mode is StrecthedBillboard', + velocityScale: 'Lerp speed of particle along move direction when render mode is Stretched Billboard', + lengthScale: 'Lerp length of particle along move direction when render mode is Stretched Billboard', mesh: 'Particle emit mesh', particleMaterial: 'Particle material', trailMaterial: 'Trail material of particle', @@ -354,7 +354,7 @@ module.exports = { color: 'Render color', }, rotationOvertimeModule: { - separateAxes: 'Set rotation of X, Y and Z respectively(not supported now)', + separateAxes: 'Set rotation of X, Y and Z respectively (not supported now)', x: 'Set rotation of X-axis', y: 'Set rotation of Y-axis', z: 'Set rotation of Z-axis', @@ -367,7 +367,7 @@ module.exports = { z: 'How particle size along Z-axis will change during its lifetime', }, textureAnimationModule: { - mode: 'Set mode of texture animation(support Grid only now)', + mode: 'Set mode of texture animation (support Grid only now)', numTilesX: 'Animation frames along X-axis', numTilesY: 'Animation frames along Y-axis', animation: 'Animation play mode', @@ -393,7 +393,7 @@ module.exports = { hover_sprite: 'The Sprite that is used when the Toggle is hovered over.', disabled_sprite: 'The Sprite that is used when the Toggle is in a disabled sate.', target: - "reference to the Sprite as Toggle's background. When the state of the button changes the sprite's color or spriteFrame will be updated.", + "reference to the Sprite as Toggle's background. When the state of the button changes the sprite's color or sprite frame will be updated.", isChecked: 'If this flag is true, the associated checkMark sprite component will be enabled, otherwise the checkMark will be disabled.', checkMark: 'The Sprite component displayed when Toggle is checked.', @@ -419,12 +419,12 @@ module.exports = { sphericalDirectionAmount: 'Lerp value between current emit direction and current move direction', randomPositionAmount: 'Random setting of particle move position(particle will appear beyond emit range)', radius: 'Radius of particle emitter', - radiusThickness: 'Radius thickness of particle emitter(invalid when emitter type is Box):\n - 0 emit from surface;\n - 1 emit from center;\n - 0 ~ 1 emit between center and surface', + radiusThickness: 'Radius thickness of particle emitter (invalid when emitter type is Box):\n - 0 emit from surface;\n - 1 emit from center;\n - 0 ~ 1 emit between center and surface', arcMode: 'Emit mode in the sector range', arcSpread: 'Space margin along arc', arcSpeed: 'Emit speed along arc', length: 'The axis length from the top section of the cone to the bottom', - boxThickness: 'Thickness of particle emitter(only valid when emitter type is Box)', + boxThickness: 'Thickness of particle emitter (only valid when emitter type is Box)', }, slider: { handle: 'The "handle" part of the slider', @@ -448,7 +448,7 @@ module.exports = { x: 'Velocity component along X-axis', y: 'Velocity component along Y-axis', z: 'Velocity component along Z-axis', - speedModifier: 'Speed ​​correction factor(CPU particle supported only)', + speedModifier: 'Speed ​​correction factor (CPU particle supported only)', space: 'Space where velocity calculated', }, widget: { @@ -461,10 +461,10 @@ module.exports = { align_h_center: 'Align to the horizontal midpoint of the target Node', align_v_center: 'Align to the vertical midpoint of the target Node', align_mode: 'Specifies the alignment mode of the Widget, which determines when the widget should refresh at runtime.', - top: 'Top edge postion in pixels. This can be a percentage and a positive or negative value', - bottom: 'Bottom edge postion in pixels. This can be a percentage and a positive or negative value', - left: 'Left edge postion in pixels. This can be a percentage and a positive or negative value', - right: 'Right edge postion in pixels. This can be a percentage and a positive or negative value', + top: 'Top edge position in pixels. This can be a percentage and a positive or negative value', + bottom: 'Bottom edge position in pixels. This can be a percentage and a positive or negative value', + left: 'Left edge position in pixels. This can be a percentage and a positive or negative value', + right: 'Right edge position in pixels. This can be a percentage and a positive or negative value', horizontal_center: 'Horizontal midpoint offset in pixels, This can be a percentage and a positive or negative value', vertical_center: 'Vertical midpoint offset in pixels, This can be a percentage and a positive or negative value', }, @@ -497,9 +497,9 @@ module.exports = { sync_tips: 'Synchronize the parameters in the File to Custom', }, editbox: { - string: 'The initial input text of EditBox.', - backgroundImage: 'The background image of EditBox.', - returnType: 'The keyboard return type of EditBox. This is useful for keyboard of mobile device.', + string: 'The initial input text of Edit Box.', + backgroundImage: 'The background image of Edit Box.', + returnType: 'The keyboard return type of Edit Box. This is useful for keyboard of mobile device.', input_flag: 'Specify the input flag: password or capitalize word. ', input_mode: 'Specify the input mode: multiline or single line.', font_size: 'The font size of input label.', @@ -524,7 +524,7 @@ module.exports = { clip: 'The local video clip', playOnAwake: 'Whether the video start playing automatically after loaded?', volume: 'The volume of the video.(0.0 ~ 1.0)', - mute: 'Mutes the VideoPlayer. Mute sets the volume=0, Un-Mute restore the original volume.', + mute: 'Mutes the VideoPlayer. Mute sets the volume = 0, Un-Mute restore the original volume.', playbackRate: 'The Video playback rate', loop: 'Whether the video should be played again at the end', keepAspectRatio: 'Whether keep the aspect ration of the original video.', @@ -543,16 +543,16 @@ module.exports = { horizontal_align: 'Horizontal alignment', vertical_align: 'Vertical alignment', font_size: 'Font size, in points', - font: 'Custom TTF font of RichText', - font_family:'Custom System font of RichText', + font: 'Custom TTF font of Rich Text', + font_family:'Custom System font of Rich Text', use_system_font: 'Using system font', cache_mode: 'The cache mode of label. This mode only supports system fonts.', max_width: 'The maximize width of RichText, pass 0 means not limit the maximize width.', line_height: 'Line height, in points', image_atlas: - 'The image atlas for the img tag. For each src value in the img tag, there should be a valid spriteFrame in the image atlas.', + 'The image atlas for the img tag. For each src value in the img tag, there should be a valid sprite frame in the image atlas.', handleTouchEvent: - 'Once checked, the RichText will block all input events (mouse and touch) within the bounding box of the node, preventing the input from penetrating into the underlying node.', + 'Once checked, the Rich Text will block all input events (mouse and touch) within the bounding box of the node, preventing the input from penetrating into the underlying node.', }, UICoordinateTracker: { target: 'Target node', @@ -610,8 +610,8 @@ module.exports = { preview: 'Play particle in edit mode', custom: 'If set custom to true, then use custom properties instead of read particle file', file: 'The plist file', - spriteFrame: 'SpriteFrame of Particle System', - texture: 'Texture of Particle System, readonly, please use spriteFrame to setup new texture', + spriteFrame: 'Sprite Frame of Particle System', + texture: 'Texture of Particle System, readonly, please use Sprite Frame to setup new texture', particleCount: 'Current quantity of particles that are being simulated', srcBlendFactor: 'Specify the source Blend Factor', dstBlendFactor: 'Specify the destination Blend Factor', @@ -640,7 +640,7 @@ module.exports = { rotationIsDir: 'Indicate whether the rotation of each particle equals to its direction. Only available in Gravity mode', startRadius: 'Starting radius and variation of the particles. Only available in Radius mode', endRadius: 'Ending radius and variation of the particles. Only available in Radius mode', - rotatePerS: 'Number of degress to rotate a particle around the source pos per second and variation. Only available in Radius mode', + rotatePerS: 'Number of degrees to rotate a particle around the source pos per second and variation. Only available in Radius mode', capacity: 'Maximum particle amount that the system can generate', scaleSpace: 'Scale space', startSize3D: 'Set start size of X, Y and Z respectively if true', @@ -656,11 +656,11 @@ module.exports = { startLifetime: 'Life time of the particle', duration: 'Particle duration', loop: 'Loop animation', - prewarm: 'Animation plays from the end state of last round(only valid when loop activated)', + prewarm: 'Animation plays from the end state of last round (only valid when loop activated)', simulationSpace: 'The particle space your calculation is done in', simulationSpeed: 'Update ratio of particles', playOnAwake: 'Play on awake', - gravityModifier: 'How much particles get affected by the gravity(only support on CPU)', + gravityModifier: 'How much particles get affected by the gravity (only support on CPU)', rateOverTime: 'Number of particles emitted per second', rateOverDistance: 'Number of particles emitted per unit distance', bursts: 'Emit a given number of particles at a certain point in time', @@ -669,14 +669,14 @@ module.exports = { sizeOvertimeModule: 'Particle size module', velocityOvertimeModule: 'Particle velocity module', forceOvertimeModule: 'Particle acceleration module', - limitVelocityOvertimeModule: 'Particle velocity limitation module(only support on CPU)', + limitVelocityOvertimeModule: 'Particle velocity limitation module (only support on CPU)', rotationOvertimeModule: 'Particle rotation module', textureAnimationModule: 'Texture animation module', - trailModule: 'Trail module(only support on CPU)', + trailModule: 'Trail module (only support on CPU)', renderer: 'Particle render module', - renderCulling: 'Whether to enable the particle culling feature. If enabled, a particle emitter bounding box will be generated, and the particle emitter will be culled if the bounding box is not in the visible range of the camera. Please refer to the cullingMode option below for the behavior settings after particle culling.', - cullingMode: 'Sets the behavior of the particle emitter after it has been culled. The available options include Pause, Pause and Catchup, and Always Simulate.\nWhen the Pause is selected, the particle will pause the simulation if the particle emitter bounding box is not in the camera\'s visible range. If it resumes visibility, the particle will continue simulating at the time of last pause.\nWhen the Pause and Catchup is selected, if the particle emitter bounding box is not in the camera\'s visible range, the particle will pause the simulation. If visible again, the particle will start simulating at the current time.\nWhen the Always Simulate is selected, the particle will keep simulating regardless of whether the particle emitter bounding box is in the camera\'s visible range, but will not render when it is not in the camera\'s visible range.', - alignSpace: 'Particle alignment space, the available options include View Space, World Space and Local Space.\nWhen the View Space is selected, the rotation direction of the particle mesh will follow the camera\'s view direction.\nWhen the World Space is selected, the direction of the particle mesh will use the world space rotation direction of the node where the particle emitter is located.\nWhen the Local Space is selected, the particle mesh will use the local space rotation direction of the node where the particle emitter is located.', + renderCulling: 'Whether to enable the particle culling feature. \nIf enabled, a particle emitter bounding box will be generated, and the particle emitter will be culled if the bounding box is not in the visible range of the camera. Please refer to the cullingMode option below for the behavior settings after particle culling.', + cullingMode: 'Sets the behavior of the particle emitter after it has been culled. \nThe available options include Pause, Pause and Catchup, and Always Simulate.\nWhen the Pause is selected, the particle will pause the simulation if the particle emitter bounding box is not in the camera\'s visible range. If it resumes visibility, the particle will continue simulating at the time of last pause.\nWhen the Pause and Catchup is selected, if the particle emitter bounding box is not in the camera\'s visible range, the particle will pause the simulation. If visible again, the particle will start simulating at the current time.\nWhen the Always Simulate is selected, the particle will keep simulating regardless of whether the particle emitter bounding box is in the camera\'s visible range, but will not render when it is not in the camera\'s visible range.', + alignSpace: 'Particle alignment space, the available options include View Space. \nWorld Space and Local Space.\nWhen the View Space is selected, the rotation direction of the particle mesh will follow the camera\'s view direction.\nWhen the World Space is selected, the direction of the particle mesh will use the world space rotation direction of the node where the particle emitter is located.\nWhen the Local Space is selected, the particle mesh will use the local space rotation direction of the node where the particle emitter is located.', aabbHalfX: 'Half width of the emitter bounding box', aabbHalfY: 'Half height of the emitter bounding box', aabbHalfZ: 'Half length of the emitter bounding box', @@ -687,7 +687,7 @@ module.exports = { spriteFrame: 'The mask image', inverted: 'The Reverse mask (Not supported Canvas Mode)', alphaThreshold: - 'The alpha threshold,The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold (Not supported Canvas Mode)', + 'The alpha threshold, The content is drawn only where the stencil have pixel with alpha greater than the alphaThreshold (Not supported Canvas Mode)', segements: 'The segements for ellipse mask', }, physics: { @@ -695,13 +695,13 @@ module.exports = { enabledContactListener: 'Should enabled contact listener. When a collision is trigger, the collision callback will only be called when enabled contact listener.', bullet: 'Is this a fast moving body that should be prevented from tunneling through other moving bodies?', - type: 'Rigidbody type : Static, Kinematic, Dynamic or Animated.', + type: 'Rigid body type : Static, Kinematic, Dynamic or Animated.', allowSleep: 'Set this flag to false if this body should never fall asleep. Note that this increases CPU usage.', gravityScale: 'Scale the gravity applied to this body.', linearDamping: - 'Linear damping is use to reduce the linear velocity. The damping parameter can be larger than 1, but the damping effect becomes sensitive to the time step when the damping parameter is large.', + 'Linear damping is use to reduce the linear velocity.\nThe damping parameter can be larger than 1, but the damping effect becomes sensitive to the time step when the damping parameter is large.', angularDamping: - 'Angular damping is use to reduce the angular velocity. The damping parameter can be larger than 1 but the damping effect becomes sensitive to the time step when the damping parameter is large.', + 'Angular damping is use to reduce the angular velocity.\nThe damping parameter can be larger than 1 but the damping effect becomes sensitive to the time step when the damping parameter is large.', linearVelocity: "The linear velocity of the body's origin in world co-ordinates", angularVelocity: 'The angular velocity of the body.', fixedRotation: 'Should this body be prevented from rotating?', @@ -712,31 +712,31 @@ module.exports = { sensor: 'A sensor collider collects contact information but never generates a collision response', friction: 'The friction coefficient, usually in the range [0,1].', restitution: 'The restitution (elasticity) usually in the range [0,1].', - anchor: 'The anchor of the rigidbody.', - connectedAnchor: 'The anchor of the connected rigidbody.', - connectedBody: 'The rigidbody to which the other end of the joint is attached.', + anchor: 'The anchor of the rigid body.', + connectedAnchor: 'The anchor of the connected rigid body.', + connectedBody: 'The rigid body to which the other end of the joint is attached.', collideConnected: 'Should the two rigid bodies connected with this joint collide with each other?', distance: 'The distance separating the two ends of the joint.', frequency: 'The spring frequency.', dampingRatio: 'The damping ratio.', - linearOffset: 'The linear offset from connected rigidbody to rigidbody.', - angularOffset: 'The angular offset from connected rigidbody to rigidbody.', - maxForce: 'The maximum force can be applied to rigidbody.', - maxTorque: 'The maximum torque can be applied to rigidbody.', + linearOffset: 'The linear offset from connected rigid body to rigid body.', + angularOffset: 'The angular offset from connected rigid body to rigid body.', + maxForce: 'The maximum force can be applied to rigid body.', + maxTorque: 'The maximum torque can be applied to rigid body.', correctionFactor: 'The position correction factor in the range [0,1].', - mouseRegion: "The node used to register touch evnet. If this is null, it will be the joint's node.", - target: 'The target point. The mouse joint will move choosed rigidbody to target point.', - localAxisA: 'The local joint axis relative to rigidbody.', + mouseRegion: "The node used to register touch event. If this is null, it will be the joint's node.", + target: 'The target point. The mouse joint will move chosen rigid body to target point.', + localAxisA: 'The local joint axis relative to rigid body.', enableLimit: 'Enable joint distance limit?', enableMotor: 'Enable joint motor?', lowerLimit: 'The lower joint limit.', upperLimit: 'The upper joint limit.', - maxMotorForce: 'The maxium force can be applied to rigidbody to rearch the target motor speed.', + maxMotorForce: 'The maximum force can be applied to rigid body to reach the target motor speed.', motorSpeed: 'The expected motor speed.', referenceAngle: 'The reference angle. An angle between bodies considered to be zero for the joint angle.', lowerAngle: 'The lower angle.', upperAngle: 'The upper angle.', - maxMotorTorque: 'The maxium torque can be applied to rigidbody to rearch the target motor speed.', + maxMotorTorque: 'The maximum torque can be applied to rigid body to reach the target motor speed.', maxLength: 'The max length.', offset: 'Position offset', size: 'Box size', @@ -747,11 +747,11 @@ module.exports = { }, block_input_events: { brief_help: - 'This component will block all input events, preventing the input from penetrating to other nodes below the screen, typically for the background of the top-level UI of the screen.', + 'This component will block all input events, \npreventing the input from penetrating to other nodes below the screen, \ntypically for the background of the top-level UI of the screen.', }, tiledtile: { - row: 'Specify the TiledTile horizontal coordinate,use map tile as the unit.', - column: 'Specify the TiledTile vertical coordinate,use map tile as the unit.', + row: 'Specify the TiledTile horizontal coordinate, use map tile as the unit.', + column: 'Specify the TiledTile vertical coordinate, use map tile as the unit.', gid: 'Specify the TiledTile gid.', layer: 'Specify which TiledLayer the TiledTile belong to.', }, @@ -900,8 +900,8 @@ module.exports = { description: "Spine Animation support.", }, dragon_bones: { - label: "DragonBones", - description: "DragonBones support.", + label: "Dragon Bones", + description: "Dragon Bones support.", }, animation: { label: "Basic Animation", @@ -915,6 +915,10 @@ module.exports = { label: "Marionette Animation System", description: "Enable the Marionette animation system", }, + custom_pipeline: { + label: "Custom Render Pipeline (Experimental)", + description: "Enable custom render pipeline", + }, }, renderable_2d: { srcBlendFactor: 'Specifies the source blend mode, it will clone a new material object.', @@ -965,7 +969,7 @@ module.exports = { plane_normal: 'The normal to the plane in the local coordinate system', plane_constant: 'The distance of the plane moving along the normal from the origin in the local coordinate system', mesh_mesh: 'Mesh resources used by collider', - mesh_convex: 'Whether to use convex hull approximation instead, the number of vertices should be less than 255, and the dynamics can be supported after turning on', + mesh_convex: 'Whether to use convex hull approximation instead, \nthe number of vertices should be less than 255, \nand the dynamics can be supported after turning on', terrain_terrain: 'Terrain resources used by collider', simplex_shapeType: 'Simplex type, point, line, triangle, tetrahedron', simplex_vertex0: 'Vertex 0 of the shape', diff --git a/editor/i18n/zh/assets.js b/editor/i18n/zh/assets.js index 83878c106b..37a981c676 100644 --- a/editor/i18n/zh/assets.js +++ b/editor/i18n/zh/assets.js @@ -15,12 +15,12 @@ module.exports = { save: '保存', locate_asset: '资源面板上定位该资源', 'label-atlas': { - SpriteFrameTip: 'SpriteFrame', + SpriteFrameTip: 'Sprite Frame', ItemWidthTip: 'Item Width', ItemHeightTip: 'Item Height', StartCharTip: 'Start Char', FontSizeTip: 'Font Size', - SpriteFrame: 'SpriteFrame', + SpriteFrame: 'Sprite Frame', ItemWidth: 'Item Width', ItemHeight: 'Item Height', StartChar: 'Start Char', @@ -32,22 +32,28 @@ module.exports = { }, erpTextureCube: { anisotropy: 'Anisotropy', + filterMode: '过滤模式', minFilter: 'Min Filter', magFilter: 'Mag Filter', + generateMipmaps: '生成 Mipmaps', mipFilter: 'Mip Filter', + wrapMode: '拼接模式', wrapModeS: 'Wrap Mode S', wrapModeT: 'Wrap Mode T', - anisotropyTip: 'Anisotropy', - minFilterTip: 'Min Filter', - magFilterTip: 'Mag Filter', - mipFilterTip: 'Mip Filter', - wrapModeSTip: 'Wrap Mode S', - wrapModeTTip: 'Wrap Mode T', + anisotropyTip: '应用各向异性过滤算法的最大阈值', + filterModeTip: '选择贴图在应用三维图形变换时的过滤模式', + minFilterTip: '缩小贴图时采用的过滤算法', + magFilterTip: '放大贴图时采用的过滤算法', + generateMipmapsTip: + '勾选此选项以自动生成 Mipmaps。Mipmaps 是一系列缩小到不同尺寸的原贴图,在物体占屏幕空间小的时候使用以提升性能和减少闪烁', + mipFilterTip: '采用多级纹理时的过滤算法', + wrapModeTip: '选择在贴图小于填充空间时的填充方式,默认模式为循环', + wrapModeSTip: '像素对纹理在 S(U)方向上的映射模式', + wrapModeTTip: '像素对纹理在 T(V)方向上的映射模式', bakeReflectionConvolution: 'Bake Reflection Convolution', faceSize: { name: 'Face Size', - title: - '每个面的尺寸。如果未指定或指定为0,将使用默认尺寸——最接近贴图宽度 / 4 的2次幂。', + title: '每个面的尺寸。如果未指定或指定为0,将使用默认尺寸——最接近贴图宽度 / 4 的2次幂。', }, }, javascript: { @@ -69,7 +75,7 @@ module.exports = { loadPluginInWebTip: 'Load In Web', loadPluginInEditorTip: 'Load In Editor', loadPluginInNativeTip: 'Load In Native', - simulateGlobalsTip: 'Simulate global variables', + simulateGlobalsTip: 'Simulate Global Variables', }, scene: { asyncLoadAssets: '异步加载', @@ -129,29 +135,36 @@ module.exports = { edit: 'Edit', editTip: '编辑', meshType: 'Mesh Type', - meshTypeTip: 'SpriteFrame 生成的网格类型', + meshTypeTip: 'Sprite Frame 生成的网格类型', pixelsToUnit: 'Pixels To Unit', - pixelsToUnitTip: 'SpriteFrame 像素对应世界空间内单位长度的比例尺', + pixelsToUnitTip: 'Sprite Frame 像素对应世界空间内单位长度的比例尺', pivotX: 'Pivot X', - pivotXTip: 'SpriteFrame 本地坐标系原点的 X 轴位置', + pivotXTip: 'Sprite Frame 本地坐标系原点的 X 轴位置', pivotY: 'Pivot Y', - pivotYTip: 'SpriteFrame 本地坐标系原点的 Y 轴位置', + pivotYTip: 'Sprite Frame 本地坐标系原点的 Y 轴位置', }, texture: { anisotropy: 'Anisotropy', anisotropyTip: '应用各向异性过滤算法的最大阈值', + filterMode: '过滤模式', + filterModeTip: '选择贴图在应用三维图形变换时的过滤模式', minfilter: 'Min Filter', minfilterTip: '缩小贴图时采用的过滤算法', magfilter: 'Mag Filter', magfilterTip: '放大贴图时采用的过滤算法', + generateMipmaps: '生成 Mipmaps', + generateMipmapsTip: + '勾选此选项以自动生成 Mipmaps。Mipmaps 是一系列缩小到不同尺寸的原贴图,在物体占屏幕空间小的时候使用以提升性能和减少闪烁', mipfilter: 'Mip Filter', mipfilterTip: '采用多级纹理时的过滤算法', + wrapMode: '拼接模式', + wrapModeTip: '选择在贴图小于填充空间时的填充方式,默认模式为循环', wrapModeS: 'Wrap Mode S', wrapModeSTip: '像素对纹理在 S(U)方向上的映射模式', wrapModeT: 'Wrap Mode T', wrapModeTTip: '像素对纹理在 T(V)方向上的映射模式', modeWarn: - '警告:WebGL 1.0 平台不支持非 2 次幂贴图的 repeat 过滤模式,运行时会自动改为 clamp-to-edge 模式,这会使材质的 tilingOffset 等属性完全失效。', + '警告:WebGL 1.0 平台不支持非 2 次幂贴图的 Repeat 过滤模式,运行时会自动改为 Clamp 模式,这会使材质的 tilingOffset 等属性完全失效。', }, fbx: { browse: '更换贴图', @@ -237,7 +250,7 @@ module.exports = { }, depthWriteInAlphaModeBlend: { name: '混合模式下的深度写入', - title: '当 alpha 模式为 "BLEND" 时开启深度写入。', + title: '当 Alpha 模式为 "BLEND" 时开启深度写入。', }, skipValidation: { name: '跳过验证', @@ -245,7 +258,7 @@ module.exports = { }, }, addEvent: { - shouldSave: '新建的 clip 需要先提交修改后,才能添加/编辑事件', + shouldSave: '新建的 Clip 需要先提交修改后,才能添加/编辑事件', ok: '知道了', }, ImageRemap: { @@ -262,10 +275,10 @@ module.exports = { disableMeshSplit: { name: '是否禁用 Mesh 拆分', title: - '为了解决实时骨骼动画系统下 uniform vector 数量限制问题,
' + + '为了解决实时骨骼动画系统下 Uniform Vector 数量限制问题,
' + '目前在资源导入期会根据骨骼数量做拆分,这会对其他系统也产生影响。
' + '如果确定不会使用实时计算模式 (对应 SkeletalAnimation 组件的
' + - 'useBakedAnimation 选项未勾选时),可以勾选此项以提升性能。
' + + 'UseBakedAnimation 选项未勾选时),可以勾选此项以提升性能。
' + '但注意改变此选项会影响生成的 prefab 内容,需要对应更新场景中的引用。
' + '后续重构会移除此流程。', }, @@ -282,36 +295,36 @@ module.exports = { name: 'Simplification', title: 'Simplification', si: { - name: 'Achieve the ratio R', - title: 'Achieve the ratio R', + name: 'Achieve The Ratio R', + title: 'Achieve The Ratio R', }, sa: { - name: 'Aggressively simplify', - title: 'Aggressively simplify', + name: 'Aggressively Simplify', + title: 'Aggressively Simplify', }, }, scene: { name: 'Scene', title: 'Scene', kn: { - name: 'Keep nodes transform', - title: 'Keep nodes transform', + name: 'Keep Nodes Transform', + title: 'Keep Nodes Transform', }, ke: { - name: 'Keep extras data', - title: 'Keep extras data', + name: 'Keep Extras Data', + title: 'Keep Extras Data', }, }, miscellaneous: { name: 'Miscellaneous', title: 'Miscellaneous', noq: { - name: 'Disable quantization', - title: 'Disable quantization', + name: 'Disable Quantization', + title: 'Disable Quantization', }, v: { - name: 'Verbose output', - title: 'Verbose output', + name: 'Verbose Output', + title: 'Verbose Output', }, }, warn: '警告:优化后,网格资源的数量和名称会发生改变,这将会造成组件引用的资源丢失,请及时手动更新;(另外,对于模型资源中预生成的预制体,资源同步机制会自动更新)', @@ -349,11 +362,11 @@ module.exports = { wrapModeT: 'Wrap Mode T', wrapModeTTip: 'Wrap Mode T', modeWarn: - '警告:WebGL 1.0 平台不支持非 2 次幂贴图的 repeat 过滤模式,运行时会自动改为 clamp-to-edge 模式,这会使材质的 tilingOffset 等属性完全失效。', + '警告:WebGL 1.0 平台不支持非 2 次幂贴图的 Repeat 过滤模式,运行时会自动改为 Clamp-To-Edge 模式,这会使材质的 Tiling Offset 等属性完全失效。', }, material: { - 'fail-to-load-custom-inspector': 'material: 自定义 effect {effect} 的 inspector 加载失败', - 'illegal-inspector-url': "Inspector的路径不合法", + 'fail-to-load-custom-inspector': 'Material: 自定义 Effect {effect} 的 Inspector 加载失败', + 'illegal-inspector-url': "Inspector 的路径不合法", }, animationGraph: { edit: '编辑', @@ -362,7 +375,7 @@ module.exports = { importSkeleton: '导入骨骼', clearAllNodes: '清空', clearAllNodesWarn: '确定清空所有遮罩数据吗?', - illegalFbx: '导入骨骼失败:此 fbx 文件不含有 prefab 子资源。', + illegalFbx: '导入骨骼失败:此 FBX 文件不含有 Prefab 子资源。', nodeEnableTip: '是否启用该节点及其子孙节点
按住 Alt + 点击,只切换自身的状态。', }, multipleWarning: '不支持此类型资源的多选编辑', diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index f75c669399..f4855446b4 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -102,7 +102,7 @@ module.exports = { saturation: '阴影饱和度,建议设置为 1.0。若需要减小方向光阴影的饱和程度,推荐通过增加环境光来实现,而不是调节该值。', pcf: '开启软阴影,目前支持 HARD(硬采样)、SOFT(4 倍采样)、SOFT_2X(9 倍采样)类型', bias: '增加深度偏移值(世界空间单位)可以有效消除阴影摩尔纹,但是过大的值可能造成漏光现象', - normalBias: '法线深度偏移值(世界空间单位),可以消除物体表面朝向平行于阳光方向的阴影摩尔纹,防止曲面出现锯齿状;但是过大的值可能会造成阴影位置偏差', + normalBias: '法线深度偏移值(世界空间单位),可以消除物体表面朝向平行于阳光方向的阴影摩尔纹,\n防止曲面出现锯齿状;但是过大的值可能会造成阴影位置偏差', shadowMapSize: '阴影贴图分辨率,目前支持 Low_256x256、Medium_512x512、High_1024x1024、Ultra_2048x2048 四种精度的纹理', fixedArea: '切换固定区域和 CSM 模式。固定区域是一种旧模式,我们并不推荐使用。勾选该项则开启 CSM 模式,该模式下阴影会跟随方向光节点的位置,在方向光包围盒附近分布,而非跟随相机。', near: '固定区域开始值', @@ -116,7 +116,7 @@ module.exports = { default_clip: '在勾选自动播放或调用 play() 时默认播放的动画 clip。', clips: '通过脚本可以访问并播放的 AnimationClip 列表', play_on_load: '是否在运行游戏后自动播放默认动画 clip。', - use_baked_animation: '是否使用预烘焙动画,默认启用,可以大幅提高运行效时率,但所有动画效果会被彻底固定,不支持任何形式的编辑', + use_baked_animation: '是否使用预烘焙动画,默认启用,可以大幅提高运行效时率,\n但所有动画效果会被彻底固定,不支持任何形式的编辑', sockets: '当前动画组件维护的挂点数组。要挂载自定义节点到受动画驱动的骨骼上,必须先在此注册挂点', }, audio: { @@ -168,25 +168,25 @@ module.exports = { sprite: { gray_scale: '是否开启灰度渲染模式', atlas: '图片资源所属的 Atlas 图集资源', - sprite_frame: '渲染 Sprite 使用的 SpriteFrame 图片资源', + sprite_frame: '渲染 Sprite 使用的 Sprite Frame 图片资源', type: '渲染模式:\n - 普通(Simple):修改尺寸会整体拉伸图像,适用于序列帧动画和普通图像 \n' + - '- 九宫格(Sliced):修改尺寸时四个角的区域不会拉伸,适用于 UI 按钮和面板背景 \n' + - '- 平铺(Tiled):修改尺寸时会不断平铺原始大小的图片 \n' + - '- 填充(Filled):设置一定的填充起始位置和方向,能够以一定比率剪裁显示图片', + '- 九宫格 Sliced 修改尺寸时四个角的区域不会拉伸,适用于 UI 按钮和面板背景 \n' + + '- 平铺 Tiled 修改尺寸时会不断平铺原始大小的图片 \n' + + '- 填充 Filled 设置一定的填充起始位置和方向,能够以一定比率剪裁显示图片', original_size: '是否使用图片资源的原始尺寸作为 Sprite 节点的 size', edit_button: '编辑', select_button: '选择', select_tooltip: '选择 Atlas 中的其他 SpriteFrame', edit_tooltip: '打开 Sprite 编辑器,设置九宫格等数据', - fill_type: '填充方向,可以选择横向(Horizontal),纵向(Vertical)和扇形(Radial)三种方向', + fill_type: '填充方向,可以选择横向 Horizontal,纵向 Vertical 和扇形 Radial 三种方向', fill_center: '扇形填充时,指定扇形的中心点,取值范围 0 ~ 1', fill_start: '填充起始位置,输入一个 0 ~ 1 之间的小数表示起始位置的百分比', fill_range: '填充总量,取值范围 0 ~ 1 指定显示图像范围的百分比', src_blend_factor: '混合显示两张图片时,源图片的取值模式', dst_blend_factor: '混合显示两张图片时,目标图片的取值模式', size_mode: - '指定 Sprite 所在节点的尺寸,CUSTOM 表示自定义尺寸,TRIMMED 表示取原始图片剪裁透明像素后的尺寸,RAW 表示取原始图片未剪裁的尺寸', + '指定 Sprite 所在节点的尺寸\nCUSTOM 表示自定义尺寸\nTRIMMED 表示取原始图片剪裁透明像素后的尺寸\nRAW 表示取原始图片未剪裁的尺寸', trim: '节点约束框内是否包括透明像素区域,勾选此项会去除节点约束框内的透明区域', }, UIOpacity: { @@ -214,7 +214,7 @@ module.exports = { duration: '按钮颜色变化或者缩放变化的过渡时间', zoom_scale: '当用户点击按钮后,按钮会缩放到一个值,这个值等于 Button 原始 scale * zoomScale, zoomScale 可以为负数', auto_gray_effect: - '如果这个标记为 true,当 button 的 interactable 属性为 false 的时候,会使用内置 shader 让 button 的 target 节点的 sprite 组件变灰', + '如果这个标记为 true,当 button 的 interactable 属性为 false 的时候,\n会使用内置 shader 让 button 的 target 节点的 sprite 组件变灰', normal_sprite: '普通状态的按钮背景图资源', pressed_sprite: '按下状态的按钮背景图资源', hover_sprite: '悬停状态的按钮背景图资源', @@ -223,10 +223,10 @@ module.exports = { click_events: '按钮点击事件的列表。先将数量改为1或更多,就可以为每个点击事件设置接受者和处理方法', }, canvas: { - camera: '2D渲染相机', + camera: '2D 渲染相机', align: '自动为 camera 计算参数', design_resolution: - '设计分辨率是游戏在设计时使用的分辨率参考,以像素为单位,通过下面的适配策略,可以在不同分辨率的设备上按照一定的方式对 Canvas 进行整体缩放来适配。', + '设计分辨率是游戏在设计时使用的分辨率参考,以像素为单位,通过下面的适配策略,\n可以在不同分辨率的设备上按照一定的方式对 Canvas 进行整体缩放来适配。', fit_height: '自动缩放 Canvas 使设计分辨率的高度充满设备屏幕的高度', fit_width: '自动缩放 Canvas 使设计分辨率的宽度充满设备屏幕的宽度', }, @@ -299,18 +299,18 @@ module.exports = { scrollbar: { handle: '作为当前滚动区域位置显示的滑块 Sprite', direction: 'ScrollBar的滚动方向', - auto_hide: '是否在没有滚动动作时自动隐藏 ScrollBar', - auto_hide_time: '没有滚动动作后经过多久会自动隐藏\n注意:只有当 “enableAutoHide” 为 true 时,才有效', + auto_hide: '是否在没有滚动动作时自动隐藏 Scroll Bar', + auto_hide_time: '没有滚动动作后经过多久会自动隐藏\n注意:只有当 Enable Auto Hide 为 true 时才有效', }, scrollview: { content: '包含可滚动展示内容的节点引用', horizontal: '是否开启水平滚动', vertical: '是否开启垂直滚动', inertia: '是否开启滚动惯性', - brake: '开启惯性后,在用户停止触摸后滚动多快停止,0表示永不停止,1表示立刻停止', + brake: '开启惯性后,在用户停止触摸后滚动多快停止,0 表示永不停止,1 表示立刻停止', elastic: '是否允许滚动内容超过边界,并在停止触摸后回弹', - horizontal_bar: '水平滚动的 ScrollBar', - vertical_bar: '垂直滚动的 ScrollBar', + horizontal_bar: '水平滚动的滚动条', + vertical_bar: '垂直滚动的滚动条', bounceDuration: '回弹持续的时间,0 表示将立即反弹', scrollEvents: '滚动视图的事件回调函数', cancelInnerEvents: '滚动行为是否会取消子节点上注册的触摸事件', @@ -319,7 +319,7 @@ module.exports = { sizeMode: '页面视图中每个页面大小类型', direction: '页面视图滚动方向', scrollThreshold: '滚动临界值,默认单位百分比,当拖拽超出该数值时,松开会自动滚动下一页,小于时则还原', - pageTurningEventTiming: '设置 PageView 页面自动滚动动画结束的阈值,修改此值可以调整 PageView 事件的发送时机。', + pageTurningEventTiming: '设置 Page View 页面自动滚动动画结束的阈值,\n修改此值可以调整 Page View 事件的发送时机。', indicator: '页面视图指示器组件', pageTurningSpeed: '每个页面翻页时所需时间。单位:秒', pageEvents: '页面视图的事件回调函数', @@ -334,8 +334,8 @@ module.exports = { }, particleSystemRenderer: { renderMode: '设定粒子生成模式', - velocityScale: '在粒子生成方式为 StrecthedBillboard 时,对粒子在运动方向上按速度大小进行拉伸', - lengthScale: '在粒子生成方式为 StrecthedBillboard 时,对粒子在运动方向上按粒子大小进行拉伸', + velocityScale: '在粒子生成方式为 Stretched Billboard 时,对粒子在运动方向上按速度大小进行拉伸', + lengthScale: '在粒子生成方式为 Stretched Billboard 时,对粒子在运动方向上按粒子大小进行拉伸', mesh: '粒子发射的模型', particleMaterial: '粒子使用的材质', trailMaterial: '拖尾使用的材质', @@ -368,8 +368,8 @@ module.exports = { frameOverTime: '一个周期内动画播放的帧与时间变化曲线', startFrame: '从第几帧开始播放,时间为整个粒子系统的生命周期', cycleCount: '一个生命周期内播放循环的次数', - randomRow: '随机从动画贴图中选择一行以生成动画,\n此选项仅在动画播放方式为 SingleRow 时生效', - rowIndex: '从动画贴图中选择特定行以生成动画,\n此选项仅在动画播放方式为 SingleRow 时且禁用 randomRow 时可用', + randomRow: '随机从动画贴图中选择一行以生成动画,\n此选项仅在动画播放方式为 Single Row 时生效', + rowIndex: '从动画贴图中选择特定行以生成动画,\n此选项仅在动画播放方式为 Single Row 时且禁用 Random Row 时可用', }, toggle: { interactable: 'Toggle 是否可交互,这一项未选中时,Toggle 处在禁用状态', @@ -380,9 +380,9 @@ module.exports = { hover_color: '悬停状态的 Toggle 背景颜色', disabled_color: '禁用状态的 Toggle 背景颜色', duration: 'Toggle 颜色变化或者缩放变化的过渡时间', - zoom_scale: '当用户点击 Toggle 后,Toggle 会缩放到一个值,这个值等于 Toggle 原始 scale * zoomScale, zoomScale 可以为负数', + zoom_scale: '当用户点击 Toggle 后,Toggle 会缩放到一个值,\n这个值等于 Toggle 原始 scale * zoomScale, zoomScale 可以为负数', auto_gray_effect: - '如果这个标记为 true,当 toggle 的 interactable 属性为 false 的时候,会使用内置 shader 让 toggle 的 target 节点的 sprite 组件变灰', + '如果这个标记为 true,当 toggle 的 interactable 属性为 false 的时候,\n会使用内置 shader 让 toggle 的 target 节点的 sprite 组件变灰', normal_sprite: '普通状态的 Toggle 背景图资源', pressed_sprite: '按下状态的 Toggle 背景图资源', hover_sprite: '悬停状态的 Toggle 背景图资源', @@ -391,7 +391,7 @@ module.exports = { isChecked: '如果这个设置为 true,则 check mark 组件会处于 enabled 状态,否则处于 disabled 状态。', checkMark: 'Toggle 处于选中状态时显示的精灵图片', toggleGroup: - 'Toggle 所属的 ToggleGroup,这个属性是可选的。如果这个属性为 null,则 Toggle 是一个 CheckBox,否则,Toggle 是一个 RadioButton。', + 'Toggle 所属的 Toggle Group,这个属性是可选的。\n如果这个属性为 null,则 Toggle 是一个 CheckBox,否则,Toggle 是一个 Radio Button。', check_events: 'Toggle 按钮的点击事件列表', }, toggle_group: { @@ -428,8 +428,8 @@ module.exports = { mode: 'Particle在每个粒子的运动轨迹上形成拖尾效果', lifeTime: '拖尾的生命周期', minParticleDistance: '粒子每生成一个拖尾节点所运行的最短距离', - space: '拖尾所在的坐标系,World在世界坐标系中运行,Local在本地坐标系中运行', - textureMode: '贴图在拖尾上的展开形式,Stretch贴图覆盖在整条拖尾上,Repeat贴图覆盖在一段拖尾上', + space: '拖尾所在的坐标系,\nWorld 在世界坐标系中运行,\nLocal 在本地坐标系中运行', + textureMode: '贴图在拖尾上的展开形式,\nStretch 贴图覆盖在整条拖尾上,\nRepeat 贴图覆盖在一段拖尾上', widthFromParticle: '拖尾宽度继承自粒子大小', widthRatio: '拖尾宽度,如果继承自粒子则是粒子大小的比例', colorFromParticle: '拖尾颜色是否继承自粒子', @@ -539,8 +539,8 @@ module.exports = { cache_mode: '文本缓存模式, 该模式只支持系统字体', max_width: '富文本的最大宽度, 传 0 的话意味着必须手动换行.', line_height: '字体行高, 单位是 point', - image_atlas: '对于 img 标签里面的 src 属性名称,都需要在 imageAtlas 里面找到一个有效的 spriteFrame,否则 img tag 会判定为无效', - handleTouchEvent: '选中此选项后,RichText 将阻止节点边界框中的所有输入事件(鼠标和触摸),从而防止输入事件穿透到底层节点', + image_atlas: '对于 img 标签里面的 src 属性名称,都需要在 image atlas 里面找到一个有效的 sprite frame,否则 img tag 会判定为无效', + handleTouchEvent: '选中此选项后,rich text 将阻止节点边界框中的所有输入事件(鼠标和触摸),从而防止输入事件穿透到底层节点', }, UICoordinateTracker: { target: '目标对象', @@ -564,12 +564,12 @@ module.exports = { premultipliedAlpha: '是否启用贴图预乘', }, dragon_bones: { - dragon_bones_asset: '骨骼信息数据,拖拽 DragonBones 导出的骨骼动画信息 json 资源到这里来开始使用', - dragon_bones_atlas_asset: 'Texture 信息数据,拖拽 DragonBones 导出的 Texture 信息 json 资源到这里来开始使用', + dragon_bones_asset: '骨骼信息数据,拖拽 Dragon Bones 导出的骨骼动画信息 json 资源到这里来开始使用', + dragon_bones_atlas_asset: 'Texture 信息数据,拖拽 Dragon Bones 导出的 Texture 信息 json 资源到这里来开始使用', armature_name: '当前的 Armature 名称', animation_name: '当前播放的动画名称', time_scale: '当前骨骼中所有动画的时间缩放率', - play_times: '播放默认动画的循环次数\n-1 表示使用配置文件中的默认值\n0 表示无限循环\n>0 表示循环次数', + play_times: '播放默认动画的循环次数\n - 1 表示使用配置文件中的默认值\n0 表示无限循环\n > 0 表示循环次数', debug_bones: '是否显示 bone 的 debug 信息', }, motionStreak: { @@ -595,7 +595,7 @@ module.exports = { custom: '是否自定义粒子属性', file: 'plist 格式的粒子配置文件', spriteFrame: '粒子贴图定义', - texture: '粒子贴图,只读属性,请使用 spriteFrame 属性来替换贴图', + texture: '粒子贴图,只读属性,请使用 sprite Frame 属性来替换贴图', particleCount: '当前播放的粒子数量', srcBlendFactor: '指定原图混合模式', dstBlendFactor: '指定目标的混合模式', @@ -627,15 +627,15 @@ module.exports = { rotatePerS: '粒子每秒围绕起始点的旋转角度及变化范围,只有在半径模式下可用', capacity: '粒子系统能生成的最大粒子数量', scaleSpace: '选择缩放坐标系', - startSize3D: '是否分别设置粒子X,Y和Z轴的初始大小', - startSizeX: 'X轴初始大小', - startSizeY: 'Y轴初始大小', - startSizeZ: 'Z轴初始大小', + startSize3D: '是否分别设置粒子 X, Y 和 Z 轴的初始大小', + startSizeX: 'X 轴初始大小', + startSizeY: 'Y 轴初始大小', + startSizeZ: 'Z 轴初始大小', startSpeed: '初始速度', - startRotation3D: '是否分别设置粒子X,Y和Z轴的初始旋转角度', - startRotationX: 'X轴初始旋转角度', - startRotationY: 'Y轴初始旋转角度', - startRotationZ: 'Z轴初始旋转角度', + startRotation3D: '是否分别设置粒子 X, Y 和 Z 轴的初始旋转角度', + startRotationX: 'X 轴初始旋转角度', + startRotationY: 'Y 轴初始旋转角度', + startRotationZ: 'Z 轴初始旋转角度', startDelay: '粒子系统开始运行后,延迟粒子发射的时间', startLifetime: '粒子生命周期', duration: '粒子系统运行时间', @@ -670,14 +670,14 @@ module.exports = { type: '遮罩类型', spriteFrame: '遮罩所需要的贴图', inverted: '反向遮罩(不支持 Canvas 模式)', - alphaThreshold: 'Alpha阈值,只有当模板的像素的 alpha 大于 alphaThreshold 时,才会绘制内容(不支持 Canvas 模式)', + alphaThreshold: 'Alpha阈值,只有当模板的像素的 alpha 大于 alpha Threshold 时,才会绘制内容(不支持 Canvas 模式)', segements: '椭圆遮罩的曲线细分数', }, physics: { rigidbody: { enabledContactListener: '是否启用接触接听器。当 collider 产生碰撞时,只有开启了接触接听器才会调用相应的回调函数', bullet: '这个刚体是否是一个快速移动的刚体,并且需要禁止穿过其他快速移动的刚体', - type: '刚体类型: Static(静态), Kinematic(不受外力), Dynamic(动态)和 Animated(通过设置线性速度和角速度驱动)', + type: '刚体类型:\nStatic(静态), \nKinematic(不受外力), \nDynamic(动态)和 Animated(通过设置线性速度和角速度驱动)', allowSleep: '如果此刚体永远都不应该进入睡眠,那么设置这个属性为 false。需要注意这将使 CPU 占用率提高', gravityScale: '缩放应用在此刚体上的重力值', linearDamping: @@ -731,10 +731,10 @@ module.exports = { brief_help: '该组件将拦截所有输入事件,防止输入穿透到屏幕下方的其它节点,一般用于屏幕上层 UI 的背景。', }, tiledtile: { - row: '指定 TiledTile 的横向坐标,以地图块为单位', - column: '指定 TiledTile 的纵向坐标,以地图块为单位', - gid: '指定 TiledTile 的 gid 值', - layer: '指定 TiledTile 属于哪一个 TiledLayer', + row: '指定 Tiled Tile 的横向坐标,以地图块为单位', + column: '指定 Tiled Tile 的纵向坐标,以地图块为单位', + gid: '指定 Tiled Tile 的 gid 值', + layer: '指定 Tiled Tile 属于哪一个 Tiled Layer', }, INSPECTOR: { component: { @@ -881,8 +881,8 @@ module.exports = { description: "Spine 动画支持。", }, dragon_bones: { - label: "DragonBones", - description: "DragonBones 支持。", + label: "Dragon Bones", + description: "Dragon Bones 支持。", }, animation: { label: "基础动画功能", @@ -896,6 +896,10 @@ module.exports = { label: "Marionette 动画系统", description: "启用 Marionette 动画系统。", }, + custom_pipeline: { + label: "自定义渲染管线(实验)", + description: "启用自定义渲染管线。", + }, }, renderable_2d: { srcBlendFactor: '指定源的混合模式,这会克隆一个新的材质对象,注意这带来的性能和内存损耗', @@ -918,7 +922,7 @@ module.exports = { physics3d: { rigidbody: { group: '刚体分组', - type: '刚体类型:Static为静态, Kinematic为运动学(通过变换信息操控), Dynamic为动力学(通过物理数值操控)', + type: '刚体类型:\nStatic为静态, \nKinematic 为运动学(通过变换信息操控), \nDynamic 为动力学(通过物理数值操控)', mass: '刚体质量,需大于 0', allowSleep: '是否允许自动休眠', linearDamping: '线性阻尼,用于衰减线性速度,值越大,衰减越快', @@ -949,10 +953,10 @@ module.exports = { mesh_convex: '是否使用凸包近似代替,顶点数应小于255,开启后可以支持动力学', terrain_terrain: '所使用的地形资源', simplex_shapeType: '单纯形类型,点、线、三角形、四面体', - simplex_vertex0: '形状的顶点0', - simplex_vertex1: '形状的顶点1', - simplex_vertex2: '形状的顶点2', - simplex_vertex3: '形状的顶点3', + simplex_vertex0: '形状的顶点 0', + simplex_vertex1: '形状的顶点 1', + simplex_vertex2: '形状的顶点 2', + simplex_vertex3: '形状的顶点 3', }, constant_force:{ force: '在世界坐标系中,对刚体施加的力', diff --git a/editor/inspector/assets/effect.js b/editor/inspector/assets/effect.js index 2a816699b8..84a9082e63 100644 --- a/editor/inspector/assets/effect.js +++ b/editor/inspector/assets/effect.js @@ -29,20 +29,20 @@ exports.style = ` } .asset-effect > .config > .description { text-align: center; - color: var(--color-normal-border-weakest); + color: var(--color-normal-fill-weakest); } .asset-effect > .config > .combinations { padding: 10px 0; } - .asset-effect > .config > .combinations .checktab { + .asset-effect > .config > .combinations .tab { line-height: 20px; margin-left: 5px; margin-right: 5px; min-width: 60px; } - .asset-effect > .config > .combinations .checktab[checked="true"] { - border-color: var(--color-focus-contrast-weakest); - background-color: var(--color-focus-fill-weaker); + .asset-effect > .config > .combinations .tab[checked="true"] { + background-color: var(--color-focus-fill-emphasis); + color: var(--color-focus-contrast-emphasis); } .asset-effect > .codes > * { margin-bottom: 8px; @@ -57,7 +57,9 @@ exports.style = ` text-align: center; cursor: pointer; display: inline-block; - background: var(--color-normal-fill-weakest); + background-color: var(--color-normal-fill-emphasis); + color: var(--color-default-contrast-emphasis); + border: calc(var(--size-normal-border) * 1px) solid var(--color-normal-border); } .asset-effect > .codes .tabs > .tab:first-child { border-top-left-radius: 4px; @@ -70,7 +72,8 @@ exports.style = ` border-left: 1px solid var(--color-normal-fill-emphasis); } .asset-effect > .codes .tabs > .tab[active="true"] { - background: var(--color-normal-fill-emphasis); + background-color: var(--color-normal-fill); + color: var(--color-focus-fill-emphasis); } .asset-effect > .codes ui-code { max-height: 400px; @@ -152,7 +155,7 @@ const Elements = { const button = document.createElement('ui-button'); content.appendChild(button); - button.setAttribute('class', 'checktab'); + button.setAttribute('class', 'tab'); button.setAttribute('checked', checked); panel.updateReadonly(button); button.innerText = name; diff --git a/editor/inspector/assets/erp-texture-cube.js b/editor/inspector/assets/erp-texture-cube.js index 97bcae6a8c..6ff0749a4a 100644 --- a/editor/inspector/assets/erp-texture-cube.js +++ b/editor/inspector/assets/erp-texture-cube.js @@ -1,108 +1,54 @@ -exports.template = /* html */` +exports.template = /* html */ `
- - - - + + - - - - + + - - - - - - - + + +
+ + + + + + + + + + + + +
+ + + + +
+
- - - - - - - + + +
+ + + + + + + + +
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
@@ -113,17 +59,28 @@ exports.style = ` .asset-erp-texture-cube ui-prop{ margin-top: 4px; } +.asset-erp-texture-cube #filterAdvancedSection, +.asset-erp-texture-cube #wrapAdvancedSection, +.asset-erp-texture-cube #generateMipmapsSection { + margin-left: 1.2em; + display: none; +} `; exports.$ = { anisotropy: '#anisotropy', faceSize: '#faceSize', + filterMode: '#filterMode', + filterAdvancedSection: '#filterAdvancedSection', minfilter: '#minfilter', magfilter: '#magfilter', + generateMipmaps: '#generateMipmaps', + generateMipmapsSection: '#generateMipmapsSection', mipfilter: '#mipfilter', + wrapMode: '#wrapMode', + wrapAdvancedSection: '#wrapAdvancedSection', wrapModeS: '#wrapModeS', wrapModeT: '#wrapModeT', - bakeReflectionConvo: '.bake-reflection-convo', mipBakeMode: '#mipBakeMode', }; @@ -148,6 +105,45 @@ exports.update = function(assetList, metaList) { } }; +const ModeMap = { + filter: { + 'Nearest (None)': { + minfilter: 'nearest', + magfilter: 'nearest', + mipfilter: 'none', + }, + Bilinear: { + minfilter: 'linear', + magfilter: 'linear', + mipfilter: 'none', + }, + 'Bilinear with Mipmaps': { + minfilter: 'linear', + magfilter: 'linear', + mipfilter: 'nearest', + }, + 'Trilinear with Mipmaps': { + minfilter: 'linear', + magfilter: 'linear', + mipfilter: 'linear', + }, + }, + wrap: { + Repeat: { + wrapModeS: 'repeat', + wrapModeT: 'repeat', + }, + Clamp: { + wrapModeS: 'clamp-to-edge', + wrapModeT: 'clamp-to-edge', + }, + Mirror: { + wrapModeS: 'mirrored-repeat', + wrapModeT: 'mirrored-repeat', + }, + }, +}; + const Elements = { anisotropy: { ready() { @@ -164,18 +160,64 @@ const Elements = { this.$.faceSize.addEventListener('change', this.dataChange.bind(this, 'faceSize')); }, update() { - this.$.faceSize.value = this.meta.userData.faceSize; this.updateInvalid(this.$.faceSize, 'faceSize'); this.updateReadonly(this.$.faceSize); }, }, + filterMode: { + ready() { + this.$.filterMode.addEventListener('change', this.dataChange.bind(this, 'filterMode')); + }, + update() { + let optionsHtml = ''; + // FilterMode 选项 + const types = Object.keys(ModeMap.filter).concat('Advanced'); + types.forEach((type) => { + optionsHtml += ``; + }); + this.$.filterMode.innerHTML = optionsHtml; + + // 匹配 filterMode 值,没有匹配到组合,则为自定义 Advanced + let value = 'Advanced'; + for (const filterKey of Object.keys(ModeMap.filter)) { + const filterItem = ModeMap.filter[filterKey]; + let flag = true; + for (const key of Object.keys(filterItem)) { + if (this.meta.userData[key] !== filterItem[key]) { + flag = false; + break; + } + } + if (flag) { + value = filterKey; + break; + } + } + this.$.filterMode.value = value; + + // 更新时需要判断是否显示自定义项 + value === 'Advanced' + ? (this.$.filterAdvancedSection.style.display = 'block') + : (this.$.filterAdvancedSection.style.display = 'none'); + + this.updateInvalid(this.$.filterMode, 'filterMode'); + this.updateReadonly(this.$.filterMode); + }, + }, minfilter: { ready() { this.$.minfilter.addEventListener('change', this.dataChange.bind(this, 'minfilter')); }, update() { - this.$.minfilter.value = this.meta.userData.minfilter; + let optionsHtml = ''; + const types = ['nearest', 'linear']; + types.forEach((type) => { + optionsHtml += ``; + }); + this.$.minfilter.innerHTML = optionsHtml; + + this.$.minfilter.value = this.meta.userData.minfilte || 'nearest'; this.updateInvalid(this.$.minfilter, 'minfilter'); this.updateReadonly(this.$.minfilter); }, @@ -185,27 +227,108 @@ const Elements = { this.$.magfilter.addEventListener('change', this.dataChange.bind(this, 'magfilter')); }, update() { - this.$.magfilter.value = this.meta.userData.magfilter; + let optionsHtml = ''; + const types = ['nearest', 'linear']; + types.forEach((type) => { + optionsHtml += ``; + }); + this.$.magfilter.innerHTML = optionsHtml; + + this.$.magfilter.value = this.meta.userData.magfilter || 'nearest'; this.updateInvalid(this.$.magfilter, 'magfilter'); this.updateReadonly(this.$.magfilter); }, }, + generateMipmaps: { + ready() { + this.$.generateMipmaps.addEventListener('change', this.dataChange.bind(this, 'generateMipmaps')); + }, + update() { + this.$.generateMipmaps.value = this.meta.userData.mipfilter ? this.meta.userData.mipfilter !== 'none' : false; + + // 更新时判断是否显示 mipfilter 选项 + this.$.generateMipmaps.value + ? (this.$.generateMipmapsSection.style.display = 'block') + : (this.$.generateMipmapsSection.style.display = 'none'); + + this.updateInvalid(this.$.generateMipmaps, 'generateMipmaps'); + this.updateReadonly(this.$.generateMipmaps); + }, + }, mipfilter: { ready() { this.$.mipfilter.addEventListener('change', this.dataChange.bind(this, 'mipfilter')); }, update() { - this.$.mipfilter.value = this.meta.userData.mipfilter; + let optionsHtml = ''; + const types = ['nearest', 'linear']; + types.forEach((type) => { + optionsHtml += ``; + }); + this.$.mipfilter.innerHTML = optionsHtml; + + this.$.mipfilter.value = this.meta.userData.mipfilter || 'nearest'; this.updateInvalid(this.$.mipfilter, 'mipfilter'); this.updateReadonly(this.$.mipfilter); }, }, + wrapMode: { + ready() { + this.$.wrapMode.addEventListener('change', this.dataChange.bind(this, 'wrapMode')); + }, + update() { + let optionsHtml = ''; + // WrapMode 选项 + const types = Object.keys(ModeMap.wrap).concat('Advanced'); + types.forEach((type) => { + optionsHtml += ``; + }); + this.$.wrapMode.innerHTML = optionsHtml; + + // 匹配 wrapMode 值,没有匹配到组合,则为自定义 Advanced + let value = 'Advanced'; + for (const wrapKey of Object.keys(ModeMap.wrap)) { + const wrapItem = ModeMap.wrap[wrapKey]; + let flag = true; + for (const key of Object.keys(wrapItem)) { + if (this.meta.userData[key] !== wrapItem[key]) { + flag = false; + break; + } + } + if (flag) { + value = wrapKey; + break; + } + } + this.$.wrapMode.value = value; + + // 更新时需要判断是否显示自定义项 + value === 'Advanced' + ? (this.$.wrapAdvancedSection.style.display = 'block') + : (this.$.wrapAdvancedSection.style.display = 'none'); + + this.updateInvalid(this.$.wrapMode, 'wrapMode'); + this.updateReadonly(this.$.wrapMode); + }, + }, wrapModeS: { ready() { this.$.wrapModeS.addEventListener('change', this.dataChange.bind(this, 'wrapModeS')); }, update() { - this.$.wrapModeS.value = this.meta.userData.wrapModeS; + let optionsHtml = ''; + const types = { + Repeat: 'repeat', + Clamp: 'clamp-to-edge', + Mirror: 'mirrored-repeat', + }; + for (const type in types) { + optionsHtml += ``; + } + this.$.wrapModeS.innerHTML = optionsHtml; + + this.$.wrapModeS.value = this.meta.userData.wrapModeS || 'repeat'; this.updateInvalid(this.$.wrapModeS, 'wrapModeS'); this.updateReadonly(this.$.wrapModeS); }, @@ -215,7 +338,18 @@ const Elements = { this.$.wrapModeT.addEventListener('change', this.dataChange.bind(this, 'wrapModeT')); }, update() { - this.$.wrapModeT.value = this.meta.userData.wrapModeT; + let optionsHtml = ''; + const types = { + Repeat: 'repeat', + Clamp: 'clamp-to-edge', + Mirror: 'mirrored-repeat', + }; + for (const type in types) { + optionsHtml += ``; + } + this.$.wrapModeT.innerHTML = optionsHtml; + + this.$.wrapModeT.value = this.meta.userData.wrapModeT || 'repeat'; this.updateInvalid(this.$.wrapModeT, 'wrapModeT'); this.updateReadonly(this.$.wrapModeT); }, @@ -228,17 +362,46 @@ const Elements = { this.$.mipBakeMode.value = this.meta.userData.mipBakeMode === 2 ? true : false; this.updateInvalid(this.$.mipBakeMode, 'mipBakeMode'); this.updateReadonly(this.$.mipBakeMode); - this.updateBakeReflectionVisible(this.meta.userData.mipfilter === 'linear'); }, }, - }; exports.methods = { updateInvalid(element, prop) { - const invalid = this.metaList.some((meta) => { - return meta.userData[prop] !== this.meta.userData[prop]; - }); + let invalid; + // filterMode、 wrapMode 和 generateMipmaps 需要拆解进行判断 + switch (prop) { + case 'filterMode': + invalid = this.metaList.some((meta) => { + for (const key of Object.keys(ModeMap.filter.Bilinear)) { + if (meta.userData[key] !== this.meta.userData[key]) { + return true; + } + } + return false; + }); + break; + case 'wrapMode': + invalid = this.metaList.some((meta) => { + for (const key of Object.keys(ModeMap.wrap.Repeat)) { + if (meta.userData[key] !== this.meta.userData[key]) { + return true; + } + } + return false; + }); + break; + case 'generateMipmaps': + invalid = this.metaList.some((meta) => { + return meta.userData['mipfilter'] !== this.meta.userData['mipfilter']; + }); + break; + default: + invalid = this.metaList.some((meta) => { + return meta.userData[prop] !== this.meta.userData[prop]; + }); + break; + } element.invalid = invalid; }, updateReadonly(element) { @@ -248,20 +411,50 @@ exports.methods = { element.removeAttribute('disabled'); } }, - updateBakeReflectionVisible(show) { - this.$.bakeReflectionConvo.style.display = show ? 'block' : 'none'; - - }, dataChange(key, event) { let value = event.target.value; if (key === 'mipBakeMode') { value = event.target.value ? 2 : 1; } - if (key === 'mipfilter') { - this.updateBakeReflectionVisible(value === 'linear'); - } this.metaList.forEach((meta) => { - meta.userData[key] = value || undefined; + if (key === 'filterMode') { + if (ModeMap.filter[value]) { + const data = ModeMap.filter[value]; + for (const key of Object.keys(data)) { + meta.userData[key] = data[key]; + } + this.$.filterAdvancedSection.style.display = 'none'; + } else { + // 选择 advanced 显示自定义项 + this.$.filterAdvancedSection.style.display = 'block'; + } + } else if (key === 'generateMipmaps') { + if (!value) { + // 没勾选 生成 mipmaps,不显示 mipfilter 选项 + meta.userData.mipfilter = 'none'; + this.$.generateMipmapsSection.style.display = 'none'; + } else { + this.$.generateMipmapsSection.style.display = 'block'; + if (this.$.mipfilter.value === 'none') { + this.$.mipfilter.value = 'nearest'; + // TODO: 目前 ui-select 通过 .value 修改组件值后没有触发 change 事件,需要手动提交 + this.$.mipfilter.dispatch('change'); + } + } + } else if (key === 'wrapMode') { + if (ModeMap.wrap[value]) { + const data = ModeMap.wrap[value]; + for (const key of Object.keys(data)) { + meta.userData[key] = data[key]; + } + this.$.wrapAdvancedSection.style.display = 'none'; + } else { + // 选择 advanced 需要显示自定义项 + this.$.wrapAdvancedSection.style.display = 'block'; + } + } else { + meta.userData[key] = value || undefined; + } }); this.dispatch('change'); diff --git a/editor/inspector/assets/image.js b/editor/inspector/assets/image.js index 30d25adec8..2acf90eccc 100644 --- a/editor/inspector/assets/image.js +++ b/editor/inspector/assets/image.js @@ -73,6 +73,14 @@ const Elements = { const panel = this; panel.$.typeSelect.addEventListener('change', (event) => { + // metaList 时以以选中的第一个 asset 的类型进行处理 + let spriteFrameChange; + if (panel.meta.userData.type === 'sprite-frame') { + spriteFrameChange = 'spriteFrameToOthers'; + } else if (event.target.value === 'sprite-frame') { + spriteFrameChange = 'othersToSpriteFrame'; + } + panel.metaList.forEach((meta) => { meta.userData.type = event.target.value; }); @@ -81,7 +89,8 @@ const Elements = { // There are other properties whose updates depend on its changes attribute corresponds to the edit element Elements.isRGBE.update.call(panel); Elements.fixAlphaTransparencyArtifacts.update.call(panel); - panel.updatePanel(); + // imageAssets 类型有 spriteFrame 变化的话需要处理 mipmaps + panel.updatePanel(spriteFrameChange); }); }, update() { @@ -147,7 +156,6 @@ const Elements = { panel.$.fixAlphaTransparencyArtifactsCheckbox.addEventListener('change', (event) => { panel.metaList.forEach((meta) => { meta.userData.fixAlphaTransparencyArtifacts = event.target.value; - }); panel.dispatch('change'); }); @@ -169,7 +177,6 @@ const Elements = { } else { fixATAProp.style.display = 'none'; } - }, }, isRGBE: { @@ -260,7 +267,7 @@ exports.methods = { } }, - async _updatePanel($section, type) { + _updatePanel($section, type, spriteFrameChange) { const assetList = []; const metaList = []; @@ -306,6 +313,13 @@ exports.methods = { } if (subMeta.importer === imageImporter) { + if (spriteFrameChange === 'othersToSpriteFrame') { + // imageAsset 类型切换到 spriteFrame,禁用 mipmaps + subMeta.userData.mipfilter = 'none'; + } else if (spriteFrameChange === 'spriteFrameToOthers' && subMeta.userData.mipfilter === 'none') { + // imageAsset 类型从 spriteFrame 切换到其他,原来没启用的话 mipmaps 默认 nearest + subMeta.userData.mipfilter = 'nearest'; + } metaList.push(subMeta); break; } @@ -327,10 +341,14 @@ exports.methods = { $panel.update(assetList, metaList); }, - async updatePanel() { - this._updatePanel(this.$.panelSection, this.meta.userData.type); + /** + * 更新属性 panel + * @param {*} spriteFrameChange imageAsset 类型是否切换和 spriteFrame 是否有关 + */ + updatePanel(spriteFrameChange) { + this._updatePanel(this.$.panelSection, this.meta.userData.type, spriteFrameChange); if (this.meta.userData.type === 'sprite-frame') { - this._updatePanel(this.$.texturePanelSection, 'texture'); + this._updatePanel(this.$.texturePanelSection, 'texture', spriteFrameChange); } else { this.$.texturePanelSection.style.display = 'none'; } diff --git a/editor/inspector/assets/texture/texture.js b/editor/inspector/assets/texture/texture.js index fce26c1221..fff852696d 100644 --- a/editor/inspector/assets/texture/texture.js +++ b/editor/inspector/assets/texture/texture.js @@ -9,26 +9,44 @@ exports.template = ` - - + + - - - +
+ + + + + + + + + + + + +
+ + + + +
+
+ + + - - - - - - - - - - - - -