diff --git a/.github/workflows/build-problem-matcher.json b/.github/workflows/build-problem-matcher.json index 3244c39f7f..90cf3caba6 100644 --- a/.github/workflows/build-problem-matcher.json +++ b/.github/workflows/build-problem-matcher.json @@ -2,7 +2,7 @@ { "problemMatcher": [ { - "owner": "circular-reference-check", + "owner": " build", "pattern": [ { "regexp": "^Circular dependency: (.*)$", diff --git a/.github/workflows/get-native-external-version.js b/.github/workflows/get-native-external-version.js new file mode 100644 index 0000000000..aba1e38803 --- /dev/null +++ b/.github/workflows/get-native-external-version.js @@ -0,0 +1,8 @@ +const path = require('path'); +const fs = require('fs'); + +const configJsonPath = path.join(__dirname, '../../native/external-config.json'); +const configData = fs.readFileSync(configJsonPath); +const config = JSON.parse(configData); +const externalVersion = config.from.checkout; +console.log(externalVersion); \ No newline at end of file diff --git a/.github/workflows/mirror_gitee.yml b/.github/workflows/mirror_gitee.yml deleted file mode 100644 index a2f16c42b1..0000000000 --- a/.github/workflows/mirror_gitee.yml +++ /dev/null @@ -1,17 +0,0 @@ -name: 'GitHub Actions Mirror' - -on: [create, push, delete] - -jobs: - mirror_to_gitee: - runs-on: ubuntu-latest - steps: - - name: 'Checkout' - uses: actions/checkout@v1 - - name: 'Mirror to gitee' - uses: pixta-dev/repository-mirroring-action@v1 - with: - target_repo_url: - git@gitee.com:creator-cocos/engine.git - ssh_private_key: - ${{ secrets.GITEE_KEY }} diff --git a/.github/workflows/native-bindings.yml b/.github/workflows/native-bindings.yml index 2c8eb9c6e2..d008ae8658 100644 --- a/.github/workflows/native-bindings.yml +++ b/.github/workflows/native-bindings.yml @@ -3,6 +3,9 @@ name: Glue on: pull_request_target: types: [closed] + paths: + - 'templates/**' + - 'native/**' jobs: generate-jsb: @@ -12,11 +15,17 @@ jobs: - uses: actions/checkout@v2 - name: Download external libraries run: | - EXT_VERSION=`grep version native/external-config.json |awk -F'"' '{print $4}'` + 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 rm -rf native/external/.git - + - uses: nttld/setup-ndk@v1 + id: setup-ndk + with: + ndk-version: r21e + add-to-path: false - name: Run genbindings.py + 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 @@ -34,6 +43,7 @@ jobs: title: '[ci skip][AUTO]: Automated PR to generate code' body: | Automated PR to genbindings & built resources + [X] does not change any runtime related code or build configuration committer: cocos-robot author: cocos-robot commit-message: "[ci skip][AUTO]: Automated code generating update: ${{ github.event.pull_request.head.sha }} (#${{ github.event.number }})" @@ -42,7 +52,6 @@ jobs: branch: t/bot/genbindings branch-suffix: short-commit-hash delete-branch: true - milestone: 1 #- name: Make PR # run: | diff --git a/.github/workflows/native-clang-format.yml b/.github/workflows/native-clang-format.yml index a5342fb904..e6b0f8a5ba 100644 --- a/.github/workflows/native-clang-format.yml +++ b/.github/workflows/native-clang-format.yml @@ -4,6 +4,9 @@ name: Apply clang format on: pull_request_target: types: [closed] + paths: + - 'templates/**' + - 'native/**' jobs: Clang-Format: @@ -50,4 +53,3 @@ jobs: branch: t/bot/fix-format branch-suffix: short-commit-hash delete-branch: true - milestone: 1 diff --git a/.github/workflows/native-compile-linux.yml b/.github/workflows/native-compile-linux.yml index 4d0dbffd35..b5d92b6913 100644 --- a/.github/workflows/native-compile-linux.yml +++ b/.github/workflows/native-compile-linux.yml @@ -1,19 +1,37 @@ name: Linux -on: [pull_request] +on: + pull_request: + paths: + - 'templates/**' + - 'native/**' + +# github.head_ref is only defined on pull_request events +concurrency: + group: ${{ github.workflow }}-${{ github.actor }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true jobs: compile_linux: name: "Linux-Ubuntu" + 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=`grep version native/external-config.json |awk -F'"' '{print $4}'` + 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 @@ -27,9 +45,9 @@ jobs: env: COCOS_ENGINE_DEV: 1 run: | - COCOS2DX_ROOT=$GITHUB_WORKSPACE/native + NATIVE_ROOT=$GITHUB_WORKSPACE/native echo "Compiling Linux ... " - cd $COCOS2DX_ROOT/templates/linux + cd $GITHUB_WORKSPACE/templates/linux mkdir -p build-linux/proj touch build-linux/proj/cfg.cmake echo "set(CC_USE_VULKAN OFF)" >> build-linux/proj/cfg.cmake @@ -41,8 +59,8 @@ jobs: echo "set(USE_PHYSICS_PHYSX OFF)" >> build-linux/proj/cfg.cmake mkdir build-linux/assets - RES_DIR=$COCOS2DX_ROOT/templates/linux/build-linux + RES_DIR=$GITHUB_WORKSPACE/templates/linux/build-linux cd build-linux - cmake ../ -GNinja -DRES_DIR=$RES_DIR -DCOCOS_X_PATH=$COCOS2DX_ROOT + cmake ../ -GNinja -DRES_DIR=$RES_DIR -DCOCOS_X_PATH=$NATIVE_ROOT set +e cmake --build . \ No newline at end of file diff --git a/.github/workflows/native-compile-platforms.yml b/.github/workflows/native-compile-platforms.yml index 4606075b78..5d0d36e63c 100644 --- a/.github/workflows/native-compile-platforms.yml +++ b/.github/workflows/native-compile-platforms.yml @@ -1,25 +1,42 @@ name: Compile -on: [pull_request] +on: + pull_request: + paths: + - 'templates/**' + - 'native/**' + +# github.head_ref is only defined on pull_request events +concurrency: + group: ${{ github.workflow }}-${{ github.actor }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true jobs: compile_windows: - runs-on: windows-2019 name: "Windows" - + if: + (! contains(github.event.pull_request.body, '[X] does not change any runtime related code or build configuration')) + runs-on: windows-2019 steps: - uses: actions/checkout@v2 - name: Download external libraries shell: bash run: | - EXT_VERSION=`grep version native/external-config.json |awk -F'"' '{print $4}'` + 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 - name: Install deps run: | choco install --forcex86 vulkan-sdk python -m pip install PyYAML==5.4.1 Cheetah3 + - uses: nttld/setup-ndk@v1 + id: setup-ndk + with: + ndk-version: r21e + add-to-path: false - name: Generate bindings shell: bash + env: + ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }} run: | python -V cd ./native/tools/tojs @@ -31,7 +48,9 @@ jobs: env: COCOS_ENGINE_DEV: 1 run: | - cd $GITHUB_WORKSPACE/native/templates/windows + cd $GITHUB_WORKSPACE/templates/windows + echo "message(STATUS \"hook before \${CC_TARGET_NAME}\")" >> Pre-Sample.cmake + echo "message(STATUS \"hook after \${CC_TARGET_NAME}\")" >> Post-Sample.cmake mkdir -p build-win64/proj touch build-win64/proj/cfg.cmake echo "set(CC_USE_GLES3 ON)" >> build-win64/proj/cfg.cmake @@ -43,7 +62,7 @@ jobs: echo "set(CMAKE_CXX_STANDARD_REQUIRED ON)" >> build-win64/proj/cfg.cmake mkdir build-win64/assets cd build-win64 - RES_DIR=${GITHUB_WORKSPACE//\\//}/native/templates/windows/build-win64 + RES_DIR=${GITHUB_WORKSPACE//\\//}/templates/windows/build-win64 COCOS_X_PATH=${GITHUB_WORKSPACE//\\//}/native cmake ../ -G"Visual Studio 16 2019" -DRES_DIR=$RES_DIR -DCOCOS_X_PATH=$COCOS_X_PATH -Ax64 cmake --build . --config Release @@ -51,15 +70,24 @@ jobs: compile_android: name: "Android" + 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=`grep version native/external-config.json |awk -F'"' '{print $4}'` + 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 @@ -68,15 +96,17 @@ jobs: env: COCOS_ENGINE_DEV: 1 run: | - COCOS2DX_ROOT=$GITHUB_WORKSPACE/native + NATIVE_ROOT=$GITHUB_WORKSPACE/native ANDORID_NDK=$ANDROID_NDK_LATEST_HOME - NATIVE_DIR=$COCOS2DX_ROOT/templates/android-template + NATIVE_DIR=$GITHUB_WORKSPACE/templates/android-template echo "Compiling Android ... " - cd $COCOS2DX_ROOT/templates/ + 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 $COCOS2DX_ROOT/templates/android/build + cd $GITHUB_WORKSPACE/templates/android/build mkdir -p build-android/proj touch build-android/proj/cfg.cmake echo "set(CC_USE_GLES3 ON)" >> build-android/proj/cfg.cmake @@ -87,12 +117,12 @@ jobs: mkdir -p build-android/assets - ASSET_DIR=$COCOS2DX_ROOT/templates/android/build/build-android/ + 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=$COCOS2DX_ROOT@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 @@ -106,6 +136,8 @@ jobs: compile_mac_x86_64: name: "MacOS x86_64" + if: + (! contains(github.event.pull_request.body, '[X] does not change any runtime related code or build configuration')) runs-on: macos-latest steps: - uses: actions/checkout@v2 @@ -115,9 +147,16 @@ jobs: - name: Download external libraries shell: bash run: | - EXT_VERSION=`grep version native/external-config.json |awk -F'"' '{print $4}'` + 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: | python -m pip install PyYAML==5.4.1 Cheetah3 python ./native/tools/tojs/genbindings.py @@ -127,9 +166,11 @@ jobs: COCOS_ENGINE_DEV: 1 run: | NUM_OF_CORES=`getconf _NPROCESSORS_ONLN` - COCOS2DX_ROOT=$GITHUB_WORKSPACE/native + NATIVE_ROOT=$GITHUB_WORKSPACE/native echo "Compiling MacOSX ... " - cd $COCOS2DX_ROOT/templates/mac + cd $GITHUB_WORKSPACE/templates/mac + echo "message(STATUS \"hook before \${CC_TARGET_NAME}\")" >> Pre-Sample.cmake + echo "message(STATUS \"hook after \${CC_TARGET_NAME}\")" >> Post-Sample.cmake mkdir -p build-mac/proj touch build-mac/proj/cfg.cmake echo "set(CC_USE_VULKAN OFF)" >> build-mac/proj/cfg.cmake @@ -140,9 +181,9 @@ jobs: echo "set(CMAKE_CXX_STANDARD_REQUIRED ON)" >> build-mac/proj/cfg.cmake mkdir build-mac/assets - RES_DIR=$COCOS2DX_ROOT/templates/mac/build-mac + RES_DIR=$GITHUB_WORKSPACE/templates/mac/build-mac cd build-mac - cmake ../ -GXcode -DCMAKE_OSX_ARCHITECTURES=x86_64 -DRES_DIR=$RES_DIR -DCOCOS_X_PATH=$COCOS2DX_ROOT + cmake ../ -GXcode -DCMAKE_OSX_ARCHITECTURES=x86_64 -DRES_DIR=$RES_DIR -DCOCOS_X_PATH=$NATIVE_ROOT set +e cmake --build . --config Release -- -quiet -jobs $NUM_OF_CORES -arch x86_64 retcode=$? @@ -157,6 +198,8 @@ jobs: compile_mac_arm64: name: "MacOS arm64" + if: + (! contains(github.event.pull_request.body, '[X] does not change any runtime related code or build configuration')) runs-on: macos-latest steps: - uses: actions/checkout@v2 @@ -166,9 +209,16 @@ jobs: - name: Download external libraries shell: bash run: | - EXT_VERSION=`grep version native/external-config.json |awk -F'"' '{print $4}'` + 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: | python -m pip install PyYAML==5.4.1 Cheetah3 python ./native/tools/tojs/genbindings.py @@ -178,9 +228,9 @@ jobs: COCOS_ENGINE_DEV: 1 run: | NUM_OF_CORES=`getconf _NPROCESSORS_ONLN` - COCOS2DX_ROOT=$GITHUB_WORKSPACE/native + NATIVE_ROOT=$GITHUB_WORKSPACE/native echo "Compiling MacOSX ... " - cd $COCOS2DX_ROOT/templates/mac + cd $GITHUB_WORKSPACE/templates/mac mkdir -p build-mac/proj touch build-mac/proj/cfg.cmake echo "set(CC_USE_VULKAN OFF)" >> build-mac/proj/cfg.cmake @@ -191,9 +241,9 @@ jobs: echo "set(CMAKE_CXX_STANDARD_REQUIRED ON)" >> build-mac/proj/cfg.cmake mkdir build-mac/assets - RES_DIR=$COCOS2DX_ROOT/templates/mac/build-mac + RES_DIR=$GITHUB_WORKSPACE/templates/mac/build-mac cd build-mac - cmake ../ -GXcode -DCMAKE_OSX_ARCHITECTURES=arm64 -DRES_DIR=$RES_DIR -DCOCOS_X_PATH=$COCOS2DX_ROOT + cmake ../ -GXcode -DCMAKE_OSX_ARCHITECTURES=arm64 -DRES_DIR=$RES_DIR -DCOCOS_X_PATH=$NATIVE_ROOT set +e cmake --build . --config Release -- -quiet -jobs $NUM_OF_CORES -arch arm64 retcode=$? @@ -208,6 +258,8 @@ jobs: compile_iOS: name: "iOS" + if: + (! contains(github.event.pull_request.body, '[X] does not change any runtime related code or build configuration')) runs-on: macos-latest steps: - uses: maxim-lobanov/setup-xcode@v1 @@ -220,9 +272,16 @@ jobs: - name: Download external libraries shell: bash run: | - EXT_VERSION=`grep version native/external-config.json |awk -F'"' '{print $4}'` + 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: | python -m pip install PyYAML==5.4.1 Cheetah3 python ./native/tools/tojs/genbindings.py @@ -233,9 +292,11 @@ jobs: run: | set -x NUM_OF_CORES=`getconf _NPROCESSORS_ONLN` - COCOS2DX_ROOT=$GITHUB_WORKSPACE/native + NATIVE_ROOT=$GITHUB_WORKSPACE/native echo "Compiling iOS ... " - cd $COCOS2DX_ROOT/templates/ios + cd $GITHUB_WORKSPACE/templates/ios + echo "message(STATUS \"hook before \${CC_TARGET_NAME}\")" >> Pre-Sample.cmake + echo "message(STATUS \"hook after \${CC_TARGET_NAME}\")" >> Post-Sample.cmake mkdir -p build-ios/proj touch build-ios/proj/cfg.cmake echo "set(CC_USE_GLES3 OFF)" >> build-ios/proj/cfg.cmake @@ -249,14 +310,14 @@ jobs: echo "set(MACOSX_BUNDLE_GUI_IDENTIFIER com.cocos.demo.ios)" >> build-ios/proj/cfg.cmake mkdir build-ios/assets cd build-ios - RES_DIR=$COCOS2DX_ROOT/templates/ios/build-ios + RES_DIR=$GITHUB_WORKSPACE/templates/ios/build-ios cmake ../ -GXcode -DCMAKE_SYSTEM_NAME=iOS \ -DCMAKE_OSX_SYSROOT=iphoneos \ -DCMAKE_OSX_ARCHITECTURES=arm64 \ -DRES_DIR=$RES_DIR \ - -DCOCOS_X_PATH=$COCOS2DX_ROOT + -DCOCOS_X_PATH=$NATIVE_ROOT set +e - #cmake --build . --config Debug -- -quiet -jobs $NUM_OF_CORES -allowProvisioningUpdates CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO + #cmake --build . --config Debug -- -quiet -jobs $NUM_OF_CORES -allowProvisioningUpdates CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO cmake --build . --config Debug -- -quiet -jobs $NUM_OF_CORES CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO retcode=$? set -e @@ -277,7 +338,7 @@ jobs: - name: Download external libraries shell: bash run: | - EXT_VERSION=`grep version native/external-config.json |awk -F'"' '{print $4}'` + 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 - name: Setup Emscripten run: | @@ -291,8 +352,8 @@ jobs: env: COCOS_ENGINE_DEV: 1 run: | - COCOS2DX_ROOT=$GITHUB_WORKSPACE/native - cd $COCOS2DX_ROOT/cocos/renderer/gfx-wgpu - $COCOS2DX_ROOT/../emsdk/upstream/emscripten/emcmake cmake . - $COCOS2DX_ROOT/../emsdk/upstream/emscripten/emmake make + NATIVE_ROOT=$GITHUB_WORKSPACE/native + cd $NATIVE_ROOT/cocos/renderer/gfx-wgpu + $NATIVE_ROOT/../emsdk/upstream/emscripten/emcmake cmake . + $NATIVE_ROOT/../emsdk/upstream/emscripten/emmake make echo "Compile WGPU by ems on MacOS Done!" diff --git a/.github/workflows/native-linter-android.yml b/.github/workflows/native-linter-android.yml index 81c9de4151..3a1b8e2709 100644 --- a/.github/workflows/native-linter-android.yml +++ b/.github/workflows/native-linter-android.yml @@ -1,6 +1,15 @@ name: Linter -on: pull_request +on: + pull_request: + paths: + - 'templates/**' + - 'native/**' + +# github.head_ref is only defined on pull_request events +concurrency: + group: ${{ github.workflow }}-${{ github.actor }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true jobs: # Set the job key. The key is displayed as the job name @@ -9,6 +18,8 @@ jobs: # Name the Job name: ClangTidy Android # Set the type of machine to run on + if: + (! contains(github.event.pull_request.body, '[X] does not change any runtime related code or build configuration')) runs-on: ubuntu-latest steps: @@ -26,11 +37,18 @@ jobs: python -m pip install PyYAML==5.4.1 Cheetah3 - name: Download external run: | - EXT_VERSION=`grep version native/external-config.json |awk -F'"' '{print $4}'` + 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 shell: bash + env: + ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }} + run: | python -V cd ./native/tools/tojs @@ -70,6 +88,8 @@ jobs: - name: Generate Compile database shell: bash + env: + ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }} run: | cd native ./utils/generate_compile_commands_android.sh diff --git a/.github/workflows/native-simulator.yml b/.github/workflows/native-simulator.yml index 4c66f5331f..9c5c894e5c 100644 --- a/.github/workflows/native-simulator.yml +++ b/.github/workflows/native-simulator.yml @@ -6,9 +6,16 @@ on: paths: - 'native/**' +# github.head_ref is only defined on pull_request events +concurrency: + group: ${{ github.workflow }}-${{ github.actor }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + jobs: win_gen_simulator: runs-on: windows-2019 + if: + (! contains(github.event.pull_request.body, '[X] does not change any runtime related code or build configuration')) name: Windows defaults: run: @@ -29,60 +36,71 @@ jobs: - name: install vulkan-sdk run: | choco install vulkan-sdk + - uses: nttld/setup-ndk@v1 + id: setup-ndk + with: + ndk-version: r21e + add-to-path: false - name: pip install run: | python -m pip install PyYAML==5.4.1 Cheetah3 - name: generate bindings glue codes shell: bash + env: + ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }} run: | python -V cd ./tools/tojs echo "Create auto-generated jsbinding glue codes." python ./genbindings.py rm userconf.ini + - name: gen simulator + run: | + gulp gen-simulator + - name: check result + run: | + Get-ChildItem ./simulator/Release -Name SimulatorApp-Win32.exe + if(Test-Path ./simulator/Release/SimulatorApp-Win32.exe) {exit 0} else {exit 1} + + mac_gen_simulator: + runs-on: macos-latest + name: MacOS + defaults: + run: + working-directory: ${{github.workspace}}/native + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-python@v2 + with: + python-version: "3.x" + - name: npm install + run: | + npm install + npm install gulp -g + - name: pip install + run: | + python -m pip install PyYAML Cheetah3 + - name: Download external libraries + run: | + node ./utils/download-deps.js + - 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: | + python -m pip install PyYAML==5.4.1 Cheetah3 + cd ./tools/tojs + echo "Create auto-generated jsbinding glue codes." + python ./genbindings.py + rm userconf.ini - name: gen simulator run: | gulp gen-simulator-release - name: check result run: | - Get-ChildItem ./simulator/Debug -Name SimulatorApp-Win32.exe - if(Test-Path ./simulator/Debug/SimulatorApp-Win32.exe) {exit 0} else {exit 1} - - # mac_gen_simulator: - # runs-on: macos-latest - # name: MacOS - # defaults: - # run: - # working-directory: ${{github.workspace}}/native - # steps: - # - uses: actions/checkout@v2 - # - uses: actions/setup-python@v2 - # with: - # python-version: "3.x" - # - name: npm install - # run: | - # npm install - # npm install gulp -g - # - name: download external libraries - # run: | - # node ./utils/download-deps.js - # - name: pip install - # run: | - # python -m pip install PyYAML Cheetah3 - # - name: generate bindings glue codes - # shell: bash - # run: | - # python -V - # cd ${{github.workspace}}/tools/travis-scripts - # echo "Create auto-generated jsbinding glue codes." - # pushd ${{github.workspace}}/tools/tojs - # python ./genbindings.py - # rm userconf.ini - # popd - # - name: gen simulator - # run: | - # gulp gen-simulator-release - # - name: check result - # run: | - # find ./ -name SimulatorApp-Mac - # [ -f ./simulator/Debug/SimulatorApp-Mac.app/Contents/MacOS/SimulatorApp-Mac ] && exit 0 || exit 1 + find ./ -name SimulatorApp-Mac + [ -f ./simulator/Release/SimulatorApp-Mac.app/Contents/MacOS/SimulatorApp-Mac ] && exit 0 || exit 1 diff --git a/.github/workflows/native-sync-template-version.yml b/.github/workflows/native-sync-template-version.yml new file mode 100644 index 0000000000..29377f2928 --- /dev/null +++ b/.github/workflows/native-sync-template-version.yml @@ -0,0 +1,45 @@ +name: Template Validation + +#on: [pull_request] +on: + pull_request: + paths: + - 'templates/common/**' + - 'templates/android/**' + - 'templates/windows/**' + - 'templates/ios/**' + - 'templates/mac/**' + - 'templates/qnx/**' + - 'templates/linux/**' + - 'templates/ohos/**' + +# github.head_ref is only defined on pull_request events +concurrency: + group: ${{ github.workflow }}-${{ github.actor }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + compile_linux: + name: "Linux-Ubuntu" + 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 + - id: files + continue-on-error: true + name: compatibility-info.json need update + uses: jitterbit/get-changed-files@v1 + - run: | + subfile="templates/compatibility-info.json" + for changed_file in ${{ steps.files.outputs.all }}; do + echo "Do something with this ${changed_file}." + if [[ "$changed_file" =~ .*"$subfile" ]]; then + echo "compatibility-info.json updated!" + exit 0 + else + echo "Test file $changed_file" + fi + done + echo "native templates is modified, pls consider if 'templates/compatibility-info.json' needs to be updated." + exit 1 \ No newline at end of file diff --git a/.github/workflows/native-unit-test.yml b/.github/workflows/native-unit-test.yml index c10b87c359..4a1d3635fc 100644 --- a/.github/workflows/native-unit-test.yml +++ b/.github/workflows/native-unit-test.yml @@ -1,10 +1,66 @@ name: Run Tests -on: [pull_request] +on: + pull_request: + paths: + - 'templates/**' + - 'native/**' + +# github.head_ref is only defined on pull_request events +concurrency: + group: ${{ github.workflow }}-${{ github.actor }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true jobs: unit-test-with-cmake: name: "Run on windows" + if: + (! contains(github.event.pull_request.body, '[X] does not change any runtime related code or build configuration')) + runs-on: windows-latest + defaults: + run: + working-directory: ${{github.workspace}}/native + steps: + - uses: actions/checkout@v2 + - uses: actions/setup-python@v2 + with: + python-version: "3.x" + + - name: Downlad external libraties + run: | + npm install + npm install gulp -g + node ./utils/download-deps.js + - uses: nttld/setup-ndk@v1 + id: setup-ndk + with: + ndk-version: r21e + add-to-path: false + - name: Generate bindings + shell: bash + env: + ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }} + run: | + python -m pip install PyYAML==5.4.1 Cheetah3 + python ./tools/tojs/genbindings.py + + - name: Run Unit Tests + shell: bash + run: | + cmake -B tests/unit-test/build -S tests/unit-test + cmake --build tests/unit-test/build --config Release + ./tests/unit-test/build/src/Release/CocosTest.exe + + #### TODO(PatriceJiang): model split + # - name: Run Module Tests + # shell: bash + # run: | + # cd tests/module-tests + # bash run-test-windows.sh + sebind-with-windows: + name: "sebind tests" + if: + (! contains(github.event.pull_request.body, '[X] does not change any runtime related code or build configuration')) runs-on: windows-latest defaults: run: @@ -21,22 +77,76 @@ jobs: npm install gulp -g node ./utils/download-deps.js + - uses: nttld/setup-ndk@v1 + id: setup-ndk + with: + ndk-version: r21e + add-to-path: false - name: Generate bindings shell: bash + env: + ANDROID_NDK_HOME: ${{ steps.setup-ndk.outputs.ndk-path }} run: | python -m pip install PyYAML==5.4.1 Cheetah3 python ./tools/tojs/genbindings.py - - name: Run Unit Tests + - name: Run Sebind Tests shell: bash run: | - cmake -B tests/unit-test/build -S tests/unit-test - cmake --build tests/unit-test/build --config Release - ./tests/unit-test/build/src/Release/CocosTest.exe - - #### TODO(PatriceJiang): model split - # - name: Run Module Tests - # shell: bash - # run: | - # cd tests/module-tests - # bash run-test-windows.sh + cd ${GITHUB_WORKSPACE}/native + cp -r ../templates/windows tests/sebind-tests/win64 + cd tests/sebind-tests + mkdir -p proj + cp cfg.cmake proj/ + GW="${GITHUB_WORKSPACE//\\/\/}" + cmake -B proj -S win64 -DRES_DIR="${GW}/native/tests/sebind-tests" -DCOCOS_X_PATH="${GW}/native" -DAPP_NAME=sebind + cmake --build proj + # cd proj/Debug + ## can not boot on this machine + # ./sebind.exe || true + # if [[ -f "result.txt" ]]; + # then + # echo "success!" + # else + # echo "Run sebind-tests fail!" + # exit 1 + # fi + + # sebind-run-on-linux: + # name: "Test sebind on Ubuntu" + # 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 + # - name: Generate bindings + # run: | + # python3 -m pip install PyYAML==5.4.1 Cheetah3 + # python3 ./native/tools/tojs/genbindings.py + # rm ./native/tools/tojs/userconf.ini + # - name: Install dependencies + # run: | + # sudo apt install libx11-dev -y + # sudo apt install libsndio-dev -y + # sudo apt install ninja-build -y + # - name: Run Sebind Tests + # shell: bash + # run: | + # cd ${GITHUB_WORKSPACE}/native + # cp -r ../templates/linux tests/sebind-tests/linux + # cd tests/sebind-tests + # mkdir -p proj + # cp cfg.cmake proj + # cmake -G Ninja -B proj -S linux -DRES_DIR=${GITHUB_WORKSPACE}/native/tests/sebind-tests/ -DCOCOS_X_PATH=${GITHUB_WORKSPACE}/native -DAPP_NAME=sebind + # cmake --build proj + # cd proj + # ./sebind || true + # if [[ -f "result.txt" ]]; + # then + # echo "success!" + # else + # echo "Run sebind-tests fail!" > /dev/stderr + # fi diff --git a/.github/workflows/native_compile_self.yml b/.github/workflows/native_compile_self.yml deleted file mode 100644 index 0f4c2d1111..0000000000 --- a/.github/workflows/native_compile_self.yml +++ /dev/null @@ -1,107 +0,0 @@ -name: Compile-self - -on: - pull_request: - paths: - - 'native/**' - -jobs: - compile_android: - name: "Android" - runs-on: aws-linux-action - - steps: - - uses: actions/checkout@v2 - - name: Download external libraries - shell: bash - run: | - EXT_VERSION=`grep version native/external-config.json |awk -F'"' '{print $4}'` - git clone --branch $EXT_VERSION --depth 1 https://github.com/cocos-creator/engine-native-external native/external - - - name: Generate bindings - run: | - NDK_ROOT='/home/tools/android-sdk-linux/ndk-bundle' - ANDROID_NDK_HOME='/home/tools/android-sdk-linux/ndk-bundle' - export NDK_ROOT ANDROID_NDK_HOME - python3 ./native/tools/tojs/genbindings.py - rm ./native/tools/tojs/userconf.ini - - - name: Compile - env: - COCOS_ENGINE_DEV: 1 - run: | - COCOS2DX_ROOT=$GITHUB_WORKSPACE/native - ANDORID_NDK='/home/tools/android-sdk-linux/ndk-bundle' - ANDROID_NDK_HOME='/home/tools/android-sdk-linux/ndk-bundle' - ANDROID_SDK_ROOT='/home/tools/android-sdk-linux' - export ANDORID_NDK ANDROID_SDK_ROOT ANDROID_NDK_HOME - NATIVE_DIR=$COCOS2DX_ROOT/templates/android-template - echo "Compiling Android ... " - cd $COCOS2DX_ROOT/templates/ - if [ ! -d android-template ]; then - cp -r android/template android-template - fi - cd $COCOS2DX_ROOT/templates/android/build - mkdir -p build-android/proj - touch build-android/proj/cfg.cmake - echo "set(CC_USE_GLES3 ON)" >> build-android/proj/cfg.cmake - echo "set(CC_USE_VULKAN ON)" >> build-android/proj/cfg.cmake - echo "set(CC_USE_GLES2 ON)" >> build-android/proj/cfg.cmake - echo "set(USE_WEBSOCKET_SERVER ON)" >> build-android/proj/cfg.cmake - echo "set(CMAKE_CXX_STANDARD_REQUIRED ON)" >> build-android/proj/cfg.cmake - mkdir -p build-android/assets - ASSET_DIR=$COCOS2DX_ROOT/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=$COCOS2DX_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_windows: - name: "Windows" - runs-on: aws-win-action - - steps: - - uses: actions/checkout@v2 - - name: Download external libraries - shell: bash - run: | - EXT_VERSION=`grep version native/external-config.json |awk -F'"' '{print $4}'` - git clone --branch $EXT_VERSION --depth 1 https://github.com/cocos-creator/engine-native-external native/external - - - name: Generate bindings - shell: bash - run: | - python2 -V - cd ./native/tools/tojs - echo "Create auto-generated jsbinding glue codes." - python2 ./genbindings.py - rm userconf.ini - - - name: Compile win64 - shell: bash - env: - COCOS_ENGINE_DEV: 1 - run: | - cd $GITHUB_WORKSPACE/native/templates/windows - mkdir -p build-win64/proj - touch build-win64/proj/cfg.cmake - echo "set(CC_USE_GLES3 ON)" >> build-win64/proj/cfg.cmake - echo "set(CC_USE_VULKAN ON)" >> build-win64/proj/cfg.cmake - echo "set(CC_USE_GLES2 ON)" >> build-win64/proj/cfg.cmake - echo "set(USE_WEBSOCKET_SERVER ON)" >> build-win64/proj/cfg.cmake - echo "set(CMAKE_CXX_STANDARD_REQUIRED ON)" >> build-win64/proj/cfg.cmake - mkdir build-win64/assets - cd build-win64 - RES_DIR=${GITHUB_WORKSPACE//\\//}/native/templates/windows/build-win64 - COCOS_X_PATH=${GITHUB_WORKSPACE//\\//}/native - cmake ../ -G"Visual Studio 15 2017" -DRES_DIR=$RES_DIR -DCOCOS_X_PATH=$COCOS_X_PATH -Ax64 - cmake --build . --config Release - echo "Compile Win64 Release Done!" diff --git a/.github/workflows/run_test_cases.yml b/.github/workflows/run_test_cases.yml index c419816edf..1baa89c064 100644 --- a/.github/workflows/run_test_cases.yml +++ b/.github/workflows/run_test_cases.yml @@ -1,14 +1,13 @@ name: run test cases on: - pull_request: pull_request_target: issue_comment: types: [created, edited] # github.head_ref is only defined on pull_request events concurrency: - group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + group: ${{ github.workflow }}-${{ github.actor }}-${{ github.head_ref || github.run_id }} cancel-in-progress: true jobs: @@ -16,7 +15,6 @@ jobs: if: | contains(github.event.pull_request.body, '[X] needs automatic test cases check') || contains(github.event.comment.body, '@cocos-robot run test cases') - runs-on: self-hosted-win steps: @@ -30,7 +28,6 @@ jobs: else { Write-Host "::set-output name=pr_number::${{ github.event.pull_request.number }}" } - - name: Get PR Details id: pr_details uses: octokit/request-action@v2.x @@ -53,14 +50,12 @@ jobs: Write-Host "::set-output name=pr_head_sha::$($pull_request.head.sha)" Write-Host "::set-output name=pr_base_ref::$($pull_request.base.ref)" Write-Host "::set-output name=pr_base_sha::$($pull_request.base.sha)" - - name: Check Job Parameter run: | echo "${{ steps.parse_pr.outputs.pr_head_ref }}" echo "${{ steps.parse_pr.outputs.pr_head_sha }}" echo "${{ steps.parse_pr.outputs.pr_base_ref }}" echo "${{ steps.parse_pr.outputs.pr_base_sha }}" - - name: Checkout engine uses: actions/checkout@v3 with: @@ -77,19 +72,16 @@ jobs: git branch ${{ steps.parse_pr.outputs.pr_base_ref }} git fetch origin pull/${{ steps.get_pr.outputs.pr_number }}/head:pull-${{ steps.get_pr.outputs.pr_number }} git merge --ff -s recursive --no-verify -m "PR Test" origin/${{ steps.parse_pr.outputs.pr_base_ref }} pull-${{ steps.get_pr.outputs.pr_number }} - - name: npm install run: | npm -v npm install --registry https://registry.npm.taobao.org - - name: Run test cases timeout-minutes: 120 id: run_test_cases run: | cd .. python3 -u ./python/main.py ${{ steps.parse_pr.outputs.pr_base_ref }} - - name: Update Comment uses: peter-evans/create-or-update-comment@v1 with: @@ -101,13 +93,10 @@ jobs: - Task URL: ${{ steps.run_test_cases.outputs.url }} - Task Details: ${{ steps.run_test_cases.outputs.msg }} - GitHub Action: https://github.com/cocos/cocos-engine/actions/runs/${{ github.run_id }} - - macOS-RunTestCases: if: | contains(github.event.pull_request.body, '[X] needs automatic test cases check') || contains(github.event.comment.body, '@cocos-robot run test cases') - runs-on: self-hosted-mac steps: @@ -121,7 +110,6 @@ jobs: else { Write-Host "::set-output name=pr_number::${{ github.event.pull_request.number }}" } - - name: Get PR Details id: pr_deatils uses: octokit/request-action@v2.x @@ -144,7 +132,6 @@ jobs: Write-Host "::set-output name=pr_head_sha::$($pull_request.head.sha)" Write-Host "::set-output name=pr_base_ref::$($pull_request.base.ref)" Write-Host "::set-output name=pr_base_sha::$($pull_request.base.sha)" - - name: Check Job Parameter run: | echo "${{ steps.parse_pr.outputs.pr_head_ref }}" @@ -168,19 +155,16 @@ jobs: git branch ${{ steps.parse_pr.outputs.pr_base_ref }} git fetch origin pull/${{ steps.get_pr.outputs.pr_number }}/head:pull-${{ steps.get_pr.outputs.pr_number }} git merge --ff -s recursive --no-verify -m "PR Test" origin/${{ steps.parse_pr.outputs.pr_base_ref }} pull-${{ steps.get_pr.outputs.pr_number }} - - name: npm install run: | npm -v npm install --registry https://registry.npm.taobao.org - - name: Run test cases timeout-minutes: 90 id: run_test_cases run: | cd .. python3 -u ./python/main.py ${{ steps.parse_pr.outputs.pr_base_ref }} - - name: Update Comment uses: peter-evans/create-or-update-comment@v1 with: diff --git a/.github/workflows/web-build.yml b/.github/workflows/web-build.yml index f98fbe3914..ca410269a7 100644 --- a/.github/workflows/web-build.yml +++ b/.github/workflows/web-build.yml @@ -5,11 +5,17 @@ name: build on: [pull_request] + +# github.head_ref is only defined on pull_request events +concurrency: + group: ${{ github.workflow }}-${{ github.actor }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + jobs: build: - runs-on: ubuntu-latest - + if: + (! contains(github.event.pull_request.body, '[X] does not change any runtime related code or build configuration')) strategy: matrix: node-version: [12.x] diff --git a/.github/workflows/web-check_version.yml b/.github/workflows/web-check_version.yml index 63dad91928..fdfa953cf2 100644 --- a/.github/workflows/web-check_version.yml +++ b/.github/workflows/web-check_version.yml @@ -3,10 +3,16 @@ name: Check version #on: push on: [create, pull_request] +# github.head_ref is only defined on pull_request events +concurrency: + group: ${{ github.workflow }}-${{ github.actor }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + jobs: - Check_pull_request_version: + Check_package_version: runs-on: ubuntu-latest - if: github.event_name == 'pull_request' + if: + (! contains(github.event.pull_request.body, '[X] does not change any runtime related code or build configuration')) steps: - uses: actions/checkout@v2 @@ -15,25 +21,16 @@ jobs: node -v npm install || exit 0 - - name: check version + - name: check version pull_request + if: github.event_name == 'pull_request' run: | branch=`echo ${{ github.base_ref }} | awk -F'/' '{print $NF}'` echo "Branch: ${branch}" npm run varify-engine-version -- ${branch} - - Check_create_version: - runs-on: ubuntu-latest - if: github.event_name == 'create' - steps: - - uses: actions/checkout@v2 - - - name: npm install - run: | - node -v - npm install || exit 0 - - name: check version + + - name: check version create + if: github.event_name == 'create' run: | branch=`echo ${{ github.ref }} | awk -F'/' '{print $NF}'` echo "Branch: ${branch}" npm run varify-engine-version -- ${branch} - diff --git a/.github/workflows/web-interface-check.yml b/.github/workflows/web-interface-check.yml index 99f25eab62..979b53ff41 100644 --- a/.github/workflows/web-interface-check.yml +++ b/.github/workflows/web-interface-check.yml @@ -3,8 +3,15 @@ name: Interface check #on: push on: [pull_request_target] +# github.head_ref is only defined on pull_request events +concurrency: + group: ${{ github.workflow }}-${{ github.actor }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + jobs: interface_check: + if: + (! contains(github.event.pull_request.body, '[X] does not change any runtime related code or build configuration')) runs-on: ubuntu-latest steps: - name: clone REPO @@ -36,6 +43,7 @@ jobs: run: | git checkout . git clean -xfd + npm cache clean --force ls -la - name: merge HEAD branch diff --git a/.github/workflows/web-npm_test.yml b/.github/workflows/web-npm_test.yml index c438f46dc5..e745221ac5 100644 --- a/.github/workflows/web-npm_test.yml +++ b/.github/workflows/web-npm_test.yml @@ -2,10 +2,16 @@ name: npm test on: [push, pull_request] +# github.head_ref is only defined on pull_request events +concurrency: + group: ${{ github.workflow }}-${{ github.actor }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + jobs: npm_test: + if: + (! contains(github.event.pull_request.body, '[X] does not change any runtime related code or build configuration')) runs-on: ubuntu-18.04 - steps: - uses: actions/checkout@v2 diff --git a/.github/workflows/web-quality.yml b/.github/workflows/web-quality.yml index 7a6ee86f55..77564ec05e 100644 --- a/.github/workflows/web-quality.yml +++ b/.github/workflows/web-quality.yml @@ -1,9 +1,18 @@ name: Quality + on: [push, pull_request] + +# github.head_ref is only defined on pull_request events +concurrency: + group: ${{ github.workflow }}-${{ github.actor }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + jobs: eslint: name: Run ESLint - if: github.actor!= 'dependabot' # ignore the pull request which comes from user dependabot. See https://github.community/t/how-to-stop-github-actions-workflow-to-trigger-when-the-pull-request-is-from-dependabot-preview/116486/3 + #if: github.actor!= 'dependabot' # ignore the pull request which comes from user dependabot. See https://github.community/t/how-to-stop-github-actions-workflow-to-trigger-when-the-pull-request-is-from-dependabot-preview/116486/3 + 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 diff --git a/.gitignore b/.gitignore index 55142568c0..ccdb19bfec 100644 --- a/.gitignore +++ b/.gitignore @@ -20,6 +20,8 @@ playground/library 3d-api-docs scripts/build-engine/node_modules scripts/build-engine/dist +scripts/native-pack-tool/dist +scripts/native-pack-tool/node_modules tests/core/serialization/ccob-serialized-gallery @@ -43,3 +45,6 @@ scripts/runtime-web-adapter native/external/ scripts/typedoc-plugin/lib/ +!templates/**/* + +@types/consts.d.ts \ No newline at end of file diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000000..8351c19397 --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +14 diff --git a/.vscode/cSpell.json b/.vscode/cSpell.json index 08c64ae1b8..43327368fb 100644 --- a/.vscode/cSpell.json +++ b/.vscode/cSpell.json @@ -21,6 +21,7 @@ "eventified", "eventify", "forin", + "interruptible", "glsl", "grayscale", "IGFX", diff --git a/.vscode/launch.json b/.vscode/launch.json index 4d2e6e6087..23f1727d5e 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -56,7 +56,8 @@ "program": "${workspaceFolder}/node_modules/jest/bin/jest.js" }, "args": [ - "${fileBasenameNoExtension}" + "--runTestsByPath", + "${relativeFileDirname}/${fileBasename}" ], "cwd": "${workspaceFolder}", "console": "integratedTerminal", diff --git a/.vscode/settings.json b/.vscode/settings.json index e7a4528355..8433aab21d 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -18,4 +18,7 @@ "editor.codeActionsOnSave": { "source.fixAll": true, }, + "files.associations": { + "iterator": "cpp" + }, } diff --git a/@types/consts.d.ts b/@types/consts.d.ts deleted file mode 100644 index 3aee7256f3..0000000000 --- a/@types/consts.d.ts +++ /dev/null @@ -1,124 +0,0 @@ -declare module 'internal:constants' { - /** - * This constant is private and used for internal purpose only. - * - * If true, some of the constants of `internal:constants` would be also export to the global namespace. - * For example would set `CC_EDITOR` on `globalThis` as `EDITOR`. - * This is due to we at present inherits the way how Creator prior to 3.0 deploys the build time constants. - */ - export const EXPORT_TO_GLOBAL: boolean; - - /** - * Running in published project. - */ - export const BUILD: boolean; - - /** - * Running in the engine's unit test. - */ - export const TEST: boolean; - - /** - * Running in the editor. - */ - export const EDITOR: boolean; - - /** - * Preview in browser or simulator. - */ - export const PREVIEW: boolean; - - /** - * Running in the editor or preview. - */ - export const DEV: boolean; - - /** - * Running in the editor or preview, or build in debug mode. - */ - export const DEBUG: boolean; - - /** - * Running in native platform (mobile app, desktop app, or simulator). - */ - export const NATIVE: boolean; - - export const JSB: boolean; - - export const HTML5: boolean; - - /** - * Running in the Wechat's mini game. - */ - export const WECHAT: boolean; - - /** - * Running in the alipay's mini game. - */ - export const ALIPAY: boolean; - - /** - * Running in the xiaomi's quick game. - */ - export const XIAOMI: boolean; - - /** - * Running in the ByteDance's quick game. - */ - export const BYTEDANCE: boolean; - - /** - * Running in the baidu's mini game. - */ - export const BAIDU: boolean; - - /** - * Running in the cocosplay. - */ - export const COCOSPLAY: boolean; - - /** - * Running in the huawei's quick game. - */ - export const HUAWEI: boolean; - - /** - * Running in the oppo's mini game. - */ - export const OPPO: boolean; - - /** - * Running in the vivo's mini game. - */ - export const VIVO: boolean; - - /** - * Running in the qtt's quick game. - */ - export const QTT: boolean; - - /** - * Running in the linksure's quick game. - */ - export const LINKSURE: boolean; - - /** - * Running in mini game. - */ - export const MINIGAME: boolean; - - /** - * Running in runtime environments. - */ - export const RUNTIME_BASED: boolean; - - /** - * Environment support JIT, currently iOS native and mini game doesn't support JIT - */ - export const SUPPORT_JIT: boolean; - - /** - * Running in server mode. - */ - export const SERVER_MODE: boolean; -} diff --git a/@types/globals.d.ts b/@types/globals.d.ts index 750b84f324..d82abda768 100644 --- a/@types/globals.d.ts +++ b/@types/globals.d.ts @@ -84,6 +84,8 @@ declare interface IWritableArrayLike { declare type Constructor = new (...args: any[]) => T; +declare type AbstractedConstructor = abstract new (...args: any[]) => T; + /** * Alias of `Function` but suppress eslint warning. * Please avoid using it and explicitly specify function signatures as possible. diff --git a/@types/jsb.d.ts b/@types/jsb.d.ts index 2bbd0547f0..588f5e757c 100644 --- a/@types/jsb.d.ts +++ b/@types/jsb.d.ts @@ -5,6 +5,8 @@ * API for jsb module * Author: haroel * Homepage: https://github.com/haroel/creatorexDTS + * + * @deprecated since v3.6.0, please import `native` from 'cc' module instead like `import { native } from 'cc';`. */ declare namespace jsb { @@ -88,9 +90,27 @@ declare namespace jsb { export let onClose: () => void | undefined; export function openURL(url: string): void; export function garbageCollect(): void; - + enum AudioFormat { + UNKNOWN, + SIGNED_8, + UNSIGNED_8, + SIGNED_16, + UNSIGNED_16, + SIGNED_32, + UNSIGNED_32, + FLOAT_32, + FLOAT_64 + } + interface PCMHeader { + totalFrames: number; + sampleRate: number; + bytesPerFrame: number; + audioFormat: AudioFormat; + channelCount: number; + } export namespace AudioEngine { export function preload (url: string, cb: (isSuccess: boolean) => void); + export function play2d (url: string, loop: boolean, volume: number): number; export function pause (id: number); export function pauseAll (); @@ -115,6 +135,17 @@ declare namespace jsb { export function uncacheAll (); export function setErrorCallback (id: number, cb: (err: any) => void); export function setFinishCallback (id: number, cb: () => void); + + /** + * Get PCM header without pcm data. if you want to get pcm data, use getOriginalPCMBuffer instead + */ + export function getPCMHeader (url: string) : PCMHeader; + /** + * Get PCM Data in decode format for example Int16Array, the format information is written in PCMHeader. + * @param url: file relative path, for example player._path + * @param channelID: ChannelID which should smaller than channel count, start from 0 + */ + export function getOriginalPCMBuffer (url: string, channelID: number): ArrayBuffer | undefined; } export namespace reflection{ @@ -167,30 +198,6 @@ declare namespace jsb { */ export function removeAllListeners(); } - /** - * 下载任务对象 - */ - export type DownloaderTask = { requestURL: string, storagePath: string, identifier: string }; - - /** - * Http file downloader for jsb! - */ - export class Downloader { - /** - * create a download task - * @param requestURL - * @param storagePath - * @param identifier - */ - createDownloadFileTask (requestURL:string, storagePath:string, identifier?:string): DownloaderTask; - - setOnFileTaskSuccess (onSucceed: (task: DownloaderTask) => void): void; - - setOnTaskProgress (onProgress: (task: DownloaderTask, bytesReceived: number, - totalBytesReceived: number, totalBytesExpected: number) => void): void; - - setOnTaskError (onError: (task: DownloaderTask, errorCode: number, errorCodeInternal: number, errorStr: string) => void): void; - } export interface ManifestAsset { md5: string; @@ -310,460 +317,4 @@ declare namespace jsb { setVerifyCallback (verifyCallback: (path: string, asset: ManifestAsset) => boolean): void; setEventCallback (eventCallback: (event: EventAssetsManager) => void): void; } - - /** - * FileUtils Helper class to handle file operations. - */ - export namespace fileUtils{ - /** - * Checks whether the path is an absolute path. - * - * @note On Android, if the parameter passed in is relative to "@assets/", this method will treat it as an absolute path. - * Also on Blackberry, path starts with "app/native/Resources/" is treated as an absolute path. - * - * @param path The path that needs to be checked. - * @return True if it's an absolute path, false if not. - */ - export function isAbsolutePath (path:string):boolean; - /** Returns the fullpath for a given filename. - - First it will try to get a new filename from the "filenameLookup" dictionary. - If a new filename can't be found on the dictionary, it will use the original filename. - Then it will try to obtain the full path of the filename using the FileUtils search rules: resolutions, and search paths. - The file search is based on the array element order of search paths and resolution directories. - - For instance: - - We set two elements("/mnt/sdcard/", "internal_dir/") to search paths vector by setSearchPaths, - and set three elements("resources-ipadhd/", "resources-ipad/", "resources-iphonehd") - to resolutions vector by setSearchResolutionsOrder. The "internal_dir" is relative to "Resources/". - - If we have a file named 'sprite.png', the mapping in fileLookup dictionary contains `key: sprite.png -> value: sprite.pvr.gz`. - Firstly, it will replace 'sprite.png' with 'sprite.pvr.gz', then searching the file sprite.pvr.gz as follows: - - /mnt/sdcard/resources-ipadhd/sprite.pvr.gz (if not found, search next) - /mnt/sdcard/resources-ipad/sprite.pvr.gz (if not found, search next) - /mnt/sdcard/resources-iphonehd/sprite.pvr.gz (if not found, search next) - /mnt/sdcard/sprite.pvr.gz (if not found, search next) - internal_dir/resources-ipadhd/sprite.pvr.gz (if not found, search next) - internal_dir/resources-ipad/sprite.pvr.gz (if not found, search next) - internal_dir/resources-iphonehd/sprite.pvr.gz (if not found, search next) - internal_dir/sprite.pvr.gz (if not found, return "sprite.png") - - If the filename contains relative path like "gamescene/uilayer/sprite.png", - and the mapping in fileLookup dictionary contains `key: gamescene/uilayer/sprite.png -> value: gamescene/uilayer/sprite.pvr.gz`. - The file search order will be: - - /mnt/sdcard/gamescene/uilayer/resources-ipadhd/sprite.pvr.gz (if not found, search next) - /mnt/sdcard/gamescene/uilayer/resources-ipad/sprite.pvr.gz (if not found, search next) - /mnt/sdcard/gamescene/uilayer/resources-iphonehd/sprite.pvr.gz (if not found, search next) - /mnt/sdcard/gamescene/uilayer/sprite.pvr.gz (if not found, search next) - internal_dir/gamescene/uilayer/resources-ipadhd/sprite.pvr.gz (if not found, search next) - internal_dir/gamescene/uilayer/resources-ipad/sprite.pvr.gz (if not found, search next) - internal_dir/gamescene/uilayer/resources-iphonehd/sprite.pvr.gz (if not found, search next) - internal_dir/gamescene/uilayer/sprite.pvr.gz (if not found, return "gamescene/uilayer/sprite.png") - - If the new file can't be found on the file system, it will return the parameter filename directly. - - This method was added to simplify multiplatform support. - Whether you are using cocos2d-js or any cross-compilation toolchain like StellaSDK or Apportable, - you might need to load different resources for a given file in the different platforms. - - @since v2.1 - */ - export function fullPathForFilename (filename:string):string; - /** - * Gets string from a file. - */ - export function getStringFromFile (filename:string):string; - /** - * Removes a file. - * - * @param filepath The full path of the file, it must be an absolute path. - * @return True if the file have been removed successfully, false if not. - */ - export function removeFile (filepath:string):boolean; - /** - * Checks whether the path is a directory. - * - * @param dirPath The path of the directory, it could be a relative or an absolute path. - * @return True if the directory exists, false if not. - */ - export function isDirectoryExist (dirPath:string):boolean; - /** - * Normalize: remove . and .. - * @param filepath - */ - export function normalizePath (filepath:string):string; - /** - * Get default resource root path. - */ - export function getDefaultResourceRootPath ():string; - /** - * Loads the filenameLookup dictionary from the contents of a filename. - * - * @note The plist file name should follow the format below: - * - * @code - * - * - * - * - * filenames - * - * sounds/click.wav - * sounds/click.caf - * sounds/endgame.wav - * sounds/endgame.caf - * sounds/gem-0.wav - * sounds/gem-0.caf - * - * metadata - * - * version - * 1 - * - * - * - * @endcode - * @param filename The plist file name. - * - @since v2.1 - * @js loadFilenameLookup - * @lua loadFilenameLookup - */ - export function loadFilenameLookup (filepath:string):void; - /** Checks whether to pop up a message box when failed to load an image. - * @return True if pop up a message box when failed to load an image, false if not. - */ - export function isPopupNotify ():boolean; - /** - * Sets whether to pop-up a message box when failed to load an image. - */ - export function setPopupNotify (notify:boolean):void; - - // Converts the contents of a file to a ValueVector. - // This method is used internally. - export function getValueVectorFromFile (filepath:string):Array; - /** - * Gets the array of search paths. - * - * @return The array of search paths which may contain the prefix of default resource root path. - * @note In best practise, getter function should return the value of setter function passes in. - * But since we should not break the compatibility, we keep using the old logic. - * Therefore, If you want to get the original search paths, please call 'getOriginalSearchPaths()' instead. - * @see fullPathForFilename(const char*). - * @lua NA - */ - export function getSearchPaths ():Array; - /** - * - * @param filepath - */ - export function getFileDir (filepath:string):string; - /** - * write a ValueMap into a plist file - * - *@param dict the ValueMap want to save (key,value) - *@param fullPath The full path to the file you want to save a string - *@return bool - */ - export function writeToFile (valueMap:any):boolean; - /** - * Gets the original search path array set by 'setSearchPaths' or 'addSearchPath'. - * @return The array of the original search paths - */ - export function getOriginalSearchPaths ():Array; - /** - * List all files in a directory. - * - * @param dirPath The path of the directory, it could be a relative or an absolute path. - * @return File paths in a string vector - */ - export function listFiles (filepath:string):Array; - /** - * Converts the contents of a file to a ValueMap. - * @param filename The filename of the file to gets content. - * @return ValueMap of the file contents. - * @note This method is used internally. - */ - export function getValueMapFromFile (filepath:string):any; - /** - * Retrieve the file size. - * - * @note If a relative path was passed in, it will be inserted a default root path at the beginning. - * @param filepath The path of the file, it could be a relative or absolute path. - * @return The file size. - */ - export function getFileSize (filepath:string):number; - - /** Converts the contents of a file to a ValueMap. - * This method is used internally. - */ - export function getValueMapFromData (filedata:string, filesize:number):any; - /** - * Removes a directory. - * - * @param dirPath The full path of the directory, it must be an absolute path. - * @return True if the directory have been removed successfully, false if not. - */ - export function removeDirectory (dirPath:string):boolean; - /** - * Sets the array of search paths. - * - * You can use this array to modify the search path of the resources. - * If you want to use "themes" or search resources in the "cache", you can do it easily by adding new entries in this array. - * - * @note This method could access relative path and absolute path. - * If the relative path was passed to the vector, FileUtils will add the default resource directory before the relative path. - * For instance: - * On Android, the default resource root path is "@assets/". - * If "/mnt/sdcard/" and "resources-large" were set to the search paths vector, - * "resources-large" will be converted to "@assets/resources-large" since it was a relative path. - * - * @param searchPaths The array contains search paths. - * @see fullPathForFilename(const char*) - * @since v2.1 - * In js:var setSearchPaths(var jsval); - * @lua NA - */ - export function setSearchPaths (searchPath:Array):void; - /** - * write a string into a file - * - * @param dataStr the string want to save - * @param fullPath The full path to the file you want to save a string - * @return bool True if write success - */ - export function writeStringToFile (dataStr:string, fullPath:string):boolean; - /** - * Sets the array that contains the search order of the resources. - * - * @param searchResolutionsOrder The source array that contains the search order of the resources. - * @see getSearchResolutionsOrder(), fullPathForFilename(const char*). - * @since v2.1 - * In js:var setSearchResolutionsOrder(var jsval) - * @lua NA - */ - export function setSearchResolutionsOrder (searchResolutionsOrder:Array):void; - /** - * Append search order of the resources. - * - * @see setSearchResolutionsOrder(), fullPathForFilename(). - * @since v2.1 - */ - export function addSearchResolutionsOrder (order:string, front:boolean):void; - /** - * Add search path. - * - * @since v2.1 - */ - export function addSearchPath (path:string, front:boolean):void; - /** - * write ValueVector into a plist file - * - *@param vecData the ValueVector want to save - *@param fullPath The full path to the file you want to save a string - *@return bool - */ - export function writeValueVectorToFile (vecData:Array, fullPath:string):boolean; - /** - * Checks whether a file exists. - * - * @note If a relative path was passed in, it will be inserted a default root path at the beginning. - * @param filename The path of the file, it could be a relative or absolute path. - * @return True if the file exists, false if not. - */ - export function isFileExist (filename:string):boolean; - /** - * Purges full path caches. - */ - export function purgeCachedEntries ():void; - /** - * Gets full path from a file name and the path of the relative file. - * @param filename The file name. - * @param relativeFile The path of the relative file. - * @return The full path. - * e.g. filename: hello.png, pszRelativeFile: /User/path1/path2/hello.plist - * Return: /User/path1/path2/hello.pvr (If there a a key(hello.png)-value(hello.pvr) in FilenameLookup dictionary. ) - * - */ - export function fullPathFromRelativeFile (filename:string, relativeFile:string):string; - /** - * Windows fopen can't support UTF-8 filename - * Need convert all parameters fopen and other 3rd-party libs - * - * @param filenameUtf8 std::string name file for conversion from utf-8 - * @return std::string ansi filename in current locale - */ - export function getSuitableFOpen (filenameUtf8:string):string; - /** - * write ValueMap into a plist file - * - *@param dict the ValueMap want to save - *@param fullPath The full path to the file you want to save a string - *@return bool - */ - export function writeValueMapToFile (dict:any, fullPath:string):string; - /** - * Gets filename extension is a suffix (separated from the base filename by a dot) in lower case. - * Examples of filename extensions are .png, .jpeg, .exe, .dmg and .txt. - * @param filePath The path of the file, it could be a relative or absolute path. - * @return suffix for filename in lower case or empty if a dot not found. - */ - export function getFileExtension (filePath:string):string; - /** - * Sets writable path. - */ - export function setWritablePath (writablePath:string):void; - /** - * Set default resource root path. - */ - export function setDefaultResourceRootPath (filepath:string):void; - - /** - * Gets the array that contains the search order of the resources. - * - * @see setSearchResolutionsOrder(const std::vector&), fullPathForFilename(const char*). - * @since v2.1 - * @lua NA - */ - export function getSearchResolutionsOrder ():Array; - /** - * Creates a directory. - * - * @param dirPath The path of the directory, it must be an absolute path. - * @return True if the directory have been created successfully, false if not. - */ - export function createDirectory (dirPath:string):string; - /** - * List all files recursively in a directory. - * - * @param dirPath The path of the directory, it could be a relative or an absolute path. - * @return File paths in a string vector - */ - export function listFilesRecursively (dirPath:string, files:Array):void; - /** - * Gets the writable path. - * @return The path that can be write/read a file in - */ - export function getWritablePath ():string; - } - - /** - * ZipUtils Helper class to handle unzip related operations. - */ - export namespace zipUtils{ - /** - * Inflates either zlib or gzip deflated memory. The inflated memory is expected to be freed by the caller. - * - * It will allocate 256k for the destination buffer. - * If it is not enough it will multiply the previous buffer size per 2, until there is enough memory. - * - * @param outLengthHint It is assumed to be the needed room to allocate the inflated buffer, which is optional. - * - * - * @return The deflated buffer. - */ - export function inflateMemory(input:string | ArrayBuffer | TypedArray, outLengthHint?: number): ArrayBuffer | null; - - /** - * Inflates a GZip file into memory. - * - * @return The deflated buffer. - */ - export function inflateGZipFile(path:string): ArrayBuffer | null; - - /** - * Test a file is a GZip format file or not. - * - * @return True is a GZip format file. false is not. - */ - export function isGZipFile(path:string): boolean; - - /** - * Test the buffer is GZip format or not. - * - * @return True is GZip format. false is not. - */ - export function isGZipBuffer(buffer:string | ArrayBuffer | TypedArray): boolean; - - /** - * Inflates a CCZ file into memory. - * - * @return The deflated buffer. - */ - export function inflateCCZFile(path:string): ArrayBuffer | null; - - /** - * Inflates a buffer with CCZ format into memory. - * - * @return The deflated buffer. - */ - export function inflateCCZBuffer(buffer:string | ArrayBuffer | TypedArray): ArrayBuffer | null; - - /** - * Test a file is a CCZ format file or not. - * - * @return True is a CCZ format file. false is not. - */ - export function isCCZFile(path:string): boolean; - - /** - * Test the buffer is CCZ format or not. - * - * @return True is CCZ format. false is not. - */ - export function isCCZBuffer(buffer:string | ArrayBuffer | TypedArray): boolean; - - /** - * Sets the pvr.ccz encryption key parts separately for added security. - * - * Example: If the key used to encrypt the pvr.ccz file is - * 0xaaaaaaaabbbbbbbbccccccccdddddddd you will call this function 4 - * different times, preferably from 4 different source files, as follows - * - * setPvrEncryptionKeyPart(0, 0xaaaaaaaa); - * setPvrEncryptionKeyPart(1, 0xbbbbbbbb); - * setPvrEncryptionKeyPart(2, 0xcccccccc); - * setPvrEncryptionKeyPart(3, 0xdddddddd); - * - * Splitting the key into 4 parts and calling the function from 4 different source - * files increases the difficulty to reverse engineer the encryption key. - * Be aware that encryption is *never* 100% secure and the key code - * can be cracked by knowledgable persons. - * - * IMPORTANT: Be sure to call setPvrEncryptionKey or - * setPvrEncryptionKeyPart with all of the key parts *before* loading - * the sprite sheet or decryption will fail and the sprite sheet - * will fail to load. - * - * @param index Part of the key [0..3]. - * @param value Value of the key part. - */ - export function setPvrEncryptionKeyPart(index:number, value:number): void; - - /** - * Sets the pvr.ccz encryption key. - * - * Example: If the key used to encrypt the pvr.ccz file is - * 0xaaaaaaaabbbbbbbbccccccccdddddddd you will call this function with - * the key split into 4 parts as follows - * - * setPvrEncryptionKey(0xaaaaaaaa, 0xbbbbbbbb, 0xcccccccc, 0xdddddddd); - * - * Note that using this function makes it easier to reverse engineer and discover - * the complete key because the key parts are present in one function call. - * - * IMPORTANT: Be sure to call setPvrEncryptionKey or setPvrEncryptionKeyPart - * with all of the key parts *before* loading the spritesheet or decryption - * will fail and the sprite sheet will fail to load. - * - * @param keyPart1 The key value part 1. - * @param keyPart2 The key value part 2. - * @param keyPart3 The key value part 3. - * @param keyPart4 The key value part 4. - */ - export function setPvrEncryptionKey(keyPart1:number, keyPart2:number, keyPart3:number, keyPart4:number): void; - } } diff --git a/@types/pal/audio.d.ts b/@types/pal/audio.d.ts index fbaebe7da2..45a18e8c0e 100644 --- a/@types/pal/audio.d.ts +++ b/@types/pal/audio.d.ts @@ -117,6 +117,17 @@ declare module 'pal/audio' { */ get currentTime (): number; + /** + * Get the sample rate. + */ + get sampleRate (): number; + + /** + * Get pcm data view from specified channel. + * @param channelIndex The channel index. 0 is left channel, 1 is right channel. + */ + public getPCMData (channelIndex: number): import('pal/audio/type').AudioPCMDataView | undefined; + /** * Asynchronously seeks the player's playing time onto specified location. * @param time Desired playing time. diff --git a/@types/pal/env.d.ts b/@types/pal/env.d.ts new file mode 100644 index 0000000000..059b47ae25 --- /dev/null +++ b/@types/pal/env.d.ts @@ -0,0 +1,4 @@ +declare module 'pal/env' { + export function findCanvas (): { frame: HTMLDivElement, container: HTMLDivElement, canvas: HTMLCanvasElement }; + export function loadJsFile (path: string): Promise; +} diff --git a/@types/pal/input.d.ts b/@types/pal/input.d.ts index faaaa22e78..b834576d77 100644 --- a/@types/pal/input.d.ts +++ b/@types/pal/input.d.ts @@ -19,6 +19,11 @@ declare module 'pal/input' { * Register the mouse event callback. */ public on (eventType: import('cocos/input/types/event-enum').InputEventType, callback: MouseCallback, target?: any); + + public dispatchMouseDownEvent? (nativeMouseEvent: any); + public dispatchMouseMoveEvent? (nativeMouseEvent: any); + public dispatchMouseUpEvent? (nativeMouseEvent: any); + public dispatchScrollEvent? (nativeMouseEvent: any); } type KeyboardCallback = (res: import('cocos/input/types').EventKeyboard) => void; @@ -30,6 +35,9 @@ declare module 'pal/input' { * Register the keyboard event callback. */ public on (eventType: import('cocos/input/types/event-enum').InputEventType, callback: KeyboardCallback, target?: any); + + public dispatchKeyboardDownEvent? (nativeKeyboardEvent: any); + public dispatchKeyboardUpEvent? (nativeKeyboardEvent: any); } /** diff --git a/@types/pal/minigame.d.ts b/@types/pal/minigame.d.ts index 45a07ef8af..54fe041bc8 100644 --- a/@types/pal/minigame.d.ts +++ b/@types/pal/minigame.d.ts @@ -1,9 +1,11 @@ declare module 'pal/minigame' { export const minigame: IMiniGame; export interface IMiniGame { + setPreferredFramesPerSecond(_targetFrameRate: number); // platform related wx?: WeChatAPI; tt?: ByteDanceAPI; + ral?: RuntimeAPI; // system isDevTool: boolean; @@ -24,6 +26,8 @@ declare module 'pal/minigame' { triggerGC(): void; getBatteryInfoSync(): BatteryInfo; + exitMiniProgram? (): void; + // render getSharedCanvas(): any; getOpenDataContext(): any; @@ -82,6 +86,23 @@ declare module 'pal/minigame' { deltaY: number; deltaZ: number; } + + interface ICANVAS_CONTEXT2D_TEXTBASELINE_ALPHABETIC { + name: string, + enable: number, + } + interface ICANVAS_CONTEXT2D_TEXTBASELINE_DEFAULT { + name: string, + alphabetic: number, + } + + interface RuntimeAPI { + CANVAS_CONTEXT2D_TEXTBASELINE_ALPHABETIC: ICANVAS_CONTEXT2D_TEXTBASELINE_ALPHABETIC, + CANVAS_CONTEXT2D_TEXTBASELINE_DEFAULT: ICANVAS_CONTEXT2D_TEXTBASELINE_DEFAULT, + getFeaturePropertyInt(featureName: string): number; + setFeaturePropertyInt(featureName: string, value: number); + } + interface ByteDanceAPI { getAudioContext?: () => AudioContext; } diff --git a/@types/pal/pacer.d.ts b/@types/pal/pacer.d.ts new file mode 100644 index 0000000000..19f548cc1a --- /dev/null +++ b/@types/pal/pacer.d.ts @@ -0,0 +1,10 @@ +declare module 'pal/pacer' { + + export class Pacer { + get targetFrameRate (): number; + set targetFrameRate (val: number); + onTick: (() => void) | null; + start (): void; + stop (): void; + } +} diff --git a/EngineErrorMap.md b/EngineErrorMap.md index 4b0e8df27b..3269cafad4 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -1837,6 +1837,13 @@ We don't currently support conversion of \`CubicSplineQuatValue\`. Instancing/Batching enabled for non-baked skinning model '%s', this may result in unexpected rendering artifacts. Consider turning it off in the material if you do not intend to do this. +### 3937 +Previous error occurred when instantiating animation clip %s on node %s. + +### 3938 + +'%s' is not found from '%s'. It's specified as the root node to play animation clip '%s'. + ### 4000 @@ -3083,7 +3090,7 @@ Failed to allocate chunk in StaticVBAccessor, the requested buffer might be too ### 9005 -BATCHER2D_MEM_INCREMENT is too large, the Max value for BATCHER2D_MEM_INCREMENT is 2303KB (smaller than 65536 * 9 * 4 / 1024 = 2304KB) +BATCHER2D_MEM_INCREMENT is too large, the Max value for BATCHER2D_MEM_INCREMENT is 2303KB (smaller than 65536 *9* 4 / 1024 = 2304KB) ### 9006 @@ -3234,3 +3241,49 @@ The primitiveIndex is out of range. ### 14300 Can not keep world transform due to the zero scaling of parent node + +### 14400 + +Spline error: less than 2 knots. + +### 14401 + +Spline error: less than 4 knots or not a multiple of 4. + + + +### 15000 + +Can not find corresponding diffuse map for environment lighting, use hemisphere diffuse instead, change environment lighting type to regenerate diffuse map + +### 15001 + +Can not find environment map, disable IBL lighting + +### 15002 + +Diffuse map resource is missing, please change environment lighting type to regenerate resource + +### 15003 + +The shadow visible distance is so small that CSM stratification is not effective, Please change the value of shadowDistance so that it is 10 times greater than 0.1 + +### 15004 + +The native folder may be generated from older versions, please refer https://docs.cocos.com/creator/manual/en/release-notes/ to upgrade. + +### 16000 + +'%s' is deprecated since v%s. + +### 16001 + +'%s' is deprecated since v%s, please use '%s' instead. + +### 16002 + +'%s' is removed since v%s. + +### 16003 + +'%s' is removed since v%s, please use '%s' instead. \ No newline at end of file diff --git a/README.md b/README.md index aa7b1a4787..16bd096d94 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,8 @@ This is all you have to do to setup engine development environment. npm run build ``` +Please refer to [native readme](native/README.md) if want to develop native applications. + ## Example Project - [Example Cases](https://github.com/cocos/cocos-example-projects): Simple yet expressive demo scenes for baseline testing and topic-specific case study. diff --git a/cc.config.json b/cc.config.json index a21678aef1..0abf04065e 100644 --- a/cc.config.json +++ b/cc.config.json @@ -1,14 +1,60 @@ { + "$schema": "./cc.config.schema.json", + "features": { - "base": { "modules": [ "base" ] }, + "base": { "modules": [ "base", "native" ], "dependentAssets": [ + "ff9be190-20a4-4e48-b68c-76e3c7cff085", + "970b0598-bcb0-4714-91fb-2e81440dccd8", + "bcd64cc6-2dd9-43f6-abbe-66318d332032", + "d930590d-bb92-4cc8-8bd1-23cd027f9edf", + "a3cd009f-0ab0-420d-9278-b9fdab939bbc" + ]}, "gfx-webgl": { "modules": [ "gfx-webgl" ] }, "gfx-webgl2": { "modules": [ "gfx-webgl2" ] }, - "3d": { "modules": [ "3d" ], "dependentAssets": ["0835f102-5471-47a3-9a76-01c07ac9cdb2", "b5475517-23b9-4873-bc1a-968d96616081", "0ed97c56-390e-4dd1-96b7-e7f2d93a98ed", "b23391b6-52eb-46a6-8da1-6244d9d315fb"] }, + "3d": { + "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", + "ec8106fe-05bf-4e94-943c-e0d3b7bb5e45", + "620b6bf3-0369-4560-837f-2a2c00b73c26" + ] + }, "animation": { "modules": ["animation"] }, "skeletal-animation": { "modules": ["animation", "skeletal-animation"] }, - "2d": { "modules": [ "2d" ] }, + "2d": { + "modules": [ "2d" ], + "dependentAssets": [ + "60f7195c-ec2a-45eb-ba94-8955f60e81d0", + "1c02ae6f-4492-4915-b8f8-7492a3b1e4cd", + "810e96e4-e456-4468-9b59-f4e8f39732c0", + "efe8e2a3-eace-427b-b4f1-cb8a937ec77d", + "e9aa9a3e-5b2b-4ac7-a2c7-073de2b2b24f", + "8bbdbcdd-5cd4-4100-b6d5-b7c9625b6107", + "50f4348b-c883-4e2f-8f11-ce233b859fa1", + "fda095cb-831d-4601-ad94-846013963de8", + "f92806d7-1768-443f-afe8-12bcde84d0f0", + "dd3a144d-ab7f-41f0-82b8-2e43a090d496", + "f0416e68-0200-4b77-a926-4f9d16e494da" + ] + }, "ui": { "modules": [ "ui", "2d" ] }, - "particle": { "modules": [ "particle" ] }, + "particle": { + "modules": [ "particle" ], + "dependentAssets": [ + "d1346436-ac96-4271-b863-1f4fdead95b0", + "971bdb23-3ff6-43eb-b422-1c30165a3663", + "17debcc3-0a6b-4b8a-b00b-dc58b885581e", + "711ebe11-f673-4cd9-9a83-63c60ba54c5b", + "c0143906-9aed-447e-9436-2ae8512d1b6e", + "14da1725-c4c2-42b4-ab08-ee0aeb6898b3", + "081cab31-dccd-428e-8652-f2404cc81c47", + "78e0584a-4343-4727-8f37-e14e65c2a2db" + ] + }, "particle-2d": { "modules": [ "particle-2d" ] }, "physics-framework": { "modules": [ "physics-framework" ] }, "physics-cannon": { "modules": [ "physics-cannon", "physics-framework" ] }, @@ -20,29 +66,73 @@ "physics-2d-builtin": { "modules": [ "physics-2d-builtin", "physics-2d-framework" ] }, "intersection-2d": { "modules": [ "intersection-2d" ] }, "primitive": { "modules": [ "primitive" ] }, - "profiler": { "modules": [ "profiler" ] }, + "profiler": { + "modules": [ "profiler" ], + "dependentAssets": [ "871c3b6c-7379-419d-bda3-794b239ab90d" ] + }, + "occlusion-query": { + "modules": [], + "dependentAssets": [ "d9937e59-61fe-4ec6-92ab-7ac5a19c89b0" ] + }, + "geometry-renderer": { + "modules": [ "geometry-renderer" ], + "dependentAssets": [ "4bb480dd-8384-4bc9-987f-de67cc53052a" ] + }, + "debug-renderer": { + "modules": [], + "dependentAssets": [ + "0835f102-5471-47a3-9a76-01c07ac9cdb2", + "b5475517-23b9-4873-bc1a-968d96616081", + "0ed97c56-390e-4dd1-96b7-e7f2d93a98ed", + "b23391b6-52eb-46a6-8da1-6244d9d315fb" + ] + }, "audio": { "modules": [ "audio" ] }, "video": { "modules": [ "video" ] }, - "terrain": { "modules": [ "terrain" ] }, + "terrain": { + "modules": [ "terrain" ], + "dependentAssets": [ "1d08ef62-a503-4ce2-8b9a-46c90873f7d3" ] + }, "webview": { "modules": [ "webview" ] }, "tween": { "modules": [ "tween" ] }, "tiled-map": { "modules": [ "tiled-map" ] }, - "spine": { "modules": [ "spine" ] }, + "spine": { + "modules": [ "spine" ], + "dependentAssets":[ + "c27215d8-6835-4b68-bfbb-bdeac6100c04", + "b5d6115f-0370-4d7c-aad3-c194cc71cf98" + ] + }, "dragon-bones": { "modules": [ "dragon-bones" ] }, "marionette": { "modules": [], "intrinsicFlags": { "MARIONETTE": true } - } + }, + "custom-pipeline": { "modules": ["custom-pipeline"] } }, "moduleOverrides": [ + { + "test": "true", + "isVirtualModule": true, + "overrides": { + "internal:native": "cocos/native-binding/impl.ts" + } + }, { "test": "context.mode === 'BUILD'", "isVirtualModule": false, "overrides": { } }, + { + "test": "context.platform !== 'NATIVE'", + "isVirtualModule": false, + "overrides": { + "cocos/2d/renderer/native-2d.ts": "cocos/2d/renderer/native-2d-empty.ts" + } + }, { "test": "context.platform === 'NATIVE'", "isVirtualModule": false, @@ -59,11 +149,12 @@ "cocos/core/renderer/core/sampler-lib.ts": "cocos/core/renderer/core/sampler.jsb.ts", "cocos/core/renderer/scene/camera.ts": "cocos/core/renderer/scene/camera.jsb.ts", "cocos/core/renderer/scene/model.ts": "cocos/core/renderer/scene/model.jsb.ts", - "cocos/core/renderer/scene/render-scene.ts": "cocos/core/renderer/scene/render-scene.jsb.ts", + "cocos/core/renderer/core/render-scene.ts": "cocos/core/renderer/core/render-scene.jsb.ts", "cocos/core/renderer/scene/submodel.ts": "cocos/core/renderer/scene/submodel.jsb.ts", "cocos/core/renderer/scene/index.ts": "cocos/core/renderer/scene/index.jsb.ts", + "cocos/2d/renderer/native-2d.ts": "cocos/2d/renderer/native-2d.jsb.ts", + "cocos/core/gfx/base/pipeline-state.ts": "cocos/core/gfx/base/pipeline-state.jsb.ts", "cocos/core/gfx/index.ts": "cocos/core/gfx/index.jsb.ts", - "cocos/core/gfx/pipeline-state.ts": "cocos/core/gfx/pipeline-state.jsb.ts", "cocos/spine/index.ts": "cocos/spine/index.jsb.ts", "cocos/dragon-bones/index.ts": "cocos/dragon-bones/index.jsb.ts", "cocos/physics/physx/instantiate.ts": "cocos/physics/physx/instantiate.jsb.ts", @@ -104,7 +195,9 @@ "pal/audio": "pal/audio/web/player.ts", "pal/system-info": "pal/system-info/web/system-info.ts", "pal/screen-adapter": "pal/screen-adapter/web/screen-adapter.ts", - "pal/input": "pal/input/web/index.ts" + "pal/input": "pal/input/web/index.ts", + "pal/env": "pal/env/web/env.ts", + "pal/pacer": "pal/pacer/pacer-web.ts" } }, { @@ -115,7 +208,9 @@ "pal/audio": "pal/audio/native/player.ts", "pal/system-info": "pal/system-info/native/system-info.ts", "pal/screen-adapter": "pal/screen-adapter/native/screen-adapter.ts", - "pal/input": "pal/input/native/index.ts" + "pal/input": "pal/input/native/index.ts", + "pal/env": "pal/env/native/env.ts", + "pal/pacer": "pal/pacer/pacer-native.ts" } }, { @@ -126,7 +221,9 @@ "pal/audio": "pal/audio/minigame/player.ts", "pal/system-info": "pal/system-info/minigame/system-info.ts", "pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.ts", - "pal/input": "pal/input/minigame/index.ts" + "pal/input": "pal/input/minigame/index.ts", + "pal/env": "pal/env/minigame/env.ts", + "pal/pacer": "pal/pacer/pacer-minigame.ts" } }, { @@ -137,7 +234,9 @@ "pal/audio": "pal/audio/minigame/player.ts", "pal/system-info": "pal/system-info/minigame/system-info.ts", "pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.ts", - "pal/input": "pal/input/minigame/index.ts" + "pal/input": "pal/input/minigame/index.ts", + "pal/env": "pal/env/runtime/env.ts", + "pal/pacer": "pal/pacer/pacer-minigame.ts" } }, { @@ -160,5 +259,167 @@ "./editor/exports/**/*.{ts,js,json}", "./cocos/**/*.{ts,js,json}", "./pal/**/*.{ts,js,json}" - ] + ], + + "constants": { + "HTML5": { + "comment": "Running in Web platform", + "value": false, + "internal": false, + "dynamic": true + }, + "NATIVE": { + "comment": "Running in native platform (mobile app, desktop app, or simulator).", + "value": false, + "internal": false, + "dynamic": true + }, + "WECHAT": { + "comment": "Running in the Wechat's mini game.", + "value": false, + "ccGlobal": true, + "internal": false + }, + "BAIDU": { + "comment": "Running in the baidu's mini game.", + "value": false, + "ccGlobal": true, + "internal": false + }, + "XIAOMI": { + "comment": "Running in the xiaomi's quick game.", + "value": false, + "ccGlobal": true, + "internal": false + }, + "ALIPAY": { + "comment": "Running in the alipay's mini game.", + "value": false, + "ccGlobal": true, + "internal": false + }, + "BYTEDANCE": { + "comment": "Running in the ByteDance's mini game.", + "value": false, + "ccGlobal": true, + "internal": false + }, + "OPPO": { + "comment": "Running in the oppo's quick game.", + "value": false, + "ccGlobal": true, + "internal": false + }, + "VIVO": { + "comment": "Running in the vivo's quick game.", + "value": false, + "ccGlobal": true, + "internal": false + }, + "HUAWEI": { + "comment": "Running in the huawei's quick game.", + "value": false, + "ccGlobal": true, + "internal": false + }, + "COCOSPLAY": { + "comment": "Running in the cocosplay.", + "value": false, + "ccGlobal": true, + "internal": false + }, + "QTT": { + "comment": "Running in the qtt's quick game.", + "value": false, + "ccGlobal": true, + "internal": false + }, + "LINKSURE": { + "comment": "Running in the linksure's quick game.", + "value": false, + "ccGlobal": true, + "internal": false + }, + + "EDITOR": { + "comment": "Running in the editor.", + "value": false, + "ccGlobal": true, + "internal": false, + "dynamic": true + }, + "PREVIEW": { + "comment": "Preview in browser or simulator.", + "value": false, + "ccGlobal": true, + "internal": false, + "dynamic": true + }, + "BUILD": { + "comment": "Running in published project.", + "value": false, + "ccGlobal": true, + "internal": false + }, + "TEST": { + "comment": "Running in the engine's unit test.", + "value": false, + "ccGlobal": true, + "internal": false, + "dynamic": true + }, + + + "DEBUG": { + "comment": "Running debug mode.", + "value": true, + "ccGlobal": true, + "internal": false + }, + "SERVER_MODE": { + "comment": "Running in the server mode.", + "value": false, + "internal": false + }, + + + "DEV": { + "comment": "Running in the editor or preview.", + "value": "$EDITOR || $PREVIEW || $TEST", + "ccGlobal": true, + "internal": false, + "dynamic": true + }, + "MINIGAME": { + "comment": "Running in mini game.", + "value": "$WECHAT || $BAIDU || $XIAOMI || $ALIPAY || $BYTEDANCE", + "ccGlobal": true, + "internal": false + }, + "RUNTIME_BASED": { + "comment": "Running in runtime based environment.", + "value": "$OPPO || $VIVO || $HUAWEI || $COCOSPLAY || $QTT || $LINKSURE", + "ccGlobal": true, + "internal": false + }, + "SUPPORT_JIT": { + "comment": "Support JIT.", + "value": "!($MINIGAME || $RUNTIME_BASED)", + "ccGlobal": true, + "internal": false, + "dynamic": true + }, + "JSB": { + "comment": "Running in environment where using JSB as the JavaScript interface binding scheme.", + "value": "$NATIVE", + "ccGlobal": true, + "internal": false, + "dynamic": true + }, + "NOT_PACK_PHYSX_LIBS": { + "comment": "This is an internal constant to determine whether pack physx libs.", + "value": false, + "internal": true + } + } } diff --git a/cc.config.schema.json b/cc.config.schema.json new file mode 100644 index 0000000000..e2f0b72edf --- /dev/null +++ b/cc.config.schema.json @@ -0,0 +1,157 @@ +{ + "$ref": "#/definitions/Config", + "$schema": "http://json-schema.org/draft-07/schema#", + "definitions": { + "Config": { + "additionalProperties": false, + "properties": { + "constants": { + "$ref": "#/definitions/IConstantConfig", + "description": "The constants config for engine and user." + }, + "features": { + "additionalProperties": { + "$ref": "#/definitions/Feature" + }, + "description": "Engine features. Keys are feature IDs.", + "type": "object" + }, + "includes": { + "description": "Included files for quick-compiler.", + "items": { + "type": "string" + }, + "type": "array" + }, + "index": { + "$ref": "#/definitions/IndexConfig", + "description": "Describe how to generate the index module `'cc'`. Currently not used." + }, + "moduleOverrides": { + "items": { + "additionalProperties": false, + "properties": { + "isVirtualModule": { + "type": "boolean" + }, + "overrides": { + "additionalProperties": { + "type": "string" + }, + "description": "Construct a type with a set of properties K of type T", + "type": "object" + }, + "test": { + "$ref": "#/definitions/Test" + } + }, + "required": [ + "test", + "overrides", + "isVirtualModule" + ], + "type": "object" + }, + "type": "array" + } + }, + "required": [ + "features", + "includes", + "constants" + ], + "type": "object" + }, + "Feature": { + "additionalProperties": false, + "description": "An engine feature.", + "properties": { + "intrinsicFlags": { + "additionalProperties": {}, + "description": "Flags to set when this feature is enabled.", + "type": "object" + }, + "modules": { + "description": "Modules to be included in this feature in their IDs. The ID of a module is its relative path(no extension) under /exports/.", + "items": { + "type": "string" + }, + "type": "array" + } + }, + "required": [ + "modules" + ], + "type": "object" + }, + "IConstantConfig": { + "additionalProperties": { + "$ref": "#/definitions/IConstantInfo" + }, + "type": "object" + }, + "IConstantInfo": { + "additionalProperties": false, + "properties": { + "ccGlobal": { + "default": false, + "description": "Whether exported to global as a `CC_XXXX` constant. eg. WECHAT is exported to global.CC_WECHAT NOTE: this is a feature of compatibility with Cocos 2.x engine. Default is false.", + "type": "boolean" + }, + "comment": { + "description": "The comment of the constant. Which is used to generate the consts.d.ts file.", + "type": "string" + }, + "dynamic": { + "default": false, + "description": "Some constant can't specify the value in the Editor, Preview or Test environment, so we need to dynamically judge them in runtime. These values are specified in a helper called `helper-dynamic-constants.ts`. Default is false.", + "type": "boolean" + }, + "internal": { + "description": "Whether exported to developer. If true, it's only exported to engine.", + "type": "boolean" + }, + "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().", + "type": [ + "boolean", + "string" + ] + } + }, + "required": [ + "comment", + "value", + "internal" + ], + "type": "object" + }, + "IndexConfig": { + "additionalProperties": false, + "properties": { + "modules": { + "additionalProperties": { + "additionalProperties": false, + "properties": { + "deprecated": { + "description": "If `true`, accesses the exports of this module from `'cc'` will be marked as deprecated.", + "type": "boolean" + }, + "ns": { + "description": "If specified, export contents of the module into a namespace specified by `ns` and then export that namespace into `'cc'`. If not specified, contents of the module will be directly exported into `'cc'`.", + "type": "string" + } + }, + "type": "object" + }, + "description": "Construct a type with a set of properties K of type T", + "type": "object" + } + }, + "type": "object" + }, + "Test": { + "type": "string" + } + } +} \ No newline at end of file diff --git a/cocos/2d/assembler/graphics/webgl/graphics-assembler.ts b/cocos/2d/assembler/graphics/webgl/graphics-assembler.ts index 88bb73b940..a397147dac 100644 --- a/cocos/2d/assembler/graphics/webgl/graphics-assembler.ts +++ b/cocos/2d/assembler/graphics/webgl/graphics-assembler.ts @@ -22,12 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - -/** - * @packageDocumentation - * @module ui-assembler - */ - +import { JSB } from 'internal:constants'; import { Color, Vec3 } from '../../../../core/math'; import { IAssembler } from '../../../renderer/base'; import { MeshRenderData } from '../../../renderer/render-data'; @@ -82,7 +77,11 @@ export const graphicsAssembler: IAssembler = { useModel: true, updateRenderData (graphics: Graphics) { - + if (JSB) { + if (graphics.renderData) { + graphics.renderData.material = graphics.getMaterialInstance(0); + } + } }, fillBuffers (graphics: Graphics, renderer: IBatcher) { diff --git a/cocos/2d/assembler/graphics/webgl/impl.ts b/cocos/2d/assembler/graphics/webgl/impl.ts index a93f85479b..3e171534c5 100644 --- a/cocos/2d/assembler/graphics/webgl/impl.ts +++ b/cocos/2d/assembler/graphics/webgl/impl.ts @@ -23,8 +23,11 @@ THE SOFTWARE. */ +import { JSB } from 'internal:constants'; import { Color, Vec2 } from '../../../../core/math'; +import { Graphics } from '../../../components'; import { MeshRenderData } from '../../../renderer/render-data'; +import { RenderDrawInfoType } from '../../../renderer/render-draw-info'; import { arc, ellipse, roundRect, tesselateBezier } from '../helper'; import { LineCap, LineJoin, PointFlags } from '../types'; @@ -96,6 +99,11 @@ export class Impl { private _points: Point[] = []; private _renderDataList: MeshRenderData[] = []; private _curPath: Path | null = null; + private _comp: Graphics; + + constructor (comp: Graphics) { + this._comp = comp; + } public moveTo (x: number, y: number) { if (this.updatePathOffset) { @@ -187,6 +195,7 @@ export class Impl { } MeshRenderData.remove(data); + data.removeRenderDrawInfo(this._comp); } this._renderDataList.length = 0; @@ -199,6 +208,13 @@ export class Impl { public requestRenderData () { const renderData = MeshRenderData.add(); this._renderDataList.push(renderData); + if (JSB) { + renderData.initRenderDrawInfo(this._comp, RenderDrawInfoType.MODEL); + // @ts-expect-error temporary no care + this._comp._renderData = renderData; + // @ts-expect-error temporary no care + this._comp._renderData!.material = this._comp.getMaterialInstance(0)!;// hack + } return renderData; } diff --git a/cocos/2d/assembler/graphics/webgl/index.ts b/cocos/2d/assembler/graphics/webgl/index.ts index ec98152e78..73f4a19c22 100644 --- a/cocos/2d/assembler/graphics/webgl/index.ts +++ b/cocos/2d/assembler/graphics/webgl/index.ts @@ -23,7 +23,7 @@ THE SOFTWARE. */ -import { Renderable2D } from '../../../framework/renderable-2d'; +import { UIRenderer } from '../../../framework/ui-renderer'; import { IAssemblerManager } from '../../../renderer/base'; import { Graphics } from '../../../components'; import { graphicsAssembler as graphics } from './graphics-assembler'; @@ -31,7 +31,7 @@ import { graphicsAssembler as graphics } from './graphics-assembler'; export { earcut } from './earcut'; const graphicsAssemblerManager: IAssemblerManager = { - getAssembler (sprite: Renderable2D) { + getAssembler (sprite: UIRenderer) { return graphics; }, }; diff --git a/cocos/2d/assembler/index.ts b/cocos/2d/assembler/index.ts index b422354fb5..54f5a8c8e4 100644 --- a/cocos/2d/assembler/index.ts +++ b/cocos/2d/assembler/index.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import './utils'; export * from './graphics'; diff --git a/cocos/2d/assembler/label/bmfont.ts b/cocos/2d/assembler/label/bmfont.ts index 4bb3e1722f..fcfe388d51 100644 --- a/cocos/2d/assembler/label/bmfont.ts +++ b/cocos/2d/assembler/label/bmfont.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui-assembler - */ - import { SpriteFrame } from '../../assets/sprite-frame'; import * as js from '../../../core/utils/js'; import { Color, Rect } from '../../../core/math'; @@ -117,10 +112,6 @@ export const bmfont: IAssembler = { dataList[dataOffset + 3].x = x + rectWidth * scale; dataList[dataOffset + 3].y = y; }, - - updateColor (comp: Label) { - - }, }; js.addon(bmfont, bmfontUtils); diff --git a/cocos/2d/assembler/label/bmfontUtils.ts b/cocos/2d/assembler/label/bmfontUtils.ts index 4d709ef744..13a58f4c1d 100644 --- a/cocos/2d/assembler/label/bmfontUtils.ts +++ b/cocos/2d/assembler/label/bmfontUtils.ts @@ -23,6 +23,7 @@ THE SOFTWARE. */ +import { JSB } from 'internal:constants'; import { BitmapFont, IConfig, FontLetterDefinition } from '../../assets/bitmap-font'; import { SpriteFrame } from '../../assets/sprite-frame'; import { isUnicodeCJK, isUnicodeSpace } from '../../utils/text-utils'; @@ -76,6 +77,7 @@ let _isWrapText = false; let _labelWidth = 0; let _labelHeight = 0; let _maxLineWidth = 0; +let QUAD_INDICES; export const bmfontUtils = { updateRenderData (comp: Label) { @@ -95,11 +97,12 @@ export const bmfontUtils = { _comp.actualFontSize = _fontSize; _uiTrans.setContentSize(_contentSize); - this.updateUVs(comp); + this.updateUVs(comp);// dirty need + this.updateColor(comp); // dirty need _comp.renderData!.vertDirty = false; // fix bmfont run updateRenderData twice bug - _comp.markForUpdateRenderData(false); + // _comp.markForUpdateRenderData(false); _comp = null; @@ -126,6 +129,29 @@ export const bmfontUtils = { } }, + updateColor (label: Label) { + if (JSB) { + const renderData = label.renderData!; + const vertexCount = renderData.vertexCount; + if (vertexCount === 0) return; + const vData = renderData.chunk.vb; + const stride = renderData.floatStride; + let colorOffset = 5; + const color = label.color; + const colorR = color.r / 255; + const colorG = color.g / 255; + const colorB = color.b / 255; + const colorA = color.a / 255; + for (let i = 0; i < vertexCount; i++) { + vData[colorOffset] = colorR; + vData[colorOffset + 1] = colorG; + vData[colorOffset + 2] = colorB; + vData[colorOffset + 3] = colorA; + colorOffset += stride; + } + } + }, + _updateFontScale () { _bmfontScale = _fontSize / _originFontSize; }, @@ -622,10 +648,31 @@ export const bmfontUtils = { this.appendQuad(_comp, texture, _tmpRect, isRotated, letterPositionX - appX, py - appY, _bmfontScale); } } - + const indexCount = renderData.indexCount; + this.createQuadIndices(indexCount); + renderData.chunk.setIndexBuffer(QUAD_INDICES); return ret; }, + createQuadIndices (indexCount) { + if (indexCount % 6 !== 0) { + console.error('illegal index count!'); + return; + } + const quadCount = indexCount / 6; + QUAD_INDICES = null; + QUAD_INDICES = new Uint16Array(indexCount); + let offset = 0; + for (let i = 0; i < quadCount; i++) { + QUAD_INDICES[offset++] = 0 + i * 4; + QUAD_INDICES[offset++] = 1 + i * 4; + QUAD_INDICES[offset++] = 2 + i * 4; + QUAD_INDICES[offset++] = 1 + i * 4; + QUAD_INDICES[offset++] = 3 + i * 4; + QUAD_INDICES[offset++] = 2 + i * 4; + } + }, + appendQuad (comp, texture, rect, rotated, x, y, scale) { }, diff --git a/cocos/2d/assembler/label/index.ts b/cocos/2d/assembler/label/index.ts index 92ec7af9f0..c466369f85 100644 --- a/cocos/2d/assembler/label/index.ts +++ b/cocos/2d/assembler/label/index.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui-assembler - */ - import { BitmapFont } from '../../assets'; import { Label } from '../../components'; import { IAssemblerManager } from '../../renderer/base'; diff --git a/cocos/2d/assembler/label/letter.ts b/cocos/2d/assembler/label/letter.ts index 5dceee06f0..cb1d79b473 100644 --- a/cocos/2d/assembler/label/letter.ts +++ b/cocos/2d/assembler/label/letter.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui-assembler - */ - import { addon } from '../../../core/utils/js'; import { IBatcher } from '../../renderer/i-batcher'; import { Label } from '../../components/label'; @@ -58,10 +53,6 @@ export const letter = { fillMeshVertices3D(node, renderer, comp.renderData, tempColor); }, - updateColor (comp: Label) { - - }, - appendQuad: bmfont.appendQuad, }; diff --git a/cocos/2d/assembler/label/ttf.ts b/cocos/2d/assembler/label/ttf.ts index a7b05c4f37..1b54e318d4 100644 --- a/cocos/2d/assembler/label/ttf.ts +++ b/cocos/2d/assembler/label/ttf.ts @@ -29,7 +29,7 @@ */ import * as js from '../../../core/utils/js'; -import { Color } from '../../../core/math'; +import { Color, Vec3 } from '../../../core/math'; import { IBatcher } from '../../renderer/i-batcher'; import { Label } from '../../components/label'; import { IAssembler } from '../../renderer/base'; @@ -37,6 +37,8 @@ import { ttfUtils } from './ttfUtils'; import { IRenderData } from '../../renderer/render-data'; const WHITE = Color.WHITE.clone(); +const vec3_temp = new Vec3(); +const QUAD_INDICES = Uint16Array.from([0, 1, 2, 1, 3, 2]); /** * ttf 组装器 @@ -46,7 +48,7 @@ export const ttf: IAssembler = { createData (comp: Label) { const renderData = comp.requestRenderData()!; - renderData.dataLength = 2; + renderData.dataLength = 4; renderData.resize(4, 6); const vData = renderData.chunk.vb; @@ -58,47 +60,35 @@ export const ttf: IAssembler = { Color.toArray(vData, WHITE, offset); offset += 9; } + renderData.vertexRow = 2; + renderData.vertexCol = 2; + renderData.chunk.setIndexBuffer(QUAD_INDICES); return renderData; }, fillBuffers (comp: Label, renderer: IBatcher) { - const chunk = comp.renderData!.chunk; - const dataList: IRenderData[] = comp.renderData!.data; + const renderData = comp.renderData!; + const chunk = renderData.chunk; + const dataList: IRenderData[] = renderData.data; const node = comp.node; const vData = chunk.vb; - const data0 = dataList[0]; - const data3 = dataList[1]; - /* */ - node.updateWorldTransform(); - // @ts-expect-error private property access - const pos = node._pos; const rot = node._rot; const scale = node._scale; - const ax = data0.x * scale.x; const bx = data3.x * scale.x; - const ay = data0.y * scale.y; const by = data3.y * scale.y; - const qx = rot.x; const qy = rot.y; const qz = rot.z; const qw = rot.w; - const qxy = qx * qy; const qzw = qz * qw; - const qxy2 = qx * qx - qy * qy; - const qzw2 = qw * qw - qz * qz; - const cx1 = qzw2 + qxy2; - const cx2 = (qxy - qzw) * 2; - const cy1 = qzw2 - qxy2; - const cy2 = (qxy + qzw) * 2; - const x = pos.x; const y = pos.y; - // left bottom - vData[0] = cx1 * ax + cx2 * ay + x; - vData[1] = cy1 * ay + cy2 * ax + y; - // right bottom - vData[9] = cx1 * bx + cx2 * ay + x; - vData[10] = cy1 * ay + cy2 * bx + y; - // left top - vData[18] = cx1 * ax + cx2 * by + x; - vData[19] = cy1 * by + cy2 * ax + y; - // right top - vData[27] = cx1 * bx + cx2 * by + x; - vData[28] = cy1 * by + cy2 * bx + y; + + // normal version + const matrix = node.worldMatrix; + const stride = renderData.floatStride; + let offset = 0; + for (let i = 0; i < dataList.length; i++) { + const curData = dataList[i]; + Vec3.set(vec3_temp, curData.x, curData.y, 0); + Vec3.transformMat4(vec3_temp, vec3_temp, matrix); + offset = i * stride; + vData[offset++] = vec3_temp.x; + vData[offset++] = vec3_temp.y; + vData[offset++] = vec3_temp.z; + } // quick version - const bid = chunk.bufferId; const vid = chunk.vertexOffset; const meshBuffer = chunk.meshBuffer; const ib = chunk.meshBuffer.iData; @@ -127,10 +117,14 @@ export const ttf: IAssembler = { const appY = uiTrans.anchorY * height; const data = renderData.data; - data[0].x = -appX; - data[0].y = -appY; - data[1].x = width - appX; - data[1].y = height - appY; + data[0].x = -appX; // l + data[0].y = -appY; // b + data[1].x = width - appX; // r + data[1].y = -appY; // b + data[2].x = -appX; // l + data[2].y = height - appY; // t + data[3].x = width - appX; // r + data[3].y = height - appY; // t }, updateUVs (comp: Label) { diff --git a/cocos/2d/assembler/label/ttfUtils.ts b/cocos/2d/assembler/label/ttfUtils.ts index 9ac263a750..816d2e064a 100644 --- a/cocos/2d/assembler/label/ttfUtils.ts +++ b/cocos/2d/assembler/label/ttfUtils.ts @@ -23,6 +23,7 @@ THE SOFTWARE. */ +import { JSB } from 'internal:constants'; import { SpriteFrame } from '../../assets'; import { Texture2D } from '../../../core/assets'; import { fragmentText, safeMeasureText, getBaselineOffset, BASELINE_RATIO } from '../../utils/text-utils'; @@ -35,6 +36,7 @@ import { legacyCC } from '../../../core/global-exports'; import { assetManager } from '../../../core/asset-manager'; import { dynamicAtlasManager } from '../../utils/dynamic-atlas/atlas-manager'; import { BlendFactor } from '../../../core/gfx'; +import { WrapMode } from '../../../core/assets/asset-enum'; const Overflow = Label.Overflow; const MAX_SIZE = 2048; @@ -115,9 +117,9 @@ export const ttfUtils = { trans.setContentSize(_canvasSize); this.updateVertexData(comp); - this.updateUVs(comp); - - comp.markForUpdateRenderData(false); + this.updateUVs(comp); // Empty + comp.renderData.vertDirty = false; + // comp.markForUpdateRenderData(false); _context = null; _canvas = null; @@ -330,6 +332,7 @@ export const ttfUtils = { mipmapLevel: 1, }); tex.uploadData(_canvas); + tex.setWrapMode(WrapMode.CLAMP_TO_EDGE, WrapMode.CLAMP_TO_EDGE); if (_texture instanceof SpriteFrame) { _texture.rect = new Rect(0, 0, _canvas.width, _canvas.height); _texture._calculateUV(); @@ -338,7 +341,11 @@ export const ttfUtils = { comp.renderData.textureDirty = true; } if (legacyCC.director.root && legacyCC.director.root.batcher2D) { - legacyCC.director.root.batcher2D._releaseDescriptorSetCache(tex.getHash()); + if (JSB) { + legacyCC.director.root.batcher2D._releaseDescriptorSetCache(tex.getGFXTexture(), tex.getGFXSampler()); + } else { + legacyCC.director.root.batcher2D._releaseDescriptorSetCache(tex.getHash()); + } } } } diff --git a/cocos/2d/assembler/mask/index.ts b/cocos/2d/assembler/mask/index.ts index f59ed5f4f4..ae2cf72dc9 100644 --- a/cocos/2d/assembler/mask/index.ts +++ b/cocos/2d/assembler/mask/index.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { maskAssembler as mask, maskEndAssembler as maskEnd } from './mask-assembler'; export { diff --git a/cocos/2d/assembler/mask/mask-assembler.ts b/cocos/2d/assembler/mask/mask-assembler.ts index f2a12b5812..77eb48e9d8 100644 --- a/cocos/2d/assembler/mask/mask-assembler.ts +++ b/cocos/2d/assembler/mask/mask-assembler.ts @@ -23,16 +23,10 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui-assembler - */ - 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 { simple } from '../sprite'; const _stencilManager = StencilManager.sharedManager!; @@ -44,27 +38,18 @@ function applyClearMask (mask: Mask, renderer: IBatcher) { function applyAreaMask (mask: Mask, renderer: IBatcher) { _stencilManager.enterLevel(mask); if (mask.type === MaskType.IMAGE_STENCIL) { - simple.fillBuffers(mask, renderer); - const mat = mask.graphics!.getMaterialInstance(0)!; - renderer.forceMergeBatches(mat, mask.spriteFrame, mask.graphics!); - } else { - mask.graphics!.updateAssembler(renderer); + // Apply stencil stage + _stencilManager.stage = mask.subComp!.stencilStage; } } export const maskAssembler: IAssembler = { createData (mask: Mask) { const renderData = mask.requestRenderData(); - renderData.dataLength = 2; - renderData.resize(4, 6); return renderData; }, updateRenderData (mask: Mask) { - if (mask.type === MaskType.IMAGE_STENCIL) { - simple.updateRenderData(mask); - simple.updateColor(mask); - } }, fillBuffers (mask: Mask, renderer: IBatcher) { @@ -74,8 +59,6 @@ export const maskAssembler: IAssembler = { renderer.finishMergeBatches(); applyClearMask(mask, renderer); applyAreaMask(mask, renderer); - - _stencilManager.enableMask(); } }, }; @@ -98,5 +81,18 @@ const PostAssembler: IAssemblerManager = { }, }; +const childPostAssembler: IAssemblerManager = { + getAssembler () { + return childEndAssembler; + }, +}; + +export const childEndAssembler: IAssembler = { + fillBuffers (subComp: any, ui: IBatcher) { + _stencilManager.enableMask(); + }, +}; + Mask.Assembler = StartAssembler; Mask.PostAssembler = PostAssembler; +Mask.ChildPostAssembler = childPostAssembler; diff --git a/cocos/2d/assembler/sprite/bar-filled.ts b/cocos/2d/assembler/sprite/bar-filled.ts index ee94de7533..13d39c0dd6 100644 --- a/cocos/2d/assembler/sprite/bar-filled.ts +++ b/cocos/2d/assembler/sprite/bar-filled.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui-assembler - */ - import { Color, Mat4, Vec3 } from '../../../core/math'; import { IRenderData, RenderData } from '../../renderer/render-data'; import { IBatcher } from '../../renderer/i-batcher'; @@ -40,6 +35,7 @@ import { StaticVBChunk } from '../../renderer/static-vb-accessor'; const FillType = Sprite.FillType; const matrix = new Mat4(); const vec3_temp = new Vec3(); +const QUAD_INDICES = Uint16Array.from([0, 1, 2, 1, 3, 2]); /** * barFilled 组装器 @@ -53,7 +49,6 @@ export const barFilled: IAssembler = { const renderData = sprite.renderData; if (renderData && frame) { - renderData.updateRenderData(sprite, frame); const vertDirty = renderData.vertDirty; if (!vertDirty) { @@ -76,8 +71,10 @@ export const barFilled: IAssembler = { let fillEnd = fillStart + fillRange; fillEnd = fillEnd > 1 ? 1 : fillEnd; - this.updateUVs(sprite, fillStart, fillEnd); + this.updateColor(sprite); // need Dirty + this.updateUVs(sprite, fillStart, fillEnd); // need Dirty this.updateVertexData(sprite, fillStart, fillEnd); + renderData.updateRenderData(sprite, frame); } }, @@ -203,7 +200,11 @@ export const barFilled: IAssembler = { // 0-4 for local vertex renderData.dataLength = 4; renderData.resize(4, 6); + renderData.vertexRow = 2; + renderData.vertexCol = 2; + renderData.chunk.setIndexBuffer(QUAD_INDICES); + // not need const dataList = renderData.data; for (const data of dataList) { data.z = 0; @@ -224,7 +225,8 @@ export const barFilled: IAssembler = { let offset = 0; for (let i = 0; i < 4; i++) { const local = dataList[i]; - Vec3.transformMat4(vec3_temp, local, matrix); + Vec3.set(vec3_temp, local.x, local.y, 0); + Vec3.transformMat4(vec3_temp, vec3_temp, matrix); offset = i * stride; vData[offset] = vec3_temp.x; vData[offset + 1] = vec3_temp.y; diff --git a/cocos/2d/assembler/sprite/index.ts b/cocos/2d/assembler/sprite/index.ts index 83803130f4..ba2f9b2d0e 100644 --- a/cocos/2d/assembler/sprite/index.ts +++ b/cocos/2d/assembler/sprite/index.ts @@ -23,9 +23,7 @@ THE SOFTWARE. */ - - -import { Renderable2D } from '../../framework/renderable-2d'; +import { UIRenderer } from '../../framework/ui-renderer'; import { IAssemblerManager } from '../../renderer/base'; import { Sprite } from '../../components'; import { barFilled } from './bar-filled'; @@ -40,7 +38,7 @@ const FillType = Sprite.FillType; // Inline all type switch to avoid jit deoptimization during inlined function change const spriteAssembler: IAssemblerManager = { - getAssembler (spriteComp: Renderable2D) { + getAssembler (spriteComp: UIRenderer) { let util = simple; const comp = spriteComp as Sprite; diff --git a/cocos/2d/assembler/sprite/radial-filled.ts b/cocos/2d/assembler/sprite/radial-filled.ts index 153846db63..028af69c65 100644 --- a/cocos/2d/assembler/sprite/radial-filled.ts +++ b/cocos/2d/assembler/sprite/radial-filled.ts @@ -23,11 +23,7 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui-assembler - */ - +import { JSB } from 'internal:constants'; import { SpriteFrame } from '../../assets'; import { Color, Mat4, Vec2, Vec3 } from '../../../core/math'; import { IRenderData, RenderData } from '../../renderer/render-data'; @@ -49,6 +45,7 @@ const _intersectPoint_1: Vec2[] = [new Vec2(), new Vec2(), new Vec2(), new Vec2( const _intersectPoint_2: Vec2[] = [new Vec2(), new Vec2(), new Vec2(), new Vec2()]; const _center = new Vec2(); const _triangles: Vec2[] = [new Vec2(), new Vec2(), new Vec2(), new Vec2()]; +let QUAD_INDICES; function _calcIntersectedPoints (left, right, bottom, top, center: Vec2, angle, intersectPoints: Vec2[]) { // left bottom, right, top @@ -345,12 +342,33 @@ export const radialFilled: IAssembler = { endAngle += PI_2; } } - + // hack for native when offset is 0 + if (offset === 0) { + renderData.dataLength = 0; + } renderData.resize(offset, offset); + if (JSB) { + const indexCount = renderData.indexCount; + this.createQuadIndices(indexCount); + renderData.chunk.setIndexBuffer(QUAD_INDICES); + // may can update color & uv here + // need dirty + this.updateWorldUVData(sprite); + this.updateColorLate(sprite); + } renderData.updateRenderData(sprite, frame); } }, + createQuadIndices (indexCount) { + QUAD_INDICES = null; + QUAD_INDICES = new Uint16Array(indexCount); + let offset = 0; + for (let i = 0; i < indexCount; i++) { + QUAD_INDICES[offset++] = i; + } + }, + fillBuffers (comp: Sprite, renderer: IBatcher) { const node = comp.node; const renderData: RenderData = comp.renderData!; @@ -361,7 +379,7 @@ export const radialFilled: IAssembler = { } // forColor - this.updataColorLate(comp); + this.updateColorLate(comp); const bid = chunk.bufferId; const vid = chunk.vertexOffset; @@ -375,6 +393,19 @@ export const radialFilled: IAssembler = { meshBuffer.setDirty(); }, + updateWorldUVData (sprite: Sprite, chunk: StaticVBChunk) { + const renderData = sprite.renderData!; + const stride = renderData.floatStride; + const dataList: IRenderData[] = renderData.data; + const vData = renderData.chunk.vb; + for (let i = 0; i < dataList.length; i++) { + const offset = i * stride; + vData[offset + 3] = dataList[i].u; + vData[offset + 4] = dataList[i].v; + } + }, + + // only for TS updateWorldVertexAndUVData (sprite: Sprite, chunk: StaticVBChunk) { const node = sprite.node; node.getWorldMatrix(matrix); @@ -399,6 +430,8 @@ export const radialFilled: IAssembler = { } }, + // dirty Mark + // the real update uv is on updateWorldUVData updateUVs (sprite: Sprite) { const renderData = sprite.renderData!; renderData.vertDirty = true; @@ -406,7 +439,7 @@ export const radialFilled: IAssembler = { }, // fill color here - updataColorLate (sprite: Sprite) { + updateColorLate (sprite: Sprite) { const renderData = sprite.renderData!; const vData = renderData.chunk.vb; const stride = renderData.floatStride; diff --git a/cocos/2d/assembler/sprite/simple.ts b/cocos/2d/assembler/sprite/simple.ts index 99cd370c6f..8456f4e33d 100644 --- a/cocos/2d/assembler/sprite/simple.ts +++ b/cocos/2d/assembler/sprite/simple.ts @@ -28,19 +28,25 @@ * @module ui-assembler */ -import { Vec3 } from '../../../core/math'; +import { JSB } from 'internal:constants'; +import { Vec3, Vec2, Color } from '../../../core/math'; import { IAssembler } from '../../renderer/base'; import { IRenderData, RenderData } from '../../renderer/render-data'; import { IBatcher } from '../../renderer/i-batcher'; import { Sprite } from '../../components'; import { dynamicAtlasManager } from '../../utils/dynamic-atlas/atlas-manager'; import { StaticVBChunk } from '../../renderer/static-vb-accessor'; +import { RenderDrawInfo } from '../../renderer/render-draw-info'; +import { Batcher2D } from '../../renderer/batcher-2d'; +import { director } from '../../../core'; const vec3_temps: Vec3[] = []; for (let i = 0; i < 4; i++) { vec3_temps.push(new Vec3()); } +const QUAD_INDICES = Uint16Array.from([0, 1, 2, 1, 3, 2]); + /** * simple 组装器 * 可通过 `UI.simple` 获取该组装器。 @@ -48,26 +54,20 @@ for (let i = 0; i < 4; i++) { export const simple: IAssembler = { createData (sprite: Sprite) { const renderData = sprite.requestRenderData(); - renderData.dataLength = 2; + renderData.dataLength = 4; renderData.resize(4, 6); + renderData.vertexRow = 2; + renderData.vertexCol = 2; + renderData.chunk.setIndexBuffer(QUAD_INDICES); return renderData; }, updateRenderData (sprite: Sprite) { const frame = sprite.spriteFrame; - // TODO: Material API design and export from editor could affect the material activation process - // need to update the logic here - // if (frame) { - // if (!frame._original && dynamicAtlasManager) { - // dynamicAtlasManager.insertSpriteFrame(frame); - // } - // if (sprite._material._texture !== frame._texture) { - // sprite._activateMaterial(); - // } - // } dynamicAtlasManager.packToDynamicAtlas(sprite, frame); - this.updateUVs(sprite); + this.updateUVs(sprite);// dirty need + //this.updateColor(sprite);// dirty need const renderData = sprite.renderData; if (renderData && frame) { @@ -84,60 +84,20 @@ export const simple: IAssembler = { const dataList: IRenderData[] = renderData.data; const node = sprite.node; - - const data0 = dataList[0]; - const data3 = dataList[1]; const matrix = node.worldMatrix; - const a = matrix.m00; const b = matrix.m01; - const c = matrix.m04; const d = matrix.m05; - const justTranslate = a === 1 && b === 0 && c === 0 && d === 1; + const stride = renderData.floatStride; - const tx = matrix.m12; const ty = matrix.m13; - const vl = data0.x; const vr = data3.x; - const vb = data0.y; const vt = data3.y; - - if (justTranslate) { - const vltx = vl + tx; - const vrtx = vr + tx; - const vbty = vb + ty; - const vtty = vt + ty; - - // left bottom - vData[0] = vltx; - vData[1] = vbty; - // right bottom - vData[9] = vrtx; - vData[10] = vbty; - // left top - vData[18] = vltx; - vData[19] = vtty; - // right top - vData[27] = vrtx; - vData[28] = vtty; - } else { - const al = a * vl; const ar = a * vr; - const bl = b * vl; const br = b * vr; - const cb = c * vb; const ct = c * vt; - const db = d * vb; const dt = d * vt; - - const cbtx = cb + tx; - const cttx = ct + tx; - const dbty = db + ty; - const dtty = dt + ty; - - // left bottom - vData[0] = al + cbtx; - vData[1] = bl + dbty; - // right bottom - vData[9] = ar + cbtx; - vData[10] = br + dbty; - // left top - vData[18] = al + cttx; - vData[19] = bl + dtty; - // right top - vData[27] = ar + cttx; - vData[28] = br + dtty; + const vec3_temp = vec3_temps[0]; + let offset = 0; + for (let i = 0; i < dataList.length; i++) { + const curData = dataList[i]; + Vec3.set(vec3_temp, curData.x, curData.y, 0); + Vec3.transformMat4(vec3_temp, vec3_temp, matrix); + offset = i * stride; + vData[offset++] = vec3_temp.x; + vData[offset++] = vec3_temp.y; + vData[offset++] = vec3_temp.z; } }, @@ -145,6 +105,7 @@ export const simple: IAssembler = { if (sprite === null) { return; } + const renderData = sprite.renderData!; const chunk = renderData.chunk; if (sprite.node.hasChangedFlags || renderData.vertDirty) { @@ -155,18 +116,35 @@ export const simple: IAssembler = { // quick version const bid = chunk.bufferId; - const vid = chunk.vertexOffset; + const vidOrigin = chunk.vertexOffset; const meshBuffer = chunk.meshBuffer; const ib = chunk.meshBuffer.iData; let indexOffset = meshBuffer.indexOffset; - ib[indexOffset++] = vid; - ib[indexOffset++] = vid + 1; - ib[indexOffset++] = vid + 2; - ib[indexOffset++] = vid + 2; - ib[indexOffset++] = vid + 1; - ib[indexOffset++] = vid + 3; - meshBuffer.indexOffset += 6; + // rect count = vertex count - 1 + for (let curRow = 0; curRow < renderData.vertexRow - 1; curRow++) { + for (let curCol = 0; curCol < renderData.vertexCol - 1; curCol++) { + // vid is the index of the left bottom vertex in each rect. + const vid = vidOrigin + curRow * renderData.vertexCol + curCol; + + // left bottom + ib[indexOffset++] = vid; + // right bottom + ib[indexOffset++] = vid + 1; + // left top + ib[indexOffset++] = vid + renderData.vertexCol; + + // right bottom + ib[indexOffset++] = vid + 1; + // right top + ib[indexOffset++] = vid + 1 + renderData.vertexCol; + // left top + ib[indexOffset++] = vid + renderData.vertexCol; + + // IndexOffset should add 6 when vertices of a rect are visited. + meshBuffer.indexOffset += 6; + } + } // slow version // renderer.switchBufferAccessor().appendIndices(chunk); }, @@ -217,7 +195,13 @@ export const simple: IAssembler = { dataList[0].y = b; dataList[1].x = r; - dataList[1].y = t; + dataList[1].y = b; + + dataList[2].x = l; + dataList[2].y = t; + + dataList[3].x = r; + dataList[3].y = t; renderData.vertDirty = true; }, diff --git a/cocos/2d/assembler/sprite/sliced.ts b/cocos/2d/assembler/sprite/sliced.ts index c1ab2d260b..8b84f870a3 100644 --- a/cocos/2d/assembler/sprite/sliced.ts +++ b/cocos/2d/assembler/sprite/sliced.ts @@ -23,12 +23,7 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui-assembler - */ - -import { Mat4, Vec3 } from '../../../core/math'; +import { Color, Mat4, Vec3 } from '../../../core/math'; import { IRenderData, RenderData } from '../../renderer/render-data'; import { IBatcher } from '../../renderer/i-batcher'; import { Sprite } from '../../components'; @@ -38,6 +33,10 @@ import { StaticVBChunk } from '../../renderer/static-vb-accessor'; const vec3_temp = new Vec3(); const matrix = new Mat4(); +const tempRenderData: IRenderData[] = []; +for (let i = 0; i < 4; i++) { + tempRenderData.push({ x: 0, y: 0, z: 0, u: 0, v: 0, color: new Color() }); +} /** * sliced 组装器 @@ -48,11 +47,40 @@ export const sliced: IAssembler = { createData (sprite: Sprite) { const renderData: RenderData | null = sprite.requestRenderData()!; // 0-4 for local vertex - renderData.dataLength = 4; + renderData.dataLength = 16; renderData.resize(16, 54); + renderData.vertexRow = 4; + renderData.vertexCol = 4; + this.QUAD_INDICES = new Uint16Array(54); + this.createQuadIndices(4, 4); + renderData.chunk.setIndexBuffer(this.QUAD_INDICES); return renderData; }, + createQuadIndices (vertexRow: number, vertexCol: number) { + let offset = 0; + for (let curRow = 0; curRow < vertexRow - 1; curRow++) { + for (let curCol = 0; curCol < vertexCol - 1; curCol++) { + // vid is the index of the left bottom vertex in each rect. + const vid = curRow * vertexCol + curCol; + + // left bottom + this.QUAD_INDICES[offset++] = vid; + // right bottom + this.QUAD_INDICES[offset++] = vid + 1; + // left top + this.QUAD_INDICES[offset++] = vid + vertexCol; + + // right bottom + this.QUAD_INDICES[offset++] = vid + 1; + // right top + this.QUAD_INDICES[offset++] = vid + 1 + vertexCol; + // left top + this.QUAD_INDICES[offset++] = vid + vertexCol; + } + } + }, + updateRenderData (sprite: Sprite) { const frame = sprite.spriteFrame; @@ -68,7 +96,8 @@ export const sliced: IAssembler = { // } dynamicAtlasManager.packToDynamicAtlas(sprite, frame); // TODO update material and uv - this.updateUVs(sprite); + this.updateUVs(sprite); // dirty need + //this.updateColor(sprite); // dirty need const renderData = sprite.renderData; if (renderData && frame) { @@ -104,14 +133,26 @@ export const sliced: IAssembler = { sizableWidth = sizableWidth < 0 ? 0 : sizableWidth; sizableHeight = sizableHeight < 0 ? 0 : sizableHeight; - dataList[0].x = -appX; - dataList[0].y = -appY; - dataList[1].x = leftWidth * xScale - appX; - dataList[1].y = bottomHeight * yScale - appY; - dataList[2].x = dataList[1].x + sizableWidth; - dataList[2].y = dataList[1].y + sizableHeight; - dataList[3].x = width - appX; - dataList[3].y = height - appY; + tempRenderData[0].x = -appX; + tempRenderData[0].y = -appY; + tempRenderData[1].x = leftWidth * xScale - appX; + tempRenderData[1].y = bottomHeight * yScale - appY; + tempRenderData[2].x = tempRenderData[1].x + sizableWidth; + tempRenderData[2].y = tempRenderData[1].y + sizableHeight; + tempRenderData[3].x = width - appX; + tempRenderData[3].y = height - appY; + + for (let curRow = 0; curRow < renderData.vertexRow; curRow++) { + for (let curCol = 0; curCol < renderData.vertexCol; curCol++) { + const curIndex = curRow * renderData.vertexCol + curCol; + if (curIndex < renderData.dataLength + && curRow < tempRenderData.length + && curCol < tempRenderData.length) { + dataList[curIndex].x = tempRenderData[curCol].x; + dataList[curIndex].y = tempRenderData[curRow].y; + } + } + } }, fillBuffers (sprite: Sprite, renderer: IBatcher) { @@ -152,7 +193,7 @@ export const sliced: IAssembler = { let offset = 0; for (let row = 0; row < 4; ++row) { - const rowD = dataList[row]; + const rowD = dataList[row * 4]; for (let col = 0; col < 4; ++col) { const colD = dataList[col]; diff --git a/cocos/2d/assembler/sprite/tiled.ts b/cocos/2d/assembler/sprite/tiled.ts index e1e55814b1..5350a62158 100644 --- a/cocos/2d/assembler/sprite/tiled.ts +++ b/cocos/2d/assembler/sprite/tiled.ts @@ -23,14 +23,13 @@ THE SOFTWARE. */ - - -import { IUV } from '../../assets'; +import { JSB } from 'internal:constants'; +import { IUV, SpriteFrame } from '../../assets'; import { Mat4, Vec3, Color } from '../../../core/math'; import { IRenderData, RenderData } from '../../renderer/render-data'; import { IBatcher } from '../../renderer/i-batcher'; import { Sprite } from '../../components/sprite'; -import { Renderable2D } from '../../framework/renderable-2d'; +import { UIRenderer } from '../../framework/ui-renderer'; import { IAssembler } from '../../renderer/base'; import { StaticVBChunk } from '../../renderer/static-vb-accessor'; @@ -38,10 +37,35 @@ const vec3_temps: Vec3[] = []; for (let i = 0; i < 4; i++) { vec3_temps.push(new Vec3()); } + const matrix = new Mat4(); +const vec3_temp = new Vec3(); + +let origin:IUV; +let leftInner:IUV; +let rightInner:IUV; +let rightOuter:IUV; +let bottomInner:IUV; +let topInner:IUV; +let topOuter:IUV; +let tempRenderDataLength = 0; +const tempRenderData: IRenderData[] = []; +let QUAD_INDICES; + +function has9SlicedOffsetVertexCount (spriteFrame: SpriteFrame) { + if (spriteFrame) { + if (spriteFrame.insetTop > 0 + || spriteFrame.insetBottom > 0 + || spriteFrame.insetLeft > 0 + || spriteFrame.insetRight > 0) { + return 2; // left + right + } + } + return 0; +} export const tiled: IAssembler = { - createData (sprite: Renderable2D) { + createData (sprite: UIRenderer) { return sprite.requestRenderData(); }, @@ -52,8 +76,6 @@ export const tiled: IAssembler = { return; } - renderData.updateRenderData(sprite, frame); - if (!renderData.vertDirty) { return; } @@ -77,17 +99,54 @@ export const tiled: IAssembler = { const hRepeat = centerWidth === 0 ? sizableWidth : sizableWidth / centerWidth; const vRepeat = centerHeight === 0 ? sizableHeight : sizableHeight / centerHeight; - const row = Math.ceil(vRepeat + 2); - const col = Math.ceil(hRepeat + 2); + const offsetVertexCount = has9SlicedOffsetVertexCount(frame); + const row = Math.ceil(vRepeat + offsetVertexCount); + const col = Math.ceil(hRepeat + offsetVertexCount); - renderData.dataLength = Math.max(8, row + 1, col + 1); + renderData.dataLength = (row * 2) * (col * 2); this.updateVerts(sprite, sizableWidth, sizableHeight, row, col); + if (renderData.vertexCount !== row * col * 4) { + if (sprite.renderEntity) { sprite.renderEntity.colorDirty = true; } + } // update data property renderData.resize(row * col * 4, row * col * 6); + // update index here + if (JSB) { + const indexCount = renderData.indexCount; + this.createQuadIndices(indexCount); + renderData.chunk.setIndexBuffer(QUAD_INDICES); + // may can update color & uv here + // need dirty + this.updateWorldUVData(sprite); + //this.updateColorLate(sprite); + } + + renderData.updateRenderData(sprite, frame); }, + createQuadIndices (indexCount) { + if (indexCount % 6 !== 0) { + console.error('illegal index count!'); + return; + } + const quadCount = indexCount / 6; + QUAD_INDICES = null; + QUAD_INDICES = new Uint16Array(indexCount); + let offset = 0; + for (let i = 0; i < quadCount; i++) { + QUAD_INDICES[offset++] = 0 + i * 4; + QUAD_INDICES[offset++] = 1 + i * 4; + QUAD_INDICES[offset++] = 2 + i * 4; + QUAD_INDICES[offset++] = 1 + i * 4; + QUAD_INDICES[offset++] = 3 + i * 4; + QUAD_INDICES[offset++] = 2 + i * 4; + } + }, + + // dirty Mark + // the real update uv is on updateWorldUVData updateUVs (sprite: Sprite) { const renderData = sprite.renderData!; renderData.vertDirty = true; @@ -104,7 +163,7 @@ export const tiled: IAssembler = { } // forColor - this.updataColorLate(sprite); + this.updateColorLate(sprite); // update indices const bid = chunk.bufferId; @@ -125,6 +184,19 @@ export const tiled: IAssembler = { meshBuffer.setDirty(); }, + updateWorldUVData (sprite: Sprite) { + const renderData = sprite.renderData!; + const stride = renderData.floatStride; + const dataList: IRenderData[] = renderData.data; + const vData = renderData.chunk.vb; + for (let i = 0; i < dataList.length; i++) { + const offset = i * stride; + vData[offset + 3] = dataList[i].u; + vData[offset + 4] = dataList[i].v; + } + }, + + // only for TS updateWorldVertexAndUVData (sprite: Sprite, chunk: StaticVBChunk) { const node = sprite.node; node.getWorldMatrix(matrix); @@ -134,170 +206,22 @@ export const tiled: IAssembler = { const dataList: IRenderData[] = renderData.data; const vData = chunk.vb; - const uiTrans = node._uiProps.uiTransformComp!; - const contentWidth = Math.abs(uiTrans.width); - const contentHeight = Math.abs(uiTrans.height); - - const frame = sprite.spriteFrame!; - const rotated = frame.rotated; - const uv = frame.uv; - const uvSliced: IUV[] = frame.uvSliced; - const rect = frame.rect; - - const leftWidth = frame.insetLeft; - const rightWidth = frame.insetRight; - const centerWidth = rect.width - leftWidth - rightWidth; - const topHeight = frame.insetTop; - const bottomHeight = frame.insetBottom; - const centerHeight = rect.height - topHeight - bottomHeight; - let sizableWidth = contentWidth - leftWidth - rightWidth; - let sizableHeight = contentHeight - topHeight - bottomHeight; - sizableWidth = sizableWidth > 0 ? sizableWidth : 0; - sizableHeight = sizableHeight > 0 ? sizableHeight : 0; - const hRepeat = centerWidth === 0 ? sizableWidth : sizableWidth / centerWidth; - const vRepeat = centerHeight === 0 ? sizableHeight : sizableHeight / centerHeight; - const row = Math.ceil(vRepeat + 2); - const col = Math.ceil(hRepeat + 2); - - // update Vertex - let vertexOffset = 0; - let x = 0; let x1 = 0; let y = 0; let y1 = 0; - for (let yIndex = 0, yLength = row; yIndex < yLength; ++yIndex) { - y = dataList[yIndex].y; - y1 = dataList[yIndex + 1].y; - for (let xIndex = 0, xLength = col; xIndex < xLength; ++xIndex) { - x = dataList[xIndex].x; - x1 = dataList[xIndex + 1].x; - - Vec3.set(vec3_temps[0], x, y, 0); - Vec3.set(vec3_temps[1], x1, y, 0); - Vec3.set(vec3_temps[2], x, y1, 0); - Vec3.set(vec3_temps[3], x1, y1, 0); - - for (let i = 0; i < 4; i++) { - const vec3_temp = vec3_temps[i]; - Vec3.transformMat4(vec3_temp, vec3_temp, matrix); - const offset = i * stride; - vData[vertexOffset + offset] = vec3_temp.x; - vData[vertexOffset + offset + 1] = vec3_temp.y; - vData[vertexOffset + offset + 2] = vec3_temp.z; - } - vertexOffset += 4 * stride; - } + for (let i = 0; i < dataList.length; i++) { + Vec3.set(vec3_temp, dataList[i].x, dataList[i].y, dataList[i].z); + Vec3.transformMat4(vec3_temp, vec3_temp, matrix); + const offset = i * stride; + vData[offset] = vec3_temp.x; + vData[offset + 1] = vec3_temp.y; + vData[offset + 2] = vec3_temp.z; } - // update UVs - vertexOffset = 0; - const offset = stride; - const offset1 = offset; const offset2 = offset * 2; const offset3 = offset * 3; const offset4 = offset * 4; - let coefU = 0; let coefV = 0; - const tempXVerts :any = []; - const tempYVerts :any = []; - for (let yIndex = 0, yLength = row; yIndex < yLength; ++yIndex) { - if (sizableHeight > centerHeight) { - if (sizableHeight >= yIndex * centerHeight) { - coefV = 1; - } else { - coefV = vRepeat % 1; - } - } else { - coefV = vRepeat; - } - for (let xIndex = 0, xLength = col; xIndex < xLength; ++xIndex) { - if (sizableWidth > centerWidth) { - if (sizableWidth >= xIndex * centerWidth) { - coefU = 1; - } else { - coefU = hRepeat % 1; - } - } else { - coefU = hRepeat; - } - - const vertexOffsetU = vertexOffset + 3; - const vertexOffsetV = vertexOffsetU + 1; - // UV - if (rotated) { - if (yIndex === 0) { - tempXVerts[0] = uvSliced[0].u; - tempXVerts[1] = uvSliced[0].u; - tempXVerts[2] = uvSliced[4].u + (uvSliced[8].u - uvSliced[4].u) * coefV; - } else if (yIndex < (row - 1)) { - tempXVerts[0] = uvSliced[4].u; - tempXVerts[1] = uvSliced[4].u; - tempXVerts[2] = uvSliced[4].u + (uvSliced[8].u - uvSliced[4].u) * coefV; - } else if (yIndex === (row - 1)) { - tempXVerts[0] = uvSliced[8].u; - tempXVerts[1] = uvSliced[8].u; - tempXVerts[2] = uvSliced[12].u; - } - if (xIndex === 0) { - tempYVerts[0] = uvSliced[0].v; - tempYVerts[1] = uvSliced[1].v + (uvSliced[2].v - uvSliced[1].v) * coefU; - tempYVerts[2] = uvSliced[0].v; - } else if (xIndex < (col - 1)) { - tempYVerts[0] = uvSliced[1].v; - tempYVerts[1] = uvSliced[1].v + (uvSliced[2].v - uvSliced[1].v) * coefU; - tempYVerts[2] = uvSliced[1].v; - } else if (xIndex === (col - 1)) { - tempYVerts[0] = uvSliced[2].v; - tempYVerts[1] = uvSliced[3].v; - tempYVerts[2] = uvSliced[2].v; - } - tempXVerts[3] = tempXVerts[2]; - tempYVerts[3] = tempYVerts[1]; - } else { - if (xIndex === 0) { - tempXVerts[0] = uvSliced[0].u; - tempXVerts[1] = uvSliced[1].u + (uvSliced[2].u - uvSliced[1].u) * coefU; - tempXVerts[2] = uv[0]; - } else if (xIndex < (col - 1)) { - tempXVerts[0] = uvSliced[1].u; - tempXVerts[1] = uvSliced[1].u + (uvSliced[2].u - uvSliced[1].u) * coefU; - tempXVerts[2] = uvSliced[1].u; - } else if (xIndex === (col - 1)) { - tempXVerts[0] = uvSliced[2].u; - tempXVerts[1] = uvSliced[3].u; - tempXVerts[2] = uvSliced[2].u; - } - if (yIndex === 0) { - tempYVerts[0] = uvSliced[0].v; - tempYVerts[1] = uvSliced[0].v; - tempYVerts[2] = uvSliced[4].v + (uvSliced[8].v - uvSliced[4].v) * coefV; - } else if (yIndex < (row - 1)) { - tempYVerts[0] = uvSliced[4].v; - tempYVerts[1] = uvSliced[4].v; - tempYVerts[2] = uvSliced[4].v + (uvSliced[8].v - uvSliced[4].v) * coefV; - } else if (yIndex === (row - 1)) { - tempYVerts[0] = uvSliced[8].v; - tempYVerts[1] = uvSliced[8].v; - tempYVerts[2] = uvSliced[12].v; - } - tempXVerts[3] = tempXVerts[1]; - tempYVerts[3] = tempYVerts[2]; - } - // lb - vData[vertexOffsetU] = tempXVerts[0]; - vData[vertexOffsetV] = tempYVerts[0]; - // rb - vData[vertexOffsetU + offset1] = tempXVerts[1]; - vData[vertexOffsetV + offset1] = tempYVerts[1]; - // lt - vData[vertexOffsetU + offset2] = tempXVerts[2]; - vData[vertexOffsetV + offset2] = tempYVerts[2]; - // rt - vData[vertexOffsetU + offset3] = tempXVerts[3]; - vData[vertexOffsetV + offset3] = tempYVerts[3]; - - vertexOffset += offset4; - } - } + this.updateWorldUVData(sprite); }, updateVerts (sprite: Sprite, sizableWidth: number, sizableHeight: number, row: number, col: number) { const uiTrans = sprite.node._uiProps.uiTransformComp!; - const renderData: RenderData | null = sprite.renderData; - const data: IRenderData[] = renderData!.data; + const renderData: RenderData = sprite.renderData!; + const dataList: IRenderData[] = renderData.data; const frame = sprite.spriteFrame!; const rect = frame.rect; @@ -311,12 +235,10 @@ export const tiled: IAssembler = { const topHeight = frame.insetTop; const bottomHeight = frame.insetBottom; const centerHeight = rect.height - topHeight - bottomHeight; - const xScale = (uiTrans.width / (leftWidth + rightWidth)) > 1 ? 1 : (uiTrans.width / (leftWidth + rightWidth)); const yScale = (uiTrans.height / (topHeight + bottomHeight)) > 1 ? 1 : (uiTrans.height / (topHeight + bottomHeight)); let offsetWidth = 0; let offsetHeight = 0; - if (centerWidth > 0) { /* * Because the float numerical calculation in javascript is not accurate enough, @@ -332,48 +254,243 @@ export const tiled: IAssembler = { offsetHeight = sizableHeight; } - for (let i = 0; i <= col; i++) { - if (i === 0) { - data[i].x = -appx; - } else if (i > 0 && i < col) { - if (i === 1) { - data[i].x = leftWidth * xScale + Math.min(centerWidth, sizableWidth) - appx; - } else if (centerWidth > 0) { - if (i === (col - 1)) { - data[i].x = leftWidth + offsetWidth + centerWidth * (i - 2) - appx; - } else { - data[i].x = leftWidth + Math.min(centerWidth, sizableWidth) + centerWidth * (i - 2) - appx; - } + // 临时变量存前置数据 + tempRenderDataLength = Math.max(row + 1, col + 1); + for (let i = 0; i < tempRenderDataLength; i++) { + tempRenderData.push({ x: 0, y: 0, z: 0, u: 0, v: 0, color: new Color() }); + } + + const offsetVertexCount = has9SlicedOffsetVertexCount(frame); + if (offsetVertexCount === 0) { + for (let i = 0; i < tempRenderDataLength; i++) { + // for x + if (i >= col) { + tempRenderData[i].x = contentWidth - appx; } else { - data[i].x = leftWidth + sizableWidth - appx; + tempRenderData[i].x = -appx + i * centerWidth; + } + + // for y + if (i >= row) { + tempRenderData[i].y = contentHeight - appy; + } else { + tempRenderData[i].y = -appy + i * centerHeight; + } + } + } else { + for (let i = 0; i < tempRenderDataLength; i++) { + // for x + if (i === 0) { + tempRenderData[i].x = -appx; + } else if (i === 1) { + tempRenderData[i].x = -appx + leftWidth * xScale; + } else if (i > 1 && i < col - 1) { + if (centerWidth > 0) { + tempRenderData[i].x = -appx + leftWidth * xScale + centerWidth * (i - 1); + } else { + tempRenderData[i].x = leftWidth + sizableWidth - appx; + } + } else if (i === col - 1) { + tempRenderData[i].x = -appx + leftWidth * xScale + offsetWidth + centerWidth * (i - 2); + } else if (i >= col) { + tempRenderData[i].x = Math.min(leftWidth + sizableWidth + rightWidth, contentWidth) - appx; + } + + // for y + if (i === 0) { + tempRenderData[i].y = -appy; + } else if (i === 1) { + tempRenderData[i].y = -appy + bottomHeight * yScale; + } else if (i > 1 && i < row - 1) { + if (centerHeight > 0) { + tempRenderData[i].y = -appy + bottomHeight * yScale + centerHeight * (i - 1); + } else { + tempRenderData[i].y = bottomHeight + sizableHeight - appy; + } + } else if (i === row - 1) { + tempRenderData[i].y = -appy + bottomHeight * yScale + offsetHeight + centerHeight * (i - 2); + } else if (i >= row) { + tempRenderData[i].y = Math.min(bottomHeight + sizableHeight + topHeight, contentHeight) - appy; } - } else if (i === col) { - data[i].x = Math.min(leftWidth + sizableWidth + rightWidth, contentWidth) - appx; } } - for (let i = 0; i <= row; i++) { - if (i === 0) { - data[i].y = -appy; - } else if (i > 0 && i < row) { - if (i === 1) { - data[i].y = bottomHeight * yScale + Math.min(centerHeight, sizableHeight) - appy; - } else if (centerHeight > 0) { - if (i === (row - 1)) { - data[i].y = bottomHeight + offsetHeight + (i - 2) * centerHeight - appy; + + // 填datalist + let x = 0; let x1 = 0; let y = 0; let y1 = 0; + for (let yIndex = 0; yIndex < row; ++yIndex) { + y = tempRenderData[yIndex].y; + y1 = tempRenderData[yIndex + 1].y; + for (let xIndex = 0; xIndex < col; ++xIndex) { + x = tempRenderData[xIndex].x; + x1 = tempRenderData[xIndex + 1].x; + + // 4 vertices in a rect + const curIndex = 4 * (yIndex * col + xIndex); + //left bottom + dataList[curIndex].x = x; + dataList[curIndex].y = y; + //right bottom + dataList[curIndex + 1].x = x1; + dataList[curIndex + 1].y = y; + //left top + dataList[curIndex + 2].x = x; + dataList[curIndex + 2].y = y1; + //right top + dataList[curIndex + 3].x = x1; + dataList[curIndex + 3].y = y1; + } + } + + const rotated = frame.rotated; + const uv = frame.uv; + const uvSliced: IUV[] = frame.uvSliced; + // origin at left bottom + origin = uvSliced[0]; + // on bottom edge + leftInner = uvSliced[1]; + rightInner = uvSliced[2]; + rightOuter = uvSliced[3]; + // on left edge + bottomInner = uvSliced[4]; + topInner = uvSliced[8]; + topOuter = uvSliced[12]; + + let coefU = 0; + let coefV = 0; + const hRepeat = centerWidth === 0 ? sizableWidth : sizableWidth / centerWidth; + const vRepeat = centerHeight === 0 ? sizableHeight : sizableHeight / centerHeight; + const tempXVerts :any = []; + const tempYVerts :any = []; + + for (let yIndexUV = 0; yIndexUV < row; ++yIndexUV) { + if (sizableHeight > centerHeight) { + //if 9 sliced, we should exclude bottom border vertex (yIndex-1) + const curYRectCount = offsetVertexCount > 0 ? yIndexUV : yIndexUV + 1; + // The height of the rect which contains the left bottom vertex in current loop should be calculated in total height. + if (sizableHeight >= curYRectCount * centerHeight) { + coefV = 1; + } else { + coefV = vRepeat % 1; + } + } else { + coefV = vRepeat; + } + for (let xIndexUV = 0; xIndexUV < col; ++xIndexUV) { + if (sizableWidth > centerWidth) { + //if 9 sliced, we should exclude left border vertex (xIndex-1) + const curXRectCount = offsetVertexCount > 0 ? xIndexUV : xIndexUV + 1; + // The width of the rect which contains the left bottom vertex in current loop should be calculated in total width. + // Example: xIndex = 2 means that these is the third vertex, we should take the rect whose left bottom vertex is this + // vertex into account, so the following condition should be comparing the values of content size and (2+1)*centerWidth. + if (sizableWidth >= curXRectCount * centerWidth) { + coefU = 1; } else { - data[i].y = bottomHeight + Math.min(centerHeight, sizableHeight) + (i - 2) * centerHeight - appy; + coefU = hRepeat % 1; } } else { - data[i].y = bottomHeight + sizableHeight - appy; + coefU = hRepeat; } - } else if (i === row) { - data[i].y = Math.min(bottomHeight + sizableHeight + topHeight, contentHeight) - appy; + + if (rotated) { + if (offsetVertexCount === 0) { //无九宫 + tempXVerts[0] = bottomInner.u; + tempXVerts[1] = bottomInner.u; + tempXVerts[2] = bottomInner.u + (topInner.u - bottomInner.u) * coefV; + + tempYVerts[0] = leftInner.v; + tempYVerts[1] = leftInner.v + (rightInner.v - leftInner.v) * coefU; + tempYVerts[2] = leftInner.v; + } else { //有九宫 + if (yIndexUV === 0) { + tempXVerts[0] = origin.u; + tempXVerts[1] = origin.u; + tempXVerts[2] = bottomInner.u; + } else if (yIndexUV < (row - 1)) { + tempXVerts[0] = bottomInner.u; + tempXVerts[1] = bottomInner.u; + tempXVerts[2] = bottomInner.u + (topInner.u - bottomInner.u) * coefV; + } else if (yIndexUV === (row - 1)) { + tempXVerts[0] = topInner.u; + tempXVerts[1] = topInner.u; + tempXVerts[2] = topOuter.u; + } + if (xIndexUV === 0) { + tempYVerts[0] = origin.v; + tempYVerts[1] = leftInner.v; + tempYVerts[2] = origin.v; + } else if (xIndexUV < (col - 1)) { + tempYVerts[0] = leftInner.v; + tempYVerts[1] = leftInner.v + (rightInner.v - leftInner.v) * coefU; + tempYVerts[2] = leftInner.v; + } else if (xIndexUV === (col - 1)) { + tempYVerts[0] = rightInner.v; + tempYVerts[1] = rightOuter.v; + tempYVerts[2] = rightInner.v; + } + } + tempXVerts[3] = tempXVerts[2]; + tempYVerts[3] = tempYVerts[1]; + } else { + if (offsetVertexCount === 0) { //无九宫 + tempXVerts[0] = leftInner.u; + tempXVerts[1] = leftInner.u + (rightInner.u - leftInner.u) * coefU; + tempXVerts[2] = leftInner.u; + + tempYVerts[0] = bottomInner.v; + tempYVerts[1] = bottomInner.v; + tempYVerts[2] = bottomInner.v + (topInner.v - bottomInner.v) * coefV; + } else { //有九宫 + if (xIndexUV === 0) { + tempXVerts[0] = origin.u; + tempXVerts[1] = leftInner.u; + tempXVerts[2] = origin.u; + } else if (xIndexUV < (col - 1)) { + tempXVerts[0] = leftInner.u; + tempXVerts[1] = leftInner.u + (rightInner.u - leftInner.u) * coefU; + tempXVerts[2] = leftInner.u; + } else if (xIndexUV === (col - 1)) { + tempXVerts[0] = rightInner.u; + tempXVerts[1] = rightOuter.u; + tempXVerts[2] = rightInner.u; + } + if (yIndexUV === 0) { + tempYVerts[0] = origin.v; + tempYVerts[1] = origin.v; + tempYVerts[2] = bottomInner.v; + } else if (yIndexUV < (row - 1)) { + tempYVerts[0] = bottomInner.v; + tempYVerts[1] = bottomInner.v; + tempYVerts[2] = bottomInner.v + (topInner.v - bottomInner.v) * coefV; + } else if (yIndexUV === (row - 1)) { + tempYVerts[0] = topInner.v; + tempYVerts[1] = topInner.v; + tempYVerts[2] = topOuter.v; + } + } + tempXVerts[3] = tempXVerts[1]; + tempYVerts[3] = tempYVerts[2]; + } + + // it represents the left bottom corner vertex of a rect + const curIndex = 4 * (yIndexUV * col + xIndexUV); + // lb + dataList[curIndex].u = tempXVerts[0]; + dataList[curIndex].v = tempYVerts[0]; + // rb + dataList[curIndex + 1].u = tempXVerts[1]; + dataList[curIndex + 1].v = tempYVerts[1]; + // lt + dataList[curIndex + 2].u = tempXVerts[2]; + dataList[curIndex + 2].v = tempYVerts[2]; + // rt + dataList[curIndex + 3].u = tempXVerts[3]; + dataList[curIndex + 3].v = tempYVerts[3]; } } }, // fill color here - updataColorLate (sprite: Sprite) { + updateColorLate (sprite: Sprite) { const renderData = sprite.renderData!; const vData = renderData.chunk.vb; const stride = renderData.floatStride; diff --git a/cocos/2d/assembler/utils.ts b/cocos/2d/assembler/utils.ts index 3471a8a056..e67ee93aeb 100644 --- a/cocos/2d/assembler/utils.ts +++ b/cocos/2d/assembler/utils.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { Color, Mat4, Vec3 } from '../../core/math'; import { RenderData } from '../renderer/render-data'; import { IBatcher } from '../renderer/i-batcher'; diff --git a/cocos/2d/assets/bitmap-font.ts b/cocos/2d/assets/bitmap-font.ts index 9081038b48..ecbda85704 100644 --- a/cocos/2d/assets/bitmap-font.ts +++ b/cocos/2d/assets/bitmap-font.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { ccclass, type, serializable, editable } from 'cc.decorator'; import { Font } from './font'; import { SpriteFrame } from './sprite-frame'; diff --git a/cocos/2d/assets/font.ts b/cocos/2d/assets/font.ts index b57a343e2a..77bb1aa523 100644 --- a/cocos/2d/assets/font.ts +++ b/cocos/2d/assets/font.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { ccclass } from 'cc.decorator'; import { Asset } from '../../core/assets'; import { legacyCC } from '../../core/global-exports'; diff --git a/cocos/2d/assets/index.ts b/cocos/2d/assets/index.ts index c7ca8ccf53..23f063af1d 100644 --- a/cocos/2d/assets/index.ts +++ b/cocos/2d/assets/index.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module asset - */ + export * from './sprite-frame'; export { SpriteAtlas } from './sprite-atlas'; diff --git a/cocos/2d/assets/label-atlas.ts b/cocos/2d/assets/label-atlas.ts index dc9cde306a..339c480c18 100644 --- a/cocos/2d/assets/label-atlas.ts +++ b/cocos/2d/assets/label-atlas.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { ccclass } from 'cc.decorator'; import { BitmapFont } from './bitmap-font'; import { legacyCC } from '../../core/global-exports'; diff --git a/cocos/2d/assets/sprite-atlas.ts b/cocos/2d/assets/sprite-atlas.ts index 1c94726148..19ef76af89 100644 --- a/cocos/2d/assets/sprite-atlas.ts +++ b/cocos/2d/assets/sprite-atlas.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { EDITOR, TEST } from 'internal:constants'; import { ccclass, serializable, editable } from 'cc.decorator'; import * as js from '../../core/utils/js'; @@ -107,7 +102,7 @@ export class SpriteAtlas extends Asset { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _serialize (ctxForExporting: any): any { if (EDITOR || TEST) { @@ -130,7 +125,7 @@ export class SpriteAtlas extends Asset { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _deserialize (serializeData: any, handle: any) { const data = serializeData as ISpriteAtlasSerializeData; @@ -138,7 +133,7 @@ export class SpriteAtlas extends Asset { const frames = data.spriteFrames; this.spriteFrames = js.createMap(); for (let i = 0; i < frames.length; i += 2) { - handle.result.push(this.spriteFrames, frames[i], frames[i + 1], js._getClassId(SpriteFrame)); + handle.result.push(this.spriteFrames, frames[i], frames[i + 1], js.getClassId(SpriteFrame)); } } } diff --git a/cocos/2d/assets/sprite-frame.ts b/cocos/2d/assets/sprite-frame.ts index 0edc9c08c7..f402ba798e 100644 --- a/cocos/2d/assets/sprite-frame.ts +++ b/cocos/2d/assets/sprite-frame.ts @@ -25,14 +25,9 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { ccclass } from 'cc.decorator'; import { EDITOR, TEST, BUILD } from 'internal:constants'; -import { Rect, Size, Vec2 } from '../../core/math'; +import { Color, Mat4, Rect, Size, Vec2, Vec3 } from '../../core/math'; import { Asset } from '../../core/assets/asset'; import { TextureBase } from '../../core/assets/texture-base'; import { legacyCC } from '../../core/global-exports'; @@ -41,11 +36,21 @@ import { Texture2D } from '../../core/assets/texture-2d'; import { errorID, warnID } from '../../core/platform/debug'; import { dynamicAtlasManager } from '../utils/dynamic-atlas/atlas-manager'; import { js } from '../../core/utils/js'; +import { Mesh } from '../../3d/assets/mesh'; +import { createMesh } from '../../3d/misc'; +import { Attribute, AttributeName, Format, PrimitiveMode } from '../../core/gfx'; const INSET_LEFT = 0; const INSET_TOP = 1; const INSET_RIGHT = 2; const INSET_BOTTOM = 3; +const temp_vec3 = new Vec3(); +const temp_matrix = new Mat4(); + +enum MeshType { + RECT = 0, + POLYGON = 1, // Todo: Polygon mode need add +} export interface IUV { u: number; @@ -53,13 +58,22 @@ export interface IUV { } interface IVertices { - x: any; - y: any; - triangles: any; - nu: number[]; - u: number[]; - nv: number[]; - v: number[]; + rawPosition: Vec3[]; // Original position of the vertex, pixel value + positions: number[]; // The position of the vertex after being affected by the attribute + indexes: number[]; // IB + uv: number[]; // Pixel uv value + nuv: number[]; // Normalized uv value + minPos: Vec3; + maxPos: Vec3; +} + +interface IVerticesSerialize { // hack for format + rawPosition: number[]; + indexes: number[]; + uv: number[]; + nuv: number[]; + minPos: Vec3; + maxPos: Vec3; } interface ISpriteFramesSerializeData { @@ -72,9 +86,12 @@ interface ISpriteFramesSerializeData { originalSize: Size; rotated: boolean; capInsets: number[]; - vertices: IVertices; + vertices: IVerticesSerialize; texture: string; packable: boolean; + pixelsToUnit: number; + pivot: Vec2; + meshType: MeshType; } interface ISpriteFrameOriginal { @@ -239,10 +256,11 @@ export class SpriteFrame extends Asset { } /** - * @en - * @zh + * @en uv update event + * @zh uv 更新事件 */ public static EVENT_UV_UPDATED = 'uv_updated'; + public static MeshType = MeshType; /** * @en Top border distance of sliced 9 rect. @@ -492,6 +510,30 @@ export class SpriteFrame extends Asset { return this._original; } + /** + * @en Number of pixels corresponding to unit size in world space (pixels per meter) + * @zh 世界空间中的单位大小对应的像素数量(像素每米) + */ + get pixelsToUnit () { + return this._pixelsToUnit; + } + + /** + * @en Local origin position when generating the mesh + * @zh 生成 mesh 时本地坐标原点位置 + */ + get pivot () { + return this._pivot; + } + + /** + * @en mesh information, you should call the [[ensureMeshData]] function before using it + * @zh mesh 信息,你应该在使用它之前调用 [[ensureMeshData]] 函数来确保其可用 + */ + get mesh () { + return this._mesh; + } + /** * @en Vertex list for the mesh type sprite frame * @zh 网格类型精灵帧的所有顶点列表 @@ -542,6 +584,28 @@ export class SpriteFrame extends Asset { protected _packable = true; + protected _pixelsToUnit = 100; + + protected _pivot = new Vec2(0.5, 0.5); // center + + // Todo: Some features need add + protected _meshType = MeshType.RECT; + protected _extrude = 0; // when polygon type use + protected _customOutLine = [];// MayBe later + // Here you can generate polygons by polygon-separator, expecting the generated polygons to be pixel-standard vertex arrays, + // and save this array in the file + // that is, the mesh information of the original image + // (two-dimensional mesh information, which needs to be serialized and is the basis for the polygon mesh generation) + // In addition to the vertex array, a mesh should be generated based on the conditions + // i.e., the mesh information generated by combining the above five conditions, which needs to be serialized + // and at runtime, the actual mesh used is the generated mesh (static mesh) + // (updated after attribute value changes in the editor, adjusting vertices/re-generation) + + // Mesh api + protected declare _mesh: Mesh | null; + protected _minPos = new Vec3(); + protected _maxPos = new Vec3(); + constructor () { super(); @@ -661,7 +725,7 @@ export class SpriteFrame extends Asset { } /** - * @en Gets the related GFX [[Texture]] resource + * @en Gets the related GFX [[gfx.Texture]] resource * @zh 获取渲染贴图的 GFX 资源 */ public getGFXTexture () { @@ -791,6 +855,17 @@ export class SpriteFrame extends Asset { return true; } + /** + * @en Make sure the mesh is available, you should call it before using the mesh + * @zh 确保 mesh 可用,你应该在使用 mesh 之前调用它 + */ + public ensureMeshData () { + if (this._mesh) return; + // If SpriteFrame from load, we need init vertices when use mesh + this._initVertices(); + this._createMesh(); + } + public destroy () { if (this._packable && dynamicAtlasManager) { dynamicAtlasManager.deleteAtlasSpriteFrame(this); @@ -800,7 +875,7 @@ export class SpriteFrame extends Asset { /** * Calculate UV for sliced - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _calculateSlicedUV () { const rect = this._rect; @@ -866,7 +941,7 @@ export class SpriteFrame extends Asset { /** * Calculate UV - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _calculateUV () { const rect = this._rect; @@ -1086,21 +1161,11 @@ export class SpriteFrame extends Asset { } } - const vertices = this.vertices; - if (vertices) { - vertices.nu.length = 0; - vertices.nv.length = 0; - for (let i = 0; i < vertices.u.length; i++) { - vertices.nu[i] = vertices.u[i] / texw; - vertices.nv[i] = vertices.v[i] / texh; - } - } - this._calculateSlicedUV(); } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _setDynamicAtlasFrame (frame) { if (!frame) return; @@ -1118,7 +1183,7 @@ export class SpriteFrame extends Asset { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _resetDynamicAtlasFrame () { if (!this._original) return; @@ -1130,7 +1195,7 @@ export class SpriteFrame extends Asset { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _checkPackable () { const dynamicAtlas = dynamicAtlasManager; @@ -1156,7 +1221,7 @@ export class SpriteFrame extends Asset { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _serialize (ctxForExporting: any): any { if (EDITOR || TEST) { @@ -1173,12 +1238,18 @@ export class SpriteFrame extends Asset { let vertices; if (this.vertices) { + const posArray = []; + for (let i = 0; i < this.vertices.rawPosition.length; i++) { + const pos = this.vertices.rawPosition[i]; + Vec3.toArray(posArray, pos, 3 * i); + } vertices = { - triangles: this.vertices.triangles, - x: this.vertices.x, - y: this.vertices.y, - u: this.vertices.u, - v: this.vertices.v, + rawPosition: posArray, + indexes: this.vertices.indexes, + uv: this.vertices.uv, + nuv: this.vertices.nuv, + minPos: { x: this.vertices.minPos.x, y: this.vertices.minPos.y, z: this.vertices.minPos.z }, + maxPos: { x: this.vertices.maxPos.x, y: this.vertices.maxPos.y, z: this.vertices.maxPos.z }, }; } @@ -1193,6 +1264,9 @@ export class SpriteFrame extends Asset { vertices, texture: (!ctxForExporting && texture) || undefined, packable: this._packable, + pixelsToUnit: this._pixelsToUnit, + pivot: this._pivot, + meshType: this._meshType, }; // 为 underfined 的数据则不在序列化文件里显示 @@ -1202,7 +1276,7 @@ export class SpriteFrame extends Asset { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _deserialize (serializeData: any, handle: any) { const data = serializeData as ISpriteFramesSerializeData; @@ -1224,6 +1298,13 @@ export class SpriteFrame extends Asset { this._name = data.name; this._packable = !!data.packable; + this._pixelsToUnit = data.pixelsToUnit; + const pivot = data.pivot; + if (pivot) { + this._pivot = new Vec2(pivot.x, pivot.y); + } + this._meshType = data.meshType; + const capInsets = data.capInsets; if (capInsets) { this._capInsets[INSET_LEFT] = capInsets[INSET_LEFT]; @@ -1235,7 +1316,7 @@ export class SpriteFrame extends Asset { if (!BUILD) { // manually load texture via _textureSetter if (data.texture) { - handle.result.push(this, '_textureSource', data.texture, js._getClassId(Texture2D)); + handle.result.push(this, '_textureSource', data.texture, js.getClassId(Texture2D)); } } @@ -1243,11 +1324,25 @@ export class SpriteFrame extends Asset { this._atlasUuid = data.atlas ? data.atlas : ''; } - this.vertices = data.vertices; - if (this.vertices) { - // initialize normal uv arrays - this.vertices.nu = []; - this.vertices.nv = []; + const vertices = data.vertices; + if (vertices) { + if (!this.vertices) { + this.vertices = { + rawPosition: [], + positions: [], + indexes: vertices.indexes, + uv: vertices.uv, + nuv: vertices.nuv, + minPos: new Vec3(vertices.minPos.x, vertices.minPos.y, vertices.minPos.z), + maxPos: new Vec3(vertices.maxPos.x, vertices.maxPos.y, vertices.maxPos.z), + }; + } + this.vertices.rawPosition.length = 0; + const rawPosition = vertices.rawPosition; + for (let i = 0; i < rawPosition.length; i += 3) { + this.vertices.rawPosition.push(new Vec3(rawPosition[i], rawPosition[i + 1], rawPosition[i + 2])); + } + this._updateMeshVertices(); } } @@ -1255,13 +1350,13 @@ export class SpriteFrame extends Asset { const sp = new SpriteFrame(); const v = this.vertices; sp.vertices = v ? { - x: v.x, - y: v.y, - triangles: v.triangles, /* need clone ? */ - nu: v.nu?.slice(0), - u: v.u?.slice(0), - nv: v.nv?.slice(0), - v: v.v?.slice(0), + rawPosition: v.rawPosition.slice(0), + positions: v.positions.slice(0), + indexes: v.indexes.slice(0), + uv: v.uv.slice(0), + nuv: v.nuv.slice(0), + minPos: v.minPos.clone(), + maxPos: v.minPos.clone(), } : null as any; sp.uv.splice(0, sp.uv.length, ...this.uv); sp.unbiasUV.splice(0, sp.unbiasUV.length, ...this.unbiasUV); @@ -1275,6 +1370,9 @@ export class SpriteFrame extends Asset { sp._texture = this._texture; sp._isFlipUVX = this._isFlipUVX; sp._isFlipUVY = this._isFlipUVY; + sp._pixelsToUnit = this._pixelsToUnit; + sp._pivot.set(this._pivot); + sp._meshType = this._meshType; return sp; } @@ -1303,6 +1401,9 @@ export class SpriteFrame extends Asset { } this._checkPackable(); + if (this._mesh) { + this._updateMesh(); + } } public initDefault (uuid?: string) { @@ -1316,6 +1417,140 @@ export class SpriteFrame extends Asset { public validate () { return this._texture && this._rect && this._rect.width !== 0 && this._rect.height !== 0; } + + protected _initVertices () { + if (!this.vertices) { + this.vertices = { + rawPosition: [], + positions: [], + indexes: [], + uv: [], + nuv: [], + minPos: new Vec3(), + maxPos: new Vec3(), + }; + } else { + this.vertices.rawPosition.length = 0; + this.vertices.positions.length = 0; + this.vertices.indexes.length = 0; + this.vertices.uv.length = 0; + this.vertices.nuv.length = 0; + this.vertices.minPos.set(0, 0, 0); + this.vertices.maxPos.set(0, 0, 0); + } + if (this._meshType === MeshType.POLYGON) { + // Use Bayazit to generate vertices and assign values + } else { // Rect mode + // default center is 0.5,0.5 + const tex = this.texture; + const texw = tex.width; + const texh = tex.height; + const rect = this.rect; + const width = rect.width; + const height = rect.height; + const rectX = rect.x; + const rectY = texh - rect.y - height; + const halfWidth = width / 2; + const halfHeight = height / 2; + + const l = texw === 0 ? 0 : rectX / texw; + const r = texw === 0 ? 1 : (rectX + width) / texw; + const t = texh === 0 ? 1 : (rectY + height) / texh; + const b = texh === 0 ? 0 : rect.y / texh; + + // left bottom + temp_vec3.set(-halfWidth, -halfHeight, 0); + this.vertices.rawPosition.push(temp_vec3.clone()); + this.vertices.uv.push(rectX); + this.vertices.uv.push(rectY + height); + this.vertices.nuv.push(l); + this.vertices.nuv.push(b); + this.vertices.minPos.set(temp_vec3); + // right bottom + temp_vec3.set(halfWidth, -halfHeight, 0); + this.vertices.rawPosition.push(temp_vec3.clone()); + this.vertices.uv.push(rectX + width); + this.vertices.uv.push(rectY + height); + this.vertices.nuv.push(r); + this.vertices.nuv.push(b); + // left top + temp_vec3.set(-halfWidth, halfHeight, 0); + this.vertices.rawPosition.push(temp_vec3.clone()); + this.vertices.uv.push(rectX); + this.vertices.uv.push(rectY); + this.vertices.nuv.push(l); + this.vertices.nuv.push(t); + // right top + temp_vec3.set(halfWidth, halfHeight, 0); + this.vertices.rawPosition.push(temp_vec3.clone()); + this.vertices.uv.push(rectX + width); + this.vertices.uv.push(rectY); + this.vertices.nuv.push(r); + this.vertices.nuv.push(t); + this.vertices.maxPos.set(temp_vec3); + + this.vertices.indexes.push(0); + this.vertices.indexes.push(1); + this.vertices.indexes.push(2); + this.vertices.indexes.push(2); + this.vertices.indexes.push(1); + this.vertices.indexes.push(3); + } + this._updateMeshVertices(); + } + + // Combine vertex information, unit information, anchor points, extrude and even customOutline to generate the actual vertices used + protected _updateMeshVertices () { + // Start generating the Geometry information to generate the mesh + temp_matrix.identity(); + + const units = 1 / this._pixelsToUnit; + const temp_vec3 = new Vec3(units, units, 1); + temp_matrix.scale(temp_vec3); + const PosX = -(this._pivot.x - 0.5) * this.rect.width * units; + const PosY = -(this._pivot.y - 0.5) * this.rect.height * units; + temp_vec3.set(PosX, PosY, 0); + temp_matrix.translate(temp_vec3); + const vertices = this.vertices!; + + for (let i = 0; i < vertices.rawPosition.length; i++) { + const pos = vertices.rawPosition[i]; + Vec3.transformMat4(temp_vec3, pos, temp_matrix); + Vec3.toArray(vertices.positions, temp_vec3, 3 * i); + } + Vec3.transformMat4(this._minPos, vertices.minPos, temp_matrix); + Vec3.transformMat4(this._maxPos, vertices.maxPos, temp_matrix); + } + + protected _createMesh () { + this._mesh = createMesh({ + primitiveMode: PrimitiveMode.TRIANGLE_LIST, + positions: this.vertices!.positions, + uvs: this.vertices!.nuv, + indices: this.vertices!.indexes, + minPos: this._minPos, + maxPos: this._maxPos, + + // colors: [ + // Color.WHITE.r, Color.WHITE.g, Color.WHITE.b, Color.WHITE.a, + // Color.WHITE.r, Color.WHITE.g, Color.WHITE.b, Color.WHITE.a, + // Color.WHITE.r, Color.WHITE.g, Color.WHITE.b, Color.WHITE.a, + // Color.WHITE.r, Color.WHITE.g, Color.WHITE.b, Color.WHITE.a], + attributes: [ + new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), + new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), + // new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8UI, true), + ], + }); + } + + protected _updateMesh () { + if (this._mesh) { + this._mesh.destroy(); + } + this._initVertices(); + this._createMesh(); + } } legacyCC.SpriteFrame = SpriteFrame; diff --git a/cocos/2d/assets/ttf-font.ts b/cocos/2d/assets/ttf-font.ts index f17cec14ce..6e1c7ad23e 100644 --- a/cocos/2d/assets/ttf-font.ts +++ b/cocos/2d/assets/ttf-font.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { ccclass, string, override, serializable } from 'cc.decorator'; import { extname } from '../../core/utils/path'; import { Font } from './font'; @@ -41,13 +36,13 @@ import { legacyCC } from '../../core/global-exports'; @ccclass('cc.TTFFont') export class TTFFont extends Font { /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @serializable public _fontFamily: string | null = null; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @override @string @@ -59,7 +54,7 @@ export class TTFFont extends Font { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @override get _nativeDep () { diff --git a/cocos/2d/category.json b/cocos/2d/category.json new file mode 100644 index 0000000000..f7fc841ca6 --- /dev/null +++ b/cocos/2d/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "2D 渲染", + "en": "2D Rendering" + }, + "description": { + "zh": "2D 渲染相关的组件与资源", + "en": "2D rendering related components and assets" + } +} \ No newline at end of file diff --git a/cocos/2d/components/deprecated.ts b/cocos/2d/components/deprecated.ts index 9d0edd1588..49ed13365f 100644 --- a/cocos/2d/components/deprecated.ts +++ b/cocos/2d/components/deprecated.ts @@ -23,10 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ import { Mask } from './mask'; import { Label } from './label'; import { LabelOutline } from './label-outline'; @@ -38,6 +34,7 @@ import { UIStaticBatch } from './ui-static-batch'; import { UIOpacity } from './ui-opacity'; import { js } from '../../core/utils/js'; import { legacyCC } from '../../core/global-exports'; +import { replaceProperty } from '../../core/utils'; /** * Alias of [[Mask]] @@ -101,3 +98,12 @@ js.setClassAlias(UIStaticBatch, 'cc.UIStaticBatchComponent'); */ export { UIOpacity as UIOpacityComponent }; js.setClassAlias(UIOpacity, 'cc.UIOpacityComponent'); + +replaceProperty(Mask.prototype, 'Mask', [ + { + name: 'graphics', + newName: 'subComp', + target: Mask.prototype, + targetName: 'Mask', + }, +]); diff --git a/cocos/2d/components/graphics.ts b/cocos/2d/components/graphics.ts index 93659738cf..166ffee7e2 100644 --- a/cocos/2d/components/graphics.ts +++ b/cocos/2d/components/graphics.ts @@ -24,14 +24,10 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, executionOrder, menu, tooltip, type, visible, override, editable, serializable } from 'cc.decorator'; +import { JSB } from 'internal:constants'; import { builtinResMgr } from '../../core/builtin'; -import { InstanceMaterialType, Renderable2D } from '../framework/renderable-2d'; +import { InstanceMaterialType, UIRenderer } from '../framework/ui-renderer'; import { director } from '../../core/director'; import { Color } from '../../core/math'; import { scene } from '../../core/renderer'; @@ -40,10 +36,12 @@ import { IBatcher } from '../renderer/i-batcher'; import { LineCap, LineJoin } from '../assembler/graphics/types'; import { Impl } from '../assembler/graphics/webgl/impl'; import { RenderingSubMesh } from '../../core/assets'; -import { Format, PrimitiveMode, Attribute, Device, BufferUsageBit, BufferInfo, MemoryUsageBit } from '../../core/gfx'; +import { Format, PrimitiveMode, Attribute, Device, BufferUsageBit, BufferInfo, MemoryUsageBit, deviceManager } from '../../core/gfx'; import { vfmtPosColor, getAttributeStride, getComponentPerVertex } from '../renderer/vertex-format'; import { legacyCC } from '../../core/global-exports'; import { warnID } from '../../core/platform/debug'; +import { NativeUIModelProxy } from '../renderer/native-2d'; +import { RenderEntity, RenderEntityType } from '../renderer/render-entity'; const attributes = vfmtPosColor.concat([ new Attribute('a_dist', Format.R32F), @@ -64,7 +62,7 @@ const stride = getAttributeStride(attributes); @help('i18n:cc.Graphics') @executionOrder(110) @menu('2D/Graphics') -export class Graphics extends Renderable2D { +export class Graphics extends UIRenderer { /** * @en * Current line width. @@ -241,10 +239,19 @@ export class Graphics extends Renderable2D { private _graphicsUseSubMeshes: RenderingSubMesh[] = []; + //nativeObj + protected declare _graphicsNativeProxy:NativeUIModelProxy; + get graphicsNativeProxy () { + return this._graphicsNativeProxy; + } + constructor () { super(); this._instanceMaterialType = InstanceMaterialType.ADD_COLOR; - this.impl = new Impl(); + this.impl = new Impl(this); + if (JSB) { + this._graphicsNativeProxy = new NativeUIModelProxy(); + } } public onRestore () { @@ -254,9 +261,22 @@ export class Graphics extends Renderable2D { } public onLoad () { + super.onLoad(); this.model = director.root!.createModel(scene.Model); this.model.node = this.model.transform = this.node; this._flushAssembler(); + if (JSB) { + this._graphicsNativeProxy.initModel(this.node); + } + } + + // hack for mask + protected _postRender (render: IBatcher) { + if (!this._postAssembler) { + return; + } + + render.commitComp(this, null, null, this._postAssembler, null); } public onEnable () { @@ -264,10 +284,6 @@ export class Graphics extends Renderable2D { this._updateMtlForGraphics(); } - public onDisable () { - super.onDisable(); - } - public onDestroy () { this._sceneGetter = null; if (this.model) { @@ -299,8 +315,10 @@ export class Graphics extends Renderable2D { * @zh * 移动路径起点到坐标(x, y)。 * - * @param x - 移动坐标 x 轴。 - * @param y - 移动坐标 y 轴。 + * @param x @en The x-axis coordinate of the target position. + * @zh 目标位置的 X 轴坐标。 + * @param y @en The y-axis coordinate of the target position. + * @zh 目标位置的 y 轴坐标。 */ public moveTo (x: number, y: number) { if (!this.impl) { @@ -317,8 +335,10 @@ export class Graphics extends Renderable2D { * @zh * 绘制直线路径。 * - * @param x - 绘制路径坐标 x 轴。 - * @param y - 绘制路径坐标 y 轴。 + * @param x @en The x-axis coordinate of the target position. + * @zh 目标位置的 x 轴坐标。 + * @param y @en The x-axis coordinate of the target position. + * @zh 目标位置的 y 轴坐标。 */ public lineTo (x: number, y: number) { if (!this.impl) { @@ -335,12 +355,18 @@ export class Graphics extends Renderable2D { * @zh * 绘制三次贝赛尔曲线路径。 * - * @param c1x - 第一个控制点的坐标 x 轴。 - * @param c1y - 第一个控制点的坐标 y 轴。 - * @param c2x - 第二个控制点的坐标 x 轴。 - * @param c2y - 第二个控制点的坐标 y 轴。 - * @param x - 最后一个控制点的坐标 x 轴。 - * @param y - 最后一个控制点的坐标 y 轴。 + * @param c1x @en The x-axis coordinate of the first control point. + * @zh 第一个控制点的 x 轴坐标。 + * @param c1y @en The y-axis coordinate of the first control point. + * @zh 第一个控制点的 y 轴坐标。 + * @param c2x @en The x-axis coordinate of the second control point. + * @zh 第二个控制点的 x 轴坐标。 + * @param c2y @en The y-axis coordinate of the second control point. + * @zh 第二个控制点的 y 轴坐标。 + * @param x @en The x-axis coordinate of the last control point. + * @zh 最后一个控制点的 x 轴坐标。 + * @param y @en The y-axis coordinate of the last control point. + * @zh 最后一个控制点的 y 轴坐标。 */ public bezierCurveTo (c1x: number, c1y: number, c2x: number, c2y: number, x: number, y: number) { if (!this.impl) { @@ -357,10 +383,14 @@ export class Graphics extends Renderable2D { * @zh * 绘制二次贝赛尔曲线路径。 * - * @param cx - 起始控制点的坐标 x 轴。 - * @param cy - 起始控制点的坐标 y 轴。 - * @param x - 终点控制点的坐标 x 轴。 - * @param y - 终点控制点的坐标 x 轴。 + * @param cx @en The x-axis coordinate of the starting control point. + * @zh 起始控制点的 x 轴坐标。 + * @param cy @en The y-axis coordinate of the starting control point. + * @zh 起始控制点的 y 轴坐标。 + * @param x @en The x-axis coordinates of the endpoint control point. + * @zh 终点控制点的 x 轴坐标。 + * @param y @en The y-axis coordinates of the endpoint control point. + * @zh 终点控制点的 x 轴坐标。 */ public quadraticCurveTo (cx: number, cy: number, x: number, y: number) { if (!this.impl) { @@ -378,12 +408,18 @@ export class Graphics extends Renderable2D { * @zh * 绘制圆弧路径。圆弧路径的圆心在 (cx, cy) 位置,半径为 r ,根据 counterclockwise (默认为false)指定的方向从 startAngle 开始绘制,到 endAngle 结束。 * - * @param cx - 中心控制点的坐标 x 轴。 - * @param cy - 中心控制点的坐标 y 轴。 - * @param r - 圆弧弧度。 - * @param startAngle - 开始弧度,从正 x 轴顺时针方向测量。 - * @param endAngle - 结束弧度,从正 x 轴顺时针方向测量。 - * @param counterclockwise 如果为真,在两个角度之间逆时针绘制。默认顺时针。 + * @param cx @en The coordinate x-axis of the central control point. + * @zh 中心控制点的坐标 x 轴。 + * @param cy @en The coordinate y-axis of the central control point. + * @zh 中心控制点的坐标 y 轴。 + * @param r @en Angle in Radian. + * @zh 圆弧弧度。 + * @param startAngle @en The starting angle in radian, measured clockwise from the positive x-axis. + * @zh 弧度起点,从正 x 轴顺时针方向测量。 + * @param endAngle @en The ending angle in radian, measured clockwise from the positive x-axis. + * @zh 弧度终点,从正 x 轴顺时针方向测量。 + * @param counterclockwise @en If true, draws counterclockwise between the two angles. Default is clockwise. + * @zh 如果为真,在两个角度之间逆时针绘制。默认顺时针。 */ public arc (cx: number, cy: number, r: number, startAngle: number, endAngle: number, counterclockwise: boolean) { if (!this.impl) { @@ -400,10 +436,14 @@ export class Graphics extends Renderable2D { * @zh * 绘制椭圆路径。 * - * @param cx - 中心点的坐标 x 轴。 - * @param cy - 中心点的坐标 y 轴。 - * @param rx - 椭圆 x 轴半径。 - * @param ry - 椭圆 y 轴半径。 + * @param cx @en The x-axis coordinates of the center point. + * @zh 中心点的 x 轴坐标。 + * @param cy @en The y-axis coordinates of the center point. + * @zh 中心点的 y 轴坐标。 + * @param rx @en The radius of the x-axis of the ellipse. + * @zh 椭圆 x 轴半径。 + * @param ry @en The radius of the y-axis of the ellipse. + * @zh 椭圆 y 轴半径。 */ public ellipse (cx: number, cy: number, rx: number, ry: number) { if (!this.impl) { @@ -420,9 +460,12 @@ export class Graphics extends Renderable2D { * @zh * 绘制圆形路径。 * - * @param cx - 中心点的坐标 x 轴。 - * @param cy - 中心点的坐标 y 轴。 - * @param r - 圆半径。 + * @param cx @en The x-axis coordinates of the center point. + * @zh 中心点的 x 轴坐标。 + * @param cy @en The y-axis coordinates of the center point. + * @zh 中心点的 y 轴坐标。 + * @param r @en Radius. + * @zh 圆半径。 */ public circle (cx: number, cy: number, r: number) { if (!this.impl) { @@ -439,10 +482,14 @@ export class Graphics extends Renderable2D { * @zh * 绘制矩形路径。 * - * @param x - 矩形起始坐标 x 轴。 - * @param y - 矩形起始坐标 y 轴。 - * @param w - 矩形宽度。 - * @param h - 矩形高度。 + * @param x @en The x-axis coordinate of the top left point of the rectangle. + * @zh 矩形起始 x 轴坐标。 + * @param y @en The y-axis coordinate of the top left point of the rectangle. + * @zh 矩形起始 y 轴坐标。 + * @param w @en The width of the rectangle. + * @zh 矩形宽度。 + * @param h @en The height of the rectangle. + * @zh 矩形高度。 */ public rect (x: number, y: number, w: number, h: number) { if (!this.impl) { @@ -459,11 +506,16 @@ export class Graphics extends Renderable2D { * @zh * 绘制圆角矩形路径。 * - * @param x - 矩形起始坐标 x 轴。 - * @param y - 矩形起始坐标 y 轴。 - * @param w - 矩形宽度。 - * @param h - 矩形高度。 - * @param r - 矩形圆角半径。 + * @param x @en The x-axis coordinate of the top left point of the rectangle. + * @zh 矩形起始 x 轴坐标。 + * @param y @en The y-axis coordinate of the top left point of the rectangle. + * @zh 矩形起始 y 轴坐标。 + * @param w @en The width of the rectangle. + * @zh 矩形宽度。 + * @param h @en The height of the rectangle. + * @zh 矩形高度。 + * @param r @en Radius of rectangular rounded corners. + * @zh 矩形圆角半径。 */ public roundRect (x: number, y: number, w: number, h: number, r: number) { if (!this.impl) { @@ -480,10 +532,14 @@ export class Graphics extends Renderable2D { * @zh * 绘制填充矩形。 * - * @param x - 矩形起始坐标 x 轴。 - * @param y - 矩形起始坐标 y 轴。 - * @param w - 矩形宽度。 - * @param h - 矩形高度。 + * @param x @en The x-axis coordinate of the top left point of the rectangle. + * @zh 矩形起始 x 轴坐标。 + * @param y @en The y-axis coordinate of the top left point of the rectangle. + * @zh 矩形起始 y 轴坐标。 + * @param w @en The width of the rectangle. + * @zh 矩形宽度。 + * @param h @en The height of the rectangle. + * @zh 矩形高度。 */ public fillRect (x, y, w, h) { this.rect(x, y, w, h); @@ -509,6 +565,9 @@ export class Graphics extends Renderable2D { const subModel = this.model.subModels[i]; subModel.inputAssembler.indexCount = 0; } + if (JSB) { + this._graphicsNativeProxy.clear();// need native + } } this.markForUpdateRenderData(); @@ -583,7 +642,7 @@ export class Graphics extends Renderable2D { } if (this.model.subModels.length <= idx) { - const gfxDevice: Device = legacyCC.director.root.device; + const gfxDevice: Device = deviceManager.gfxDevice; const vertexBuffer = gfxDevice.createBuffer(new BufferInfo( BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, @@ -669,6 +728,32 @@ export class Graphics extends Renderable2D { return !!this.model && this._isDrawing; } + + public updateRenderer () { + super.updateRenderer(); + if (JSB) { + if (this._isNeedUploadData) { + if (this.impl) { + const renderDataList = this.impl.getRenderDataList(); + for (let i = 0; i < renderDataList.length; i++) { + renderDataList[i].setRenderDrawInfoAttributes(); + } + const len = this.model!.subModels.length; + if (renderDataList.length > len) { + for (let i = len; i < renderDataList.length; i++) { + this._graphicsNativeProxy.activeSubModel(i); + } + } + } + this._graphicsNativeProxy.uploadData(); + this._isNeedUploadData = false; + } + } + } + + protected createRenderEntity () { + return new RenderEntity(RenderEntityType.DYNAMIC); + } } legacyCC.Graphics = Graphics; diff --git a/cocos/2d/components/label-outline.ts b/cocos/2d/components/label-outline.ts index 68ff79713f..ddeb4e526f 100644 --- a/cocos/2d/components/label-outline.ts +++ b/cocos/2d/components/label-outline.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, executionOrder, menu, tooltip, requireComponent, executeInEditMode, serializable } from 'cc.decorator'; import { Component } from '../../core/components/component'; import { Color } from '../../core/math'; diff --git a/cocos/2d/components/label-shadow.ts b/cocos/2d/components/label-shadow.ts index 9e094173b3..b56c31dfd7 100644 --- a/cocos/2d/components/label-shadow.ts +++ b/cocos/2d/components/label-shadow.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, executionOrder, menu, tooltip, requireComponent, executeInEditMode, serializable } from 'cc.decorator'; import { Component } from '../../core/components/component'; import { Color, Vec2 } from '../../core/math'; diff --git a/cocos/2d/components/label.ts b/cocos/2d/components/label.ts index dbd1ceeac0..d6c3071a98 100644 --- a/cocos/2d/components/label.ts +++ b/cocos/2d/components/label.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, executionOrder, menu, tooltip, displayOrder, visible, multiline, type, serializable, editable } from 'cc.decorator'; import { BYTEDANCE, EDITOR } from 'internal:constants'; import { minigame } from 'pal/minigame'; @@ -38,7 +33,7 @@ import { ccenum } from '../../core/value-types/enum'; import { IBatcher } from '../renderer/i-batcher'; import { FontAtlas } from '../assets/bitmap-font'; import { CanvasPool, ISharedLabelData, LetterRenderTexture } from '../assembler/label/font-utils'; -import { InstanceMaterialType, Renderable2D } from '../framework/renderable-2d'; +import { InstanceMaterialType, UIRenderer } from '../framework/ui-renderer'; import { TextureBase } from '../../core/assets/texture-base'; import { PixelFormat } from '../../core/assets/asset-enum'; import { legacyCC } from '../../core/global-exports'; @@ -194,7 +189,7 @@ ccenum(CacheMode); @help('i18n:cc.Label') @executionOrder(110) @menu('2D/Label') -export class Label extends Renderable2D { +export class Label extends UIRenderer { public static HorizontalAlign = HorizontalTextAlignment; public static VerticalAlign = VerticalTextAlignment; public static Overflow = Overflow; @@ -229,7 +224,7 @@ export class Label extends Renderable2D { } this._string = value; - this.updateRenderData(); + this.markForUpdateRenderData(); } /** @@ -251,7 +246,7 @@ export class Label extends Renderable2D { } this._horizontalAlign = value; - this.updateRenderData(); + this.markForUpdateRenderData(); } /** @@ -273,7 +268,7 @@ export class Label extends Renderable2D { } this._verticalAlign = value; - this.updateRenderData(); + this.markForUpdateRenderData(); } /** @@ -308,7 +303,7 @@ export class Label extends Renderable2D { } this._fontSize = value; - this.updateRenderData(); + this.markForUpdateRenderData(); } /** @@ -330,7 +325,7 @@ export class Label extends Renderable2D { } this._fontFamily = value; - this.updateRenderData(); + this.markForUpdateRenderData(); } /** @@ -351,7 +346,7 @@ export class Label extends Renderable2D { } this._lineHeight = value; - this.updateRenderData(); + this.markForUpdateRenderData(); } /** @@ -375,7 +370,7 @@ export class Label extends Renderable2D { } this._spacingX = value; - this.updateRenderData(); + this.markForUpdateRenderData(); } /** @@ -397,7 +392,7 @@ export class Label extends Renderable2D { } this._overflow = value; - this.updateRenderData(); + this.markForUpdateRenderData(); } /** @@ -418,7 +413,7 @@ export class Label extends Renderable2D { } this._enableWrapText = value; - this.updateRenderData(); + this.markForUpdateRenderData(); } /** @@ -444,7 +439,7 @@ export class Label extends Renderable2D { // if delete the font, we should change isSystemFontUsed to true this._isSystemFontUsed = !value; - if (EDITOR && value) { + if (EDITOR) { this._userDefinedFont = value; } @@ -453,10 +448,7 @@ export class Label extends Renderable2D { // if (value && this._isSystemFontUsed) // this._isSystemFontUsed = false; - if (this._renderData) { - this.destroyRenderData(); - this._renderData = null; - } + this.destroyRenderData(); this._fontAtlas = null; this.updateRenderData(true); @@ -480,7 +472,6 @@ export class Label extends Renderable2D { } this.destroyRenderData(); - this._renderData = null; if (EDITOR) { if (!value && this._isSystemFontUsed && this._userDefinedFont) { @@ -495,7 +486,7 @@ export class Label extends Renderable2D { this.font = null; } this._flushAssembler(); - this.updateRenderData(); + this.markForUpdateRenderData(); } /** @@ -545,7 +536,7 @@ export class Label extends Renderable2D { } this._isBold = value; - this.updateRenderData(); + this.markForUpdateRenderData(); } /** @@ -566,7 +557,7 @@ export class Label extends Renderable2D { } this._isItalic = value; - this.updateRenderData(); + this.markForUpdateRenderData(); } /** @@ -587,7 +578,7 @@ export class Label extends Renderable2D { } this._isUnderline = value; - this.updateRenderData(); + this.markForUpdateRenderData(); } /** @@ -604,7 +595,7 @@ export class Label extends Renderable2D { public set underlineHeight (value) { if (this._underlineHeight === value) return; this._underlineHeight = value; - this.updateRenderData(); + this.markForUpdateRenderData(); } get spriteFrame () { @@ -628,7 +619,7 @@ export class Label extends Renderable2D { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ get _bmFontOriginalSize () { if (this._font instanceof BitmapFont) { @@ -734,17 +725,15 @@ export class Label extends Renderable2D { } public updateRenderData (force = false) { - this.markForUpdateRenderData(); - if (force) { this._flushAssembler(); // Hack: Fixed the bug that richText wants to get the label length by _measureText, // _assembler.updateRenderData will update the content size immediately. if (this.renderData) this.renderData.vertDirty = true; this._applyFontTexture(); - if (this._assembler) { - this._assembler.updateRenderData(this); - } + } + if (this._assembler) { + this._assembler.updateRenderData(this); } } @@ -755,7 +744,7 @@ export class Label extends Renderable2D { // Cannot use the base class methods directly because BMFont and CHAR cannot be updated in assambler with just color. protected _updateColor () { super._updateColor(); - this.updateRenderData(false); + this.markForUpdateRenderData(); } protected _canRender () { @@ -783,10 +772,11 @@ export class Label extends Renderable2D { this._assembler = assembler; } - if (!this._renderData) { + if (!this.renderData) { if (this._assembler && this._assembler.createData) { this._renderData = this._assembler.createData(this); - this._renderData!.material = this.material; + this.renderData!.material = this.material; + this._updateColor(); } } } diff --git a/cocos/2d/components/mask.ts b/cocos/2d/components/mask.ts index ffb0c96186..fed0237cb2 100644 --- a/cocos/2d/components/mask.ts +++ b/cocos/2d/components/mask.ts @@ -24,13 +24,9 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, executionOrder, menu, tooltip, displayOrder, type, visible, override, serializable, range, slide } from 'cc.decorator'; -import { InstanceMaterialType, Renderable2D } from '../framework/renderable-2d'; +import { JSB } from 'internal:constants'; +import { InstanceMaterialType, UIRenderer } from '../framework/ui-renderer'; import { clamp, Color, Mat4, Vec2, Vec3 } from '../../core/math'; import { warnID } from '../../core/platform'; import { IBatcher } from '../renderer/i-batcher'; @@ -38,8 +34,8 @@ import { ccenum } from '../../core/value-types/enum'; import { Graphics } from './graphics'; import { TransformBit } from '../../core/scene-graph/node-enum'; import { SpriteFrame } from '../assets/sprite-frame'; -import { Game, Material, builtinResMgr, director, CCObject } from '../../core'; -import { Device, BufferInfo, BufferUsageBit, MemoryUsageBit, PrimitiveMode } from '../../core/gfx'; +import { Game, Material, builtinResMgr, director, CCObject, Node, NodeEventType } from '../../core'; +import { Device, BufferInfo, BufferUsageBit, MemoryUsageBit, PrimitiveMode, deviceManager } from '../../core/gfx'; import { legacyCC } from '../../core/global-exports'; import { MaterialInstance, scene } from '../../core/renderer'; import { Model } from '../../core/renderer/scene'; @@ -47,6 +43,10 @@ import { vfmt, getAttributeStride } from '../renderer/vertex-format'; 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 { RenderDrawInfoType } from '../renderer/render-draw-info'; +import { Sprite } from './sprite'; const _worldMatrix = new Mat4(); const _vec2_temp = new Vec2(); @@ -118,7 +118,9 @@ const SEGMENTS_MAX = 10000; @help('i18n:cc.Mask') @executionOrder(110) @menu('2D/Mask') -export class Mask extends Renderable2D { +export class Mask extends UIRenderer { + // only for the mask use to reset stage + public static ChildPostAssembler: IAssemblerManager | null = null; /** * @en * The mask type. @@ -137,26 +139,34 @@ export class Mask extends Renderable2D { return; } - // if (this._type === MaskType.IMAGE_STENCIL && !this._spriteFrame) { - // this._detachClearModel(); - // } - this._type = value; this.markForUpdateRenderData(false); this._updateMaterial(); if (this._type !== MaskType.IMAGE_STENCIL) { + if (this._sprite) { + this._sprite = null; + } this._spriteFrame = null; + this._maskNode!.parent = null; + this._changeRenderType(); this._updateGraphics(); - if (this._renderData) { - this.destroyRenderData(); - this._renderData = null; + if (JSB) { + this.subComp!.renderEntity.setIsSubMask(true); + // subMask and mask should have the same inverted flag + this.subComp!.renderEntity.setIsMaskInverted(this._inverted); } } else { - this._useRenderData(); - if (this._graphics) { this._graphics.clear(); + this._graphics = null; + } + 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); } } } @@ -179,6 +189,12 @@ export class Mask extends Renderable2D { this.stencilStage = Stage.DISABLED; if (this._graphics) { this._graphics.stencilStage = Stage.DISABLED; + } else if (this._sprite) { + this._sprite.stencilStage = Stage.DISABLED; + } + + if (JSB) { + this._renderEntity.setIsMaskInverted(this._inverted); } } @@ -226,13 +242,12 @@ export class Mask extends Renderable2D { return; } - const lastSp = this._spriteFrame; this._spriteFrame = value; - if (this._type === MaskType.IMAGE_STENCIL) { - if (!lastSp && value) { - this.markForUpdateRenderData(); - } + + if (this._sprite) { + this._sprite.spriteFrame = value; } + this._updateMaterial(); } /** @@ -263,40 +278,14 @@ export class Mask extends Renderable2D { } this._alphaThreshold = value; - if (this.type === MaskType.IMAGE_STENCIL && this._graphics) { - const mat = this._graphics.getMaterialInstance(0)!; + if (this.type === MaskType.IMAGE_STENCIL && this._sprite) { + const mat = this._sprite.getMaterialInstance(0)!; mat.setProperty('alphaThreshold', this._alphaThreshold); } } - get graphics () { - return this._graphics; - } - - get dstBlendFactor () { - return this._dstBlendFactor; - } - - set dstBlendFactor (value) { - if (this._dstBlendFactor === value) { - return; - } - - this._dstBlendFactor = value; - this._updateBlendFunc(); - } - - get srcBlendFactor () { - return this._srcBlendFactor; - } - - set srcBlendFactor (value) { - if (this._srcBlendFactor === value) { - return; - } - - this._srcBlendFactor = value; - this._updateBlendFunc(); + get subComp () { + return this._graphics || this._sprite; } @override @@ -307,12 +296,7 @@ export class Mask extends Renderable2D { } set color (value) { - if (this._color === value) { - return; - } - - this._color.set(value); - this.markForUpdateRenderData(); + super.color = value; } @override @@ -328,11 +312,11 @@ export class Mask extends Renderable2D { public static Type = MaskType; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _clearStencilMtl: Material | null = null; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _clearModel: Model | null = null; @@ -345,15 +329,19 @@ export class Mask extends Renderable2D { @serializable protected _segments = 64; + // for image stencil @serializable protected _spriteFrame: SpriteFrame | null = null; @serializable protected _alphaThreshold = 0.1; + protected _sprite: Sprite | null = null; protected _graphics: Graphics | null = null; + protected _maskNode: Node | null = null; // child node,is graphics or sprite - private _clearModelMesh: RenderingSubMesh| null = null; + // always use + private _clearModelMesh: RenderingSubMesh | null = null; constructor () { super(); @@ -361,11 +349,21 @@ export class Mask extends Renderable2D { } public onLoad () { + super.onLoad(); this._createClearModel(); - this._createGraphics(); + this._changeRenderType(); - if (this._graphics) { - this._graphics.onLoad(); + 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); + // hack for isMeshBuffer flag + this.renderData.renderDrawInfo.setIsMeshBuffer(true); + this.renderData.drawInfoType = RenderDrawInfoType.MODEL; + } } } @@ -373,6 +371,12 @@ export class Mask extends Renderable2D { super.onEnable(); this._updateGraphics(); this._enableGraphics(); + this.node.on(NodeEventType.SIZE_CHANGED, this._sizeChange, this); + this.node.on(NodeEventType.SIBLING_ORDER_CHANGED, this._siblingChange, this); + this.node.on(NodeEventType.LAYER_CHANGED, this._layerChange, this); + this._sizeChange(); + this._siblingChange(); + this._layerChange(); } /** @@ -380,15 +384,18 @@ export class Mask extends Renderable2D { * 图形内容重塑。 */ public onRestore () { - this._createGraphics(); + this._changeRenderType(); super.updateMaterial(); this._updateGraphics(); - this._renderFlag = this._canRender(); + this.markForUpdateRenderData(); } public onDisable () { super.onDisable(); this._disableGraphics(); + this.node.off(NodeEventType.SIZE_CHANGED, this._sizeChange, this); + this.node.off(NodeEventType.SIBLING_ORDER_CHANGED, this._siblingChange, this); + this.node.off(NodeEventType.LAYER_CHANGED, this._layerChange, this); } public onDestroy () { @@ -401,7 +408,7 @@ export class Mask extends Renderable2D { this._clearStencilMtl.destroy(); } - this._removeGraphics(); + this._removeMaskNode(); super.onDestroy(); } @@ -465,7 +472,11 @@ export class Mask extends Renderable2D { return false; } - return this._graphics !== null && (this._type !== MaskType.IMAGE_STENCIL || this._spriteFrame !== null); + if (this._type !== MaskType.IMAGE_STENCIL) { + return this._graphics !== null; + } else { + return this._sprite !== null && this._spriteFrame !== null; // Or use sprite canRender + } } protected _flushAssembler () { @@ -484,16 +495,79 @@ export class Mask extends Renderable2D { this._useRenderData(); } + private _changeRenderType () { + const isGraphics = (this._type !== MaskType.IMAGE_STENCIL); + if (isGraphics) { + this._createGraphics(); + } else { + this._createSprite(); + } + } + + private _initSpriteNode () { + const node = new Node('MASK_CHILD'); + node.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy; + node.addComponent(Sprite); + node.setPosition(0, 0, 0); + node.layer = this.node.layer; + this._maskNode = node; + this.node.insertChild(node, 0); + } + + private _sizeChange () { + if (this._sprite) { + this._maskNode!._uiProps.uiTransformComp!.setContentSize(this.node._uiProps.uiTransformComp!.contentSize); + } + } + + private _siblingChange () { + if (this._maskNode && this._maskNode.getSiblingIndex() !== 0) { + this._maskNode.setSiblingIndex(0); + } + } + + private _layerChange () { + if (this._maskNode) { + this._maskNode.layer = this.node.layer; + } + } + + protected _createSprite () { + if (!this._sprite) { + this._initSpriteNode(); + const sprite = this._sprite = this._maskNode!.getComponent(Sprite)!; + sprite.color = Color.WHITE.clone(); + // @ts-expect-error Mask hack + sprite._postAssembler = Mask.ChildPostAssembler!.getAssembler(this); + sprite.sizeMode = 0; + this._sizeChange(); + } + this._sprite.spriteFrame = this._spriteFrame; + this._updateMaterial(); + } + + private _initGraphicsNode () { + const node = new Node('MASK_CHILD'); + node.hideFlags |= CCObject.Flags.DontSave | CCObject.Flags.HideInHierarchy; + node.addComponent(Graphics); + node.setPosition(0, 0, 0); + node.layer = this.node.layer; + this._maskNode = node; + this.node.insertChild(node, 0); + } + protected _createGraphics () { if (!this._graphics) { - const graphics = this._graphics = new Graphics(); + this._initGraphicsNode(); + const graphics = this._graphics = this._maskNode!.getComponent(Graphics)!; graphics._objFlags |= CCObject.Flags.IsOnLoadCalled;// hack for destroy - graphics.node = this.node; graphics.node.getWorldMatrix(); graphics.lineWidth = 0; const color = Color.WHITE.clone(); color.a = 0; graphics.fillColor = color; + // @ts-expect-error hack for graphics protected attributes + graphics._postAssembler = Mask.ChildPostAssembler!.getAssembler(this); } this._updateMaterial(); @@ -546,7 +620,7 @@ export class Mask extends Renderable2D { this._clearModel = director.root!.createModel(scene.Model); this._clearModel.node = this._clearModel.transform = this.node; const stride = getAttributeStride(vfmt); - const gfxDevice: Device = legacyCC.director.root.device; + const gfxDevice: Device = deviceManager.gfxDevice; const vertexBuffer = gfxDevice.createBuffer(new BufferInfo( BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, @@ -569,56 +643,75 @@ export class Mask extends Renderable2D { this._clearModelMesh.subMeshIdx = 0; this._clearModel.initSubModel(0, this._clearModelMesh, this._clearStencilMtl); + + // sync to native + if (JSB) { + if (this._renderData) { + const drawInfo = this._renderData.renderDrawInfo; + drawInfo.setModel(this._clearModel); + drawInfo.setMaterial(this._clearStencilMtl); + } + } } } + protected _updateBuiltinMaterial (): Material { + return this._clearStencilMtl!; + } + protected _updateMaterial () { if (this._graphics) { const target = this._graphics; target.stencilStage = Stage.DISABLED; - let mat; - if (this._type === MaskType.IMAGE_STENCIL) { - mat = builtinResMgr.get('ui-alpha-test-material'); - target.setMaterial(mat, 0); - mat = target.getMaterialInstance(0); - mat.setProperty('alphaThreshold', this._alphaThreshold); - } else { - mat = builtinResMgr.get('ui-graphics-material'); - target.setMaterial(mat, 0); - target.getMaterialInstance(0); - } + const mat = builtinResMgr.get('ui-graphics-material'); + target.setMaterial(mat, 0); + target.getMaterialInstance(0); + } else if (this._sprite) { + const target = this._sprite; + target.stencilStage = Stage.DISABLED; + let mat = builtinResMgr.get('ui-alpha-test-material'); + target.setMaterial(mat, 0); + mat = target.getMaterialInstance(0)!; + mat.setProperty('alphaThreshold', this._alphaThreshold); } } protected _enableGraphics () { - if (this._graphics) { - // @ts-expect-error hack for mask _graphics renderFlag - this._graphics._renderFlag = this._graphics._canRender(); + if (this.subComp) { + this.subComp.enabled = true; } } protected _disableGraphics () { - if (this._graphics) { - this._graphics.onDisable(); + if (this.subComp) { + this.subComp.enabled = false; } } - protected _removeGraphics () { - if (this._graphics) { - this._graphics.destroy(); - this._graphics._destroyImmediate(); // FIX: cocos-creator/2d-tasks#2511. TODO: cocos-creator/2d-tasks#2516 + protected _removeMaskNode () { + if (this._maskNode && this._maskNode.isValid) { + this._maskNode.destroy(); + // this._graphics._destroyImmediate(); // FIX: cocos-creator/2d-tasks#2511. TODO: cocos-creator/2d-tasks#2516 + this._sprite = null; this._graphics = null; } } protected _useRenderData () { - if (this._type === MaskType.IMAGE_STENCIL && !this._renderData) { + //if (this._type === MaskType.IMAGE_STENCIL && !this.renderData) { + if (!this.renderData) { if (this._assembler && this._assembler.createData) { this._renderData = this._assembler.createData(this); this.markForUpdateRenderData(); } } } + + // RenderEntity + // it should be overwritten by inherited classes + protected createRenderEntity () { + return new RenderEntity(RenderEntityType.DYNAMIC); + } } NodeEventProcessor._maskComp = Mask; diff --git a/cocos/2d/components/rich-text.ts b/cocos/2d/components/rich-text.ts index 5f6a653eef..8d59472278 100644 --- a/cocos/2d/components/rich-text.ts +++ b/cocos/2d/components/rich-text.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, executeInEditMode, executionOrder, help, menu, tooltip, multiline, type, displayOrder, serializable } from 'cc.decorator'; import { DEV, EDITOR } from 'internal:constants'; import { Font, SpriteAtlas, TTFFont, SpriteFrame } from '../assets'; @@ -47,7 +42,6 @@ import { legacyCC } from '../../core/global-exports'; import { Component } from '../../core/components'; import { CCObject } from '../../core'; import { NodeEventType } from '../../core/scene-graph/node-event'; -import { CylinderColliderComponent } from '../../physics/framework/deprecated'; const _htmlTextParser = new HtmlTextParser(); const RichTextChildName = 'RICHTEXT_CHILD'; @@ -115,6 +109,7 @@ function getSegmentByPool (type: string, content: string | SpriteFrame) { seg.comp.string = content as string; seg.comp.horizontalAlign = HorizontalTextAlignment.LEFT; seg.comp.verticalAlign = VerticalTextAlignment.TOP; + seg.comp.underlineHeight = 2; } node.setPosition(0, 0, 0); const trans = node._uiProps.uiTransformComp!; @@ -476,6 +471,7 @@ export class RichText extends Component { protected _layoutDirty = true; protected _lineOffsetX = 0; protected _updateRichTextStatus: () => void; + protected _labelChildrenNum = 0; // only ISegment constructor () { super(); @@ -695,7 +691,6 @@ export class RichText extends Component { } } - console.error(`try times = ${1000 - leftTryTimes}`); return partStringArr; } @@ -780,10 +775,9 @@ export class RichText extends Component { segment.comp = child.getComponent(Sprite); imagePool.put(segment); } + this._labelChildrenNum--; } } - // Tolerate null parent child (upgrade issue may cause this special case) - children.length = 0; this._segments.length = 0; this._labelSegmentsCache.length = 0; @@ -827,7 +821,7 @@ export class RichText extends Component { labelSegment.lineCount = this._lineCount; labelSegment.node._uiProps.uiTransformComp!.setAnchorPoint(0, 0); labelSegment.node.layer = this.node.layer; - this.node.addChild(labelSegment.node); + this.node.insertChild(labelSegment.node, this._labelChildrenNum++); this._applyTextAttribute(labelSegment); this._segments.push(labelSegment); @@ -964,7 +958,7 @@ export class RichText extends Component { segment.imageOffset = style.imageOffset; } segment.node.layer = this.node.layer; - this.node.addChild(segment.node); + this.node.insertChild(segment.node, this._labelChildrenNum++); this._segments.push(segment); const spriteRect = spriteFrame.rect.clone(); diff --git a/cocos/2d/components/sprite.ts b/cocos/2d/components/sprite.ts index 8ac3ad8416..3ed18783e3 100644 --- a/cocos/2d/components/sprite.ts +++ b/cocos/2d/components/sprite.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, executionOrder, menu, tooltip, displayOrder, type, range, editable, serializable, visible } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { SpriteAtlas } from '../assets/sprite-atlas'; @@ -37,7 +32,7 @@ import { Vec2 } from '../../core/math'; import { ccenum } from '../../core/value-types/enum'; import { clamp } from '../../core/math/utils'; import { IBatcher } from '../renderer/i-batcher'; -import { Renderable2D, InstanceMaterialType } from '../framework/renderable-2d'; +import { UIRenderer, InstanceMaterialType } from '../framework/ui-renderer'; import { PixelFormat } from '../../core/assets/asset-enum'; import { TextureBase } from '../../core/assets/texture-base'; import { Material, RenderTexture } from '../../core'; @@ -175,7 +170,7 @@ enum EventType { @help('i18n:cc.Sprite') @executionOrder(110) @menu('2D/Sprite') -export class Sprite extends Renderable2D { +export class Sprite extends UIRenderer { /** * @en * The sprite atlas where the sprite is. @@ -216,8 +211,7 @@ export class Sprite extends Renderable2D { const lastSprite = this._spriteFrame; this._spriteFrame = value; - // render & update render data flag will be triggered while applying new sprite frame - this.markForUpdateRenderData(false); + this.markForUpdateRenderData(); this._applySpriteFrame(lastSprite); if (EDITOR) { this.node.emit(EventType.SPRITE_FRAME_CHANGED, this); @@ -273,8 +267,7 @@ export class Sprite extends Renderable2D { if (this._fillType !== value) { if (value === FillType.RADIAL || this._fillType === FillType.RADIAL) { this.destroyRenderData(); - this._renderData = null; - } else if (this._renderData) { + } else if (this.renderData) { this.markForUpdateRenderData(true); } } @@ -304,7 +297,7 @@ export class Sprite extends Renderable2D { set fillCenter (value) { this._fillCenter.x = value.x; this._fillCenter.y = value.y; - if (this._type === SpriteType.FILLED && this._renderData) { + if (this._type === SpriteType.FILLED && this.renderData) { this.markForUpdateRenderData(); } } @@ -331,7 +324,7 @@ export class Sprite extends Renderable2D { set fillStart (value) { this._fillStart = clamp(value, 0, 1); - if (this._type === SpriteType.FILLED && this._renderData) { + if (this._type === SpriteType.FILLED && this.renderData) { this.markForUpdateRenderData(); this._updateUVs(); } @@ -359,7 +352,7 @@ export class Sprite extends Renderable2D { set fillRange (value) { // positive: counterclockwise, negative: clockwise this._fillRange = clamp(value, -1, 1); - if (this._type === SpriteType.FILLED && this._renderData) { + if (this._type === SpriteType.FILLED && this.renderData) { this.markForUpdateRenderData(); this._updateUVs(); } @@ -392,7 +385,7 @@ export class Sprite extends Renderable2D { this._isTrimmedMode = value; if ((this._type === SpriteType.SIMPLE /* || this._type === SpriteType.MESH */) - && this._renderData) { + && this.renderData) { this.markForUpdateRenderData(true); } } @@ -493,6 +486,7 @@ export class Sprite extends Renderable2D { } public onDisable () { + super.onDisable(); if (this._spriteFrame && this._type === SpriteType.SLICED) { this._spriteFrame.off(SpriteFrame.EVENT_UV_UPDATED, this._updateUVs, this); } @@ -589,10 +583,10 @@ export class Sprite extends Renderable2D { this._assembler = assembler; } - if (!this._renderData) { + if (!this.renderData) { if (this._assembler && this._assembler.createData) { this._renderData = this._assembler.createData(this); - this._renderData!.material = this.getRenderMaterial(0); + this.renderData!.material = this.getRenderMaterial(0); this.markForUpdateRenderData(); if (this.spriteFrame) { this._assembler.updateUVs(this); @@ -611,6 +605,15 @@ export class Sprite extends Renderable2D { } } + // hack for mask + protected _postRender (render: IBatcher) { + if (!this._postAssembler) { + return; + } + + render.commitComp(this, null, null, this._postAssembler, null); + } + private _applySpriteSize () { if (this._spriteFrame) { if (!this._spriteFrame.isDefault) { @@ -661,8 +664,8 @@ export class Sprite extends Renderable2D { } } - if (this._renderData) { - this._renderData.material = material; + if (this.renderData) { + this.renderData.material = material; } } @@ -686,7 +689,7 @@ export class Sprite extends Renderable2D { textureChanged = true; } if (textureChanged) { - if (this._renderData) this._renderData.textureDirty = true; + if (this.renderData) this.renderData.textureDirty = true; this.changeMaterialForDefine(); } this._applySpriteSize(); diff --git a/cocos/2d/components/ui-mesh-renderer.ts b/cocos/2d/components/ui-mesh-renderer.ts index 43f05132de..ca585daa8b 100644 --- a/cocos/2d/components/ui-mesh-renderer.ts +++ b/cocos/2d/components/ui-mesh-renderer.ts @@ -24,61 +24,95 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - -import { ccclass, help, executionOrder, menu } from 'cc.decorator'; -import { RenderableComponent } from '../../core/components/renderable-component'; +import { ccclass, help, executionOrder, menu, executeInEditMode } from 'cc.decorator'; +import { JSB } from 'internal:constants'; +import { ModelRenderer } from '../../core/components/model-renderer'; import { RenderPriority } from '../../core/pipeline/define'; import { IBatcher } from '../renderer/i-batcher'; -import { scene } from '../../core/renderer'; import { Stage } from '../renderer/stencil-manager'; import { Component } from '../../core/components'; import { legacyCC } from '../../core/global-exports'; +import { NativeUIModelProxy } from '../renderer/native-2d'; +import { uiRendererManager } from '../framework/ui-renderer-manager'; +import { RenderEntity, RenderEntityType } from '../renderer/render-entity'; +import { director } from '../../core/director'; +import { MeshRenderData, RenderData } from '../renderer/render-data'; +import { assert } from '../../core'; +import { RenderDrawInfoType } from '../renderer/render-draw-info'; /** * @en * The component of model. * When you place particles or models in the UI, you must add this component to render. - * The component must be placed on a node with the [[MeshRenderer]] or the [[Particle]]. + * The component must be placed on a node with the [[MeshRenderer]] or the [[ParticleSystem]]. * * @zh * UI 模型基础组件。 - * 当你在 UI 中放置模型或者粒子的时候,必须添加该组件才能渲染。该组件必须放置在带有 [[MeshRenderer]] 或者 [[Particle]] 组件的节点上。 + * 当你在 UI 中放置模型或者粒子的时候,必须添加该组件才能渲染。该组件必须放置在带有 [[MeshRenderer]] 或者 [[ParticleSystem]] 组件的节点上。 */ @ccclass('cc.UIMeshRenderer') @help('i18n:cc.UIMeshRenderer') @executionOrder(110) @menu('UI/UIMeshRenderer') +@executeInEditMode export class UIMeshRenderer extends Component { + constructor () { + super(); + this._renderEntity = new RenderEntity(RenderEntityType.DYNAMIC); + if (JSB) { + this._UIModelNativeProxy = new NativeUIModelProxy(); + } + } + public get modelComponent () { return this._modelComponent; } - private _modelComponent: RenderableComponent | null = null; + private _modelComponent: ModelRenderer | null = null; + + //nativeObj + private declare _UIModelNativeProxy: NativeUIModelProxy; + protected declare _renderEntity : RenderEntity; + private modelCount = 0; + public _dirtyVersion = -1; + public _internalId = -1; public __preload () { this.node._uiProps.uiComp = this; } + onEnable () { + uiRendererManager.addRenderer(this); + this.markForUpdateRenderData(); + } + + onDisable () { + uiRendererManager.removeRenderer(this); + if (this.renderEntity) this.renderEntity.enabled = false; + } + public onLoad () { if (!this.node._uiProps.uiTransformComp) { this.node.addComponent('cc.UITransform'); } - this._modelComponent = this.getComponent('cc.RenderableComponent') as RenderableComponent; + this._modelComponent = this.getComponent('cc.ModelRenderer') as ModelRenderer; if (!this._modelComponent) { console.warn(`node '${this.node && this.node.name}' doesn't have any renderable component`); + return; } + if (JSB) { + this._UIModelNativeProxy.attachNode(this.node); + } + this.renderEntity.setNode(this.node); } public onDestroy () { + this.renderEntity.setNode(null); if (this.node._uiProps.uiComp === this) { this.node._uiProps.uiComp = null; } - this._modelComponent = this.getComponent('cc.RenderableComponent') as RenderableComponent; + this._modelComponent = this.getComponent('cc.ModelRenderer') as ModelRenderer; if (!this._modelComponent) { return; } @@ -94,7 +128,7 @@ export class UIMeshRenderer extends Component { * 一般在 UI 渲染流程中调用,用于组装所有的渲染数据到顶点数据缓冲区。 * 注意:不要手动调用该函数,除非你理解整个流程。 */ - public updateAssembler (render: IBatcher) { + public _render (render: IBatcher) { if (this._modelComponent) { const models = this._modelComponent._collectModels(); // @ts-expect-error: UIMeshRenderer do not attachToScene @@ -110,6 +144,42 @@ export class UIMeshRenderer extends Component { return false; } + public fillBuffers (render: IBatcher) { + if (this.enabled) { + this._render(render); + } + } + + // Native updateAssembler + public updateRenderer () { + if (JSB) { + if (this._modelComponent) { + const models = this._modelComponent._collectModels(); + // @ts-expect-error: UIMeshRenderer do not attachToScene + this._modelComponent._detachFromScene(); // JSB + if (models.length !== this.modelCount) { + for (let i = this.modelCount; i < models.length; i++) { + this._uploadRenderData(i); + this._UIModelNativeProxy.updateModels(models[i]); + } + } + this.modelCount = models.length; + this._UIModelNativeProxy.attachDrawInfo(); + } + } + } + + private _uploadRenderData (index) { + if (JSB) { + const renderData = MeshRenderData.add(); + // @ts-expect-error temporary no care + renderData.initRenderDrawInfo(this, RenderDrawInfoType.MODEL); + // @ts-expect-error temporary no care + this._renderData = renderData; + this._renderData!.material = this._modelComponent!.getMaterialInstance(index); + } + } + /** * @en Post render data submission procedure, it's executed after assembler updated for all children. * It may assemble some extra render data to the geometry buffers, or it may only change some render states. @@ -122,6 +192,14 @@ export class UIMeshRenderer extends Component { } public update () { + if (JSB) { + if (this._modelComponent) { + const models = this._modelComponent._collectModels(); + if (models.length !== this.modelCount) { + this.markForUpdateRenderData(); + } + } + } this._fitUIRenderQueue(); } @@ -151,15 +229,26 @@ export class UIMeshRenderer extends Component { // interface public markForUpdateRenderData (enable = true) { + uiRendererManager.markDirtyRenderer(this); } - public stencilStage : Stage = Stage.DISABLED; + public stencilStage: Stage = Stage.DISABLED; public setNodeDirty () { } public setTextureDirty () { } + + get renderEntity () { + assert(this._renderEntity); + return this._renderEntity; + } + + protected _renderData: RenderData | null = null; + get renderData () { + return this._renderData; + } } legacyCC.UIMeshRenderer = UIMeshRenderer; diff --git a/cocos/2d/components/ui-opacity.ts b/cocos/2d/components/ui-opacity.ts index 0bfcea196f..3e1e11f2eb 100644 --- a/cocos/2d/components/ui-opacity.ts +++ b/cocos/2d/components/ui-opacity.ts @@ -23,14 +23,11 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, disallowMultiple, editable, executeInEditMode, executionOrder, help, menu, serializable, tooltip } from 'cc.decorator'; +import { JSB } from 'internal:constants'; import { Component } from '../../core/components/component'; import { clampf } from '../../core/utils/misc'; +import { UIRenderer } from '../framework/ui-renderer'; /** * @en @@ -68,6 +65,18 @@ export class UIOpacity extends Component { value = clampf(value, 0, 255); this._opacity = value; this.node._uiProps.localOpacity = value / 255; + + this.setEntityColorDirtyRecursively(true); + } + + private setEntityColorDirtyRecursively (dirty: boolean) { + if (JSB) { + const render = this.node._uiProps.uiComp as UIRenderer; + if (render) { + render.setEntityOpacity(this.node._uiProps.localOpacity); + } + UIRenderer.setEntityColorDirtyRecursively(this.node, dirty); + } } @serializable @@ -75,9 +84,11 @@ export class UIOpacity extends Component { public onEnable () { this.node._uiProps.localOpacity = this._opacity / 255; + this.setEntityColorDirtyRecursively(true); } public onDisable () { this.node._uiProps.localOpacity = 1; + this.setEntityColorDirtyRecursively(true); } } diff --git a/cocos/2d/components/ui-static-batch.ts b/cocos/2d/components/ui-static-batch.ts index c3afedb4d0..ecae9dbdc9 100644 --- a/cocos/2d/components/ui-static-batch.ts +++ b/cocos/2d/components/ui-static-batch.ts @@ -23,13 +23,8 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, menu, executionOrder, visible, override } from 'cc.decorator'; -import { Renderable2D } from '../framework/renderable-2d'; +import { UIRenderer } from '../framework/ui-renderer'; import { IBatcher } from '../renderer/i-batcher'; import { DrawBatch2D } from '../renderer/draw-batch'; import { director, Color, warnID } from '../../core'; @@ -54,7 +49,7 @@ import { StaticVBAccessor } from '../renderer/static-vb-accessor'; @help('i18n:cc.UIStaticBatch') @menu('2D/UIStaticBatch') @executionOrder(110) -export class UIStaticBatch extends Renderable2D { +export class UIStaticBatch extends UIRenderer { @override @visible(false) get color (): Readonly { @@ -78,39 +73,6 @@ export class UIStaticBatch extends Renderable2D { protected _dirty = true; private _uiDrawBatchList: DrawBatch2D[] = []; - public onLoad () { - // const ui = this._getBatcher(); - // if (!ui) { - // return; - // } - - // const attr = vfmtPosUvColor; - // this._bufferAccessor = ui.switchBufferAccessor(vfmtPosUvColor); - // // buffer.initialize(attr, this._arrivalMaxBuffer.bind(this)); - } - - public onDestroy () { - // super.onDestroy(); - - // this._clearData(); - // if (this._bufferAccessor) { - // this._bufferAccessor.destroy(); - // this._bufferAccessor = null; - // } - } - - public updateAssembler (render: IBatcher) { - // render.currIsStatic = true; - // if (this._dirty) { - // render.setupStaticBatch(this, this._bufferAccessor!); - // } - - // if (this._init) { - // render.finishMergeBatches(); - // render.commitStaticBatch(this); - // } - } - public postUpdateAssembler (render: IBatcher) { // if (this._dirty) { // this._dirty = false; @@ -141,7 +103,7 @@ export class UIStaticBatch extends Renderable2D { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _requireDrawBatch () { const batch = new DrawBatch2D(); diff --git a/cocos/2d/framework/canvas.ts b/cocos/2d/framework/canvas.ts index 1863e6d2c8..6bc7018a51 100644 --- a/cocos/2d/framework/canvas.ts +++ b/cocos/2d/framework/canvas.ts @@ -24,17 +24,11 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, disallowMultiple, executeInEditMode, executionOrder, menu, tooltip, type, serializable } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { Camera } from '../../core/components/camera-component'; import { Widget } from '../../ui/widget'; -import { game } from '../../core/game'; import { Vec3 } from '../../core/math'; import { view } from '../../core/platform/view'; import { legacyCC } from '../../core/global-exports'; @@ -82,7 +76,7 @@ export class Canvas extends RenderRoot2D { * intersperse 下可以指定 Canvas 与场景中的相机的渲染顺序,overlay 下 Canvas 会在所有场景相机渲染完成后渲染。 * 注意:场景里的相机(包括 Canvas 内置的相机)必须有一个的 ClearFlag 选择 SOLID_COLOR,否则在移动端可能会出现闪屏。 * - * @deprecated since v3.0, please use [[cameraComponent.priority]] to control overlapping between cameras. + * @deprecated since v3.0, please use [[Camera.priority]] to control overlapping between cameras. */ get renderMode () { return this._renderMode; diff --git a/cocos/2d/framework/deprecated.ts b/cocos/2d/framework/deprecated.ts index bb8b8bc4e8..69223363d9 100644 --- a/cocos/2d/framework/deprecated.ts +++ b/cocos/2d/framework/deprecated.ts @@ -24,15 +24,10 @@ */ /* eslint-disable @typescript-eslint/no-unsafe-return */ -/** - * @packageDocumentation - * @module ui - */ - import { markAsWarning, removeProperty, replaceProperty } from '../../core/utils'; import { UIComponent } from './ui-component'; import { UITransform } from './ui-transform'; -import { Renderable2D } from './renderable-2d'; +import { UIRenderer } from './ui-renderer'; import { Canvas } from './canvas'; import { js } from '../../core/utils/js'; import { legacyCC } from '../../core/global-exports'; @@ -47,7 +42,7 @@ removeProperty(UIComponent.prototype, 'UIComponent', [ }, ]); -removeProperty(Renderable2D.prototype, 'Renderable2D.prototype', [ +removeProperty(UIRenderer.prototype, 'Renderable2D.prototype', [ { name: 'srcBlendFactor', }, @@ -142,13 +137,13 @@ js.setClassAlias(UITransform, 'cc.UITransformComponent'); * Alias of [[Renderable2D]] * @deprecated Since v1.2 */ -export { Renderable2D as RenderComponent }; +export { UIRenderer as RenderComponent }; /** * Alias of [[Renderable2D]] * @deprecated Since v3.0 */ -export { Renderable2D as UIRenderable }; -js.setClassAlias(Renderable2D, 'cc.RenderComponent'); +export { UIRenderer as UIRenderable }; +js.setClassAlias(UIRenderer, 'cc.RenderComponent'); /** * Alias of [[Canvas]] @@ -157,3 +152,11 @@ js.setClassAlias(Renderable2D, 'cc.RenderComponent'); export { Canvas as CanvasComponent }; legacyCC.CanvasComponent = Canvas; js.setClassAlias(Canvas, 'cc.CanvasComponent'); + +/** + * Alias of [[Renderable2D]] + * @deprecated Since v3.6 + */ +export { UIRenderer as Renderable2D }; +legacyCC.internal.Renderable2D = UIRenderer; +js.setClassAlias(UIRenderer, 'cc.Renderable2D'); diff --git a/cocos/2d/framework/index.ts b/cocos/2d/framework/index.ts index a2bde527a1..4a804dbcbe 100644 --- a/cocos/2d/framework/index.ts +++ b/cocos/2d/framework/index.ts @@ -23,11 +23,10 @@ THE SOFTWARE. */ - - export * from './canvas'; export * from './ui-component'; -export * from './renderable-2d'; +export * from './ui-renderer'; export * from './ui-transform'; export * from './deprecated'; export * from './render-root-2d'; +export * from './sprite-renderer'; diff --git a/cocos/2d/framework/render-root-2d.ts b/cocos/2d/framework/render-root-2d.ts index 049fb2abd1..839dcc64dd 100644 --- a/cocos/2d/framework/render-root-2d.ts +++ b/cocos/2d/framework/render-root-2d.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, disallowMultiple, executeInEditMode, executionOrder, menu, requireComponent } from 'cc.decorator'; import { Component } from '../../core/components/component'; diff --git a/cocos/2d/framework/sprite-renderer.ts b/cocos/2d/framework/sprite-renderer.ts new file mode 100644 index 0000000000..a46059f790 --- /dev/null +++ b/cocos/2d/framework/sprite-renderer.ts @@ -0,0 +1,247 @@ +/* + Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + + http://www.cocos2d-x.org + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + 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 { ccclass, executeInEditMode, executionOrder, help, menu, serializable, type, visible } from 'cc.decorator'; +import { EDITOR } from 'internal:constants'; +import { builtinResMgr, Color, Material, ModelRenderer, Vec2 } from '../../core'; +import { legacyCC } from '../../core/global-exports'; +import { ModelLocalBindings } from '../../core/pipeline/define'; +import { Model } from '../../core/renderer/scene'; +import { Root } from '../../core/root'; +import { TransformBit } from '../../core/scene-graph/node-enum'; +import { SpriteFrame } from '../assets/sprite-frame'; + +enum SpriteMode { + SIMPLE = 0, + SLICED = 1, + TILED = 2, +} + +/** + * @en 2D rendering component that provides the ability to render sprite in 3D space. + * @zh 2D 渲染基础组件,提供精灵渲染在 3D 空间中的能力。 + */ +@ccclass('cc.SpriteRenderer') +@help('i18n:cc.SpriteRenderer') +@executionOrder(100) +@menu('2D/SpriteRenderer') +@executeInEditMode +export class SpriteRenderer extends ModelRenderer { + /** + * @en The spriteFrame that the component should render + * @zh 该组件应渲染的 spriteFrame + */ + @type(SpriteFrame) + get spriteFrame () { + return this._spriteFrame; + } + + set spriteFrame (value) { + if (this._spriteFrame === value) { + return; + } + + const lastSprite = this._spriteFrame; + this._spriteFrame = value; + if (this._spriteFrame) { + this._spriteFrame.ensureMeshData(); // Make sure the mesh is available, you should call it before using the mesh + const mesh = this._spriteFrame.mesh!; + mesh.initialize(); + } + this._updateModels(); + if (this.enabledInHierarchy) { + this._attachToScene(); + } + // TODO Update on Editor + } + + /** + * @en Rendering model of the component + * @zh 该组件的渲染模型 + */ + get model () { + return this._model; + } + + @serializable + protected _spriteFrame: SpriteFrame | null = null; + @serializable + protected _mode = SpriteMode.SIMPLE; + @serializable + protected _color: Color = Color.WHITE.clone(); + @serializable + protected _flipX = false; + @serializable + protected _flipY = false; + @visible(false) + @serializable + protected _size: Vec2 = new Vec2(); // todo for sliced & tiled + + private _model: Model | null = null; + + public onLoad () { + if (this._spriteFrame) { + if (!this._spriteFrame.mesh) { + this._spriteFrame.ensureMeshData(); + } + this._spriteFrame.mesh!.initialize(); + } + this._updateModels(); + } + + public onRestore () { + this._updateModels(); + if (this.enabledInHierarchy) { + this._attachToScene(); + } + } + + public onEnable () { + if (!this._model) { + this._updateModels(); + } + this._attachToScene(); + } + + public onDisable () { + if (this._model) { + this._detachFromScene(); + } + } + + public onDestroy () { + if (this._model) { + legacyCC.director.root.destroyModel(this._model); + this._model = null; + this._models.length = 0; + } + } + + protected _updateModels () { + if (!this._spriteFrame) { + return; + } + + const model = this._model; + if (model) { + model.destroy(); + model.initialize(); + model.node = model.transform = this.node; + } else { + this._createModel(); + } + + if (this._model) { + const mesh = this._spriteFrame.mesh!; + this._model.createBoundingShape(mesh.struct.minPosition, mesh.struct.maxPosition); + this._updateModelParams(); + this._onUpdateLocalDescriptorSet(); + } + } + + protected _createModel () { + const model = this._model = (legacyCC.director.root as Root).createModel(Model); + model.visFlags = this.visibility; + model.node = model.transform = this.node; + this._models.length = 0; + this._models.push(this._model); + } + + protected _updateModelParams () { + if (!this._spriteFrame || !this._model) { return; } + this._spriteFrame.ensureMeshData(); + const mesh = this._spriteFrame.mesh!; + this.node.hasChangedFlags |= TransformBit.POSITION; // Same as model, Maybe a hack + this._model.transform.hasChangedFlags |= TransformBit.POSITION; + const meshCount = mesh ? mesh.renderingSubMeshes.length : 0; + const renderingMesh = mesh.renderingSubMeshes; + if (renderingMesh) { + for (let i = 0; i < meshCount; ++i) { + let material = this.getRenderMaterial(i); + if (material && !material.isValid) { + material = null; + } + const subMeshData = renderingMesh[i]; + if (subMeshData) { + this._model.initSubModel(i, subMeshData, material || this._getBuiltinMaterial()); + } + } + } + this._model.enabled = true; + } + + protected _getBuiltinMaterial () { + // classic ugly pink indicating missing material + return builtinResMgr.get('missing-material'); + } + + protected _onMaterialModified (idx: number, material: Material | null) { + super._onMaterialModified(idx, material); + if (!this._spriteFrame || !this._model || !this._model.inited) { + return; + } + this._onRebuildPSO(idx, material || this._getBuiltinMaterial()); + } + + protected _onRebuildPSO (idx: number, material: Material) { + if (!this._model || !this._model.inited) { return; } + this._model.setSubModelMaterial(idx, material); + this._onUpdateLocalDescriptorSet(); + } + + protected _onUpdateLocalDescriptorSet () { + if (!this._spriteFrame || !this._model || !this._model.inited) { + return; + } + + const texture = this._spriteFrame.getGFXTexture()!; + const sampler = this._spriteFrame.getGFXSampler(); + // We need a api like updateLocalDescriptors(texture,sampler,binding) from model + const subModels = this._model.subModels; + const binding = ModelLocalBindings.SAMPLER_SPRITE; + for (let i = 0; i < subModels.length; i++) { + const { descriptorSet } = subModels[i]; + descriptorSet.bindTexture(binding, texture); + descriptorSet.bindSampler(binding, sampler); + descriptorSet.update(); + } + } + + protected _attachToScene () { + if (!this.node.scene || !this._model) { + return; + } + const renderScene = this._getRenderScene(); + if (this._model.scene !== null) { + this._detachFromScene(); + } + renderScene.addModel(this._model); + } + + protected _detachFromScene () { + if (this._model && this._model.scene) { + this._model.scene.removeModel(this._model); + } + } +} diff --git a/cocos/2d/framework/ui-component.ts b/cocos/2d/framework/ui-component.ts index f726b57709..ebfb335255 100644 --- a/cocos/2d/framework/ui-component.ts +++ b/cocos/2d/framework/ui-component.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, disallowMultiple, executeInEditMode, executionOrder, requireComponent } from 'cc.decorator'; import { IBatcher } from '../renderer/i-batcher'; import { Component } from '../../core/components/component'; @@ -37,9 +32,9 @@ import { Stage } from '../renderer/stencil-manager'; /** * @en Legacy 2D base class for rendering component, please use [[Renderable2D]] instead. - * This component will setup [[NodeUIProperties.uiComp]] in its owner [[Node]] + * This component will setup NodeUIProperties.uiComp in its owner [[Node]] * @zh 旧的 2D 渲染组件基类,请使用 [[Renderable2D]] 替代。 - * 这个组件会设置 [[Node]] 上的 [[NodeUIProperties.uiComp]]。 + * 这个组件会设置 [[Node]] 上的 NodeUIProperties.uiComp。 * @deprecated since v3.4.1 */ @ccclass('cc.UIComponent') @@ -70,17 +65,6 @@ export class UIComponent extends Component { } } - /** - * @en Render data submission procedure, it update and assemble the render data to 2D data buffers before all children submission process. - * Usually called each frame when the ui flow assemble all render data to geometry buffers. - * Don't call it unless you know what you are doing. - * @zh 渲染数据组装程序,这个方法会在所有子节点数据组装之前更新并组装当前组件的渲染数据到 UI 的顶点数据缓冲区中。 - * 一般在 UI 渲染流程中调用,用于组装所有的渲染数据到顶点数据缓冲区。 - * 注意:不要手动调用该函数,除非你理解整个流程。 - */ - public updateAssembler (render: IBatcher) { - } - /** * @en Post render data submission procedure, it's executed after assembler updated for all children. * It may assemble some extra render data to the geometry buffers, or it may only change some render states. diff --git a/cocos/2d/framework/ui-renderer-manager.ts b/cocos/2d/framework/ui-renderer-manager.ts new file mode 100644 index 0000000000..3d598477d8 --- /dev/null +++ b/cocos/2d/framework/ui-renderer-manager.ts @@ -0,0 +1,55 @@ +import { DEBUG } from 'internal:constants'; +import { assert } from '../../core/platform/debug'; +import { js } from '../../core/utils/js'; +import { UIMeshRenderer } from '../components'; +import { UIRenderer } from './ui-renderer'; + +export class UIRendererManager { + private _allRenderers: (UIRenderer | UIMeshRenderer)[] = []; + private _dirtyRenderers: (UIRenderer | UIMeshRenderer)[] = []; + private _dirtyVersion = 0; + public addRenderer (uiRenderer: UIRenderer | UIMeshRenderer) { + if (uiRenderer._internalId === -1) { + uiRenderer._internalId = this._allRenderers.length; + this._allRenderers.push(uiRenderer); + } + } + + public removeRenderer (uiRenderer: UIRenderer | UIMeshRenderer) { + if (uiRenderer._internalId !== -1) { + if (DEBUG) { + assert(this._allRenderers[uiRenderer._internalId] === uiRenderer); + } + const id = uiRenderer._internalId; + this._allRenderers[this._allRenderers.length - 1]._internalId = id; + js.array.fastRemoveAt(this._allRenderers, id); + uiRenderer._internalId = -1; + if (uiRenderer._dirtyVersion === this._dirtyVersion) { + js.array.fastRemove(this._dirtyRenderers, uiRenderer); + uiRenderer._dirtyVersion = -1; + } + } + } + + public markDirtyRenderer (uiRenderer: UIRenderer | UIMeshRenderer) { + if (uiRenderer._dirtyVersion !== this._dirtyVersion && uiRenderer._internalId !== -1) { + this._dirtyRenderers.push(uiRenderer); + uiRenderer._dirtyVersion = this._dirtyVersion; + } + } + + public updateAllDirtyRenderers () { + const length = this._dirtyRenderers.length; + const dirtyRenderers = this._dirtyRenderers; + for (let i = 0; i < length; i++) { + if (DEBUG) { + assert(dirtyRenderers[i]._internalId !== -1); + } + dirtyRenderers[i].updateRenderer(); + } + this._dirtyRenderers.length = 0; + this._dirtyVersion++; + } +} + +export const uiRendererManager = new UIRendererManager(); diff --git a/cocos/2d/framework/renderable-2d.ts b/cocos/2d/framework/ui-renderer.ts similarity index 73% rename from cocos/2d/framework/renderable-2d.ts rename to cocos/2d/framework/ui-renderer.ts index 88397783c8..059c48c5a0 100644 --- a/cocos/2d/framework/renderable-2d.ts +++ b/cocos/2d/framework/ui-renderer.ts @@ -23,13 +23,11 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ -import { EDITOR } from 'internal:constants'; -import { ccclass, executeInEditMode, requireComponent, disallowMultiple, tooltip, - type, displayOrder, serializable, override, visible, displayName } from 'cc.decorator'; +import { EDITOR, JSB } from 'internal:constants'; +import { + ccclass, executeInEditMode, requireComponent, disallowMultiple, tooltip, + type, displayOrder, serializable, override, visible, displayName, disallowAnimation, +} from 'cc.decorator'; import { Color } from '../../core/math'; import { ccenum } from '../../core/value-types/enum'; import { builtinResMgr } from '../../core/builtin'; @@ -41,11 +39,13 @@ import { IBatcher } from '../renderer/i-batcher'; import { Node } from '../../core/scene-graph'; import { TransformBit } from '../../core/scene-graph/node-enum'; import { UITransform } from './ui-transform'; -import { RenderableComponent } from '../../core/components/renderable-component'; import { Stage } from '../renderer/stencil-manager'; -import { warnID } from '../../core/platform/debug'; import { legacyCC } from '../../core/global-exports'; import { NodeEventType } from '../../core/scene-graph/node-event'; +import { Renderer } from '../../core/components/renderer'; +import { RenderEntity, RenderEntityType } from '../renderer/render-entity'; +import { uiRendererManager } from './ui-renderer-manager'; +import { assert, director } from '../../core'; // hack ccenum(BlendFactor); @@ -105,21 +105,21 @@ export enum InstanceMaterialType { } /** - * @en Base class for 2D components which supports rendering features. - * This component will setup [[NodeUIProperties.uiComp]] in its owner [[Node]] + * @en Base class for UI components which supports rendering features. + * This component will setup NodeUIProperties.uiComp in its owner [[Node]] * - * @zh 所有支持渲染的 2D 组件的基类。 - * 这个组件会设置 [[Node]] 上的 [[NodeUIProperties.uiComp]]。 + * @zh 所有支持渲染的 UI 组件的基类。 + * 这个组件会设置 [[Node]] 上的 NodeUIProperties.uiComp。 */ -@ccclass('cc.Renderable2D') +@ccclass('cc.UIRenderer') @requireComponent(UITransform) @disallowMultiple @executeInEditMode -export class Renderable2D extends RenderableComponent { +export class UIRenderer extends Renderer { /** * @en The blend factor enums * @zh 混合模式枚举类型 - * @see [[BlendFactor]] + * @see [[gfx.BlendFactor]] */ public static BlendState = BlendFactor; /** @@ -133,8 +133,10 @@ export class Renderable2D extends RenderableComponent { */ public static PostAssembler: IAssemblerManager | null = null; - @override - protected _materials: (Material | null)[] = []; + constructor () { + super(); + this._renderEntity = this.createRenderEntity(); + } @override @visible(false) @@ -157,9 +159,6 @@ export class Renderable2D extends RenderableComponent { } } - @type(Material) - protected _customMaterial: Material| null = null; - /** * @en The customMaterial * @zh 用户自定材质 @@ -168,6 +167,7 @@ export class Renderable2D extends RenderableComponent { @displayOrder(0) @tooltip('i18n:renderable2D.customMaterial') @displayName('CustomMaterial') + @disallowAnimation get customMaterial () { return this._customMaterial; } @@ -198,11 +198,32 @@ export class Renderable2D extends RenderableComponent { } } + protected _renderData: RenderData | null = null; + /** + * @internal + */ get renderData () { return this._renderData; } + /** + * @internal + */ + get blendHash () { + return this._blendHash; + } + + /** + * @internal + */ + get useVertexOpacity () { + return this._useVertexOpacity; + } + // Render data can be submitted even if it is not on the node tree + /** + * @internal + */ set delegateSrc (value: Node) { this._delegateSrc = value; } @@ -211,7 +232,18 @@ export class Renderable2D extends RenderableComponent { * @en The component stencil stage (please do not any modification directly on this object) * @zh 组件模板缓冲状态 (注意:请不要直接修改它的值) */ - public stencilStage : Stage = Stage.DISABLED; + get stencilStage (): Stage { + return this._stencilStage; + } + set stencilStage (val: Stage) { + this._stencilStage = val; + this._renderEntity.setStencilStage(val); + } + + @override + protected _materials: (Material | null)[] = []; + @type(Material) + protected _customMaterial: Material | null = null; @serializable protected _srcBlendFactor = BlendFactor.SRC_ALPHA; @@ -220,23 +252,41 @@ export class Renderable2D extends RenderableComponent { @serializable protected _color: Color = Color.WHITE.clone(); + protected _stencilStage: Stage = Stage.DISABLED; + protected _assembler: IAssembler | null = null; protected _postAssembler: IAssembler | null = null; - protected _renderData: RenderData | null = null; + + // RenderEntity + //protected renderData: RenderData | null = null; protected _renderDataFlag = true; protected _renderFlag = true; + protected _renderEntity: RenderEntity; + // 特殊渲染节点,给一些不在节点树上的组件做依赖渲染(例如 mask 组件内置两个 graphics 来渲染) + // Special delegate node for the renderer component, it allows standalone component to be rendered as if it's attached to the delegate node + // It's used by graphics stencil component in Mask protected _delegateSrc: Node | null = null; protected _instanceMaterialType = -1; protected _blendState: BlendState = new BlendState(); protected _blendHash = 0; - /** - * TODO mark internal + * @internal */ - get blendHash () { - return this._blendHash; + public _dirtyVersion = -1; + /** + * @internal + */ + public _internalId = -1; + + get batcher () { + return director.root!.batcher2D; + } + + get renderEntity () { + assert(this._renderEntity); + return this._renderEntity; } /** @@ -244,17 +294,13 @@ export class Renderable2D extends RenderableComponent { * @zh 标记组件是否逐顶点计算透明度 */ protected _useVertexOpacity = false; - get useVertexOpacity () { - return this._useVertexOpacity; - } - - public updateBlendHash () { - const dst = this._blendState.targets[0].blendDst << 4; - this._blendHash = dst | this._blendState.targets[0].blendSrc; - } protected _lastParent: Node | null = null; + public onLoad () { + this._renderEntity.setNode(this.node); + } + public __preload () { this.node._uiProps.uiComp = this; if (this._flushAssembler) { @@ -267,7 +313,9 @@ export class Renderable2D extends RenderableComponent { this.node.on(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this); this.node.on(NodeEventType.PARENT_CHANGED, this._colorDirty, this); this.updateMaterial(); - this._renderFlag = this._canRender(); + this._colorDirty(); + uiRendererManager.addRenderer(this); + this.markForUpdateRenderData(); } // For Redo, Undo @@ -281,10 +329,13 @@ export class Renderable2D extends RenderableComponent { this.node.off(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this); this.node.off(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this); this.node.off(NodeEventType.PARENT_CHANGED, this._colorDirty, this); + uiRendererManager.removeRenderer(this); this._renderFlag = false; + this._renderEntity.enabled = false; } public onDestroy () { + this._renderEntity.setNode(null); if (this.node._uiProps.uiComp === this) { this.node._uiProps.uiComp = null; } @@ -300,22 +351,27 @@ export class Renderable2D extends RenderableComponent { } } + /** + * @en Update the hash for the blend states. + * @zh 更新混合模式的哈希值标记 + */ + public updateBlendHash () { + const dst = this._blendState.targets[0].blendDst << 4; + this._blendHash = dst | this._blendState.targets[0].blendSrc; + } + /** * @en Marks the render data of the current component as modified so that the render data is recalculated. * @zh 标记当前组件的渲染数据为已修改状态,这样渲染数据才会重新计算。 * @param enable Marked necessary to update or not */ public markForUpdateRenderData (enable = true) { - this._renderFlag = this._canRender(); if (enable) { - const renderData = this._renderData; + const renderData = this.renderData; if (renderData) { renderData.vertDirty = true; } - - this._renderDataFlag = enable; - } else { - this._renderDataFlag = enable; + uiRendererManager.markDirtyRenderer(this); } } @@ -326,6 +382,7 @@ export class Renderable2D extends RenderableComponent { */ public requestRenderData () { const data = RenderData.add(); + data.initRenderDrawInfo(this); this._renderData = data; return data; } @@ -335,26 +392,24 @@ export class Renderable2D extends RenderableComponent { * @zh 销毁当前渲染数据。 */ public destroyRenderData () { - if (!this._renderData) { + if (!this.renderData) { return; } - RenderData.remove(this._renderData); + RenderData.remove(this.renderData); this._renderData = null; } - /** - * @en Render data submission procedure, it update and assemble the render data to 2D data buffers before all children submission process. - * Usually called each frame when the ui flow assemble all render data to geometry buffers. - * Don't call it unless you know what you are doing. - * @zh 渲染数据组装程序,这个方法会在所有子节点数据组装之前更新并组装当前组件的渲染数据到 UI 的顶点数据缓冲区中。 - * 一般在 UI 渲染流程中调用,用于组装所有的渲染数据到顶点数据缓冲区。 - * 注意:不要手动调用该函数,除非你理解整个流程。 - */ - public updateAssembler (render: IBatcher) { - if (this._renderDataFlag) { - this._assembler!.updateRenderData(this, render); - this._renderDataFlag = false; + // test code: to replace prev part updateAssembler + public updateRenderer () { + if (this._assembler) { + this._assembler.updateRenderData(this); } + this._renderFlag = this._canRender(); + this._renderEntity.enabled = this._renderFlag; + } + + // test code: to replace after part updateAssembler + public fillBuffers (render: IBatcher) { if (this._renderFlag) { this._render(render); } @@ -374,42 +429,37 @@ export class Renderable2D extends RenderableComponent { } } - protected _render (render: IBatcher) {} + protected _render (render: IBatcher) { } - protected _postRender (render: IBatcher) {} + protected _postRender (render: IBatcher) { } protected _canRender () { return this.isValid - && this.getMaterial(0) !== null - && this.enabled - && (this._delegateSrc ? this._delegateSrc.activeInHierarchy : this.enabledInHierarchy) - && this._color.a > 0; + && this.getMaterial(0) !== null + && this.enabled + && (this._delegateSrc ? this._delegateSrc.activeInHierarchy : this.enabledInHierarchy) + && this._color.a > 0; } - protected _postCanRender () {} + protected _postCanRender () { } protected updateMaterial () { if (this._customMaterial) { this.setMaterial(this._customMaterial, 0); - if (this._renderData) { - this._renderData.material = this._customMaterial; - this.markForUpdateRenderData(); - this._renderData.passDirty = true; - } this._blendHash = -1; // a flag to check merge return; } const mat = this._updateBuiltinMaterial(); this.setMaterial(mat, 0); - if (this._renderData) { - this._renderData.material = mat; - this.markForUpdateRenderData(); - } this._updateBlendFunc(); } protected _updateColor () { this.node._uiProps.colorDirty = true; + this.setEntityColorDirty(true); + this.setEntityColor(this._color); + this.setEntityOpacity(this.node._uiProps.localOpacity); + if (this._assembler) { this._assembler.updateColor(this); // Need update rendFlag when opacity changes from 0 to !0 or 0 to !0 @@ -417,8 +467,38 @@ export class Renderable2D extends RenderableComponent { } } + // for common + public static setEntityColorDirtyRecursively (node: Node, dirty: boolean) { + const render = node._uiProps.uiComp as UIRenderer; + if (render) { + render._renderEntity.colorDirty = dirty; + render._renderEntity.color = render.color;// necessity to be considering + } + for (let i = 0; i < node.children.length; i++) { + UIRenderer.setEntityColorDirtyRecursively(node.children[i], dirty); + } + } + + private setEntityColorDirty (dirty: boolean) { + if (JSB) { + UIRenderer.setEntityColorDirtyRecursively(this.node, dirty); + } + } + + public setEntityColor (color: Color) { + if (JSB) { + this._renderEntity.color = color; + } + } + + public setEntityOpacity (opacity: number) { + if (JSB) { + this._renderEntity.localOpacity = opacity; + } + } + /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _updateBlendFunc () { // todo: Not only Pass[0].target[0] @@ -445,13 +525,13 @@ export class Renderable2D extends RenderableComponent { // pos, rot, scale changed protected _nodeStateChange (transformType: TransformBit) { - if (this._renderData) { + if (this.renderData) { this.markForUpdateRenderData(); } for (let i = 0; i < this.node.children.length; ++i) { const child = this.node.children[i]; - const renderComp = child.getComponent(Renderable2D); + const renderComp = child.getComponent(UIRenderer); if (renderComp) { renderComp.markForUpdateRenderData(); } @@ -460,18 +540,19 @@ export class Renderable2D extends RenderableComponent { protected _colorDirty () { this.node._uiProps.colorDirty = true; + this.setEntityColorDirty(true); } protected _onMaterialModified (idx: number, material: Material | null) { - if (this._renderData) { + if (this.renderData) { this.markForUpdateRenderData(); - this._renderData.passDirty = true; + this.renderData.passDirty = true; } super._onMaterialModified(idx, material); } - protected _updateBuiltinMaterial () : Material { - let mat : Material; + protected _updateBuiltinMaterial (): Material { + let mat: Material; switch (this._instanceMaterialType) { case InstanceMaterialType.ADD_COLOR: mat = builtinResMgr.get(`ui-base-material`); @@ -492,7 +573,7 @@ export class Renderable2D extends RenderableComponent { return mat; } - protected _flushAssembler? (): void; + protected _flushAssembler?(): void; public setNodeDirty () { if (this.renderData) { @@ -505,6 +586,12 @@ export class Renderable2D extends RenderableComponent { this.renderData.textureDirty = true; } } + + // RenderEntity + // it should be overwritten by inherited classes + protected createRenderEntity () { + return new RenderEntity(RenderEntityType.STATIC); + } } -legacyCC.internal.Renderable2D = Renderable2D; +legacyCC.internal.UIRenderer = UIRenderer; diff --git a/cocos/2d/framework/ui-transform.ts b/cocos/2d/framework/ui-transform.ts index 9d4eb8409f..4be2516f72 100644 --- a/cocos/2d/framework/ui-transform.ts +++ b/cocos/2d/framework/ui-transform.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, executeInEditMode, executionOrder, menu, tooltip, displayOrder, serializable, disallowMultiple } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { Component } from '../../core/components'; @@ -367,8 +362,10 @@ export class UITransform extends Component { * 默认的锚点是(0.5,0.5),因此它开始于节点的中心位置。
* 注意:Creator 中的锚点仅用于定位所在的节点,子节点的定位不受影响。 * - * @param point - 节点锚点或节点 x 轴锚。 - * @param y - 节点 y 轴锚。 + * @param point @en Node anchor point or node x-axis anchor. + * @zh 节点锚点或节点 x 轴锚。 + * @param y @en The y-axis anchor of the node. + * @zh 节点 y 轴锚。 * @example * ```ts * import { Vec2 } from 'cc'; @@ -401,7 +398,8 @@ export class UITransform extends Component { } /** - * Hit test with point in UI Space. + * @zh UI 空间中的点击测试。 + * @en Hit test with point in UI Space. * * @param uiPoint point in UI Space. * @deprecated since v3.5.0, please use `uiTransform.hitTest(screenPoint: Vec2)` instead. @@ -447,13 +445,13 @@ export class UITransform extends Component { return false; } - /** - * Hit test with point in Screen Space. + * @zh 屏幕空间中的点击测试。 + * @en Hit test with point in Screen Space. * * @param screenPoint point in Screen Space. */ - public hitTest (screenPoint: Vec2) { + public hitTest (screenPoint: Vec2) { const w = this._contentSize.width; const h = this._contentSize.height; const v3WorldPt = _vec3a; @@ -463,7 +461,7 @@ export class UITransform extends Component { const cameras = this._getRenderScene().cameras; for (let i = 0; i < cameras.length; i++) { const camera = cameras[i]; - if (!(camera.visibility & this.node.layer)) continue; + if (!(camera.visibility & this.node.layer) || (camera.window && !camera.window.swapchain)) continue; // Convert Screen Space into World Space. Vec3.set(v3WorldPt, screenPoint.x, screenPoint.y, 0); // vec3 screen pos @@ -529,9 +527,12 @@ export class UITransform extends Component { * 将一个 UI 节点世界坐标系下点转换到另一个 UI 节点 (局部) 空间坐标系,这个坐标系以锚点为原点。 * 非 UI 节点转换到 UI 节点(局部) 空间坐标系,请走 Camera 的 `convertToUINode`。 * - * @param worldPoint - 世界坐标点。 - * @param out - 转换后坐标。 - * @returns - 返回与目标节点的相对位置。 + * @param worldPoint @en Point in world space. + * @zh 世界坐标点。 + * @param out @en Point in local space. + * @zh 转换后坐标。 + * @returns @en Return the relative position to the target node. + * @zh 返回与目标节点的相对位置。 * @example * ```ts * const newVec3 = uiTransform.convertToNodeSpaceAR(cc.v3(100, 100, 0)); @@ -554,9 +555,12 @@ export class UITransform extends Component { * @zh * 将距当前节点坐标系下的一个点转换到世界坐标系。 * - * @param nodePoint - 节点坐标。 - * @param out - 转换后坐标。 - * @returns - 返回 UI 世界坐标系。 + * @param nodePoint @en Point in local space. + * @zh 节点坐标。 + * @param out @en Point in world space. + * @zh 转换后坐标。 + * @returns @en Returns the coordinates in the UI world coordinate system. + * @zh 返回 UI 世界坐标系。 * @example * ```ts * const newVec3 = uiTransform.convertToWorldSpaceAR(3(100, 100, 0)); @@ -629,7 +633,8 @@ export class UITransform extends Component { * @zh * 返回包含当前包围盒及其子节点包围盒的最小包围盒。 * - * @param parentMat - 父节点矩阵。 + * @param parentMat @en The parent node matrix. + * @zh 父节点矩阵。 * @returns */ public getBoundingBoxTo (parentMat: Mat4) { @@ -712,8 +717,6 @@ export class UITransform extends Component { const uiComp = this.node._uiProps.uiComp; if (uiComp) { uiComp.markForUpdateRenderData(); - // @ts-expect-error hack for canRender is false // HACK,Need remove - if (uiComp.renderData) { uiComp.renderData.vertDirty = true; } } } diff --git a/cocos/2d/renderer/base.ts b/cocos/2d/renderer/base.ts index e1b91661c6..b7d6797649 100644 --- a/cocos/2d/renderer/base.ts +++ b/cocos/2d/renderer/base.ts @@ -28,12 +28,12 @@ * @module ui */ -import { Renderable2D } from '../framework/renderable-2d'; +import { UIRenderer } from '../framework/ui-renderer'; export interface IAssembler { [key: string]: any; } export interface IAssemblerManager { - getAssembler (component: Renderable2D): IAssembler; + getAssembler (component: UIRenderer): IAssembler; } diff --git a/cocos/2d/renderer/batcher-2d.ts b/cocos/2d/renderer/batcher-2d.ts index 0f08056ca9..aff394be8d 100644 --- a/cocos/2d/renderer/batcher-2d.ts +++ b/cocos/2d/renderer/batcher-2d.ts @@ -27,9 +27,9 @@ import { JSB } from 'internal:constants'; import { Camera, Model } from 'cocos/core/renderer/scene'; import type { UIStaticBatch } from '../components/ui-static-batch'; import { Material } from '../../core/assets/material'; -import { RenderRoot2D, Renderable2D } from '../framework'; +import { RenderRoot2D, UIRenderer } from '../framework'; import { Texture, Device, Attribute, Sampler, DescriptorSetInfo, Buffer, - BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet, InputAssembler } from '../../core/gfx'; + BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet, InputAssembler, deviceManager } from '../../core/gfx'; import { Pool } from '../../core/memop'; import { CachedArray } from '../../core/memop/cached-array'; import { Root } from '../../core/root'; @@ -40,14 +40,19 @@ import { legacyCC } from '../../core/global-exports'; import { ModelLocalBindings, UBOLocal } from '../../core/pipeline/define'; import { SpriteFrame } from '../assets'; import { TextureBase } from '../../core/assets/texture-base'; -import { Mat4 } from '../../core/math'; +import { Mat4, Vec3 } from '../../core/math'; import { IBatcher } from './i-batcher'; -import { StaticVBAccessor } from './static-vb-accessor'; +import { StaticVBAccessor, StaticVBChunk } from './static-vb-accessor'; import { assertIsTrue } from '../../core/data/utils/asserts'; import { getAttributeStride, vfmtPosUvColor } from './vertex-format'; import { updateOpacity } from '../assembler/utils'; -import { BaseRenderData, MeshRenderData } from './render-data'; +import { BaseRenderData, MeshRenderData, RenderData } from './render-data'; import { UIMeshRenderer } from '../components/ui-mesh-renderer'; +import { RenderDrawInfo } from './render-draw-info'; +import { NativeBatcher2d, NativeRenderDrawInfo, NativeUIMeshBuffer } from './native-2d'; +import { mapBuffer, readBuffer } from '../../3d/misc'; +import { MeshBuffer } from './mesh-buffer'; +import { propertyDefine } from '../../core/utils/misc'; const _dsInfo = new DescriptorSetInfo(null!); const m4_1 = new Mat4(); @@ -57,6 +62,11 @@ const m4_1 = new Mat4(); * UI 渲染流程 */ export class Batcher2D implements IBatcher { + protected declare _nativeObj: NativeBatcher2d; + public get nativeObj (): NativeBatcher2d { + return this._nativeObj; + } + get currBufferAccessor () { if (this._staticVBBuffer) return this._staticVBBuffer; // create if not set @@ -92,7 +102,7 @@ export class Batcher2D implements IBatcher { private _currTexture: Texture | null = null; private _currSampler: Sampler | null = null; private _currStaticRoot: UIStaticBatch | null = null; - private _currComponent: Renderable2D | null = null; + private _currComponent: UIRenderer | null = null; private _currTransform: Node | null = null; private _currTextureHash = 0; private _currSamplerHash = 0; @@ -141,6 +151,16 @@ export class Batcher2D implements IBatcher { StencilManager.sharedManager!.destroy(); } + private syncRootNodesToNative() { + if (JSB) { + const rootNodes: Node[] = []; + for (const screen of this._screens) { + rootNodes.push(screen.node); + } + this._nativeObj.syncRootNodesToNative(rootNodes); + } + } + /** * @en * Add the managed Canvas. @@ -148,30 +168,40 @@ export class Batcher2D implements IBatcher { * @zh * 添加屏幕组件管理。 * - * @param comp - 屏幕组件。 + * @param comp @en The render root of 2d. + * @zh 2d 渲染入口组件。 */ public addScreen (comp: RenderRoot2D) { this._screens.push(comp); this._screens.sort(this._screenSort); + if (JSB) { + this.syncRootNodesToNative(); + } } /** * @zh * Removes the Canvas from the list. * - * @param comp - 被移除的屏幕。 + * @param comp @en The target to removed. + * @zh 被移除的屏幕。 */ public removeScreen (comp: RenderRoot2D) { const idx = this._screens.indexOf(comp); if (idx === -1) { return; } - this._screens.splice(idx, 1); + if (JSB) { + this.syncRootNodesToNative(); + } } public sortScreens () { this._screens.sort(this._screenSort); + if (JSB) { + this.syncRootNodesToNative(); + } } public getFirstRenderCamera (node: Node): Camera | null { @@ -188,6 +218,9 @@ export class Batcher2D implements IBatcher { } public update () { + if (JSB) { + return; + } const screens = this._screens; let offset = 0; for (let i = 0; i < screens.length; ++i) { @@ -199,7 +232,9 @@ export class Batcher2D implements IBatcher { // Reset state and walk this._opacityDirty = 0; this._pOpacity = 1; + this.walk(screen.node); + this.autoMergeBatches(this._currComponent!); this.resetRenderStates(); @@ -223,7 +258,9 @@ export class Batcher2D implements IBatcher { } public uploadBuffers () { - if (this._batches.length > 0) { + if (JSB) { + this._nativeObj.uploadBuffers(); + } else if (this._batches.length > 0) { this._meshDataArray.forEach((rd) => { rd.uploadBuffers(); }); @@ -238,43 +275,47 @@ export class Batcher2D implements IBatcher { } public reset () { - // Reset batches - for (let i = 0; i < this._batches.length; ++i) { - const batch = this._batches.array[i]; - if (batch.isStatic) { - continue; + if (JSB) { + this._nativeObj.reset(); + } else { + for (let i = 0; i < this._batches.length; ++i) { + const batch = this._batches.array[i]; + if (batch.isStatic) { + continue; + } + + batch.clear(); + this._drawBatchPool.free(batch); } + // Reset buffer accessors + this._bufferAccessors.forEach((accessor: StaticVBAccessor) => { + accessor.reset(); + }); + this._meshDataArray.forEach((rd) => { + rd.freeIAPool(); + }); + this._meshDataArray.length = 0; + this._staticVBBuffer = null; - batch.clear(); - this._drawBatchPool.free(batch); + this._currBID = -1; + this._indexStart = 0; + this._currHash = 0; + this._currLayer = 0; + this._currRenderData = null; + this._currMaterial = this._emptyMaterial; + this._currTexture = null; + this._currSampler = null; + this._currComponent = null; + this._currTransform = null; + this._batches.clear(); + StencilManager.sharedManager!.reset(); } - // Reset buffer accessors - this._bufferAccessors.forEach((accessor: StaticVBAccessor) => { - accessor.reset(); - }); - this._meshDataArray.forEach((rd) => { - rd.freeIAPool(); - }); - this._meshDataArray.length = 0; - this._staticVBBuffer = null; - - this._currBID = -1; - this._indexStart = 0; - this._currHash = 0; - this._currLayer = 0; - this._currRenderData = null; - this._currMaterial = this._emptyMaterial; - this._currTexture = null; - this._currSampler = null; - this._currComponent = null; - this._currTransform = null; - this._batches.clear(); - StencilManager.sharedManager!.reset(); } /** - * Switch the mesh buffer for corresponding vertex layout if necessary. - * @param attributes use [[VertexFormat.vfmtPosUvColor]] by default + * @zh 如果有必要,为相应的顶点布局切换网格缓冲区。 + * @en Switch the mesh buffer for corresponding vertex layout if necessary. + * @param attributes use VertexFormat.vfmtPosUvColor by default */ public switchBufferAccessor (attributes: Attribute[] = vfmtPosUvColor) { const strideBytes = attributes === vfmtPosUvColor ? 36 /* 9x4 */ : getAttributeStride(attributes); @@ -321,7 +362,7 @@ export class Batcher2D implements IBatcher { * @param assembler - The assembler for the current component, could be null * @param transform - Node type transform, if passed, then batcher will consider it's using model matrix, could be null */ - public commitComp (comp: Renderable2D, renderData: BaseRenderData|null, frame: TextureBase|SpriteFrame|null, assembler, transform: Node|null) { + public commitComp (comp: UIRenderer, renderData: BaseRenderData|null, frame: TextureBase|SpriteFrame|null, assembler, transform: Node|null) { let dataHash = 0; let mat; let bufferID = -1; @@ -338,7 +379,7 @@ export class Batcher2D implements IBatcher { || this._currDepthStencilStateStage !== depthStencilStateStage) { // Merge all previous data to a render batch, and update buffer for next render data this.autoMergeBatches(this._currComponent!); - if (renderData && !renderData.isMeshBuffer) { + if (renderData && !renderData._isMeshBuffer) { this.updateBuffer(renderData.vertexFormat, bufferID); } @@ -368,17 +409,17 @@ export class Batcher2D implements IBatcher { /** * @en - * Render component data submission process for individual [[InputAssembler]] + * Render component data submission process for individual [[gfx.InputAssembler]] * @zh - * 渲染组件中针对独立 [[InputAssembler]] 的提交流程 + * 渲染组件中针对独立 [[gfx.InputAssembler]] 的提交流程 * 例如:Spine 和 DragonBones 等包含动态数据和材质的组件在内部管理 IA 并提交批次 * @param comp - The committed renderable component - * @param ia - The committed [[InputAssembler]] + * @param ia - The committed [[gfx.InputAssembler]] * @param tex - The texture used * @param mat - The material used * @param [transform] - The related node transform if the render data is based on node's local coordinates */ - public commitIA (renderComp: Renderable2D, ia: InputAssembler, tex?: TextureBase, mat?: Material, transform?: Node) { + public commitIA (renderComp: UIRenderer, ia: InputAssembler, tex?: TextureBase, mat?: Material, transform?: Node) { // if the last comp is spriteComp, previous comps should be batched. if (this._currMaterial !== this._emptyMaterial) { this.autoMergeBatches(this._currComponent!); @@ -427,7 +468,7 @@ export class Batcher2D implements IBatcher { * @param model - The committed model * @param mat - The material used, could be null */ - public commitModel (comp: UIMeshRenderer | Renderable2D, model: Model | null, mat: Material | null) { + public commitModel (comp: UIMeshRenderer | UIRenderer, model: Model | null, mat: Material | null) { // if the last comp is spriteComp, previous comps should be batched. if (this._currMaterial !== this._emptyMaterial) { this.autoMergeBatches(this._currComponent!); @@ -489,7 +530,8 @@ export class Batcher2D implements IBatcher { * * @zh * 提交独立渲染数据. - * @param comp 静态组件 + * @param comp @en The UIStaticBatch component. + * @zh 静态组件 */ public commitStaticBatch (comp: UIStaticBatch) { this._batches.concat(comp.drawBatchList); @@ -503,7 +545,7 @@ export class Batcher2D implements IBatcher { * @zh * 根据合批条件,结束一段渲染数据并提交。 */ - public autoMergeBatches (renderComp?: Renderable2D) { + public autoMergeBatches (renderComp?: UIRenderer) { const mat = this._currMaterial; if (!mat) { return; @@ -512,7 +554,7 @@ export class Batcher2D implements IBatcher { const rd = this._currRenderData as MeshRenderData; const accessor = this._staticVBBuffer; // Previous batch using mesh buffer - if (rd && rd.isMeshBuffer) { + if (rd && rd._isMeshBuffer) { ia = rd.requestIA(this.device); if (this._meshDataArray.indexOf(rd) === -1) { this._meshDataArray.push(rd); @@ -577,10 +619,12 @@ export class Batcher2D implements IBatcher { * @zh * 强行修改当前批次数据并合并。 * - * @param material - 当前批次的材质。 - * @param sprite - 当前批次的精灵帧。 + * @param material @en The material of the current batch. + * @zh 当前批次的材质。 + * @param sprite @en Sprite frame of current batch. + * @zh 当前批次的精灵帧。 */ - public forceMergeBatches (material: Material, frame: TextureBase | SpriteFrame | null, renderComp: Renderable2D) { + public forceMergeBatches (material: Material, frame: TextureBase | SpriteFrame | null, renderComp: UIRenderer) { this._currMaterial = material; if (frame) { @@ -637,7 +681,7 @@ export class Batcher2D implements IBatcher { } const children = node.children; const uiProps = node._uiProps; - const render = uiProps.uiComp as Renderable2D; + const render = uiProps.uiComp as UIRenderer; // Save opacity const parentOpacity = this._pOpacity; @@ -655,7 +699,7 @@ export class Batcher2D implements IBatcher { // Render assembler update logic if (render && render.enabledInHierarchy) { - render.updateAssembler(this); + render.fillBuffers(this);// for rendering } // Update cascaded opacity to vertex buffer @@ -697,8 +741,23 @@ export class Batcher2D implements IBatcher { } // TODO: Not a good way to do the job - private _releaseDescriptorSetCache (textureHash: number) { - this._descriptorSetCache.releaseDescriptorSetCache(textureHash); + private _releaseDescriptorSetCache (textureHash, sampler = null!) { + if (JSB) { + this._nativeObj.releaseDescriptorSetCache(textureHash, sampler); + } else { + this._descriptorSetCache.releaseDescriptorSetCache(textureHash); + } + } + + //sync mesh buffer to naive + public syncMeshBuffersToNative (accId: number, buffers: MeshBuffer[]) { + if (JSB) { + const nativeBuffers:NativeUIMeshBuffer[] = []; + buffers.forEach((x) => { + nativeBuffers.push(x.nativeObj); + }); + this._nativeObj.syncMeshBuffersToNative(accId, nativeBuffers); + } } } @@ -716,7 +775,7 @@ class LocalDescriptorSet { } constructor () { - const device = legacyCC.director.root.device; + const device = deviceManager.gfxDevice; this._localData = new Float32Array(UBOLocal.COUNT); this._localBuffer = device.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, @@ -727,17 +786,17 @@ class LocalDescriptorSet { } public initialize (batch) { - const device = legacyCC.director.root.device; + const device = deviceManager.gfxDevice; this._transform = batch.useLocalData; this._textureHash = batch.textureHash; this._samplerHash = batch.samplerHash; _dsInfo.layout = batch.passes[0].localSetLayout; this._descriptorSet = device.createDescriptorSet(_dsInfo); - this._descriptorSet!.bindBuffer(UBOLocal.BINDING, this._localBuffer!); + this._descriptorSet.bindBuffer(UBOLocal.BINDING, this._localBuffer!); const binding = ModelLocalBindings.SAMPLER_SPRITE; - this._descriptorSet!.bindTexture(binding, batch.texture!); - this._descriptorSet!.bindSampler(binding, batch.sampler!); - this._descriptorSet!.update(); + this._descriptorSet.bindTexture(binding, batch.texture!); + this._descriptorSet.bindSampler(binding, batch.sampler!); + this._descriptorSet.update(); this._transformUpdate = true; } @@ -832,7 +891,7 @@ class DescriptorSetCache { return this._descriptorSetCache.get(hash)!; } else { _dsInfo.layout = batch.passes[0].localSetLayout; - const descriptorSet = root.device.createDescriptorSet(_dsInfo) as DescriptorSet; + const descriptorSet = deviceManager.gfxDevice.createDescriptorSet(_dsInfo); const binding = ModelLocalBindings.SAMPLER_SPRITE; descriptorSet.bindTexture(binding, batch.texture!); descriptorSet.bindSampler(binding, batch.sampler!); diff --git a/cocos/2d/renderer/buffer-accessor.ts b/cocos/2d/renderer/buffer-accessor.ts index c5979e7d9f..1e6794a5e6 100644 --- a/cocos/2d/renderer/buffer-accessor.ts +++ b/cocos/2d/renderer/buffer-accessor.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { Attribute, Device } from '../../core/gfx'; import type { MeshBuffer } from './mesh-buffer'; import { getComponentPerVertex } from './vertex-format'; diff --git a/cocos/2d/renderer/draw-batch.ts b/cocos/2d/renderer/draw-batch.ts index fb3a232388..4f079da6ad 100644 --- a/cocos/2d/renderer/draw-batch.ts +++ b/cocos/2d/renderer/draw-batch.ts @@ -29,7 +29,7 @@ import { Material } from '../../core/assets/material'; import { Texture, Sampler, InputAssembler, DescriptorSet, Shader } from '../../core/gfx'; import { Node } from '../../core/scene-graph'; import { Camera } from '../../core/renderer/scene/camera'; -import { RenderScene } from '../../core/renderer/scene/render-scene'; +import { RenderScene } from '../../core/renderer/core/render-scene'; import { Model } from '../../core/renderer/scene/model'; import { Layers } from '../../core/scene-graph/layers'; import { legacyCC } from '../../core/global-exports'; @@ -44,9 +44,6 @@ export class DrawBatch2D { public set inputAssembler (ia: InputAssembler | null) { this._inputAssembler = ia; - if (JSB) { - this._nativeObj.inputAssembler = ia; - } } public get descriptorSet () { @@ -55,9 +52,6 @@ export class DrawBatch2D { public set descriptorSet (ds: DescriptorSet | null) { this._descriptorSet = ds; - if (JSB) { - this._nativeObj.descriptorSet = ds; - } } public get visFlags () { @@ -65,13 +59,6 @@ export class DrawBatch2D { } public set visFlags (vis) { this._visFlags = vis; - if (JSB) { - this._nativeObj.visFlags = vis; - } - } - - public get native () { - return this._nativeObj; } get passes () { @@ -82,14 +69,14 @@ export class DrawBatch2D { return this._shaders; } - public bufferBatch: MeshBuffer | null = null; - public camera: Camera | null = null; - public renderScene: RenderScene | null = null; - public model: Model | null = null; + // public bufferBatch: MeshBuffer | null = null; // use less + // public camera: Camera | null = null; // use less + // public renderScene: RenderScene | null = null; // use less for now + public model: Model | null = null; // for uimodel public texture: Texture | null = null; public sampler: Sampler | null = null; public useLocalData: Node | null = null; - public isStatic = false; + public isStatic = false; // use less,remove when remove Static batch public textureHash = 0; public samplerHash = 0; private _passes: Pass[] = []; @@ -97,28 +84,17 @@ export class DrawBatch2D { private _visFlags: number = UI_VIS_FLAG; private _inputAssembler: InputAssembler | null = null; private _descriptorSet: DescriptorSet | null = null; - private declare _nativeObj: any; - - constructor () { - if (JSB) { - // @ts-expect-error jsb related codes - this._nativeObj = new jsb.DrawBatch2D(); - this._nativeObj.visFlags = this._visFlags; - } - } + //private declare _nativeObj: any; public destroy (ui: IBatcher) { this._passes = []; - if (JSB) { - this._nativeObj = null; - } } public clear () { - this.bufferBatch = null; + // this.bufferBatch = null; this._inputAssembler = null; this._descriptorSet = null; - this.camera = null; + // this.camera = null; this.texture = null; this.sampler = null; this.textureHash = 0; @@ -127,7 +103,7 @@ export class DrawBatch2D { this.isStatic = false; this.useLocalData = null; this.visFlags = UI_VIS_FLAG; - this.renderScene = null; + // this.renderScene = null; } // object version @@ -171,13 +147,6 @@ export class DrawBatch2D { dirty = true; } - - if (JSB) { - if (dirty) { - this._nativeObj.passes = this._passes; - this._nativeObj.shaders = this._shaders; - } - } } } } diff --git a/cocos/2d/renderer/i-batcher.ts b/cocos/2d/renderer/i-batcher.ts index 7c04947f11..97b906d608 100644 --- a/cocos/2d/renderer/i-batcher.ts +++ b/cocos/2d/renderer/i-batcher.ts @@ -6,7 +6,7 @@ import { Camera } from '../../core/renderer/scene/camera'; import { Model } from '../../core/renderer/scene/model'; import { SpriteFrame } from '../assets/sprite-frame'; import { UIStaticBatch } from '../components/ui-static-batch'; -import { Renderable2D, RenderRoot2D } from '../framework'; +import { UIRenderer, RenderRoot2D } from '../framework'; import { StaticVBAccessor } from './static-vb-accessor'; import { DrawBatch2D } from './draw-batch'; import { BaseRenderData } from './render-data'; @@ -38,15 +38,15 @@ export interface IBatcher { switchBufferAccessor (attributes?: Attribute[]): StaticVBAccessor; - commitComp (comp: Renderable2D, renderData: BaseRenderData|null, frame: TextureBase | SpriteFrame | null, assembler: any, transform: Node | null); - commitModel (comp: UIMeshRenderer | Renderable2D, model: Model | null, mat: Material | null); + commitComp (comp: UIRenderer, renderData: BaseRenderData|null, frame: TextureBase | SpriteFrame | null, assembler: any, transform: Node | null); + commitModel (comp: UIMeshRenderer | UIRenderer, model: Model | null, mat: Material | null); setupStaticBatch (staticComp: UIStaticBatch, bufferAccessor: StaticVBAccessor); endStaticBatch (); commitStaticBatch (comp: UIStaticBatch); - autoMergeBatches (renderComp?: Renderable2D); - forceMergeBatches (material: Material, frame: TextureBase | SpriteFrame | null, renderComp: Renderable2D); + autoMergeBatches (renderComp?: UIRenderer); + forceMergeBatches (material: Material, frame: TextureBase | SpriteFrame | null, renderComp: UIRenderer); finishMergeBatches (); flushMaterial (mat: Material); diff --git a/cocos/2d/renderer/linear-buffer-accessor.ts b/cocos/2d/renderer/linear-buffer-accessor.ts index 1af212e838..8b26bd871f 100644 --- a/cocos/2d/renderer/linear-buffer-accessor.ts +++ b/cocos/2d/renderer/linear-buffer-accessor.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { InputAssembler, Device, Attribute } from '../../core/gfx'; import { MeshBuffer } from './mesh-buffer'; import { BufferAccessor } from './buffer-accessor'; diff --git a/cocos/2d/renderer/mesh-buffer.ts b/cocos/2d/renderer/mesh-buffer.ts index 5177e0d048..f250a55eac 100644 --- a/cocos/2d/renderer/mesh-buffer.ts +++ b/cocos/2d/renderer/mesh-buffer.ts @@ -23,15 +23,13 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ +import { JSB } from 'internal:constants'; import { Device, BufferUsageBit, MemoryUsageBit, Attribute, Buffer, BufferInfo, InputAssembler, InputAssemblerInfo } from '../../core/gfx'; import { getComponentPerVertex } from './vertex-format'; import { getError, warnID } from '../../core/platform/debug'; import { sys } from '../../core'; import { assertIsTrue } from '../../core/data/utils/asserts'; +import { NativeUIMeshBuffer } from './native-2d'; interface IIARef { ia: InputAssembler; @@ -39,19 +37,98 @@ interface IIARef { indexBuffer: Buffer; } +export enum MeshBufferSharedBufferView{ + byteOffset, + vertexOffset, + indexOffset, + dirty, + floatsPerVertex, + count = 5 +} + export class MeshBuffer { get attributes () { return this._attributes; } get vertexFormatBytes () { return this._vertexFormatBytes; } - public byteOffset = 0; - public vertexOffset = 0; - public indexOffset = 0; - public vData: Float32Array = null!; - public iData: Uint16Array = null!; + protected _byteOffset = 0; + get byteOffset () { + return this._byteOffset; + } + set byteOffset (val:number) { + this._byteOffset = val; + if (JSB) { + this._sharedBuffer[MeshBufferSharedBufferView.byteOffset] = val; + } + } + + protected _vertexOffset = 0; + get vertexOffset () { + return this._vertexOffset; + } + set vertexOffset (val:number) { + this._vertexOffset = val; + if (JSB) { + this._sharedBuffer[MeshBufferSharedBufferView.vertexOffset] = val; + } + } + + protected _indexOffset = 0; + get indexOffset () { + return this._indexOffset; + } + set indexOffset (val:number) { + this._indexOffset = val; + if (JSB) { + this._sharedBuffer[MeshBufferSharedBufferView.indexOffset] = val; + } + } + + protected _dirty = false; + get dirty () { + return this._dirty; + } + set dirty (val:boolean) { + this._dirty = val; + if (JSB) { + this._sharedBuffer[MeshBufferSharedBufferView.dirty] = val ? 1 : 0; + } + } + + protected _floatsPerVertex = 0; + get floatsPerVertex () { + return this._floatsPerVertex; + } + set floatsPerVertex (val:number) { + this._floatsPerVertex = val; + if (JSB) { + this._sharedBuffer[MeshBufferSharedBufferView.floatsPerVertex] = val; + } + } + + protected _vData: Float32Array = null!; + get vData () { + return this._vData; + } + set vData (val:Float32Array) { + this._vData = val; + //还得看是否需要共享.buffer + if (JSB) { + this._nativeObj.vData = val; + } + } + + protected _iData: Uint16Array = null!; + get iData () { + return this._iData; + } + set iData (val:Uint16Array) { + this._iData = val; + if (JSB) { + this._nativeObj.iData = val; + } + } - private _dirty = false; private _vertexFormatBytes = 0; - private _floatsPerVertex = 0; private _initVDataCount = 0; private _initIDataCount = 0; private _attributes: Attribute[] = null!; @@ -61,11 +138,46 @@ export class MeshBuffer { private _iaInfo: InputAssemblerInfo = null!; private _nextFreeIAHandle = 0; + //nativeObj + protected declare _nativeObj:NativeUIMeshBuffer; + get nativeObj () { + return this._nativeObj; + } + + //sharedBuffer + protected declare _sharedBuffer: Uint32Array; + get sharedBuffer () { + return this._sharedBuffer; + } + + public initSharedBuffer () { + if (JSB) { + this._sharedBuffer = new Uint32Array(MeshBufferSharedBufferView.count); + } + } + + public syncSharedBufferToNative () { + if (JSB) { + this._nativeObj.syncSharedBufferToNative(this._sharedBuffer); + } + } + + constructor () { + if (JSB) { + this._nativeObj = new NativeUIMeshBuffer(); + } + this.initSharedBuffer(); + this.syncSharedBufferToNative(); + } + public initialize (device: Device, attrs: Attribute[], vFloatCount: number, iCount: number) { this._initVDataCount = vFloatCount; this._initIDataCount = iCount; this._attributes = attrs; - this._floatsPerVertex = getComponentPerVertex(attrs); + + //sync to native + this.floatsPerVertex = getComponentPerVertex(attrs); + assertIsTrue(this._initVDataCount / this._floatsPerVertex < 65536, getError(9005)); if (!this.vData || !this.iData) { @@ -74,11 +186,14 @@ export class MeshBuffer { } // Initialize the first ia this._iaPool.push(this.createNewIA(device)); + if (JSB) { + this._nativeObj.initialize(device, attrs, vFloatCount, iCount); + } } public reset () { this._nextFreeIAHandle = 0; - this._dirty = false; + this.dirty = false; } public destroy () { @@ -103,7 +218,7 @@ export class MeshBuffer { } public setDirty () { - this._dirty = true; + this.dirty = true; } /** @@ -115,6 +230,7 @@ export class MeshBuffer { return false; } + //有返回值暂时没写 public requireFreeIA (device: Device) { if (this._iaPool.length <= this._nextFreeIAHandle) { this._iaPool.push(this.createNewIA(device)); @@ -123,6 +239,7 @@ export class MeshBuffer { return ia; } + //参数暂时没传 public recycleIA (ia: InputAssembler) { const pool = this._iaPool; for (let i = 0; i < this._nextFreeIAHandle; ++i) { @@ -137,7 +254,7 @@ export class MeshBuffer { } public checkCapacity (vertexCount: number, indexCount: number) { - const maxVertex = this.vertexOffset + vertexCount; + const maxVertex = (this.vertexOffset + vertexCount) * this._floatsPerVertex; const maxIndex = this.indexOffset + indexCount; if (maxVertex > this._initVDataCount || maxIndex > this._initIDataCount) { return false; @@ -180,9 +297,10 @@ export class MeshBuffer { } iaRef.indexBuffer.update(indicesData); } - this._dirty = false; + this.dirty = false; } + //有返回值,暂时没原生化 private createNewIA (device: Device): IIARef { let ia; let vertexBuffers; diff --git a/cocos/2d/renderer/native-2d-empty.ts b/cocos/2d/renderer/native-2d-empty.ts new file mode 100644 index 0000000000..eb4c24f6a7 --- /dev/null +++ b/cocos/2d/renderer/native-2d-empty.ts @@ -0,0 +1,7 @@ + +export const NativeRenderDrawInfo = undefined; +export const NativeBatcher2d = undefined; +export const NativeUIMeshBuffer = undefined; +export const NativeRenderEntity = undefined; +export const NativeUIModelProxy = undefined; +export const NativeStencilManager = undefined; \ No newline at end of file diff --git a/cocos/2d/renderer/native-2d.jsb.ts b/cocos/2d/renderer/native-2d.jsb.ts new file mode 100644 index 0000000000..4e1cf0a516 --- /dev/null +++ b/cocos/2d/renderer/native-2d.jsb.ts @@ -0,0 +1,9 @@ +// 2d +declare const n2d: any; + +export const NativeRenderDrawInfo = n2d.RenderDrawInfo; +export const NativeBatcher2d = n2d.Batcher2d; +export const NativeUIMeshBuffer = n2d.UIMeshBuffer; +export const NativeRenderEntity = n2d.RenderEntity; +export const NativeUIModelProxy = n2d.UIModelProxy; +export const NativeStencilManager = n2d.StencilManager; \ No newline at end of file diff --git a/cocos/2d/renderer/native-2d.ts b/cocos/2d/renderer/native-2d.ts new file mode 100644 index 0000000000..59b219f318 --- /dev/null +++ b/cocos/2d/renderer/native-2d.ts @@ -0,0 +1,147 @@ +import { Material } from '../../core/assets'; +import { Attribute, Device, Sampler, Texture } from '../../core/gfx'; +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); + + get vbBuffer(): ArrayBufferLike; + set vbBuffer(vbBuffer: ArrayBufferLike); + + get ibBuffer(): ArrayBufferLike; + set ibBuffer(ibBuffer: ArrayBufferLike); + + get vDataBuffer(): ArrayBufferLike; + set vDataBuffer(vDataBuffer: ArrayBufferLike); + + 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); + + setRender2dBufferToNative(data: TypedArray, stride: number, size: number); + syncSharedBufferToNative(data: TypedArray); + getAttrSharedBufferForJS(): ArrayBufferLike; +} + +export declare class NativeRenderEntity { + constructor(batcher: NativeBatcher2d); + + 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); + + get stencilStage(): number; + set stencilStage(stage: number); + + get staticDrawInfoSize(): number; + set staticDrawInfoSize(size: number); + + setRenderEntityType(type: number); + getStaticRenderDrawInfo(index: number): NativeRenderDrawInfo; + getEntitySharedBufferForJS(): ArrayBufferLike; +} + +export declare class NativeUIMeshBuffer { + get vData(): Float32Array; + set vData(val: Float32Array); + get iData(): Uint16Array; + set iData(val: Uint16Array); + + syncSharedBufferToNative(data: TypedArray); + + initialize(device: Device, attrs: Attribute[], vFloatCount: number, iCount: number); + reset(); + destroy(); + setDirty(); + recycleIA(); + uploadBuffers(); +} + +export declare class NativeBatcher2d { + syncMeshBuffersToNative(accId: number, buffers: NativeUIMeshBuffer[]); + update(); + uploadBuffers(); + reset(); + syncRootNodesToNative(nodes: Node[]); + releaseDescriptorSetCache(texture: Texture, sampler: Sampler); +} + +export declare class NativeUIModelProxy { + initModel(node); + activeSubModel(index: number); + uploadData(); + destroy(); + clear(); + updateModels(model); + attachDrawInfo(); + attachNode(node); +} + +export declare class NativeStencilManager { + setStencilStage(stageIndex: number); + getStencilSharedBufferForJS(): ArrayBufferLike; +} diff --git a/cocos/2d/renderer/render-data.ts b/cocos/2d/renderer/render-data.ts index c8caa5cd04..1a96a925fe 100644 --- a/cocos/2d/renderer/render-data.ts +++ b/cocos/2d/renderer/render-data.ts @@ -23,8 +23,7 @@ THE SOFTWARE. */ - - +import { JSB } from 'internal:constants'; import { director } from '../../core/director'; import { Material } from '../../core/assets/material'; import { TextureBase } from '../../core/assets/texture-base'; @@ -32,12 +31,19 @@ import { Color } from '../../core/math'; import { Pool, RecyclePool } from '../../core/memop'; import { murmurhash2_32_gc } from '../../core/utils/murmurhash2_gc'; import { SpriteFrame } from '../assets/sprite-frame'; -import { Renderable2D } from '../framework/renderable-2d'; +import { UIRenderer } from '../framework/ui-renderer'; import { StaticVBAccessor, StaticVBChunk } from './static-vb-accessor'; -import { getAttributeStride, vfmtPosUvColor } from './vertex-format'; -import { Buffer, BufferInfo, BufferUsageBit, Device, InputAssembler, InputAssemblerInfo, MemoryUsageBit } from '../../core/gfx'; +import { getAttributeStride, vfmtPosUvColor, vfmtPosUvTwoColor } from './vertex-format'; +import { Buffer, BufferInfo, BufferUsageBit, Device, Attribute, InputAssembler, InputAssemblerInfo, MemoryUsageBit } from '../../core/gfx'; import { assertIsTrue } from '../../core/data/utils/asserts'; +import { RenderDrawInfo, RenderDrawInfoType } from './render-draw-info'; +import { StencilManager } from './stencil-manager'; +import { Batcher2D } from './batcher-2d'; +import { RenderEntity, RenderEntityType } from './render-entity'; +/** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ export interface IRenderData { x: number; y: number; @@ -58,10 +64,12 @@ const _dataPool = new Pool(() => ({ color: Color.WHITE.clone(), }), 128); -let _pool: RecyclePool = null!; +const _pool: RecyclePool = null!; +/** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ export class BaseRenderData { - public material: Material | null = null; get vertexCount () { return this._vc; } @@ -78,15 +86,66 @@ export class BaseRenderData { return this._vertexFormat; } + get drawInfoType () { + return this._drawInfoType; + } + set drawInfoType (type: RenderDrawInfoType) { + this._drawInfoType = type; + if (this._renderDrawInfo) { + this._renderDrawInfo.setDrawInfoType(type); + } + } + public chunk: StaticVBChunk = null!; - public dataHash = 0; - public isMeshBuffer = false; + // entity for native + protected _renderDrawInfo: RenderDrawInfo = null!; + public get renderDrawInfo () { + return this._renderDrawInfo; + } + + protected _material: Material | null = null; + get material () { + return this._material!; + } + set material (val: Material | null) { + this._material = val; + if (this._renderDrawInfo) { + this._renderDrawInfo.setMaterial(val!); + } + } + + protected _dataHash = 0; + get dataHash () { + return this._dataHash; + } + set dataHash (val: number) { + this._dataHash = val; + if (this._renderDrawInfo) { + this._renderDrawInfo.setDataHash(val); + } + } + + public _isMeshBuffer = false; protected _vc = 0; protected _ic = 0; protected _floatStride = 0; protected _vertexFormat = vfmtPosUvColor; + protected _drawInfoType :RenderDrawInfoType = RenderDrawInfoType.COMP; + protected _multiOwner = false; + get multiOwner () { return this._multiOwner; } + set multiOwner (val) { + this._multiOwner = val; + } + + protected _batcher: Batcher2D | null = null; + get batcher () { + if (!this._batcher) { + this._batcher = director.root!.batcher2D; + } + return this._batcher; + } constructor (vertexFormat = vfmtPosUvColor) { this._floatStride = vertexFormat === vfmtPosUvColor ? DEFAULT_STRIDE : (getAttributeStride(vertexFormat) >> 2); @@ -96,14 +155,75 @@ export class BaseRenderData { public isValid () { return this._ic > 0 && this.chunk.vertexAccessor; } + + // it should be invoked at where a render data is allocated. + public initRenderDrawInfo (comp: UIRenderer, drawInfoType: RenderDrawInfoType = RenderDrawInfoType.COMP) { + if (JSB) { + const renderEntity: RenderEntity = comp.renderEntity; + + if (renderEntity.renderEntityType === RenderEntityType.STATIC) { + if (!this._renderDrawInfo) { + // initialization should be in native + const drawInfo = renderEntity.getStaticRenderDrawInfo(); + if (drawInfo) { + this._renderDrawInfo = drawInfo; + } + } + } else if (this.multiOwner === false) { + if (!this._renderDrawInfo) { + this._renderDrawInfo = new RenderDrawInfo(); + // for no resize() invoking components + this.setRenderDrawInfoAttributes(); + renderEntity.addDynamicRenderDrawInfo(this._renderDrawInfo); + } + } + + this.drawInfoType = drawInfoType; + } + } + + public removeRenderDrawInfo (comp: UIRenderer) { + if (JSB) { + const renderEntity: RenderEntity = comp.renderEntity; + if (renderEntity.renderEntityType === RenderEntityType.DYNAMIC) { + renderEntity.removeDynamicRenderDrawInfo(); + } + } + } + + protected setRenderDrawInfoAttributes () { + if (JSB) { + if (!this._renderDrawInfo) { + return; + } + if (this.chunk) { + this._renderDrawInfo.setBufferId(this.chunk.bufferId); + this._renderDrawInfo.setVertexOffset(this.chunk.vertexOffset); + this._renderDrawInfo.setVB(this.chunk.vb); + this._renderDrawInfo.setIB(this.chunk.ib); + if (this.chunk.meshBuffer) { + this._renderDrawInfo.setIndexOffset(this.chunk.meshBuffer.indexOffset); + this._renderDrawInfo.setVData(this.chunk.meshBuffer.vData.buffer); + this._renderDrawInfo.setIData(this.chunk.meshBuffer.iData.buffer); + } + } + this._renderDrawInfo.setVBCount(this._vc); + this._renderDrawInfo.setIBCount(this._ic); + + this._renderDrawInfo.setDataHash(this.dataHash); + this._renderDrawInfo.setIsMeshBuffer(this._isMeshBuffer); + this._renderDrawInfo.setMaterial(this.material!); + this._renderDrawInfo.setDrawInfoType(this._drawInfoType); + } + } } +/** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ export class RenderData extends BaseRenderData { public static add (vertexFormat = vfmtPosUvColor, accessor?: StaticVBAccessor) { - if (!_pool) { - _pool = new RecyclePool(() => new RenderData(), 32); - } - const rd = _pool.add(); + const rd = new RenderData(vertexFormat); rd._floatStride = vertexFormat === vfmtPosUvColor ? DEFAULT_STRIDE : (getAttributeStride(vertexFormat) >> 2); rd._vertexFormat = vertexFormat; if (!accessor) { @@ -115,14 +235,14 @@ export class RenderData extends BaseRenderData { } public static remove (data: RenderData) { - const idx = _pool.data.indexOf(data); - if (idx === -1) { - return; - } + // const idx = _pool.data.indexOf(data); + // if (idx === -1) { + // return; + // } data.clear(); data._accessor = null!; - _pool.removeAt(idx); + // _pool.removeAt(idx); } get dataLength () { @@ -145,19 +265,65 @@ export class RenderData extends BaseRenderData { data.length = length; } + + this.syncRender2dBuffer(); } get data () { return this._data; } - public indices: Uint16Array | null = null; - public vertDirty = true; + public _vertDirty = true; + get vertDirty () { + return this._vertDirty; + } + set vertDirty (val: boolean) { + this._vertDirty = val; + if (this._renderDrawInfo && val) { + this._renderDrawInfo.setVertDirty(val); + } + } - public frame; + protected _textureHash = 0; + get textureHash () { + return this._textureHash; + } + set textureHash (val: number) { + this._textureHash = val; + if (this._renderDrawInfo) { + this._renderDrawInfo.setTextureHash(val); + } + } + + protected _blendHash = -1; + get blendHash () { + return this._blendHash; + } + set blendHash (val: number) { + this._blendHash = val; + if (this._renderDrawInfo) { + this._renderDrawInfo.setBlendHash(val); + } + } + + public indices: Uint16Array | null = null; + + public set frame (val: SpriteFrame | TextureBase | null) { + this._frame = val; + if (this._renderDrawInfo) { + if (this._frame) { + this._renderDrawInfo.setTexture(this._frame.getGFXTexture()); + this._renderDrawInfo.setSampler(this._frame.getGFXSampler()); + } else { + this._renderDrawInfo.setTexture(null); + this._renderDrawInfo.setSampler(null); + } + } + } + public get frame () { + return this._frame; + } public layer = 0; - public blendHash = -1; - public textureHash = 0; public nodeDirty = true; public passDirty = true; @@ -169,13 +335,16 @@ export class RenderData extends BaseRenderData { private _pivotY = 0; private _width = 0; private _height = 0; + private _frame: SpriteFrame | TextureBase | null = null; protected _accessor: StaticVBAccessor = null!; + public vertexRow = 1; + public vertexCol = 1; + public constructor (vertexFormat = vfmtPosUvColor, accessor?: StaticVBAccessor) { super(vertexFormat); if (!accessor) { - const batcher = director.root!.batcher2D; - accessor = batcher.switchBufferAccessor(this._vertexFormat); + accessor = this.batcher.switchBufferAccessor(this._vertexFormat); } this._accessor = accessor; } @@ -191,6 +360,67 @@ export class RenderData extends BaseRenderData { // renderData always have chunk this.chunk = this._accessor.allocateChunk(vertexCount, indexCount)!; this.updateHash(); + + if (JSB && this.multiOwner === false && this._renderDrawInfo) { + // for sync vData and iData address to native + this._renderDrawInfo.setDrawInfoType(this._drawInfoType); + this._renderDrawInfo.setBufferId(this.chunk.bufferId); + this._renderDrawInfo.setVertexOffset(this.chunk.vertexOffset); + this._renderDrawInfo.setIndexOffset(this.chunk.meshBuffer.indexOffset); + this._renderDrawInfo.setVB(this.chunk.vb); + this._renderDrawInfo.setIB(this.chunk.ib); + this._renderDrawInfo.setVData(this.chunk.meshBuffer.vData.buffer); + this._renderDrawInfo.setIData(this.chunk.meshBuffer.iData.buffer); + this._renderDrawInfo.setVBCount(this._vc); + this._renderDrawInfo.setIBCount(this._ic); + } + } + + protected setRenderDrawInfoAttributes () { + if (JSB) { + if (!this._renderDrawInfo) { + return; + } + 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); + } + } + + public fillDrawInfoAttributes (drawInfo: RenderDrawInfo) { + if (JSB) { + if (!drawInfo) { + return; + } + + drawInfo.setAccId(this._accessor.id); + drawInfo.setDrawInfoType(this._drawInfoType); + drawInfo.setBufferId(this.chunk.bufferId); + drawInfo.setVertexOffset(this.chunk.vertexOffset); + drawInfo.setIndexOffset(this.chunk.meshBuffer.indexOffset); + drawInfo.setVB(this.chunk.vb); + drawInfo.setIB(this.chunk.ib); + drawInfo.setVData(this.chunk.meshBuffer.vData.buffer); + drawInfo.setIData(this.chunk.meshBuffer.iData.buffer); + drawInfo.setVBCount(this._vc); + drawInfo.setIBCount(this._ic); + drawInfo.setDataHash(this.dataHash); + drawInfo.setIsMeshBuffer(this._isMeshBuffer); + } + } + + // Initial advance render data for native + protected syncRender2dBuffer () { + if (JSB && this.multiOwner === false) { + if (!this._renderDrawInfo) { + return; + } + this.renderDrawInfo.initRender2dBuffer(this.dataLength, this.floatStride); + this.renderDrawInfo.setRender2dBufferToNative(); + } } public resizeAndCopy (vertexCount: number, indexCount: number) { @@ -216,14 +446,14 @@ export class RenderData extends BaseRenderData { } } - public updateNode (comp: Renderable2D) { + public updateNode (comp: UIRenderer) { this.layer = comp.node.layer; this.nodeDirty = false; this.hashDirty = true; } - public updatePass (comp: Renderable2D) { - this.material = comp.getRenderMaterial(0); + public updatePass (comp: UIRenderer) { + this.material = comp.getRenderMaterial(0)!; this.blendHash = comp.blendHash; this.passDirty = false; this.hashDirty = true; @@ -243,9 +473,9 @@ export class RenderData extends BaseRenderData { this.hashDirty = false; } - public updateRenderData (comp: Renderable2D, frame: SpriteFrame | TextureBase) { + public updateRenderData (comp: UIRenderer, frame: SpriteFrame | TextureBase) { if (this.passDirty) { - this.material = comp.getRenderMaterial(0); + this.material = comp.getRenderMaterial(0)!; this.blendHash = comp.blendHash; this.passDirty = false; this.hashDirty = true; @@ -268,6 +498,28 @@ export class RenderData extends BaseRenderData { if (this.hashDirty) { this.updateHash(); } + + // Hack Do not update pre frame + if (JSB && this.multiOwner === false) { + // for sync vData and iData address to native + this.setRenderDrawInfoAttributes(); + // sync shared buffer to native + this.copyRenderDataToSharedBuffer(); + } + } + + copyRenderDataToSharedBuffer () { + if (JSB) { + const entity = this._renderDrawInfo; + const sharedBuffer = entity.render2dBuffer; + + if (sharedBuffer.length < this.floatStride * this._data.length) { + console.error('Vertex count doesn\'t match.'); + return; + } + + entity.fillRender2dBuffer(this._data); + } } public updateSizeNPivot (width: number, height: number, pivotX: number, pivotY: number) { @@ -304,31 +556,45 @@ export class RenderData extends BaseRenderData { this.frame = null; this.textureHash = 0; this.dataHash = 0; + if (JSB && this._renderDrawInfo) { + this._renderDrawInfo.clear(); + } + } + public static createStaticVBAccessor (attributes: Attribute[], vCount?: number, iCount?: number): StaticVBAccessor { + const device = director.root!.device; + const accessor = new StaticVBAccessor(device, attributes, vCount, iCount); + return accessor; } } +/** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ export class MeshRenderData extends BaseRenderData { public static add (vertexFormat = vfmtPosUvColor) { - const rd = _meshDataPool.add(); + // const rd = _meshDataPool.add(); + const rd = new MeshRenderData(); rd._floatStride = vertexFormat === vfmtPosUvColor ? DEFAULT_STRIDE : (getAttributeStride(vertexFormat) >> 2); rd._vertexFormat = vertexFormat; return rd; } public static remove (data: MeshRenderData) { - const idx = _meshDataPool.data.indexOf(data); - if (idx === -1) { - return; - } + // const idx = _meshDataPool.data.indexOf(data); + // if (idx === -1) { + // return; + // } - _meshDataPool.data[idx].clear(); - _meshDataPool.removeAt(idx); + // _meshDataPool.data[idx].clear(); + // _meshDataPool.removeAt(idx); + + data.clear(); } /** * @deprecated */ - set formatByte (value: number) {} + set formatByte (value: number) { } get formatByte () { return this.stride; } get floatStride () { return this._floatStride; } @@ -338,7 +604,7 @@ export class MeshRenderData extends BaseRenderData { */ get vDataOffset () { return this._byteLength >>> 2; } - public isMeshBuffer = true; + public _isMeshBuffer = true; public vData: Float32Array; public iData: Uint16Array; /** @@ -361,6 +627,8 @@ export class MeshRenderData extends BaseRenderData { public lastFilledIndex = 0; public lastFilledVertex = 0; + public frame; + private _byteLength = 0; private _vertexBuffers: Buffer[] = []; private _indexBuffer: Buffer = null!; @@ -518,7 +786,7 @@ export class MeshRenderData extends BaseRenderData { )); } this._iaInfo = new InputAssemblerInfo(this._vertexFormat, vbs, this._indexBuffer); - this._iaPool = new RecyclePool(() => device.createInputAssembler(this._iaInfo), 1, (ia) => { ia.destroy(); }); + this._iaPool = new RecyclePool(() => device.createInputAssembler(this._iaInfo), 1, (ia) => { ia.destroy(); }); } } @@ -535,6 +803,40 @@ export class MeshRenderData extends BaseRenderData { this.iData.set(oldIData, 0); } } + + public setRenderDrawInfoAttributes () { + if (JSB) { + if (!this._renderDrawInfo) { + return; + } + this._renderDrawInfo.setVData(this.vData.buffer); + this._renderDrawInfo.setIData(this.iData.buffer); + this._renderDrawInfo.setVBCount(this._vc); + this._renderDrawInfo.setIBCount(this._ic); + this._renderDrawInfo.setVertexOffset(this.vertexStart); + this._renderDrawInfo.setIndexOffset(this.indexStart); + + this._renderDrawInfo.setIsMeshBuffer(this._isMeshBuffer); + this._renderDrawInfo.setMaterial(this.material!); + this._renderDrawInfo.setTexture(this.frame?.getGFXTexture()); + this._renderDrawInfo.setSampler(this.frame?.getGFXSampler()); + } + } + + // only for particle2d + public particleInitRenderDrawInfo (entity: RenderEntity) { + if (JSB) { + if (entity.renderEntityType === RenderEntityType.STATIC) { + if (!this._renderDrawInfo) { + // initialization should be in native + const drawInfo = entity.getStaticRenderDrawInfo(); + if (drawInfo) { + this._renderDrawInfo = drawInfo; + } + } + } + } + } } const _meshDataPool: RecyclePool = new RecyclePool(() => new MeshRenderData(), 32); diff --git a/cocos/2d/renderer/render-draw-info.ts b/cocos/2d/renderer/render-draw-info.ts new file mode 100644 index 0000000000..1e4d410f26 --- /dev/null +++ b/cocos/2d/renderer/render-draw-info.ts @@ -0,0 +1,291 @@ +import { JSB } from 'internal:constants'; +import { BaseRenderData, IRenderData } from './render-data'; +import { Stage } from './stencil-manager'; +import { NativeRenderDrawInfo } from './native-2d'; +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 RenderDrawInfoType { + COMP, + MODEL, + IA, +} + +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 _texture: Texture | null = null; + protected _textureHash: number | undefined; + protected _sampler: Sampler | null = null; + protected _blendHash: number | undefined; + + protected _model: Model | undefined; + + protected _drawInfoType :RenderDrawInfoType = RenderDrawInfoType.COMP; + + protected declare _nativeObj: NativeRenderDrawInfo; + + // 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); + } + + get nativeObj () { + return this._nativeObj; + } + // set nativeObj (val:NativeRenderDrawInfo) { + // this._nativeObj = val; + // } + + get render2dBuffer () { + return this._render2dBuffer; + } + + private init (nativeDrawInfo?: NativeRenderDrawInfo) { + if (JSB) { + if (nativeDrawInfo) { + this._nativeObj = nativeDrawInfo; + } + if (!this._nativeObj) { + this._nativeObj = new NativeRenderDrawInfo(director.root!.batcher2D.nativeObj); + } + } + + this.initSharedBuffer(); + } + + public clear () { + this._bufferId = 0; + this._vertexOffset = 0; + this._indexOffset = 0; + this._vertDirty = false; + } + + public setAccId (accId) { + this._accId = accId; + if (JSB) { + this._nativeObj.accId = accId; + } + } + + public setBufferId (bufferId) { + this._bufferId = bufferId; + if (JSB) { + this._nativeObj.bufferId = bufferId; + } + } + + public setVertexOffset (vertexOffset) { + this._vertexOffset = vertexOffset; + if (JSB) { + this._nativeObj.vertexOffset = vertexOffset; + } + } + + public setIndexOffset (indexOffset) { + this._indexOffset = indexOffset; + if (JSB) { + this._nativeObj.indexOffset = indexOffset; + } + } + + public setVB (vbBuffer: Float32Array) { + if (JSB) { + this._nativeObj.vbBuffer = vbBuffer; + } + } + + public setIB (ibBuffer: Uint16Array) { + if (JSB) { + this._nativeObj.ibBuffer = ibBuffer; + } + } + + public setVData (vDataBuffer: ArrayBufferLike) { + if (JSB) { + this._nativeObj.vDataBuffer = vDataBuffer; + } + } + + public setIData (iDataBuffer: ArrayBufferLike) { + if (JSB) { + this._nativeObj.iDataBuffer = iDataBuffer; + } + } + + public setVBCount (vbCount) { + if (JSB) { + this._nativeObj.vbCount = vbCount; + } + } + + public setIBCount (ibCount) { + if (JSB) { + this._nativeObj.ibCount = ibCount; + } + } + + public setVertDirty (val: boolean) { + if (JSB) { + this._nativeObj.vertDirty = val; + } + this._vertDirty = val; + } + + public setDataHash (dataHash: number) { + if (JSB) { + if (this._dataHash !== dataHash) { + this._nativeObj.dataHash = dataHash; + } + } + this._dataHash = dataHash; + } + + public setIsMeshBuffer (isMeshBuffer: boolean) { + if (JSB) { + if (this._isMeshBuffer !== isMeshBuffer) { + this._nativeObj.isMeshBuffer = isMeshBuffer; + } + } + this._isMeshBuffer = isMeshBuffer; + } + + public setMaterial (material: Material) { + if (JSB) { + if (this._material !== material) { + this._nativeObj.material = material; + } + } + this._material = material; + } + + public setTexture (texture: Texture | null) { + if (JSB) { + if (this._texture !== texture) { + this._nativeObj.texture = texture; + } + } + 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) { + this._nativeObj.sampler = sampler; + } + } + 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) { + this._nativeObj.model = model; + } + } + } + + public setDrawInfoType (drawInfoType: RenderDrawInfoType) { + if (JSB) { + if (this._drawInfoType !== drawInfoType) { + this._nativeObj.drawInfoType = drawInfoType; + } + } + this._drawInfoType = drawInfoType; + } + + public initRender2dBuffer (vertexCount: number, stride: number) { + if (JSB) { + this._stride = stride; + this._vertexCount = vertexCount; + this._render2dBuffer = new Float32Array(vertexCount * stride); + } + } + + public fillRender2dBuffer (vertexDataArr: IRenderData[]) { + if (JSB) { + const fillLength = Math.min(this._vertexCount, vertexDataArr.length); + let bufferOffset = 0; + for (let i = 0; i < fillLength; i++) { + this.updateVertexBuffer(bufferOffset, vertexDataArr[i]); + bufferOffset += this._stride; + } + } + } + + public updateVertexBuffer (bufferOffset: number, vertexData: IRenderData) { + if (JSB) { + if (bufferOffset >= this.render2dBuffer.length) { + return; + } + const temp: IRenderData = vertexData; + this._render2dBuffer[bufferOffset++] = temp.x; + this._render2dBuffer[bufferOffset++] = temp.y; + this._render2dBuffer[bufferOffset++] = temp.z; + this._render2dBuffer[bufferOffset++] = temp.u; + this._render2dBuffer[bufferOffset++] = temp.v; + this._render2dBuffer[bufferOffset++] = temp.color.r; + this._render2dBuffer[bufferOffset++] = temp.color.g; + this._render2dBuffer[bufferOffset++] = temp.color.b; + 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 new file mode 100644 index 0000000000..2faffde36b --- /dev/null +++ b/cocos/2d/renderer/render-entity.ts @@ -0,0 +1,242 @@ +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'; +import { color, Color, director, Material, Node } from '../../core'; +import { EmitLocation } from '../../particle/enum'; +import { Stage } from './stencil-manager'; + +export enum RenderEntityType { + STATIC, + DYNAMIC, +} + +export enum RenderEntityFloatSharedBufferView { + localOpacity, + count, +} + +export enum RenderEntityUInt8SharedBufferView { + colorR, + colorG, + colorB, + colorA, + count, +} + +export enum RenderEntityBoolSharedBufferView{ + colorDirty, + enabled, + padding0, + padding1, + count, +} + +export class RenderEntity { + private _renderEntityType: RenderEntityType = RenderEntityType.STATIC; + + private _dynamicDrawInfoArr: RenderDrawInfo[] = []; + + 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 declare _floatSharedBuffer: Float32Array; + protected declare _uint8SharedBuffer: Uint8Array; + protected declare _boolSharedBuffer:Uint8Array; + + private declare _nativeObj: NativeRenderEntity; + get nativeObj () { + return this._nativeObj; + } + + get renderDrawInfoArr () { + return this._dynamicDrawInfoArr; + } + + get renderEntityType () { + return this._renderEntityType; + } + // set renderEntityType (val:RenderEntityType) { + // this._renderEntityType = val; + // } + + protected _color: Color = Color.WHITE; + get color () { + return this._color; + } + set color (val: Color) { + this._color = val; + if (JSB) { + this._uint8SharedBuffer[RenderEntityUInt8SharedBufferView.colorR] = val.r; + this._uint8SharedBuffer[RenderEntityUInt8SharedBufferView.colorG] = val.g; + this._uint8SharedBuffer[RenderEntityUInt8SharedBufferView.colorB] = val.b; + this._uint8SharedBuffer[RenderEntityUInt8SharedBufferView.colorA] = val.a; + } + } + + protected _localOpacity = 255; + get localOpacity () { + return this._localOpacity; + } + set localOpacity (val: number) { + this._localOpacity = val; + if (JSB) { + this._floatSharedBuffer[RenderEntityFloatSharedBufferView.localOpacity] = val; + } + } + + protected _colorDirty = true; + get colorDirty () { + return this._colorDirty; + } + set colorDirty (val: boolean) { + this._colorDirty = val; + if (JSB) { + this._boolSharedBuffer[RenderEntityBoolSharedBufferView.colorDirty] = val ? 1 : 0; + } + } + + protected _enabled = true; + get enabled () { + return this._enabled; + } + set enabled (val: boolean) { + this._enabled = val; + if (JSB) { + this._boolSharedBuffer[RenderEntityBoolSharedBufferView.enabled] = val ? 1 : 0; + } + } + + constructor (entityType: RenderEntityType) { + if (JSB) { + if (!this._nativeObj) { + this._nativeObj = new NativeRenderEntity(director.root!.batcher2D.nativeObj); + } + this.setRenderEntityType(entityType); + + this.initSharedBuffer(); + } + } + + public addDynamicRenderDrawInfo (renderDrawInfo: RenderDrawInfo | null) { + if (JSB) { + if (renderDrawInfo) { + this._dynamicDrawInfoArr.push(renderDrawInfo); + this._nativeObj.addDynamicRenderDrawInfo(renderDrawInfo.nativeObj); + } + } + } + + public removeDynamicRenderDrawInfo () { + if (JSB) { + this._dynamicDrawInfoArr.pop(); + this._nativeObj.removeDynamicRenderDrawInfo(); + } + } + + public clearDynamicRenderDrawInfos () { + if (JSB) { + this._dynamicDrawInfoArr.length = 0; + this._nativeObj.clearDynamicRenderDrawInfos(); + } + } + + public setDynamicRenderDrawInfo (renderDrawInfo: RenderDrawInfo | null, index: number) { + if (JSB) { + if (renderDrawInfo) { + if (this._dynamicDrawInfoArr.length < index + 1) { + this._dynamicDrawInfoArr.push(renderDrawInfo); + this._nativeObj.addDynamicRenderDrawInfo(renderDrawInfo.nativeObj); + } else { + this._dynamicDrawInfoArr[index] = renderDrawInfo; + this._nativeObj.setDynamicRenderDrawInfo(renderDrawInfo.nativeObj, index); + } + } + } + } + + public getStaticRenderDrawInfo (): RenderDrawInfo | null { + if (JSB) { + const nativeDrawInfo = this._nativeObj.getStaticRenderDrawInfo(this._nativeObj.staticDrawInfoSize++); + const drawInfo = new RenderDrawInfo(nativeDrawInfo); + return drawInfo; + } + 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) { + this._nativeObj.node = node; + } + } + this._node = node; + } + + setStencilStage (stage: Stage) { + if (JSB) { + if (this._stencilStage !== stage) { + this._nativeObj.stencilStage = stage; + } + } + this._stencilStage = stage; + } + + setRenderEntityType (type: RenderEntityType) { + if (JSB) { + if (this._renderEntityType !== type) { + this._nativeObj.setRenderEntityType(type); + } + } + this._renderEntityType = type; + } + + private initSharedBuffer () { + if (JSB) { + //this._sharedBuffer = new Float32Array(RenderEntitySharedBufferView.count); + const buffer = this._nativeObj.getEntitySharedBufferForJS(); + let offset = 0; + this._floatSharedBuffer = new Float32Array(buffer, offset, RenderEntityFloatSharedBufferView.count); + offset += RenderEntityFloatSharedBufferView.count * 4; + this._uint8SharedBuffer = new Uint8Array(buffer, offset, RenderEntityUInt8SharedBufferView.count); + offset += RenderEntityUInt8SharedBufferView.count * 1; + this._boolSharedBuffer = new Uint8Array(buffer, offset, RenderEntityBoolSharedBufferView.count); + } + } +} diff --git a/cocos/2d/renderer/static-vb-accessor.ts b/cocos/2d/renderer/static-vb-accessor.ts index aafc4defd9..767d431355 100644 --- a/cocos/2d/renderer/static-vb-accessor.ts +++ b/cocos/2d/renderer/static-vb-accessor.ts @@ -23,15 +23,15 @@ THE SOFTWARE. */ - - +import { JSB } from 'internal:constants'; import { Device, Attribute } from '../../core/gfx'; import { MeshBuffer } from './mesh-buffer'; import { BufferAccessor } from './buffer-accessor'; -import { assertID, warnID } from '../../core/platform/debug'; +import { assertID, errorID } from '../../core/platform/debug'; import { assertIsTrue } from '../../core/data/utils/asserts'; import { Pool } from '../../core/memop/pool'; import { macro } from '../../core/platform/macro'; +import { director } from '../../core'; interface IFreeEntry { offset: number; @@ -47,30 +47,51 @@ const _entryPool = new Pool(() => ({ * @internal */ export class StaticVBChunk { + // JSB + public get ib (): Readonly { + return this._ib; + } + private _ib: Uint16Array; + constructor ( public vertexAccessor: StaticVBAccessor, public bufferId: number, public meshBuffer: MeshBuffer, public vertexOffset: number, public vb: Float32Array, - indexCount: number, + public indexCount: number, ) { + this._ib = new Uint16Array(indexCount); // JSB assertIsTrue(meshBuffer === vertexAccessor.getMeshBuffer(bufferId)); } + + setIndexBuffer (indices: ArrayLike) { + if (JSB) { + // 放到原生 + assertIsTrue(indices.length === this.ib.length); + for (let i = 0; i < indices.length; ++i) { + const vid = indices[i]; + this._ib[i] = this.vertexOffset + vid; + } + } + } } export class StaticVBAccessor extends BufferAccessor { public static IB_SCALE = 4; // ib size scale based on vertex count + public static ID_COUNT = 0; private _freeLists: IFreeEntry[][] = []; private _vCount = 0; private _iCount = 0; + private _id = 0; + get id () { return this._id; } public constructor (device: Device, attributes: Attribute[], vCount?: number, iCount?: number) { super(device, attributes); this._vCount = vCount || Math.floor(macro.BATCHER2D_MEM_INCREMENT * 1024 / this._vertexFormatBytes); this._iCount = iCount || (this._vCount * StaticVBAccessor.IB_SCALE); - + this._id = StaticVBAccessor.generateID(); // Initialize first mesh buffer this._allocateBuffer(); } @@ -170,7 +191,7 @@ export class StaticVBAccessor extends BufferAccessor { return new StaticVBChunk(this, bid, buf, vertexOffset, vb, indexCount); } else { - warnID(9004, byteLength); + errorID(9004, byteLength); return null; } } @@ -275,6 +296,16 @@ export class StaticVBAccessor extends BufferAccessor { entry.length = buffer.vData.byteLength; const freeList = [entry]; this._freeLists.push(freeList); + + //sync to native + // temporarily batcher transports buffers + // It is better to put accessor to native + const batcher = director.root!.batcher2D; + batcher.syncMeshBuffersToNative(this.id, this._buffers); + return this._buffers.length - 1; } + static generateID () : number { + return StaticVBAccessor.ID_COUNT++; + } } diff --git a/cocos/2d/renderer/stencil-manager.ts b/cocos/2d/renderer/stencil-manager.ts index 751aa7529a..bc628a0cf6 100644 --- a/cocos/2d/renderer/stencil-manager.ts +++ b/cocos/2d/renderer/stencil-manager.ts @@ -23,10 +23,11 @@ THE SOFTWARE. */ - +import { JSB } from 'internal:constants'; import { ComparisonFunc, StencilOp, DepthStencilState } from '../../core/gfx'; import { Mask } from '../components/mask'; import { Material } from '../../core'; +import { NativeStencilManager } from './native-2d'; // Stage types export enum Stage { @@ -46,9 +47,20 @@ export enum Stage { ENTER_LEVEL_INVERTED = 6, } +export enum StencilSharedBufferView { + stencilTest, + func, + stencilMask, + writeMask, + failOp, + zFailOp, + passOp, + ref, + count, +} + export class StencilManager { public static sharedManager: StencilManager | null = null; - public stage = Stage.DISABLED; private _maskStack: any[] = []; private _stencilPattern = { stencilTest: true, @@ -61,6 +73,14 @@ export class StencilManager { ref: 1, }; + private _stage:Stage = Stage.DISABLED; + get stage () { + return this._stage; + } + set stage (val:Stage) { + this._stage = val; + } + get pattern () { return this._stencilPattern; } @@ -75,7 +95,7 @@ export class StencilManager { } public enterLevel (comp: Mask) { - comp.graphics!.stencilStage = comp.inverted ? Stage.ENTER_LEVEL_INVERTED : Stage.ENTER_LEVEL; + comp.subComp!.stencilStage = comp.inverted ? Stage.ENTER_LEVEL_INVERTED : Stage.ENTER_LEVEL; // this.stage = Stage.ENTER_LEVEL; } diff --git a/cocos/2d/renderer/vertex-format.ts b/cocos/2d/renderer/vertex-format.ts index 041ed19808..85b0a09015 100644 --- a/cocos/2d/renderer/vertex-format.ts +++ b/cocos/2d/renderer/vertex-format.ts @@ -26,21 +26,55 @@ import { AttributeName, Format, FormatInfos, Attribute } from '../../core/gfx'; import { legacyCC } from '../../core/global-exports'; +/** + * @en Vertex format with vector 3 position attribute + * @zh 包含三维位置属性的顶点格式 + */ export const vfmt = [ new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), ]; +/** + * @en Vertex format with the following layout + * 1. Vector 3 position attribute (Float32) + * 2. Vector 4 color attribute (Float32) + * @zh 包含以下数据的顶点格式 + * 1. 三维位置属性(Float32) + * 2. RGBA 颜色属性(Float32) + */ export const vfmtPosColor = [ new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F), ]; +/** + * @en Vertex format with the following layout + * 1. Vector 3 position attribute (Float32) + * 2. Vector 2 uv attribute (Float32) + * 3. Vector 4 color attribute (Float32) + * @zh 包含以下数据的顶点格式 + * 1. 三维位置属性(Float32) + * 2. 二维贴图 UV 属性(Float32) + * 3. RGBA 颜色属性(Float32) + */ export const vfmtPosUvColor = [ new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F), ]; +/** + * @en Vertex format with the following layout + * 1. Vector 3 position attribute (Float32) + * 2. Vector 2 uv attribute (Float32) + * 3. First vector 4 color attribute (Float32) + * 4. Second vector 4 color attribute (Float32) + * @zh 包含以下数据的顶点格式 + * 1. 三维位置属性(Float32) + * 2. 二维贴图 UV 属性(Float32) + * 3. 第一套 RGBA 颜色属性(Float32) + * 3. 第二套 RGBA 颜色属性(Float32) + */ export const vfmtPosUvTwoColor = [ new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), @@ -48,6 +82,12 @@ export const vfmtPosUvTwoColor = [ new Attribute(AttributeName.ATTR_COLOR2, Format.RGBA32F), ]; +/** + * @en Get total components count for all attributes per vertex. + * @zh 获取每个顶点上所有属性的分量数总和 + * @param attrs All attributes of the vertex format + * @returns Total components count + */ export function getComponentPerVertex (attrs: Attribute[]) { let count = 0; for (let i = 0; i < attrs.length; i++) { @@ -59,6 +99,12 @@ export function getComponentPerVertex (attrs: Attribute[]) { return count; } +/** + * @en Get total stride for all attributes per vertex. + * @zh 获取每个顶点上所有属性的总步进 + * @param attrs All attributes of the vertex format + * @returns Total stride + */ export function getAttributeStride (attrs: Attribute[]) { let count = 0; for (let i = 0; i < attrs.length; i++) { diff --git a/cocos/2d/utils/dynamic-atlas/atlas-manager.ts b/cocos/2d/utils/dynamic-atlas/atlas-manager.ts index d2d7423108..3c84eb9010 100644 --- a/cocos/2d/utils/dynamic-atlas/atlas-manager.ts +++ b/cocos/2d/utils/dynamic-atlas/atlas-manager.ts @@ -1,14 +1,12 @@ -/** - * @packageDocumentation - */ - import { EDITOR } from 'internal:constants'; +import { director, System } from '../../../core'; import { Filter } from '../../../core/assets/asset-enum'; import { legacyCC } from '../../../core/global-exports'; +import { macro } from '../../../core/platform'; import { js } from '../../../core/utils/js'; import { Atlas } from './atlas'; -export class DynamicAtlasManager { +export class DynamicAtlasManager extends System { public static instance: DynamicAtlasManager; private _atlases: Atlas[] = []; @@ -125,6 +123,13 @@ export class DynamicAtlasManager { this.reset(); } + /** + * @internal + */ + public init () { + this.enabled = !macro.CLEANUP_IMAGE_CACHE; + } + /** * @en * Append a sprite frame into the dynamic atlas. @@ -136,7 +141,7 @@ export class DynamicAtlasManager { * @param spriteFrame the sprite frame that will be inserted in the atlas. */ public insertSpriteFrame (spriteFrame) { - if (EDITOR) return null; + if (EDITOR && !legacyCC.GAME_VIEW) return null; if (!this._enabled || this._atlasIndex === this._maxAtlasCount || !spriteFrame || spriteFrame._original) return null; @@ -235,7 +240,7 @@ export class DynamicAtlasManager { * @param frame the sprite frame that will be packed in the dynamic atlas. */ public packToDynamicAtlas (comp, frame) { - if (EDITOR) return; + if (EDITOR && !legacyCC.GAME_VIEW) return; if (frame && !frame._original && frame.packable && frame.texture && frame.texture.width > 0 && frame.texture.height > 0) { const packedFrame = this.insertSpriteFrame(frame); @@ -248,4 +253,6 @@ export class DynamicAtlasManager { export const dynamicAtlasManager: DynamicAtlasManager = DynamicAtlasManager.instance = new DynamicAtlasManager(); +director.registerSystem('dynamicAtlasManager', dynamicAtlasManager, 0); + legacyCC.internal.dynamicAtlasManager = dynamicAtlasManager; diff --git a/cocos/2d/utils/dynamic-atlas/atlas.ts b/cocos/2d/utils/dynamic-atlas/atlas.ts index ebb580b312..6e7f29b5a2 100644 --- a/cocos/2d/utils/dynamic-atlas/atlas.ts +++ b/cocos/2d/utils/dynamic-atlas/atlas.ts @@ -1,7 +1,3 @@ -/** - * @packageDocumentation - */ - import { PixelFormat } from '../../../core/assets/asset-enum'; import { ImageAsset } from '../../../core/assets/image-asset'; import { Texture2D } from '../../../core/assets/texture-2d'; diff --git a/cocos/2d/utils/font-loader.ts b/cocos/2d/utils/font-loader.ts index d2550456ed..71d77ff2d1 100644 --- a/cocos/2d/utils/font-loader.ts +++ b/cocos/2d/utils/font-loader.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { warnID } from '../../core/platform/debug'; import { safeMeasureText } from './text-utils'; import { CompleteCallback, IDownloadParseOptions } from '../../core/asset-manager/shared'; diff --git a/cocos/2d/utils/html-text-parser.ts b/cocos/2d/utils/html-text-parser.ts index 23b3bec0d3..237f1b8842 100644 --- a/cocos/2d/utils/html-text-parser.ts +++ b/cocos/2d/utils/html-text-parser.ts @@ -28,19 +28,23 @@ import { TEST } from 'internal:constants'; import { legacyCC } from '../../core/global-exports'; /** - * + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ const eventRegx = /^(click)(\s)*=|(param)(\s)*=/; const imageAttrReg = /(\s)*src(\s)*=|(\s)*height(\s)*=|(\s)*width(\s)*=|(\s)*align(\s)*=|(\s)*offset(\s)*=|(\s)*click(\s)*=|(\s)*param(\s)*=/; + /** * A utils class for parsing HTML texts. The parsed results will be an object array. + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ - export interface IHtmlTextParserResultObj{ text?: string; style?: IHtmlTextParserStack; } +/** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ export interface IHtmlTextParserStack{ color?: string; size?: number; @@ -58,6 +62,9 @@ export interface IHtmlTextParserStack{ outline?: { color: string, width: number }; } +/** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ export class HtmlTextParser { private _specialSymbolArray: Array<[RegExp, string]> = []; private _stack: IHtmlTextParserStack[] = []; @@ -165,6 +172,7 @@ export class HtmlTextParser { header = /^(img(\s)*src(\s)*=[^>]+\/)/.exec(attribute); let remainingArgument = ''; + let rightQuot = -1; if (header && header[0].length > 0) { tagName = header[0].trim(); if (tagName.startsWith('img') && tagName[tagName.length - 1] === '/') { @@ -175,16 +183,24 @@ export class HtmlTextParser { // skip the invalid tags at first attribute = attribute.substring(attribute.indexOf(header[0])); tagName = attribute.substr(0, header[0].length); - // remove space and = character - remainingArgument = attribute.substring(tagName.length).trim(); - nextSpace = remainingArgument.indexOf(' '); - - tagValue = (nextSpace > -1) ? remainingArgument.substr(0, nextSpace) : remainingArgument; + const originTagNameLength = tagName.length; tagName = tagName.replace(/[^a-zA-Z]/g, '').trim(); tagName = tagName.toLowerCase(); + // remove space and = character + remainingArgument = attribute.substring(originTagNameLength).trim(); + if (tagName === 'src') { + rightQuot = this.getRightQuotationIndex(remainingArgument); + } else { + rightQuot = -1; + } + nextSpace = remainingArgument.indexOf(' ', rightQuot + 1 >= remainingArgument.length ? -1 : rightQuot + 1); + tagValue = (nextSpace > -1) ? remainingArgument.substr(0, nextSpace) : remainingArgument; attribute = remainingArgument.substring(nextSpace).trim(); - if (tagValue.endsWith('/')) tagValue = tagValue.slice(0, -1); + + if (tagValue.endsWith('/')) { + tagValue = tagValue.slice(0, -1); + } if (tagName === 'src') { switch (tagValue.charCodeAt(0)) { case 34: // " @@ -301,6 +317,27 @@ export class HtmlTextParser { return obj; } + // find the right part of the first pair of following quotations. + private getRightQuotationIndex (remainingArgument: string) { + let leftQuot = -1; + let rightQuot = -1; + // Skip a pair of quotations for avoiding spaces in image name are detected. + const leftSingleQuot = remainingArgument.indexOf('\''); + const leftDoubleQuot = remainingArgument.indexOf('"'); + + const useSingleQuot = leftSingleQuot > -1 && (leftSingleQuot < leftDoubleQuot || leftDoubleQuot === -1); + const useDoubleQuot = leftDoubleQuot > -1 && (leftDoubleQuot < leftSingleQuot || leftSingleQuot === -1); + if (useSingleQuot) { + leftQuot = leftSingleQuot; + rightQuot = remainingArgument.indexOf('\'', leftQuot + 1 >= remainingArgument.length ? -1 : leftQuot + 1); + } else if (useDoubleQuot) { + leftQuot = leftDoubleQuot; + rightQuot = remainingArgument.indexOf('"', leftQuot + 1 >= remainingArgument.length ? -1 : leftQuot + 1); + } + + return rightQuot; + } + private _processEventHandler (eventString: string) { const obj = {}; let index = 0; diff --git a/cocos/2d/utils/text-utils.ts b/cocos/2d/utils/text-utils.ts index 10b15a7561..6c2fe47d36 100644 --- a/cocos/2d/utils/text-utils.ts +++ b/cocos/2d/utils/text-utils.ts @@ -25,12 +25,30 @@ */ import { RUNTIME_BASED } from 'internal:constants'; +import { minigame } from 'pal/minigame'; import Pool from '../../core/utils/pool'; export const BASELINE_RATIO = 0.26; let _BASELINE_OFFSET = 0; + if (RUNTIME_BASED) { _BASELINE_OFFSET = BASELINE_RATIO * 2 / 3; + + const ral = minigame.ral!; + const featureAlphabeticeName = ral.CANVAS_CONTEXT2D_TEXTBASELINE_ALPHABETIC.name; + const featureAlphabeticEnable = ral.CANVAS_CONTEXT2D_TEXTBASELINE_ALPHABETIC.enable; + + const defaultBaselineName = ral.CANVAS_CONTEXT2D_TEXTBASELINE_DEFAULT.name; + const defaultIsAlphaBetic = ral.CANVAS_CONTEXT2D_TEXTBASELINE_DEFAULT.alphabetic; + + if (ral.getFeaturePropertyInt(featureAlphabeticeName) === featureAlphabeticEnable) { + // if support alphabetic baseline, set default baseline to alphabetic + ral.setFeaturePropertyInt(defaultBaselineName, defaultIsAlphaBetic); + if (ral.getFeaturePropertyInt(defaultBaselineName) === defaultIsAlphaBetic) { + // if default baseline has been successfully set to alphabetic, _BASELINE_OFFSET should be 0. + _BASELINE_OFFSET = 0; + } + } } export const MIDDLE_RATIO = (BASELINE_RATIO + 1) / 2 - BASELINE_RATIO; export function getBaselineOffset () { @@ -142,9 +160,9 @@ const measureCache = new LRUCache(MAX_CACHE_SIZE); const WORD_REG = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûа-яА-ЯЁё]+|\S)/; // eslint-disable-next-line no-useless-escape const SYMBOL_REG = /^[!,.:;'}\]%\?>、‘“》?。,!]/; -const LAST_WORD_REG = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]+|\S)$/; -const LAST_ENGLISH_REG = /[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]+$/; -const FIRST_ENGLISH_REG = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁё]/; +const LAST_WORD_REG = /([a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁёáàảạãăắằẳẵặâấầẩẫậéèẻẽẹêếềểễệiíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵđÁÀẢẠÃĂẮẰẲẴẶÂẤẦẨẪẬÉÈẺẼẸÊẾỀỂỄỆIÍÌỈĨỊÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰÝỲỶỸỴĐ]+|\S)$/; +const LAST_ENGLISH_REG = /[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁёáàảạãăắằẳẵặâấầẩẫậéèẻẽẹêếềểễệiíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵđÁÀẢẠÃĂẮẰẲẴẶÂẤẦẨẪẬÉÈẺẼẸÊẾỀỂỄỆIÍÌỈĨỊÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰÝỲỶỸỴĐ]+$/; +const FIRST_ENGLISH_REG = /^[a-zA-Z0-9ÄÖÜäöüßéèçàùêâîôûаíìÍÌïÁÀáàÉÈÒÓòóŐőÙÚŰúűñÑæÆœŒÃÂãÔõěščřžýáíéóúůťďňĚŠČŘŽÁÍÉÓÚŤżźśóńłęćąŻŹŚÓŃŁĘĆĄ-яА-ЯЁёáàảạãăắằẳẵặâấầẩẫậéèẻẽẹêếềểễệiíìỉĩịóòỏõọôốồổỗộơớờởỡợúùủũụưứừửữựýỳỷỹỵđÁÀẢẠÃĂẮẰẲẴẶÂẤẦẨẪẬÉÈẺẼẸÊẾỀỂỄỆIÍÌỈĨỊÓÒỎÕỌÔỐỒỔỖỘƠỚỜỞỠỢÚÙỦŨỤƯỨỪỬỮỰÝỲỶỸỴĐ]/; const WRAP_INSPECTION = true; // The unicode standard will never assign a character from code point 0xD800 to 0xDFFF // high surrogate (0xD800-0xDBFF) and low surrogate(0xDC00-0xDFFF) combines to a character on the Supplementary Multilingual Plane diff --git a/cocos/3d/assets/index.ts b/cocos/3d/assets/index.ts index bcf222903b..233c1d6ce2 100644 --- a/cocos/3d/assets/index.ts +++ b/cocos/3d/assets/index.ts @@ -28,3 +28,4 @@ import './deprecated'; export { Mesh } from './mesh'; export { Skeleton } from './skeleton'; +export type { Morph, MorphTarget, SubMeshMorph } from './morph'; diff --git a/cocos/3d/assets/mesh.jsb.ts b/cocos/3d/assets/mesh.jsb.ts index 98bd979074..a286755e50 100644 --- a/cocos/3d/assets/mesh.jsb.ts +++ b/cocos/3d/assets/mesh.jsb.ts @@ -23,8 +23,8 @@ THE SOFTWARE. */ import { ccclass, serializable } from 'cc.decorator'; -import { _applyDecoratedDescriptor } from '../../core/data/utils/decorator-jsb-utils'; import { legacyCC } from '../../core/global-exports'; +import '../../core/assets/asset'; export declare namespace Mesh { export interface IBufferView { @@ -46,35 +46,10 @@ export const Mesh = jsb.Mesh; const meshAssetProto: any = jsb.Mesh.prototype; meshAssetProto.createNode = null!; - -const clsDecorator = ccclass('cc.Mesh'); - -const _class2$V = Mesh; - -const _descriptor$M = _applyDecoratedDescriptor(_class2$V.prototype, '_struct', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return { - vertexBundles: [], - primitives: [], - }; - }, -}); -const _descriptor2$y = _applyDecoratedDescriptor(_class2$V.prototype, '_hash', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return 0; - }, -}); +const originOnLoaded = meshAssetProto.onLoaded; meshAssetProto._ctor = function () { jsb.Asset.prototype._ctor.apply(this, arguments); - // _initializerDefineProperty(_this, "_struct", _descriptor$M, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, "_hash", _descriptor2$y, _assertThisInitialized(_this)); this._struct = { vertexBundles: [], primitives: [], @@ -90,11 +65,20 @@ Object.defineProperty(meshAssetProto, 'struct', { }); meshAssetProto.onLoaded = function () { - this.setStruct(this._struct); + // might be undefined + if (this._struct != undefined) { + this.setStruct(this._struct); + } // Set to null to release memory in JS this._struct = null; + originOnLoaded.apply(this); }; -clsDecorator(Mesh); - legacyCC.Mesh = jsb.Mesh; + +// handle meta data, it is generated automatically +const MeshProto = Mesh.prototype; +serializable(MeshProto, '_struct'); +serializable(MeshProto, '_hash'); +serializable(MeshProto, '_allowDataAccess'); +ccclass('cc.Mesh')(Mesh); diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 4c854197b4..a95f072c2b 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { ccclass, serializable } from 'cc.decorator'; import { Asset } from '../../core/assets/asset'; import { IDynamicGeometry } from '../../primitive/define'; @@ -42,10 +37,11 @@ import { warnID } from '../../core/platform/debug'; import { RenderingSubMesh } from '../../core/assets'; import { Attribute, Device, Buffer, BufferInfo, AttributeName, BufferUsageBit, Feature, Format, - FormatInfos, FormatType, MemoryUsageBit, PrimitiveMode, getTypedArrayConstructor, DrawInfo, + FormatInfos, FormatType, MemoryUsageBit, PrimitiveMode, getTypedArrayConstructor, DrawInfo, FormatInfo, deviceManager, } from '../../core/gfx'; import { Mat4, Quat, Vec3 } from '../../core/math'; -import { Morph, MorphRendering, createMorphRendering } from './morph'; +import { Morph } from './morph'; +import { MorphRendering, createMorphRendering } from './morph-rendering'; function getIndexStrideCtor (stride: number) { switch (stride) { @@ -73,6 +69,7 @@ export declare namespace Mesh { /** * @en The actual value for all vertex attributes. * You must use DataView to access the data. + * Because there is no guarantee that the starting offsets of all properties are byte aligned as required by TypedArray. * @zh 所有顶点属性的实际数据块。 * 你必须使用 DataView 来读取数据。 * 因为不能保证所有属性的起始偏移都按 TypedArray 要求的字节对齐。 @@ -117,6 +114,10 @@ export declare namespace Mesh { jointMapIndex?: number; } + /** + * @en dynamic info used to create dyanmic mesh + * @zh 动态信息,用于创建动态网格 + */ export interface IDynamicInfo { /** * @en max submesh count @@ -137,6 +138,10 @@ export declare namespace Mesh { maxSubMeshIndices: number; } + /** + * @en dynamic struct + * @zh 动态结构体 + */ export interface IDynamicStruct { /** * @en dynamic mesh info @@ -200,6 +205,10 @@ export declare namespace Mesh { dynamic?: IDynamicStruct; } + /** + * @en The create info of the mesh + * @zh 网格创建信息 + */ export interface ICreateInfo { /** * @en Mesh structure @@ -220,13 +229,15 @@ const v3_2 = new Vec3(); const globalEmptyMeshBuffer = new Uint8Array(); /** - * @en Mesh asset - * @zh 网格资源。 + * @en A representation of a mesh asset + * A mesh can contain multiple sub-mesh resources. The mesh mainly provides data such as vertices and indices for model instances. + * @zh 代表一个网格资源 + * 一个网格可包含多个子网格资源,网格主要为模型实例提供顶点,索引等数据 */ @ccclass('cc.Mesh') export class Mesh extends Asset { /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ get _nativeAsset (): ArrayBuffer { return this._data.buffer; @@ -290,7 +301,8 @@ export class Mesh extends Asset { } /** - * The index of the joint buffer of all sub meshes in the joint map buffers + * @en The index of the joint buffer of all sub meshes in the joint map buffers + * @zh 所有子网格的关节索引集合 */ get jointBufferIndices () { if (this._jointBufferIndices) { return this._jointBufferIndices; } @@ -306,6 +318,10 @@ export class Mesh extends Asset { return this._renderingSubMeshes!; } + /** + * @en morph rendering data + * @zh 变形渲染数据 + */ public morphRendering: MorphRendering | null = null; @serializable @@ -321,6 +337,11 @@ export class Mesh extends Asset { private _initialized = false; + @serializable + private _allowDataAccess = true; + + private _isMeshDataUploaded = false; + private _renderingSubMeshes: RenderingSubMesh[] | null = null; private _boneSpaceBounds: Map = new Map(); @@ -331,10 +352,18 @@ export class Mesh extends Asset { super(); } + /** + * @en complete loading callback + * @zh 加载完成回调 + */ public onLoaded () { this.initialize(); } + /** + * @en mesh init + * @zh 网格初始化函数 + */ public initialize () { if (this._initialized) { return; @@ -343,10 +372,10 @@ export class Mesh extends Asset { this._initialized = true; if (this._struct.dynamic) { - const device: Device = legacyCC.director.root.device; + const device: Device = deviceManager.gfxDevice; const vertexBuffers: Buffer[] = []; const subMeshes: RenderingSubMesh[] = []; - + for (let i = 0; i < this._struct.vertexBundles.length; i++) { const vertexBundle = this._struct.vertexBundles[i]; const vertexBuffer = device.createBuffer(new BufferInfo( @@ -355,15 +384,15 @@ export class Mesh extends Asset { vertexBundle.view.length, vertexBundle.view.stride, )); - + vertexBuffers.push(vertexBuffer); } - + for (let i = 0; i < this._struct.primitives.length; i++) { const primitive = this._struct.primitives[i]; const indexView = primitive.indexView; let indexBuffer: Buffer | null = null; - + if (indexView) { indexBuffer = device.createBuffer(new BufferInfo( BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, @@ -372,13 +401,13 @@ export class Mesh extends Asset { indexView.stride, )); } - + const subVBs: Buffer[] = []; for (let k = 0; k < primitive.vertexBundelIndices.length; k++) { const idx = primitive.vertexBundelIndices[k]; subVBs.push(vertexBuffers[idx]); } - + const attributes: Attribute[] = []; for (let k = 0; k < primitive.vertexBundelIndices.length; k++) { const idx = primitive.vertexBundelIndices[k]; @@ -389,34 +418,34 @@ export class Mesh extends Asset { attributes.push(attribute); } } - + const subMesh = new RenderingSubMesh(subVBs, attributes, primitive.primitiveMode, indexBuffer); subMesh.drawInfo = new DrawInfo(); subMesh.mesh = this; subMesh.subMeshIdx = i; - + subMeshes.push(subMesh); } - + this._renderingSubMeshes = subMeshes; } else { const { buffer } = this._data; - const gfxDevice: Device = legacyCC.director.root.device; + const gfxDevice: Device = deviceManager.gfxDevice; const vertexBuffers = this._createVertexBuffers(gfxDevice, buffer); const indexBuffers: Buffer[] = []; const subMeshes: RenderingSubMesh[] = []; - + for (let i = 0; i < this._struct.primitives.length; i++) { const prim = this._struct.primitives[i]; if (prim.vertexBundelIndices.length === 0) { continue; } - + let indexBuffer: Buffer | null = null; let ib: any = null; if (prim.indexView) { const idxView = prim.indexView; - + let dstStride = idxView.stride; let dstSize = idxView.length; if (dstStride === 4 && !gfxDevice.hasFeature(Feature.ELEMENT_INDEX_UINT)) { @@ -429,7 +458,7 @@ export class Mesh extends Asset { dstSize >>= 1; } } - + indexBuffer = gfxDevice.createBuffer(new BufferInfo( BufferUsageBit.INDEX, MemoryUsageBit.DEVICE, @@ -437,16 +466,16 @@ export class Mesh extends Asset { dstStride, )); indexBuffers.push(indexBuffer); - + ib = new (getIndexStrideCtor(idxView.stride))(buffer, idxView.offset, idxView.count); if (idxView.stride !== dstStride) { ib = getIndexStrideCtor(dstStride).from(ib); } indexBuffer.update(ib); } - + const vbReference = prim.vertexBundelIndices.map((idx) => vertexBuffers[idx]); - + const gfxAttributes: Attribute[] = []; if (prim.vertexBundelIndices.length > 0) { const idx = prim.vertexBundelIndices[0]; @@ -457,26 +486,31 @@ export class Mesh extends Asset { gfxAttributes[j] = new Attribute(attr.name, attr.format, attr.isNormalized, attr.stream, attr.isInstanced, attr.location); } } - + const subMesh = new RenderingSubMesh(vbReference, gfxAttributes, prim.primitiveMode, indexBuffer); subMesh.mesh = this; subMesh.subMeshIdx = i; - + subMeshes.push(subMesh); } - + this._renderingSubMeshes = subMeshes; - + if (this._struct.morph) { this.morphRendering = createMorphRendering(this, gfxDevice); } - } + + this._isMeshDataUploaded = true; + if (!this._allowDataAccess) { + this.releaseData(); + } + } } /** * @en update dynamic sub mesh geometry * @zh 更新动态子网格的几何数据 - * @param primitiveIndex: sub mesh index - * @param geometry: sub mesh geometry data + * @param primitiveIndex @en sub mesh index @zh 子网格索引 + * @param geometry @en sub mesh geometry data @zh 子网格几何数据 */ public updateSubMesh (primitiveIndex: number, geometry: IDynamicGeometry) { if (!this._struct.dynamic) { @@ -611,14 +645,15 @@ export class Mesh extends Asset { } this._renderingSubMeshes = null; this._initialized = false; + this._isMeshDataUploaded = false; } } /** * @en Reset the struct and data of the mesh * @zh 重置此网格的结构和数据。 - * @param struct The new struct - * @param data The new data + * @param struct @en The new struct @zh 新结构 + * @param data @en The new data @zh 新数据 * @deprecated Will be removed in v3.0.0, please use [[reset]] instead */ public assign (struct: Mesh.IStruct, data: Uint8Array) { @@ -631,7 +666,7 @@ export class Mesh extends Asset { /** * @en Reset the mesh with mesh creation information * @zh 重置此网格。 - * @param info Mesh creation information including struct and data + * @param info @en Mesh creation information including struct and data @zh 网格创建信息,包含结构及数据 */ public reset (info: Mesh.ICreateInfo) { this.destroyRenderingMesh(); @@ -641,9 +676,10 @@ export class Mesh extends Asset { } /** - * @en Get [[AABB]] bounds in the skeleton's bone space - * @zh 获取骨骼变换空间内下的 [[AABB]] 包围盒 - * @param skeleton + * @en Get [[geometry.AABB]] bounds in the skeleton's bone space + * @zh 获取骨骼变换空间内下的 [[geometry.AABB]] 包围盒 + * @param skeleton @en skeleton data @zh 骨骼信息 + * @param skeleton @en skeleton data @zh 骨骼信息 */ public getBoneSpaceBounds (skeleton: Skeleton) { if (this._boneSpaceBounds.has(skeleton.hash)) { @@ -688,10 +724,10 @@ export class Mesh extends Asset { /** * @en Merge the given mesh into the current mesh * @zh 合并指定的网格到此网格中。 - * @param mesh The mesh to be merged - * @param worldMatrix The world matrix of the given mesh - * @param [validate=false] Whether to validate the mesh - * @returns Check the mesh state and return the validation result. + * @param mesh @en The mesh to be merged @zh 要合并的网格 + * @param worldMatrix @en The world matrix of the given mesh @zh 给定网格的模型变换矩阵 + * @param validate @en Whether to validate the mesh @zh 是否验证网格顶点布局 + * @returns @en whether the merging was successful or not @zh 返回合并成功与否 */ public merge (mesh: Mesh, worldMatrix?: Mat4, validate?: boolean): boolean { if (validate) { @@ -1003,7 +1039,7 @@ export class Mesh extends Asset { * 两个子网格布局一致,当且仅当: * - 它们具有相同的图元类型并且引用相同数量、相同索引的顶点块;并且, * - 要么都需要索引绘制,要么都不需要索引绘制。 - * @param mesh The other mesh to be validated + * @param mesh @en The other mesh to be validated @zh 待验证的网格 */ public validateMergingMesh (mesh: Mesh) { // dynamic mesh is not allowed to merge. @@ -1064,10 +1100,10 @@ export class Mesh extends Asset { /** * @en Read the requested attribute of the given sub mesh * @zh 读取子网格的指定属性。 - * @param primitiveIndex Sub mesh index - * @param attributeName Attribute name - * @returns Return null if not found or can't read, otherwise, will create a large enough typed array to contain all data of the attribute, - * the array type will match the data type of the attribute. + * @param primitiveIndex @en Sub mesh index @zh 子网格索引 + * @param attributeName @en Attribute name @zh 属性名称 + * @returns @en Return null if not found or can't read, otherwise, will create a large enough typed array to contain all data of the attribute, + * the array type will match the data type of the attribute. @zh 读取失败返回 null, 否则返回对应的类型数组 */ public readAttribute (primitiveIndex: number, attributeName: AttributeName): TypedArray | null { let result: TypedArray | null = null; @@ -1105,12 +1141,12 @@ export class Mesh extends Asset { /** * @en Read the requested attribute of the given sub mesh and fill into the given buffer. * @zh 读取子网格的指定属性到目标缓冲区中。 - * @param primitiveIndex Sub mesh index - * @param attributeName Attribute name - * @param buffer The target array buffer - * @param stride Byte distance between two attributes in the target buffer - * @param offset The offset of the first attribute in the target buffer - * @returns Return false if failed to access attribute, return true otherwise. + * @param primitiveIndex @en Sub mesh index @zh 子网格索引 + * @param attributeName @en Attribute name @zh 属性名称 + * @param buffer @en The target array buffer @zh 目标缓冲区 + * @param stride @en attribute stride @zh 属性跨距 + * @param offset @en The offset of the first attribute in the target buffer @zh 第一个属性在目标缓冲区的偏移 + * @returns @en false if failed to access attribute, true otherwise @zh 是否成功拷贝 */ public copyAttribute (primitiveIndex: number, attributeName: AttributeName, buffer: ArrayBuffer, stride: number, offset: number) { let written = false; @@ -1158,9 +1194,9 @@ export class Mesh extends Asset { /** * @en Read the indices data of the given sub mesh * @zh 读取子网格的索引数据。 - * @param primitiveIndex Sub mesh index - * @returns Return null if not found or can't read, otherwise, will create a large enough typed array to contain all indices data, - * the array type will use the corresponding stride size. + * @param primitiveIndex @en Sub mesh index @zh 子网格索引 + * @returns @en Return null if not found or can't read, otherwise, will create a large enough typed array to contain all indices data, + * the array type will use the corresponding stride size. @zh 读取失败返回 null,否则返回索引数据 */ public readIndices (primitiveIndex: number) { if (primitiveIndex >= this._struct.primitives.length) { @@ -1178,9 +1214,9 @@ export class Mesh extends Asset { /** * @en Read the indices data of the given sub mesh and fill into the given array * @zh 读取子网格的索引数据到目标数组中。 - * @param primitiveIndex Sub mesh index - * @param outputArray The target output array - * @returns Return false if failed to access the indices data, return true otherwise. + * @param primitiveIndex @en Sub mesh index @zh 子网格索引 + * @param outputArray @en The target output array @zh 目标索引数组 + * @returns @en Return false if failed to access the indices data, return true otherwise. @zh 拷贝失败返回 false, 否则返回 true */ public copyIndices (primitiveIndex: number, outputArray: number[] | ArrayBufferView): boolean { if (primitiveIndex >= this._struct.primitives.length) { @@ -1199,6 +1235,24 @@ export class Mesh extends Asset { return true; } + /** + * @en Read the format by attributeName of submesh + * @zh 根据属性名读取子网格的属性信息。 + * @param primitiveIndex @en Sub mesh index @zh 子网格索引 + * @param attributeName @en Attribute name @zh 属性名称 + * @returns @en Return null if failed to read format, return the format otherwise. @zh 读取失败返回 null, 否则返回 format + */ + public readAttributeFormat (primitiveIndex: number, attributeName: AttributeName): FormatInfo | null { + let result: FormatInfo | null = null; + + this._accessAttribute(primitiveIndex, attributeName, (vertexBundle, iAttribute) => { + const format = vertexBundle.attributes[iAttribute].format; + result = FormatInfos[format]; + }); + + return result; + } + private _accessAttribute ( primitiveIndex: number, attributeName: AttributeName, @@ -1234,6 +1288,11 @@ export class Mesh extends Asset { }); } + /** + * @en default init + * @zh 默认初始化 + * @param uuid @en asset uuid @zh 资源 uuid + */ public initDefault (uuid?: string) { super.initDefault(uuid); this.reset({ @@ -1244,6 +1303,31 @@ export class Mesh extends Asset { data: globalEmptyMeshBuffer, }); } + + /** + * @en Set whether the data of this mesh could be accessed (read or wrote), it could be used only for static mesh + * @zh 设置此网格的数据是否可被存取,此接口只针对静态网格资源生效 + * @param allowDataAccess @en Indicate whether the data of this mesh could be accessed (read or wrote) @zh 是否允许存取网格数据 + */ + public set allowDataAccess (allowDataAccess: boolean) { + this._allowDataAccess = allowDataAccess; + if (this._isMeshDataUploaded && !this._allowDataAccess) { + this.releaseData(); + } + } + + /** + * @en Get whether the data of this mesh could be read or wrote + * @zh 获取此网格的数据是否可被存取 + * @return @en whether the data of this mesh could be accessed (read or wrote) @zh 此网格的数据是否可被存取 + */ + public get allowDataAccess () { + return this._allowDataAccess; + } + + private releaseData () { + this._data = globalEmptyMeshBuffer; + } } legacyCC.Mesh = Mesh; diff --git a/cocos/3d/assets/morph-rendering.ts b/cocos/3d/assets/morph-rendering.ts index c0c4852bfc..0a87f7cc6b 100644 --- a/cocos/3d/assets/morph-rendering.ts +++ b/cocos/3d/assets/morph-rendering.ts @@ -23,11 +23,8 @@ THE SOFTWARE. */ - - import { - AttributeName, Buffer, BufferUsageBit, Device, Feature, MemoryUsageBit, DescriptorSet, BufferInfo, - FormatFeatureBit, Format, + AttributeName, Buffer, BufferUsageBit, Device, MemoryUsageBit, DescriptorSet, BufferInfo, FormatFeatureBit, Format, } from '../../core/gfx'; import { Mesh } from './mesh'; import { Texture2D } from '../../core/assets/texture-2d'; @@ -35,7 +32,7 @@ import { ImageAsset } from '../../core/assets/image-asset'; import { UBOMorph, UNIFORM_NORMAL_MORPH_TEXTURE_BINDING, UNIFORM_POSITION_MORPH_TEXTURE_BINDING, UNIFORM_TANGENT_MORPH_TEXTURE_BINDING } from '../../core/pipeline/define'; import { warn } from '../../core/platform/debug'; -import { Morph, MorphRendering, MorphRenderingInstance, SubMeshMorph } from './morph'; +import { Morph, SubMeshMorph } from './morph'; import { assertIsNonNullable, assertIsTrue } from '../../core/data/utils/asserts'; import { log2, nextPow2 } from '../../core/math/bits'; import { IMacroPatch } from '../../core/renderer'; @@ -44,13 +41,67 @@ import { PixelFormat } from '../../core/assets/asset-enum'; /** * True if force to use cpu computing based sub-mesh rendering. + * Only customizable by modify the internal engine code. */ const preferCpuComputing = false; /** - * Standard morph rendering. - * The standard morph rendering renders each of sub-mesh morph separately. - * Sub-mesh morph rendering may select different technique according sub-mesh morph itself. + * @en Interface for classes which control the rendering of morph resources. + * @zh 支持形变网格渲染的基类。 + */ +export interface MorphRendering { + createInstance (): MorphRenderingInstance; +} + +/** + * @en The instance of [[MorphRendering]] for dedicated control in the mesh renderer. + * The root [[MorphRendering]] is owned by [[Mesh]] asset, each [[MeshRenderer]] can have its own morph rendering instance. + * @zh 用于网格渲染器中独立控制 [[MorphRendering]] 的实例。原始 [[MorphRendering]] 被 [[Mesh]] 资源持有,每个 [[MeshRenderer]] 都持有自己的形变网格渲染实例。 + */ +export interface MorphRenderingInstance { + /** + * Sets weights of targets of specified sub mesh. + * @param subMeshIndex + * @param weights + */ + setWeights (subMeshIndex: number, weights: number[]): void; + + /** + * Adapts pipeline state to do the rendering. + * @param subMeshIndex + * @param pipelineState + */ + adaptPipelineState (subMeshIndex: number, descriptorSet: DescriptorSet): void; + + /** + * Acquire the define overrides needed to do the rendering. + */ + requiredPatches (subMeshIndex: number): IMacroPatch[] | null; + + /** + * Destroy the rendering instance. + */ + destroy (): void; +} + +/** + * @en Create morph rendering from mesh which contains morph targets data. + * @zh 从包含形变对象的网格资源中创建形变网格渲染对象。 + * @param mesh @en The mesh to create morph rendering from. @zh 用于创建形变网格渲染对象的原始网格资源。 + * @param gfxDevice @en The device instance acquired from [[Root]]. @zh 设备对象实例,可以从 [[Root]] 获取。 + */ +export function createMorphRendering (mesh: Mesh, gfxDevice: Device): MorphRendering { + return new StdMorphRendering(mesh, gfxDevice); +} + +/** + * @en Standard morph rendering class, it supports both GPU and CPU based morph blending. + * If sub mesh morph targets count is less than [[pipeline.UBOMorph.MAX_MORPH_TARGET_COUNT]], then GPU based blending is enabled. + * Each of the sub-mesh morph has its own [[MorphRenderingInstance]], + * its morph target weights, render pipeline state and strategy of morph blending are controlled separately. + * @zh 标准形变网格渲染类,它同时支持 CPU 和 GPU 的形变混合计算。 + * 如果子网格形变目标数量少于 [[pipeline.UBOMorph.MAX_MORPH_TARGET_COUNT]],那么就会使用基于 GPU 的形变混合计算。 + * 每个子网格形变都使用自己独立的 [[MorphRenderingInstance]],它的形变目标权重、渲染管线状态和形变混合计算策略都是独立控制的。 */ export class StdMorphRendering implements MorphRendering { private _mesh: Mesh; @@ -138,7 +189,8 @@ export class StdMorphRendering implements MorphRendering { } /** - * Describes how to render a sub-mesh morph. + * @en Sub-mesh morph rendering describes how to render a sub-mesh morph. + * @zh 子网格形变渲染定义如何渲染一个子网格形变。 */ interface SubMeshMorphRendering { /** @@ -148,7 +200,9 @@ interface SubMeshMorphRendering { } /** - * The instance of once sub-mesh morph rendering. + * @en The instance of sub-mesh morph rendering, each sub-mesh have its own instance + * for controlling its morph target weights, render pipeline state and strategy of morph blending. + * @zh 子网格形变渲染的实例,每个子网格都拥有自己独立的子网格形变渲染实例,用于独立控制形变目标权重、渲染管线状态和形变混合计算策略。 */ interface SubMeshMorphRenderingInstance { /** @@ -467,11 +521,6 @@ class MorphUniforms { } } -/** - * - * @param gfxDevice - * @param vec4Capacity Capacity of vec4. - */ function createVec4TextureFactory (gfxDevice: Device, vec4Capacity: number) { const hasFeatureFloatTexture = gfxDevice.getFormatFeatures(Format.RGBA32F) & FormatFeatureBit.SAMPLED_TEXTURE; @@ -563,12 +612,8 @@ function createVec4TextureFactory (gfxDevice: Device, vec4Capacity: number) { type MorphTexture = ReturnType['create']>; /** - * When use vertex-texture-fetch technique, we do need - * `gl_vertexId` when we sample per-vertex data. + * When use vertex-texture-fetch technique, we do need `gl_vertexId` when we sample per-vertex data. * WebGL 1.0 does not have `gl_vertexId`; WebGL 2.0, however, does. - * @param mesh - * @param subMeshIndex - * @param gfxDevice */ function enableVertexId (mesh: Mesh, subMeshIndex: number, gfxDevice: Device) { mesh.renderingSubMeshes[subMeshIndex].enableVertexIdChannel(gfxDevice); diff --git a/cocos/3d/assets/morph.ts b/cocos/3d/assets/morph.ts index 7611da99af..9ba9877fca 100644 --- a/cocos/3d/assets/morph.ts +++ b/cocos/3d/assets/morph.ts @@ -23,31 +23,13 @@ THE SOFTWARE. */ - - -import { AttributeName, Device, DescriptorSet } from '../../core/gfx'; +import { AttributeName } from '../../core/gfx'; import { Mesh } from './mesh'; -import { StdMorphRendering } from './morph-rendering'; -import { IMacroPatch } from '../../core/renderer'; - -export interface Morph { - /** - * Morph data of each sub-mesh. - */ - subMeshMorphs: (SubMeshMorph | null)[]; - - /** - * Common initial weights of each sub-mesh. - */ - weights?: number[]; - - /** - * Name of each target of each sub-mesh morph. - * This field is only meaningful if every sub-mesh has the same number of targets. - */ - targetNames?: string[]; -} +/** + * @en Morph target contains all displacements data of each vertex attribute like position and normal. + * @zh 形变目标数据包含网格顶点属性在形变下的变化值,可能包含位移、法线等属性 + */ export interface MorphTarget { /** * Displacement of each target attribute. @@ -55,6 +37,11 @@ export interface MorphTarget { displacements: Mesh.IBufferView[]; } +/** + * @en Sub mesh morph data describes all morph targets for one sub mesh, + * including attributes in each morph target, morph targets data and weights corresponding each targets. + * @zh 子网格形变数据描述一个子网格下所有的形变目标数据,包含顶点形变属性,形变目标数据和对应每个形变目标的权重。 + */ export interface SubMeshMorph { /** * Attributes to morph. @@ -72,39 +59,28 @@ export interface SubMeshMorph { weights?: number[]; } -export function createMorphRendering (mesh: Mesh, gfxDevice: Device): MorphRendering | null { - return new StdMorphRendering(mesh, gfxDevice); -} - /** - * Class which control rendering of a morph resource. + * @en Mesh morph data structure to describe the sub meshes data of all sub meshes, + * it also contains all sub mesh morphs, global weights configuration and target names. + * Normally the global weights configuration should be identical to the sub mesh morph weights, + * but if not, the global weights in morph is less prioritized. + * @zh 网格的形变数据结构,包含所有子网格形变数据,全局的权重配置和所有形变目标名称。 + * 一般来说,全局权重配置和子网格形变数据中保持一致,但如果有差异,以子网格形变数据中的权重配置为准。 */ -export interface MorphRendering { - createInstance (): MorphRenderingInstance; -} - -/** - * This rendering instance of a morph resource. - */ -export interface MorphRenderingInstance { - /** - * Sets weights of targets of specified sub mesh. - * @param subMeshIndex - * @param weights - */ - setWeights (subMeshIndex: number, weights: number[]): void; - - /** - * Adapts pipeline state to do the rendering. - * @param subMeshIndex - * @param pipelineState - */ - adaptPipelineState (subMeshIndex: number, descriptorSet: DescriptorSet): void; - - requiredPatches (subMeshIndex: number): IMacroPatch[] | null; - - /** - * Destroy the rendering instance. - */ - destroy (): void; +export interface Morph { + /** + * Morph data of each sub-mesh. + */ + subMeshMorphs: (SubMeshMorph | null)[]; + + /** + * Common initial weights of each sub-mesh. + */ + weights?: number[]; + + /** + * Name of each target of each sub-mesh morph. + * This field is only meaningful if every sub-mesh has the same number of targets. + */ + targetNames?: string[]; } diff --git a/cocos/3d/assets/skeleton.jsb.ts b/cocos/3d/assets/skeleton.jsb.ts index f6dd8dc5b7..6a165f9340 100644 --- a/cocos/3d/assets/skeleton.jsb.ts +++ b/cocos/3d/assets/skeleton.jsb.ts @@ -23,26 +23,18 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { ccclass, type, serializable } from 'cc.decorator'; import { CCString } from '../../core/data/utils/attribute'; import { Mat4 } from '../../core/math'; import { DataPoolManager } from '../skeletal-animation/data-pool-manager'; import { Asset } from '../../core/assets/asset'; import { legacyCC } from '../../core/global-exports'; -import { _applyDecoratedDescriptor } from '../../core/data/utils/decorator-jsb-utils'; export const Skeleton = jsb.Skeleton; export type Skeleton = jsb.Skeleton; legacyCC.Skeleton = Skeleton; const skeletonProto: any = Skeleton.prototype; -const skeletonDecorator = ccclass('cc.Skeleton'); - Object.defineProperty(skeletonProto, 'bindposes', { enumerable: true, configurable: true, @@ -55,35 +47,6 @@ Object.defineProperty(skeletonProto, 'bindposes', { }, }); -const _dec2$1 = type([CCString]); -const _dec3$1 = type([Mat4]); - -const _descriptor$2 = _applyDecoratedDescriptor(skeletonProto, '_joints', [_dec2$1], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return []; - }, -}); - -const _descriptor2$2 = _applyDecoratedDescriptor(skeletonProto, '_bindposes', [_dec3$1], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return []; - }, -}); - -const _descriptor3$1 = _applyDecoratedDescriptor(skeletonProto, '_hash', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return 0; - }, -}); skeletonProto._ctor = function () { jsb.Asset.prototype._ctor.apply(this, arguments); @@ -101,4 +64,9 @@ skeletonProto.onLoaded = function () { oldSkeletonProtoOnLoaded.call(this); }; -skeletonDecorator(Skeleton); +// handle meta data, it is generated automatically +const SkeletonProto = Skeleton.prototype; +type([CCString])(SkeletonProto, '_joints'); +type([Mat4])(SkeletonProto, '_bindposes'); +serializable(SkeletonProto, '_hash'); +ccclass('cc.Skeleton')(Skeleton); \ No newline at end of file diff --git a/cocos/3d/assets/skeleton.ts b/cocos/3d/assets/skeleton.ts index 39871a6c1f..fea8cbe7fa 100644 --- a/cocos/3d/assets/skeleton.ts +++ b/cocos/3d/assets/skeleton.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { ccclass, type, serializable } from 'cc.decorator'; import { CCString } from '../../core/data/utils/attribute'; import { Mat4 } from '../../core/math'; @@ -119,6 +114,11 @@ export class Skeleton extends Asset { return super.destroy(); } + /** + * @en Check whether the skeleton is validate which means it has both joints and bindposes data. + * @zh 检查当前骨骼对象是否是有效的,取决于它是否包含关节路径和绑定姿势数据。 + * @returns @en Whether the skeleton is valid or not @zh 此骨骼是否有效 + */ public validate () { return this.joints.length > 0 && this.bindposes.length > 0; } diff --git a/cocos/3d/category.json b/cocos/3d/category.json new file mode 100644 index 0000000000..3772ae52dc --- /dev/null +++ b/cocos/3d/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "3D 渲染", + "en": "3D Rendering" + }, + "description": { + "zh": "3D 渲染相关的组件与资源", + "en": "3D rendering related components and assets" + } +} \ No newline at end of file diff --git a/cocos/3d/framework/deprecated.ts b/cocos/3d/framework/deprecated.ts index 6f98e29d77..dcc249d860 100644 --- a/cocos/3d/framework/deprecated.ts +++ b/cocos/3d/framework/deprecated.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component - */ - import { removeProperty } from '../../core/utils'; import { MeshRenderer } from './mesh-renderer'; import { js } from '../../core/utils/js'; diff --git a/cocos/3d/framework/index.ts b/cocos/3d/framework/index.ts index 54f2f58f38..dc20bfbf3d 100644 --- a/cocos/3d/framework/index.ts +++ b/cocos/3d/framework/index.ts @@ -24,7 +24,6 @@ THE SOFTWARE. */ - export { MeshRenderer } from './mesh-renderer'; /** deprecated */ diff --git a/cocos/3d/framework/mesh-renderer.ts b/cocos/3d/framework/mesh-renderer.ts index d74bf31f8e..939f7440e0 100644 --- a/cocos/3d/framework/mesh-renderer.ts +++ b/cocos/3d/framework/mesh-renderer.ts @@ -23,13 +23,9 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module model - */ - import { ccclass, help, executeInEditMode, executionOrder, menu, tooltip, visible, type, formerlySerializedAs, serializable, editable, disallowAnimation } from 'cc.decorator'; +import { JSB } from 'internal:constants'; import { Texture2D } from '../../core/assets'; import { Material } from '../../core/assets/material'; import { Mesh } from '../assets/mesh'; @@ -40,8 +36,8 @@ import { Root } from '../../core/root'; import { TransformBit } from '../../core/scene-graph/node-enum'; import { Enum } from '../../core/value-types'; import { builtinResMgr } from '../../core/builtin'; -import { RenderableComponent } from '../../core/components/renderable-component'; -import { MorphRenderingInstance } from '../assets/morph'; +import { ModelRenderer } from '../../core/components/model-renderer'; +import { MorphRenderingInstance } from '../assets/morph-rendering'; import { legacyCC } from '../../core/global-exports'; import { assertIsTrue } from '../../core/data/utils/asserts'; import { CCFloat } from '../../core/data/utils/attribute'; @@ -70,19 +66,19 @@ const ModelShadowCastingMode = Enum({ */ const ModelShadowReceivingMode = Enum({ /** - * @en Disable shadow projection. + * @en Disable shadow receiving. * @zh 不接收阴影。 */ OFF: 0, /** - * @en Enable shadow projection. + * @en Enable shadow receiving. * @zh 开启阴影投射。 */ ON: 1, }); /** - * @en model light map settings. + * @en Model's light map settings. * @zh 模型光照图设置 */ @ccclass('cc.ModelLightmapSettings') @@ -101,8 +97,10 @@ class ModelLightmapSettings { protected _lightmapSize = 64; /** - * @en bakeable. - * @zh 是否可烘培。 + * @en Whether the model is static and bake-able with light map. + * Notice: the model's vertex data must have the second UV attribute to enable light map baking. + * @zh 模型是否是静态的并可以烘培光照贴图。 + * 注意:模型顶点数据必须包含第二套 UV 属性来支持光照贴图烘焙。 */ @editable get bakeable () { @@ -114,8 +112,8 @@ class ModelLightmapSettings { } /** - * @en cast shadow. - * @zh 是否投射阴影。 + * @en Whether to cast shadow in light map baking. + * @zh 在光照贴图烘焙中是否投射阴影。 */ @editable get castShadow () { @@ -127,8 +125,8 @@ class ModelLightmapSettings { } /** - * @en receive shadow. - * @zh 是否接受阴影。 + * @en Whether to receive shadow in light map baking. + * @zh 在光照贴图烘焙中是否接受阴影。 */ @editable get receiveShadow () { @@ -140,8 +138,8 @@ class ModelLightmapSettings { } /** - * @en lightmap size. - * @zh 光照图大小 + * @en The lightmap size. + * @zh 光照图大小。 */ @editable get lightmapSize () { @@ -154,18 +152,32 @@ class ModelLightmapSettings { } /** - * @en Mesh renderer component - * @zh 网格渲染器组件。 + * @en Mesh renderer component for general 3d model rendering, it generates and link to a Model in the render scene. + * It supports real time lighting and shadow, baked light map, and morph rendering. + * @zh 用于通用模型渲染的网格渲染器组件,会创建并关联一个渲染场景中的模型对象。 + * 该组件支持实时光照和阴影,预烘焙光照贴图和形变网格渲染。 */ @ccclass('cc.MeshRenderer') @help('i18n:cc.MeshRenderer') @executionOrder(100) @menu('Mesh/MeshRenderer') @executeInEditMode -export class MeshRenderer extends RenderableComponent { +export class MeshRenderer extends ModelRenderer { + /** + * @en Shadow projection mode enumeration. + * @zh 阴影投射方式枚举。 + */ public static ShadowCastingMode = ModelShadowCastingMode; + /** + * @en Shadow receive mode enumeration. + * @zh 阴影接收方式枚举。 + */ public static ShadowReceivingMode = ModelShadowReceivingMode; + /** + * @en The settings for light map baking + * @zh 光照贴图烘焙的配置 + */ @serializable @editable @disallowAnimation @@ -180,18 +192,18 @@ export class MeshRenderer extends RenderableComponent { @serializable protected _shadowReceivingMode = ModelShadowReceivingMode.ON; - // @serializable - private _subMeshShapesWeights: number[][] = []; - @serializable protected _shadowBias = 0; @serializable protected _shadowNormalBias = 0; + // @serializable + private _subMeshShapesWeights: number[][] = []; + /** - * @en local shadow bias. - * @zh 模型局部的阴影偏移。 + * @en Local shadow bias for real time lighting. + * @zh 实时光照下模型局部的阴影偏移。 */ @type(CCFloat) @tooltip('i18n:model.shadow_bias') @@ -208,8 +220,8 @@ export class MeshRenderer extends RenderableComponent { } /** - * @en local shadow normal bias. - * @zh 模型局部的阴影法线偏移。 + * @en local shadow normal bias for real time lighting. + * @zh 实时光照下模型局部的阴影法线偏移。 */ @type(CCFloat) @tooltip('i18n:model.shadow_normal_bias') @@ -227,7 +239,7 @@ export class MeshRenderer extends RenderableComponent { /** * @en Shadow projection mode. - * @zh 阴影投射方式。 + * @zh 实时光照下阴影投射方式。 */ @type(ModelShadowCastingMode) @tooltip('i18n:model.shadow_casting_model') @@ -244,7 +256,7 @@ export class MeshRenderer extends RenderableComponent { /** * @en receive shadow. - * @zh 是否接受阴影。 + * @zh 实时光照下是否接受阴影。 */ @type(ModelShadowReceivingMode) @tooltip('i18n:model.shadow_receiving_model') @@ -261,9 +273,9 @@ export class MeshRenderer extends RenderableComponent { /** * @en Gets or sets the mesh of the model. - * Note, when set, all shape's weights would be reset to zero. + * Note, when set, all morph targets' weights would be reset to zero. * @zh 获取或设置模型的网格数据。 - * 注意,设置时,所有形状的权重都将归零。 + * 注意,设置时,所有形变目标的权重都将归零。 */ @type(Mesh) @tooltip('i18n:model.mesh') @@ -286,10 +298,18 @@ export class MeshRenderer extends RenderableComponent { this._updateReceiveShadow(); } + /** + * @en Gets the model in [[RenderScene]]. + * @zh 获取渲染场景 [[RenderScene]] 中对应的模型。 + */ get model () { return this._model; } + /** + * @en Whether to enable morph rendering. + * @zh 是否启用形变网格渲染。 + */ // eslint-disable-next-line func-names @visible(function (this: MeshRenderer) { return !!( @@ -347,6 +367,7 @@ export class MeshRenderer extends RenderableComponent { } public onEnable () { + super.onEnable(); if (!this._model) { this._updateModels(); } @@ -384,10 +405,10 @@ export class MeshRenderer extends RenderableComponent { } /** - * @zh 获取子网格指定外形的权重。 - * @en Gets the weight at specified shape of specified sub mesh. + * @zh 获取子网格指定形变目标的权重。 + * @en Gets the weight at specified morph target of the specified sub mesh. * @param subMeshIndex Index to the sub mesh. - * @param shapeIndex Index to the shape of the sub mesh. + * @param shapeIndex Index to the morph target of the sub mesh. * @returns The weight. */ public getWeight (subMeshIndex: number, shapeIndex: number) { @@ -400,13 +421,11 @@ export class MeshRenderer extends RenderableComponent { /** * @zh - * 设置子网格所有外形的权重。 - * `subMeshIndex` 是无效索引或 `weights` 的长度不匹配子网格的外形数量时,此方法不会生效。 + * 设置子网格所有形变目标的权重。 + * `subMeshIndex` 是无效索引或 `weights` 的长度不匹配子网格的形变目标数量时,此方法不会生效。 * @en - * Sets weights of each shape of specified sub mesh. - * If takes no effect if - * `subMeshIndex` out of bounds or - * `weights` has a different length with shapes count of the sub mesh. + * Sets weights of each morph target of the specified sub mesh. + * If takes no effect if `subMeshIndex` is out of bounds or if `weights` has a different length with morph targets count of the sub mesh. * @param weights The weights. * @param subMeshIndex Index to the sub mesh. */ @@ -449,18 +468,25 @@ export class MeshRenderer extends RenderableComponent { } public setInstancedAttribute (name: string, value: ArrayLike) { - if (!this.model) { return; } - const { attributes, views } = this.model.instancedAttributes; - for (let i = 0; i < attributes.length; i++) { - if (attributes[i].name === name) { - views[i].set(value); - break; + if (!this.model) { + return; + } + + if (JSB) { + (this.model as any)._setInstancedAttribute(name, value); + } else { + const { attributes, views } = this.model.instancedAttributes; + for (let i = 0; i < attributes.length; i++) { + if (attributes[i].name === name) { + views[i].set(value); + break; + } } } } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _updateLightmap (lightmap: Texture2D|null, uOff: number, vOff: number, scale: number, lum: number) { this.lightmapSettings.texture = lightmap; @@ -490,6 +516,9 @@ export class MeshRenderer extends RenderableComponent { if (this._mesh) { this._model.createBoundingShape(this._mesh.struct.minPosition, this._mesh.struct.maxPosition); } + // Initialize lighting map before model initializing + // because the lighting map will influence the model's shader + this._model.initLightingmap(this.lightmapSettings.texture, this.lightmapSettings.uvParam); this._updateModelParams(); this._onUpdateLightingmap(); this._onUpdateLocalShadowBias(); @@ -739,6 +768,14 @@ export class MeshRenderer extends RenderableComponent { } export declare namespace MeshRenderer { + /** + * @en Shadow projection mode. + * @zh 阴影投射方式。 + */ export type ShadowCastingMode = EnumAlias; + /** + * @en Shadow receive mode. + * @zh 阴影接收方式。 + */ export type ShadowReceivingMode = EnumAlias; } diff --git a/cocos/3d/index.ts b/cocos/3d/index.ts index 892432fd4f..2bbdca2893 100644 --- a/cocos/3d/index.ts +++ b/cocos/3d/index.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import * as utils from './misc'; import { legacyCC } from '../core/global-exports'; diff --git a/cocos/3d/lights/deprecated.ts b/cocos/3d/lights/deprecated.ts index d533d5b347..e9c901cac8 100644 --- a/cocos/3d/lights/deprecated.ts +++ b/cocos/3d/lights/deprecated.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component - */ - import { Light } from './light-component'; import { SpotLight } from './spot-light-component'; import { SphereLight } from './sphere-light-component'; diff --git a/cocos/3d/lights/directional-light-component.ts b/cocos/3d/lights/directional-light-component.ts index b64ac19e7d..a20a5fd904 100644 --- a/cocos/3d/lights/directional-light-component.ts +++ b/cocos/3d/lights/directional-light-component.ts @@ -23,22 +23,21 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component/light - */ - import { ccclass, range, slide, type, editable, visible, help, executeInEditMode, menu, tooltip, serializable, formerlySerializedAs } from 'cc.decorator'; import { Light } from './light-component'; import { scene } from '../../core/renderer'; import { legacyCC } from '../../core/global-exports'; -import { Camera, PCFType, Shadows, ShadowType } from '../../core/renderer/scene'; +import { Camera, PCFType, Shadows, ShadowType, CSMOptimizationMode, CSMLevel } from '../../core/renderer/scene'; import { Root } from '../../core/root'; import { property } from '../../core/data/class-decorator'; import { CCBoolean, CCFloat } from '../../core/data/utils/attribute'; -import { clamp } from '../../core'; +import { clamp, warnID } from '../../core'; +/** + * @en The directional light component, only one real time directional light is permitted in one scene, it act as the main light of the scene. + * @zh 平行光源组件,一个场景只允许存在一个实时的平行光源,作为场景的主光源存在。 + */ @ccclass('cc.DirectionalLight') @help('i18n:cc.DirectionalLight') @menu('Light/DirectionalLight') @@ -49,7 +48,7 @@ export class DirectionalLight extends Light { protected _illuminanceHDR = 65000; @serializable - protected _illuminanceLDR = 1.0; + protected _illuminanceLDR = 65000 * Camera.standardExposureValue; // Public properties of shadow @serializable @@ -65,9 +64,15 @@ export class DirectionalLight extends Light { @serializable protected _shadowSaturation = 1.0; @serializable - protected _shadowDistance = 100; + protected _shadowDistance = 50; @serializable protected _shadowInvisibleOcclusionRange = 200; + @serializable + protected _csmLevel = CSMLevel.LEVEL_4; + @serializable + protected _csmLayerLambda = 0.75; + @serializable + protected _csmOptimizationMode = CSMOptimizationMode.RemoveDuplicates; // fixed area properties @serializable @@ -83,10 +88,8 @@ export class DirectionalLight extends Light { protected _light: scene.DirectionalLight | null = null; /** - * @en - * The light source intensity. - * @zh - * 光源强度。 + * @en The light source intensity. + * @zh 光源强度。 */ @tooltip('i18n:lights.illuminance') get illuminance () { @@ -109,8 +112,8 @@ export class DirectionalLight extends Light { } /** - * @en Whether activate shadow - * @zh 是否启用阴影? + * @en Whether activate real time shadow. + * @zh 是否启用实时阴影? */ @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) @property({ group: { name: 'DynamicShadowSettings', displayOrder: 1 } }) @@ -127,8 +130,8 @@ export class DirectionalLight extends Light { } /** - * @en get or set shadow pcf. - * @zh 获取或者设置阴影pcf等级。 + * @en The shadow pcf for real time shadow. + * @zh 实时阴影计算中的阴影 pcf 等级。 */ @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) @property({ group: { name: 'DynamicShadowSettings', displayOrder: 5 } }) @@ -145,8 +148,8 @@ export class DirectionalLight extends Light { } /** - * @en get or set shadow map sampler offset - * @zh 获取或者设置阴影纹理偏移值 + * @en The shadow map sampler offset for real time shadow. + * @zh 实时阴影计算中的阴影纹理偏移值。 */ @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) @property({ group: { name: 'DynamicShadowSettings', displayOrder: 6 } }) @@ -163,8 +166,8 @@ export class DirectionalLight extends Light { } /** - * @en get or set normal bias. - * @zh 设置或者获取法线偏移。 + * @en The global normal bias for real time shadow. + * @zh 实时阴影计算中的法线偏移。 */ @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) @property({ group: { name: 'DynamicShadowSettings', displayOrder: 7 } }) @@ -181,8 +184,8 @@ export class DirectionalLight extends Light { } /** - * @en Shadow color saturation - * @zh 阴影颜色饱和度 + * @en The shadow color saturation for real time shadow. + * @zh 实时阴影计算中的阴影颜色饱和度。 */ @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) @property({ group: { name: 'DynamicShadowSettings', displayOrder: 8 } }) @@ -202,8 +205,8 @@ export class DirectionalLight extends Light { } /** - * @en get or set shadow camera far - * @zh 获取或者设置潜在阴影产生的范围 + * @en The potential shadow distance from the camera for real time shadow. + * @zh 实时阴影计算中潜在阴影产生的范围 */ @visible(function (this: DirectionalLight) { return (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type @@ -220,14 +223,16 @@ export class DirectionalLight extends Light { } set shadowDistance (val) { this._shadowDistance = Math.min(val, Shadows.MAX_FAR); + if (this._shadowDistance / 0.1 < 10.0) { warnID(15003, this._shadowDistance); } if (this._light) { this._light.shadowDistance = this._shadowDistance; + this._light.csmNeedUpdate = true; } } /** - * @en get or set shadow camera far - * @zh 获取或者设置潜在阴影产生的范围 + * @en The occlusion range for real time shadow. + * @zh 实时阴影计算中剔除阴影的范围 */ @visible(function (this: DirectionalLight) { return (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type @@ -236,7 +241,7 @@ export class DirectionalLight extends Light { @property({ group: { name: 'DynamicShadowSettings', displayOrder: 10 } }) @editable @tooltip('if shadow has been culled, increase this value to fix it') - @range([0.0, 2000.0, 0.1]) + @range([0.0, 2000.0, 1.0]) @slide @type(CCFloat) get shadowInvisibleOcclusionRange () { @@ -250,11 +255,99 @@ export class DirectionalLight extends Light { } /** - * @en get or set fixed area shadow - * @zh 是否是固定区域阴影 + * @en get or set shadow CSM level + * @zh 获取或者设置阴影层级 + */ + @visible(false) + @property({ group: { name: 'DynamicShadowSettings', displayOrder: 11 } }) + @editable + @tooltip('CSM Level') + @slide + @type(CSMLevel) + get csmLevel () { + return this._csmLevel; + } + set csmLevel (val) { + this._csmLevel = val; + if (this._light) { + this._light.csmLevel = this._csmLevel; + this._light.csmNeedUpdate = true; + } + } + + /** + * @en enable csm + * @zh 开启或关闭 csm 模式 + */ + @visible(function (this: DirectionalLight) { + return (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type + === ShadowType.ShadowMap && this._shadowFixedArea === false; + }) + @property({ group: { name: 'DynamicShadowSettings', displayOrder: 12 } }) + @editable + @tooltip('enable CSM') + @slide + @type(CCBoolean) + get enableCSM () { + return this._csmLevel > CSMLevel.LEVEL_1; + } + set enableCSM (val) { + this._csmLevel = val ? CSMLevel.LEVEL_4 : CSMLevel.LEVEL_1; + if (this._light) { + this._light.csmLevel = this._csmLevel; + this._light.csmNeedUpdate = true; + } + } + + /** + * @en get or set shadow CSM level ratio + * @zh 获取或者设置阴影层级系数 + */ + @visible(false) + @property({ group: { name: 'DynamicShadowSettings', displayOrder: 13 } }) + @editable + @tooltip('CSM Level ratio') + @range([0.0, 1.0, 0.01]) + @slide + @type(CCFloat) + get csmLayerLambda () { + return this._csmLayerLambda; + } + set csmLayerLambda (val) { + this._csmLayerLambda = val; + if (this._light) { + this._light.csmLayerLambda = this._csmLayerLambda; + this._light.csmNeedUpdate = true; + } + } + + /** + * @en get or set shadow CSM performance optimization mode + * @zh 获取或者设置级联阴影性能优化模式 + * @internal + */ + @visible(false) + @property({ group: { name: 'DynamicShadowSettings', displayOrder: 14 } }) + @editable + @tooltip('CSM Performance Optimization Mode') + @slide + @type(CSMOptimizationMode) + get csmOptimizationMode () { + return this._csmOptimizationMode; + } + set csmOptimizationMode (val) { + this._csmOptimizationMode = val; + if (this._light) { + this._light.csmOptimizationMode = this._csmOptimizationMode; + } + } + + /** + * @en Whether to use fixed area shadow in real time shadow. + * @zh 实时阴影计算中是否使用固定区域阴影。 */ @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) - @property({ group: { name: 'DynamicShadowSettings', displayOrder: 11 } }) + @property({ group: { name: 'DynamicShadowSettings', displayOrder: 15 } }) @editable @type(CCBoolean) get shadowFixedArea () { @@ -268,14 +361,14 @@ export class DirectionalLight extends Light { } /** - * @en get or set shadow camera near - * @zh 获取或者设置阴影相机近裁剪面 + * @en The near clip plane of the shadow camera for fixed area shadow + * @zh 固定区域阴影设置中阴影相机近裁剪面 */ @visible(function (this: DirectionalLight) { return (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap && this._shadowFixedArea === true; }) - @property({ group: { name: 'DynamicShadowSettings', displayOrder: 12 } }) + @property({ group: { name: 'DynamicShadowSettings', displayOrder: 16 } }) @editable @type(CCFloat) get shadowNear () { @@ -289,14 +382,14 @@ export class DirectionalLight extends Light { } /** - * @en get or set shadow camera far - * @zh 获取或者设置阴影相机远裁剪面 + * @en The far clip plane of the shadow camera for fixed area shadow. + * @zh 固定区域阴影设置中阴影相机远裁剪面。 */ @visible(function (this: DirectionalLight) { return (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap && this._shadowFixedArea === true; }) - @property({ group: { name: 'DynamicShadowSettings', displayOrder: 13 } }) + @property({ group: { name: 'DynamicShadowSettings', displayOrder: 17 } }) @editable @type(CCFloat) get shadowFar () { @@ -310,14 +403,14 @@ export class DirectionalLight extends Light { } /** - * @en get or set shadow camera orthoSize - * @zh 获取或者设置阴影相机正交大小 + * @en The orthogonal size of the shadow camera for fixed area shadow. + * @zh 固定区域阴影设置中阴影相机的正交尺寸 */ @visible(function (this: DirectionalLight) { return (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap && this._shadowFixedArea === true; }) - @property({ group: { name: 'DynamicShadowSettings', displayOrder: 14 } }) + @property({ group: { name: 'DynamicShadowSettings', displayOrder: 18 } }) @type(CCFloat) get shadowOrthoSize () { return this._shadowOrthoSize; @@ -336,7 +429,6 @@ export class DirectionalLight extends Light { protected _createLight () { super._createLight(); - this._illuminanceLDR = this._illuminanceHDR * Camera.standardExposureValue; if (this._light) { this._light.illuminanceHDR = this._illuminanceHDR; this._light.illuminanceLDR = this._illuminanceLDR; @@ -352,6 +444,9 @@ export class DirectionalLight extends Light { this._light.shadowNear = this._shadowNear; this._light.shadowFar = this._shadowFar; this._light.shadowOrthoSize = this._shadowOrthoSize; + this._light.csmLevel = this._csmLevel; + this._light.csmLayerLambda = this._csmLayerLambda; + this._light.csmOptimizationMode = this._csmOptimizationMode; } } } diff --git a/cocos/3d/lights/index.ts b/cocos/3d/lights/index.ts index 702e96c7c0..67d85771f6 100644 --- a/cocos/3d/lights/index.ts +++ b/cocos/3d/lights/index.ts @@ -24,7 +24,6 @@ THE SOFTWARE. */ - export { DirectionalLight } from './directional-light-component'; export { Light } from './light-component'; export { SphereLight } from './sphere-light-component'; diff --git a/cocos/3d/lights/light-component.ts b/cocos/3d/lights/light-component.ts index 95141a7d5e..a9f3f43d4c 100644 --- a/cocos/3d/lights/light-component.ts +++ b/cocos/3d/lights/light-component.ts @@ -23,27 +23,27 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component/light - */ - import { ccclass, tooltip, range, slide, type, displayOrder, serializable, editable } from 'cc.decorator'; import { Component } from '../../core/components/component'; import { Color, Vec3 } from '../../core/math'; import { Enum } from '../../core/value-types'; - import { scene } from '../../core/renderer'; import { Root } from '../../core/root'; import { legacyCC } from '../../core/global-exports'; +const _color_tmp = new Vec3(); + +/** + * @en The physical term used for light. + * @zh 光源所使用的物理计量单位。 + */ export const PhotometricTerm = Enum({ LUMINOUS_FLUX: 0, LUMINANCE: 1, }); -const _color_tmp = new Vec3(); + /** - * @en static light settings. + * @en Static light settings. * @zh 静态灯光设置 */ @ccclass('cc.StaticLightSettings') @@ -58,7 +58,7 @@ class StaticLightSettings { protected _castShadow = false; /** - * @en editor only. + * @en Whether the light is editor only. * @zh 是否只在编辑器里生效。 */ @editable @@ -70,7 +70,8 @@ class StaticLightSettings { } /** - * bake state + * @en Whether the light is baked + * @zh 光源是否被烘焙 */ get baked () { return this._baked; @@ -81,8 +82,8 @@ class StaticLightSettings { } /** - * @en bakeable. - * @zh 是否可烘培。 + * @en Whether the light is bake-able. + * @zh 光源是否可烘培。 */ @editable get bakeable () { @@ -94,8 +95,8 @@ class StaticLightSettings { } /** - * @en cast shadow. - * @zh 是否投射阴影。 + * @en Whether the light will cast shadow during baking process. + * @zh 光源在烘焙时是否投射阴影。 */ @editable get castShadow () { @@ -112,9 +113,21 @@ export declare namespace Light { export type PhotometricTerm = EnumAlias; } +/** + * @en The base class of all light components, contains basic light settings for both real time light and baked light. + * @zh 光源组件基类,包含实时光源和烘焙光源的基本配置信息。 + */ @ccclass('cc.Light') export class Light extends Component { + /** + * @en The light type enumeration. + * @zh 光源类型枚举。 + */ public static Type = scene.LightType; + /** + * @en The physical term used for light. + * @zh 光源所使用的物理计量单位。 + */ public static PhotometricTerm = PhotometricTerm; @serializable @@ -131,10 +144,8 @@ export class Light extends Component { protected _light: scene.Light | null = null; /** - * @en - * Color of the light. - * @zh - * 光源颜色。 + * @en The color of the light. + * @zh 光源颜色。 */ @tooltip('i18n:lights.color') get color (): Readonly { @@ -200,17 +211,16 @@ export class Light extends Component { } /** - * @en - * The light type. - * @zh - * 光源类型。 + * @en The light type. + * @zh 光源类型。 */ get type () { return this._type; } /** - * bake state + * @en Whether the light is baked + * @zh 光源是否被烘焙 */ get baked () { return this.staticSettings.baked; @@ -257,7 +267,7 @@ export class Light extends Component { protected _destroyLight () { if (this._light) { - legacyCC.director.root.destroyLight(this); + legacyCC.director.root.recycleLight(this._light); this._light = null; } } diff --git a/cocos/3d/lights/sphere-light-component.ts b/cocos/3d/lights/sphere-light-component.ts index 027bdb84f4..1db1b4893d 100644 --- a/cocos/3d/lights/sphere-light-component.ts +++ b/cocos/3d/lights/sphere-light-component.ts @@ -22,10 +22,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component/light - */ import { ccclass, help, executeInEditMode, menu, tooltip, type, displayOrder, serializable, formerlySerializedAs } from 'cc.decorator'; import { scene } from '../../core/renderer'; @@ -34,6 +30,10 @@ import { legacyCC } from '../../core/global-exports'; import { Camera } from '../../core/renderer/scene'; import { Root } from '../../core/root'; +/** + * @en The sphere light component, multiple sphere lights can be added to one scene. + * @zh 球面光源组件,场景中可以添加多个球面光源。 + */ @ccclass('cc.SphereLight') @help('i18n:cc.SphereLight') @menu('Light/SphereLight') @@ -45,7 +45,7 @@ export class SphereLight extends Light { @formerlySerializedAs('_luminance') protected _luminanceHDR = 1700 / scene.nt2lm(0.15); @serializable - protected _luminanceLDR = 1.0; + protected _luminanceLDR = 1700 / scene.nt2lm(0.15) * Camera.standardExposureValue * Camera.standardLightMeterScale; @serializable protected _term = PhotometricTerm.LUMINOUS_FLUX; @serializable @@ -159,11 +159,6 @@ export class SphereLight extends Light { super._createLight(); this.size = this._size; this.range = this._range; - if ((legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR) { - this._luminanceLDR = this._luminanceHDR * Camera.standardExposureValue * Camera.standardLightMeterScale; - } else { - this._luminanceHDR = this._luminanceLDR / Camera.standardExposureValue / Camera.standardLightMeterScale; - } if (this._light) { this._light.luminanceHDR = this._luminanceHDR; diff --git a/cocos/3d/lights/spot-light-component.ts b/cocos/3d/lights/spot-light-component.ts index b53911b75e..b79fdc0d9b 100644 --- a/cocos/3d/lights/spot-light-component.ts +++ b/cocos/3d/lights/spot-light-component.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component/light - */ - import { ccclass, range, slide, type, editable, displayOrder, help, executeInEditMode, menu, tooltip, serializable, formerlySerializedAs, visible } from 'cc.decorator'; import { toRadian } from '../../core/math'; @@ -39,6 +34,10 @@ import { Camera, PCFType, ShadowType } from '../../core/renderer/scene'; import { property } from '../../core/data/class-decorator'; import { CCBoolean, CCFloat } from '../../core/data/utils/attribute'; +/** + * @en The spot light component, multiple spot lights can be added to one scene. + * @zh 聚光灯光源组件,场景中可以添加多个聚光灯光源。 + */ @ccclass('cc.SpotLight') @help('i18n:cc.SpotLight') @menu('Light/SpotLight') @@ -52,7 +51,7 @@ export class SpotLight extends Light { protected _luminanceHDR = 1700 / scene.nt2lm(0.15); @serializable - protected _luminanceLDR = 1.0; + protected _luminanceLDR = 1700 / scene.nt2lm(0.15) * Camera.standardExposureValue * Camera.standardLightMeterScale; @serializable protected _term = PhotometricTerm.LUMINOUS_FLUX; @@ -215,8 +214,8 @@ export class SpotLight extends Light { } /** - * @en get or set shadow pcf. - * @zh 获取或者设置阴影pcf等级。 + * @en The pcf level of the shadow generation. + * @zh 获取或者设置阴影 pcf 等级。 */ @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) @property({ group: { name: 'DynamicShadowSettings', displayOrder: 2 } }) @@ -233,8 +232,8 @@ export class SpotLight extends Light { } /** - * @en get or set shadow map sampler offset - * @zh 获取或者设置阴影纹理偏移值 + * @en The depth offset of shadow to avoid moire pattern artifacts + * @zh 阴影的深度偏移, 可以减弱跨像素导致的条纹状失真 */ @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) @property({ group: { name: 'DynamicShadowSettings', displayOrder: 3 } }) @@ -251,7 +250,7 @@ export class SpotLight extends Light { } /** - * @en get or set normal bias. + * @en The normal bias of the shadow map. * @zh 设置或者获取法线偏移。 */ @visible(() => (legacyCC.director.root as Root).pipeline.pipelineSceneData.shadows.type === ShadowType.ShadowMap) @@ -278,11 +277,6 @@ export class SpotLight extends Light { this.size = this._size; this.range = this._range; this.spotAngle = this._spotAngle; - if ((legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR) { - this._luminanceLDR = this._luminanceHDR * Camera.standardExposureValue * Camera.standardLightMeterScale; - } else { - this._luminanceHDR = this._luminanceLDR / Camera.standardExposureValue / Camera.standardLightMeterScale; - } if (this._light) { this._light.luminanceHDR = this._luminanceHDR; diff --git a/cocos/3d/misc/batch-utils.ts b/cocos/3d/misc/batch-utils.ts index c67a489102..3887c9095d 100644 --- a/cocos/3d/misc/batch-utils.ts +++ b/cocos/3d/misc/batch-utils.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ - import { MeshRenderer } from '../framework/mesh-renderer'; import { Mesh } from '../assets/mesh'; import { Mat4 } from '../../core/math/mat4'; @@ -52,12 +47,19 @@ function checkMaterialisSame (comp1: MeshRenderer, comp2: MeshRenderer): boolean */ export class BatchingUtility { /** + * @en * Collect the Models under `staticModelRoot`, * merge all the meshes statically into one (while disabling each component), * and attach it to a new Model on `batchedRoot`. * The world transform of each model is guaranteed to be preserved. * * For a more fine-grained control over the process, use `Mesh.merge` directly. + * @zh + * 在`staticModelRoot`下收集模型。 + * 将所有的网格静态地合并成一个(同时禁用每个组件)。 + * 并将其附加到 `batchedRoot` 上的一个新模型。 + * 每个模型的世界变换都被保证保留下来。 + * 如果要对这个过程进行更精细的控制,可以直接使用 `Mesh.merge`。 * @param staticModelRoot root of all the static models to be batched * @param batchedRoot the target output node */ @@ -96,7 +98,10 @@ export class BatchingUtility { } /** + * @en * Undoes everything `batchStaticModel` did. + * @zh + * 回退 `batchStaticModel` 做的工作 * * @param staticModelRoot root of all the static models to be batched * @param batchedRoot the target output node diff --git a/cocos/3d/misc/create-mesh.ts b/cocos/3d/misc/create-mesh.ts index 3931992d0e..2892333921 100644 --- a/cocos/3d/misc/create-mesh.ts +++ b/cocos/3d/misc/create-mesh.ts @@ -414,6 +414,10 @@ export class MeshUtils { /** * @en create a static mesh. * @zh 创建一个静态网格。 + * @param geometry @en geometry data use for creating @zh 用于创建的几何数据 + * @param out @en output static mesh @zh 输出的静态网格 + * @param options @en options of creating @zh 创建选项 + * @return @en The created static mesh, which is same as out @zh 新创建的静态网格,同 out 参数 */ static createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMeshOptions) { return createMesh(geometry, out, options); @@ -422,6 +426,11 @@ export class MeshUtils { /** * @en create a dynamic mesh. * @zh 创建一个动态网格。 + * @param primitiveIndex @en sub mesh index @zh 子网格索引 + * @param geometry @en geometry data use for creating @zh 用于创建的几何数据 + * @param out @en output dynamic mesh @zh 输出的动态网格 + * @param options @en options of creating @zh 创建选项 + * @return @en The created dynamic mesh, which is same as out @zh 新创建的动态网格,同 out 参数 */ static createDynamicMesh (primitiveIndex: number, geometry: IDynamicGeometry, out?: Mesh, options?: ICreateDynamicMeshOptions) { return createDynamicMesh(primitiveIndex, geometry, out, options); diff --git a/cocos/3d/misc/ppm.ts b/cocos/3d/misc/ppm.ts index 22bb9a0202..d87753b1d9 100644 --- a/cocos/3d/misc/ppm.ts +++ b/cocos/3d/misc/ppm.ts @@ -24,7 +24,13 @@ */ /** + * @en * save a color buffer to a PPM file + * @zh + * 保存一个颜色缓冲到 PPM 文件中 + * @param buffer color buffer + * @param w width + * @param h height */ export function toPPM (buffer: Uint8Array, w: number, h: number) { return `P3 ${w} ${h} 255\n${buffer.filter((e, i) => i % 4 < 3).toString()}\n`; diff --git a/cocos/3d/models/baked-skinning-model.ts b/cocos/3d/models/baked-skinning-model.ts index 4c2936de55..8103bbe9c6 100644 --- a/cocos/3d/models/baked-skinning-model.ts +++ b/cocos/3d/models/baked-skinning-model.ts @@ -53,11 +53,15 @@ const myPatches = [ /** * @en - * The skinning model that is using baked animation. + * The skinning model that is using GPU baked animation. * @zh - * 预烘焙动画的蒙皮模型。 + * GPU 预烘焙动画的蒙皮模型。 */ export class BakedSkinningModel extends MorphModel { + /** + * @en The animation clip that have been uploaded + * @zh 已被上传的动画片段 + */ public uploadedAnim: AnimationClip | null | undefined = undefined; // uninitialized private _jointsMedium: IJointsInfo; @@ -87,6 +91,7 @@ export class BakedSkinningModel extends MorphModel { super.destroy(); } + // Override public bindSkeleton (skeleton: Skeleton | null = null, skinningRoot: Node | null = null, mesh: Mesh | null = null) { this._skeleton = skeleton; this._mesh = mesh; @@ -104,6 +109,7 @@ export class BakedSkinningModel extends MorphModel { } } + // Override public updateTransform (stamp: number) { super.updateTransform(stamp); @@ -118,7 +124,7 @@ export class BakedSkinningModel extends MorphModel { } } - // update fid buffer only when visible + // Override, update fid buffer only when visible public updateUBOs (stamp: number) { super.updateUBOs(stamp); @@ -134,6 +140,21 @@ export class BakedSkinningModel extends MorphModel { return true; } + // Override + public getMacroPatches (subModelIndex: number): IMacroPatch[] | null { + const patches = super.getMacroPatches(subModelIndex); + return patches ? patches.concat(myPatches) : myPatches; + } + + /** + * @en Pre-simulate and store the frames data of the given animation clip to a joint texture and upload it to GPU. + * Normally, it's automatically managed by [[SkeletalAnimationState]]. + * But user can also use Joint Texture Layout Settings in the editor to manually organize the joint textures. + * @zh 预计算并存储一个指定动画片段的完整帧数据到一张骨骼贴图上,并将其上传到 GPU。 + * 一般情况下 [[SkeletalAnimationState]] 会自动管理所有骨骼贴图,但用户也可以使用编辑器的骨骼贴图布局设置面板来手动管理所有骨骼贴图。 + * @param anim @en The animation clip to be uploaded to the joint texture. @zh 需要上传到骨骼贴图上的动画片段。 + * @returns void + */ public uploadAnimation (anim: AnimationClip | null) { if (!this._skeleton || !this._mesh || this.uploadedAnim === anim) { return; } this.uploadedAnim = anim; @@ -146,7 +167,7 @@ export class BakedSkinningModel extends MorphModel { } else { texture = resMgr.jointTexturePool.getDefaultPoseTexture(this._skeleton, this._mesh, this.transform); this._jointsMedium.boundsInfo = null; - this._modelBounds = texture && texture.bounds.get(this._mesh.hash)![0]; + this._modelBounds = texture && texture.bounds.get(this._mesh.hash)![0]; } this._applyJointTexture(texture); } @@ -171,11 +192,6 @@ export class BakedSkinningModel extends MorphModel { } } - public getMacroPatches (subModelIndex: number): IMacroPatch[] | null { - const patches = super.getMacroPatches(subModelIndex); - return patches ? patches.concat(myPatches) : myPatches; - } - protected _updateLocalDescriptors (submodelIdx: number, descriptorSet: DescriptorSet) { super._updateLocalDescriptors(submodelIdx, descriptorSet); const { buffer, texture, animInfo } = this._jointsMedium; diff --git a/cocos/3d/models/morph-model.ts b/cocos/3d/models/morph-model.ts index de232b36c1..ddab4f223e 100644 --- a/cocos/3d/models/morph-model.ts +++ b/cocos/3d/models/morph-model.ts @@ -23,27 +23,48 @@ THE SOFTWARE. */ - - import { Model } from '../../core/renderer/scene/model'; -import { MorphRenderingInstance } from '../assets/morph'; +import { MorphRenderingInstance } from '../assets/morph-rendering'; import { Material } from '../../core/assets/material'; import { RenderingSubMesh } from '../../core/assets/rendering-sub-mesh'; import { DescriptorSet } from '../../core/gfx'; import { IMacroPatch } from '../../core/renderer'; +/** + * @en + * The model that support morph target rendering. + * @zh + * 支持渲染蒙皮形变的模型。 + */ export class MorphModel extends Model { private _morphRenderingInstance: MorphRenderingInstance | null = null; private _usedMaterials = new Set(); + /** + * @en Acquire the material's macro patches for the given sub model. + * @zh 获取指定子模型的材质宏组合。 + * @param subModelIndex @en The index for the requested sub model. @zh 子模型的序号。 + * @returns @en The macro patches. @zh 材质宏组合 + */ public getMacroPatches (subModelIndex: number) : IMacroPatch[] | null { + const superMacroPatches = super.getMacroPatches(subModelIndex); if (this._morphRenderingInstance) { - return this._morphRenderingInstance.requiredPatches(subModelIndex); - } else { - return super.getMacroPatches(subModelIndex); + const morphInstanceMacroPatches = this._morphRenderingInstance.requiredPatches(subModelIndex); + if (morphInstanceMacroPatches) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return + return morphInstanceMacroPatches.concat(superMacroPatches ?? []); + } } + return superMacroPatches; } + /** + * @en Initialize a sub model with the sub mesh data and the material. + * @zh 用子网格数据和材质初始化一个子模型。 + * @param idx @en The index of the sub model @zh 子模型的序号 + * @param subMeshData @en The sub mesh data to be set @zh 需要设置的子网格 + * @param mat sub material + */ public initSubModel (subModelIndex: number, subMeshData: RenderingSubMesh, material: Material) { return super.initSubModel( subModelIndex, @@ -57,10 +78,25 @@ export class MorphModel extends Model { this._morphRenderingInstance = null; } + /** + * @en Sets the material for a given sub model. + * @zh 给指定的子模型设置材质。 + * @param subModelIndex @en The index of the sub model @zh 子模型的序号 + * @param material @en The material to be set @zh 需要设置的材质 + * @returns void + */ public setSubModelMaterial (subModelIndex: number, material: Material) { return super.setSubModelMaterial(subModelIndex, this._launderMaterial(material)); } + /** + * Sets morph rendering instance for the model, it's managed by the MeshRenderer + * @internal + */ + public setMorphRendering (morphRendering: MorphRenderingInstance) { + this._morphRenderingInstance = morphRendering; + } + protected _updateLocalDescriptors (submodelIdx: number, descriptorSet: DescriptorSet) { super._updateLocalDescriptors(submodelIdx, descriptorSet); @@ -80,8 +116,4 @@ export class MorphModel extends Model { // return material; // } } - - public setMorphRendering (morphRendering: MorphRenderingInstance) { - this._morphRenderingInstance = morphRendering; - } } diff --git a/cocos/3d/models/skinning-model.ts b/cocos/3d/models/skinning-model.ts index 9c439230d2..4ff2e3e07a 100644 --- a/cocos/3d/models/skinning-model.ts +++ b/cocos/3d/models/skinning-model.ts @@ -23,27 +23,31 @@ THE SOFTWARE. */ - - import { Material } from '../../core/assets/material'; import { RenderingSubMesh } from '../../core/assets/rendering-sub-mesh'; import { Mesh } from '../assets/mesh'; import { Skeleton } from '../assets/skeleton'; import { AABB } from '../../core/geometry'; -import { BufferUsageBit, MemoryUsageBit, DescriptorSet, Buffer, BufferInfo, Attribute } from '../../core/gfx'; +import { BufferUsageBit, MemoryUsageBit, DescriptorSet, Buffer, BufferInfo, Attribute, FormatFeatureBit, Format, Texture } from '../../core/gfx'; import { Mat4, Vec3 } from '../../core/math'; -import { UBOSkinning } from '../../core/pipeline/define'; +import { UBOSkinning, UNIFORM_REALTIME_JOINT_TEXTURE_BINDING } from '../../core/pipeline/define'; import { Node } from '../../core/scene-graph/node'; import { ModelType } from '../../core/renderer/scene/model'; import { uploadJointData } from '../skeletal-animation/skeletal-animation-utils'; import { MorphModel } from './morph-model'; import { deleteTransform, getTransform, getWorldMatrix, IJointTransform } from '../../core/animation/skeletal-animation-utils'; import { IMacroPatch, BatchingSchemes, Pass } from '../../core/renderer'; - import { warnID } from '../../core/platform/debug'; +import { ImageAsset, Texture2D, director } from '../../core'; +import { PixelFormat } from '../../core/assets/asset-enum'; -const myPatches: IMacroPatch[] = [ +const uniformPatches: IMacroPatch[] = [ { name: 'CC_USE_SKINNING', value: true }, + { name: 'CC_USE_REAL_TIME_JOINT_TEXTURE', value: false }, +]; +const texturePatches: IMacroPatch[] = [ + { name: 'CC_USE_SKINNING', value: true }, + { name: 'CC_USE_REAL_TIME_JOINT_TEXTURE', value: true }, ]; function getRelevantBuffers (outIndices: number[], outBuffers: number[], jointMaps: number[][], targetJoint: number) { @@ -76,6 +80,14 @@ const v3_2 = new Vec3(); const m4_1 = new Mat4(); const ab_1 = new AABB(); +class RealTimeJointTexture { + public static readonly WIDTH = 256; + public static readonly HEIGHT = 3; + public _format = PixelFormat.RGBA32F; // default use float texture + public _textures: Texture2D[] = []; + public _buffers: Float32Array[] = []; +} + /** * @en * The skinning model that is using real-time pose calculation. @@ -83,12 +95,12 @@ const ab_1 = new AABB(); * 实时计算动画的蒙皮模型。 */ export class SkinningModel extends MorphModel { - public uploadAnimation = null; - private _buffers: Buffer[] = []; private _dataArray: Float32Array[] = []; private _joints: IJointInfo[] = []; private _bufferIndices: number[] | null = null; + private _realTimeJointTexture = new RealTimeJointTexture(); + private _realTimeTextureMode = false; constructor () { super(); this.type = ModelType.SKINNING; @@ -102,20 +114,43 @@ export class SkinningModel extends MorphModel { } this._buffers.length = 0; } + this._dataArray.length = 0; + this._realTimeJointTexture._textures.forEach((tex) => { + tex.destroy(); + }); + this._realTimeJointTexture._textures.length = 0; + this._realTimeJointTexture._buffers.length = 0; super.destroy(); } + /** + * @en Abstract function for [[BakedSkinningModel]], empty implementation. + * @zh 由 [[BakedSkinningModel]] 继承的空函数。 + */ + public uploadAnimation () {} + + /** + * @en Bind the skeleton with its skinning root node and the mesh data. + * @zh 在模型中绑定一个骨骼,需要提供骨骼的蒙皮根节点和蒙皮网格数据。 + * @param skeleton @en The skeleton to be bound @zh 要绑定的骨骼 + * @param skinningRoot @en The skinning root of the skeleton @zh 骨骼的蒙皮根节点 + * @param mesh @en The mesh @zh 蒙皮网格 + * @returns void + */ public bindSkeleton (skeleton: Skeleton | null = null, skinningRoot: Node | null = null, mesh: Mesh | null = null) { for (let i = 0; i < this._joints.length; i++) { deleteTransform(this._joints[i].target); } this._bufferIndices = null; this._joints.length = 0; if (!skeleton || !skinningRoot || !mesh) { return; } + this._realTimeTextureMode = false; + if (UBOSkinning.JOINT_UNIFORM_CAPACITY < skeleton.joints.length) { this._realTimeTextureMode = true; } this.transform = skinningRoot; const boneSpaceBounds = mesh.getBoneSpaceBounds(skeleton); const jointMaps = mesh.struct.jointMaps; this._ensureEnoughBuffers(jointMaps && jointMaps.length || 1); this._bufferIndices = mesh.jointBufferIndices; + this._initRealTimeJointTexture(); for (let index = 0; index < skeleton.joints.length; index++) { const bound = boneSpaceBounds[index]; const target = skinningRoot.getChildByPath(skeleton.joints[index]); @@ -129,6 +164,11 @@ export class SkinningModel extends MorphModel { } } + /** + * @en Update world transform and bounding boxes for the model + * @zh 更新模型的世界矩阵和包围盒 + * @param stamp @en The update time stamp @zh 更新的时间戳 + */ public updateTransform (stamp: number) { const root = this.transform; // @ts-expect-error TS2445 @@ -156,6 +196,12 @@ export class SkinningModel extends MorphModel { } } + /** + * @en Update uniform buffer objects for rendering. + * @zh 更新用于渲染的 UBO + * @param stamp @en The update time stamp @zh 更新的时间戳 + * @returns @en successful or not @zh 更新是否成功 + */ public updateUBOs (stamp: number) { super.updateUBOs(stamp); for (let i = 0; i < this._joints.length; i++) { @@ -165,12 +211,23 @@ export class SkinningModel extends MorphModel { uploadJointData(this._dataArray[buffers[b]], indices[b] * 12, m4_1, i === 0); } } - for (let b = 0; b < this._buffers.length; b++) { - this._buffers[b].update(this._dataArray[b]); + if (this._realTimeTextureMode) { + this._updateRealTimeJointTextureBuffer(); + } else { + for (let b = 0; b < this._buffers.length; b++) { + this._buffers[b].update(this._dataArray[b]); + } } return true; } + /** + * @en Initialize sub model with the sub mesh data and the material + * @zh 用子网格数据和材质初始化一个子模型 + * @param idx @en The index of the sub model to be initialized @zh 需要初始化的子模型序号 + * @param subMeshData @en The sub mesh data @zh 子网格数据 + * @param mat @en The material @zh 子模型材质 + */ public initSubModel (idx: number, subMeshData: RenderingSubMesh, mat: Material) { const original = subMeshData.vertexBuffers; const iaInfo = subMeshData.iaInfo; @@ -179,9 +236,13 @@ export class SkinningModel extends MorphModel { iaInfo.vertexBuffers = original; } + // override public getMacroPatches (subModelIndex: number): IMacroPatch[] | null { const superMacroPatches = super.getMacroPatches(subModelIndex); - + let myPatches = uniformPatches; + if (this._realTimeTextureMode) { + myPatches = texturePatches; + } if (superMacroPatches) { return myPatches.concat(superMacroPatches); } @@ -189,12 +250,17 @@ export class SkinningModel extends MorphModel { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _updateLocalDescriptors (submodelIdx: number, descriptorSet: DescriptorSet) { super._updateLocalDescriptors(submodelIdx, descriptorSet); - const buffer = this._buffers[this._bufferIndices![submodelIdx]]; - if (buffer) { descriptorSet.bindBuffer(UBOSkinning.BINDING, buffer); } + const idx = this._bufferIndices![submodelIdx]; + if (this._realTimeTextureMode) { + this._bindRealTimeJointTexture(idx, descriptorSet); + } else { + const buffer = this._buffers[idx]; + if (buffer) { descriptorSet.bindBuffer(UBOSkinning.BINDING, buffer); } + } } protected _updateInstancedAttributes (attributes: Attribute[], pass: Pass) { @@ -206,18 +272,117 @@ export class SkinningModel extends MorphModel { } private _ensureEnoughBuffers (count: number) { - for (let i = 0; i < count; i++) { - if (!this._buffers[i]) { + if (this._buffers.length) { + for (let i = 0; i < this._buffers.length; i++) { + this._buffers[i].destroy(); + } + this._buffers.length = 0; + } + + if (this._dataArray.length) this._dataArray.length = 0; + + if (!this._realTimeTextureMode) { + for (let i = 0; i < count; i++) { this._buffers[i] = this._device.createBuffer(new BufferInfo( BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, UBOSkinning.SIZE, UBOSkinning.SIZE, )); + const maxJoints = UBOSkinning.JOINT_UNIFORM_CAPACITY; + this._dataArray[i] = new Float32Array(12 * maxJoints); } - if (!this._dataArray[i]) { - this._dataArray[i] = new Float32Array(UBOSkinning.COUNT); + } else { + for (let i = 0; i < count; i++) { + const maxJoints = RealTimeJointTexture.WIDTH; + this._dataArray[i] = new Float32Array(12 * maxJoints); } } } + + private _initRealTimeJointTexture () { + if (this._realTimeJointTexture._textures.length) { + this._realTimeJointTexture._textures.forEach((tex) => { + tex.destroy(); + }); + this._realTimeJointTexture._textures.length = 0; + } + this._realTimeJointTexture._buffers.length = 0; + if (!this._realTimeTextureMode) return; + + const gfxDevice = director.root!.device; + let width = RealTimeJointTexture.WIDTH; + const height = RealTimeJointTexture.HEIGHT; + const hasFeatureFloatTexture = gfxDevice.getFormatFeatures(Format.RGBA32F) & FormatFeatureBit.SAMPLED_TEXTURE; + if (hasFeatureFloatTexture === 0) { + this._realTimeJointTexture._format = PixelFormat.RGBA8888; + width = 4 * RealTimeJointTexture.WIDTH; + } + + const textures = this._realTimeJointTexture._textures; + const buffers = this._realTimeJointTexture._buffers; + const pixelFormat = this._realTimeJointTexture._format; + for (let i = 0; i < this._dataArray.length; i++) { + buffers[i] = new Float32Array(4 * RealTimeJointTexture.HEIGHT * RealTimeJointTexture.WIDTH); + const arrayBuffer = buffers[i]; + const updateView = pixelFormat === PixelFormat.RGBA32F ? arrayBuffer : new Uint8Array(arrayBuffer.buffer); + const image = new ImageAsset({ + width, + height, + _data: updateView, + _compressed: false, + format: pixelFormat, + }); + const texture = new Texture2D(); + texture.setFilters(Texture2D.Filter.NEAREST, Texture2D.Filter.NEAREST); + texture.setMipFilter(Texture2D.Filter.NONE); + texture.setWrapMode(Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE, Texture2D.WrapMode.CLAMP_TO_EDGE); + texture.image = image; + textures[i] = texture; + } + } + + private _bindRealTimeJointTexture (idx: number, descriptorSet: DescriptorSet) { + if (!this._realTimeTextureMode) return; + const jointTexture = this._realTimeJointTexture._textures[idx]; + if (jointTexture) { + const gfxTexture = jointTexture.getGFXTexture(); + const sampler = jointTexture.getGFXSampler(); + descriptorSet.bindTexture(UNIFORM_REALTIME_JOINT_TEXTURE_BINDING, gfxTexture!); + descriptorSet.bindSampler(UNIFORM_REALTIME_JOINT_TEXTURE_BINDING, sampler); + } + } + + private _updateRealTimeJointTextureBuffer () { + if (!this._realTimeTextureMode) return; + const textures = this._realTimeJointTexture._textures; + const buffers = this._realTimeJointTexture._buffers; + for (let idx = 0; idx < textures.length; idx++) { + const arrayBuffer = buffers[idx]; + const src = this._dataArray[idx]; + const count = src.length / 12; // mat3x4 + let idxSrc = 0; + let idxDst = 0; + for (let i = 0; i < count; i++) { + idxDst = 4 * i; + arrayBuffer[idxDst++] = src[idxSrc++]; + arrayBuffer[idxDst++] = src[idxSrc++]; + arrayBuffer[idxDst++] = src[idxSrc++]; + arrayBuffer[idxDst++] = src[idxSrc++]; + idxDst = 4 * (i + RealTimeJointTexture.WIDTH); + arrayBuffer[idxDst++] = src[idxSrc++]; + arrayBuffer[idxDst++] = src[idxSrc++]; + arrayBuffer[idxDst++] = src[idxSrc++]; + arrayBuffer[idxDst++] = src[idxSrc++]; + idxDst = 4 * (i + 2 * RealTimeJointTexture.WIDTH); + arrayBuffer[idxDst++] = src[idxSrc++]; + arrayBuffer[idxDst++] = src[idxSrc++]; + arrayBuffer[idxDst++] = src[idxSrc++]; + arrayBuffer[idxDst++] = src[idxSrc++]; + } + const pixelFormat = this._realTimeJointTexture._format; + const updateView = pixelFormat === PixelFormat.RGBA32F ? arrayBuffer : new Uint8Array(arrayBuffer.buffer); + textures[idx].uploadData(updateView); + } + } } diff --git a/cocos/3d/skeletal-animation/data-pool-manager.ts b/cocos/3d/skeletal-animation/data-pool-manager.ts index 89e6c77953..165812b5b5 100644 --- a/cocos/3d/skeletal-animation/data-pool-manager.ts +++ b/cocos/3d/skeletal-animation/data-pool-manager.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import type { AnimationClip } from '../../core/animation/animation-clip'; import type { Skeleton } from '../assets'; import { Device } from '../../core/gfx'; diff --git a/cocos/3d/skeletal-animation/deprecated.ts b/cocos/3d/skeletal-animation/deprecated.ts index dee04f8122..86c3a8d4e2 100644 --- a/cocos/3d/skeletal-animation/deprecated.ts +++ b/cocos/3d/skeletal-animation/deprecated.ts @@ -23,10 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module animation - */ import { js } from '../../core/utils/js'; import { legacyCC } from '../../core/global-exports'; import { SkeletalAnimation } from './skeletal-animation'; diff --git a/cocos/3d/skeletal-animation/index.ts b/cocos/3d/skeletal-animation/index.ts index fbdecc71e9..bb11159cb2 100644 --- a/cocos/3d/skeletal-animation/index.ts +++ b/cocos/3d/skeletal-animation/index.ts @@ -23,7 +23,6 @@ THE SOFTWARE. */ - import './data-pool-manager'; export * from './skeletal-animation-data-hub'; diff --git a/cocos/3d/skeletal-animation/skeletal-animation-blending.ts b/cocos/3d/skeletal-animation/skeletal-animation-blending.ts index 3de11f2919..b2ab97e4f6 100644 --- a/cocos/3d/skeletal-animation/skeletal-animation-blending.ts +++ b/cocos/3d/skeletal-animation/skeletal-animation-blending.ts @@ -24,10 +24,10 @@ */ import { DEBUG } from 'internal:constants'; -import { Vec3, Quat, approx } from '../../core/math'; +import { Vec3, Quat } from '../../core/math'; import { Node } from '../../core/scene-graph'; import { RuntimeBinding } from '../../core/animation/tracks/track'; -import { assertIsNonNullable, assertIsTrue } from '../../core/data/utils/asserts'; +import { assertIsTrue } from '../../core/data/utils/asserts'; import { MAX_ANIMATION_LAYER } from './limits'; export abstract class BlendStateBuffer< diff --git a/cocos/3d/skeletal-animation/skeletal-animation-data-hub.ts b/cocos/3d/skeletal-animation/skeletal-animation-data-hub.ts index be34c58924..0564780e09 100644 --- a/cocos/3d/skeletal-animation/skeletal-animation-data-hub.ts +++ b/cocos/3d/skeletal-animation/skeletal-animation-data-hub.ts @@ -23,10 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module animation - */ import { DataPoolManager } from './data-pool-manager'; import type { AnimationClip } from '../../core/animation/animation-clip'; import { legacyCC } from '../../core/global-exports'; @@ -35,7 +31,11 @@ import { BAKE_SKELETON_CURVE_SYMBOL } from '../../core/animation/internal-symbol type BakeData = ReturnType; /** + * @en + * The data conversion tool for skeleton animation + * @zh * 骨骼动画数据转换中心。 + * @internal */ export class SkelAnimDataHub { public static getOrExtract (clip: AnimationClip): BakeData { diff --git a/cocos/3d/skeletal-animation/skeletal-animation-state.ts b/cocos/3d/skeletal-animation/skeletal-animation-state.ts index 4b7727ee99..ff6c611645 100644 --- a/cocos/3d/skeletal-animation/skeletal-animation-state.ts +++ b/cocos/3d/skeletal-animation/skeletal-animation-state.ts @@ -23,11 +23,7 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module animation - */ - +import { JSB } from 'internal:constants'; import { Mat4, Quat, Vec3 } from '../../core/math'; import { IAnimInfo, JointAnimationInfo } from './skeletal-animation-utils'; import { Node } from '../../core/scene-graph/node'; @@ -36,7 +32,6 @@ import { AnimationState } from '../../core/animation/animation-state'; import { SkeletalAnimation, Socket } from './skeletal-animation'; import { SkelAnimDataHub } from './skeletal-animation-data-hub'; import { legacyCC } from '../../core/global-exports'; -import { JSB } from '../../core/default-constants'; const m4_1 = new Mat4(); const m4_2 = new Mat4(); @@ -52,6 +47,10 @@ interface ISocketData { frames: ITransform[]; } +/** + * @en The animation state for skeletal animations. + * @zh 骨骼动画的动画状态控制对象。 + */ export class SkeletalAnimationState extends AnimationState { protected _frames = 1; @@ -104,6 +103,12 @@ export class SkeletalAnimationState extends AnimationState { } } + /** + * @en Rebuild animation curves and register the socket transforms per frame to the sockets. It will replace the internal sockets list. + * @zh 为所有指定挂点更新动画曲线运算结果,并存储所有挂点的逐帧变换矩阵。这个方法会用传入的挂点更新取代内部挂点列表。 + * @param sockets @en The sockets need update @zh 需要重建的挂点列表 + * @returns void + */ public rebuildSocketCurves (sockets: Socket[]) { this._sockets.length = 0; if (!this._targetNode) { return; } diff --git a/cocos/3d/skeletal-animation/skeletal-animation-utils.ts b/cocos/3d/skeletal-animation/skeletal-animation-utils.ts index 519423162b..b78ffb4bb6 100644 --- a/cocos/3d/skeletal-animation/skeletal-animation-utils.ts +++ b/cocos/3d/skeletal-animation/skeletal-animation-utils.ts @@ -139,6 +139,10 @@ export interface ICustomJointTextureLayout { // For (Infinity - Infinity) evaluates to NaN const Inf = Number.MAX_SAFE_INTEGER; +/** + * The pool for joint textures. + * @internal + */ export class JointTexturePool { private _device: Device; diff --git a/cocos/3d/skeletal-animation/skeletal-animation.ts b/cocos/3d/skeletal-animation/skeletal-animation.ts index caa1283269..8690ba00c0 100644 --- a/cocos/3d/skeletal-animation/skeletal-animation.ts +++ b/cocos/3d/skeletal-animation/skeletal-animation.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module animation - */ - import { ccclass, executeInEditMode, executionOrder, help, menu, tooltip, type, serializable, editable, } from 'cc.decorator'; @@ -46,6 +41,10 @@ import type { AnimationState } from '../../core/animation/animation-state'; import { assertIsTrue } from '../../core/data/utils/asserts'; import { getGlobalAnimationManager } from '../../core/animation/global-animation-manager'; +/** + * @en The socket to synchronize transform from skeletal joint to target node. + * @zh 骨骼动画的挂点,用于将骨骼树的挂点节点变化矩阵同步到目标节点上 + */ @ccclass('cc.SkeletalAnimation.Socket') export class Socket { /** @@ -186,6 +185,16 @@ export class SkeletalAnimation extends Animation { this._removeAllUsers(); } + public onEnable () { + super.onEnable(); + this._currentBakedState?.resume(); + } + + public onDisable () { + super.onDisable(); + this._currentBakedState?.pause(); + } + public start () { this.sockets = this._sockets; this.useBakedAnimation = this._useBakedAnimation; @@ -217,6 +226,11 @@ export class SkeletalAnimation extends Animation { } } + /** + * @en Query all socket paths + * @zh 获取所有挂点的骨骼路径 + * @returns @en All socket paths @zh 所有挂点的骨骼路径 + */ public querySockets () { const animPaths = (this._defaultClip && Object.keys(SkelAnimDataHub.getOrExtract(this._defaultClip).joints).sort() .reduce((acc, cur) => (cur.startsWith(acc[acc.length - 1]) ? acc : (acc.push(cur), acc)), [] as string[])) || []; @@ -232,6 +246,10 @@ export class SkeletalAnimation extends Animation { return out; } + /** + * @en Rebuild animations to synchronize immediately all sockets to their target node. + * @zh 重建动画并立即同步所有挂点的转换矩阵到它们的目标节点上。 + */ public rebuildSocketAnimations () { for (const socket of this._sockets) { const joint = this.node.getChildByPath(socket.path); @@ -250,6 +268,14 @@ export class SkeletalAnimation extends Animation { } } + /** + * @en Create or get the target node from a socket. + * If a socket haven't been created for the corresponding path, this function will register a new socket. + * @zh 创建或获取一个挂点的同步目标节点。 + * 如果对应路径还没有创建挂点,这个函数会创建一个新的挂点。 + * @param path @en Path of the target joint. @zh 此挂点的骨骼路径。 + * @returns @en The target node of the socket. @zh 挂点的目标节点 + */ public createSocket (path: string) { const socket = this._sockets.find((s) => s.path === path); if (socket) { return socket.target; } @@ -286,7 +312,7 @@ export class SkeletalAnimation extends Animation { * @internal This method only friends to skinned mesh renderer. */ public notifySkinnedMeshRemoved (skinnedMeshRenderer: SkinnedMeshRenderer) { - assertIsTrue(skinnedMeshRenderer.associatedAnimation === this); + assertIsTrue(skinnedMeshRenderer.associatedAnimation === this || skinnedMeshRenderer.associatedAnimation === null); skinnedMeshRenderer.setUseBakedAnimation(false); skinnedMeshRenderer.associatedAnimation = null; this._users.delete(skinnedMeshRenderer); diff --git a/cocos/3d/skinned-mesh-renderer/deprecated.ts b/cocos/3d/skinned-mesh-renderer/deprecated.ts index 6f251d7816..f4780bd92d 100644 --- a/cocos/3d/skinned-mesh-renderer/deprecated.ts +++ b/cocos/3d/skinned-mesh-renderer/deprecated.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component - */ - import { SkinnedMeshRenderer } from './skinned-mesh-renderer'; import { SkinnedMeshBatchRenderer, SkinnedMeshUnit } from './skinned-mesh-batch-renderer'; import { js } from '../../core/utils/js'; diff --git a/cocos/3d/skinned-mesh-renderer/skinned-mesh-batch-renderer.ts b/cocos/3d/skinned-mesh-renderer/skinned-mesh-batch-renderer.ts index f601042fc1..2bf278e24d 100644 --- a/cocos/3d/skinned-mesh-renderer/skinned-mesh-batch-renderer.ts +++ b/cocos/3d/skinned-mesh-renderer/skinned-mesh-batch-renderer.ts @@ -22,11 +22,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module model - */ - import { EDITOR } from 'internal:constants'; import { ccclass, help, executeInEditMode, executionOrder, menu, tooltip, type, visible, override, serializable, editable, @@ -73,7 +68,9 @@ export class SkinnedMeshUnit { public material: Material | null = null; /** - * @legacyPublic + * @en Local transform matrix + * @zh 本地变换矩阵 + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @serializable public _localTransform = new Mat4(); @@ -213,7 +210,7 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _onMaterialModified (idx: number, material: Material | null) { this.cookMaterials(); diff --git a/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts b/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts index 75f5791b97..3ee9d4b6bf 100644 --- a/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts +++ b/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module model - */ - import { ccclass, executeInEditMode, executionOrder, help, menu, tooltip, type, } from 'cc.decorator'; @@ -77,7 +72,7 @@ export class SkinnedMeshRenderer extends MeshRenderer { /** * @en The skinning root. (The node where the controlling Animation is located) - * 骨骼根节点的引用,对应控制此模型的动画组件所在节点。 + * @zh 骨骼根节点的引用,对应控制此模型的动画组件所在节点。 */ @type(Node) @tooltip('i18n:model.skinning_root') @@ -142,6 +137,7 @@ export class SkinnedMeshRenderer extends MeshRenderer { this._models.length = 0; this._updateModels(); this._updateCastShadow(); + this._updateReceiveShadow(); if (this.enabledInHierarchy) { this._attachToScene(); } diff --git a/cocos/audio/audio-clip.ts b/cocos/audio/audio-clip.ts index 624c9ab0e7..da23bd5c6c 100644 --- a/cocos/audio/audio-clip.ts +++ b/cocos/audio/audio-clip.ts @@ -23,15 +23,8 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component/audio - */ - -import { - ccclass, type, serializable, override, -} from 'cc.decorator'; -import { AudioPlayer, OneShotAudio } from 'pal/audio'; +import { ccclass, serializable, override } from 'cc.decorator'; +import { AudioPlayer } from 'pal/audio'; import { Asset } from '../core/assets/asset'; import { legacyCC } from '../core/global-exports'; import { AudioState, AudioType } from '../../pal/audio/type'; @@ -45,9 +38,9 @@ export interface AudioMeta { /** * @en - * The audio clip asset.
+ * The audio clip asset. * @zh - * 音频片段资源。
+ * 音频片段资源。 */ @ccclass('cc.AudioClip') export class AudioClip extends Asset { @@ -73,7 +66,7 @@ export class AudioClip extends Asset { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ set _nativeAsset (meta: AudioMeta | null) { this._meta = meta; @@ -91,7 +84,7 @@ export class AudioClip extends Asset { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @override get _nativeDep () { diff --git a/cocos/audio/audio-downloader.ts b/cocos/audio/audio-downloader.ts index 76cac464c6..2a61fa730a 100644 --- a/cocos/audio/audio-downloader.ts +++ b/cocos/audio/audio-downloader.ts @@ -23,10 +23,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset-manager - */ import { AudioPlayer } from 'pal/audio'; import { AudioClip, AudioMeta } from './audio-clip'; diff --git a/cocos/audio/audio-source.ts b/cocos/audio/audio-source.ts index f784801f11..68b58b4dd4 100644 --- a/cocos/audio/audio-source.ts +++ b/cocos/audio/audio-source.ts @@ -23,20 +23,17 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component/audio - */ - import { AudioPlayer } from 'pal/audio'; import { ccclass, help, menu, tooltip, type, range, serializable } from 'cc.decorator'; -import { AudioState } from '../../pal/audio/type'; +import { AudioPCMDataView, AudioState } from '../../pal/audio/type'; import { Component } from '../core/components/component'; import { clamp } from '../core/math'; import { AudioClip } from './audio-clip'; import { audioManager } from './audio-manager'; import { Node } from '../core'; +const _LOADED_EVENT = 'audiosource-loaded'; + enum AudioSourceEventType { STARTED = 'started', ENDED = 'ended', @@ -111,6 +108,7 @@ export class AudioSource extends Component { return; } this._lastSetClip = clip; + this._operationsBeforeLoading.length = 0; AudioPlayer.load(clip._nativeAsset.url, { audioLoadMode: clip.loadMode, }).then((player) => { @@ -124,6 +122,7 @@ export class AudioSource extends Component { this._isLoaded = true; // clear old player if (this._player) { + audioManager.removePlaying(this._player); this._player.offEnded(); this._player.offInterruptionBegin(); this._player.offInterruptionEnd(); @@ -132,7 +131,7 @@ export class AudioSource extends Component { this._player = player; player.onEnded(() => { audioManager.removePlaying(player); - this.node.emit(AudioSourceEventType.ENDED, this); + this.node?.emit(AudioSourceEventType.ENDED, this); }); player.onInterruptionBegin(() => { audioManager.removePlaying(player); @@ -141,6 +140,7 @@ export class AudioSource extends Component { audioManager.addPlaying(player); }); this._syncStates(); + this.node?.emit(_LOADED_EVENT); }).catch((e) => {}); } @@ -226,6 +226,67 @@ export class AudioSource extends Component { this._player?.destroy(); this._player = null; } + /** + * @en + * Get PCM data from specified channel. + * Currently it is only available in Native platform and Web Audio (including Web and ByteDance platforms). + * + * @zh + * 通过指定的通道获取音频的 PCM data。 + * 目前仅在原生平台和 Web Audio(包括 Web 和 字节平台)中可用。 + * + * @param channelIndex The channel index. 0 is left channel, 1 is right channel. + * @returns A Promise to get the PCM data after audio is loaded. + * + * @example + * ```ts + * audioSource.getPCMData(0).then(dataView => { + * if (!dataView) return; + * for (let i = 0; i < dataView.length; ++i) { + * console.log('data: ' + dataView.getData(i)); + * } + * }); + * ``` + */ + public getPCMData (channelIndex: number): Promise { + return new Promise((resolve) => { + if (channelIndex !== 0 && channelIndex !== 1) { + console.warn('Only support channel index 0 or 1 to get buffer'); + resolve(undefined); + return; + } + if (this._player) { + resolve(this._player.getPCMData(channelIndex)); + } else { + this.node?.once(_LOADED_EVENT, () => { + resolve(this._player?.getPCMData(channelIndex)); + }); + } + }); + } + + /** + * @en + * Get the sample rate of audio. + * Currently it is only available in Native platform and Web Audio (including Web and ByteDance platforms). + * + * @zh + * 获取音频的采样率。 + * 目前仅在原生平台和 Web Audio(包括 Web 和 字节平台)中可用。 + * + * @returns A Promise to get the sample rate after audio is loaded. + */ + public getSampleRate (): Promise { + return new Promise((resolve) => { + if (this._player) { + resolve(this._player.sampleRate); + } else { + this.node?.once(_LOADED_EVENT, () => { + resolve(this._player!.sampleRate); + }); + } + }); + } private _getRootNode (): Node | null | undefined { let currentNode = this.node as Node | undefined | null; @@ -259,7 +320,7 @@ export class AudioSource extends Component { * - 直接播放音频,引擎会在下一次发生用户交互时自动播放。 */ public play () { - if (!this._isLoaded) { + if (!this._isLoaded && this.clip) { this._operationsBeforeLoading.push('play'); return; } @@ -270,7 +331,7 @@ export class AudioSource extends Component { } this._player?.play().then(() => { audioManager.addPlaying(this._player!); - this.node.emit(AudioSourceEventType.STARTED, this); + this.node?.emit(AudioSourceEventType.STARTED, this); }).catch((e) => {}); } @@ -281,7 +342,7 @@ export class AudioSource extends Component { * 暂停播放。 */ public pause () { - if (!this._isLoaded) { + if (!this._isLoaded && this.clip) { this._operationsBeforeLoading.push('pause'); return; } @@ -297,7 +358,7 @@ export class AudioSource extends Component { * 停止播放。 */ public stop () { - if (!this._isLoaded) { + if (!this._isLoaded && this.clip) { this._operationsBeforeLoading.push('stop'); return; } @@ -376,7 +437,7 @@ export class AudioSource extends Component { * 获取以秒为单位的音频总时长。 */ get duration () { - return this._clip?.getDuration() ?? (this._player ? this._player.currentTime : 0); + return this._clip?.getDuration() ?? (this._player ? this._player.duration : 0); } /** diff --git a/cocos/audio/category.json b/cocos/audio/category.json new file mode 100644 index 0000000000..51b6e7e92c --- /dev/null +++ b/cocos/audio/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "音频", + "en": "Audio" + }, + "description": { + "zh": "音乐是游戏中不可或缺的一部分,好的音乐能让游戏更加真实、富有沉浸感。Cocos Creator 的音频系统支持导入并播放大多数常见的音频文件格式", + "en": "Music is an integral part of a game, and good music makes a game more realistic and immersive. the audio system in Cocos Creator supports importing and playing most common audio file formats" + } +} \ No newline at end of file diff --git a/cocos/audio/deprecated.ts b/cocos/audio/deprecated.ts index b733daa73a..d305e82548 100644 --- a/cocos/audio/deprecated.ts +++ b/cocos/audio/deprecated.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { AudioSource } from './audio-source'; import { replaceProperty, markAsWarning } from '../core/utils/x-deprecated'; import { AudioClip } from './audio-clip'; diff --git a/cocos/audio/index.ts b/cocos/audio/index.ts index 10dd1eb83a..09882e8488 100644 --- a/cocos/audio/index.ts +++ b/cocos/audio/index.ts @@ -23,8 +23,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ - - import './audio-downloader'; import { AudioSource } from './audio-source'; @@ -35,6 +33,7 @@ import './deprecated'; export { AudioClip } from './audio-clip'; export { AudioSource }; +export { AudioPCMDataView } from '../../pal/audio/type'; export { AudioSource as AudioSourceComponent }; legacyCC.AudioSourceComponent = AudioSource; diff --git a/cocos/core/animation/animation-clip.ts b/cocos/core/animation/animation-clip.ts index 3422031900..c98ce97c20 100644 --- a/cocos/core/animation/animation-clip.ts +++ b/cocos/core/animation/animation-clip.ts @@ -23,12 +23,8 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module animation - */ - import { ccclass, serializable } from 'cc.decorator'; +import { DEBUG } from 'internal:constants'; import { Asset } from '../assets/asset'; import { SpriteFrame } from '../../2d/assets/sprite-frame'; import { error, errorID, getError, warn, warnID } from '../platform/debug'; @@ -38,7 +34,7 @@ import { murmurhash2_32_gc } from '../utils/murmurhash2_gc'; import { SkelAnimDataHub } from '../../3d/skeletal-animation/skeletal-animation-data-hub'; import { WrapMode as AnimationWrapMode, WrapMode, WrapModeMask } from './types'; import { legacyCC } from '../global-exports'; -import { Mat4, Quat, Vec3 } from '../math'; +import { approx, clamp, Mat4, Quat, Vec3 } from '../math'; import { Node } from '../scene-graph/node'; import { assertIsTrue } from '../data/utils/asserts'; import type { PoseOutput } from './pose-output'; @@ -54,6 +50,7 @@ import './exotic-animation/exotic-animation'; import { array } from '../utils/js'; import type { AnimationMask } from './marionette/animation-mask'; import { getGlobalAnimationManager } from './global-animation-manager'; +import { EmbeddedPlayableState, EmbeddedPlayer } from './embedded-player/embedded-player'; export declare namespace AnimationClip { export interface IEvent { @@ -62,6 +59,9 @@ export declare namespace AnimationClip { params: string[]; } + /** + * @internal + */ export type { legacy as _legacy }; } @@ -84,6 +84,12 @@ interface SkeletonAnimationBakeInfo { export const exoticAnimationTag = Symbol('ExoticAnimation'); +export const embeddedPlayerCountTag = Symbol('[[EmbeddedPlayerCount]]'); +export const getEmbeddedPlayersTag = Symbol('[[GetEmbeddedPlayers]]'); +export const addEmbeddedPlayerTag = Symbol('[[AddEmbeddedPlayer]]'); +export const removeEmbeddedPlayerTag = Symbol('[[RemoveEmbeddedPlayer]]'); +export const clearEmbeddedPlayersTag = Symbol('[[ClearEmbeddedPlayers]]'); + /** * @zh 动画剪辑表示一段使用动画编辑器编辑的关键帧动画或是外部美术工具生产的骨骼动画。 * 它的数据主要被分为几层:轨道、关键帧和曲线。 @@ -141,7 +147,7 @@ export class AnimationClip extends Asset { /** * Sets if node TRS curves in this animation can be blended. * Normally this flag is enabled for model animation and disabled for other case. - * @legacyPublic This is an internal slot. Never use it in your code. + * @internal This is an internal slot. Never use it in your code. */ @serializable public enableTrsBlending = false; @@ -159,14 +165,20 @@ export class AnimationClip extends Asset { } /** + * @en * Gets the count of tracks this animation owns. + * @zh + * 获取此动画中的轨道数量。 */ get tracksCount () { return this._tracks.length; } /** + * @en * Gets an iterable to tracks. + * @zh + * 获取可用于迭代轨道的对象。 */ get tracks (): Iterable { return this._tracks; @@ -233,7 +245,10 @@ export class AnimationClip extends Asset { } /** - * Counts the time range this animation spans. + * @en + * Counts the time range that the tracks within this animation span. + * @zh + * 获取此动画所有轨道占据的时间范围。 * @returns The time range. */ public range () { @@ -250,7 +265,10 @@ export class AnimationClip extends Asset { } /** + * @en * Gets the specified track. + * @zh + * 获取指定的轨道。 * @param index Index to the track. * @returns The track. */ @@ -259,7 +277,10 @@ export class AnimationClip extends Asset { } /** + * @en * Adds a track into this animation. + * @zh + * 添加一个轨道到此动画中。 * @param track The track. * @returns Index to the track. */ @@ -270,7 +291,10 @@ export class AnimationClip extends Asset { } /** + * @en * Removes a track from this animation. + * @zh + * 移除此动画中的指定轨道。 * @param index Index to the track. */ public removeTrack (index: number) { @@ -278,7 +302,10 @@ export class AnimationClip extends Asset { } /** + * @en * Removes all tracks from this animation. + * @zh + * 移除此动画的所有轨道。 */ public clearTracks () { this._tracks.length = 0; @@ -287,8 +314,7 @@ export class AnimationClip extends Asset { /** * Creates an event evaluator for this animation. * @param targetNode Target node used to fire events. - * @returns - * @legacyPublic Do not use this in your code. + * @internal Do not use this in your code. */ public createEventEvaluator (targetNode: Node) { return new EventEvaluator( @@ -299,11 +325,23 @@ export class AnimationClip extends Asset { ); } + /** + * Creates an embedded player evaluator for this animation. + * @param targetNode Target node. + * @internal Do not use this in your code. + */ + public createEmbeddedPlayerEvaluator (targetNode: Node) { + return new EmbeddedPlayerEvaluation( + this._embeddedPlayers, + targetNode, + ); + } + /** * Creates an evaluator for this animation. * @param context The context. * @returns The evaluator. - * @legacyPublic Do not use this in your code. + * @internal Do not use this in your code. */ public createEvaluator (context: AnimationClipEvalContext) { const { @@ -320,7 +358,17 @@ export class AnimationClip extends Asset { this.enableTrsBlending ? context.pose : undefined, false, ); - // TODO: warning + if (DEBUG && !trackTarget) { + // If we got a null track target here, we should already have warn logged, + // To elaborate on error details, we warn here as well. + // Note: if in the future this log appears alone, + // it must be a BUG which break promise by above statement. + warnID( + 3937, + this.name, + (context.target instanceof Node) ? context.target.name : context.target, + ); + } return trackTarget ?? undefined; }; @@ -413,7 +461,7 @@ export class AnimationClip extends Asset { /** * Convert all untyped tracks into typed ones and delete the original. * @param refine How to decide the type on specified path. - * @legacyPublic DO NOT USE THIS IN YOUR CODE. + * @internal DO NOT USE THIS IN YOUR CODE. */ public upgradeUntypedTracks (refine: UntypedTrackRefine) { const newTracks: Track[] = []; @@ -439,7 +487,7 @@ export class AnimationClip extends Asset { } /** - * Export for test. + * @internal Export for test. */ public [searchForRootBonePathSymbol] () { return this._searchForRootBonePath(); @@ -491,6 +539,9 @@ export class AnimationClip extends Asset { } /** + * @en + * The animation's data. + * @zh * 此动画的数据。 * @deprecated Since V3.3. Please reference to the track/channel/curve mechanism introduced in V3.3. */ @@ -506,7 +557,6 @@ export class AnimationClip extends Asset { } /** - * @protected * @deprecated Since V3.3. Please reference to the track/channel/curve mechanism introduced in V3.3. */ get eventGroups (): readonly IAnimationEventGroup[] { @@ -538,7 +588,7 @@ export class AnimationClip extends Asset { * Migrates legacy data into tracks. * NOTE: This method tend to be used as internal purpose or patch. * DO NOT use it in your code since it might be removed for the future at any time. - * @deprecated Since V3.3. Please reference to the track/channel/curve mechanism introduced in V3.3. + * @internal Since V3.3. Please reference to the track/channel/curve mechanism introduced in V3.3. */ public syncLegacyData () { if (this._legacyData) { @@ -549,6 +599,44 @@ export class AnimationClip extends Asset { // #endregion + /** + * @internal + */ + get [embeddedPlayerCountTag] () { + return this._embeddedPlayers.length; + } + + /** + * @internal + */ + public [getEmbeddedPlayersTag] (): Iterable { + return this._embeddedPlayers; + } + + /** + * @internal + */ + public [addEmbeddedPlayerTag] (embeddedPlayer: EmbeddedPlayer) { + this._embeddedPlayers.push(embeddedPlayer); + } + + /** + * @internal + */ + public [removeEmbeddedPlayerTag] (embeddedPlayer: EmbeddedPlayer) { + const iEmbeddedPlayer = this._embeddedPlayers.indexOf(embeddedPlayer); + if (iEmbeddedPlayer >= 0) { + this._embeddedPlayers.splice(iEmbeddedPlayer, 1); + } + } + + /** + * @internal + */ + public [clearEmbeddedPlayersTag] () { + this._embeddedPlayers.length = 0; + } + @serializable private _duration = 0; @@ -570,6 +658,9 @@ export class AnimationClip extends Asset { @serializable private _events: AnimationClip.IEvent[] = []; + @serializable + private _embeddedPlayers: EmbeddedPlayer[] = []; + private _runtimeEvents: { ratios: number[]; eventGroups: IAnimationEventGroup[]; @@ -826,6 +917,184 @@ interface RootMotionOptions { type ExoticAnimationEvaluator = ReturnType; +class EmbeddedPlayerEvaluation { + constructor (embeddedPlayers: ReadonlyArray, rootNode: Node) { + this._embeddedPlayers = embeddedPlayers; + this._embeddedPlayerEvaluationInfos = embeddedPlayers.map( + (embeddedPlayer): EmbeddedPlayerEvaluation['_embeddedPlayerEvaluationInfos'][0] => { + const { playable: player } = embeddedPlayer; + if (!player) { + return null; + } + const instantiatedPlayer = player.instantiate(rootNode); + if (!instantiatedPlayer) { + return null; + } + return { + instantiatedPlayer, + entered: false, + hostPauseTime: 0.0, + lastIterations: 0, + }; + }, + ); + } + + /** + * Evaluates the embedded players. + * @param time The time([0, clipDuration]). + * @param iterations The iterations the evaluation occurred. Should be integral. + */ + public evaluate (time: number, iterations: number) { + assertIsTrue(Number.isInteger(iterations)); + const { + _embeddedPlayers: embeddedPlayers, + _embeddedPlayerEvaluationInfos: embeddedPlayerEvaluationInfos, + } = this; + const nEmbeddedPlayers = embeddedPlayers.length; + for (let iEmbeddedPlayer = 0; iEmbeddedPlayer < nEmbeddedPlayers; ++iEmbeddedPlayer) { + const embeddedPlayerEvaluationInfo = embeddedPlayerEvaluationInfos[iEmbeddedPlayer]; + if (!embeddedPlayerEvaluationInfo) { + continue; + } + const { entered, instantiatedPlayer, lastIterations } = embeddedPlayerEvaluationInfo; + const { begin, end } = embeddedPlayers[iEmbeddedPlayer]; + const withinEmbeddedPlayer = time >= begin && time <= end; + if (withinEmbeddedPlayer) { + if (!entered) { + instantiatedPlayer.play(); + embeddedPlayerEvaluationInfo.entered = true; + } else if (iterations !== lastIterations) { + instantiatedPlayer.stop(); + instantiatedPlayer.play(); + embeddedPlayerEvaluationInfo.entered = true; + } + } else if (entered) { + instantiatedPlayer.stop(); + embeddedPlayerEvaluationInfo.entered = false; + } + embeddedPlayerEvaluationInfo.lastIterations = iterations; + if (embeddedPlayerEvaluationInfo.entered) { + const playerTime = time - begin; + embeddedPlayerEvaluationInfo.instantiatedPlayer.setTime(playerTime); + } + } + } + + public notifyHostSpeedChanged (speed: number) { + // Transmit the speed to embedded players that want a reconciled speed. + const { + _embeddedPlayers: embeddedPlayers, + _embeddedPlayerEvaluationInfos: embeddedPlayerEvaluationInfos, + } = this; + const nEmbeddedPlayers = embeddedPlayers.length; + for (let iEmbeddedPlayer = 0; iEmbeddedPlayer < nEmbeddedPlayers; ++iEmbeddedPlayer) { + const embeddedPlayerEvaluationInfo = embeddedPlayerEvaluationInfos[iEmbeddedPlayer]; + if (!embeddedPlayerEvaluationInfo) { + continue; + } + const { instantiatedPlayer } = embeddedPlayerEvaluationInfo; + const { reconciledSpeed } = embeddedPlayers[iEmbeddedPlayer]; + if (reconciledSpeed) { + instantiatedPlayer.setSpeed(speed); + } + } + } + + /** + * Notifies that the host has ran into **playing** state. + * @param time The time where host ran into playing state. + */ + public notifyHostPlay (time: number) { + // Host has switched to "playing", this can be happened when: + // - Previous state is "stopped": we must have stopped all embedded players. + // - Is pausing: we need to resume all embedded players. + const { + _embeddedPlayers: embeddedPlayers, + _embeddedPlayerEvaluationInfos: embeddedPlayerEvaluationInfos, + } = this; + const nEmbeddedPlayers = embeddedPlayers.length; + for (let iEmbeddedPlayer = 0; iEmbeddedPlayer < nEmbeddedPlayers; ++iEmbeddedPlayer) { + const embeddedPlayerEvaluationInfo = embeddedPlayerEvaluationInfos[iEmbeddedPlayer]; + if (!embeddedPlayerEvaluationInfo) { + continue; + } + const { begin, end } = embeddedPlayers[iEmbeddedPlayer]; + const { instantiatedPlayer, entered } = embeddedPlayerEvaluationInfo; + if (entered) { + const { hostPauseTime } = embeddedPlayerEvaluationInfo; + // We can resume the embedded player + // only if the pause/play happened at the same time + // or the embedded player supports random access. + // Otherwise we have to say goodbye to that embedded player. + if (instantiatedPlayer.randomAccess || approx(hostPauseTime, time, 1e-5)) { + const startTime = clamp(time, begin, end); + instantiatedPlayer.play(); + instantiatedPlayer.setTime(startTime - begin); + } else { + instantiatedPlayer.stop(); + } + } + } + } + + /** + * Notifies that the host has ran into **pause** state. + */ + public notifyHostPause (time: number) { + // Host is paused, simply transmit this to embedded players. + const { + _embeddedPlayers: embeddedPlayers, + _embeddedPlayerEvaluationInfos: embeddedPlayerEvaluationInfos, + } = this; + const nEmbeddedPlayers = embeddedPlayers.length; + for (let iEmbeddedPlayer = 0; iEmbeddedPlayer < nEmbeddedPlayers; ++iEmbeddedPlayer) { + const embeddedPlayerEvaluationInfo = embeddedPlayerEvaluationInfos[iEmbeddedPlayer]; + if (!embeddedPlayerEvaluationInfo) { + continue; + } + const { instantiatedPlayer, entered } = embeddedPlayerEvaluationInfo; + if (entered) { + instantiatedPlayer.pause(); + embeddedPlayerEvaluationInfo.hostPauseTime = time; + } + } + } + + /** + * Notifies that the host has ran into **stopped** state. + */ + public notifyHostStop () { + // Now that host is stopped, we stop all embedded players' playing + // regardless of their progresses. + const { + _embeddedPlayers: embeddedPlayers, + _embeddedPlayerEvaluationInfos: embeddedPlayerEvaluationInfos, + } = this; + const nEmbeddedPlayers = embeddedPlayers.length; + for (let iEmbeddedPlayer = 0; iEmbeddedPlayer < nEmbeddedPlayers; ++iEmbeddedPlayer) { + const embeddedPlayerEvaluationInfo = embeddedPlayerEvaluationInfos[iEmbeddedPlayer]; + if (!embeddedPlayerEvaluationInfo) { + continue; + } + const { instantiatedPlayer, entered } = embeddedPlayerEvaluationInfo; + if (entered) { + embeddedPlayerEvaluationInfo.entered = false; + instantiatedPlayer.stop(); + } + } + } + + private declare _embeddedPlayers: ReadonlyArray; + + private declare _embeddedPlayerEvaluationInfos: Array; +} + class AnimationClipEvaluation { constructor ( trackEvalStatuses: TrackEvalStatus[], diff --git a/cocos/core/animation/animation-component.ts b/cocos/core/animation/animation-component.ts index 251687c8ad..e5b668cbbc 100644 --- a/cocos/core/animation/animation-component.ts +++ b/cocos/core/animation/animation-component.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module animation - */ - import { ccclass, executeInEditMode, executionOrder, help, menu, tooltip, type, serializable } from 'cc.decorator'; import { EDITOR, TEST } from 'internal:constants'; import { Component } from '../components/component'; @@ -39,10 +34,7 @@ import { AnimationClip } from './animation-clip'; import { AnimationState, EventType } from './animation-state'; import { CrossFade } from './cross-fade'; import { legacyCC } from '../global-exports'; -import { LegacyBlendStateBuffer } from '../../3d/skeletal-animation/skeletal-animation-blending'; -import { AnimationUpdateTaskHandle } from './animation-manager'; -import { assertIsTrue } from '../data/utils/asserts'; -import { getGlobalAnimationManager } from './global-animation-manager'; +import { js } from '../utils/js'; /** * @en @@ -110,7 +102,7 @@ export class Animation extends Eventify(Component) { * @en * Gets or sets the default clip. * Two clips that both have same non-empty UUID are treat as equivalent. - * @en + * @zh * 获取或设置默认剪辑。 * 设置时,若指定的剪辑不在 `this.clips` 中则会被自动添加至 `this.clips`。 * 具有相同的非空 UUID 的两个动画剪辑将被视为是相同的。 @@ -148,18 +140,28 @@ export class Animation extends Eventify(Component) { @tooltip('i18n:animation.play_on_load') public playOnLoad = false; + /** + * @internal + */ protected _crossFade = new CrossFade(); + /** + * @internal + */ protected _nameToState: Record = createMap(true); + /** + * @internal + */ @type([AnimationClip]) protected _clips: (AnimationClip | null)[] = []; + /** + * @internal + */ @serializable protected _defaultClip: AnimationClip | null = null; - private _animationUpdateTaskHandle: AnimationUpdateTaskHandle | undefined = undefined; - /** * Whether if `crossFade()` or `play()` has been called before this component starts. */ @@ -169,7 +171,7 @@ export class Animation extends Eventify(Component) { this.clips = this._clips; for (const stateName in this._nameToState) { const state = this._nameToState[stateName]; - this._initializeState(state); + state.initialize(this.node); } } @@ -180,20 +182,15 @@ export class Animation extends Eventify(Component) { } public onEnable () { - assertIsTrue(!this._animationUpdateTaskHandle); - this._animationUpdateTaskHandle = getGlobalAnimationManager().addUpdateTask( - this._onAnimationSystemUpdate, - this, - ); + this._crossFade.resume(); } public onDisable () { - assertIsTrue(typeof this._animationUpdateTaskHandle !== 'undefined'); - getGlobalAnimationManager().removeUpdateTask(this._animationUpdateTaskHandle); - this._animationUpdateTaskHandle = undefined; + this._crossFade.pause(); } public onDestroy () { + this._crossFade.stop(); for (const name in this._nameToState) { const state = this._nameToState[name]; state.destroy(); @@ -210,7 +207,6 @@ export class Animation extends Eventify(Component) { */ public play (name?: string) { this._hasBeenPlayed = true; - this._playing = true; if (!name) { if (!this._defaultClip) { return; @@ -223,14 +219,13 @@ export class Animation extends Eventify(Component) { /** * @en * Smoothly switch to play specified animation state. - * @zn + * @zh * 平滑地切换到指定动画状态。 * @param name The name of the animation to switch to * @param duration The duration of the cross fade, default value is 0.3s */ public crossFade (name: string, duration = 0.3) { this._hasBeenPlayed = true; - this._playing = true; const state = this._nameToState[name]; if (state) { this.doPlayOrCrossFade(state, duration); @@ -244,7 +239,6 @@ export class Animation extends Eventify(Component) { * 暂停所有动画状态,并暂停所有切换。 */ public pause () { - this._playing = false; this._crossFade.pause(); } @@ -255,7 +249,6 @@ export class Animation extends Eventify(Component) { * 恢复所有动画状态,并恢复所有切换。 */ public resume () { - this._playing = true; this._crossFade.resume(); } @@ -266,19 +259,7 @@ export class Animation extends Eventify(Component) { * 停止所有动画状态,并停止所有切换。 */ public stop () { - this._playing = false; - this._crossFade.clear(); - } - - /** - * @en - * Get specified animation state. - * @zh - * 获取指定的动画状态。 - * @deprecated please use [[getState]] - */ - public getAnimationState (name: string) { - return this.getState(name); + this._crossFade.stop(); } /** @@ -292,7 +273,7 @@ export class Animation extends Eventify(Component) { public getState (name: string) { const state = this._nameToState[name]; if (state && !state.curveLoaded) { - this._initializeState(state); + state.initialize(this.node); } return state || null; } @@ -332,8 +313,10 @@ export class Animation extends Eventify(Component) { } /** + * @zh * 添加一个动画剪辑到 `this.clips`中并以此剪辑创建动画状态。 - * @deprecated please use [[createState]] + * @en + * Adds an animation clip into this component and creates a animation state for this clip. * @param clip The animation clip * @param name The animation state name, if absent, the default clip's name will be used * @returns The created animation state @@ -355,7 +338,6 @@ export class Animation extends Eventify(Component) { * 从动画列表中移除指定的动画剪辑,
* 如果依赖于 clip 的 AnimationState 正在播放或者 clip 是 defaultClip 的话,默认是不会删除 clip 的。
* 但是如果 force 参数为 true,则会强制停止该动画,然后移除该动画剪辑和相关的动画。这时候如果 clip 是 defaultClip,defaultClip 将会被重置为 null。
- * @deprecated please use [[removeState]] * @param force - If force is true, then will always remove the clip and any animation states based on it. */ public removeClip (clip: AnimationClip, force?: boolean) { @@ -451,50 +433,35 @@ export class Animation extends Eventify(Component) { } } + /** + * @internal + */ protected _createState (clip: AnimationClip, name?: string) { return new AnimationState(clip, name); } + /** + * @internal + */ protected _doCreateState (clip: AnimationClip, name: string) { const state = this._createState(clip, name); state._setEventTarget(this); state.allowLastFrameEvent(this.hasEventListener(EventType.LASTFRAME)); if (this.node) { - this._initializeState(state); + state.initialize(this.node); } this._nameToState[state.name] = state; return state; } /** - * * @internal This method only friends to skeletal animation component. */ protected doPlayOrCrossFade (state: AnimationState, duration: number) { + this._crossFade.play(); this._crossFade.crossFade(state, duration); } - private _playing = false; - - private _blendStateBuffer = new LegacyBlendStateBuffer(); - - private _onAnimationSystemUpdate (deltaTime: number) { - if (!this._playing) { - return; - } - - this._crossFade.update(deltaTime); - - for (const name in this._nameToState) { - const state = this._nameToState[name]; - if (!state.isMotionless) { - state.update(deltaTime); - } - } - - this._blendStateBuffer.apply(); - } - private _removeStateOfAutomaticClip (clip: AnimationClip) { for (const name in this._nameToState) { const state = this._nameToState[name]; @@ -520,19 +487,12 @@ export class Animation extends Eventify(Component) { } } } - - private _initializeState (state: AnimationState) { - state.initialize( - this.node, - this._blendStateBuffer, - undefined, // Animation Mask - true, // Passive - The updating of animation state is handled by us - ); - } } +type EventType_ = EventType; + export declare namespace Animation { - export type EventType = EnumAlias; + export type EventType = EventType_; } function equalClips (clip1: AnimationClip | null, clip2: AnimationClip | null) { @@ -543,3 +503,11 @@ function equalClips (clip1: AnimationClip | null, clip2: AnimationClip | null) { } legacyCC.Animation = Animation; + +/** + * Alias of [[Animation]] + * @deprecated Since v1.2 + */ +export { Animation as AnimationComponent }; +legacyCC.AnimationComponent = Animation; +js.setClassAlias(Animation, 'cc.AnimationComponent'); diff --git a/cocos/core/animation/animation-curve.ts b/cocos/core/animation/animation-curve.ts index 55b5e68680..eeeff2b43d 100644 --- a/cocos/core/animation/animation-curve.ts +++ b/cocos/core/animation/animation-curve.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module animation - */ - import { binarySearchEpsilon as binarySearch } from '../algorithm/binary-search'; import { lerp, Quat } from '../math'; import { errorID } from '../platform/debug'; @@ -38,6 +33,9 @@ import { ILerpable, isLerpable } from './types'; import { legacyCC } from '../global-exports'; import type * as legacy from './legacy-clip-data'; +/** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ export class RatioSampler { public ratios: number[]; @@ -69,7 +67,11 @@ export class RatioSampler { legacyCC.RatioSampler = RatioSampler; /** + * @en + * Animation curve. + * @zh * 动画曲线。 + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ export class AnimCurve { public static Linear = null; @@ -232,10 +234,14 @@ export class EventInfo { } /** + * @zh * 采样动画曲线。 - * @param curve 动画曲线。 - * @param sampler 采样器。 - * @param ratio 采样比率。 + * @en + * Samples an animation curve. + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + * @param curve @zh 动画曲线。@en The curve. + * @param sampler @zh 采样器。@en The sampler. + * @param ratio @zh 采样比率。@en Sample ratio([0, 1]). */ export function sampleAnimationCurve (curve: AnimCurve, sampler: RatioSampler, ratio: number) { let index = sampler.sample(ratio); @@ -258,10 +264,14 @@ export function sampleAnimationCurve (curve: AnimCurve, sampler: RatioSampler, r legacyCC.sampleAnimationCurve = sampleAnimationCurve; /** + * @en * Compute a new ratio by curve type. + * @zh + * 根据曲线类型计算新的比例。 * @param ratio - The origin ratio * @param type - If it's Array, then ratio will be computed with bezierByTime. * If it's string, then ratio will be computed with cc.easing function + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ export function computeRatioByType (ratio: number, type: legacy.LegacyEasingMethod) { if (typeof type === 'string') { diff --git a/cocos/core/animation/animation-manager.ts b/cocos/core/animation/animation-manager.ts index b2944fd206..fe960f6c8d 100644 --- a/cocos/core/animation/animation-manager.ts +++ b/cocos/core/animation/animation-manager.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module animation - */ - import { ccclass } from 'cc.decorator'; import System from '../components/system'; import { director, Director } from '../director'; @@ -37,6 +32,7 @@ import { Scheduler } from '../scheduler'; import { MutableForwardIterator, remove } from '../utils/array'; import { LegacyBlendStateBuffer } from '../../3d/skeletal-animation/skeletal-animation-blending'; import { AnimationState } from './animation-state'; +import type { CrossFade } from './cross-fade'; import { legacyCC } from '../global-exports'; import { IJointTransform, deleteTransform, getTransform, getWorldMatrix } from './skeletal-animation-utils'; import { Socket } from '../../3d/skeletal-animation/skeletal-animation'; @@ -46,18 +42,6 @@ interface ISocketData { transform: IJointTransform; } -/** - * Opacity value which is guaranteed to not be null or undefined. - */ -export interface AnimationUpdateTaskHandle { - readonly __brand: 'AnimationUpdateTaskHandle'; -} - -interface AnimationUpdateTask extends AnimationUpdateTaskHandle { - callback: (this: T, deltaTime: number) => void; - thisArg: T; -} - @ccclass export class AnimationManager extends System { public get blendState (): LegacyBlendStateBuffer { @@ -66,6 +50,7 @@ export class AnimationManager extends System { public static ID = 'animation'; private _anims = new MutableForwardIterator([]); + private _crossFades = new MutableForwardIterator([]); private _delayEvents: { fn: (...args: any[]) => void; thisArg: any; @@ -73,25 +58,32 @@ export class AnimationManager extends System { }[] = []; private _blendStateBuffer: LegacyBlendStateBuffer = new LegacyBlendStateBuffer(); private _sockets: ISocketData[] = []; - private _updateTasks: AnimationUpdateTask[] = []; - public addUpdateTask (callback: (this: T, deltaTime: number) => void, thisArg: T): AnimationUpdateTaskHandle { - const task = { callback, thisArg } as AnimationUpdateTask; - this._updateTasks.push(task); - return task; + public addCrossFade (crossFade: CrossFade) { + const index = this._crossFades.array.indexOf(crossFade); + if (index === -1) { + this._crossFades.push(crossFade); + } } - public removeUpdateTask (handle: AnimationUpdateTaskHandle) { - remove(this._updateTasks, handle); + public removeCrossFade (crossFade: CrossFade) { + const index = this._crossFades.array.indexOf(crossFade); + if (index >= 0) { + this._crossFades.fastRemoveAt(index); + } else { + errorID(3907); + } } public update (dt: number) { - const { _updateTasks: updateTasks, _delayEvents, _sockets } = this; + const { _delayEvents, _crossFades: crossFadesIter, _sockets } = this; - const nUpdateTasks = updateTasks.length; - for (let iUpdateTask = 0; iUpdateTask < nUpdateTasks; ++iUpdateTask) { - const { callback, thisArg } = updateTasks[iUpdateTask]; - callback.call(thisArg, dt); + { // Update cross fades + const crossFades = crossFadesIter.array; + for (crossFadesIter.i = 0; crossFadesIter.i < crossFades.length; ++crossFadesIter.i) { + const crossFade = crossFades[crossFadesIter.i]; + crossFade.update(dt); + } } const iterator = this._anims; diff --git a/cocos/core/animation/animation-state.ts b/cocos/core/animation/animation-state.ts index b87cd3c9c9..6e883dee0a 100644 --- a/cocos/core/animation/animation-state.ts +++ b/cocos/core/animation/animation-state.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module animation - */ - import { EDITOR } from 'internal:constants'; import { Node } from '../scene-graph/node'; import { AnimationClip } from './animation-clip'; @@ -221,7 +216,14 @@ export class AnimationState extends Playable { * @zh 播放速率。 * @default: 1.0 */ - public speed = 1.0; + get speed () { + return this._speed; + } + + set speed (value) { + this._speed = value; + this._clipEmbeddedPlayerEval.notifyHostSpeedChanged(value); + } /** * @en The current accumulated time of this animation in seconds. @@ -243,11 +245,14 @@ export class AnimationState extends Playable { * @zh 获取动画播放的比例时间。 */ get ratio () { - return this.current / this.duration; + return this.duration === 0.0 ? 0.0 : this.current / this.duration; } /** - * The weight. + * @en + * The weight of this animation state. + * @zh + * 此动画状态的权重。 */ get weight () { return this._weight; @@ -263,16 +268,17 @@ export class AnimationState extends Playable { public frameRate = 0; /** - * This field is only visible from within internal. + * @internal This field is only visible from within internal. */ protected _targetNode: Node | null = null; /** - * This field is only visible from within internal. + * @internal This field is only visible from within internal. */ protected _curveLoaded = false; private _clip: AnimationClip; + private _speed = 1.0; private _useSimpleProcess = false; private _target: Node | null = null; private _wrapMode = WrapMode.Normal; @@ -299,15 +305,9 @@ export class AnimationState extends Playable { private _weight = 1.0; private _clipEval: ReturnType | undefined; private _clipEventEval: ReturnType | undefined; + private declare _clipEmbeddedPlayerEval: ReturnType; /** - * Sets if this animation state is passive. - * If a state is passive, - * the state's `update()` should be called somewhere to drive the effect of `play()`. - * Otherwise, the `update()` is called uniformly by main loop. - */ - private _passive = false; - /** - * For internal usage. Really hack... + * @internal For internal usage. Really hack... */ protected _doNotCreateEval = false; @@ -332,7 +332,7 @@ export class AnimationState extends Playable { return this._curveLoaded; } - public initialize (root: Node, blendStateBuffer?: BlendStateBuffer, mask?: AnimationMask, passive?: boolean) { + public initialize (root: Node, blendStateBuffer?: BlendStateBuffer, mask?: AnimationMask) { if (this._curveLoaded) { return; } this._curveLoaded = true; if (this._poseOutput) { @@ -348,7 +348,7 @@ export class AnimationState extends Playable { this.duration = clip.duration; this._invDuration = 1.0 / this.duration; - this.speed = clip.speed; + this._speed = clip.speed; this.wrapMode = clip.wrapMode; this.frameRate = clip.sample; this._playbackRange.min = 0.0; @@ -376,14 +376,14 @@ export class AnimationState extends Playable { if (!(EDITOR && !legacyCC.GAME_VIEW)) { this._clipEventEval = clip.createEventEvaluator(this._targetNode); } - this._passive = passive ?? false; + + this._clipEmbeddedPlayerEval = clip.createEmbeddedPlayerEvaluator(this._targetNode); + this._clipEmbeddedPlayerEval.notifyHostSpeedChanged(this._speed); } public destroy () { - if (!this._passive) { - if (!this.isMotionless) { - getGlobalAnimationManager().removeAnimation(this); - } + if (!this.isMotionless) { + getGlobalAnimationManager().removeAnimation(this); } if (this._poseOutput) { this._poseOutput.destroy(); @@ -453,7 +453,7 @@ export class AnimationState extends Playable { /** * This method is used for internal purpose only. - * @legacyPublic + * @internal */ public _setEventTarget (target) { this._target = target; @@ -498,6 +498,7 @@ export class AnimationState extends Playable { if (!EDITOR || legacyCC.GAME_VIEW) { this._sampleEvents(info); } + this._sampleEmbeddedPlayers(info); return info; } @@ -506,6 +507,7 @@ export class AnimationState extends Playable { this._delayTime = this._delay; this._onReplayOrResume(); this.emit(EventType.PLAY, this); + this._clipEmbeddedPlayerEval.notifyHostPlay(this.current); } protected onStop () { @@ -513,18 +515,24 @@ export class AnimationState extends Playable { this._onPauseOrStop(); } this.emit(EventType.STOP, this); + this._clipEmbeddedPlayerEval.notifyHostStop(); } protected onResume () { this._onReplayOrResume(); this.emit(EventType.RESUME, this); + this._clipEmbeddedPlayerEval.notifyHostPlay(this.current); } protected onPause () { this._onPauseOrStop(); this.emit(EventType.PAUSE, this); + this._clipEmbeddedPlayerEval.notifyHostPause(this.current); } + /** + * @internal + */ protected _sampleCurves (time: number) { const { _poseOutput: poseOutput, _clipEval: clipEval } = this; if (poseOutput) { @@ -572,16 +580,25 @@ export class AnimationState extends Playable { const playbackStart = this._playbackRange.min; const playbackDuration = this._playbackDuration; - let time = this.time % playbackDuration; - if (time < 0.0) { time += playbackDuration; } - const realTime = playbackStart + time; - const ratio = realTime * this._invDuration; + let time = 0.0; + let ratio = 0.0; + if (playbackDuration !== 0.0) { + time = this.time % playbackDuration; + if (time < 0.0) { + time += playbackDuration; + } + const realTime = playbackStart + time; + ratio = realTime * this._invDuration; + } this._sampleCurves(playbackStart + time); + const wrapInfo = this.getWrappedInfo(this.time, this._wrappedInfo); if (!EDITOR || legacyCC.GAME_VIEW) { - this._sampleEvents(this.getWrappedInfo(this.time, this._wrappedInfo)); + this._sampleEvents(wrapInfo); } + this._sampleEmbeddedPlayers(wrapInfo); + if (this._allowLastFrame) { if (Number.isNaN(this._lastIterations)) { this._lastIterations = ratio; @@ -622,9 +639,18 @@ export class AnimationState extends Playable { const playbackStart = this._getPlaybackStart(); const playbackEnd = this._getPlaybackEnd(); const playbackDuration = playbackEnd - playbackStart; + const repeatCount = this.repeatCount; + + if (playbackDuration === 0.0) { + info.time = 0.0; + info.ratio = 0.0; + info.direction = 1.0; + info.stopped = !!Number.isFinite(repeatCount); + info.iterations = 0.0; + return info; + } let stopped = false; - const repeatCount = this.repeatCount; time -= playbackStart; @@ -689,6 +715,13 @@ export class AnimationState extends Playable { ); } + private _sampleEmbeddedPlayers (wrapInfo: WrappedInfo) { + this._clipEmbeddedPlayerEval.evaluate( + wrapInfo.time, + Math.trunc(wrapInfo.iterations), + ); + } + private _emit (type, state) { if (this._target && this._target.isValid) { this._target.emit(type, type, state); @@ -696,15 +729,11 @@ export class AnimationState extends Playable { } private _onReplayOrResume () { - if (!this._passive) { - getGlobalAnimationManager().addAnimation(this); - } + getGlobalAnimationManager().addAnimation(this); } private _onPauseOrStop () { - if (!this._passive) { - getGlobalAnimationManager().removeAnimation(this); - } + getGlobalAnimationManager().removeAnimation(this); } } diff --git a/cocos/core/animation/animation.ts b/cocos/core/animation/animation.ts index c066f9a6a0..53f5f5c109 100644 --- a/cocos/core/animation/animation.ts +++ b/cocos/core/animation/animation.ts @@ -23,7 +23,10 @@ THE SOFTWARE. */ - +import './embedded-player/embedded-player'; +import './embedded-player/embedded-animation-clip-player'; +import './embedded-player/embedded-particle-system-player'; +import './tracks/array-track'; export * from './target-path'; export * from './value-proxy'; diff --git a/cocos/core/animation/category.json b/cocos/core/animation/category.json index 41974fb9ca..8c19295caf 100644 --- a/cocos/core/animation/category.json +++ b/cocos/core/animation/category.json @@ -4,7 +4,7 @@ "en": "Animation" }, "description": { - "zh": "动画", - "en": "Animation" + "zh": "Cocos Creator 内置了通用的动画系统用以实现基于关键帧的动画。除了支持标准的位移、旋转、缩放动画和帧动画之外,还支持任意组件属性和用户自定义属性的驱动,再加上可任意编辑的时间曲线和创新的移动轨迹编辑功能,能够让内容生产人员不写一行代码就制作出细腻的各种动态效果。", + "en": "Cocos Creator has a built-in universal animation system for implementing keyframe-based animations. In addition to standard moving, rotation, scaling and frame animations, it also supports arbitrary component properties and user-defined property drivers, plus arbitrary time curves and innovative trajectory editing, allowing content producers to create detailed dynamic effects without writing a single line of code." } } \ No newline at end of file diff --git a/cocos/core/animation/compression/compressed-data.ts b/cocos/core/animation/compression/compressed-data.ts index 6fcb88205c..ac040e9e50 100644 --- a/cocos/core/animation/compression/compressed-data.ts +++ b/cocos/core/animation/compression/compressed-data.ts @@ -175,7 +175,7 @@ export class CompressedData { } /** - * @legacyPublic + * @internal */ public _addQuatCurve (curve: QuatCurve): CompressedQuatCurvePointer { const times = Array.from(curve.times()); diff --git a/cocos/core/animation/cross-fade.ts b/cocos/core/animation/cross-fade.ts index dbe74f9f7f..1d4707d15e 100644 --- a/cocos/core/animation/cross-fade.ts +++ b/cocos/core/animation/cross-fade.ts @@ -23,15 +23,11 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module animation - */ - import { clamp01 } from '../math/utils'; import { remove } from '../utils/array'; -import type { AnimationState } from './animation-state'; +import { AnimationState } from './animation-state'; import { Playable } from './playable'; +import { getGlobalAnimationManager } from './global-animation-manager'; interface IManagedState { state: AnimationState | null; @@ -44,17 +40,25 @@ interface IFading { easeDuration: number; } -/** - * Helper class to allocate weights for animation states, - * according to the invocation of "cross fading". - */ -export class CrossFade { +interface CrossFadeScheduler { + addCrossFade(crossFade: CrossFade): void; + + removeCrossFade(crossFade: CrossFade): void; +} + +export class CrossFade extends Playable { private readonly _managedStates: IManagedState[] = []; private readonly _fadings: IFading[] = []; - private _finished = true; + private _scheduled = false; + private declare _scheduler: CrossFadeScheduler; + + constructor (scheduler?: CrossFadeScheduler) { + super(); + this._scheduler = scheduler ?? getGlobalAnimationManager(); + } public update (deltaTime: number) { - if (this._finished) { + if (this.isMotionless) { return; } @@ -71,7 +75,7 @@ export class CrossFade { } if (managedStates.length === 1 && fadings.length === 1) { // Definitely not code repetition - this._finished = true; + this._unscheduleThis(); } } @@ -81,8 +85,6 @@ export class CrossFade { * @param duration 切换时间。 */ public crossFade (state: AnimationState | null, duration: number) { - this._finished = false; - if (this._managedStates.length === 0) { // If we are cross fade from a "initial" pose, // we do not use the duration. @@ -110,11 +112,12 @@ export class CrossFade { easeTime: 0, target, }); + + if (!this.isMotionless) { + this._scheduleThis(); + } } - /** - * Invoke `stop()` on all managed states then clear fade queue. - */ public clear () { for (let iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) { const state = this._managedStates[iManagedState].state; @@ -124,31 +127,47 @@ export class CrossFade { } this._managedStates.length = 0; this._fadings.length = 0; - this._finished = true; + } + + protected onPlay () { + super.onPlay(); + this._scheduleThis(); } /** - * Invoke `pause()` on all managed states. + * 停止我们淡入淡出的所有动画状态并停止淡入淡出。 */ - public pause () { + protected onPause () { + super.onPause(); for (let iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) { const state = this._managedStates[iManagedState].state; if (state) { state.pause(); } } + this._unscheduleThis(); } /** - * Invoke `resume()` on all managed states. + * 恢复我们淡入淡出的所有动画状态并继续淡入淡出。 */ - public resume () { + protected onResume () { + super.onResume(); for (let iManagedState = 0; iManagedState < this._managedStates.length; ++iManagedState) { const state = this._managedStates[iManagedState].state; if (state) { state.resume(); } } + this._scheduleThis(); + } + + /** + * 停止所有淡入淡出的动画状态。 + */ + protected onStop () { + super.onStop(); + this.clear(); } private _calculateWeights (deltaTime: number) { @@ -199,4 +218,18 @@ export class CrossFade { fadings.splice(deadFadingBegin); } } + + private _scheduleThis () { + if (!this._scheduled) { + this._scheduler.addCrossFade(this); + this._scheduled = true; + } + } + + private _unscheduleThis () { + if (this._scheduled) { + this._scheduler.removeCrossFade(this); + this._scheduled = false; + } + } } diff --git a/cocos/core/animation/cubic-spline-value.ts b/cocos/core/animation/cubic-spline-value.ts index 6733e436cf..d2e6c4bf5b 100644 --- a/cocos/core/animation/cubic-spline-value.ts +++ b/cocos/core/animation/cubic-spline-value.ts @@ -23,15 +23,9 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module animation - */ - import { ccclass, serializable } from 'cc.decorator'; import { Quat, Vec2, Vec3, Vec4 } from '../math'; import { ILerpable } from './types'; -import { legacyCC } from '../global-exports'; interface ICubicSplineValue extends ILerpable { dataPoint: T; @@ -109,30 +103,52 @@ function makeCubicSplineValueConstructor ( return CubicSplineValueClass; } +/** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ export const CubicSplineVec2Value = makeCubicSplineValueConstructor( 'cc.CubicSplineVec2Value', Vec2, Vec2.multiplyScalar, Vec2.scaleAndAdd, ); +/** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ export type CubicSplineVec2Value = ICubicSplineValue; -legacyCC.CubicSplineVec2Value = CubicSplineVec2Value; +/** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ export const CubicSplineVec3Value = makeCubicSplineValueConstructor( 'cc.CubicSplineVec3Value', Vec3, Vec3.multiplyScalar, Vec3.scaleAndAdd, ); -export type CubicSplineVec3Value = ICubicSplineValue; -legacyCC.CubicSplineVec3Value = CubicSplineVec3Value; +/** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ +export type CubicSplineVec3Value = ICubicSplineValue; + +/** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ export const CubicSplineVec4Value = makeCubicSplineValueConstructor( 'cc.CubicSplineVec4Value', Vec4, Vec4.multiplyScalar, Vec4.scaleAndAdd, ); -export type CubicSplineVec4Value = ICubicSplineValue; -legacyCC.CubicSplineVec4Value = CubicSplineVec4Value; +/** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ +export type CubicSplineVec4Value = ICubicSplineValue; + +/** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ export const CubicSplineQuatValue = makeCubicSplineValueConstructor( 'cc.CubicSplineQuatValue', Quat, Quat.multiplyScalar, Quat.scaleAndAdd, ); -legacyCC.CubicSplineQuatValue = CubicSplineQuatValue; +/** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ @ccclass('cc.CubicSplineNumberValue') export class CubicSplineNumberValue implements ICubicSplineValue { @serializable @@ -169,4 +185,3 @@ export class CubicSplineNumberValue implements ICubicSplineValue { return this.dataPoint; } } -legacyCC.CubicSplineNumberValue = CubicSplineNumberValue; diff --git a/cocos/core/animation/deprecated.ts b/cocos/core/animation/deprecated.ts deleted file mode 100644 index bc8a16dbb7..0000000000 --- a/cocos/core/animation/deprecated.ts +++ /dev/null @@ -1,63 +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. - */ - -/** - * @packageDocumentation - * @module animation - */ - -import { replaceProperty } from '../utils/x-deprecated'; -import { Animation } from './animation-component'; -import { AnimationClip } from './animation-clip'; -import { js } from '../utils/js'; -import { legacyCC } from '../global-exports'; - -// deprecated -replaceProperty(Animation.prototype, 'Animation', [ - { - name: 'getAnimationState', - newName: 'getState', - }, - { - name: 'addClip', - newName: 'createState', - }, - { - name: 'removeClip', - newName: 'removeState', - customFunction (...args: any) { - const arg0 = args[0] as AnimationClip; - return Animation.prototype.removeState.call(this, arg0.name); - }, - }, -]); - -/** - * Alias of [[Animation]] - * @deprecated Since v1.2 - */ -export { Animation as AnimationComponent }; -legacyCC.AnimationComponent = Animation; -js.setClassAlias(Animation, 'cc.AnimationComponent'); diff --git a/cocos/core/animation/embedded-player/embedded-animation-clip-player.ts b/cocos/core/animation/embedded-player/embedded-animation-clip-player.ts new file mode 100644 index 0000000000..df00661fff --- /dev/null +++ b/cocos/core/animation/embedded-player/embedded-animation-clip-player.ts @@ -0,0 +1,96 @@ +import { ccclass, serializable } from 'cc.decorator'; +import { errorID } from '../../platform/debug'; +import type { Node } from '../../scene-graph/node'; +import { AnimationClip } from '../animation-clip'; +import { AnimationState } from '../animation-state'; +import { CLASS_NAME_PREFIX_ANIM } from '../define'; +import { EmbeddedPlayableState, EmbeddedPlayable } from './embedded-player'; + +/** + * @en + * The embedded animation clip playable. The playable play animation clip on a embedded player. + * @zh + * 动画剪辑子区域播放器。此播放器在子区域上播放动画剪辑。 + */ +@ccclass(`${CLASS_NAME_PREFIX_ANIM}EmbeddedAnimationClipPlayable`) +export class EmbeddedAnimationClipPlayable extends EmbeddedPlayable { + /** + * @en + * Path to the node onto which the animation clip would be played, relative from animation context root. + * @zh + * 要播放动画剪辑的节点的路径,相对于动画上下文的根节点。 + */ + @serializable + public path = ''; + + /** + * @en + * The animation clip to play. + * @zh + * 要播放的动画剪辑。 + */ + @serializable + public clip: AnimationClip | null = null; + + public instantiate (root: Node) { + const { clip, path } = this; + if (!clip) { + return null; + } + const clipRoot = root.getChildByPath(path); + if (!clipRoot) { + errorID(3938, path, root.getPathInHierarchy(), clip.name); + return null; + } + const state = new AnimationState(clip); + state.initialize( + clipRoot, + ); + return new EmbeddedAnimationClipPlayableState(state); + } +} + +class EmbeddedAnimationClipPlayableState extends EmbeddedPlayableState { + constructor (animationState: AnimationState) { + super(true); + this._animationState = animationState; + } + + public destroy (): void { + this._animationState.destroy(); + } + + /** + * Plays the animation state at specified time. + */ + public play (): void { + this._animationState.play(); + } + + /** + * Pause the animation state. + */ + public pause (): void { + this._animationState.pause(); + } + + /** + * Stops the animation state. + */ + public stop (): void { + this._animationState.stop(); + } + + /** + * Sets the speed of the animation state. + */ + public setSpeed (speed: number): void { + this._animationState.speed = speed; + } + + public setTime (time: number): void { + this._animationState.time = time; + } + + private _animationState: AnimationState; +} diff --git a/cocos/core/animation/embedded-player/embedded-particle-system-player.ts b/cocos/core/animation/embedded-player/embedded-particle-system-player.ts new file mode 100644 index 0000000000..3fcf15610f --- /dev/null +++ b/cocos/core/animation/embedded-player/embedded-particle-system-player.ts @@ -0,0 +1,87 @@ +import { ccclass, serializable } from 'cc.decorator'; +import type { ParticleSystem } from '../../../particle'; +import { warn } from '../../platform/debug'; +import type { Node } from '../../scene-graph/node'; +import { getClassByName } from '../../utils/js-typed'; +import { CLASS_NAME_PREFIX_ANIM } from '../define'; +import { EmbeddedPlayableState, EmbeddedPlayable } from './embedded-player'; + +/** + * @en + * The embedded particle system playable. The players play particle system on a embedded player. + * @zh + * 粒子系统子区域播放器。此播放器在子区域上播放粒子系统。 + */ +@ccclass(`${CLASS_NAME_PREFIX_ANIM}EmbeddedParticleSystemPlayable`) +export class EmbeddedParticleSystemPlayable extends EmbeddedPlayable { + /** + * @en + * Path to the node where particle system inhabits, relative from animation context root. + * @zh + * 粒子系统所在的结点路径,相对于动画上下文的根节点。 + */ + @serializable + public path = ''; + + public instantiate (root: Node) { + const node = root.getChildByPath(this.path); + if (!node) { + warn(`Hierarchy path ${this.path} does not exists.`); + return null; + } + // TODO: we shouldn't wanna know the name of `ParticleSystem` indeed. + const ParticleSystemConstructor = getClassByName(`cc.ParticleSystem`) as Constructor | undefined; + if (!ParticleSystemConstructor) { + warn(`Particle system is required for embedded particle system player.`); + return null; + } + const particleSystem = node.getComponent(ParticleSystemConstructor); + if (!particleSystem) { + warn(`${this.path} does not includes a particle system component.`); + return null; + } + return new EmbeddedParticleSystemPlayableState(particleSystem); + } +} + +class EmbeddedParticleSystemPlayableState extends EmbeddedPlayableState { + constructor (particleSystem: ParticleSystem) { + super(false); + this._particleSystem = particleSystem; + } + + public destroy (): void { + // DO NOTHING + } + + /** + * Plays the particle system from the beginning no matter current time. + */ + public play (): void { + this._particleSystem.play(); + } + + /** + * Pause the particle system no matter current time. + */ + public pause (): void { + this._particleSystem.stopEmitting(); + } + + /** + * Stops the particle system. + */ + public stop (): void { + this._particleSystem.stopEmitting(); + } + + /** + * Sets the speed of the particle system. + * @param speed The speed. + */ + public setSpeed (speed: number): void { + this._particleSystem.simulationSpeed = speed; + } + + private _particleSystem: ParticleSystem; +} diff --git a/cocos/core/animation/embedded-player/embedded-player.ts b/cocos/core/animation/embedded-player/embedded-player.ts new file mode 100644 index 0000000000..02c553d2f2 --- /dev/null +++ b/cocos/core/animation/embedded-player/embedded-player.ts @@ -0,0 +1,117 @@ +import { ccclass, serializable } from 'cc.decorator'; +import { EditorExtendable } from '../../data/editor-extendable'; +import type { Node } from '../../scene-graph'; +import { CLASS_NAME_PREFIX_ANIM } from '../define'; + +@ccclass(`${CLASS_NAME_PREFIX_ANIM}EmbeddedPlayer`) +export class EmbeddedPlayer extends EditorExtendable { + /** + * @en + * Begin time, in seconds. + * @zh + * 开始时间,以秒为单位。 + */ + @serializable + public begin = 0.0; + + /** + * @en + * End time, in seconds. + * @zh + * 结束时间,以秒为单位。 + */ + @serializable + public end = 0.0; + + /** + * @en + * Whether the speed of this embedded player should be reconciled with the host animation clip. + * @zh + * 子区域的播放速度是否应和宿主动画剪辑保持一致。 + */ + @serializable + public reconciledSpeed = false; + + /** + * @en + * Player of the embedded player. + * @zh + * 子区域的播放器。 + */ + @serializable + public playable: EmbeddedPlayable | null = null; +} + +export abstract class EmbeddedPlayable { + /** + * @en + * Instantiates this sub region. + * @zh + * 实例化此子区域。 + * @param root The root node of animation context. + * @internal + */ + public abstract instantiate(root: Node): EmbeddedPlayableState | null; +} + +export abstract class EmbeddedPlayableState { + constructor (randomAccess: boolean) { + this._randomAccess = randomAccess; + } + + /** + * @zh + * 是否可以随意调整此播放器到任何时间。 + * @en + * Indicates if this player can be adjusted to any time. + */ + public get randomAccess () { + return this._randomAccess; + } + + /** + * @zh + * 销毁此播放器。 + * @zh + * Destroys this player state. + */ + public abstract destroy (): void; + + /** + * @zh + * 该方法在此播放器开始播放时触发。 + * @en + * This method is called when this player gets to play. + */ + public abstract play(): void; + + /** + * @zh + * 该方法在此播放器暂停播放时触发。 + * @en + * This method is called when this player pauses. + */ + public abstract pause(): void; + + /** + * @zh + * 该方法在此播放器结束播放时触发,或在宿主动画剪辑本身停止播放时触发。 + * @en + * This method is called when this player ends its playback, and is called when the host animation clip is stopped. + */ + public abstract stop(): void; + + /** + * @zh + * 如果 [[`EmbeddedPlayer.reconciledSpeed`]] 为 `true`,则在宿主的播放速度改变时触发。 + * @en + * If [[`EmbeddedPlayer.reconciledSpeed`]] is `true`, is called when the host changes its speed. + * @param speed The speed. + */ + public abstract setSpeed(speed: number): void; + + public setTime (_time: number) { + } + + private declare _randomAccess: boolean; +} diff --git a/cocos/core/animation/exotic-animation/exotic-animation.ts b/cocos/core/animation/exotic-animation/exotic-animation.ts index 2c14af0e5f..7fd9eac5d0 100644 --- a/cocos/core/animation/exotic-animation/exotic-animation.ts +++ b/cocos/core/animation/exotic-animation/exotic-animation.ts @@ -50,7 +50,7 @@ export class ExoticAnimation { } /** - * @legacyPublic + * @internal */ public toHashString () { return this._nodeAnimations.map((nodeAnimation) => nodeAnimation.toHashString()).join('\n'); @@ -116,7 +116,7 @@ class ExoticNodeAnimation { } /** - * @legacyPublic + * @internal */ public toHashString (): string { return `${this._path}\n${ @@ -183,7 +183,7 @@ class ExoticVectorLikeTrackValues { } /** - * @legacyPublic + * @internal */ public toHashString (): string { const { _isQuantized: isQuantized, _values: values } = this; @@ -305,7 +305,7 @@ class ExoticTrack { public values!: TTrackValues; /** - * @legacyPublic + * @internal */ public toHashString (): string { const { times, values } = this; @@ -802,7 +802,7 @@ class QuantizedFloatArray { } /** - * @legacyPublic + * @internal */ public toHashString (): string { const { originalPrecision, min, extent, values } = this; diff --git a/cocos/core/animation/index.ts b/cocos/core/animation/index.ts index 43a67fdcf3..8567e8a7dc 100644 --- a/cocos/core/animation/index.ts +++ b/cocos/core/animation/index.ts @@ -23,17 +23,10 @@ THE SOFTWARE. */ - -import { ccclass } from 'cc.decorator'; import * as animation from './animation'; import * as easing from '../easing/easing'; -import { ComponentPath, HierarchyPath, ICustomTargetPath, TargetPath } from './target-path'; -import { IValueProxyFactory } from './value-proxy'; -import { UniformProxyFactory } from './value-proxy-factories/uniform'; import { legacyCC } from '../global-exports'; -export * from './deprecated'; - legacyCC.easing = easing; export * from '../curves/bezier'; export { easing }; @@ -43,79 +36,10 @@ export * from './animation-manager'; export { AnimationState, } from './animation-state'; -export * from './animation-component'; +export { + Animation, + AnimationComponent, +} from './animation-component'; export * from './transform-utils'; export { animation }; - -/** - * Use stuffs in `import('cc').animation` instead. - * @deprecated Since v1.1. - */ -export * from './cubic-spline-value'; - -/** - * Alias of `HierarchyPath`. - * @deprecated Since v1.1. - */ -@ccclass('cc.HierachyModifier') -export class HierachyModifier extends HierarchyPath {} -legacyCC.HierachyModifier = HierachyModifier; - -/** - * Alias of `ComponentPath`. - * @deprecated Since v1.1. - */ -@ccclass('cc.ComponentModifier') -export class ComponentModifier extends ComponentPath {} -legacyCC.ComponentModifier = ComponentModifier; - -/** - * Implements `IValueProxyFactory` but do nothing. - * @deprecated Since v1.1. - */ -@ccclass('cc.CurveValueAdapter') -export class CurveValueAdapter implements IValueProxyFactory { - public forTarget (target: any) { - return { - set: () => { - - }, - }; - } -} -legacyCC.CurveValueAdapter = CurveValueAdapter; - -/** - * Alias of `UniformProxyFactory`. - * @deprecated Since v1.1. - */ -@ccclass('cc.UniformCurveValueAdapter') -export class UniformCurveValueAdapter extends UniformProxyFactory {} -legacyCC.UniformCurveValueAdapter = UniformCurveValueAdapter; - -/** - * Alias of `isPropertyPath(path) && typeof path === 'string'`. - * @deprecated Since v1.1. - */ -export function isPropertyModifier (path: TargetPath): path is string { - return typeof path === 'string'; -} -legacyCC.isPropertyModifier = isPropertyModifier; - -/** - * Alias of `isPropertyPath(path) && typeof path === 'number'`. - * @deprecated Since v1.1. - */ -export function isElementModifier (path: TargetPath): path is number { - return typeof path === 'number'; -} -legacyCC.isElementModifier = isElementModifier; - -/** - * Alias of `isCustomPath()`. - * @deprecated Since v1.1. - */ -export function isCustomTargetModifier (path: TargetPath, constructor: Constructor): path is T { - return path instanceof constructor; -} -legacyCC.isCustomTargetModifier = isCustomTargetModifier; +export type { ILerpable } from './types'; diff --git a/cocos/core/animation/marionette/animation-controller.ts b/cocos/core/animation/marionette/animation-controller.ts index a3a7a5cffe..263566611d 100644 --- a/cocos/core/animation/marionette/animation-controller.ts +++ b/cocos/core/animation/marionette/animation-controller.ts @@ -37,7 +37,7 @@ export class AnimationController extends Component { private _graphEval: AnimationGraphEval | null = null; - public start () { + public __preload () { if (this.graph) { this._graphEval = new AnimationGraphEval(this.graph as AnimationGraph, this.node, this); } @@ -67,8 +67,8 @@ export class AnimationController extends Component { /** * @zh 设置动画图实例中变量的值。 * @en Sets the value of the variable in the animation graph instance. - * @param name 变量名称。 - * @param value 变量的值。 + * @param name @en Variable's name. @zh 变量的名称。 + * @param value @en Variable's value. @zh 变量的值。 * @example * ```ts * animationController.setValue('speed', 3.14); @@ -85,8 +85,8 @@ export class AnimationController extends Component { /** * @zh 获取动画图实例中变量的值。 * @en Gets the value of the variable in the animation graph instance. - * @param name 变量名称。 - * @returns 变量当前的值。 + * @param name @en Variable's name. @zh 变量的名称。 + * @returns @en Variable's value. @zh 变量的值。 */ public getValue (name: string) { const { _graphEval: graphEval } = this; @@ -97,8 +97,9 @@ export class AnimationController extends Component { /** * @zh 获取动画图实例中当前状态的运行状况。 * @en Gets the running status of the current state in the animation graph instance. - * @param layer 层级索引。(必须为 `0`) - * @returns 当前的状态运作状态对象。 + * @param layer @en Index of the layer. @zh 层级索引。 + * @returns @en The running status of the current state. + * @zh 当前的状态运作状态对象。 */ public getCurrentStateStatus (layer: number) { const { _graphEval: graphEval } = this; @@ -109,8 +110,9 @@ export class AnimationController extends Component { /** * @zh 获取动画图实例中当前状态上包含的所有动画剪辑的运行状况。 * @en Gets the running status of all the animation clips added on the current state in the animation graph instance. - * @param layer 层级索引。(必须为 `0`) - * @returns 到动画剪辑运作状态的迭代器。 + * @param layer @en Index of the layer. @zh 层级索引。 + * @returns @en Iterable to the animation clip statuses on current state. + * @zh 到动画剪辑运作状态的迭代器。 */ public getCurrentClipStatuses (layer: number) { const { _graphEval: graphEval } = this; @@ -121,8 +123,9 @@ export class AnimationController extends Component { /** * @zh 获取动画图实例中当前正在进行的过渡的运行状况。 * @en Gets the running status of the transition currently in progress in the animation graph instance. - * @param layer 层级索引。(必须为 `0`) - * @returns 当前正在进行的过渡,若没有进行任何过渡,则返回 `null`。 + * @param layer @en Index of the layer. @zh 层级索引。 + * @returns @en Current transition status. `null` is returned in case of no transition. + * @zh 当前正在进行的过渡,若没有进行任何过渡,则返回 `null`。 */ public getCurrentTransition (layer: number) { const { _graphEval: graphEval } = this; @@ -133,8 +136,9 @@ export class AnimationController extends Component { /** * @zh 获取动画图实例中下一个状态的运行状况。 * @en Gets the running status of the next state in the animation graph instance. - * @param layer 层级索引。(必须为 `0`) - * @returns 下一状态运作状态对象,若未在进行过渡,则返回 `null`。 + * @param layer @en Index of the layer. @zh 层级索引。 + * @returns @en The running status of the next state. `null` is returned in case of no transition. + * @zh 下一状态运作状态对象,若未在进行过渡,则返回 `null`。 */ public getNextStateStatus (layer: number) { const { _graphEval: graphEval } = this; @@ -145,8 +149,9 @@ export class AnimationController extends Component { /** * @zh 获取动画图实例中下一个状态上添加的所有动画剪辑的运行状况。 * @en Gets the running status of all the animation clips added on the next state in the animation graph instance. - * @param layer 层级索引。(必须为 `0`) - * @returns 到下一状态上包含的动画剪辑运作状态的迭代器,若未在进行过渡,则返回一个空的迭代器。 + * @param layer @en Index of the layer. @zh 层级索引。 + * @returns @en Iterable to the animation clip statuses on next state. An empty iterable is returned in case of no transition. + * @zh 到下一状态上包含的动画剪辑运作状态的迭代器,若未在进行过渡,则返回一个空的迭代器。 */ public getNextClipStatuses (layer: number) { const { _graphEval: graphEval } = this; @@ -154,6 +159,22 @@ export class AnimationController extends Component { return graphEval.getNextClipStatuses(layer); } + /** + * @zh 获取层级权重。 + * @en Gets the weight of specified layer. + * @param layer @en Index of the layer. @zh 层级索引。 + */ + public getLayerWeight (layer: number) { + const { _graphEval: graphEval } = this; + assertIsNonNullable(graphEval); + return graphEval.getLayerWeight(layer); + } + + /** + * @zh 设置层级权重。 + * @en Sets the weight of specified layer. + * @param layer @en Index of the layer. @zh 层级索引。 + */ public setLayerWeight (layer: number, weight: number) { const { _graphEval: graphEval } = this; assertIsNonNullable(graphEval); diff --git a/cocos/core/animation/marionette/animation-graph.ts b/cocos/core/animation/marionette/animation-graph.ts index 146a1d5199..13a95401bc 100644 --- a/cocos/core/animation/marionette/animation-graph.ts +++ b/cocos/core/animation/marionette/animation-graph.ts @@ -6,7 +6,7 @@ import { Motion, MotionEval, MotionEvalContext } from './motion'; import type { Condition } from './condition'; import { Asset } from '../../assets'; import { OwnedBy, assertsOwnedBy, own, markAsDangling, ownerSymbol } from './ownership'; -import { Value } from './variable'; +import { TriggerResetMode, Value, VariableType } from './variable'; import { InvalidTransitionError } from './errors'; import { createEval } from './create-eval'; import { MotionState } from './motion-state'; @@ -18,7 +18,7 @@ import { move } from '../../algorithm/move'; import { onAfterDeserializedTag } from '../../data/deserialize-symbols'; import { CLASS_NAME_PREFIX_ANIM } from '../define'; import { StateMachineComponent } from './state-machine-component'; -import { VariableType } from './parametric'; +import { clamp } from '../../math'; export { State }; @@ -65,6 +65,14 @@ export type { TransitionView as Transition }; export type TransitionInternal = Transition; +export enum TransitionInterruptionSource { + NONE, + CURRENT_STATE, + NEXT_STATE, + CURRENT_STATE_THEN_NEXT_STATE, + NEXT_STATE_THEN_CURRENT_STATE, +} + @ccclass(`${CLASS_NAME_PREFIX_ANIM}AnimationTransition`) class AnimationTransition extends Transition { /** @@ -84,6 +92,14 @@ class AnimationTransition extends Transition { @serializable public exitConditionEnabled = true; + /** + * @en The start time of (final) destination motion state when this transition starts. + * Its unit is the duration of destination motion state. + * @zh 此过渡开始时,(最终)目标动作状态的起始时间。其单位是目标动作状态的周期。 + */ + @serializable + public destinationStart = 0.0; + get exitCondition () { return this._exitCondition; } @@ -93,6 +109,25 @@ class AnimationTransition extends Transition { this._exitCondition = value; } + /** + * @internal This field is exposed for **experimental editor only** usage. + */ + get interruptible () { + return this.interruptionSource !== TransitionInterruptionSource.NONE; + } + + set interruptible (value) { + this.interruptionSource = value + ? TransitionInterruptionSource.CURRENT_STATE_THEN_NEXT_STATE + : TransitionInterruptionSource.NONE; + } + + /** + * @internal This field is exposed for **internal** usage. + */ + @serializable + public interruptionSource = TransitionInterruptionSource.NONE; + @serializable private _exitCondition = 1.0; } @@ -120,6 +155,14 @@ export class EmptyStateTransition extends Transition { */ @serializable public duration = 0.3; + + /** + * @en The start time of (final) destination motion state when this transition starts. + * Its unit is the duration of destination motion state. + * @zh 此过渡开始时,(最终)目标动作状态的起始时间。其单位是目标动作状态的周期。 + */ + @serializable + public destinationStart = 0.0; } @ccclass('cc.animation.StateMachine') @@ -141,7 +184,7 @@ export class StateMachine extends EditorExtendable { /** * // TODO: HACK - * @legacyPublic + * @internal */ public __callOnAfterDeserializeRecursive () { this[onAfterDeserializedTag](); @@ -226,9 +269,12 @@ export class StateMachine extends EditorExtendable { } /** - * Gets all outgoing transitions of specified state. - * @param to The state. - * @returns Result transitions. + * @en + * Gets all transitions outgoing from specified state. + * @zh + * 获取从指定状态引出的所有过渡。 + * @param from @en The state. @zh 指定状态。 + * @returns @en Iterable to result transitions, in priority order. @zh 到结果过渡的迭代器,按优先级顺序。 */ public getOutgoings (from: State): Iterable { assertsOwnedBy(from, this); @@ -424,6 +470,46 @@ export class StateMachine extends EditorExtendable { this.eraseOutgoings(state); } + /** + * @en + * Adjusts the priority of a transition. + * + * To demonstrate, one can imagine a transition array sorted by their priority. + * - If `diff` is zero, nothing's gonna happen. + * - Negative `diff` raises the priority: + * `diff` number of transitions originally having higher priority than `adjusting` + * will then have lower priority than `adjusting`. + * - Positive `diff` reduce the priority: + * `|diff|` number of transitions originally having lower priority than `adjusting` + * will then have higher priority than `adjusting`. + * + * If the number of transitions indicated by `diff` + * is more than the actual one, the actual number would be taken. + * @zh + * 调整过渡的优先级。 + * + * 为了说明,可以想象一个由优先级排序的过渡数组。 + * - 如果 `diff` 是 0,无事发生。 + * - 负的 `diff` 会提升该过渡的优先级:原本优先于 `adjusting` 的 `diff` 条过渡的优先级会设置为低于 `adjusting`。 + * - 正的 `diff` 会降低该过渡的优先级:原本优先级低于 `adjusting` 的 `|diff|` 条过渡会设置为优先于 `adjusting`。 + * + * 如果 `diff` 指示的过渡数量比实际多,则会使用实际数量。 + * + * @param adjusting @en The transition to adjust the priority. @zh 需要调整优先级的过渡。 + * @param diff @en Indicates how to adjust the priority. @zh 指示如何调整优先级。 + */ + public adjustTransitionPriority (adjusting: Transition, diff: number) { + const { from } = adjusting; + if (diff === 0) { + return; + } + const outgoings = from[outgoingsSymbol]; + const iAdjusting = outgoings.indexOf(adjusting); + assertIsTrue(iAdjusting >= 0); + const iOver = clamp(iAdjusting + diff, 0, outgoings.length - 1); + move(outgoings, iAdjusting, iOver); + } + public clone () { const that = new StateMachine(); const stateMap = new Map(); @@ -521,21 +607,6 @@ export enum LayerBlending { additive, } -/** - * @zh 布尔类型变量的重置模式,指示在哪些情况下将变量重置为 `false`。 - */ -export enum TriggerResetMode { - /** - * @zh 在该变量被动画过渡消耗后自动重置。 - */ - AFTER_CONSUMED, - - /** - * @zh 下一帧自动重置;在该变量被动画过渡消耗后也会自动重置。 - */ - NEXT_FRAME_OR_AFTER_CONSUMED, -} - const TRIGGER_VARIABLE_FLAG_VALUE_START = 0; const TRIGGER_VARIABLE_FLAG_VALUE_MASK = 1; const TRIGGER_VARIABLE_FLAG_RESET_MODE_START = 1; @@ -635,7 +706,9 @@ class TriggerVariable implements BasicVariableDescription } set resetMode (value: TriggerResetMode) { - this._flags &= ~(TRIGGER_VARIABLE_FLAG_RESET_MODE_MASK << TRIGGER_VARIABLE_FLAG_RESET_MODE_START); + // Clear + this._flags &= ~TRIGGER_VARIABLE_FLAG_RESET_MODE_MASK; + // Set this._flags |= (value << TRIGGER_VARIABLE_FLAG_RESET_MODE_START); } @@ -645,7 +718,16 @@ class TriggerVariable implements BasicVariableDescription private _flags = TRIGGER_VARIABLE_DEFAULT_FLAGS; } +/** + * @en + * An opacity type which denotes what the animation graph seems like outside the engine. + * @zh + * 一个非透明的类型,它是动画图在引擎外部的表示。 + */ export interface AnimationGraphRunTime { + /** + * @internal + */ readonly __brand: 'AnimationGraph'; } @@ -776,4 +858,30 @@ export class AnimationGraph extends Asset implements AnimationGraphRunTime { public getVariable (name: string): VariableDescription | undefined { return this._variables[name] as VariableDescription | undefined; } + + /** + * @zh 重命名一个变量。注意,所有对该变量的引用都不会修改。 + * 如果变量的原始名称不存在或者新的名称已存在,此方法不会做任何事。 + * 变量在图中的顺序会保持不变。 + * @en Renames an variable. Note, this won't changes any reference to the variable. + * If the original name of the variable doesn't exists or + * the new name has already existed, this method won't do anything. + * The variable's order in the graph is also retained. + * @param name @zh 要重命名的变量的名字。 @en The name of the variable to be renamed. + * @param newName @zh 新的名字。 @en New name. + */ + public renameVariable (name: string, newName: string) { + const { _variables: variables } = this; + if (!(name in variables)) { + return; + } + if (newName in variables) { + return; + } + // Rename but also retain order. + this._variables = Object.entries(variables).reduce((result, [k, v]) => { + result[k === name ? newName : k] = v; + return result; + }, {} as AnimationGraph['_variables']); + } } diff --git a/cocos/core/animation/marionette/animation-mask.ts b/cocos/core/animation/marionette/animation-mask.ts index 3473b75d0e..ac0cc2e5e2 100644 --- a/cocos/core/animation/marionette/animation-mask.ts +++ b/cocos/core/animation/marionette/animation-mask.ts @@ -7,13 +7,20 @@ import { CLASS_NAME_PREFIX_ANIM } from '../define'; @ccclass(`${CLASS_NAME_PREFIX_ANIM}AnimationMask`) export class AnimationMask extends Asset { @serializable - @editable private _jointMasks: JointMask[] = []; + @editable get joints (): Iterable { return this._jointMasks; } + set joints (value) { + this.clear(); + for (const joint of value) { + this.addJoint(joint.path, joint.enabled); + } + } + /** * It's undefined behaviour to add same joint path for twice or more. * @param path diff --git a/cocos/core/animation/marionette/asset-creation.ts b/cocos/core/animation/marionette/asset-creation.ts index fd78123fb7..7d1ca13192 100644 --- a/cocos/core/animation/marionette/asset-creation.ts +++ b/cocos/core/animation/marionette/asset-creation.ts @@ -4,6 +4,7 @@ export type { Transition, AnimationTransition, Layer, State, VariableDescription export { BinaryCondition, UnaryCondition, TriggerCondition } from './condition'; export type { Condition } from './condition'; export type { Value } from './variable'; +export { TriggerResetMode } from './variable'; export { MotionState } from './motion-state'; export { ClipMotion } from './clip-motion'; export type { AnimationBlend } from './animation-blend'; diff --git a/cocos/core/animation/marionette/clip-motion.ts b/cocos/core/animation/marionette/clip-motion.ts index 36572f2544..abb9356ad1 100644 --- a/cocos/core/animation/marionette/clip-motion.ts +++ b/cocos/core/animation/marionette/clip-motion.ts @@ -33,7 +33,7 @@ export class ClipMotion extends EditorExtendable implements Motion { class ClipMotionEval implements MotionEval { /** - * @legacyPublic + * @internal */ public declare __DEBUG__ID__?: string; @@ -81,7 +81,9 @@ class ClipMotionEval implements MotionEval { if (weight === 0.0) { return; } - pushWeight(this._state.name, weight); + if (GRAPH_DEBUG_ENABLED) { + pushWeight(this._state.name, weight); + } const time = this._state.duration * progress; this._state.time = time; this._state.weight = weight; diff --git a/cocos/core/animation/marionette/graph-eval.ts b/cocos/core/animation/marionette/graph-eval.ts index f5acf22058..b3e8047587 100644 --- a/cocos/core/animation/marionette/graph-eval.ts +++ b/cocos/core/animation/marionette/graph-eval.ts @@ -1,13 +1,13 @@ import { DEBUG } from 'internal:constants'; import { AnimationGraph, Layer, StateMachine, State, isAnimationTransition, - SubStateMachine, EmptyState, EmptyStateTransition, TriggerResetMode, + SubStateMachine, EmptyState, EmptyStateTransition, TransitionInterruptionSource, } from './animation-graph'; import { assertIsTrue, assertIsNonNullable } from '../../data/utils/asserts'; import { MotionEval, MotionEvalContext } from './motion'; import type { Node } from '../../scene-graph/node'; import { createEval } from './create-eval'; -import { Value, VarInstance } from './variable'; +import { Value, VarInstance, TriggerResetMode } from './variable'; import { BindContext, bindOr, validateVariableExistence, validateVariableType, VariableType } from './parametric'; import { ConditionEval, TriggerCondition } from './condition'; import { VariableNotDefinedError, VariableTypeMismatchedError } from './errors'; @@ -99,8 +99,8 @@ export class AnimationGraphEval { const { _varInstances: varInstances } = this; for (const varName in varInstances) { const varInstance = varInstances[varName]; - if (varInstance.type === VariableType.TRIGGER && - varInstance.resetMode === TriggerResetMode.NEXT_FRAME_OR_AFTER_CONSUMED) { + if (varInstance.type === VariableType.TRIGGER + && varInstance.resetMode === TriggerResetMode.NEXT_FRAME_OR_AFTER_CONSUMED) { varInstance.value = false; } } @@ -159,6 +159,10 @@ export class AnimationGraphEval { varInstance.value = value; } + public getLayerWeight (layerIndex: number) { + return this._layerEvaluations[layerIndex].weight; + } + public setLayerWeight (layerIndex: number, weight: number) { this._layerEvaluations[layerIndex].weight = weight; } @@ -167,30 +171,60 @@ export class AnimationGraphEval { private _hasAutoTrigger = false; } +/** + * @en + * Runtime status of a transition. + * @zh + * 过渡的运行状态。 + */ export interface TransitionStatus { /** + * @en * The duration of the transition. + * @zh + * 过渡的周期。 */ duration: number; /** + * @en * The progress of the transition. + * @zh + * 过渡的进度。 */ time: number; } +/** + * @en + * Runtime clip status of a motion state. + * @zh + * 动作状态中包含的剪辑的运行状态。 + */ export interface ClipStatus { /** + * @en * The clip object. + * @zh + * 剪辑对象。 */ clip: AnimationClip; /** + * @en * The clip's weight. + * @zh + * 剪辑的权重。 */ weight: number; } +/** + * @en + * Runtime status of a motion state. + * @zh + * 动作状态的运行状态。 + */ export interface MotionStateStatus { /** * For testing. @@ -200,7 +234,15 @@ export interface MotionStateStatus { __DEBUG_ID__?: string; /** + * @en * The normalized time of the state. + * It would be the fraction part of `elapsed-time / duration` if elapsed time is non-negative, + * and would be 1 plus the fraction part of `(elapsed-time / duration)` otherwise. + * This is **NOT** the clip's progress if the state is not a clip motion or its wrap mode isn't loop. + * @zh + * 状态的规范化时间。 + * 如果流逝的时间是非负的,它就是 `流逝时间 / 周期` 的小数部分;否则,它是 `(流逝时间 / 周期)` 的小数部分加 1。 + * 它并不一定代表剪辑的进度,因为该状态可能并不是一个剪辑动作,或者它的循环模式并非循环。 */ progress: number; } @@ -272,6 +314,8 @@ class LayerEval { const { _currentNode: currentNode } = this; if (currentNode.kind === NodeKind.animation) { return currentNode.getFromPortStatus(); + } else if (currentNode.kind === NodeKind.transitionSnapshot) { + return currentNode.first.getFromPortStatus(); } else { return null; } @@ -281,6 +325,8 @@ class LayerEval { const { _currentNode: currentNode } = this; if (currentNode.kind === NodeKind.animation) { return currentNode.getClipStatuses(this._fromWeight); + } else if (currentNode.kind === NodeKind.transitionSnapshot) { + return currentNode.first.getClipStatuses(this._fromWeight); } else { return emptyClipStatusesIterable; } @@ -298,7 +344,12 @@ class LayerEval { normalizedDuration, } = currentTransitionPath[0]; const durationInSeconds = transitionStatus.duration = normalizedDuration - ? duration * (this._currentNode.kind === NodeKind.animation ? this._currentNode.duration : 0.0) + ? duration * (this._currentNode.kind === NodeKind.animation + ? this._currentNode.duration + : this._currentNode.kind === NodeKind.transitionSnapshot + ? this._currentNode.first.duration + : 0.0 + ) : duration; transitionStatus.time = this._transitionProgress * durationInSeconds; return true; @@ -337,6 +388,10 @@ class LayerEval { private _toWeight = 0.0; private _fromUpdated = false; private _toUpdated = false; + /** + * A virtual state which represents the transition snapshot captured when a transition is interrupted. + */ + private _transitionSnapshot = new TransitionSnapshotEval(); private _addStateMachine ( graph: StateMachine, parentStateMachineInfo: StateMachineInfo | null, context: LayerContext, __DEBUG_ID__: string, @@ -443,8 +498,10 @@ class LayerEval { triggers: undefined, duration: 0.0, normalizedDuration: false, + destinationStart: 0.0, exitCondition: 0.0, exitConditionEnabled: false, + interruption: TransitionInterruptionSource.NONE, }; if (isAnimationTransition(outgoing)) { @@ -452,8 +509,11 @@ class LayerEval { transitionEval.normalizedDuration = outgoing.relativeDuration; transitionEval.exitConditionEnabled = outgoing.exitConditionEnabled; transitionEval.exitCondition = outgoing.exitCondition; + transitionEval.destinationStart = outgoing.destinationStart; + transitionEval.interruption = outgoing.interruptionSource; } else if (outgoing instanceof EmptyStateTransition) { transitionEval.duration = outgoing.duration; + transitionEval.destinationStart = outgoing.destinationStart; } transitionEval.conditions.forEach((conditionEval, iCondition) => { @@ -516,6 +576,17 @@ class LayerEval { // Update current transition if we're in transition. // If currently no transition, we simple fallthrough. if (this._currentTransitionPath.length > 0) { + const transitionMatch = this._detectInterruption(remainTimePiece, interruptingTransitionMatchCache); + if (transitionMatch) { + remainTimePiece -= transitionMatch.requires; + const ranIntoNonMotionState = this._interrupt(transitionMatch); + if (ranIntoNonMotionState) { + break; + } + continueNextIterationForce = true; + continue; + } + const currentUpdatingConsume = this._updateCurrentTransition(remainTimePiece); if (GRAPH_DEBUG_ENABLED) { passConsumed = currentUpdatingConsume; @@ -609,91 +680,113 @@ class LayerEval { } } else if (currentTransitionToNode && currentTransitionToNode.kind === NodeKind.empty) { this.passthroughWeight = fromWeight; - if (currentNode.kind === NodeKind.animation) { - currentNode.sampleFromPort(1.0); - } + this._sampleSource(1.0); } else { this.passthroughWeight = 1.0; - if (currentNode.kind === NodeKind.animation) { - currentNode.sampleFromPort(fromWeight); - } + this._sampleSource(fromWeight); if (currentTransitionToNode && currentTransitionToNode.kind === NodeKind.animation) { currentTransitionToNode.sampleToPort(toWeight); } } } + private _sampleSource (weight: number) { + const { + _currentNode: currentNode, + } = this; + if (currentNode.kind === NodeKind.animation) { + currentNode.sampleFromPort(weight); + } else if (currentNode.kind === NodeKind.transitionSnapshot) { + currentNode.sample(weight); + } + } + /** * Searches for a transition which should be performed * if current node update for no more than `deltaTime`. * @param deltaTime * @returns */ - private _matchCurrentNodeTransition (deltaTime: Readonly) { + private _matchCurrentNodeTransition (deltaTime: Readonly): TransitionMatch | null { const currentNode = this._currentNode; - let minDeltaTimeRequired = Infinity; - let transitionRequiringMinDeltaTime: TransitionEval | null = null; + const transitionMatch = transitionMatchCache.reset(); - const match0 = this._matchTransition( + this._matchTransition( currentNode, currentNode, deltaTime, - transitionMatchCacheRegular, + null, + transitionMatch, ); - if (match0) { - ({ - requires: minDeltaTimeRequired, - transition: transitionRequiringMinDeltaTime, - } = match0); + if (transitionMatch.hasZeroCost()) { + return transitionMatch; } if (currentNode.kind === NodeKind.animation) { - for (let ancestor: StateMachineInfo | null = currentNode.stateMachine; - ancestor !== null; - ancestor = ancestor.parent) { - const anyMatch = this._matchTransition( - ancestor.any, - currentNode, - deltaTime, - transitionMatchCacheAny, - ); - if (anyMatch && anyMatch.requires < minDeltaTimeRequired) { - ({ - requires: minDeltaTimeRequired, - transition: transitionRequiringMinDeltaTime, - } = anyMatch); - } + this._matchAnyScoped( + currentNode, + deltaTime, + transitionMatch, + ); + if (transitionMatch.hasZeroCost()) { + return transitionMatch; } } - const result = transitionMatchCache; - - if (transitionRequiringMinDeltaTime) { - return result.set(transitionRequiringMinDeltaTime, minDeltaTimeRequired); + if (transitionMatch.isValid()) { + return transitionMatch; } return null; } + /** + * Notes the real node is used: + * - to determinate the starting state machine from where the any states are matched; + * - so we can solve transitions' relative durations. + */ + private _matchAnyScoped (realNode: MotionStateEval, deltaTime: number, result: TransitionMatchCache) { + let transitionMatchUpdated = false; + for (let ancestor: StateMachineInfo | null = realNode.stateMachine; + ancestor !== null; + ancestor = ancestor.parent) { + const updated = this._matchTransition( + ancestor.any, + realNode, + deltaTime, + null, + result, + ); + if (updated) { + transitionMatchUpdated = true; + } + if (result.hasZeroCost()) { + break; + } + } + return transitionMatchUpdated; + } + /** * Searches for a transition which should be performed - * if specified node update for no more than `deltaTime`. - * @param node - * @param realNode - * @param deltaTime - * @returns + * if specified node updates for no more than `deltaTime` and less than `result.requires`. + * We solve the relative durations of transitions based on duration of `realNode`. + * @returns True if a transition match is updated into the `result`. */ private _matchTransition ( - node: NodeEval, realNode: NodeEval, deltaTime: Readonly, result: TransitionMatchCache, - ): TransitionMatch | null { + node: NodeEval, realNode: NodeEval, deltaTime: Readonly, except: TransitionEval | null, result: TransitionMatchCache, + ) { assertIsTrue(node === realNode || node.kind === NodeKind.any); const { outgoingTransitions } = node; const nTransitions = outgoingTransitions.length; - let minDeltaTimeRequired = Infinity; - let transitionRequiringMinDeltaTime: TransitionEval | null = null; + let resultUpdated = false; for (let iTransition = 0; iTransition < nTransitions; ++iTransition) { const transition = outgoingTransitions[iTransition]; + if (transition === except) { + continue; + } + const { conditions } = transition; const nConditions = conditions.length; @@ -701,7 +794,9 @@ class LayerEval { if (nConditions === 0) { if (node.kind === NodeKind.entry || node.kind === NodeKind.exit) { // These kinds of transition is definitely chosen. - return result.set(transition, 0.0); + result.set(transition, 0.0); + resultUpdated = true; + break; } if (!transition.exitConditionEnabled) { // Invalid transition, ignored. @@ -714,7 +809,8 @@ class LayerEval { if (realNode.kind === NodeKind.animation && transition.exitConditionEnabled) { const exitTime = realNode.duration * transition.exitCondition; deltaTimeRequired = Math.max(exitTime - realNode.fromPortTime, 0.0); - if (deltaTimeRequired > deltaTime) { + // Note: the >= is reasonable in compare to >: we select the first-minimal requires. + if (deltaTimeRequired > deltaTime || deltaTimeRequired >= result.requires) { continue; } } @@ -733,30 +829,24 @@ class LayerEval { if (deltaTimeRequired === 0.0) { // Exit condition is disabled or the exit condition is just 0.0. - return result.set(transition, 0.0); + result.set(transition, 0.0); + resultUpdated = true; + break; } - if (deltaTimeRequired < minDeltaTimeRequired) { - minDeltaTimeRequired = deltaTimeRequired; - transitionRequiringMinDeltaTime = transition; - } + assertIsTrue(deltaTimeRequired <= result.requires); + result.set(transition, deltaTimeRequired); + resultUpdated = true; } - if (transitionRequiringMinDeltaTime) { - return result.set(transitionRequiringMinDeltaTime, minDeltaTimeRequired); - } - return null; + return resultUpdated; } /** - * Try switch current node using specified transition. + * Try switch current node or transition snapshot using specified transition. * @param transition The transition. * @returns If the transition finally ran into entry/exit state. */ private _switchTo (transition: TransitionEval) { - const { _currentNode: currentNode } = this; - - graphDebugGroup(`[SubStateMachine ${this.name}]: STARTED ${currentNode.name} -> ${transition.to.name}.`); - const { _currentTransitionPath: currentTransitionPath } = this; this._consumeTransition(transition); @@ -815,13 +905,15 @@ class LayerEval { const lastTransition = currentTransitionPath[lenCurrentTransitionPath - 1]; let tailNode = lastTransition.to; for (; tailNode.kind !== NodeKind.animation && tailNode.kind !== NodeKind.empty;) { - const transitionMatch = this._matchTransition( + const transitionMatch = transitionMatchCache.reset(); + this._matchTransition( tailNode, tailNode, 0.0, - transitionMatchCache, + null, + transitionMatch, ); - if (!transitionMatch) { + if (!transitionMatch.transition) { break; } const transition = transitionMatch.transition; @@ -853,6 +945,12 @@ class LayerEval { } private _doTransitionToMotion (targetNode: MotionStateEval | EmptyStateEval) { + const { + _currentTransitionPath: currentTransitionPath, + } = this; + + assertIsTrue(currentTransitionPath.length !== 0); + // Reset triggers this._resetTriggersAlongThePath(); @@ -861,7 +959,10 @@ class LayerEval { this._toUpdated = false; if (targetNode.kind === NodeKind.animation) { - targetNode.resetToPort(); + const { + destinationStart, + } = currentTransitionPath[0]; + targetNode.resetToPort(destinationStart); } this._callEnterMethods(targetNode); } @@ -897,11 +998,13 @@ class LayerEval { contrib = 0.0; ratio = 1.0; } else { - assertIsTrue(fromNode.kind === NodeKind.animation || fromNode.kind === NodeKind.empty); + assertIsTrue(fromNode.kind === NodeKind.animation || fromNode.kind === NodeKind.empty || fromNode.kind === NodeKind.transitionSnapshot); const { _transitionProgress: transitionProgress } = this; const durationSeconds = fromNode.kind === NodeKind.empty ? transitionDuration - : normalizedDuration ? transitionDuration * fromNode.duration : transitionDuration; + : normalizedDuration + ? transitionDuration * (fromNode.kind === NodeKind.animation ? fromNode.duration : fromNode.first.duration) + : transitionDuration; const progressSeconds = transitionProgress * durationSeconds; const remain = durationSeconds - progressSeconds; assertIsTrue(remain >= 0.0); @@ -937,35 +1040,220 @@ class LayerEval { if (hasFinished) { // Transition done. graphDebug(`[SubStateMachine ${this.name}]: Transition finished: ${fromNode.name} -> ${toNodeName}.`); - - this._callExitMethods(fromNode); - // Exiting overrides the updating - // Processed below. - // this._fromUpdated = false; - const { _currentTransitionPath: transitions } = this; - const nTransition = transitions.length; - for (let iTransition = 0; iTransition < nTransition; ++iTransition) { - const { to } = transitions[iTransition]; - if (to.kind === NodeKind.exit) { - this._callExitMethods(to); - } - } - this._fromUpdated = this._toUpdated; - this._toUpdated = false; - if (toNode.kind === NodeKind.animation) { - toNode.finishTransition(); - } - this._currentNode = toNode; - this._currentTransitionToNode = null; - this._currentTransitionPath.length = 0; - // Make sure we won't suffer from precision problem - this._fromWeight = 1.0; - this._toWeight = 0.0; + this._finishCurrentTransition(); } return contrib; } + private _finishCurrentTransition () { + const { + _currentTransitionPath: currentTransitionPath, + _currentTransitionToNode: currentTransitionToNode, + } = this; + + assertIsNonNullable(currentTransitionPath.length > 0); + assertIsNonNullable(currentTransitionToNode); + + const fromNode = this._currentNode; + const toNode = currentTransitionToNode; + + this._callExitMethods(fromNode); + // Exiting overrides the updating + // Processed below. + // this._fromUpdated = false; + const { _currentTransitionPath: transitions } = this; + const nTransition = transitions.length; + for (let iTransition = 0; iTransition < nTransition; ++iTransition) { + const { to } = transitions[iTransition]; + if (to.kind === NodeKind.exit) { + this._callExitMethods(to); + } + } + this._fromUpdated = this._toUpdated; + this._toUpdated = false; + this._dropCurrentTransition(); + this._currentNode = toNode; + if (fromNode.kind === NodeKind.transitionSnapshot) { + fromNode.clear(); + } + } + + private _dropCurrentTransition () { + const { + _currentTransitionToNode: currentTransitionToNode, + } = this; + assertIsNonNullable(currentTransitionToNode); + if (currentTransitionToNode.kind === NodeKind.animation) { + currentTransitionToNode.finishTransition(); + } + this._currentTransitionToNode = null; + this._currentTransitionPath.length = 0; + // Make sure we won't suffer from precision problem + this._fromWeight = 1.0; + this._toWeight = 0.0; + } + + private _detectInterruption (remainTimePiece: number, result: InterruptingTransitionMatchCache): InterruptingTransitionMatch | null { + const { + _currentTransitionPath: currentTransitionPath, + _currentNode: currentNode, + _currentTransitionToNode: currentTransitionToNode, + } = this; + + if (currentNode.kind !== NodeKind.animation + && currentNode.kind !== NodeKind.transitionSnapshot) { + return null; + } + + if (!currentTransitionToNode + || currentTransitionToNode.kind !== NodeKind.animation) { + return null; + } + + assertIsTrue(currentTransitionPath.length !== 0); + const currentTransition = currentTransitionPath[0]; + const { interruption } = currentTransition; + if (interruption === TransitionInterruptionSource.NONE) { + return null; + } + + const transitionMatch = transitionMatchCache.reset(); + let transitionMatchSource: MotionStateEval | null = null; + + // We have to decide what to be used as unit 1 + // to interpret the relative transition duration. + const anyTransitionMeasureBaseState = currentNode.kind === NodeKind.animation + ? currentNode + : currentNode.first; + let transitionMatchUpdated = this._matchAnyScoped( + anyTransitionMeasureBaseState, + remainTimePiece, + transitionMatch, + ); + if (transitionMatchUpdated) { + transitionMatchSource = anyTransitionMeasureBaseState; // TODO: shall be any? + } + if (transitionMatch.hasZeroCost()) { + // TODO + } + + const motion0: MotionStateEval = interruption === TransitionInterruptionSource.CURRENT_STATE + || interruption === TransitionInterruptionSource.CURRENT_STATE_THEN_NEXT_STATE + ? getInterruptionSourceMotion(currentNode) + : currentTransitionToNode; + transitionMatchUpdated = this._matchTransition( + motion0, + motion0, + remainTimePiece, + currentTransition, + transitionMatch, + ); + if (transitionMatchUpdated) { + transitionMatchSource = motion0; + } + if (transitionMatch.hasZeroCost()) { + // TODO + } + + const motion1 = interruption === TransitionInterruptionSource.NEXT_STATE_THEN_CURRENT_STATE ? getInterruptionSourceMotion(currentNode) + : interruption === TransitionInterruptionSource.CURRENT_STATE_THEN_NEXT_STATE ? currentTransitionToNode + : null; + if (motion1) { + transitionMatchUpdated = this._matchTransition( + motion1, + motion1, + remainTimePiece, + currentTransition, + transitionMatch, + ); + if (transitionMatchUpdated) { + transitionMatchSource = motion1; + } + if (transitionMatch.hasZeroCost()) { + // TODO + } + } + + if (transitionMatchCache.transition) { + assertIsNonNullable(transitionMatchSource); + return result.set( + transitionMatchSource, + transitionMatchCache.transition, + transitionMatchCache.requires, + ); + } + + return null; + } + + /** + * Important: `transitionSource` may not be `this._currentNode`. + */ + private _interrupt ({ + from: transitionSource, + transition, + requires: transitionRequires, + }: InterruptingTransitionMatch) { + const { + _currentNode: currentNode, + } = this; + assertIsTrue(currentNode.kind === NodeKind.animation || currentNode.kind === NodeKind.transitionSnapshot); + // If we're interrupting motion->*, + // we update the motion then do the first enqueue to transition snapshot. + if (currentNode.kind === NodeKind.animation) { + currentNode.updateFromPort(transitionRequires); + this._fromUpdated = true; + + const { _transitionSnapshot: transitionSnapshot } = this; + assertIsTrue(transitionSnapshot.empty); + transitionSnapshot.enqueue(currentNode, 1.0); + } + this._takeCurrentTransitionSnapshot(transitionSource); + this._dropCurrentTransition(); + // Install the snapshot as "current" + this._currentNode = this._transitionSnapshot; + const ranIntoNonMotionState = this._switchTo(transition); + return ranIntoNonMotionState; + } + + /** + * A thing to note is `transitionSource` may not be `this._currentNode`. + */ + private _takeCurrentTransitionSnapshot (transitionSource: MotionStateEval) { + const { + _currentTransitionPath: currentTransitionPath, + _currentTransitionToNode: currentTransitionToNode, + _transitionSnapshot: transitionSnapshot, + } = this; + + assertIsTrue(currentTransitionPath.length !== 0); + assertIsTrue(currentTransitionToNode && currentTransitionToNode.kind === NodeKind.animation); + + const currentTransition = currentTransitionPath[0]; + + const { + duration: transitionDuration, + normalizedDuration, + } = currentTransition; + + const fromNode = transitionSource; + let ratio = 0.0; + if (transitionDuration <= 0) { + ratio = 1.0; + } else { + const { _transitionProgress: transitionProgress } = this; + const durationSeconds = normalizedDuration ? transitionDuration * fromNode.duration : transitionDuration; + const progressSeconds = transitionProgress * durationSeconds; + const remain = durationSeconds - progressSeconds; + assertIsTrue(remain >= 0.0); + ratio = progressSeconds / durationSeconds; + assertIsTrue(ratio >= 0.0 && ratio <= 1.0); + } + + transitionSnapshot.enqueue(currentTransitionToNode, ratio); + } + private _resetTriggersOnTransition (transition: TransitionEval) { const { triggers } = transition; if (triggers) { @@ -1013,14 +1301,41 @@ class LayerEval { } } +/** + * Gets the motion of current motion state or transition snapshot + * whose outgoing transitions, called "interruption source", will be inspected to + * detect the interrupting transition. + */ +function getInterruptionSourceMotion (state: MotionStateEval | TransitionSnapshotEval) { + // If current state is a motion state, then it's the result. + // Otherwise the current state is a transition snapshot -- + // we support nested interruptions, eg, + // _A->B_ was interrupted by _B->C_, + // then _(A->B)->C_ can be interrupted further by _C->D_. + // In such cases, we need to decide which transition could interrupt _(A->B)->C_. + // Outgoing transitions from destination motion are always inspected. + // And as the code following suggested, we order that: + // outgoing transitions from **the first** motion of "current transition snapshot" + // are also inspected. No other transitions are considered. + // This means for instance, in above example, + // _(A->B)->C_ can and can only be further interrupted by: + // - _A->D_, since it's outgoing from _A_; + // - _C->D_, since it's outgoing from _D_. + // However it can not be interrupted by _B->C_. + // + // > Tip: The term "nested interruption" was taken from here: + // > https://stackoverflow.com/a/24128928 + return state.kind === NodeKind.animation ? state : state.first; +} + function createStateStatusCache (): MotionStateStatus { return { progress: 0.0, }; } -const emptyClipStatusesIterator: Iterator = Object.freeze({ - next () { +const emptyClipStatusesIterator: Readonly> = Object.freeze({ + next (..._args: [] | [undefined]): IteratorResult { return { done: true, value: undefined, @@ -1046,38 +1361,70 @@ interface TransitionMatch { requires: number; } +interface InterruptingTransitionMatch extends TransitionMatch { + from: MotionStateEval; +} + class TransitionMatchCache { public transition: TransitionMatch['transition'] | null = null; - public requires = 0.0; + public requires = Infinity; + + public hasZeroCost (): this is TransitionMatch { + return this.requires === 0; + } + + public isValid (): this is TransitionMatch { + return this.transition !== null; + } public set (transition: TransitionMatch['transition'], requires: number) { this.transition = transition; this.requires = requires; - return this as TransitionMatch; + return this; + } + + public reset () { + this.requires = Infinity; + this.transition = null; + return this; } } const transitionMatchCache = new TransitionMatchCache(); -const transitionMatchCacheRegular = new TransitionMatchCache(); +class InterruptingTransitionMatchCache { + public transition: TransitionMatch['transition'] | null = null; -const transitionMatchCacheAny = new TransitionMatchCache(); + public requires = 0.0; + + public from: InterruptingTransitionMatch['from'] | null = null; + + public set (from: MotionStateEval, transition: TransitionMatch['transition'], requires: number) { + this.from = from; + this.transition = transition; + this.requires = requires; + return this as InterruptingTransitionMatch; + } +} + +const interruptingTransitionMatchCache = new InterruptingTransitionMatchCache(); enum NodeKind { entry, exit, any, animation, empty, + transitionSnapshot, } export class StateEval { /** - * @legacyPublic + * @internal */ public declare __DEBUG_ID__?: string; public declare stateMachine: StateMachineInfo; - constructor (node: State) { + constructor (node: { name: string }) { this.name = node.name; } @@ -1215,6 +1562,10 @@ export class MotionStateEval extends StateEval { } public updateToPort (deltaTime: number) { + if (DEBUG) { + // See `this.finishTransition()` + assertIsTrue(!Number.isNaN(this._toPort.progress)); + } this._toPort.progress = calcProgressUpdate( this._toPort.progress, this.duration, @@ -1240,6 +1591,10 @@ export class MotionStateEval extends StateEval { } public getToPortStatus (): Readonly { + if (DEBUG) { + // See `this.finishTransition()` + assertIsTrue(!Number.isNaN(this._toPort.progress)); + } const { statusCache: stateStatus } = this._toPort; if (DEBUG) { stateStatus.__DEBUG_ID__ = this.name; @@ -1248,12 +1603,22 @@ export class MotionStateEval extends StateEval { return stateStatus; } - public resetToPort () { - this._toPort.progress = 0.0; + public resetToPort (at: number) { + this._toPort.progress = at; } public finishTransition () { this._fromPort.progress = this._toPort.progress; + if (DEBUG) { + // Well, this statement exists for debugging purpose. + // Once the transition was finished, this method is called to + // switch this motion from "target" to "source". + // After, this motion can no longer be used as "target" + // unless `this.resetToPort()` is called. + // Let's set progress of this motion's "to port" to NaN, + // to catch such a violation. + this._toPort.progress = Number.NaN; + } } public sampleFromPort (weight: number) { @@ -1261,6 +1626,10 @@ export class MotionStateEval extends StateEval { } public sampleToPort (weight: number) { + if (DEBUG) { + // See `this.finishTransition()` + assertIsTrue(!Number.isNaN(this._toPort.progress)); + } this._source?.sample(this._toPort.progress, weight); } @@ -1302,7 +1671,8 @@ function calcProgressUpdate (currentProgress: number, duration: number, deltaTim } function normalizeProgress (progress: number) { - return progress - Math.trunc(progress); + const signedFrac = progress - Math.trunc(progress); + return signedFrac >= 0.0 ? signedFrac : (1.0 + signedFrac); } interface MotionEvalPort { @@ -1327,7 +1697,59 @@ export class EmptyStateEval extends StateEval { } } -export type NodeEval = MotionStateEval | SpecialStateEval | EmptyStateEval; +class QueuedMotion { + constructor (public motion: MotionStateEval, public weight: number) { + } +} + +class TransitionSnapshotEval extends StateEval { + public readonly kind = NodeKind.transitionSnapshot; + + constructor () { + super({ name: `[[TransitionSnapshotEval]]` }); + } + + get empty () { + return this._queue.length === 0; + } + + get first () { + const { _queue: queue } = this; + assertIsTrue(queue.length > 0); + return queue[0].motion; + } + + public sample (weight: number) { + const { _queue: queue } = this; + const nQueue = queue.length; + for (let iQueuedMotions = 0; iQueuedMotions < nQueue; ++iQueuedMotions) { + const { + motion, + weight: snapshotWeight, + } = queue[iQueuedMotions]; + // Here implies: motions added to snapshot should have been switched from "target" to "source". + motion.sampleFromPort(snapshotWeight * weight); + } + } + + public clear () { + this._queue.length = 0; + } + + public enqueue (state: MotionStateEval, weight: number) { + const { _queue: queue } = this; + const nQueue = queue.length; + const complementWeight = 1.0 - weight; + for (let iQueuedMotions = 0; iQueuedMotions < nQueue; ++iQueuedMotions) { + queue[iQueuedMotions].weight *= complementWeight; + } + queue.push(new QueuedMotion(state, weight)); + } + + private _queue: QueuedMotion[] = []; +} + +export type NodeEval = MotionStateEval | SpecialStateEval | EmptyStateEval | TransitionSnapshotEval; interface TransitionEval { to: NodeEval; @@ -1336,10 +1758,12 @@ interface TransitionEval { conditions: ConditionEval[]; exitConditionEnabled: boolean; exitCondition: number; + destinationStart: number; /** * Bound triggers, once this transition satisfied. All triggers would be reset. */ triggers: string[] | undefined; + interruption: TransitionInterruptionSource; } export type { VarInstance } from './variable'; diff --git a/cocos/core/animation/marionette/runtime-exports.ts b/cocos/core/animation/marionette/runtime-exports.ts index 5783d5f547..b31621e42a 100644 --- a/cocos/core/animation/marionette/runtime-exports.ts +++ b/cocos/core/animation/marionette/runtime-exports.ts @@ -13,8 +13,3 @@ export type { ClipStatus, TransitionStatus, MotionStateStatus } from './animatio export { VariableType } from './parametric'; export { StateMachineComponent } from './state-machine-component'; export type { Value } from './variable'; - -/** - * @deprecated Since v3.4-preview-2. Use `MotionStateStatus` instead. - */ -export type StateStatus = MotionStateStatus; diff --git a/cocos/core/animation/marionette/state-machine-component.ts b/cocos/core/animation/marionette/state-machine-component.ts index 1a3d2a2987..875fe85120 100644 --- a/cocos/core/animation/marionette/state-machine-component.ts +++ b/cocos/core/animation/marionette/state-machine-component.ts @@ -2,10 +2,17 @@ import { ccclass } from 'cc.decorator'; import { CLASS_NAME_PREFIX_ANIM } from '../define'; import type { AnimationController, MotionStateStatus } from './animation-controller'; +/** + * @en State machine component. + * @zh 状态机组件。 + */ @ccclass(`${CLASS_NAME_PREFIX_ANIM}StateMachineComponent`) export class StateMachineComponent { /** + * @en * Called when a motion state right after it entered. + * @zh + * 在刚刚进入动作状态时调用。 * @param controller The animation controller it within. * @param motionStateStatus The status of the motion. */ @@ -14,7 +21,10 @@ export class StateMachineComponent { } /** + * @en * Called when a motion state is going to be exited. + * @zh + * 在即将退出动作状态时调用。 * @param controller The animation controller it within. * @param motionStateStatus The status of the motion. */ @@ -23,7 +33,10 @@ export class StateMachineComponent { } /** + * @en * Called when a motion state updated except for the first and last frame. + * @zh + * 在动作状态更新时调用,但不会在第一次和最后一次时调用。 * @param controller The animation controller it within. * @param motionStateStatus The status of the motion. */ @@ -32,7 +45,10 @@ export class StateMachineComponent { } /** + * @en * Called when a state machine right after it entered. + * @zh + * 在刚刚进入状态机时调用。 * @param controller The animation controller it within. */ public onStateMachineEnter (controller: AnimationController) { @@ -40,7 +56,10 @@ export class StateMachineComponent { } /** + * @en * Called when a state machine right after it entered. + * @zh + * 在即将退出状态机时调用。 * @param controller The animation controller it within. */ public onStateMachineExit (controller: AnimationController) { diff --git a/cocos/core/animation/marionette/variable.ts b/cocos/core/animation/marionette/variable.ts index 52df9dd49e..3906056fdc 100644 --- a/cocos/core/animation/marionette/variable.ts +++ b/cocos/core/animation/marionette/variable.ts @@ -1,17 +1,69 @@ -import { TriggerResetMode } from "./animation-graph"; - +/** + * @en + * Represents variable's value. + * @zh + * 表示变量的值。 + */ export type Value = number | string | boolean; +/** + * @en + * Represents animation graph variable types. + * @zh + * 表示动画图变量的类型。 + */ export enum VariableType { + /** + * @en + * A floating. + * @zh + * 浮点数。 + */ FLOAT, + /** + * @en + * A boolean. + * @zh + * 布尔值。 + */ BOOLEAN, + /** + * @en + * A trigger. + * @zh + * 触发器。 + */ TRIGGER, + /** + * @en + * An integer. + * @zh + * 整数。 + */ INTEGER, } +/** + * @en The reset mode of boolean variables. It indicates when to reset the variable as `false`. + * @zh 布尔类型变量的重置模式,指示在哪些情况下将变量重置为 `false`。 + */ +export enum TriggerResetMode { + /** + * @en The variable is reset when it's consumed by animation transition. + * @zh 在该变量被动画过渡消耗后自动重置。 + */ + AFTER_CONSUMED, + + /** + * @en The variable is reset in next frame or when it's consumed by animation transition. + * @zh 下一帧自动重置;在该变量被动画过渡消耗后也会自动重置。 + */ + NEXT_FRAME_OR_AFTER_CONSUMED, +} + export class VarInstance { public type: VariableType; diff --git a/cocos/core/animation/motion-path-helper.ts b/cocos/core/animation/motion-path-helper.ts index ea9d545627..961d7f9dca 100644 --- a/cocos/core/animation/motion-path-helper.ts +++ b/cocos/core/animation/motion-path-helper.ts @@ -23,16 +23,12 @@ THE SOFTWARE. */ - - import { binarySearchEpsilon as binarySearch } from '../algorithm/binary-search'; import { errorID } from '../platform/debug'; import { Vec2, Vec3 } from '../math'; import { AnimCurve, computeRatioByType, CurveValue, EasingMethod } from './animation-curve'; import { bezier } from './bezier'; - - export class Curve { public beziers: Bezier[] = []; @@ -92,7 +88,7 @@ export class Bezier { public endCtrlPoint = new Vec2(); /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public __arcLengthDivisions?: number; diff --git a/cocos/core/animation/playable.ts b/cocos/core/animation/playable.ts index 7c24c96e39..bf3e6c6019 100644 --- a/cocos/core/animation/playable.ts +++ b/cocos/core/animation/playable.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module animation - */ - import { getError } from '../platform/debug'; export class Playable { diff --git a/cocos/core/animation/skeletal-animation-utils.ts b/cocos/core/animation/skeletal-animation-utils.ts index 65563e0084..8f5d6dbd04 100644 --- a/cocos/core/animation/skeletal-animation-utils.ts +++ b/cocos/core/animation/skeletal-animation-utils.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { EDITOR } from 'internal:constants'; import { Mat4 } from '../math'; import { Node } from '../scene-graph/node'; diff --git a/cocos/core/animation/target-path.ts b/cocos/core/animation/target-path.ts index 317bc36681..6b7a061492 100644 --- a/cocos/core/animation/target-path.ts +++ b/cocos/core/animation/target-path.ts @@ -23,32 +23,53 @@ THE SOFTWARE. */ - - import { ccclass, serializable } from 'cc.decorator'; import { Node } from '../scene-graph/node'; import { warn, warnID } from '../platform/debug'; +/** + * @deprecated Since V3.3, use [[TrackPath]] instead. + */ export type PropertyPath = string | number; +/** + * @deprecated Since V3.3, use [[TrackPath]] instead. + */ export interface ICustomTargetPath { /** + * @en + * Gets next target from current target. * If errors are encountered, `null` should be returned. + * @zh + * 从当前目标中获取下一个目标。 + * 若错误发生,应返回 `null`。 * @param target */ get(target: any): any; } +/** + * @deprecated Since V3.3, use [[TrackPath]] instead. + */ export type TargetPath = PropertyPath | ICustomTargetPath; +/** + * @deprecated Since V3.3, use [[TrackPath]] instead. + */ export function isPropertyPath (path: TargetPath): path is PropertyPath { return typeof path === 'string' || typeof path === 'number'; } +/** + * @deprecated Since V3.3, use [[TrackPath]] instead. + */ export function isCustomPath (path: TargetPath, constructor: Constructor): path is T { return path instanceof constructor; } +/** + * @deprecated Since V3.3, use [[TrackPath]] instead. + */ @ccclass('cc.animation.HierarchyPath') export class HierarchyPath implements ICustomTargetPath { @serializable @@ -72,6 +93,9 @@ export class HierarchyPath implements ICustomTargetPath { } } +/** + * @deprecated Since V3.3, use [[TrackPath]] instead. + */ @ccclass('cc.animation.ComponentPath') export class ComponentPath implements ICustomTargetPath { @serializable diff --git a/cocos/core/animation/tracks/array-track.ts b/cocos/core/animation/tracks/array-track.ts new file mode 100644 index 0000000000..3a2df0c00d --- /dev/null +++ b/cocos/core/animation/tracks/array-track.ts @@ -0,0 +1,78 @@ +import { ccclass, serializable } from 'cc.decorator'; +import { RealCurve } from '../../curves'; +import { CLASS_NAME_PREFIX_ANIM, createEvalSymbol } from '../define'; +import { Channel, RealChannel, RuntimeBinding, Track } from './track'; + +/** + * @en + * A real array track animates a real array attribute of target(such as morph weights of mesh renderer). + * Every element in the array is corresponding to a real channel. + * @zh + * 实数数组轨道描述目标上某个实数数组属性(例如网格渲染器的形变权重)的动画。 + * 数组中的每个元素都对应一条实数通道。 + */ +@ccclass(`${CLASS_NAME_PREFIX_ANIM}RealArrayTrack`) +export class RealArrayTrack extends Track { + /** + * @en The number of elements in the array which this track produces. + * If you increased the count, there will be new empty real channels appended. + * Otherwise if you decreased the count, the last specified number channels would be removed. + * @zh 此轨道产生的数组元素的数量。 + * 当你增加数量时,会增加新的空实数通道;当你减少数量时,最后几个指定数量的通道会被移除。 + */ + get elementCount () { + return this._channels.length; + } + + set elementCount (value) { + const { _channels: channels } = this; + const nChannels = channels.length; + if (value < nChannels) { + this._channels.splice(value); + } else if (value > nChannels) { + this._channels.push( + ...Array.from({ length: value - nChannels }, + () => new Channel(new RealCurve())), + ); + } + } + + /** + * @en The channels of the track. + * @zh 返回此轨道的所有通道的数组。 + */ + public channels () { + return this._channels; + } + + /** + * @internal + */ + public [createEvalSymbol] () { + return new RealArrayTrackEval(this._channels.map(({ curve }) => curve)); + } + + @serializable + private _channels: RealChannel[] = []; +} + +export class RealArrayTrackEval { + constructor ( + private _curves: RealCurve[], + ) { + this._result = new Array(_curves.length).fill(0.0); + } + + public evaluate (time: number, _runtimeBinding: RuntimeBinding) { + const { + _result: result, + } = this; + const nElements = result.length; + for (let iElement = 0; iElement < nElements; ++iElement) { + result[iElement] = this._curves[iElement].evaluate(time); + } + return this._result; + } + + private declare _result: number[]; +} diff --git a/cocos/core/animation/tracks/color-track.ts b/cocos/core/animation/tracks/color-track.ts index 0e756891e0..46a789a952 100644 --- a/cocos/core/animation/tracks/color-track.ts +++ b/cocos/core/animation/tracks/color-track.ts @@ -7,6 +7,12 @@ import { maskIfEmpty } from './utils'; const CHANNEL_NAMES: ReadonlyArray = ['Red', 'Green', 'Blue', 'Alpha']; +/** + * @en + * A color track animates a color attribute of target. + * @zh + * 颜色轨道描述目标上某个颜色属性的动画。 + */ @ccclass(`${CLASS_NAME_PREFIX_ANIM}ColorTrack`) export class ColorTrack extends Track { constructor () { @@ -19,10 +25,19 @@ export class ColorTrack extends Track { } } + /** + * @en The four channel of the track. + * @zh 返回此轨道的四条通道。 + * @returns An readonly four length array in which + * the element at n denotes the channel of n-th(in order of RGBA) color component(in form of integer within 0-255). + */ public channels () { return this._channels; } + /** + * @internal + */ public [createEvalSymbol] () { return new ColorTrackEval( maskIfEmpty(this._channels[0].curve), diff --git a/cocos/core/animation/tracks/object-track.ts b/cocos/core/animation/tracks/object-track.ts index 9d3b9a73c7..fbbd79b0c7 100644 --- a/cocos/core/animation/tracks/object-track.ts +++ b/cocos/core/animation/tracks/object-track.ts @@ -3,8 +3,17 @@ import { ObjectCurve } from '../../curves'; import { CLASS_NAME_PREFIX_ANIM, createEvalSymbol } from '../define'; import { SingleChannelTrack } from './track'; +/** + * @en + * An object track animates an object of attribute of target. + * @zh + * 对象轨道描述目标上某个对象类型的属性的动画。 + */ @ccclass(`${CLASS_NAME_PREFIX_ANIM}ObjectTrack`) export class ObjectTrack extends SingleChannelTrack> { + /** + * @internal + */ protected createCurve () { return new ObjectCurve(); } diff --git a/cocos/core/animation/tracks/quat-track.ts b/cocos/core/animation/tracks/quat-track.ts index ca47898257..2bb73c2555 100644 --- a/cocos/core/animation/tracks/quat-track.ts +++ b/cocos/core/animation/tracks/quat-track.ts @@ -4,12 +4,24 @@ import { CLASS_NAME_PREFIX_ANIM, createEvalSymbol } from '../define'; import { SingleChannelTrack } from './track'; import { Quat } from '../../math'; +/** + * @en + * A quaternion track animates a quaternion(rotation) attribute of target. + * @zh + * 四元数轨道描述目标上某个四元数(旋转)属性的动画。 + */ @ccclass(`${CLASS_NAME_PREFIX_ANIM}QuatTrack`) export class QuatTrack extends SingleChannelTrack { + /** + * @internal + */ protected createCurve () { return new QuatCurve(); } + /** + * @internal + */ public [createEvalSymbol] () { return new QuatTrackEval(this.channels()[0].curve); } diff --git a/cocos/core/animation/tracks/real-track.ts b/cocos/core/animation/tracks/real-track.ts index 760691457f..60c2b4b324 100644 --- a/cocos/core/animation/tracks/real-track.ts +++ b/cocos/core/animation/tracks/real-track.ts @@ -3,8 +3,17 @@ import { RealCurve } from '../../curves'; import { CLASS_NAME_PREFIX_ANIM } from '../define'; import { SingleChannelTrack } from './track'; +/** + * @en + * A real track animates a scalar attribute of target. + * @zh + * 实数轨道描述目标上某个标量属性的动画。 + */ @ccclass(`${CLASS_NAME_PREFIX_ANIM}RealTrack`) export class RealTrack extends SingleChannelTrack { + /** + * @internal + */ protected createCurve () { return new RealCurve(); } diff --git a/cocos/core/animation/tracks/size-track.ts b/cocos/core/animation/tracks/size-track.ts index d9871b3459..c167381819 100644 --- a/cocos/core/animation/tracks/size-track.ts +++ b/cocos/core/animation/tracks/size-track.ts @@ -7,6 +7,12 @@ import { maskIfEmpty } from './utils'; const CHANNEL_NAMES: ReadonlyArray = ['Width', 'Height']; +/** + * @en + * A size track animates a size attribute of target. + * @zh + * 尺寸轨道描述目标上某个尺寸属性的动画。 + */ @ccclass(`${CLASS_NAME_PREFIX_ANIM}SizeTrack`) export class SizeTrack extends Track { constructor () { @@ -19,10 +25,19 @@ export class SizeTrack extends Track { } } + /** + * @en The width channel and the height channel of the track. + * @zh 返回此轨道的宽度通道和高度通道。 + * @returns An readonly array in which + * the first element is the width channel and the second element is the height channel. + */ public channels () { return this._channels; } + /** + * @internal + */ public [createEvalSymbol] () { return new SizeTrackEval( maskIfEmpty(this._channels[0].curve), diff --git a/cocos/core/animation/tracks/track.ts b/cocos/core/animation/tracks/track.ts index d1996f453d..4f4389e9e7 100644 --- a/cocos/core/animation/tracks/track.ts +++ b/cocos/core/animation/tracks/track.ts @@ -28,27 +28,59 @@ export type Binder = (binding: TrackBinding) => undefined | RuntimeBinding; export type TrsTrackPath = [HierarchyPath, 'position' | 'rotation' | 'scale' | 'eulerAngles']; +/** + * @en Describes how to find the animation target. + * @zh 描述怎样寻址动画目标。 + */ @ccclass(`${CLASS_NAME_PREFIX_ANIM}TrackPath`) class TrackPath { + /** + * @en The length of the path. + * @zh 此路径的段数。 + */ get length () { return this._paths.length; } + /** + * @en Appends a property path. + * @zh 附加一段属性路径。 + * @param name The property's name. + * @returns `this` + */ public toProperty (name: string) { this._paths.push(name); return this; } + /** + * @en Appends an array element path. + * @zh 附加一段数组元素路径。 + * @param index The element's index. + * @returns `this` + */ public toElement (index: number) { this._paths.push(index); return this; } + /** + * @en Appends a hierarchy path. + * @zh 附加一段层级路径。 + * @param nodePath Path to the children. + * @returns `this` + */ public toHierarchy (nodePath: string) { this._paths.push(new HierarchyPath(nodePath)); return this; } + /** + * @en Appends a component path. + * @zh 附加一段组件路径。 + * @param constructor @en The constructor of the component. @zh 组件的构造函数。 + * @returns `this` + */ public toComponent (constructor: Constructor | string) { const path = new ComponentPath(typeof constructor === 'string' ? constructor : js.getClassName(constructor)); this._paths.push(path); @@ -56,65 +88,132 @@ class TrackPath { } /** - * @legacyPublic Reserved for backward compatibility. DO NOT USE IT IN YOUR CODE. + * @internal Reserved for backward compatibility. DO NOT USE IT IN YOUR CODE. */ public toCustomized (resolver: CustomizedTrackPathResolver) { this._paths.push(resolver); return this; } + /** + * @en Appends paths to this path. + * @zh 附加指定路径到此路径后。 + * @param trackPaths Paths to append. + * @returns `this`. + */ public append (...trackPaths: TrackPath[]) { const paths = this._paths.concat(...trackPaths.map((trackPath) => trackPath._paths)); this._paths = paths; return this; } + /** + * @zh 判断指定路径段是否是属性路径。 + * @en Decides if the specific path segment is property path. + * @param index Index to the segment。 + * @returns The judgement result. + */ public isPropertyAt (index: number) { return typeof (this._paths[index]) === 'string'; } + /** + * @zh 将指定路径段视为属性路径,获取其描述的属性。 + * @en Treats the path segment as a property path. Obtains the property it describes. + * @param index Index to the segment。 + * @returns The property. + */ public parsePropertyAt (index: number): string { return this._paths[index] as string; } + /** + * @zh 判断指定路径段是否是数组元素路径。 + * @en Decides if the specific path segment is an array element path. + * @param index Index to the segment。 + * @returns The judgement result. + */ public isElementAt (index: number) { return typeof this._paths[index] === 'number'; } + /** + * @zh 将指定路径段视为数组元素路径,获取其描述的数组元素。 + * @en Treats the path segment as an array element path. Obtains the element index it describes. + * @param index Index to the segment。 + * @returns The element index. + */ public parseElementAt (index: number): number { return this._paths[index] as number; } + /** + * @zh 判断指定路径段是否是层级路径。 + * @en Decides if the specific path segment is a hierarchy path. + * @param index Index to the segment。 + * @returns The judgement result. + */ public isHierarchyAt (index: number) { return this._paths[index] instanceof HierarchyPath; } + /** + * @zh 将指定路径段视为层级路径,获取其描述的层级路径。 + * @en Treats the path segment as a hierarchy path. Obtains the hierarchy path it describes. + * @param index Index to the segment。 + * @returns The hierarchy path. + */ public parseHierarchyAt (index: number) { assertIsTrue(this.isHierarchyAt(index)); return (this._paths[index] as HierarchyPath).path; } + /** + * @zh 判断指定路径段是否是组件路径。 + * @en Decides if the specific path segment is a component path. + * @param index Index to the segment。 + * @returns The judgement result. + */ public isComponentAt (index: number) { return this._paths[index] instanceof ComponentPath; } + /** + * @zh 将指定路径段视为组件路径,获取其描述的组件路径。 + * @en Treats the path segment as a hierarchy path. Obtains the component path it describes. + * @param index Index to the segment。 + * @returns The component path. + */ public parseComponentAt (index: number) { assertIsTrue(this.isComponentAt(index)); return (this._paths[index] as ComponentPath).component; } + /** + * @en Slices a interval of the path. + * @zh 分割指定区段上的路径。 + * @param beginIndex Begin index to the segment. Default to 0. + * @param endIndex End index to the segment. Default to the last segment. + * @returns The new path. + */ public slice (beginIndex?: number, endIndex?: number) { const trackPath = new TrackPath(); trackPath._paths = this._paths.slice(beginIndex, endIndex); return trackPath; } + /** + * @internal + */ public trace (object: unknown, beginIndex?: number, endIndex?: number) { beginIndex ??= 0; endIndex ??= this._paths.length; return this[normalizedFollowTag](object, beginIndex, endIndex); } + /** + * @internal + */ public [parseTrsPathTag] () { const { _paths: paths } = this; const nPaths = paths.length; @@ -158,6 +257,9 @@ class TrackPath { return { node: nodePath, property: prs }; } + /** + * @internal + */ public [normalizedFollowTag] (root: unknown, beginIndex: number, endIndex: number) { const { _paths: paths } = this; let result = root; @@ -285,11 +387,18 @@ interface CustomizedTrackPathResolver { export { TrackPath }; /** - * A track describes the path of animate a target. + * @en + * A track describes how to trace the target and how to animate it. * It's the basic unit of animation clip. + * @zh + * 轨道描述了动画目标的路径和动画的方式。它是动画剪辑的基础单元。 */ @ccclass(`${CLASS_NAME_PREFIX_ANIM}Track`) export abstract class Track { + /** + * @en Track path. + * @zh 轨道路径。 + */ get path () { return this._binding.path; } @@ -298,6 +407,10 @@ export abstract class Track { this._binding.path = value; } + /** + * @en Value proxy for the target. + * @zh 目标的值代理。 + */ get proxy () { return this._binding.proxy; } @@ -306,14 +419,27 @@ export abstract class Track { this._binding.proxy = value; } + /** + * @internal + */ get [trackBindingTag] () { return this._binding; } + /** + * @en Channels on this track. + * @zh 此轨道上的通道。 + * @returns Iterator to the channels. + */ public channels (): Iterable { return []; } + /** + * @en Time range of this track. + * @zh 此轨道的时间范围。 + * @returns The time range. + */ public range (): Range { const range: Range = { min: Infinity, max: -Infinity }; for (const channel of this.channels()) { @@ -323,6 +449,9 @@ export abstract class Track { return range; } + /** + * @internal + */ public abstract [createEvalSymbol] (runtimeBinding: RuntimeBinding): TrackEval; @serializable @@ -339,6 +468,12 @@ export interface TrackEval { export type Curve = RealCurve | QuatCurve | ObjectCurve; +/** + * @en + * Channel contains a curve. + * @zh + * 通道包含了一条曲线。 + */ @ccclass(`${CLASS_NAME_PREFIX_ANIM}Channel`) export class Channel { constructor (curve: T) { @@ -346,10 +481,14 @@ export class Channel { } /** - * Not used for now. + * @internal Not used for now. */ public name = ''; + /** + * @en The curve within the channel. + * @zh 通道中的曲线。 + */ get curve () { return this._curve; } @@ -362,6 +501,10 @@ export type RealChannel = Channel; export type QuatChannel = Channel; +/** + * @en 表示一个包含了单条通道的轨道。 + * @zh Describes a track which contains only single channel. + */ @ccclass(`${CLASS_NAME_PREFIX_ANIM}SingleChannelTrack`) export abstract class SingleChannelTrack extends Track { constructor () { @@ -369,6 +512,10 @@ export abstract class SingleChannelTrack extends Track { this._channel = new Channel(this.createCurve()); } + /** + * @en The channel within the track. + * @zh 轨道包含的通道。 + */ get channel () { return this._channel; } @@ -377,10 +524,16 @@ export abstract class SingleChannelTrack extends Track { return [this._channel]; } + /** + * @internal + */ protected createCurve (): TCurve { throw new Error(`Not impl`); } + /** + * @internal + */ public [createEvalSymbol] (_runtimeBinding: RuntimeBinding): TrackEval { const { curve } = this._channel; return new SingleChannelTrackEval(curve); diff --git a/cocos/core/animation/tracks/untyped-track.ts b/cocos/core/animation/tracks/untyped-track.ts index 5c6482c97b..15655c0483 100644 --- a/cocos/core/animation/tracks/untyped-track.ts +++ b/cocos/core/animation/tracks/untyped-track.ts @@ -28,6 +28,9 @@ export class UntypedTrack extends Track { return this._channels; } + /** + * @internal + */ public [createEvalSymbol] (runtimeBinding: RuntimeBinding) { if (!runtimeBinding.getValue) { throw new Error(getError(3930)); diff --git a/cocos/core/animation/tracks/vector-track.ts b/cocos/core/animation/tracks/vector-track.ts index 0608912bca..a553f318f5 100644 --- a/cocos/core/animation/tracks/vector-track.ts +++ b/cocos/core/animation/tracks/vector-track.ts @@ -7,6 +7,12 @@ import { maskIfEmpty } from './utils'; const CHANNEL_NAMES: ReadonlyArray = ['X', 'Y', 'Z', 'W']; +/** + * @en + * A vector track animates a vector(in 2, 3, 4 dimension) attribute of target. + * @zh + * 向量轨道描述目标上某个(二、三、四维)向量属性的动画。 + */ @ccclass(`${CLASS_NAME_PREFIX_ANIM}VectorTrack`) export class VectorTrack extends Track { constructor () { @@ -19,6 +25,10 @@ export class VectorTrack extends Track { } } + /** + * @en Gets or sets the count of components(dimension) available while evaluating of this track. + * @zh 获取或设置此轨道在求值时有效的分量数(维度)。 + */ get componentsCount () { return this._nComponents; } @@ -27,10 +37,19 @@ export class VectorTrack extends Track { this._nComponents = value; } + /** + * @en The four channel of the track. + * @zh 返回此轨道的四条通道。 + * @returns An readonly four length array in which + * the element at n denotes the channel of n-th vector component. + */ public channels () { return this._channels; } + /** + * @internal + */ public [createEvalSymbol] () { switch (this._nComponents) { default: diff --git a/cocos/core/animation/transform-utils.ts b/cocos/core/animation/transform-utils.ts index d809d15491..670a34c972 100644 --- a/cocos/core/animation/transform-utils.ts +++ b/cocos/core/animation/transform-utils.ts @@ -23,16 +23,14 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module animation - */ - import { Mat4 } from '../math'; import { Node } from '../scene-graph'; const m4_1 = new Mat4(); +/** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ export function getPathFromRoot (target: Node | null, root: Node) { let node: Node | null = target; let path = ''; @@ -43,6 +41,9 @@ export function getPathFromRoot (target: Node | null, root: Node) { return path.slice(0, -1); } +/** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ export function getWorldTransformUntilRoot (target: Node, root: Node, outMatrix: Mat4) { Mat4.identity(outMatrix); while (target !== root) { diff --git a/cocos/core/animation/types.ts b/cocos/core/animation/types.ts index 6ba36624fb..83450cc289 100644 --- a/cocos/core/animation/types.ts +++ b/cocos/core/animation/types.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module animation - */ - import { ccenum } from '../value-types/enum'; export enum WrapModeMask { diff --git a/cocos/core/animation/value-proxy-factories/index.ts b/cocos/core/animation/value-proxy-factories/index.ts index 0f44967c6b..f289d423b4 100644 --- a/cocos/core/animation/value-proxy-factories/index.ts +++ b/cocos/core/animation/value-proxy-factories/index.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - export * from './uniform'; export { MorphWeightValueProxy, MorphWeightsValueProxy, MorphWeightsAllValueProxy } from './morph-weights'; diff --git a/cocos/core/animation/value-proxy-factories/morph-weights.ts b/cocos/core/animation/value-proxy-factories/morph-weights.ts index 26c9ab3db0..42cccb000b 100644 --- a/cocos/core/animation/value-proxy-factories/morph-weights.ts +++ b/cocos/core/animation/value-proxy-factories/morph-weights.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { ccclass, serializable } from 'cc.decorator'; import { MeshRenderer } from '../../../3d/framework/mesh-renderer'; import { IValueProxyFactory } from '../value-proxy'; diff --git a/cocos/core/animation/value-proxy-factories/uniform.ts b/cocos/core/animation/value-proxy-factories/uniform.ts index 088a86366b..df1bde8913 100644 --- a/cocos/core/animation/value-proxy-factories/uniform.ts +++ b/cocos/core/animation/value-proxy-factories/uniform.ts @@ -23,14 +23,12 @@ THE SOFTWARE. */ - - import { ccclass, float, serializable } from 'cc.decorator'; import { builtinResMgr } from '../../builtin/builtin-res-mgr'; import { Material } from '../../assets/material'; import { SpriteFrame } from '../../../2d/assets/sprite-frame'; import { TextureBase } from '../../assets/texture-base'; -import { Type } from '../../gfx'; +import { deviceManager, Type } from '../../gfx'; import { Pass } from '../../renderer/core/pass'; import { getDefaultFromType } from '../../renderer/core/pass-utils'; import { IValueProxy, IValueProxyFactory } from '../value-proxy'; @@ -117,7 +115,7 @@ export class UniformProxyFactory implements IValueProxyFactory { if (!texture || !texture.width || !texture.height) { return; } pass.bindTexture(binding, texture); if (value instanceof TextureBase) { - pass.bindSampler(binding, legacyCC.game._gfxDevice.getSampler(value.getSamplerInfo())); + pass.bindSampler(binding, deviceManager.gfxDevice.getSampler(value.getSamplerInfo())); } }, }; diff --git a/cocos/core/animation/value-proxy.ts b/cocos/core/animation/value-proxy.ts index ab84d194ec..cfb6d0dd89 100644 --- a/cocos/core/animation/value-proxy.ts +++ b/cocos/core/animation/value-proxy.ts @@ -24,17 +24,27 @@ */ /** - * @packageDocumentation - * @module animation - */ - -/** + * @en + * Value proxies are used to set curve value to target. They are "generalized assignment". + * Every value proxy associates with a target object. + * @zh * 曲线值代理用来设置曲线值到目标,是广义的赋值。 * 每个曲线值代理都关联着一个目标对象。 */ export interface IValueProxy { - get?: () => any; /** + * @en + * Gets the value from the target. + * This method is used for implementing component-wise animation in certain circumstance. + * @zh + * 从目标中获取值。某些情况下可能需要这个接口来实现分量动画。 + */ + get?: () => any; + + /** + * @en + * Sets a value. + * @zh * 设置曲线值到目标对象上。 */ set: (value: any) => void; @@ -42,8 +52,11 @@ export interface IValueProxy { export interface IValueProxyFactory { /** + * @en + * Returns a value proxy for specific target. + * @zh * 返回指定目标的曲线值代理。 - * @param target + * @param target The target acquiring the value proxy. */ forTarget (target: any): IValueProxy; } diff --git a/cocos/core/asset-manager/asset-manager.ts b/cocos/core/asset-manager/asset-manager.ts index 4d75e311fa..e7ad816ea4 100644 --- a/cocos/core/asset-manager/asset-manager.ts +++ b/cocos/core/asset-manager/asset-manager.ts @@ -22,15 +22,13 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset-manager - */ -import { BUILD, EDITOR, PREVIEW } from 'internal:constants'; + +import { BUILD, EDITOR, PREVIEW, TEST } from 'internal:constants'; import { Asset } from '../assets/asset'; import { legacyCC } from '../global-exports'; import { error } from '../platform/debug'; import { sys } from '../platform/sys'; +import { Settings, settings } from '../settings'; import { basename, extname } from '../utils/path'; import Bundle from './bundle'; import Cache, { ICache } from './cache'; @@ -116,10 +114,10 @@ export interface IAssetManagerOptions { /** * @en * This module controls asset's behaviors and information, include loading, releasing etc. it is a singleton - * All member can be accessed with `cc.assetManager`. + * All member can be accessed with `assetManager`. * * @zh - * 此模块管理资源的行为和信息,包括加载,释放等,这是一个单例,所有成员能够通过 `cc.assetManager` 调用 + * 此模块管理资源的行为和信息,包括加载,释放等,这是一个单例,所有成员能够通过 `assetManager` 调用 * */ export class AssetManager { @@ -155,20 +153,20 @@ export class AssetManager { /** * @en - * The collection of bundle which is already loaded, you can remove cache with {{#crossLink "AssetManager/removeBundle:method"}}{{/crossLink}} + * The collection of bundle which is already loaded, you can remove cache with [[removeBundle]] * * @zh - * 已加载 bundle 的集合, 你能通过 {{#crossLink "AssetManager/removeBundle:method"}}{{/crossLink}} 来移除缓存 + * 已加载 bundle 的集合, 你能通过 [[removeBundle]] 来移除缓存 * */ public bundles: ICache = bundles; /** * @en - * The collection of asset which is already loaded, you can remove cache with {{#crossLink "AssetManager/releaseAsset:method"}}{{/crossLink}} + * The collection of asset which is already loaded, you can remove cache with [[releaseAsset]] * * @zh - * 已加载资源的集合, 你能通过 {{#crossLink "AssetManager/releaseAsset:method"}}{{/crossLink}} 来移除缓存 + * 已加载资源的集合, 你能通过 [[releaseAsset]] 来移除缓存 */ public assets: ICache = assets; @@ -325,20 +323,23 @@ export class AssetManager { * */ public init (options: IAssetManagerOptions = {}) { + const server = options.server || settings.querySettings(Settings.Category.ASSETS, 'server') || ''; + const bundleVers = options.bundleVers || settings.querySettings(Settings.Category.ASSETS, 'bundleVers') || {}; + const remoteBundles = options.remoteBundles || settings.querySettings(Settings.Category.ASSETS, 'remoteBundles') || []; this._files.clear(); this._parsed.clear(); this._releaseManager.init(); this.assets.clear(); this.bundles.clear(); this.packManager.init(); - this.downloader.init(options.server, options.bundleVers, options.remoteBundles); + this.downloader.init(server, bundleVers, remoteBundles); this.parser.init(); this.dependUtil.init(); - let importBase = options.importBase || ''; + let importBase = options.importBase || settings.querySettings(Settings.Category.ASSETS, 'importBase') || ''; if (importBase && importBase.endsWith('/')) { importBase = importBase.substr(0, importBase.length - 1); } - let nativeBase = options.nativeBase || ''; + let nativeBase = options.nativeBase || settings.querySettings(Settings.Category.ASSETS, 'nativeBase') || ''; if (nativeBase && nativeBase.endsWith('/')) { nativeBase = nativeBase.substr(0, nativeBase.length - 1); } @@ -358,9 +359,9 @@ export class AssetManager { * * @example * // ${project}/assets/test1 - * cc.assetManager.getBundle('test1'); + * assetManager.getBundle('test1'); * - * cc.assetManager.getBundle('resources'); + * assetManager.getBundle('resources'); * */ public getBundle (name: string): Bundle | null { @@ -370,15 +371,15 @@ export class AssetManager { /** * @en * Remove this bundle. NOTE: The asset within this bundle will not be released automatically, - * you can call {{#crossLink "Bundle/releaseAll:method"}}{{/crossLink}} manually before remove it if you need + * you can call [[AssetManager.Bundle.releaseAll]] manually before remove it if you need * * @zh - * 移除此包, 注意:这个包内的资源不会自动释放, 如果需要的话你可以在摧毁之前手动调用 {{#crossLink "Bundle/releaseAll:method"}}{{/crossLink}} 进行释放 + * 移除此包, 注意:这个包内的资源不会自动释放, 如果需要的话你可以在摧毁之前手动调用 [[AssetManager.Bundle.releaseAll]] 进行释放 * * @param bundle - The bundle to be removed * * @typescript - * removeBundle(bundle: cc.AssetManager.Bundle): void + * removeBundle(bundle: AssetManager.Bundle): void */ public removeBundle (bundle: Bundle) { bundle._destroy(); @@ -420,20 +421,20 @@ export class AssetManager { * @param onComplete.data - The loaded content * * @example - * cc.assetManager.loadAny({url: 'http://example.com/a.png'}, (err, img) => cc.log(img)); - * cc.assetManager.loadAny(['60sVXiTH1D/6Aft4MRt9VC'], (err, assets) => cc.log(assets)); - * cc.assetManager.loadAny([{ uuid: '0cbZa5Y71CTZAccaIFluuZ'}, {url: 'http://example.com/a.png'}], (err, assets) => cc.log(assets)); - * cc.assetManager.downloader.register('.asset', (url, options, onComplete) => { + * assetManager.loadAny({url: 'http://example.com/a.png'}, (err, img) => log(img)); + * assetManager.loadAny(['60sVXiTH1D/6Aft4MRt9VC'], (err, assets) => log(assets)); + * assetManager.loadAny([{ uuid: '0cbZa5Y71CTZAccaIFluuZ'}, {url: 'http://example.com/a.png'}], (err, assets) => log(assets)); + * assetManager.downloader.register('.asset', (url, options, onComplete) => { * url += '?userName=' + options.userName + "&password=" + options.password; - * cc.assetManager.downloader.downloadFile(url, null, onComplete); + * assetManager.downloader.downloadFile(url, null, onComplete); * }); - * cc.assetManager.parser.register('.asset', (file, options, onComplete) => { + * assetManager.parser.register('.asset', (file, options, onComplete) => { * var json = JSON.parse(file); * var skin = json[options.skin]; * var model = json[options.model]; * onComplete(null, {skin, model}); * }); - * cc.assetManager.loadAny({ url: 'http://example.com/my.asset', skin: 'xxx', model: 'xxx', userName: 'xxx', password: 'xxx' }); + * assetManager.loadAny({ url: 'http://example.com/my.asset', skin: 'xxx', model: 'xxx', userName: 'xxx', password: 'xxx' }); * */ public loadAny (requests: Request, options: IOptions | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; @@ -458,13 +459,13 @@ export class AssetManager { /** * @en * General interface used to preload assets with a progression callback and a complete callback.It is highly recommended that you use - * more simple API, such as `preloadRes`, `preloadResDir` etc. Everything about preload is just likes `cc.assetManager.loadAny`, the - * difference is `cc.assetManager.preloadAny` will only download asset but not parse asset. You need to invoke `cc.assetManager.loadAny(preloadTask)` + * more simple API, such as `preloadRes`, `preloadResDir` etc. Everything about preload is just likes `assetManager.loadAny`, the + * difference is `assetManager.preloadAny` will only download asset but not parse asset. You need to invoke `assetManager.loadAny(preloadTask)` * to finish loading asset * * @zh * 通用预加载资源接口,可传入进度回调以及完成回调,非常建议你使用更简单的 API ,例如 `preloadRes`, `preloadResDir` 等。`preloadAny` 和 `loadAny` - * 几乎一样,区别在于 `preloadAny` 只会下载资源,不会去解析资源,你需要调用 `cc.assetManager.loadAny(preloadTask)` 来完成资源加载。 + * 几乎一样,区别在于 `preloadAny` 只会下载资源,不会去解析资源,你需要调用 `assetManager.loadAny(preloadTask)` 来完成资源加载。 * * @param requests - The request you want to preload * @param options - Optional parameters @@ -477,7 +478,7 @@ export class AssetManager { * @param onComplete.items - The preloaded content * * @example - * cc.assetManager.preloadAny('0cbZa5Y71CTZAccaIFluuZ', (err) => cc.assetManager.loadAny('0cbZa5Y71CTZAccaIFluuZ')); + * assetManager.preloadAny('0cbZa5Y71CTZAccaIFluuZ', (err) => assetManager.loadAny('0cbZa5Y71CTZAccaIFluuZ')); * */ public preloadAny ( @@ -517,9 +518,9 @@ export class AssetManager { * @param onComplete.asset - The loaded texture * * @example - * cc.assetManager.loadRemote('http://www.cloud.com/test1.jpg', (err, texture) => console.log(err)); - * cc.assetManager.loadRemote('http://www.cloud.com/test2.mp3', (err, audioClip) => console.log(err)); - * cc.assetManager.loadRemote('http://www.cloud.com/test3', { ext: '.png' }, (err, texture) => console.log(err)); + * assetManager.loadRemote('http://www.cloud.com/test1.jpg', (err, texture) => console.log(err)); + * assetManager.loadRemote('http://www.cloud.com/test2.mp3', (err, audioClip) => console.log(err)); + * assetManager.loadRemote('http://www.cloud.com/test3', { ext: '.png' }, (err, texture) => console.log(err)); * */ public loadRemote (url: string, options: IRemoteOptions | null, onComplete?: CompleteCallbackWithData | null): void; @@ -608,7 +609,7 @@ export class AssetManager { * * @example * // release a texture which is no longer need - * cc.assetManager.releaseAsset(texture); + * assetManager.releaseAsset(texture); * */ public releaseAsset (asset: Asset): void { @@ -617,10 +618,10 @@ export class AssetManager { /** * @en - * Release all unused assets. Refer to {{#crossLink "AssetManager/releaseAsset:method"}}{{/crossLink}} for detailed information. + * Release all unused assets. Refer to [[releaseAsset]] for detailed information. * * @zh - * 释放所有没有用到的资源。详细信息请参考 {{#crossLink "AssetManager/releaseAsset:method"}}{{/crossLink}} + * 释放所有没有用到的资源。详细信息请参考 [[releaseAsset]] * * @engineInternal * @@ -633,10 +634,10 @@ export class AssetManager { /** * @en - * Release all assets. Refer to {{#crossLink "AssetManager/releaseAsset:method"}}{{/crossLink}} for detailed information. + * Release all assets. Refer to [[releaseAsset]] for detailed information. * * @zh - * 释放所有资源。详细信息请参考 {{#crossLink "AssetManager/releaseAsset:method"}}{{/crossLink}} + * 释放所有资源。详细信息请参考 [[releaseAsset]] * */ public releaseAll () { diff --git a/cocos/core/asset-manager/bundle.ts b/cocos/core/asset-manager/bundle.ts index 821a0c8b51..2196dc6580 100644 --- a/cocos/core/asset-manager/bundle.ts +++ b/cocos/core/asset-manager/bundle.ts @@ -22,10 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset-manager - */ + import { Asset } from '../assets/asset'; import { SceneAsset } from '../assets/scene-asset'; import { legacyCC } from '../global-exports'; @@ -99,11 +96,11 @@ export default class Bundle { * 使用 path 获取资源的配置信息 * * @param path - The relative path of asset, such as 'images/a' - * @param type - The constructor of asset, such as `cc.Texture2D` + * @param type - The constructor of asset, such as `Texture2D` * @returns The asset info * * @example - * var info = bundle.getInfoWithPath('image/a', cc.Texture2D); + * var info = bundle.getInfoWithPath('image/a', Texture2D); * */ public getInfoWithPath (path: string, type?: AssetType | null): IAddressableInfo | null { @@ -124,7 +121,7 @@ export default class Bundle { * * @example * var infos = []; - * bundle.getDirWithPath('images', cc.Texture2D, infos); + * bundle.getDirWithPath('images', Texture2D, infos); */ public getDirWithPath (path: string, type?: AssetType | null, out?: IAddressableInfo[]): IAddressableInfo[] { return this._config.getDirWithPath(path, type, out); @@ -202,16 +199,16 @@ export default class Bundle { * * @example * // load the texture (${project}/assets/resources/textures/background.jpg) from resources - * cc.resources.load('textures/background', cc.Texture2D, (err, texture) => console.log(err)); + * resources.load('textures/background', Texture2D, (err, texture) => console.log(err)); * * // load the audio (${project}/assets/resources/music/hit.mp3) from resources - * cc.resources.load('music/hit', cc.AudioClip, (err, audio) => console.log(err)); + * resources.load('music/hit', AudioClip, (err, audio) => console.log(err)); * * // load the prefab (${project}/assets/bundle1/misc/character/cocos) from bundle1 folder - * bundle1.load('misc/character/cocos', cc.Prefab, (err, prefab) => console.log(err)); + * bundle1.load('misc/character/cocos', Prefab, (err, prefab) => console.log(err)); * * // load the sprite frame (${project}/assets/some/xxx/bundle2/imgs/cocos.png) from bundle2 folder - * bundle2.load('imgs/cocos', cc.SpriteFrame, null, (err, spriteFrame) => console.log(err)); + * bundle2.load('imgs/cocos', SpriteFrame, null, (err, spriteFrame) => console.log(err)); * */ public load ( @@ -263,20 +260,20 @@ export default class Bundle { * * @example * // preload the texture (${project}/assets/resources/textures/background.jpg) from resources - * cc.resources.preload('textures/background', cc.Texture2D); + * resources.preload('textures/background', Texture2D); * * // preload the audio (${project}/assets/resources/music/hit.mp3) from resources - * cc.resources.preload('music/hit', cc.AudioClip); + * resources.preload('music/hit', AudioClip); * // wait for while - * cc.resources.load('music/hit', cc.AudioClip, (err, audioClip) => {}); + * resources.load('music/hit', AudioClip, (err, audioClip) => {}); * * * // preload the prefab (${project}/assets/bundle1/misc/character/cocos) from bundle1 folder - * bundle1.preload('misc/character/cocos', cc.Prefab); + * bundle1.preload('misc/character/cocos', Prefab); * * // load the sprite frame of (${project}/assets/bundle2/imgs/cocos.png) from bundle2 folder - * bundle2.preload('imgs/cocos', cc.SpriteFrame); + * bundle2.preload('imgs/cocos', SpriteFrame); * // wait for while - * bundle2.load('imgs/cocos', cc.SpriteFrame, (err, spriteFrame) => {}); + * bundle2.load('imgs/cocos', SpriteFrame, (err, spriteFrame) => {}); * */ public preload (paths: string|string[], type: AssetType|null, onProgress: ProgressCallback|null, onComplete: CompleteCallbackWithData|null): void; @@ -315,19 +312,19 @@ export default class Bundle { * * @example * // load all audios (resources/audios/) - * cc.resources.loadDir('audios', cc.AudioClip, (err, audios) => {}); + * resources.loadDir('audios', AudioClip, (err, audios) => {}); * * // load all textures in "resources/imgs/" - * cc.resources.loadDir('imgs', cc.Texture2D, null, function (err, textures) { + * resources.loadDir('imgs', Texture2D, null, function (err, textures) { * var texture1 = textures[0]; * var texture2 = textures[1]; * }); * * // load all prefabs (${project}/assets/bundle1/misc/characters/) from bundle1 folder - * bundle1.loadDir('misc/characters', cc.Prefab, (err, prefabs) => console.log(err)); + * bundle1.loadDir('misc/characters', Prefab, (err, prefabs) => console.log(err)); * * // load all sprite frame (${project}/assets/some/xxx/bundle2/skills/) from bundle2 folder - * bundle2.loadDir('skills', cc.SpriteFrame, null, (err, spriteFrames) => console.log(err)); + * bundle2.loadDir('skills', SpriteFrame, null, (err, spriteFrames) => console.log(err)); * */ public loadDir (dir: string, type: AssetType | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; @@ -367,20 +364,20 @@ export default class Bundle { * * @example * // preload all audios (resources/audios/) - * cc.resources.preloadDir('audios', cc.AudioClip); + * resources.preloadDir('audios', AudioClip); * * // preload all textures in "resources/imgs/" - * cc.resources.preloadDir('imgs', cc.Texture2D); + * resources.preloadDir('imgs', Texture2D); * // wait for while - * cc.resources.loadDir('imgs', cc.Texture2D, (err, textures) => {}); + * resources.loadDir('imgs', Texture2D, (err, textures) => {}); * * // preload all prefabs (${project}/assets/bundle1/misc/characters/) from bundle1 folder - * bundle1.preloadDir('misc/characters', cc.Prefab); + * bundle1.preloadDir('misc/characters', Prefab); * * // preload all sprite frame (${project}/assets/some/xxx/bundle2/skills/) from bundle2 folder - * bundle2.preloadDir('skills', cc.SpriteFrame); + * bundle2.preloadDir('skills', SpriteFrame); * // wait for while - * bundle2.loadDir('skills', cc.SpriteFrame, (err, spriteFrames) => {}); + * bundle2.loadDir('skills', SpriteFrame, (err, spriteFrames) => {}); */ public preloadDir (dir: string, type: AssetType | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; public preloadDir (dir: string, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; @@ -414,7 +411,7 @@ export default class Bundle { * @param onComplete.sceneAsset - The scene asset * * @example - * bundle1.loadScene('first', (err, sceneAsset) => cc.director.runScene(sceneAsset)); + * bundle1.loadScene('first', (err, sceneAsset) => director.runScene(sceneAsset)); * */ public loadScene (sceneName: string, options: IAssetOptions | null, onProgress: ProgressCallback | null, onComplete: CompleteCallbackWithData | null): void; @@ -434,9 +431,8 @@ export default class Bundle { legacyCC.assetManager.loadAny({ scene: sceneName }, opts, onProg, (err, sceneAsset) => { if (err) { error(err.message, err.stack); - } else if (sceneAsset instanceof SceneAsset && sceneAsset.scene) { + } else if (sceneAsset.scene) { const scene = sceneAsset.scene; - // @ts-expect-error set private property scene._id = sceneAsset._uuid; scene.name = sceneAsset.name; } else { @@ -449,12 +445,12 @@ export default class Bundle { /** * @en * Preload the scene asset within this bundle by its name. After calling this method, you still need to finish loading - * by calling `Bundle.loadScene` or `cc.director.loadScene`.It will be totally fine to call `Bundle.loadDir` at any + * by calling `Bundle.loadScene` or `director.loadScene`.It will be totally fine to call `Bundle.loadDir` at any * time even if the preloading is not yet finished * * @zh - * 通过场景名称预加载分包中的场景资源.调用完后,你仍然需要通过 `Bundle.loadScene` 或 `cc.director.loadScene` 来完成加载。 - * 就算预加载还没完成,你也可以直接调用 `Bundle.loadScene` 或 `cc.director.loadScene`。 + * 通过场景名称预加载分包中的场景资源.调用完后,你仍然需要通过 `Bundle.loadScene` 或 `director.loadScene` 来完成加载。 + * 就算预加载还没完成,你也可以直接调用 `Bundle.loadScene` 或 `director.loadScene`。 * * @param sceneName - The name of the scene to preload. * @param options - Some optional parameters @@ -468,7 +464,7 @@ export default class Bundle { * @example * bundle1.preloadScene('first'); * // wait for a while - * bundle1.loadScene('first', (err, scene) => cc.director.runScene(scene)); + * bundle1.loadScene('first', (err, scene) => director.runScene(scene)); * */ public preloadScene (sceneName: string, options: IAssetOptions | null, onProgress: ProgressCallback, onComplete: CompleteCallbackNoData | null): void; @@ -495,14 +491,14 @@ export default class Bundle { /** * @en * Get cached asset within this bundle by path and type.
- * After you load asset with {{#crossLink "Bundle/load:method"}}{{/crossLink}} or {{#crossLink "Bundle/loadDir:method"}}{{/crossLink}}, + * After you load asset with [[load]] or [[loadDir]], * you can acquire them by passing the path to this API. * * NOTE:The `path` and `type` parameters passed need to be the same as those passed to `Bundle.load`, * otherwise it may return some other resources with the same name! * * @zh - * 通过路径与类型获取已缓存资源。在你使用 {{#crossLink "Bundle/load:method"}}{{/crossLink}} 或者 {{#crossLink "Bundle/loadDir:method"}}{{/crossLink}} 之后, + * 通过路径与类型获取已缓存资源。在你使用 [[load]] 或者 [[loadDir]] 之后, * 你能通过传路径通过这个 API 获取到这些资源。 * * 注意:传入的 path 与 type 参数需要与 `Bundle.load` 加载资源时传入的参数一致,否则可能会获取到其他同名资源 @@ -512,7 +508,7 @@ export default class Bundle { * @returns - the asset has been cached * * @example - * bundle1.get('music/hit', cc.AudioClip); + * bundle1.get('music/hit', AudioClip); */ public get (path: string, type?: AssetType | null): T | null { const info = this.getInfoWithPath(path, type); @@ -525,15 +521,15 @@ export default class Bundle { /** * @en - * Release the asset loaded by {{#crossLink "Bundle/load:method"}}{{/crossLink}} or {{#crossLink "Bundle/loadDir:method"}}{{/crossLink}} - * and it's dependencies. Refer to {{#crossLink "AssetManager/releaseAsset:method"}}{{/crossLink}} for detailed informations. + * Release the asset loaded by [[load]] or [[loadDir]] + * and it's dependencies. Refer to [[AssetManager.releaseAsset]] for detailed informations. * * NOTE:The `path` and `type` parameters passed need to be the same as those passed to `Bundle.load`, * otherwise it may release some other resources with the same name! * * @zh - * 释放通过 {{#crossLink "Bundle/load:method"}}{{/crossLink}} 或者 {{#crossLink "Bundle/loadDir:method"}}{{/crossLink}} 加载的资源。 - * 详细信息请参考 {{#crossLink "AssetManager/releaseAsset:method"}}{{/crossLink}} + * 释放通过 [[load]] 或者 [[loadDir]] 加载的资源。 + * 详细信息请参考 [[AssetManager.releaseAsset]] * * 注意:传入的 path 与 type 参数需要与 `Bundle.load` 加载资源时传入的参数一致,否则可能会释放到其他同名资源 * @@ -554,10 +550,10 @@ export default class Bundle { /** * @en - * Release all unused assets within this bundle. Refer to {{#crossLink "AssetManager/releaseAll:method"}}{{/crossLink}} for detailed informations. + * Release all unused assets within this bundle. Refer to [[AssetManager.releaseAll]] for detailed informations. * * @zh - * 释放此包中的所有没有用到的资源。详细信息请参考 {{#crossLink "AssetManager/releaseAll:method"}}{{/crossLink}} + * 释放此包中的所有没有用到的资源。详细信息请参考 [[AssetManager.releaseAll]] * * @private * @@ -577,10 +573,10 @@ export default class Bundle { /** * @en - * Release all assets within this bundle. Refer to {{#crossLink "AssetManager/releaseAll:method"}}{{/crossLink}} for detailed informations. + * Release all assets within this bundle. Refer to [[AssetManager.releaseAll]] for detailed information. * * @zh - * 释放此包中的所有资源。详细信息请参考 {{#crossLink "AssetManager/releaseAll:method"}}{{/crossLink}} + * 释放此包中的所有资源。详细信息请参考 [[AssetManager.releaseAll]] * * @example * // release all asset within bundle1 @@ -596,7 +592,7 @@ export default class Bundle { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _destroy () { this._config.destroy(); diff --git a/cocos/core/asset-manager/cache-manager.ts b/cocos/core/asset-manager/cache-manager.ts index ab3ade133a..446eb42e10 100644 --- a/cocos/core/asset-manager/cache-manager.ts +++ b/cocos/core/asset-manager/cache-manager.ts @@ -23,19 +23,15 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset-manager - */ import Cache from './cache'; /** * @en * Cache manager is a module which controls all caches downloaded from server in non-web platform, it is a singleton - * All member can be accessed with `cc.assetManager.cacheManager`. + * All member can be accessed with `assetManager.cacheManager`. * * @zh - * 缓存管理器是一个模块,在非 WEB 平台上,用于管理所有从服务器上下载下来的缓存,这是一个单例,所有成员能通过 `cc.assetManager.cacheManager` 访问。 + * 缓存管理器是一个模块,在非 WEB 平台上,用于管理所有从服务器上下载下来的缓存,这是一个单例,所有成员能通过 `assetManager.cacheManager` 访问。 * */ export default abstract class CacheManager { diff --git a/cocos/core/asset-manager/cache.ts b/cocos/core/asset-manager/cache.ts index 774903f26c..9863f133eb 100644 --- a/cocos/core/asset-manager/cache.ts +++ b/cocos/core/asset-manager/cache.ts @@ -22,10 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset-manager - */ + import { js } from '../utils/js'; export interface ICache { diff --git a/cocos/core/asset-manager/category.json b/cocos/core/asset-manager/category.json new file mode 100644 index 0000000000..3e5b97ef04 --- /dev/null +++ b/cocos/core/asset-manager/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "资源", + "en": "Asset" + }, + "description": { + "zh": "资源是游戏中的重要组成部分,Cocos Creator 支持导入不同类型的资源,并允许开发者将该资源运用在游戏中", + "en": "Assets are crucial for game content, Cocos Creator supports importing various types of assets and allows developers to use these resources in the game logic in runtime" + } +} \ No newline at end of file diff --git a/cocos/core/asset-manager/config.ts b/cocos/core/asset-manager/config.ts index 31f063978f..896e8a3631 100644 --- a/cocos/core/asset-manager/config.ts +++ b/cocos/core/asset-manager/config.ts @@ -288,7 +288,7 @@ export default class Config { const assetInfo = this.assetInfos.get(uuid) as IAddressableInfo; assetInfo.path = path; - assetInfo.ctor = js._getClassById(type) as Constructor; + assetInfo.ctor = js.getClassById(type) as Constructor; if (paths.has(path)) { if (isSubAsset) { paths.get(path)!.push(assetInfo); diff --git a/cocos/core/asset-manager/depend-util.ts b/cocos/core/asset-manager/depend-util.ts index 1b85636b00..4ffe422c2b 100644 --- a/cocos/core/asset-manager/depend-util.ts +++ b/cocos/core/asset-manager/depend-util.ts @@ -22,10 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset-manager - */ + import { BUILD, DEV, EDITOR } from 'internal:constants'; import { Asset } from '..'; import { hasNativeDep, isCompiledJson, parseUuidDependencies } from '../data/deserialize'; @@ -46,15 +43,15 @@ export interface IDependencies { /** * @en - * Control asset's dependency list, it is a singleton. All member can be accessed with `cc.assetManager.dependUtil` + * Control asset's dependency list, it is a singleton. All member can be accessed with `assetManager.dependUtil` * * @zh - * 控制资源的依赖列表,这是一个单例, 所有成员能通过 `cc.assetManager.dependUtil` 访问 + * 控制资源的依赖列表,这是一个单例, 所有成员能通过 `assetManager.dependUtil` 访问 * */ export class DependUtil { /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _depends: Cache = new Cache(); diff --git a/cocos/core/asset-manager/deprecated.ts b/cocos/core/asset-manager/deprecated.ts index 4f1d856b44..67ca877e0c 100644 --- a/cocos/core/asset-manager/deprecated.ts +++ b/cocos/core/asset-manager/deprecated.ts @@ -22,10 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module loader - */ + import { BUILD, DEBUG } from 'internal:constants'; import { Asset } from '../assets'; import { director } from '../director'; @@ -87,8 +84,8 @@ type LoadCompleteCallback = (error: Error | null, asset: T) => void; type LoadDirCompleteCallback = (error: Error | null, asset: T[], urls: string[]) => void; /** - * @en Loader for resource loading process. The engine automatically initialize its singleton object {{loader}}. - * @zh 资源加载管理器,引擎会自动创建一个单例对象 {{loader}}。 + * @en Loader for resource loading process. The engine automatically initialize its singleton object [[loader]]. + * @zh 资源加载管理器,引擎会自动创建一个单例对象 [[loader]]。 * * @class loader * @static @@ -97,8 +94,8 @@ type LoadDirCompleteCallback = (error: Error | null, asset: T[], urls: string export class CCLoader { /** * @en The default progression callback during the loading process, - * if no progression callback is passed to {{load}} function, then this default callback will be used. - * @zh Loader 默认的进度回调函数,如果在调用 {{load}} 函数时没有指定进度回调函数的话,会调用默认进度回调函数。 + * if no progression callback is passed to [[load]] function, then this default callback will be used. + * @zh Loader 默认的进度回调函数,如果在调用 [[load]] 函数时没有指定进度回调函数的话,会调用默认进度回调函数。 * * @deprecated since v3.0, loader.onProgress is deprecated, please transfer onProgress to API as a parameter */ @@ -107,13 +104,13 @@ export class CCLoader { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _autoReleaseSetting: Record = Object.create(null); private _parseLoadResArgs = parseLoadResArgs; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public get _cache (): Record { if (assets instanceof Cache) { @@ -138,15 +135,15 @@ export class CCLoader { * @example * ```TypeScript * loader.load('a.png', function (err, tex) { - * cc.log('Result should be a texture: ' + (tex instanceof cc.Texture2D)); + * log('Result should be a texture: ' + (tex instanceof Texture2D)); * }); * * loader.load('http://example.com/a.png', function (err, tex) { - * cc.log('Should load a texture from external url: ' + (tex instanceof cc.Texture2D)); + * log('Should load a texture from external url: ' + (tex instanceof Texture2D)); * }); * * loader.load({url: 'http://example.com/getImageREST?file=a.png', type: 'png'}, function (err, tex) { - * cc.log('Should load a texture from RESTful API by specify the type: ' + (tex instanceof cc.Texture2D)); + * log('Should load a texture from RESTful API by specify the type: ' + (tex instanceof Texture2D)); * }); * ``` * @@ -275,19 +272,19 @@ export class CCLoader { * // load the prefab (project/assets/resources/misc/character/cocos) from resources folder * loader.loadRes('misc/character/cocos', function (err, prefab) { * if (err) { - * cc.error(err.message || err); + * error(err.message || err); * return; * } - * cc.log('Result should be a prefab: ' + (prefab instanceof cc.Prefab)); + * log('Result should be a prefab: ' + (prefab instanceof Prefab)); * }); * * // load the sprite frame of (project/assets/resources/imgs/cocos.png) from resources folder - * loader.loadRes('imgs/cocos', cc.SpriteFrame, function (err, spriteFrame) { + * loader.loadRes('imgs/cocos', SpriteFrame, function (err, spriteFrame) { * if (err) { - * cc.error(err.message || err); + * error(err.message || err); * return; * } - * cc.log('Result should be a sprite frame: ' + (spriteFrame instanceof cc.SpriteFrame)); + * log('Result should be a sprite frame: ' + (spriteFrame instanceof SpriteFrame)); * }); * */ @@ -349,9 +346,9 @@ export class CCLoader { * // load the SpriteFrames from resources folder * let spriteFrames; * let urls = ['misc/characters/character_01', 'misc/weapons/weapons_01']; - * loader.loadResArray(urls, cc.SpriteFrame, function (err, assets) { + * loader.loadResArray(urls, SpriteFrame, function (err, assets) { * if (err) { - * cc.error(err); + * error(err); * return; * } * spriteFrames = assets; @@ -406,7 +403,7 @@ export class CCLoader { * // load the texture (resources/imgs/cocos.png) and the corresponding sprite frame * loader.loadResDir('imgs/cocos', function (err, assets) { * if (err) { - * cc.error(err); + * error(err); * return; * } * let texture = assets[0]; @@ -414,7 +411,7 @@ export class CCLoader { * }); * * // load all textures in "resources/imgs/" - * loader.loadResDir('imgs', cc.Texture2D, function (err, textures) { + * loader.loadResDir('imgs', Texture2D, function (err, textures) { * let texture1 = textures[0]; * let texture2 = textures[1]; * }); @@ -518,7 +515,7 @@ export class CCLoader { * let textures = []; * for (let i = 0; i < deps.length; ++i) { * let item = loader.getRes(deps[i]); - * if (item instanceof cc.Texture2D) { + * if (item instanceof Texture2D) { * textures.push(item); * } * } @@ -631,7 +628,7 @@ export class CCLoader { * Release the content of an asset or an array of assets by uuid.
* This method will not only remove the cache of the asset in loader, but also clean up its content.
* For example, if you release a texture, the texture asset and its gl texture data will be freed up.
- * In complexe project, you can use this function with [[getDependsRecursively]] to free up memory in critical circumstances.
+ * In complex project, you can use this function with [[getDependsRecursively]] to free up memory in critical circumstances.
* Notice, this method may cause the texture to be unusable, if there are still other nodes use the same texture, they may turn to black * and report gl errors.
* @zh @@ -676,8 +673,8 @@ export class CCLoader { } /** - * @en Release the asset by its object. Refer to {{release}} for detailed informations. - * @zh 通过资源对象自身来释放资源。详细信息请参考 {{release}} + * @en Release the asset by its object. Refer to [[release]] for detailed informations. + * @zh 通过资源对象自身来释放资源。详细信息请参考 [[release]] * @param asset The asset to be released * * @deprecated since v3.0 loader.releaseAsset is deprecated, please use assetManager.releaseAsset instead @@ -687,12 +684,12 @@ export class CCLoader { } /** - * @en Release the asset loaded by {{loadRes}}. Refer to {{release}} for detailed informations. - * @zh 释放通过 {{loadRes}} 加载的资源。详细信息请参考 {{release}} + * @en Release the asset loaded by [[loadRes]]. Refer to [[release]] for detailed informations. + * @zh 释放通过 [[loadRes]] 加载的资源。详细信息请参考 [[release]] * @param res The asset url, it should be related path without extension to the `resources` folder. * @param type If type is provided, the asset for correspond type will be returned * - * @deprecated since v3.0 loader.releaseRes is deprecated, please use cc.assetManager.releaseRes instead + * @deprecated since v3.0 loader.releaseRes is deprecated, please use assetManager.releaseRes instead */ public releaseRes (res: string, type?: Constructor) { resources.release(res, type); @@ -700,8 +697,8 @@ export class CCLoader { /** * - * @en Resource all assets. Refer to {{release}} for detailed informations. - * @zh 释放所有资源。详细信息请参考 {{release}} + * @en Resource all assets. Refer to [[release]] for detailed informations. + * @zh 释放所有资源。详细信息请参考 [[release]] * * @deprecated since v3.0 loader.releaseAll is deprecated, please use assetManager.releaseAll instead */ @@ -713,11 +710,11 @@ export class CCLoader { /** * @en Removes an completed item in pipeline. * It will only remove the cache in the pipeline or loader, its dependencies won't be released. - * cc.loader provided another method to completely cleanup the resource and its dependencies, - * please refer to {{Loader.release}} + * loader provided another method to completely cleanup the resource and its dependencies, + * please refer to [[release]] * @zh 移除指定的已完成 item。 * 这将仅仅从 pipeline 或者 loader 中删除其缓存,并不会释放它所依赖的资源。 - * cc.loader 中提供了另一种删除资源及其依赖的清理方法,请参考 {{Loader.release}} + * loader 中提供了另一种删除资源及其依赖的清理方法,请参考 [[release]] * @param id The id of the item * @return succeed or not * @@ -736,14 +733,14 @@ export class CCLoader { * will not be affected by that option, remain not released by default.
* Use this API to change the default behavior on a single asset, to force preserve or release specified asset when scene switching.
*
- * See: {{setAutoReleaseRecursively}}, {{isAutoRelease}} + * See: [[setAutoReleaseRecursively]], [[isAutoRelease]] * @zh * 设置当场景切换时是否自动释放资源。
* 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。
* 而使用 `loader.loadRes` 或 `loader.loadResDir` 动态加载的资源,则不受场景设置的影响,默认不自动释放。
* 使用这个 API 可以在单个资源上改变这个默认行为,强制在切换场景时保留或者释放指定资源。
*
- * 参考:{{setAutoReleaseRecursively}},{{isAutoRelease}} + * 参考:[[setAutoReleaseRecursively]],[[isAutoRelease]] * * @example * ```typescript @@ -774,14 +771,14 @@ export class CCLoader { * Use this API to change the default behavior on the specified asset and its recursively referenced assets, * to force preserve or release specified asset when scene switching.
*
- * See: {{setAutoRelease}}, {{isAutoRelease}} + * See: [[setAutoRelease]], [[isAutoRelease]] * @zh * 设置当场景切换时是否自动释放资源及资源引用的其它资源。
* 默认情况下,当加载新场景时,旧场景的资源根据旧场景是否勾选“Auto Release Assets”,将会被释放或者保留。
* 而使用 `loader.loadRes` 或 `loader.loadResDir` 动态加载的资源,则不受场景设置的影响,默认不自动释放。
* 使用这个 API 可以在指定资源及资源递归引用到的所有资源上改变这个默认行为,强制在切换场景时保留或者释放指定资源。
*
- * 参考:{{setAutoRelease}},{{isAutoRelease}} + * 参考:[[setAutoRelease]],[[isAutoRelease]] * * @example * ```typescript @@ -809,15 +806,15 @@ export class CCLoader { /** * @en Returns whether the asset is configured as auto released, despite how "Auto Release Assets" property is set on scene asset.
*
- * See: {{setAutoRelease}}, {{setAutoReleaseRecursively}} + * See: [[setAutoRelease]], [[setAutoReleaseRecursively]] * @zh 返回指定的资源是否有被设置为自动释放,不论场景的“Auto Release Assets”如何设置。
*
- * 参考:{{setAutoRelease}},{{setAutoReleaseRecursively}} + * 参考:[[setAutoRelease]],[[setAutoReleaseRecursively]] * * @method isAutoRelease * @param {Asset|String} asset - asset object or the raw asset's url * @returns {Boolean} - * @deprecated cc.loader.isAutoRelease is deprecated + * @deprecated loader.isAutoRelease is deprecated */ public isAutoRelease (asset: Asset|string): boolean { if (typeof asset === 'object') { asset = asset._uuid; } @@ -831,10 +828,10 @@ export class CCLoader { export const loader = new CCLoader(); /** - * /** + * @en + * Used to load/unload resources in the project + * @zh * 管理项目中加载/卸载资源的资源库。 - * @class AssetLibrary - * @static * * @deprecated since v3.0 AssetLibrary is deprecated, please backup your project and upgrade to assetManager */ @@ -882,7 +879,7 @@ export const AssetLibrary = { * @zh * 加载资源。 * @param {String} uuid - * @param {loadCallback} callback - 加载完成后执行的回调函数。 + * @param {loadCallback} callback - @en Callback function to be executed after loading asset. @zh 加载完成后执行的回调函数。 * @param {Object} options * @param {Boolean} options.readMainCache - 默认为true。如果为false,则资源及其所有依赖资源将重新加载并从库中创建新实例。 * @param {Boolean} options.writeMainCache - 默认为true。如果为true,则结果将缓存到 AssetLibrary,并且必须由用户手动卸载。 @@ -899,7 +896,7 @@ export const AssetLibrary = { * @class url * @static * - * @deprecated since v3.0 cc.url is deprecated + * @deprecated since v3.0 url is deprecated */ export const url = {}; @@ -931,7 +928,7 @@ replaceProperty(url, 'url', [ removeProperty(AssetLibrary, 'AssetLibrary', [ { name: 'getLibUrlNoExt', - suggest: 'AssetLibrary.getLibUrlNoExt was removed, if you want to transform url, please use cc.assetManager.utils.getUrlWithUuid instead', + suggest: 'AssetLibrary.getLibUrlNoExt was removed, if you want to transform url, please use assetManager.utils.getUrlWithUuid instead', }, { name: 'queryAssetInfo', @@ -950,7 +947,7 @@ removeProperty(loader, 'loader', [ }, { name: 'assetLoader', - suggest: 'cc.loader.assetLoader was removed, assetLoader and md5Pipe were merged into cc.assetManager.transformPipeline', + suggest: 'loader.assetLoader was removed, assetLoader and md5Pipe were merged into assetManager.transformPipeline', }, ]); @@ -982,7 +979,7 @@ replaceProperty(legacyCC, 'cc', [ removeProperty(legacyCC, 'cc', [{ name: 'LoadingItems', - suggest: getError(1400, 'cc.LoadingItems', 'cc.AssetManager.Task'), + suggest: getError(1400, 'LoadingItems', 'AssetManager.Task'), }]); replaceProperty(macro, 'macro', [ diff --git a/cocos/core/asset-manager/deserialize.ts b/cocos/core/asset-manager/deserialize.ts index e32357e441..3fdda8bd80 100644 --- a/cocos/core/asset-manager/deserialize.ts +++ b/cocos/core/asset-manager/deserialize.ts @@ -91,7 +91,7 @@ export default function deserializeAsset (json: Record, options: Re uuid: decodeUuid(dependUuid), owner: objList[i], prop: propList[i], - type: js._getClassById(typeList[i]) as Constructor, + type: js.getClassById(typeList[i]) as Constructor, }; } diff --git a/cocos/core/asset-manager/download-dom-image.ts b/cocos/core/asset-manager/download-dom-image.ts index 2041e2e2eb..81f69852c0 100644 --- a/cocos/core/asset-manager/download-dom-image.ts +++ b/cocos/core/asset-manager/download-dom-image.ts @@ -24,7 +24,6 @@ THE SOFTWARE. */ - import { getError } from '../platform/debug'; import { CompleteCallback, IDownloadParseOptions } from './shared'; diff --git a/cocos/core/asset-manager/download-script.ts b/cocos/core/asset-manager/download-script.ts index 428567fe0f..39e2c99257 100644 --- a/cocos/core/asset-manager/download-script.ts +++ b/cocos/core/asset-manager/download-script.ts @@ -32,7 +32,7 @@ export default function downloadScript ( url: string, options: IBundleOptions, onComplete: CompleteCallback, -): HTMLScriptElement | null{ +): HTMLScriptElement | null { // no need to load script again if (downloaded[url]) { if (onComplete) { onComplete(null); } diff --git a/cocos/core/asset-manager/downloader.ts b/cocos/core/asset-manager/downloader.ts index 6f5c3ff151..429f01a73e 100644 --- a/cocos/core/asset-manager/downloader.ts +++ b/cocos/core/asset-manager/downloader.ts @@ -22,15 +22,12 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset-manager - */ + import { BUILD, EDITOR } from 'internal:constants'; import { sys } from '../platform/sys'; -import { js, path } from '../utils'; +import { js } from '../utils/js'; import { callInNextTick } from '../utils/misc'; -import { basename } from '../utils/path'; +import { basename, mainFileName } from '../utils/path'; import Cache from './cache'; import downloadDomImage from './download-dom-image'; import downloadFile from './download-file'; @@ -83,7 +80,7 @@ const downloadCCON = (url: string, options: IDownloadParseOptions, onComplete: C } const cconPreface = parseCCONJson(json); const chunkPromises = Promise.all(cconPreface.chunks.map((chunk) => new Promise((resolve, reject) => { - downloadArrayBuffer(`${path.mainFileName(url)}${chunk}`, {}, (errChunk, chunkBuffer) => { + downloadArrayBuffer(`${mainFileName(url)}${chunk}`, {}, (errChunk, chunkBuffer) => { if (err) { reject(err); } else { @@ -156,7 +153,7 @@ const downloadBundle = (nameOrUrl: string, options: IBundleOptions, onComplete: /** * @en * Control all download process, it is a singleton. - * All member can be accessed with `cc.assetManager.downloader`, it can download several types of files: + * All member can be accessed with `assetManager.downloader`, it can download several types of files: * 1. Text * 2. Image * 3. Audio @@ -164,7 +161,7 @@ const downloadBundle = (nameOrUrl: string, options: IBundleOptions, onComplete: * 5. Scripts * * @zh - * 管理所有下载过程,downloader 是个单例,所有成员能通过 `cc.assetManager.downloader` 访问,它能下载以下几种类型的文件: + * 管理所有下载过程,downloader 是个单例,所有成员能通过 `assetManager.downloader` 访问,它能下载以下几种类型的文件: * 1. 文本 * 2. 图片 * 3. 音频 diff --git a/cocos/core/asset-manager/editor-path-replace.ts b/cocos/core/asset-manager/editor-path-replace.ts new file mode 100644 index 0000000000..c1049544ba --- /dev/null +++ b/cocos/core/asset-manager/editor-path-replace.ts @@ -0,0 +1,111 @@ +/* + Copyright (c) 2019-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 { EDITOR, NATIVE, PREVIEW, TEST } from 'internal:constants'; +import { assert } from '../platform/debug'; +import { Settings, settings } from '../settings'; +import { fetchPipeline, pipeline } from './shared'; +import Task, { TaskCompleteCallback } from './task'; + +declare const Editor: any; +if ((EDITOR || PREVIEW) && !TEST) { + const cache: {[uuid: string]: string | null} = {}; + const resolveMap: { [uuid: string]: Function[] } = {}; + const replaceExtension = (task: Task, done: TaskCompleteCallback) => { + task.output = task.input; + (async () => { + for (let i = 0; i < task.input.length; i++) { + const item = task.input[i]; + if (!item.uuid || item.isNative) { continue; } + try { + const extension = await queryExtension(item.uuid); + if (extension) { + item.ext = extension; + item.url = item.url.replace('.json', extension); + } + } catch (err) { + continue; + } + } + })().then(() => { + done(null, null); + }).catch((reason) => { + done(reason, null); + }); + }; + + const fetchText = (url) => new Promise((resolve, reject) => { + const xhr = new XMLHttpRequest(); + xhr.open('GET', url, true); + xhr.onload = () => { + if (xhr.status !== 200) { + reject(); + return; + } + resolve(xhr.response); + }; + xhr.send(null); + }); + + const queryExtension = async (uuid: string): Promise => { + if (uuid in cache) { + if (cache[uuid] !== null) { + return cache[uuid] as string; + } + return new Promise((resolve) => { + resolveMap[uuid] = resolveMap[uuid] || []; + resolveMap[uuid].push(resolve); + }); + } + cache[uuid] = null; + try { + let text = ''; + if (EDITOR) { + const info = await Editor.Message.request('asset-db', 'query-asset-info', uuid); + if (info && info.library['.cconb']) { + text = '.cconb'; + } + } else { + let previewServer = ''; + if (NATIVE) { + previewServer = settings.querySettings(Settings.Category.PATH, 'previewServer') || ''; + assert(previewServer); + } + text = await fetchText(`${previewServer}/query-extname/${uuid}`) as string; + } + cache[uuid] = text; + if (resolveMap[uuid]) { + resolveMap[uuid].forEach((func) => func(text)); + resolveMap[uuid] = []; + } + return text; + } catch (error) { + console.error(error); + cache[uuid] = ''; + return ''; + } + }; + pipeline.insert(replaceExtension, 1); + fetchPipeline.insert(replaceExtension, 1); +} diff --git a/cocos/core/asset-manager/factory.ts b/cocos/core/asset-manager/factory.ts index 2644c5b17b..7748dc3383 100644 --- a/cocos/core/asset-manager/factory.ts +++ b/cocos/core/asset-manager/factory.ts @@ -23,12 +23,10 @@ THE SOFTWARE. */ - - -import { VideoClip } from '../../video/assets/video-clip'; -import { - ImageAsset, JsonAsset, TextAsset, Asset, -} from '../assets'; +import { ImageAsset } from '../assets/image-asset'; +import JsonAsset from '../assets/json-asset'; +import TextAsset from '../assets/text-asset'; +import { Asset } from '../assets/asset'; import { BufferAsset } from '../assets/buffer-asset'; import { js } from '../utils/js'; import Bundle, { resources } from './bundle'; diff --git a/cocos/core/asset-manager/fetch.ts b/cocos/core/asset-manager/fetch.ts index ec0cab2383..07538cb55f 100644 --- a/cocos/core/asset-manager/fetch.ts +++ b/cocos/core/asset-manager/fetch.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { Asset } from '../assets'; import { error } from '../platform/debug'; import packManager from './pack-manager'; diff --git a/cocos/core/asset-manager/helper.ts b/cocos/core/asset-manager/helper.ts index 4c1ff9babe..895481b765 100644 --- a/cocos/core/asset-manager/helper.ts +++ b/cocos/core/asset-manager/helper.ts @@ -32,11 +32,6 @@ const _uuidRegex = /.*[/\\][0-9a-fA-F]{2}[/\\]([0-9a-fA-F-@]{8,}).*/; export { default as decodeUuid } from '../utils/decode-uuid'; -/** - * @packageDocumentation - * @module asset-manager - */ - /** * @en * Extract uuid from url @@ -104,7 +99,7 @@ export function getUrlWithUuid (uuid: string, options?: { [k: string]: any, isNa * * @method isScene * @param {*} asset - asset - * @returns {boolean} - whether or not type is cc.SceneAsset + * @returns {boolean} - whether or not type is SceneAsset * */ export function isScene (asset) { diff --git a/cocos/core/asset-manager/index.ts b/cocos/core/asset-manager/index.ts index cbf185b7b4..a1123ad615 100644 --- a/cocos/core/asset-manager/index.ts +++ b/cocos/core/asset-manager/index.ts @@ -24,8 +24,7 @@ THE SOFTWARE. */ - - +import './editor-path-replace'; export { default as assetManager, AssetManager } from './asset-manager'; export { resources } from './bundle'; export * from './deprecated'; diff --git a/cocos/core/asset-manager/load.ts b/cocos/core/asset-manager/load.ts index 5afedbaa17..6531473c12 100644 --- a/cocos/core/asset-manager/load.ts +++ b/cocos/core/asset-manager/load.ts @@ -23,7 +23,7 @@ THE SOFTWARE. */ import { BUILD, EDITOR, PREVIEW } from 'internal:constants'; -import { Asset, SceneAsset } from '../assets'; +import { Asset } from '../assets/asset'; import { error, warn } from '../platform/debug'; import packManager from './pack-manager'; import parser from './parser'; @@ -35,7 +35,6 @@ import { cache, checkCircleReference, clear, forEach, gatherAsset, getDepends, s import { legacyCC } from '../global-exports'; import { nativeDependMap, onLoadedInvokedMap } from './depend-maps'; - interface IProgress { finish: number; total: number; @@ -228,7 +227,7 @@ function loadDepends (task: Task, asset: Asset, done: CompleteCallbackNoData) { } else { // TODO: remove it. // scene asset might be a json in editor or preview - SceneAsset.prototype.initDefault.call(asset); + legacyCC.SceneAsset.prototype.initDefault.call(asset); } } } diff --git a/cocos/core/asset-manager/pack-manager.ts b/cocos/core/asset-manager/pack-manager.ts index 6bfc60b7a6..7e081f673b 100644 --- a/cocos/core/asset-manager/pack-manager.ts +++ b/cocos/core/asset-manager/pack-manager.ts @@ -22,12 +22,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset-manager - */ -import { ImageAsset, Texture2D } from '../assets'; +import { ImageAsset } from '../assets/image-asset'; +import { Texture2D } from '../assets/texture-2d'; import { packCustomObjData, unpackJSONs } from '../data/deserialize'; import { error, errorID } from '../platform/debug'; import { js } from '../utils/js'; @@ -46,10 +43,10 @@ interface IUnpackRequest { /** * @en - * Handle the packed asset, include unpacking, loading, cache and so on. It is a singleton. All member can be accessed with `cc.assetManager.packManager` + * Handle the packed asset, include unpacking, loading, cache and so on. It is a singleton. All member can be accessed with `assetManager.packManager` * * @zh - * 处理打包资源,包括拆包,加载,缓存等等,这是一个单例, 所有成员能通过 `cc.assetManager.packManager` 访问 + * 处理打包资源,包括拆包,加载,缓存等等,这是一个单例, 所有成员能通过 `assetManager.packManager` 访问 * */ export class PackManager { @@ -92,8 +89,8 @@ export class PackManager { out[`${pack[i]}@import`] = json[i]; } } else { - const textureType = js._getClassId(Texture2D); - const imageAssetType = js._getClassId(ImageAsset); + const textureType = js.getClassId(Texture2D); + const imageAssetType = js.getClassId(ImageAsset); if (json.type === textureType && json.data) { const datas = json.data; if (datas.length !== pack.length) { @@ -199,7 +196,7 @@ export class PackManager { * @param onComplete.data - The unpacked data retrieved from package * * @example - * var requestItem = cc.AssetManager.RequestItem.create(); + * var requestItem = AssetManager.RequestItem.create(); * requestItem.uuid = 'fcmR3XADNLgJ1ByKhqcC5Z'; * requestItem.info = config.getAssetInfo('fcmR3XADNLgJ1ByKhqcC5Z'); * packManager.load(requestItem, null, (err, data) => console.log(err)); diff --git a/cocos/core/asset-manager/parser.ts b/cocos/core/asset-manager/parser.ts index 76b2de9a31..c7cb7b513d 100644 --- a/cocos/core/asset-manager/parser.ts +++ b/cocos/core/asset-manager/parser.ts @@ -22,13 +22,10 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset-manager - */ + import { Asset } from '..'; import { IMemoryImageSource } from '../assets/image-asset'; -import { js } from '../utils'; +import { js } from '../utils/js'; import Cache from './cache'; import deserialize from './deserialize'; import { isScene } from './helper'; @@ -132,10 +129,10 @@ export type ParseHandler = (file: any, options: IDownloadParseOptions, onComplet /** * @en - * Parse the downloaded file, it's a singleton, all member can be accessed with `cc.assetManager.parser` + * Parse the downloaded file, it's a singleton, all member can be accessed with `assetManager.parser` * * @zh - * 解析已下载的文件,parser 是一个单例, 所有成员能通过 `cc.assetManaager.parser` 访问 + * 解析已下载的文件,parser 是一个单例, 所有成员能通过 `assetManaager.parser` 访问 * */ export class Parser { diff --git a/cocos/core/asset-manager/pipeline.ts b/cocos/core/asset-manager/pipeline.ts index 68a1540a09..246ca4bf46 100644 --- a/cocos/core/asset-manager/pipeline.ts +++ b/cocos/core/asset-manager/pipeline.ts @@ -22,10 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset-manager - */ + import { warnID } from '../platform/debug'; import { CompleteCallbackNoData } from './shared'; import Task from './task'; @@ -87,17 +84,17 @@ export class Pipeline { * the first is a `Task` flowed in pipeline, the second is complete callback * * @example - * var pipeline = new Pipeline('download', [ + * const pipeline = new Pipeline('download', [ * (task, done) => { - * var url = task.input; - * cc.assetManager.downloader.downloadFile(url, null, null, (err, result) => { + * const url = task.input; + * assetManager.downloader.downloadFile(url, null, null, (err, result) => { * task.output = result; * done(err); * }); * }, * (task, done) => { - * var text = task.input; - * var json = JSON.stringify(text); + * const text = task.input; + * const json = JSON.stringify(text); * task.output = json; * done(); * } diff --git a/cocos/core/asset-manager/plist-parser.ts b/cocos/core/asset-manager/plist-parser.ts index 40de3c6bf4..ef509d836a 100644 --- a/cocos/core/asset-manager/plist-parser.ts +++ b/cocos/core/asset-manager/plist-parser.ts @@ -25,8 +25,6 @@ THE SOFTWARE. */ - - import { EDITOR } from 'internal:constants'; import { warnID } from '../platform/debug'; diff --git a/cocos/core/asset-manager/preprocess.ts b/cocos/core/asset-manager/preprocess.ts index 6892a8c5cc..00d6434ad5 100644 --- a/cocos/core/asset-manager/preprocess.ts +++ b/cocos/core/asset-manager/preprocess.ts @@ -23,7 +23,6 @@ THE SOFTWARE. */ - import { CompleteCallbackNoData, RequestType, transformPipeline } from './shared'; import Task from './task'; diff --git a/cocos/core/asset-manager/release-manager.ts b/cocos/core/asset-manager/release-manager.ts index 3635cafb9e..e9a8338b5c 100644 --- a/cocos/core/asset-manager/release-manager.ts +++ b/cocos/core/asset-manager/release-manager.ts @@ -119,6 +119,11 @@ class ReleaseManager { private _persistNodeDeps = new Cache(); private _toDelete = new Cache(); private _eventListener = false; + private _dontDestroyAssets: string[] = []; + + public addIgnoredAsset (asset: Asset) { + this._dontDestroyAssets.push(asset._uuid); + } public init (): void { this._persistNodeDeps.clear(); @@ -126,7 +131,7 @@ class ReleaseManager { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _addPersistNodeRef (node: Node) { const deps = []; @@ -141,7 +146,7 @@ class ReleaseManager { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _removePersistNodeRef (node: Node) { if (!this._persistNodeDeps.has(node.uuid)) { return; } @@ -158,7 +163,7 @@ class ReleaseManager { // do auto release /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _autoRelease (oldScene: Scene, newScene: Scene, persistNodes: Record) { if (oldScene) { @@ -230,7 +235,7 @@ class ReleaseManager { const uuid = asset._uuid; this._toDelete.remove(uuid); - if (!isValid(asset, true)) { return; } + if (!isValid(asset, true) || this._dontDestroyAssets.indexOf(uuid) !== -1) { return; } if (!force) { if (asset.refCount > 0) { diff --git a/cocos/core/asset-manager/request-item.ts b/cocos/core/asset-manager/request-item.ts index cde88b645b..b6f4577531 100644 --- a/cocos/core/asset-manager/request-item.ts +++ b/cocos/core/asset-manager/request-item.ts @@ -22,10 +22,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset-manager - */ import Config, { IAssetInfo } from './config'; diff --git a/cocos/core/asset-manager/shared.ts b/cocos/core/asset-manager/shared.ts index ced278dddc..5d01627410 100644 --- a/cocos/core/asset-manager/shared.ts +++ b/cocos/core/asset-manager/shared.ts @@ -152,6 +152,15 @@ export const presets: Record> = { * */ export enum BuiltinBundleName { + /** + * @en + * The builtin bundle of default asset + * + * @zh + * 内置 bundle, 对应默认资源 + */ + INTERNAL = 'internal', + /** * @en * The builtin bundle corresponds to 'assets/resources'. diff --git a/cocos/core/asset-manager/task.ts b/cocos/core/asset-manager/task.ts index 13c89a3106..22207ab1a6 100644 --- a/cocos/core/asset-manager/task.ts +++ b/cocos/core/asset-manager/task.ts @@ -22,10 +22,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset-manager - */ + export type TaskCompleteCallback = (err: Error | null | undefined, data: any) => void; export type TaskProgressCallback = (...args: any[]) => void; export type TaskErrorCallback = (...args: any[]) => void; diff --git a/cocos/core/asset-manager/url-transformer.ts b/cocos/core/asset-manager/url-transformer.ts index b00edafd56..87cc0818d8 100644 --- a/cocos/core/asset-manager/url-transformer.ts +++ b/cocos/core/asset-manager/url-transformer.ts @@ -24,7 +24,8 @@ */ import { legacyCC } from '../global-exports'; -import { js, path } from '../utils'; +import { js } from '../utils/js'; +import * as path from '../utils/path'; import Config, { IAddressableInfo, IAssetInfo } from './config'; import { decodeUuid } from './helper'; import RequestItem from './request-item'; diff --git a/cocos/core/asset-manager/utilities.ts b/cocos/core/asset-manager/utilities.ts index 22eb2582a4..f6494fa575 100644 --- a/cocos/core/asset-manager/utilities.ts +++ b/cocos/core/asset-manager/utilities.ts @@ -24,7 +24,7 @@ */ import { EDITOR } from 'internal:constants'; -import { Asset, Prefab, SceneAsset } from '../assets'; +import { Asset } from '../assets/asset'; import { legacyCC } from '../global-exports'; import { error } from '../platform/debug'; import { js } from '../utils/js'; @@ -32,7 +32,6 @@ import { callInNextTick } from '../utils/misc'; import Config from './config'; import { dependMap, nativeDependMap } from './depend-maps'; import dependUtil from './depend-util'; -import { IDependProp } from './deserialize'; import { isScene } from './helper'; import RequestItem from './request-item'; import { assets, AssetType, CompleteCallbackNoData, CompleteCallback, IOptions, ProgressCallback, references } from './shared'; diff --git a/cocos/core/assets/asset-enum.ts b/cocos/core/assets/asset-enum.ts index 2a9eef991b..40a5e06952 100644 --- a/cocos/core/assets/asset-enum.ts +++ b/cocos/core/assets/asset-enum.ts @@ -23,15 +23,10 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { Address, Filter as GFXFilter, Format } from '../gfx'; // define a specified number for the pixel format which gfx do not have a standard definition. -let CUSTOM_PIXEL_FORMAT = 1024; +const CUSTOM_PIXEL_FORMAT = 1024; /** * @en @@ -131,7 +126,7 @@ export enum PixelFormat { * @zh 包含 RGBA 通道的 PVR 2BPP 压缩纹理格式 * 这种压缩纹理格式贴图的高度是普通 RGB_PVRTC_2BPPV1 贴图高度的两倍,使用上半部分作为原始 RGB 通道数据,下半部分用来存储透明通道数据。 */ - RGB_A_PVRTC_2BPPV1 = CUSTOM_PIXEL_FORMAT++, + RGB_A_PVRTC_2BPPV1 = CUSTOM_PIXEL_FORMAT, /** * @en A pixel format containing red, green, and blue channels that is PVR 4bpp compressed. * @zh 包含 RGB 通道的 PVR 4BPP 压缩纹理格式 @@ -147,9 +142,9 @@ export enum PixelFormat { * RGB_A_PVRTC_4BPPV1 texture is a 2x height RGB_PVRTC_4BPPV1 format texture. * It separate the origin alpha channel to the bottom half atlas, the origin rgb channel to the top half atlas. * @zh 包含 RGBA 通道的 PVR 4BPP 压缩纹理格式 - * 这种压缩纹理格式贴图的高度是普通 RGB_PVRTC_4BPPV1 贴图高度的两倍,使用上半部分作为原始 RGB 通道数据,下半部分用来存储透明通道数据。 + * 这种压缩纹理格式贴图的高度是普通 RGB_PVRTC_4BPPV1 贴图高度的两倍,使用上半部分作为原始 RGB 通道数据,下半部分用来存储透明通道数据。 */ - RGB_A_PVRTC_4BPPV1 = CUSTOM_PIXEL_FORMAT++, + RGB_A_PVRTC_4BPPV1 = CUSTOM_PIXEL_FORMAT + 1, /** * @en A pixel format containing red, green, and blue channels that is ETC1 compressed. * @zh 包含 RGB 通道的 ETC1 压缩纹理格式 @@ -159,7 +154,7 @@ export enum PixelFormat { * @en A pixel format containing red, green, blue, and alpha channels that is ETC1 compressed. * @zh 包含 RGBA 通道的 ETC1 压缩纹理格式 */ - RGBA_ETC1 = CUSTOM_PIXEL_FORMAT++, + RGBA_ETC1 = CUSTOM_PIXEL_FORMAT + 2, /** * @en A pixel format containing red, green, and blue channels that is ETC2 compressed. * @zh 包含 RGB 通道的 ETC2 压缩纹理格式 diff --git a/cocos/core/assets/asset.jsb.ts b/cocos/core/assets/asset.jsb.ts index 5787059fca..fdda2fd2ac 100644 --- a/cocos/core/assets/asset.jsb.ts +++ b/cocos/core/assets/asset.jsb.ts @@ -22,12 +22,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import { ccclass, editable, serializable } from 'cc.decorator'; -import { - _applyDecoratedDescriptor, - _assertThisInitialized, - _initializerDefineProperty, -} from '../data/utils/decorator-jsb-utils'; +import { ccclass, serializable } from 'cc.decorator'; + import { legacyCC } from '../global-exports'; import { CallbacksInvoker } from '../event/callbacks-invoker'; import { applyMixins } from '../event/event-target-factory'; @@ -124,40 +120,11 @@ assetProto.createNode = null!; export type Asset = jsb.Asset; export const Asset = jsb.Asset; -const clsDecorator = ccclass('cc.Asset'); - -const _class2$1 = Asset; -const _descriptor$1 = _applyDecoratedDescriptor(_class2$1.prototype, '_native', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return ''; - }, -}); - -//cjh FIXME: replace object.ts with object.jsb.ts -_applyDecoratedDescriptor(jsb.CCObject.prototype, '_name', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return ''; - }, -}); - -_applyDecoratedDescriptor(jsb.CCObject.prototype, '_objFlags', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return 0; - }, -}); -// - -_applyDecoratedDescriptor(_class2$1.prototype, '_nativeAsset', [property], Object.getOwnPropertyDescriptor(_class2$1.prototype, '_nativeAsset'), _class2$1.prototype); - -clsDecorator(Asset); - legacyCC.Asset = jsb.Asset; + +// handle meta data, it is generated automatically +const AssetProto = Asset.prototype; +serializable(AssetProto, '_native'); +const _nativeAssetDescriptor = Object.getOwnPropertyDescriptor(AssetProto, '_nativeAsset'); +property(AssetProto, '_nativeAsset', _nativeAssetDescriptor); +ccclass('cc.Asset')(Asset); diff --git a/cocos/core/assets/asset.ts b/cocos/core/assets/asset.ts index d1677a7b79..2b4bea6d24 100644 --- a/cocos/core/assets/asset.ts +++ b/cocos/core/assets/asset.ts @@ -24,21 +24,16 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { ccclass, serializable } from 'cc.decorator'; import { EDITOR, PREVIEW } from 'internal:constants'; import { property } from '../data/decorators/property'; import { getUrlWithUuid } from '../asset-manager/helper'; import { Eventify } from '../event'; -import { GCObject } from '../data/gc-object'; import { Node } from '../scene-graph'; import { legacyCC } from '../global-exports'; import { extname } from '../utils/path'; import { debug, getError, warn } from '../platform/debug'; +import { CCObject } from '../data/object'; /** * @en @@ -62,9 +57,10 @@ import { debug, getError, warn } from '../platform/debug'; * @extends CCObject */ @ccclass('cc.Asset') -export class Asset extends Eventify(GCObject) { +export class Asset extends Eventify(CCObject) { /** * 应 AssetDB 要求提供这个方法。 + * @internal * @method deserialize * @param {String} data * @return {Asset} @@ -85,10 +81,13 @@ export class Asset extends Eventify(GCObject) { public loaded = true; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public declare _uuid: string; + /** + * @internal + */ public declare isDefault: boolean; /** @@ -98,12 +97,12 @@ export class Asset extends Eventify(GCObject) { * 用于本机资产的可序列化URL。供内部使用。 * @default "" * - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @serializable public _native = ''; /** - * @legacyPublic + * @internal */ public _nativeUrl = ''; @@ -146,7 +145,7 @@ export class Asset extends Eventify(GCObject) { * 此资源的基础资源(如果有)。 此属性可用于访问与资源相关的其他详细信息或功能。
* 如果`_native`可用,则此属性将由加载器初始化。 * @default null - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @property get _nativeAsset () { @@ -157,7 +156,7 @@ export class Asset extends Eventify(GCObject) { this._file = obj; } - constructor (...args: ConstructorParameters) { + constructor (...args: ConstructorParameters) { super(...args); Object.defineProperty(this, '_uuid', { @@ -219,7 +218,7 @@ export class Asset extends Eventify(GCObject) { * * @param filename * @param inLibrary - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _setRawAsset (filename: string, inLibrary = true) { if (inLibrary !== false) { @@ -240,7 +239,7 @@ export class Asset extends Eventify(GCObject) { public createNode? (callback: CreateNodeCallback): void; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public get _nativeDep () { if (this._native) { diff --git a/cocos/core/assets/buffer-asset.jsb.ts b/cocos/core/assets/buffer-asset.jsb.ts index 24aa37b0f6..d9e82f8713 100644 --- a/cocos/core/assets/buffer-asset.jsb.ts +++ b/cocos/core/assets/buffer-asset.jsb.ts @@ -23,21 +23,16 @@ THE SOFTWARE. */ import { ccclass, override } from 'cc.decorator'; -import { - _applyDecoratedDescriptor, - _assertThisInitialized, - _initializerDefineProperty, -} from '../data/utils/decorator-jsb-utils'; import { legacyCC } from '../global-exports'; +import './asset'; export type BufferAsset = jsb.BufferAsset; export const BufferAsset = jsb.BufferAsset; -const clsDecorator = ccclass('cc.BufferAsset'); - -const _class2$D = BufferAsset; -//cjh FIXME: _applyDecoratedDescriptor(_class2$D.prototype, '_nativeAsset', [override], Object.getOwnPropertyDescriptor(_class2$D.prototype, '_nativeAsset'), _class2$D.prototype); - -clsDecorator(BufferAsset); - legacyCC.BufferAsset = jsb.BufferAsset; + +// handle meta data, it is generated automatically +const BufferAssetProto = BufferAsset.prototype; +const _nativeAssetDescriptor = Object.getOwnPropertyDescriptor(BufferAssetProto, '_nativeAsset'); +override(BufferAssetProto, '_nativeAsset', _nativeAssetDescriptor); +ccclass('cc.BufferAsset')(BufferAsset); diff --git a/cocos/core/assets/buffer-asset.ts b/cocos/core/assets/buffer-asset.ts index d04f4b5332..7d381d5096 100644 --- a/cocos/core/assets/buffer-asset.ts +++ b/cocos/core/assets/buffer-asset.ts @@ -23,12 +23,8 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { ccclass, override } from 'cc.decorator'; +import { assertIsNonNullable } from '../data/utils/asserts'; import { legacyCC } from '../global-exports'; import { Asset } from './asset'; @@ -37,7 +33,7 @@ export class BufferAsset extends Asset { private _buffer: ArrayBuffer | null = null; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @override get _nativeAsset () { @@ -51,7 +47,13 @@ export class BufferAsset extends Asset { } } + /** + * @zh 获取此资源中的缓冲数据。 + * @en Get the ArrayBuffer data of this asset. + * @returns @en The ArrayBuffer. @zh 缓冲数据。 + */ public buffer () { + assertIsNonNullable(this._buffer); return this._buffer; } diff --git a/cocos/core/assets/category.json b/cocos/core/assets/category.json new file mode 100644 index 0000000000..3e5b97ef04 --- /dev/null +++ b/cocos/core/assets/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "资源", + "en": "Asset" + }, + "description": { + "zh": "资源是游戏中的重要组成部分,Cocos Creator 支持导入不同类型的资源,并允许开发者将该资源运用在游戏中", + "en": "Assets are crucial for game content, Cocos Creator supports importing various types of assets and allows developers to use these resources in the game logic in runtime" + } +} \ No newline at end of file diff --git a/cocos/core/assets/deprecation.ts b/cocos/core/assets/deprecation.ts index da2bdc424a..c04b4a57e2 100644 --- a/cocos/core/assets/deprecation.ts +++ b/cocos/core/assets/deprecation.ts @@ -23,9 +23,7 @@ THE SOFTWARE. */ - - -import { removeProperty, replaceProperty } from '../utils'; +import { removeProperty, replaceProperty } from '../utils/x-deprecated'; import { TextureBase } from './texture-base'; import { RenderTexture } from './render-texture'; diff --git a/cocos/core/assets/effect-asset.jsb.ts b/cocos/core/assets/effect-asset.jsb.ts index 5ca6dc084a..0d392ffaf2 100644 --- a/cocos/core/assets/effect-asset.jsb.ts +++ b/cocos/core/assets/effect-asset.jsb.ts @@ -25,64 +25,28 @@ import { ccclass, editable, editorOnly, serializable } from 'cc.decorator'; import { legacyCC } from '../global-exports'; -import { - _applyDecoratedDescriptor, - _assertThisInitialized, - _initializerDefineProperty, -} from '../data/utils/decorator-jsb-utils'; +import './asset'; export type EffectAsset = jsb.EffectAsset; export const EffectAsset = jsb.EffectAsset; legacyCC.EffectAsset = EffectAsset; -const clsDecorator = ccclass('cc.EffectAsset'); - const effectAssetProto: any = EffectAsset.prototype; -const _descriptor_techniques = _applyDecoratedDescriptor(effectAssetProto, 'techniques', [serializable, editable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return []; - }, -}); - -const _descriptor_shaders = _applyDecoratedDescriptor(effectAssetProto, 'shaders', [serializable, editable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return []; - }, -}); - -const _descriptor_combinations = _applyDecoratedDescriptor(effectAssetProto, 'combinations', [serializable, editable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return []; - }, -}); - -const _descriptor_hideInEditor = _applyDecoratedDescriptor(effectAssetProto, 'hideInEditor', [serializable, editorOnly], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return false; - }, -}); - effectAssetProto._ctor = function () { jsb.Asset.prototype._ctor.apply(this, arguments); this.hideInEditor = false; - // _initializerDefineProperty(this, 'techniques', _descriptor_techniques, _assertThisInitialized(this)); - // _initializerDefineProperty(this, 'shaders', _descriptor_shaders, _assertThisInitialized(this)); - // _initializerDefineProperty(this, 'combinations', _descriptor_combinations, _assertThisInitialized(this)); - // _initializerDefineProperty(this, 'hideInEditor', _descriptor_hideInEditor, _assertThisInitialized(this)); }; -clsDecorator(EffectAsset); +// handle meta data, it is generated automatically +const EffectAssetProto = EffectAsset.prototype; +editable(EffectAssetProto, 'techniques'); +serializable(EffectAssetProto, 'techniques'); +editable(EffectAssetProto, 'shaders'); +serializable(EffectAssetProto, 'shaders'); +editable(EffectAssetProto, 'combinations'); +serializable(EffectAssetProto, 'combinations'); +editorOnly(EffectAssetProto, 'hideInEditor'); +serializable(EffectAssetProto, 'hideInEditor'); +ccclass('cc.EffectAsset')(EffectAsset); diff --git a/cocos/core/assets/effect-asset.ts b/cocos/core/assets/effect-asset.ts index b5a676769e..1f4438c0ce 100644 --- a/cocos/core/assets/effect-asset.ts +++ b/cocos/core/assets/effect-asset.ts @@ -23,16 +23,11 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module material - */ - import { ccclass, serializable, editable, editorOnly } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { Root } from '../root'; import { BlendState, DepthStencilState, RasterizerState, - DynamicStateFlags, PrimitiveMode, ShaderStageFlags, Type, Uniform, MemoryAccess, Format } from '../gfx'; + DynamicStateFlags, PrimitiveMode, ShaderStageFlags, Type, Uniform, MemoryAccess, Format, deviceManager } from '../gfx'; import { RenderPassStage } from '../pipeline/define'; import { MacroRecord } from '../renderer/core/pass-utils'; import { programLib } from '../renderer/core/program-lib'; @@ -180,7 +175,10 @@ export class EffectAsset extends Asset { * @en Register the effect asset to the static map * @zh 将指定 effect 注册到全局管理器。 */ - public static register (asset: EffectAsset) { EffectAsset._effects[asset.name] = asset; } + public static register (asset: EffectAsset) { + EffectAsset._effects[asset.name] = asset; + EffectAsset._layoutValid = false; + } /** * @en Unregister the effect asset from the static map @@ -188,7 +186,7 @@ export class EffectAsset extends Asset { */ public static remove (asset: EffectAsset | string) { if (typeof asset !== 'string') { - if (EffectAsset._effects[asset.name] && EffectAsset._effects[asset.name].equals(asset)) { + if (EffectAsset._effects[asset.name] && EffectAsset._effects[asset.name] === asset) { delete EffectAsset._effects[asset.name]; } } else { @@ -223,6 +221,10 @@ export class EffectAsset extends Asset { public static getAll () { return EffectAsset._effects; } protected static _effects: Record = {}; + public static isLayoutValid (): boolean { return EffectAsset._layoutValid; } + public static setLayoutValid (): void { EffectAsset._layoutValid = true; } + protected static _layoutValid = true; + /** * @en The techniques used by the current effect. * @zh 当前 effect 的所有可用 technique。 @@ -252,13 +254,13 @@ export class EffectAsset extends Asset { public hideInEditor = false; /** - * @en The loaded callback which should be invoked by the [[Loader]], will automatically register the effect. - * @zh 通过 [[Loader]] 加载完成时的回调,将自动注册 effect 资源。 + * @en The loaded callback which should be invoked by the [[CCLoader]], will automatically register the effect. + * @zh 通过 [[CCLoader]] 加载完成时的回调,将自动注册 effect 资源。 */ public onLoaded () { programLib.register(this); EffectAsset.register(this); - if (!EDITOR) { legacyCC.game.once(legacyCC.Game.EVENT_ENGINE_INITED, this._precompile, this); } + if (!EDITOR || legacyCC.GAME_VIEW) { legacyCC.game.once(legacyCC.Game.EVENT_RENDERER_INITED, this._precompile, this); } } protected _precompile () { @@ -277,7 +279,7 @@ export class EffectAsset extends Asset { return acc; }, [] as MacroRecord[]), [{}] as MacroRecord[]); defines.forEach( - (defines) => programLib.getGFXShader(root.device, shader.name, defines, root.pipeline), + (defines) => programLib.getGFXShader(deviceManager.gfxDevice, shader.name, defines, root.pipeline), ); } } @@ -289,8 +291,8 @@ export class EffectAsset extends Asset { public initDefault (uuid?: string) { super.initDefault(uuid); - const effect = EffectAsset.get('unlit'); - this.name = 'unlit'; + const effect = EffectAsset.get('builtin-unlit'); + this.name = 'builtin-unlit'; this.shaders = effect!.shaders; this.combinations = effect!.combinations; this.techniques = effect!.techniques; diff --git a/cocos/core/assets/image-asset.jsb.ts b/cocos/core/assets/image-asset.jsb.ts index d58c9129ed..91ef2b4d32 100644 --- a/cocos/core/assets/image-asset.jsb.ts +++ b/cocos/core/assets/image-asset.jsb.ts @@ -24,16 +24,13 @@ */ import { ccclass, override } from 'cc.decorator'; import { ALIPAY, XIAOMI, JSB, TEST, BAIDU } from 'internal:constants'; - -import { - _applyDecoratedDescriptor, - _assertThisInitialized, - _initializerDefineProperty, -} from '../data/utils/decorator-jsb-utils'; -import { Device, Feature, Format, FormatFeatureBit } from '../gfx'; +import { Format, FormatFeatureBit, deviceManager } from '../gfx'; import { legacyCC } from '../global-exports'; import { PixelFormat } from './asset-enum'; -import { warnID } from '../platform'; +import { sys } from '../platform/sys'; +import { macro } from '../platform/macro'; +import { warnID } from '../platform/debug'; +import './asset'; export type ImageAsset = jsb.ImageAsset; export const ImageAsset = jsb.ImageAsset; @@ -51,7 +48,7 @@ export type ImageSource = HTMLCanvasElement | HTMLImageElement | IMemoryImageSou const extnames = ['.png', '.jpg', '.jpeg', '.bmp', '.webp', '.pvr', '.pkm', '.astc']; function isImageBitmap (imageSource: any): boolean { - return !!(legacyCC.sys.capabilities.imageBitmap && imageSource instanceof ImageBitmap); + return !!(sys.hasFeature(sys.Feature.IMAGE_BITMAP) && imageSource instanceof ImageBitmap); } function isNativeImage (imageSource: ImageSource): imageSource is (HTMLImageElement | HTMLCanvasElement | ImageBitmap) { @@ -130,6 +127,18 @@ imageAssetProto.reset = function (data: ImageSource) { this._syncDataToNative(); }; +const superDestroy = jsb.Asset.prototype.destroy; +imageAssetProto.destroy = function () { + if(this.data && this.data instanceof HTMLImageElement) { + this.data.src = ''; + this._setRawAsset(''); + this.data.destroy(); + } else if (isImageBitmap(this.data)) { + this.data.close && this.data.close(); + } + return superDestroy.call(this); +}; + Object.defineProperty(imageAssetProto, 'width', { configurable: true, enumerable: true, @@ -153,7 +162,7 @@ imageAssetProto._syncDataToNative = function () { this.setWidth(this._width); this.setHeight(this._height); - this.setUrl(this.nativeUrl); + this.url = this.nativeUrl; if (data instanceof HTMLCanvasElement) { this.setData(data._data.data); @@ -200,14 +209,14 @@ imageAssetProto._deserialize = function (data: any) { this._height = data.h; fmtStr = data.fmt; } - const device = legacyCC.director.root.device; + const device = deviceManager.gfxDevice; const extensionIDs = fmtStr.split('_'); let preferedExtensionIndex = Number.MAX_VALUE; // let format = this._format; let format = this.format; let ext = ''; - const SupportTextureFormats = legacyCC.macro.SUPPORT_TEXTURE_FORMATS as string[]; + const SupportTextureFormats = macro.SUPPORT_TEXTURE_FORMATS as string[]; for (const extensionID of extensionIDs) { const extFormat = extensionID.split('@'); @@ -231,7 +240,7 @@ imageAssetProto._deserialize = function (data: any) { } else if ((fmt === PixelFormat.RGB_ETC2 || fmt === PixelFormat.RGBA_ETC2) && (!device || !(device.getFormatFeatures(Format.ETC2_RGB8) & FormatFeatureBit.SAMPLED_TEXTURE))) { continue; - } else if (tmpExt === '.webp' && !legacyCC.sys.capabilities.webp) { + } else if (tmpExt === '.webp' && !sys.hasFeature(sys.Feature.WEBP)) { continue; } preferedExtensionIndex = index; @@ -249,12 +258,10 @@ imageAssetProto._deserialize = function (data: any) { } }; -const clsDecorator = ccclass('cc.ImageAsset'); - -const _class2$a = ImageAsset; - -// cjh FIXME: _applyDecoratedDescriptor(_class2$a.prototype, '_nativeAsset', [override], Object.getOwnPropertyDescriptor(_class2$a.prototype, '_nativeAsset'), _class2$a.prototype); - -clsDecorator(ImageAsset); - legacyCC.ImageAsset = jsb.ImageAsset; + +// handle meta data, it is generated automatically +const ImageAssetProto = ImageAsset.prototype; +const _nativeAssetDescriptor = Object.getOwnPropertyDescriptor(ImageAssetProto, '_nativeAsset'); +override(ImageAssetProto, '_nativeAsset', _nativeAssetDescriptor); +ccclass('cc.ImageAsset')(ImageAsset); diff --git a/cocos/core/assets/image-asset.ts b/cocos/core/assets/image-asset.ts index 1c07dbee3f..43089417e3 100644 --- a/cocos/core/assets/image-asset.ts +++ b/cocos/core/assets/image-asset.ts @@ -23,19 +23,16 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - // @ts-check import { ccclass, override } from 'cc.decorator'; -import { EDITOR, MINIGAME, ALIPAY, XIAOMI, JSB, TEST, BAIDU } from 'internal:constants'; -import { Device, Feature, Format, FormatFeatureBit } from '../gfx'; +import { EDITOR, ALIPAY, XIAOMI, JSB, TEST, BAIDU } from 'internal:constants'; +import { Device, Format, FormatFeatureBit, deviceManager } from '../gfx'; import { Asset } from './asset'; import { PixelFormat } from './asset-enum'; import { legacyCC } from '../global-exports'; import { warnID } from '../platform/debug'; +import { macro } from '../platform/macro'; +import { sys } from '../platform/sys'; /** * @en Image source in memory @@ -56,7 +53,7 @@ export interface IMemoryImageSource { export type ImageSource = HTMLCanvasElement | HTMLImageElement | IMemoryImageSource | ImageBitmap; function isImageBitmap (imageSource: any): boolean { - return !!(legacyCC.sys.hasFeature(legacyCC.sys.Feature.IMAGE_BITMAP) && imageSource instanceof ImageBitmap); + return !!(sys.hasFeature(sys.Feature.IMAGE_BITMAP) && imageSource instanceof ImageBitmap); } function fetchImageSource (imageSource: ImageSource) { @@ -83,7 +80,7 @@ function isNativeImage (imageSource: ImageSource): imageSource is (HTMLImageElem @ccclass('cc.ImageAsset') export class ImageAsset extends Asset { /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @override get _nativeAsset () { @@ -218,7 +215,7 @@ export class ImageAsset extends Asset { // SERIALIZATION /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ // eslint-disable-next-line consistent-return public _serialize () { @@ -247,7 +244,7 @@ export class ImageAsset extends Asset { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _deserialize (data: any) { let fmtStr = ''; @@ -264,7 +261,7 @@ export class ImageAsset extends Asset { let preferedExtensionIndex = Number.MAX_VALUE; let format = this._format; let ext = ''; - const SupportTextureFormats = legacyCC.macro.SUPPORT_TEXTURE_FORMATS as string[]; + const SupportTextureFormats = macro.SUPPORT_TEXTURE_FORMATS; for (const extensionID of extensionIDs) { const extFormat = extensionID.split('@'); @@ -285,7 +282,7 @@ export class ImageAsset extends Asset { } else if ((fmt === PixelFormat.RGB_ETC2 || fmt === PixelFormat.RGBA_ETC2) && (!device || !(device.getFormatFeatures(Format.ETC2_RGB8) & FormatFeatureBit.SAMPLED_TEXTURE))) { continue; - } else if (tmpExt === '.webp' && !legacyCC.sys.hasFeature(legacyCC.sys.Feature.WEBP)) { + } else if (tmpExt === '.webp' && !sys.hasFeature(sys.Feature.WEBP)) { continue; } preferedExtensionIndex = index; @@ -325,10 +322,6 @@ export class ImageAsset extends Asset { } function _getGlobalDevice (): Device | null { - if (legacyCC.director.root) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return legacyCC.director.root.device; - } - return null; + return deviceManager.gfxDevice; } legacyCC.ImageAsset = ImageAsset; diff --git a/cocos/core/assets/index.jsb.ts b/cocos/core/assets/index.jsb.ts index 6d2cbf4c6f..5fdc8930b1 100644 --- a/cocos/core/assets/index.jsb.ts +++ b/cocos/core/assets/index.jsb.ts @@ -24,10 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @hidden - */ import './deprecation'; export { Asset } from './asset'; diff --git a/cocos/core/assets/index.ts b/cocos/core/assets/index.ts index 00f110f317..8ce78e1716 100644 --- a/cocos/core/assets/index.ts +++ b/cocos/core/assets/index.ts @@ -24,7 +24,6 @@ THE SOFTWARE. */ - import './deprecation'; export { Asset } from './asset'; @@ -39,5 +38,6 @@ export { ImageAsset } from './image-asset'; export { Texture2D } from './texture-2d'; export { TextureCube } from './texture-cube'; export { EffectAsset } from './effect-asset'; +export type { IMaterialInfo } from './material'; export { Material } from './material'; export { RenderTexture } from './render-texture'; diff --git a/cocos/core/assets/json-asset.ts b/cocos/core/assets/json-asset.ts index faab702c67..58615ddae7 100644 --- a/cocos/core/assets/json-asset.ts +++ b/cocos/core/assets/json-asset.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { ccclass, serializable, editable } from 'cc.decorator'; import { Asset } from './asset'; import { legacyCC } from '../global-exports'; diff --git a/cocos/core/assets/material.jsb.ts b/cocos/core/assets/material.jsb.ts index ac594665e0..6b69ce2161 100644 --- a/cocos/core/assets/material.jsb.ts +++ b/cocos/core/assets/material.jsb.ts @@ -23,10 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module material - */ import { EffectAsset } from './effect-asset'; import { Texture } from '../gfx'; import { TextureBase } from './texture-base'; @@ -34,9 +30,8 @@ import { legacyCC } from '../global-exports'; import { PassOverrides, MacroRecord, MaterialProperty } from '../renderer'; import { Color, Mat3, Mat4, Quat, Vec2, Vec3, Vec4 } from '../math'; -import { setClassName } from '../utils/js-typed'; -import { _applyDecoratedDescriptor, _assertThisInitialized, _initializerDefineProperty } from '../data/utils/decorator-jsb-utils'; import { ccclass, serializable, type } from '../data/decorators'; +import './asset'; /** * @en The basic infos for material initialization. @@ -87,13 +82,24 @@ const matProto: any = jsb.Material.prototype; type setProperyCB = (name: string, val: MaterialPropertyFull | MaterialPropertyFull[], passIdx?: number) => void; function wrapSetProperty (cb: setProperyCB, target: Material, name: string, val: MaterialPropertyFull | MaterialPropertyFull[], passIdx?: number) { - if (passIdx) { + if (passIdx != undefined) { cb.call(target, name, val, passIdx); } else { cb.call(target, name, val); } } - +// Note: The MathType should be synchronized with MathType in jsb_conversion_spec.cpp +enum MathType { + VEC2 = 0, + VEC3, + VEC4, + QUATERNION, + MAT3, + MAT4, + SIZE, + RECT, + COLOR, +}; matProto.setProperty = function (name: string, val: MaterialPropertyFull | MaterialPropertyFull[], passIdx?: number) { if (Array.isArray(val)) { const first = val[0]; @@ -148,37 +154,49 @@ matProto.setProperty = function (name: string, val: MaterialPropertyFull | Mater wrapSetProperty(this.setPropertyTextureBase, this, name, val, passIdx); } else if (val instanceof Texture) { wrapSetProperty(this.setPropertyGFXTexture, this, name, val, passIdx); - } else { + } else if (val === null) { + if (passIdx) { + this.setPropertyNull(name, passIdx); + } else { + this.setPropertyNull(name); + } + } + else { legacyCC.error(`Material.setProperty Unknown type: ${val}`); } }; matProto.getProperty = function (name: string, passIdx?: number) { - const val = this._getProperty(name, passIdx); + let val: any; + if (passIdx !== undefined) { + val = this._getProperty(name, passIdx); + } else { + val = this._getProperty(name); + } if (Array.isArray(val)) { const first = val[0]; const arr: any[] = []; // cjh TODO: optimize temporary gc objects being created - if (first instanceof Vec2) { + if (first instanceof jsb.Vec2 || first.type === MathType.VEC2) { // The type of first is uncertain, might be jsb.Color or plainObject. for (let i = 0, len = val.length; i < len; ++i) { const e = val[i]; arr.push(new Vec2(e.x, e.y)); } - } else if (first instanceof Vec3) { + } else if (first.type === MathType.VEC3) { for (let i = 0, len = val.length; i < len; ++i) { const e = val[i]; arr.push(new Vec3(e.x, e.y, e.z)); } - } else if (first instanceof Vec4) { + } else if (first.type === MathType.VEC4) { for (let i = 0, len = val.length; i < len; ++i) { const e = val[i]; arr.push(new Vec4(e.x, e.y, e.z, e.w)); } - } else if (first instanceof Color) { + } else if (first instanceof jsb.Color) { for (let i = 0, len = val.length; i < len; ++i) { const e = val[i]; arr.push(new Color(e.r, e.g, e.b, e.a)); } - } else if (first instanceof Mat3) { + } else if (first.type === MathType.MAT3) { for (let i = 0, len = val.length; i < len; ++i) { const e = val[i]; arr.push(new Mat3( @@ -187,7 +205,7 @@ matProto.getProperty = function (name: string, passIdx?: number) { e[6], e[7], e[8], )); } - } else if (first instanceof Mat4) { + } else if (first.type === MathType.MAT4) { for (let i = 0, len = val.length; i < len; ++i) { const e = val[i]; arr.push(new Mat4( @@ -197,7 +215,7 @@ matProto.getProperty = function (name: string, passIdx?: number) { e[12], e[13], e[14], e[15], )); } - } else if (first instanceof Quat) { + } else if (first.type === MathType.QUATERNION) { for (let i = 0, len = val.length; i < len; ++i) { const e = val[i]; arr.push(new Quat(e.x, e.y, e.z, e.w)); @@ -209,28 +227,28 @@ matProto.getProperty = function (name: string, passIdx?: number) { let ret; const e = val; - if (val instanceof Vec2) { + if (val instanceof jsb.Vec2 || val.type === MathType.VEC2) { ret = new Vec3(e.x, e.y); - } else if (val instanceof Vec3) { + } else if (val.type === MathType.VEC3) { ret = new Vec3(e.x, e.y, e.z); - } else if (val instanceof Vec4) { + } else if (val.type === MathType.VEC4) { ret = new Vec4(e.x, e.y, e.z, e.w); - } else if (val instanceof Color) { + } else if (val instanceof jsb.Color) { ret = new Color(e.r, e.g, e.b, e.a); - } else if (val instanceof Mat3) { + } else if (val.type === MathType.MAT3) { ret = new Mat3( e[0], e[1], e[2], e[3], e[4], e[5], e[6], e[7], e[8], ); - } else if (val instanceof Mat4) { + } else if (val.type === MathType.MAT4) { ret = new Mat4( e[0], e[1], e[2], e[3], e[4], e[5], e[6], e[7], e[8], e[9], e[10], e[11], e[12], e[13], e[14], e[15], ); - } else if (val instanceof Quat) { + } else if (val.type === MathType.QUATERNION) { ret = new Quat(e.x, e.y, e.z, e.w); } @@ -244,54 +262,6 @@ legacyCC.Material = Material; const materialProto: any = Material.prototype; -const clsDecorator = ccclass('cc.Material'); - -// Deserialization -const _class2$f = Material; -const _dec2$7 = type(EffectAsset); -const _descriptor$d = _applyDecoratedDescriptor(_class2$f.prototype, '_effectAsset', [_dec2$7], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return null; - }, -}); - -const _descriptor2$9 = _applyDecoratedDescriptor(_class2$f.prototype, '_techIdx', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return 0; - }, -}); - -const _descriptor3$7 = _applyDecoratedDescriptor(_class2$f.prototype, '_defines', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return []; - }, -}); -const _descriptor4$6 = _applyDecoratedDescriptor(_class2$f.prototype, '_states', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return []; - }, -}); -const _descriptor5$4 = _applyDecoratedDescriptor(_class2$f.prototype, '_props', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return []; - }, -}); - materialProto._ctor = function () { jsb.Asset.prototype._ctor.apply(this, arguments); this._props = []; @@ -331,4 +301,11 @@ Object.defineProperty(materialProto, 'passes', { }, }); -clsDecorator(Material); +// handle meta data, it is generated automatically +const MaterialProto = Material.prototype; +type(EffectAsset)(MaterialProto, '_effectAsset'); +serializable(MaterialProto, '_techIdx'); +serializable(MaterialProto, '_defines'); +serializable(MaterialProto, '_states'); +serializable(MaterialProto, '_props'); +ccclass('cc.Material')(Material); diff --git a/cocos/core/assets/material.ts b/cocos/core/assets/material.ts index 27ff5529c6..b13c33727f 100644 --- a/cocos/core/assets/material.ts +++ b/cocos/core/assets/material.ts @@ -23,15 +23,9 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module material - */ - import { ccclass, serializable, type } from 'cc.decorator'; import { Asset } from './asset'; import { EffectAsset } from './effect-asset'; -import { RenderableComponent } from '../components/renderable-component'; import { Texture, Type } from '../gfx'; import { TextureBase } from './texture-base'; import { legacyCC } from '../global-exports'; @@ -41,6 +35,7 @@ import { Color } from '../math/color'; import { warnID } from '../platform/debug'; import { Vec4 } from '../math'; import { SRGBToLinear } from '../pipeline/pipeline-funcs'; +import { Renderer } from '../components/renderer'; const v4_1 = new Vec4(); @@ -48,7 +43,7 @@ const v4_1 = new Vec4(); * @en The basic infos for material initialization. * @zh 用来初始化材质的基本信息。 */ -interface IMaterialInfo { +export interface IMaterialInfo { /** * @en The EffectAsset to use. Must provide if `effectName` is not specified. * @zh @@ -182,7 +177,7 @@ export class Material extends Asset { * @en The owner render component * @zh 该材质所归属的渲染组件 */ - get owner (): RenderableComponent | null { + get owner (): Renderer | null { return null; } @@ -246,8 +241,8 @@ export class Material extends Asset { } /** - * @en Callback function after material is loaded in [[Loader]]. Initialize the resources automatically. - * @zh 通过 [[Loader]] 加载完成时的回调,将自动初始化材质资源。 + * @en Callback function after material is loaded in [[CCLoader]]. Initialize the resources automatically. + * @zh 通过 [[CCLoader]] 加载完成时的回调,将自动初始化材质资源。 */ public onLoaded () { this._update(); @@ -271,10 +266,10 @@ export class Material extends Asset { /** * @en * Convenient property setter provided for quick material setup.
- * [[Pass.setUniform]] should be used instead if you need to do per-frame uniform update. + * [[renderer.Pass.setUniform]] should be used instead if you need to do per-frame uniform update. * @zh * 设置材质 uniform 参数的统一入口。
- * 注意如果需要每帧更新 uniform,建议使用 [[Pass.setUniform]] 以获得更好的性能。 + * 注意如果需要每帧更新 uniform,建议使用 [[renderer.Pass.setUniform]] 以获得更好的性能。 * @param name The target uniform name. * @param val The target value. * @param passIdx The pass to apply to. Will apply to all passes if not specified. @@ -308,11 +303,11 @@ export class Material extends Asset { * @en * Get the specified uniform value for this material.
* Note that only uniforms set through [[Material.setProperty]] can be acquired here.
- * For the complete rendering data, use [[Pass.getUniform]] instead. + * For the complete rendering data, use [[renderer.Pass.getUniform]] instead. * @zh * 获取当前材质的指定 uniform 参数的值。
* 注意只有通过 [[Material.setProperty]] 函数设置的参数才能从此函数取出,
- * 如需取出完整的渲染数据,请使用 [[Pass.getUniform]]。 + * 如需取出完整的渲染数据,请使用 [[renderer.Pass.getUniform]]。 * @param name The property or uniform name. * @param passIdx The target pass index. If not specified, return the first found value in all passes. */ @@ -484,8 +479,9 @@ export class Material extends Asset { public initDefault (uuid?: string) { super.initDefault(uuid); this.initialize({ - effectName: 'unlit', + effectName: 'builtin-unlit', defines: { USE_COLOR: true }, + technique: 0, }); this.setProperty('mainColor', new Color('#ff00ff')); } diff --git a/cocos/core/assets/prefab.jsb.ts b/cocos/core/assets/prefab.jsb.ts index 94581e27e9..826a249a9b 100644 --- a/cocos/core/assets/prefab.jsb.ts +++ b/cocos/core/assets/prefab.jsb.ts @@ -23,13 +23,9 @@ THE SOFTWARE. */ import { ccclass, editable, serializable } from 'cc.decorator'; -import { - _applyDecoratedDescriptor, - _assertThisInitialized, - _initializerDefineProperty, -} from '../data/utils/decorator-jsb-utils'; import { legacyCC } from '../global-exports'; import { Enum } from '../value-types'; +import './asset'; export const Prefab = jsb.Prefab; export type Prefab = jsb.Prefab; @@ -62,42 +58,22 @@ const OptimizationPolicy = Enum({ MULTI_INSTANCE: 2, }); -const clsDecorator = ccclass('cc.Prefab'); - const prefabProto: any = Prefab.prototype; -const _class2$B = Prefab; -const _descriptor$v = _applyDecoratedDescriptor(_class2$B.prototype, 'data', [serializable, editable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return null; - }, -}); -const _descriptor2$o = _applyDecoratedDescriptor(_class2$B.prototype, 'optimizationPolicy', [serializable, editable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return OptimizationPolicy.AUTO; - }, -}); -const _descriptor2$p = _applyDecoratedDescriptor(_class2$B.prototype, 'persistent', [serializable, editable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return false; - }, -}); - prefabProto._ctor = function () { jsb.Asset.prototype._ctor.apply(this, arguments); // _initializerDefineProperty(_this, 'data', _descriptor$v, _assertThisInitialized(_this)); // _initializerDefineProperty(_this, 'optimizationPolicy', _descriptor2$o, _assertThisInitialized(_this)); }; -clsDecorator(Prefab); - legacyCC.Prefab = Prefab; + +// handle meta data, it is generated automatically +const PrefabProto = Prefab.prototype; +editable(PrefabProto, 'data'); +serializable(PrefabProto, 'data'); +editable(PrefabProto, 'optimizationPolicy'); +serializable(PrefabProto, 'optimizationPolicy'); +editable(PrefabProto, 'persistent'); +serializable(PrefabProto, 'persistent'); +ccclass('cc.Prefab')(Prefab); diff --git a/cocos/core/assets/prefab.ts b/cocos/core/assets/prefab.ts index ca611c76b0..e837948b92 100644 --- a/cocos/core/assets/prefab.ts +++ b/cocos/core/assets/prefab.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { ccclass, serializable, editable } from 'cc.decorator'; import { SUPPORT_JIT, ALIPAY, RUNTIME_BASED } from 'internal:constants'; import { compile } from '../data/instantiate-jit'; diff --git a/cocos/core/assets/render-texture.jsb.ts b/cocos/core/assets/render-texture.jsb.ts index 7f3bc1c5c9..ab20235074 100644 --- a/cocos/core/assets/render-texture.jsb.ts +++ b/cocos/core/assets/render-texture.jsb.ts @@ -22,15 +22,11 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import { ccclass, rangeMax, rangeMin, serializable } from 'cc.decorator'; -import { - _applyDecoratedDescriptor, - _assertThisInitialized, - _initializerDefineProperty, -} from '../data/utils/decorator-jsb-utils'; +import { ccclass } from 'cc.decorator'; +import { EDITOR, TEST } from 'internal:constants'; import { legacyCC } from '../global-exports'; import { Filter, PixelFormat, WrapMode } from './asset-enum'; -import { EDITOR, TEST } from '../default-constants'; +import './asset'; declare const jsb: any; const renderTextureProto: any = jsb.RenderTexture.prototype; @@ -46,39 +42,6 @@ RenderTexture.Filter = Filter; RenderTexture.PixelFormat = PixelFormat; RenderTexture.WrapMode = WrapMode; -const clsDecorator = ccclass('cc.RenderTexture'); - -const _class2$j = RenderTexture; -const _dec2$b = rangeMin(1); -const _dec3$6 = rangeMax(1024); -const _dec4$5 = rangeMin(1); -const _dec5$2 = rangeMax(1024); - -const _descriptor$h = _applyDecoratedDescriptor(_class2$j.prototype, '_width', [serializable, _dec2$b, _dec3$6], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return 1; - }, -}); - -const _descriptor2$d = _applyDecoratedDescriptor(_class2$j.prototype, '_height', [serializable, _dec4$5, _dec5$2], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return 1; - }, -}); - -renderTextureProto._ctor = function () { - textureBaseProto._ctor.apply(this, arguments); - // for deserialization - // _initializerDefineProperty(_this, '_width', _descriptor$h, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, '_height', _descriptor2$d, _assertThisInitialized(_this)); -}; - renderTextureProto._serialize = function (ctxForExporting: any): any { if (EDITOR || TEST) { return { base: textureBaseProto._serialize(ctxForExporting), w: this._width, h: this._height, n: this._name }; @@ -100,7 +63,7 @@ renderTextureProto.readPixels = function readPixels (x: number, y: number, width x = x || 0; y = y || 0; width = width || this.width; - height = width || this.height; + height = height || this.height; let tmpBuffer = oldReadPixels.call(this, x, y, width, height); @@ -111,6 +74,7 @@ renderTextureProto.readPixels = function readPixels (x: number, y: number, width return buffer; }; -clsDecorator(RenderTexture); - legacyCC.RenderTexture = jsb.RenderTexture; + +// handle meta data, it is generated automatically +ccclass('cc.RenderTexture')(RenderTexture); diff --git a/cocos/core/assets/render-texture.ts b/cocos/core/assets/render-texture.ts index 061d7b68be..4f9a6ec4b9 100644 --- a/cocos/core/assets/render-texture.ts +++ b/cocos/core/assets/render-texture.ts @@ -23,15 +23,10 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { ccclass } from 'cc.decorator'; import { EDITOR, TEST } from 'internal:constants'; import { clamp } from '../math/utils'; -import { Texture, ColorAttachment, DepthStencilAttachment, GeneralBarrierInfo, AccessFlagBit, RenderPassInfo, Format } from '../gfx'; +import { Texture, ColorAttachment, DepthStencilAttachment, GeneralBarrierInfo, AccessFlagBit, RenderPassInfo, Format, deviceManager } from '../gfx'; import { legacyCC } from '../global-exports'; import { RenderWindow, IRenderWindowInfo } from '../renderer/core/render-window'; import { Root } from '../root'; @@ -75,6 +70,11 @@ export class RenderTexture extends TextureBase { return this._window; } + /** + * @en Initialize the render texture. Using IRenderTextureCreateInfo. + * @zh 初始化渲染贴图。设置渲染贴图的名称、尺寸、渲染通道信息。 + * @param info @en The create info of render texture @zh 渲染贴图的创建信息 + */ public initialize (info: IRenderTextureCreateInfo) { this._name = info.name || ''; this._width = info.width; @@ -82,10 +82,19 @@ export class RenderTexture extends TextureBase { this._initWindow(info); } + /** + * @en Reset the render texture. User may change the name, size or render pass info of the render texture. + * @zh 重新初始化渲染贴图。用户可以更改渲染贴图的名称、尺寸、渲染通道信息。 + * @param info @en The create info of render texture @zh 渲染贴图的创建信息 + */ public reset (info: IRenderTextureCreateInfo) { // to be consistent with other assets this.initialize(info); } + /** + * @en Destroy the render texture. + * @zh 销毁渲染贴图。 + */ public destroy () { if (this._window) { const root = legacyCC.director.root as Root; @@ -112,7 +121,7 @@ export class RenderTexture extends TextureBase { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _serialize (ctxForExporting: any): any { if (EDITOR || TEST) { @@ -122,7 +131,7 @@ export class RenderTexture extends TextureBase { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _deserialize (serializedData: any, handle: any) { const data = serializedData; @@ -134,17 +143,26 @@ export class RenderTexture extends TextureBase { // To be compatible with material property interface /** - * @en Gets the related [[Texture]] resource, it's also the color attachment for the render window + * @en Gets the related [[gfx.Texture]] resource, it's also the color attachment for the render window * @zh 获取渲染贴图的 GFX 资源,同时也是渲染窗口所指向的颜色缓冲贴图资源 */ public getGFXTexture (): Texture | null { return this._window && this._window.framebuffer.colorTextures[0]; } + /** + * @en Callback function after render texture is loaded in [[CCLoader]]. Initialize the render texture. + * @zh 通过 [[CCLoader]] 加载完成时的回调,初始化渲染贴图。 + */ public onLoaded () { this._initWindow(); } + /** + * @en Implementation of the render texture initialization. + * @zh 初始化渲染贴图的具体实现。 + * @param info @en The create info of render texture @zh 渲染贴图的创建信息 + */ protected _initWindow (info?: IRenderTextureCreateInfo) { const root = legacyCC.director.root as Root; @@ -153,41 +171,45 @@ export class RenderTexture extends TextureBase { _windowInfo.height = this._height; _windowInfo.renderPassInfo = info && info.passInfo ? info.passInfo : passInfo; - _colorAttachment.barrier = root.device.getGeneralBarrier(new GeneralBarrierInfo( + _colorAttachment.barrier = deviceManager.gfxDevice.getGeneralBarrier(new GeneralBarrierInfo( AccessFlagBit.FRAGMENT_SHADER_READ_TEXTURE, AccessFlagBit.FRAGMENT_SHADER_READ_TEXTURE, )); if (this._window) { this._window.destroy(); - this._window.initialize(root.device, _windowInfo); + this._window.initialize(deviceManager.gfxDevice, _windowInfo); } else { this._window = root.createWindow(_windowInfo); } } + /** + * @en Initialize the render texture with uuid. The default size is 1x1. + * @zh 初始化渲染贴图。使用uuid进行初始化,贴图的尺寸为 1x1。 + * @param uuid @en asset uuid @zh 资源 uuid + */ public initDefault (uuid?: string) { super.initDefault(uuid); this._width = this._height = 1; this._initWindow(); } + /** + * @en Validate the correctness of the render texture. + * @zh 验证渲染贴图的正确性。 + */ public validate () { return this.width >= 1 && this.width <= 2048 && this.height >= 1 && this.height <= 2048; } /** - * @en Read pixel buffer from render texture - * @param x The location on x axis - * @param y The location on y axis - * @param width The pixel width - * @param height The pixel height - * @zh 从 render texture 读取像素数据 - * @param x 起始位置X轴坐标 - * @param y 起始位置Y轴坐标 - * @param width 像素宽度 - * @param height 像素高度 - * @param buffer 像素缓存 + * @en Read pixel buffer from render texture @zh 从 render texture 读取像素数据 + * @param x @en The location on x axis @zh 起始位置X轴坐标 + * @param y @en The location on y axis @zh 起始位置Y轴坐标 + * @param width @en The pixel width @zh 像素宽度 + * @param height @en The pixel height @zh 像素高度 + * @param buffer @en The buffer to hold pixel data @zh 像素缓存 */ public readPixels (x = 0, y = 0, width?: number, height?: number, buffer?: Uint8Array) : Uint8Array | null { width = width || this.width; diff --git a/cocos/core/assets/rendering-sub-mesh.ts b/cocos/core/assets/rendering-sub-mesh.ts index c6ac8210e3..092a46f7f7 100644 --- a/cocos/core/assets/rendering-sub-mesh.ts +++ b/cocos/core/assets/rendering-sub-mesh.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { legacyCC } from '../global-exports'; import { mapBuffer } from '../../3d/misc/buffer'; import { @@ -84,12 +79,24 @@ export interface IFlatBuffer { } /** - * @en Sub mesh for rendering which contains all geometry data, it can be used to create [[InputAssembler]]. - * @zh 包含所有顶点数据的渲染子网格,可以用来创建 [[InputAssembler]]。 + * @en Sub mesh for rendering which contains all geometry data, it can be used to create [[gfx.InputAssembler]]. + * @zh 包含所有顶点数据的渲染子网格,可以用来创建 [[gfx.InputAssembler]]。 */ export class RenderingSubMesh { + /** + * @en + * mesh object where this sub mesh locates + * @zh + * 子网格所处的网格模型对象 + */ public mesh?: Mesh; + /** + * @en + * sub mesh's index in mesh + * @zh + * 子网格在网格模型中的索引 + */ public subMeshIdx?: number; private _flatBuffers: IFlatBuffer[] = []; @@ -114,11 +121,25 @@ export class RenderingSubMesh { private _iaInfo: InputAssemblerInfo; + private _isOwnerOfIndexBuffer = true; + private _drawInfo?: DrawInfo | null = null; + /** + * @en + * sub mesh's constructor + * @zh + * 子网格构造函数 + * @param vertexBuffers @en vertex buffers @zh 顶点缓冲区数组 + * @param attributes @en vertex attributes @zh 顶点属性数组 + * @param primitiveMode @en primitive mode @zh 图元类型 + * @param indexBuffer @en index buffer @zh 索引缓冲区 + * @param indirectBuffer @en indirect buffer @zh 间接缓冲区 + */ constructor ( vertexBuffers: Buffer[], attributes: Attribute[], primitiveMode: PrimitiveMode, indexBuffer: Buffer | null = null, indirectBuffer: Buffer | null = null, + isOwnerOfIndexBuffer = true, ) { this._attributes = attributes; this._vertexBuffers = vertexBuffers; @@ -126,6 +147,7 @@ export class RenderingSubMesh { this._indirectBuffer = indirectBuffer; this._primitiveMode = primitiveMode; this._iaInfo = new InputAssemblerInfo(attributes, vertexBuffers, indexBuffer, indirectBuffer); + this._isOwnerOfIndexBuffer = isOwnerOfIndexBuffer; } /** @@ -214,17 +236,13 @@ export class RenderingSubMesh { public invalidateGeometricInfo () { this._geometricInfo = undefined; } /** - * @en set the draw range - * @zh 设置渲染范围 + * @en the draw range + * @zh 渲染范围 */ set drawInfo (info: DrawInfo | null | undefined) { this._drawInfo = info; } - /** - * @en get the draw range - * @zh 获取渲染范围 - */ get drawInfo (): DrawInfo | null | undefined { return this._drawInfo; } @@ -235,6 +253,10 @@ export class RenderingSubMesh { */ get flatBuffers () { return this._flatBuffers; } + /** + * @en generate flatted vertex buffers + * @zh 生成扁平化的顶点缓冲区。 + */ public genFlatBuffers () { if (this._flatBuffers.length || !this.mesh || this.subMeshIdx === undefined) { return; } @@ -323,15 +345,25 @@ export class RenderingSubMesh { return buffers; } + /** + * @en The input assembler info + * @zh 输入汇集器信息 + */ get iaInfo () { return this._iaInfo; } + /** + * @en destroy sub mesh + * @zh 销毁子网格 + */ public destroy () { for (let i = 0; i < this.vertexBuffers.length; i++) { this.vertexBuffers[i].destroy(); } this.vertexBuffers.length = 0; if (this._indexBuffer) { - this._indexBuffer.destroy(); + if (this._isOwnerOfIndexBuffer) { + this._indexBuffer.destroy(); + } this._indexBuffer = null; } if (this._jointMappedBuffers && this._jointMappedBufferIndices) { @@ -352,7 +384,9 @@ export class RenderingSubMesh { * This is useful if you want to simulate `gl_VertexId` in WebGL context prior to 2.0. * Once you call this function, the vertex attribute is permanently added. * Subsequent calls to this function take no effect. - * @param device Device used to create related rendering resources. + * @zh 添加一个 'a_vertexId' 顶点属性, 用于在 WebGL 2.0 之前的平台模拟 `gl_VertexId`, + * 一旦你调用此函数, 顶点属性永久被添加, 后续调用无效果。 + * @param device @en Device used to create related rendering resources @zh 用于创建相关渲染资源的设备对象 */ public enableVertexIdChannel (device: Device) { if (this._vertexIdChannel) { diff --git a/cocos/core/assets/scene-asset.jsb.ts b/cocos/core/assets/scene-asset.jsb.ts index e9d850e651..1aa2431330 100644 --- a/cocos/core/assets/scene-asset.jsb.ts +++ b/cocos/core/assets/scene-asset.jsb.ts @@ -23,30 +23,16 @@ THE SOFTWARE. */ import { ccclass, editable, serializable } from 'cc.decorator'; -import { - _applyDecoratedDescriptor, - _assertThisInitialized, - _initializerDefineProperty, -} from '../data/utils/decorator-jsb-utils'; import { legacyCC } from '../global-exports'; +import './asset'; export const SceneAsset = jsb.SceneAsset; export type SceneAsset = jsb.SceneAsset; legacyCC.SceneAsset = SceneAsset; -const sceneAssetDecorator = ccclass('cc.SceneAsset'); const sceneAssetProto: any = SceneAsset.prototype; -const des_scene = _applyDecoratedDescriptor(sceneAssetProto, 'scene', [editable, serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return null; - }, -}); - Object.defineProperty(sceneAssetProto, 'scene', { enumerable: true, configurable: true, @@ -64,8 +50,11 @@ Object.defineProperty(sceneAssetProto, 'scene', { sceneAssetProto._ctor = function () { jsb.Asset.prototype._ctor.apply(this, arguments); - // _initializerDefineProperty(this, "scene", des_scene, _assertThisInitialized(this)); this._scene = null; }; -sceneAssetDecorator(SceneAsset); +// handle meta data, it is generated automatically +const SceneAssetProto = SceneAsset.prototype; +serializable(SceneAssetProto, 'scene'); +editable(SceneAssetProto, 'scene'); +ccclass('cc.SceneAsset')(SceneAsset); diff --git a/cocos/core/assets/scene-asset.ts b/cocos/core/assets/scene-asset.ts index be36a69cea..e806a03b96 100644 --- a/cocos/core/assets/scene-asset.ts +++ b/cocos/core/assets/scene-asset.ts @@ -24,13 +24,8 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { ccclass, editable, serializable } from 'cc.decorator'; -import { Scene } from '../scene-graph'; +import { Scene } from '../scene-graph/scene'; import { Asset } from './asset'; import { legacyCC } from '../global-exports'; diff --git a/cocos/core/assets/scripts.ts b/cocos/core/assets/scripts.ts index 3eb8fc5064..efda5018fe 100644 --- a/cocos/core/assets/scripts.ts +++ b/cocos/core/assets/scripts.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { ccclass } from 'cc.decorator'; import { Asset } from './asset'; import { legacyCC } from '../global-exports'; diff --git a/cocos/core/assets/simple-texture.jsb.ts b/cocos/core/assets/simple-texture.jsb.ts index b41bcb88ee..4ea85d9afa 100644 --- a/cocos/core/assets/simple-texture.jsb.ts +++ b/cocos/core/assets/simple-texture.jsb.ts @@ -25,9 +25,10 @@ import { ccclass } from 'cc.decorator'; import { legacyCC } from '../global-exports'; import { Filter, PixelFormat, WrapMode } from './asset-enum'; -import { macro } from '../platform'; +import { macro } from '../platform/macro'; import dependUtil from '../asset-manager/depend-util'; import { fastRemoveAt } from '../utils/array'; +import './texture-base'; declare const jsb: any; diff --git a/cocos/core/assets/simple-texture.ts b/cocos/core/assets/simple-texture.ts index bc6d09238c..a9fc32a68d 100644 --- a/cocos/core/assets/simple-texture.ts +++ b/cocos/core/assets/simple-texture.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { ccclass } from 'cc.decorator'; import { DEV } from 'internal:constants'; import { TextureFlagBit, TextureUsageBit, API, Texture, TextureInfo, TextureViewInfo, Device, BufferTextureCopy } from '../gfx'; @@ -76,7 +71,7 @@ export class SimpleTexture extends TextureBase { private _textureHeight = 0; protected _baseLevel = 0; - protected _maxLevel = 0; + protected _maxLevel = 1000; /** * @en The mipmap level of the texture @@ -196,8 +191,11 @@ export class SimpleTexture extends TextureBase { } /** + * @en * Set mipmap level of this texture. * The value is passes as presumed info to `this._getGfxTextureCreateInfo()`. + * @zh + * 设置此贴图的 mipmap 层级 * @param value The mipmap level. */ protected _setMipmapLevel (value: number) { @@ -205,15 +203,13 @@ export class SimpleTexture extends TextureBase { } protected _setMipRange (baseLevel: number, maxLevel: number) { - this._baseLevel = baseLevel < 0 ? 0 : baseLevel; - this._baseLevel = this._baseLevel < this._mipmapLevel ? this._baseLevel : this._mipmapLevel - 1; - - this._maxLevel = maxLevel < this._baseLevel ? this._baseLevel : maxLevel; - this._maxLevel = this._maxLevel < this._mipmapLevel ? this._maxLevel : this._mipmapLevel - 1; + this._baseLevel = baseLevel < 1 ? 0 : baseLevel; + this._maxLevel = maxLevel < 1 ? 0 : maxLevel; } /** - * Set mipmap level range for this texture. + * @en Set mipmap level range for this texture. + * @zh 设置当前贴图的 mipmap 范围。 * @param baseLevel The base mipmap level. * @param maxLevel The maximum mipmap level. */ @@ -226,12 +222,15 @@ export class SimpleTexture extends TextureBase { if (!device) { return; } + // create a new texture view before the destruction of the previous one to bypass the bug that + // vulkan destroys textureview in use. This is a temporary solution, should be fixed later. + const textureView = this._createTextureView(device); this._tryDestroyTextureView(); - this._createTextureView(device); + this._gfxTextureView = textureView; } /** - * @en This method is overrided by derived classes to provide GFX texture info. + * @en This method is override by derived classes to provide GFX texture info. * @zh 这个方法被派生类重写以提供 GFX 纹理信息。 * @param presumed The presumed GFX texture info. */ @@ -259,7 +258,15 @@ export class SimpleTexture extends TextureBase { return; } this._createTexture(device); - this._createTextureView(device); + this._gfxTextureView = this._createTextureView(device); + } + + /** + * @en Whether mipmaps are baked convolutional maps. + * @zh mipmaps是否为烘焙出来的卷积图。 + */ + public isUsingOfflineMipmaps (): boolean { + return false; } protected _createTexture (device: Device) { @@ -267,9 +274,10 @@ export class SimpleTexture extends TextureBase { let flags = TextureFlagBit.NONE; if (this._mipFilter !== Filter.NONE && canGenerateMipmap(device, this._width, this._height)) { this._mipmapLevel = getMipLevel(this._width, this._height); - flags = TextureFlagBit.GEN_MIPMAP; + if (!this.isUsingOfflineMipmaps()) { + flags = TextureFlagBit.GEN_MIPMAP; + } } - const textureCreateInfo = this._getGfxTextureCreateInfo({ usage: TextureUsageBit.SAMPLED | TextureUsageBit.TRANSFER_DST, format: this._getGFXFormat(), @@ -287,22 +295,22 @@ export class SimpleTexture extends TextureBase { this._gfxTexture = texture; } - protected _createTextureView (device: Device) { + protected _createTextureView (device: Device): Texture | null { if (!this._gfxTexture) { - return; + return null; } + const maxLevel = this._maxLevel < this._mipmapLevel ? this._maxLevel : this._mipmapLevel - 1; const textureViewCreateInfo = this._getGfxTextureViewCreateInfo({ texture: this._gfxTexture, format: this._getGFXFormat(), baseLevel: this._baseLevel, - levelCount: this._maxLevel - this._baseLevel + 1, + levelCount: maxLevel - this._baseLevel + 1, }); if (!textureViewCreateInfo) { - return; + return null; } - const textureView = device.createTexture(textureViewCreateInfo); - this._gfxTextureView = textureView; + return device.createTexture(textureViewCreateInfo); } protected _tryDestroyTexture () { diff --git a/cocos/core/assets/text-asset.jsb.ts b/cocos/core/assets/text-asset.jsb.ts index b708148beb..57f47298d6 100644 --- a/cocos/core/assets/text-asset.jsb.ts +++ b/cocos/core/assets/text-asset.jsb.ts @@ -22,13 +22,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import { ccclass, editable, serializable, type } from 'cc.decorator'; -import { - _applyDecoratedDescriptor, - _assertThisInitialized, - _initializerDefineProperty, -} from '../data/utils/decorator-jsb-utils'; +import { ccclass, editable, serializable } from 'cc.decorator'; import { legacyCC } from '../global-exports'; +import './asset'; const textAssetProto: any = jsb.TextAsset.prototype; @@ -37,23 +33,14 @@ textAssetProto.createNode = null!; export type TextAsset = jsb.TextAsset; export const TextAsset = jsb.TextAsset; -const clsDecorator = ccclass('cc.TextAsset'); - -const _class2$F = TextAsset; -const _descriptor$y = _applyDecoratedDescriptor(_class2$F.prototype, 'text', [serializable, editable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return ''; - }, -}); - textAssetProto._ctor = function () { jsb.Asset.prototype._ctor.apply(this, arguments); - // _initializerDefineProperty(_this, 'text', _descriptor$y, _assertThisInitialized(_this)); }; -clsDecorator(TextAsset); - legacyCC.TextAsset = jsb.TextAsset; + +// handle meta data, it is generated automatically +const TextAssetProto = TextAsset.prototype; +editable(TextAssetProto, 'text'); +serializable(TextAssetProto, 'text'); +ccclass('cc.TextAsset')(TextAsset); diff --git a/cocos/core/assets/text-asset.ts b/cocos/core/assets/text-asset.ts index 3e33cc2673..9714fd1a96 100644 --- a/cocos/core/assets/text-asset.ts +++ b/cocos/core/assets/text-asset.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { ccclass, serializable, editable } from 'cc.decorator'; import { Asset } from './asset'; import { legacyCC } from '../global-exports'; diff --git a/cocos/core/assets/texture-2d.jsb.ts b/cocos/core/assets/texture-2d.jsb.ts index 862c66431b..bf70a4a475 100644 --- a/cocos/core/assets/texture-2d.jsb.ts +++ b/cocos/core/assets/texture-2d.jsb.ts @@ -23,17 +23,13 @@ THE SOFTWARE. */ import { ccclass, type } from 'cc.decorator'; -import { - _applyDecoratedDescriptor, - _assertThisInitialized, - _initializerDefineProperty, -} from '../data/utils/decorator-jsb-utils'; import { legacyCC } from '../global-exports'; import { ImageAsset } from './image-asset'; import { SimpleTexture } from './simple-texture'; import { TextureBase } from './texture-base.jsb'; import { js } from '../utils/js'; import { Filter, PixelFormat, WrapMode } from './asset-enum'; +import './simple-texture'; const texture2DProto: any = jsb.Texture2D.prototype; @@ -51,30 +47,11 @@ export interface ITexture2DSerializeData { mipmaps: string[]; } -const clsDecorator = ccclass('cc.Texture2D'); - -const _class2$c = Texture2D; -const _dec2$6 = type([ImageAsset]); // xwx: jsb.ImageAsset? - -const _descriptor$a = _applyDecoratedDescriptor(_class2$c.prototype, '_mipmaps', [_dec2$6], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return []; - }, -}); - texture2DProto._ctor = function () { SimpleTexture.prototype._ctor.apply(this, arguments); this._mipmaps = []; - // for deserialization - // _initializerDefineProperty(_this, 'isRGBE', _descriptor$b, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, '_mipmaps', _descriptor2$7, _assertThisInitialized(_this)); }; -clsDecorator(Texture2D); - texture2DProto._serialize = function (ctxForExporting: any) { if (EDITOR || TEST) { return { @@ -107,7 +84,7 @@ texture2DProto._deserialize = function (serializedData: any, handle: any) { continue; } const mipmapUUID = data.mipmaps[i]; - handle.result.push(this._mipmaps, `${i}`, mipmapUUID, js._getClassId(ImageAsset)); + handle.result.push(this._mipmaps, `${i}`, mipmapUUID, js.getClassId(ImageAsset)); } }; @@ -144,3 +121,8 @@ Object.defineProperty(texture2DProto, 'mipmaps', { }); legacyCC.Texture2D = jsb.Texture2D; + +// handle meta data, it is generated automatically +const Texture2DProto = Texture2D.prototype; +type([ImageAsset])(Texture2DProto, '_mipmaps'); +ccclass('cc.Texture2D')(Texture2D); diff --git a/cocos/core/assets/texture-2d.ts b/cocos/core/assets/texture-2d.ts index 70301eaf2e..d73190a57d 100644 --- a/cocos/core/assets/texture-2d.ts +++ b/cocos/core/assets/texture-2d.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { EDITOR, TEST } from 'internal:constants'; import { ccclass, type } from 'cc.decorator'; import { TextureType, TextureInfo, TextureViewInfo } from '../gfx'; @@ -79,7 +74,7 @@ export interface ITexture2DCreateInfo { /** * @en The selected maximum mipmap level * @zh 选择使用的最大 mipmap 层级。 - * @default 1 + * @default 1000 */ maxLevel?: number; } @@ -143,7 +138,7 @@ export class Texture2D extends SimpleTexture { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @type([ImageAsset]) public _mipmaps: ImageAsset[] = []; @@ -169,8 +164,8 @@ export class Texture2D extends SimpleTexture { this._setGFXFormat(info.format); const mipLevels = info.mipmapLevel === undefined ? 1 : info.mipmapLevel; this._setMipmapLevel(mipLevels); - const minLod = info.baseLevel || 0; - const maxLod = info.maxLevel === undefined ? (mipLevels - 1) : info.maxLevel; + const minLod = info.baseLevel === undefined ? 0 : info.baseLevel; + const maxLod = info.maxLevel === undefined ? 1000 : info.maxLevel; this._setMipRange(minLod, maxLod); this._tryReset(); } @@ -188,7 +183,7 @@ export class Texture2D extends SimpleTexture { * @param maxLevel Mipmap maximum level * @deprecated since v1.0 please use [[reset]] instead */ - public create (width: number, height: number, format = PixelFormat.RGBA8888, mipmapLevel = 1, baseLevel = 0, maxLevel = 0) { + public create (width: number, height: number, format = PixelFormat.RGBA8888, mipmapLevel = 1, baseLevel = 0, maxLevel = 1000) { this.reset({ width, height, @@ -223,7 +218,7 @@ export class Texture2D extends SimpleTexture { * @en If the level 0 mipmap image is a HTML element, then return it, otherwise return null. * @zh 若此贴图 0 级 Mipmap 的图像资源的实际源存在并为 HTML 元素则返回它,否则返回 `null`。 * @returns HTML element or `null` - * @deprecated Please use [[image.data]] instead + * @deprecated Please use [[ImageAsset.data]] instead */ public getHtmlElementObj () { return (this._mipmaps[0] && (this._mipmaps[0].data instanceof HTMLElement)) ? this._mipmaps[0].data : null; @@ -258,7 +253,7 @@ export class Texture2D extends SimpleTexture { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _serialize (ctxForExporting: any) { if (EDITOR || TEST) { @@ -280,7 +275,7 @@ export class Texture2D extends SimpleTexture { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _deserialize (serializedData: any, handle: any) { const data = serializedData as ITexture2DSerializeData; @@ -294,7 +289,7 @@ export class Texture2D extends SimpleTexture { continue; } const mipmapUUID = data.mipmaps[i]; - handle.result.push(this._mipmaps, `${i}`, mipmapUUID, js._getClassId(ImageAsset)); + handle.result.push(this._mipmaps, `${i}`, mipmapUUID, js.getClassId(ImageAsset)); } } diff --git a/cocos/core/assets/texture-base.jsb.ts b/cocos/core/assets/texture-base.jsb.ts index 77472c6ba8..cbc850a136 100644 --- a/cocos/core/assets/texture-base.jsb.ts +++ b/cocos/core/assets/texture-base.jsb.ts @@ -23,13 +23,10 @@ THE SOFTWARE. */ import { ccclass, serializable } from 'cc.decorator'; -import { - _applyDecoratedDescriptor, - _assertThisInitialized, - _initializerDefineProperty, -} from '../data/utils/decorator-jsb-utils'; +import { deviceManager } from '../gfx'; import { legacyCC } from '../global-exports'; import { Filter, PixelFormat, WrapMode } from './asset-enum'; +import './asset'; const textureBaseProto: any = jsb.TextureBase.prototype; @@ -57,10 +54,7 @@ textureBaseProto._deserialize = function (serializedData: any, handle: any) { }; textureBaseProto._getGFXDevice = function () { - if (legacyCC.director.root) { - return legacyCC.director.root.device; - } - return null; + return deviceManager.gfxDevice; }; textureBaseProto._getGFXFormat = function () { @@ -91,73 +85,6 @@ TextureBase.Filter = Filter; TextureBase.PixelFormat = PixelFormat; TextureBase.WrapMode = WrapMode; -const clsDecorator = ccclass('cc.TextureBase'); - -const _class2$b = TextureBase; -const _descriptor$9 = _applyDecoratedDescriptor(_class2$b.prototype, '_format', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return PixelFormat.RGBA8888; - }, -}); -const _descriptor2$6 = _applyDecoratedDescriptor(_class2$b.prototype, '_minFilter', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return Filter.LINEAR; - }, -}); -const _descriptor3$5 = _applyDecoratedDescriptor(_class2$b.prototype, '_magFilter', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return Filter.LINEAR; - }, -}); -const _descriptor4$4 = _applyDecoratedDescriptor(_class2$b.prototype, '_mipFilter', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return Filter.NONE; - }, -}); -const _descriptor5$3 = _applyDecoratedDescriptor(_class2$b.prototype, '_wrapS', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return WrapMode.REPEAT; - }, -}); -const _descriptor6$1 = _applyDecoratedDescriptor(_class2$b.prototype, '_wrapT', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return WrapMode.REPEAT; - }, -}); -const _descriptor7$1 = _applyDecoratedDescriptor(_class2$b.prototype, '_wrapR', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return WrapMode.REPEAT; - }, -}); -const _descriptor8$1 = _applyDecoratedDescriptor(_class2$b.prototype, '_anisotropy', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return 0; - }, -}); textureBaseProto._ctor = function () { jsb.Asset.prototype._ctor.apply(this, arguments); this._gfxSampler = null; @@ -165,15 +92,6 @@ textureBaseProto._ctor = function () { this._textureHash = 0; this._registerGFXSamplerUpdatedListener(); - // for deserialization - // _initializerDefineProperty(_this, "_format", _descriptor$9, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, "_minFilter", _descriptor2$6, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, "_magFilter", _descriptor3$5, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, "_mipFilter", _descriptor4$4, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, "_wrapS", _descriptor5$3, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, "_wrapT", _descriptor6$1, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, "_wrapR", _descriptor7$1, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, "_anisotropy", _descriptor8$1, _assertThisInitialized(_this)); }; const oldGetGFXSampler = textureBaseProto.getGFXSampler; @@ -200,11 +118,31 @@ textureBaseProto.getSamplerInfo = function () { return this._samplerInfo; }; +const oldDestroy = textureBaseProto.destroy; +textureBaseProto.destroy = function () { + if (legacyCC.director.root?.batcher2D) { + // legacyCC.director.root.batcher2D._releaseDescriptorSetCache(this.getHash()); + legacyCC.director.root.batcher2D._releaseDescriptorSetCache(this.getGFXTexture(), this.getGFXSampler()); + } + // dispatch into C++ virtual function CCObject::destroy + return oldDestroy.call(this); +}; + textureBaseProto._onGFXSamplerUpdated = function (gfxSampler, samplerInfo) { this._gfxSampler = gfxSampler; this._samplerInfo = samplerInfo; }; -clsDecorator(TextureBase); - legacyCC.TextureBase = jsb.TextureBase; + +// handle meta data, it is generated automatically +const TextureBaseProto = TextureBase.prototype; +serializable(TextureBaseProto, '_format'); +serializable(TextureBaseProto, '_minFilter'); +serializable(TextureBaseProto, '_magFilter'); +serializable(TextureBaseProto, '_mipFilter'); +serializable(TextureBaseProto, '_wrapS'); +serializable(TextureBaseProto, '_wrapT'); +serializable(TextureBaseProto, '_wrapR'); +serializable(TextureBaseProto, '_anisotropy'); +ccclass('cc.TextureBase')(TextureBase); diff --git a/cocos/core/assets/texture-base.ts b/cocos/core/assets/texture-base.ts index 2f5ebb9271..d2a90c9e99 100644 --- a/cocos/core/assets/texture-base.ts +++ b/cocos/core/assets/texture-base.ts @@ -24,18 +24,13 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - // @ts-check -import { EDITOR, TEST } from 'internal:constants'; +import { EDITOR, JSB, TEST } from 'internal:constants'; import { ccclass, serializable } from 'cc.decorator'; import IDGenerator from '../utils/id-generator'; import { Asset } from './asset'; import { Filter, PixelFormat, WrapMode } from './asset-enum'; -import { Sampler, Texture, Device, Format, SamplerInfo, Address, Filter as GFXFilter } from '../gfx'; +import { Sampler, Texture, Device, Format, SamplerInfo, Address, Filter as GFXFilter, deviceManager } from '../gfx'; import { legacyCC } from '../global-exports'; import { errorID } from '../platform/debug'; import { murmurhash2_32_gc } from '../utils/murmurhash2_gc'; @@ -287,7 +282,7 @@ export class TextureBase extends Asset { // SERIALIZATION /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _serialize (ctxForExporting: any): any { if (EDITOR || TEST) { @@ -299,7 +294,7 @@ export class TextureBase extends Asset { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _deserialize (serializedData: any, handle: any) { const data = serializedData as string; @@ -318,10 +313,7 @@ export class TextureBase extends Asset { } protected _getGFXDevice (): Device | null { - if (legacyCC.director.root) { - return legacyCC.director.root.device as Device; - } - return null; + return deviceManager.gfxDevice; } protected _getGFXFormat () { diff --git a/cocos/core/assets/texture-cube.jsb.ts b/cocos/core/assets/texture-cube.jsb.ts index 428e90d0ad..4eed88162d 100644 --- a/cocos/core/assets/texture-cube.jsb.ts +++ b/cocos/core/assets/texture-cube.jsb.ts @@ -23,19 +23,25 @@ THE SOFTWARE. */ import { ccclass, serializable } from 'cc.decorator'; -import { - _applyDecoratedDescriptor, - _assertThisInitialized, - _initializerDefineProperty, -} from '../data/utils/decorator-jsb-utils'; import { legacyCC } from '../global-exports'; import { Filter, PixelFormat, WrapMode } from './asset-enum'; import { js } from '../utils/js'; +import './simple-texture'; const textureCubeProto: any = jsb.TextureCube.prototype; interface ITextureCubeSerializeData { base: string; rgbe: boolean; + mipmapMode: number; + mipmapAtlas: { + front: string; + back: string; + left: string; + right: string; + top: string; + bottom: string; + }; + mipmapLayout: []; mipmaps: { front: string; back: string; @@ -54,7 +60,11 @@ enum FaceIndex { front = 4, back = 5, } - +enum MipmapMode { + NONE = 0, + AUTO = 1, + BAKED_CONVOLUTION_MAP = 2, +} textureCubeProto.createNode = null!; export type TextureCube = jsb.TextureCube; @@ -64,32 +74,10 @@ TextureCube.Filter = Filter; TextureCube.PixelFormat = PixelFormat; TextureCube.WrapMode = WrapMode; -const clsDecorator = ccclass('cc.TextureCube'); - -const _class2$d = TextureCube; -const _descriptor$b = _applyDecoratedDescriptor(_class2$d.prototype, 'isRGBE', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return false; - }, -}); -const _descriptor2$7 = _applyDecoratedDescriptor(_class2$d.prototype, '_mipmaps', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return []; - }, -}); - textureCubeProto._ctor = function () { jsb.SimpleTexture.prototype._ctor.apply(this, arguments); this._mipmaps = null; - // for deserialization - // _initializerDefineProperty(_this, 'isRGBE', _descriptor$b, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, '_mipmaps', _descriptor2$7, _assertThisInitialized(_this)); + this._mipmapAtlas = null; }; function _forEachFace (mipmap, callback: (face, faceIndex) => void) { @@ -132,6 +120,7 @@ Object.defineProperty(textureCubeProto, 'mipmaps', { } }); + Object.defineProperty(textureCubeProto, 'image', { get () { return this._mipmaps.length === 0 ? null : this._mipmaps[0]; @@ -143,31 +132,66 @@ Object.defineProperty(textureCubeProto, 'image', { const oldOnLoaded = textureCubeProto.onLoaded; textureCubeProto.onLoaded = function () { - this.setMipmapsForJS(this._mipmaps); + if (this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP) { + this.setMipmapAtlasForJS(this._mipmapAtlas); + } else { + this.setMipmapsForJS(this._mipmaps); + } oldOnLoaded.apply(this); } textureCubeProto._serialize = function (ctxForExporting: any): Record | null { if (EDITOR || TEST) { - return { - base: jsb.TextureBase.prototype._serialize(ctxForExporting), - rgbe: this.isRGBE, - mipmaps: this._mipmaps.map((mipmap) => ((ctxForExporting && ctxForExporting._compressUuid) ? { - front: EditorExtends.UuidUtils.compressUuid(mipmap.front._uuid, true), - back: EditorExtends.UuidUtils.compressUuid(mipmap.back._uuid, true), - left: EditorExtends.UuidUtils.compressUuid(mipmap.left._uuid, true), - right: EditorExtends.UuidUtils.compressUuid(mipmap.right._uuid, true), - top: EditorExtends.UuidUtils.compressUuid(mipmap.top._uuid, true), - bottom: EditorExtends.UuidUtils.compressUuid(mipmap.bottom._uuid, true), - } : { - front: mipmap.front._uuid, - back: mipmap.back._uuid, - left: mipmap.left._uuid, - right: mipmap.right._uuid, - top: mipmap.top._uuid, - bottom: mipmap.bottom._uuid, - })), - }; + if (this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP) { + const atlas = this._mipmapAtlas!.atlas; + let uuids = {}; + if (ctxForExporting && ctxForExporting._compressUuid) { + uuids = { + front: EditorExtends.UuidUtils.compressUuid(atlas.front._uuid, true), + back: EditorExtends.UuidUtils.compressUuid(atlas.back._uuid, true), + left: EditorExtends.UuidUtils.compressUuid(atlas.left._uuid, true), + right: EditorExtends.UuidUtils.compressUuid(atlas.right._uuid, true), + top: EditorExtends.UuidUtils.compressUuid(atlas.top._uuid, true), + bottom: EditorExtends.UuidUtils.compressUuid(atlas.bottom._uuid, true), + }; + } else { + uuids = { + front: atlas.front._uuid, + back: atlas.back._uuid, + left: atlas.left._uuid, + right: atlas.right._uuid, + top: atlas.top._uuid, + bottom: atlas.bottom._uuid, + }; + } + return { + base: jsb.TextureBase.prototype._serialize(ctxForExporting), + rgbe: this.isRGBE, + mipmapMode: this._mipmapMode, + mipmapAtlas: uuids, + mipmapLayout: this._mipmapAtlas!.layout, + }; + } else { + return { + base: jsb.TextureBase.prototype._serialize(ctxForExporting), + rgbe: this.isRGBE, + mipmaps: this._mipmaps.map((mipmap) => ((ctxForExporting && ctxForExporting._compressUuid) ? { + front: EditorExtends.UuidUtils.compressUuid(mipmap.front._uuid, true), + back: EditorExtends.UuidUtils.compressUuid(mipmap.back._uuid, true), + left: EditorExtends.UuidUtils.compressUuid(mipmap.left._uuid, true), + right: EditorExtends.UuidUtils.compressUuid(mipmap.right._uuid, true), + top: EditorExtends.UuidUtils.compressUuid(mipmap.top._uuid, true), + bottom: EditorExtends.UuidUtils.compressUuid(mipmap.bottom._uuid, true), + } : { + front: mipmap.front._uuid, + back: mipmap.back._uuid, + left: mipmap.left._uuid, + right: mipmap.right._uuid, + top: mipmap.top._uuid, + bottom: mipmap.bottom._uuid, + })), + }; + } } return null; } @@ -176,10 +200,15 @@ textureCubeProto._deserialize = function (serializedData: ITextureCubeSerializeD const data = serializedData; jsb.TextureBase.prototype._deserialize.call(this, data.base, handle); this.isRGBE = data.rgbe; - this._mipmaps = new Array(data.mipmaps.length); - for (let i = 0; i < data.mipmaps.length; ++i) { - // Prevent resource load failed - this._mipmaps[i] = { + this._mipmapMode = parseInt(data.mipmapMode); + if (this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP) { + const mipmapAtlas = data.mipmapAtlas; + const mipmapLayout = data.mipmapLayout; + this._mipmapAtlas = { + atlas: {}, + layout: mipmapLayout, + }; + this._mipmapAtlas.atlas = { front: new jsb.ImageAsset(), back: new jsb.ImageAsset(), left: new jsb.ImageAsset(), @@ -187,17 +216,45 @@ textureCubeProto._deserialize = function (serializedData: ITextureCubeSerializeD top: new jsb.ImageAsset(), bottom: new jsb.ImageAsset(), }; - const mipmap = data.mipmaps[i]; - const imageAssetClassId = js._getClassId(jsb.ImageAsset); - handle.result.push(this._mipmaps[i], `front`, mipmap.front, imageAssetClassId); - handle.result.push(this._mipmaps[i], `back`, mipmap.back, imageAssetClassId); - handle.result.push(this._mipmaps[i], `left`, mipmap.left, imageAssetClassId); - handle.result.push(this._mipmaps[i], `right`, mipmap.right, imageAssetClassId); - handle.result.push(this._mipmaps[i], `top`, mipmap.top, imageAssetClassId); - handle.result.push(this._mipmaps[i], `bottom`, mipmap.bottom, imageAssetClassId); + if (mipmapAtlas) { + const imageAssetClassId = js.getClassId(jsb.ImageAsset); + handle.result.push(this._mipmapAtlas.atlas, `front`, mipmapAtlas.front, imageAssetClassId); + handle.result.push(this._mipmapAtlas.atlas, `back`, mipmapAtlas.back, imageAssetClassId); + handle.result.push(this._mipmapAtlas.atlas, `left`, mipmapAtlas.left, imageAssetClassId); + handle.result.push(this._mipmapAtlas.atlas, `right`, mipmapAtlas.right, imageAssetClassId); + handle.result.push(this._mipmapAtlas.atlas, `top`, mipmapAtlas.top, imageAssetClassId); + handle.result.push(this._mipmapAtlas.atlas, `bottom`, mipmapAtlas.bottom, imageAssetClassId); + } + } else { + this._mipmaps = new Array(data.mipmaps.length); + for (let i = 0; i < data.mipmaps.length; ++i) { + // Prevent resource load failed + this._mipmaps[i] = { + front: new jsb.ImageAsset(), + back: new jsb.ImageAsset(), + left: new jsb.ImageAsset(), + right: new jsb.ImageAsset(), + top: new jsb.ImageAsset(), + bottom: new jsb.ImageAsset(), + }; + const mipmap = data.mipmaps[i]; + const imageAssetClassId = js.getClassId(jsb.ImageAsset); + handle.result.push(this._mipmaps[i], `front`, mipmap.front, imageAssetClassId); + handle.result.push(this._mipmaps[i], `back`, mipmap.back, imageAssetClassId); + handle.result.push(this._mipmaps[i], `left`, mipmap.left, imageAssetClassId); + handle.result.push(this._mipmaps[i], `right`, mipmap.right, imageAssetClassId); + handle.result.push(this._mipmaps[i], `top`, mipmap.top, imageAssetClassId); + handle.result.push(this._mipmaps[i], `bottom`, mipmap.bottom, imageAssetClassId); + } } } -clsDecorator(TextureCube); - legacyCC.TextureCube = jsb.TextureCube; + +// handle meta data, it is generated automatically +const TextureCubeProto = TextureCube.prototype; +serializable(TextureCubeProto, 'isRGBE'); +serializable(TextureCubeProto, '_mipmaps'); +serializable(TextureCubeProto, '_mipmapMode'); +serializable(TextureCubeProto, '_mipmapAtlas'); +ccclass('cc.TextureCube')(TextureCube); diff --git a/cocos/core/assets/texture-cube.ts b/cocos/core/assets/texture-cube.ts index 1beb320bc4..b7ef45c411 100644 --- a/cocos/core/assets/texture-cube.ts +++ b/cocos/core/assets/texture-cube.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { EDITOR, TEST } from 'internal:constants'; import { ccclass, serializable } from 'cc.decorator'; import { TextureType, TextureInfo, TextureViewInfo } from '../gfx'; @@ -38,6 +33,25 @@ import { legacyCC } from '../global-exports'; import { js } from '../utils/js'; export type ITextureCubeCreateInfo = ITexture2DCreateInfo; +/** + * @en The MipmapAtlas region interface + * @zh MipmapAtlas的region接口。 + */ +interface IMipmapAtlasLayout { + left: number; + top: number; + width: number; + height: number; + level: number; +} +/** + * @en The texture cube MipmapAtlas interface + * @zh 立方体贴图的 MipmapAtlas 接口。 + */ +interface ITextureCubeMipmapAtlas { + atlas: ITextureCubeMipmap; + layout: IMipmapAtlasLayout[]; +} /** * @en The texture cube mipmap interface @@ -64,6 +78,36 @@ enum FaceIndex { front = 4, back = 5, } +/** + * @en The way to fill mipmaps. + * @zh 填充mipmaps的方式。 + */ +export enum MipmapMode { + /** + * @zh + * 不使用mipmaps + * @en + * Not using mipmaps + * @readonly + */ + NONE = 0, + /** + * @zh + * 使用自动生成的mipmaps + * @en + * Using the automatically generated mipmaps + * @readonly + */ + AUTO = 1, + /** + * @zh + * 使用卷积图填充mipmaps + * @en + * Filling mipmaps with convolutional maps + * @readonly + */ + BAKED_CONVOLUTION_MAP = 2, +} /** * @en The texture cube asset. @@ -78,6 +122,12 @@ export class TextureCube extends SimpleTexture { @serializable isRGBE = false; + @serializable + _mipmapAtlas: ITextureCubeMipmapAtlas | null = null; + + @serializable + _mipmapMode = MipmapMode.NONE; + /** * @en All levels of mipmap images, be noted, automatically generated mipmaps are not included. * When setup mipmap, the size of the texture and pixel format could be modified. @@ -117,6 +167,74 @@ export class TextureCube extends SimpleTexture { } } + /** + * @en Fill mipmaps with convolutional maps. + * @zh 使用卷积图填充mipmaps。 + * @param value All mipmaps of each face of the cube map are stored in the form of atlas + * and the value contains the atlas of the 6 faces and the layout information of each mipmap layer. + */ + set mipmapAtlas (value: ITextureCubeMipmapAtlas | null) { + this._mipmapAtlas = value; + if (!this._mipmapAtlas) { + this.reset({ + width: 0, + height: 0, + mipmapLevel: 0, + }); + return; + } + const imageAtlasAsset: ImageAsset = this._mipmapAtlas.atlas.front; + if (!imageAtlasAsset.data) { + return; + } + const faceAtlas = this._mipmapAtlas.atlas; + const layout = this._mipmapAtlas.layout; + const mip0Layout = layout[0]; + + const ctx = Object.assign(document.createElement('canvas'), { + width: imageAtlasAsset.width, + height: imageAtlasAsset.height, + }).getContext('2d'); + + this.reset({ + width: mip0Layout.width, + height: mip0Layout.height, + format: imageAtlasAsset.format, + mipmapLevel: layout.length, + }); + + for (let j = 0; j < layout.length; j++) { + const layoutInfo = layout[j]; + _forEachFace(faceAtlas, (face, faceIndex) => { + ctx!.clearRect(0, 0, imageAtlasAsset.width, imageAtlasAsset.height); + const drawImg = face.data as HTMLImageElement; + ctx!.drawImage(drawImg, 0, 0); + const rawData = ctx!.getImageData(layoutInfo.left, layoutInfo.top, layoutInfo.width, layoutInfo.height); + + const bufferAsset = new ImageAsset({ + _data: rawData.data, + _compressed: face.isCompressed, + width: rawData.width, + height: rawData.height, + format: face.format, + }); + this._assignImage(bufferAsset, layoutInfo.level, faceIndex); + }); + } + } + + get mipmapAtlas () { + return this._mipmapAtlas; + } + + /** + * @en Whether mipmaps are baked convolutional maps. + * @zh mipmaps是否为烘焙出来的卷积图。 + */ + public isUsingOfflineMipmaps (): boolean { + return this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP; + } + /** * @en Level 0 mipmap image. * Be noted, `this.image = img` equals `this.mipmaps = [img]`, @@ -173,13 +291,17 @@ export class TextureCube extends SimpleTexture { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @serializable public _mipmaps: ITextureCubeMipmap[] = []; public onLoaded () { - this.mipmaps = this._mipmaps; + if (this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP) { + this.mipmapAtlas = this._mipmapAtlas; + } else { + this.mipmaps = this._mipmaps; + } } /** @@ -195,8 +317,8 @@ export class TextureCube extends SimpleTexture { this._setGFXFormat(info.format); const mipLevels = info.mipmapLevel === undefined ? 1 : info.mipmapLevel; this._setMipmapLevel(mipLevels); - const minLod = info.baseLevel || 0; - const maxLod = info.maxLevel === undefined ? (mipLevels - 1) : info.maxLevel; + const minLod = info.baseLevel === undefined ? 0 : info.baseLevel; + const maxLod = info.maxLevel === undefined ? 1000 : info.maxLevel; this._setMipRange(minLod, maxLod); this._tryReset(); } @@ -220,10 +342,12 @@ export class TextureCube extends SimpleTexture { } /** - * 销毁此贴图,清空所有 Mipmap 并释放占用的 GPU 资源。 + * @en Destroy this texture, clear all mipmaps and release GPU resources + * @zh 销毁此贴图,清空所有 Mipmap 并释放占用的 GPU 资源。 */ public destroy () { this._mipmaps = []; + this._mipmapAtlas = null; return super.destroy(); } @@ -234,47 +358,84 @@ export class TextureCube extends SimpleTexture { */ public releaseTexture () { this.mipmaps = []; + this._mipmapAtlas = null; } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _serialize (ctxForExporting: any): Record | null { if (EDITOR || TEST) { - return { - base: super._serialize(ctxForExporting), - rgbe: this.isRGBE, - mipmaps: this._mipmaps.map((mipmap) => ((ctxForExporting && ctxForExporting._compressUuid) ? { - front: EditorExtends.UuidUtils.compressUuid(mipmap.front._uuid, true), - back: EditorExtends.UuidUtils.compressUuid(mipmap.back._uuid, true), - left: EditorExtends.UuidUtils.compressUuid(mipmap.left._uuid, true), - right: EditorExtends.UuidUtils.compressUuid(mipmap.right._uuid, true), - top: EditorExtends.UuidUtils.compressUuid(mipmap.top._uuid, true), - bottom: EditorExtends.UuidUtils.compressUuid(mipmap.bottom._uuid, true), - } : { - front: mipmap.front._uuid, - back: mipmap.back._uuid, - left: mipmap.left._uuid, - right: mipmap.right._uuid, - top: mipmap.top._uuid, - bottom: mipmap.bottom._uuid, - })), - }; + if (this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP) { + const atlas = this._mipmapAtlas!.atlas; + let uuids = {}; + if (ctxForExporting && ctxForExporting._compressUuid) { + uuids = { + front: EditorExtends.UuidUtils.compressUuid(atlas.front._uuid, true), + back: EditorExtends.UuidUtils.compressUuid(atlas.back._uuid, true), + left: EditorExtends.UuidUtils.compressUuid(atlas.left._uuid, true), + right: EditorExtends.UuidUtils.compressUuid(atlas.right._uuid, true), + top: EditorExtends.UuidUtils.compressUuid(atlas.top._uuid, true), + bottom: EditorExtends.UuidUtils.compressUuid(atlas.bottom._uuid, true), + }; + } else { + uuids = { + front: atlas.front._uuid, + back: atlas.back._uuid, + left: atlas.left._uuid, + right: atlas.right._uuid, + top: atlas.top._uuid, + bottom: atlas.bottom._uuid, + }; + } + return { + base: super._serialize(ctxForExporting), + rgbe: this.isRGBE, + mipmapMode: this._mipmapMode, + mipmapAtlas: uuids, + mipmapLayout: this._mipmapAtlas!.layout, + }; + } else { + return { + base: super._serialize(ctxForExporting), + rgbe: this.isRGBE, + mipmaps: this._mipmaps.map((mipmap) => ((ctxForExporting && ctxForExporting._compressUuid) ? { + front: EditorExtends.UuidUtils.compressUuid(mipmap.front._uuid, true), + back: EditorExtends.UuidUtils.compressUuid(mipmap.back._uuid, true), + left: EditorExtends.UuidUtils.compressUuid(mipmap.left._uuid, true), + right: EditorExtends.UuidUtils.compressUuid(mipmap.right._uuid, true), + top: EditorExtends.UuidUtils.compressUuid(mipmap.top._uuid, true), + bottom: EditorExtends.UuidUtils.compressUuid(mipmap.bottom._uuid, true), + } : { + front: mipmap.front._uuid, + back: mipmap.back._uuid, + left: mipmap.left._uuid, + right: mipmap.right._uuid, + top: mipmap.top._uuid, + bottom: mipmap.bottom._uuid, + })), + }; + } } return null; } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _deserialize (serializedData: ITextureCubeSerializeData, handle: any) { const data = serializedData; super._deserialize(data.base, handle); this.isRGBE = data.rgbe; - this._mipmaps = new Array(data.mipmaps.length); - for (let i = 0; i < data.mipmaps.length; ++i) { - // Prevent resource load failed - this._mipmaps[i] = { + this._mipmapMode = data.mipmapMode; + if (this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP) { + const mipmapAtlas = data.mipmapAtlas; + const mipmapLayout = data.mipmapLayout; + this._mipmapAtlas = { + atlas: {} as ITextureCubeMipmap, + layout: mipmapLayout, + }; + this._mipmapAtlas.atlas = { front: new ImageAsset(), back: new ImageAsset(), left: new ImageAsset(), @@ -282,14 +443,34 @@ export class TextureCube extends SimpleTexture { top: new ImageAsset(), bottom: new ImageAsset(), }; - const mipmap = data.mipmaps[i]; - const imageAssetClassId = js._getClassId(ImageAsset); - handle.result.push(this._mipmaps[i], `front`, mipmap.front, imageAssetClassId); - handle.result.push(this._mipmaps[i], `back`, mipmap.back, imageAssetClassId); - handle.result.push(this._mipmaps[i], `left`, mipmap.left, imageAssetClassId); - handle.result.push(this._mipmaps[i], `right`, mipmap.right, imageAssetClassId); - handle.result.push(this._mipmaps[i], `top`, mipmap.top, imageAssetClassId); - handle.result.push(this._mipmaps[i], `bottom`, mipmap.bottom, imageAssetClassId); + const imageAssetClassId = js.getClassId(ImageAsset); + handle.result.push(this._mipmapAtlas.atlas, `front`, mipmapAtlas.front, imageAssetClassId); + handle.result.push(this._mipmapAtlas.atlas, `back`, mipmapAtlas.back, imageAssetClassId); + handle.result.push(this._mipmapAtlas.atlas, `left`, mipmapAtlas.left, imageAssetClassId); + handle.result.push(this._mipmapAtlas.atlas, `right`, mipmapAtlas.right, imageAssetClassId); + handle.result.push(this._mipmapAtlas.atlas, `top`, mipmapAtlas.top, imageAssetClassId); + handle.result.push(this._mipmapAtlas.atlas, `bottom`, mipmapAtlas.bottom, imageAssetClassId); + } else { + this._mipmaps = new Array(data.mipmaps.length); + for (let i = 0; i < data.mipmaps.length; ++i) { + // Prevent resource load failed + this._mipmaps[i] = { + front: new ImageAsset(), + back: new ImageAsset(), + left: new ImageAsset(), + right: new ImageAsset(), + top: new ImageAsset(), + bottom: new ImageAsset(), + }; + const mipmap = data.mipmaps[i]; + const imageAssetClassId = js.getClassId(ImageAsset); + handle.result.push(this._mipmaps[i], `front`, mipmap.front, imageAssetClassId); + handle.result.push(this._mipmaps[i], `back`, mipmap.back, imageAssetClassId); + handle.result.push(this._mipmaps[i], `left`, mipmap.left, imageAssetClassId); + handle.result.push(this._mipmaps[i], `right`, mipmap.right, imageAssetClassId); + handle.result.push(this._mipmaps[i], `top`, mipmap.top, imageAssetClassId); + handle.result.push(this._mipmaps[i], `bottom`, mipmap.bottom, imageAssetClassId); + } } } @@ -327,7 +508,15 @@ export class TextureCube extends SimpleTexture { } public validate () { - return this._mipmaps.length !== 0 && !this._mipmaps.find((x) => !(x.top && x.bottom && x.front && x.back && x.left && x.right)); + if (this._mipmapMode === MipmapMode.BAKED_CONVOLUTION_MAP) { + if (this.mipmapAtlas === null || this.mipmapAtlas.layout.length === 0) { + return false; + } + const atlas = this.mipmapAtlas.atlas; + return !!(atlas.top && atlas.bottom && atlas.front && atlas.back && atlas.left && atlas.right); + } else { + return this._mipmaps.length !== 0 && !this._mipmaps.find((x) => !(x.top && x.bottom && x.front && x.back && x.left && x.right)); + } } } @@ -336,6 +525,16 @@ legacyCC.TextureCube = TextureCube; interface ITextureCubeSerializeData { base: string; rgbe: boolean; + mipmapMode: number; + mipmapAtlas: { + front: string; + back: string; + left: string; + right: string; + top: string; + bottom: string; + }; + mipmapLayout: []; mipmaps: { front: string; back: string; diff --git a/cocos/core/builtin/builtin-res-mgr.jsb.ts b/cocos/core/builtin/builtin-res-mgr.jsb.ts index 06de76495e..c61d0fcd68 100644 --- a/cocos/core/builtin/builtin-res-mgr.jsb.ts +++ b/cocos/core/builtin/builtin-res-mgr.jsb.ts @@ -24,10 +24,13 @@ */ import { legacyCC } from '../global-exports'; -import { Device } from '../gfx'; import { SpriteFrame } from '../../2d/assets/sprite-frame'; import type { ImageSource } from '../assets/image-asset'; -import { AssetManager } from '../asset-manager/asset-manager'; +import assetManager from '../asset-manager/asset-manager'; +import { BuiltinBundleName } from '../asset-manager/shared'; +import { TEST } from 'internal:constants'; +import { Settings, settings } from '../settings'; +import releaseManager from '../asset-manager/release-manager'; declare const jsb: any; @@ -37,11 +40,9 @@ const ImageAsset = jsb.ImageAsset; const BuiltinResMgr = jsb.BuiltinResMgr; const builtinResMgrProto = BuiltinResMgr.prototype; -const oldInitBuiltinRes = builtinResMgrProto.initBuiltinRes; - -builtinResMgrProto.initBuiltinRes = function (device: Device): Promise { +builtinResMgrProto.init = function (): Promise { this._resources = {}; - this._device = device; + this._materialsToBeCompiled = []; const resources = this._resources; const len = 2; const numChannels = 4; @@ -80,37 +81,55 @@ builtinResMgrProto.initBuiltinRes = function (device: Device): Promise { resources[spriteFrame._uuid] = spriteFrame; } - return Promise.resolve().then(() => { - oldInitBuiltinRes.call(this, device); - }).then(() => this._preloadAssets()); + this.initBuiltinRes(); }; -/** - * @internal - */ -builtinResMgrProto._preloadAssets = async function () { - const resources = this._resources; - if (window._CCSettings && window._CCSettings.preloadAssets && window._CCSettings.preloadAssets.length > 0) { - const preloadedAssets = window._CCSettings.preloadAssets as string[]; - return new Promise((resolve, reject) => (legacyCC.assetManager as AssetManager).loadAny(preloadedAssets, { __outputAsArray__: true }, (err, assets) => { - if (err) { - reject(err); - } else { - assets.forEach((asset) => { - resources[asset._uuid] = asset; - const url = asset.nativeUrl; // update native url obviously. - this.addAsset(asset._uuid, asset); - }); - resolve(); - } - })); - } -} - builtinResMgrProto.get = function (uuid: string) { const res = this._resources[uuid]; return res || this.getAsset(uuid); }; + +builtinResMgrProto.compileBuiltinMaterial = function () { + // NOTE: Builtin material should be compiled again after the render pipeline setup + for (let i = 0; i < this._materialsToBeCompiled.length; ++i) { + const mat = this._materialsToBeCompiled[i]; + for (let j = 0; j < mat.passes.length; ++j) { + mat.passes[j].tryCompile(); + } + } + this._materialsToBeCompiled.length = 0; +}; + +builtinResMgrProto.loadBuiltinAssets = function () { + const builtinAssets = settings.querySettings(Settings.Category.ENGINE, 'builtinAssets'); + if (TEST || !builtinAssets) return Promise.resolve(); + const resources = this._resources; + return new Promise((resolve, reject) => { + assetManager.loadBundle(BuiltinBundleName.INTERNAL, (err, bundle) => { + if (err) { + reject(err); + return; + } + assetManager.loadAny(builtinAssets, (err, assets) => { + if (err) { + reject(err); + } else { + assets.forEach((asset) => { + resources[asset.name] = asset; + const url = asset.nativeUrl; + releaseManager.addIgnoredAsset(asset); + this.addAsset(asset.name, asset); + if (asset instanceof legacyCC.Material) { + this._materialsToBeCompiled.push(asset); + } + }); + resolve(); + } + }); + }); + }); +} + const builtinResMgr = legacyCC.builtinResMgr = BuiltinResMgr.getInstance(); export { builtinResMgr }; diff --git a/cocos/core/builtin/builtin-res-mgr.ts b/cocos/core/builtin/builtin-res-mgr.ts index 55132e6212..d8592ace42 100644 --- a/cocos/core/builtin/builtin-res-mgr.ts +++ b/cocos/core/builtin/builtin-res-mgr.ts @@ -23,26 +23,26 @@ THE SOFTWARE. */ -import { TEST } from 'internal:constants'; +import { EDITOR, TEST } from 'internal:constants'; import { Asset } from '../assets/asset'; import { ImageAsset, ImageSource } from '../assets/image-asset'; import { SpriteFrame } from '../../2d/assets/sprite-frame'; import { Texture2D } from '../assets/texture-2d'; import { TextureCube } from '../assets/texture-cube'; -import { Device } from '../gfx'; -import { effects } from './effects'; import { legacyCC } from '../global-exports'; -import { getDeviceShaderVersion } from '../renderer/core/program-lib'; -import shaderSourceAssembly from './shader-source-assembly'; -import { AssetManager } from '../asset-manager/asset-manager'; +import assetManager from '../asset-manager/asset-manager'; +import { BuiltinBundleName } from '../asset-manager/shared'; +import Bundle from '../asset-manager/bundle'; +import { Settings, settings } from '../settings'; +import releaseManager from '../asset-manager/release-manager'; +import { Material } from '../assets'; class BuiltinResMgr { - protected _device: Device | null = null; protected _resources: Record = {}; + protected _materialsToBeCompiled: Material[] = []; // this should be called after renderer initialized - public initBuiltinRes (device: Device): Promise { - this._device = device; + public init () { const resources = this._resources; const len = 2; const numChannels = 4; @@ -267,33 +267,30 @@ class BuiltinResMgr { resources[spriteFrame._uuid] = spriteFrame; } - const shaderVersionKey = getDeviceShaderVersion(device); - if (!shaderVersionKey) { - return Promise.reject(Error('Failed to initialize builtin shaders: unknown device.')); - } - - const shaderSources = shaderSourceAssembly[shaderVersionKey]; - if (!shaderSources) { - return Promise.reject(Error( - `Current device is requiring builtin shaders of version ${shaderVersionKey} ` - + `but shaders of that version are not assembled in this build.`, - )); - } - - return Promise.resolve().then(() => { - effects.forEach((e, effectIndex) => { - const effect = Object.assign(new legacyCC.EffectAsset(), e); - effect.shaders.forEach((shaderInfo, shaderIndex) => { - const shaderSource = shaderSources[effectIndex][shaderIndex]; - if (shaderSource) { - shaderInfo[shaderVersionKey] = shaderSource; - } - }); - effect.hideInEditor = true; - effect.onLoaded(); + if (EDITOR) { + const builtinAssets = settings.querySettings(Settings.Category.ENGINE, 'builtinAssets'); + const builtinBundle = new Bundle(); + builtinBundle.init({ + name: BuiltinBundleName.INTERNAL, + uuids: builtinAssets || [], + deps: [], + importBase: '', + nativeBase: '', + base: '', + paths: {}, + scenes: {}, + packs: {}, + versions: { import: [], native: [] }, + redirect: [], + debug: false, + types: [], + extensionMap: {}, }); - this._initMaterials(); - }).then(() => this._preloadAssets()); + } + } + + public addAsset (key: string, asset: Asset) { + this._resources[key] = asset; } public get (uuid: string) { @@ -303,187 +300,43 @@ class BuiltinResMgr { /** * @internal */ - private _initMaterials () { + public loadBuiltinAssets () { + const builtinAssets = settings.querySettings(Settings.Category.ENGINE, 'builtinAssets'); + if (TEST || !builtinAssets) return Promise.resolve(); const resources = this._resources; - const materialsToBeCompiled: any[] = []; - - // standard material - const standardMtl = new legacyCC.Material(); - standardMtl._uuid = 'standard-material'; - standardMtl.initialize({ - effectName: 'standard', - }); - resources[standardMtl._uuid] = standardMtl; - materialsToBeCompiled.push(standardMtl); - - // material indicating missing effect (yellow) - const missingEfxMtl = new legacyCC.Material(); - missingEfxMtl._uuid = 'missing-effect-material'; - missingEfxMtl.initialize({ - effectName: 'unlit', - defines: { USE_COLOR: true }, - }); - missingEfxMtl.setProperty('mainColor', legacyCC.color('#ffff00')); - resources[missingEfxMtl._uuid] = missingEfxMtl; - materialsToBeCompiled.push(missingEfxMtl); - - // material indicating missing material (purple) - const missingMtl = new legacyCC.Material(); - missingMtl._uuid = 'missing-material'; - missingMtl.initialize({ - effectName: 'unlit', - defines: { USE_COLOR: true }, - }); - missingMtl.setProperty('mainColor', legacyCC.color('#ff00ff')); - resources[missingMtl._uuid] = missingMtl; - materialsToBeCompiled.push(missingMtl); - - const clearStencilMtl = new legacyCC.Material(); - clearStencilMtl._uuid = 'default-clear-stencil'; - clearStencilMtl.initialize({ - defines: { USE_TEXTURE: false }, - effectName: 'clear-stencil', - }); - resources[clearStencilMtl._uuid] = clearStencilMtl; - materialsToBeCompiled.push(clearStencilMtl); - - // sprite material - const spriteMtl = new legacyCC.Material(); - spriteMtl._uuid = 'ui-base-material'; - spriteMtl.initialize({ - defines: { USE_TEXTURE: false }, - effectName: 'sprite', - }); - resources[spriteMtl._uuid] = spriteMtl; - materialsToBeCompiled.push(spriteMtl); - - // sprite material - const spriteColorMtl = new legacyCC.Material(); - spriteColorMtl._uuid = 'ui-sprite-material'; - spriteColorMtl.initialize({ - defines: { USE_TEXTURE: true, CC_USE_EMBEDDED_ALPHA: false, IS_GRAY: false }, - effectName: 'sprite', - }); - resources[spriteColorMtl._uuid] = spriteColorMtl; - materialsToBeCompiled.push(spriteColorMtl); - - // sprite alpha test material - const alphaTestMaskMtl = new legacyCC.Material(); - alphaTestMaskMtl._uuid = 'ui-alpha-test-material'; - alphaTestMaskMtl.initialize({ - defines: { USE_TEXTURE: true, USE_ALPHA_TEST: true, CC_USE_EMBEDDED_ALPHA: false, IS_GRAY: false }, - effectName: 'sprite', - }); - resources[alphaTestMaskMtl._uuid] = alphaTestMaskMtl; - materialsToBeCompiled.push(alphaTestMaskMtl); - - // sprite gray material - const spriteGrayMtl = new legacyCC.Material(); - spriteGrayMtl._uuid = 'ui-sprite-gray-material'; - spriteGrayMtl.initialize({ - defines: { USE_TEXTURE: true, CC_USE_EMBEDDED_ALPHA: false, IS_GRAY: true }, - effectName: 'sprite', - }); - resources[spriteGrayMtl._uuid] = spriteGrayMtl; - materialsToBeCompiled.push(spriteGrayMtl); - - // sprite alpha material - const spriteAlphaMtl = new legacyCC.Material(); - spriteAlphaMtl._uuid = 'ui-sprite-alpha-sep-material'; - spriteAlphaMtl.initialize({ - defines: { USE_TEXTURE: true, CC_USE_EMBEDDED_ALPHA: true, IS_GRAY: false }, - effectName: 'sprite', - }); - resources[spriteAlphaMtl._uuid] = spriteAlphaMtl; - materialsToBeCompiled.push(spriteAlphaMtl); - - // sprite alpha & gray material - const spriteAlphaGrayMtl = new legacyCC.Material(); - spriteAlphaGrayMtl._uuid = 'ui-sprite-gray-alpha-sep-material'; - spriteAlphaGrayMtl.initialize({ - defines: { USE_TEXTURE: true, CC_USE_EMBEDDED_ALPHA: true, IS_GRAY: true }, - effectName: 'sprite', - }); - resources[spriteAlphaGrayMtl._uuid] = spriteAlphaGrayMtl; - materialsToBeCompiled.push(spriteAlphaGrayMtl); - - // ui graphics material - const defaultGraphicsMtl = new legacyCC.Material(); - defaultGraphicsMtl._uuid = 'ui-graphics-material'; - defaultGraphicsMtl.initialize({ effectName: 'graphics' }); - resources[defaultGraphicsMtl._uuid] = defaultGraphicsMtl; - materialsToBeCompiled.push(defaultGraphicsMtl); - - // default particle material - const defaultParticleMtl = new legacyCC.Material(); - defaultParticleMtl._uuid = 'default-particle-material'; - defaultParticleMtl.initialize({ effectName: 'particle' }); - resources[defaultParticleMtl._uuid] = defaultParticleMtl; - materialsToBeCompiled.push(defaultParticleMtl); - - // default particle gpu material - if (!TEST) { - const defaultParticleGPUMtl = new legacyCC.Material(); - defaultParticleGPUMtl._uuid = 'default-particle-gpu-material'; - defaultParticleGPUMtl.initialize({ effectName: 'particle-gpu' }); - resources[defaultParticleGPUMtl._uuid] = defaultParticleGPUMtl; - materialsToBeCompiled.push(defaultParticleGPUMtl); - } - - // default particle material - const defaultTrailMtl = new legacyCC.Material(); - defaultTrailMtl._uuid = 'default-trail-material'; - defaultTrailMtl.initialize({ effectName: 'particle-trail' }); - resources[defaultTrailMtl._uuid] = defaultTrailMtl; - materialsToBeCompiled.push(defaultTrailMtl); - - // default particle material - const defaultBillboardMtl = new legacyCC.Material(); - defaultBillboardMtl._uuid = 'default-billboard-material'; - defaultBillboardMtl.initialize({ effectName: 'billboard' }); - resources[defaultBillboardMtl._uuid] = defaultBillboardMtl; - materialsToBeCompiled.push(defaultBillboardMtl); - - // ui spine two color material - const spineTwoColorMtl = new legacyCC.Material(); - spineTwoColorMtl._uuid = 'default-spine-material'; - spineTwoColorMtl.initialize({ - defines: { - USE_TEXTURE: true, - CC_USE_EMBEDDED_ALPHA: false, - IS_GRAY: false, - }, - effectName: 'spine', - }); - resources[spineTwoColorMtl._uuid] = spineTwoColorMtl; - materialsToBeCompiled.push(spineTwoColorMtl); - - legacyCC.game.on(legacyCC.Game.EVENT_GAME_INITED, () => { - for (let i = 0; i < materialsToBeCompiled.length; ++i) { - const mat = materialsToBeCompiled[i]; - for (let j = 0; j < mat.passes.length; ++j) { - mat.passes[j].tryCompile(); + return new Promise((resolve, reject) => { + assetManager.loadBundle(BuiltinBundleName.INTERNAL, (err, bundle) => { + if (err) { + reject(err); + return; } - } + assetManager.loadAny(builtinAssets, (err, assets) => { + if (err) { + reject(err); + } else { + assets.forEach((asset) => { + resources[asset.name] = asset; + releaseManager.addIgnoredAsset(asset); + if (asset instanceof legacyCC.Material) { + this._materialsToBeCompiled.push(asset as Material); + } + }); + resolve(); + } + }); + }); }); } - /** - * @internal - */ - private async _preloadAssets () { - const resources = this._resources; - if (window._CCSettings && window._CCSettings.preloadAssets && window._CCSettings.preloadAssets.length > 0) { - const preloadedAssets = window._CCSettings.preloadAssets as string[]; - return new Promise((resolve, reject) => (legacyCC.assetManager as AssetManager).loadAny(preloadedAssets, { __outputAsArray__: true }, (err, assets) => { - if (err) { - reject(err); - } else { - assets.forEach((asset) => resources[asset._uuid] = asset); - resolve(); - } - })); + public compileBuiltinMaterial () { + // NOTE: Builtin material should be compiled again after the render pipeline setup + for (let i = 0; i < this._materialsToBeCompiled.length; ++i) { + const mat = this._materialsToBeCompiled[i]; + for (let j = 0; j < mat.passes.length; ++j) { + mat.passes[j].tryCompile(); + } } + this._materialsToBeCompiled.length = 0; } } diff --git a/cocos/core/builtin/index.ts b/cocos/core/builtin/index.ts index 1eb064907b..01819e38b5 100644 --- a/cocos/core/builtin/index.ts +++ b/cocos/core/builtin/index.ts @@ -24,4 +24,3 @@ */ export * from './builtin-res-mgr'; -export { effects } from './effects'; diff --git a/cocos/core/builtin/shader-source-assembly.ts b/cocos/core/builtin/shader-source-assembly.ts deleted file mode 100644 index ccaf8e77a5..0000000000 --- a/cocos/core/builtin/shader-source-assembly.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { HTML5, MINIGAME, RUNTIME_BASED, WECHAT, TEST } from 'internal:constants'; -import { glsl1 } from './shader-sources/glsl1'; -import { glsl3 } from './shader-sources/glsl3'; -import { glsl4 } from './shader-sources/glsl4'; - -type ShaderVersion = 'glsl1' | 'glsl3' | 'glsl4'; - -type ShaderSource = Record[][]; - -/** - * The shader sources assembled in this build. - */ -const assembly: Partial> = (() => { - if (TEST) { - return { - glsl1, - glsl3, - glsl4, - }; - } else if (HTML5 || WECHAT || RUNTIME_BASED) { - return { - glsl1, - glsl3, - }; - } else if (MINIGAME) { - return { - glsl1, - }; - } else { - return { - glsl1, - glsl3, - glsl4, - }; - } -})(); - -export default assembly; diff --git a/cocos/core/builtin/shader-sources/glsl1.ts b/cocos/core/builtin/shader-sources/glsl1.ts deleted file mode 100644 index 8053e89b6d..0000000000 --- a/cocos/core/builtin/shader-sources/glsl1.ts +++ /dev/null @@ -1,169 +0,0 @@ -/* eslint-disable */ -export const glsl1 = [ - [ - { - "vert": "\nprecision mediump float;\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matViewInv;\nuniform highp mat4 cc_matViewProj;\n#if USE_BATCHING\n#endif\nuniform highp mat4 cc_matWorld;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\nmat3 m = mat3(xAxis,yAxis,zAxis);\nfloat trace = m[0][0] + m[1][1] + m[2][2];\nvec4 quat;\nif (trace > 0.) {\nfloat s = 0.5 / sqrt(trace + 1.0);\nquat.w = 0.25 / s;\nquat.x = (m[2][1] - m[1][2]) * s;\nquat.y = (m[0][2] - m[2][0]) * s;\nquat.z = (m[1][0] - m[0][1]) * s;\n} else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\nfloat s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\nquat.w = (m[2][1] - m[1][2]) / s;\nquat.x = 0.25 * s;\nquat.y = (m[0][1] + m[1][0]) / s;\nquat.z = (m[0][2] + m[2][0]) / s;\n} else if (m[1][1] > m[2][2]) {\nfloat s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\nquat.w = (m[0][2] - m[2][0]) / s;\nquat.x = (m[0][1] + m[1][0]) / s;\nquat.y = 0.25 * s;\nquat.z = (m[1][2] + m[2][1]) / s;\n} else {\nfloat s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\nquat.w = (m[1][0] - m[0][1]) / s;\nquat.x = (m[0][2] + m[2][0]) / s;\nquat.y = (m[1][2] + m[2][1]) / s;\nquat.z = 0.25 * s;\n}\nfloat len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\nif (len > 0.) {\nlen = 1. / sqrt(len);\nquat.x = quat.x * len;\nquat.y = quat.y * len;\nquat.z = quat.z * len;\nquat.w = quat.w * len;\n}\nreturn quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\nfloat x = angle.x / 2.;\nfloat y = angle.y / 2.;\nfloat z = angle.z / 2.;\nfloat sx = sin(x);\nfloat cx = cos(x);\nfloat sy = sin(y);\nfloat cy = cos(y);\nfloat sz = sin(z);\nfloat cz = cos(z);\nvec4 quat = vec4(0);\nquat.x = sx * cy * cz + cx * sy * sz;\nquat.y = cx * sy * cz + sx * cy * sz;\nquat.z = cx * cy * sz - sx * sy * cz;\nquat.w = cx * cy * cz - sx * sy * sz;\nreturn quat;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\nvec4 quat;\nquat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\nquat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\nquat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\nquat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\nreturn quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\nfloat ix = q.w * v.x + q.y * v.z - q.z * v.y;\nfloat iy = q.w * v.y + q.z * v.x - q.x * v.z;\nfloat iz = q.w * v.z + q.x * v.y - q.y * v.x;\nfloat iw = -q.x * v.x - q.y * v.y - q.z * v.z;\nv.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\nv.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\nv.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\nvec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\nvec4 rotQuat = quatMultiply(viewQuat, q);\nrotateVecFromQuat(pos, rotQuat);\nreturn pos;\n}\nvarying mediump vec2 uv;\nvarying mediump vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n, mat4 viewInv\n) {\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\nvec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\nvec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n}\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nuniform vec4 cc_size_rotation;\nvec4 vs_main() {\nvec4 pos = vec4(a_position, 1);\npos = cc_matWorld * pos;\nvec2 vertOffset = a_texCoord.xy - 0.5;\ncomputeVertPos(pos, vertOffset, quaternionFromEuler(vec3(0., 0., cc_size_rotation.z)), vec3(cc_size_rotation.xy, 0.), cc_matViewInv);\npos = cc_matViewProj * pos;\nuv = a_texCoord.xy;\ncolor = a_color;\nreturn pos;\n}\nvoid main() { gl_Position = vs_main(); }", - "frag": "\nprecision mediump float;\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nvarying vec2 uv;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nuniform vec4 tintColor;\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\nreturn CCFragOutput(col);\n}\nvoid main() { gl_FragColor = add(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\nattribute vec3 a_position;\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\nvec4 frag () {\nvec4 o = vec4(1.0);\nreturn o;\n}\nvoid main() { gl_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nuniform mediump vec4 cc_screenSize;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_surfaceTransform;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nvarying vec2 v_texCoord;\nvarying vec4 v_color;\nvec4 vert () {\nint orientation = int(cc_surfaceTransform.x);\nvec4 transform = vec4(1.0, 0.0, 0.0, 1.0);\nif (orientation == 0) {\ntransform = vec4(1.0, 0.0, 0.0, 1.0);\n} else if (orientation == 1) {\ntransform = vec4(0.0, 1.0, -1.0, 0.0);\n} else if (orientation == 2) {\ntransform = vec4(-1.0, 0.0, 0.0, -1.0);\n} else if (orientation == 3) {\ntransform = vec4(0.0, -1.0, 1.0, 0.0);\n}\nvec2 invScreenSize = (orientation == 1 || orientation == 3) ? cc_screenSize.wz : cc_screenSize.zw;\nvec2 position = a_position * invScreenSize;\nposition = position * vec2(2.0, -2.0) + vec2(-1.0, 1.0);\nvec2 clipPos = vec2(dot(transform.xy, position), dot(transform.zw, position));\nclipPos = cc_cameraPos.w == 0.0 ? vec2(clipPos.x, -clipPos.y) : clipPos;\nv_texCoord = a_texCoord;\nv_color = a_color;\nreturn vec4(clipPos, 0.0, 1.0);\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nvarying vec2 v_texCoord;\nvarying vec4 v_color;\nuniform sampler2D mainTexture;\nvec4 frag () {\nvec4 color = vec4(v_color.rgb, v_color.a * texture2D(mainTexture, v_texCoord).r);\nreturn CCFragOutput(color);\n}\nvoid main() { gl_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nuniform highp mat4 cc_matViewProj;\nattribute highp vec3 a_position;\nattribute vec4 a_color;\nvarying vec4 v_color;\nvec4 vert () {\nvec4 pos = cc_matViewProj * vec4(a_position, 1);\npos.z -= 0.000001;\nv_color = a_color;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nvarying vec4 v_color;\nvec4 front() {\n#if USE_FORWARD_PIPELINE\nreturn CCFragOutput(v_color);\n#else\nreturn v_color;\n#endif\n}\nvoid main() { gl_FragColor = front(); }", - }, - { - "vert": "\nprecision mediump float;\nuniform highp mat4 cc_matViewProj;\nattribute highp vec3 a_position;\nattribute vec4 a_color;\nvarying vec4 v_color;\nvec4 vert () {\nvec4 pos = cc_matViewProj * vec4(a_position, 1);\npos.z -= 0.000001;\nv_color = a_color;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nvarying vec4 v_color;\nvec4 back() {\n#if USE_FORWARD_PIPELINE\nreturn CCFragOutput(vec4(v_color.rgb, v_color.a * 0.2));\n#else\nreturn vec4(v_color.rgb, v_color.a * 0.2);\n#endif\n}\nvoid main() { gl_FragColor = back(); }", - }, - { - "vert": "\nprecision mediump float;\nuniform highp mat4 cc_matViewProj;\nattribute highp vec3 a_position;\nattribute vec4 a_color;\nvarying vec4 v_color;\nvarying float v_distance;\nvec4 vert () {\nvec4 pos = cc_matViewProj * vec4(a_position, 1);\npos.z -= 0.000001;\nv_color = a_color;\nv_distance = dot(a_position, vec3(1.0, 1.0, 1.0));\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nvarying vec4 v_color;\nvarying float v_distance;\nvec4 front() {\nif (fract(v_distance) > 0.5) {\ndiscard;\n}\n#if USE_FORWARD_PIPELINE\nreturn CCFragOutput(v_color);\n#else\nreturn v_color;\n#endif\n}\nvoid main() { gl_FragColor = front(); }", - }, - { - "vert": "\nprecision mediump float;\nuniform highp mat4 cc_matViewProj;\nattribute highp vec3 a_position;\nattribute vec4 a_color;\nvarying vec4 v_color;\nvarying float v_distance;\nvec4 vert () {\nvec4 pos = cc_matViewProj * vec4(a_position, 1);\npos.z -= 0.000001;\nv_color = a_color;\nv_distance = dot(a_position, vec3(1.0, 1.0, 1.0));\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nvarying vec4 v_color;\nvarying float v_distance;\nvec4 back() {\nif (fract(v_distance) > 0.5) {\ndiscard;\n}\n#if USE_FORWARD_PIPELINE\nreturn CCFragOutput(vec4(v_color.rgb, v_color.a * 0.2));\n#else\nreturn vec4(v_color.rgb, v_color.a * 0.2);\n#endif\n}\nvoid main() { gl_FragColor = back(); }", - }, - { - "vert": "\nprecision mediump float;\nuniform highp mat4 cc_matViewProj;\nattribute highp vec3 a_position;\nattribute vec4 a_normal;\nattribute vec4 a_color;\nvarying vec4 v_color;\nvec4 vert () {\nvec4 pos = cc_matViewProj * vec4(a_position, 1);\nv_color = a_color;\nfloat intensity = dot(vec3(1, 2, 4), a_normal.xyz);\nv_color.rgb -= a_normal.w * intensity * 0.1;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nvarying vec4 v_color;\nvec4 front() {\n#if USE_FORWARD_PIPELINE\nreturn CCFragOutput(v_color);\n#else\nreturn v_color;\n#endif\n}\nvoid main() { gl_FragColor = front(); }", - }, - { - "vert": "\nprecision mediump float;\nuniform highp mat4 cc_matViewProj;\nattribute highp vec3 a_position;\nattribute vec4 a_normal;\nattribute vec4 a_color;\nvarying vec4 v_color;\nvec4 vert () {\nvec4 pos = cc_matViewProj * vec4(a_position, 1);\nv_color = a_color;\nfloat intensity = dot(vec3(1, 2, 4), a_normal.xyz);\nv_color.rgb -= a_normal.w * intensity * 0.1;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nvarying vec4 v_color;\nvec4 back() {\n#if USE_FORWARD_PIPELINE\nreturn CCFragOutput(vec4(v_color.rgb, v_color.a * 0.2));\n#else\nreturn vec4(v_color.rgb, v_color.a * 0.2);\n#endif\n}\nvoid main() { gl_FragColor = back(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\nuniform highp mat4 cc_matViewProj;\n#if USE_BATCHING\n#endif\nuniform highp mat4 cc_matWorld;\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying vec4 v_color;\nattribute float a_dist;\nvarying float v_dist;\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\npos = cc_matViewProj * cc_matWorld * pos;\nv_color = a_color;\nv_dist = a_dist;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\n#ifdef GL_OES_standard_derivatives\n#extension GL_OES_standard_derivatives: enable\n#endif\nprecision highp float;\nvarying vec4 v_color;\nvarying float v_dist;\nvec4 frag () {\nvec4 o = v_color;\n#ifdef GL_OES_standard_derivatives\nfloat aa = fwidth(v_dist);\n#else\nfloat aa = 0.05;\n#endif\nfloat alpha = 1. - smoothstep(-aa, 0., abs(v_dist) - 1.0);\no.rgb *= o.a;\no *= alpha;\nreturn o;\n}\nvoid main() { gl_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\nuniform highp mat4 cc_matViewProj;\nuniform highp vec4 cc_worldBoundCenter;\nuniform highp vec4 cc_worldBoundHalfExtents;\nattribute vec3 a_position;\nvec4 vert () {\nvec4 position;\nposition = vec4(a_position, 1.0);\nposition *= cc_worldBoundHalfExtents;\nposition += cc_worldBoundCenter;\nposition = cc_matViewProj * position;\nreturn position;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nvec4 frag () {\nreturn vec4(1, 0, 0, 1);\n}\nvoid main() { gl_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\nmat3 m = mat3(xAxis,yAxis,zAxis);\nfloat trace = m[0][0] + m[1][1] + m[2][2];\nvec4 quat;\nif (trace > 0.) {\nfloat s = 0.5 / sqrt(trace + 1.0);\nquat.w = 0.25 / s;\nquat.x = (m[2][1] - m[1][2]) * s;\nquat.y = (m[0][2] - m[2][0]) * s;\nquat.z = (m[1][0] - m[0][1]) * s;\n} else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\nfloat s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\nquat.w = (m[2][1] - m[1][2]) / s;\nquat.x = 0.25 * s;\nquat.y = (m[0][1] + m[1][0]) / s;\nquat.z = (m[0][2] + m[2][0]) / s;\n} else if (m[1][1] > m[2][2]) {\nfloat s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\nquat.w = (m[0][2] - m[2][0]) / s;\nquat.x = (m[0][1] + m[1][0]) / s;\nquat.y = 0.25 * s;\nquat.z = (m[1][2] + m[2][1]) / s;\n} else {\nfloat s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\nquat.w = (m[1][0] - m[0][1]) / s;\nquat.x = (m[0][2] + m[2][0]) / s;\nquat.y = (m[1][2] + m[2][1]) / s;\nquat.z = 0.25 * s;\n}\nfloat len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\nif (len > 0.) {\nlen = 1. / sqrt(len);\nquat.x = quat.x * len;\nquat.y = quat.y * len;\nquat.z = quat.z * len;\nquat.w = quat.w * len;\n}\nreturn quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\nfloat x = angle.x / 2.;\nfloat y = angle.y / 2.;\nfloat z = angle.z / 2.;\nfloat sx = sin(x);\nfloat cx = cos(x);\nfloat sy = sin(y);\nfloat cy = cos(y);\nfloat sz = sin(z);\nfloat cz = cos(z);\nvec4 quat = vec4(0);\nquat.x = sx * cy * cz + cx * sy * sz;\nquat.y = cx * sy * cz + sx * cy * sz;\nquat.z = cx * cy * sz - sx * sy * cz;\nquat.w = cx * cy * cz - sx * sy * sz;\nreturn quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\nfloat x2 = q.x + q.x;\nfloat y2 = q.y + q.y;\nfloat z2 = q.z + q.z;\nfloat xx = q.x * x2;\nfloat xy = q.x * y2;\nfloat xz = q.x * z2;\nfloat yy = q.y * y2;\nfloat yz = q.y * z2;\nfloat zz = q.z * z2;\nfloat wx = q.w * x2;\nfloat wy = q.w * y2;\nfloat wz = q.w * z2;\nreturn mat4(\n1. - (yy + zz), xy + wz, xz - wy, 0,\nxy - wz, 1. - (xx + zz), yz + wx, 0,\nxz + wy, yz - wx, 1. - (xx + yy), 0,\np.x, p.y, p.z, 1\n);\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\nfloat x = q.x, y = q.y, z = q.z, w = q.w;\nfloat x2 = x + x;\nfloat y2 = y + y;\nfloat z2 = z + z;\nfloat xx = x * x2;\nfloat xy = x * y2;\nfloat xz = x * z2;\nfloat yy = y * y2;\nfloat yz = y * z2;\nfloat zz = z * z2;\nfloat wx = w * x2;\nfloat wy = w * y2;\nfloat wz = w * z2;\nfloat sx = s.x;\nfloat sy = s.y;\nfloat sz = s.z;\nreturn mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n(xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n(xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\nt.x, t.y, t.z, 1);\n}\nvec4 quatMultiply (vec4 a, vec4 b){\nvec4 quat;\nquat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\nquat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\nquat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\nquat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\nreturn quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\nfloat ix = q.w * v.x + q.y * v.z - q.z * v.y;\nfloat iy = q.w * v.y + q.z * v.x - q.x * v.z;\nfloat iz = q.w * v.z + q.x * v.y - q.y * v.x;\nfloat iw = -q.x * v.x - q.y * v.y - q.z * v.z;\nv.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\nv.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\nv.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\nvec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\nvec4 rotQuat = quatMultiply(viewQuat, q);\nrotateVecFromQuat(pos, rotQuat);\nreturn pos;\n}\nmat3 quatToMat3(vec4 q) {\nvec3 m0 = vec3(\n1.0 - 2.0 * q.y * q.y - 2.0 * q.z * q.z,\n2.0 * q.x * q.y + 2.0 * q.w * q.z,\n2.0 * q.x * q.z - 2.0 * q.w * q.y);\nvec3 m1 = vec3(\n2.0 * q.x * q.y - 2.0 * q.w * q.z,\n1.0 - 2.0 * q.x * q.x - 2.0 * q.z * q.z,\n2.0 * q.y * q.z + 2.0 * q.w * q.x);\nvec3 m2 = vec3(\n2.0 * q.x * q.z + 2.0 * q.w * q.y,\n2.0 * q.y * q.z - 2.0 * q.w * q.x,\n1.0 - 2.0 * q.x * q.x - 2.0 * q.y * q.y);\nreturn mat3(m0, m1, m2);\n}\nvec4 mat3ToQuat(mat3 mat) {\nfloat tr = mat[0][0] + mat[1][1] + mat[2][2];\nfloat qw, qx, qy, qz;\nif (tr > 0.0) {\nfloat S = sqrt(tr + 1.0) * 2.0;\nfloat invS = 1.0 / S;\nqw = 0.25 * S;\nqx = (mat[1][2] - mat[2][1]) * invS;\nqy = (mat[2][0] - mat[0][2]) * invS;\nqz = (mat[0][1] - mat[1][0]) * invS;\n} else if ((mat[0][0] > mat[1][1])&&(mat[0][0] > mat[2][2])) {\nfloat S = sqrt(1.0 + mat[0][0] - mat[1][1] - mat[2][2]) * 2.0;\nfloat invS = 1.0 / S;\nqw = (mat[1][2] - mat[2][1]) * invS;\nqx = 0.25 * S;\nqy = (mat[1][0] + mat[0][1]) * invS;\nqz = (mat[2][0] + mat[0][2]) * invS;\n} else if (mat[1][1] > mat[2][2]) {\nfloat S = sqrt(1.0 + mat[1][1] - mat[0][0] - mat[2][2]) * 2.0;\nfloat invS = 1.0 / S;\nqw = (mat[2][0] - mat[0][2]) * invS;\nqx = (mat[1][0] + mat[0][1]) * invS;\nqy = 0.25 * S;\nqz = (mat[2][1] + mat[1][2]) * invS;\n} else {\nfloat S = sqrt(1.0 + mat[2][2] - mat[0][0] - mat[1][1]) * 2.0;\nfloat invS = 1.0 / S;\nqw = (mat[0][1] - mat[1][0]) * invS;\nqx = (mat[2][0] + mat[0][2]) * invS;\nqy = (mat[2][1] + mat[1][2]) * invS;\nqz = 0.25 * S;\n}\nreturn vec4(qx, qy, qz, qw);\n}\nvec4 eulerToQuat(vec3 euler) {\nvec3 er = euler * 0.5;\nfloat x = er.x, y = er.y, z = er.z;\nfloat sx = sin(x);\nfloat cx = cos(x);\nfloat sy = sin(y);\nfloat cy = cos(y);\nfloat sz = sin(z);\nfloat cz = cos(z);\nvec4 quat;\nquat.x = sx * cy * cz + cx * sy * sz;\nquat.y = cx * sy * cz + sx * cy * sz;\nquat.z = cx * cy * sz - sx * sy * cz;\nquat.w = cx * cy * cz - sx * sy * sz;\nreturn quat;\n}\nuniform vec4 mainTiling_Offset;\nuniform vec4 frameTile_velLenScale;\nuniform vec4 scale;\nuniform vec4 nodeRotation;\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matViewInv;\nuniform highp mat4 cc_matViewProj;\nuniform highp vec4 cc_cameraPos;\n#if USE_BATCHING\n#endif\nuniform highp mat4 cc_matWorld;\nvarying mediump vec2 uv;\nvarying mediump vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n, mat4 viewInv\n#endif\n#if CC_RENDER_MODE == 1\n, vec3 eye\n, vec4 velocity\n, float velocityScale\n, float lengthScale\n, float xIndex\n#endif\n) {\n#if CC_RENDER_MODE == 0\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\nvec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\nvec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_RENDER_MODE == 1\nvec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\nvec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\npos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_RENDER_MODE == 2\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = vec3(1, 0, 0);\nvec3 camY = vec3(0, 0, -1);\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_RENDER_MODE == 3\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nrotateVecFromQuat(viewSpaceVert, q);\nvec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\nvec3 camY = vec3(0, 1, 0);\nvec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\npos.xyz += offset;\n#else\npos.x += vertOffset.x;\npos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV (float frameIndex, vec2 vertIndex, vec2 frameTile){\nvec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\naniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if CC_RENDER_MODE != 4\nvertIndex.y = 1. - vertIndex.y;\n#endif\nreturn (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nuniform vec4 u_sampleInfo;\nuniform vec4 u_worldRot;\nuniform vec4 u_timeDelta;\nattribute vec4 a_position_starttime;\nattribute vec4 a_size_uv;\nattribute vec4 a_rotation_uv;\nattribute vec4 a_color;\nattribute vec4 a_dir_life;\nattribute float a_rndSeed;\n#if CC_RENDER_MODE == 4\nattribute vec3 a_texCoord;\nattribute vec3 a_texCoord3;\nattribute vec3 a_normal;\nattribute vec4 a_color1;\n#endif\nvec3 unpackCurveData (sampler2D tex, vec2 coord) {\nvec4 a = texture2D(tex, coord);\nvec4 b = texture2D(tex, coord + u_sampleInfo.y);\nfloat c = fract(coord.x * u_sampleInfo.x);\nreturn mix(a.xyz, b.xyz, c);\n}\nvec3 unpackCurveData (sampler2D tex, vec2 coord, out float w) {\nvec4 a = texture2D(tex, coord);\nvec4 b = texture2D(tex, coord + u_sampleInfo.y);\nfloat c = fract(coord.x * u_sampleInfo.x);\nw = mix(a.w, b.w, c);\nreturn mix(a.xyz, b.xyz, c);\n}\nfloat pseudoRandom(float x) {\n#if USE_VK_SHADER\nfloat o = x;\nx = mod(x - 1.0, 2.0) - 1.0;\nfloat freqVar = 10.16640753482;\nfloat y = sin(freqVar * floor(o * 0.5 - 0.5));\nfloat v = max(0.0, 1.0-abs(x));\nv *= 0.7071067812;\nv = y < 0.0 ? -v : v;\nreturn v;\n#else\nfloat seed = mod(x, 233280.);\nfloat q = (seed * 9301. + 49297.) / 233280.;\nreturn fract(q);\n#endif\n}\n#if COLOR_OVER_TIME_MODULE_ENABLE\nuniform sampler2D color_over_time_tex0;\nuniform int u_color_mode;\n#endif\n#if ROTATION_OVER_TIME_MODULE_ENABLE\nuniform sampler2D rotation_over_time_tex0;\nuniform int u_rotation_mode;\n#endif\n#if SIZE_OVER_TIME_MODULE_ENABLE\nuniform sampler2D size_over_time_tex0;\nuniform int u_size_mode;\n#endif\n#if FORCE_OVER_TIME_MODULE_ENABLE\nuniform sampler2D force_over_time_tex0;\nuniform int u_force_mode;\nuniform int u_force_space;\n#endif\n#if VELOCITY_OVER_TIME_MODULE_ENABLE\nuniform sampler2D velocity_over_time_tex0;\nuniform int u_velocity_mode;\nuniform int u_velocity_space;\n#endif\n#if TEXTURE_ANIMATION_MODULE_ENABLE\nuniform sampler2D texture_animation_tex0;\nuniform vec4 u_anim_info;\n#endif\nfloat repeat (float t, float length) {\nreturn t - floor(t / length) * length;\n}\nvec4 rotateQuat (vec4 p, vec4 q) {\nvec3 iv = cross(q.xyz, p.xyz) + q.w * p.xyz;\nvec3 res = p.xyz + 2.0 * cross(q.xyz, iv);\nreturn vec4(res.xyz, p.w);\n}\nvec4 gpvs_main () {\nfloat activeTime = u_timeDelta.x - a_position_starttime.w;\nfloat normalizedTime = clamp(activeTime / a_dir_life.w, 0.0, 1.0);\nvec2 timeCoord0 = vec2(normalizedTime, 0.);\nvec2 timeCoord1 = vec2(normalizedTime, 1.);\n#if CC_RENDER_MODE == 4\nvec2 vertIdx = vec2(a_texCoord.x, a_texCoord.y);\n#else\nvec2 vertIdx = vec2(a_size_uv.w, a_rotation_uv.w);\n#endif\nvec4 velocity = vec4(a_dir_life.xyz, 0.);\nvec4 pos = vec4(a_position_starttime.xyz, 1.);\nvec3 size = a_size_uv.xyz;\n#if SIZE_OVER_TIME_MODULE_ENABLE\nif (u_size_mode == 1) {\nsize *= unpackCurveData(size_over_time_tex0, timeCoord0);\n} else {\nvec3 size_0 = unpackCurveData(size_over_time_tex0, timeCoord0);\nvec3 size_1 = unpackCurveData(size_over_time_tex0, timeCoord1);\nfloat factor_s = pseudoRandom(a_rndSeed + 39825.);\nsize *= mix(size_0, size_1, factor_s);\n}\n#endif\nvec3 compScale = scale.xyz * size;\n#if FORCE_OVER_TIME_MODULE_ENABLE\nvec3 forceAnim = vec3(0.);\nif (u_force_mode == 1) {\nforceAnim = unpackCurveData(force_over_time_tex0, timeCoord0);\n} else {\nvec3 force_0 = unpackCurveData(force_over_time_tex0, timeCoord0);\nvec3 force_1 = unpackCurveData(force_over_time_tex0, timeCoord1);\nfloat factor_f = pseudoRandom(a_rndSeed + 212165.);\nforceAnim = mix(force_0, force_1, factor_f);\n}\nvec4 forceTrack = vec4(forceAnim, 0.);\nif (u_force_space == 0) {\nforceTrack = rotateQuat(forceTrack, u_worldRot);\n}\nvelocity.xyz += forceTrack.xyz;\n#endif\n#if VELOCITY_OVER_TIME_MODULE_ENABLE\nfloat speedModifier0 = 1.;\nfloat speedModifier1 = 1.;\nvec3 velocityAnim = vec3(0.);\nif (u_velocity_mode == 1) {\nvelocityAnim = unpackCurveData(velocity_over_time_tex0, timeCoord0, speedModifier0);\n} else {\nvec3 vectory_0 = unpackCurveData(velocity_over_time_tex0, timeCoord0, speedModifier0);\nvec3 vectory_1 = unpackCurveData(velocity_over_time_tex0, timeCoord1, speedModifier1);\nfloat factor_v = pseudoRandom(a_rndSeed + 197866.);\nvelocityAnim = mix(vectory_0, vectory_1, factor_v);\nspeedModifier0 = mix(speedModifier0, speedModifier1, factor_v);\n}\nvec4 velocityTrack = vec4(velocityAnim, 0.);\nif (u_velocity_space == 0) {\nvelocityTrack = rotateQuat(velocityTrack, u_worldRot);\n}\nvelocity.xyz += velocityTrack.xyz;\nvelocity.xyz *= speedModifier0;\n#endif\npos.xyz += velocity.xyz * normalizedTime * a_dir_life.w;\n#if !CC_USE_WORLD_SPACE\npos = cc_matWorld * pos;\n#if CC_RENDER_MODE == 1\nvelocity = rotateQuat(velocity, u_worldRot);\n#endif\n#endif\nvec3 startRotation = a_rotation_uv.xyz;\n#if CC_RENDER_MODE != 4\n#if CC_RENDER_MODE == 0\nvec3 rotEuler = startRotation.xyz;\n#elif CC_RENDER_MODE == 1\nvec3 rotEuler = vec3(0.);\n#else\nvec3 rotEuler = vec3(0., 0., startRotation.z);\n#endif\nvec4 rot = quaternionFromEuler(rotEuler);\n#else\nvec4 rot = quaternionFromEuler(startRotation);\n#endif\n#if ROTATION_OVER_TIME_MODULE_ENABLE\nif (u_rotation_mode == 1) {\nvec3 euler = unpackCurveData(rotation_over_time_tex0, timeCoord0) * normalizedTime * a_dir_life.w;\nvec4 quat = eulerToQuat(euler);\nmat3 mLocal = quatToMat3(quat);\nmat3 mStart = quatToMat3(rot);\nrot = mat3ToQuat(mStart * mLocal);\n} else {\nvec3 rotation_0 = unpackCurveData(rotation_over_time_tex0, timeCoord0);\nvec3 rotation_1 = unpackCurveData(rotation_over_time_tex0, timeCoord1);\nfloat factor_r = pseudoRandom(a_rndSeed + 125292.);\nvec3 euler = mix(rotation_0, rotation_1, factor_r) * normalizedTime * a_dir_life.w;\n#if CC_RENDER_MODE == 3 || CC_RENDER_MODE == 2\neuler = vec3(0.0, 0.0, euler.z);\n#endif\nvec4 quat = eulerToQuat(euler);\nmat3 mLocal = quatToMat3(quat);\nmat3 mStart = quatToMat3(rot);\nrot = mat3ToQuat(mStart * mLocal);\n}\n#endif\n#if COLOR_OVER_TIME_MODULE_ENABLE\nif (u_color_mode == 1) {\ncolor = a_color * texture2D(color_over_time_tex0, timeCoord0);\n} else {\nvec4 color_0 = texture2D(color_over_time_tex0, timeCoord0);\nvec4 color_1 = texture2D(color_over_time_tex0, timeCoord1);\nfloat factor_c = pseudoRandom(a_rndSeed + 91041.);\ncolor = a_color * mix(color_0, color_1, factor_c);\n}\n#else\ncolor = a_color;\n#endif\n#if CC_RENDER_MODE != 4\nvec2 cornerOffset = vec2((vertIdx - 0.5));\n#if CC_RENDER_MODE == 1\nrot = vec4(0.0, 0.0, 0.0, 1.0);\n#endif\ncomputeVertPos(pos, cornerOffset, rot, compScale\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n, cc_matViewInv\n#endif\n#if CC_RENDER_MODE == 1\n, cc_cameraPos.xyz\n, velocity\n, frameTile_velLenScale.z\n, frameTile_velLenScale.w\n, a_size_uv.w\n#endif\n);\n#else\nmat3 rotMat = quatToMat3(rot);\nmat3 nodeMat = quatToMat3(nodeRotation);\nrotMat = nodeMat * rotMat;\nrot = mat3ToQuat(rotMat);\nmat4 xformNoScale = matrixFromRT(rot, pos.xyz);\nmat4 xform = matFromRTS(rot, pos.xyz, compScale);\npos = xform * vec4(a_texCoord3, 1);\nvec4 normal = xformNoScale * vec4(a_normal, 0);\ncolor *= a_color1;\n#endif\npos = cc_matViewProj * pos;\nfloat frameIndex = 0.;\n#if TEXTURE_ANIMATION_MODULE_ENABLE\nfloat startFrame = 0.;\nvec3 frameInfo = vec3(0.);\nif (int(u_anim_info.x) == 1) {\nframeInfo = unpackCurveData(texture_animation_tex0, timeCoord0);\n} else {\nvec3 frameInfo0 = unpackCurveData(texture_animation_tex0, timeCoord0);\nvec3 frameInfo1 = unpackCurveData(texture_animation_tex0, timeCoord1);\nfloat factor_t = pseudoRandom(a_rndSeed + 90794.);\nframeInfo = mix(frameInfo0, frameInfo1, factor_t);\n}\nstartFrame = frameInfo.x / u_anim_info.y;\nframeIndex = repeat(u_anim_info.z * (frameInfo.y + startFrame), 1.);\n#endif\nuv = computeUV(frameIndex, vertIdx, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\nreturn pos;\n}\nvoid main() { gl_Position = gpvs_main(); }", - "frag": "\nprecision mediump float;\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nvarying vec2 uv;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nuniform vec4 tintColor;\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\nreturn CCFragOutput(col);\n}\nvoid main() { gl_FragColor = add(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nuniform vec4 mainTiling_Offset;\nuniform highp mat4 cc_matViewProj;\nuniform highp vec4 cc_cameraPos;\n#if USE_BATCHING\n#endif\nuniform highp mat4 cc_matWorld;\nvarying mediump vec2 uv;\nvarying mediump vec4 color;\nattribute vec3 a_position;\nattribute vec4 a_texCoord;\nattribute vec3 a_texCoord1;\nattribute vec3 a_texCoord2;\nattribute vec4 a_color;\n#if CC_DRAW_WIRE_FRAME\nvarying vec3 vBarycentric;\n#endif\nvec4 vs_main() {\nhighp vec4 pos = vec4(a_position, 1);\nvec4 velocity = vec4(a_texCoord1.xyz, 0);\n#if !CC_USE_WORLD_SPACE\npos = cc_matWorld * pos;\nvelocity = cc_matWorld * velocity;\n#endif\nfloat vertOffset = (a_texCoord.x - 0.5) * a_texCoord.y;\nvec3 camUp = normalize(cross(pos.xyz - cc_cameraPos.xyz, velocity.xyz));\npos.xyz += camUp * vertOffset;\npos = cc_matViewProj * pos;\nuv = a_texCoord.zw * mainTiling_Offset.xy + mainTiling_Offset.zw;;\ncolor = a_color;\n#if CC_DRAW_WIRE_FRAME\nvBarycentric = a_texCoord2;\n#endif\nreturn pos;\n}\nvoid main() { gl_Position = vs_main(); }", - "frag": "\nprecision mediump float;\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nvarying vec2 uv;\nvarying vec4 color;\n#if CC_DRAW_WIRE_FRAME\nvarying vec3 vBarycentric;\n#endif\nuniform sampler2D mainTexture;\nuniform vec4 tintColor;\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\n#if CC_DRAW_WIRE_FRAME\nif (any(lessThan(vBarycentric, vec3(0.02)))) {\ncol = vec4(0., 1., 1., 1.);\n}\n#endif\nreturn CCFragOutput(col);\n}\nvoid main() { gl_FragColor = add(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\nmat3 m = mat3(xAxis,yAxis,zAxis);\nfloat trace = m[0][0] + m[1][1] + m[2][2];\nvec4 quat;\nif (trace > 0.) {\nfloat s = 0.5 / sqrt(trace + 1.0);\nquat.w = 0.25 / s;\nquat.x = (m[2][1] - m[1][2]) * s;\nquat.y = (m[0][2] - m[2][0]) * s;\nquat.z = (m[1][0] - m[0][1]) * s;\n} else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\nfloat s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\nquat.w = (m[2][1] - m[1][2]) / s;\nquat.x = 0.25 * s;\nquat.y = (m[0][1] + m[1][0]) / s;\nquat.z = (m[0][2] + m[2][0]) / s;\n} else if (m[1][1] > m[2][2]) {\nfloat s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\nquat.w = (m[0][2] - m[2][0]) / s;\nquat.x = (m[0][1] + m[1][0]) / s;\nquat.y = 0.25 * s;\nquat.z = (m[1][2] + m[2][1]) / s;\n} else {\nfloat s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\nquat.w = (m[1][0] - m[0][1]) / s;\nquat.x = (m[0][2] + m[2][0]) / s;\nquat.y = (m[1][2] + m[2][1]) / s;\nquat.z = 0.25 * s;\n}\nfloat len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\nif (len > 0.) {\nlen = 1. / sqrt(len);\nquat.x = quat.x * len;\nquat.y = quat.y * len;\nquat.z = quat.z * len;\nquat.w = quat.w * len;\n}\nreturn quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\nfloat x = angle.x / 2.;\nfloat y = angle.y / 2.;\nfloat z = angle.z / 2.;\nfloat sx = sin(x);\nfloat cx = cos(x);\nfloat sy = sin(y);\nfloat cy = cos(y);\nfloat sz = sin(z);\nfloat cz = cos(z);\nvec4 quat = vec4(0);\nquat.x = sx * cy * cz + cx * sy * sz;\nquat.y = cx * sy * cz + sx * cy * sz;\nquat.z = cx * cy * sz - sx * sy * cz;\nquat.w = cx * cy * cz - sx * sy * sz;\nreturn quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\nfloat x2 = q.x + q.x;\nfloat y2 = q.y + q.y;\nfloat z2 = q.z + q.z;\nfloat xx = q.x * x2;\nfloat xy = q.x * y2;\nfloat xz = q.x * z2;\nfloat yy = q.y * y2;\nfloat yz = q.y * z2;\nfloat zz = q.z * z2;\nfloat wx = q.w * x2;\nfloat wy = q.w * y2;\nfloat wz = q.w * z2;\nreturn mat4(\n1. - (yy + zz), xy + wz, xz - wy, 0,\nxy - wz, 1. - (xx + zz), yz + wx, 0,\nxz + wy, yz - wx, 1. - (xx + yy), 0,\np.x, p.y, p.z, 1\n);\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\nfloat x = q.x, y = q.y, z = q.z, w = q.w;\nfloat x2 = x + x;\nfloat y2 = y + y;\nfloat z2 = z + z;\nfloat xx = x * x2;\nfloat xy = x * y2;\nfloat xz = x * z2;\nfloat yy = y * y2;\nfloat yz = y * z2;\nfloat zz = z * z2;\nfloat wx = w * x2;\nfloat wy = w * y2;\nfloat wz = w * z2;\nfloat sx = s.x;\nfloat sy = s.y;\nfloat sz = s.z;\nreturn mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n(xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n(xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\nt.x, t.y, t.z, 1);\n}\nvec4 quatMultiply (vec4 a, vec4 b){\nvec4 quat;\nquat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\nquat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\nquat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\nquat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\nreturn quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\nfloat ix = q.w * v.x + q.y * v.z - q.z * v.y;\nfloat iy = q.w * v.y + q.z * v.x - q.x * v.z;\nfloat iz = q.w * v.z + q.x * v.y - q.y * v.x;\nfloat iw = -q.x * v.x - q.y * v.y - q.z * v.z;\nv.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\nv.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\nv.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\nvec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\nvec4 rotQuat = quatMultiply(viewQuat, q);\nrotateVecFromQuat(pos, rotQuat);\nreturn pos;\n}\nmat3 quatToMat3(vec4 q) {\nvec3 m0 = vec3(\n1.0 - 2.0 * q.y * q.y - 2.0 * q.z * q.z,\n2.0 * q.x * q.y + 2.0 * q.w * q.z,\n2.0 * q.x * q.z - 2.0 * q.w * q.y);\nvec3 m1 = vec3(\n2.0 * q.x * q.y - 2.0 * q.w * q.z,\n1.0 - 2.0 * q.x * q.x - 2.0 * q.z * q.z,\n2.0 * q.y * q.z + 2.0 * q.w * q.x);\nvec3 m2 = vec3(\n2.0 * q.x * q.z + 2.0 * q.w * q.y,\n2.0 * q.y * q.z - 2.0 * q.w * q.x,\n1.0 - 2.0 * q.x * q.x - 2.0 * q.y * q.y);\nreturn mat3(m0, m1, m2);\n}\nvec4 mat3ToQuat(mat3 mat) {\nfloat tr = mat[0][0] + mat[1][1] + mat[2][2];\nfloat qw, qx, qy, qz;\nif (tr > 0.0) {\nfloat S = sqrt(tr + 1.0) * 2.0;\nfloat invS = 1.0 / S;\nqw = 0.25 * S;\nqx = (mat[1][2] - mat[2][1]) * invS;\nqy = (mat[2][0] - mat[0][2]) * invS;\nqz = (mat[0][1] - mat[1][0]) * invS;\n} else if ((mat[0][0] > mat[1][1])&&(mat[0][0] > mat[2][2])) {\nfloat S = sqrt(1.0 + mat[0][0] - mat[1][1] - mat[2][2]) * 2.0;\nfloat invS = 1.0 / S;\nqw = (mat[1][2] - mat[2][1]) * invS;\nqx = 0.25 * S;\nqy = (mat[1][0] + mat[0][1]) * invS;\nqz = (mat[2][0] + mat[0][2]) * invS;\n} else if (mat[1][1] > mat[2][2]) {\nfloat S = sqrt(1.0 + mat[1][1] - mat[0][0] - mat[2][2]) * 2.0;\nfloat invS = 1.0 / S;\nqw = (mat[2][0] - mat[0][2]) * invS;\nqx = (mat[1][0] + mat[0][1]) * invS;\nqy = 0.25 * S;\nqz = (mat[2][1] + mat[1][2]) * invS;\n} else {\nfloat S = sqrt(1.0 + mat[2][2] - mat[0][0] - mat[1][1]) * 2.0;\nfloat invS = 1.0 / S;\nqw = (mat[0][1] - mat[1][0]) * invS;\nqx = (mat[2][0] + mat[0][2]) * invS;\nqy = (mat[2][1] + mat[1][2]) * invS;\nqz = 0.25 * S;\n}\nreturn vec4(qx, qy, qz, qw);\n}\nuniform vec4 mainTiling_Offset;\nuniform vec4 frameTile_velLenScale;\nuniform vec4 scale;\nuniform vec4 nodeRotation;\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matViewInv;\nuniform highp mat4 cc_matViewProj;\nuniform highp vec4 cc_cameraPos;\n#if USE_BATCHING\n#endif\nuniform highp mat4 cc_matWorld;\nvarying mediump vec2 uv;\nvarying mediump vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n, mat4 viewInv\n#endif\n#if CC_RENDER_MODE == 1\n, vec3 eye\n, vec4 velocity\n, float velocityScale\n, float lengthScale\n, float xIndex\n#endif\n) {\n#if CC_RENDER_MODE == 0\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\nvec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\nvec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_RENDER_MODE == 1\nvec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\nvec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\npos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_RENDER_MODE == 2\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = vec3(1, 0, 0);\nvec3 camY = vec3(0, 0, -1);\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_RENDER_MODE == 3\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nrotateVecFromQuat(viewSpaceVert, q);\nvec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\nvec3 camY = vec3(0, 1, 0);\nvec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\npos.xyz += offset;\n#else\npos.x += vertOffset.x;\npos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV (float frameIndex, vec2 vertIndex, vec2 frameTile){\nvec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\naniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if CC_RENDER_MODE != 4\nvertIndex.y = 1. - vertIndex.y;\n#endif\nreturn (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nattribute vec3 a_position;\nattribute vec3 a_texCoord;\nattribute vec3 a_texCoord1;\nattribute vec3 a_texCoord2;\nattribute vec4 a_color;\n#if CC_RENDER_MODE == 1\nattribute vec3 a_color1;\n#endif\n#if CC_RENDER_MODE == 4\nattribute vec3 a_texCoord3;\nattribute vec3 a_normal;\nattribute vec4 a_color1;\n#endif\nvec4 lpvs_main () {\nvec3 compScale = scale.xyz * a_texCoord1;\nvec4 pos = vec4(a_position, 1);\n#if CC_RENDER_MODE == 1\nvec4 velocity = vec4(a_color1.xyz, 0);\n#endif\n#if !CC_USE_WORLD_SPACE\npos = cc_matWorld * pos;\n#if CC_RENDER_MODE == 1\nvelocity = cc_matWorld * velocity;\n#endif\n#endif\n#if ROTATION_OVER_TIME_MODULE_ENABLE\nvec3 rotTmp = a_texCoord2;\nfloat mulFactor = 1.0;\nif (rotTmp.x > 10.0 * 0.5) {\nrotTmp.x -= 10.0;\nmulFactor = -1.0;\n}\nvec4 rot = vec4(rotTmp, 0.0);\nrot.w = mulFactor * sqrt(abs(1.0 - rot.x * rot.x - rot.y * rot.y - rot.z * rot.z));\n#else\n#if CC_RENDER_MODE != 4\n#if CC_RENDER_MODE == 0\nvec3 rotEuler = a_texCoord2;\n#elif CC_RENDER_MODE == 1\nvec3 rotEuler = vec3(0.);\n#else\nvec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n#endif\nvec4 rot = quaternionFromEuler(rotEuler);\n#else\nvec4 rot = quaternionFromEuler(a_texCoord2);\n#endif\n#endif\n#if CC_RENDER_MODE != 4\nvec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\ncomputeVertPos(pos, cornerOffset, rot, compScale, cc_matViewInv);\n#elif CC_RENDER_MODE == 1\ncomputeVertPos(pos, cornerOffset, rot, compScale, cc_cameraPos.xyz, velocity, frameTile_velLenScale.z, frameTile_velLenScale.w, a_texCoord.x);\n#elif 2\ncomputeVertPos(pos, cornerOffset, rot, compScale);\n#endif\ncolor = a_color;\n#else\nmat3 rotMat = quatToMat3(rot);\nmat3 nodeMat = quatToMat3(nodeRotation);\nrotMat = nodeMat * rotMat;\nrot = mat3ToQuat(rotMat);\nmat4 xformNoScale = matrixFromRT(rot, pos.xyz);\nmat4 xform = matFromRTS(rot, pos.xyz, compScale);\npos = xform * vec4(a_texCoord3, 1);\nvec4 normal = xformNoScale * vec4(a_normal, 0);\ncolor = a_color * a_color1;\n#endif\nuv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\npos = cc_matViewProj * pos;\nreturn pos;\n}\nvoid main() { gl_Position = lpvs_main(); }", - "frag": "\nprecision mediump float;\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nvarying vec2 uv;\nvarying vec4 color;\nuniform sampler2D mainTexture;\nuniform vec4 tintColor;\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture2D(mainTexture, uv);\nreturn CCFragOutput(col);\n}\nvoid main() { gl_FragColor = add(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\nuniform highp mat4 cc_matViewProj;\n#if USE_LOCAL\n#if USE_BATCHING\n#endif\nuniform highp mat4 cc_matWorld;\n#endif\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nvarying vec4 v_light;\nvarying vec2 uv0;\n#if TWO_COLORED\nattribute vec4 a_color2;\nvarying vec4 v_dark;\n#endif\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\n#if USE_LOCAL\npos = cc_matWorld * pos;\n#endif\npos = cc_matViewProj * pos;\nuv0 = a_texCoord;\nv_light = a_color;\n#if TWO_COLORED\nv_dark = a_color2;\n#endif\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\n#if USE_ALPHA_TEST\nuniform float alphaThreshold;\n#endif\nvoid ALPHA_TEST (in vec4 color) {\n#if USE_ALPHA_TEST\nif (color.a < alphaThreshold) discard;\n#endif\n}\nvoid ALPHA_TEST (in float alpha) {\n#if USE_ALPHA_TEST\nif (alpha < alphaThreshold) discard;\n#endif\n}\nvarying vec4 v_light;\n#if TWO_COLORED\nvarying vec4 v_dark;\n#endif\nvarying vec2 uv0;\nuniform sampler2D cc_spriteTexture;\nvec4 frag () {\nvec4 o = vec4(1, 1, 1, 1);\n#if TWO_COLORED\nvec4 texColor = vec4(1, 1, 1, 1);\ntexColor *= texture2D(cc_spriteTexture, uv0);\no.a = texColor.a * v_light.a;\no.rgb = ((texColor.a - 1.0) * v_dark.a + 1.0 - texColor.rgb) * v_dark.rgb + texColor.rgb * v_light.rgb;\n#else\no *= texture2D(cc_spriteTexture, uv0);\no *= v_light;\n#endif\nALPHA_TEST(o);\nreturn o;\n}\nvoid main() { gl_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\nuniform highp mat4 cc_matViewProj;\nuniform highp vec4 cc_cameraPos;\n#if USE_LOCAL\n#if USE_BATCHING\n#endif\nuniform highp mat4 cc_matWorld;\n#endif\n#if SAMPLE_FROM_RT\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\n#endif\nattribute vec3 a_position;\nattribute vec2 a_texCoord;\nattribute vec4 a_color;\nvarying vec4 color;\nvarying vec2 uv0;\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\n#if USE_LOCAL\npos = cc_matWorld * pos;\n#endif\n#if USE_PIXEL_ALIGNMENT\npos = cc_matView * pos;\npos.xyz = floor(pos.xyz);\npos = cc_matProj * pos;\n#else\npos = cc_matViewProj * pos;\n#endif\nuv0 = a_texCoord;\n#if SAMPLE_FROM_RT\nuv0 = cc_cameraPos.w > 1.0 ? vec2(uv0.x, 1.0 - uv0.y) : uv0;\n#endif\ncolor = a_color;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\nvec4 CCSampleWithAlphaSeparated(sampler2D tex, vec2 uv) {\n#if CC_USE_EMBEDDED_ALPHA\nreturn vec4(texture2D(tex, uv).rgb, texture2D(tex, uv + vec2(0.0, 0.5)).r);\n#else\nreturn texture2D(tex, uv);\n#endif\n}\n#if USE_ALPHA_TEST\nuniform float alphaThreshold;\n#endif\nvoid ALPHA_TEST (in vec4 color) {\n#if USE_ALPHA_TEST\nif (color.a < alphaThreshold) discard;\n#endif\n}\nvoid ALPHA_TEST (in float alpha) {\n#if USE_ALPHA_TEST\nif (alpha < alphaThreshold) discard;\n#endif\n}\nvarying vec4 color;\n#if USE_TEXTURE\nvarying vec2 uv0;\nuniform sampler2D cc_spriteTexture;\n#endif\nvec4 frag () {\nvec4 o = vec4(1, 1, 1, 1);\n#if USE_TEXTURE\no *= CCSampleWithAlphaSeparated(cc_spriteTexture, uv0);\n#if IS_GRAY\nfloat gray = 0.2126 * o.r + 0.7152 * o.g + 0.0722 * o.b;\no.r = o.g = o.b = gray;\n#endif\n#endif\no *= color;\nALPHA_TEST(o);\nreturn o;\n}\nvoid main() { gl_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nattribute vec4 a_tangent;\n#if USE_INSTANCING\nattribute vec4 a_matWorld0;\nattribute vec4 a_matWorld1;\nattribute vec4 a_matWorld2;\n#if USE_LIGHTMAP\nattribute vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nattribute vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nattribute float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nattribute float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_joints;\nattribute vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 uv = getPixelCoordFromLocation(location, cc_displacementTextureInfo.xy);\nreturn texture2D(tex, uv);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture2D(tex, x)),\ndecode32(texture2D(tex, y)),\ndecode32(texture2D(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nattribute highp vec4 a_jointAnimInfo;\n#endif\nuniform highp vec4 cc_jointTextureInfo;\nuniform highp vec4 cc_jointAnimInfo;\nuniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nuniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_fogBase;\nuniform mediump vec4 cc_fogAdd;\n#if USE_BATCHING\nuniform highp mat4 cc_matWorlds[10];\n#endif\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matWorldIT;\nuniform highp vec4 cc_lightingMapUVParam;\nuniform highp vec4 cc_localShadowBias;\nvoid CCGetWorldMatrixFull(out mat4 matWorld, out mat4 matWorldIT)\n{\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\nmatWorldIT = matWorld;\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\nmatWorldIT = matWorld;\n#else\nmatWorld = cc_matWorld;\nmatWorldIT = cc_matWorldIT;\n#endif\n}\nuniform vec4 tilingOffset;\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\n#if !CC_USE_ACCURATE_FOG\nvarying float v_fog_factor;\n#endif\nvoid CC_TRANSFER_FOG(vec4 pos) {\n#if !CC_USE_ACCURATE_FOG\nCC_TRANSFER_FOG_BASE(pos, v_fog_factor);\n#endif\n}\nvarying highp vec4 v_shadowPos;\nuniform highp mat4 cc_matLightViewProj;\nuniform mediump vec4 cc_shadowWHPBInfo;\nuniform mediump vec4 cc_shadowLPNNInfo;\n#if CC_RECEIVE_SHADOW\nuniform highp sampler2D cc_shadowMap;\nuniform highp sampler2D cc_spotLightingMap;\n#endif\n#if CC_RECEIVE_SHADOW\nvec2 CCGetShadowBias()\n{\n#if USE_INSTANCING\nreturn vec2(a_localShadowBias.x + cc_shadowWHPBInfo.w, a_localShadowBias.y + cc_shadowLPNNInfo.z);\n#else\nreturn vec2(cc_localShadowBias.x + cc_shadowWHPBInfo.w, cc_localShadowBias.y + cc_shadowLPNNInfo.z);\n#endif\n}\n#endif\n#if USE_VERTEX_COLOR\nattribute vec4 a_color;\nvarying vec4 v_color;\n#endif\nvarying vec3 v_position;\nvarying vec3 v_normal;\nvarying vec2 v_uv;\nvarying vec2 v_uv1;\n#if CC_RECEIVE_SHADOW\nvarying vec2 v_shadowBias;\n#endif\n#if USE_NORMAL_MAP\nvarying vec3 v_tangent;\nvarying vec3 v_bitangent;\n#endif\n#if HAS_SECOND_UV || USE_LIGHTMAP\nattribute vec2 a_texCoord1;\n#endif\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nvarying vec3 v_luv;\nvoid CCLightingMapCaclUV()\n{\n#if !USE_INSTANCING\nv_luv.xy = cc_lightingMapUVParam.xy + a_texCoord1 * cc_lightingMapUVParam.zw;\nv_luv.z = cc_lightingMapUVParam.z;\n#else\nv_luv.xy = a_lightingMapUVParam.xy + a_texCoord1 * a_lightingMapUVParam.zw;\nv_luv.z = a_lightingMapUVParam.z;\n#endif\n}\n#endif\nvoid main () {\nStandardVertInput In;\nCCVertInput(In);\nmat4 matWorld, matWorldIT;\nCCGetWorldMatrixFull(matWorld, matWorldIT);\nvec4 pos = matWorld * In.position;\nv_position = pos.xyz;\nv_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n#if CC_RECEIVE_SHADOW\nv_shadowBias = CCGetShadowBias();\n#endif\n#if USE_TWOSIDE\nvec3 viewDirect = normalize(cc_cameraPos.xyz - v_position);\nv_normal *= dot(v_normal, viewDirect) < 0.0 ? -1.0 : 1.0;\n#endif\n#if USE_NORMAL_MAP\nv_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\nv_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n#endif\nv_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n#if SAMPLE_FROM_RT\nv_uv = cc_cameraPos.w > 1.0 ? vec2(v_uv.x, 1.0 - v_uv.y) : v_uv;\n#endif\n#if HAS_SECOND_UV\nv_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n#if SAMPLE_FROM_RT\nv_uv1 = cc_cameraPos.w > 1.0 ? vec2(v_uv1.x, 1.0 - v_uv1.y) : v_uv1;\n#endif\n#endif\n#if USE_VERTEX_COLOR\nv_color = a_color;\n#endif\nCC_TRANSFER_FOG(pos);\nv_shadowPos = cc_matLightViewProj * pos;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nCCLightingMapCaclUV();\n#endif\ngl_Position = cc_matProj * (cc_matView * matWorld) * In.position;\n}", - "frag": "\n#ifdef GL_EXT_draw_buffers\n#extension GL_EXT_draw_buffers: enable\n#endif\n#ifdef GL_OES_standard_derivatives\n#extension GL_OES_standard_derivatives: enable\n#endif\n#ifdef GL_EXT_shader_texture_lod\n#extension GL_EXT_shader_texture_lod: enable\n#endif\nprecision highp float;\nuniform highp mat4 cc_matView;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_mainLitDir;\nuniform mediump vec4 cc_mainLitColor;\nuniform mediump vec4 cc_ambientSky;\nuniform mediump vec4 cc_ambientGround;\nuniform mediump vec4 cc_fogColor;\nuniform mediump vec4 cc_fogBase;\nuniform mediump vec4 cc_fogAdd;\nuniform mediump vec4 cc_nearFar;\nuniform mediump vec4 cc_viewPort;\nuniform vec4 albedo;\nuniform vec4 albedoScaleAndCutoff;\nuniform vec4 pbrParams;\nuniform vec4 emissive;\nuniform vec4 emissiveScaleParam;\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\nvoid CC_APPLY_FOG_BASE(inout vec4 color, float factor) {\ncolor = vec4(mix(cc_fogColor.rgb, color.rgb, factor), color.a);\n}\n#if !CC_USE_ACCURATE_FOG\nvarying float v_fog_factor;\n#endif\nvoid CC_APPLY_FOG(inout vec4 color) {\n#if !CC_USE_ACCURATE_FOG\nCC_APPLY_FOG_BASE(color, v_fog_factor);\n#endif\n}\nvoid CC_APPLY_FOG(inout vec4 color, vec3 worldPos) {\n#if CC_USE_ACCURATE_FOG\nfloat factor;\nCC_TRANSFER_FOG_BASE(vec4(worldPos, 1.0), factor);\n#else\nfloat factor = v_fog_factor;\n#endif\nCC_APPLY_FOG_BASE(color, factor);\n}\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nuniform highp mat4 cc_matLightView;\nuniform highp vec4 cc_shadowInvProjDepthInfo;\nuniform highp vec4 cc_shadowProjDepthInfo;\nuniform highp vec4 cc_shadowProjInfo;\nuniform mediump vec4 cc_shadowNFLSInfo;\nuniform mediump vec4 cc_shadowWHPBInfo;\nuniform mediump vec4 cc_shadowLPNNInfo;\nhighp float unpackHighpData (float mainPart, float modPart) {\nhighp float data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out float mainPart, out float modPart, highp float data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp float unpackHighpData (float mainPart, float modPart, const float modValue) {\nhighp float data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out float mainPart, out float modPart, highp float data, const float modValue) {\nhighp float divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\nhighp vec2 unpackHighpData (vec2 mainPart, vec2 modPart) {\nhighp vec2 data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out vec2 mainPart, out vec2 modPart, highp vec2 data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp vec2 unpackHighpData (vec2 mainPart, vec2 modPart, const float modValue) {\nhighp vec2 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out vec2 mainPart, out vec2 modPart, highp vec2 data, const float modValue) {\nhighp vec2 divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\nhighp vec3 unpackHighpData (vec3 mainPart, vec3 modPart) {\nhighp vec3 data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out vec3 mainPart, out vec3 modPart, highp vec3 data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp vec3 unpackHighpData (vec3 mainPart, vec3 modPart, const float modValue) {\nhighp vec3 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out vec3 mainPart, out vec3 modPart, highp vec3 data, const float modValue) {\nhighp vec3 divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\nhighp vec4 unpackHighpData (vec4 mainPart, vec4 modPart) {\nhighp vec4 data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out vec4 mainPart, out vec4 modPart, highp vec4 data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp vec4 unpackHighpData (vec4 mainPart, vec4 modPart, const float modValue) {\nhighp vec4 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out vec4 mainPart, out vec4 modPart, highp vec4 data, const float modValue) {\nhighp vec4 divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\n#if USE_BATCHING\n#endif\nfloat CCGetLinearDepthFromViewSpace(vec3 viewPos) {\nfloat dist = length(viewPos);\nreturn (dist - cc_shadowNFLSInfo.x) / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x);\n}\nfloat CCGetLinearDepth(vec3 worldPos) {\nvec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0);\nreturn CCGetLinearDepthFromViewSpace(viewStartPos.xyz);\n}\n#if CC_RECEIVE_SHADOW\nuniform highp sampler2D cc_shadowMap;\nuniform highp sampler2D cc_spotLightingMap;\nvec4 ApplyShadowDepthBias_FaceNormal(vec4 shadowPos, vec3 worldNormal, float normalBias)\n{\nvec4 newShadowPos = shadowPos;\nif(normalBias > 0.0001)\n{\nvec4 viewNormal = cc_matLightView * vec4(worldNormal, 0.0);\nif(viewNormal.z < 0.1)\nnewShadowPos.xy += viewNormal.xy * cc_shadowProjInfo.xy * normalBias * clamp(viewNormal.z, 0.001, 0.1);\n}\nreturn newShadowPos;\n}\nvec4 ApplyShadowDepthBias_Perspective(vec4 shadowPos, float viewspaceDepthBias)\n{\nvec3 viewSpacePos;\nviewSpacePos.xy = shadowPos.xy * cc_shadowProjInfo.zw;\nviewSpacePos.z = shadowPos.z * cc_shadowInvProjDepthInfo.x + shadowPos.w * cc_shadowInvProjDepthInfo.y;\nviewSpacePos.xyz += cc_shadowProjDepthInfo.z * normalize(viewSpacePos.xyz) * viewspaceDepthBias;\nvec4 clipSpacePos;\nclipSpacePos.xy = viewSpacePos.xy * cc_shadowProjInfo.xy;\nclipSpacePos.zw = viewSpacePos.z * cc_shadowProjDepthInfo.xz + vec2(cc_shadowProjDepthInfo.y, 0.0);\nif (cc_shadowNFLSInfo.z > 0.000001) {\nclipSpacePos.z = CCGetLinearDepthFromViewSpace(viewSpacePos.xyz);\nclipSpacePos.z = (clipSpacePos.z * 2.0 - 1.0) * clipSpacePos.w;\n}\nreturn clipSpacePos;\n}\nvec4 ApplyShadowDepthBias_Orthographic(vec4 shadowPos, float viewspaceDepthBias)\n{\nfloat coeffA = cc_shadowProjDepthInfo.x;\nfloat coeffB = cc_shadowProjDepthInfo.y;\nfloat viewSpacePos_z = (shadowPos.z - coeffB) / coeffA;\nviewSpacePos_z += viewspaceDepthBias;\nvec4 result = shadowPos;\nresult.z = viewSpacePos_z * coeffA + coeffB;\nreturn result;\n}\nfloat CCGetShadowFactorHard (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture2D(cc_shadowMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n} else {\nclosestDepth = texture2D(cc_shadowMap, clipPos.xy).x;\n}\nshadow = step(clipPos.z, closestDepth);\nreturn shadow;\n}\nfloat CCGetShadowFactorSoft (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x);\nblock1 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)).x);\nblock2 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)).x);\nblock3 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetShadowFactorSoft2X (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock4 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock5 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock6 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock7 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock8 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)).x);\nblock1 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)).x);\nblock2 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)).x);\nblock3 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)).x);\nblock4 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x);\nblock5 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)).x);\nblock6 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)).x);\nblock7 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)).x);\nblock8 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCGetSpotLightShadowFactorHard (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nfloat depth = clipPos.z;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture2D(cc_spotLightingMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n} else {\nclosestDepth = texture2D(cc_spotLightingMap, clipPos.xy).x;\n}\nshadow = step(depth, closestDepth);\nreturn shadow;\n}\nfloat CCGetSpotLightShadowFactorSoft (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nvec2 oneTap = 1.0 / cc_shadowWHPBInfo.xy;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x);\nblock1 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)).x);\nblock2 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)).x);\nblock3 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * cc_shadowWHPBInfo.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY = mod(clipPos.y, oneTap.y) * cc_shadowWHPBInfo.y;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetSpotLightShadowFactorSoft2X (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock4 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock5 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock6 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock7 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock8 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)).x);\nblock1 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)).x);\nblock2 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)).x);\nblock3 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)).x);\nblock4 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x);\nblock5 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)).x);\nblock6 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)).x);\nblock7 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)).x);\nblock8 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCSpotShadowFactorBase(vec4 shadowPos, vec3 worldPos, vec2 shadowBias)\n{\nfloat pcf = cc_shadowWHPBInfo.z;\nif (pcf > 1.9) {\nreturn CCGetSpotLightShadowFactorSoft2X(shadowPos, worldPos, shadowBias.x);\n}else if (pcf > 0.9) {\nreturn CCGetSpotLightShadowFactorSoft(shadowPos, worldPos, shadowBias.x);\n}else {\nreturn CCGetSpotLightShadowFactorHard(shadowPos, worldPos, shadowBias.x);\n}\n}\nfloat CCShadowFactorBase(vec4 shadowPos, vec3 N, vec2 shadowBias)\n{\nfloat realtimeShadow = 1.0;\nvec4 pos = ApplyShadowDepthBias_FaceNormal(shadowPos, N, shadowBias.y);\nfloat pcf = cc_shadowWHPBInfo.z;\nif (pcf > 1.9) {\nrealtimeShadow = CCGetShadowFactorSoft2X(pos, shadowBias.x);\n}else if (pcf > 0.9) {\nrealtimeShadow = CCGetShadowFactorSoft(pos, shadowBias.x);\n}else {\nrealtimeShadow = CCGetShadowFactorHard(pos, shadowBias.x);\n}\nreturn mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w);\n}\n#endif\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\n#ifdef GL_EXT_shader_texture_lod\nreturn texture2DLodEXT(tex, coord, lod);\n#else\nreturn texture2D(tex, coord, lod);\n#endif\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\n#ifdef GL_EXT_shader_texture_lod\nreturn textureCubeLodEXT(tex, coord, lod);\n#else\nreturn textureCube(tex, coord, lod);\n#endif\n}\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(1.1, rgbe.a * 255.0 - 128.0);\n}\n#if CC_USE_DIFFUSEMAP\nuniform samplerCube cc_diffuseMap;\n#endif\n#endif\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\nvec3 NxH = cross(N, H);\nfloat OneMinusNoHSqr = dot(NxH, NxH);\nfloat a = roughness * roughness;\nfloat n = NoH * a;\nfloat p = a / (OneMinusNoHSqr + n * n);\nreturn p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\nreturn (roughness * 0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\nconst vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\nconst vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\nvec4 r = roughness * c0 + c1;\nfloat a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;\nvec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;\nAB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\nreturn specular * AB.x + AB.y;\n}\n#if USE_REFLECTION_DENOISE\nvec3 GetEnvReflectionWithMipFiltering(vec3 R, float roughness, float mipCount, float denoiseIntensity) {\n#if CC_USE_IBL\nfloat mip = roughness * mipCount;\nfloat delta = (dot(dFdx(R), dFdy(R))) * 1000.0;\nfloat mipBias = mix(0.0, 5.0, clamp(delta, 0.0, 1.0));\nvec4 biased = fragTextureLod(cc_environment, R, mip + mipBias);\nvec4 filtered = textureCube(cc_environment, R);\n#if CC_USE_IBL == 2\nbiased.rgb = unpackRGBE(biased);\nfiltered.rgb = unpackRGBE(filtered);\n#else\nbiased.rgb = SRGBToLinear(biased.rgb);\nfiltered.rgb = SRGBToLinear(filtered.rgb);\n#endif\nreturn mix(biased.rgb, filtered.rgb, denoiseIntensity);\n#else\nreturn vec3(0.0, 0.0, 0.0);\n#endif\n}\n#endif\nstruct StandardSurface {\nvec4 albedo;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nvec3 position, position_fract_part;\n#else\nvec3 position;\n#endif\nvec3 normal;\nvec3 emissive;\nvec3 lightmap;\nfloat lightmap_test;\nfloat roughness;\nfloat metallic;\nfloat occlusion;\n#if CC_RECEIVE_SHADOW\nvec2 shadowBias;\n#endif\n};\nvec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.0);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 L = normalize(-cc_mainLitDir.xyz);\nvec3 H = normalize(L + V);\nfloat NH = max(dot(N, H), 0.0);\nfloat NL = max(dot(N, L), 0.0);\nvec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w;\nvec3 diffuseContrib = diffuse;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nif (s.lightmap_test > 0.0001) {\nfinalColor = s.lightmap.rgb;\n}\n#else\ndiffuseContrib /= PI;\n#endif\nvec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\nvec3 dirlightContrib = (diffuseContrib + specularContrib);\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (NL > 0.0 && cc_mainLitDir.w > 0.0) {\nshadow = CCShadowFactorBase(shadowPos, N, s.shadowBias);\n}\n#endif\ndirlightContrib *= shadow;\nfinalColor *= dirlightContrib;\nfloat fAmb = 0.5 - N.y * 0.5;\nvec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb);\n#if CC_USE_IBL\n#if CC_USE_DIFFUSEMAP\nvec4 diffuseMap = textureCube(cc_diffuseMap, N);\n#if CC_USE_DIFFUSEMAP == 2\nambDiff = unpackRGBE(diffuseMap);\n#else\nambDiff = SRGBToLinear(diffuseMap.rgb);\n#endif\n#endif\nvec3 R = normalize(reflect(-V, N));\n#if USE_REFLECTION_DENOISE\nvec3 env = GetEnvReflectionWithMipFiltering(R, s.roughness, cc_ambientGround.w, 0.6);\n#else\nvec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n#if CC_USE_IBL == 2\nvec3 env = unpackRGBE(envmap);\n#else\nvec3 env = SRGBToLinear(envmap.rgb);\n#endif\n#endif\nfinalColor += env * cc_ambientSky.w * specular * s.occlusion;\n#endif\nfinalColor += ambDiff.rgb * cc_ambientSky.w * diffuse * s.occlusion;\nfinalColor += s.emissive;\nreturn vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = ACESToneMap(color.rgb);\n#endif\ncolor.rgb = sqrt(color.rgb);\nreturn color;\n}\nvarying highp vec4 v_shadowPos;\n#if CC_RECEIVE_SHADOW\n#endif\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nvarying vec3 v_luv;\nuniform sampler2D cc_lightingMap;\nvec3 UnpackLightingmap(vec4 color) {\nvec3 c;\nfloat e = 1.0 + color.a * (8.0 - 1.0);\nc.r = color.r * e;\nc.g = color.g * e;\nc.b = color.b * e;\nreturn c;\n}\n#endif\nvarying vec3 v_position;\nvarying vec2 v_uv;\nvarying vec2 v_uv1;\nvarying vec3 v_normal;\n#if CC_RECEIVE_SHADOW\nvarying vec2 v_shadowBias;\n#endif\n#if USE_VERTEX_COLOR\nvarying vec4 v_color;\n#endif\n#if USE_ALBEDO_MAP\nuniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\nvarying vec3 v_tangent;\nvarying vec3 v_bitangent;\nuniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\nuniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\nuniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\nuniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\nuniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\nvec4 baseColor = albedo;\n#if USE_VERTEX_COLOR\nbaseColor.rgb *= SRGBToLinear(v_color.rgb);\nbaseColor.a *= v_color.a;\n#endif\n#if USE_ALBEDO_MAP\nvec4 texColor = texture2D(albedoMap, ALBEDO_UV);\ntexColor.rgb = SRGBToLinear(texColor.rgb);\nbaseColor *= texColor;\n#endif\ns.albedo = baseColor;\ns.albedo.rgb *= albedoScaleAndCutoff.xyz;\n#if USE_ALPHA_TEST\nif (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n#endif\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nvec4 lightColor = texture2D(cc_lightingMap, v_luv.xy);\ns.lightmap = UnpackLightingmap(lightColor);\ns.lightmap_test = v_luv.z;\n#endif\ns.normal = v_normal;\n#if CC_RECEIVE_SHADOW\ns.shadowBias = v_shadowBias;\n#endif\n#if USE_NORMAL_MAP\nvec3 nmmp = texture2D(normalMap, NORMAL_UV).xyz - vec3(0.5);\ns.normal =\n(nmmp.x * emissiveScaleParam.w) * normalize(v_tangent) +\n(nmmp.y * emissiveScaleParam.w) * normalize(v_bitangent) +\nnmmp.z * normalize(s.normal);\n#endif\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\npackHighpData(s.position, s.position_fract_part, v_position);\n#else\ns.position = v_position;\n#endif\nvec4 pbr = pbrParams;\n#if USE_PBR_MAP\nvec4 res = texture2D(pbrMap, PBR_UV);\npbr.x *= res.r;\npbr.y *= res.g;\npbr.z *= res.b;\npbr.w *= res.a;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\nvec4 metallicRoughness = texture2D(metallicRoughnessMap, PBR_UV);\npbr.z *= metallicRoughness.b;\npbr.y *= metallicRoughness.g;\n#endif\n#if USE_OCCLUSION_MAP\npbr.x *= texture2D(occlusionMap, PBR_UV).r;\n#endif\ns.occlusion = pbr.x;\ns.roughness = pbr.y;\ns.metallic = pbr.z;\ns.emissive = emissive.rgb * emissiveScaleParam.xyz;\n#if USE_EMISSIVE_MAP\ns.emissive *= SRGBToLinear(texture2D(emissiveMap, EMISSIVE_UV).rgb);\n#endif\n}\n#if CC_FORWARD_ADD\n#if CC_PIPELINE_TYPE == 0\n#define LIGHTS_PER_PASS 1\n#else\n#define LIGHTS_PER_PASS 10\n#endif\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0\nuniform highp vec4 cc_lightPos[LIGHTS_PER_PASS];\nuniform vec4 cc_lightColor[LIGHTS_PER_PASS];\nuniform vec4 cc_lightSizeRangeAngle[LIGHTS_PER_PASS];\nuniform vec4 cc_lightDir[LIGHTS_PER_PASS];\n#endif\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\nfloat factor = distSqr * invSqrAttRadius;\nfloat smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\nreturn smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\nfloat attenuation = 1.0 / max(distSqr, 0.01*0.01);\nattenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\nreturn attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\nfloat cd = dot(litDir, L);\nfloat attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\nreturn (attenuation * attenuation);\n}\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0\nvec4 CCStandardShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / PI;\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.0);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nint numLights = CC_PIPELINE_TYPE == 0 ? LIGHTS_PER_PASS : int(cc_lightDir[0].w);\nfor (int i = 0; i < LIGHTS_PER_PASS; i++) {\nif (i >= numLights) break;\nvec3 SLU = cc_lightPos[i].xyz - position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.0);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = cc_lightSizeRangeAngle[i].x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = PI * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(cc_lightSizeRangeAngle[i].y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (cc_lightPos[i].w > 0.0) {\nfloat cosInner = max(dot(-cc_lightDir[i].xyz, SL), 0.01);\nfloat cosOuter = cc_lightSizeRangeAngle[i].z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -cc_lightDir[i].xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = cc_lightColor[i].rgb;\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (cc_lightPos[i].w > 0.0 && cc_lightSizeRangeAngle[i].w > 0.0) {\nshadow = CCSpotShadowFactorBase(shadowPos, position, s.shadowBias);\n}\n#endif\nlightColor *= shadow;\nfinalColor += SNL * lightColor * cc_lightColor[i].w * illum * att * (diffuseContrib + lspec);\n}\nreturn vec4(finalColor, 0.0);\n}\n#endif\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1\nreadonly buffer b_ccLightsBuffer { vec4 b_ccLights[]; };\nreadonly buffer b_clusterLightIndicesBuffer { uint b_clusterLightIndices[]; };\nreadonly buffer b_clusterLightGridBuffer { uvec4 b_clusterLightGrid[]; };\nstruct CCLight\n{\nvec4 cc_lightPos;\nvec4 cc_lightColor;\nvec4 cc_lightSizeRangeAngle;\nvec4 cc_lightDir;\n};\nstruct Cluster\n{\nvec3 minBounds;\nvec3 maxBounds;\n};\nstruct LightGrid\n{\nuint offset;\nuint ccLights;\n};\nCCLight getCCLight(uint i)\n{\nCCLight light;\nlight.cc_lightPos = b_ccLights[4u * i + 0u];\nlight.cc_lightColor = b_ccLights[4u * i + 1u];\nlight.cc_lightSizeRangeAngle = b_ccLights[4u * i + 2u];\nlight.cc_lightDir = b_ccLights[4u * i + 3u];\nreturn light;\n}\nLightGrid getLightGrid(uint cluster)\n{\nuvec4 gridvec = b_clusterLightGrid[cluster];\nLightGrid grid;\ngrid.offset = gridvec.x;\ngrid.ccLights = gridvec.y;\nreturn grid;\n}\nuint getGridLightIndex(uint start, uint offset)\n{\nreturn b_clusterLightIndices[start + offset];\n}\nuint getClusterZIndex(vec4 worldPos)\n{\nfloat scale = float(24) / log(cc_nearFar.y / cc_nearFar.x);\nfloat bias = -(float(24) * log(cc_nearFar.x) / log(cc_nearFar.y / cc_nearFar.x));\nfloat eyeDepth = -(cc_matView * worldPos).z;\nuint zIndex = uint(max(log(eyeDepth) * scale + bias, 0.0));\nreturn zIndex;\n}\nuint getClusterIndex(vec4 fragCoord, vec4 worldPos)\n{\nuint zIndex = getClusterZIndex(worldPos);\nfloat clusterSizeX = ceil(cc_viewPort.z / float(16));\nfloat clusterSizeY = ceil(cc_viewPort.w / float(8));\nuvec3 indices = uvec3(uvec2(fragCoord.xy / vec2(clusterSizeX, clusterSizeY)), zIndex);\nuint cluster = (16u * 8u) * indices.z + 16u * indices.y + indices.x;\nreturn cluster;\n}\nvec4 CCClusterShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / PI;\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nuint cluster = getClusterIndex(gl_FragCoord, vec4(position, 1.0));\nLightGrid grid = getLightGrid(cluster);\nuint numLights = grid.ccLights;\nfor (uint i = 0u; i < 100u; i++) {\nif (i >= numLights) break;\nuint lightIndex = getGridLightIndex(grid.offset, i);\nCCLight light = getCCLight(lightIndex);\nvec3 SLU = light.cc_lightPos.xyz - position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.001);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = light.cc_lightSizeRangeAngle.x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = PI * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(light.cc_lightSizeRangeAngle.y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (light.cc_lightPos.w > 0.0) {\nfloat cosInner = max(dot(-light.cc_lightDir.xyz, SL), 0.01);\nfloat cosOuter = light.cc_lightSizeRangeAngle.z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -light.cc_lightDir.xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = light.cc_lightColor.rgb;\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (light.cc_lightPos.w > 0.0) {\nshadow = CCSpotShadowFactorBase(shadowPos, position, s.shadowBias);\n}\n#endif\nlightColor *= shadow;\nfinalColor += SNL * lightColor * light.cc_lightColor.w * illum * att * (diffuseContrib + lspec);\n}\nreturn vec4(finalColor, 0.0);\n}\n#endif\nvoid main () {\nStandardSurface s; surf(s);\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1\nvec4 color = CCClusterShadingAdditive(s, v_shadowPos);\n#else\nvec4 color = CCStandardShadingAdditive(s, v_shadowPos);\n#endif\nCC_APPLY_FOG(color, s.position.xyz);\ngl_FragData[0] = CCFragOutput(color);\n}\n#elif (CC_PIPELINE_TYPE == 0 || CC_FORCE_FORWARD_SHADING)\nvoid main () {\nStandardSurface s; surf(s);\nvec4 color = CCStandardShadingBase(s, v_shadowPos);\nCC_APPLY_FOG(color, s.position.xyz);\ngl_FragData[0] = CCFragOutput(color);\n}\n#elif CC_PIPELINE_TYPE == 1\nvec2 signNotZero(vec2 v) {\nreturn vec2((v.x >= 0.0) ? +1.0 : -1.0, (v.y >= 0.0) ? +1.0 : -1.0);\n}\nvec2 float32x3_to_oct(in vec3 v) {\nvec2 p = v.xy * (1.0 / (abs(v.x) + abs(v.y) + abs(v.z)));\nreturn (v.z <= 0.0) ? ((1.0 - abs(p.yx)) * signNotZero(p)) : p;\n}\nvoid main () {\nStandardSurface s; surf(s);\ngl_FragData[0] = s.albedo;\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\ngl_FragData[1] = vec4(position, s.roughness);\ngl_FragData[1] = vec4(float32x3_to_oct(s.normal), s.roughness, s.metallic);\nfragColor3 = vec4(s.emissive, s.occlusion);\n}\n#endif", - }, - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nattribute vec4 a_tangent;\n#if USE_INSTANCING\nattribute vec4 a_matWorld0;\nattribute vec4 a_matWorld1;\nattribute vec4 a_matWorld2;\n#if USE_LIGHTMAP\nattribute vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nattribute vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nattribute float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nattribute float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_joints;\nattribute vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 uv = getPixelCoordFromLocation(location, cc_displacementTextureInfo.xy);\nreturn texture2D(tex, uv);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture2D(tex, x)),\ndecode32(texture2D(tex, y)),\ndecode32(texture2D(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nattribute highp vec4 a_jointAnimInfo;\n#endif\nuniform highp vec4 cc_jointTextureInfo;\nuniform highp vec4 cc_jointAnimInfo;\nuniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nuniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\n#if USE_BATCHING\nuniform highp mat4 cc_matWorlds[10];\n#endif\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matWorldIT;\nvoid CCGetWorldMatrixFull(out mat4 matWorld, out mat4 matWorldIT)\n{\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\nmatWorldIT = matWorld;\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\nmatWorldIT = matWorld;\n#else\nmatWorld = cc_matWorld;\nmatWorldIT = cc_matWorldIT;\n#endif\n}\nuniform vec4 tilingOffset;\nuniform highp mat4 cc_matLightViewProj;\n#if HAS_SECOND_UV || USE_LIGHTMAP\nattribute vec2 a_texCoord1;\n#endif\nvarying vec2 v_uv;\nvarying vec2 v_uv1;\nvarying vec4 v_worldPos;\nvarying float v_clip_depth;\nvec4 vert () {\nStandardVertInput In;\nCCVertInput(In);\nmat4 matWorld, matWorldIT;\nCCGetWorldMatrixFull(matWorld, matWorldIT);\nv_worldPos = matWorld * In.position;\nvec4 clipPos = cc_matLightViewProj * v_worldPos;\nv_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n#if HAS_SECOND_UV\nv_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n#endif\nv_clip_depth = clipPos.z / clipPos.w * 0.5 + 0.5;\nreturn clipPos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\nuniform vec4 albedo;\nuniform vec4 albedoScaleAndCutoff;\nvec4 packDepthToRGBA (float depth) {\nvec4 ret = vec4(1.0, 255.0, 65025.0, 16581375.0) * depth;\nret = fract(ret);\nret -= vec4(ret.yzw, 0.0) / 255.0;\nreturn ret;\n}\nuniform highp mat4 cc_matLightView;\nuniform mediump vec4 cc_shadowNFLSInfo;\nuniform mediump vec4 cc_shadowLPNNInfo;\n#if USE_BATCHING\n#endif\nfloat CCGetLinearDepthFromViewSpace(vec3 viewPos) {\nfloat dist = length(viewPos);\nreturn (dist - cc_shadowNFLSInfo.x) / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x);\n}\nfloat CCGetLinearDepth(vec3 worldPos) {\nvec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0);\nreturn CCGetLinearDepthFromViewSpace(viewStartPos.xyz);\n}\n#if CC_RECEIVE_SHADOW\nuniform highp sampler2D cc_shadowMap;\nuniform highp sampler2D cc_spotLightingMap;\n#endif\nvarying vec2 v_uv;\nvarying vec2 v_uv1;\nvarying vec4 v_worldPos;\nvarying float v_clip_depth;\n#if USE_ALBEDO_MAP\nuniform sampler2D albedoMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvec4 frag () {\nvec4 baseColor = albedo;\n#if USE_ALBEDO_MAP\nbaseColor *= texture2D(albedoMap, ALBEDO_UV);\n#endif\n#if USE_ALPHA_TEST\nif (baseColor.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n#endif\nif(cc_shadowLPNNInfo.x > 0.000001 && cc_shadowLPNNInfo.x < 1.999999) {\nif (cc_shadowNFLSInfo.z > 0.000001) {\nreturn vec4(CCGetLinearDepth(v_worldPos.xyz), 1.0, 1.0, 1.0);\n}\n}\nif (cc_shadowLPNNInfo.y > 0.000001) {\nreturn packDepthToRGBA(v_clip_depth);\n}\nreturn vec4(v_clip_depth, 1.0, 1.0, 1.0);\n}\nvoid main() { gl_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nuniform highp mat4 cc_matViewProj;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_fogBase;\nuniform mediump vec4 cc_fogAdd;\n#if USE_BATCHING\n#endif\nuniform highp mat4 cc_matWorld;\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\n#if !CC_USE_ACCURATE_FOG\nvarying float v_fog_factor;\n#endif\nvoid CC_TRANSFER_FOG(vec4 pos) {\n#if !CC_USE_ACCURATE_FOG\nCC_TRANSFER_FOG_BASE(pos, v_fog_factor);\n#endif\n}\nvarying highp vec4 v_shadowPos;\nuniform highp mat4 cc_matLightViewProj;\n#if CC_RECEIVE_SHADOW\nuniform highp sampler2D cc_shadowMap;\nuniform highp sampler2D cc_spotLightingMap;\n#endif\n#if CC_RECEIVE_SHADOW\n#endif\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\n#if CC_RECEIVE_SHADOW\nvarying vec2 v_shadowBias;\n#endif\nvarying highp vec3 v_position;\nvarying mediump vec3 v_normal;\n#if USE_NORMALMAP\nvarying mediump vec3 v_tangent;\nvarying mediump vec3 v_binormal;\n#endif\nvarying mediump vec2 uvw;\nvarying mediump vec2 uv0;\nvarying mediump vec2 uv1;\nvarying mediump vec2 uv2;\nvarying mediump vec2 uv3;\nvarying mediump vec3 luv;\nvarying mediump vec3 diffuse;\nuniform vec4 UVScale;\nuniform vec4 lightMapUVParam;\nvoid main () {\nvec3 worldPos;\nworldPos.x = cc_matWorld[3][0] + a_position.x;\nworldPos.y = cc_matWorld[3][1] + a_position.y;\nworldPos.z = cc_matWorld[3][2] + a_position.z;\nvec4 pos = vec4(worldPos, 1.0);\npos = cc_matViewProj * pos;\nuvw = a_texCoord;\nuv0 = a_position.xz * UVScale.x;\nuv1 = a_position.xz * UVScale.y;\nuv2 = a_position.xz * UVScale.z;\nuv3 = a_position.xz * UVScale.w;\n#if USE_LIGHTMAP\nluv.xy = lightMapUVParam.xy + a_texCoord * lightMapUVParam.zw;\nluv.z = lightMapUVParam.z;\n#endif\nv_position = worldPos;\nv_normal = a_normal;\nCC_TRANSFER_FOG(vec4(worldPos, 1.0));\n#if CC_RECEIVE_SHADOW\nv_shadowBias = vec2(0.0, 0.0);\n#endif\n#if USE_NORMALMAP\nv_tangent = vec3(1.0, 0.0, 0.0);\nv_binormal = vec3(0.0, 0.0, 1.0);\nv_binormal = cross(v_tangent, a_normal);\nv_tangent = cross(a_normal, v_binormal);\n#endif\nv_shadowPos = cc_matLightViewProj * vec4(worldPos, 1.0);\ngl_Position = pos;\n}", - "frag": "\n#ifdef GL_EXT_draw_buffers\n#extension GL_EXT_draw_buffers: enable\n#endif\n#ifdef GL_OES_standard_derivatives\n#extension GL_OES_standard_derivatives: enable\n#endif\n#ifdef GL_EXT_shader_texture_lod\n#extension GL_EXT_shader_texture_lod: enable\n#endif\nprecision highp float;\nuniform highp mat4 cc_matView;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_mainLitDir;\nuniform mediump vec4 cc_mainLitColor;\nuniform mediump vec4 cc_ambientSky;\nuniform mediump vec4 cc_ambientGround;\nuniform mediump vec4 cc_fogColor;\nuniform mediump vec4 cc_fogBase;\nuniform mediump vec4 cc_fogAdd;\nuniform mediump vec4 cc_nearFar;\nuniform mediump vec4 cc_viewPort;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nuniform highp mat4 cc_matLightView;\nuniform highp vec4 cc_shadowInvProjDepthInfo;\nuniform highp vec4 cc_shadowProjDepthInfo;\nuniform highp vec4 cc_shadowProjInfo;\nuniform mediump vec4 cc_shadowNFLSInfo;\nuniform mediump vec4 cc_shadowWHPBInfo;\nuniform mediump vec4 cc_shadowLPNNInfo;\nhighp float unpackHighpData (float mainPart, float modPart) {\nhighp float data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out float mainPart, out float modPart, highp float data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp float unpackHighpData (float mainPart, float modPart, const float modValue) {\nhighp float data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out float mainPart, out float modPart, highp float data, const float modValue) {\nhighp float divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\nhighp vec2 unpackHighpData (vec2 mainPart, vec2 modPart) {\nhighp vec2 data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out vec2 mainPart, out vec2 modPart, highp vec2 data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp vec2 unpackHighpData (vec2 mainPart, vec2 modPart, const float modValue) {\nhighp vec2 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out vec2 mainPart, out vec2 modPart, highp vec2 data, const float modValue) {\nhighp vec2 divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\nhighp vec3 unpackHighpData (vec3 mainPart, vec3 modPart) {\nhighp vec3 data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out vec3 mainPart, out vec3 modPart, highp vec3 data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp vec3 unpackHighpData (vec3 mainPart, vec3 modPart, const float modValue) {\nhighp vec3 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out vec3 mainPart, out vec3 modPart, highp vec3 data, const float modValue) {\nhighp vec3 divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\nhighp vec4 unpackHighpData (vec4 mainPart, vec4 modPart) {\nhighp vec4 data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out vec4 mainPart, out vec4 modPart, highp vec4 data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp vec4 unpackHighpData (vec4 mainPart, vec4 modPart, const float modValue) {\nhighp vec4 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out vec4 mainPart, out vec4 modPart, highp vec4 data, const float modValue) {\nhighp vec4 divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\n#if USE_BATCHING\n#endif\nfloat CCGetLinearDepthFromViewSpace(vec3 viewPos) {\nfloat dist = length(viewPos);\nreturn (dist - cc_shadowNFLSInfo.x) / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x);\n}\nfloat CCGetLinearDepth(vec3 worldPos) {\nvec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0);\nreturn CCGetLinearDepthFromViewSpace(viewStartPos.xyz);\n}\n#if CC_RECEIVE_SHADOW\nuniform highp sampler2D cc_shadowMap;\nuniform highp sampler2D cc_spotLightingMap;\nvec4 ApplyShadowDepthBias_FaceNormal(vec4 shadowPos, vec3 worldNormal, float normalBias)\n{\nvec4 newShadowPos = shadowPos;\nif(normalBias > 0.0001)\n{\nvec4 viewNormal = cc_matLightView * vec4(worldNormal, 0.0);\nif(viewNormal.z < 0.1)\nnewShadowPos.xy += viewNormal.xy * cc_shadowProjInfo.xy * normalBias * clamp(viewNormal.z, 0.001, 0.1);\n}\nreturn newShadowPos;\n}\nvec4 ApplyShadowDepthBias_Perspective(vec4 shadowPos, float viewspaceDepthBias)\n{\nvec3 viewSpacePos;\nviewSpacePos.xy = shadowPos.xy * cc_shadowProjInfo.zw;\nviewSpacePos.z = shadowPos.z * cc_shadowInvProjDepthInfo.x + shadowPos.w * cc_shadowInvProjDepthInfo.y;\nviewSpacePos.xyz += cc_shadowProjDepthInfo.z * normalize(viewSpacePos.xyz) * viewspaceDepthBias;\nvec4 clipSpacePos;\nclipSpacePos.xy = viewSpacePos.xy * cc_shadowProjInfo.xy;\nclipSpacePos.zw = viewSpacePos.z * cc_shadowProjDepthInfo.xz + vec2(cc_shadowProjDepthInfo.y, 0.0);\nif (cc_shadowNFLSInfo.z > 0.000001) {\nclipSpacePos.z = CCGetLinearDepthFromViewSpace(viewSpacePos.xyz);\nclipSpacePos.z = (clipSpacePos.z * 2.0 - 1.0) * clipSpacePos.w;\n}\nreturn clipSpacePos;\n}\nvec4 ApplyShadowDepthBias_Orthographic(vec4 shadowPos, float viewspaceDepthBias)\n{\nfloat coeffA = cc_shadowProjDepthInfo.x;\nfloat coeffB = cc_shadowProjDepthInfo.y;\nfloat viewSpacePos_z = (shadowPos.z - coeffB) / coeffA;\nviewSpacePos_z += viewspaceDepthBias;\nvec4 result = shadowPos;\nresult.z = viewSpacePos_z * coeffA + coeffB;\nreturn result;\n}\nfloat CCGetShadowFactorHard (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture2D(cc_shadowMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n} else {\nclosestDepth = texture2D(cc_shadowMap, clipPos.xy).x;\n}\nshadow = step(clipPos.z, closestDepth);\nreturn shadow;\n}\nfloat CCGetShadowFactorSoft (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x);\nblock1 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)).x);\nblock2 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)).x);\nblock3 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetShadowFactorSoft2X (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock4 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock5 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock6 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock7 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock8 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)).x);\nblock1 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)).x);\nblock2 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)).x);\nblock3 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)).x);\nblock4 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x);\nblock5 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)).x);\nblock6 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)).x);\nblock7 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)).x);\nblock8 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCGetSpotLightShadowFactorHard (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nfloat depth = clipPos.z;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture2D(cc_spotLightingMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n} else {\nclosestDepth = texture2D(cc_spotLightingMap, clipPos.xy).x;\n}\nshadow = step(depth, closestDepth);\nreturn shadow;\n}\nfloat CCGetSpotLightShadowFactorSoft (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nvec2 oneTap = 1.0 / cc_shadowWHPBInfo.xy;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x);\nblock1 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)).x);\nblock2 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)).x);\nblock3 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * cc_shadowWHPBInfo.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY = mod(clipPos.y, oneTap.y) * cc_shadowWHPBInfo.y;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetSpotLightShadowFactorSoft2X (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock4 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock5 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock6 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock7 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock8 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)).x);\nblock1 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)).x);\nblock2 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)).x);\nblock3 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)).x);\nblock4 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x);\nblock5 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)).x);\nblock6 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)).x);\nblock7 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)).x);\nblock8 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCSpotShadowFactorBase(vec4 shadowPos, vec3 worldPos, vec2 shadowBias)\n{\nfloat pcf = cc_shadowWHPBInfo.z;\nif (pcf > 1.9) {\nreturn CCGetSpotLightShadowFactorSoft2X(shadowPos, worldPos, shadowBias.x);\n}else if (pcf > 0.9) {\nreturn CCGetSpotLightShadowFactorSoft(shadowPos, worldPos, shadowBias.x);\n}else {\nreturn CCGetSpotLightShadowFactorHard(shadowPos, worldPos, shadowBias.x);\n}\n}\nfloat CCShadowFactorBase(vec4 shadowPos, vec3 N, vec2 shadowBias)\n{\nfloat realtimeShadow = 1.0;\nvec4 pos = ApplyShadowDepthBias_FaceNormal(shadowPos, N, shadowBias.y);\nfloat pcf = cc_shadowWHPBInfo.z;\nif (pcf > 1.9) {\nrealtimeShadow = CCGetShadowFactorSoft2X(pos, shadowBias.x);\n}else if (pcf > 0.9) {\nrealtimeShadow = CCGetShadowFactorSoft(pos, shadowBias.x);\n}else {\nrealtimeShadow = CCGetShadowFactorHard(pos, shadowBias.x);\n}\nreturn mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w);\n}\n#endif\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\n#ifdef GL_EXT_shader_texture_lod\nreturn texture2DLodEXT(tex, coord, lod);\n#else\nreturn texture2D(tex, coord, lod);\n#endif\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\n#ifdef GL_EXT_shader_texture_lod\nreturn textureCubeLodEXT(tex, coord, lod);\n#else\nreturn textureCube(tex, coord, lod);\n#endif\n}\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(1.1, rgbe.a * 255.0 - 128.0);\n}\n#if CC_USE_DIFFUSEMAP\nuniform samplerCube cc_diffuseMap;\n#endif\n#endif\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\nvec3 NxH = cross(N, H);\nfloat OneMinusNoHSqr = dot(NxH, NxH);\nfloat a = roughness * roughness;\nfloat n = NoH * a;\nfloat p = a / (OneMinusNoHSqr + n * n);\nreturn p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\nreturn (roughness * 0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\nconst vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\nconst vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\nvec4 r = roughness * c0 + c1;\nfloat a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;\nvec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;\nAB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\nreturn specular * AB.x + AB.y;\n}\n#if USE_REFLECTION_DENOISE\nvec3 GetEnvReflectionWithMipFiltering(vec3 R, float roughness, float mipCount, float denoiseIntensity) {\n#if CC_USE_IBL\nfloat mip = roughness * mipCount;\nfloat delta = (dot(dFdx(R), dFdy(R))) * 1000.0;\nfloat mipBias = mix(0.0, 5.0, clamp(delta, 0.0, 1.0));\nvec4 biased = fragTextureLod(cc_environment, R, mip + mipBias);\nvec4 filtered = textureCube(cc_environment, R);\n#if CC_USE_IBL == 2\nbiased.rgb = unpackRGBE(biased);\nfiltered.rgb = unpackRGBE(filtered);\n#else\nbiased.rgb = SRGBToLinear(biased.rgb);\nfiltered.rgb = SRGBToLinear(filtered.rgb);\n#endif\nreturn mix(biased.rgb, filtered.rgb, denoiseIntensity);\n#else\nreturn vec3(0.0, 0.0, 0.0);\n#endif\n}\n#endif\nstruct StandardSurface {\nvec4 albedo;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nvec3 position, position_fract_part;\n#else\nvec3 position;\n#endif\nvec3 normal;\nvec3 emissive;\nvec3 lightmap;\nfloat lightmap_test;\nfloat roughness;\nfloat metallic;\nfloat occlusion;\n#if CC_RECEIVE_SHADOW\nvec2 shadowBias;\n#endif\n};\nvec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.0);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 L = normalize(-cc_mainLitDir.xyz);\nvec3 H = normalize(L + V);\nfloat NH = max(dot(N, H), 0.0);\nfloat NL = max(dot(N, L), 0.0);\nvec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w;\nvec3 diffuseContrib = diffuse;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nif (s.lightmap_test > 0.0001) {\nfinalColor = s.lightmap.rgb;\n}\n#else\ndiffuseContrib /= PI;\n#endif\nvec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\nvec3 dirlightContrib = (diffuseContrib + specularContrib);\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (NL > 0.0 && cc_mainLitDir.w > 0.0) {\nshadow = CCShadowFactorBase(shadowPos, N, s.shadowBias);\n}\n#endif\ndirlightContrib *= shadow;\nfinalColor *= dirlightContrib;\nfloat fAmb = 0.5 - N.y * 0.5;\nvec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb);\n#if CC_USE_IBL\n#if CC_USE_DIFFUSEMAP\nvec4 diffuseMap = textureCube(cc_diffuseMap, N);\n#if CC_USE_DIFFUSEMAP == 2\nambDiff = unpackRGBE(diffuseMap);\n#else\nambDiff = SRGBToLinear(diffuseMap.rgb);\n#endif\n#endif\nvec3 R = normalize(reflect(-V, N));\n#if USE_REFLECTION_DENOISE\nvec3 env = GetEnvReflectionWithMipFiltering(R, s.roughness, cc_ambientGround.w, 0.6);\n#else\nvec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n#if CC_USE_IBL == 2\nvec3 env = unpackRGBE(envmap);\n#else\nvec3 env = SRGBToLinear(envmap.rgb);\n#endif\n#endif\nfinalColor += env * cc_ambientSky.w * specular * s.occlusion;\n#endif\nfinalColor += ambDiff.rgb * cc_ambientSky.w * diffuse * s.occlusion;\nfinalColor += s.emissive;\nreturn vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = ACESToneMap(color.rgb);\n#endif\ncolor.rgb = sqrt(color.rgb);\nreturn color;\n}\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\nvoid CC_APPLY_FOG_BASE(inout vec4 color, float factor) {\ncolor = vec4(mix(cc_fogColor.rgb, color.rgb, factor), color.a);\n}\n#if !CC_USE_ACCURATE_FOG\nvarying float v_fog_factor;\n#endif\nvoid CC_APPLY_FOG(inout vec4 color) {\n#if !CC_USE_ACCURATE_FOG\nCC_APPLY_FOG_BASE(color, v_fog_factor);\n#endif\n}\nvoid CC_APPLY_FOG(inout vec4 color, vec3 worldPos) {\n#if CC_USE_ACCURATE_FOG\nfloat factor;\nCC_TRANSFER_FOG_BASE(vec4(worldPos, 1.0), factor);\n#else\nfloat factor = v_fog_factor;\n#endif\nCC_APPLY_FOG_BASE(color, factor);\n}\nvarying highp vec4 v_shadowPos;\n#if CC_RECEIVE_SHADOW\n#endif\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nvarying vec3 v_luv;\nuniform sampler2D cc_lightingMap;\nvec3 UnpackLightingmap(vec4 color) {\nvec3 c;\nfloat e = 1.0 + color.a * (8.0 - 1.0);\nc.r = color.r * e;\nc.g = color.g * e;\nc.b = color.b * e;\nreturn c;\n}\n#endif\nvarying highp vec3 v_position;\nvarying mediump vec3 v_normal;\n#if CC_RECEIVE_SHADOW\nvarying vec2 v_shadowBias;\n#endif\n#if USE_NORMALMAP\nvarying mediump vec3 v_tangent;\nvarying mediump vec3 v_binormal;\n#endif\nvarying mediump vec2 uvw;\nvarying mediump vec2 uv0;\nvarying mediump vec2 uv1;\nvarying mediump vec2 uv2;\nvarying mediump vec2 uv3;\nvarying mediump vec3 diffuse;\nvarying mediump vec3 luv;\nuniform vec4 metallic;\nuniform vec4 roughness;\nuniform sampler2D weightMap;\nuniform sampler2D detailMap0;\nuniform sampler2D detailMap1;\nuniform sampler2D detailMap2;\nuniform sampler2D detailMap3;\nuniform sampler2D normalMap0;\nuniform sampler2D normalMap1;\nuniform sampler2D normalMap2;\nuniform sampler2D normalMap3;\nuniform sampler2D lightMap;\nvoid surf (out StandardSurface s) {\n#if LAYERS > 1\nvec4 w = texture2D(weightMap, uvw);\n#endif\nvec4 baseColor = vec4(0, 0, 0, 0);\n#if LAYERS == 1\nbaseColor = texture2D(detailMap0, uv0);\n#elif LAYERS == 2\nbaseColor += texture2D(detailMap0, uv0) * w.r;\nbaseColor += texture2D(detailMap1, uv1) * w.g;\n#elif LAYERS == 3\nbaseColor += texture2D(detailMap0, uv0) * w.r;\nbaseColor += texture2D(detailMap1, uv1) * w.g;\nbaseColor += texture2D(detailMap2, uv2) * w.b;\n#elif LAYERS == 4\nbaseColor += texture2D(detailMap0, uv0) * w.r;\nbaseColor += texture2D(detailMap1, uv1) * w.g;\nbaseColor += texture2D(detailMap2, uv2) * w.b;\nbaseColor += texture2D(detailMap3, uv3) * w.a;\n#else\nbaseColor = texture2D(detailMap0, uv0);\n#endif\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\npackHighpData(s.position, s.position_fract_part, v_position);\n#else\ns.position = v_position;\n#endif\n#if USE_NORMALMAP\nvec4 baseNormal = vec4(0, 0, 0, 0);\n#if LAYERS == 1\nbaseNormal = texture2D(normalMap0, uv0);\n#elif LAYERS == 2\nbaseNormal += texture2D(normalMap0, uv0) * w.r;\nbaseNormal += texture2D(normalMap1, uv1) * w.g;\n#elif LAYERS == 3\nbaseNormal += texture2D(normalMap0, uv0) * w.r;\nbaseNormal += texture2D(normalMap1, uv1) * w.g;\nbaseNormal += texture2D(normalMap2, uv2) * w.b;\n#elif LAYERS == 4\nbaseNormal += texture2D(normalMap0, uv0) * w.r;\nbaseNormal += texture2D(normalMap1, uv1) * w.g;\nbaseNormal += texture2D(normalMap2, uv2) * w.b;\nbaseNormal += texture2D(normalMap3, uv3) * w.a;\n#else\nbaseNormal = texture2D(normalMap0, uv0);\n#endif\nvec3 nmmp = baseNormal.xyz - vec3(0.5);\ns.normal =\nnmmp.x * normalize(v_tangent) +\nnmmp.y * normalize(v_binormal) +\nnmmp.z * normalize(v_normal);\n#else\ns.normal = v_normal;\n#endif\n#if CC_RECEIVE_SHADOW\ns.shadowBias = v_shadowBias;\n#endif\ns.albedo = vec4(SRGBToLinear(baseColor.rgb), 1.0);\ns.occlusion = 1.0;\n#if USE_PBR\ns.roughness = 0.0;\n#if LAYERS == 1\ns.roughness = roughness.x;\n#elif LAYERS == 2\ns.roughness += roughness.x * w.r;\ns.roughness += roughness.y * w.g;\n#elif LAYERS == 3\ns.roughness += roughness.x * w.r;\ns.roughness += roughness.y * w.g;\ns.roughness += roughness.z * w.b;\n#elif LAYERS == 4\ns.roughness += roughness.x * w.r;\ns.roughness += roughness.y * w.g;\ns.roughness += roughness.z * w.b;\ns.roughness += roughness.w * w.a;\n#else\ns.roughness = 1.0;\n#endif\ns.metallic = 0.0;\n#if LAYERS == 1\ns.metallic = metallic.x;\n#elif LAYERS == 2\ns.metallic += metallic.x * w.r;\ns.metallic += metallic.y * w.g;\n#elif LAYERS == 3\ns.metallic += metallic.x * w.r;\ns.metallic += metallic.y * w.g;\ns.metallic += metallic.z * w.b;\n#elif LAYERS == 4\ns.metallic += metallic.x * w.r;\ns.metallic += metallic.y * w.g;\ns.metallic += metallic.z * w.b;\ns.metallic += metallic.w * w.a;\n#else\ns.metallic = 0.0;\n#endif\n#else\ns.roughness = 1.0;\ns.metallic = 0.0;\n#endif\ns.emissive = vec3(0.0, 0.0, 0.0);\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nvec4 lightColor = texture2D(lightMap, luv.xy);\ns.lightmap = UnpackLightingmap(lightColor);\ns.lightmap_test = luv.z;\n#endif\n}\n#if CC_FORWARD_ADD\n#if CC_PIPELINE_TYPE == 0\n#define LIGHTS_PER_PASS 1\n#else\n#define LIGHTS_PER_PASS 10\n#endif\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0\nuniform highp vec4 cc_lightPos[LIGHTS_PER_PASS];\nuniform vec4 cc_lightColor[LIGHTS_PER_PASS];\nuniform vec4 cc_lightSizeRangeAngle[LIGHTS_PER_PASS];\nuniform vec4 cc_lightDir[LIGHTS_PER_PASS];\n#endif\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\nfloat factor = distSqr * invSqrAttRadius;\nfloat smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\nreturn smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\nfloat attenuation = 1.0 / max(distSqr, 0.01*0.01);\nattenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\nreturn attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\nfloat cd = dot(litDir, L);\nfloat attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\nreturn (attenuation * attenuation);\n}\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0\nvec4 CCStandardShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / PI;\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.0);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nint numLights = CC_PIPELINE_TYPE == 0 ? LIGHTS_PER_PASS : int(cc_lightDir[0].w);\nfor (int i = 0; i < LIGHTS_PER_PASS; i++) {\nif (i >= numLights) break;\nvec3 SLU = cc_lightPos[i].xyz - position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.0);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = cc_lightSizeRangeAngle[i].x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = PI * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(cc_lightSizeRangeAngle[i].y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (cc_lightPos[i].w > 0.0) {\nfloat cosInner = max(dot(-cc_lightDir[i].xyz, SL), 0.01);\nfloat cosOuter = cc_lightSizeRangeAngle[i].z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -cc_lightDir[i].xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = cc_lightColor[i].rgb;\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (cc_lightPos[i].w > 0.0 && cc_lightSizeRangeAngle[i].w > 0.0) {\nshadow = CCSpotShadowFactorBase(shadowPos, position, s.shadowBias);\n}\n#endif\nlightColor *= shadow;\nfinalColor += SNL * lightColor * cc_lightColor[i].w * illum * att * (diffuseContrib + lspec);\n}\nreturn vec4(finalColor, 0.0);\n}\n#endif\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1\nreadonly buffer b_ccLightsBuffer { vec4 b_ccLights[]; };\nreadonly buffer b_clusterLightIndicesBuffer { uint b_clusterLightIndices[]; };\nreadonly buffer b_clusterLightGridBuffer { uvec4 b_clusterLightGrid[]; };\nstruct CCLight\n{\nvec4 cc_lightPos;\nvec4 cc_lightColor;\nvec4 cc_lightSizeRangeAngle;\nvec4 cc_lightDir;\n};\nstruct Cluster\n{\nvec3 minBounds;\nvec3 maxBounds;\n};\nstruct LightGrid\n{\nuint offset;\nuint ccLights;\n};\nCCLight getCCLight(uint i)\n{\nCCLight light;\nlight.cc_lightPos = b_ccLights[4u * i + 0u];\nlight.cc_lightColor = b_ccLights[4u * i + 1u];\nlight.cc_lightSizeRangeAngle = b_ccLights[4u * i + 2u];\nlight.cc_lightDir = b_ccLights[4u * i + 3u];\nreturn light;\n}\nLightGrid getLightGrid(uint cluster)\n{\nuvec4 gridvec = b_clusterLightGrid[cluster];\nLightGrid grid;\ngrid.offset = gridvec.x;\ngrid.ccLights = gridvec.y;\nreturn grid;\n}\nuint getGridLightIndex(uint start, uint offset)\n{\nreturn b_clusterLightIndices[start + offset];\n}\nuint getClusterZIndex(vec4 worldPos)\n{\nfloat scale = float(24) / log(cc_nearFar.y / cc_nearFar.x);\nfloat bias = -(float(24) * log(cc_nearFar.x) / log(cc_nearFar.y / cc_nearFar.x));\nfloat eyeDepth = -(cc_matView * worldPos).z;\nuint zIndex = uint(max(log(eyeDepth) * scale + bias, 0.0));\nreturn zIndex;\n}\nuint getClusterIndex(vec4 fragCoord, vec4 worldPos)\n{\nuint zIndex = getClusterZIndex(worldPos);\nfloat clusterSizeX = ceil(cc_viewPort.z / float(16));\nfloat clusterSizeY = ceil(cc_viewPort.w / float(8));\nuvec3 indices = uvec3(uvec2(fragCoord.xy / vec2(clusterSizeX, clusterSizeY)), zIndex);\nuint cluster = (16u * 8u) * indices.z + 16u * indices.y + indices.x;\nreturn cluster;\n}\nvec4 CCClusterShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / PI;\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nuint cluster = getClusterIndex(gl_FragCoord, vec4(position, 1.0));\nLightGrid grid = getLightGrid(cluster);\nuint numLights = grid.ccLights;\nfor (uint i = 0u; i < 100u; i++) {\nif (i >= numLights) break;\nuint lightIndex = getGridLightIndex(grid.offset, i);\nCCLight light = getCCLight(lightIndex);\nvec3 SLU = light.cc_lightPos.xyz - position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.001);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = light.cc_lightSizeRangeAngle.x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = PI * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(light.cc_lightSizeRangeAngle.y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (light.cc_lightPos.w > 0.0) {\nfloat cosInner = max(dot(-light.cc_lightDir.xyz, SL), 0.01);\nfloat cosOuter = light.cc_lightSizeRangeAngle.z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -light.cc_lightDir.xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = light.cc_lightColor.rgb;\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (light.cc_lightPos.w > 0.0) {\nshadow = CCSpotShadowFactorBase(shadowPos, position, s.shadowBias);\n}\n#endif\nlightColor *= shadow;\nfinalColor += SNL * lightColor * light.cc_lightColor.w * illum * att * (diffuseContrib + lspec);\n}\nreturn vec4(finalColor, 0.0);\n}\n#endif\nvoid main () {\nStandardSurface s; surf(s);\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1\nvec4 color = CCClusterShadingAdditive(s, v_shadowPos);\n#else\nvec4 color = CCStandardShadingAdditive(s, v_shadowPos);\n#endif\nCC_APPLY_FOG(color, s.position.xyz);\ngl_FragData[0] = CCFragOutput(color);\n}\n#elif (CC_PIPELINE_TYPE == 0 || CC_FORCE_FORWARD_SHADING)\nvoid main () {\nStandardSurface s; surf(s);\nvec4 color = CCStandardShadingBase(s, v_shadowPos);\nCC_APPLY_FOG(color, s.position.xyz);\ngl_FragData[0] = CCFragOutput(color);\n}\n#elif CC_PIPELINE_TYPE == 1\nvec2 signNotZero(vec2 v) {\nreturn vec2((v.x >= 0.0) ? +1.0 : -1.0, (v.y >= 0.0) ? +1.0 : -1.0);\n}\nvec2 float32x3_to_oct(in vec3 v) {\nvec2 p = v.xy * (1.0 / (abs(v.x) + abs(v.y) + abs(v.z)));\nreturn (v.z <= 0.0) ? ((1.0 - abs(p.yx)) * signNotZero(p)) : p;\n}\nvoid main () {\nStandardSurface s; surf(s);\ngl_FragData[0] = s.albedo;\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\ngl_FragData[1] = vec4(position, s.roughness);\ngl_FragData[1] = vec4(float32x3_to_oct(s.normal), s.roughness, s.metallic);\nfragColor3 = vec4(s.emissive, s.occlusion);\n}\n#endif", - }, - { - "vert": "\nprecision highp float;\n#if USE_BATCHING\n#endif\nuniform highp mat4 cc_matWorld;\nuniform highp mat4 cc_matLightViewProj;\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nvarying vec2 v_clip_depth;\nvec4 vert () {\nvec4 worldPos;\nworldPos.x = cc_matWorld[3][0] + a_position.x;\nworldPos.y = cc_matWorld[3][1] + a_position.y;\nworldPos.z = cc_matWorld[3][2] + a_position.z;\nworldPos.w = 1.0;\nvec4 clipPos = cc_matLightViewProj * worldPos;\nv_clip_depth = clipPos.zw;\nreturn clipPos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\nvec4 packDepthToRGBA (float depth) {\nvec4 ret = vec4(1.0, 255.0, 65025.0, 16581375.0) * depth;\nret = fract(ret);\nret -= vec4(ret.yzw, 0.0) / 255.0;\nreturn ret;\n}\nvarying vec2 v_clip_depth;\nvec4 frag () {\nreturn packDepthToRGBA(v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5);\n}\nvoid main() { gl_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nattribute vec4 a_tangent;\n#if USE_INSTANCING\nattribute vec4 a_matWorld0;\nattribute vec4 a_matWorld1;\nattribute vec4 a_matWorld2;\n#if USE_LIGHTMAP\nattribute vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nattribute vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nattribute float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nattribute float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_joints;\nattribute vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 uv = getPixelCoordFromLocation(location, cc_displacementTextureInfo.xy);\nreturn texture2D(tex, uv);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture2D(tex, x)),\ndecode32(texture2D(tex, y)),\ndecode32(texture2D(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nattribute highp vec4 a_jointAnimInfo;\n#endif\nuniform highp vec4 cc_jointTextureInfo;\nuniform highp vec4 cc_jointAnimInfo;\nuniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nuniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout vec4 In)\n{\nIn = vec4(a_position, 1.0);\n#if CC_USE_MORPH\napplyMorph(In);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In);\n#endif\n}\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_fogBase;\nuniform mediump vec4 cc_fogAdd;\n#if USE_BATCHING\nuniform highp mat4 cc_matWorlds[10];\n#endif\nuniform highp mat4 cc_matWorld;\nvoid CCGetWorldMatrix(out mat4 matWorld)\n{\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\n#else\nmatWorld = cc_matWorld;\n#endif\n}\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\n#if !CC_USE_ACCURATE_FOG\nvarying float v_fog_factor;\n#endif\nvoid CC_TRANSFER_FOG(vec4 pos) {\n#if !CC_USE_ACCURATE_FOG\nCC_TRANSFER_FOG_BASE(pos, v_fog_factor);\n#endif\n}\n#if USE_VERTEX_COLOR\nattribute lowp vec4 a_color;\nvarying lowp vec4 v_color;\n#endif\n#if USE_TEXTURE\nvarying vec2 v_uv;\nuniform vec4 tilingOffset;\n#endif\nvec4 vert () {\nvec4 position;\nCCVertInput(position);\nmat4 matWorld;\nCCGetWorldMatrix(matWorld);\n#if USE_TEXTURE\nv_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n#if SAMPLE_FROM_RT\nv_uv = cc_cameraPos.w > 1.0 ? vec2(v_uv.x, 1.0 - v_uv.y) : v_uv;\n#endif\n#endif\n#if USE_VERTEX_COLOR\nv_color = a_color;\n#endif\nCC_TRANSFER_FOG(matWorld * position);\nreturn cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = ACESToneMap(color.rgb);\n#endif\ncolor.rgb = sqrt(color.rgb);\nreturn color;\n}\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_fogColor;\nuniform mediump vec4 cc_fogBase;\nuniform mediump vec4 cc_fogAdd;\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\nvoid CC_APPLY_FOG_BASE(inout vec4 color, float factor) {\ncolor = vec4(mix(cc_fogColor.rgb, color.rgb, factor), color.a);\n}\n#if !CC_USE_ACCURATE_FOG\nvarying float v_fog_factor;\n#endif\nvoid CC_APPLY_FOG(inout vec4 color) {\n#if !CC_USE_ACCURATE_FOG\nCC_APPLY_FOG_BASE(color, v_fog_factor);\n#endif\n}\nvoid CC_APPLY_FOG(inout vec4 color, vec3 worldPos) {\n#if CC_USE_ACCURATE_FOG\nfloat factor;\nCC_TRANSFER_FOG_BASE(vec4(worldPos, 1.0), factor);\n#else\nfloat factor = v_fog_factor;\n#endif\nCC_APPLY_FOG_BASE(color, factor);\n}\n#if USE_ALPHA_TEST\n#endif\n#if USE_TEXTURE\nvarying vec2 v_uv;\nuniform sampler2D mainTexture;\n#endif\nuniform vec4 mainColor;\nuniform vec4 colorScaleAndCutoff;\n#if USE_VERTEX_COLOR\nvarying lowp vec4 v_color;\n#endif\nvec4 frag () {\nvec4 o = mainColor;\no.rgb *= colorScaleAndCutoff.xyz;\n#if USE_VERTEX_COLOR\no.rgb *= SRGBToLinear(v_color.rgb);\no.a *= v_color.a;\n#endif\n#if USE_TEXTURE\nvec4 texColor = texture2D(mainTexture, v_uv);\ntexColor.rgb = SRGBToLinear(texColor.rgb);\no *= texColor;\n#endif\n#if USE_ALPHA_TEST\nif (o.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard;\n#endif\nCC_APPLY_FOG(o);\nreturn CCFragOutput(o);\n}\nvoid main() { gl_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nattribute vec4 a_tangent;\n#if USE_INSTANCING\nattribute vec4 a_matWorld0;\nattribute vec4 a_matWorld1;\nattribute vec4 a_matWorld2;\n#if USE_LIGHTMAP\nattribute vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nattribute vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nattribute float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nattribute float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_joints;\nattribute vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 uv = getPixelCoordFromLocation(location, cc_displacementTextureInfo.xy);\nreturn texture2D(tex, uv);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture2D(tex, x)),\ndecode32(texture2D(tex, y)),\ndecode32(texture2D(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nattribute highp vec4 a_jointAnimInfo;\n#endif\nuniform highp vec4 cc_jointTextureInfo;\nuniform highp vec4 cc_jointAnimInfo;\nuniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nuniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\nuniform highp vec4 cc_cameraPos;\nvarying vec2 v_uv;\nvoid main () {\nStandardVertInput In;\nCCVertInput(In);\nIn.position.xy = cc_cameraPos.w == 0.0 ? vec2(In.position.xy.x, -In.position.xy.y) : In.position.xy;\ngl_Position = In.position;\ngl_Position.y = gl_Position.y;\nv_uv = a_texCoord;\n}", - "frag": "\nprecision highp float;\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvarying vec2 v_uv;\nuniform mediump vec4 texSize;\nuniform sampler2D outputResultMap;\nfloat luminance(vec3 color) {\nreturn dot(color, vec3(0.2126, 0.7152, 0.0722));\n}\nvoid main() {\nvec3 color = texture2D(outputResultMap, v_uv).xyz;\nif (luminance(SRGBToLinear(color)) > texSize.z) {\ngl_FragColor = vec4(color, 1.0);\n} else {\ngl_FragColor = vec4(0.0, 0.0, 0.0, 1.0);\n}\n}", - }, - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nattribute vec4 a_tangent;\n#if USE_INSTANCING\nattribute vec4 a_matWorld0;\nattribute vec4 a_matWorld1;\nattribute vec4 a_matWorld2;\n#if USE_LIGHTMAP\nattribute vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nattribute vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nattribute float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nattribute float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_joints;\nattribute vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 uv = getPixelCoordFromLocation(location, cc_displacementTextureInfo.xy);\nreturn texture2D(tex, uv);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture2D(tex, x)),\ndecode32(texture2D(tex, y)),\ndecode32(texture2D(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nattribute highp vec4 a_jointAnimInfo;\n#endif\nuniform highp vec4 cc_jointTextureInfo;\nuniform highp vec4 cc_jointAnimInfo;\nuniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nuniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\nuniform highp vec4 cc_cameraPos;\nvarying vec2 v_uv;\nvoid main () {\nStandardVertInput In;\nCCVertInput(In);\nIn.position.xy = cc_cameraPos.w == 0.0 ? vec2(In.position.xy.x, -In.position.xy.y) : In.position.xy;\ngl_Position = In.position;\ngl_Position.y = gl_Position.y;\nv_uv = a_texCoord;\n}", - "frag": "\nprecision highp float;\nvarying vec2 v_uv;\nuniform mediump vec4 texSize;\nuniform sampler2D bloomTexture;\nvec3 downsample4taps(vec2 uv, vec2 halfpixel) {\nvec3 sum = texture2D(bloomTexture, uv + vec2(-halfpixel.x, halfpixel.y)).xyz;\nsum += texture2D(bloomTexture, uv + vec2(halfpixel.x, halfpixel.y)).xyz;\nsum += texture2D(bloomTexture, uv + vec2(halfpixel.x, -halfpixel.y)).xyz;\nsum += texture2D(bloomTexture, uv + vec2(-halfpixel.x, -halfpixel.y)).xyz;\nreturn sum / 4.0;\n}\nvoid main()\n{\nvec3 result = downsample4taps(v_uv, 1.0 / texSize.xy).rgb;\ngl_FragColor = vec4(result, 1.0);\n}", - }, - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nattribute vec4 a_tangent;\n#if USE_INSTANCING\nattribute vec4 a_matWorld0;\nattribute vec4 a_matWorld1;\nattribute vec4 a_matWorld2;\n#if USE_LIGHTMAP\nattribute vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nattribute vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nattribute float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nattribute float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_joints;\nattribute vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 uv = getPixelCoordFromLocation(location, cc_displacementTextureInfo.xy);\nreturn texture2D(tex, uv);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture2D(tex, x)),\ndecode32(texture2D(tex, y)),\ndecode32(texture2D(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nattribute highp vec4 a_jointAnimInfo;\n#endif\nuniform highp vec4 cc_jointTextureInfo;\nuniform highp vec4 cc_jointAnimInfo;\nuniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nuniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\nuniform highp vec4 cc_cameraPos;\nvarying vec2 v_uv;\nvoid main () {\nStandardVertInput In;\nCCVertInput(In);\nIn.position.xy = cc_cameraPos.w == 0.0 ? vec2(In.position.xy.x, -In.position.xy.y) : In.position.xy;\ngl_Position = In.position;\ngl_Position.y = gl_Position.y;\nv_uv = a_texCoord;\n}", - "frag": "\nprecision highp float;\nvarying vec2 v_uv;\nuniform mediump vec4 texSize;\nuniform sampler2D bloomTexture;\nvec3 upsample4taps(vec2 uv, vec2 halfpixel) {\nvec3 sum = texture2D(bloomTexture, uv + vec2(-halfpixel.x, halfpixel.y)).xyz;\nsum += texture2D(bloomTexture, uv + vec2(halfpixel.x, halfpixel.y)).xyz;\nsum += texture2D(bloomTexture, uv + vec2(halfpixel.x, -halfpixel.y)).xyz;\nsum += texture2D(bloomTexture, uv + vec2(-halfpixel.x, -halfpixel.y)).xyz;\nreturn sum / 4.0;\n}\nvoid main() {\nvec3 result = upsample4taps(v_uv, 0.5 / texSize.xy).rgb;\ngl_FragColor = vec4(result, 1.0);\n}", - }, - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nattribute vec4 a_tangent;\n#if USE_INSTANCING\nattribute vec4 a_matWorld0;\nattribute vec4 a_matWorld1;\nattribute vec4 a_matWorld2;\n#if USE_LIGHTMAP\nattribute vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nattribute vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nattribute float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nattribute float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_joints;\nattribute vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 uv = getPixelCoordFromLocation(location, cc_displacementTextureInfo.xy);\nreturn texture2D(tex, uv);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture2D(tex, x)),\ndecode32(texture2D(tex, y)),\ndecode32(texture2D(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nattribute highp vec4 a_jointAnimInfo;\n#endif\nuniform highp vec4 cc_jointTextureInfo;\nuniform highp vec4 cc_jointAnimInfo;\nuniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nuniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\nuniform highp vec4 cc_cameraPos;\nvarying vec2 v_uv;\nvoid main () {\nStandardVertInput In;\nCCVertInput(In);\nIn.position.xy = cc_cameraPos.w == 0.0 ? vec2(In.position.xy.x, -In.position.xy.y) : In.position.xy;\ngl_Position = In.position;\ngl_Position.y = gl_Position.y;\nv_uv = a_texCoord;\n}", - "frag": "\nprecision highp float;\nvarying vec2 v_uv;\nuniform mediump vec4 texSize;\nuniform sampler2D outputResultMap;\nuniform sampler2D bloomTexture;\nvoid main() {\nvec4 hdrColor = texture2D(outputResultMap, v_uv);\nvec3 bloomColor = texture2D(bloomTexture, v_uv).rgb;\nvec3 result = hdrColor.rgb + bloomColor * texSize.w * hdrColor.a;\ngl_FragColor = vec4(result, hdrColor.a);\n}", - } - ], - [ - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nattribute vec4 a_tangent;\n#if USE_INSTANCING\nattribute vec4 a_matWorld0;\nattribute vec4 a_matWorld1;\nattribute vec4 a_matWorld2;\n#if USE_LIGHTMAP\nattribute vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nattribute vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nattribute float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nattribute float a_vertexId;\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_joints;\nattribute vec4 a_weights;\n#endif\nuniform highp vec4 cc_cameraPos;\nvarying vec2 v_uv;\nvoid main () {\nvec4 position;\nposition = vec4(a_position, 1.0);\nposition.xy = cc_cameraPos.w == 0.0 ? vec2(position.xy.x, -position.xy.y) : position.xy;\ngl_Position = vec4(position.x, position.y, 1.0, 1.0);\nv_uv = a_texCoord;\n}", - "frag": "\n#ifdef GL_EXT_shader_framebuffer_fetch\n#extension GL_EXT_shader_framebuffer_fetch: enable\n#endif\n#ifdef GL_OES_standard_derivatives\n#extension GL_OES_standard_derivatives: enable\n#endif\n#ifdef GL_EXT_shader_texture_lod\n#extension GL_EXT_shader_texture_lod: enable\n#endif\nprecision highp float;\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matViewProjInv;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_mainLitDir;\nuniform mediump vec4 cc_mainLitColor;\nuniform mediump vec4 cc_ambientSky;\nuniform mediump vec4 cc_ambientGround;\nuniform mediump vec4 cc_fogColor;\nuniform mediump vec4 cc_fogBase;\nuniform mediump vec4 cc_fogAdd;\nuniform mediump vec4 cc_nearFar;\nuniform mediump vec4 cc_viewPort;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nuniform highp mat4 cc_matLightView;\nuniform highp mat4 cc_matLightViewProj;\nuniform highp vec4 cc_shadowInvProjDepthInfo;\nuniform highp vec4 cc_shadowProjDepthInfo;\nuniform highp vec4 cc_shadowProjInfo;\nuniform mediump vec4 cc_shadowNFLSInfo;\nuniform mediump vec4 cc_shadowWHPBInfo;\nuniform mediump vec4 cc_shadowLPNNInfo;\nhighp float unpackHighpData (float mainPart, float modPart) {\nhighp float data = mainPart;\nreturn data + modPart;\n}\nhighp float unpackHighpData (float mainPart, float modPart, const float modValue) {\nhighp float data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nhighp vec2 unpackHighpData (vec2 mainPart, vec2 modPart) {\nhighp vec2 data = mainPart;\nreturn data + modPart;\n}\nhighp vec2 unpackHighpData (vec2 mainPart, vec2 modPart, const float modValue) {\nhighp vec2 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nhighp vec3 unpackHighpData (vec3 mainPart, vec3 modPart) {\nhighp vec3 data = mainPart;\nreturn data + modPart;\n}\nhighp vec3 unpackHighpData (vec3 mainPart, vec3 modPart, const float modValue) {\nhighp vec3 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nhighp vec4 unpackHighpData (vec4 mainPart, vec4 modPart) {\nhighp vec4 data = mainPart;\nreturn data + modPart;\n}\nhighp vec4 unpackHighpData (vec4 mainPart, vec4 modPart, const float modValue) {\nhighp vec4 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\n#if USE_BATCHING\n#endif\nfloat CCGetLinearDepthFromViewSpace(vec3 viewPos) {\nfloat dist = length(viewPos);\nreturn (dist - cc_shadowNFLSInfo.x) / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x);\n}\nfloat CCGetLinearDepth(vec3 worldPos) {\nvec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0);\nreturn CCGetLinearDepthFromViewSpace(viewStartPos.xyz);\n}\n#if CC_RECEIVE_SHADOW\nuniform highp sampler2D cc_shadowMap;\nuniform highp sampler2D cc_spotLightingMap;\nvec4 ApplyShadowDepthBias_FaceNormal(vec4 shadowPos, vec3 worldNormal, float normalBias)\n{\nvec4 newShadowPos = shadowPos;\nif(normalBias > 0.0001)\n{\nvec4 viewNormal = cc_matLightView * vec4(worldNormal, 0.0);\nif(viewNormal.z < 0.1)\nnewShadowPos.xy += viewNormal.xy * cc_shadowProjInfo.xy * normalBias * clamp(viewNormal.z, 0.001, 0.1);\n}\nreturn newShadowPos;\n}\nvec4 ApplyShadowDepthBias_Perspective(vec4 shadowPos, float viewspaceDepthBias)\n{\nvec3 viewSpacePos;\nviewSpacePos.xy = shadowPos.xy * cc_shadowProjInfo.zw;\nviewSpacePos.z = shadowPos.z * cc_shadowInvProjDepthInfo.x + shadowPos.w * cc_shadowInvProjDepthInfo.y;\nviewSpacePos.xyz += cc_shadowProjDepthInfo.z * normalize(viewSpacePos.xyz) * viewspaceDepthBias;\nvec4 clipSpacePos;\nclipSpacePos.xy = viewSpacePos.xy * cc_shadowProjInfo.xy;\nclipSpacePos.zw = viewSpacePos.z * cc_shadowProjDepthInfo.xz + vec2(cc_shadowProjDepthInfo.y, 0.0);\nif (cc_shadowNFLSInfo.z > 0.000001) {\nclipSpacePos.z = CCGetLinearDepthFromViewSpace(viewSpacePos.xyz);\nclipSpacePos.z = (clipSpacePos.z * 2.0 - 1.0) * clipSpacePos.w;\n}\nreturn clipSpacePos;\n}\nvec4 ApplyShadowDepthBias_Orthographic(vec4 shadowPos, float viewspaceDepthBias)\n{\nfloat coeffA = cc_shadowProjDepthInfo.x;\nfloat coeffB = cc_shadowProjDepthInfo.y;\nfloat viewSpacePos_z = (shadowPos.z - coeffB) / coeffA;\nviewSpacePos_z += viewspaceDepthBias;\nvec4 result = shadowPos;\nresult.z = viewSpacePos_z * coeffA + coeffB;\nreturn result;\n}\nfloat CCGetShadowFactorHard (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture2D(cc_shadowMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n} else {\nclosestDepth = texture2D(cc_shadowMap, clipPos.xy).x;\n}\nshadow = step(clipPos.z, closestDepth);\nreturn shadow;\n}\nfloat CCGetShadowFactorSoft (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x);\nblock1 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)).x);\nblock2 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)).x);\nblock3 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetShadowFactorSoft2X (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock4 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock5 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock6 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock7 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock8 = step(offsetDepth, dot(texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)).x);\nblock1 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)).x);\nblock2 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)).x);\nblock3 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)).x);\nblock4 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x);\nblock5 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)).x);\nblock6 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)).x);\nblock7 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)).x);\nblock8 = step(offsetDepth, texture2D(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCGetSpotLightShadowFactorHard (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nfloat depth = clipPos.z;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture2D(cc_spotLightingMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n} else {\nclosestDepth = texture2D(cc_spotLightingMap, clipPos.xy).x;\n}\nshadow = step(depth, closestDepth);\nreturn shadow;\n}\nfloat CCGetSpotLightShadowFactorSoft (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nvec2 oneTap = 1.0 / cc_shadowWHPBInfo.xy;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x);\nblock1 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)).x);\nblock2 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)).x);\nblock3 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * cc_shadowWHPBInfo.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY = mod(clipPos.y, oneTap.y) * cc_shadowWHPBInfo.y;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetSpotLightShadowFactorSoft2X (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock4 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock5 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock6 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock7 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock8 = step(depth, dot(texture2D(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)).x);\nblock1 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)).x);\nblock2 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)).x);\nblock3 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)).x);\nblock4 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x);\nblock5 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)).x);\nblock6 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)).x);\nblock7 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)).x);\nblock8 = step(depth, texture2D(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCSpotShadowFactorBase(vec4 shadowPos, vec3 worldPos, vec2 shadowBias)\n{\nfloat pcf = cc_shadowWHPBInfo.z;\nif (pcf > 1.9) {\nreturn CCGetSpotLightShadowFactorSoft2X(shadowPos, worldPos, shadowBias.x);\n}else if (pcf > 0.9) {\nreturn CCGetSpotLightShadowFactorSoft(shadowPos, worldPos, shadowBias.x);\n}else {\nreturn CCGetSpotLightShadowFactorHard(shadowPos, worldPos, shadowBias.x);\n}\n}\nfloat CCShadowFactorBase(vec4 shadowPos, vec3 N, vec2 shadowBias)\n{\nfloat realtimeShadow = 1.0;\nvec4 pos = ApplyShadowDepthBias_FaceNormal(shadowPos, N, shadowBias.y);\nfloat pcf = cc_shadowWHPBInfo.z;\nif (pcf > 1.9) {\nrealtimeShadow = CCGetShadowFactorSoft2X(pos, shadowBias.x);\n}else if (pcf > 0.9) {\nrealtimeShadow = CCGetShadowFactorSoft(pos, shadowBias.x);\n}else {\nrealtimeShadow = CCGetShadowFactorHard(pos, shadowBias.x);\n}\nreturn mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w);\n}\n#endif\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\n#ifdef GL_EXT_shader_texture_lod\nreturn texture2DLodEXT(tex, coord, lod);\n#else\nreturn texture2D(tex, coord, lod);\n#endif\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\n#ifdef GL_EXT_shader_texture_lod\nreturn textureCubeLodEXT(tex, coord, lod);\n#else\nreturn textureCube(tex, coord, lod);\n#endif\n}\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(1.1, rgbe.a * 255.0 - 128.0);\n}\n#if CC_USE_DIFFUSEMAP\nuniform samplerCube cc_diffuseMap;\n#endif\n#endif\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\nvec3 NxH = cross(N, H);\nfloat OneMinusNoHSqr = dot(NxH, NxH);\nfloat a = roughness * roughness;\nfloat n = NoH * a;\nfloat p = a / (OneMinusNoHSqr + n * n);\nreturn p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\nreturn (roughness * 0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\nconst vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\nconst vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\nvec4 r = roughness * c0 + c1;\nfloat a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;\nvec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;\nAB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\nreturn specular * AB.x + AB.y;\n}\n#if USE_REFLECTION_DENOISE\nvec3 GetEnvReflectionWithMipFiltering(vec3 R, float roughness, float mipCount, float denoiseIntensity) {\n#if CC_USE_IBL\nfloat mip = roughness * mipCount;\nfloat delta = (dot(dFdx(R), dFdy(R))) * 1000.0;\nfloat mipBias = mix(0.0, 5.0, clamp(delta, 0.0, 1.0));\nvec4 biased = fragTextureLod(cc_environment, R, mip + mipBias);\nvec4 filtered = textureCube(cc_environment, R);\n#if CC_USE_IBL == 2\nbiased.rgb = unpackRGBE(biased);\nfiltered.rgb = unpackRGBE(filtered);\n#else\nbiased.rgb = SRGBToLinear(biased.rgb);\nfiltered.rgb = SRGBToLinear(filtered.rgb);\n#endif\nreturn mix(biased.rgb, filtered.rgb, denoiseIntensity);\n#else\nreturn vec3(0.0, 0.0, 0.0);\n#endif\n}\n#endif\nstruct StandardSurface {\nvec4 albedo;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nvec3 position, position_fract_part;\n#else\nvec3 position;\n#endif\nvec3 normal;\nvec3 emissive;\nvec3 lightmap;\nfloat lightmap_test;\nfloat roughness;\nfloat metallic;\nfloat occlusion;\n#if CC_RECEIVE_SHADOW\nvec2 shadowBias;\n#endif\n};\nvec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.0);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 L = normalize(-cc_mainLitDir.xyz);\nvec3 H = normalize(L + V);\nfloat NH = max(dot(N, H), 0.0);\nfloat NL = max(dot(N, L), 0.0);\nvec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w;\nvec3 diffuseContrib = diffuse;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nif (s.lightmap_test > 0.0001) {\nfinalColor = s.lightmap.rgb;\n}\n#else\ndiffuseContrib /= PI;\n#endif\nvec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\nvec3 dirlightContrib = (diffuseContrib + specularContrib);\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (NL > 0.0 && cc_mainLitDir.w > 0.0) {\nshadow = CCShadowFactorBase(shadowPos, N, s.shadowBias);\n}\n#endif\ndirlightContrib *= shadow;\nfinalColor *= dirlightContrib;\nfloat fAmb = 0.5 - N.y * 0.5;\nvec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb);\n#if CC_USE_IBL\n#if CC_USE_DIFFUSEMAP\nvec4 diffuseMap = textureCube(cc_diffuseMap, N);\n#if CC_USE_DIFFUSEMAP == 2\nambDiff = unpackRGBE(diffuseMap);\n#else\nambDiff = SRGBToLinear(diffuseMap.rgb);\n#endif\n#endif\nvec3 R = normalize(reflect(-V, N));\n#if USE_REFLECTION_DENOISE\nvec3 env = GetEnvReflectionWithMipFiltering(R, s.roughness, cc_ambientGround.w, 0.6);\n#else\nvec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n#if CC_USE_IBL == 2\nvec3 env = unpackRGBE(envmap);\n#else\nvec3 env = SRGBToLinear(envmap.rgb);\n#endif\n#endif\nfinalColor += env * cc_ambientSky.w * specular * s.occlusion;\n#endif\nfinalColor += ambDiff.rgb * cc_ambientSky.w * diffuse * s.occlusion;\nfinalColor += s.emissive;\nreturn vec4(finalColor, s.albedo.a);\n}\n#if CC_PIPELINE_TYPE == 0\n#define LIGHTS_PER_PASS 1\n#else\n#define LIGHTS_PER_PASS 10\n#endif\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0\nuniform highp vec4 cc_lightPos[LIGHTS_PER_PASS];\nuniform vec4 cc_lightColor[LIGHTS_PER_PASS];\nuniform vec4 cc_lightSizeRangeAngle[LIGHTS_PER_PASS];\nuniform vec4 cc_lightDir[LIGHTS_PER_PASS];\n#endif\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\nfloat factor = distSqr * invSqrAttRadius;\nfloat smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\nreturn smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\nfloat attenuation = 1.0 / max(distSqr, 0.01*0.01);\nattenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\nreturn attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\nfloat cd = dot(litDir, L);\nfloat attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\nreturn (attenuation * attenuation);\n}\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0\nvec4 CCStandardShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / PI;\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.0);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nint numLights = CC_PIPELINE_TYPE == 0 ? LIGHTS_PER_PASS : int(cc_lightDir[0].w);\nfor (int i = 0; i < LIGHTS_PER_PASS; i++) {\nif (i >= numLights) break;\nvec3 SLU = cc_lightPos[i].xyz - position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.0);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = cc_lightSizeRangeAngle[i].x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = PI * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(cc_lightSizeRangeAngle[i].y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (cc_lightPos[i].w > 0.0) {\nfloat cosInner = max(dot(-cc_lightDir[i].xyz, SL), 0.01);\nfloat cosOuter = cc_lightSizeRangeAngle[i].z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -cc_lightDir[i].xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = cc_lightColor[i].rgb;\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (cc_lightPos[i].w > 0.0 && cc_lightSizeRangeAngle[i].w > 0.0) {\nshadow = CCSpotShadowFactorBase(shadowPos, position, s.shadowBias);\n}\n#endif\nlightColor *= shadow;\nfinalColor += SNL * lightColor * cc_lightColor[i].w * illum * att * (diffuseContrib + lspec);\n}\nreturn vec4(finalColor, 0.0);\n}\n#endif\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1\nreadonly buffer b_ccLightsBuffer { vec4 b_ccLights[]; };\nreadonly buffer b_clusterLightIndicesBuffer { uint b_clusterLightIndices[]; };\nreadonly buffer b_clusterLightGridBuffer { uvec4 b_clusterLightGrid[]; };\nstruct CCLight\n{\nvec4 cc_lightPos;\nvec4 cc_lightColor;\nvec4 cc_lightSizeRangeAngle;\nvec4 cc_lightDir;\n};\nstruct Cluster\n{\nvec3 minBounds;\nvec3 maxBounds;\n};\nstruct LightGrid\n{\nuint offset;\nuint ccLights;\n};\nCCLight getCCLight(uint i)\n{\nCCLight light;\nlight.cc_lightPos = b_ccLights[4u * i + 0u];\nlight.cc_lightColor = b_ccLights[4u * i + 1u];\nlight.cc_lightSizeRangeAngle = b_ccLights[4u * i + 2u];\nlight.cc_lightDir = b_ccLights[4u * i + 3u];\nreturn light;\n}\nLightGrid getLightGrid(uint cluster)\n{\nuvec4 gridvec = b_clusterLightGrid[cluster];\nLightGrid grid;\ngrid.offset = gridvec.x;\ngrid.ccLights = gridvec.y;\nreturn grid;\n}\nuint getGridLightIndex(uint start, uint offset)\n{\nreturn b_clusterLightIndices[start + offset];\n}\nuint getClusterZIndex(vec4 worldPos)\n{\nfloat scale = float(24) / log(cc_nearFar.y / cc_nearFar.x);\nfloat bias = -(float(24) * log(cc_nearFar.x) / log(cc_nearFar.y / cc_nearFar.x));\nfloat eyeDepth = -(cc_matView * worldPos).z;\nuint zIndex = uint(max(log(eyeDepth) * scale + bias, 0.0));\nreturn zIndex;\n}\nuint getClusterIndex(vec4 fragCoord, vec4 worldPos)\n{\nuint zIndex = getClusterZIndex(worldPos);\nfloat clusterSizeX = ceil(cc_viewPort.z / float(16));\nfloat clusterSizeY = ceil(cc_viewPort.w / float(8));\nuvec3 indices = uvec3(uvec2(fragCoord.xy / vec2(clusterSizeX, clusterSizeY)), zIndex);\nuint cluster = (16u * 8u) * indices.z + 16u * indices.y + indices.x;\nreturn cluster;\n}\nvec4 CCClusterShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / PI;\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nuint cluster = getClusterIndex(gl_FragCoord, vec4(position, 1.0));\nLightGrid grid = getLightGrid(cluster);\nuint numLights = grid.ccLights;\nfor (uint i = 0u; i < 100u; i++) {\nif (i >= numLights) break;\nuint lightIndex = getGridLightIndex(grid.offset, i);\nCCLight light = getCCLight(lightIndex);\nvec3 SLU = light.cc_lightPos.xyz - position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.001);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = light.cc_lightSizeRangeAngle.x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = PI * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(light.cc_lightSizeRangeAngle.y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (light.cc_lightPos.w > 0.0) {\nfloat cosInner = max(dot(-light.cc_lightDir.xyz, SL), 0.01);\nfloat cosOuter = light.cc_lightSizeRangeAngle.z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -light.cc_lightDir.xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = light.cc_lightColor.rgb;\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (light.cc_lightPos.w > 0.0) {\nshadow = CCSpotShadowFactorBase(shadowPos, position, s.shadowBias);\n}\n#endif\nlightColor *= shadow;\nfinalColor += SNL * lightColor * light.cc_lightColor.w * illum * att * (diffuseContrib + lspec);\n}\nreturn vec4(finalColor, 0.0);\n}\n#endif\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = ACESToneMap(color.rgb);\n#endif\ncolor.rgb = sqrt(color.rgb);\nreturn color;\n}\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\nvoid CC_APPLY_FOG_BASE(inout vec4 color, float factor) {\ncolor = vec4(mix(cc_fogColor.rgb, color.rgb, factor), color.a);\n}\nvec2 signNotZero(vec2 v) {\nreturn vec2((v.x >= 0.0) ? +1.0 : -1.0, (v.y >= 0.0) ? +1.0 : -1.0);\n}\nvec3 oct_to_float32x3(vec2 e) {\nvec3 v = vec3(e.xy, 1.0 - abs(e.x) - abs(e.y));\nif (v.z < 0.0) v.xy = (1.0 - abs(v.yx)) * signNotZero(v.xy);\nreturn normalize(v);\n}\nvec4 screen2WS(vec3 coord) {\nvec3 ndc = vec3(\n2.0 * (coord.x - cc_viewPort.x) / cc_viewPort.z - 1.0,\n2.0 * (coord.y - cc_viewPort.y) / cc_viewPort.w - 1.0,\n2.0 * coord.z - 1.0);\nvec4 world = ((cc_matViewProjInv) * (vec4(ndc, 1.0)));\nworld = world / world.w;\nreturn world;\n}\nvarying vec2 v_uv;\n#if CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT\n#else\nuniform sampler2D gbuffer_albedoMap;\nuniform sampler2D gbuffer_normalMap;\nuniform sampler2D gbuffer_emissiveMap;\n#endif\nuniform sampler2D depth_stencil;\n#if !CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT || __VERSION__ >= 450\n#endif\nvoid main () {\nStandardSurface s;\n#if CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT\nvec4 albedoMap = gl_LastFragData[0];\nvec4 normalMap = gl_LastFragData[1];\nvec4 emissiveMap = gl_LastFragDat[2];\n#else\nvec4 albedoMap = texture2D(gbuffer_albedoMap,v_uv);\nvec4 normalMap = texture2D(gbuffer_normalMap,v_uv);\nvec4 emissiveMap = texture2D(gbuffer_emissiveMap,v_uv);\n#endif\nfloat depth = texture2D(depth_stencil, v_uv).x;\ns.albedo = albedoMap;\nvec3 position = screen2WS(vec3(gl_FragCoord.xy, depth)).xyz;\ns.position = position;\ns.roughness = normalMap.z;\ns.normal = oct_to_float32x3(normalMap.xy);\ns.metallic = normalMap.w;\ns.emissive = emissiveMap.xyz;\ns.occlusion = emissiveMap.w;\nfloat fogFactor;\nCC_TRANSFER_FOG_BASE(vec4(position, 1), fogFactor);\nvec4 shadowPos;\nshadowPos = cc_matLightViewProj * vec4(position, 1);\nvec4 color = CCStandardShadingBase(s, shadowPos) +\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1\nCCClusterShadingAdditive(s, shadowPos);\n#else\nCCStandardShadingAdditive(s, shadowPos);\n#endif\nCC_APPLY_FOG_BASE(color, fogFactor);\ncolor = CCFragOutput(color);\n#if CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT\ngl_FragData[2] = color;\n#else\ngl_FragColor = color;\n#endif\n}", - } - ], - [ - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nattribute vec4 a_tangent;\n#if USE_INSTANCING\nattribute vec4 a_matWorld0;\nattribute vec4 a_matWorld1;\nattribute vec4 a_matWorld2;\n#if USE_LIGHTMAP\nattribute vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nattribute vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nattribute float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nattribute float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_joints;\nattribute vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 uv = getPixelCoordFromLocation(location, cc_displacementTextureInfo.xy);\nreturn texture2D(tex, uv);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture2D(tex, x)),\ndecode32(texture2D(tex, y)),\ndecode32(texture2D(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nattribute highp vec4 a_jointAnimInfo;\n#endif\nuniform highp vec4 cc_jointTextureInfo;\nuniform highp vec4 cc_jointAnimInfo;\nuniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nuniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout vec4 In)\n{\nIn = vec4(a_position, 1.0);\n#if CC_USE_MORPH\napplyMorph(In);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In);\n#endif\n}\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\nuniform highp vec4 cc_cameraPos;\nuniform mediump vec4 cc_mainLitDir;\n#if USE_BATCHING\nuniform highp mat4 cc_matWorlds[10];\n#endif\nuniform highp mat4 cc_matWorld;\nvoid CCGetWorldMatrix(out mat4 matWorld)\n{\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\n#else\nmatWorld = cc_matWorld;\n#endif\n}\nuniform mediump vec4 cc_planarNDInfo;\nvarying float v_dist;\nvec4 vert () {\nvec4 position;\nCCVertInput(position);\nmat4 matWorld;\nCCGetWorldMatrix(matWorld);\nvec3 P = (matWorld * position).xyz;\nvec3 L = cc_mainLitDir.xyz;\nvec3 N = cc_planarNDInfo.xyz;\nfloat d = cc_planarNDInfo.w + 0.001;\nfloat dist = (-d - dot(P, N)) / (dot(L, N) + 0.0001);\nvec3 shadowPos = P + L * dist;\nvec3 view = normalize(cc_cameraPos.xyz - shadowPos);\nfloat viewLength = length(cc_cameraPos.xyz - shadowPos);\nshadowPos += view * min(1.0, 0.005 * viewLength);\nposition = cc_matProj * cc_matView * vec4(shadowPos, 1.0);\nv_dist = dist;\nreturn position;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nuniform lowp vec4 cc_shadowColor;\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nvarying float v_dist;\nvec4 frag () {\nif(v_dist < 0.0)\ndiscard;\nreturn CCFragOutput(cc_shadowColor);\n}\nvoid main() { gl_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nattribute vec4 a_tangent;\n#if USE_INSTANCING\nattribute vec4 a_matWorld0;\nattribute vec4 a_matWorld1;\nattribute vec4 a_matWorld2;\n#if USE_LIGHTMAP\nattribute vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nattribute vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nattribute float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nattribute float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_joints;\nattribute vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nuniform vec4 cc_displacementWeights[15];\nuniform vec4 cc_displacementTextureInfo;\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 uv = getPixelCoordFromLocation(location, cc_displacementTextureInfo.xy);\nreturn texture2D(tex, uv);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture2D(tex, x)),\ndecode32(texture2D(tex, y)),\ndecode32(texture2D(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nattribute highp vec4 a_jointAnimInfo;\n#endif\nuniform highp vec4 cc_jointTextureInfo;\nuniform highp vec4 cc_jointAnimInfo;\nuniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nuniform highp vec4 cc_joints[90];\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture2D(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture2D(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\nuniform highp vec4 cc_cameraPos;\nvarying vec2 v_uv;\nvoid main () {\nStandardVertInput In;\nCCVertInput(In);\nIn.position.xy = cc_cameraPos.w == 0.0 ? vec2(In.position.xy.x, -In.position.xy.y) : In.position.xy;\ngl_Position = In.position;\ngl_Position.y = gl_Position.y;\nv_uv = a_texCoord;\n}", - "frag": "\nprecision highp float;\nuniform mediump vec4 cc_screenSize;\n#if ANTIALIAS_TYPE == 1\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\nvec2 v_rgbNW, vec2 v_rgbNE,\nvec2 v_rgbSW, vec2 v_rgbSE,\nvec2 v_rgbM) {\nvec4 color;\nmediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\nvec3 rgbNW = texture2D(tex, v_rgbNW).xyz;\nvec3 rgbNE = texture2D(tex, v_rgbNE).xyz;\nvec3 rgbSW = texture2D(tex, v_rgbSW).xyz;\nvec3 rgbSE = texture2D(tex, v_rgbSE).xyz;\nvec4 texColor = texture2D(tex, v_rgbM);\nvec3 rgbM = texColor.xyz;\nvec3 luma = vec3(0.299, 0.587, 0.114);\nfloat lumaNW = dot(rgbNW, luma);\nfloat lumaNE = dot(rgbNE, luma);\nfloat lumaSW = dot(rgbSW, luma);\nfloat lumaSE = dot(rgbSE, luma);\nfloat lumaM = dot(rgbM, luma);\nfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\nfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\nmediump vec2 dir;\ndir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\ndir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\nfloat dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n(0.25 * (1.0 / 8.0)), (1.0/ 128.0));\nfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\ndir = min(vec2(8.0, 8.0),\nmax(vec2(-8.0, -8.0),\ndir * rcpDirMin)) * inverseVP;\nvec3 rgbA = 0.5 * (\ntexture2D(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\ntexture2D(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\nvec3 rgbB = rgbA * 0.5 + 0.25 * (\ntexture2D(tex, fragCoord * inverseVP + dir * -0.5).xyz +\ntexture2D(tex, fragCoord * inverseVP + dir * 0.5).xyz);\nfloat lumaB = dot(rgbB, luma);\nif ((lumaB < lumaMin) || (lumaB > lumaMax))\ncolor = vec4(rgbA, texColor.a);\nelse\ncolor = vec4(rgbB, texColor.a);\nreturn color;\n}\n#endif\nvarying vec2 v_uv;\nuniform sampler2D outputResultMap;\nvoid texcoords(vec2 fragCoord, vec2 resolution,\nout vec2 v_rgbNW, out vec2 v_rgbNE,\nout vec2 v_rgbSW, out vec2 v_rgbSE,\nout vec2 v_rgbM) {\nvec2 inverseVP = 1.0 / resolution.xy;\nv_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\nv_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\nv_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\nv_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\nv_rgbM = vec2(fragCoord * inverseVP);\n}\nvoid main () {\nmediump vec2 v_rgbNW;\nmediump vec2 v_rgbNE;\nmediump vec2 v_rgbSW;\nmediump vec2 v_rgbSE;\nmediump vec2 v_rgbM;\n#if ANTIALIAS_TYPE == 1\nvec2 resolution = cc_screenSize.xy;\nvec2 fragCoord = v_uv * resolution;\ntexcoords(fragCoord, resolution, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\ngl_FragColor = fxaa(outputResultMap, fragCoord, resolution, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n#else\ngl_FragColor = texture2D(outputResultMap, v_uv);\n#endif\n}", - } - ], - [ - { - "vert": "\nprecision highp float;\nuniform highp mat4 cc_matView;\nuniform highp mat4 cc_matProj;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nattribute vec3 a_position;\nattribute vec3 a_normal;\nattribute vec2 a_texCoord;\nattribute vec4 a_tangent;\n#if USE_INSTANCING\nattribute vec4 a_matWorld0;\nattribute vec4 a_matWorld1;\nattribute vec4 a_matWorld2;\n#if USE_LIGHTMAP\nattribute vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nattribute vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nattribute float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nattribute float a_vertexId;\n#endif\n#if CC_USE_SKINNING\nattribute vec4 a_joints;\nattribute vec4 a_weights;\n#endif\nvarying mediump vec4 viewDir;\nvec4 vert () {\nviewDir = vec4(a_position, 1.0);\nmat4 matViewRotOnly = mat4(mat3(cc_matView));\nvec4 pos = matViewRotOnly * viewDir;\nif (cc_matProj[3].w > 0.0) {\nmat4 matProj = cc_matProj;\nmatProj[0].x = 5.2;\nmatProj[1].y = 2.6;\nmatProj[2].zw = vec2(-1.0);\nmatProj[3].zw = vec2(0.0);\npos = matProj * pos;\n} else {\npos = cc_matProj * pos;\n}\npos.z = 0.99999 * pos.w;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nuniform mediump vec4 cc_ambientSky;\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(1.1, rgbe.a * 255.0 - 128.0);\n}\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = ACESToneMap(color.rgb);\n#endif\ncolor.rgb = sqrt(color.rgb);\nreturn color;\n}\nvarying mediump vec4 viewDir;\nvec4 frag () {\n#if USE_RGBE_CUBEMAP\nvec3 c = unpackRGBE(textureCube(cc_environment, viewDir.xyz));\n#else\nvec3 c = SRGBToLinear(textureCube(cc_environment, viewDir.xyz).rgb);\n#endif\nreturn CCFragOutput(vec4(c * cc_ambientSky.w, 1.0));\n}\nvoid main() { gl_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nuniform highp mat4 cc_matProj;\nattribute vec3 a_position;\nattribute vec4 a_color;\nvarying vec2 v_uv;\nuniform vec4 offset;\nuniform vec4 digits[20];\nfloat getComponent(vec4 v, float i) {\nif (i < 1.0) { return v.x; }\nelse if (i < 2.0) { return v.y; }\nelse if (i < 3.0) { return v.z; }\nelse { return v.w; }\n}\nvec4 vert () {\nmat2 proj = mat2(cc_matProj[0].xy, cc_matProj[1].xy);\nproj /= abs(proj[1].x + proj[1].y);\nvec2 position = proj * a_position.xy + offset.xy;\nv_uv = a_color.xy;\nif (a_color.z >= 0.0) {\nfloat n = getComponent(digits[int(a_color.z)], a_color.w);\nv_uv += vec2(offset.z * n, 0.0);\n}\nreturn vec4(position, 0.0, 1.0);\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nvarying vec2 v_uv;\nuniform sampler2D mainTexture;\nvec4 frag () {\nreturn CCFragOutput(texture2D(mainTexture, v_uv));\n}\nvoid main() { gl_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nattribute vec2 a_position;\nattribute vec2 a_texCoord;\nvarying vec2 v_uv;\nuniform vec4 u_buffer0;\nuniform vec4 u_buffer1;\nuniform mat4 u_projection;\nvec4 vert () {\nvec2 worldPos = a_position * u_buffer1.xy + u_buffer1.zw;\nvec2 clipSpace = worldPos / u_buffer0.xy * 2.0 - 1.0;\nvec4 screenPos = u_projection * vec4(clipSpace, 0.0, 1.0);\nv_uv = a_texCoord;\nreturn screenPos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nvarying vec2 v_uv;\nuniform float u_percent;\nuniform sampler2D mainTexture;\nvec4 frag () {\nvec4 color = texture2D(mainTexture, v_uv);\nfloat percent = clamp(u_percent, 0.0, 1.0);\ncolor.xyz *= percent;\nreturn color;\n}\nvoid main() { gl_FragColor = frag(); }", - } - ] -]; diff --git a/cocos/core/builtin/shader-sources/glsl3.ts b/cocos/core/builtin/shader-sources/glsl3.ts deleted file mode 100644 index 30b9f29b98..0000000000 --- a/cocos/core/builtin/shader-sources/glsl3.ts +++ /dev/null @@ -1,169 +0,0 @@ -/* eslint-disable */ -export const glsl3 = [ - [ - { - "vert": "\nprecision mediump float;\nlayout(std140) uniform Constants {\nvec4 mainTiling_Offset;\nvec4 frameTile_velLenScale;\nvec4 scale;\nvec4 nodeRotation;\n};\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\nmat3 m = mat3(xAxis,yAxis,zAxis);\nfloat trace = m[0][0] + m[1][1] + m[2][2];\nvec4 quat;\nif (trace > 0.) {\nfloat s = 0.5 / sqrt(trace + 1.0);\nquat.w = 0.25 / s;\nquat.x = (m[2][1] - m[1][2]) * s;\nquat.y = (m[0][2] - m[2][0]) * s;\nquat.z = (m[1][0] - m[0][1]) * s;\n} else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\nfloat s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\nquat.w = (m[2][1] - m[1][2]) / s;\nquat.x = 0.25 * s;\nquat.y = (m[0][1] + m[1][0]) / s;\nquat.z = (m[0][2] + m[2][0]) / s;\n} else if (m[1][1] > m[2][2]) {\nfloat s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\nquat.w = (m[0][2] - m[2][0]) / s;\nquat.x = (m[0][1] + m[1][0]) / s;\nquat.y = 0.25 * s;\nquat.z = (m[1][2] + m[2][1]) / s;\n} else {\nfloat s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\nquat.w = (m[1][0] - m[0][1]) / s;\nquat.x = (m[0][2] + m[2][0]) / s;\nquat.y = (m[1][2] + m[2][1]) / s;\nquat.z = 0.25 * s;\n}\nfloat len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\nif (len > 0.) {\nlen = 1. / sqrt(len);\nquat.x = quat.x * len;\nquat.y = quat.y * len;\nquat.z = quat.z * len;\nquat.w = quat.w * len;\n}\nreturn quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\nfloat x = angle.x / 2.;\nfloat y = angle.y / 2.;\nfloat z = angle.z / 2.;\nfloat sx = sin(x);\nfloat cx = cos(x);\nfloat sy = sin(y);\nfloat cy = cos(y);\nfloat sz = sin(z);\nfloat cz = cos(z);\nvec4 quat = vec4(0);\nquat.x = sx * cy * cz + cx * sy * sz;\nquat.y = cx * sy * cz + sx * cy * sz;\nquat.z = cx * cy * sz - sx * sy * cz;\nquat.w = cx * cy * cz - sx * sy * sz;\nreturn quat;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\nvec4 quat;\nquat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\nquat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\nquat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\nquat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\nreturn quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\nfloat ix = q.w * v.x + q.y * v.z - q.z * v.y;\nfloat iy = q.w * v.y + q.z * v.x - q.x * v.z;\nfloat iz = q.w * v.z + q.x * v.y - q.y * v.x;\nfloat iw = -q.x * v.x - q.y * v.y - q.z * v.z;\nv.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\nv.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\nv.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\nvec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\nvec4 rotQuat = quatMultiply(viewQuat, q);\nrotateVecFromQuat(pos, rotQuat);\nreturn pos;\n}\nout mediump vec2 uv;\nout mediump vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n, mat4 viewInv\n) {\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\nvec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\nvec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n}\nin vec3 a_position;\nin vec2 a_texCoord;\nin vec4 a_color;\nlayout(std140) uniform builtin {\nvec4 cc_size_rotation;\n};\nvec4 vs_main() {\nvec4 pos = vec4(a_position, 1);\npos = cc_matWorld * pos;\nvec2 vertOffset = a_texCoord.xy - 0.5;\ncomputeVertPos(pos, vertOffset, quaternionFromEuler(vec3(0., 0., cc_size_rotation.z)), vec3(cc_size_rotation.xy, 0.), cc_matViewInv);\npos = cc_matViewProj * pos;\nuv = a_texCoord.xy;\ncolor = a_color;\nreturn pos;\n}\nvoid main() { gl_Position = vs_main(); }", - "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nin vec2 uv;\nin vec4 color;\nuniform sampler2D mainTexture;\nlayout(std140) uniform FragConstants {\nvec4 tintColor;\n};\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\nreturn CCFragOutput(col);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\nin vec3 a_position;\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\nvec4 frag () {\nvec4 o = vec4(1.0);\nreturn o;\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nin vec2 a_position;\nin vec2 a_texCoord;\nin vec4 a_color;\nout vec2 v_texCoord;\nout vec4 v_color;\nvec4 vert () {\nint orientation = int(cc_surfaceTransform.x);\nvec4 transform = vec4(1.0, 0.0, 0.0, 1.0);\nif (orientation == 0) {\ntransform = vec4(1.0, 0.0, 0.0, 1.0);\n} else if (orientation == 1) {\ntransform = vec4(0.0, 1.0, -1.0, 0.0);\n} else if (orientation == 2) {\ntransform = vec4(-1.0, 0.0, 0.0, -1.0);\n} else if (orientation == 3) {\ntransform = vec4(0.0, -1.0, 1.0, 0.0);\n}\nvec2 invScreenSize = (orientation == 1 || orientation == 3) ? cc_screenSize.wz : cc_screenSize.zw;\nvec2 position = a_position * invScreenSize;\nposition = position * vec2(2.0, -2.0) + vec2(-1.0, 1.0);\nvec2 clipPos = vec2(dot(transform.xy, position), dot(transform.zw, position));\nclipPos = cc_cameraPos.w == 0.0 ? vec2(clipPos.x, -clipPos.y) : clipPos;\nv_texCoord = a_texCoord;\nv_color = a_color;\nreturn vec4(clipPos, 0.0, 1.0);\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nin vec2 v_texCoord;\nin vec4 v_color;\nuniform sampler2D mainTexture;\nvec4 frag () {\nvec4 color = vec4(v_color.rgb, v_color.a * texture(mainTexture, v_texCoord).r);\nreturn CCFragOutput(color);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nin highp vec3 a_position;\nin vec4 a_color;\nout vec4 v_color;\nvec4 vert () {\nvec4 pos = cc_matViewProj * vec4(a_position, 1);\npos.z -= 0.000001;\nv_color = a_color;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nin vec4 v_color;\nvec4 front() {\n#if USE_FORWARD_PIPELINE\nreturn CCFragOutput(v_color);\n#else\nreturn v_color;\n#endif\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = front(); }", - }, - { - "vert": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nin highp vec3 a_position;\nin vec4 a_color;\nout vec4 v_color;\nvec4 vert () {\nvec4 pos = cc_matViewProj * vec4(a_position, 1);\npos.z -= 0.000001;\nv_color = a_color;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nin vec4 v_color;\nvec4 back() {\n#if USE_FORWARD_PIPELINE\nreturn CCFragOutput(vec4(v_color.rgb, v_color.a * 0.2));\n#else\nreturn vec4(v_color.rgb, v_color.a * 0.2);\n#endif\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = back(); }", - }, - { - "vert": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nin highp vec3 a_position;\nin vec4 a_color;\nout vec4 v_color;\nout float v_distance;\nvec4 vert () {\nvec4 pos = cc_matViewProj * vec4(a_position, 1);\npos.z -= 0.000001;\nv_color = a_color;\nv_distance = dot(a_position, vec3(1.0, 1.0, 1.0));\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nin vec4 v_color;\nin float v_distance;\nvec4 front() {\nif (fract(v_distance) > 0.5) {\ndiscard;\n}\n#if USE_FORWARD_PIPELINE\nreturn CCFragOutput(v_color);\n#else\nreturn v_color;\n#endif\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = front(); }", - }, - { - "vert": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nin highp vec3 a_position;\nin vec4 a_color;\nout vec4 v_color;\nout float v_distance;\nvec4 vert () {\nvec4 pos = cc_matViewProj * vec4(a_position, 1);\npos.z -= 0.000001;\nv_color = a_color;\nv_distance = dot(a_position, vec3(1.0, 1.0, 1.0));\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nin vec4 v_color;\nin float v_distance;\nvec4 back() {\nif (fract(v_distance) > 0.5) {\ndiscard;\n}\n#if USE_FORWARD_PIPELINE\nreturn CCFragOutput(vec4(v_color.rgb, v_color.a * 0.2));\n#else\nreturn vec4(v_color.rgb, v_color.a * 0.2);\n#endif\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = back(); }", - }, - { - "vert": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nin highp vec3 a_position;\nin vec4 a_normal;\nin vec4 a_color;\nout vec4 v_color;\nvec4 vert () {\nvec4 pos = cc_matViewProj * vec4(a_position, 1);\nv_color = a_color;\nfloat intensity = dot(vec3(1, 2, 4), a_normal.xyz);\nv_color.rgb -= a_normal.w * intensity * 0.1;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nin vec4 v_color;\nvec4 front() {\n#if USE_FORWARD_PIPELINE\nreturn CCFragOutput(v_color);\n#else\nreturn v_color;\n#endif\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = front(); }", - }, - { - "vert": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nin highp vec3 a_position;\nin vec4 a_normal;\nin vec4 a_color;\nout vec4 v_color;\nvec4 vert () {\nvec4 pos = cc_matViewProj * vec4(a_position, 1);\nv_color = a_color;\nfloat intensity = dot(vec3(1, 2, 4), a_normal.xyz);\nv_color.rgb -= a_normal.w * intensity * 0.1;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nin vec4 v_color;\nvec4 back() {\n#if USE_FORWARD_PIPELINE\nreturn CCFragOutput(vec4(v_color.rgb, v_color.a * 0.2));\n#else\nreturn vec4(v_color.rgb, v_color.a * 0.2);\n#endif\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = back(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nin vec3 a_position;\nin vec4 a_color;\nout vec4 v_color;\nin float a_dist;\nout float v_dist;\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\npos = cc_matViewProj * cc_matWorld * pos;\nv_color = a_color;\nv_dist = a_dist;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\nin vec4 v_color;\nin float v_dist;\nvec4 frag () {\nvec4 o = v_color;\nfloat aa = fwidth(v_dist);\nfloat alpha = 1. - smoothstep(-aa, 0., abs(v_dist) - 1.0);\no.rgb *= o.a;\no *= alpha;\nreturn o;\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(std140) uniform CCWorldBound {\nhighp vec4 cc_worldBoundCenter;\nhighp vec4 cc_worldBoundHalfExtents;\n};\nin vec3 a_position;\nvec4 vert () {\nvec4 position;\nposition = vec4(a_position, 1.0);\nposition *= cc_worldBoundHalfExtents;\nposition += cc_worldBoundCenter;\nposition = cc_matViewProj * position;\nreturn position;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nvec4 frag () {\nreturn vec4(1, 0, 0, 1);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\nmat3 m = mat3(xAxis,yAxis,zAxis);\nfloat trace = m[0][0] + m[1][1] + m[2][2];\nvec4 quat;\nif (trace > 0.) {\nfloat s = 0.5 / sqrt(trace + 1.0);\nquat.w = 0.25 / s;\nquat.x = (m[2][1] - m[1][2]) * s;\nquat.y = (m[0][2] - m[2][0]) * s;\nquat.z = (m[1][0] - m[0][1]) * s;\n} else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\nfloat s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\nquat.w = (m[2][1] - m[1][2]) / s;\nquat.x = 0.25 * s;\nquat.y = (m[0][1] + m[1][0]) / s;\nquat.z = (m[0][2] + m[2][0]) / s;\n} else if (m[1][1] > m[2][2]) {\nfloat s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\nquat.w = (m[0][2] - m[2][0]) / s;\nquat.x = (m[0][1] + m[1][0]) / s;\nquat.y = 0.25 * s;\nquat.z = (m[1][2] + m[2][1]) / s;\n} else {\nfloat s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\nquat.w = (m[1][0] - m[0][1]) / s;\nquat.x = (m[0][2] + m[2][0]) / s;\nquat.y = (m[1][2] + m[2][1]) / s;\nquat.z = 0.25 * s;\n}\nfloat len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\nif (len > 0.) {\nlen = 1. / sqrt(len);\nquat.x = quat.x * len;\nquat.y = quat.y * len;\nquat.z = quat.z * len;\nquat.w = quat.w * len;\n}\nreturn quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\nfloat x = angle.x / 2.;\nfloat y = angle.y / 2.;\nfloat z = angle.z / 2.;\nfloat sx = sin(x);\nfloat cx = cos(x);\nfloat sy = sin(y);\nfloat cy = cos(y);\nfloat sz = sin(z);\nfloat cz = cos(z);\nvec4 quat = vec4(0);\nquat.x = sx * cy * cz + cx * sy * sz;\nquat.y = cx * sy * cz + sx * cy * sz;\nquat.z = cx * cy * sz - sx * sy * cz;\nquat.w = cx * cy * cz - sx * sy * sz;\nreturn quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\nfloat x2 = q.x + q.x;\nfloat y2 = q.y + q.y;\nfloat z2 = q.z + q.z;\nfloat xx = q.x * x2;\nfloat xy = q.x * y2;\nfloat xz = q.x * z2;\nfloat yy = q.y * y2;\nfloat yz = q.y * z2;\nfloat zz = q.z * z2;\nfloat wx = q.w * x2;\nfloat wy = q.w * y2;\nfloat wz = q.w * z2;\nreturn mat4(\n1. - (yy + zz), xy + wz, xz - wy, 0,\nxy - wz, 1. - (xx + zz), yz + wx, 0,\nxz + wy, yz - wx, 1. - (xx + yy), 0,\np.x, p.y, p.z, 1\n);\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\nfloat x = q.x, y = q.y, z = q.z, w = q.w;\nfloat x2 = x + x;\nfloat y2 = y + y;\nfloat z2 = z + z;\nfloat xx = x * x2;\nfloat xy = x * y2;\nfloat xz = x * z2;\nfloat yy = y * y2;\nfloat yz = y * z2;\nfloat zz = z * z2;\nfloat wx = w * x2;\nfloat wy = w * y2;\nfloat wz = w * z2;\nfloat sx = s.x;\nfloat sy = s.y;\nfloat sz = s.z;\nreturn mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n(xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n(xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\nt.x, t.y, t.z, 1);\n}\nvec4 quatMultiply (vec4 a, vec4 b){\nvec4 quat;\nquat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\nquat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\nquat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\nquat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\nreturn quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\nfloat ix = q.w * v.x + q.y * v.z - q.z * v.y;\nfloat iy = q.w * v.y + q.z * v.x - q.x * v.z;\nfloat iz = q.w * v.z + q.x * v.y - q.y * v.x;\nfloat iw = -q.x * v.x - q.y * v.y - q.z * v.z;\nv.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\nv.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\nv.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\nvec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\nvec4 rotQuat = quatMultiply(viewQuat, q);\nrotateVecFromQuat(pos, rotQuat);\nreturn pos;\n}\nmat3 quatToMat3(vec4 q) {\nvec3 m0 = vec3(\n1.0 - 2.0 * q.y * q.y - 2.0 * q.z * q.z,\n2.0 * q.x * q.y + 2.0 * q.w * q.z,\n2.0 * q.x * q.z - 2.0 * q.w * q.y);\nvec3 m1 = vec3(\n2.0 * q.x * q.y - 2.0 * q.w * q.z,\n1.0 - 2.0 * q.x * q.x - 2.0 * q.z * q.z,\n2.0 * q.y * q.z + 2.0 * q.w * q.x);\nvec3 m2 = vec3(\n2.0 * q.x * q.z + 2.0 * q.w * q.y,\n2.0 * q.y * q.z - 2.0 * q.w * q.x,\n1.0 - 2.0 * q.x * q.x - 2.0 * q.y * q.y);\nreturn mat3(m0, m1, m2);\n}\nvec4 mat3ToQuat(mat3 mat) {\nfloat tr = mat[0][0] + mat[1][1] + mat[2][2];\nfloat qw, qx, qy, qz;\nif (tr > 0.0) {\nfloat S = sqrt(tr + 1.0) * 2.0;\nfloat invS = 1.0 / S;\nqw = 0.25 * S;\nqx = (mat[1][2] - mat[2][1]) * invS;\nqy = (mat[2][0] - mat[0][2]) * invS;\nqz = (mat[0][1] - mat[1][0]) * invS;\n} else if ((mat[0][0] > mat[1][1])&&(mat[0][0] > mat[2][2])) {\nfloat S = sqrt(1.0 + mat[0][0] - mat[1][1] - mat[2][2]) * 2.0;\nfloat invS = 1.0 / S;\nqw = (mat[1][2] - mat[2][1]) * invS;\nqx = 0.25 * S;\nqy = (mat[1][0] + mat[0][1]) * invS;\nqz = (mat[2][0] + mat[0][2]) * invS;\n} else if (mat[1][1] > mat[2][2]) {\nfloat S = sqrt(1.0 + mat[1][1] - mat[0][0] - mat[2][2]) * 2.0;\nfloat invS = 1.0 / S;\nqw = (mat[2][0] - mat[0][2]) * invS;\nqx = (mat[1][0] + mat[0][1]) * invS;\nqy = 0.25 * S;\nqz = (mat[2][1] + mat[1][2]) * invS;\n} else {\nfloat S = sqrt(1.0 + mat[2][2] - mat[0][0] - mat[1][1]) * 2.0;\nfloat invS = 1.0 / S;\nqw = (mat[0][1] - mat[1][0]) * invS;\nqx = (mat[2][0] + mat[0][2]) * invS;\nqy = (mat[2][1] + mat[1][2]) * invS;\nqz = 0.25 * S;\n}\nreturn vec4(qx, qy, qz, qw);\n}\nvec4 eulerToQuat(vec3 euler) {\nvec3 er = euler * 0.5;\nfloat x = er.x, y = er.y, z = er.z;\nfloat sx = sin(x);\nfloat cx = cos(x);\nfloat sy = sin(y);\nfloat cy = cos(y);\nfloat sz = sin(z);\nfloat cz = cos(z);\nvec4 quat;\nquat.x = sx * cy * cz + cx * sy * sz;\nquat.y = cx * sy * cz + sx * cy * sz;\nquat.z = cx * cy * sz - sx * sy * cz;\nquat.w = cx * cy * cz - sx * sy * sz;\nreturn quat;\n}\nlayout(std140) uniform Constants {\nvec4 mainTiling_Offset;\nvec4 frameTile_velLenScale;\nvec4 scale;\nvec4 nodeRotation;\n};\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nout mediump vec2 uv;\nout mediump vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n, mat4 viewInv\n#endif\n#if CC_RENDER_MODE == 1\n, vec3 eye\n, vec4 velocity\n, float velocityScale\n, float lengthScale\n, float xIndex\n#endif\n) {\n#if CC_RENDER_MODE == 0\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\nvec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\nvec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_RENDER_MODE == 1\nvec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\nvec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\npos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_RENDER_MODE == 2\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = vec3(1, 0, 0);\nvec3 camY = vec3(0, 0, -1);\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_RENDER_MODE == 3\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nrotateVecFromQuat(viewSpaceVert, q);\nvec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\nvec3 camY = vec3(0, 1, 0);\nvec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\npos.xyz += offset;\n#else\npos.x += vertOffset.x;\npos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV (float frameIndex, vec2 vertIndex, vec2 frameTile){\nvec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\naniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if CC_RENDER_MODE != 4\nvertIndex.y = 1. - vertIndex.y;\n#endif\nreturn (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nlayout(std140) uniform SampleConstants {\nvec4 u_sampleInfo;\n};\nlayout(std140) uniform TickConstants {\nvec4 u_worldRot;\nvec4 u_timeDelta;\n};\nin vec4 a_position_starttime;\nin vec4 a_size_uv;\nin vec4 a_rotation_uv;\nin vec4 a_color;\nin vec4 a_dir_life;\nin float a_rndSeed;\n#if CC_RENDER_MODE == 4\nin vec3 a_texCoord;\nin vec3 a_texCoord3;\nin vec3 a_normal;\nin vec4 a_color1;\n#endif\nvec3 unpackCurveData (sampler2D tex, vec2 coord) {\nvec4 a = texture(tex, coord);\nvec4 b = texture(tex, coord + u_sampleInfo.y);\nfloat c = fract(coord.x * u_sampleInfo.x);\nreturn mix(a.xyz, b.xyz, c);\n}\nvec3 unpackCurveData (sampler2D tex, vec2 coord, out float w) {\nvec4 a = texture(tex, coord);\nvec4 b = texture(tex, coord + u_sampleInfo.y);\nfloat c = fract(coord.x * u_sampleInfo.x);\nw = mix(a.w, b.w, c);\nreturn mix(a.xyz, b.xyz, c);\n}\nfloat pseudoRandom(float x) {\n#if USE_VK_SHADER\nfloat o = x;\nx = mod(x - 1.0, 2.0) - 1.0;\nfloat freqVar = 10.16640753482;\nfloat y = sin(freqVar * floor(o * 0.5 - 0.5));\nfloat v = max(0.0, 1.0-abs(x));\nv *= 0.7071067812;\nv = y < 0.0 ? -v : v;\nreturn v;\n#else\nfloat seed = mod(x, 233280.);\nfloat q = (seed * 9301. + 49297.) / 233280.;\nreturn fract(q);\n#endif\n}\n#if COLOR_OVER_TIME_MODULE_ENABLE\nuniform sampler2D color_over_time_tex0;\nlayout(std140) uniform ColorConstant {\nint u_color_mode;\n};\n#endif\n#if ROTATION_OVER_TIME_MODULE_ENABLE\nuniform sampler2D rotation_over_time_tex0;\nlayout(std140) uniform RotationConstant {\nint u_rotation_mode;\n};\n#endif\n#if SIZE_OVER_TIME_MODULE_ENABLE\nuniform sampler2D size_over_time_tex0;\nlayout(std140) uniform SizeConstant {\nint u_size_mode;\n};\n#endif\n#if FORCE_OVER_TIME_MODULE_ENABLE\nuniform sampler2D force_over_time_tex0;\nlayout(std140) uniform ForceConstant {\nint u_force_mode;\nint u_force_space;\n};\n#endif\n#if VELOCITY_OVER_TIME_MODULE_ENABLE\nuniform sampler2D velocity_over_time_tex0;\nlayout(std140) uniform VelocityConstant {\nint u_velocity_mode;\nint u_velocity_space;\n};\n#endif\n#if TEXTURE_ANIMATION_MODULE_ENABLE\nuniform sampler2D texture_animation_tex0;\nlayout(std140) uniform AnimationConstant {\nvec4 u_anim_info;\n};\n#endif\nfloat repeat (float t, float length) {\nreturn t - floor(t / length) * length;\n}\nvec4 rotateQuat (vec4 p, vec4 q) {\nvec3 iv = cross(q.xyz, p.xyz) + q.w * p.xyz;\nvec3 res = p.xyz + 2.0 * cross(q.xyz, iv);\nreturn vec4(res.xyz, p.w);\n}\nvec4 gpvs_main () {\nfloat activeTime = u_timeDelta.x - a_position_starttime.w;\nfloat normalizedTime = clamp(activeTime / a_dir_life.w, 0.0, 1.0);\nvec2 timeCoord0 = vec2(normalizedTime, 0.);\nvec2 timeCoord1 = vec2(normalizedTime, 1.);\n#if CC_RENDER_MODE == 4\nvec2 vertIdx = vec2(a_texCoord.x, a_texCoord.y);\n#else\nvec2 vertIdx = vec2(a_size_uv.w, a_rotation_uv.w);\n#endif\nvec4 velocity = vec4(a_dir_life.xyz, 0.);\nvec4 pos = vec4(a_position_starttime.xyz, 1.);\nvec3 size = a_size_uv.xyz;\n#if SIZE_OVER_TIME_MODULE_ENABLE\nif (u_size_mode == 1) {\nsize *= unpackCurveData(size_over_time_tex0, timeCoord0);\n} else {\nvec3 size_0 = unpackCurveData(size_over_time_tex0, timeCoord0);\nvec3 size_1 = unpackCurveData(size_over_time_tex0, timeCoord1);\nfloat factor_s = pseudoRandom(a_rndSeed + 39825.);\nsize *= mix(size_0, size_1, factor_s);\n}\n#endif\nvec3 compScale = scale.xyz * size;\n#if FORCE_OVER_TIME_MODULE_ENABLE\nvec3 forceAnim = vec3(0.);\nif (u_force_mode == 1) {\nforceAnim = unpackCurveData(force_over_time_tex0, timeCoord0);\n} else {\nvec3 force_0 = unpackCurveData(force_over_time_tex0, timeCoord0);\nvec3 force_1 = unpackCurveData(force_over_time_tex0, timeCoord1);\nfloat factor_f = pseudoRandom(a_rndSeed + 212165.);\nforceAnim = mix(force_0, force_1, factor_f);\n}\nvec4 forceTrack = vec4(forceAnim, 0.);\nif (u_force_space == 0) {\nforceTrack = rotateQuat(forceTrack, u_worldRot);\n}\nvelocity.xyz += forceTrack.xyz;\n#endif\n#if VELOCITY_OVER_TIME_MODULE_ENABLE\nfloat speedModifier0 = 1.;\nfloat speedModifier1 = 1.;\nvec3 velocityAnim = vec3(0.);\nif (u_velocity_mode == 1) {\nvelocityAnim = unpackCurveData(velocity_over_time_tex0, timeCoord0, speedModifier0);\n} else {\nvec3 vectory_0 = unpackCurveData(velocity_over_time_tex0, timeCoord0, speedModifier0);\nvec3 vectory_1 = unpackCurveData(velocity_over_time_tex0, timeCoord1, speedModifier1);\nfloat factor_v = pseudoRandom(a_rndSeed + 197866.);\nvelocityAnim = mix(vectory_0, vectory_1, factor_v);\nspeedModifier0 = mix(speedModifier0, speedModifier1, factor_v);\n}\nvec4 velocityTrack = vec4(velocityAnim, 0.);\nif (u_velocity_space == 0) {\nvelocityTrack = rotateQuat(velocityTrack, u_worldRot);\n}\nvelocity.xyz += velocityTrack.xyz;\nvelocity.xyz *= speedModifier0;\n#endif\npos.xyz += velocity.xyz * normalizedTime * a_dir_life.w;\n#if !CC_USE_WORLD_SPACE\npos = cc_matWorld * pos;\n#if CC_RENDER_MODE == 1\nvelocity = rotateQuat(velocity, u_worldRot);\n#endif\n#endif\nvec3 startRotation = a_rotation_uv.xyz;\n#if CC_RENDER_MODE != 4\n#if CC_RENDER_MODE == 0\nvec3 rotEuler = startRotation.xyz;\n#elif CC_RENDER_MODE == 1\nvec3 rotEuler = vec3(0.);\n#else\nvec3 rotEuler = vec3(0., 0., startRotation.z);\n#endif\nvec4 rot = quaternionFromEuler(rotEuler);\n#else\nvec4 rot = quaternionFromEuler(startRotation);\n#endif\n#if ROTATION_OVER_TIME_MODULE_ENABLE\nif (u_rotation_mode == 1) {\nvec3 euler = unpackCurveData(rotation_over_time_tex0, timeCoord0) * normalizedTime * a_dir_life.w;\nvec4 quat = eulerToQuat(euler);\nmat3 mLocal = quatToMat3(quat);\nmat3 mStart = quatToMat3(rot);\nrot = mat3ToQuat(mStart * mLocal);\n} else {\nvec3 rotation_0 = unpackCurveData(rotation_over_time_tex0, timeCoord0);\nvec3 rotation_1 = unpackCurveData(rotation_over_time_tex0, timeCoord1);\nfloat factor_r = pseudoRandom(a_rndSeed + 125292.);\nvec3 euler = mix(rotation_0, rotation_1, factor_r) * normalizedTime * a_dir_life.w;\n#if CC_RENDER_MODE == 3 || CC_RENDER_MODE == 2\neuler = vec3(0.0, 0.0, euler.z);\n#endif\nvec4 quat = eulerToQuat(euler);\nmat3 mLocal = quatToMat3(quat);\nmat3 mStart = quatToMat3(rot);\nrot = mat3ToQuat(mStart * mLocal);\n}\n#endif\n#if COLOR_OVER_TIME_MODULE_ENABLE\nif (u_color_mode == 1) {\ncolor = a_color * texture(color_over_time_tex0, timeCoord0);\n} else {\nvec4 color_0 = texture(color_over_time_tex0, timeCoord0);\nvec4 color_1 = texture(color_over_time_tex0, timeCoord1);\nfloat factor_c = pseudoRandom(a_rndSeed + 91041.);\ncolor = a_color * mix(color_0, color_1, factor_c);\n}\n#else\ncolor = a_color;\n#endif\n#if CC_RENDER_MODE != 4\nvec2 cornerOffset = vec2((vertIdx - 0.5));\n#if CC_RENDER_MODE == 1\nrot = vec4(0.0, 0.0, 0.0, 1.0);\n#endif\ncomputeVertPos(pos, cornerOffset, rot, compScale\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n, cc_matViewInv\n#endif\n#if CC_RENDER_MODE == 1\n, cc_cameraPos.xyz\n, velocity\n, frameTile_velLenScale.z\n, frameTile_velLenScale.w\n, a_size_uv.w\n#endif\n);\n#else\nmat3 rotMat = quatToMat3(rot);\nmat3 nodeMat = quatToMat3(nodeRotation);\nrotMat = nodeMat * rotMat;\nrot = mat3ToQuat(rotMat);\nmat4 xformNoScale = matrixFromRT(rot, pos.xyz);\nmat4 xform = matFromRTS(rot, pos.xyz, compScale);\npos = xform * vec4(a_texCoord3, 1);\nvec4 normal = xformNoScale * vec4(a_normal, 0);\ncolor *= a_color1;\n#endif\npos = cc_matViewProj * pos;\nfloat frameIndex = 0.;\n#if TEXTURE_ANIMATION_MODULE_ENABLE\nfloat startFrame = 0.;\nvec3 frameInfo = vec3(0.);\nif (int(u_anim_info.x) == 1) {\nframeInfo = unpackCurveData(texture_animation_tex0, timeCoord0);\n} else {\nvec3 frameInfo0 = unpackCurveData(texture_animation_tex0, timeCoord0);\nvec3 frameInfo1 = unpackCurveData(texture_animation_tex0, timeCoord1);\nfloat factor_t = pseudoRandom(a_rndSeed + 90794.);\nframeInfo = mix(frameInfo0, frameInfo1, factor_t);\n}\nstartFrame = frameInfo.x / u_anim_info.y;\nframeIndex = repeat(u_anim_info.z * (frameInfo.y + startFrame), 1.);\n#endif\nuv = computeUV(frameIndex, vertIdx, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\nreturn pos;\n}\nvoid main() { gl_Position = gpvs_main(); }", - "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nin vec2 uv;\nin vec4 color;\nuniform sampler2D mainTexture;\nlayout(std140) uniform FragConstants {\nvec4 tintColor;\n};\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\nreturn CCFragOutput(col);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nlayout(std140) uniform Constants {\nvec4 mainTiling_Offset;\nvec4 frameTile_velLenScale;\nvec4 scale;\nvec4 nodeRotation;\n};\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nout mediump vec2 uv;\nout mediump vec4 color;\nin vec3 a_position;\nin vec4 a_texCoord;\nin vec3 a_texCoord1;\nin vec3 a_texCoord2;\nin vec4 a_color;\n#if CC_DRAW_WIRE_FRAME\nout vec3 vBarycentric;\n#endif\nvec4 vs_main() {\nhighp vec4 pos = vec4(a_position, 1);\nvec4 velocity = vec4(a_texCoord1.xyz, 0);\n#if !CC_USE_WORLD_SPACE\npos = cc_matWorld * pos;\nvelocity = cc_matWorld * velocity;\n#endif\nfloat vertOffset = (a_texCoord.x - 0.5) * a_texCoord.y;\nvec3 camUp = normalize(cross(pos.xyz - cc_cameraPos.xyz, velocity.xyz));\npos.xyz += camUp * vertOffset;\npos = cc_matViewProj * pos;\nuv = a_texCoord.zw * mainTiling_Offset.xy + mainTiling_Offset.zw;;\ncolor = a_color;\n#if CC_DRAW_WIRE_FRAME\nvBarycentric = a_texCoord2;\n#endif\nreturn pos;\n}\nvoid main() { gl_Position = vs_main(); }", - "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nin vec2 uv;\nin vec4 color;\n#if CC_DRAW_WIRE_FRAME\nin vec3 vBarycentric;\n#endif\nuniform sampler2D mainTexture;\nlayout(std140) uniform FragConstants {\nvec4 tintColor;\n};\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n#if CC_DRAW_WIRE_FRAME\nif (any(lessThan(vBarycentric, vec3(0.02)))) {\ncol = vec4(0., 1., 1., 1.);\n}\n#endif\nreturn CCFragOutput(col);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\nmat3 m = mat3(xAxis,yAxis,zAxis);\nfloat trace = m[0][0] + m[1][1] + m[2][2];\nvec4 quat;\nif (trace > 0.) {\nfloat s = 0.5 / sqrt(trace + 1.0);\nquat.w = 0.25 / s;\nquat.x = (m[2][1] - m[1][2]) * s;\nquat.y = (m[0][2] - m[2][0]) * s;\nquat.z = (m[1][0] - m[0][1]) * s;\n} else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\nfloat s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\nquat.w = (m[2][1] - m[1][2]) / s;\nquat.x = 0.25 * s;\nquat.y = (m[0][1] + m[1][0]) / s;\nquat.z = (m[0][2] + m[2][0]) / s;\n} else if (m[1][1] > m[2][2]) {\nfloat s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\nquat.w = (m[0][2] - m[2][0]) / s;\nquat.x = (m[0][1] + m[1][0]) / s;\nquat.y = 0.25 * s;\nquat.z = (m[1][2] + m[2][1]) / s;\n} else {\nfloat s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\nquat.w = (m[1][0] - m[0][1]) / s;\nquat.x = (m[0][2] + m[2][0]) / s;\nquat.y = (m[1][2] + m[2][1]) / s;\nquat.z = 0.25 * s;\n}\nfloat len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\nif (len > 0.) {\nlen = 1. / sqrt(len);\nquat.x = quat.x * len;\nquat.y = quat.y * len;\nquat.z = quat.z * len;\nquat.w = quat.w * len;\n}\nreturn quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\nfloat x = angle.x / 2.;\nfloat y = angle.y / 2.;\nfloat z = angle.z / 2.;\nfloat sx = sin(x);\nfloat cx = cos(x);\nfloat sy = sin(y);\nfloat cy = cos(y);\nfloat sz = sin(z);\nfloat cz = cos(z);\nvec4 quat = vec4(0);\nquat.x = sx * cy * cz + cx * sy * sz;\nquat.y = cx * sy * cz + sx * cy * sz;\nquat.z = cx * cy * sz - sx * sy * cz;\nquat.w = cx * cy * cz - sx * sy * sz;\nreturn quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\nfloat x2 = q.x + q.x;\nfloat y2 = q.y + q.y;\nfloat z2 = q.z + q.z;\nfloat xx = q.x * x2;\nfloat xy = q.x * y2;\nfloat xz = q.x * z2;\nfloat yy = q.y * y2;\nfloat yz = q.y * z2;\nfloat zz = q.z * z2;\nfloat wx = q.w * x2;\nfloat wy = q.w * y2;\nfloat wz = q.w * z2;\nreturn mat4(\n1. - (yy + zz), xy + wz, xz - wy, 0,\nxy - wz, 1. - (xx + zz), yz + wx, 0,\nxz + wy, yz - wx, 1. - (xx + yy), 0,\np.x, p.y, p.z, 1\n);\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\nfloat x = q.x, y = q.y, z = q.z, w = q.w;\nfloat x2 = x + x;\nfloat y2 = y + y;\nfloat z2 = z + z;\nfloat xx = x * x2;\nfloat xy = x * y2;\nfloat xz = x * z2;\nfloat yy = y * y2;\nfloat yz = y * z2;\nfloat zz = z * z2;\nfloat wx = w * x2;\nfloat wy = w * y2;\nfloat wz = w * z2;\nfloat sx = s.x;\nfloat sy = s.y;\nfloat sz = s.z;\nreturn mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n(xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n(xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\nt.x, t.y, t.z, 1);\n}\nvec4 quatMultiply (vec4 a, vec4 b){\nvec4 quat;\nquat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\nquat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\nquat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\nquat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\nreturn quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\nfloat ix = q.w * v.x + q.y * v.z - q.z * v.y;\nfloat iy = q.w * v.y + q.z * v.x - q.x * v.z;\nfloat iz = q.w * v.z + q.x * v.y - q.y * v.x;\nfloat iw = -q.x * v.x - q.y * v.y - q.z * v.z;\nv.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\nv.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\nv.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\nvec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\nvec4 rotQuat = quatMultiply(viewQuat, q);\nrotateVecFromQuat(pos, rotQuat);\nreturn pos;\n}\nmat3 quatToMat3(vec4 q) {\nvec3 m0 = vec3(\n1.0 - 2.0 * q.y * q.y - 2.0 * q.z * q.z,\n2.0 * q.x * q.y + 2.0 * q.w * q.z,\n2.0 * q.x * q.z - 2.0 * q.w * q.y);\nvec3 m1 = vec3(\n2.0 * q.x * q.y - 2.0 * q.w * q.z,\n1.0 - 2.0 * q.x * q.x - 2.0 * q.z * q.z,\n2.0 * q.y * q.z + 2.0 * q.w * q.x);\nvec3 m2 = vec3(\n2.0 * q.x * q.z + 2.0 * q.w * q.y,\n2.0 * q.y * q.z - 2.0 * q.w * q.x,\n1.0 - 2.0 * q.x * q.x - 2.0 * q.y * q.y);\nreturn mat3(m0, m1, m2);\n}\nvec4 mat3ToQuat(mat3 mat) {\nfloat tr = mat[0][0] + mat[1][1] + mat[2][2];\nfloat qw, qx, qy, qz;\nif (tr > 0.0) {\nfloat S = sqrt(tr + 1.0) * 2.0;\nfloat invS = 1.0 / S;\nqw = 0.25 * S;\nqx = (mat[1][2] - mat[2][1]) * invS;\nqy = (mat[2][0] - mat[0][2]) * invS;\nqz = (mat[0][1] - mat[1][0]) * invS;\n} else if ((mat[0][0] > mat[1][1])&&(mat[0][0] > mat[2][2])) {\nfloat S = sqrt(1.0 + mat[0][0] - mat[1][1] - mat[2][2]) * 2.0;\nfloat invS = 1.0 / S;\nqw = (mat[1][2] - mat[2][1]) * invS;\nqx = 0.25 * S;\nqy = (mat[1][0] + mat[0][1]) * invS;\nqz = (mat[2][0] + mat[0][2]) * invS;\n} else if (mat[1][1] > mat[2][2]) {\nfloat S = sqrt(1.0 + mat[1][1] - mat[0][0] - mat[2][2]) * 2.0;\nfloat invS = 1.0 / S;\nqw = (mat[2][0] - mat[0][2]) * invS;\nqx = (mat[1][0] + mat[0][1]) * invS;\nqy = 0.25 * S;\nqz = (mat[2][1] + mat[1][2]) * invS;\n} else {\nfloat S = sqrt(1.0 + mat[2][2] - mat[0][0] - mat[1][1]) * 2.0;\nfloat invS = 1.0 / S;\nqw = (mat[0][1] - mat[1][0]) * invS;\nqx = (mat[2][0] + mat[0][2]) * invS;\nqy = (mat[2][1] + mat[1][2]) * invS;\nqz = 0.25 * S;\n}\nreturn vec4(qx, qy, qz, qw);\n}\nlayout(std140) uniform Constants {\nvec4 mainTiling_Offset;\nvec4 frameTile_velLenScale;\nvec4 scale;\nvec4 nodeRotation;\n};\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nout mediump vec2 uv;\nout mediump vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n, mat4 viewInv\n#endif\n#if CC_RENDER_MODE == 1\n, vec3 eye\n, vec4 velocity\n, float velocityScale\n, float lengthScale\n, float xIndex\n#endif\n) {\n#if CC_RENDER_MODE == 0\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\nvec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\nvec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_RENDER_MODE == 1\nvec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\nvec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\npos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_RENDER_MODE == 2\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = vec3(1, 0, 0);\nvec3 camY = vec3(0, 0, -1);\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_RENDER_MODE == 3\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nrotateVecFromQuat(viewSpaceVert, q);\nvec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\nvec3 camY = vec3(0, 1, 0);\nvec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\npos.xyz += offset;\n#else\npos.x += vertOffset.x;\npos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV (float frameIndex, vec2 vertIndex, vec2 frameTile){\nvec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\naniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if CC_RENDER_MODE != 4\nvertIndex.y = 1. - vertIndex.y;\n#endif\nreturn (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nin vec3 a_position;\nin vec3 a_texCoord;\nin vec3 a_texCoord1;\nin vec3 a_texCoord2;\nin vec4 a_color;\n#if CC_RENDER_MODE == 1\nin vec3 a_color1;\n#endif\n#if CC_RENDER_MODE == 4\nin vec3 a_texCoord3;\nin vec3 a_normal;\nin vec4 a_color1;\n#endif\nvec4 lpvs_main () {\nvec3 compScale = scale.xyz * a_texCoord1;\nvec4 pos = vec4(a_position, 1);\n#if CC_RENDER_MODE == 1\nvec4 velocity = vec4(a_color1.xyz, 0);\n#endif\n#if !CC_USE_WORLD_SPACE\npos = cc_matWorld * pos;\n#if CC_RENDER_MODE == 1\nvelocity = cc_matWorld * velocity;\n#endif\n#endif\n#if ROTATION_OVER_TIME_MODULE_ENABLE\nvec3 rotTmp = a_texCoord2;\nfloat mulFactor = 1.0;\nif (rotTmp.x > 10.0 * 0.5) {\nrotTmp.x -= 10.0;\nmulFactor = -1.0;\n}\nvec4 rot = vec4(rotTmp, 0.0);\nrot.w = mulFactor * sqrt(abs(1.0 - rot.x * rot.x - rot.y * rot.y - rot.z * rot.z));\n#else\n#if CC_RENDER_MODE != 4\n#if CC_RENDER_MODE == 0\nvec3 rotEuler = a_texCoord2;\n#elif CC_RENDER_MODE == 1\nvec3 rotEuler = vec3(0.);\n#else\nvec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n#endif\nvec4 rot = quaternionFromEuler(rotEuler);\n#else\nvec4 rot = quaternionFromEuler(a_texCoord2);\n#endif\n#endif\n#if CC_RENDER_MODE != 4\nvec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\ncomputeVertPos(pos, cornerOffset, rot, compScale, cc_matViewInv);\n#elif CC_RENDER_MODE == 1\ncomputeVertPos(pos, cornerOffset, rot, compScale, cc_cameraPos.xyz, velocity, frameTile_velLenScale.z, frameTile_velLenScale.w, a_texCoord.x);\n#elif 2\ncomputeVertPos(pos, cornerOffset, rot, compScale);\n#endif\ncolor = a_color;\n#else\nmat3 rotMat = quatToMat3(rot);\nmat3 nodeMat = quatToMat3(nodeRotation);\nrotMat = nodeMat * rotMat;\nrot = mat3ToQuat(rotMat);\nmat4 xformNoScale = matrixFromRT(rot, pos.xyz);\nmat4 xform = matFromRTS(rot, pos.xyz, compScale);\npos = xform * vec4(a_texCoord3, 1);\nvec4 normal = xformNoScale * vec4(a_normal, 0);\ncolor = a_color * a_color1;\n#endif\nuv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\npos = cc_matViewProj * pos;\nreturn pos;\n}\nvoid main() { gl_Position = lpvs_main(); }", - "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nin vec2 uv;\nin vec4 color;\nuniform sampler2D mainTexture;\nlayout(std140) uniform FragConstants {\nvec4 tintColor;\n};\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\nreturn CCFragOutput(col);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_LOCAL\n#if USE_BATCHING\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\n#endif\nin vec3 a_position;\nin vec2 a_texCoord;\nin vec4 a_color;\nout vec4 v_light;\nout vec2 uv0;\n#if TWO_COLORED\nin vec4 a_color2;\nout vec4 v_dark;\n#endif\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\n#if USE_LOCAL\npos = cc_matWorld * pos;\n#endif\npos = cc_matViewProj * pos;\nuv0 = a_texCoord;\nv_light = a_color;\n#if TWO_COLORED\nv_dark = a_color2;\n#endif\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\n#if USE_ALPHA_TEST\nlayout(std140) uniform ALPHA_TEST_DATA {\nfloat alphaThreshold;\n};\n#endif\nvoid ALPHA_TEST (in vec4 color) {\n#if USE_ALPHA_TEST\nif (color.a < alphaThreshold) discard;\n#endif\n}\nvoid ALPHA_TEST (in float alpha) {\n#if USE_ALPHA_TEST\nif (alpha < alphaThreshold) discard;\n#endif\n}\nin vec4 v_light;\n#if TWO_COLORED\nin vec4 v_dark;\n#endif\nin vec2 uv0;\nuniform sampler2D cc_spriteTexture;\nvec4 frag () {\nvec4 o = vec4(1, 1, 1, 1);\n#if TWO_COLORED\nvec4 texColor = vec4(1, 1, 1, 1);\ntexColor *= texture(cc_spriteTexture, uv0);\no.a = texColor.a * v_light.a;\no.rgb = ((texColor.a - 1.0) * v_dark.a + 1.0 - texColor.rgb) * v_dark.rgb + texColor.rgb * v_light.rgb;\n#else\no *= texture(cc_spriteTexture, uv0);\no *= v_light;\n#endif\nALPHA_TEST(o);\nreturn o;\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_LOCAL\n#if USE_BATCHING\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\n#endif\n#if SAMPLE_FROM_RT\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\n#endif\nin vec3 a_position;\nin vec2 a_texCoord;\nin vec4 a_color;\nout vec4 color;\nout vec2 uv0;\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\n#if USE_LOCAL\npos = cc_matWorld * pos;\n#endif\n#if USE_PIXEL_ALIGNMENT\npos = cc_matView * pos;\npos.xyz = floor(pos.xyz);\npos = cc_matProj * pos;\n#else\npos = cc_matViewProj * pos;\n#endif\nuv0 = a_texCoord;\n#if SAMPLE_FROM_RT\nuv0 = cc_cameraPos.w > 1.0 ? vec2(uv0.x, 1.0 - uv0.y) : uv0;\n#endif\ncolor = a_color;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\nvec4 CCSampleWithAlphaSeparated(sampler2D tex, vec2 uv) {\n#if CC_USE_EMBEDDED_ALPHA\nreturn vec4(texture(tex, uv).rgb, texture(tex, uv + vec2(0.0, 0.5)).r);\n#else\nreturn texture(tex, uv);\n#endif\n}\n#if USE_ALPHA_TEST\nlayout(std140) uniform ALPHA_TEST_DATA {\nfloat alphaThreshold;\n};\n#endif\nvoid ALPHA_TEST (in vec4 color) {\n#if USE_ALPHA_TEST\nif (color.a < alphaThreshold) discard;\n#endif\n}\nvoid ALPHA_TEST (in float alpha) {\n#if USE_ALPHA_TEST\nif (alpha < alphaThreshold) discard;\n#endif\n}\nin vec4 color;\n#if USE_TEXTURE\nin vec2 uv0;\nuniform sampler2D cc_spriteTexture;\n#endif\nvec4 frag () {\nvec4 o = vec4(1, 1, 1, 1);\n#if USE_TEXTURE\no *= CCSampleWithAlphaSeparated(cc_spriteTexture, uv0);\n#if IS_GRAY\nfloat gray = 0.2126 * o.r + 0.7152 * o.g + 0.0722 * o.b;\no.r = o.g = o.b = gray;\n#endif\n#endif\no *= color;\nALPHA_TEST(o);\nreturn o;\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nin vec4 a_tangent;\n#if USE_INSTANCING\nin vec4 a_matWorld0;\nin vec4 a_matWorld1;\nin vec4 a_matWorld2;\n#if USE_LIGHTMAP\nin vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nin vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nin float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nin float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_joints;\nin vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nlayout(std140) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nin highp vec4 a_jointAnimInfo;\n#endif\nlayout(std140) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(std140) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nuniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nlayout(std140) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nvoid CCGetWorldMatrixFull(out mat4 matWorld, out mat4 matWorldIT)\n{\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\nmatWorldIT = matWorld;\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\nmatWorldIT = matWorld;\n#else\nmatWorld = cc_matWorld;\nmatWorldIT = cc_matWorldIT;\n#endif\n}\nlayout(std140) uniform Constants {\nvec4 tilingOffset;\nvec4 albedo;\nvec4 albedoScaleAndCutoff;\nvec4 pbrParams;\nvec4 emissive;\nvec4 emissiveScaleParam;\n};\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\n#if !CC_USE_ACCURATE_FOG\nout float v_fog_factor;\n#endif\nvoid CC_TRANSFER_FOG(vec4 pos) {\n#if !CC_USE_ACCURATE_FOG\nCC_TRANSFER_FOG_BASE(pos, v_fog_factor);\n#endif\n}\nout highp vec4 v_shadowPos;\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\n#if CC_RECEIVE_SHADOW\nuniform highp sampler2D cc_shadowMap;\nuniform highp sampler2D cc_spotLightingMap;\n#endif\n#if CC_RECEIVE_SHADOW\nvec2 CCGetShadowBias()\n{\n#if USE_INSTANCING\nreturn vec2(a_localShadowBias.x + cc_shadowWHPBInfo.w, a_localShadowBias.y + cc_shadowLPNNInfo.z);\n#else\nreturn vec2(cc_localShadowBias.x + cc_shadowWHPBInfo.w, cc_localShadowBias.y + cc_shadowLPNNInfo.z);\n#endif\n}\n#endif\n#if USE_VERTEX_COLOR\nin vec4 a_color;\nout vec4 v_color;\n#endif\nout vec3 v_position;\nout vec3 v_normal;\nout vec2 v_uv;\nout vec2 v_uv1;\n#if CC_RECEIVE_SHADOW\nout vec2 v_shadowBias;\n#endif\n#if USE_NORMAL_MAP\nout vec3 v_tangent;\nout vec3 v_bitangent;\n#endif\n#if HAS_SECOND_UV || USE_LIGHTMAP\nin vec2 a_texCoord1;\n#endif\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nout vec3 v_luv;\nvoid CCLightingMapCaclUV()\n{\n#if !USE_INSTANCING\nv_luv.xy = cc_lightingMapUVParam.xy + a_texCoord1 * cc_lightingMapUVParam.zw;\nv_luv.z = cc_lightingMapUVParam.z;\n#else\nv_luv.xy = a_lightingMapUVParam.xy + a_texCoord1 * a_lightingMapUVParam.zw;\nv_luv.z = a_lightingMapUVParam.z;\n#endif\n}\n#endif\nvoid main () {\nStandardVertInput In;\nCCVertInput(In);\nmat4 matWorld, matWorldIT;\nCCGetWorldMatrixFull(matWorld, matWorldIT);\nvec4 pos = matWorld * In.position;\nv_position = pos.xyz;\nv_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n#if CC_RECEIVE_SHADOW\nv_shadowBias = CCGetShadowBias();\n#endif\n#if USE_TWOSIDE\nvec3 viewDirect = normalize(cc_cameraPos.xyz - v_position);\nv_normal *= dot(v_normal, viewDirect) < 0.0 ? -1.0 : 1.0;\n#endif\n#if USE_NORMAL_MAP\nv_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\nv_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n#endif\nv_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n#if SAMPLE_FROM_RT\nv_uv = cc_cameraPos.w > 1.0 ? vec2(v_uv.x, 1.0 - v_uv.y) : v_uv;\n#endif\n#if HAS_SECOND_UV\nv_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n#if SAMPLE_FROM_RT\nv_uv1 = cc_cameraPos.w > 1.0 ? vec2(v_uv1.x, 1.0 - v_uv1.y) : v_uv1;\n#endif\n#endif\n#if USE_VERTEX_COLOR\nv_color = a_color;\n#endif\nCC_TRANSFER_FOG(pos);\nv_shadowPos = cc_matLightViewProj * pos;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nCCLightingMapCaclUV();\n#endif\ngl_Position = cc_matProj * (cc_matView * matWorld) * In.position;\n}", - "frag": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(std140) uniform Constants {\nvec4 tilingOffset;\nvec4 albedo;\nvec4 albedoScaleAndCutoff;\nvec4 pbrParams;\nvec4 emissive;\nvec4 emissiveScaleParam;\n};\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\nvoid CC_APPLY_FOG_BASE(inout vec4 color, float factor) {\ncolor = vec4(mix(cc_fogColor.rgb, color.rgb, factor), color.a);\n}\n#if !CC_USE_ACCURATE_FOG\nin float v_fog_factor;\n#endif\nvoid CC_APPLY_FOG(inout vec4 color) {\n#if !CC_USE_ACCURATE_FOG\nCC_APPLY_FOG_BASE(color, v_fog_factor);\n#endif\n}\nvoid CC_APPLY_FOG(inout vec4 color, vec3 worldPos) {\n#if CC_USE_ACCURATE_FOG\nfloat factor;\nCC_TRANSFER_FOG_BASE(vec4(worldPos, 1.0), factor);\n#else\nfloat factor = v_fog_factor;\n#endif\nCC_APPLY_FOG_BASE(color, factor);\n}\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\nhighp float unpackHighpData (float mainPart, float modPart) {\nhighp float data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out float mainPart, out float modPart, highp float data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp float unpackHighpData (float mainPart, float modPart, const float modValue) {\nhighp float data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out float mainPart, out float modPart, highp float data, const float modValue) {\nhighp float divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\nhighp vec2 unpackHighpData (vec2 mainPart, vec2 modPart) {\nhighp vec2 data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out vec2 mainPart, out vec2 modPart, highp vec2 data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp vec2 unpackHighpData (vec2 mainPart, vec2 modPart, const float modValue) {\nhighp vec2 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out vec2 mainPart, out vec2 modPart, highp vec2 data, const float modValue) {\nhighp vec2 divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\nhighp vec3 unpackHighpData (vec3 mainPart, vec3 modPart) {\nhighp vec3 data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out vec3 mainPart, out vec3 modPart, highp vec3 data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp vec3 unpackHighpData (vec3 mainPart, vec3 modPart, const float modValue) {\nhighp vec3 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out vec3 mainPart, out vec3 modPart, highp vec3 data, const float modValue) {\nhighp vec3 divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\nhighp vec4 unpackHighpData (vec4 mainPart, vec4 modPart) {\nhighp vec4 data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out vec4 mainPart, out vec4 modPart, highp vec4 data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp vec4 unpackHighpData (vec4 mainPart, vec4 modPart, const float modValue) {\nhighp vec4 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out vec4 mainPart, out vec4 modPart, highp vec4 data, const float modValue) {\nhighp vec4 divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\n#if USE_BATCHING\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nfloat CCGetLinearDepthFromViewSpace(vec3 viewPos) {\nfloat dist = length(viewPos);\nreturn (dist - cc_shadowNFLSInfo.x) / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x);\n}\nfloat CCGetLinearDepth(vec3 worldPos) {\nvec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0);\nreturn CCGetLinearDepthFromViewSpace(viewStartPos.xyz);\n}\n#if CC_RECEIVE_SHADOW\nuniform highp sampler2D cc_shadowMap;\nuniform highp sampler2D cc_spotLightingMap;\nvec4 ApplyShadowDepthBias_FaceNormal(vec4 shadowPos, vec3 worldNormal, float normalBias)\n{\nvec4 newShadowPos = shadowPos;\nif(normalBias > 0.0001)\n{\nvec4 viewNormal = cc_matLightView * vec4(worldNormal, 0.0);\nif(viewNormal.z < 0.1)\nnewShadowPos.xy += viewNormal.xy * cc_shadowProjInfo.xy * normalBias * clamp(viewNormal.z, 0.001, 0.1);\n}\nreturn newShadowPos;\n}\nvec4 ApplyShadowDepthBias_Perspective(vec4 shadowPos, float viewspaceDepthBias)\n{\nvec3 viewSpacePos;\nviewSpacePos.xy = shadowPos.xy * cc_shadowProjInfo.zw;\nviewSpacePos.z = shadowPos.z * cc_shadowInvProjDepthInfo.x + shadowPos.w * cc_shadowInvProjDepthInfo.y;\nviewSpacePos.xyz += cc_shadowProjDepthInfo.z * normalize(viewSpacePos.xyz) * viewspaceDepthBias;\nvec4 clipSpacePos;\nclipSpacePos.xy = viewSpacePos.xy * cc_shadowProjInfo.xy;\nclipSpacePos.zw = viewSpacePos.z * cc_shadowProjDepthInfo.xz + vec2(cc_shadowProjDepthInfo.y, 0.0);\nif (cc_shadowNFLSInfo.z > 0.000001) {\nclipSpacePos.z = CCGetLinearDepthFromViewSpace(viewSpacePos.xyz);\nclipSpacePos.z = (clipSpacePos.z * 2.0 - 1.0) * clipSpacePos.w;\n}\nreturn clipSpacePos;\n}\nvec4 ApplyShadowDepthBias_Orthographic(vec4 shadowPos, float viewspaceDepthBias)\n{\nfloat coeffA = cc_shadowProjDepthInfo.x;\nfloat coeffB = cc_shadowProjDepthInfo.y;\nfloat viewSpacePos_z = (shadowPos.z - coeffB) / coeffA;\nviewSpacePos_z += viewspaceDepthBias;\nvec4 result = shadowPos;\nresult.z = viewSpacePos_z * coeffA + coeffB;\nreturn result;\n}\nfloat CCGetShadowFactorHard (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture(cc_shadowMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n} else {\nclosestDepth = texture(cc_shadowMap, clipPos.xy).x;\n}\nshadow = step(clipPos.z, closestDepth);\nreturn shadow;\n}\nfloat CCGetShadowFactorSoft (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x);\nblock1 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)).x);\nblock2 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)).x);\nblock3 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetShadowFactorSoft2X (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock4 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock5 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock6 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock7 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock8 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)).x);\nblock1 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)).x);\nblock2 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)).x);\nblock3 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)).x);\nblock4 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x);\nblock5 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)).x);\nblock6 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)).x);\nblock7 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)).x);\nblock8 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCGetSpotLightShadowFactorHard (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nfloat depth = clipPos.z;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture(cc_spotLightingMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n} else {\nclosestDepth = texture(cc_spotLightingMap, clipPos.xy).x;\n}\nshadow = step(depth, closestDepth);\nreturn shadow;\n}\nfloat CCGetSpotLightShadowFactorSoft (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nvec2 oneTap = 1.0 / cc_shadowWHPBInfo.xy;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x);\nblock1 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)).x);\nblock2 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)).x);\nblock3 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * cc_shadowWHPBInfo.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY = mod(clipPos.y, oneTap.y) * cc_shadowWHPBInfo.y;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetSpotLightShadowFactorSoft2X (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock4 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock5 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock6 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock7 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock8 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)).x);\nblock1 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)).x);\nblock2 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)).x);\nblock3 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)).x);\nblock4 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x);\nblock5 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)).x);\nblock6 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)).x);\nblock7 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)).x);\nblock8 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCSpotShadowFactorBase(vec4 shadowPos, vec3 worldPos, vec2 shadowBias)\n{\nfloat pcf = cc_shadowWHPBInfo.z;\nif (pcf > 1.9) {\nreturn CCGetSpotLightShadowFactorSoft2X(shadowPos, worldPos, shadowBias.x);\n}else if (pcf > 0.9) {\nreturn CCGetSpotLightShadowFactorSoft(shadowPos, worldPos, shadowBias.x);\n}else {\nreturn CCGetSpotLightShadowFactorHard(shadowPos, worldPos, shadowBias.x);\n}\n}\nfloat CCShadowFactorBase(vec4 shadowPos, vec3 N, vec2 shadowBias)\n{\nfloat realtimeShadow = 1.0;\nvec4 pos = ApplyShadowDepthBias_FaceNormal(shadowPos, N, shadowBias.y);\nfloat pcf = cc_shadowWHPBInfo.z;\nif (pcf > 1.9) {\nrealtimeShadow = CCGetShadowFactorSoft2X(pos, shadowBias.x);\n}else if (pcf > 0.9) {\nrealtimeShadow = CCGetShadowFactorSoft(pos, shadowBias.x);\n}else {\nrealtimeShadow = CCGetShadowFactorHard(pos, shadowBias.x);\n}\nreturn mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w);\n}\n#endif\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\nreturn textureLod(tex, coord, lod);\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\nreturn textureLod(tex, coord, lod);\n}\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(1.1, rgbe.a * 255.0 - 128.0);\n}\n#if CC_USE_DIFFUSEMAP\nuniform samplerCube cc_diffuseMap;\n#endif\n#endif\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\nvec3 NxH = cross(N, H);\nfloat OneMinusNoHSqr = dot(NxH, NxH);\nfloat a = roughness * roughness;\nfloat n = NoH * a;\nfloat p = a / (OneMinusNoHSqr + n * n);\nreturn p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\nreturn (roughness * 0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\nconst vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\nconst vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\nvec4 r = roughness * c0 + c1;\nfloat a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;\nvec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;\nAB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\nreturn specular * AB.x + AB.y;\n}\n#if USE_REFLECTION_DENOISE\nvec3 GetEnvReflectionWithMipFiltering(vec3 R, float roughness, float mipCount, float denoiseIntensity) {\n#if CC_USE_IBL\nfloat mip = roughness * mipCount;\nfloat delta = (dot(dFdx(R), dFdy(R))) * 1000.0;\nfloat mipBias = mix(0.0, 5.0, clamp(delta, 0.0, 1.0));\nvec4 biased = fragTextureLod(cc_environment, R, mip + mipBias);\nvec4 filtered = texture(cc_environment, R);\n#if CC_USE_IBL == 2\nbiased.rgb = unpackRGBE(biased);\nfiltered.rgb = unpackRGBE(filtered);\n#else\nbiased.rgb = SRGBToLinear(biased.rgb);\nfiltered.rgb = SRGBToLinear(filtered.rgb);\n#endif\nreturn mix(biased.rgb, filtered.rgb, denoiseIntensity);\n#else\nreturn vec3(0.0, 0.0, 0.0);\n#endif\n}\n#endif\nstruct StandardSurface {\nvec4 albedo;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nvec3 position, position_fract_part;\n#else\nvec3 position;\n#endif\nvec3 normal;\nvec3 emissive;\nvec3 lightmap;\nfloat lightmap_test;\nfloat roughness;\nfloat metallic;\nfloat occlusion;\n#if CC_RECEIVE_SHADOW\nvec2 shadowBias;\n#endif\n};\nvec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.0);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 L = normalize(-cc_mainLitDir.xyz);\nvec3 H = normalize(L + V);\nfloat NH = max(dot(N, H), 0.0);\nfloat NL = max(dot(N, L), 0.0);\nvec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w;\nvec3 diffuseContrib = diffuse;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nif (s.lightmap_test > 0.0001) {\nfinalColor = s.lightmap.rgb;\n}\n#else\ndiffuseContrib /= PI;\n#endif\nvec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\nvec3 dirlightContrib = (diffuseContrib + specularContrib);\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (NL > 0.0 && cc_mainLitDir.w > 0.0) {\nshadow = CCShadowFactorBase(shadowPos, N, s.shadowBias);\n}\n#endif\ndirlightContrib *= shadow;\nfinalColor *= dirlightContrib;\nfloat fAmb = 0.5 - N.y * 0.5;\nvec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb);\n#if CC_USE_IBL\n#if CC_USE_DIFFUSEMAP\nvec4 diffuseMap = texture(cc_diffuseMap, N);\n#if CC_USE_DIFFUSEMAP == 2\nambDiff = unpackRGBE(diffuseMap);\n#else\nambDiff = SRGBToLinear(diffuseMap.rgb);\n#endif\n#endif\nvec3 R = normalize(reflect(-V, N));\n#if USE_REFLECTION_DENOISE\nvec3 env = GetEnvReflectionWithMipFiltering(R, s.roughness, cc_ambientGround.w, 0.6);\n#else\nvec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n#if CC_USE_IBL == 2\nvec3 env = unpackRGBE(envmap);\n#else\nvec3 env = SRGBToLinear(envmap.rgb);\n#endif\n#endif\nfinalColor += env * cc_ambientSky.w * specular * s.occlusion;\n#endif\nfinalColor += ambDiff.rgb * cc_ambientSky.w * diffuse * s.occlusion;\nfinalColor += s.emissive;\nreturn vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = ACESToneMap(color.rgb);\n#endif\ncolor.rgb = sqrt(color.rgb);\nreturn color;\n}\nin highp vec4 v_shadowPos;\n#if CC_RECEIVE_SHADOW\n#endif\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nin vec3 v_luv;\nuniform sampler2D cc_lightingMap;\nvec3 UnpackLightingmap(vec4 color) {\nvec3 c;\nfloat e = 1.0 + color.a * (8.0 - 1.0);\nc.r = color.r * e;\nc.g = color.g * e;\nc.b = color.b * e;\nreturn c;\n}\n#endif\nin vec3 v_position;\nin vec2 v_uv;\nin vec2 v_uv1;\nin vec3 v_normal;\n#if CC_RECEIVE_SHADOW\nin vec2 v_shadowBias;\n#endif\n#if USE_VERTEX_COLOR\nin vec4 v_color;\n#endif\n#if USE_ALBEDO_MAP\nuniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\nin vec3 v_tangent;\nin vec3 v_bitangent;\nuniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\nuniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\nuniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\nuniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\nuniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\nvec4 baseColor = albedo;\n#if USE_VERTEX_COLOR\nbaseColor.rgb *= SRGBToLinear(v_color.rgb);\nbaseColor.a *= v_color.a;\n#endif\n#if USE_ALBEDO_MAP\nvec4 texColor = texture(albedoMap, ALBEDO_UV);\ntexColor.rgb = SRGBToLinear(texColor.rgb);\nbaseColor *= texColor;\n#endif\ns.albedo = baseColor;\ns.albedo.rgb *= albedoScaleAndCutoff.xyz;\n#if USE_ALPHA_TEST\nif (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n#endif\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nvec4 lightColor = texture(cc_lightingMap, v_luv.xy);\ns.lightmap = UnpackLightingmap(lightColor);\ns.lightmap_test = v_luv.z;\n#endif\ns.normal = v_normal;\n#if CC_RECEIVE_SHADOW\ns.shadowBias = v_shadowBias;\n#endif\n#if USE_NORMAL_MAP\nvec3 nmmp = texture(normalMap, NORMAL_UV).xyz - vec3(0.5);\ns.normal =\n(nmmp.x * emissiveScaleParam.w) * normalize(v_tangent) +\n(nmmp.y * emissiveScaleParam.w) * normalize(v_bitangent) +\nnmmp.z * normalize(s.normal);\n#endif\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\npackHighpData(s.position, s.position_fract_part, v_position);\n#else\ns.position = v_position;\n#endif\nvec4 pbr = pbrParams;\n#if USE_PBR_MAP\nvec4 res = texture(pbrMap, PBR_UV);\npbr.x *= res.r;\npbr.y *= res.g;\npbr.z *= res.b;\npbr.w *= res.a;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\nvec4 metallicRoughness = texture(metallicRoughnessMap, PBR_UV);\npbr.z *= metallicRoughness.b;\npbr.y *= metallicRoughness.g;\n#endif\n#if USE_OCCLUSION_MAP\npbr.x *= texture(occlusionMap, PBR_UV).r;\n#endif\ns.occlusion = pbr.x;\ns.roughness = pbr.y;\ns.metallic = pbr.z;\ns.emissive = emissive.rgb * emissiveScaleParam.xyz;\n#if USE_EMISSIVE_MAP\ns.emissive *= SRGBToLinear(texture(emissiveMap, EMISSIVE_UV).rgb);\n#endif\n}\n#if CC_FORWARD_ADD\n#if CC_PIPELINE_TYPE == 0\n#define LIGHTS_PER_PASS 1\n#else\n#define LIGHTS_PER_PASS 10\n#endif\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0\nlayout(std140) uniform CCForwardLight {\nhighp vec4 cc_lightPos[LIGHTS_PER_PASS];\nvec4 cc_lightColor[LIGHTS_PER_PASS];\nvec4 cc_lightSizeRangeAngle[LIGHTS_PER_PASS];\nvec4 cc_lightDir[LIGHTS_PER_PASS];\n};\n#endif\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\nfloat factor = distSqr * invSqrAttRadius;\nfloat smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\nreturn smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\nfloat attenuation = 1.0 / max(distSqr, 0.01*0.01);\nattenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\nreturn attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\nfloat cd = dot(litDir, L);\nfloat attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\nreturn (attenuation * attenuation);\n}\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0\nvec4 CCStandardShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / PI;\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.0);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nint numLights = CC_PIPELINE_TYPE == 0 ? LIGHTS_PER_PASS : int(cc_lightDir[0].w);\nfor (int i = 0; i < LIGHTS_PER_PASS; i++) {\nif (i >= numLights) break;\nvec3 SLU = cc_lightPos[i].xyz - position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.0);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = cc_lightSizeRangeAngle[i].x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = PI * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(cc_lightSizeRangeAngle[i].y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (cc_lightPos[i].w > 0.0) {\nfloat cosInner = max(dot(-cc_lightDir[i].xyz, SL), 0.01);\nfloat cosOuter = cc_lightSizeRangeAngle[i].z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -cc_lightDir[i].xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = cc_lightColor[i].rgb;\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (cc_lightPos[i].w > 0.0 && cc_lightSizeRangeAngle[i].w > 0.0) {\nshadow = CCSpotShadowFactorBase(shadowPos, position, s.shadowBias);\n}\n#endif\nlightColor *= shadow;\nfinalColor += SNL * lightColor * cc_lightColor[i].w * illum * att * (diffuseContrib + lspec);\n}\nreturn vec4(finalColor, 0.0);\n}\n#endif\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1\nlayout(std430, binding = 4) readonly buffer b_ccLightsBuffer { vec4 b_ccLights[]; };\nlayout(std430, binding = 5) readonly buffer b_clusterLightIndicesBuffer { uint b_clusterLightIndices[]; };\nlayout(std430, binding = 6) readonly buffer b_clusterLightGridBuffer { uvec4 b_clusterLightGrid[]; };\nstruct CCLight\n{\nvec4 cc_lightPos;\nvec4 cc_lightColor;\nvec4 cc_lightSizeRangeAngle;\nvec4 cc_lightDir;\n};\nstruct Cluster\n{\nvec3 minBounds;\nvec3 maxBounds;\n};\nstruct LightGrid\n{\nuint offset;\nuint ccLights;\n};\nCCLight getCCLight(uint i)\n{\nCCLight light;\nlight.cc_lightPos = b_ccLights[4u * i + 0u];\nlight.cc_lightColor = b_ccLights[4u * i + 1u];\nlight.cc_lightSizeRangeAngle = b_ccLights[4u * i + 2u];\nlight.cc_lightDir = b_ccLights[4u * i + 3u];\nreturn light;\n}\nLightGrid getLightGrid(uint cluster)\n{\nuvec4 gridvec = b_clusterLightGrid[cluster];\nLightGrid grid;\ngrid.offset = gridvec.x;\ngrid.ccLights = gridvec.y;\nreturn grid;\n}\nuint getGridLightIndex(uint start, uint offset)\n{\nreturn b_clusterLightIndices[start + offset];\n}\nuint getClusterZIndex(vec4 worldPos)\n{\nfloat scale = float(24) / log(cc_nearFar.y / cc_nearFar.x);\nfloat bias = -(float(24) * log(cc_nearFar.x) / log(cc_nearFar.y / cc_nearFar.x));\nfloat eyeDepth = -(cc_matView * worldPos).z;\nuint zIndex = uint(max(log(eyeDepth) * scale + bias, 0.0));\nreturn zIndex;\n}\nuint getClusterIndex(vec4 fragCoord, vec4 worldPos)\n{\nuint zIndex = getClusterZIndex(worldPos);\nfloat clusterSizeX = ceil(cc_viewPort.z / float(16));\nfloat clusterSizeY = ceil(cc_viewPort.w / float(8));\nuvec3 indices = uvec3(uvec2(fragCoord.xy / vec2(clusterSizeX, clusterSizeY)), zIndex);\nuint cluster = (16u * 8u) * indices.z + 16u * indices.y + indices.x;\nreturn cluster;\n}\nvec4 CCClusterShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / PI;\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nuint cluster = getClusterIndex(gl_FragCoord, vec4(position, 1.0));\nLightGrid grid = getLightGrid(cluster);\nuint numLights = grid.ccLights;\nfor (uint i = 0u; i < 100u; i++) {\nif (i >= numLights) break;\nuint lightIndex = getGridLightIndex(grid.offset, i);\nCCLight light = getCCLight(lightIndex);\nvec3 SLU = light.cc_lightPos.xyz - position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.001);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = light.cc_lightSizeRangeAngle.x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = PI * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(light.cc_lightSizeRangeAngle.y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (light.cc_lightPos.w > 0.0) {\nfloat cosInner = max(dot(-light.cc_lightDir.xyz, SL), 0.01);\nfloat cosOuter = light.cc_lightSizeRangeAngle.z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -light.cc_lightDir.xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = light.cc_lightColor.rgb;\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (light.cc_lightPos.w > 0.0) {\nshadow = CCSpotShadowFactorBase(shadowPos, position, s.shadowBias);\n}\n#endif\nlightColor *= shadow;\nfinalColor += SNL * lightColor * light.cc_lightColor.w * illum * att * (diffuseContrib + lspec);\n}\nreturn vec4(finalColor, 0.0);\n}\n#endif\nlayout(location = 0) out vec4 fragColorX;\nvoid main () {\nStandardSurface s; surf(s);\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1\nvec4 color = CCClusterShadingAdditive(s, v_shadowPos);\n#else\nvec4 color = CCStandardShadingAdditive(s, v_shadowPos);\n#endif\nCC_APPLY_FOG(color, s.position.xyz);\nfragColorX = CCFragOutput(color);\n}\n#elif (CC_PIPELINE_TYPE == 0 || CC_FORCE_FORWARD_SHADING)\nlayout(location = 0) out vec4 fragColorX;\nvoid main () {\nStandardSurface s; surf(s);\nvec4 color = CCStandardShadingBase(s, v_shadowPos);\nCC_APPLY_FOG(color, s.position.xyz);\nfragColorX = CCFragOutput(color);\n}\n#elif CC_PIPELINE_TYPE == 1\nvec2 signNotZero(vec2 v) {\nreturn vec2((v.x >= 0.0) ? +1.0 : -1.0, (v.y >= 0.0) ? +1.0 : -1.0);\n}\nvec2 float32x3_to_oct(in vec3 v) {\nvec2 p = v.xy * (1.0 / (abs(v.x) + abs(v.y) + abs(v.z)));\nreturn (v.z <= 0.0) ? ((1.0 - abs(p.yx)) * signNotZero(p)) : p;\n}\nlayout(location = 0) out vec4 fragColor0;\nlayout(location = 1) out vec4 fragColor1;\nlayout(location = 2) out vec4 fragColor2;\nvoid main () {\nStandardSurface s; surf(s);\nfragColor0 = s.albedo;\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nfragColor1 = vec4(position, s.roughness);\nfragColor1 = vec4(float32x3_to_oct(s.normal), s.roughness, s.metallic);\nfragColor3 = vec4(s.emissive, s.occlusion);\n}\n#endif", - }, - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nin vec4 a_tangent;\n#if USE_INSTANCING\nin vec4 a_matWorld0;\nin vec4 a_matWorld1;\nin vec4 a_matWorld2;\n#if USE_LIGHTMAP\nin vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nin vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nin float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nin float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_joints;\nin vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nlayout(std140) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nin highp vec4 a_jointAnimInfo;\n#endif\nlayout(std140) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(std140) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nuniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nlayout(std140) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\n#if USE_BATCHING\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nvoid CCGetWorldMatrixFull(out mat4 matWorld, out mat4 matWorldIT)\n{\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\nmatWorldIT = matWorld;\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\nmatWorldIT = matWorld;\n#else\nmatWorld = cc_matWorld;\nmatWorldIT = cc_matWorldIT;\n#endif\n}\nlayout(std140) uniform Constants {\nvec4 tilingOffset;\nvec4 albedo;\nvec4 albedoScaleAndCutoff;\nvec4 pbrParams;\nvec4 emissive;\nvec4 emissiveScaleParam;\n};\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\n#if HAS_SECOND_UV || USE_LIGHTMAP\nin vec2 a_texCoord1;\n#endif\nout vec2 v_uv;\nout vec2 v_uv1;\nout vec4 v_worldPos;\nout float v_clip_depth;\nvec4 vert () {\nStandardVertInput In;\nCCVertInput(In);\nmat4 matWorld, matWorldIT;\nCCGetWorldMatrixFull(matWorld, matWorldIT);\nv_worldPos = matWorld * In.position;\nvec4 clipPos = cc_matLightViewProj * v_worldPos;\nv_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n#if HAS_SECOND_UV\nv_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n#endif\nv_clip_depth = clipPos.z / clipPos.w * 0.5 + 0.5;\nreturn clipPos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\nlayout(std140) uniform Constants {\nvec4 tilingOffset;\nvec4 albedo;\nvec4 albedoScaleAndCutoff;\nvec4 pbrParams;\nvec4 emissive;\nvec4 emissiveScaleParam;\n};\nvec4 packDepthToRGBA (float depth) {\nvec4 ret = vec4(1.0, 255.0, 65025.0, 16581375.0) * depth;\nret = fract(ret);\nret -= vec4(ret.yzw, 0.0) / 255.0;\nreturn ret;\n}\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\n#if USE_BATCHING\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nfloat CCGetLinearDepthFromViewSpace(vec3 viewPos) {\nfloat dist = length(viewPos);\nreturn (dist - cc_shadowNFLSInfo.x) / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x);\n}\nfloat CCGetLinearDepth(vec3 worldPos) {\nvec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0);\nreturn CCGetLinearDepthFromViewSpace(viewStartPos.xyz);\n}\n#if CC_RECEIVE_SHADOW\nuniform highp sampler2D cc_shadowMap;\nuniform highp sampler2D cc_spotLightingMap;\n#endif\nin vec2 v_uv;\nin vec2 v_uv1;\nin vec4 v_worldPos;\nin float v_clip_depth;\n#if USE_ALBEDO_MAP\nuniform sampler2D albedoMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvec4 frag () {\nvec4 baseColor = albedo;\n#if USE_ALBEDO_MAP\nbaseColor *= texture(albedoMap, ALBEDO_UV);\n#endif\n#if USE_ALPHA_TEST\nif (baseColor.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n#endif\nif(cc_shadowLPNNInfo.x > 0.000001 && cc_shadowLPNNInfo.x < 1.999999) {\nif (cc_shadowNFLSInfo.z > 0.000001) {\nreturn vec4(CCGetLinearDepth(v_worldPos.xyz), 1.0, 1.0, 1.0);\n}\n}\nif (cc_shadowLPNNInfo.y > 0.000001) {\nreturn packDepthToRGBA(v_clip_depth);\n}\nreturn vec4(v_clip_depth, 1.0, 1.0, 1.0);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\n#if !CC_USE_ACCURATE_FOG\nout float v_fog_factor;\n#endif\nvoid CC_TRANSFER_FOG(vec4 pos) {\n#if !CC_USE_ACCURATE_FOG\nCC_TRANSFER_FOG_BASE(pos, v_fog_factor);\n#endif\n}\nout highp vec4 v_shadowPos;\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\n#if CC_RECEIVE_SHADOW\nuniform highp sampler2D cc_shadowMap;\nuniform highp sampler2D cc_spotLightingMap;\n#endif\n#if CC_RECEIVE_SHADOW\n#endif\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\n#if CC_RECEIVE_SHADOW\nout vec2 v_shadowBias;\n#endif\nout highp vec3 v_position;\nout mediump vec3 v_normal;\n#if USE_NORMALMAP\nout mediump vec3 v_tangent;\nout mediump vec3 v_binormal;\n#endif\nout mediump vec2 uvw;\nout mediump vec2 uv0;\nout mediump vec2 uv1;\nout mediump vec2 uv2;\nout mediump vec2 uv3;\nout mediump vec3 luv;\nout mediump vec3 diffuse;\nlayout(std140) uniform TexCoords {\nvec4 UVScale;\nvec4 lightMapUVParam;\n};\nvoid main () {\nvec3 worldPos;\nworldPos.x = cc_matWorld[3][0] + a_position.x;\nworldPos.y = cc_matWorld[3][1] + a_position.y;\nworldPos.z = cc_matWorld[3][2] + a_position.z;\nvec4 pos = vec4(worldPos, 1.0);\npos = cc_matViewProj * pos;\nuvw = a_texCoord;\nuv0 = a_position.xz * UVScale.x;\nuv1 = a_position.xz * UVScale.y;\nuv2 = a_position.xz * UVScale.z;\nuv3 = a_position.xz * UVScale.w;\n#if USE_LIGHTMAP\nluv.xy = lightMapUVParam.xy + a_texCoord * lightMapUVParam.zw;\nluv.z = lightMapUVParam.z;\n#endif\nv_position = worldPos;\nv_normal = a_normal;\nCC_TRANSFER_FOG(vec4(worldPos, 1.0));\n#if CC_RECEIVE_SHADOW\nv_shadowBias = vec2(0.0, 0.0);\n#endif\n#if USE_NORMALMAP\nv_tangent = vec3(1.0, 0.0, 0.0);\nv_binormal = vec3(0.0, 0.0, 1.0);\nv_binormal = cross(v_tangent, a_normal);\nv_tangent = cross(a_normal, v_binormal);\n#endif\nv_shadowPos = cc_matLightViewProj * vec4(worldPos, 1.0);\ngl_Position = pos;\n}", - "frag": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\nhighp float unpackHighpData (float mainPart, float modPart) {\nhighp float data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out float mainPart, out float modPart, highp float data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp float unpackHighpData (float mainPart, float modPart, const float modValue) {\nhighp float data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out float mainPart, out float modPart, highp float data, const float modValue) {\nhighp float divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\nhighp vec2 unpackHighpData (vec2 mainPart, vec2 modPart) {\nhighp vec2 data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out vec2 mainPart, out vec2 modPart, highp vec2 data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp vec2 unpackHighpData (vec2 mainPart, vec2 modPart, const float modValue) {\nhighp vec2 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out vec2 mainPart, out vec2 modPart, highp vec2 data, const float modValue) {\nhighp vec2 divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\nhighp vec3 unpackHighpData (vec3 mainPart, vec3 modPart) {\nhighp vec3 data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out vec3 mainPart, out vec3 modPart, highp vec3 data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp vec3 unpackHighpData (vec3 mainPart, vec3 modPart, const float modValue) {\nhighp vec3 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out vec3 mainPart, out vec3 modPart, highp vec3 data, const float modValue) {\nhighp vec3 divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\nhighp vec4 unpackHighpData (vec4 mainPart, vec4 modPart) {\nhighp vec4 data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out vec4 mainPart, out vec4 modPart, highp vec4 data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp vec4 unpackHighpData (vec4 mainPart, vec4 modPart, const float modValue) {\nhighp vec4 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out vec4 mainPart, out vec4 modPart, highp vec4 data, const float modValue) {\nhighp vec4 divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\n#if USE_BATCHING\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nfloat CCGetLinearDepthFromViewSpace(vec3 viewPos) {\nfloat dist = length(viewPos);\nreturn (dist - cc_shadowNFLSInfo.x) / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x);\n}\nfloat CCGetLinearDepth(vec3 worldPos) {\nvec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0);\nreturn CCGetLinearDepthFromViewSpace(viewStartPos.xyz);\n}\n#if CC_RECEIVE_SHADOW\nuniform highp sampler2D cc_shadowMap;\nuniform highp sampler2D cc_spotLightingMap;\nvec4 ApplyShadowDepthBias_FaceNormal(vec4 shadowPos, vec3 worldNormal, float normalBias)\n{\nvec4 newShadowPos = shadowPos;\nif(normalBias > 0.0001)\n{\nvec4 viewNormal = cc_matLightView * vec4(worldNormal, 0.0);\nif(viewNormal.z < 0.1)\nnewShadowPos.xy += viewNormal.xy * cc_shadowProjInfo.xy * normalBias * clamp(viewNormal.z, 0.001, 0.1);\n}\nreturn newShadowPos;\n}\nvec4 ApplyShadowDepthBias_Perspective(vec4 shadowPos, float viewspaceDepthBias)\n{\nvec3 viewSpacePos;\nviewSpacePos.xy = shadowPos.xy * cc_shadowProjInfo.zw;\nviewSpacePos.z = shadowPos.z * cc_shadowInvProjDepthInfo.x + shadowPos.w * cc_shadowInvProjDepthInfo.y;\nviewSpacePos.xyz += cc_shadowProjDepthInfo.z * normalize(viewSpacePos.xyz) * viewspaceDepthBias;\nvec4 clipSpacePos;\nclipSpacePos.xy = viewSpacePos.xy * cc_shadowProjInfo.xy;\nclipSpacePos.zw = viewSpacePos.z * cc_shadowProjDepthInfo.xz + vec2(cc_shadowProjDepthInfo.y, 0.0);\nif (cc_shadowNFLSInfo.z > 0.000001) {\nclipSpacePos.z = CCGetLinearDepthFromViewSpace(viewSpacePos.xyz);\nclipSpacePos.z = (clipSpacePos.z * 2.0 - 1.0) * clipSpacePos.w;\n}\nreturn clipSpacePos;\n}\nvec4 ApplyShadowDepthBias_Orthographic(vec4 shadowPos, float viewspaceDepthBias)\n{\nfloat coeffA = cc_shadowProjDepthInfo.x;\nfloat coeffB = cc_shadowProjDepthInfo.y;\nfloat viewSpacePos_z = (shadowPos.z - coeffB) / coeffA;\nviewSpacePos_z += viewspaceDepthBias;\nvec4 result = shadowPos;\nresult.z = viewSpacePos_z * coeffA + coeffB;\nreturn result;\n}\nfloat CCGetShadowFactorHard (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture(cc_shadowMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n} else {\nclosestDepth = texture(cc_shadowMap, clipPos.xy).x;\n}\nshadow = step(clipPos.z, closestDepth);\nreturn shadow;\n}\nfloat CCGetShadowFactorSoft (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x);\nblock1 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)).x);\nblock2 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)).x);\nblock3 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetShadowFactorSoft2X (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock4 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock5 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock6 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock7 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock8 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)).x);\nblock1 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)).x);\nblock2 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)).x);\nblock3 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)).x);\nblock4 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x);\nblock5 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)).x);\nblock6 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)).x);\nblock7 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)).x);\nblock8 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCGetSpotLightShadowFactorHard (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nfloat depth = clipPos.z;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture(cc_spotLightingMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n} else {\nclosestDepth = texture(cc_spotLightingMap, clipPos.xy).x;\n}\nshadow = step(depth, closestDepth);\nreturn shadow;\n}\nfloat CCGetSpotLightShadowFactorSoft (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nvec2 oneTap = 1.0 / cc_shadowWHPBInfo.xy;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x);\nblock1 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)).x);\nblock2 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)).x);\nblock3 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * cc_shadowWHPBInfo.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY = mod(clipPos.y, oneTap.y) * cc_shadowWHPBInfo.y;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetSpotLightShadowFactorSoft2X (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock4 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock5 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock6 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock7 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock8 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)).x);\nblock1 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)).x);\nblock2 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)).x);\nblock3 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)).x);\nblock4 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x);\nblock5 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)).x);\nblock6 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)).x);\nblock7 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)).x);\nblock8 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCSpotShadowFactorBase(vec4 shadowPos, vec3 worldPos, vec2 shadowBias)\n{\nfloat pcf = cc_shadowWHPBInfo.z;\nif (pcf > 1.9) {\nreturn CCGetSpotLightShadowFactorSoft2X(shadowPos, worldPos, shadowBias.x);\n}else if (pcf > 0.9) {\nreturn CCGetSpotLightShadowFactorSoft(shadowPos, worldPos, shadowBias.x);\n}else {\nreturn CCGetSpotLightShadowFactorHard(shadowPos, worldPos, shadowBias.x);\n}\n}\nfloat CCShadowFactorBase(vec4 shadowPos, vec3 N, vec2 shadowBias)\n{\nfloat realtimeShadow = 1.0;\nvec4 pos = ApplyShadowDepthBias_FaceNormal(shadowPos, N, shadowBias.y);\nfloat pcf = cc_shadowWHPBInfo.z;\nif (pcf > 1.9) {\nrealtimeShadow = CCGetShadowFactorSoft2X(pos, shadowBias.x);\n}else if (pcf > 0.9) {\nrealtimeShadow = CCGetShadowFactorSoft(pos, shadowBias.x);\n}else {\nrealtimeShadow = CCGetShadowFactorHard(pos, shadowBias.x);\n}\nreturn mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w);\n}\n#endif\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\nreturn textureLod(tex, coord, lod);\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\nreturn textureLod(tex, coord, lod);\n}\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(1.1, rgbe.a * 255.0 - 128.0);\n}\n#if CC_USE_DIFFUSEMAP\nuniform samplerCube cc_diffuseMap;\n#endif\n#endif\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\nvec3 NxH = cross(N, H);\nfloat OneMinusNoHSqr = dot(NxH, NxH);\nfloat a = roughness * roughness;\nfloat n = NoH * a;\nfloat p = a / (OneMinusNoHSqr + n * n);\nreturn p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\nreturn (roughness * 0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\nconst vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\nconst vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\nvec4 r = roughness * c0 + c1;\nfloat a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;\nvec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;\nAB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\nreturn specular * AB.x + AB.y;\n}\n#if USE_REFLECTION_DENOISE\nvec3 GetEnvReflectionWithMipFiltering(vec3 R, float roughness, float mipCount, float denoiseIntensity) {\n#if CC_USE_IBL\nfloat mip = roughness * mipCount;\nfloat delta = (dot(dFdx(R), dFdy(R))) * 1000.0;\nfloat mipBias = mix(0.0, 5.0, clamp(delta, 0.0, 1.0));\nvec4 biased = fragTextureLod(cc_environment, R, mip + mipBias);\nvec4 filtered = texture(cc_environment, R);\n#if CC_USE_IBL == 2\nbiased.rgb = unpackRGBE(biased);\nfiltered.rgb = unpackRGBE(filtered);\n#else\nbiased.rgb = SRGBToLinear(biased.rgb);\nfiltered.rgb = SRGBToLinear(filtered.rgb);\n#endif\nreturn mix(biased.rgb, filtered.rgb, denoiseIntensity);\n#else\nreturn vec3(0.0, 0.0, 0.0);\n#endif\n}\n#endif\nstruct StandardSurface {\nvec4 albedo;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nvec3 position, position_fract_part;\n#else\nvec3 position;\n#endif\nvec3 normal;\nvec3 emissive;\nvec3 lightmap;\nfloat lightmap_test;\nfloat roughness;\nfloat metallic;\nfloat occlusion;\n#if CC_RECEIVE_SHADOW\nvec2 shadowBias;\n#endif\n};\nvec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.0);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 L = normalize(-cc_mainLitDir.xyz);\nvec3 H = normalize(L + V);\nfloat NH = max(dot(N, H), 0.0);\nfloat NL = max(dot(N, L), 0.0);\nvec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w;\nvec3 diffuseContrib = diffuse;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nif (s.lightmap_test > 0.0001) {\nfinalColor = s.lightmap.rgb;\n}\n#else\ndiffuseContrib /= PI;\n#endif\nvec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\nvec3 dirlightContrib = (diffuseContrib + specularContrib);\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (NL > 0.0 && cc_mainLitDir.w > 0.0) {\nshadow = CCShadowFactorBase(shadowPos, N, s.shadowBias);\n}\n#endif\ndirlightContrib *= shadow;\nfinalColor *= dirlightContrib;\nfloat fAmb = 0.5 - N.y * 0.5;\nvec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb);\n#if CC_USE_IBL\n#if CC_USE_DIFFUSEMAP\nvec4 diffuseMap = texture(cc_diffuseMap, N);\n#if CC_USE_DIFFUSEMAP == 2\nambDiff = unpackRGBE(diffuseMap);\n#else\nambDiff = SRGBToLinear(diffuseMap.rgb);\n#endif\n#endif\nvec3 R = normalize(reflect(-V, N));\n#if USE_REFLECTION_DENOISE\nvec3 env = GetEnvReflectionWithMipFiltering(R, s.roughness, cc_ambientGround.w, 0.6);\n#else\nvec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n#if CC_USE_IBL == 2\nvec3 env = unpackRGBE(envmap);\n#else\nvec3 env = SRGBToLinear(envmap.rgb);\n#endif\n#endif\nfinalColor += env * cc_ambientSky.w * specular * s.occlusion;\n#endif\nfinalColor += ambDiff.rgb * cc_ambientSky.w * diffuse * s.occlusion;\nfinalColor += s.emissive;\nreturn vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = ACESToneMap(color.rgb);\n#endif\ncolor.rgb = sqrt(color.rgb);\nreturn color;\n}\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\nvoid CC_APPLY_FOG_BASE(inout vec4 color, float factor) {\ncolor = vec4(mix(cc_fogColor.rgb, color.rgb, factor), color.a);\n}\n#if !CC_USE_ACCURATE_FOG\nin float v_fog_factor;\n#endif\nvoid CC_APPLY_FOG(inout vec4 color) {\n#if !CC_USE_ACCURATE_FOG\nCC_APPLY_FOG_BASE(color, v_fog_factor);\n#endif\n}\nvoid CC_APPLY_FOG(inout vec4 color, vec3 worldPos) {\n#if CC_USE_ACCURATE_FOG\nfloat factor;\nCC_TRANSFER_FOG_BASE(vec4(worldPos, 1.0), factor);\n#else\nfloat factor = v_fog_factor;\n#endif\nCC_APPLY_FOG_BASE(color, factor);\n}\nin highp vec4 v_shadowPos;\n#if CC_RECEIVE_SHADOW\n#endif\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nin vec3 v_luv;\nuniform sampler2D cc_lightingMap;\nvec3 UnpackLightingmap(vec4 color) {\nvec3 c;\nfloat e = 1.0 + color.a * (8.0 - 1.0);\nc.r = color.r * e;\nc.g = color.g * e;\nc.b = color.b * e;\nreturn c;\n}\n#endif\nin highp vec3 v_position;\nin mediump vec3 v_normal;\n#if CC_RECEIVE_SHADOW\nin vec2 v_shadowBias;\n#endif\n#if USE_NORMALMAP\nin mediump vec3 v_tangent;\nin mediump vec3 v_binormal;\n#endif\nin mediump vec2 uvw;\nin mediump vec2 uv0;\nin mediump vec2 uv1;\nin mediump vec2 uv2;\nin mediump vec2 uv3;\nin mediump vec3 diffuse;\nin mediump vec3 luv;\nlayout(std140) uniform PbrParams {\nvec4 metallic;\nvec4 roughness;\n};\nuniform sampler2D weightMap;\nuniform sampler2D detailMap0;\nuniform sampler2D detailMap1;\nuniform sampler2D detailMap2;\nuniform sampler2D detailMap3;\nuniform sampler2D normalMap0;\nuniform sampler2D normalMap1;\nuniform sampler2D normalMap2;\nuniform sampler2D normalMap3;\nuniform sampler2D lightMap;\nvoid surf (out StandardSurface s) {\n#if LAYERS > 1\nvec4 w = texture(weightMap, uvw);\n#endif\nvec4 baseColor = vec4(0, 0, 0, 0);\n#if LAYERS == 1\nbaseColor = texture(detailMap0, uv0);\n#elif LAYERS == 2\nbaseColor += texture(detailMap0, uv0) * w.r;\nbaseColor += texture(detailMap1, uv1) * w.g;\n#elif LAYERS == 3\nbaseColor += texture(detailMap0, uv0) * w.r;\nbaseColor += texture(detailMap1, uv1) * w.g;\nbaseColor += texture(detailMap2, uv2) * w.b;\n#elif LAYERS == 4\nbaseColor += texture(detailMap0, uv0) * w.r;\nbaseColor += texture(detailMap1, uv1) * w.g;\nbaseColor += texture(detailMap2, uv2) * w.b;\nbaseColor += texture(detailMap3, uv3) * w.a;\n#else\nbaseColor = texture(detailMap0, uv0);\n#endif\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\npackHighpData(s.position, s.position_fract_part, v_position);\n#else\ns.position = v_position;\n#endif\n#if USE_NORMALMAP\nvec4 baseNormal = vec4(0, 0, 0, 0);\n#if LAYERS == 1\nbaseNormal = texture(normalMap0, uv0);\n#elif LAYERS == 2\nbaseNormal += texture(normalMap0, uv0) * w.r;\nbaseNormal += texture(normalMap1, uv1) * w.g;\n#elif LAYERS == 3\nbaseNormal += texture(normalMap0, uv0) * w.r;\nbaseNormal += texture(normalMap1, uv1) * w.g;\nbaseNormal += texture(normalMap2, uv2) * w.b;\n#elif LAYERS == 4\nbaseNormal += texture(normalMap0, uv0) * w.r;\nbaseNormal += texture(normalMap1, uv1) * w.g;\nbaseNormal += texture(normalMap2, uv2) * w.b;\nbaseNormal += texture(normalMap3, uv3) * w.a;\n#else\nbaseNormal = texture(normalMap0, uv0);\n#endif\nvec3 nmmp = baseNormal.xyz - vec3(0.5);\ns.normal =\nnmmp.x * normalize(v_tangent) +\nnmmp.y * normalize(v_binormal) +\nnmmp.z * normalize(v_normal);\n#else\ns.normal = v_normal;\n#endif\n#if CC_RECEIVE_SHADOW\ns.shadowBias = v_shadowBias;\n#endif\ns.albedo = vec4(SRGBToLinear(baseColor.rgb), 1.0);\ns.occlusion = 1.0;\n#if USE_PBR\ns.roughness = 0.0;\n#if LAYERS == 1\ns.roughness = roughness.x;\n#elif LAYERS == 2\ns.roughness += roughness.x * w.r;\ns.roughness += roughness.y * w.g;\n#elif LAYERS == 3\ns.roughness += roughness.x * w.r;\ns.roughness += roughness.y * w.g;\ns.roughness += roughness.z * w.b;\n#elif LAYERS == 4\ns.roughness += roughness.x * w.r;\ns.roughness += roughness.y * w.g;\ns.roughness += roughness.z * w.b;\ns.roughness += roughness.w * w.a;\n#else\ns.roughness = 1.0;\n#endif\ns.metallic = 0.0;\n#if LAYERS == 1\ns.metallic = metallic.x;\n#elif LAYERS == 2\ns.metallic += metallic.x * w.r;\ns.metallic += metallic.y * w.g;\n#elif LAYERS == 3\ns.metallic += metallic.x * w.r;\ns.metallic += metallic.y * w.g;\ns.metallic += metallic.z * w.b;\n#elif LAYERS == 4\ns.metallic += metallic.x * w.r;\ns.metallic += metallic.y * w.g;\ns.metallic += metallic.z * w.b;\ns.metallic += metallic.w * w.a;\n#else\ns.metallic = 0.0;\n#endif\n#else\ns.roughness = 1.0;\ns.metallic = 0.0;\n#endif\ns.emissive = vec3(0.0, 0.0, 0.0);\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nvec4 lightColor = texture(lightMap, luv.xy);\ns.lightmap = UnpackLightingmap(lightColor);\ns.lightmap_test = luv.z;\n#endif\n}\n#if CC_FORWARD_ADD\n#if CC_PIPELINE_TYPE == 0\n#define LIGHTS_PER_PASS 1\n#else\n#define LIGHTS_PER_PASS 10\n#endif\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0\nlayout(std140) uniform CCForwardLight {\nhighp vec4 cc_lightPos[LIGHTS_PER_PASS];\nvec4 cc_lightColor[LIGHTS_PER_PASS];\nvec4 cc_lightSizeRangeAngle[LIGHTS_PER_PASS];\nvec4 cc_lightDir[LIGHTS_PER_PASS];\n};\n#endif\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\nfloat factor = distSqr * invSqrAttRadius;\nfloat smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\nreturn smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\nfloat attenuation = 1.0 / max(distSqr, 0.01*0.01);\nattenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\nreturn attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\nfloat cd = dot(litDir, L);\nfloat attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\nreturn (attenuation * attenuation);\n}\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0\nvec4 CCStandardShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / PI;\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.0);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nint numLights = CC_PIPELINE_TYPE == 0 ? LIGHTS_PER_PASS : int(cc_lightDir[0].w);\nfor (int i = 0; i < LIGHTS_PER_PASS; i++) {\nif (i >= numLights) break;\nvec3 SLU = cc_lightPos[i].xyz - position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.0);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = cc_lightSizeRangeAngle[i].x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = PI * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(cc_lightSizeRangeAngle[i].y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (cc_lightPos[i].w > 0.0) {\nfloat cosInner = max(dot(-cc_lightDir[i].xyz, SL), 0.01);\nfloat cosOuter = cc_lightSizeRangeAngle[i].z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -cc_lightDir[i].xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = cc_lightColor[i].rgb;\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (cc_lightPos[i].w > 0.0 && cc_lightSizeRangeAngle[i].w > 0.0) {\nshadow = CCSpotShadowFactorBase(shadowPos, position, s.shadowBias);\n}\n#endif\nlightColor *= shadow;\nfinalColor += SNL * lightColor * cc_lightColor[i].w * illum * att * (diffuseContrib + lspec);\n}\nreturn vec4(finalColor, 0.0);\n}\n#endif\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1\nlayout(std430, binding = 4) readonly buffer b_ccLightsBuffer { vec4 b_ccLights[]; };\nlayout(std430, binding = 5) readonly buffer b_clusterLightIndicesBuffer { uint b_clusterLightIndices[]; };\nlayout(std430, binding = 6) readonly buffer b_clusterLightGridBuffer { uvec4 b_clusterLightGrid[]; };\nstruct CCLight\n{\nvec4 cc_lightPos;\nvec4 cc_lightColor;\nvec4 cc_lightSizeRangeAngle;\nvec4 cc_lightDir;\n};\nstruct Cluster\n{\nvec3 minBounds;\nvec3 maxBounds;\n};\nstruct LightGrid\n{\nuint offset;\nuint ccLights;\n};\nCCLight getCCLight(uint i)\n{\nCCLight light;\nlight.cc_lightPos = b_ccLights[4u * i + 0u];\nlight.cc_lightColor = b_ccLights[4u * i + 1u];\nlight.cc_lightSizeRangeAngle = b_ccLights[4u * i + 2u];\nlight.cc_lightDir = b_ccLights[4u * i + 3u];\nreturn light;\n}\nLightGrid getLightGrid(uint cluster)\n{\nuvec4 gridvec = b_clusterLightGrid[cluster];\nLightGrid grid;\ngrid.offset = gridvec.x;\ngrid.ccLights = gridvec.y;\nreturn grid;\n}\nuint getGridLightIndex(uint start, uint offset)\n{\nreturn b_clusterLightIndices[start + offset];\n}\nuint getClusterZIndex(vec4 worldPos)\n{\nfloat scale = float(24) / log(cc_nearFar.y / cc_nearFar.x);\nfloat bias = -(float(24) * log(cc_nearFar.x) / log(cc_nearFar.y / cc_nearFar.x));\nfloat eyeDepth = -(cc_matView * worldPos).z;\nuint zIndex = uint(max(log(eyeDepth) * scale + bias, 0.0));\nreturn zIndex;\n}\nuint getClusterIndex(vec4 fragCoord, vec4 worldPos)\n{\nuint zIndex = getClusterZIndex(worldPos);\nfloat clusterSizeX = ceil(cc_viewPort.z / float(16));\nfloat clusterSizeY = ceil(cc_viewPort.w / float(8));\nuvec3 indices = uvec3(uvec2(fragCoord.xy / vec2(clusterSizeX, clusterSizeY)), zIndex);\nuint cluster = (16u * 8u) * indices.z + 16u * indices.y + indices.x;\nreturn cluster;\n}\nvec4 CCClusterShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / PI;\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nuint cluster = getClusterIndex(gl_FragCoord, vec4(position, 1.0));\nLightGrid grid = getLightGrid(cluster);\nuint numLights = grid.ccLights;\nfor (uint i = 0u; i < 100u; i++) {\nif (i >= numLights) break;\nuint lightIndex = getGridLightIndex(grid.offset, i);\nCCLight light = getCCLight(lightIndex);\nvec3 SLU = light.cc_lightPos.xyz - position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.001);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = light.cc_lightSizeRangeAngle.x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = PI * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(light.cc_lightSizeRangeAngle.y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (light.cc_lightPos.w > 0.0) {\nfloat cosInner = max(dot(-light.cc_lightDir.xyz, SL), 0.01);\nfloat cosOuter = light.cc_lightSizeRangeAngle.z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -light.cc_lightDir.xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = light.cc_lightColor.rgb;\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (light.cc_lightPos.w > 0.0) {\nshadow = CCSpotShadowFactorBase(shadowPos, position, s.shadowBias);\n}\n#endif\nlightColor *= shadow;\nfinalColor += SNL * lightColor * light.cc_lightColor.w * illum * att * (diffuseContrib + lspec);\n}\nreturn vec4(finalColor, 0.0);\n}\n#endif\nlayout(location = 0) out vec4 fragColorX;\nvoid main () {\nStandardSurface s; surf(s);\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1\nvec4 color = CCClusterShadingAdditive(s, v_shadowPos);\n#else\nvec4 color = CCStandardShadingAdditive(s, v_shadowPos);\n#endif\nCC_APPLY_FOG(color, s.position.xyz);\nfragColorX = CCFragOutput(color);\n}\n#elif (CC_PIPELINE_TYPE == 0 || CC_FORCE_FORWARD_SHADING)\nlayout(location = 0) out vec4 fragColorX;\nvoid main () {\nStandardSurface s; surf(s);\nvec4 color = CCStandardShadingBase(s, v_shadowPos);\nCC_APPLY_FOG(color, s.position.xyz);\nfragColorX = CCFragOutput(color);\n}\n#elif CC_PIPELINE_TYPE == 1\nvec2 signNotZero(vec2 v) {\nreturn vec2((v.x >= 0.0) ? +1.0 : -1.0, (v.y >= 0.0) ? +1.0 : -1.0);\n}\nvec2 float32x3_to_oct(in vec3 v) {\nvec2 p = v.xy * (1.0 / (abs(v.x) + abs(v.y) + abs(v.z)));\nreturn (v.z <= 0.0) ? ((1.0 - abs(p.yx)) * signNotZero(p)) : p;\n}\nlayout(location = 0) out vec4 fragColor0;\nlayout(location = 1) out vec4 fragColor1;\nlayout(location = 2) out vec4 fragColor2;\nvoid main () {\nStandardSurface s; surf(s);\nfragColor0 = s.albedo;\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nfragColor1 = vec4(position, s.roughness);\nfragColor1 = vec4(float32x3_to_oct(s.normal), s.roughness, s.metallic);\nfragColor3 = vec4(s.emissive, s.occlusion);\n}\n#endif", - }, - { - "vert": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nout vec2 v_clip_depth;\nvec4 vert () {\nvec4 worldPos;\nworldPos.x = cc_matWorld[3][0] + a_position.x;\nworldPos.y = cc_matWorld[3][1] + a_position.y;\nworldPos.z = cc_matWorld[3][2] + a_position.z;\nworldPos.w = 1.0;\nvec4 clipPos = cc_matLightViewProj * worldPos;\nv_clip_depth = clipPos.zw;\nreturn clipPos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\nvec4 packDepthToRGBA (float depth) {\nvec4 ret = vec4(1.0, 255.0, 65025.0, 16581375.0) * depth;\nret = fract(ret);\nret -= vec4(ret.yzw, 0.0) / 255.0;\nreturn ret;\n}\nin vec2 v_clip_depth;\nvec4 frag () {\nreturn packDepthToRGBA(v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nin vec4 a_tangent;\n#if USE_INSTANCING\nin vec4 a_matWorld0;\nin vec4 a_matWorld1;\nin vec4 a_matWorld2;\n#if USE_LIGHTMAP\nin vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nin vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nin float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nin float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_joints;\nin vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nlayout(std140) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nin highp vec4 a_jointAnimInfo;\n#endif\nlayout(std140) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(std140) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nuniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nlayout(std140) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout vec4 In)\n{\nIn = vec4(a_position, 1.0);\n#if CC_USE_MORPH\napplyMorph(In);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In);\n#endif\n}\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nvoid CCGetWorldMatrix(out mat4 matWorld)\n{\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\n#else\nmatWorld = cc_matWorld;\n#endif\n}\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\n#if !CC_USE_ACCURATE_FOG\nout float v_fog_factor;\n#endif\nvoid CC_TRANSFER_FOG(vec4 pos) {\n#if !CC_USE_ACCURATE_FOG\nCC_TRANSFER_FOG_BASE(pos, v_fog_factor);\n#endif\n}\n#if USE_VERTEX_COLOR\nin lowp vec4 a_color;\nout lowp vec4 v_color;\n#endif\n#if USE_TEXTURE\nout vec2 v_uv;\nlayout(std140) uniform TexCoords {\nvec4 tilingOffset;\n};\n#endif\nvec4 vert () {\nvec4 position;\nCCVertInput(position);\nmat4 matWorld;\nCCGetWorldMatrix(matWorld);\n#if USE_TEXTURE\nv_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n#if SAMPLE_FROM_RT\nv_uv = cc_cameraPos.w > 1.0 ? vec2(v_uv.x, 1.0 - v_uv.y) : v_uv;\n#endif\n#endif\n#if USE_VERTEX_COLOR\nv_color = a_color;\n#endif\nCC_TRANSFER_FOG(matWorld * position);\nreturn cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = ACESToneMap(color.rgb);\n#endif\ncolor.rgb = sqrt(color.rgb);\nreturn color;\n}\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\nvoid CC_APPLY_FOG_BASE(inout vec4 color, float factor) {\ncolor = vec4(mix(cc_fogColor.rgb, color.rgb, factor), color.a);\n}\n#if !CC_USE_ACCURATE_FOG\nin float v_fog_factor;\n#endif\nvoid CC_APPLY_FOG(inout vec4 color) {\n#if !CC_USE_ACCURATE_FOG\nCC_APPLY_FOG_BASE(color, v_fog_factor);\n#endif\n}\nvoid CC_APPLY_FOG(inout vec4 color, vec3 worldPos) {\n#if CC_USE_ACCURATE_FOG\nfloat factor;\nCC_TRANSFER_FOG_BASE(vec4(worldPos, 1.0), factor);\n#else\nfloat factor = v_fog_factor;\n#endif\nCC_APPLY_FOG_BASE(color, factor);\n}\n#if USE_ALPHA_TEST\n#endif\n#if USE_TEXTURE\nin vec2 v_uv;\nuniform sampler2D mainTexture;\n#endif\nlayout(std140) uniform Constant {\nvec4 mainColor;\nvec4 colorScaleAndCutoff;\n};\n#if USE_VERTEX_COLOR\nin lowp vec4 v_color;\n#endif\nvec4 frag () {\nvec4 o = mainColor;\no.rgb *= colorScaleAndCutoff.xyz;\n#if USE_VERTEX_COLOR\no.rgb *= SRGBToLinear(v_color.rgb);\no.a *= v_color.a;\n#endif\n#if USE_TEXTURE\nvec4 texColor = texture(mainTexture, v_uv);\ntexColor.rgb = SRGBToLinear(texColor.rgb);\no *= texColor;\n#endif\n#if USE_ALPHA_TEST\nif (o.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard;\n#endif\nCC_APPLY_FOG(o);\nreturn CCFragOutput(o);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nin vec4 a_tangent;\n#if USE_INSTANCING\nin vec4 a_matWorld0;\nin vec4 a_matWorld1;\nin vec4 a_matWorld2;\n#if USE_LIGHTMAP\nin vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nin vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nin float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nin float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_joints;\nin vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nlayout(std140) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nin highp vec4 a_jointAnimInfo;\n#endif\nlayout(std140) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(std140) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nuniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nlayout(std140) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nout vec2 v_uv;\nvoid main () {\nStandardVertInput In;\nCCVertInput(In);\nIn.position.xy = cc_cameraPos.w == 0.0 ? vec2(In.position.xy.x, -In.position.xy.y) : In.position.xy;\ngl_Position = In.position;\ngl_Position.y = gl_Position.y;\nv_uv = a_texCoord;\n}", - "frag": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nin vec2 v_uv;\nlayout(std140) uniform BloomUBO {\nmediump vec4 texSize;\n};\nuniform sampler2D outputResultMap;\nlayout(location = 0) out vec4 fragColor;\nfloat luminance(vec3 color) {\nreturn dot(color, vec3(0.2126, 0.7152, 0.0722));\n}\nvoid main() {\nvec3 color = texture(outputResultMap, v_uv).xyz;\nif (luminance(SRGBToLinear(color)) > texSize.z) {\nfragColor = vec4(color, 1.0);\n} else {\nfragColor = vec4(0.0, 0.0, 0.0, 1.0);\n}\n}", - }, - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nin vec4 a_tangent;\n#if USE_INSTANCING\nin vec4 a_matWorld0;\nin vec4 a_matWorld1;\nin vec4 a_matWorld2;\n#if USE_LIGHTMAP\nin vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nin vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nin float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nin float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_joints;\nin vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nlayout(std140) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nin highp vec4 a_jointAnimInfo;\n#endif\nlayout(std140) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(std140) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nuniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nlayout(std140) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nout vec2 v_uv;\nvoid main () {\nStandardVertInput In;\nCCVertInput(In);\nIn.position.xy = cc_cameraPos.w == 0.0 ? vec2(In.position.xy.x, -In.position.xy.y) : In.position.xy;\ngl_Position = In.position;\ngl_Position.y = gl_Position.y;\nv_uv = a_texCoord;\n}", - "frag": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nin vec2 v_uv;\nlayout(std140) uniform BloomUBO {\nmediump vec4 texSize;\n};\nuniform sampler2D bloomTexture;\nlayout(location = 0) out vec4 fragColor;\nvec3 downsample4taps(vec2 uv, vec2 halfpixel) {\nvec3 sum = texture(bloomTexture, uv + vec2(-halfpixel.x, halfpixel.y)).xyz;\nsum += texture(bloomTexture, uv + vec2(halfpixel.x, halfpixel.y)).xyz;\nsum += texture(bloomTexture, uv + vec2(halfpixel.x, -halfpixel.y)).xyz;\nsum += texture(bloomTexture, uv + vec2(-halfpixel.x, -halfpixel.y)).xyz;\nreturn sum / 4.0;\n}\nvoid main()\n{\nvec3 result = downsample4taps(v_uv, 1.0 / texSize.xy).rgb;\nfragColor = vec4(result, 1.0);\n}", - }, - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nin vec4 a_tangent;\n#if USE_INSTANCING\nin vec4 a_matWorld0;\nin vec4 a_matWorld1;\nin vec4 a_matWorld2;\n#if USE_LIGHTMAP\nin vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nin vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nin float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nin float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_joints;\nin vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nlayout(std140) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nin highp vec4 a_jointAnimInfo;\n#endif\nlayout(std140) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(std140) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nuniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nlayout(std140) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nout vec2 v_uv;\nvoid main () {\nStandardVertInput In;\nCCVertInput(In);\nIn.position.xy = cc_cameraPos.w == 0.0 ? vec2(In.position.xy.x, -In.position.xy.y) : In.position.xy;\ngl_Position = In.position;\ngl_Position.y = gl_Position.y;\nv_uv = a_texCoord;\n}", - "frag": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nin vec2 v_uv;\nlayout(std140) uniform BloomUBO {\nmediump vec4 texSize;\n};\nuniform sampler2D bloomTexture;\nlayout(location = 0) out vec4 fragColor;\nvec3 upsample4taps(vec2 uv, vec2 halfpixel) {\nvec3 sum = texture(bloomTexture, uv + vec2(-halfpixel.x, halfpixel.y)).xyz;\nsum += texture(bloomTexture, uv + vec2(halfpixel.x, halfpixel.y)).xyz;\nsum += texture(bloomTexture, uv + vec2(halfpixel.x, -halfpixel.y)).xyz;\nsum += texture(bloomTexture, uv + vec2(-halfpixel.x, -halfpixel.y)).xyz;\nreturn sum / 4.0;\n}\nvoid main() {\nvec3 result = upsample4taps(v_uv, 0.5 / texSize.xy).rgb;\nfragColor = vec4(result, 1.0);\n}", - }, - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nin vec4 a_tangent;\n#if USE_INSTANCING\nin vec4 a_matWorld0;\nin vec4 a_matWorld1;\nin vec4 a_matWorld2;\n#if USE_LIGHTMAP\nin vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nin vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nin float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nin float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_joints;\nin vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nlayout(std140) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nin highp vec4 a_jointAnimInfo;\n#endif\nlayout(std140) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(std140) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nuniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nlayout(std140) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nout vec2 v_uv;\nvoid main () {\nStandardVertInput In;\nCCVertInput(In);\nIn.position.xy = cc_cameraPos.w == 0.0 ? vec2(In.position.xy.x, -In.position.xy.y) : In.position.xy;\ngl_Position = In.position;\ngl_Position.y = gl_Position.y;\nv_uv = a_texCoord;\n}", - "frag": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nin vec2 v_uv;\nlayout(std140) uniform BloomUBO {\nmediump vec4 texSize;\n};\nuniform sampler2D outputResultMap;\nuniform sampler2D bloomTexture;\nlayout(location = 0) out vec4 fragColor;\nvoid main() {\nvec4 hdrColor = texture(outputResultMap, v_uv);\nvec3 bloomColor = texture(bloomTexture, v_uv).rgb;\nvec3 result = hdrColor.rgb + bloomColor * texSize.w * hdrColor.a;\nfragColor = vec4(result, hdrColor.a);\n}", - } - ], - [ - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nin vec4 a_tangent;\n#if USE_INSTANCING\nin vec4 a_matWorld0;\nin vec4 a_matWorld1;\nin vec4 a_matWorld2;\n#if USE_LIGHTMAP\nin vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nin vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nin float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nin float a_vertexId;\n#endif\n#if CC_USE_SKINNING\nin vec4 a_joints;\nin vec4 a_weights;\n#endif\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nout vec2 v_uv;\nvoid main () {\nvec4 position;\nposition = vec4(a_position, 1.0);\nposition.xy = cc_cameraPos.w == 0.0 ? vec2(position.xy.x, -position.xy.y) : position.xy;\ngl_Position = vec4(position.x, position.y, 1.0, 1.0);\nv_uv = a_texCoord;\n}", - "frag": "\n#ifdef GL_EXT_shader_framebuffer_fetch\n#extension GL_EXT_shader_framebuffer_fetch: enable\n#endif\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\nhighp float unpackHighpData (float mainPart, float modPart) {\nhighp float data = mainPart;\nreturn data + modPart;\n}\nhighp float unpackHighpData (float mainPart, float modPart, const float modValue) {\nhighp float data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nhighp vec2 unpackHighpData (vec2 mainPart, vec2 modPart) {\nhighp vec2 data = mainPart;\nreturn data + modPart;\n}\nhighp vec2 unpackHighpData (vec2 mainPart, vec2 modPart, const float modValue) {\nhighp vec2 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nhighp vec3 unpackHighpData (vec3 mainPart, vec3 modPart) {\nhighp vec3 data = mainPart;\nreturn data + modPart;\n}\nhighp vec3 unpackHighpData (vec3 mainPart, vec3 modPart, const float modValue) {\nhighp vec3 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nhighp vec4 unpackHighpData (vec4 mainPart, vec4 modPart) {\nhighp vec4 data = mainPart;\nreturn data + modPart;\n}\nhighp vec4 unpackHighpData (vec4 mainPart, vec4 modPart, const float modValue) {\nhighp vec4 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\n#if USE_BATCHING\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nfloat CCGetLinearDepthFromViewSpace(vec3 viewPos) {\nfloat dist = length(viewPos);\nreturn (dist - cc_shadowNFLSInfo.x) / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x);\n}\nfloat CCGetLinearDepth(vec3 worldPos) {\nvec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0);\nreturn CCGetLinearDepthFromViewSpace(viewStartPos.xyz);\n}\n#if CC_RECEIVE_SHADOW\nuniform highp sampler2D cc_shadowMap;\nuniform highp sampler2D cc_spotLightingMap;\nvec4 ApplyShadowDepthBias_FaceNormal(vec4 shadowPos, vec3 worldNormal, float normalBias)\n{\nvec4 newShadowPos = shadowPos;\nif(normalBias > 0.0001)\n{\nvec4 viewNormal = cc_matLightView * vec4(worldNormal, 0.0);\nif(viewNormal.z < 0.1)\nnewShadowPos.xy += viewNormal.xy * cc_shadowProjInfo.xy * normalBias * clamp(viewNormal.z, 0.001, 0.1);\n}\nreturn newShadowPos;\n}\nvec4 ApplyShadowDepthBias_Perspective(vec4 shadowPos, float viewspaceDepthBias)\n{\nvec3 viewSpacePos;\nviewSpacePos.xy = shadowPos.xy * cc_shadowProjInfo.zw;\nviewSpacePos.z = shadowPos.z * cc_shadowInvProjDepthInfo.x + shadowPos.w * cc_shadowInvProjDepthInfo.y;\nviewSpacePos.xyz += cc_shadowProjDepthInfo.z * normalize(viewSpacePos.xyz) * viewspaceDepthBias;\nvec4 clipSpacePos;\nclipSpacePos.xy = viewSpacePos.xy * cc_shadowProjInfo.xy;\nclipSpacePos.zw = viewSpacePos.z * cc_shadowProjDepthInfo.xz + vec2(cc_shadowProjDepthInfo.y, 0.0);\nif (cc_shadowNFLSInfo.z > 0.000001) {\nclipSpacePos.z = CCGetLinearDepthFromViewSpace(viewSpacePos.xyz);\nclipSpacePos.z = (clipSpacePos.z * 2.0 - 1.0) * clipSpacePos.w;\n}\nreturn clipSpacePos;\n}\nvec4 ApplyShadowDepthBias_Orthographic(vec4 shadowPos, float viewspaceDepthBias)\n{\nfloat coeffA = cc_shadowProjDepthInfo.x;\nfloat coeffB = cc_shadowProjDepthInfo.y;\nfloat viewSpacePos_z = (shadowPos.z - coeffB) / coeffA;\nviewSpacePos_z += viewspaceDepthBias;\nvec4 result = shadowPos;\nresult.z = viewSpacePos_z * coeffA + coeffB;\nreturn result;\n}\nfloat CCGetShadowFactorHard (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture(cc_shadowMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n} else {\nclosestDepth = texture(cc_shadowMap, clipPos.xy).x;\n}\nshadow = step(clipPos.z, closestDepth);\nreturn shadow;\n}\nfloat CCGetShadowFactorSoft (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x);\nblock1 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)).x);\nblock2 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)).x);\nblock3 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetShadowFactorSoft2X (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock4 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock5 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock6 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock7 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock8 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)).x);\nblock1 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)).x);\nblock2 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)).x);\nblock3 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)).x);\nblock4 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x);\nblock5 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)).x);\nblock6 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)).x);\nblock7 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)).x);\nblock8 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCGetSpotLightShadowFactorHard (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nfloat depth = clipPos.z;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture(cc_spotLightingMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n} else {\nclosestDepth = texture(cc_spotLightingMap, clipPos.xy).x;\n}\nshadow = step(depth, closestDepth);\nreturn shadow;\n}\nfloat CCGetSpotLightShadowFactorSoft (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nvec2 oneTap = 1.0 / cc_shadowWHPBInfo.xy;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x);\nblock1 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)).x);\nblock2 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)).x);\nblock3 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * cc_shadowWHPBInfo.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY = mod(clipPos.y, oneTap.y) * cc_shadowWHPBInfo.y;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetSpotLightShadowFactorSoft2X (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock4 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock5 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock6 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock7 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock8 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)).x);\nblock1 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)).x);\nblock2 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)).x);\nblock3 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)).x);\nblock4 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x);\nblock5 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)).x);\nblock6 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)).x);\nblock7 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)).x);\nblock8 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCSpotShadowFactorBase(vec4 shadowPos, vec3 worldPos, vec2 shadowBias)\n{\nfloat pcf = cc_shadowWHPBInfo.z;\nif (pcf > 1.9) {\nreturn CCGetSpotLightShadowFactorSoft2X(shadowPos, worldPos, shadowBias.x);\n}else if (pcf > 0.9) {\nreturn CCGetSpotLightShadowFactorSoft(shadowPos, worldPos, shadowBias.x);\n}else {\nreturn CCGetSpotLightShadowFactorHard(shadowPos, worldPos, shadowBias.x);\n}\n}\nfloat CCShadowFactorBase(vec4 shadowPos, vec3 N, vec2 shadowBias)\n{\nfloat realtimeShadow = 1.0;\nvec4 pos = ApplyShadowDepthBias_FaceNormal(shadowPos, N, shadowBias.y);\nfloat pcf = cc_shadowWHPBInfo.z;\nif (pcf > 1.9) {\nrealtimeShadow = CCGetShadowFactorSoft2X(pos, shadowBias.x);\n}else if (pcf > 0.9) {\nrealtimeShadow = CCGetShadowFactorSoft(pos, shadowBias.x);\n}else {\nrealtimeShadow = CCGetShadowFactorHard(pos, shadowBias.x);\n}\nreturn mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w);\n}\n#endif\n#if CC_USE_IBL\nuniform samplerCube cc_environment;\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\nreturn textureLod(tex, coord, lod);\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\nreturn textureLod(tex, coord, lod);\n}\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(1.1, rgbe.a * 255.0 - 128.0);\n}\n#if CC_USE_DIFFUSEMAP\nuniform samplerCube cc_diffuseMap;\n#endif\n#endif\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\nvec3 NxH = cross(N, H);\nfloat OneMinusNoHSqr = dot(NxH, NxH);\nfloat a = roughness * roughness;\nfloat n = NoH * a;\nfloat p = a / (OneMinusNoHSqr + n * n);\nreturn p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\nreturn (roughness * 0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\nconst vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\nconst vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\nvec4 r = roughness * c0 + c1;\nfloat a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;\nvec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;\nAB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\nreturn specular * AB.x + AB.y;\n}\n#if USE_REFLECTION_DENOISE\nvec3 GetEnvReflectionWithMipFiltering(vec3 R, float roughness, float mipCount, float denoiseIntensity) {\n#if CC_USE_IBL\nfloat mip = roughness * mipCount;\nfloat delta = (dot(dFdx(R), dFdy(R))) * 1000.0;\nfloat mipBias = mix(0.0, 5.0, clamp(delta, 0.0, 1.0));\nvec4 biased = fragTextureLod(cc_environment, R, mip + mipBias);\nvec4 filtered = texture(cc_environment, R);\n#if CC_USE_IBL == 2\nbiased.rgb = unpackRGBE(biased);\nfiltered.rgb = unpackRGBE(filtered);\n#else\nbiased.rgb = SRGBToLinear(biased.rgb);\nfiltered.rgb = SRGBToLinear(filtered.rgb);\n#endif\nreturn mix(biased.rgb, filtered.rgb, denoiseIntensity);\n#else\nreturn vec3(0.0, 0.0, 0.0);\n#endif\n}\n#endif\nstruct StandardSurface {\nvec4 albedo;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nvec3 position, position_fract_part;\n#else\nvec3 position;\n#endif\nvec3 normal;\nvec3 emissive;\nvec3 lightmap;\nfloat lightmap_test;\nfloat roughness;\nfloat metallic;\nfloat occlusion;\n#if CC_RECEIVE_SHADOW\nvec2 shadowBias;\n#endif\n};\nvec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.0);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 L = normalize(-cc_mainLitDir.xyz);\nvec3 H = normalize(L + V);\nfloat NH = max(dot(N, H), 0.0);\nfloat NL = max(dot(N, L), 0.0);\nvec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w;\nvec3 diffuseContrib = diffuse;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nif (s.lightmap_test > 0.0001) {\nfinalColor = s.lightmap.rgb;\n}\n#else\ndiffuseContrib /= PI;\n#endif\nvec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\nvec3 dirlightContrib = (diffuseContrib + specularContrib);\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (NL > 0.0 && cc_mainLitDir.w > 0.0) {\nshadow = CCShadowFactorBase(shadowPos, N, s.shadowBias);\n}\n#endif\ndirlightContrib *= shadow;\nfinalColor *= dirlightContrib;\nfloat fAmb = 0.5 - N.y * 0.5;\nvec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb);\n#if CC_USE_IBL\n#if CC_USE_DIFFUSEMAP\nvec4 diffuseMap = texture(cc_diffuseMap, N);\n#if CC_USE_DIFFUSEMAP == 2\nambDiff = unpackRGBE(diffuseMap);\n#else\nambDiff = SRGBToLinear(diffuseMap.rgb);\n#endif\n#endif\nvec3 R = normalize(reflect(-V, N));\n#if USE_REFLECTION_DENOISE\nvec3 env = GetEnvReflectionWithMipFiltering(R, s.roughness, cc_ambientGround.w, 0.6);\n#else\nvec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n#if CC_USE_IBL == 2\nvec3 env = unpackRGBE(envmap);\n#else\nvec3 env = SRGBToLinear(envmap.rgb);\n#endif\n#endif\nfinalColor += env * cc_ambientSky.w * specular * s.occlusion;\n#endif\nfinalColor += ambDiff.rgb * cc_ambientSky.w * diffuse * s.occlusion;\nfinalColor += s.emissive;\nreturn vec4(finalColor, s.albedo.a);\n}\n#if CC_PIPELINE_TYPE == 0\n#define LIGHTS_PER_PASS 1\n#else\n#define LIGHTS_PER_PASS 10\n#endif\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0\nlayout(std140) uniform CCForwardLight {\nhighp vec4 cc_lightPos[LIGHTS_PER_PASS];\nvec4 cc_lightColor[LIGHTS_PER_PASS];\nvec4 cc_lightSizeRangeAngle[LIGHTS_PER_PASS];\nvec4 cc_lightDir[LIGHTS_PER_PASS];\n};\n#endif\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\nfloat factor = distSqr * invSqrAttRadius;\nfloat smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\nreturn smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\nfloat attenuation = 1.0 / max(distSqr, 0.01*0.01);\nattenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\nreturn attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\nfloat cd = dot(litDir, L);\nfloat attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\nreturn (attenuation * attenuation);\n}\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0\nvec4 CCStandardShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / PI;\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.0);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nint numLights = CC_PIPELINE_TYPE == 0 ? LIGHTS_PER_PASS : int(cc_lightDir[0].w);\nfor (int i = 0; i < LIGHTS_PER_PASS; i++) {\nif (i >= numLights) break;\nvec3 SLU = cc_lightPos[i].xyz - position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.0);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = cc_lightSizeRangeAngle[i].x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = PI * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(cc_lightSizeRangeAngle[i].y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (cc_lightPos[i].w > 0.0) {\nfloat cosInner = max(dot(-cc_lightDir[i].xyz, SL), 0.01);\nfloat cosOuter = cc_lightSizeRangeAngle[i].z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -cc_lightDir[i].xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = cc_lightColor[i].rgb;\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (cc_lightPos[i].w > 0.0 && cc_lightSizeRangeAngle[i].w > 0.0) {\nshadow = CCSpotShadowFactorBase(shadowPos, position, s.shadowBias);\n}\n#endif\nlightColor *= shadow;\nfinalColor += SNL * lightColor * cc_lightColor[i].w * illum * att * (diffuseContrib + lspec);\n}\nreturn vec4(finalColor, 0.0);\n}\n#endif\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1\nlayout(std430, binding = 4) readonly buffer b_ccLightsBuffer { vec4 b_ccLights[]; };\nlayout(std430, binding = 5) readonly buffer b_clusterLightIndicesBuffer { uint b_clusterLightIndices[]; };\nlayout(std430, binding = 6) readonly buffer b_clusterLightGridBuffer { uvec4 b_clusterLightGrid[]; };\nstruct CCLight\n{\nvec4 cc_lightPos;\nvec4 cc_lightColor;\nvec4 cc_lightSizeRangeAngle;\nvec4 cc_lightDir;\n};\nstruct Cluster\n{\nvec3 minBounds;\nvec3 maxBounds;\n};\nstruct LightGrid\n{\nuint offset;\nuint ccLights;\n};\nCCLight getCCLight(uint i)\n{\nCCLight light;\nlight.cc_lightPos = b_ccLights[4u * i + 0u];\nlight.cc_lightColor = b_ccLights[4u * i + 1u];\nlight.cc_lightSizeRangeAngle = b_ccLights[4u * i + 2u];\nlight.cc_lightDir = b_ccLights[4u * i + 3u];\nreturn light;\n}\nLightGrid getLightGrid(uint cluster)\n{\nuvec4 gridvec = b_clusterLightGrid[cluster];\nLightGrid grid;\ngrid.offset = gridvec.x;\ngrid.ccLights = gridvec.y;\nreturn grid;\n}\nuint getGridLightIndex(uint start, uint offset)\n{\nreturn b_clusterLightIndices[start + offset];\n}\nuint getClusterZIndex(vec4 worldPos)\n{\nfloat scale = float(24) / log(cc_nearFar.y / cc_nearFar.x);\nfloat bias = -(float(24) * log(cc_nearFar.x) / log(cc_nearFar.y / cc_nearFar.x));\nfloat eyeDepth = -(cc_matView * worldPos).z;\nuint zIndex = uint(max(log(eyeDepth) * scale + bias, 0.0));\nreturn zIndex;\n}\nuint getClusterIndex(vec4 fragCoord, vec4 worldPos)\n{\nuint zIndex = getClusterZIndex(worldPos);\nfloat clusterSizeX = ceil(cc_viewPort.z / float(16));\nfloat clusterSizeY = ceil(cc_viewPort.w / float(8));\nuvec3 indices = uvec3(uvec2(fragCoord.xy / vec2(clusterSizeX, clusterSizeY)), zIndex);\nuint cluster = (16u * 8u) * indices.z + 16u * indices.y + indices.x;\nreturn cluster;\n}\nvec4 CCClusterShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / PI;\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nuint cluster = getClusterIndex(gl_FragCoord, vec4(position, 1.0));\nLightGrid grid = getLightGrid(cluster);\nuint numLights = grid.ccLights;\nfor (uint i = 0u; i < 100u; i++) {\nif (i >= numLights) break;\nuint lightIndex = getGridLightIndex(grid.offset, i);\nCCLight light = getCCLight(lightIndex);\nvec3 SLU = light.cc_lightPos.xyz - position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.001);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = light.cc_lightSizeRangeAngle.x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = PI * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(light.cc_lightSizeRangeAngle.y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (light.cc_lightPos.w > 0.0) {\nfloat cosInner = max(dot(-light.cc_lightDir.xyz, SL), 0.01);\nfloat cosOuter = light.cc_lightSizeRangeAngle.z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -light.cc_lightDir.xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = light.cc_lightColor.rgb;\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (light.cc_lightPos.w > 0.0) {\nshadow = CCSpotShadowFactorBase(shadowPos, position, s.shadowBias);\n}\n#endif\nlightColor *= shadow;\nfinalColor += SNL * lightColor * light.cc_lightColor.w * illum * att * (diffuseContrib + lspec);\n}\nreturn vec4(finalColor, 0.0);\n}\n#endif\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = ACESToneMap(color.rgb);\n#endif\ncolor.rgb = sqrt(color.rgb);\nreturn color;\n}\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\nvoid CC_APPLY_FOG_BASE(inout vec4 color, float factor) {\ncolor = vec4(mix(cc_fogColor.rgb, color.rgb, factor), color.a);\n}\nvec2 signNotZero(vec2 v) {\nreturn vec2((v.x >= 0.0) ? +1.0 : -1.0, (v.y >= 0.0) ? +1.0 : -1.0);\n}\nvec3 oct_to_float32x3(vec2 e) {\nvec3 v = vec3(e.xy, 1.0 - abs(e.x) - abs(e.y));\nif (v.z < 0.0) v.xy = (1.0 - abs(v.yx)) * signNotZero(v.xy);\nreturn normalize(v);\n}\nvec4 screen2WS(vec3 coord) {\nvec3 ndc = vec3(\n2.0 * (coord.x - cc_viewPort.x) / cc_viewPort.z - 1.0,\n2.0 * (coord.y - cc_viewPort.y) / cc_viewPort.w - 1.0,\n2.0 * coord.z - 1.0);\nvec4 world = ((cc_matViewProjInv) * (vec4(ndc, 1.0)));\nworld = world / world.w;\nreturn world;\n}\nin vec2 v_uv;\n#if CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT\nlayout(location = 0) inout vec4 gbuffer_albedoMap;\nlayout(location = 1) inout vec4 gbuffer_normalMap;\nlayout(location = 2) inout vec4 gbuffer_emissiveMap;\n#else\nuniform sampler2D gbuffer_albedoMap;\nuniform sampler2D gbuffer_normalMap;\nuniform sampler2D gbuffer_emissiveMap;\n#endif\nuniform sampler2D depth_stencil;\n#if !CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT || __VERSION__ >= 450\nlayout(location = 0) out vec4 fragColor;\n#endif\nvoid main () {\nStandardSurface s;\n#if CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT\nvec4 albedoMap = gbuffer_albedoMap;\nvec4 normalMap = gbuffer_normalMap;\nvec4 emissiveMap = gbuffer_emissiveMap;\n#else\nvec4 albedoMap = texture(gbuffer_albedoMap,v_uv);\nvec4 normalMap = texture(gbuffer_normalMap,v_uv);\nvec4 emissiveMap = texture(gbuffer_emissiveMap,v_uv);\n#endif\nfloat depth = texture(depth_stencil, v_uv).x;\ns.albedo = albedoMap;\nvec3 position = screen2WS(vec3(gl_FragCoord.xy, depth)).xyz;\ns.position = position;\ns.roughness = normalMap.z;\ns.normal = oct_to_float32x3(normalMap.xy);\ns.metallic = normalMap.w;\ns.emissive = emissiveMap.xyz;\ns.occlusion = emissiveMap.w;\nfloat fogFactor;\nCC_TRANSFER_FOG_BASE(vec4(position, 1), fogFactor);\nvec4 shadowPos;\nshadowPos = cc_matLightViewProj * vec4(position, 1);\nvec4 color = CCStandardShadingBase(s, shadowPos) +\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1\nCCClusterShadingAdditive(s, shadowPos);\n#else\nCCStandardShadingAdditive(s, shadowPos);\n#endif\nCC_APPLY_FOG_BASE(color, fogFactor);\ncolor = CCFragOutput(color);\n#if CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT\ngbuffer_emissiveMap = color;\n#else\nfragColor = color;\n#endif\n}", - } - ], - [ - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nin vec4 a_tangent;\n#if USE_INSTANCING\nin vec4 a_matWorld0;\nin vec4 a_matWorld1;\nin vec4 a_matWorld2;\n#if USE_LIGHTMAP\nin vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nin vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nin float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nin float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_joints;\nin vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nlayout(std140) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nin highp vec4 a_jointAnimInfo;\n#endif\nlayout(std140) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(std140) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nuniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nlayout(std140) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout vec4 In)\n{\nIn = vec4(a_position, 1.0);\n#if CC_USE_MORPH\napplyMorph(In);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In);\n#endif\n}\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(std140) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(std140) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nvoid CCGetWorldMatrix(out mat4 matWorld)\n{\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\n#else\nmatWorld = cc_matWorld;\n#endif\n}\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\nout float v_dist;\nvec4 vert () {\nvec4 position;\nCCVertInput(position);\nmat4 matWorld;\nCCGetWorldMatrix(matWorld);\nvec3 P = (matWorld * position).xyz;\nvec3 L = cc_mainLitDir.xyz;\nvec3 N = cc_planarNDInfo.xyz;\nfloat d = cc_planarNDInfo.w + 0.001;\nfloat dist = (-d - dot(P, N)) / (dot(L, N) + 0.0001);\nvec3 shadowPos = P + L * dist;\nvec3 view = normalize(cc_cameraPos.xyz - shadowPos);\nfloat viewLength = length(cc_cameraPos.xyz - shadowPos);\nshadowPos += view * min(1.0, 0.005 * viewLength);\nposition = cc_matProj * cc_matView * vec4(shadowPos, 1.0);\nv_dist = dist;\nreturn position;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(std140) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nin float v_dist;\nvec4 frag () {\nif(v_dist < 0.0)\ndiscard;\nreturn CCFragOutput(cc_shadowColor);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nin vec4 a_tangent;\n#if USE_INSTANCING\nin vec4 a_matWorld0;\nin vec4 a_matWorld1;\nin vec4 a_matWorld2;\n#if USE_LIGHTMAP\nin vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nin vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nin float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nin float a_vertexId;\nint getVertexId() {\nreturn int(a_vertexId);\n}\n#endif\n#if CC_USE_SKINNING\nin vec4 a_joints;\nin vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nlayout(std140) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nuniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nuniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nuniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nin highp vec4 a_jointAnimInfo;\n#endif\nlayout(std140) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(std140) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nuniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nlayout(std140) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nout vec2 v_uv;\nvoid main () {\nStandardVertInput In;\nCCVertInput(In);\nIn.position.xy = cc_cameraPos.w == 0.0 ? vec2(In.position.xy.x, -In.position.xy.y) : In.position.xy;\ngl_Position = In.position;\ngl_Position.y = gl_Position.y;\nv_uv = a_texCoord;\n}", - "frag": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if ANTIALIAS_TYPE == 1\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\nvec2 v_rgbNW, vec2 v_rgbNE,\nvec2 v_rgbSW, vec2 v_rgbSE,\nvec2 v_rgbM) {\nvec4 color;\nmediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\nvec3 rgbNW = texture(tex, v_rgbNW).xyz;\nvec3 rgbNE = texture(tex, v_rgbNE).xyz;\nvec3 rgbSW = texture(tex, v_rgbSW).xyz;\nvec3 rgbSE = texture(tex, v_rgbSE).xyz;\nvec4 texColor = texture(tex, v_rgbM);\nvec3 rgbM = texColor.xyz;\nvec3 luma = vec3(0.299, 0.587, 0.114);\nfloat lumaNW = dot(rgbNW, luma);\nfloat lumaNE = dot(rgbNE, luma);\nfloat lumaSW = dot(rgbSW, luma);\nfloat lumaSE = dot(rgbSE, luma);\nfloat lumaM = dot(rgbM, luma);\nfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\nfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\nmediump vec2 dir;\ndir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\ndir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\nfloat dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n(0.25 * (1.0 / 8.0)), (1.0/ 128.0));\nfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\ndir = min(vec2(8.0, 8.0),\nmax(vec2(-8.0, -8.0),\ndir * rcpDirMin)) * inverseVP;\nvec3 rgbA = 0.5 * (\ntexture(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\ntexture(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\nvec3 rgbB = rgbA * 0.5 + 0.25 * (\ntexture(tex, fragCoord * inverseVP + dir * -0.5).xyz +\ntexture(tex, fragCoord * inverseVP + dir * 0.5).xyz);\nfloat lumaB = dot(rgbB, luma);\nif ((lumaB < lumaMin) || (lumaB > lumaMax))\ncolor = vec4(rgbA, texColor.a);\nelse\ncolor = vec4(rgbB, texColor.a);\nreturn color;\n}\n#endif\nin vec2 v_uv;\nuniform sampler2D outputResultMap;\nlayout(location = 0) out vec4 fragColor;\nvoid texcoords(vec2 fragCoord, vec2 resolution,\nout vec2 v_rgbNW, out vec2 v_rgbNE,\nout vec2 v_rgbSW, out vec2 v_rgbSE,\nout vec2 v_rgbM) {\nvec2 inverseVP = 1.0 / resolution.xy;\nv_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\nv_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\nv_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\nv_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\nv_rgbM = vec2(fragCoord * inverseVP);\n}\nvoid main () {\nmediump vec2 v_rgbNW;\nmediump vec2 v_rgbNE;\nmediump vec2 v_rgbSW;\nmediump vec2 v_rgbSE;\nmediump vec2 v_rgbM;\n#if ANTIALIAS_TYPE == 1\nvec2 resolution = cc_screenSize.xy;\nvec2 fragCoord = v_uv * resolution;\ntexcoords(fragCoord, resolution, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\nfragColor = fxaa(outputResultMap, fragCoord, resolution, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n#else\nfragColor = texture(outputResultMap, v_uv);\n#endif\n}", - } - ], - [ - { - "vert": "\nprecision highp float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nin vec3 a_position;\nin vec3 a_normal;\nin vec2 a_texCoord;\nin vec4 a_tangent;\n#if USE_INSTANCING\nin vec4 a_matWorld0;\nin vec4 a_matWorld1;\nin vec4 a_matWorld2;\n#if USE_LIGHTMAP\nin vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nin vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nin float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nin float a_vertexId;\n#endif\n#if CC_USE_SKINNING\nin vec4 a_joints;\nin vec4 a_weights;\n#endif\nout mediump vec4 viewDir;\nvec4 vert () {\nviewDir = vec4(a_position, 1.0);\nmat4 matViewRotOnly = mat4(mat3(cc_matView));\nvec4 pos = matViewRotOnly * viewDir;\nif (cc_matProj[3].w > 0.0) {\nmat4 matProj = cc_matProj;\nmatProj[0].x = 5.2;\nmatProj[1].y = 2.6;\nmatProj[2].zw = vec2(-1.0);\nmatProj[3].zw = vec2(0.0);\npos = matProj * pos;\n} else {\npos = cc_matProj * pos;\n}\npos.z = 0.99999 * pos.w;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nuniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(1.1, rgbe.a * 255.0 - 128.0);\n}\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = ACESToneMap(color.rgb);\n#endif\ncolor.rgb = sqrt(color.rgb);\nreturn color;\n}\nin mediump vec4 viewDir;\nvec4 frag () {\n#if USE_RGBE_CUBEMAP\nvec3 c = unpackRGBE(texture(cc_environment, viewDir.xyz));\n#else\nvec3 c = SRGBToLinear(texture(cc_environment, viewDir.xyz).rgb);\n#endif\nreturn CCFragOutput(vec4(c * cc_ambientSky.w, 1.0));\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nin vec3 a_position;\nin vec4 a_color;\nout vec2 v_uv;\nlayout(std140) uniform Constants {\nvec4 offset;\n};\nlayout(std140) uniform PerFrameInfo {\nvec4 digits[8 * 10 / 4];\n};\nfloat getComponent(vec4 v, float i) {\nif (i < 1.0) { return v.x; }\nelse if (i < 2.0) { return v.y; }\nelse if (i < 3.0) { return v.z; }\nelse { return v.w; }\n}\nvec4 vert () {\nmat2 proj = mat2(cc_matProj[0].xy, cc_matProj[1].xy);\nproj /= abs(proj[1].x + proj[1].y);\nvec2 position = proj * a_position.xy + offset.xy;\nv_uv = a_color.xy;\nif (a_color.z >= 0.0) {\nfloat n = getComponent(digits[int(a_color.z)], a_color.w);\nv_uv += vec2(offset.z * n, 0.0);\n}\nreturn vec4(position, 0.0, 1.0);\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(std140) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(std140) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nin vec2 v_uv;\nuniform sampler2D mainTexture;\nvec4 frag () {\nreturn CCFragOutput(texture(mainTexture, v_uv));\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nin vec2 a_position;\nin vec2 a_texCoord;\nout vec2 v_uv;\nlayout(std140) uniform Constant {\nvec4 u_buffer0;\nvec4 u_buffer1;\nmat4 u_projection;\n};\nvec4 vert () {\nvec2 worldPos = a_position * u_buffer1.xy + u_buffer1.zw;\nvec2 clipSpace = worldPos / u_buffer0.xy * 2.0 - 1.0;\nvec4 screenPos = u_projection * vec4(clipSpace, 0.0, 1.0);\nv_uv = a_texCoord;\nreturn screenPos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nin vec2 v_uv;\nlayout(std140) uniform Factor {\nfloat u_percent;\n};\nuniform sampler2D mainTexture;\nvec4 frag () {\nvec4 color = texture(mainTexture, v_uv);\nfloat percent = clamp(u_percent, 0.0, 1.0);\ncolor.xyz *= percent;\nreturn color;\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ] -]; diff --git a/cocos/core/builtin/shader-sources/glsl4.ts b/cocos/core/builtin/shader-sources/glsl4.ts deleted file mode 100644 index 82b9772796..0000000000 --- a/cocos/core/builtin/shader-sources/glsl4.ts +++ /dev/null @@ -1,169 +0,0 @@ -/* eslint-disable */ -export const glsl4 = [ - [ - { - "vert": "\nprecision mediump float;\nlayout(set = 1, binding = 0) uniform Constants {\nvec4 mainTiling_Offset;\nvec4 frameTile_velLenScale;\nvec4 scale;\nvec4 nodeRotation;\n};\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(set = 2, binding = 0) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(set = 2, binding = 0) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\nmat3 m = mat3(xAxis,yAxis,zAxis);\nfloat trace = m[0][0] + m[1][1] + m[2][2];\nvec4 quat;\nif (trace > 0.) {\nfloat s = 0.5 / sqrt(trace + 1.0);\nquat.w = 0.25 / s;\nquat.x = (m[2][1] - m[1][2]) * s;\nquat.y = (m[0][2] - m[2][0]) * s;\nquat.z = (m[1][0] - m[0][1]) * s;\n} else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\nfloat s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\nquat.w = (m[2][1] - m[1][2]) / s;\nquat.x = 0.25 * s;\nquat.y = (m[0][1] + m[1][0]) / s;\nquat.z = (m[0][2] + m[2][0]) / s;\n} else if (m[1][1] > m[2][2]) {\nfloat s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\nquat.w = (m[0][2] - m[2][0]) / s;\nquat.x = (m[0][1] + m[1][0]) / s;\nquat.y = 0.25 * s;\nquat.z = (m[1][2] + m[2][1]) / s;\n} else {\nfloat s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\nquat.w = (m[1][0] - m[0][1]) / s;\nquat.x = (m[0][2] + m[2][0]) / s;\nquat.y = (m[1][2] + m[2][1]) / s;\nquat.z = 0.25 * s;\n}\nfloat len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\nif (len > 0.) {\nlen = 1. / sqrt(len);\nquat.x = quat.x * len;\nquat.y = quat.y * len;\nquat.z = quat.z * len;\nquat.w = quat.w * len;\n}\nreturn quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\nfloat x = angle.x / 2.;\nfloat y = angle.y / 2.;\nfloat z = angle.z / 2.;\nfloat sx = sin(x);\nfloat cx = cos(x);\nfloat sy = sin(y);\nfloat cy = cos(y);\nfloat sz = sin(z);\nfloat cz = cos(z);\nvec4 quat = vec4(0);\nquat.x = sx * cy * cz + cx * sy * sz;\nquat.y = cx * sy * cz + sx * cy * sz;\nquat.z = cx * cy * sz - sx * sy * cz;\nquat.w = cx * cy * cz - sx * sy * sz;\nreturn quat;\n}\nvec4 quatMultiply (vec4 a, vec4 b){\nvec4 quat;\nquat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\nquat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\nquat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\nquat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\nreturn quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\nfloat ix = q.w * v.x + q.y * v.z - q.z * v.y;\nfloat iy = q.w * v.y + q.z * v.x - q.x * v.z;\nfloat iz = q.w * v.z + q.x * v.y - q.y * v.x;\nfloat iw = -q.x * v.x - q.y * v.y - q.z * v.z;\nv.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\nv.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\nv.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\nvec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\nvec4 rotQuat = quatMultiply(viewQuat, q);\nrotateVecFromQuat(pos, rotQuat);\nreturn pos;\n}\nlayout(location = 0) out mediump vec2 uv;\nlayout(location = 1) out mediump vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n, mat4 viewInv\n) {\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\nvec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\nvec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n}\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec2 a_texCoord;\nlayout(location = 2) in vec4 a_color;\nlayout(set = 1, binding = 1) uniform builtin {\nvec4 cc_size_rotation;\n};\nvec4 vs_main() {\nvec4 pos = vec4(a_position, 1);\npos = cc_matWorld * pos;\nvec2 vertOffset = a_texCoord.xy - 0.5;\ncomputeVertPos(pos, vertOffset, quaternionFromEuler(vec3(0., 0., cc_size_rotation.z)), vec3(cc_size_rotation.xy, 0.), cc_matViewInv);\npos = cc_matViewProj * pos;\nuv = a_texCoord.xy;\ncolor = a_color;\nreturn pos;\n}\nvoid main() { gl_Position = vs_main(); }", - "frag": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nlayout(location = 0) in vec2 uv;\nlayout(location = 1) in vec4 color;\nlayout(set = 1, binding = 3) uniform sampler2D mainTexture;\nlayout(set = 1, binding = 2) uniform FragConstants {\nvec4 tintColor;\n};\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\nreturn CCFragOutput(col);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\nlayout(location = 0) in vec3 a_position;\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\nvec4 frag () {\nvec4 o = vec4(1.0);\nreturn o;\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\nlayout(location = 2) in vec4 a_color;\nlayout(location = 0) out vec2 v_texCoord;\nlayout(location = 1) out vec4 v_color;\nvec4 vert () {\nint orientation = int(cc_surfaceTransform.x);\nvec4 transform = vec4(1.0, 0.0, 0.0, 1.0);\nif (orientation == 0) {\ntransform = vec4(1.0, 0.0, 0.0, 1.0);\n} else if (orientation == 1) {\ntransform = vec4(0.0, 1.0, -1.0, 0.0);\n} else if (orientation == 2) {\ntransform = vec4(-1.0, 0.0, 0.0, -1.0);\n} else if (orientation == 3) {\ntransform = vec4(0.0, -1.0, 1.0, 0.0);\n}\nvec2 invScreenSize = (orientation == 1 || orientation == 3) ? cc_screenSize.wz : cc_screenSize.zw;\nvec2 position = a_position * invScreenSize;\nposition = position * vec2(2.0, -2.0) + vec2(-1.0, 1.0);\nvec2 clipPos = vec2(dot(transform.xy, position), dot(transform.zw, position));\nclipPos = cc_cameraPos.w == 0.0 ? vec2(clipPos.x, -clipPos.y) : clipPos;\nv_texCoord = a_texCoord;\nv_color = a_color;\nreturn vec4(clipPos, 0.0, 1.0);\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nlayout(location = 0) in vec2 v_texCoord;\nlayout(location = 1) in vec4 v_color;\nlayout(set = 1, binding = 0) uniform sampler2D mainTexture;\nvec4 frag () {\nvec4 color = vec4(v_color.rgb, v_color.a * texture(mainTexture, v_texCoord).r);\nreturn CCFragOutput(color);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(location = 0) in highp vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 0) out vec4 v_color;\nvec4 vert () {\nvec4 pos = cc_matViewProj * vec4(a_position, 1);\npos.z -= 0.000001;\nv_color = a_color;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nlayout(location = 0) in vec4 v_color;\nvec4 front() {\n#if USE_FORWARD_PIPELINE\nreturn CCFragOutput(v_color);\n#else\nreturn v_color;\n#endif\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = front(); }", - }, - { - "vert": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(location = 0) in highp vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 0) out vec4 v_color;\nvec4 vert () {\nvec4 pos = cc_matViewProj * vec4(a_position, 1);\npos.z -= 0.000001;\nv_color = a_color;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nlayout(location = 0) in vec4 v_color;\nvec4 back() {\n#if USE_FORWARD_PIPELINE\nreturn CCFragOutput(vec4(v_color.rgb, v_color.a * 0.2));\n#else\nreturn vec4(v_color.rgb, v_color.a * 0.2);\n#endif\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = back(); }", - }, - { - "vert": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(location = 0) in highp vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 0) out vec4 v_color;\nlayout(location = 1) out float v_distance;\nvec4 vert () {\nvec4 pos = cc_matViewProj * vec4(a_position, 1);\npos.z -= 0.000001;\nv_color = a_color;\nv_distance = dot(a_position, vec3(1.0, 1.0, 1.0));\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nlayout(location = 0) in vec4 v_color;\nlayout(location = 1) in float v_distance;\nvec4 front() {\nif (fract(v_distance) > 0.5) {\ndiscard;\n}\n#if USE_FORWARD_PIPELINE\nreturn CCFragOutput(v_color);\n#else\nreturn v_color;\n#endif\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = front(); }", - }, - { - "vert": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(location = 0) in highp vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 0) out vec4 v_color;\nlayout(location = 1) out float v_distance;\nvec4 vert () {\nvec4 pos = cc_matViewProj * vec4(a_position, 1);\npos.z -= 0.000001;\nv_color = a_color;\nv_distance = dot(a_position, vec3(1.0, 1.0, 1.0));\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nlayout(location = 0) in vec4 v_color;\nlayout(location = 1) in float v_distance;\nvec4 back() {\nif (fract(v_distance) > 0.5) {\ndiscard;\n}\n#if USE_FORWARD_PIPELINE\nreturn CCFragOutput(vec4(v_color.rgb, v_color.a * 0.2));\n#else\nreturn vec4(v_color.rgb, v_color.a * 0.2);\n#endif\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = back(); }", - }, - { - "vert": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(location = 0) in highp vec3 a_position;\nlayout(location = 1) in vec4 a_normal;\nlayout(location = 2) in vec4 a_color;\nlayout(location = 0) out vec4 v_color;\nvec4 vert () {\nvec4 pos = cc_matViewProj * vec4(a_position, 1);\nv_color = a_color;\nfloat intensity = dot(vec3(1, 2, 4), a_normal.xyz);\nv_color.rgb -= a_normal.w * intensity * 0.1;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nlayout(location = 0) in vec4 v_color;\nvec4 front() {\n#if USE_FORWARD_PIPELINE\nreturn CCFragOutput(v_color);\n#else\nreturn v_color;\n#endif\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = front(); }", - }, - { - "vert": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(location = 0) in highp vec3 a_position;\nlayout(location = 1) in vec4 a_normal;\nlayout(location = 2) in vec4 a_color;\nlayout(location = 0) out vec4 v_color;\nvec4 vert () {\nvec4 pos = cc_matViewProj * vec4(a_position, 1);\nv_color = a_color;\nfloat intensity = dot(vec3(1, 2, 4), a_normal.xyz);\nv_color.rgb -= a_normal.w * intensity * 0.1;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nlayout(location = 0) in vec4 v_color;\nvec4 back() {\n#if USE_FORWARD_PIPELINE\nreturn CCFragOutput(vec4(v_color.rgb, v_color.a * 0.2));\n#else\nreturn vec4(v_color.rgb, v_color.a * 0.2);\n#endif\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = back(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(set = 2, binding = 0) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(set = 2, binding = 0) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 0) out vec4 v_color;\nlayout(location = 2) in float a_dist;\nlayout(location = 1) out float v_dist;\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\npos = cc_matViewProj * cc_matWorld * pos;\nv_color = a_color;\nv_dist = a_dist;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\nlayout(location = 0) in vec4 v_color;\nlayout(location = 1) in float v_dist;\nvec4 frag () {\nvec4 o = v_color;\nfloat aa = fwidth(v_dist);\nfloat alpha = 1. - smoothstep(-aa, 0., abs(v_dist) - 1.0);\no.rgb *= o.a;\no *= alpha;\nreturn o;\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(set = 2, binding = 0) uniform CCWorldBound {\nhighp vec4 cc_worldBoundCenter;\nhighp vec4 cc_worldBoundHalfExtents;\n};\nlayout(location = 0) in vec3 a_position;\nvec4 vert () {\nvec4 position;\nposition = vec4(a_position, 1.0);\nposition *= cc_worldBoundHalfExtents;\nposition += cc_worldBoundCenter;\nposition = cc_matViewProj * position;\nreturn position;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nvec4 frag () {\nreturn vec4(1, 0, 0, 1);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\nmat3 m = mat3(xAxis,yAxis,zAxis);\nfloat trace = m[0][0] + m[1][1] + m[2][2];\nvec4 quat;\nif (trace > 0.) {\nfloat s = 0.5 / sqrt(trace + 1.0);\nquat.w = 0.25 / s;\nquat.x = (m[2][1] - m[1][2]) * s;\nquat.y = (m[0][2] - m[2][0]) * s;\nquat.z = (m[1][0] - m[0][1]) * s;\n} else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\nfloat s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\nquat.w = (m[2][1] - m[1][2]) / s;\nquat.x = 0.25 * s;\nquat.y = (m[0][1] + m[1][0]) / s;\nquat.z = (m[0][2] + m[2][0]) / s;\n} else if (m[1][1] > m[2][2]) {\nfloat s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\nquat.w = (m[0][2] - m[2][0]) / s;\nquat.x = (m[0][1] + m[1][0]) / s;\nquat.y = 0.25 * s;\nquat.z = (m[1][2] + m[2][1]) / s;\n} else {\nfloat s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\nquat.w = (m[1][0] - m[0][1]) / s;\nquat.x = (m[0][2] + m[2][0]) / s;\nquat.y = (m[1][2] + m[2][1]) / s;\nquat.z = 0.25 * s;\n}\nfloat len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\nif (len > 0.) {\nlen = 1. / sqrt(len);\nquat.x = quat.x * len;\nquat.y = quat.y * len;\nquat.z = quat.z * len;\nquat.w = quat.w * len;\n}\nreturn quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\nfloat x = angle.x / 2.;\nfloat y = angle.y / 2.;\nfloat z = angle.z / 2.;\nfloat sx = sin(x);\nfloat cx = cos(x);\nfloat sy = sin(y);\nfloat cy = cos(y);\nfloat sz = sin(z);\nfloat cz = cos(z);\nvec4 quat = vec4(0);\nquat.x = sx * cy * cz + cx * sy * sz;\nquat.y = cx * sy * cz + sx * cy * sz;\nquat.z = cx * cy * sz - sx * sy * cz;\nquat.w = cx * cy * cz - sx * sy * sz;\nreturn quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\nfloat x2 = q.x + q.x;\nfloat y2 = q.y + q.y;\nfloat z2 = q.z + q.z;\nfloat xx = q.x * x2;\nfloat xy = q.x * y2;\nfloat xz = q.x * z2;\nfloat yy = q.y * y2;\nfloat yz = q.y * z2;\nfloat zz = q.z * z2;\nfloat wx = q.w * x2;\nfloat wy = q.w * y2;\nfloat wz = q.w * z2;\nreturn mat4(\n1. - (yy + zz), xy + wz, xz - wy, 0,\nxy - wz, 1. - (xx + zz), yz + wx, 0,\nxz + wy, yz - wx, 1. - (xx + yy), 0,\np.x, p.y, p.z, 1\n);\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\nfloat x = q.x, y = q.y, z = q.z, w = q.w;\nfloat x2 = x + x;\nfloat y2 = y + y;\nfloat z2 = z + z;\nfloat xx = x * x2;\nfloat xy = x * y2;\nfloat xz = x * z2;\nfloat yy = y * y2;\nfloat yz = y * z2;\nfloat zz = z * z2;\nfloat wx = w * x2;\nfloat wy = w * y2;\nfloat wz = w * z2;\nfloat sx = s.x;\nfloat sy = s.y;\nfloat sz = s.z;\nreturn mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n(xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n(xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\nt.x, t.y, t.z, 1);\n}\nvec4 quatMultiply (vec4 a, vec4 b){\nvec4 quat;\nquat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\nquat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\nquat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\nquat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\nreturn quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\nfloat ix = q.w * v.x + q.y * v.z - q.z * v.y;\nfloat iy = q.w * v.y + q.z * v.x - q.x * v.z;\nfloat iz = q.w * v.z + q.x * v.y - q.y * v.x;\nfloat iw = -q.x * v.x - q.y * v.y - q.z * v.z;\nv.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\nv.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\nv.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\nvec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\nvec4 rotQuat = quatMultiply(viewQuat, q);\nrotateVecFromQuat(pos, rotQuat);\nreturn pos;\n}\nmat3 quatToMat3(vec4 q) {\nvec3 m0 = vec3(\n1.0 - 2.0 * q.y * q.y - 2.0 * q.z * q.z,\n2.0 * q.x * q.y + 2.0 * q.w * q.z,\n2.0 * q.x * q.z - 2.0 * q.w * q.y);\nvec3 m1 = vec3(\n2.0 * q.x * q.y - 2.0 * q.w * q.z,\n1.0 - 2.0 * q.x * q.x - 2.0 * q.z * q.z,\n2.0 * q.y * q.z + 2.0 * q.w * q.x);\nvec3 m2 = vec3(\n2.0 * q.x * q.z + 2.0 * q.w * q.y,\n2.0 * q.y * q.z - 2.0 * q.w * q.x,\n1.0 - 2.0 * q.x * q.x - 2.0 * q.y * q.y);\nreturn mat3(m0, m1, m2);\n}\nvec4 mat3ToQuat(mat3 mat) {\nfloat tr = mat[0][0] + mat[1][1] + mat[2][2];\nfloat qw, qx, qy, qz;\nif (tr > 0.0) {\nfloat S = sqrt(tr + 1.0) * 2.0;\nfloat invS = 1.0 / S;\nqw = 0.25 * S;\nqx = (mat[1][2] - mat[2][1]) * invS;\nqy = (mat[2][0] - mat[0][2]) * invS;\nqz = (mat[0][1] - mat[1][0]) * invS;\n} else if ((mat[0][0] > mat[1][1])&&(mat[0][0] > mat[2][2])) {\nfloat S = sqrt(1.0 + mat[0][0] - mat[1][1] - mat[2][2]) * 2.0;\nfloat invS = 1.0 / S;\nqw = (mat[1][2] - mat[2][1]) * invS;\nqx = 0.25 * S;\nqy = (mat[1][0] + mat[0][1]) * invS;\nqz = (mat[2][0] + mat[0][2]) * invS;\n} else if (mat[1][1] > mat[2][2]) {\nfloat S = sqrt(1.0 + mat[1][1] - mat[0][0] - mat[2][2]) * 2.0;\nfloat invS = 1.0 / S;\nqw = (mat[2][0] - mat[0][2]) * invS;\nqx = (mat[1][0] + mat[0][1]) * invS;\nqy = 0.25 * S;\nqz = (mat[2][1] + mat[1][2]) * invS;\n} else {\nfloat S = sqrt(1.0 + mat[2][2] - mat[0][0] - mat[1][1]) * 2.0;\nfloat invS = 1.0 / S;\nqw = (mat[0][1] - mat[1][0]) * invS;\nqx = (mat[2][0] + mat[0][2]) * invS;\nqy = (mat[2][1] + mat[1][2]) * invS;\nqz = 0.25 * S;\n}\nreturn vec4(qx, qy, qz, qw);\n}\nvec4 eulerToQuat(vec3 euler) {\nvec3 er = euler * 0.5;\nfloat x = er.x, y = er.y, z = er.z;\nfloat sx = sin(x);\nfloat cx = cos(x);\nfloat sy = sin(y);\nfloat cy = cos(y);\nfloat sz = sin(z);\nfloat cz = cos(z);\nvec4 quat;\nquat.x = sx * cy * cz + cx * sy * sz;\nquat.y = cx * sy * cz + sx * cy * sz;\nquat.z = cx * cy * sz - sx * sy * cz;\nquat.w = cx * cy * cz - sx * sy * sz;\nreturn quat;\n}\nlayout(set = 1, binding = 0) uniform Constants {\nvec4 mainTiling_Offset;\nvec4 frameTile_velLenScale;\nvec4 scale;\nvec4 nodeRotation;\n};\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(set = 2, binding = 0) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(set = 2, binding = 0) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nlayout(location = 0) out mediump vec2 uv;\nlayout(location = 1) out mediump vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n, mat4 viewInv\n#endif\n#if CC_RENDER_MODE == 1\n, vec3 eye\n, vec4 velocity\n, float velocityScale\n, float lengthScale\n, float xIndex\n#endif\n) {\n#if CC_RENDER_MODE == 0\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\nvec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\nvec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_RENDER_MODE == 1\nvec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\nvec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\npos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_RENDER_MODE == 2\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = vec3(1, 0, 0);\nvec3 camY = vec3(0, 0, -1);\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_RENDER_MODE == 3\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nrotateVecFromQuat(viewSpaceVert, q);\nvec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\nvec3 camY = vec3(0, 1, 0);\nvec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\npos.xyz += offset;\n#else\npos.x += vertOffset.x;\npos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV (float frameIndex, vec2 vertIndex, vec2 frameTile){\nvec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\naniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if CC_RENDER_MODE != 4\nvertIndex.y = 1. - vertIndex.y;\n#endif\nreturn (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nlayout(set = 1, binding = 1) uniform SampleConstants {\nvec4 u_sampleInfo;\n};\nlayout(set = 1, binding = 2) uniform TickConstants {\nvec4 u_worldRot;\nvec4 u_timeDelta;\n};\nlayout(location = 0) in vec4 a_position_starttime;\nlayout(location = 1) in vec4 a_size_uv;\nlayout(location = 2) in vec4 a_rotation_uv;\nlayout(location = 3) in vec4 a_color;\nlayout(location = 4) in vec4 a_dir_life;\nlayout(location = 5) in float a_rndSeed;\n#if CC_RENDER_MODE == 4\nlayout(location = 6) in vec3 a_texCoord;\nlayout(location = 7) in vec3 a_texCoord3;\nlayout(location = 8) in vec3 a_normal;\nlayout(location = 9) in vec4 a_color1;\n#endif\nvec3 unpackCurveData (sampler2D tex, vec2 coord) {\nvec4 a = texture(tex, coord);\nvec4 b = texture(tex, coord + u_sampleInfo.y);\nfloat c = fract(coord.x * u_sampleInfo.x);\nreturn mix(a.xyz, b.xyz, c);\n}\nvec3 unpackCurveData (sampler2D tex, vec2 coord, out float w) {\nvec4 a = texture(tex, coord);\nvec4 b = texture(tex, coord + u_sampleInfo.y);\nfloat c = fract(coord.x * u_sampleInfo.x);\nw = mix(a.w, b.w, c);\nreturn mix(a.xyz, b.xyz, c);\n}\nfloat pseudoRandom(float x) {\n#if USE_VK_SHADER\nfloat o = x;\nx = mod(x - 1.0, 2.0) - 1.0;\nfloat freqVar = 10.16640753482;\nfloat y = sin(freqVar * floor(o * 0.5 - 0.5));\nfloat v = max(0.0, 1.0-abs(x));\nv *= 0.7071067812;\nv = y < 0.0 ? -v : v;\nreturn v;\n#else\nfloat seed = mod(x, 233280.);\nfloat q = (seed * 9301. + 49297.) / 233280.;\nreturn fract(q);\n#endif\n}\n#if COLOR_OVER_TIME_MODULE_ENABLE\nlayout(set = 1, binding = 10) uniform sampler2D color_over_time_tex0;\nlayout(set = 1, binding = 3) uniform ColorConstant {\nint u_color_mode;\n};\n#endif\n#if ROTATION_OVER_TIME_MODULE_ENABLE\nlayout(set = 1, binding = 11) uniform sampler2D rotation_over_time_tex0;\nlayout(set = 1, binding = 4) uniform RotationConstant {\nint u_rotation_mode;\n};\n#endif\n#if SIZE_OVER_TIME_MODULE_ENABLE\nlayout(set = 1, binding = 12) uniform sampler2D size_over_time_tex0;\nlayout(set = 1, binding = 5) uniform SizeConstant {\nint u_size_mode;\n};\n#endif\n#if FORCE_OVER_TIME_MODULE_ENABLE\nlayout(set = 1, binding = 13) uniform sampler2D force_over_time_tex0;\nlayout(set = 1, binding = 6) uniform ForceConstant {\nint u_force_mode;\nint u_force_space;\n};\n#endif\n#if VELOCITY_OVER_TIME_MODULE_ENABLE\nlayout(set = 1, binding = 14) uniform sampler2D velocity_over_time_tex0;\nlayout(set = 1, binding = 7) uniform VelocityConstant {\nint u_velocity_mode;\nint u_velocity_space;\n};\n#endif\n#if TEXTURE_ANIMATION_MODULE_ENABLE\nlayout(set = 1, binding = 15) uniform sampler2D texture_animation_tex0;\nlayout(set = 1, binding = 8) uniform AnimationConstant {\nvec4 u_anim_info;\n};\n#endif\nfloat repeat (float t, float length) {\nreturn t - floor(t / length) * length;\n}\nvec4 rotateQuat (vec4 p, vec4 q) {\nvec3 iv = cross(q.xyz, p.xyz) + q.w * p.xyz;\nvec3 res = p.xyz + 2.0 * cross(q.xyz, iv);\nreturn vec4(res.xyz, p.w);\n}\nvec4 gpvs_main () {\nfloat activeTime = u_timeDelta.x - a_position_starttime.w;\nfloat normalizedTime = clamp(activeTime / a_dir_life.w, 0.0, 1.0);\nvec2 timeCoord0 = vec2(normalizedTime, 0.);\nvec2 timeCoord1 = vec2(normalizedTime, 1.);\n#if CC_RENDER_MODE == 4\nvec2 vertIdx = vec2(a_texCoord.x, a_texCoord.y);\n#else\nvec2 vertIdx = vec2(a_size_uv.w, a_rotation_uv.w);\n#endif\nvec4 velocity = vec4(a_dir_life.xyz, 0.);\nvec4 pos = vec4(a_position_starttime.xyz, 1.);\nvec3 size = a_size_uv.xyz;\n#if SIZE_OVER_TIME_MODULE_ENABLE\nif (u_size_mode == 1) {\nsize *= unpackCurveData(size_over_time_tex0, timeCoord0);\n} else {\nvec3 size_0 = unpackCurveData(size_over_time_tex0, timeCoord0);\nvec3 size_1 = unpackCurveData(size_over_time_tex0, timeCoord1);\nfloat factor_s = pseudoRandom(a_rndSeed + 39825.);\nsize *= mix(size_0, size_1, factor_s);\n}\n#endif\nvec3 compScale = scale.xyz * size;\n#if FORCE_OVER_TIME_MODULE_ENABLE\nvec3 forceAnim = vec3(0.);\nif (u_force_mode == 1) {\nforceAnim = unpackCurveData(force_over_time_tex0, timeCoord0);\n} else {\nvec3 force_0 = unpackCurveData(force_over_time_tex0, timeCoord0);\nvec3 force_1 = unpackCurveData(force_over_time_tex0, timeCoord1);\nfloat factor_f = pseudoRandom(a_rndSeed + 212165.);\nforceAnim = mix(force_0, force_1, factor_f);\n}\nvec4 forceTrack = vec4(forceAnim, 0.);\nif (u_force_space == 0) {\nforceTrack = rotateQuat(forceTrack, u_worldRot);\n}\nvelocity.xyz += forceTrack.xyz;\n#endif\n#if VELOCITY_OVER_TIME_MODULE_ENABLE\nfloat speedModifier0 = 1.;\nfloat speedModifier1 = 1.;\nvec3 velocityAnim = vec3(0.);\nif (u_velocity_mode == 1) {\nvelocityAnim = unpackCurveData(velocity_over_time_tex0, timeCoord0, speedModifier0);\n} else {\nvec3 vectory_0 = unpackCurveData(velocity_over_time_tex0, timeCoord0, speedModifier0);\nvec3 vectory_1 = unpackCurveData(velocity_over_time_tex0, timeCoord1, speedModifier1);\nfloat factor_v = pseudoRandom(a_rndSeed + 197866.);\nvelocityAnim = mix(vectory_0, vectory_1, factor_v);\nspeedModifier0 = mix(speedModifier0, speedModifier1, factor_v);\n}\nvec4 velocityTrack = vec4(velocityAnim, 0.);\nif (u_velocity_space == 0) {\nvelocityTrack = rotateQuat(velocityTrack, u_worldRot);\n}\nvelocity.xyz += velocityTrack.xyz;\nvelocity.xyz *= speedModifier0;\n#endif\npos.xyz += velocity.xyz * normalizedTime * a_dir_life.w;\n#if !CC_USE_WORLD_SPACE\npos = cc_matWorld * pos;\n#if CC_RENDER_MODE == 1\nvelocity = rotateQuat(velocity, u_worldRot);\n#endif\n#endif\nvec3 startRotation = a_rotation_uv.xyz;\n#if CC_RENDER_MODE != 4\n#if CC_RENDER_MODE == 0\nvec3 rotEuler = startRotation.xyz;\n#elif CC_RENDER_MODE == 1\nvec3 rotEuler = vec3(0.);\n#else\nvec3 rotEuler = vec3(0., 0., startRotation.z);\n#endif\nvec4 rot = quaternionFromEuler(rotEuler);\n#else\nvec4 rot = quaternionFromEuler(startRotation);\n#endif\n#if ROTATION_OVER_TIME_MODULE_ENABLE\nif (u_rotation_mode == 1) {\nvec3 euler = unpackCurveData(rotation_over_time_tex0, timeCoord0) * normalizedTime * a_dir_life.w;\nvec4 quat = eulerToQuat(euler);\nmat3 mLocal = quatToMat3(quat);\nmat3 mStart = quatToMat3(rot);\nrot = mat3ToQuat(mStart * mLocal);\n} else {\nvec3 rotation_0 = unpackCurveData(rotation_over_time_tex0, timeCoord0);\nvec3 rotation_1 = unpackCurveData(rotation_over_time_tex0, timeCoord1);\nfloat factor_r = pseudoRandom(a_rndSeed + 125292.);\nvec3 euler = mix(rotation_0, rotation_1, factor_r) * normalizedTime * a_dir_life.w;\n#if CC_RENDER_MODE == 3 || CC_RENDER_MODE == 2\neuler = vec3(0.0, 0.0, euler.z);\n#endif\nvec4 quat = eulerToQuat(euler);\nmat3 mLocal = quatToMat3(quat);\nmat3 mStart = quatToMat3(rot);\nrot = mat3ToQuat(mStart * mLocal);\n}\n#endif\n#if COLOR_OVER_TIME_MODULE_ENABLE\nif (u_color_mode == 1) {\ncolor = a_color * texture(color_over_time_tex0, timeCoord0);\n} else {\nvec4 color_0 = texture(color_over_time_tex0, timeCoord0);\nvec4 color_1 = texture(color_over_time_tex0, timeCoord1);\nfloat factor_c = pseudoRandom(a_rndSeed + 91041.);\ncolor = a_color * mix(color_0, color_1, factor_c);\n}\n#else\ncolor = a_color;\n#endif\n#if CC_RENDER_MODE != 4\nvec2 cornerOffset = vec2((vertIdx - 0.5));\n#if CC_RENDER_MODE == 1\nrot = vec4(0.0, 0.0, 0.0, 1.0);\n#endif\ncomputeVertPos(pos, cornerOffset, rot, compScale\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n, cc_matViewInv\n#endif\n#if CC_RENDER_MODE == 1\n, cc_cameraPos.xyz\n, velocity\n, frameTile_velLenScale.z\n, frameTile_velLenScale.w\n, a_size_uv.w\n#endif\n);\n#else\nmat3 rotMat = quatToMat3(rot);\nmat3 nodeMat = quatToMat3(nodeRotation);\nrotMat = nodeMat * rotMat;\nrot = mat3ToQuat(rotMat);\nmat4 xformNoScale = matrixFromRT(rot, pos.xyz);\nmat4 xform = matFromRTS(rot, pos.xyz, compScale);\npos = xform * vec4(a_texCoord3, 1);\nvec4 normal = xformNoScale * vec4(a_normal, 0);\ncolor *= a_color1;\n#endif\npos = cc_matViewProj * pos;\nfloat frameIndex = 0.;\n#if TEXTURE_ANIMATION_MODULE_ENABLE\nfloat startFrame = 0.;\nvec3 frameInfo = vec3(0.);\nif (int(u_anim_info.x) == 1) {\nframeInfo = unpackCurveData(texture_animation_tex0, timeCoord0);\n} else {\nvec3 frameInfo0 = unpackCurveData(texture_animation_tex0, timeCoord0);\nvec3 frameInfo1 = unpackCurveData(texture_animation_tex0, timeCoord1);\nfloat factor_t = pseudoRandom(a_rndSeed + 90794.);\nframeInfo = mix(frameInfo0, frameInfo1, factor_t);\n}\nstartFrame = frameInfo.x / u_anim_info.y;\nframeIndex = repeat(u_anim_info.z * (frameInfo.y + startFrame), 1.);\n#endif\nuv = computeUV(frameIndex, vertIdx, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\nreturn pos;\n}\nvoid main() { gl_Position = gpvs_main(); }", - "frag": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nlayout(location = 0) in vec2 uv;\nlayout(location = 1) in vec4 color;\nlayout(set = 1, binding = 16) uniform sampler2D mainTexture;\nlayout(set = 1, binding = 9) uniform FragConstants {\nvec4 tintColor;\n};\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\nreturn CCFragOutput(col);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nlayout(set = 1, binding = 0) uniform Constants {\nvec4 mainTiling_Offset;\nvec4 frameTile_velLenScale;\nvec4 scale;\nvec4 nodeRotation;\n};\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(set = 2, binding = 0) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(set = 2, binding = 0) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nlayout(location = 0) out mediump vec2 uv;\nlayout(location = 1) out mediump vec4 color;\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_texCoord;\nlayout(location = 2) in vec3 a_texCoord1;\nlayout(location = 3) in vec3 a_texCoord2;\nlayout(location = 4) in vec4 a_color;\n#if CC_DRAW_WIRE_FRAME\nlayout(location = 2) out vec3 vBarycentric;\n#endif\nvec4 vs_main() {\nhighp vec4 pos = vec4(a_position, 1);\nvec4 velocity = vec4(a_texCoord1.xyz, 0);\n#if !CC_USE_WORLD_SPACE\npos = cc_matWorld * pos;\nvelocity = cc_matWorld * velocity;\n#endif\nfloat vertOffset = (a_texCoord.x - 0.5) * a_texCoord.y;\nvec3 camUp = normalize(cross(pos.xyz - cc_cameraPos.xyz, velocity.xyz));\npos.xyz += camUp * vertOffset;\npos = cc_matViewProj * pos;\nuv = a_texCoord.zw * mainTiling_Offset.xy + mainTiling_Offset.zw;;\ncolor = a_color;\n#if CC_DRAW_WIRE_FRAME\nvBarycentric = a_texCoord2;\n#endif\nreturn pos;\n}\nvoid main() { gl_Position = vs_main(); }", - "frag": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nlayout(location = 0) in vec2 uv;\nlayout(location = 1) in vec4 color;\n#if CC_DRAW_WIRE_FRAME\nlayout(location = 2) in vec3 vBarycentric;\n#endif\nlayout(set = 1, binding = 2) uniform sampler2D mainTexture;\nlayout(set = 1, binding = 1) uniform FragConstants {\nvec4 tintColor;\n};\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\n#if CC_DRAW_WIRE_FRAME\nif (any(lessThan(vBarycentric, vec3(0.02)))) {\ncol = vec4(0., 1., 1., 1.);\n}\n#endif\nreturn CCFragOutput(col);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\nvec4 quaternionFromAxis (vec3 xAxis,vec3 yAxis,vec3 zAxis){\nmat3 m = mat3(xAxis,yAxis,zAxis);\nfloat trace = m[0][0] + m[1][1] + m[2][2];\nvec4 quat;\nif (trace > 0.) {\nfloat s = 0.5 / sqrt(trace + 1.0);\nquat.w = 0.25 / s;\nquat.x = (m[2][1] - m[1][2]) * s;\nquat.y = (m[0][2] - m[2][0]) * s;\nquat.z = (m[1][0] - m[0][1]) * s;\n} else if ((m[0][0] > m[1][1]) && (m[0][0] > m[2][2])) {\nfloat s = 2.0 * sqrt(1.0 + m[0][0] - m[1][1] - m[2][2]);\nquat.w = (m[2][1] - m[1][2]) / s;\nquat.x = 0.25 * s;\nquat.y = (m[0][1] + m[1][0]) / s;\nquat.z = (m[0][2] + m[2][0]) / s;\n} else if (m[1][1] > m[2][2]) {\nfloat s = 2.0 * sqrt(1.0 + m[1][1] - m[0][0] - m[2][2]);\nquat.w = (m[0][2] - m[2][0]) / s;\nquat.x = (m[0][1] + m[1][0]) / s;\nquat.y = 0.25 * s;\nquat.z = (m[1][2] + m[2][1]) / s;\n} else {\nfloat s = 2.0 * sqrt(1.0 + m[2][2] - m[0][0] - m[1][1]);\nquat.w = (m[1][0] - m[0][1]) / s;\nquat.x = (m[0][2] + m[2][0]) / s;\nquat.y = (m[1][2] + m[2][1]) / s;\nquat.z = 0.25 * s;\n}\nfloat len = quat.x * quat.x + quat.y * quat.y + quat.z * quat.z + quat.w * quat.w;\nif (len > 0.) {\nlen = 1. / sqrt(len);\nquat.x = quat.x * len;\nquat.y = quat.y * len;\nquat.z = quat.z * len;\nquat.w = quat.w * len;\n}\nreturn quat;\n}\nvec4 quaternionFromEuler (vec3 angle){\nfloat x = angle.x / 2.;\nfloat y = angle.y / 2.;\nfloat z = angle.z / 2.;\nfloat sx = sin(x);\nfloat cx = cos(x);\nfloat sy = sin(y);\nfloat cy = cos(y);\nfloat sz = sin(z);\nfloat cz = cos(z);\nvec4 quat = vec4(0);\nquat.x = sx * cy * cz + cx * sy * sz;\nquat.y = cx * sy * cz + sx * cy * sz;\nquat.z = cx * cy * sz - sx * sy * cz;\nquat.w = cx * cy * cz - sx * sy * sz;\nreturn quat;\n}\nmat4 matrixFromRT (vec4 q, vec3 p){\nfloat x2 = q.x + q.x;\nfloat y2 = q.y + q.y;\nfloat z2 = q.z + q.z;\nfloat xx = q.x * x2;\nfloat xy = q.x * y2;\nfloat xz = q.x * z2;\nfloat yy = q.y * y2;\nfloat yz = q.y * z2;\nfloat zz = q.z * z2;\nfloat wx = q.w * x2;\nfloat wy = q.w * y2;\nfloat wz = q.w * z2;\nreturn mat4(\n1. - (yy + zz), xy + wz, xz - wy, 0,\nxy - wz, 1. - (xx + zz), yz + wx, 0,\nxz + wy, yz - wx, 1. - (xx + yy), 0,\np.x, p.y, p.z, 1\n);\n}\nmat4 matFromRTS (vec4 q, vec3 t, vec3 s){\nfloat x = q.x, y = q.y, z = q.z, w = q.w;\nfloat x2 = x + x;\nfloat y2 = y + y;\nfloat z2 = z + z;\nfloat xx = x * x2;\nfloat xy = x * y2;\nfloat xz = x * z2;\nfloat yy = y * y2;\nfloat yz = y * z2;\nfloat zz = z * z2;\nfloat wx = w * x2;\nfloat wy = w * y2;\nfloat wz = w * z2;\nfloat sx = s.x;\nfloat sy = s.y;\nfloat sz = s.z;\nreturn mat4((1. - (yy + zz)) * sx, (xy + wz) * sx, (xz - wy) * sx, 0,\n(xy - wz) * sy, (1. - (xx + zz)) * sy, (yz + wx) * sy, 0,\n(xz + wy) * sz, (yz - wx) * sz, (1. - (xx + yy)) * sz, 0,\nt.x, t.y, t.z, 1);\n}\nvec4 quatMultiply (vec4 a, vec4 b){\nvec4 quat;\nquat.x = a.x * b.w + a.w * b.x + a.y * b.z - a.z * b.y;\nquat.y = a.y * b.w + a.w * b.y + a.z * b.x - a.x * b.z;\nquat.z = a.z * b.w + a.w * b.z + a.x * b.y - a.y * b.x;\nquat.w = a.w * b.w - a.x * b.x - a.y * b.y - a.z * b.z;\nreturn quat;\n}\nvoid rotateVecFromQuat (inout vec3 v, vec4 q){\nfloat ix = q.w * v.x + q.y * v.z - q.z * v.y;\nfloat iy = q.w * v.y + q.z * v.x - q.x * v.z;\nfloat iz = q.w * v.z + q.x * v.y - q.y * v.x;\nfloat iw = -q.x * v.x - q.y * v.y - q.z * v.z;\nv.x = ix * q.w + iw * -q.x + iy * -q.z - iz * -q.y;\nv.y = iy * q.w + iw * -q.y + iz * -q.x - ix * -q.z;\nv.z = iz * q.w + iw * -q.z + ix * -q.y - iy * -q.x;\n}\nvec3 rotateInLocalSpace (vec3 pos, vec3 xAxis, vec3 yAxis, vec3 zAxis, vec4 q){\nvec4 viewQuat = quaternionFromAxis(xAxis, yAxis, zAxis);\nvec4 rotQuat = quatMultiply(viewQuat, q);\nrotateVecFromQuat(pos, rotQuat);\nreturn pos;\n}\nmat3 quatToMat3(vec4 q) {\nvec3 m0 = vec3(\n1.0 - 2.0 * q.y * q.y - 2.0 * q.z * q.z,\n2.0 * q.x * q.y + 2.0 * q.w * q.z,\n2.0 * q.x * q.z - 2.0 * q.w * q.y);\nvec3 m1 = vec3(\n2.0 * q.x * q.y - 2.0 * q.w * q.z,\n1.0 - 2.0 * q.x * q.x - 2.0 * q.z * q.z,\n2.0 * q.y * q.z + 2.0 * q.w * q.x);\nvec3 m2 = vec3(\n2.0 * q.x * q.z + 2.0 * q.w * q.y,\n2.0 * q.y * q.z - 2.0 * q.w * q.x,\n1.0 - 2.0 * q.x * q.x - 2.0 * q.y * q.y);\nreturn mat3(m0, m1, m2);\n}\nvec4 mat3ToQuat(mat3 mat) {\nfloat tr = mat[0][0] + mat[1][1] + mat[2][2];\nfloat qw, qx, qy, qz;\nif (tr > 0.0) {\nfloat S = sqrt(tr + 1.0) * 2.0;\nfloat invS = 1.0 / S;\nqw = 0.25 * S;\nqx = (mat[1][2] - mat[2][1]) * invS;\nqy = (mat[2][0] - mat[0][2]) * invS;\nqz = (mat[0][1] - mat[1][0]) * invS;\n} else if ((mat[0][0] > mat[1][1])&&(mat[0][0] > mat[2][2])) {\nfloat S = sqrt(1.0 + mat[0][0] - mat[1][1] - mat[2][2]) * 2.0;\nfloat invS = 1.0 / S;\nqw = (mat[1][2] - mat[2][1]) * invS;\nqx = 0.25 * S;\nqy = (mat[1][0] + mat[0][1]) * invS;\nqz = (mat[2][0] + mat[0][2]) * invS;\n} else if (mat[1][1] > mat[2][2]) {\nfloat S = sqrt(1.0 + mat[1][1] - mat[0][0] - mat[2][2]) * 2.0;\nfloat invS = 1.0 / S;\nqw = (mat[2][0] - mat[0][2]) * invS;\nqx = (mat[1][0] + mat[0][1]) * invS;\nqy = 0.25 * S;\nqz = (mat[2][1] + mat[1][2]) * invS;\n} else {\nfloat S = sqrt(1.0 + mat[2][2] - mat[0][0] - mat[1][1]) * 2.0;\nfloat invS = 1.0 / S;\nqw = (mat[0][1] - mat[1][0]) * invS;\nqx = (mat[2][0] + mat[0][2]) * invS;\nqy = (mat[2][1] + mat[1][2]) * invS;\nqz = 0.25 * S;\n}\nreturn vec4(qx, qy, qz, qw);\n}\nlayout(set = 1, binding = 0) uniform Constants {\nvec4 mainTiling_Offset;\nvec4 frameTile_velLenScale;\nvec4 scale;\nvec4 nodeRotation;\n};\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(set = 2, binding = 0) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(set = 2, binding = 0) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nlayout(location = 0) out mediump vec2 uv;\nlayout(location = 1) out mediump vec4 color;\nvoid computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\n, mat4 viewInv\n#endif\n#if CC_RENDER_MODE == 1\n, vec3 eye\n, vec4 velocity\n, float velocityScale\n, float lengthScale\n, float xIndex\n#endif\n) {\n#if CC_RENDER_MODE == 0\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = normalize(vec3(viewInv[0][0], viewInv[1][0], viewInv[2][0]));\nvec3 camY = normalize(vec3(viewInv[0][1], viewInv[1][1], viewInv[2][1]));\nvec3 camZ = normalize(vec3(viewInv[0][2], viewInv[1][2], viewInv[2][2]));\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, camZ, q);\n#elif CC_RENDER_MODE == 1\nvec3 camRight = normalize(cross(pos.xyz - eye, velocity.xyz)) * s.x;\nvec3 camUp = velocity.xyz * velocityScale + normalize(velocity.xyz) * lengthScale * s.y;\npos.xyz += (camRight * abs(vertOffset.x) * sign(vertOffset.y)) - camUp * xIndex;\n#elif CC_RENDER_MODE == 2\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nvec3 camX = vec3(1, 0, 0);\nvec3 camY = vec3(0, 0, -1);\npos.xyz += rotateInLocalSpace(viewSpaceVert, camX, camY, cross(camX, camY), q);\n#elif CC_RENDER_MODE == 3\nvec3 viewSpaceVert = vec3(vertOffset.x * s.x, vertOffset.y * s.y, 0.);\nrotateVecFromQuat(viewSpaceVert, q);\nvec3 camX = normalize(vec3(cc_matView[0][0], cc_matView[1][0], cc_matView[2][0]));\nvec3 camY = vec3(0, 1, 0);\nvec3 offset = camX * viewSpaceVert.x + camY * viewSpaceVert.y;\npos.xyz += offset;\n#else\npos.x += vertOffset.x;\npos.y += vertOffset.y;\n#endif\n}\nvec2 computeUV (float frameIndex, vec2 vertIndex, vec2 frameTile){\nvec2 aniUV = vec2(0, floor(frameIndex * frameTile.y));\naniUV.x = floor(frameIndex * frameTile.x * frameTile.y - aniUV.y * frameTile.x);\n#if CC_RENDER_MODE != 4\nvertIndex.y = 1. - vertIndex.y;\n#endif\nreturn (aniUV.xy + vertIndex) / vec2(frameTile.x, frameTile.y);\n}\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_texCoord;\nlayout(location = 2) in vec3 a_texCoord1;\nlayout(location = 3) in vec3 a_texCoord2;\nlayout(location = 4) in vec4 a_color;\n#if CC_RENDER_MODE == 1\nlayout(location = 8) in vec3 a_color1;\n#endif\n#if CC_RENDER_MODE == 4\nlayout(location = 6) in vec3 a_texCoord3;\nlayout(location = 7) in vec3 a_normal;\nlayout(location = 8) in vec4 a_color1;\n#endif\nvec4 lpvs_main () {\nvec3 compScale = scale.xyz * a_texCoord1;\nvec4 pos = vec4(a_position, 1);\n#if CC_RENDER_MODE == 1\nvec4 velocity = vec4(a_color1.xyz, 0);\n#endif\n#if !CC_USE_WORLD_SPACE\npos = cc_matWorld * pos;\n#if CC_RENDER_MODE == 1\nvelocity = cc_matWorld * velocity;\n#endif\n#endif\n#if ROTATION_OVER_TIME_MODULE_ENABLE\nvec3 rotTmp = a_texCoord2;\nfloat mulFactor = 1.0;\nif (rotTmp.x > 10.0 * 0.5) {\nrotTmp.x -= 10.0;\nmulFactor = -1.0;\n}\nvec4 rot = vec4(rotTmp, 0.0);\nrot.w = mulFactor * sqrt(abs(1.0 - rot.x * rot.x - rot.y * rot.y - rot.z * rot.z));\n#else\n#if CC_RENDER_MODE != 4\n#if CC_RENDER_MODE == 0\nvec3 rotEuler = a_texCoord2;\n#elif CC_RENDER_MODE == 1\nvec3 rotEuler = vec3(0.);\n#else\nvec3 rotEuler = vec3(0., 0., a_texCoord2.z);\n#endif\nvec4 rot = quaternionFromEuler(rotEuler);\n#else\nvec4 rot = quaternionFromEuler(a_texCoord2);\n#endif\n#endif\n#if CC_RENDER_MODE != 4\nvec2 cornerOffset = vec2((a_texCoord.xy - 0.5));\n#if CC_RENDER_MODE == 0 || CC_RENDER_MODE == 3\ncomputeVertPos(pos, cornerOffset, rot, compScale, cc_matViewInv);\n#elif CC_RENDER_MODE == 1\ncomputeVertPos(pos, cornerOffset, rot, compScale, cc_cameraPos.xyz, velocity, frameTile_velLenScale.z, frameTile_velLenScale.w, a_texCoord.x);\n#elif 2\ncomputeVertPos(pos, cornerOffset, rot, compScale);\n#endif\ncolor = a_color;\n#else\nmat3 rotMat = quatToMat3(rot);\nmat3 nodeMat = quatToMat3(nodeRotation);\nrotMat = nodeMat * rotMat;\nrot = mat3ToQuat(rotMat);\nmat4 xformNoScale = matrixFromRT(rot, pos.xyz);\nmat4 xform = matFromRTS(rot, pos.xyz, compScale);\npos = xform * vec4(a_texCoord3, 1);\nvec4 normal = xformNoScale * vec4(a_normal, 0);\ncolor = a_color * a_color1;\n#endif\nuv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;\npos = cc_matViewProj * pos;\nreturn pos;\n}\nvoid main() { gl_Position = lpvs_main(); }", - "frag": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nlayout(location = 0) in vec2 uv;\nlayout(location = 1) in vec4 color;\nlayout(set = 1, binding = 2) uniform sampler2D mainTexture;\nlayout(set = 1, binding = 1) uniform FragConstants {\nvec4 tintColor;\n};\nvec4 add () {\nvec4 col = 2.0 * color * tintColor * texture(mainTexture, uv);\nreturn CCFragOutput(col);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = add(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_LOCAL\n#if USE_BATCHING\nlayout(set = 2, binding = 0) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(set = 2, binding = 0) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\n#endif\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec2 a_texCoord;\nlayout(location = 2) in vec4 a_color;\nlayout(location = 0) out vec4 v_light;\nlayout(location = 1) out vec2 uv0;\n#if TWO_COLORED\nlayout(location = 3) in vec4 a_color2;\nlayout(location = 2) out vec4 v_dark;\n#endif\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\n#if USE_LOCAL\npos = cc_matWorld * pos;\n#endif\npos = cc_matViewProj * pos;\nuv0 = a_texCoord;\nv_light = a_color;\n#if TWO_COLORED\nv_dark = a_color2;\n#endif\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\n#if USE_ALPHA_TEST\nlayout(set = 1, binding = 0) uniform ALPHA_TEST_DATA {\nfloat alphaThreshold;\n};\n#endif\nvoid ALPHA_TEST (in vec4 color) {\n#if USE_ALPHA_TEST\nif (color.a < alphaThreshold) discard;\n#endif\n}\nvoid ALPHA_TEST (in float alpha) {\n#if USE_ALPHA_TEST\nif (alpha < alphaThreshold) discard;\n#endif\n}\nlayout(location = 0) in vec4 v_light;\n#if TWO_COLORED\nlayout(location = 2) in vec4 v_dark;\n#endif\nlayout(location = 1) in vec2 uv0;\nlayout(set = 2, binding = 11) uniform sampler2D cc_spriteTexture;\nvec4 frag () {\nvec4 o = vec4(1, 1, 1, 1);\n#if TWO_COLORED\nvec4 texColor = vec4(1, 1, 1, 1);\ntexColor *= texture(cc_spriteTexture, uv0);\no.a = texColor.a * v_light.a;\no.rgb = ((texColor.a - 1.0) * v_dark.a + 1.0 - texColor.rgb) * v_dark.rgb + texColor.rgb * v_light.rgb;\n#else\no *= texture(cc_spriteTexture, uv0);\no *= v_light;\n#endif\nALPHA_TEST(o);\nreturn o;\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision highp float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_LOCAL\n#if USE_BATCHING\nlayout(set = 2, binding = 0) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(set = 2, binding = 0) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\n#endif\n#if SAMPLE_FROM_RT\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\n#endif\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec2 a_texCoord;\nlayout(location = 2) in vec4 a_color;\nlayout(location = 0) out vec4 color;\nlayout(location = 1) out vec2 uv0;\nvec4 vert () {\nvec4 pos = vec4(a_position, 1);\n#if USE_LOCAL\npos = cc_matWorld * pos;\n#endif\n#if USE_PIXEL_ALIGNMENT\npos = cc_matView * pos;\npos.xyz = floor(pos.xyz);\npos = cc_matProj * pos;\n#else\npos = cc_matViewProj * pos;\n#endif\nuv0 = a_texCoord;\n#if SAMPLE_FROM_RT\nuv0 = cc_cameraPos.w > 1.0 ? vec2(uv0.x, 1.0 - uv0.y) : uv0;\n#endif\ncolor = a_color;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\nvec4 CCSampleWithAlphaSeparated(sampler2D tex, vec2 uv) {\n#if CC_USE_EMBEDDED_ALPHA\nreturn vec4(texture(tex, uv).rgb, texture(tex, uv + vec2(0.0, 0.5)).r);\n#else\nreturn texture(tex, uv);\n#endif\n}\n#if USE_ALPHA_TEST\nlayout(set = 1, binding = 0) uniform ALPHA_TEST_DATA {\nfloat alphaThreshold;\n};\n#endif\nvoid ALPHA_TEST (in vec4 color) {\n#if USE_ALPHA_TEST\nif (color.a < alphaThreshold) discard;\n#endif\n}\nvoid ALPHA_TEST (in float alpha) {\n#if USE_ALPHA_TEST\nif (alpha < alphaThreshold) discard;\n#endif\n}\nlayout(location = 0) in vec4 color;\n#if USE_TEXTURE\nlayout(location = 1) in vec2 uv0;\nlayout(set = 2, binding = 11) uniform sampler2D cc_spriteTexture;\n#endif\nvec4 frag () {\nvec4 o = vec4(1, 1, 1, 1);\n#if USE_TEXTURE\no *= CCSampleWithAlphaSeparated(cc_spriteTexture, uv0);\n#if IS_GRAY\nfloat gray = 0.2126 * o.r + 0.7152 * o.g + 0.0722 * o.b;\no.r = o.g = o.b = gray;\n#endif\n#endif\no *= color;\nALPHA_TEST(o);\nreturn o;\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "#extension GL_EXT_shader_explicit_arithmetic_types_int32: require\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\nlayout(location = 3) in vec4 a_tangent;\n#if USE_INSTANCING\nlayout(location = 6) in vec4 a_matWorld0;\nlayout(location = 7) in vec4 a_matWorld1;\nlayout(location = 8) in vec4 a_matWorld2;\n#if USE_LIGHTMAP\nlayout(location = 9) in vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nlayout(location = 10) in vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nlayout(location = 11) in float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nint getVertexId() {\nreturn gl_VertexIndex;\n}\n#endif\n#if CC_USE_SKINNING\nlayout(location = 4) in u32vec4 a_joints;\nlayout(location = 5) in vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nlayout(set = 2, binding = 4) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nlayout(set = 2, binding = 7) uniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nlayout(set = 2, binding = 8) uniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nlayout(set = 2, binding = 9) uniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nlayout(location = 13) in highp vec4 a_jointAnimInfo;\n#endif\nlayout(set = 2, binding = 3) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(set = 2, binding = 2) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nlayout(set = 2, binding = 6) uniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nlayout(set = 2, binding = 3) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(set = 2, binding = 0) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(set = 2, binding = 0) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nvoid CCGetWorldMatrixFull(out mat4 matWorld, out mat4 matWorldIT)\n{\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\nmatWorldIT = matWorld;\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\nmatWorldIT = matWorld;\n#else\nmatWorld = cc_matWorld;\nmatWorldIT = cc_matWorldIT;\n#endif\n}\nlayout(set = 1, binding = 0) uniform Constants {\nvec4 tilingOffset;\nvec4 albedo;\nvec4 albedoScaleAndCutoff;\nvec4 pbrParams;\nvec4 emissive;\nvec4 emissiveScaleParam;\n};\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\n#if !CC_USE_ACCURATE_FOG\nlayout(location = 0) out float v_fog_factor;\n#endif\nvoid CC_TRANSFER_FOG(vec4 pos) {\n#if !CC_USE_ACCURATE_FOG\nCC_TRANSFER_FOG_BASE(pos, v_fog_factor);\n#endif\n}\nlayout(location = 1) out highp vec4 v_shadowPos;\nlayout(set = 0, binding = 2) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\n#if CC_RECEIVE_SHADOW\nlayout(set = 0, binding = 3) uniform highp sampler2D cc_shadowMap;\nlayout(set = 0, binding = 5) uniform highp sampler2D cc_spotLightingMap;\n#endif\n#if CC_RECEIVE_SHADOW\nvec2 CCGetShadowBias()\n{\n#if USE_INSTANCING\nreturn vec2(a_localShadowBias.x + cc_shadowWHPBInfo.w, a_localShadowBias.y + cc_shadowLPNNInfo.z);\n#else\nreturn vec2(cc_localShadowBias.x + cc_shadowWHPBInfo.w, cc_localShadowBias.y + cc_shadowLPNNInfo.z);\n#endif\n}\n#endif\n#if USE_VERTEX_COLOR\nlayout(location = 14) in vec4 a_color;\nlayout(location = 2) out vec4 v_color;\n#endif\nlayout(location = 3) out vec3 v_position;\nlayout(location = 4) out vec3 v_normal;\nlayout(location = 5) out vec2 v_uv;\nlayout(location = 6) out vec2 v_uv1;\n#if CC_RECEIVE_SHADOW\nlayout(location = 7) out vec2 v_shadowBias;\n#endif\n#if USE_NORMAL_MAP\nlayout(location = 8) out vec3 v_tangent;\nlayout(location = 9) out vec3 v_bitangent;\n#endif\n#if HAS_SECOND_UV || USE_LIGHTMAP\nlayout(location = 15) in vec2 a_texCoord1;\n#endif\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nlayout(location = 10) out vec3 v_luv;\nvoid CCLightingMapCaclUV()\n{\n#if !USE_INSTANCING\nv_luv.xy = cc_lightingMapUVParam.xy + a_texCoord1 * cc_lightingMapUVParam.zw;\nv_luv.z = cc_lightingMapUVParam.z;\n#else\nv_luv.xy = a_lightingMapUVParam.xy + a_texCoord1 * a_lightingMapUVParam.zw;\nv_luv.z = a_lightingMapUVParam.z;\n#endif\n}\n#endif\nvoid main () {\nStandardVertInput In;\nCCVertInput(In);\nmat4 matWorld, matWorldIT;\nCCGetWorldMatrixFull(matWorld, matWorldIT);\nvec4 pos = matWorld * In.position;\nv_position = pos.xyz;\nv_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz);\n#if CC_RECEIVE_SHADOW\nv_shadowBias = CCGetShadowBias();\n#endif\n#if USE_TWOSIDE\nvec3 viewDirect = normalize(cc_cameraPos.xyz - v_position);\nv_normal *= dot(v_normal, viewDirect) < 0.0 ? -1.0 : 1.0;\n#endif\n#if USE_NORMAL_MAP\nv_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz);\nv_bitangent = cross(v_normal, v_tangent) * In.tangent.w;\n#endif\nv_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n#if SAMPLE_FROM_RT\nv_uv = cc_cameraPos.w > 1.0 ? vec2(v_uv.x, 1.0 - v_uv.y) : v_uv;\n#endif\n#if HAS_SECOND_UV\nv_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n#if SAMPLE_FROM_RT\nv_uv1 = cc_cameraPos.w > 1.0 ? vec2(v_uv1.x, 1.0 - v_uv1.y) : v_uv1;\n#endif\n#endif\n#if USE_VERTEX_COLOR\nv_color = a_color;\n#endif\nCC_TRANSFER_FOG(pos);\nv_shadowPos = cc_matLightViewProj * pos;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nCCLightingMapCaclUV();\n#endif\ngl_Position = cc_matProj * (cc_matView * matWorld) * In.position;\n}", - "frag": "\nprecision highp float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(set = 1, binding = 0) uniform Constants {\nvec4 tilingOffset;\nvec4 albedo;\nvec4 albedoScaleAndCutoff;\nvec4 pbrParams;\nvec4 emissive;\nvec4 emissiveScaleParam;\n};\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\nvoid CC_APPLY_FOG_BASE(inout vec4 color, float factor) {\ncolor = vec4(mix(cc_fogColor.rgb, color.rgb, factor), color.a);\n}\n#if !CC_USE_ACCURATE_FOG\nlayout(location = 0) in float v_fog_factor;\n#endif\nvoid CC_APPLY_FOG(inout vec4 color) {\n#if !CC_USE_ACCURATE_FOG\nCC_APPLY_FOG_BASE(color, v_fog_factor);\n#endif\n}\nvoid CC_APPLY_FOG(inout vec4 color, vec3 worldPos) {\n#if CC_USE_ACCURATE_FOG\nfloat factor;\nCC_TRANSFER_FOG_BASE(vec4(worldPos, 1.0), factor);\n#else\nfloat factor = v_fog_factor;\n#endif\nCC_APPLY_FOG_BASE(color, factor);\n}\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nlayout(set = 0, binding = 2) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\nhighp float unpackHighpData (float mainPart, float modPart) {\nhighp float data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out float mainPart, out float modPart, highp float data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp float unpackHighpData (float mainPart, float modPart, const float modValue) {\nhighp float data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out float mainPart, out float modPart, highp float data, const float modValue) {\nhighp float divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\nhighp vec2 unpackHighpData (vec2 mainPart, vec2 modPart) {\nhighp vec2 data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out vec2 mainPart, out vec2 modPart, highp vec2 data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp vec2 unpackHighpData (vec2 mainPart, vec2 modPart, const float modValue) {\nhighp vec2 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out vec2 mainPart, out vec2 modPart, highp vec2 data, const float modValue) {\nhighp vec2 divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\nhighp vec3 unpackHighpData (vec3 mainPart, vec3 modPart) {\nhighp vec3 data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out vec3 mainPart, out vec3 modPart, highp vec3 data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp vec3 unpackHighpData (vec3 mainPart, vec3 modPart, const float modValue) {\nhighp vec3 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out vec3 mainPart, out vec3 modPart, highp vec3 data, const float modValue) {\nhighp vec3 divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\nhighp vec4 unpackHighpData (vec4 mainPart, vec4 modPart) {\nhighp vec4 data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out vec4 mainPart, out vec4 modPart, highp vec4 data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp vec4 unpackHighpData (vec4 mainPart, vec4 modPart, const float modValue) {\nhighp vec4 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out vec4 mainPart, out vec4 modPart, highp vec4 data, const float modValue) {\nhighp vec4 divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\n#if USE_BATCHING\nlayout(set = 2, binding = 0) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(set = 2, binding = 0) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nfloat CCGetLinearDepthFromViewSpace(vec3 viewPos) {\nfloat dist = length(viewPos);\nreturn (dist - cc_shadowNFLSInfo.x) / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x);\n}\nfloat CCGetLinearDepth(vec3 worldPos) {\nvec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0);\nreturn CCGetLinearDepthFromViewSpace(viewStartPos.xyz);\n}\n#if CC_RECEIVE_SHADOW\nlayout(set = 0, binding = 3) uniform highp sampler2D cc_shadowMap;\nlayout(set = 0, binding = 5) uniform highp sampler2D cc_spotLightingMap;\nvec4 ApplyShadowDepthBias_FaceNormal(vec4 shadowPos, vec3 worldNormal, float normalBias)\n{\nvec4 newShadowPos = shadowPos;\nif(normalBias > 0.0001)\n{\nvec4 viewNormal = cc_matLightView * vec4(worldNormal, 0.0);\nif(viewNormal.z < 0.1)\nnewShadowPos.xy += viewNormal.xy * cc_shadowProjInfo.xy * normalBias * clamp(viewNormal.z, 0.001, 0.1);\n}\nreturn newShadowPos;\n}\nvec4 ApplyShadowDepthBias_Perspective(vec4 shadowPos, float viewspaceDepthBias)\n{\nvec3 viewSpacePos;\nviewSpacePos.xy = shadowPos.xy * cc_shadowProjInfo.zw;\nviewSpacePos.z = shadowPos.z * cc_shadowInvProjDepthInfo.x + shadowPos.w * cc_shadowInvProjDepthInfo.y;\nviewSpacePos.xyz += cc_shadowProjDepthInfo.z * normalize(viewSpacePos.xyz) * viewspaceDepthBias;\nvec4 clipSpacePos;\nclipSpacePos.xy = viewSpacePos.xy * cc_shadowProjInfo.xy;\nclipSpacePos.zw = viewSpacePos.z * cc_shadowProjDepthInfo.xz + vec2(cc_shadowProjDepthInfo.y, 0.0);\nif (cc_shadowNFLSInfo.z > 0.000001) {\nclipSpacePos.z = CCGetLinearDepthFromViewSpace(viewSpacePos.xyz);\nclipSpacePos.z = (clipSpacePos.z * 2.0 - 1.0) * clipSpacePos.w;\n}\nreturn clipSpacePos;\n}\nvec4 ApplyShadowDepthBias_Orthographic(vec4 shadowPos, float viewspaceDepthBias)\n{\nfloat coeffA = cc_shadowProjDepthInfo.x;\nfloat coeffB = cc_shadowProjDepthInfo.y;\nfloat viewSpacePos_z = (shadowPos.z - coeffB) / coeffA;\nviewSpacePos_z += viewspaceDepthBias;\nvec4 result = shadowPos;\nresult.z = viewSpacePos_z * coeffA + coeffB;\nreturn result;\n}\nfloat CCGetShadowFactorHard (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture(cc_shadowMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n} else {\nclosestDepth = texture(cc_shadowMap, clipPos.xy).x;\n}\nshadow = step(clipPos.z, closestDepth);\nreturn shadow;\n}\nfloat CCGetShadowFactorSoft (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x);\nblock1 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)).x);\nblock2 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)).x);\nblock3 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetShadowFactorSoft2X (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock4 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock5 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock6 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock7 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock8 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)).x);\nblock1 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)).x);\nblock2 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)).x);\nblock3 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)).x);\nblock4 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x);\nblock5 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)).x);\nblock6 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)).x);\nblock7 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)).x);\nblock8 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCGetSpotLightShadowFactorHard (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nfloat depth = clipPos.z;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture(cc_spotLightingMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n} else {\nclosestDepth = texture(cc_spotLightingMap, clipPos.xy).x;\n}\nshadow = step(depth, closestDepth);\nreturn shadow;\n}\nfloat CCGetSpotLightShadowFactorSoft (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nvec2 oneTap = 1.0 / cc_shadowWHPBInfo.xy;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x);\nblock1 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)).x);\nblock2 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)).x);\nblock3 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * cc_shadowWHPBInfo.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY = mod(clipPos.y, oneTap.y) * cc_shadowWHPBInfo.y;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetSpotLightShadowFactorSoft2X (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock4 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock5 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock6 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock7 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock8 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)).x);\nblock1 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)).x);\nblock2 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)).x);\nblock3 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)).x);\nblock4 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x);\nblock5 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)).x);\nblock6 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)).x);\nblock7 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)).x);\nblock8 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCSpotShadowFactorBase(vec4 shadowPos, vec3 worldPos, vec2 shadowBias)\n{\nfloat pcf = cc_shadowWHPBInfo.z;\nif (pcf > 1.9) {\nreturn CCGetSpotLightShadowFactorSoft2X(shadowPos, worldPos, shadowBias.x);\n}else if (pcf > 0.9) {\nreturn CCGetSpotLightShadowFactorSoft(shadowPos, worldPos, shadowBias.x);\n}else {\nreturn CCGetSpotLightShadowFactorHard(shadowPos, worldPos, shadowBias.x);\n}\n}\nfloat CCShadowFactorBase(vec4 shadowPos, vec3 N, vec2 shadowBias)\n{\nfloat realtimeShadow = 1.0;\nvec4 pos = ApplyShadowDepthBias_FaceNormal(shadowPos, N, shadowBias.y);\nfloat pcf = cc_shadowWHPBInfo.z;\nif (pcf > 1.9) {\nrealtimeShadow = CCGetShadowFactorSoft2X(pos, shadowBias.x);\n}else if (pcf > 0.9) {\nrealtimeShadow = CCGetShadowFactorSoft(pos, shadowBias.x);\n}else {\nrealtimeShadow = CCGetShadowFactorHard(pos, shadowBias.x);\n}\nreturn mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w);\n}\n#endif\n#if CC_USE_IBL\nlayout(set = 0, binding = 4) uniform samplerCube cc_environment;\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\nreturn textureLod(tex, coord, lod);\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\nreturn textureLod(tex, coord, lod);\n}\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(1.1, rgbe.a * 255.0 - 128.0);\n}\n#if CC_USE_DIFFUSEMAP\nlayout(set = 0, binding = 6) uniform samplerCube cc_diffuseMap;\n#endif\n#endif\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\nvec3 NxH = cross(N, H);\nfloat OneMinusNoHSqr = dot(NxH, NxH);\nfloat a = roughness * roughness;\nfloat n = NoH * a;\nfloat p = a / (OneMinusNoHSqr + n * n);\nreturn p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\nreturn (roughness * 0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\nconst vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\nconst vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\nvec4 r = roughness * c0 + c1;\nfloat a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;\nvec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;\nAB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\nreturn specular * AB.x + AB.y;\n}\n#if USE_REFLECTION_DENOISE\nvec3 GetEnvReflectionWithMipFiltering(vec3 R, float roughness, float mipCount, float denoiseIntensity) {\n#if CC_USE_IBL\nfloat mip = roughness * mipCount;\nfloat delta = (dot(dFdx(R), dFdy(R))) * 1000.0;\nfloat mipBias = mix(0.0, 5.0, clamp(delta, 0.0, 1.0));\nvec4 biased = fragTextureLod(cc_environment, R, mip + mipBias);\nvec4 filtered = texture(cc_environment, R);\n#if CC_USE_IBL == 2\nbiased.rgb = unpackRGBE(biased);\nfiltered.rgb = unpackRGBE(filtered);\n#else\nbiased.rgb = SRGBToLinear(biased.rgb);\nfiltered.rgb = SRGBToLinear(filtered.rgb);\n#endif\nreturn mix(biased.rgb, filtered.rgb, denoiseIntensity);\n#else\nreturn vec3(0.0, 0.0, 0.0);\n#endif\n}\n#endif\nstruct StandardSurface {\nvec4 albedo;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nvec3 position, position_fract_part;\n#else\nvec3 position;\n#endif\nvec3 normal;\nvec3 emissive;\nvec3 lightmap;\nfloat lightmap_test;\nfloat roughness;\nfloat metallic;\nfloat occlusion;\n#if CC_RECEIVE_SHADOW\nvec2 shadowBias;\n#endif\n};\nvec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.0);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 L = normalize(-cc_mainLitDir.xyz);\nvec3 H = normalize(L + V);\nfloat NH = max(dot(N, H), 0.0);\nfloat NL = max(dot(N, L), 0.0);\nvec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w;\nvec3 diffuseContrib = diffuse;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nif (s.lightmap_test > 0.0001) {\nfinalColor = s.lightmap.rgb;\n}\n#else\ndiffuseContrib /= PI;\n#endif\nvec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\nvec3 dirlightContrib = (diffuseContrib + specularContrib);\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (NL > 0.0 && cc_mainLitDir.w > 0.0) {\nshadow = CCShadowFactorBase(shadowPos, N, s.shadowBias);\n}\n#endif\ndirlightContrib *= shadow;\nfinalColor *= dirlightContrib;\nfloat fAmb = 0.5 - N.y * 0.5;\nvec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb);\n#if CC_USE_IBL\n#if CC_USE_DIFFUSEMAP\nvec4 diffuseMap = texture(cc_diffuseMap, N);\n#if CC_USE_DIFFUSEMAP == 2\nambDiff = unpackRGBE(diffuseMap);\n#else\nambDiff = SRGBToLinear(diffuseMap.rgb);\n#endif\n#endif\nvec3 R = normalize(reflect(-V, N));\n#if USE_REFLECTION_DENOISE\nvec3 env = GetEnvReflectionWithMipFiltering(R, s.roughness, cc_ambientGround.w, 0.6);\n#else\nvec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n#if CC_USE_IBL == 2\nvec3 env = unpackRGBE(envmap);\n#else\nvec3 env = SRGBToLinear(envmap.rgb);\n#endif\n#endif\nfinalColor += env * cc_ambientSky.w * specular * s.occlusion;\n#endif\nfinalColor += ambDiff.rgb * cc_ambientSky.w * diffuse * s.occlusion;\nfinalColor += s.emissive;\nreturn vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = ACESToneMap(color.rgb);\n#endif\ncolor.rgb = sqrt(color.rgb);\nreturn color;\n}\nlayout(location = 1) in highp vec4 v_shadowPos;\n#if CC_RECEIVE_SHADOW\n#endif\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nlayout(location = 10) in vec3 v_luv;\nlayout(set = 2, binding = 10) uniform sampler2D cc_lightingMap;\nvec3 UnpackLightingmap(vec4 color) {\nvec3 c;\nfloat e = 1.0 + color.a * (8.0 - 1.0);\nc.r = color.r * e;\nc.g = color.g * e;\nc.b = color.b * e;\nreturn c;\n}\n#endif\nlayout(location = 3) in vec3 v_position;\nlayout(location = 5) in vec2 v_uv;\nlayout(location = 6) in vec2 v_uv1;\nlayout(location = 4) in vec3 v_normal;\n#if CC_RECEIVE_SHADOW\nlayout(location = 7) in vec2 v_shadowBias;\n#endif\n#if USE_VERTEX_COLOR\nlayout(location = 2) in vec4 v_color;\n#endif\n#if USE_ALBEDO_MAP\nlayout(set = 1, binding = 1) uniform sampler2D albedoMap;\n#endif\n#if USE_NORMAL_MAP\nlayout(location = 8) in vec3 v_tangent;\nlayout(location = 9) in vec3 v_bitangent;\nlayout(set = 1, binding = 2) uniform sampler2D normalMap;\n#endif\n#if USE_PBR_MAP\nlayout(set = 1, binding = 3) uniform sampler2D pbrMap;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\nlayout(set = 1, binding = 4) uniform sampler2D metallicRoughnessMap;\n#endif\n#if USE_OCCLUSION_MAP\nlayout(set = 1, binding = 5) uniform sampler2D occlusionMap;\n#endif\n#if USE_EMISSIVE_MAP\nlayout(set = 1, binding = 6) uniform sampler2D emissiveMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvoid surf (out StandardSurface s) {\nvec4 baseColor = albedo;\n#if USE_VERTEX_COLOR\nbaseColor.rgb *= SRGBToLinear(v_color.rgb);\nbaseColor.a *= v_color.a;\n#endif\n#if USE_ALBEDO_MAP\nvec4 texColor = texture(albedoMap, ALBEDO_UV);\ntexColor.rgb = SRGBToLinear(texColor.rgb);\nbaseColor *= texColor;\n#endif\ns.albedo = baseColor;\ns.albedo.rgb *= albedoScaleAndCutoff.xyz;\n#if USE_ALPHA_TEST\nif (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n#endif\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nvec4 lightColor = texture(cc_lightingMap, v_luv.xy);\ns.lightmap = UnpackLightingmap(lightColor);\ns.lightmap_test = v_luv.z;\n#endif\ns.normal = v_normal;\n#if CC_RECEIVE_SHADOW\ns.shadowBias = v_shadowBias;\n#endif\n#if USE_NORMAL_MAP\nvec3 nmmp = texture(normalMap, NORMAL_UV).xyz - vec3(0.5);\ns.normal =\n(nmmp.x * emissiveScaleParam.w) * normalize(v_tangent) +\n(nmmp.y * emissiveScaleParam.w) * normalize(v_bitangent) +\nnmmp.z * normalize(s.normal);\n#endif\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\npackHighpData(s.position, s.position_fract_part, v_position);\n#else\ns.position = v_position;\n#endif\nvec4 pbr = pbrParams;\n#if USE_PBR_MAP\nvec4 res = texture(pbrMap, PBR_UV);\npbr.x *= res.r;\npbr.y *= res.g;\npbr.z *= res.b;\npbr.w *= res.a;\n#endif\n#if USE_METALLIC_ROUGHNESS_MAP\nvec4 metallicRoughness = texture(metallicRoughnessMap, PBR_UV);\npbr.z *= metallicRoughness.b;\npbr.y *= metallicRoughness.g;\n#endif\n#if USE_OCCLUSION_MAP\npbr.x *= texture(occlusionMap, PBR_UV).r;\n#endif\ns.occlusion = pbr.x;\ns.roughness = pbr.y;\ns.metallic = pbr.z;\ns.emissive = emissive.rgb * emissiveScaleParam.xyz;\n#if USE_EMISSIVE_MAP\ns.emissive *= SRGBToLinear(texture(emissiveMap, EMISSIVE_UV).rgb);\n#endif\n}\n#if CC_FORWARD_ADD\n#if CC_PIPELINE_TYPE == 0\n#define LIGHTS_PER_PASS 1\n#else\n#define LIGHTS_PER_PASS 10\n#endif\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0\nlayout(set = 2, binding = 1) uniform CCForwardLight {\nhighp vec4 cc_lightPos[LIGHTS_PER_PASS];\nvec4 cc_lightColor[LIGHTS_PER_PASS];\nvec4 cc_lightSizeRangeAngle[LIGHTS_PER_PASS];\nvec4 cc_lightDir[LIGHTS_PER_PASS];\n};\n#endif\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\nfloat factor = distSqr * invSqrAttRadius;\nfloat smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\nreturn smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\nfloat attenuation = 1.0 / max(distSqr, 0.01*0.01);\nattenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\nreturn attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\nfloat cd = dot(litDir, L);\nfloat attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\nreturn (attenuation * attenuation);\n}\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0\nvec4 CCStandardShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / PI;\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.0);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nint numLights = CC_PIPELINE_TYPE == 0 ? LIGHTS_PER_PASS : int(cc_lightDir[0].w);\nfor (int i = 0; i < LIGHTS_PER_PASS; i++) {\nif (i >= numLights) break;\nvec3 SLU = cc_lightPos[i].xyz - position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.0);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = cc_lightSizeRangeAngle[i].x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = PI * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(cc_lightSizeRangeAngle[i].y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (cc_lightPos[i].w > 0.0) {\nfloat cosInner = max(dot(-cc_lightDir[i].xyz, SL), 0.01);\nfloat cosOuter = cc_lightSizeRangeAngle[i].z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -cc_lightDir[i].xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = cc_lightColor[i].rgb;\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (cc_lightPos[i].w > 0.0 && cc_lightSizeRangeAngle[i].w > 0.0) {\nshadow = CCSpotShadowFactorBase(shadowPos, position, s.shadowBias);\n}\n#endif\nlightColor *= shadow;\nfinalColor += SNL * lightColor * cc_lightColor[i].w * illum * att * (diffuseContrib + lspec);\n}\nreturn vec4(finalColor, 0.0);\n}\n#endif\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1\nlayout(set = 1, binding = 7) readonly buffer b_ccLightsBuffer { vec4 b_ccLights[]; };\nlayout(set = 1, binding = 8) readonly buffer b_clusterLightIndicesBuffer { uint b_clusterLightIndices[]; };\nlayout(set = 1, binding = 9) readonly buffer b_clusterLightGridBuffer { uvec4 b_clusterLightGrid[]; };\nstruct CCLight\n{\nvec4 cc_lightPos;\nvec4 cc_lightColor;\nvec4 cc_lightSizeRangeAngle;\nvec4 cc_lightDir;\n};\nstruct Cluster\n{\nvec3 minBounds;\nvec3 maxBounds;\n};\nstruct LightGrid\n{\nuint offset;\nuint ccLights;\n};\nCCLight getCCLight(uint i)\n{\nCCLight light;\nlight.cc_lightPos = b_ccLights[4u * i + 0u];\nlight.cc_lightColor = b_ccLights[4u * i + 1u];\nlight.cc_lightSizeRangeAngle = b_ccLights[4u * i + 2u];\nlight.cc_lightDir = b_ccLights[4u * i + 3u];\nreturn light;\n}\nLightGrid getLightGrid(uint cluster)\n{\nuvec4 gridvec = b_clusterLightGrid[cluster];\nLightGrid grid;\ngrid.offset = gridvec.x;\ngrid.ccLights = gridvec.y;\nreturn grid;\n}\nuint getGridLightIndex(uint start, uint offset)\n{\nreturn b_clusterLightIndices[start + offset];\n}\nuint getClusterZIndex(vec4 worldPos)\n{\nfloat scale = float(24) / log(cc_nearFar.y / cc_nearFar.x);\nfloat bias = -(float(24) * log(cc_nearFar.x) / log(cc_nearFar.y / cc_nearFar.x));\nfloat eyeDepth = -(cc_matView * worldPos).z;\nuint zIndex = uint(max(log(eyeDepth) * scale + bias, 0.0));\nreturn zIndex;\n}\nuint getClusterIndex(vec4 fragCoord, vec4 worldPos)\n{\nuint zIndex = getClusterZIndex(worldPos);\nfloat clusterSizeX = ceil(cc_viewPort.z / float(16));\nfloat clusterSizeY = ceil(cc_viewPort.w / float(8));\nuvec3 indices = uvec3(uvec2(fragCoord.xy / vec2(clusterSizeX, clusterSizeY)), zIndex);\nuint cluster = (16u * 8u) * indices.z + 16u * indices.y + indices.x;\nreturn cluster;\n}\nvec4 CCClusterShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / PI;\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nuint cluster = getClusterIndex(gl_FragCoord, vec4(position, 1.0));\nLightGrid grid = getLightGrid(cluster);\nuint numLights = grid.ccLights;\nfor (uint i = 0u; i < 100u; i++) {\nif (i >= numLights) break;\nuint lightIndex = getGridLightIndex(grid.offset, i);\nCCLight light = getCCLight(lightIndex);\nvec3 SLU = light.cc_lightPos.xyz - position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.001);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = light.cc_lightSizeRangeAngle.x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = PI * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(light.cc_lightSizeRangeAngle.y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (light.cc_lightPos.w > 0.0) {\nfloat cosInner = max(dot(-light.cc_lightDir.xyz, SL), 0.01);\nfloat cosOuter = light.cc_lightSizeRangeAngle.z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -light.cc_lightDir.xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = light.cc_lightColor.rgb;\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (light.cc_lightPos.w > 0.0) {\nshadow = CCSpotShadowFactorBase(shadowPos, position, s.shadowBias);\n}\n#endif\nlightColor *= shadow;\nfinalColor += SNL * lightColor * light.cc_lightColor.w * illum * att * (diffuseContrib + lspec);\n}\nreturn vec4(finalColor, 0.0);\n}\n#endif\nlayout(location = 0) out vec4 fragColorX;\nvoid main () {\nStandardSurface s; surf(s);\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1\nvec4 color = CCClusterShadingAdditive(s, v_shadowPos);\n#else\nvec4 color = CCStandardShadingAdditive(s, v_shadowPos);\n#endif\nCC_APPLY_FOG(color, s.position.xyz);\nfragColorX = CCFragOutput(color);\n}\n#elif (CC_PIPELINE_TYPE == 0 || CC_FORCE_FORWARD_SHADING)\nlayout(location = 0) out vec4 fragColorX;\nvoid main () {\nStandardSurface s; surf(s);\nvec4 color = CCStandardShadingBase(s, v_shadowPos);\nCC_APPLY_FOG(color, s.position.xyz);\nfragColorX = CCFragOutput(color);\n}\n#elif CC_PIPELINE_TYPE == 1\nvec2 signNotZero(vec2 v) {\nreturn vec2((v.x >= 0.0) ? +1.0 : -1.0, (v.y >= 0.0) ? +1.0 : -1.0);\n}\nvec2 float32x3_to_oct(in vec3 v) {\nvec2 p = v.xy * (1.0 / (abs(v.x) + abs(v.y) + abs(v.z)));\nreturn (v.z <= 0.0) ? ((1.0 - abs(p.yx)) * signNotZero(p)) : p;\n}\nlayout(location = 0) out vec4 fragColor0;\nlayout(location = 1) out vec4 fragColor1;\nlayout(location = 2) out vec4 fragColor2;\nvoid main () {\nStandardSurface s; surf(s);\nfragColor0 = s.albedo;\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nfragColor1 = vec4(position, s.roughness);\nfragColor1 = vec4(float32x3_to_oct(s.normal), s.roughness, s.metallic);\nfragColor3 = vec4(s.emissive, s.occlusion);\n}\n#endif", - }, - { - "vert": "#extension GL_EXT_shader_explicit_arithmetic_types_int32: require\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\nlayout(location = 3) in vec4 a_tangent;\n#if USE_INSTANCING\nlayout(location = 6) in vec4 a_matWorld0;\nlayout(location = 7) in vec4 a_matWorld1;\nlayout(location = 8) in vec4 a_matWorld2;\n#if USE_LIGHTMAP\nlayout(location = 9) in vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nlayout(location = 10) in vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nlayout(location = 11) in float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nint getVertexId() {\nreturn gl_VertexIndex;\n}\n#endif\n#if CC_USE_SKINNING\nlayout(location = 4) in u32vec4 a_joints;\nlayout(location = 5) in vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nlayout(set = 2, binding = 4) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nlayout(set = 2, binding = 7) uniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nlayout(set = 2, binding = 8) uniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nlayout(set = 2, binding = 9) uniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nlayout(location = 13) in highp vec4 a_jointAnimInfo;\n#endif\nlayout(set = 2, binding = 3) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(set = 2, binding = 2) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nlayout(set = 2, binding = 6) uniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nlayout(set = 2, binding = 3) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\n#if USE_BATCHING\nlayout(set = 2, binding = 0) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(set = 2, binding = 0) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nvoid CCGetWorldMatrixFull(out mat4 matWorld, out mat4 matWorldIT)\n{\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\nmatWorldIT = matWorld;\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\nmatWorldIT = matWorld;\n#else\nmatWorld = cc_matWorld;\nmatWorldIT = cc_matWorldIT;\n#endif\n}\nlayout(set = 1, binding = 0) uniform Constants {\nvec4 tilingOffset;\nvec4 albedo;\nvec4 albedoScaleAndCutoff;\nvec4 pbrParams;\nvec4 emissive;\nvec4 emissiveScaleParam;\n};\nlayout(set = 0, binding = 2) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\n#if HAS_SECOND_UV || USE_LIGHTMAP\nlayout(location = 14) in vec2 a_texCoord1;\n#endif\nlayout(location = 0) out vec2 v_uv;\nlayout(location = 1) out vec2 v_uv1;\nlayout(location = 2) out vec4 v_worldPos;\nlayout(location = 3) out float v_clip_depth;\nvec4 vert () {\nStandardVertInput In;\nCCVertInput(In);\nmat4 matWorld, matWorldIT;\nCCGetWorldMatrixFull(matWorld, matWorldIT);\nv_worldPos = matWorld * In.position;\nvec4 clipPos = cc_matLightViewProj * v_worldPos;\nv_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n#if HAS_SECOND_UV\nv_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw;\n#endif\nv_clip_depth = clipPos.z / clipPos.w * 0.5 + 0.5;\nreturn clipPos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\nlayout(set = 1, binding = 0) uniform Constants {\nvec4 tilingOffset;\nvec4 albedo;\nvec4 albedoScaleAndCutoff;\nvec4 pbrParams;\nvec4 emissive;\nvec4 emissiveScaleParam;\n};\nvec4 packDepthToRGBA (float depth) {\nvec4 ret = vec4(1.0, 255.0, 65025.0, 16581375.0) * depth;\nret = fract(ret);\nret -= vec4(ret.yzw, 0.0) / 255.0;\nreturn ret;\n}\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(set = 0, binding = 2) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\n#if USE_BATCHING\nlayout(set = 2, binding = 0) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(set = 2, binding = 0) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nfloat CCGetLinearDepthFromViewSpace(vec3 viewPos) {\nfloat dist = length(viewPos);\nreturn (dist - cc_shadowNFLSInfo.x) / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x);\n}\nfloat CCGetLinearDepth(vec3 worldPos) {\nvec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0);\nreturn CCGetLinearDepthFromViewSpace(viewStartPos.xyz);\n}\n#if CC_RECEIVE_SHADOW\nlayout(set = 0, binding = 3) uniform highp sampler2D cc_shadowMap;\nlayout(set = 0, binding = 5) uniform highp sampler2D cc_spotLightingMap;\n#endif\nlayout(location = 0) in vec2 v_uv;\nlayout(location = 1) in vec2 v_uv1;\nlayout(location = 2) in vec4 v_worldPos;\nlayout(location = 3) in float v_clip_depth;\n#if USE_ALBEDO_MAP\nlayout(set = 1, binding = 1) uniform sampler2D albedoMap;\n#endif\n#if USE_ALPHA_TEST\n#endif\nvec4 frag () {\nvec4 baseColor = albedo;\n#if USE_ALBEDO_MAP\nbaseColor *= texture(albedoMap, ALBEDO_UV);\n#endif\n#if USE_ALPHA_TEST\nif (baseColor.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard;\n#endif\nif(cc_shadowLPNNInfo.x > 0.000001 && cc_shadowLPNNInfo.x < 1.999999) {\nif (cc_shadowNFLSInfo.z > 0.000001) {\nreturn vec4(CCGetLinearDepth(v_worldPos.xyz), 1.0, 1.0, 1.0);\n}\n}\nif (cc_shadowLPNNInfo.y > 0.000001) {\nreturn packDepthToRGBA(v_clip_depth);\n}\nreturn vec4(v_clip_depth, 1.0, 1.0, 1.0);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(set = 2, binding = 0) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(set = 2, binding = 0) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\n#if !CC_USE_ACCURATE_FOG\nlayout(location = 0) out float v_fog_factor;\n#endif\nvoid CC_TRANSFER_FOG(vec4 pos) {\n#if !CC_USE_ACCURATE_FOG\nCC_TRANSFER_FOG_BASE(pos, v_fog_factor);\n#endif\n}\nlayout(location = 1) out highp vec4 v_shadowPos;\nlayout(set = 0, binding = 2) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\n#if CC_RECEIVE_SHADOW\nlayout(set = 0, binding = 3) uniform highp sampler2D cc_shadowMap;\nlayout(set = 0, binding = 5) uniform highp sampler2D cc_spotLightingMap;\n#endif\n#if CC_RECEIVE_SHADOW\n#endif\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\n#if CC_RECEIVE_SHADOW\nlayout(location = 2) out vec2 v_shadowBias;\n#endif\nlayout(location = 3) out highp vec3 v_position;\nlayout(location = 4) out mediump vec3 v_normal;\n#if USE_NORMALMAP\nlayout(location = 5) out mediump vec3 v_tangent;\nlayout(location = 6) out mediump vec3 v_binormal;\n#endif\nlayout(location = 7) out mediump vec2 uvw;\nlayout(location = 8) out mediump vec2 uv0;\nlayout(location = 9) out mediump vec2 uv1;\nlayout(location = 10) out mediump vec2 uv2;\nlayout(location = 11) out mediump vec2 uv3;\nlayout(location = 12) out mediump vec3 luv;\nlayout(location = 13) out mediump vec3 diffuse;\nlayout(set = 1, binding = 0) uniform TexCoords {\nvec4 UVScale;\nvec4 lightMapUVParam;\n};\nvoid main () {\nvec3 worldPos;\nworldPos.x = cc_matWorld[3][0] + a_position.x;\nworldPos.y = cc_matWorld[3][1] + a_position.y;\nworldPos.z = cc_matWorld[3][2] + a_position.z;\nvec4 pos = vec4(worldPos, 1.0);\npos = cc_matViewProj * pos;\nuvw = a_texCoord;\nuv0 = a_position.xz * UVScale.x;\nuv1 = a_position.xz * UVScale.y;\nuv2 = a_position.xz * UVScale.z;\nuv3 = a_position.xz * UVScale.w;\n#if USE_LIGHTMAP\nluv.xy = lightMapUVParam.xy + a_texCoord * lightMapUVParam.zw;\nluv.z = lightMapUVParam.z;\n#endif\nv_position = worldPos;\nv_normal = a_normal;\nCC_TRANSFER_FOG(vec4(worldPos, 1.0));\n#if CC_RECEIVE_SHADOW\nv_shadowBias = vec2(0.0, 0.0);\n#endif\n#if USE_NORMALMAP\nv_tangent = vec3(1.0, 0.0, 0.0);\nv_binormal = vec3(0.0, 0.0, 1.0);\nv_binormal = cross(v_tangent, a_normal);\nv_tangent = cross(a_normal, v_binormal);\n#endif\nv_shadowPos = cc_matLightViewProj * vec4(worldPos, 1.0);\ngl_Position = pos;\n}", - "frag": "\nprecision highp float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nlayout(set = 0, binding = 2) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\nhighp float unpackHighpData (float mainPart, float modPart) {\nhighp float data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out float mainPart, out float modPart, highp float data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp float unpackHighpData (float mainPart, float modPart, const float modValue) {\nhighp float data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out float mainPart, out float modPart, highp float data, const float modValue) {\nhighp float divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\nhighp vec2 unpackHighpData (vec2 mainPart, vec2 modPart) {\nhighp vec2 data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out vec2 mainPart, out vec2 modPart, highp vec2 data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp vec2 unpackHighpData (vec2 mainPart, vec2 modPart, const float modValue) {\nhighp vec2 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out vec2 mainPart, out vec2 modPart, highp vec2 data, const float modValue) {\nhighp vec2 divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\nhighp vec3 unpackHighpData (vec3 mainPart, vec3 modPart) {\nhighp vec3 data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out vec3 mainPart, out vec3 modPart, highp vec3 data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp vec3 unpackHighpData (vec3 mainPart, vec3 modPart, const float modValue) {\nhighp vec3 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out vec3 mainPart, out vec3 modPart, highp vec3 data, const float modValue) {\nhighp vec3 divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\nhighp vec4 unpackHighpData (vec4 mainPart, vec4 modPart) {\nhighp vec4 data = mainPart;\nreturn data + modPart;\n}\nvoid packHighpData (out vec4 mainPart, out vec4 modPart, highp vec4 data) {\nmainPart = fract(data);\nmodPart = data - mainPart;\n}\nhighp vec4 unpackHighpData (vec4 mainPart, vec4 modPart, const float modValue) {\nhighp vec4 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nvoid packHighpData (out vec4 mainPart, out vec4 modPart, highp vec4 data, const float modValue) {\nhighp vec4 divide = data / modValue;\nmainPart = floor(divide);\nmodPart = (data - mainPart * modValue) / modValue;\n}\n#if USE_BATCHING\nlayout(set = 2, binding = 0) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(set = 2, binding = 0) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nfloat CCGetLinearDepthFromViewSpace(vec3 viewPos) {\nfloat dist = length(viewPos);\nreturn (dist - cc_shadowNFLSInfo.x) / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x);\n}\nfloat CCGetLinearDepth(vec3 worldPos) {\nvec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0);\nreturn CCGetLinearDepthFromViewSpace(viewStartPos.xyz);\n}\n#if CC_RECEIVE_SHADOW\nlayout(set = 0, binding = 3) uniform highp sampler2D cc_shadowMap;\nlayout(set = 0, binding = 5) uniform highp sampler2D cc_spotLightingMap;\nvec4 ApplyShadowDepthBias_FaceNormal(vec4 shadowPos, vec3 worldNormal, float normalBias)\n{\nvec4 newShadowPos = shadowPos;\nif(normalBias > 0.0001)\n{\nvec4 viewNormal = cc_matLightView * vec4(worldNormal, 0.0);\nif(viewNormal.z < 0.1)\nnewShadowPos.xy += viewNormal.xy * cc_shadowProjInfo.xy * normalBias * clamp(viewNormal.z, 0.001, 0.1);\n}\nreturn newShadowPos;\n}\nvec4 ApplyShadowDepthBias_Perspective(vec4 shadowPos, float viewspaceDepthBias)\n{\nvec3 viewSpacePos;\nviewSpacePos.xy = shadowPos.xy * cc_shadowProjInfo.zw;\nviewSpacePos.z = shadowPos.z * cc_shadowInvProjDepthInfo.x + shadowPos.w * cc_shadowInvProjDepthInfo.y;\nviewSpacePos.xyz += cc_shadowProjDepthInfo.z * normalize(viewSpacePos.xyz) * viewspaceDepthBias;\nvec4 clipSpacePos;\nclipSpacePos.xy = viewSpacePos.xy * cc_shadowProjInfo.xy;\nclipSpacePos.zw = viewSpacePos.z * cc_shadowProjDepthInfo.xz + vec2(cc_shadowProjDepthInfo.y, 0.0);\nif (cc_shadowNFLSInfo.z > 0.000001) {\nclipSpacePos.z = CCGetLinearDepthFromViewSpace(viewSpacePos.xyz);\nclipSpacePos.z = (clipSpacePos.z * 2.0 - 1.0) * clipSpacePos.w;\n}\nreturn clipSpacePos;\n}\nvec4 ApplyShadowDepthBias_Orthographic(vec4 shadowPos, float viewspaceDepthBias)\n{\nfloat coeffA = cc_shadowProjDepthInfo.x;\nfloat coeffB = cc_shadowProjDepthInfo.y;\nfloat viewSpacePos_z = (shadowPos.z - coeffB) / coeffA;\nviewSpacePos_z += viewspaceDepthBias;\nvec4 result = shadowPos;\nresult.z = viewSpacePos_z * coeffA + coeffB;\nreturn result;\n}\nfloat CCGetShadowFactorHard (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture(cc_shadowMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n} else {\nclosestDepth = texture(cc_shadowMap, clipPos.xy).x;\n}\nshadow = step(clipPos.z, closestDepth);\nreturn shadow;\n}\nfloat CCGetShadowFactorSoft (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x);\nblock1 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)).x);\nblock2 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)).x);\nblock3 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetShadowFactorSoft2X (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock4 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock5 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock6 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock7 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock8 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)).x);\nblock1 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)).x);\nblock2 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)).x);\nblock3 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)).x);\nblock4 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x);\nblock5 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)).x);\nblock6 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)).x);\nblock7 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)).x);\nblock8 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCGetSpotLightShadowFactorHard (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nfloat depth = clipPos.z;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture(cc_spotLightingMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n} else {\nclosestDepth = texture(cc_spotLightingMap, clipPos.xy).x;\n}\nshadow = step(depth, closestDepth);\nreturn shadow;\n}\nfloat CCGetSpotLightShadowFactorSoft (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nvec2 oneTap = 1.0 / cc_shadowWHPBInfo.xy;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x);\nblock1 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)).x);\nblock2 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)).x);\nblock3 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * cc_shadowWHPBInfo.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY = mod(clipPos.y, oneTap.y) * cc_shadowWHPBInfo.y;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetSpotLightShadowFactorSoft2X (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock4 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock5 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock6 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock7 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock8 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)).x);\nblock1 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)).x);\nblock2 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)).x);\nblock3 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)).x);\nblock4 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x);\nblock5 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)).x);\nblock6 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)).x);\nblock7 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)).x);\nblock8 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCSpotShadowFactorBase(vec4 shadowPos, vec3 worldPos, vec2 shadowBias)\n{\nfloat pcf = cc_shadowWHPBInfo.z;\nif (pcf > 1.9) {\nreturn CCGetSpotLightShadowFactorSoft2X(shadowPos, worldPos, shadowBias.x);\n}else if (pcf > 0.9) {\nreturn CCGetSpotLightShadowFactorSoft(shadowPos, worldPos, shadowBias.x);\n}else {\nreturn CCGetSpotLightShadowFactorHard(shadowPos, worldPos, shadowBias.x);\n}\n}\nfloat CCShadowFactorBase(vec4 shadowPos, vec3 N, vec2 shadowBias)\n{\nfloat realtimeShadow = 1.0;\nvec4 pos = ApplyShadowDepthBias_FaceNormal(shadowPos, N, shadowBias.y);\nfloat pcf = cc_shadowWHPBInfo.z;\nif (pcf > 1.9) {\nrealtimeShadow = CCGetShadowFactorSoft2X(pos, shadowBias.x);\n}else if (pcf > 0.9) {\nrealtimeShadow = CCGetShadowFactorSoft(pos, shadowBias.x);\n}else {\nrealtimeShadow = CCGetShadowFactorHard(pos, shadowBias.x);\n}\nreturn mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w);\n}\n#endif\n#if CC_USE_IBL\nlayout(set = 0, binding = 4) uniform samplerCube cc_environment;\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\nreturn textureLod(tex, coord, lod);\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\nreturn textureLod(tex, coord, lod);\n}\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(1.1, rgbe.a * 255.0 - 128.0);\n}\n#if CC_USE_DIFFUSEMAP\nlayout(set = 0, binding = 6) uniform samplerCube cc_diffuseMap;\n#endif\n#endif\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\nvec3 NxH = cross(N, H);\nfloat OneMinusNoHSqr = dot(NxH, NxH);\nfloat a = roughness * roughness;\nfloat n = NoH * a;\nfloat p = a / (OneMinusNoHSqr + n * n);\nreturn p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\nreturn (roughness * 0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\nconst vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\nconst vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\nvec4 r = roughness * c0 + c1;\nfloat a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;\nvec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;\nAB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\nreturn specular * AB.x + AB.y;\n}\n#if USE_REFLECTION_DENOISE\nvec3 GetEnvReflectionWithMipFiltering(vec3 R, float roughness, float mipCount, float denoiseIntensity) {\n#if CC_USE_IBL\nfloat mip = roughness * mipCount;\nfloat delta = (dot(dFdx(R), dFdy(R))) * 1000.0;\nfloat mipBias = mix(0.0, 5.0, clamp(delta, 0.0, 1.0));\nvec4 biased = fragTextureLod(cc_environment, R, mip + mipBias);\nvec4 filtered = texture(cc_environment, R);\n#if CC_USE_IBL == 2\nbiased.rgb = unpackRGBE(biased);\nfiltered.rgb = unpackRGBE(filtered);\n#else\nbiased.rgb = SRGBToLinear(biased.rgb);\nfiltered.rgb = SRGBToLinear(filtered.rgb);\n#endif\nreturn mix(biased.rgb, filtered.rgb, denoiseIntensity);\n#else\nreturn vec3(0.0, 0.0, 0.0);\n#endif\n}\n#endif\nstruct StandardSurface {\nvec4 albedo;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nvec3 position, position_fract_part;\n#else\nvec3 position;\n#endif\nvec3 normal;\nvec3 emissive;\nvec3 lightmap;\nfloat lightmap_test;\nfloat roughness;\nfloat metallic;\nfloat occlusion;\n#if CC_RECEIVE_SHADOW\nvec2 shadowBias;\n#endif\n};\nvec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.0);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 L = normalize(-cc_mainLitDir.xyz);\nvec3 H = normalize(L + V);\nfloat NH = max(dot(N, H), 0.0);\nfloat NL = max(dot(N, L), 0.0);\nvec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w;\nvec3 diffuseContrib = diffuse;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nif (s.lightmap_test > 0.0001) {\nfinalColor = s.lightmap.rgb;\n}\n#else\ndiffuseContrib /= PI;\n#endif\nvec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\nvec3 dirlightContrib = (diffuseContrib + specularContrib);\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (NL > 0.0 && cc_mainLitDir.w > 0.0) {\nshadow = CCShadowFactorBase(shadowPos, N, s.shadowBias);\n}\n#endif\ndirlightContrib *= shadow;\nfinalColor *= dirlightContrib;\nfloat fAmb = 0.5 - N.y * 0.5;\nvec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb);\n#if CC_USE_IBL\n#if CC_USE_DIFFUSEMAP\nvec4 diffuseMap = texture(cc_diffuseMap, N);\n#if CC_USE_DIFFUSEMAP == 2\nambDiff = unpackRGBE(diffuseMap);\n#else\nambDiff = SRGBToLinear(diffuseMap.rgb);\n#endif\n#endif\nvec3 R = normalize(reflect(-V, N));\n#if USE_REFLECTION_DENOISE\nvec3 env = GetEnvReflectionWithMipFiltering(R, s.roughness, cc_ambientGround.w, 0.6);\n#else\nvec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n#if CC_USE_IBL == 2\nvec3 env = unpackRGBE(envmap);\n#else\nvec3 env = SRGBToLinear(envmap.rgb);\n#endif\n#endif\nfinalColor += env * cc_ambientSky.w * specular * s.occlusion;\n#endif\nfinalColor += ambDiff.rgb * cc_ambientSky.w * diffuse * s.occlusion;\nfinalColor += s.emissive;\nreturn vec4(finalColor, s.albedo.a);\n}\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = ACESToneMap(color.rgb);\n#endif\ncolor.rgb = sqrt(color.rgb);\nreturn color;\n}\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\nvoid CC_APPLY_FOG_BASE(inout vec4 color, float factor) {\ncolor = vec4(mix(cc_fogColor.rgb, color.rgb, factor), color.a);\n}\n#if !CC_USE_ACCURATE_FOG\nlayout(location = 0) in float v_fog_factor;\n#endif\nvoid CC_APPLY_FOG(inout vec4 color) {\n#if !CC_USE_ACCURATE_FOG\nCC_APPLY_FOG_BASE(color, v_fog_factor);\n#endif\n}\nvoid CC_APPLY_FOG(inout vec4 color, vec3 worldPos) {\n#if CC_USE_ACCURATE_FOG\nfloat factor;\nCC_TRANSFER_FOG_BASE(vec4(worldPos, 1.0), factor);\n#else\nfloat factor = v_fog_factor;\n#endif\nCC_APPLY_FOG_BASE(color, factor);\n}\nlayout(location = 1) in highp vec4 v_shadowPos;\n#if CC_RECEIVE_SHADOW\n#endif\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nlayout(location = 14) in vec3 v_luv;\nlayout(set = 2, binding = 10) uniform sampler2D cc_lightingMap;\nvec3 UnpackLightingmap(vec4 color) {\nvec3 c;\nfloat e = 1.0 + color.a * (8.0 - 1.0);\nc.r = color.r * e;\nc.g = color.g * e;\nc.b = color.b * e;\nreturn c;\n}\n#endif\nlayout(location = 3) in highp vec3 v_position;\nlayout(location = 4) in mediump vec3 v_normal;\n#if CC_RECEIVE_SHADOW\nlayout(location = 2) in vec2 v_shadowBias;\n#endif\n#if USE_NORMALMAP\nlayout(location = 5) in mediump vec3 v_tangent;\nlayout(location = 6) in mediump vec3 v_binormal;\n#endif\nlayout(location = 7) in mediump vec2 uvw;\nlayout(location = 8) in mediump vec2 uv0;\nlayout(location = 9) in mediump vec2 uv1;\nlayout(location = 10) in mediump vec2 uv2;\nlayout(location = 11) in mediump vec2 uv3;\nlayout(location = 13) in mediump vec3 diffuse;\nlayout(location = 12) in mediump vec3 luv;\nlayout(set = 1, binding = 1) uniform PbrParams {\nvec4 metallic;\nvec4 roughness;\n};\nlayout(set = 1, binding = 2) uniform sampler2D weightMap;\nlayout(set = 1, binding = 3) uniform sampler2D detailMap0;\nlayout(set = 1, binding = 4) uniform sampler2D detailMap1;\nlayout(set = 1, binding = 5) uniform sampler2D detailMap2;\nlayout(set = 1, binding = 6) uniform sampler2D detailMap3;\nlayout(set = 1, binding = 7) uniform sampler2D normalMap0;\nlayout(set = 1, binding = 8) uniform sampler2D normalMap1;\nlayout(set = 1, binding = 9) uniform sampler2D normalMap2;\nlayout(set = 1, binding = 10) uniform sampler2D normalMap3;\nlayout(set = 1, binding = 11) uniform sampler2D lightMap;\nvoid surf (out StandardSurface s) {\n#if LAYERS > 1\nvec4 w = texture(weightMap, uvw);\n#endif\nvec4 baseColor = vec4(0, 0, 0, 0);\n#if LAYERS == 1\nbaseColor = texture(detailMap0, uv0);\n#elif LAYERS == 2\nbaseColor += texture(detailMap0, uv0) * w.r;\nbaseColor += texture(detailMap1, uv1) * w.g;\n#elif LAYERS == 3\nbaseColor += texture(detailMap0, uv0) * w.r;\nbaseColor += texture(detailMap1, uv1) * w.g;\nbaseColor += texture(detailMap2, uv2) * w.b;\n#elif LAYERS == 4\nbaseColor += texture(detailMap0, uv0) * w.r;\nbaseColor += texture(detailMap1, uv1) * w.g;\nbaseColor += texture(detailMap2, uv2) * w.b;\nbaseColor += texture(detailMap3, uv3) * w.a;\n#else\nbaseColor = texture(detailMap0, uv0);\n#endif\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\npackHighpData(s.position, s.position_fract_part, v_position);\n#else\ns.position = v_position;\n#endif\n#if USE_NORMALMAP\nvec4 baseNormal = vec4(0, 0, 0, 0);\n#if LAYERS == 1\nbaseNormal = texture(normalMap0, uv0);\n#elif LAYERS == 2\nbaseNormal += texture(normalMap0, uv0) * w.r;\nbaseNormal += texture(normalMap1, uv1) * w.g;\n#elif LAYERS == 3\nbaseNormal += texture(normalMap0, uv0) * w.r;\nbaseNormal += texture(normalMap1, uv1) * w.g;\nbaseNormal += texture(normalMap2, uv2) * w.b;\n#elif LAYERS == 4\nbaseNormal += texture(normalMap0, uv0) * w.r;\nbaseNormal += texture(normalMap1, uv1) * w.g;\nbaseNormal += texture(normalMap2, uv2) * w.b;\nbaseNormal += texture(normalMap3, uv3) * w.a;\n#else\nbaseNormal = texture(normalMap0, uv0);\n#endif\nvec3 nmmp = baseNormal.xyz - vec3(0.5);\ns.normal =\nnmmp.x * normalize(v_tangent) +\nnmmp.y * normalize(v_binormal) +\nnmmp.z * normalize(v_normal);\n#else\ns.normal = v_normal;\n#endif\n#if CC_RECEIVE_SHADOW\ns.shadowBias = v_shadowBias;\n#endif\ns.albedo = vec4(SRGBToLinear(baseColor.rgb), 1.0);\ns.occlusion = 1.0;\n#if USE_PBR\ns.roughness = 0.0;\n#if LAYERS == 1\ns.roughness = roughness.x;\n#elif LAYERS == 2\ns.roughness += roughness.x * w.r;\ns.roughness += roughness.y * w.g;\n#elif LAYERS == 3\ns.roughness += roughness.x * w.r;\ns.roughness += roughness.y * w.g;\ns.roughness += roughness.z * w.b;\n#elif LAYERS == 4\ns.roughness += roughness.x * w.r;\ns.roughness += roughness.y * w.g;\ns.roughness += roughness.z * w.b;\ns.roughness += roughness.w * w.a;\n#else\ns.roughness = 1.0;\n#endif\ns.metallic = 0.0;\n#if LAYERS == 1\ns.metallic = metallic.x;\n#elif LAYERS == 2\ns.metallic += metallic.x * w.r;\ns.metallic += metallic.y * w.g;\n#elif LAYERS == 3\ns.metallic += metallic.x * w.r;\ns.metallic += metallic.y * w.g;\ns.metallic += metallic.z * w.b;\n#elif LAYERS == 4\ns.metallic += metallic.x * w.r;\ns.metallic += metallic.y * w.g;\ns.metallic += metallic.z * w.b;\ns.metallic += metallic.w * w.a;\n#else\ns.metallic = 0.0;\n#endif\n#else\ns.roughness = 1.0;\ns.metallic = 0.0;\n#endif\ns.emissive = vec3(0.0, 0.0, 0.0);\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nvec4 lightColor = texture(lightMap, luv.xy);\ns.lightmap = UnpackLightingmap(lightColor);\ns.lightmap_test = luv.z;\n#endif\n}\n#if CC_FORWARD_ADD\n#if CC_PIPELINE_TYPE == 0\n#define LIGHTS_PER_PASS 1\n#else\n#define LIGHTS_PER_PASS 10\n#endif\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0\nlayout(set = 2, binding = 1) uniform CCForwardLight {\nhighp vec4 cc_lightPos[LIGHTS_PER_PASS];\nvec4 cc_lightColor[LIGHTS_PER_PASS];\nvec4 cc_lightSizeRangeAngle[LIGHTS_PER_PASS];\nvec4 cc_lightDir[LIGHTS_PER_PASS];\n};\n#endif\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\nfloat factor = distSqr * invSqrAttRadius;\nfloat smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\nreturn smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\nfloat attenuation = 1.0 / max(distSqr, 0.01*0.01);\nattenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\nreturn attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\nfloat cd = dot(litDir, L);\nfloat attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\nreturn (attenuation * attenuation);\n}\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0\nvec4 CCStandardShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / PI;\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.0);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nint numLights = CC_PIPELINE_TYPE == 0 ? LIGHTS_PER_PASS : int(cc_lightDir[0].w);\nfor (int i = 0; i < LIGHTS_PER_PASS; i++) {\nif (i >= numLights) break;\nvec3 SLU = cc_lightPos[i].xyz - position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.0);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = cc_lightSizeRangeAngle[i].x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = PI * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(cc_lightSizeRangeAngle[i].y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (cc_lightPos[i].w > 0.0) {\nfloat cosInner = max(dot(-cc_lightDir[i].xyz, SL), 0.01);\nfloat cosOuter = cc_lightSizeRangeAngle[i].z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -cc_lightDir[i].xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = cc_lightColor[i].rgb;\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (cc_lightPos[i].w > 0.0 && cc_lightSizeRangeAngle[i].w > 0.0) {\nshadow = CCSpotShadowFactorBase(shadowPos, position, s.shadowBias);\n}\n#endif\nlightColor *= shadow;\nfinalColor += SNL * lightColor * cc_lightColor[i].w * illum * att * (diffuseContrib + lspec);\n}\nreturn vec4(finalColor, 0.0);\n}\n#endif\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1\nlayout(set = 1, binding = 12) readonly buffer b_ccLightsBuffer { vec4 b_ccLights[]; };\nlayout(set = 1, binding = 13) readonly buffer b_clusterLightIndicesBuffer { uint b_clusterLightIndices[]; };\nlayout(set = 1, binding = 14) readonly buffer b_clusterLightGridBuffer { uvec4 b_clusterLightGrid[]; };\nstruct CCLight\n{\nvec4 cc_lightPos;\nvec4 cc_lightColor;\nvec4 cc_lightSizeRangeAngle;\nvec4 cc_lightDir;\n};\nstruct Cluster\n{\nvec3 minBounds;\nvec3 maxBounds;\n};\nstruct LightGrid\n{\nuint offset;\nuint ccLights;\n};\nCCLight getCCLight(uint i)\n{\nCCLight light;\nlight.cc_lightPos = b_ccLights[4u * i + 0u];\nlight.cc_lightColor = b_ccLights[4u * i + 1u];\nlight.cc_lightSizeRangeAngle = b_ccLights[4u * i + 2u];\nlight.cc_lightDir = b_ccLights[4u * i + 3u];\nreturn light;\n}\nLightGrid getLightGrid(uint cluster)\n{\nuvec4 gridvec = b_clusterLightGrid[cluster];\nLightGrid grid;\ngrid.offset = gridvec.x;\ngrid.ccLights = gridvec.y;\nreturn grid;\n}\nuint getGridLightIndex(uint start, uint offset)\n{\nreturn b_clusterLightIndices[start + offset];\n}\nuint getClusterZIndex(vec4 worldPos)\n{\nfloat scale = float(24) / log(cc_nearFar.y / cc_nearFar.x);\nfloat bias = -(float(24) * log(cc_nearFar.x) / log(cc_nearFar.y / cc_nearFar.x));\nfloat eyeDepth = -(cc_matView * worldPos).z;\nuint zIndex = uint(max(log(eyeDepth) * scale + bias, 0.0));\nreturn zIndex;\n}\nuint getClusterIndex(vec4 fragCoord, vec4 worldPos)\n{\nuint zIndex = getClusterZIndex(worldPos);\nfloat clusterSizeX = ceil(cc_viewPort.z / float(16));\nfloat clusterSizeY = ceil(cc_viewPort.w / float(8));\nuvec3 indices = uvec3(uvec2(fragCoord.xy / vec2(clusterSizeX, clusterSizeY)), zIndex);\nuint cluster = (16u * 8u) * indices.z + 16u * indices.y + indices.x;\nreturn cluster;\n}\nvec4 CCClusterShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / PI;\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nuint cluster = getClusterIndex(gl_FragCoord, vec4(position, 1.0));\nLightGrid grid = getLightGrid(cluster);\nuint numLights = grid.ccLights;\nfor (uint i = 0u; i < 100u; i++) {\nif (i >= numLights) break;\nuint lightIndex = getGridLightIndex(grid.offset, i);\nCCLight light = getCCLight(lightIndex);\nvec3 SLU = light.cc_lightPos.xyz - position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.001);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = light.cc_lightSizeRangeAngle.x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = PI * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(light.cc_lightSizeRangeAngle.y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (light.cc_lightPos.w > 0.0) {\nfloat cosInner = max(dot(-light.cc_lightDir.xyz, SL), 0.01);\nfloat cosOuter = light.cc_lightSizeRangeAngle.z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -light.cc_lightDir.xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = light.cc_lightColor.rgb;\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (light.cc_lightPos.w > 0.0) {\nshadow = CCSpotShadowFactorBase(shadowPos, position, s.shadowBias);\n}\n#endif\nlightColor *= shadow;\nfinalColor += SNL * lightColor * light.cc_lightColor.w * illum * att * (diffuseContrib + lspec);\n}\nreturn vec4(finalColor, 0.0);\n}\n#endif\nlayout(location = 0) out vec4 fragColorX;\nvoid main () {\nStandardSurface s; surf(s);\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1\nvec4 color = CCClusterShadingAdditive(s, v_shadowPos);\n#else\nvec4 color = CCStandardShadingAdditive(s, v_shadowPos);\n#endif\nCC_APPLY_FOG(color, s.position.xyz);\nfragColorX = CCFragOutput(color);\n}\n#elif (CC_PIPELINE_TYPE == 0 || CC_FORCE_FORWARD_SHADING)\nlayout(location = 0) out vec4 fragColorX;\nvoid main () {\nStandardSurface s; surf(s);\nvec4 color = CCStandardShadingBase(s, v_shadowPos);\nCC_APPLY_FOG(color, s.position.xyz);\nfragColorX = CCFragOutput(color);\n}\n#elif CC_PIPELINE_TYPE == 1\nvec2 signNotZero(vec2 v) {\nreturn vec2((v.x >= 0.0) ? +1.0 : -1.0, (v.y >= 0.0) ? +1.0 : -1.0);\n}\nvec2 float32x3_to_oct(in vec3 v) {\nvec2 p = v.xy * (1.0 / (abs(v.x) + abs(v.y) + abs(v.z)));\nreturn (v.z <= 0.0) ? ((1.0 - abs(p.yx)) * signNotZero(p)) : p;\n}\nlayout(location = 0) out vec4 fragColor0;\nlayout(location = 1) out vec4 fragColor1;\nlayout(location = 2) out vec4 fragColor2;\nvoid main () {\nStandardSurface s; surf(s);\nfragColor0 = s.albedo;\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nfragColor1 = vec4(position, s.roughness);\nfragColor1 = vec4(float32x3_to_oct(s.normal), s.roughness, s.metallic);\nfragColor3 = vec4(s.emissive, s.occlusion);\n}\n#endif", - }, - { - "vert": "\nprecision highp float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(set = 2, binding = 0) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(set = 2, binding = 0) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nlayout(set = 0, binding = 2) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\nlayout(location = 0) out vec2 v_clip_depth;\nvec4 vert () {\nvec4 worldPos;\nworldPos.x = cc_matWorld[3][0] + a_position.x;\nworldPos.y = cc_matWorld[3][1] + a_position.y;\nworldPos.z = cc_matWorld[3][2] + a_position.z;\nworldPos.w = 1.0;\nvec4 clipPos = cc_matLightViewProj * worldPos;\nv_clip_depth = clipPos.zw;\nreturn clipPos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\nvec4 packDepthToRGBA (float depth) {\nvec4 ret = vec4(1.0, 255.0, 65025.0, 16581375.0) * depth;\nret = fract(ret);\nret -= vec4(ret.yzw, 0.0) / 255.0;\nreturn ret;\n}\nlayout(location = 0) in vec2 v_clip_depth;\nvec4 frag () {\nreturn packDepthToRGBA(v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "#extension GL_EXT_shader_explicit_arithmetic_types_int32: require\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\nlayout(location = 3) in vec4 a_tangent;\n#if USE_INSTANCING\nlayout(location = 6) in vec4 a_matWorld0;\nlayout(location = 7) in vec4 a_matWorld1;\nlayout(location = 8) in vec4 a_matWorld2;\n#if USE_LIGHTMAP\nlayout(location = 9) in vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nlayout(location = 10) in vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nlayout(location = 11) in float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nint getVertexId() {\nreturn gl_VertexIndex;\n}\n#endif\n#if CC_USE_SKINNING\nlayout(location = 4) in u32vec4 a_joints;\nlayout(location = 5) in vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nlayout(set = 2, binding = 4) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nlayout(set = 2, binding = 7) uniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nlayout(set = 2, binding = 8) uniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nlayout(set = 2, binding = 9) uniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nlayout(location = 13) in highp vec4 a_jointAnimInfo;\n#endif\nlayout(set = 2, binding = 3) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(set = 2, binding = 2) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nlayout(set = 2, binding = 6) uniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nlayout(set = 2, binding = 3) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout vec4 In)\n{\nIn = vec4(a_position, 1.0);\n#if CC_USE_MORPH\napplyMorph(In);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In);\n#endif\n}\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(set = 2, binding = 0) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(set = 2, binding = 0) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nvoid CCGetWorldMatrix(out mat4 matWorld)\n{\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\n#else\nmatWorld = cc_matWorld;\n#endif\n}\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\n#if !CC_USE_ACCURATE_FOG\nlayout(location = 0) out float v_fog_factor;\n#endif\nvoid CC_TRANSFER_FOG(vec4 pos) {\n#if !CC_USE_ACCURATE_FOG\nCC_TRANSFER_FOG_BASE(pos, v_fog_factor);\n#endif\n}\n#if USE_VERTEX_COLOR\nlayout(location = 14) in lowp vec4 a_color;\nlayout(location = 1) out lowp vec4 v_color;\n#endif\n#if USE_TEXTURE\nlayout(location = 2) out vec2 v_uv;\nlayout(set = 1, binding = 0) uniform TexCoords {\nvec4 tilingOffset;\n};\n#endif\nvec4 vert () {\nvec4 position;\nCCVertInput(position);\nmat4 matWorld;\nCCGetWorldMatrix(matWorld);\n#if USE_TEXTURE\nv_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw;\n#if SAMPLE_FROM_RT\nv_uv = cc_cameraPos.w > 1.0 ? vec2(v_uv.x, 1.0 - v_uv.y) : v_uv;\n#endif\n#endif\n#if USE_VERTEX_COLOR\nv_color = a_color;\n#endif\nCC_TRANSFER_FOG(matWorld * position);\nreturn cc_matProj * (cc_matView * matWorld) * position;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision highp float;\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = ACESToneMap(color.rgb);\n#endif\ncolor.rgb = sqrt(color.rgb);\nreturn color;\n}\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\nvoid CC_APPLY_FOG_BASE(inout vec4 color, float factor) {\ncolor = vec4(mix(cc_fogColor.rgb, color.rgb, factor), color.a);\n}\n#if !CC_USE_ACCURATE_FOG\nlayout(location = 0) in float v_fog_factor;\n#endif\nvoid CC_APPLY_FOG(inout vec4 color) {\n#if !CC_USE_ACCURATE_FOG\nCC_APPLY_FOG_BASE(color, v_fog_factor);\n#endif\n}\nvoid CC_APPLY_FOG(inout vec4 color, vec3 worldPos) {\n#if CC_USE_ACCURATE_FOG\nfloat factor;\nCC_TRANSFER_FOG_BASE(vec4(worldPos, 1.0), factor);\n#else\nfloat factor = v_fog_factor;\n#endif\nCC_APPLY_FOG_BASE(color, factor);\n}\n#if USE_ALPHA_TEST\n#endif\n#if USE_TEXTURE\nlayout(location = 2) in vec2 v_uv;\nlayout(set = 1, binding = 2) uniform sampler2D mainTexture;\n#endif\nlayout(set = 1, binding = 1) uniform Constant {\nvec4 mainColor;\nvec4 colorScaleAndCutoff;\n};\n#if USE_VERTEX_COLOR\nlayout(location = 1) in lowp vec4 v_color;\n#endif\nvec4 frag () {\nvec4 o = mainColor;\no.rgb *= colorScaleAndCutoff.xyz;\n#if USE_VERTEX_COLOR\no.rgb *= SRGBToLinear(v_color.rgb);\no.a *= v_color.a;\n#endif\n#if USE_TEXTURE\nvec4 texColor = texture(mainTexture, v_uv);\ntexColor.rgb = SRGBToLinear(texColor.rgb);\no *= texColor;\n#endif\n#if USE_ALPHA_TEST\nif (o.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard;\n#endif\nCC_APPLY_FOG(o);\nreturn CCFragOutput(o);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "#extension GL_EXT_shader_explicit_arithmetic_types_int32: require\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\nlayout(location = 3) in vec4 a_tangent;\n#if USE_INSTANCING\nlayout(location = 6) in vec4 a_matWorld0;\nlayout(location = 7) in vec4 a_matWorld1;\nlayout(location = 8) in vec4 a_matWorld2;\n#if USE_LIGHTMAP\nlayout(location = 9) in vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nlayout(location = 10) in vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nlayout(location = 11) in float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nint getVertexId() {\nreturn gl_VertexIndex;\n}\n#endif\n#if CC_USE_SKINNING\nlayout(location = 4) in u32vec4 a_joints;\nlayout(location = 5) in vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nlayout(set = 2, binding = 4) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nlayout(set = 2, binding = 7) uniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nlayout(set = 2, binding = 8) uniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nlayout(set = 2, binding = 9) uniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nlayout(location = 13) in highp vec4 a_jointAnimInfo;\n#endif\nlayout(set = 2, binding = 3) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(set = 2, binding = 2) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nlayout(set = 2, binding = 6) uniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nlayout(set = 2, binding = 3) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(location = 0) out vec2 v_uv;\nvoid main () {\nStandardVertInput In;\nCCVertInput(In);\nIn.position.xy = cc_cameraPos.w == 0.0 ? vec2(In.position.xy.x, -In.position.xy.y) : In.position.xy;\ngl_Position = In.position;\ngl_Position.y = gl_Position.y;\nv_uv = a_texCoord;\n}", - "frag": "\nprecision highp float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nlayout(location = 0) in vec2 v_uv;\nlayout(set = 1, binding = 0) uniform BloomUBO {\nmediump vec4 texSize;\n};\nlayout(set = 1, binding = 1) uniform sampler2D outputResultMap;\nlayout(location = 0) out vec4 fragColor;\nfloat luminance(vec3 color) {\nreturn dot(color, vec3(0.2126, 0.7152, 0.0722));\n}\nvoid main() {\nvec3 color = texture(outputResultMap, v_uv).xyz;\nif (luminance(SRGBToLinear(color)) > texSize.z) {\nfragColor = vec4(color, 1.0);\n} else {\nfragColor = vec4(0.0, 0.0, 0.0, 1.0);\n}\n}", - }, - { - "vert": "#extension GL_EXT_shader_explicit_arithmetic_types_int32: require\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\nlayout(location = 3) in vec4 a_tangent;\n#if USE_INSTANCING\nlayout(location = 6) in vec4 a_matWorld0;\nlayout(location = 7) in vec4 a_matWorld1;\nlayout(location = 8) in vec4 a_matWorld2;\n#if USE_LIGHTMAP\nlayout(location = 9) in vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nlayout(location = 10) in vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nlayout(location = 11) in float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nint getVertexId() {\nreturn gl_VertexIndex;\n}\n#endif\n#if CC_USE_SKINNING\nlayout(location = 4) in u32vec4 a_joints;\nlayout(location = 5) in vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nlayout(set = 2, binding = 4) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nlayout(set = 2, binding = 7) uniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nlayout(set = 2, binding = 8) uniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nlayout(set = 2, binding = 9) uniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nlayout(location = 13) in highp vec4 a_jointAnimInfo;\n#endif\nlayout(set = 2, binding = 3) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(set = 2, binding = 2) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nlayout(set = 2, binding = 6) uniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nlayout(set = 2, binding = 3) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(location = 0) out vec2 v_uv;\nvoid main () {\nStandardVertInput In;\nCCVertInput(In);\nIn.position.xy = cc_cameraPos.w == 0.0 ? vec2(In.position.xy.x, -In.position.xy.y) : In.position.xy;\ngl_Position = In.position;\ngl_Position.y = gl_Position.y;\nv_uv = a_texCoord;\n}", - "frag": "\nprecision highp float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(location = 0) in vec2 v_uv;\nlayout(set = 1, binding = 0) uniform BloomUBO {\nmediump vec4 texSize;\n};\nlayout(set = 1, binding = 1) uniform sampler2D bloomTexture;\nlayout(location = 0) out vec4 fragColor;\nvec3 downsample4taps(vec2 uv, vec2 halfpixel) {\nvec3 sum = texture(bloomTexture, uv + vec2(-halfpixel.x, halfpixel.y)).xyz;\nsum += texture(bloomTexture, uv + vec2(halfpixel.x, halfpixel.y)).xyz;\nsum += texture(bloomTexture, uv + vec2(halfpixel.x, -halfpixel.y)).xyz;\nsum += texture(bloomTexture, uv + vec2(-halfpixel.x, -halfpixel.y)).xyz;\nreturn sum / 4.0;\n}\nvoid main()\n{\nvec3 result = downsample4taps(v_uv, 1.0 / texSize.xy).rgb;\nfragColor = vec4(result, 1.0);\n}", - }, - { - "vert": "#extension GL_EXT_shader_explicit_arithmetic_types_int32: require\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\nlayout(location = 3) in vec4 a_tangent;\n#if USE_INSTANCING\nlayout(location = 6) in vec4 a_matWorld0;\nlayout(location = 7) in vec4 a_matWorld1;\nlayout(location = 8) in vec4 a_matWorld2;\n#if USE_LIGHTMAP\nlayout(location = 9) in vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nlayout(location = 10) in vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nlayout(location = 11) in float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nint getVertexId() {\nreturn gl_VertexIndex;\n}\n#endif\n#if CC_USE_SKINNING\nlayout(location = 4) in u32vec4 a_joints;\nlayout(location = 5) in vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nlayout(set = 2, binding = 4) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nlayout(set = 2, binding = 7) uniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nlayout(set = 2, binding = 8) uniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nlayout(set = 2, binding = 9) uniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nlayout(location = 13) in highp vec4 a_jointAnimInfo;\n#endif\nlayout(set = 2, binding = 3) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(set = 2, binding = 2) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nlayout(set = 2, binding = 6) uniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nlayout(set = 2, binding = 3) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(location = 0) out vec2 v_uv;\nvoid main () {\nStandardVertInput In;\nCCVertInput(In);\nIn.position.xy = cc_cameraPos.w == 0.0 ? vec2(In.position.xy.x, -In.position.xy.y) : In.position.xy;\ngl_Position = In.position;\ngl_Position.y = gl_Position.y;\nv_uv = a_texCoord;\n}", - "frag": "\nprecision highp float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(location = 0) in vec2 v_uv;\nlayout(set = 1, binding = 0) uniform BloomUBO {\nmediump vec4 texSize;\n};\nlayout(set = 1, binding = 1) uniform sampler2D bloomTexture;\nlayout(location = 0) out vec4 fragColor;\nvec3 upsample4taps(vec2 uv, vec2 halfpixel) {\nvec3 sum = texture(bloomTexture, uv + vec2(-halfpixel.x, halfpixel.y)).xyz;\nsum += texture(bloomTexture, uv + vec2(halfpixel.x, halfpixel.y)).xyz;\nsum += texture(bloomTexture, uv + vec2(halfpixel.x, -halfpixel.y)).xyz;\nsum += texture(bloomTexture, uv + vec2(-halfpixel.x, -halfpixel.y)).xyz;\nreturn sum / 4.0;\n}\nvoid main() {\nvec3 result = upsample4taps(v_uv, 0.5 / texSize.xy).rgb;\nfragColor = vec4(result, 1.0);\n}", - }, - { - "vert": "#extension GL_EXT_shader_explicit_arithmetic_types_int32: require\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\nlayout(location = 3) in vec4 a_tangent;\n#if USE_INSTANCING\nlayout(location = 6) in vec4 a_matWorld0;\nlayout(location = 7) in vec4 a_matWorld1;\nlayout(location = 8) in vec4 a_matWorld2;\n#if USE_LIGHTMAP\nlayout(location = 9) in vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nlayout(location = 10) in vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nlayout(location = 11) in float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nint getVertexId() {\nreturn gl_VertexIndex;\n}\n#endif\n#if CC_USE_SKINNING\nlayout(location = 4) in u32vec4 a_joints;\nlayout(location = 5) in vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nlayout(set = 2, binding = 4) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nlayout(set = 2, binding = 7) uniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nlayout(set = 2, binding = 8) uniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nlayout(set = 2, binding = 9) uniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nlayout(location = 13) in highp vec4 a_jointAnimInfo;\n#endif\nlayout(set = 2, binding = 3) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(set = 2, binding = 2) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nlayout(set = 2, binding = 6) uniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nlayout(set = 2, binding = 3) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(location = 0) out vec2 v_uv;\nvoid main () {\nStandardVertInput In;\nCCVertInput(In);\nIn.position.xy = cc_cameraPos.w == 0.0 ? vec2(In.position.xy.x, -In.position.xy.y) : In.position.xy;\ngl_Position = In.position;\ngl_Position.y = gl_Position.y;\nv_uv = a_texCoord;\n}", - "frag": "\nprecision highp float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(location = 0) in vec2 v_uv;\nlayout(set = 1, binding = 0) uniform BloomUBO {\nmediump vec4 texSize;\n};\nlayout(set = 1, binding = 1) uniform sampler2D outputResultMap;\nlayout(set = 1, binding = 2) uniform sampler2D bloomTexture;\nlayout(location = 0) out vec4 fragColor;\nvoid main() {\nvec4 hdrColor = texture(outputResultMap, v_uv);\nvec3 bloomColor = texture(bloomTexture, v_uv).rgb;\nvec3 result = hdrColor.rgb + bloomColor * texSize.w * hdrColor.a;\nfragColor = vec4(result, hdrColor.a);\n}", - } - ], - [ - { - "vert": "\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\nlayout(location = 3) in vec4 a_tangent;\n#if USE_INSTANCING\nlayout(location = 6) in vec4 a_matWorld0;\nlayout(location = 7) in vec4 a_matWorld1;\nlayout(location = 8) in vec4 a_matWorld2;\n#if USE_LIGHTMAP\nlayout(location = 9) in vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nlayout(location = 10) in vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nlayout(location = 11) in float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\n#endif\n#if CC_USE_SKINNING\nlayout(location = 4) in u32vec4 a_joints;\nlayout(location = 5) in vec4 a_weights;\n#endif\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(location = 0) out vec2 v_uv;\nvoid main () {\nvec4 position;\nposition = vec4(a_position, 1.0);\nposition.xy = cc_cameraPos.w == 0.0 ? vec2(position.xy.x, -position.xy.y) : position.xy;\ngl_Position = vec4(position.x, position.y, 1.0, 1.0);\nv_uv = a_texCoord;\n}", - "frag": "\nprecision highp float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nlayout(set = 0, binding = 2) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\nhighp float unpackHighpData (float mainPart, float modPart) {\nhighp float data = mainPart;\nreturn data + modPart;\n}\nhighp float unpackHighpData (float mainPart, float modPart, const float modValue) {\nhighp float data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nhighp vec2 unpackHighpData (vec2 mainPart, vec2 modPart) {\nhighp vec2 data = mainPart;\nreturn data + modPart;\n}\nhighp vec2 unpackHighpData (vec2 mainPart, vec2 modPart, const float modValue) {\nhighp vec2 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nhighp vec3 unpackHighpData (vec3 mainPart, vec3 modPart) {\nhighp vec3 data = mainPart;\nreturn data + modPart;\n}\nhighp vec3 unpackHighpData (vec3 mainPart, vec3 modPart, const float modValue) {\nhighp vec3 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\nhighp vec4 unpackHighpData (vec4 mainPart, vec4 modPart) {\nhighp vec4 data = mainPart;\nreturn data + modPart;\n}\nhighp vec4 unpackHighpData (vec4 mainPart, vec4 modPart, const float modValue) {\nhighp vec4 data = mainPart * modValue;\nreturn data + modPart * modValue;\n}\n#if USE_BATCHING\nlayout(set = 2, binding = 0) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(set = 2, binding = 0) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nfloat CCGetLinearDepthFromViewSpace(vec3 viewPos) {\nfloat dist = length(viewPos);\nreturn (dist - cc_shadowNFLSInfo.x) / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x);\n}\nfloat CCGetLinearDepth(vec3 worldPos) {\nvec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0);\nreturn CCGetLinearDepthFromViewSpace(viewStartPos.xyz);\n}\n#if CC_RECEIVE_SHADOW\nlayout(set = 0, binding = 3) uniform highp sampler2D cc_shadowMap;\nlayout(set = 0, binding = 5) uniform highp sampler2D cc_spotLightingMap;\nvec4 ApplyShadowDepthBias_FaceNormal(vec4 shadowPos, vec3 worldNormal, float normalBias)\n{\nvec4 newShadowPos = shadowPos;\nif(normalBias > 0.0001)\n{\nvec4 viewNormal = cc_matLightView * vec4(worldNormal, 0.0);\nif(viewNormal.z < 0.1)\nnewShadowPos.xy += viewNormal.xy * cc_shadowProjInfo.xy * normalBias * clamp(viewNormal.z, 0.001, 0.1);\n}\nreturn newShadowPos;\n}\nvec4 ApplyShadowDepthBias_Perspective(vec4 shadowPos, float viewspaceDepthBias)\n{\nvec3 viewSpacePos;\nviewSpacePos.xy = shadowPos.xy * cc_shadowProjInfo.zw;\nviewSpacePos.z = shadowPos.z * cc_shadowInvProjDepthInfo.x + shadowPos.w * cc_shadowInvProjDepthInfo.y;\nviewSpacePos.xyz += cc_shadowProjDepthInfo.z * normalize(viewSpacePos.xyz) * viewspaceDepthBias;\nvec4 clipSpacePos;\nclipSpacePos.xy = viewSpacePos.xy * cc_shadowProjInfo.xy;\nclipSpacePos.zw = viewSpacePos.z * cc_shadowProjDepthInfo.xz + vec2(cc_shadowProjDepthInfo.y, 0.0);\nif (cc_shadowNFLSInfo.z > 0.000001) {\nclipSpacePos.z = CCGetLinearDepthFromViewSpace(viewSpacePos.xyz);\nclipSpacePos.z = (clipSpacePos.z * 2.0 - 1.0) * clipSpacePos.w;\n}\nreturn clipSpacePos;\n}\nvec4 ApplyShadowDepthBias_Orthographic(vec4 shadowPos, float viewspaceDepthBias)\n{\nfloat coeffA = cc_shadowProjDepthInfo.x;\nfloat coeffB = cc_shadowProjDepthInfo.y;\nfloat viewSpacePos_z = (shadowPos.z - coeffB) / coeffA;\nviewSpacePos_z += viewspaceDepthBias;\nvec4 result = shadowPos;\nresult.z = viewSpacePos_z * coeffA + coeffB;\nreturn result;\n}\nfloat CCGetShadowFactorHard (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture(cc_shadowMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n} else {\nclosestDepth = texture(cc_shadowMap, clipPos.xy).x;\n}\nshadow = step(clipPos.z, closestDepth);\nreturn shadow;\n}\nfloat CCGetShadowFactorSoft (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x);\nblock1 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)).x);\nblock2 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)).x);\nblock3 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetShadowFactorSoft2X (vec4 shadowPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat offsetDepth = clipPos.z;\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock4 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock5 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock6 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock7 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock8 = step(offsetDepth, dot(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)).x);\nblock1 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)).x);\nblock2 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)).x);\nblock3 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)).x);\nblock4 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x);\nblock5 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)).x);\nblock6 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)).x);\nblock7 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)).x);\nblock8 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCGetSpotLightShadowFactorHard (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat shadow = 0.0;\nfloat closestDepth = 0.0;\nfloat depth = clipPos.z;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nclosestDepth = dot(texture(cc_spotLightingMap, clipPos.xy), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0));\n} else {\nclosestDepth = texture(cc_spotLightingMap, clipPos.xy).x;\n}\nshadow = step(depth, closestDepth);\nreturn shadow;\n}\nfloat CCGetSpotLightShadowFactorSoft (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nvec2 oneTap = 1.0 / cc_shadowWHPBInfo.xy;\nvec2 clipPos_offset = clipPos.xy + oneTap;\nfloat block0, block1, block2, block3;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x);\nblock1 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)).x);\nblock2 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)).x);\nblock3 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * cc_shadowWHPBInfo.x;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block2, block3, coefX);\nfloat coefY = mod(clipPos.y, oneTap.y) * cc_shadowWHPBInfo.y;\nreturn mix(resultX, resultY, coefY);\n}\nfloat CCGetSpotLightShadowFactorSoft2X (vec4 shadowPos, vec3 worldPos, float bias) {\nvec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias);\nvec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5;\nif (clipPos.x < 0.0 || clipPos.x > 1.0 ||\nclipPos.y < 0.0 || clipPos.y > 1.0 ||\nclipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; }\nclipPos.xy = cc_cameraPos.w == 1.0 ? vec2(clipPos.xy.x, 1.0 - clipPos.xy.y) : clipPos.xy;\nfloat depth = 0.0;\nif (cc_shadowNFLSInfo.z > 0.000001) {\ndepth = CCGetLinearDepth(worldPos);\n} else {\ndepth = clipPos.z;\n}\nvec2 mapSize = cc_shadowWHPBInfo.xy;\nvec2 oneTap = 1.0 / mapSize;\nfloat clipPos_offset_L = clipPos.x - oneTap.x;\nfloat clipPos_offset_R = clipPos.x + oneTap.x;\nfloat clipPos_offset_U = clipPos.y - oneTap.y;\nfloat clipPos_offset_D = clipPos.y + oneTap.y;\nfloat block0, block1, block2, block3, block4, block5, block6, block7, block8;\nif (cc_shadowLPNNInfo.y > 0.000001) {\nblock0 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock1 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock2 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock3 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock4 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock5 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock6 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock7 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\nblock8 = step(depth, dot(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)), vec4(1.0, 1.0 / 255.0, 1.0 / 65025.0, 1.0 / 16581375.0)));\n} else {\nblock0 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)).x);\nblock1 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)).x);\nblock2 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)).x);\nblock3 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)).x);\nblock4 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x);\nblock5 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)).x);\nblock6 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)).x);\nblock7 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)).x);\nblock8 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)).x);\n}\nfloat coefX = mod(clipPos.x, oneTap.x) * mapSize.x;\nfloat coefY = mod(clipPos.y, oneTap.y) * mapSize.y;\nfloat shadow = 0.0;\nfloat resultX = mix(block0, block1, coefX);\nfloat resultY = mix(block3, block4, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block1, block2, coefX);\nresultY = mix(block4, block5, coefX);\nshadow += mix(resultX , resultY, coefY);\nresultX = mix(block3, block4, coefX);\nresultY = mix(block6, block7, coefX);\nshadow += mix(resultX, resultY, coefY);\nresultX = mix(block4, block5, coefX);\nresultY = mix(block7, block8, coefX);\nshadow += mix(resultX, resultY, coefY);\nreturn shadow * 0.25;\n}\nfloat CCSpotShadowFactorBase(vec4 shadowPos, vec3 worldPos, vec2 shadowBias)\n{\nfloat pcf = cc_shadowWHPBInfo.z;\nif (pcf > 1.9) {\nreturn CCGetSpotLightShadowFactorSoft2X(shadowPos, worldPos, shadowBias.x);\n}else if (pcf > 0.9) {\nreturn CCGetSpotLightShadowFactorSoft(shadowPos, worldPos, shadowBias.x);\n}else {\nreturn CCGetSpotLightShadowFactorHard(shadowPos, worldPos, shadowBias.x);\n}\n}\nfloat CCShadowFactorBase(vec4 shadowPos, vec3 N, vec2 shadowBias)\n{\nfloat realtimeShadow = 1.0;\nvec4 pos = ApplyShadowDepthBias_FaceNormal(shadowPos, N, shadowBias.y);\nfloat pcf = cc_shadowWHPBInfo.z;\nif (pcf > 1.9) {\nrealtimeShadow = CCGetShadowFactorSoft2X(pos, shadowBias.x);\n}else if (pcf > 0.9) {\nrealtimeShadow = CCGetShadowFactorSoft(pos, shadowBias.x);\n}else {\nrealtimeShadow = CCGetShadowFactorHard(pos, shadowBias.x);\n}\nreturn mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w);\n}\n#endif\n#if CC_USE_IBL\nlayout(set = 0, binding = 4) uniform samplerCube cc_environment;\nvec4 fragTextureLod (sampler2D tex, vec2 coord, float lod) {\nreturn textureLod(tex, coord, lod);\n}\nvec4 fragTextureLod (samplerCube tex, vec3 coord, float lod) {\nreturn textureLod(tex, coord, lod);\n}\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(1.1, rgbe.a * 255.0 - 128.0);\n}\n#if CC_USE_DIFFUSEMAP\nlayout(set = 0, binding = 6) uniform samplerCube cc_diffuseMap;\n#endif\n#endif\nfloat GGXMobile (float roughness, float NoH, vec3 H, vec3 N) {\nvec3 NxH = cross(N, H);\nfloat OneMinusNoHSqr = dot(NxH, NxH);\nfloat a = roughness * roughness;\nfloat n = NoH * a;\nfloat p = a / (OneMinusNoHSqr + n * n);\nreturn p * p;\n}\nfloat CalcSpecular (float roughness, float NoH, vec3 H, vec3 N) {\nreturn (roughness * 0.25 + 0.25) * GGXMobile(roughness, NoH, H, N);\n}\nvec3 BRDFApprox (vec3 specular, float roughness, float NoV) {\nconst vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022);\nconst vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04);\nvec4 r = roughness * c0 + c1;\nfloat a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y;\nvec2 AB = vec2(-1.04, 1.04) * a004 + r.zw;\nAB.y *= clamp(50.0 * specular.g, 0.0, 1.0);\nreturn specular * AB.x + AB.y;\n}\n#if USE_REFLECTION_DENOISE\nvec3 GetEnvReflectionWithMipFiltering(vec3 R, float roughness, float mipCount, float denoiseIntensity) {\n#if CC_USE_IBL\nfloat mip = roughness * mipCount;\nfloat delta = (dot(dFdx(R), dFdy(R))) * 1000.0;\nfloat mipBias = mix(0.0, 5.0, clamp(delta, 0.0, 1.0));\nvec4 biased = fragTextureLod(cc_environment, R, mip + mipBias);\nvec4 filtered = texture(cc_environment, R);\n#if CC_USE_IBL == 2\nbiased.rgb = unpackRGBE(biased);\nfiltered.rgb = unpackRGBE(filtered);\n#else\nbiased.rgb = SRGBToLinear(biased.rgb);\nfiltered.rgb = SRGBToLinear(filtered.rgb);\n#endif\nreturn mix(biased.rgb, filtered.rgb, denoiseIntensity);\n#else\nreturn vec3(0.0, 0.0, 0.0);\n#endif\n}\n#endif\nstruct StandardSurface {\nvec4 albedo;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nvec3 position, position_fract_part;\n#else\nvec3 position;\n#endif\nvec3 normal;\nvec3 emissive;\nvec3 lightmap;\nfloat lightmap_test;\nfloat roughness;\nfloat metallic;\nfloat occlusion;\n#if CC_RECEIVE_SHADOW\nvec2 shadowBias;\n#endif\n};\nvec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.0);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 L = normalize(-cc_mainLitDir.xyz);\nvec3 H = normalize(L + V);\nfloat NH = max(dot(N, H), 0.0);\nfloat NL = max(dot(N, L), 0.0);\nvec3 finalColor = NL * cc_mainLitColor.rgb * cc_mainLitColor.w;\nvec3 diffuseContrib = diffuse;\n#if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD\nif (s.lightmap_test > 0.0001) {\nfinalColor = s.lightmap.rgb;\n}\n#else\ndiffuseContrib /= PI;\n#endif\nvec3 specularContrib = specular * CalcSpecular(s.roughness, NH, H, N);\nvec3 dirlightContrib = (diffuseContrib + specularContrib);\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (NL > 0.0 && cc_mainLitDir.w > 0.0) {\nshadow = CCShadowFactorBase(shadowPos, N, s.shadowBias);\n}\n#endif\ndirlightContrib *= shadow;\nfinalColor *= dirlightContrib;\nfloat fAmb = 0.5 - N.y * 0.5;\nvec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb);\n#if CC_USE_IBL\n#if CC_USE_DIFFUSEMAP\nvec4 diffuseMap = texture(cc_diffuseMap, N);\n#if CC_USE_DIFFUSEMAP == 2\nambDiff = unpackRGBE(diffuseMap);\n#else\nambDiff = SRGBToLinear(diffuseMap.rgb);\n#endif\n#endif\nvec3 R = normalize(reflect(-V, N));\n#if USE_REFLECTION_DENOISE\nvec3 env = GetEnvReflectionWithMipFiltering(R, s.roughness, cc_ambientGround.w, 0.6);\n#else\nvec4 envmap = fragTextureLod(cc_environment, R, s.roughness * cc_ambientGround.w);\n#if CC_USE_IBL == 2\nvec3 env = unpackRGBE(envmap);\n#else\nvec3 env = SRGBToLinear(envmap.rgb);\n#endif\n#endif\nfinalColor += env * cc_ambientSky.w * specular * s.occlusion;\n#endif\nfinalColor += ambDiff.rgb * cc_ambientSky.w * diffuse * s.occlusion;\nfinalColor += s.emissive;\nreturn vec4(finalColor, s.albedo.a);\n}\n#if CC_PIPELINE_TYPE == 0\n#define LIGHTS_PER_PASS 1\n#else\n#define LIGHTS_PER_PASS 10\n#endif\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0\nlayout(set = 2, binding = 1) uniform CCForwardLight {\nhighp vec4 cc_lightPos[LIGHTS_PER_PASS];\nvec4 cc_lightColor[LIGHTS_PER_PASS];\nvec4 cc_lightSizeRangeAngle[LIGHTS_PER_PASS];\nvec4 cc_lightDir[LIGHTS_PER_PASS];\n};\n#endif\nfloat SmoothDistAtt (float distSqr, float invSqrAttRadius) {\nfloat factor = distSqr * invSqrAttRadius;\nfloat smoothFactor = clamp(1.0 - factor * factor, 0.0, 1.0);\nreturn smoothFactor * smoothFactor;\n}\nfloat GetDistAtt (float distSqr, float invSqrAttRadius) {\nfloat attenuation = 1.0 / max(distSqr, 0.01*0.01);\nattenuation *= SmoothDistAtt(distSqr , invSqrAttRadius);\nreturn attenuation;\n}\nfloat GetAngleAtt (vec3 L, vec3 litDir, float litAngleScale, float litAngleOffset) {\nfloat cd = dot(litDir, L);\nfloat attenuation = clamp(cd * litAngleScale + litAngleOffset, 0.0, 1.0);\nreturn (attenuation * attenuation);\n}\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0\nvec4 CCStandardShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / PI;\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.0);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nint numLights = CC_PIPELINE_TYPE == 0 ? LIGHTS_PER_PASS : int(cc_lightDir[0].w);\nfor (int i = 0; i < LIGHTS_PER_PASS; i++) {\nif (i >= numLights) break;\nvec3 SLU = cc_lightPos[i].xyz - position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.0);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = cc_lightSizeRangeAngle[i].x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = PI * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(cc_lightSizeRangeAngle[i].y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (cc_lightPos[i].w > 0.0) {\nfloat cosInner = max(dot(-cc_lightDir[i].xyz, SL), 0.01);\nfloat cosOuter = cc_lightSizeRangeAngle[i].z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -cc_lightDir[i].xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = cc_lightColor[i].rgb;\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (cc_lightPos[i].w > 0.0 && cc_lightSizeRangeAngle[i].w > 0.0) {\nshadow = CCSpotShadowFactorBase(shadowPos, position, s.shadowBias);\n}\n#endif\nlightColor *= shadow;\nfinalColor += SNL * lightColor * cc_lightColor[i].w * illum * att * (diffuseContrib + lspec);\n}\nreturn vec4(finalColor, 0.0);\n}\n#endif\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1\nlayout(set = 1, binding = 4) readonly buffer b_ccLightsBuffer { vec4 b_ccLights[]; };\nlayout(set = 1, binding = 5) readonly buffer b_clusterLightIndicesBuffer { uint b_clusterLightIndices[]; };\nlayout(set = 1, binding = 6) readonly buffer b_clusterLightGridBuffer { uvec4 b_clusterLightGrid[]; };\nstruct CCLight\n{\nvec4 cc_lightPos;\nvec4 cc_lightColor;\nvec4 cc_lightSizeRangeAngle;\nvec4 cc_lightDir;\n};\nstruct Cluster\n{\nvec3 minBounds;\nvec3 maxBounds;\n};\nstruct LightGrid\n{\nuint offset;\nuint ccLights;\n};\nCCLight getCCLight(uint i)\n{\nCCLight light;\nlight.cc_lightPos = b_ccLights[4u * i + 0u];\nlight.cc_lightColor = b_ccLights[4u * i + 1u];\nlight.cc_lightSizeRangeAngle = b_ccLights[4u * i + 2u];\nlight.cc_lightDir = b_ccLights[4u * i + 3u];\nreturn light;\n}\nLightGrid getLightGrid(uint cluster)\n{\nuvec4 gridvec = b_clusterLightGrid[cluster];\nLightGrid grid;\ngrid.offset = gridvec.x;\ngrid.ccLights = gridvec.y;\nreturn grid;\n}\nuint getGridLightIndex(uint start, uint offset)\n{\nreturn b_clusterLightIndices[start + offset];\n}\nuint getClusterZIndex(vec4 worldPos)\n{\nfloat scale = float(24) / log(cc_nearFar.y / cc_nearFar.x);\nfloat bias = -(float(24) * log(cc_nearFar.x) / log(cc_nearFar.y / cc_nearFar.x));\nfloat eyeDepth = -(cc_matView * worldPos).z;\nuint zIndex = uint(max(log(eyeDepth) * scale + bias, 0.0));\nreturn zIndex;\n}\nuint getClusterIndex(vec4 fragCoord, vec4 worldPos)\n{\nuint zIndex = getClusterZIndex(worldPos);\nfloat clusterSizeX = ceil(cc_viewPort.z / float(16));\nfloat clusterSizeY = ceil(cc_viewPort.w / float(8));\nuvec3 indices = uvec3(uvec2(fragCoord.xy / vec2(clusterSizeX, clusterSizeY)), zIndex);\nuint cluster = (16u * 8u) * indices.z + 16u * indices.y + indices.x;\nreturn cluster;\n}\nvec4 CCClusterShadingAdditive (StandardSurface s, vec4 shadowPos) {\nvec3 diffuse = s.albedo.rgb * (1.0 - s.metallic);\nvec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic);\nvec3 diffuseContrib = diffuse / PI;\nvec3 position;\n#if CC_PLATFORM_ANDROID_AND_WEBGL && CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES\nposition = unpackHighpData(s.position, s.position_fract_part);\n#else\nposition = s.position;\n#endif\nvec3 N = normalize(s.normal);\nvec3 V = normalize(cc_cameraPos.xyz - position);\nfloat NV = max(abs(dot(N, V)), 0.001);\nspecular = BRDFApprox(specular, s.roughness, NV);\nvec3 finalColor = vec3(0.0);\nuint cluster = getClusterIndex(gl_FragCoord, vec4(position, 1.0));\nLightGrid grid = getLightGrid(cluster);\nuint numLights = grid.ccLights;\nfor (uint i = 0u; i < 100u; i++) {\nif (i >= numLights) break;\nuint lightIndex = getGridLightIndex(grid.offset, i);\nCCLight light = getCCLight(lightIndex);\nvec3 SLU = light.cc_lightPos.xyz - position;\nvec3 SL = normalize(SLU);\nvec3 SH = normalize(SL + V);\nfloat SNL = max(dot(N, SL), 0.001);\nfloat SNH = max(dot(N, SH), 0.0);\nfloat distSqr = dot(SLU, SLU);\nfloat litRadius = light.cc_lightSizeRangeAngle.x;\nfloat litRadiusSqr = litRadius * litRadius;\nfloat illum = PI * (litRadiusSqr / max(litRadiusSqr , distSqr));\nfloat attRadiusSqrInv = 1.0 / max(light.cc_lightSizeRangeAngle.y, 0.01);\nattRadiusSqrInv *= attRadiusSqrInv;\nfloat att = GetDistAtt(distSqr, attRadiusSqrInv);\nvec3 lspec = specular * CalcSpecular(s.roughness, SNH, SH, N);\nif (light.cc_lightPos.w > 0.0) {\nfloat cosInner = max(dot(-light.cc_lightDir.xyz, SL), 0.01);\nfloat cosOuter = light.cc_lightSizeRangeAngle.z;\nfloat litAngleScale = 1.0 / max(0.001, cosInner - cosOuter);\nfloat litAngleOffset = -cosOuter * litAngleScale;\natt *= GetAngleAtt(SL, -light.cc_lightDir.xyz, litAngleScale, litAngleOffset);\n}\nvec3 lightColor = light.cc_lightColor.rgb;\nfloat shadow = 1.0;\n#if CC_RECEIVE_SHADOW\nif (light.cc_lightPos.w > 0.0) {\nshadow = CCSpotShadowFactorBase(shadowPos, position, s.shadowBias);\n}\n#endif\nlightColor *= shadow;\nfinalColor += SNL * lightColor * light.cc_lightColor.w * illum * att * (diffuseContrib + lspec);\n}\nreturn vec4(finalColor, 0.0);\n}\n#endif\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = ACESToneMap(color.rgb);\n#endif\ncolor.rgb = sqrt(color.rgb);\nreturn color;\n}\nfloat LinearFog(vec4 pos) {\nvec4 wPos = pos;\nfloat cam_dis = distance(cc_cameraPos, wPos);\nfloat fogStart = cc_fogBase.x;\nfloat fogEnd = cc_fogBase.y;\nreturn clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.);\n}\nfloat ExpFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * fogDensity);\nreturn f;\n}\nfloat ExpSquaredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat fogStart = cc_fogBase.x;\nfloat fogDensity = cc_fogBase.z;\nfloat cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.;\nfloat f = exp(-cam_dis * cam_dis * fogDensity * fogDensity);\nreturn f;\n}\nfloat LayeredFog(vec4 pos) {\nvec4 wPos = pos;\nfloat fogAtten = cc_fogAdd.z;\nfloat _FogTop = cc_fogAdd.x;\nfloat _FogRange = cc_fogAdd.y;\nvec3 camWorldProj = cc_cameraPos.xyz;\ncamWorldProj.y = 0.;\nvec3 worldPosProj = wPos.xyz;\nworldPosProj.y = 0.;\nfloat fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0;\nfloat fDeltaY, fDensityIntegral;\nif (cc_cameraPos.y > _FogTop) {\nif (wPos.y < _FogTop) {\nfDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0;\nfDensityIntegral = fDeltaY * fDeltaY * 0.5;\n} else {\nfDeltaY = 0.;\nfDensityIntegral = 0.;\n}\n} else {\nif (wPos.y < _FogTop) {\nfloat fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfloat fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.;\nfDeltaY = abs(fDeltaA - fDeltaB);\nfDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5));\n} else {\nfDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.;\nfDensityIntegral = abs(fDeltaY * fDeltaY * 0.5);\n}\n}\nfloat fDensity;\nif (fDeltaY != 0.) {\nfDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral;\n} else {\nfDensity = 0.;\n}\nfloat f = exp(-fDensity);\nreturn f;\n}\nvoid CC_TRANSFER_FOG_BASE(vec4 pos, out float factor)\n{\n#if CC_USE_FOG == 0\nfactor = LinearFog(pos);\n#elif CC_USE_FOG == 1\nfactor = ExpFog(pos);\n#elif CC_USE_FOG == 2\nfactor = ExpSquaredFog(pos);\n#elif CC_USE_FOG == 3\nfactor = LayeredFog(pos);\n#else\nfactor = 1.0;\n#endif\n}\nvoid CC_APPLY_FOG_BASE(inout vec4 color, float factor) {\ncolor = vec4(mix(cc_fogColor.rgb, color.rgb, factor), color.a);\n}\nvec2 signNotZero(vec2 v) {\nreturn vec2((v.x >= 0.0) ? +1.0 : -1.0, (v.y >= 0.0) ? +1.0 : -1.0);\n}\nvec3 oct_to_float32x3(vec2 e) {\nvec3 v = vec3(e.xy, 1.0 - abs(e.x) - abs(e.y));\nif (v.z < 0.0) v.xy = (1.0 - abs(v.yx)) * signNotZero(v.xy);\nreturn normalize(v);\n}\nvec4 screen2WS(vec3 coord) {\nvec3 ndc = vec3(\n2.0 * (coord.x - cc_viewPort.x) / cc_viewPort.z - 1.0,\n2.0 * (coord.y - cc_viewPort.y) / cc_viewPort.w - 1.0,\ncoord.z);\nvec4 world = ((cc_matViewProjInv) * (vec4(ndc, 1.0)));\nworld = world / world.w;\nreturn world;\n}\nlayout(location = 0) in vec2 v_uv;\n#if CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT\nlayout(set = 1, binding = 0, input_attachment_index = 0) uniform subpassInput gbuffer_albedoMap;\nlayout(set = 1, binding = 1, input_attachment_index = 1) uniform subpassInput gbuffer_normalMap;\nlayout(set = 1, binding = 2, input_attachment_index = 2) uniform subpassInput gbuffer_emissiveMap;\n#else\nlayout(set = 1, binding = 0) uniform sampler2D gbuffer_albedoMap;\nlayout(set = 1, binding = 1) uniform sampler2D gbuffer_normalMap;\nlayout(set = 1, binding = 2) uniform sampler2D gbuffer_emissiveMap;\n#endif\nlayout(set = 1, binding = 3) uniform sampler2D depth_stencil;\n#if !CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT || __VERSION__ >= 450\nlayout(location = 0) out vec4 fragColor;\n#endif\nvoid main () {\nStandardSurface s;\n#if CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT\nvec4 albedoMap = subpassLoad(gbuffer_albedoMap);\nvec4 normalMap = subpassLoad(gbuffer_normalMap);\nvec4 emissiveMap = subpassLoad(gbuffer_emissiveMap);\n#else\nvec4 albedoMap = texture(gbuffer_albedoMap,v_uv);\nvec4 normalMap = texture(gbuffer_normalMap,v_uv);\nvec4 emissiveMap = texture(gbuffer_emissiveMap,v_uv);\n#endif\nfloat depth = texture(depth_stencil, v_uv).x;\ns.albedo = albedoMap;\nvec3 position = screen2WS(vec3(gl_FragCoord.xy, depth)).xyz;\ns.position = position;\ns.roughness = normalMap.z;\ns.normal = oct_to_float32x3(normalMap.xy);\ns.metallic = normalMap.w;\ns.emissive = emissiveMap.xyz;\ns.occlusion = emissiveMap.w;\nfloat fogFactor;\nCC_TRANSFER_FOG_BASE(vec4(position, 1), fogFactor);\nvec4 shadowPos;\nshadowPos = cc_matLightViewProj * vec4(position, 1);\nvec4 color = CCStandardShadingBase(s, shadowPos) +\n#if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1\nCCClusterShadingAdditive(s, shadowPos);\n#else\nCCStandardShadingAdditive(s, shadowPos);\n#endif\nCC_APPLY_FOG_BASE(color, fogFactor);\ncolor = CCFragOutput(color);\n#if CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT\nfragColor = color;\n#else\nfragColor = color;\n#endif\n}", - } - ], - [ - { - "vert": "#extension GL_EXT_shader_explicit_arithmetic_types_int32: require\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\nlayout(location = 3) in vec4 a_tangent;\n#if USE_INSTANCING\nlayout(location = 6) in vec4 a_matWorld0;\nlayout(location = 7) in vec4 a_matWorld1;\nlayout(location = 8) in vec4 a_matWorld2;\n#if USE_LIGHTMAP\nlayout(location = 9) in vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nlayout(location = 10) in vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nlayout(location = 11) in float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nint getVertexId() {\nreturn gl_VertexIndex;\n}\n#endif\n#if CC_USE_SKINNING\nlayout(location = 4) in u32vec4 a_joints;\nlayout(location = 5) in vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nlayout(set = 2, binding = 4) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nlayout(set = 2, binding = 7) uniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nlayout(set = 2, binding = 8) uniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nlayout(set = 2, binding = 9) uniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nlayout(location = 13) in highp vec4 a_jointAnimInfo;\n#endif\nlayout(set = 2, binding = 3) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(set = 2, binding = 2) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nlayout(set = 2, binding = 6) uniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nlayout(set = 2, binding = 3) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout vec4 In)\n{\nIn = vec4(a_position, 1.0);\n#if CC_USE_MORPH\napplyMorph(In);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In);\n#endif\n}\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if USE_BATCHING\nlayout(set = 2, binding = 0) uniform CCLocalBatched {\nhighp mat4 cc_matWorlds[10];\n};\n#endif\nlayout(set = 2, binding = 0) uniform CCLocal {\nhighp mat4 cc_matWorld;\nhighp mat4 cc_matWorldIT;\nhighp vec4 cc_lightingMapUVParam;\nhighp vec4 cc_localShadowBias;\n};\nvoid CCGetWorldMatrix(out mat4 matWorld)\n{\n#if USE_INSTANCING\nmatWorld = mat4(\nvec4(a_matWorld0.xyz, 0.0),\nvec4(a_matWorld1.xyz, 0.0),\nvec4(a_matWorld2.xyz, 0.0),\nvec4(a_matWorld0.w, a_matWorld1.w, a_matWorld2.w, 1.0)\n);\n#elif USE_BATCHING\nmatWorld = cc_matWorlds[int(a_dyn_batch_id)];\n#else\nmatWorld = cc_matWorld;\n#endif\n}\nlayout(set = 0, binding = 2) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\nlayout(location = 0) out float v_dist;\nvec4 vert () {\nvec4 position;\nCCVertInput(position);\nmat4 matWorld;\nCCGetWorldMatrix(matWorld);\nvec3 P = (matWorld * position).xyz;\nvec3 L = cc_mainLitDir.xyz;\nvec3 N = cc_planarNDInfo.xyz;\nfloat d = cc_planarNDInfo.w + 0.001;\nfloat dist = (-d - dot(P, N)) / (dot(L, N) + 0.0001);\nvec3 shadowPos = P + L * dist;\nvec3 view = normalize(cc_cameraPos.xyz - shadowPos);\nfloat viewLength = length(cc_cameraPos.xyz - shadowPos);\nshadowPos += view * min(1.0, 0.005 * viewLength);\nposition = cc_matProj * cc_matView * vec4(shadowPos, 1.0);\nv_dist = dist;\nreturn position;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(set = 0, binding = 2) uniform CCShadow {\nhighp mat4 cc_matLightPlaneProj;\nhighp mat4 cc_matLightView;\nhighp mat4 cc_matLightViewProj;\nhighp vec4 cc_shadowInvProjDepthInfo;\nhighp vec4 cc_shadowProjDepthInfo;\nhighp vec4 cc_shadowProjInfo;\nmediump vec4 cc_shadowNFLSInfo;\nmediump vec4 cc_shadowWHPBInfo;\nmediump vec4 cc_shadowLPNNInfo;\nlowp vec4 cc_shadowColor;\nmediump vec4 cc_planarNDInfo;\n};\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nlayout(location = 0) in float v_dist;\nvec4 frag () {\nif(v_dist < 0.0)\ndiscard;\nreturn CCFragOutput(cc_shadowColor);\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "#extension GL_EXT_shader_explicit_arithmetic_types_int32: require\nprecision highp float;\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nhighp float decode32 (highp vec4 rgba) {\nrgba = rgba * 255.0;\nhighp float Sign = 1.0 - (step(128.0, (rgba[3]) + 0.5)) * 2.0;\nhighp float Exponent = 2.0 * (mod(float(int((rgba[3]) + 0.5)), 128.0)) + (step(128.0, (rgba[2]) + 0.5)) - 127.0;\nhighp float Mantissa = (mod(float(int((rgba[2]) + 0.5)), 128.0)) * 65536.0 + rgba[1] * 256.0 + rgba[0] + 8388608.0;\nreturn Sign * exp2(Exponent - 23.0) * Mantissa;\n}\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\nlayout(location = 3) in vec4 a_tangent;\n#if USE_INSTANCING\nlayout(location = 6) in vec4 a_matWorld0;\nlayout(location = 7) in vec4 a_matWorld1;\nlayout(location = 8) in vec4 a_matWorld2;\n#if USE_LIGHTMAP\nlayout(location = 9) in vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nlayout(location = 10) in vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nlayout(location = 11) in float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\nint getVertexId() {\nreturn gl_VertexIndex;\n}\n#endif\n#if CC_USE_SKINNING\nlayout(location = 4) in u32vec4 a_joints;\nlayout(location = 5) in vec4 a_weights;\n#endif\n#if CC_USE_MORPH\nlayout(set = 2, binding = 4) uniform CCMorph {\nvec4 cc_displacementWeights[15];\nvec4 cc_displacementTextureInfo;\n};\nvec2 getPixelLocation(vec2 textureResolution, int pixelIndex) {\nfloat pixelIndexF = float(pixelIndex);\nfloat x = mod(pixelIndexF, textureResolution.x);\nfloat y = floor(pixelIndexF / textureResolution.x);\nreturn vec2(x, y);\n}\nvec2 getPixelCoordFromLocation(vec2 location, vec2 textureResolution) {\nreturn (vec2(location.x, location.y) + .5) / textureResolution;\n}\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int pixelIndex) {\nivec2 texSize = textureSize(tex, 0);\nreturn texelFetch(tex, ivec2(pixelIndex % texSize.x, pixelIndex / texSize.x), 0);\n}\n#else\nvec4 fetchVec3ArrayFromTexture(sampler2D tex, int elementIndex) {\nint pixelIndex = elementIndex * 4;\nvec2 location = getPixelLocation(cc_displacementTextureInfo.xy, pixelIndex);\nvec2 x = getPixelCoordFromLocation(location + vec2(0.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 y = getPixelCoordFromLocation(location + vec2(1.0, 0.0), cc_displacementTextureInfo.xy);\nvec2 z = getPixelCoordFromLocation(location + vec2(2.0, 0.0), cc_displacementTextureInfo.xy);\nreturn vec4(\ndecode32(texture(tex, x)),\ndecode32(texture(tex, y)),\ndecode32(texture(tex, z)),\n1.0\n);\n}\n#endif\nfloat getDisplacementWeight(int index) {\nint quot = index / 4;\nint remainder = index - quot * 4;\nif (remainder == 0) {\nreturn cc_displacementWeights[quot].x;\n} else if (remainder == 1) {\nreturn cc_displacementWeights[quot].y;\n} else if (remainder == 2) {\nreturn cc_displacementWeights[quot].z;\n} else {\nreturn cc_displacementWeights[quot].w;\n}\n}\nvec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) {\n#if CC_MORPH_PRECOMPUTED\nreturn fetchVec3ArrayFromTexture(tex, vertexIndex).rgb;\n#else\nvec3 result = vec3(0, 0, 0);\nint nVertices = int(cc_displacementTextureInfo.z);\nfor (int iTarget = 0; iTarget < CC_MORPH_TARGET_COUNT; ++iTarget) {\nresult += (fetchVec3ArrayFromTexture(tex, nVertices * iTarget + vertexIndex).rgb * getDisplacementWeight(iTarget));\n}\nreturn result;\n#endif\n}\n#if CC_MORPH_TARGET_HAS_POSITION\nlayout(set = 2, binding = 7) uniform sampler2D cc_PositionDisplacements;\nvec3 getPositionDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nlayout(set = 2, binding = 8) uniform sampler2D cc_NormalDisplacements;\nvec3 getNormalDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId);\n}\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\nlayout(set = 2, binding = 9) uniform sampler2D cc_TangentDisplacements;\nvec3 getTangentDisplacement(int vertexId) {\nreturn getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId);\n}\n#endif\nvoid applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nint vertexId = getVertexId();\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_NORMAL\nnormal.xyz = normal.xyz + getNormalDisplacement(vertexId);\n#endif\n#if CC_MORPH_TARGET_HAS_TANGENT\ntangent.xyz = tangent.xyz + getTangentDisplacement(vertexId);\n#endif\n}\nvoid applyMorph (inout vec4 position) {\n#if CC_MORPH_TARGET_HAS_POSITION\nposition.xyz = position.xyz + getPositionDisplacement(getVertexId());\n#endif\n}\n#endif\n#if CC_USE_SKINNING\n#if CC_USE_BAKED_ANIMATION\n#if USE_INSTANCING\nlayout(location = 13) in highp vec4 a_jointAnimInfo;\n#endif\nlayout(set = 2, binding = 3) uniform CCSkinningTexture {\nhighp vec4 cc_jointTextureInfo;\n};\nlayout(set = 2, binding = 2) uniform CCSkinningAnimation {\nhighp vec4 cc_jointAnimInfo;\n};\nlayout(set = 2, binding = 6) uniform highp sampler2D cc_jointTexture;\nvoid CCGetJointTextureCoords(float pixelsPerJoint, float jointIdx, out highp float x, out highp float y, out highp float invSize)\n{\n#if USE_INSTANCING\nhighp float temp = pixelsPerJoint * (a_jointAnimInfo.x * a_jointAnimInfo.y + jointIdx) + a_jointAnimInfo.z;\n#else\nhighp float temp = pixelsPerJoint * (cc_jointAnimInfo.x * cc_jointTextureInfo.y + jointIdx) + cc_jointTextureInfo.z;\n#endif\ninvSize = cc_jointTextureInfo.w;\nhighp float tempY = floor(temp * invSize);\nx = floor(temp - tempY * cc_jointTextureInfo.x);\ny = (tempY + 0.5) * invSize;\n}\n#else\nlayout(set = 2, binding = 3) uniform CCSkinning {\nhighp vec4 cc_joints[30 * 3];\n};\n#endif\n#if CC_USE_BAKED_ANIMATION\n#if CC_DEVICE_SUPPORT_FLOAT_TEXTURE\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(3.0, i, x, y, invSize);\nvec4 v1 = texture(cc_jointTexture, vec2((x + 0.5) * invSize, y));\nvec4 v2 = texture(cc_jointTexture, vec2((x + 1.5) * invSize, y));\nvec4 v3 = texture(cc_jointTexture, vec2((x + 2.5) * invSize, y));\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#else\nmat4 getJointMatrix (float i) {\nhighp float x, y, invSize;\nCCGetJointTextureCoords(12.0, i, x, y, invSize);\nvec4 v1 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 0.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 1.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 2.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 3.5) * invSize, y)))\n);\nvec4 v2 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 4.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 5.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 6.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 7.5) * invSize, y)))\n);\nvec4 v3 = vec4(\ndecode32(texture(cc_jointTexture, vec2((x + 8.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 9.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 10.5) * invSize, y))),\ndecode32(texture(cc_jointTexture, vec2((x + 11.5) * invSize, y)))\n);\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\n#else\nmat4 getJointMatrix (float i) {\nint idx = int(i);\nvec4 v1 = cc_joints[idx * 3];\nvec4 v2 = cc_joints[idx * 3 + 1];\nvec4 v3 = cc_joints[idx * 3 + 2];\nreturn mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0));\n}\n#endif\nmat4 skinMatrix () {\nvec4 joints = vec4(a_joints);\nreturn getJointMatrix(joints.x) * a_weights.x\n+ getJointMatrix(joints.y) * a_weights.y\n+ getJointMatrix(joints.z) * a_weights.z\n+ getJointMatrix(joints.w) * a_weights.w;\n}\nvoid CCSkin (inout vec4 position) {\nmat4 m = skinMatrix();\nposition = m * position;\n}\nvoid CCSkin (inout vec4 position, inout vec3 normal, inout vec4 tangent) {\nmat4 m = skinMatrix();\nposition = m * position;\nnormal = (m * vec4(normal, 0.0)).xyz;\ntangent.xyz = (m * vec4(tangent.xyz, 0.0)).xyz;\n}\n#endif\nvoid CCVertInput(inout StandardVertInput In)\n{\nIn.position = vec4(a_position, 1.0);\nIn.normal = a_normal;\nIn.tangent = a_tangent;\n#if CC_USE_MORPH\napplyMorph(In.position, In.normal, In.tangent);\n#endif\n#if CC_USE_SKINNING\nCCSkin(In.position, In.normal, In.tangent);\n#endif\n}\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(location = 0) out vec2 v_uv;\nvoid main () {\nStandardVertInput In;\nCCVertInput(In);\nIn.position.xy = cc_cameraPos.w == 0.0 ? vec2(In.position.xy.x, -In.position.xy.y) : In.position.xy;\ngl_Position = In.position;\ngl_Position.y = gl_Position.y;\nv_uv = a_texCoord;\n}", - "frag": "\nprecision highp float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#if ANTIALIAS_TYPE == 1\nvec4 fxaa(sampler2D tex, vec2 fragCoord, vec2 resolution,\nvec2 v_rgbNW, vec2 v_rgbNE,\nvec2 v_rgbSW, vec2 v_rgbSE,\nvec2 v_rgbM) {\nvec4 color;\nmediump vec2 inverseVP = vec2(1.0 / resolution.x, 1.0 / resolution.y);\nvec3 rgbNW = texture(tex, v_rgbNW).xyz;\nvec3 rgbNE = texture(tex, v_rgbNE).xyz;\nvec3 rgbSW = texture(tex, v_rgbSW).xyz;\nvec3 rgbSE = texture(tex, v_rgbSE).xyz;\nvec4 texColor = texture(tex, v_rgbM);\nvec3 rgbM = texColor.xyz;\nvec3 luma = vec3(0.299, 0.587, 0.114);\nfloat lumaNW = dot(rgbNW, luma);\nfloat lumaNE = dot(rgbNE, luma);\nfloat lumaSW = dot(rgbSW, luma);\nfloat lumaSE = dot(rgbSE, luma);\nfloat lumaM = dot(rgbM, luma);\nfloat lumaMin = min(lumaM, min(min(lumaNW, lumaNE), min(lumaSW, lumaSE)));\nfloat lumaMax = max(lumaM, max(max(lumaNW, lumaNE), max(lumaSW, lumaSE)));\nmediump vec2 dir;\ndir.x = -((lumaNW + lumaNE) - (lumaSW + lumaSE));\ndir.y = ((lumaNW + lumaSW) - (lumaNE + lumaSE));\nfloat dirReduce = max((lumaNW + lumaNE + lumaSW + lumaSE) *\n(0.25 * (1.0 / 8.0)), (1.0/ 128.0));\nfloat rcpDirMin = 1.0 / (min(abs(dir.x), abs(dir.y)) + dirReduce);\ndir = min(vec2(8.0, 8.0),\nmax(vec2(-8.0, -8.0),\ndir * rcpDirMin)) * inverseVP;\nvec3 rgbA = 0.5 * (\ntexture(tex, fragCoord * inverseVP + dir * (1.0 / 3.0 - 0.5)).xyz +\ntexture(tex, fragCoord * inverseVP + dir * (2.0 / 3.0 - 0.5)).xyz);\nvec3 rgbB = rgbA * 0.5 + 0.25 * (\ntexture(tex, fragCoord * inverseVP + dir * -0.5).xyz +\ntexture(tex, fragCoord * inverseVP + dir * 0.5).xyz);\nfloat lumaB = dot(rgbB, luma);\nif ((lumaB < lumaMin) || (lumaB > lumaMax))\ncolor = vec4(rgbA, texColor.a);\nelse\ncolor = vec4(rgbB, texColor.a);\nreturn color;\n}\n#endif\nlayout(location = 0) in vec2 v_uv;\nlayout(set = 1, binding = 0) uniform sampler2D outputResultMap;\nlayout(location = 0) out vec4 fragColor;\nvoid texcoords(vec2 fragCoord, vec2 resolution,\nout vec2 v_rgbNW, out vec2 v_rgbNE,\nout vec2 v_rgbSW, out vec2 v_rgbSE,\nout vec2 v_rgbM) {\nvec2 inverseVP = 1.0 / resolution.xy;\nv_rgbNW = (fragCoord + vec2(-1.0, -1.0)) * inverseVP;\nv_rgbNE = (fragCoord + vec2(1.0, -1.0)) * inverseVP;\nv_rgbSW = (fragCoord + vec2(-1.0, 1.0)) * inverseVP;\nv_rgbSE = (fragCoord + vec2(1.0, 1.0)) * inverseVP;\nv_rgbM = vec2(fragCoord * inverseVP);\n}\nvoid main () {\nmediump vec2 v_rgbNW;\nmediump vec2 v_rgbNE;\nmediump vec2 v_rgbSW;\nmediump vec2 v_rgbSE;\nmediump vec2 v_rgbM;\n#if ANTIALIAS_TYPE == 1\nvec2 resolution = cc_screenSize.xy;\nvec2 fragCoord = v_uv * resolution;\ntexcoords(fragCoord, resolution, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\nfragColor = fxaa(outputResultMap, fragCoord, resolution, v_rgbNW, v_rgbNE, v_rgbSW, v_rgbSE, v_rgbM);\n#else\nfragColor = texture(outputResultMap, v_uv);\n#endif\n}", - } - ], - [ - { - "vert": "\nprecision highp float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\n#define PI 3.14159265359\n#define PI2 6.28318530718\n#define EPSILON 1e-6\n#define LOG2 1.442695\n#define FP_MAX 65504.0\n#define FP_SCALE 0.0009765625\n#define FP_SCALE_INV 1024.0\nstruct StandardVertInput {\nhighp vec4 position;\nvec3 normal;\nvec4 tangent;\n};\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec3 a_normal;\nlayout(location = 2) in vec2 a_texCoord;\nlayout(location = 3) in vec4 a_tangent;\n#if USE_INSTANCING\nlayout(location = 6) in vec4 a_matWorld0;\nlayout(location = 7) in vec4 a_matWorld1;\nlayout(location = 8) in vec4 a_matWorld2;\n#if USE_LIGHTMAP\nlayout(location = 9) in vec4 a_lightingMapUVParam;\n#endif\n#if CC_RECEIVE_SHADOW\nlayout(location = 10) in vec2 a_localShadowBias;\n#endif\n#elif USE_BATCHING\nlayout(location = 11) in float a_dyn_batch_id;\n#endif\n#if CC_USE_MORPH\n#endif\n#if CC_USE_SKINNING\nlayout(location = 4) in u32vec4 a_joints;\nlayout(location = 5) in vec4 a_weights;\n#endif\nlayout(location = 0) out mediump vec4 viewDir;\nvec4 vert () {\nviewDir = vec4(a_position, 1.0);\nmat4 matViewRotOnly = mat4(mat3(cc_matView));\nvec4 pos = matViewRotOnly * viewDir;\nif (cc_matProj[3].w > 0.0) {\nmat4 matProj = cc_matProj;\nmatProj[0].x = 5.2;\nmatProj[1].y = 2.6;\nmatProj[2].zw = vec2(-1.0);\nmatProj[3].zw = vec2(0.0);\npos = matProj * pos;\n} else {\npos = cc_matProj * pos;\n}\npos.z = 0.99999 * pos.w;\nreturn pos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(set = 0, binding = 4) uniform samplerCube cc_environment;\nvec3 unpackRGBE (vec4 rgbe) {\nreturn rgbe.rgb * pow(1.1, rgbe.a * 255.0 - 128.0);\n}\nvec3 SRGBToLinear (vec3 gamma) {\nreturn gamma * gamma;\n}\nvec3 ACESToneMap (vec3 color) {\ncolor = min(color, vec3(8.0));\nconst float A = 2.51;\nconst float B = 0.03;\nconst float C = 2.43;\nconst float D = 0.59;\nconst float E = 0.14;\nreturn (color * (A * color + B)) / (color * (C * color + D) + E);\n}\nvec4 CCFragOutput (vec4 color) {\n#if CC_USE_HDR\ncolor.rgb = ACESToneMap(color.rgb);\n#endif\ncolor.rgb = sqrt(color.rgb);\nreturn color;\n}\nlayout(location = 0) in mediump vec4 viewDir;\nvec4 frag () {\n#if USE_RGBE_CUBEMAP\nvec3 c = unpackRGBE(texture(cc_environment, viewDir.xyz));\n#else\nvec3 c = SRGBToLinear(texture(cc_environment, viewDir.xyz).rgb);\n#endif\nreturn CCFragOutput(vec4(c * cc_ambientSky.w, 1.0));\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nlayout(location = 0) in vec3 a_position;\nlayout(location = 1) in vec4 a_color;\nlayout(location = 0) out vec2 v_uv;\nlayout(set = 1, binding = 0) uniform Constants {\nvec4 offset;\n};\nlayout(set = 1, binding = 1) uniform PerFrameInfo {\nvec4 digits[8 * 10 / 4];\n};\nfloat getComponent(vec4 v, float i) {\nif (i < 1.0) { return v.x; }\nelse if (i < 2.0) { return v.y; }\nelse if (i < 3.0) { return v.z; }\nelse { return v.w; }\n}\nvec4 vert () {\nmat2 proj = mat2(cc_matProj[0].xy, cc_matProj[1].xy);\nproj /= abs(proj[1].x + proj[1].y);\nvec2 position = proj * a_position.xy + offset.xy;\nv_uv = a_color.xy;\nif (a_color.z >= 0.0) {\nfloat n = getComponent(digits[int(a_color.z)], a_color.w);\nv_uv += vec2(offset.z * n, 0.0);\n}\nreturn vec4(position, 0.0, 1.0);\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(set = 0, binding = 0) uniform CCGlobal {\nhighp vec4 cc_time;\nmediump vec4 cc_screenSize;\nmediump vec4 cc_nativeSize;\n};\nlayout(set = 0, binding = 1) uniform CCCamera {\nhighp mat4 cc_matView;\nhighp mat4 cc_matViewInv;\nhighp mat4 cc_matProj;\nhighp mat4 cc_matProjInv;\nhighp mat4 cc_matViewProj;\nhighp mat4 cc_matViewProjInv;\nhighp vec4 cc_cameraPos;\nmediump vec4 cc_surfaceTransform;\nmediump vec4 cc_screenScale;\nmediump vec4 cc_exposure;\nmediump vec4 cc_mainLitDir;\nmediump vec4 cc_mainLitColor;\nmediump vec4 cc_ambientSky;\nmediump vec4 cc_ambientGround;\nmediump vec4 cc_fogColor;\nmediump vec4 cc_fogBase;\nmediump vec4 cc_fogAdd;\nmediump vec4 cc_nearFar;\nmediump vec4 cc_viewPort;\n};\nvec4 CCFragOutput (vec4 color) {\nreturn color;\n}\nlayout(location = 0) in vec2 v_uv;\nlayout(set = 1, binding = 2) uniform sampler2D mainTexture;\nvec4 frag () {\nreturn CCFragOutput(texture(mainTexture, v_uv));\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ], - [ - { - "vert": "\nprecision mediump float;\nlayout(location = 0) in vec2 a_position;\nlayout(location = 1) in vec2 a_texCoord;\nlayout(location = 0) out vec2 v_uv;\nlayout(set = 1, binding = 0) uniform Constant {\nvec4 u_buffer0;\nvec4 u_buffer1;\nmat4 u_projection;\n};\nvec4 vert () {\nvec2 worldPos = a_position * u_buffer1.xy + u_buffer1.zw;\nvec2 clipSpace = worldPos / u_buffer0.xy * 2.0 - 1.0;\nvec4 screenPos = u_projection * vec4(clipSpace, 0.0, 1.0);\nv_uv = a_texCoord;\nreturn screenPos;\n}\nvoid main() { gl_Position = vert(); }", - "frag": "\nprecision mediump float;\nlayout(location = 0) in vec2 v_uv;\nlayout(set = 1, binding = 1) uniform Factor {\nfloat u_percent;\n};\nlayout(set = 1, binding = 2) uniform sampler2D mainTexture;\nvec4 frag () {\nvec4 color = texture(mainTexture, v_uv);\nfloat percent = clamp(u_percent, 0.0, 1.0);\ncolor.xyz *= percent;\nreturn color;\n}\nlayout(location = 0) out vec4 cc_FragColor;\nvoid main() { cc_FragColor = frag(); }", - } - ] -]; diff --git a/cocos/core/category.json b/cocos/core/category.json new file mode 100644 index 0000000000..8b94aff18f --- /dev/null +++ b/cocos/core/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "核心模块", + "en": "Core" + }, + "description": { + "zh": "Cocos Creator 核心功能。", + "en": "Cocos Creator core functionalities." + } +} \ No newline at end of file diff --git a/cocos/core/components/camera-component.ts b/cocos/core/components/camera-component.ts index f1374a950d..63a2822ae7 100644 --- a/cocos/core/components/camera-component.ts +++ b/cocos/core/components/camera-component.ts @@ -23,20 +23,14 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component/camera - */ - import { EDITOR } from 'internal:constants'; -import { ccclass, help, executeInEditMode, menu, tooltip, displayOrder, type, serializable } from 'cc.decorator'; +import { ccclass, help, executeInEditMode, menu, tooltip, displayOrder, type, serializable, visible } from 'cc.decorator'; import { RenderTexture } from '../assets/render-texture'; import { UITransform } from '../../2d/framework'; import { Component } from './component'; import { Ray } from '../geometry'; import { Color, Rect, toRadian, Vec3 } from '../math'; import { CAMERA_DEFAULT_MASK } from '../pipeline/define'; -import { view } from '../platform/view'; import { scene } from '../renderer'; import { SKYBOX_FLAG, CameraProjection, CameraFOVAxis, CameraAperture, CameraISO, CameraShutter } from '../renderer/scene/camera'; import { Root } from '../root'; @@ -85,12 +79,40 @@ export declare namespace Camera { @menu('Rendering/Camera') @executeInEditMode export class Camera extends Component { + /** + * @en The projection type enumeration of the camera. + * @zh 相机的投影类型枚举。 + */ public static ProjectionType = ProjectionType; + /** + * @en The axis type of the fov + * @zh FOV 的轴向枚举 + */ public static FOVAxis = FOVAxis; + /** + * @en The clear flag enumeration of the camera. + * @zh 相机的清除标志位枚举。 + */ public static ClearFlag = ClearFlag; + /** + * @en The aperture value's enumeration of the camera. + * @zh 相机的光圈值枚举。 + */ public static Aperture = Aperture; + /** + * @en The shutter value's enumeration of the camera. + * @zh 相机的快门值枚举。 + */ public static Shutter = Shutter; + /** + * @en The ISO value's enumeration of the camera. + * @zh 相机的感光度值枚举。 + */ public static ISO = ISO; + /** + * @en The event for target texture changing. + * @zh 目标贴图修改的事件。 + */ public static TARGET_TEXTURE_CHANGE = 'tex-change'; @serializable @@ -134,6 +156,10 @@ export class Camera extends Component { protected _inEditorMode = false; protected _flows: string[] | undefined = undefined; + /** + * @en The render camera representation. + * @zh 渲染场景中的相机对象。 + */ get camera () { return this._camera!; } @@ -259,6 +285,9 @@ export class Camera extends Component { */ @type(FOVAxis) @displayOrder(7) + @visible(function (this: Camera) { + return this._projection === ProjectionType.PERSPECTIVE; + }) @tooltip('i18n:camera.fov_axis') get fovAxis () { return this._fovAxis; @@ -278,6 +307,9 @@ export class Camera extends Component { * @zh 相机的视角大小。 */ @displayOrder(8) + @visible(function (this: Camera) { + return this._projection === ProjectionType.PERSPECTIVE; + }) @tooltip('i18n:camera.fov') get fov () { return this._fov; @@ -293,6 +325,9 @@ export class Camera extends Component { * @zh 正交模式下的相机视角高度。 */ @displayOrder(9) + @visible(function (this: Camera) { + return this._projection === ProjectionType.ORTHO; + }) @tooltip('i18n:camera.ortho_height') get orthoHeight () { return this._orthoHeight; @@ -438,6 +473,9 @@ export class Camera extends Component { if (this._camera) { this._camera.screenScale = val; } } + /** + * @internal + */ get inEditorMode () { return this._inEditorMode; } @@ -478,18 +516,40 @@ export class Camera extends Component { } } + /** + * @en Convert a screen space (left-top origin) point to a ray. + * @zh 将一个屏幕空间(左上角为原点)坐标转换为射线。 + * @param x The x axis position on screen. + * @param y The y axis position on screen. + * @param out The output ray object. + * @returns Return the output ray object. + */ public screenPointToRay (x: number, y: number, out?: Ray) { if (!out) { out = Ray.create(); } if (this._camera) { this._camera.screenPointToRay(out, x, y); } return out; } + /** + * @en Convert a world position to a screen space (left-top origin) position. + * @zh 将一个世界空间坐标转换为屏幕空间(左上角为原点)坐标。 + * @param worldPos The position in world space coordinates + * @param out The output position in screen space coordinates. + * @returns Return the output position object. + */ public worldToScreen (worldPos: Vec3 | Readonly, out?: Vec3) { if (!out) { out = new Vec3(); } if (this._camera) { this._camera.worldToScreen(out, worldPos); } return out; } + /** + * @en Convert a screen space (left-top origin) position to a world space position. + * @zh 将一个屏幕空间(左上角为原点)转换为世界空间坐标。 + * @param screenPos The position in screen space coordinates + * @param out The output position in world space coordinates + * @returns Return the output position object. + */ public screenToWorld (screenPos: Vec3, out?: Vec3) { if (!out) { out = this.node.getWorldPosition(); } if (this._camera) { this._camera.screenToWorld(out, screenPos); } @@ -497,18 +557,19 @@ export class Camera extends Component { } /** - * @en 3D node to UI local node coordinates. The converted value is the offset under the UI node. - * - * @zh 3D 节点转 UI 本地节点坐标。转换后的值是该 UI 节点下的偏移。 - * @param wpos 3D 节点世界坐标 - * @param uiNode UI 节点 - * @param out 返回在当前传入的 UI 节点下的偏移量 + * @en Convert a 3D world position to the local coordinates system of the given UI node. + * The converted position will be related to the given UI node under local space. + * @zh 将一个 3D 空间世界坐标转换到指定的 UI 本地节点坐标系下。转换后的位置是指定 UI 节点坐标系下的局部偏移。 + * @param wpos @en The world position to convert @zh 需要转换的世界坐标 + * @param uiNode @en The UI node coordinates in which the world position will be convert to @zh 用于同步位置的 UI 节点 + * @param out @en Return the corresponding position of the given world position in the UI node's local coordinates @zh 返回传入的世界坐标在 UI 节点本地坐标系下的局部坐标 * * @example * ```ts * this.convertToUINode(target.worldPosition, uiNode.parent, out); * uiNode.position = out; * ``` + * @deprecated since v3.6, please use UITransform.convertToNodeSpaceAR instead */ public convertToUINode (wpos: Vec3 | Readonly, uiNode: Node, out?: Vec3) { if (!out) { @@ -518,7 +579,7 @@ export class Camera extends Component { this.worldToScreen(wpos, _temp_vec3_1); const cmp = uiNode.getComponent('cc.UITransform') as UITransform; - const designSize = view.getVisibleSize(); + const designSize = legacyCC.view.getVisibleSize(); const xoffset = _temp_vec3_1.x - this._camera.width * 0.5; const yoffset = _temp_vec3_1.y - this._camera.height * 0.5; _temp_vec3_1.x = xoffset / legacyCC.view.getScaleX() + designSize.width * 0.5; @@ -532,7 +593,7 @@ export class Camera extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _createCamera () { if (!this._camera) { diff --git a/cocos/core/components/component-event-handler.schema.ts b/cocos/core/components/component-event-handler.schema.ts new file mode 100644 index 0000000000..e198b6d5a9 --- /dev/null +++ b/cocos/core/components/component-event-handler.schema.ts @@ -0,0 +1,6 @@ +import { CCClass } from '../data'; +import { Node } from '../scene-graph/node'; +import { EventHandler } from './component-event-handler'; + +CCClass.Attr.setClassAttr(EventHandler, 'target', 'type', 'Object'); +CCClass.Attr.setClassAttr(EventHandler, 'target', 'ctor', Node); diff --git a/cocos/core/components/component-event-handler.ts b/cocos/core/components/component-event-handler.ts index 92262ab706..b95e2d6636 100644 --- a/cocos/core/components/component-event-handler.ts +++ b/cocos/core/components/component-event-handler.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module event - */ - import { ccclass, type, serializable, editable, tooltip } from 'cc.decorator'; import type { Node } from '../scene-graph'; import { legacyCC } from '../global-exports'; @@ -64,7 +59,7 @@ import { legacyCC } from '../global-exports'; @ccclass('cc.ClickEvent') export class EventHandler { /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ get _componentName () { this._genCompIdIfNeeded(); @@ -100,8 +95,8 @@ export class EventHandler { * @zh * 事件响应组件和函数所在节点 */ - @serializable - @type(legacyCC.Node) + // @type(Node) should be removed for avoid circle reference error + // the type definition of it deal with in the file './component-event-handler.schema.ts' @serializable @tooltip('i18n:button.click_event.target') public target: Node | null = null; @@ -118,7 +113,7 @@ export class EventHandler { public component = ''; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @serializable public _componentId = ''; @@ -164,7 +159,7 @@ export class EventHandler { if (!legacyCC.isValid(target)) { return; } this._genCompIdIfNeeded(); - const compType = legacyCC.js._getClassById(this._componentId); + const compType = legacyCC.js.getClassById(this._componentId); const comp = target!.getComponent(compType); if (!legacyCC.isValid(comp)) { return; } @@ -182,11 +177,11 @@ export class EventHandler { private _compName2Id (compName) { const comp = legacyCC.js.getClassByName(compName); - return legacyCC.js._getClassId(comp); + return legacyCC.js.getClassId(comp); } private _compId2Name (compId) { - const comp = legacyCC.js._getClassById(compId); + const comp = legacyCC.js.getClassById(compId); return legacyCC.js.getClassName(comp); } diff --git a/cocos/core/components/component.ts b/cocos/core/components/component.ts index 8cd43c4a23..ad0d2c63cb 100644 --- a/cocos/core/components/component.ts +++ b/cocos/core/components/component.ts @@ -24,23 +24,18 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component - */ - import { ccclass, tooltip, displayName, type, serializable, disallowAnimation } from 'cc.decorator'; -import { EDITOR, TEST, DEV } from 'internal:constants'; +import { EDITOR, TEST } from 'internal:constants'; import { Script } from '../assets/scripts'; import { CCObject } from '../data/object'; import IDGenerator from '../utils/id-generator'; import { getClassName, value } from '../utils/js'; -import { RenderScene } from '../renderer/scene/render-scene'; +import { RenderScene } from '../renderer/core/render-scene'; import { Rect } from '../math'; import * as RF from '../data/utils/requiring-frame'; import { Node } from '../scene-graph'; import { legacyCC } from '../global-exports'; -import { errorID, warnID, assertID, error } from '../platform/debug'; +import { errorID, warnID, assertID } from '../platform/debug'; import { CompPrefabInfo } from '../utils/prefab/prefab-info'; import { EventHandler } from './component-event-handler'; @@ -99,7 +94,7 @@ class Component extends CCObject { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @displayName('Script') @type(Script) @@ -159,13 +154,14 @@ class Component extends CCObject { * log(this._isOnLoadCalled > 0); * ``` * - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ get _isOnLoadCalled () { return this._objFlags & IsOnLoadCalled; } public static system = null; + /** * @en The node this component is attached to. A component is always attached to a node. * @zh 该组件被附加到的节点。组件总会附加到一个节点。 @@ -179,32 +175,32 @@ class Component extends CCObject { public node: Node = NullNode; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @serializable public _enabled = true; /** - * @legacyPublic + * @internal */ @serializable public __prefab: CompPrefabInfo | null = null; /** - * @legacyPublic + * @internal */ public _sceneGetter: null | (() => RenderScene) = null; /** * For internal usage. - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _id: string = idGenerator.getNewId(); // private __scriptUuid = ''; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _getRenderScene (): RenderScene { if (this._sceneGetter) { @@ -382,7 +378,7 @@ class Component extends CCObject { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _onPreDestroy () { // Schedules @@ -396,7 +392,7 @@ class Component extends CCObject { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _instantiate (cloned?: Component) { if (!cloned) { diff --git a/cocos/core/components/deprecated.ts b/cocos/core/components/deprecated.ts index 19e19c4bc5..6fb9e6c6c6 100644 --- a/cocos/core/components/deprecated.ts +++ b/cocos/core/components/deprecated.ts @@ -30,6 +30,7 @@ import { Camera } from './camera-component'; import { replaceProperty } from '../utils/x-deprecated'; import { legacyCC } from '../global-exports'; import { js } from '../utils/js'; +import { ModelRenderer } from './model-renderer'; replaceProperty(Camera, 'Camera', [ { @@ -60,3 +61,11 @@ replaceProperty(Camera.prototype, 'Camera.prototype', [ export { Camera as CameraComponent }; legacyCC.CameraComponent = Camera; js.setClassAlias(Camera, 'cc.CameraComponent'); + +/** + * Alias of [[Renderer]] + * @deprecated Since v3.6 + */ +export { ModelRenderer as RenderableComponent }; +legacyCC.RenderableComponent = ModelRenderer; +js.setClassAlias(ModelRenderer, 'cc.RenderableComponent'); diff --git a/cocos/core/components/index.ts b/cocos/core/components/index.ts index 2fc6abff8b..f039fda557 100644 --- a/cocos/core/components/index.ts +++ b/cocos/core/components/index.ts @@ -23,13 +23,13 @@ THE SOFTWARE. */ - - +import './component-event-handler.schema'; export { default as System } from './system'; export { default as MissingScript } from './missing-script'; export { EventHandler } from './component-event-handler'; export { Component } from './component'; export { Camera } from './camera-component'; -export { RenderableComponent } from './renderable-component'; +export { ModelRenderer } from './model-renderer'; +export { Renderer } from './renderer'; /** deprecated */ export * from './deprecated'; diff --git a/cocos/core/components/missing-script.ts b/cocos/core/components/missing-script.ts index 5acc8940e4..897e1221ad 100644 --- a/cocos/core/components/missing-script.ts +++ b/cocos/core/components/missing-script.ts @@ -24,14 +24,9 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component - */ - import { ccclass, inspector, editorOnly, serializable, editable } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; -import { _getClassById } from '../utils/js'; +import { getClassById } from '../utils/js'; import { BUILTIN_CLASSID_RE } from '../utils/misc'; import { Component } from './component'; import { legacyCC } from '../global-exports'; @@ -61,7 +56,7 @@ export default class MissingScript extends Component { * @return {function} constructor */ public static safeFindClass (id: string) { - const cls = _getClassById(id); + const cls = getClassById(id); if (cls) { return cls; } @@ -72,7 +67,7 @@ export default class MissingScript extends Component { // the serialized data for original script object /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @serializable @editorOnly diff --git a/cocos/core/components/model-renderer.ts b/cocos/core/components/model-renderer.ts new file mode 100644 index 0000000000..9baeaf4567 --- /dev/null +++ b/cocos/core/components/model-renderer.ts @@ -0,0 +1,99 @@ +/* + 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 { + ccclass, serializable, +} from 'cc.decorator'; +import { scene } from '../renderer'; +import { Layers } from '../scene-graph/layers'; +import { Renderer } from './renderer'; + +/** + * @en Base class for all rendering components containing model. + * @zh 所有包含 model 的渲染组件基类。 + */ +@ccclass('cc.ModelRenderer') +export class ModelRenderer extends Renderer { + /** + * @en The visibility which will be applied to the committed models. + * @zh 应用于所有提交渲染的 Model 的可见性 + */ + get visibility () { + return this._visFlags; + } + + set visibility (val) { + this._visFlags = val; + this._onVisibilityChange(val); + } + + /** + * @en The priority which will be applied to the committed models.(Valid only in transparent queues) + * @zh 应用于所有提交渲染的 Model 的排序优先级(只在半透明渲染队列中起效) + */ + get priority () { + return this._priority; + } + + set priority (val) { + if (val === this._priority) return; + this._updatePriority(); + } + + @serializable + protected _visFlags = Layers.Enum.NONE; + protected _models: scene.Model[] = []; + protected _priority = 0; + + /** + * @zh 收集组件中的 models + * @en Collect the models in this component. + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ + public _collectModels (): scene.Model[] { + return this._models; + } + + protected onEnable () { + this._updatePriority(); + } + + protected _attachToScene () { + } + + protected _detachFromScene () { + } + + protected _onVisibilityChange (val) { + } + + protected _updatePriority () { + if (this._models.length > 0) { + for (let i = 0; i < this._models.length; i++) { + this._models[i].priority = this._priority; + } + } + } +} diff --git a/cocos/core/components/renderable-component.ts b/cocos/core/components/renderer.ts similarity index 73% rename from cocos/core/components/renderable-component.ts rename to cocos/core/components/renderer.ts index f1c95528a2..bee78aefd0 100644 --- a/cocos/core/components/renderable-component.ts +++ b/cocos/core/components/renderer.ts @@ -1,5 +1,5 @@ /* - Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. https://www.cocos.com/ @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module model - */ - import { EDITOR } from 'internal:constants'; import { ccclass, type, displayOrder, displayName, serializable, @@ -35,10 +30,7 @@ import { import { Material } from '../assets/material'; import { Component } from './component'; import { IMaterialInstanceInfo, MaterialInstance } from '../renderer/core/material-instance'; -import { scene } from '../renderer'; -import { Layers } from '../scene-graph/layers'; import { warnID } from '../platform/debug'; -import { legacyCC } from '../global-exports'; const _matInsInfo: IMaterialInstanceInfo = { parent: null!, @@ -46,20 +38,36 @@ const _matInsInfo: IMaterialInstanceInfo = { subModelIdx: 0, }; -@ccclass('cc.RenderableComponent') -export class RenderableComponent extends Component { - @serializable - protected _visFlags = Layers.Enum.NONE; - - get visibility () { - return this._visFlags; - } - - set visibility (val) { - this._visFlags = val; - this._onVisibilityChange(val); +/** + * @en Base class for all components which can submit contents for the rendering process. + * It manages a series of [[Model]]s and the visibility, the materials and the material instances of the models. + * There are several different material properties that must be distinguished clearly and used with caution: + * - [[sharedMaterials]] are shared for all component instances that are using the same material asset, modification will be applied universally. + * - [[materials]] are instances created independently for the component instance, modification will only be applied for the component instance. + * - Render Materials retrieved by [[getRenderMaterial]] are materials used for the actual rendering process, material instances are used if exist. + * By default, shared materials are used for rendering. + * Material instances are created only when user try to retrieve a material instance with [[material]], [[materials]] and [[getMaterialInstance]]. + * @zh 所有可以提交内容到渲染流程的可渲染类的基类,它管理着一组 [[Model]],以及它们的可见性、材质和材质实例。 + * 下面是这个组件所管理的各种材质属性的解释,需要正确区分并小心使用: + * - [[sharedMaterials]] 是共享材质,所有使用此材质资源的组件实例都默认使用材质的共享实例对象,所有修改都会影响所有使用它的组件实例。 + * - [[materials]] 是专为组件对象创建的独立材质实例,所有修改仅会影响当前组件对象。 + * - 使用 [[getRenderMaterial]] 获取的渲染材质是用于实际渲染流程的材质对象,当存在材质实例的时候,永远使用材质实例。 + * 默认情况下,渲染组件使用共享材质进行渲染,材质实例也不会被创建出来。仅在用户通过 [[material]],[[materials]] 和 [[getMaterialInstance]] 接口获取材质时才会创建材质实例。 + */ +@ccclass('cc.Renderer') +export class Renderer extends Component { + /** + * @en Get the default shared material + * @zh 获取默认的共享材质 + */ + get sharedMaterial () { + return this.getMaterial(0); } + /** + * @en All shared materials of model + * @zh 模型的所有共享材质 + */ @type(Material) @displayOrder(0) @displayName('Materials') @@ -82,13 +90,24 @@ export class RenderableComponent extends Component { } } - // _materials should be defined after sharedMaterials for Editor reset component reason - @type([Material]) - protected _materials: (Material | null)[] = []; + /** + * @en The default material instance, it will create a new instance from the default shared material if not created yet. + * @zh 获取默认的材质实例,如果还没有创建,将会根据默认共享材质创建一个新的材质实例 + */ + get material (): MaterialInstance | null { + return this.getMaterialInstance(0); + } + + set material (val: Material | MaterialInstance | null) { + if (this._materials.length === 1 && !this._materialInstances[0] && this._materials[0] === val) { + return; + } + this.setMaterialInstance(val, 0); + } /** * @en The materials of the model. - * @zh 模型材质。 + * @zh 所有模型材质。 */ get materials (): (MaterialInstance | null)[] { for (let i = 0; i < this._materials.length; i++) { @@ -114,14 +133,12 @@ export class RenderableComponent extends Component { } } + // _materials should be defined after sharedMaterials for Editor reset component reason + @type([Material]) + protected _materials: (Material | null)[] = []; + protected _materialInstances: (MaterialInstance | null)[] = []; - protected _models: scene.Model[] = []; - - get sharedMaterial () { - return this.getMaterial(0); - } - /** * @en Get the shared material asset of the specified sub-model. * @zh 获取指定子模型的共享材质资源。 @@ -151,20 +168,10 @@ export class RenderableComponent extends Component { this._onMaterialModified(index, this._materials[index]); } - get material (): MaterialInstance | null { - return this.getMaterialInstance(0); - } - - set material (val: Material | MaterialInstance | null) { - if (this._materials.length === 1 && !this._materialInstances[0] && this._materials[0] === val) { - return; - } - this.setMaterialInstance(val, 0); - } - /** * @en Get the material instance of the specified sub-model. - * @zh 获取指定子模型的材质实例。 + * It will create a new instance from the corresponding shared material if not created yet. + * @zh 获取指定子模型的材质实例。如果还没有创建,将会根据对应的共享材质创建一个新的材质实例 */ public getMaterialInstance (idx: number): MaterialInstance | null { const mat = this._materials[idx]; @@ -223,19 +230,6 @@ export class RenderableComponent extends Component { return this._materialInstances[index] || this._materials[index]; } - /** - * @legacyPublic - */ - public _collectModels (): scene.Model[] { - return this._models; - } - - protected _attachToScene () { - } - - protected _detachFromScene () { - } - protected _onMaterialModified (index: number, material: Material | null) { } @@ -244,9 +238,4 @@ export class RenderableComponent extends Component { protected _clearMaterials () { } - - protected _onVisibilityChange (val) { - } } - -legacyCC.RenderableComponent = RenderableComponent; diff --git a/cocos/core/components/system.ts b/cocos/core/components/system.ts index f4cdad50f7..0fd4988eea 100644 --- a/cocos/core/components/system.ts +++ b/cocos/core/components/system.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { ISchedulable } from '../scheduler'; import { Enum } from '../value-types/enum'; @@ -91,4 +89,6 @@ export default class System implements ISchedulable { * @param dt Delta time after the last frame */ postUpdate (dt: number) {} + + destroy () {} } diff --git a/cocos/core/curves/bezier.ts b/cocos/core/curves/bezier.ts index 8efeb84f87..d083073272 100644 --- a/cocos/core/curves/bezier.ts +++ b/cocos/core/curves/bezier.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module animation - */ - import { legacyCC } from '../global-exports'; export type BezierControlPoints = [ number, number, number, number ]; diff --git a/cocos/core/curves/curve.ts b/cocos/core/curves/curve.ts index 920b17ea57..0791a8b3fc 100644 --- a/cocos/core/curves/curve.ts +++ b/cocos/core/curves/curve.ts @@ -296,6 +296,7 @@ export class RealCurve extends KeyframeCurve { * Defaults to `ExtrapolationMode.CLAMP`. * @zh * 获取或设置此曲线的前向外推模式。 + * 默认为 `ExtrapolationMode.CLAMP`。 */ public preExtrapolation: ExtrapolationMode = ExtrapolationMode.CLAMP; @@ -305,6 +306,7 @@ export class RealCurve extends KeyframeCurve { * Defaults to `ExtrapolationMode.CLAMP`. * @zh * 获取或设置此曲线的后向外推模式。 + * 默认为 `ExtrapolationMode.CLAMP`。 */ public postExtrapolation: ExtrapolationMode = ExtrapolationMode.CLAMP; @@ -312,7 +314,7 @@ export class RealCurve extends KeyframeCurve { * @en * Evaluates this curve at specified time. * @zh - * 求值此曲线在指定时间上的值。 + * 计算此曲线在指定时间上的值。 * @param time Input time. * @returns Result value. */ @@ -391,7 +393,10 @@ export class RealCurve extends KeyframeCurve { } /** + * @en * Adds a keyframe into this curve. + * @zh + * 添加一个关键帧到此曲线。 * @param time Time of the keyframe. * @param value Value of the keyframe. * @returns The index to the new keyframe. @@ -401,7 +406,10 @@ export class RealCurve extends KeyframeCurve { } /** + * @en * Assigns all keyframes. + * @zh + * 赋值所有关键帧。 * @param keyframes An iterable to keyframes. The keyframes should be sorted by their time. */ public assignSorted (keyframes: Iterable<[number, RealKeyframeValueParameters]>): void; @@ -433,7 +441,10 @@ export class RealCurve extends KeyframeCurve { } /** + * @en * Returns if this curve is constant. + * @zh + * 返回此曲线是否是常量曲线。 * @param tolerance The tolerance. * @returns Whether it is constant. */ @@ -445,6 +456,9 @@ export class RealCurve extends KeyframeCurve { return this._values.every((frame) => approx(frame.value, firstVal, tolerance)); } + /** + * @internal + */ public [serializeTag] (output: SerializationOutput, context: SerializationContext) { if (!context.toCCON) { output.writeThis(); @@ -492,6 +506,9 @@ export class RealCurve extends KeyframeCurve { } } + /** + * @internal + */ public [deserializeTag] (input: SerializationInput, context: DeserializationContext) { if (!context.fromCCON) { input.readThis(); diff --git a/cocos/core/curves/keyframe-curve.ts b/cocos/core/curves/keyframe-curve.ts index 64f3808a73..9ce1abf87a 100644 --- a/cocos/core/curves/keyframe-curve.ts +++ b/cocos/core/curves/keyframe-curve.ts @@ -8,32 +8,47 @@ import type { CurveBase } from './curve-base'; type KeyFrame = [number, TKeyframeValue]; /** - * Curve. + * @en + * Keyframe curve. + * @zh + * 关键帧曲线。 */ export class KeyframeCurve implements CurveBase, Iterable> { /** + * @en * Gets the count of keyframes. + * @zh + * 获取关键帧数量。 */ get keyFramesCount () { return this._times.length; } /** - * Gets the minimal time. + * @en + * Gets the minimal keyframe time on this curve. + * @zh + * 获取此曲线上最小的关键帧时间。 */ get rangeMin () { return this._times[0]; } /** - * Gets the maximum time. + * @en + * Gets the maximum keyframe time on this curve. + * @zh + * 获取此曲线上最大的关键帧时间。 */ get rangeMax () { return this._times[this._values.length - 1]; } /** + * @en * Returns an iterator to keyframe pairs. + * @zh + * 返回关键帧对的迭代器。 */ [Symbol.iterator] () { let index = 0; @@ -57,22 +72,40 @@ export class KeyframeCurve implements CurveBase, Iterable> { return this; } + /** + * @en + * Returns an iterator to keyframe times. + * @zh + * 返回关键帧时间的迭代器。 + */ public times (): Iterable { return this._times; } + /** + * @en + * Returns an iterator to keyframe values. + * @zh + * 返回关键帧值的迭代器。 + */ public values (): Iterable { return this._values; } /** + * @en * Gets the time of specified keyframe. + * @zh + * 获取指定关键帧上的时间。 * @param index Index to the keyframe. * @returns The keyframe 's time. */ @@ -81,7 +114,10 @@ export class KeyframeCurve implements CurveBase, Iterable implements CurveBase, Iterable implements CurveBase, Iterable implements CurveBase, Iterable implements CurveBase, Iterable implements CurveBase, Iterable): void; /** + * @en * Assigns all keyframes. + * @zh + * 赋值所有关键帧。 * @param times Times array. Should be sorted. * @param values Values array. Corresponding to each time in `times`. */ @@ -158,7 +212,10 @@ export class KeyframeCurve implements CurveBase, Iterable; @@ -87,29 +109,43 @@ function createQuatKeyframeValue (params: QuatKeyframeValueParameters) { } /** + * @en * Quaternion curve. + * @zh + * 四元数曲线 */ @ccclass('cc.QuatCurve') export class QuatCurve extends KeyframeCurve { /** - * Gets or sets the operation should be taken - * if input time is less than the time of first keyframe when evaluating this curve. + * @en + * Gets or sets the pre-extrapolation-mode of this curve. * Defaults to `ExtrapolationMode.CLAMP`. + * @zh + * 获取或设置此曲线的前向外推模式。 + * 默认为 `ExtrapolationMode.CLAMP`。 */ @serializable public preExtrapolation: ExtrapolationMode = ExtrapolationMode.CLAMP; /** - * Gets or sets the operation should be taken - * if input time is greater than the time of last keyframe when evaluating this curve. + * @en + * Gets or sets the post-extrapolation-mode of this curve. * Defaults to `ExtrapolationMode.CLAMP`. + * @zh + * 获取或设置此曲线的后向外推模式。 + * 默认为 `ExtrapolationMode.CLAMP`。 */ @serializable public postExtrapolation: ExtrapolationMode = ExtrapolationMode.CLAMP; /** + * @en * Evaluates this curve at specified time. + * @zh + * 计算此曲线在指定时间上的值。 * @param time Input time. + * @param quat If specified, this value will be filled and returned. + * Otherwise a new quaternion object will be filled and returned. * @returns Result value. */ public evaluate (time: number, quat?: Quat): Quat { @@ -235,6 +271,9 @@ export class QuatCurve extends KeyframeCurve { } } + /** + * @internal + */ public [serializeTag] (output: SerializationOutput, context: SerializationContext) { if (!context.toCCON) { output.writeThis(); @@ -328,6 +367,9 @@ export class QuatCurve extends KeyframeCurve { output.writeProperty('bytes', bytes); } + /** + * @internal + */ public [deserializeTag] (input: SerializationInput, context: DeserializationContext) { if (!context.fromCCON) { input.readThis(); diff --git a/cocos/core/data/class.ts b/cocos/core/data/class.ts index 9c5cbb1388..f5370ab9af 100644 --- a/cocos/core/data/class.ts +++ b/cocos/core/data/class.ts @@ -24,8 +24,6 @@ THE SOFTWARE. */ - - import { DEV, EDITOR, SUPPORT_JIT, TEST } from 'internal:constants'; import { errorID, warnID, error } from '../platform/debug'; import * as js from '../utils/js'; @@ -41,6 +39,7 @@ import { legacyCC } from '../global-exports'; import { PropertyStash, PropertyStashInternalFlag } from './class-stash'; const DELIMETER = attributeUtils.DELIMETER; +const CCCLASS_TAG = '__ctors__'; // Still use this historical name to avoid unsynchronized version issue function pushUnique (array, item) { if (array.indexOf(item) < 0) { @@ -48,48 +47,6 @@ function pushUnique (array, item) { } } -const deferredInitializer: any = { - - // Configs for classes which needs deferred initialization - datas: null, - - // register new class - // data - {cls: cls, cb: properties, mixins: options.mixins} - push (data) { - if (this.datas) { - this.datas.push(data); - } else { - this.datas = [data]; - // start a new timer to initialize - const self = this; - setTimeout(() => { - self.init(); - }, 0); - } - }, - - init () { - const datas = this.datas; - if (datas) { - for (let i = 0; i < datas.length; ++i) { - const data = datas[i]; - const cls = data.cls; - let properties = data.props; - if (typeof properties === 'function') { - properties = properties(); - } - const name = js.getClassName(cls); - if (properties) { - declareProperties(cls, name, properties, cls.$super, data.mixins); - } else { - errorID(3633, name); - } - } - this.datas = null; - } - }, -}; - // both getter and prop must register the name into __props__ array function appendProp (cls, name) { if (DEV) { @@ -172,15 +129,7 @@ function getDefault (defaultVal) { return defaultVal; } -function mixinWithInherited (dest, src, filter?) { - for (const prop in src) { - if (!dest.hasOwnProperty(prop) && (!filter || filter(prop))) { - Object.defineProperty(dest, prop, js.getPropertyDescriptor(src, prop)!); - } - } -} - -function doDefine (className, baseClass, mixins, options) { +function doDefine (className, baseClass, options) { const ctor = options.ctor; if (DEV) { @@ -190,35 +139,18 @@ function doDefine (className, baseClass, mixins, options) { } } - const ctors = [ctor]; - const fireClass = ctor; + js.value(ctor, CCCLASS_TAG, true, true); - js.value(fireClass, '__ctors__', ctors.length > 0 ? ctors : null, true); - - const prototype = fireClass.prototype; + const prototype = ctor.prototype; if (baseClass) { - fireClass.$super = baseClass; + ctor.$super = baseClass; } - if (mixins) { - for (let m = mixins.length - 1; m >= 0; m--) { - const mixin = mixins[m]; - mixinWithInherited(prototype, mixin.prototype); - - // mixin attributes - if (CCClass._isCCClass(mixin)) { - mixinWithInherited(attributeUtils.getClassAttrs(fireClass), attributeUtils.getClassAttrs(mixin)); - } - } - // restore constuctor overridden by mixin - prototype.constructor = fireClass; - } - - js.setClassName(className, fireClass); - return fireClass; + js.setClassName(className, ctor); + return ctor; } -function define (className, baseClass, mixins, options) { +function define (className, baseClass, options) { const Component = legacyCC.Component; const frame = RF.peek(); @@ -234,7 +166,7 @@ function define (className, baseClass, mixins, options) { className = className || frame.script; } - const cls = doDefine(className, baseClass, mixins, options); + const cls = doDefine(className, baseClass, options); if (EDITOR) { // for RenderPipeline, RenderFlow, RenderStage @@ -314,22 +246,13 @@ function escapeForJS (s) { // simple test variable name const IDENTIFIER_RE = /^[A-Za-z_$][0-9A-Za-z_$]*$/; -function declareProperties (cls, className, properties, baseClass, mixins) { +function declareProperties (cls, className, properties, baseClass) { cls.__props__ = []; if (baseClass && baseClass.__props__) { cls.__props__ = baseClass.__props__.slice(); } - if (mixins) { - for (let m = 0; m < mixins.length; ++m) { - const mixin = mixins[m]; - if (mixin.__props__) { - cls.__props__ = cls.__props__.concat(mixin.__props__.filter((x) => cls.__props__.indexOf(x) < 0)); - } - } - } - if (properties) { // 预处理属性 preprocessAttrs(properties, className, cls); @@ -353,15 +276,13 @@ export function CCClass (options: { extends: null | (Function & { __props__?: any; _sealed?: boolean }); ctor: TFunction; properties?: any; - mixins?: (Function & { __props__?: any })[]; editor?: any; }) { let name = options.name; const base = options.extends/* || CCObject */; - const mixins = options.mixins; // create constructor - const cls = define(name, base, mixins, options); + const cls = define(name, base, options); if (!name) { name = legacyCC.js.getClassName(cls); } @@ -373,19 +294,7 @@ export function CCClass (options: { // define Properties const properties = options.properties; - if (typeof properties === 'function' - || (base && base.__props__ === null) - || (mixins && mixins.some((x) => x.__props__ === null)) - ) { - if (DEV) { - error('not yet implement deferred properties.'); - } else { - deferredInitializer.push({ cls, props: properties, mixins }); - cls.__props__ = cls.__values__ = null; - } - } else { - declareProperties(cls, name, properties, base, options.mixins); - } + declareProperties(cls, name, properties, base); const editor = options.editor; if (editor) { @@ -401,9 +310,9 @@ export function CCClass (options: { /** * @en - * Checks whether the constructor is created by `Class`. + * Checks whether the constructor is initialized by `@ccclass`. * @zh - * 检查构造函数是否由 `Class` 创建。 + * 检查构造函数是否经由 `@ccclass` 初始化。 * @method _isCCClass * @param {Function} constructor * @return {Boolean} @@ -413,7 +322,7 @@ CCClass._isCCClass = function isCCClass (constructor): boolean { // Does not support fastDefined class (ValueType). // Use `instanceof ValueType` if necessary. // eslint-disable-next-line no-prototype-builtins, @typescript-eslint/no-unsafe-return - return constructor?.hasOwnProperty?.('__ctors__'); // __ctors__ is not inherited + return constructor?.hasOwnProperty?.(CCCLASS_TAG); // Remember, the static variable is not inheritable }; // @@ -427,7 +336,6 @@ CCClass._isCCClass = function isCCClass (constructor): boolean { // CCClass.fastDefine = function (className, constructor, serializableFields) { js.setClassName(className, constructor); - // constructor.__ctors__ = constructor.__ctors__ || null; const props = constructor.__props__ = constructor.__values__ = Object.keys(serializableFields); const attrs = attributeUtils.getClassAttrs(constructor); for (let i = 0; i < props.length; i++) { @@ -440,6 +348,17 @@ CCClass.fastDefine = function (className, constructor, serializableFields) { CCClass.Attr = attributeUtils; CCClass.attr = attributeUtils.attr; +/** + * Returns if the class is a cc-class or is fast defined. + * @param constructor The constructor of the class. + * @returns Judge result. + */ +// eslint-disable-next-line @typescript-eslint/ban-types +export function isCCClassOrFastDefined (constructor: Constructor) { + // eslint-disable-next-line no-prototype-builtins, @typescript-eslint/no-unsafe-return + return constructor?.hasOwnProperty?.('__values__'); +} + /** * Return all super classes. * @param constructor The Constructor. diff --git a/cocos/core/data/custom-serializable.ts b/cocos/core/data/custom-serializable.ts index 106f6ca59a..3cf2e3f053 100644 --- a/cocos/core/data/custom-serializable.ts +++ b/cocos/core/data/custom-serializable.ts @@ -2,13 +2,13 @@ import { assertIsNonNullable, assertIsTrue } from './utils/asserts'; /** * Tag to define the custom serialization method. - * @legacyPublic + * @internal */ export const serializeTag = Symbol('[[Serialize]]'); /** * Tag to define the custom deserialization method. - * @legacyPublic + * @internal */ export const deserializeTag = Symbol('[[Deserialize]]'); @@ -52,7 +52,7 @@ export interface SerializationOutput { export type SerializationContext = { /** - * The root value passed to serialization procedure. + * The main serializing asset or root node in the scene/prefab passed to serialization procedure. */ root: unknown; @@ -82,7 +82,7 @@ export interface CustomSerializable { /** * Enables the custom serialize/deserialize method only if the (de)serialize procedure is targeting CCON. - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ export const enableIfCCON: MethodDecorator = ( // eslint-disable-next-line @typescript-eslint/ban-types diff --git a/cocos/core/data/decorators/ccclass.ts b/cocos/core/data/decorators/ccclass.ts index ff4be77b2d..a8100b82ad 100644 --- a/cocos/core/data/decorators/ccclass.ts +++ b/cocos/core/data/decorators/ccclass.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module decorator - */ - import { DEV } from 'internal:constants'; import { js } from '../../utils/js'; import { CCClass } from '../class'; @@ -35,7 +30,7 @@ import { doValidateMethodWithProps_DEV } from '../utils/preprocess-class'; import { CACHE_KEY, makeSmartClassDecorator } from './utils'; /** - * @en Declare a standard class as a CCClass, please refer to the [document](https://docs.cocos.com/creator3d/manual/zh/scripting/ccclass.html) + * @en Declare a standard class as a CCClass, please refer to the [document](https://docs.cocos.com/creator3d/manual/en/scripting/ccclass.html) * @zh 将标准写法的类声明为 CC 类,具体用法请参阅[类型定义](https://docs.cocos.com/creator3d/manual/zh/scripting/ccclass.html)。 * @param name - The class name used for serialization. * @example diff --git a/cocos/core/data/decorators/component.ts b/cocos/core/data/decorators/component.ts index c6d796ef8d..3a07b3b90a 100644 --- a/cocos/core/data/decorators/component.ts +++ b/cocos/core/data/decorators/component.ts @@ -23,13 +23,8 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module decorator - */ - -import { CCClass } from '../class'; import { DEV } from 'internal:constants'; +import { CCClass } from '../class'; import { makeEditorClassDecoratorFn, makeSmartEditorClassDecorator, emptySmartClassDecorator } from './utils'; /** diff --git a/cocos/core/data/decorators/editable.ts b/cocos/core/data/decorators/editable.ts index 042c5329d5..2549411eb6 100644 --- a/cocos/core/data/decorators/editable.ts +++ b/cocos/core/data/decorators/editable.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module decorator - */ - import { DEV, EDITOR } from 'internal:constants'; import { IExposedAttributes } from '../utils/attribute-defines'; import { getOrCreatePropertyStash } from './property'; @@ -74,8 +69,9 @@ export const executeInEditMode: ClassDecorator & ((yes?: boolean) => ClassDecora export const menu: (path: string) => ClassDecorator = DEV ? makeEditorClassDecoratorFn('menu') : emptyDecoratorFn; /** - * @en When {{executeInEditMode}} is set, this decorator will decide when a node with the component is on focus whether the editor should running in high FPS mode. - * @zh 当指定了 "executeInEditMode" 以后,playOnFocus 可以在选中当前组件所在的节点时,提高编辑器的场景刷新频率到 60 FPS,否则场景就只会在必要的时候进行重绘。 + * @en When [[_decorator.executeInEditMode]] is set, + * this decorator will make the editor running in high FPS mode when a node with the component is focused + * @zh 当指定了 [[_decorator.executeInEditMode]] 以后,playOnFocus 可以在选中当前组件所在的节点时,提高编辑器的场景刷新频率到 60 FPS,否则场景就只会在必要的时候进行重绘。 * @example * ```ts * import { _decorator, Component } from 'cc'; @@ -129,7 +125,8 @@ export const inspector: (url: string) => ClassDecorator = DEV ? makeEditorCla export const icon: (url: string) => ClassDecorator = DEV ? makeEditorClassDecoratorFn('icon') : emptyDecoratorFn; /** - * @en Define the help documentation url, if given, the component section in the **inspector** will have a help documentation icon reference to the web page given. + * @en Define the help documentation url, + * if given, the component section in the **Inspector** will have a help documentation icon reference to the web page given. * @zh 指定当前组件的帮助文档的 url,设置过后,在 **属性检查器** 中就会出现一个帮助图标,用户点击将打开指定的网页。 * @param url The url of the help documentation * @example diff --git a/cocos/core/data/decorators/index.ts b/cocos/core/data/decorators/index.ts index 7fd0fcff25..0c2f2a065d 100644 --- a/cocos/core/data/decorators/index.ts +++ b/cocos/core/data/decorators/index.ts @@ -22,10 +22,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module decorator - */ export { ccclass } from './ccclass'; export * from './component'; diff --git a/cocos/core/data/decorators/override.ts b/cocos/core/data/decorators/override.ts index 08f566e9e8..04211fc11e 100644 --- a/cocos/core/data/decorators/override.ts +++ b/cocos/core/data/decorators/override.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module decorator - */ - import { LegacyPropertyDecorator } from './utils'; import { getOrCreatePropertyStash } from './property'; diff --git a/cocos/core/data/decorators/property.ts b/cocos/core/data/decorators/property.ts index 28ac26d8a1..9adaf59ea4 100644 --- a/cocos/core/data/decorators/property.ts +++ b/cocos/core/data/decorators/property.ts @@ -23,12 +23,7 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module decorator - */ - -import { DEV, EDITOR, TEST } from 'internal:constants'; +import { DEV, EDITOR, JSB, TEST } from 'internal:constants'; import { CCString, CCInteger, CCFloat, CCBoolean } from '../utils/attribute'; import { IExposedAttributes } from '../utils/attribute-defines'; import { LegacyPropertyDecorator, getSubDict, getClassCache, BabelPropertyDecoratorDescriptor } from './utils'; @@ -37,6 +32,7 @@ import { js } from '../../utils/js'; import { getFullFormOfProperty } from '../utils/preprocess-class'; import { ClassStash, PropertyStash, PropertyStashInternalFlag } from '../class-stash'; +// eslint-disable-next-line @typescript-eslint/ban-types export type SimplePropertyType = Function | string | typeof CCString | typeof CCInteger | typeof CCFloat | typeof CCBoolean; export type PropertyType = SimplePropertyType | SimplePropertyType[]; @@ -58,7 +54,7 @@ export function property (options?: IPropertyOptions): LegacyPropertyDecorator; * @en Declare as a CCClass property with the property type * @zh 标注属性为 cc 属性。
* 等价于`@property({type})`。 - * @param type A {{ccclass}} type or a {{ValueType}} + * @param type A [[ccclass]] type or a [[ValueType]] */ export function property (type: PropertyType): LegacyPropertyDecorator; @@ -203,6 +199,7 @@ function mergePropertyOptions ( if (options) { fullOptions = getFullFormOfProperty(options, isGetset); } + // @ts-expect-error enum PropertyStashInternalFlag is used as number const propertyRecord: PropertyStash = js.mixin(propertyStash, fullOptions || options || {}); if (isGetset) { @@ -236,6 +233,7 @@ function mergePropertyOptions ( ); if ((EDITOR && !window.Build) || TEST) { + // eslint-disable-next-line no-prototype-builtins if (!fullOptions && options && options.hasOwnProperty('default')) { warnID(3653, propertyKey, js.getClassName(ctor)); } @@ -250,6 +248,12 @@ function setDefaultValue ( propertyKey: PropertyKey, descriptor: BabelPropertyDecoratorDescriptor | undefined, ) { + // Default values are needed by editor, and now editor run with web version, so don't + // have to provide default values. + if (JSB) { + return; + } + if (descriptor) { // In case of Babel, if an initializer is given for class field. // That initializer is passed to `descriptor.initializer`. diff --git a/cocos/core/data/decorators/serializable.ts b/cocos/core/data/decorators/serializable.ts index 084b156715..66adc61fdb 100644 --- a/cocos/core/data/decorators/serializable.ts +++ b/cocos/core/data/decorators/serializable.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module decorator - */ - import { EDITOR, TEST } from 'internal:constants'; import { emptyDecorator, LegacyPropertyDecorator } from './utils'; import { getOrCreatePropertyStash } from './property'; @@ -78,13 +73,13 @@ function setImplicitSerializable (propertyStash: PropertyStash) { * For example: * ```ts * import { _decorator } from 'cc'; - * \@_decorator.ccclass - * \@_decorator.uniquelyReferenced + * @_decorator.ccclass + * @_decorator.uniquelyReferenced * class Foo { } * - * \@_decorator.ccclass + * @_decorator.ccclass * class Bar { - * \@_decorator.property + * @_decorator.property * public foo = new Foo(); * } * @@ -101,13 +96,13 @@ function setImplicitSerializable (propertyStash: PropertyStash) { * 例如: * ```ts * import { _decorator } from 'cc'; - * \@_decorator.ccclass - * \@_decorator.uniquelyReferenced + * @_decorator.ccclass + * @_decorator.uniquelyReferenced * class Foo { } * - * \@_decorator.ccclass + * @_decorator.ccclass * class Bar { - * \@_decorator.property + * @_decorator.property * public foo = new Foo(); * } * diff --git a/cocos/core/data/decorators/type.ts b/cocos/core/data/decorators/type.ts index 5fdaba9d25..1f94d1d38b 100644 --- a/cocos/core/data/decorators/type.ts +++ b/cocos/core/data/decorators/type.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module decorator - */ - import { LegacyPropertyDecorator } from './utils'; import { property } from './property'; import { CCString, CCInteger, CCFloat, CCBoolean, PrimitiveType } from '../utils/attribute'; diff --git a/cocos/core/data/decorators/utils.ts b/cocos/core/data/decorators/utils.ts index 18c8846807..d5d28785b8 100644 --- a/cocos/core/data/decorators/utils.ts +++ b/cocos/core/data/decorators/utils.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module decorator - */ - import { DEV } from 'internal:constants'; import { CCClass } from '../class'; import { error } from '../../platform/debug'; diff --git a/cocos/core/data/deserialize-dynamic.ts b/cocos/core/data/deserialize-dynamic.ts index e90ed26021..ab54008dee 100644 --- a/cocos/core/data/deserialize-dynamic.ts +++ b/cocos/core/data/deserialize-dynamic.ts @@ -40,6 +40,7 @@ import type { deserialize, CCClassConstructor } from './deserialize'; import { CCON } from './ccon'; import { assertIsTrue } from './utils/asserts'; import { reportMissingClass as defaultReportMissingClass } from './report-missing-class'; +import { Asset } from '..'; function compileObjectTypeJit ( sources: string[], @@ -53,7 +54,6 @@ function compileObjectTypeJit ( if (!assumeHavePropIfIsValue) { sources.push('if(prop){'); } - // @ts-expect-error Typing const ctorCode = js.getClassName(defaultValue); sources.push(`s._deserializeFastDefinedObject(o${accessorToSet},prop,${ctorCode});`); if (!assumeHavePropIfIsValue) { @@ -110,7 +110,7 @@ function compileDeserializeJIT (self: _Deserializer, klass: CCClassConstructor): CompiledDeserializeFn { - const fastMode = misc.BUILTIN_CLASSID_RE.test(js._getClassId(klass)); + const fastMode = misc.BUILTIN_CLASSID_RE.test(js.getClassId(klass)); const shouldCopyId = js.isChildClassOf(klass, legacyCC._BaseNode) || js.isChildClassOf(klass, legacyCC.Component); let shouldCopyRawData = false; @@ -217,10 +217,11 @@ function compileDeserializeNative (_self: _Deserializer, klass: CCClassConstruct } // function undefined object(null) string boolean number const defaultValue = CCClass.getDefault(attrs[propName + POSTFIX_DEFAULT]); + const userType = attrs[propName + POSTFIX_TYPE] as AnyFunction | undefined; let isPrimitiveType = false; - if (fastMode) { + if (fastMode && (defaultValue !== undefined || userType)) { const userType = attrs[propName + POSTFIX_TYPE]; - if (defaultValue === undefined && userType) { + if (defaultValue === undefined) { isPrimitiveType = userType instanceof Attr.PrimitiveType; } else { const defaultType = typeof defaultValue; @@ -545,7 +546,7 @@ class _Deserializer { const klass = this._classFinder(type, value, owner, propName); if (!klass) { - const notReported = this._classFinder === js._getClassById; + const notReported = this._classFinder === js.getClassById; if (notReported) { this._reportMissingClass(type); } @@ -574,7 +575,6 @@ class _Deserializer { if (DEBUG) { error(`Deserialize ${klass.name} failed, ${(e as { stack: string; }).stack}`); } - this._reportMissingClass(type); const obj = createObject(MissingScript); this._deserializeInto(value, obj, MissingScript); return obj; @@ -666,14 +666,10 @@ class _Deserializer { object: Record, deserialized: Record, constructor: AnyFunction) { - try { - if (!JSON.parse(JSON.stringify(deserialized._$erialized))) { - error(`Unable to load previously serialized data. ${JSON.stringify(deserialized)}`); - } - } catch (e) { - error(`Error when checking MissingScript 7, ${e}`); - } rawDeserialize(deserializer, object, deserialized, constructor); + if (!object._$erialized) { + error(`Unable to stash previously serialized data. ${JSON.stringify(deserialized)}`); + } }; } } catch (e) { @@ -835,7 +831,7 @@ export function deserializeDynamic (data: SerializedData | CCON, details: Detail reportMissingClass?: ReportMissingClass; }) { options = options || {}; - const classFinder = options.classFinder || js._getClassById; + const classFinder = options.classFinder || js.getClassById; const createAssetRefs = options.createAssetRefs || sys.platform === Platform.EDITOR_CORE; const customEnv = options.customEnv; const ignoreEditorOnly = options.ignoreEditorOnly; @@ -853,7 +849,7 @@ export function deserializeDynamic (data: SerializedData | CCON, details: Detail _Deserializer.pool.put(deserializer); if (createAssetRefs) { - details.assignAssetsBy(EditorExtends.serialize.asAsset); + details.assignAssetsBy((uuid, options) => (EditorExtends.serialize.asAsset(uuid, options.type) as Asset)); } // var afterJson = JSON.stringify(data, null, 2); diff --git a/cocos/core/data/deserialize.ts b/cocos/core/data/deserialize.ts index c2d5236720..f1cec4fee1 100644 --- a/cocos/core/data/deserialize.ts +++ b/cocos/core/data/deserialize.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { EDITOR, TEST, PREVIEW, BUILD, DEBUG, JSB, DEV } from 'internal:constants'; import { legacyCC } from '../global-exports'; import { ValueType } from '../value-types'; @@ -536,20 +534,32 @@ interface ICustomClass { */ export class Details { /** - * the obj list whose field needs to load asset by uuid + * @en + * the object list whose field needs to load asset by uuid + * @zh + * 对象列表,其中每个对象有属性需要通过 uuid 进行资源加载 */ uuidObjList: IFileData[File.DependObjs] | null = null; /** + * @en * the corresponding field name which referenced to the asset + * @zh + * 引用着资源的字段名称 */ uuidPropList: IFileData[File.DependKeys] | null = null; /** + * @en * list of the depends assets' uuid + * @zh + * 依赖资源的 uuid 列表 */ uuidList: IFileData[File.DependUuidIndices] | null = null; /** + * @en * list of the depends assets' type + * @zh + * 依赖的资源类型列表 */ uuidTypeList: string[] = []; @@ -558,7 +568,11 @@ export class Details { }, 5); // eslint-disable-next-line @typescript-eslint/ban-types - public declare assignAssetsBy: Function; + public declare assignAssetsBy: (getter: (uuid: string, options: { + type: Constructor; + owner: Record; + prop: string; + }) => Asset) => void; /** * @method init @@ -619,13 +633,22 @@ Details.pool.get = function () { return this._get() || new Details(); }; if (EDITOR || TEST) { - Details.prototype.assignAssetsBy = function (getter: (uuid: string, type: Constructor) => any) { + Details.prototype.assignAssetsBy = function (getter: (uuid: string, options: { + type: Constructor; + owner: Record; + prop: string; + }) => any) { for (let i = 0, len = this.uuidList!.length; i < len; i++) { - const obj = this.uuidObjList![i]; - const prop = this.uuidPropList![i]; + const obj = this.uuidObjList![i] as Record; + const prop = this.uuidPropList![i] as string; const uuid = this.uuidList![i]; const type = this.uuidTypeList[i]; - obj[prop] = getter(uuid as string, js._getClassById(type) as Constructor || Asset); + const _type = js.getClassById(type) as Constructor || Asset; + obj[prop] = getter(uuid as string, { + type: _type, + owner: obj, + prop, + }); } }; } @@ -918,7 +941,7 @@ function doLookupClass (classFinder, type: string, container: any[], index: numb } function lookupClasses (data: IPackedFileData, silent: boolean, customFinder: ClassFinder | undefined, reportMissingClass: deserialize.ReportMissingClass) { - const classFinder = customFinder || js._getClassById; + const classFinder = customFinder || js.getClassById; const classes = data[File.SharedClasses]; for (let i = 0; i < classes.length; ++i) { const klassLayout = classes[i]; diff --git a/cocos/core/data/editor-extras-tag.ts b/cocos/core/data/editor-extras-tag.ts index 574ab8cd6e..fe47315fe3 100644 --- a/cocos/core/data/editor-extras-tag.ts +++ b/cocos/core/data/editor-extras-tag.ts @@ -1,13 +1,16 @@ /** * Tag to visit editor extras of an object. Never concern about its value please. + * @internal */ export const editorExtrasTag = '__editorExtras__'; /** * Engine classes with this kind of signatures are integrated with editor extendability. + * @internal */ export interface EditorExtendableObject { /** + * @en * The editor extras on this object. * * BE CAREFUL: this property is currently governed by Cocos Creator Editor. @@ -26,6 +29,24 @@ export interface EditorExtendableObject { * ```ts * node.__editorExtras__ = {}; // Error: might be break in future. * ``` + * @zh + * 此对象的编辑器额外数据。 + * + * **注意**:此属性目前由 Cocos Creator 编辑器管理。 + * 它的定义不管是对于引擎还是用户代码都是不可见的,也 **不应该** 操作该数据。 + * + * 你应该仅使用编辑器额外数据标签来访问此数据。 + * @example + * ```ts + * import { editorExtrasTag } from 'cc'; + * node[editorExtrasTag] = {}; + * node[editorExtrasTag].someWhat; + * ``` + * 即使你知道目前 `editorExtrasTag === '__editorExtras__'`, + * 也不要通过字符串属性来访问: + * ```ts + * node.__editorExtras__ = {}; // 错误:在未来可能无法生效 + * ``` */ [editorExtrasTag]: unknown; } diff --git a/cocos/core/data/garbage-collection.ts b/cocos/core/data/garbage-collection.ts index 117c5a7886..eff9cff021 100644 --- a/cocos/core/data/garbage-collection.ts +++ b/cocos/core/data/garbage-collection.ts @@ -27,33 +27,53 @@ declare class FinalizationRegistry { unregister (token: any); } +const targetSymbol = Symbol('[[target]]'); + class GarbageCollectionManager { - private _finalizationRegistry: FinalizationRegistry | null = EDITOR ? new FinalizationRegistry(this.finalizationRegistryCallback.bind(this)) : null; + private _finalizationRegistry: FinalizationRegistry | null = EDITOR && typeof FinalizationRegistry !== 'undefined' ? new FinalizationRegistry(this.finalizationRegistryCallback.bind(this)) : null; + private _gcObjects: WeakMap = new WeakMap(); public registerGCObject (gcObject: GCObject): GCObject { - if (EDITOR) { - gcObject._finalizationToken = {}; - const proxy = new Proxy(gcObject, {}); - this._finalizationRegistry!.register(proxy, gcObject, gcObject._finalizationToken); + if (EDITOR && this._finalizationRegistry) { + const token = {}; + const proxy = new Proxy(gcObject, { + get (target, property, receiver) { + if (property === targetSymbol) { + return target; + } + let val = target[property]; + if (typeof val === 'function' && property !== 'constructor') { + const original = val; + val = function newFunc () { + // @ts-expect-error this is referenced to proxy + return original.apply(this[targetSymbol], arguments) as unknown; + }; + } + return val as unknown; + }, + set (target, prop, value, receiver) { + target[prop] = value; + return true; + }, + }); + this._gcObjects.set(token, gcObject); + this._finalizationRegistry.register(proxy, token, token); return proxy; } else { return gcObject; } } - public unregisterGCObject (gcObject: GCObject) { - if (EDITOR) { - this._finalizationRegistry!.unregister(gcObject._finalizationToken); - } - } - public init () { } - private finalizationRegistryCallback (gcObject: GCObject) { - if (gcObject.isValid) { + private finalizationRegistryCallback (token: any) { + const gcObject = this._gcObjects.get(token); + if (gcObject) { + this._gcObjects.delete(token); gcObject.destroy(); } + this._finalizationRegistry!.unregister(token); } public destroy () { diff --git a/cocos/core/data/gc-object.ts b/cocos/core/data/gc-object.ts index 249dde5b58..065b81c09c 100644 --- a/cocos/core/data/gc-object.ts +++ b/cocos/core/data/gc-object.ts @@ -18,34 +18,12 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import { EDITOR } from 'internal:constants'; -import { ccclass } from './decorators'; import { garbageCollectionManager } from './garbage-collection'; -import { CCObject } from './object'; -@ccclass('cc.GCObject') -export class GCObject extends CCObject { - /** - * @legacyPublic - */ - public declare _finalizationToken: any; - - constructor (...arg: ConstructorParameters) { - super(...arg); +export class GCObject { + constructor () { return garbageCollectionManager.registerGCObject(this); } - public equals (gcObject: GCObject | null) { - if (!gcObject) { return false; } - if (EDITOR) { - return gcObject._finalizationToken === this._finalizationToken; - } else { - return gcObject === this; - } - } - - public destroy () { - garbageCollectionManager.unregisterGCObject(this); - return super.destroy(); - } + public destroy () {} } diff --git a/cocos/core/data/index.ts b/cocos/core/data/index.ts index acdf8ef66b..e348ce597f 100644 --- a/cocos/core/data/index.ts +++ b/cocos/core/data/index.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core/data - */ - import * as _decorator from './class-decorator'; import { legacyCC } from '../global-exports'; diff --git a/cocos/core/data/instantiate-jit.ts b/cocos/core/data/instantiate-jit.ts index bb73259da5..f1061e0f1f 100644 --- a/cocos/core/data/instantiate-jit.ts +++ b/cocos/core/data/instantiate-jit.ts @@ -24,14 +24,12 @@ THE SOFTWARE. */ - - // Some helper methods for compile instantiation code import { TEST } from 'internal:constants'; import * as js from '../utils/js'; -import { CCClass } from './class'; -import { CCObject } from './object'; +import { CCClass, isCCClassOrFastDefined } from './class'; +import { CCObject, isCCObject } from './object'; import * as Attr from './utils/attribute'; import { flattenCodeArray } from './utils/compiler'; import { legacyCC } from '../global-exports'; @@ -409,7 +407,7 @@ class Parser { } else if (typeof value === 'string') { return escapeForJS(value); } else { - if (key === '_objFlags' && (obj instanceof CCObject)) { + if (key === '_objFlags' && isCCObject(obj)) { value &= PersistentMask; } return value; @@ -425,7 +423,7 @@ class Parser { // codeArray - the source code array for this object public enumerateObject (codeArray, obj) { const klass = obj.constructor; - if (legacyCC.Class._isCCClass(klass)) { + if (isCCClassOrFastDefined(klass)) { this.enumerateCCClass(codeArray, obj, klass); } else { // primitive javascript object @@ -460,7 +458,7 @@ class Parser { let createCode; const ctor = obj.constructor; - if (legacyCC.Class._isCCClass(ctor)) { + if (isCCClassOrFastDefined(ctor)) { if (this.parent) { if (this.parent instanceof legacyCC.Component) { if (obj instanceof legacyCC._BaseNode || obj instanceof legacyCC.Component) { diff --git a/cocos/core/data/instantiate.ts b/cocos/core/data/instantiate.ts index 7e6c294f4b..eaacf25336 100644 --- a/cocos/core/data/instantiate.ts +++ b/cocos/core/data/instantiate.ts @@ -24,22 +24,17 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core/data - */ - -import { DEV } from 'internal:constants'; +import { DEV, JSB } from 'internal:constants'; import { isDomNode } from '../utils/misc'; import { ValueType } from '../value-types'; -import { CCObject } from './object'; +import { CCObject, isCCObject } from './object'; import { js } from '../utils/js'; import { getError, warn } from '../platform/debug'; import { legacyCC } from '../global-exports'; import { Prefab } from '../assets/prefab'; import { Node } from '../scene-graph/node'; -import { JSB } from '../default-constants'; import { updateChildrenForDeserialize } from '../utils/jsb-utils'; +import { isCCClassOrFastDefined } from './class'; const Destroyed = CCObject.Flags.Destroyed; const PersistentMask = CCObject.Flags.PersistentMask; @@ -107,15 +102,8 @@ export function instantiate (original: any, internalForce?: boolean) { } let clone; - let isCCObject = original instanceof CCObject; - if (JSB) { - if (!isCCObject) { - // @ts-expect-error: jsb related codes. - isCCObject = original instanceof jsb.CCObject; - } - } - if (isCCObject) { + if (isCCObject(original)) { if (original._instantiate) { legacyCC.game._isCloning = true; clone = original._instantiate(null, true); @@ -213,7 +201,7 @@ function enumerateObject (obj, clone, parent) { js.value(obj, '_iN$t', clone, true); objsToClearTmpVar.push(obj); const klass = obj.constructor; - if (legacyCC.Class._isCCClass(klass)) { + if (isCCClassOrFastDefined(klass)) { enumerateCCClass(klass, obj, clone, parent); } else { // primitive javascript object @@ -237,7 +225,7 @@ function enumerateObject (obj, clone, parent) { } } } - if (obj instanceof CCObject) { + if (isCCObject(obj)) { clone._objFlags &= PersistentMask; } } @@ -290,7 +278,7 @@ function instantiateObj (obj, parent) { } const ctor = obj.constructor; - if (legacyCC.Class._isCCClass(ctor)) { + if (isCCClassOrFastDefined(ctor)) { if (parent) { if (parent instanceof legacyCC.Component) { if (obj instanceof legacyCC._BaseNode || obj instanceof legacyCC.Component) { diff --git a/cocos/core/data/object.ts b/cocos/core/data/object.ts index f864914091..a7faa48c4c 100644 --- a/cocos/core/data/object.ts +++ b/cocos/core/data/object.ts @@ -23,17 +23,13 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core/data - */ - import { SUPPORT_JIT, EDITOR, TEST, JSB } from 'internal:constants'; import * as js from '../utils/js'; import { CCClass } from './class'; import { errorID, warnID } from '../platform/debug'; import { legacyCC } from '../global-exports'; import { EditorExtendableObject, editorExtrasTag } from './editor-extras-tag'; +import { copyAllProperties } from '../utils/js'; // definitions for CCObject.Flags @@ -113,7 +109,7 @@ function compileDestruct (obj, ctor) { for (let i = 0; i < propList.length; i++) { key = propList[i]; // eslint-disable-next-line @typescript-eslint/restrict-plus-operands - const attrKey = `${key + legacyCC.Class.Attr.DELIMETER}default`; + const attrKey = `${key}`; if (attrKey in attrs) { if (shouldSkipId && key === '_id') { continue; @@ -192,21 +188,15 @@ class CCObject implements EditorExtendableObject { if (EDITOR) { deferredDestroyTimer = null; } - - if (JSB) { - // release objects which hold for delay GC - // jsb function call - jsb.CCObject._deferredDestroyReleaseObjects(); - } } /** - * @legacyPublic + * @internal */ public declare [editorExtrasTag]: unknown; /** - * @legacyPublic + * @internal */ public _objFlags: number; protected _name: string; @@ -328,14 +318,28 @@ class CCObject implements EditorExtendableObject { // @ts-expect-error no function deferredDestroyTimer = setTimeout(CCObject._deferredDestroy); } + + if (JSB) { + // @ts-expect-error JSB method + this._destroy(); + } + return true; } /** + * @en * Clear all references in the instance. * * NOTE: this method will not clear the getter or setter functions which defined in the instance of CCObject. - * You can override the _destruct method if you need, for example: + * + * @zh + * 清理实例的所有引用 + * 注意:此方法不会清理实例上的 getter 与 setter 方法。 + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + * @example + * ``` + * // You can override the _destruct method if you need, for example: * _destruct: function () { * for (var key in this) { * if (this.hasOwnProperty(key)) { @@ -350,8 +354,7 @@ class CCObject implements EditorExtendableObject { * } * } * } - * - * @legacyPublic + * ``` */ public _destruct () { const ctor: any = this.constructor; @@ -364,7 +367,7 @@ class CCObject implements EditorExtendableObject { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _destroyImmediate () { if (this._objFlags & Destroyed) { @@ -623,6 +626,21 @@ declare namespace CCObject { let __values__: string[]; } +/* + * @en + * Checks whether the object is a CCObject.
+ * + * @zh + * 检查该对象是否为CCObject。
+ * + * @method isCCObject + * @param object + * @return @en Whether it is a CCObject boolean value. @zh 是否为CCObject的布尔值。 + */ +export function isCCObject (object: any) { + return object instanceof CCObject; +} + /* * @en * Checks whether the object is non-nil and not yet destroyed.
@@ -669,13 +687,17 @@ if (EDITOR || TEST) { }); } -legacyCC.Object = CCObject; -export { CCObject }; - declare const jsb: any; if (JSB) { - CCClass.fastDefine('jsb.CCObject', jsb.CCObject, { _name: '', _objFlags: 0, [editorExtrasTag]: {} }); - CCClass.Attr.setClassAttr(jsb.CCObject, editorExtrasTag, 'editorOnly', true); - CCClass.Attr.setClassAttr(jsb.CCObject, 'replicated', 'visible', false); + copyAllProperties(CCObject, jsb.CCObject, ['prototype', 'length', 'name']); + copyAllProperties(CCObject.prototype, jsb.CCObject.prototype, + ['constructor', 'name', 'hideFlags', 'replicated', 'isValid']); + + // @ts-expect-error TS2629 + // eslint-disable-next-line no-class-assign + CCObject = jsb.CCObject; } + +legacyCC.Object = CCObject; +export { CCObject }; diff --git a/cocos/core/data/serialization-metadata.ts b/cocos/core/data/serialization-metadata.ts index 9922e85a3d..8c4a5106d3 100644 --- a/cocos/core/data/serialization-metadata.ts +++ b/cocos/core/data/serialization-metadata.ts @@ -1,7 +1,7 @@ const sMetadataTag = Symbol('cc:SerializationMetadata'); /** - * For internal usage only. DO NOT USE IT IN YOUR CODES. + * @internal DO NOT USE IT IN YOUR CODES. * @param constructor * @returns */ @@ -10,13 +10,16 @@ export function getSerializationMetadata (constructor: Function): SerializationM return (constructor as MayBeInjected)[sMetadataTag]; } +/** + * @internal + */ // eslint-disable-next-line @typescript-eslint/ban-types export function getOrCreateSerializationMetadata (constructor: Function): SerializationMetadata { return (constructor as MayBeInjected)[sMetadataTag] ??= {}; } /** - * For internal usage only. DO NOT USE IT IN YOUR CODES. + * @internal For internal usage only. DO NOT USE IT IN YOUR CODES. */ export interface SerializationMetadata { uniquelyReferenced?: boolean; diff --git a/cocos/core/data/utils/attribute.ts b/cocos/core/data/utils/attribute.ts index 8fb5e85f84..2ece3db581 100644 --- a/cocos/core/data/utils/attribute.ts +++ b/cocos/core/data/utils/attribute.ts @@ -111,17 +111,20 @@ export class PrimitiveType { } /** + * @en + * Indicates that the editor should treats this property or array element as a Integer value. + * @zh * 指定编辑器以整数形式对待该属性或数组元素。 - * 例如: + * @example * ```ts - * import { CCInteger, _decorator } from "Cocos3D"; + * import { CCInteger, _decorator } from "cc"; * - * // 在 cc 类定义中: + * // in class definition: * - * \@_decorator.property({type: CCInteger}) + * @_decorator.property({type: CCInteger}) * count = 0; * - * \@_decorator.property({type: [CCInteger]}) + * @_decorator.property({type: [CCInteger]}) * array = []; * ``` */ @@ -130,17 +133,20 @@ legacyCC.Integer = CCInteger; legacyCC.CCInteger = CCInteger; /** + * @en + * Indicates that the editor should treats this property or array element as a Float value. + * @zh * 指定编辑器以浮点数形式对待该属性或数组元素。 - * 例如: + * @example * ```ts - * import { CCFloat, _decorator } from "Cocos3D"; + * import { CCFloat, _decorator } from "cc"; * - * // 在 cc 类定义中: + * // in class definition: * - * \@_decorator.property({type: CCFloat}) + * @_decorator.property({type: CCFloat}) * x = 0; * - * \@_decorator.property({type: [CCFloat]}) + * @_decorator.property({type: [CCFloat]}) * array = []; * ``` */ @@ -156,17 +162,19 @@ if (EDITOR) { } /** + * @en + * Indicates that the editor should treats this property or array element as a Boolean value. + * @zh * 指定编辑器以布尔值形式对待该属性或数组元素。 - * 例如: + * + * @example * ```ts - * import { CCBoolean, _decorator } from "Cocos3D"; - * - * // 在 cc 类定义中: - * - * \@_decorator.property({type: CCBoolean}) + * import { CCBoolean, _decorator } from "cc"; + * // in class definition + * @_decorator.property({type: CCBoolean}) * isTrue = false; * - * \@_decorator.property({type: [CCBoolean]}) + * @_decorator.property({type: [CCBoolean]}) * array = []; * ``` */ @@ -175,17 +183,20 @@ legacyCC.Boolean = CCBoolean; legacyCC.CCBoolean = CCBoolean; /** + * @en + * Indicates that the editor should treats this property or array element as a String value. + * @zh * 指定编辑器以字符串形式对待该属性或数组元素。 - * 例如: + * @example * ```ts - * import { CCString, _decorator } from "Cocos3D"; + * import { CCString, _decorator } from "cc"; * - * // 在 cc 类定义中: + * // in class definition * - * \@_decorator.property({type: CCString}) + * @_decorator.property({type: CCString}) * name = ''; * - * \@_decorator.property({type: [CCString]}) + * @_decorator.property({type: [CCString]}) * array = []; * ``` */ diff --git a/cocos/core/data/utils/compact-value-type-array.ts b/cocos/core/data/utils/compact-value-type-array.ts index a164f2fd6b..4594ffc456 100644 --- a/cocos/core/data/utils/compact-value-type-array.ts +++ b/cocos/core/data/utils/compact-value-type-array.ts @@ -56,6 +56,9 @@ export function extractStorageUnitElementType (combined: StorageUnitElementType) }; } +/** + * @deprecated Since V3.5.0. + */ @ccclass('cc.CompactValueTypeArray') export class CompactValueTypeArray { public static StorageUnit = StorageUnit; diff --git a/cocos/core/data/utils/decorator-jsb-utils.ts b/cocos/core/data/utils/decorator-jsb-utils.ts deleted file mode 100644 index bda5e9f0fc..0000000000 --- a/cocos/core/data/utils/decorator-jsb-utils.ts +++ /dev/null @@ -1,68 +0,0 @@ -export function _assertThisInitialized(self) { - if (!self) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - - return self; -} - -export function _initializerDefineProperty(target, property, descriptor, context) { - if (!descriptor) return; - Object.defineProperty(target, property, { - enumerable: descriptor.enumerable, - configurable: descriptor.configurable, - writable: descriptor.writable, - value: descriptor.initializer ? descriptor.initializer.call(context) : undefined, - }); -} - -export function _applyDecoratedDescriptor(target, property, decorators, descriptor, context?: any) { - let desc: any = {}; - Object.keys(descriptor).forEach((key) => { - desc[key] = descriptor[key]; - }); - desc.enumerable = !!desc.enumerable; - desc.configurable = !!desc.configurable; - - if ('value' in desc || desc.initializer) { - desc.writable = true; - } - - desc = decorators.slice().reverse().reduce((desc, decorator) => { - return decorator(target, property, desc) || desc; - }, desc); - - if (context && desc.initializer !== undefined) { - desc.value = desc.initializer ? desc.initializer.call(context) : undefined; - desc.initializer = undefined; - } - - if (desc.initializer === undefined) { - Object.defineProperty(target, property, desc); - desc = null; - } - - return desc; -} - -export function _inheritsLoose(subClass, superClass) { - subClass.prototype = Object.create(superClass.prototype); - subClass.prototype.constructor = subClass; - - _setPrototypeOf(subClass, superClass); -} - -export function _getPrototypeOf(o) { - const getPrototypeOf: any = Object.getPrototypeOf ? Object.getPrototypeOf : (o) => { - return o.__proto__ || Object.getPrototypeOf(o); - }; - return getPrototypeOf(o); -} - -export function _setPrototypeOf(o, p) { - const setPrototypeOf = Object.setPrototypeOf || function (o, p) { - o.__proto__ = p; - return o; - }; - return setPrototypeOf(o, p); -} diff --git a/cocos/core/data/utils/preprocess-class.ts b/cocos/core/data/utils/preprocess-class.ts index da4fdb4377..61613a5f90 100644 --- a/cocos/core/data/utils/preprocess-class.ts +++ b/cocos/core/data/utils/preprocess-class.ts @@ -137,7 +137,7 @@ function parseType (val, type, className, propName) { } if (EDITOR && typeof type === 'function') { - if (legacyCC.Class._isCCClass(type) && val.serializable !== false && !js._getClassId(type, false)) { + if (legacyCC.Class._isCCClass(type) && val.serializable !== false && !js.getClassId(type, false)) { warnID(5512, className, propName, className, propName); } } diff --git a/cocos/core/deprecated.ts b/cocos/core/deprecated.ts index beba96c36d..d06847f161 100644 --- a/cocos/core/deprecated.ts +++ b/cocos/core/deprecated.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { replaceProperty, removeProperty, markAsWarning } from './utils/x-deprecated'; import * as math from './math'; import { Scheduler } from './scheduler'; diff --git a/cocos/core/director.ts b/cocos/core/director.ts index 524cdccf15..e6e4e86935 100644 --- a/cocos/core/director.ts +++ b/cocos/core/director.ts @@ -27,28 +27,23 @@ /* spell-checker:words COORD, Quesada, INITED, Renerer */ -/** - * @packageDocumentation - * @module core - */ - import { DEBUG, EDITOR, BUILD, TEST } from 'internal:constants'; -import { SceneAsset } from './assets'; +import { SceneAsset } from './assets/scene-asset'; import System from './components/system'; import { CCObject } from './data/object'; import { EventTarget } from './event'; import { input } from '../input'; -import { game, Game } from './game'; -import { v2, Vec2 } from './math'; import { Root } from './root'; import { Node, Scene } from './scene-graph'; import { ComponentScheduler } from './scene-graph/component-scheduler'; import NodeActivator from './scene-graph/node-activator'; import { Scheduler } from './scheduler'; -import { js } from './utils'; +import { js } from './utils/js'; import { legacyCC } from './global-exports'; -import { errorID, error, assertID, warnID } from './platform/debug'; +import { errorID, error, assertID, warnID, debug } from './platform/debug'; import { containerManager } from './memop/container-manager'; +import { uiRendererManager } from '../2d/framework/ui-renderer-manager'; +import { deviceManager } from './gfx'; // ---------------------------------------------------------------------------------------------------------------------- @@ -172,29 +167,29 @@ export class Director extends EventTarget { public static readonly EVENT_BEFORE_COMMIT = 'director_before_commit'; /** - * The event which will be triggered before the physics process.
- * 物理过程之前所触发的事件。 + * @en The event which will be triggered before the physics process.
+ * @zh 物理过程之前所触发的事件。 * @event Director.EVENT_BEFORE_PHYSICS */ public static readonly EVENT_BEFORE_PHYSICS = 'director_before_physics'; /** - * The event which will be triggered after the physics process.
- * 物理过程之后所触发的事件。 + * @en The event which will be triggered after the physics process.
+ * @zh 物理过程之后所触发的事件。 * @event Director.EVENT_AFTER_PHYSICS */ public static readonly EVENT_AFTER_PHYSICS = 'director_after_physics'; /** - * The event which will be triggered at the frame begin.
- * 一帧开始时所触发的事件。 + * @en The event which will be triggered at the frame begin.
+ * @zh 一帧开始时所触发的事件。 * @event Director.EVENT_BEGIN_FRAME */ public static readonly EVENT_BEGIN_FRAME = 'director_begin_frame'; /** - * The event which will be triggered at the frame end.
- * 一帧结束之后所触发的事件。 + * @en The event which will be triggered at the frame end.
+ * @zh 一帧结束之后所触发的事件。 * @event Director.EVENT_END_FRAME */ public static readonly EVENT_END_FRAME = 'director_end_frame'; @@ -202,11 +197,11 @@ export class Director extends EventTarget { public static instance: Director; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _compScheduler: ComponentScheduler; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _nodeActivator: NodeActivator; private _invalid: boolean; @@ -217,6 +212,7 @@ export class Director extends EventTarget { private _totalFrames: number; private _scheduler: Scheduler; private _systems: System[]; + private _persistRootNodes = {}; constructor () { super(); @@ -243,8 +239,6 @@ export class Director extends EventTarget { this._nodeActivator = new NodeActivator(); this._systems = []; - - game.once(Game.EVENT_RENDERER_INITED, this._initOnRendererInitialized, this); } /** @@ -312,6 +306,13 @@ export class Director extends EventTarget { public reset () { this.purgeDirector(); + for (const id in this._persistRootNodes) { + this.removePersistRootNode(this._persistRootNodes[id]); + } + + // Clear scene + this.getScene()?.destroy(); + this.emit(Director.EVENT_RESET); this.startAnimation(); @@ -342,7 +343,7 @@ export class Director extends EventTarget { if (BUILD && DEBUG) { console.time('AttachPersist'); } - const persistNodeList = Object.keys(game._persistRootNodes).map((x) => game._persistRootNodes[x] as Node); + const persistNodeList = Object.keys(this._persistRootNodes).map((x) => this._persistRootNodes[x] as Node); for (let i = 0; i < persistNodeList.length; i++) { const node = persistNodeList[i]; node.emit(Node.EventType.SCENE_CHANGED_FOR_PERSISTS, scene.renderScene); @@ -350,9 +351,13 @@ export class Director extends EventTarget { if (existNode) { // scene also contains the persist node, select the old one const index = existNode.getSiblingIndex(); + // restore to the old saving flag + node.hideFlags &= ~CCObject.Flags.DontSave; + node.hideFlags |= CCObject.Flags.DontSave & existNode.hideFlags; existNode._destroyImmediate(); scene.insertChild(node, index); } else { + node.hideFlags |= CCObject.Flags.DontSave; // @ts-expect-error insert to new scene node.parent = scene; } @@ -374,7 +379,7 @@ export class Director extends EventTarget { if (BUILD && DEBUG) { console.time('AutoRelease'); } - legacyCC.assetManager._releaseManager._autoRelease(oldScene, scene, game._persistRootNodes); + legacyCC.assetManager._releaseManager._autoRelease(oldScene, scene, this._persistRootNodes); if (BUILD && DEBUG) { console.timeEnd('AutoRelease'); } @@ -484,8 +489,8 @@ export class Director extends EventTarget { * @zh 预加载场景资源,你可以在任何时候调用这个方法。 * 调用完后,你仍然需要通过 `director.loadScene` 来启动场景,因为这个方法不会执行场景加载操作。
* 就算预加载还没完成,你也可以直接调用 `director.loadScene`,加载完成后场景就会启动。 - * @param sceneName 场景名称。 - * @param onLoaded 加载回调。 + * @param sceneName @en The name of the scene to load @zh 场景名称。 + * @param onLoaded @en Callback to execute once the scene is loaded @zh 加载回调。 */ public preloadScene (sceneName: string, onLoaded?: Director.OnSceneLoaded): void; @@ -498,9 +503,9 @@ export class Director extends EventTarget { * @zh 预加载场景,你可以在任何时候调用这个方法。 * 调用完后,你仍然需要通过 `director.loadScene` 来启动场景,因为这个方法不会执行场景加载操作。
* 就算预加载还没完成,你也可以直接调用 `director.loadScene`,加载完成后场景就会启动。 - * @param sceneName 场景名称。 - * @param onProgress 加载进度回调。 - * @param onLoaded 加载回调。 + * @param sceneName @en The name of scene to load @zh 场景名称。 + * @param onProgress @en Callback to execute when the load progression change. @zh 加载进度回调。 + * @param onLoaded @en Callback to execute once the scene is loaded @zh 加载回调。 */ public preloadScene (sceneName: string, onProgress: Director.OnLoadSceneProgress, onLoaded: Director.OnSceneLoaded): void; @@ -556,7 +561,7 @@ export class Director extends EventTarget { * @deprecated since v3.3.0, please use game.deltaTime instead */ public getDeltaTime () { - return game.deltaTime; + return legacyCC.game.deltaTime as number; } /** @@ -565,7 +570,7 @@ export class Director extends EventTarget { * @deprecated since v3.3.0, please use game.totalTime instead */ public getTotalTime () { - return game.totalTime; + return legacyCC.game.totalTime as number; } /** @@ -574,7 +579,7 @@ export class Director extends EventTarget { * @deprecated since v3.3.0, please use game.frameStartTime instead */ public getCurrentTime () { - return game.frameStartTime; + return legacyCC.game.frameStartTime as number; } /** @@ -620,7 +625,6 @@ export class Director extends EventTarget { public registerSystem (name: string, sys: System, priority: number) { sys.id = name; sys.priority = priority; - sys.init(); this._systems.push(sys); this._systems.sort(System.sortByPriority); } @@ -667,15 +671,14 @@ export class Director extends EventTarget { /** * @en Run main loop of director * @zh 运行主循环 - * @deprecated please use [tick] instead + * @deprecated Since v3.6, please use [tick] instead */ public mainLoop (now: number) { let dt; if (EDITOR && !legacyCC.GAME_VIEW || TEST) { dt = now; } else { - // @ts-expect-error using internal API for deprecation - dt = game._calculateDT(now); + dt = legacyCC.game._calculateDT(now); } this.tick(dt); } @@ -688,7 +691,7 @@ export class Director extends EventTarget { public tick (dt: number) { if (!this._invalid) { this.emit(Director.EVENT_BEGIN_FRAME); - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { // @ts-expect-error _frameDispatchEvents is a private method. input._frameDispatchEvents(); } @@ -717,6 +720,7 @@ export class Director extends EventTarget { } this.emit(Director.EVENT_BEFORE_DRAW); + uiRendererManager.updateAllDirtyRenderers(); this._root!.frameMove(dt); this.emit(Director.EVENT_AFTER_DRAW); @@ -728,21 +732,84 @@ export class Director extends EventTarget { } } - private _initOnRendererInitialized () { + /** + * @internal + */ + public init () { this._totalFrames = 0; this._paused = false; - // Scheduler // TODO: have a solid organization of priority and expose to user this.registerSystem(Scheduler.ID, this._scheduler, 200); - + this._root = new Root(deviceManager.gfxDevice); + const rootInfo = {}; + this._root.initialize(rootInfo); + for (let i = 0; i < this._systems.length; i++) { + this._systems[i].init(); + } this.emit(Director.EVENT_INIT); } - private _init () { - this._root = new Root(game._gfxDevice!); - const rootInfo = {}; - this._root.initialize(rootInfo); + // @ Persist root node section + /** + * @en + * Add a persistent root node to the game, the persistent node won't be destroyed during scene transition.
+ * The target node must be placed in the root level of hierarchy, otherwise this API won't have any effect. + * @zh + * 声明常驻根节点,该节点不会在场景切换中被销毁。
+ * 目标节点必须位于为层级的根节点,否则无效。 + * @param node - The node to be made persistent + */ + public addPersistRootNode (node: Node) { + if (!legacyCC.Node.isNode(node) || !node.uuid) { + warnID(3800); + return; + } + const id = node.uuid; + if (!this._persistRootNodes[id]) { + const scene = this._scene as any; + if (legacyCC.isValid(scene)) { + if (!node.parent) { + node.parent = scene; + node._originalSceneId = scene.uuid; + } else if (!(node.parent instanceof Scene)) { + warnID(3801); + return; + } else if (node.parent !== scene) { + warnID(3802); + return; + } else { + node._originalSceneId = scene.uuid; + } + } + this._persistRootNodes[id] = node; + node._persistNode = true; + legacyCC.assetManager._releaseManager._addPersistNodeRef(node); + } + } + + /** + * @en Remove a persistent root node. + * @zh 取消常驻根节点。 + * @param node - The node to be removed from persistent node list + */ + public removePersistRootNode (node: Node) { + const id = node.uuid || ''; + if (node === this._persistRootNodes[id]) { + delete this._persistRootNodes[id]; + node._persistNode = false; + node._originalSceneId = ''; + legacyCC.assetManager._releaseManager._removePersistNodeRef(node); + } + } + + /** + * @en Check whether the node is a persistent root node. + * @zh 检查节点是否是常驻根节点。 + * @param node - The node to be checked + */ + public isPersistRootNode (node: Node): boolean { + return !!node._persistNode; } } @@ -766,6 +833,7 @@ export declare namespace Director { legacyCC.Director = Director; /** - * 导演类。 + * @en Director of the game, used to control game update loop and scene management + * @zh 游戏的导演,用于控制游戏更新循环与场景管理。 */ export const director: Director = Director.instance = legacyCC.director = new Director(); diff --git a/cocos/core/easing/easing.ts b/cocos/core/easing/easing.ts index e37c113604..c4b408f1f4 100644 --- a/cocos/core/easing/easing.ts +++ b/cocos/core/easing/easing.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module animation - */ - export function constant () { return 0; } diff --git a/cocos/core/event/async-delegate.ts b/cocos/core/event/async-delegate.ts new file mode 100644 index 0000000000..a192a6c23e --- /dev/null +++ b/cocos/core/event/async-delegate.ts @@ -0,0 +1,109 @@ +/* + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + http://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 { js } from '../utils/js'; + +/** + * @zh + * Async Delegate 用于支持异步回调的代理,你可以新建一个异步代理,并注册异步回调,等到对应的时机触发代理事件。 + * + * @en + * Async Delegate is a delegate that supports asynchronous callbacks. + * You can create a new AsyncDelegate, register the asynchronous callback, and wait until the corresponding time to dispatch the event. + * + * @example + * ```ts + * const ad = new AsyncDelegate(); + * ad.add(() => { + * return new Promise((resolve, reject) => { + * setTimeout(() => { + * console.log('hello world'); + * resolve(); + * }, 1000); + * }) + * }); + * await ad.dispatch(); + * ``` + */ +export class AsyncDelegate (Promise | void) = () => (Promise | void)> { + private _delegates: T[] = []; + + /** + * @en + * Add an async callback or sync callback. + * + * @zh + * 添加一个异步回调或同步回调。 + * + * @param callback + * @en The callback to add, and will be invoked when this delegate is dispatching. + * @zh 要添加的回调,并将在该委托调度时被调用。 + */ + public add (callback: T) { + if (!this._delegates.includes(callback)) { + this._delegates.push(callback); + } + } + + /** + * @zh + * 查询是否已注册某个回调。 + * @en + * Queries if a callback has been registered. + * + * @param callback @en The callback to query. @zh 要查询的回调函数。 + * @returns @en Whether the callback has been added. @zh 是否已经添加了回调。 + */ + public hasListener (callback: T) { + return this._delegates.includes(callback); + } + + /** + * @en + * Remove the specific callback of this delegate. + * + * @zh + * 移除此代理中某个具体的回调。 + * + * @param callback @en The callback to remove. @zh 要移除的某个回调。 + */ + public remove (callback: T) { + js.array.fastRemove(this._delegates, callback); + } + + /** + * @en + * Dispatching the delegate event. This function will trigger all previously registered callbacks and does not guarantee execution order. + * + * @zh + * 派发代理事件。此函数会触发所有之前注册的回调,并且不保证执行顺序。 + * + * @param args @en The parameters to be transferred to callback. @zh 传递给回调函数的参数。 + * @returns @en The promise awaiting all async callback resolved. @zh 等待所有异步回调结束的 Promise 对象。 + */ + public dispatch (...args: Parameters) { + return Promise.all(this._delegates.map((func) => func(...arguments)).filter(Boolean)); + } +} diff --git a/cocos/core/event/callbacks-invoker.ts b/cocos/core/event/callbacks-invoker.ts index 5941d1754f..0fbf588c87 100644 --- a/cocos/core/event/callbacks-invoker.ts +++ b/cocos/core/event/callbacks-invoker.ts @@ -24,12 +24,10 @@ THE SOFTWARE. */ - - import { TEST } from 'internal:constants'; import { Pool } from '../memop'; import { array, createMap } from '../utils/js'; -import { CCObject, isValid } from '../data/object'; +import { isCCObject, isValid } from '../data/object'; import { legacyCC } from '../global-exports'; const fastRemoveAt = array.fastRemoveAt; @@ -55,7 +53,7 @@ class CallbackInfo { public check () { // Validation - if (this.target instanceof CCObject && !isValid(this.target, true)) { + if (isCCObject(this.target) && !isValid(this.target, true)) { return false; } else { return true; @@ -183,7 +181,7 @@ type EventType = string | number; */ export class CallbacksInvoker { /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _callbackTable: ICallbackTable = createMap(true); private _offCallback?: () => void; diff --git a/cocos/core/event/defines.ts b/cocos/core/event/defines.ts index a8e62787c3..c208cc9473 100644 --- a/cocos/core/event/defines.ts +++ b/cocos/core/event/defines.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - export type EventArgumentsOf< K extends string, Map extends any, diff --git a/cocos/core/event/event-target-factory.ts b/cocos/core/event/event-target-factory.ts index 51237c1898..32420a9c01 100644 --- a/cocos/core/event/event-target-factory.ts +++ b/cocos/core/event/event-target-factory.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module event - */ - import { EventTarget } from './event-target'; export function applyMixins (derivedCtor: any, baseCtors: any[]) { diff --git a/cocos/core/event/event-target.ts b/cocos/core/event/event-target.ts index b96c9fc838..322c4c1d0a 100644 --- a/cocos/core/event/event-target.ts +++ b/cocos/core/event/event-target.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module event - */ - import { legacyCC } from '../global-exports'; import { Eventify } from './eventify'; diff --git a/cocos/core/event/eventify.ts b/cocos/core/event/eventify.ts index 57975d82cf..78b94e445c 100644 --- a/cocos/core/event/eventify.ts +++ b/cocos/core/event/eventify.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module event - */ - import { CallbacksInvoker } from './callbacks-invoker'; import { createMap } from '../utils/js'; diff --git a/cocos/core/event/index.ts b/cocos/core/event/index.ts index 5064d451d2..c49c848761 100644 --- a/cocos/core/event/index.ts +++ b/cocos/core/event/index.ts @@ -24,10 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module event - */ - export { EventTarget } from './event-target'; export { Eventify } from './eventify'; +export { AsyncDelegate } from './async-delegate'; diff --git a/cocos/core/game.ts b/cocos/core/game.ts index fe8e8f750c..e7d7cd2684 100644 --- a/cocos/core/game.ts +++ b/cocos/core/game.ts @@ -23,44 +23,34 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ -import { EDITOR, HTML5, JSB, PREVIEW, RUNTIME_BASED, TEST } from 'internal:constants'; +import { 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'; import { ConfigOrientation } from 'pal/screen-adapter'; -import { IAssetManagerOptions } from './asset-manager/asset-manager'; +import assetManager, { IAssetManagerOptions } from './asset-manager/asset-manager'; import { EventTarget } from './event'; +import { AsyncDelegate } from './event/async-delegate'; import { input } from '../input'; import * as debug from './platform/debug'; -import { Device, DeviceInfo, Swapchain, SwapchainInfo } from './gfx'; +import { deviceManager } from './gfx'; import { sys } from './platform/sys'; import { macro } from './platform/macro'; -import type { ICustomJointTextureLayout } from '../3d/skeletal-animation/skeletal-animation-utils'; import { legacyCC, VERSION } from './global-exports'; -import { IPhysicsConfig } from '../physics/framework/physics-config'; -import { bindingMappingInfo } from './pipeline/define'; import { SplashScreen } from './splash-screen'; import { RenderPipeline } from './pipeline/render-pipeline'; -import { Node } from './scene-graph/node'; -import { BrowserType } from '../../pal/system-info/enum-type'; -import { Layers } from './scene-graph'; -import { log2 } from './math/bits'; +import { Layers, Node } from './scene-graph'; import { garbageCollectionManager } from './data/garbage-collection'; import { screen } from './platform/screen'; import { builtinResMgr } from './builtin/builtin-res-mgr'; - -interface ISceneInfo { - url: string; - uuid: string; -} - -export interface LayerItem { - name: string; - value: number; -} +import { Settings, settings } from './settings'; +import { Director, director } from './director'; +import { bindingMappingInfo } from './pipeline/define'; +import { assert } from './platform/debug'; +import { IBundleOptions } from './asset-manager/shared'; +import { ICustomJointTextureLayout } from '../3d/skeletal-animation/skeletal-animation-utils'; +import { IPhysicsConfig } from '../physics/framework/physics-config'; /** * @zh @@ -69,6 +59,14 @@ export interface LayerItem { * Game configuration. */ export interface IGameConfig { + /** + * @zh + * 引擎配置文件路径 + * @en + * The path of settings.json + */ + settingsPath?: string; + /** * @zh * 设置 debug 模式,在浏览器中这个选项会被忽略。 @@ -79,36 +77,33 @@ export interface IGameConfig { /** * @zh - * 当 showFPS 为 true 的时候界面的左下角将显示 fps 的信息,否则被隐藏。 + * 覆盖 settings 模块中的配置项, 用于控制引擎的启动和初始化,你可以在 game.init 中传入参数,也可以在 [game.onPostBaseInitDelegate] 事件回调中覆盖。 + * 需要注意的是你需要在 application.js 模板中指定此选项和监听此事件。 * @en - * Left bottom corner fps information will show when "showFPS" equals true, otherwise it will be hide. + * Overrides the settings module's some configuration, which is used to control the startup and initialization of the engine. + * You can pass in parameters in game.init or override them in the [game.onPostBaseInitDelegate] event callback. + * Note: you need to specify this option in the application.js template or add a delegate callback. */ - showFPS?: boolean; + overrideSettings : Partial<{ [ k in Settings.Category[keyof Settings.Category] ]: Record }> /** * @zh - * 暴露类名让 Chrome DevTools 可以识别,如果开启会稍稍降低类的创建过程的性能,但对对象构造没有影响。 + * 当 showFPS 为 true 的时候界面的左下角将显示 fps 的信息,否则被隐藏。 * @en - * Expose class name to chrome debug tools, the class intantiate performance is a little bit slower when exposed. + * Left bottom corner fps information will show when "showFPS" equals true, otherwise it will be hide. + * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.PROFILING: { "showFPS": true }}``` to set this. */ - exposeClassName?: boolean; + showFPS?: boolean; /** * @zh * 设置想要的帧率你的游戏,但真正的FPS取决于你的游戏实现和运行环境。 * @en * Set the wanted frame rate for your game, but the real fps depends on your game implementation and the running environment. + * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.SCREEN: { "frameRate": 60 }}``` to set this. */ frameRate?: number; - /** - * @zh - * Web 页面上的 Canvas Element ID,仅适用于 web 端。 - * @en - * Sets the id of your canvas element on the web page, it's useful only on web. - */ - id?: string | HTMLElement; - /** * @zh * 渲染模式。 @@ -123,65 +118,63 @@ export interface IGameConfig { * - 1 - Forced to use canvas renderer. * - 2 - Forced to use WebGL renderer, but this will be ignored on mobile browsers. * - 3 - Use Headless Renderer, which is useful in test or server env, only for internal use by cocos team for now + * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.RENDERING: { "renderMode": 0 }}``` to set this. */ renderMode?: 0 | 1 | 2 | 3; /** - * @zh - * 当前包中可用场景。 * @en - * Include available scenes in the current bundle. - */ - scenes?: ISceneInfo[]; - - /** - * For internal use. - */ - jsList?: string[]; - - /** * Render pipeline resources + * @zh + * Render pipeline 资源 + * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.RENDERING: { "renderPipeline": '' }}``` to set this. */ renderPipeline?: string; /** + * @en * Asset Manager initialization options + * @zh + * 资源管理器初始化设置 + * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.ASSETS: {}}``` to set this. */ assetOptions?: IAssetManagerOptions; /** + * @en * GPU instancing options + * @zh + * GPU instancing 选项 + * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.ANIMATION: { customJointTextureLayouts: [] }}``` to set this. */ customJointTextureLayouts?: ICustomJointTextureLayout[]; /** + * @en * Physics system config + * @zh + * 物理系统设置 + * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.PHYSICS: {}}``` to set this. */ physics?: IPhysicsConfig; /** - * User layers config - */ - layers?: LayerItem[]; - - /** - * The adapter stores various platform-related objects. - */ - adapter?: { - canvas: HTMLCanvasElement, - frame: HTMLDivElement, - container: HTMLDivElement, - [x: string]: any, - }; - - /** + * @en * The orientation from the builder configuration. * Available value can be 'auto', 'landscape', 'portrait'. + * @zh + * 屏幕旋转方向,可选 “自动”,“横屏”,“竖屏” + * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.SCREEN: { 'orientation': 'auto' }}``` to set this. */ orientation?: ConfigOrientation; + /** + * @en * Determine whether the game frame exact fits the screen. * Now it only works on Web platform. + * @zh + * 是否让游戏外框对齐到屏幕上,目前只在 web 平台生效 + * @deprecated Since v3.6, Please use ```overrideSettings: { Settings.Category.SCREEN: { 'exactFitScreen': true }}``` to set this. */ exactFitScreen: boolean, } @@ -249,6 +242,49 @@ export class Game extends EventTarget { */ public static readonly EVENT_RENDERER_INITED: string = 'renderer_inited'; + /** + * @en Event triggered pre base module initialization, at this point you can not use pal/logging/sys/settings API. + * @zh 基础模块初始化之前的事件,在这个事件点你无法使用 pal/logging/sys/settings 的相关接口。 + */ + public static readonly EVENT_PRE_BASE_INIT = 'pre_base_init'; + /** + * @en Event triggered post base module initialization, at this point you can use pal/logging/sys/settings API safely. + * @zh 基础模块初始化之后的事件,在这个事件点你可以安全使用 pal/logging/sys/settings 的相关接口。 + */ + public static readonly EVENT_POST_BASE_INIT = 'post_base_init'; + /** + * @en Event triggered pre infrastructure initialization, at this point you can not use assetManager/gfx/screen/builtinResMgr/macro/Layer API. + * @zh 基础设施初始化之前的事件,在这个事件点你无法使用 assetManager/gfx/screen/builtinResMgr/macro/Layer 的相关接口。 + */ + public static readonly EVENT_PRE_INFRASTRUCTURE_INIT = 'pre_infrastructure_init'; + /** + * @en Event triggered post infrastructure initialization, at this point you can use assetManager/gfx/screen/builtinResMgr/macro/Layer API safely. + * @zh 基础设施初始化之后的事件,在这个事件点你可以安全使用 assetManager/gfx/screen/builtinResMgr/macro/Layer 的相关接口。 + */ + public static readonly EVENT_POST_INFRASTRUCTURE_INIT = 'post_infrastructure_init'; + /** + * @en Event triggered pre subsystem initialization, at this point you can not use physics/animation/rendering/tween/etc API. + * @zh 子系统初始化之前的事件,在这个事件点你无法使用 physics/animation/rendering/tween/etc 的相关接口。 + */ + public static readonly EVENT_PRE_SUBSYSTEM_INIT = 'pre_subsystem_init'; + /** + * @en Event triggered post subsystem initialization, at this point you can use physics/animation/rendering/tween/etc API safely. + * @zh 子系统初始化之后的事件,在这个事件点你可以安全使用 physics/animation/rendering/tween/etc 的相关接口。 + */ + public static readonly EVENT_POST_SUBSYSTEM_INIT = 'post_subsystem_init'; + /** + * @en Event triggered pre project data initialization, + * at this point you can not access project data using [resources.load]/[director.loadScene] API. + * @zh 项目数据初始化之前的事件,在这个事件点你无法使用访问项目数据的相关接口,例如 [resources.load]/[director.loadScene] 等 API。 + */ + public static readonly EVENT_PRE_PROJECT_INIT = 'pre_project_init'; + /** + * @en Event triggered post project data initialization, + * at this point you can access project data using [resources.load]/[director.loadScene] API safely. + * @zh 项目数据初始化之后的事件,在这个事件点你可以安全使用访问项目数据的相关接口,例如 [resources.load]/[director.loadScene] 等 API。 + */ + public static readonly EVENT_POST_PROJECT_INIT = 'post_project_init'; + /** * @en Event triggered when game restart * @zh 调用restart后,触发事件 @@ -321,7 +357,7 @@ export class Game extends EventTarget { * 当前的游戏配置 * 注意:请不要直接修改这个对象,它不会有任何效果。 */ - public config: NormalizedGameConfig = {} as NormalizedGameConfig; + public config: IGameConfig = {} as IGameConfig; /** * @en Callback when the scripts of engine have been load. @@ -354,7 +390,7 @@ export class Game extends EventTarget { } this._frameRate = frameRate; this.frameTime = 1000 / frameRate; - this._setAnimFrame(); + if (this._pacer) this._pacer.targetFrameRate = this._frameRate; } /** @@ -387,29 +423,9 @@ export class Game extends EventTarget { */ public frameTime = 1000 / 60; - public collisionMatrix = []; - public groupList: any[] = []; - - /** - * @legacyPublic - */ - public _persistRootNodes = {}; - - /** - * @legacyPublic - */ - public _gfxDevice: Device | null = null; - /** - * @legacyPublic - */ - public _swapchain: Swapchain | null = null; // states /** - * @legacyPublic - */ - public _configLoaded = false; // whether config loaded - /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _isCloning = false; // deserializing or instantiating private _inited = false; @@ -418,12 +434,58 @@ export class Game extends EventTarget { private _paused = true; // frame control private _frameRate = 60; - private _intervalId = 0; // interval target of main + private _pacer: Pacer | null = null; private _initTime = 0; private _startTime = 0; private _deltaTime = 0.0; - private declare _frameCB: (time: number) => void; - private _onEngineInitedCallback: Array<() => (Promise | void)> = []; + private _shouldLoadLaunchScene = true; + + /** + * @en The event delegate pre base module initialization. At this point you can not use pal/logging/sys/settings API. + * @zh 基础模块初始化之前的事件代理。在这个事件点你无法使用 pal/logging/sys/settings 的相关接口。 + */ + public readonly onPreBaseInitDelegate: AsyncDelegate<() => (Promise | void)> = new AsyncDelegate(); + /** + * @en The event delegate post base module initialization. At this point you can use pal/logging/sys/settings API safely. + * @zh 基础模块初始化之后的事件代理。在这个事件点你可以安全使用 pal/logging/sys/settings 的相关接口。 + */ + public readonly onPostBaseInitDelegate: AsyncDelegate<() => (Promise | void)> = new AsyncDelegate(); + /** + * @en The event delegate pre infrastructure module initialization. + * At this point you can not use assetManager/gfx/screen/builtinResMgr/macro/Layer API. + * @zh 基础设施模块初始化之前的事件代理。在这个事件点你无法使用 assetManager/gfx/screen/builtinResMgr/macro/Layer 的相关接口。 + */ + public readonly onPreInfrastructureInitDelegate: AsyncDelegate<() => (Promise | void)> = new AsyncDelegate(); + /** + * @en The event delegate post infrastructure module initialization. + * At this point you can use assetManager/gfx/screen/builtinResMgr/macro/Layer API safely. + * + * @zh 基础设施模块初始化之后的事件代理。在这个事件点你可以安全使用 assetManager/gfx/screen/builtinResMgr/macro/Layer 的相关接口。 + */ + public readonly onPostInfrastructureInitDelegate: AsyncDelegate<() => (Promise | void)> = new AsyncDelegate(); + /** + * @en The event delegate pre sub system module initialization. At this point you can not use physics/animation/rendering/tween/etc API. + * @zh 子系统模块初始化之前的事件代理。在这个事件点你无法使用 physics/animation/rendering/tween/etc 的相关接口。 + */ + public readonly onPreSubsystemInitDelegate: AsyncDelegate<() => (Promise | void)> = new AsyncDelegate(); + /** + * @en The event delegate post sub system module initialization. At this point you can use physics/animation/rendering/tween/etc API safely. + * @zh 子系统模块初始化之后的事件代理。在这个事件点你可以安全使用 physics/animation/rendering/tween/etc 的相关接口。 + */ + public readonly onPostSubsystemInitDelegate: AsyncDelegate<() => (Promise | void)> = new AsyncDelegate(); + /** + * @en The event delegate pre project data initialization. + * At this point you can not access project data using [resources.load]/[director.loadScene] API. + * @zh 项目数据初始化之前的事件代理。在这个事件点你无法使用访问项目数据的相关接口,例如 [resources.load]/[director.loadScene] 等 API。 + */ + public readonly onPreProjectInitDelegate: AsyncDelegate<() => (Promise | void)> = new AsyncDelegate(); + /** + * @en The event delegate post project data initialization. + * at this point you can access project data using [resources.load]/[director.loadScene] API safely. + * @zh 项目数据初始化之后的事件代理。 + * 在这个事件点你可以安全使用访问项目数据的相关接口,例如 [resources.load]/[director.loadScene] 等 API。 + */ + public readonly onPostProjectInitDelegate: AsyncDelegate<() => (Promise | void)> = new AsyncDelegate(); // @Methods @@ -453,7 +515,7 @@ export class Game extends EventTarget { * @zh 以固定帧间隔执行一帧游戏循环,帧间隔与设定的帧率匹配。 */ public step () { - legacyCC.director.tick(this.frameTime / 1000); + director.tick(this.frameTime / 1000); } /** @@ -474,10 +536,7 @@ export class Game extends EventTarget { public pause () { if (this._paused) { return; } this._paused = true; - if (this._intervalId) { - window.cAF(this._intervalId); - this._intervalId = 0; - } + this._pacer?.stop(); } /** @@ -489,13 +548,8 @@ export class Game extends EventTarget { if (!this._paused) { return; } // @ts-expect-error _clearEvents is a private method. input._clearEvents(); - if (this._intervalId) { - window.cAF(this._intervalId); - this._intervalId = 0; - } this._paused = false; - this._updateCallback(); - this._intervalId = window.rAF(this._frameCB); + this._pacer?.start(); } /** @@ -511,23 +565,15 @@ export class Game extends EventTarget { * @zh 重新开始游戏 */ public restart (): Promise { - const endFramePromise = new Promise((resolve) => legacyCC.director.once(legacyCC.Director.EVENT_END_FRAME, () => resolve()) as void); + const endFramePromise = new Promise((resolve) => { director.once(Director.EVENT_END_FRAME, () => resolve()); }); return endFramePromise.then(() => { - for (const id in this._persistRootNodes) { - this.removePersistRootNode(this._persistRootNodes[id]); - } - - // Clear scene - legacyCC.director.getScene().destroy(); + director.reset(); legacyCC.Object._deferredDestroy(); - - legacyCC.director.reset(); - legacyCC.profiler.reset(); this.pause(); - return this._setRenderPipelineNShowSplash().then(() => { - this.resume(); - this._safeEmit(Game.EVENT_RESTART); - }); + this.resume(); + this._shouldLoadLaunchScene = true; + SplashScreen.instance.curTime = 0; + this._safeEmit(Game.EVENT_RESTART); }); } @@ -584,44 +630,210 @@ export class Game extends EventTarget { } /** - * @en Init game with configuration object. - * @zh 使用指定的配置初始化引擎。 + * @en Init game with configuration object. Initialization process like below: + * -PreBaseInitEvent + * -BaseModuleInitialization(logging, sys, settings) + * -PostBaseInitEvent + * -PreInfrastructureInitEvent + * -InfrastructureModuleInitialization(assetManager, builtinResMgr, gfxDevice, screen, Layer, macro) + * -PostInfrastructureInitEvent + * -PreSubsystemInitEvent + * -SubsystemModuleInitialization(animation, physics, tween, ui, middleware, etc) + * -PostSubsystemInitEvent + * -EngineInitedEvent + * -PreProjectDataInitEvent + * -ProjectDataInitialization(GamePlayScripts, resources, etc) + * -PostProjectDataInitEvent + * -GameInitedEvent + * + * @zh 使用指定的配置初始化引擎。初始化流程如下: + * -PreBaseInitEvent + * -BaseModuleInitialization(logging, sys, settings) + * -PostBaseInitEvent + * -PreInfrastructureInitEvent + * -InfrastructureModuleInitialization(assetManager, builtinResMgr, gfxDevice, screen, Layer, macro) + * -PostInfrastructureInitEvent + * -PreSubsystemInitEvent + * -SubsystemModuleInitialization(animation, physics, tween, ui, middleware, etc) + * -PostSubsystemInitEvent + * -EngineInitedEvent + * -PreProjectDataInitEvent + * -ProjectDataInitialization(GamePlayScripts, resources, etc) + * -PostProjectDataInitEvent + * -GameInitedEvent * @param config - Pass configuration object */ public init (config: IGameConfig) { - this._initConfig(config); - // TODO: unify the screen initialization workflow. - if (HTML5) { - // @ts-expect-error access private method. - screen._init({ - configOrientation: config.orientation || 'auto', - exactFitScreen: config.exactFitScreen, - }); - } - // Init assetManager - if (this.config.assetOptions) { - legacyCC.assetManager.init(this.config.assetOptions); - } - - if (this.config.layers) { - const userLayers: LayerItem[] = this.config.layers; - for (let i = 0; i < userLayers.length; i++) { - const layer = userLayers[i]; - const bitNum = log2(layer.value); - Layers.addLayer(layer.name, bitNum); - } - } - - return this._initEngine().then(() => { - if (!EDITOR) { + this._compatibleWithOldParams(config); + // DONT change the order unless you know what's you doing + return Promise.resolve() + // #region Base + .then(() => { + this.emit(Game.EVENT_PRE_BASE_INIT); + return this.onPreBaseInitDelegate.dispatch(); + }) + .then(() => { + const debugMode = config.debugMode || debug.DebugMode.NONE; + debug._resetDebugSetting(debugMode); + sys.init(); this._initEvents(); - } + }) + .then(() => settings.init(config.settingsPath, config.overrideSettings)) + .then(() => { + this.emit(Game.EVENT_POST_BASE_INIT); + return this.onPostBaseInitDelegate.dispatch(); + }) + // #endregion Base + // #region Infrastructure + .then(() => { + this.emit(Game.EVENT_PRE_INFRASTRUCTURE_INIT); + return this.onPreInfrastructureInitDelegate.dispatch(); + }) + .then(() => { + macro.init(); + const adapter = findCanvas(); + if (adapter) { + this.canvas = adapter.canvas; + this.frame = adapter.frame; + this.container = adapter.container; + } + screen.init(); + garbageCollectionManager.init(); + deviceManager.init(this.canvas, bindingMappingInfo); + assetManager.init(); + builtinResMgr.init(); + Layers.init(); + this.initPacer(); + }) + .then(() => { + this.emit(Game.EVENT_POST_INFRASTRUCTURE_INIT); + return this.onPostInfrastructureInitDelegate.dispatch(); + }) + // #endregion Infrastructure + // #region Subsystem + .then(() => { + this.emit(Game.EVENT_PRE_SUBSYSTEM_INIT); + return this.onPreSubsystemInitDelegate.dispatch(); + }) + .then(() => director.init()) + .then(() => builtinResMgr.loadBuiltinAssets()) + .then(() => { + this.emit(Game.EVENT_POST_SUBSYSTEM_INIT); + return this.onPostSubsystemInitDelegate.dispatch(); + }) + .then(() => { + debug.log(`Cocos Creator v${VERSION}`); + this.emit(Game.EVENT_ENGINE_INITED); + this._engineInited = true; + }) + // #endregion Subsystem + // #region Project + .then(() => { + this.emit(Game.EVENT_PRE_PROJECT_INIT); + return this.onPreProjectInitDelegate.dispatch(); + }) + .then(() => { + const jsList = settings.querySettings(Settings.Category.PLUGINS, 'jsList'); + let promise = Promise.resolve(); + if (jsList) { + const projectPath = settings.querySettings(Settings.Category.PATH, 'projectPath') || ''; + jsList.forEach((jsListFile) => { + promise = promise.then(() => loadJsFile(`${PREVIEW ? NATIVE ? projectPath : 'plugins' : 'src'}/${jsListFile}`)); + }); + } + return promise; + }) + .then(() => { + const scriptPackages = settings.querySettings(Settings.Category.SCRIPTING, 'scriptPackages'); + if (scriptPackages) { + return Promise.all(scriptPackages.map((pack) => import(pack))); + } + return Promise.resolve([]); + }) + .then(() => this._loadProjectBundles()) + .then(() => this._setupRenderPipeline()) + .then(() => this._loadPreloadAssets()) + .then(() => builtinResMgr.compileBuiltinMaterial()) + .then(() => SplashScreen.instance.init()) + .then(() => { + this.emit(Game.EVENT_POST_PROJECT_INIT); + return this.onPostProjectInitDelegate.dispatch(); + }) + // #endregion Project + .then(() => { + this._inited = true; + this._safeEmit(Game.EVENT_GAME_INITED); + }); + } - if (legacyCC.director.root && legacyCC.director.root.dataPoolManager) { - legacyCC.director.root.dataPoolManager.jointTexturePool.registerCustomTextureLayouts(config.customJointTextureLayouts); - } - return this._engineInited; - }); + private _compatibleWithOldParams (config: IGameConfig) { + const overrideSettings = config.overrideSettings = config.overrideSettings || {}; + if ('showFPS' in config) { + overrideSettings.profiling = overrideSettings.profiling || {}; + overrideSettings.profiling.showFPS = config.showFPS; + } + if ('frameRate' in config) { + overrideSettings.screen = overrideSettings.screen || {}; + overrideSettings.screen.frameRate = config.frameRate; + } + if ('renderMode' in config) { + overrideSettings.rendering = overrideSettings.rendering || {}; + overrideSettings.rendering.renderMode = config.renderMode; + } + if ('renderPipeline' in config) { + overrideSettings.rendering = overrideSettings.rendering || {}; + overrideSettings.rendering.renderPipeline = config.renderPipeline; + } + if ('assetOptions' in config) { + overrideSettings.assets = overrideSettings.assets || {}; + Object.assign(overrideSettings.assets, config.assetOptions); + } + if ('customJointTextureLayouts' in config) { + overrideSettings.animation = overrideSettings.animation || {}; + overrideSettings.animation.customJointTextureLayouts = config.customJointTextureLayouts; + } + if ('physics' in config) { + overrideSettings.physics = overrideSettings.physics || {}; + Object.assign(overrideSettings.physics, config.physics); + } + if ('orientation' in config) { + overrideSettings.screen = overrideSettings.screen || {}; + overrideSettings.screen.orientation = config.orientation; + } + if ('exactFitScreen' in config) { + overrideSettings.screen = overrideSettings.screen || {}; + overrideSettings.screen.exactFitScreen = config.exactFitScreen; + } + } + + private _loadPreloadAssets () { + const preloadAssets = settings.querySettings(Settings.Category.ASSETS, 'preloadAssets'); + if (!preloadAssets) return Promise.resolve([]); + return Promise.all(preloadAssets.map((uuid) => new Promise((resolve, reject) => { + assetManager.loadAny(uuid, (err) => { + if (err) { + reject(err); + return; + } + resolve(); + }); + }))); + } + + private _loadProjectBundles () { + const preloadBundles = settings.querySettings<{ bundle: string, version: string }[]>(Settings.Category.ASSETS, 'preloadBundles'); + if (!preloadBundles) return Promise.resolve([]); + return Promise.all(preloadBundles.map(({ bundle, version }) => new Promise((resolve, reject) => { + const opts: IBundleOptions = {}; + if (version) opts.version = version; + assetManager.loadBundle(bundle, opts, (err) => { + if (err) { + reject(err); + return; + } + resolve(); + }); + }))); } /** @@ -629,171 +841,20 @@ export class Game extends EventTarget { * @zh 运行游戏,并且指定引擎配置和 onStart 的回调。 * @param onStart - function to be executed after game initialized */ - public run(onStart?: Game.OnStart): Promise; - - public run (configOrCallback?: Game.OnStart | IGameConfig, onStart?: Game.OnStart) { - // To compatible with older version, - // we allow the `run(config, onstart?)` form. But it's deprecated. - let initPromise: Promise | undefined; - if (typeof configOrCallback !== 'function' && configOrCallback) { - initPromise = this.init(configOrCallback); - this.onStart = onStart ?? null; - } else { - this.onStart = configOrCallback ?? null; + public run (onStart?: Game.OnStart) { + if (onStart) { + this.onStart = onStart; } - garbageCollectionManager.init(); - - return Promise.resolve(initPromise) - .then(() => Promise.resolve(builtinResMgr.initBuiltinRes(this._gfxDevice!))) - .then(() => this._setRenderPipelineNShowSplash()).then(() => { - if (!HTML5) { - // @ts-expect-error access private method. - screen._init({ - configOrientation: 'auto', - exactFitScreen: true, - }); - } - }); - } - - // @ Persist root node section - /** - * @en - * Add a persistent root node to the game, the persistent node won't be destroyed during scene transition.
- * The target node must be placed in the root level of hierarchy, otherwise this API won't have any effect. - * @zh - * 声明常驻根节点,该节点不会在场景切换中被销毁。
- * 目标节点必须位于为层级的根节点,否则无效。 - * @param node - The node to be made persistent - */ - public addPersistRootNode (node: Node) { - if (!legacyCC.Node.isNode(node) || !node.uuid) { - debug.warnID(3800); + if (!this._inited || (EDITOR && !legacyCC.GAME_VIEW)) { return; } - const id = node.uuid; - if (!this._persistRootNodes[id]) { - const scene = legacyCC.director._scene; - if (legacyCC.isValid(scene)) { - if (!node.parent) { - node.parent = scene; - } else if (!(node.parent instanceof legacyCC.Scene)) { - debug.warnID(3801); - return; - } else if (node.parent !== scene) { - debug.warnID(3802); - return; - } else { - node._originalSceneId = scene.uuid; - } - } - this._persistRootNodes[id] = node; - node._persistNode = true; - legacyCC.assetManager._releaseManager._addPersistNodeRef(node); - } - } - - /** - * @en Remove a persistent root node. - * @zh 取消常驻根节点。 - * @param node - The node to be removed from persistent node list - */ - public removePersistRootNode (node: Node) { - const id = node.uuid || ''; - if (node === this._persistRootNodes[id]) { - delete this._persistRootNodes[id]; - node._persistNode = false; - node._originalSceneId = ''; - legacyCC.assetManager._releaseManager._removePersistNodeRef(node); - } - } - - /** - * @en Check whether the node is a persistent root node. - * @zh 检查节点是否是常驻根节点。 - * @param node - The node to be checked - */ - public isPersistRootNode (node: { _persistNode: any; }): boolean { - return !!node._persistNode; - } - - /** - * TODO: Only hack for PhysX initialization, should be removed in future - * @internal - */ - public onEngineInitedAsync (func: () => (Promise | void)) { - this._onEngineInitedCallback.push(func); - } - - // @Engine loading - - private _initEngine () { - this._initDevice(); - const director = legacyCC.director; - return Promise.resolve(director._init()).then(() => { - legacyCC.view.init(); - // Log engine version - debug.log(`Cocos Creator v${VERSION}`); - this.emit(Game.EVENT_ENGINE_INITED); - this._engineInited = true; - if (legacyCC.internal.dynamicAtlasManager) { legacyCC.internal.dynamicAtlasManager.enabled = !macro.CLEANUP_IMAGE_CACHE; } - }).then(() => { - const initCallbackPromises = this._onEngineInitedCallback.map((func) => func()).filter(Boolean); - this._onEngineInitedCallback.length = 0; - return Promise.all(initCallbackPromises); - }); + this.resume(); } // @Methods - // @Time ticker section - private _setAnimFrame () { - const frameRate = this._frameRate; - if (JSB) { - // @ts-expect-error JSB Call - jsb.setPreferredFramesPerSecond(frameRate); - window.rAF = window.requestAnimationFrame; - window.cAF = window.cancelAnimationFrame; - } else { - const rAF = window.requestAnimationFrame = window.requestAnimationFrame - || window.webkitRequestAnimationFrame - || window.mozRequestAnimationFrame - || window.oRequestAnimationFrame - || window.msRequestAnimationFrame; - if (frameRate !== 60 && frameRate !== 30) { - window.rAF = this._stTime.bind(this); - window.cAF = this._ctTime; - } else { - window.rAF = rAF || this._stTime.bind(this); - window.cAF = window.cancelAnimationFrame - || window.cancelRequestAnimationFrame - || window.msCancelRequestAnimationFrame - || window.mozCancelRequestAnimationFrame - || window.oCancelRequestAnimationFrame - || window.webkitCancelRequestAnimationFrame - || window.msCancelAnimationFrame - || window.mozCancelAnimationFrame - || window.webkitCancelAnimationFrame - || window.ocancelAnimationFrame - || this._ctTime; - - // update callback function for 30 fps version - this._updateCallback(); - } - } - } - private _stTime (callback: () => void) { - const currTime = performance.now(); - const elapseTime = Math.max(0, (currTime - this._startTime)); - const timeToCall = Math.max(0, this.frameTime - elapseTime); - const id = window.setTimeout(callback, timeToCall); - return id; - } - private _ctTime (id: number | undefined) { - window.clearTimeout(id); - } - private _calculateDT (now?: number) { - if (!now) now = performance.now(); + private _calculateDT () { + const now = performance.now(); this._deltaTime = now > this._startTime ? (now - this._startTime) / 1000 : 0; if (this._deltaTime > Game.DEBUG_DT_THRESHOLD) { this._deltaTime = this.frameTime / 1000; @@ -803,153 +864,36 @@ export class Game extends EventTarget { } private _updateCallback () { - const director = legacyCC.director; - let callback; - if (!JSB && !RUNTIME_BASED && this._frameRate === 30) { - let skip = true; - callback = (time: number) => { - this._intervalId = window.rAF(this._frameCB); - skip = !skip; - if (skip) { - return; - } - director.tick(this._calculateDT(time)); - }; - } else { - callback = (time: number) => { - director.tick(this._calculateDT(time)); - this._intervalId = window.rAF(this._frameCB); - }; - } - this._frameCB = callback; - } - - // Run game. - private _runMainLoop () { - if (!this._inited || (EDITOR && !legacyCC.GAME_VIEW)) { - return; - } - const config = this.config; - const director = legacyCC.director; - - debug.setDisplayStats(!!config.showFPS); - director.startAnimation(); - this.resume(); - } - - // @Game loading section - private _initConfig (config: IGameConfig) { - // Configs adjustment - if (typeof config.debugMode !== 'number') { - config.debugMode = debug.DebugMode.NONE; - } - config.exposeClassName = !!config.exposeClassName; - if (typeof config.frameRate !== 'number') { - config.frameRate = 60; - } - const renderMode = config.renderMode; - if (typeof renderMode !== 'number' || renderMode > 3 || renderMode < 0) { - config.renderMode = 0; - } - config.showFPS = !!config.showFPS; - - debug._resetDebugSetting(config.debugMode); - - this.config = config as NormalizedGameConfig; - this._configLoaded = true; - - this.frameRate = config.frameRate; - } - - private _determineRenderType () { - const config = this.config; - const userRenderMode = parseInt(config.renderMode as any, 10); - - // Determine RenderType - this.renderType = Game.RENDER_TYPE_CANVAS; - let supportRender = false; - - if (userRenderMode === 1) { - this.renderType = Game.RENDER_TYPE_CANVAS; - supportRender = true; - } else if (userRenderMode === 0 || userRenderMode === 2) { - this.renderType = Game.RENDER_TYPE_WEBGL; - supportRender = true; - } else if (userRenderMode === 3) { - this.renderType = Game.RENDER_TYPE_HEADLESS; - supportRender = true; - } - - if (!supportRender) { - throw new Error(debug.getError(3820, userRenderMode)); - } - } - - private _initDevice () { - // Avoid setup to be called twice. - if (this._rendererInitialized) { return; } - - // Obtain platform-related objects through the adapter - const adapter = this.config.adapter; - if (adapter) { - this.canvas = adapter.canvas; - this.frame = adapter.frame; - this.container = adapter.container; - } - - this._determineRenderType(); - - // WebGL context created successfully - if (this.renderType === Game.RENDER_TYPE_WEBGL) { - const deviceInfo = new DeviceInfo(bindingMappingInfo); - - if (JSB && window.gfx) { - this._gfxDevice = gfx.DeviceManager.create(deviceInfo); + if (!this._inited) return; + if (!SplashScreen.instance.isFinished) { + SplashScreen.instance.update(this._calculateDT()); + } else if (this._shouldLoadLaunchScene) { + this._shouldLoadLaunchScene = false; + const launchScene = settings.querySettings(Settings.Category.LAUNCH, 'launchScene'); + if (launchScene) { + // load scene + director.loadScene(launchScene, () => { + console.log(`Success to load scene: ${launchScene}`); + this._initTime = performance.now(); + director.startAnimation(); + this.onStart?.(); + }); } else { - let useWebGL2 = (!!window.WebGL2RenderingContext); - const userAgent = window.navigator.userAgent.toLowerCase(); - if (userAgent.indexOf('safari') !== -1 && userAgent.indexOf('chrome') === -1 - || sys.browserType === BrowserType.UC // UC browser implementation doesn't conform to WebGL2 standard - ) { - useWebGL2 = false; - } - - const deviceCtors: Constructor[] = []; - if (useWebGL2 && legacyCC.WebGL2Device) { - deviceCtors.push(legacyCC.WebGL2Device); - } - if (legacyCC.WebGLDevice) { - deviceCtors.push(legacyCC.WebGLDevice); - } - if (legacyCC.EmptyDevice) { - deviceCtors.push(legacyCC.EmptyDevice); - } - - Device.canvas = this.canvas!; - for (let i = 0; i < deviceCtors.length; i++) { - this._gfxDevice = new deviceCtors[i](); - if (this._gfxDevice.initialize(deviceInfo)) { break; } - } + this._initTime = performance.now(); + director.startAnimation(); + this.onStart?.(); } - } else if (this.renderType === Game.RENDER_TYPE_HEADLESS && legacyCC.EmptyDevice) { - this._gfxDevice = new legacyCC.EmptyDevice(); - this._gfxDevice!.initialize(new DeviceInfo(bindingMappingInfo)); + } else { + director.tick(this._calculateDT()); } + } - if (!this._gfxDevice) { - // todo fix here for wechat game - debug.error('can not support canvas rendering in 3D'); - this.renderType = Game.RENDER_TYPE_CANVAS; - return; - } - - const swapchainInfo = new SwapchainInfo(this.canvas!); - const windowSize = screen.windowSize; - swapchainInfo.width = windowSize.width; - swapchainInfo.height = windowSize.height; - this._swapchain = this._gfxDevice.createSwapchain(swapchainInfo); - - this.canvas!.oncontextmenu = () => false; + private initPacer () { + const frameRate = settings.querySettings(Settings.Category.SCREEN, 'frameRate') ?? 60; + assert(typeof frameRate === 'number'); + this._pacer = new Pacer(); + this._pacer.onTick = this._updateCallback.bind(this); + this.frameRate = frameRate; } private _initEvents () { @@ -967,29 +911,48 @@ export class Game extends EventTarget { this.resume(); } - private _setRenderPipelineNShowSplash () { - return Promise.resolve(this._setupRenderPipeline()).then( - () => Promise.resolve(this._showSplashScreen()).then( - () => { - this._inited = true; - this._initTime = performance.now(); - this._runMainLoop(); - this._safeEmit(Game.EVENT_GAME_INITED); - if (this.onStart) { - this.onStart(); - } - }, - ), - ); + // @ Persist root node section + /** + * @en + * Add a persistent root node to the game, the persistent node won't be destroyed during scene transition.
+ * The target node must be placed in the root level of hierarchy, otherwise this API won't have any effect. + * @zh + * 声明常驻根节点,该节点不会在场景切换中被销毁。
+ * 目标节点必须位于为层级的根节点,否则无效。 + * @param node - The node to be made persistent + * @deprecated Since v3.6.0, please use director.addPersistRootNode instead. + */ + public addPersistRootNode (node: Node) { + director.addPersistRootNode(node); + } + + /** + * @en Remove a persistent root node. + * @zh 取消常驻根节点。 + * @param node - The node to be removed from persistent node list + * @deprecated Since v3.6.0, please use director.removePersistRootNode instead. + */ + public removePersistRootNode (node: Node) { + director.removePersistRootNode(node); + } + + /** + * @en Check whether the node is a persistent root node. + * @zh 检查节点是否是常驻根节点。 + * @param node - The node to be checked. + * @deprecated Since v3.6.0, please use director.isPersistRootNode instead. + */ + public isPersistRootNode (node: Node): boolean { + return director.isPersistRootNode(node); } private _setupRenderPipeline () { - const { renderPipeline } = this.config; + const renderPipeline = settings.querySettings(Settings.Category.RENDERING, 'renderPipeline'); if (!renderPipeline) { return this._setRenderPipeline(); } return new Promise((resolve, reject) => { - legacyCC.assetManager.loadAny(renderPipeline, (err, asset) => ((err || !(asset instanceof RenderPipeline)) + assetManager.loadAny(renderPipeline, (err, asset) => ((err || !(asset instanceof RenderPipeline)) ? reject(err) : resolve(asset))); }).then((asset) => { @@ -1001,20 +964,8 @@ export class Game extends EventTarget { }); } - private _showSplashScreen () { - if (!EDITOR && !PREVIEW && legacyCC.internal.SplashScreen) { - const splashScreen = legacyCC.internal.SplashScreen.instance as SplashScreen; - splashScreen.main(legacyCC.director.root); - return new Promise((resolve) => { - splashScreen.setOnFinish(() => resolve()); - splashScreen.loadFinish = true; - }); - } - return null; - } - private _setRenderPipeline (rppl?: RenderPipeline) { - if (!legacyCC.director.root.setRenderPipeline(rppl)) { + if (!director.root!.setRenderPipeline(rppl)) { this._setRenderPipeline(); } @@ -1048,7 +999,3 @@ legacyCC.Game = Game; * 这是一个 Game 类的实例,包含游戏主体信息并负责驱动游戏的游戏对象。 */ export const game = legacyCC.game = new Game(); - -type NormalizedGameConfig = IGameConfig & { - frameRate: NonNullable; -}; diff --git a/cocos/core/geometry/aabb.ts b/cocos/core/geometry/aabb.ts index c7dcd98aec..5516fc30d0 100644 --- a/cocos/core/geometry/aabb.ts +++ b/cocos/core/geometry/aabb.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module geometry - */ - import { Mat3, Mat4, Quat, Vec3 } from '../math'; import enums from './enums'; import { IVec3, IVec3Like } from '../math/type-define'; @@ -61,13 +56,13 @@ export class AABB { * create a new AABB * @zh * 创建一个新的 AABB 实例。 - * @param px - AABB 的原点的 X 坐标。 - * @param py - AABB 的原点的 Y 坐标。 - * @param pz - AABB 的原点的 Z 坐标。 - * @param hw - AABB 宽度的一半。 - * @param hh - AABB 高度的一半。 - * @param hl - AABB 长度的一半。 - * @returns 返回新创建的 AABB 实例。 + * @param px @zh AABB 的原点的 X 坐标。@en The x coordinate of the origin of the AABB. + * @param py @zh AABB 的原点的 Y 坐标。@en The y coordinate of the origin of the AABB. + * @param pz @zh AABB 的原点的 Z 坐标。 @en The z coordinate of the origin of the AABB. + * @param hw @zh AABB 宽度的一半。 @en Half the width of the AABB. + * @param hh @zh AABB 高度的一半。@en Half the height of the AABB. + * @param hl @zh AABB 长度的一半。@en Half the length of the AABB. + * @returns @zh 返回新创建的 AABB 实例。 @en A new instance of AABB. */ public static create (px?: number, py?: number, pz?: number, hw?: number, hh?: number, hl?: number) { return new AABB(px, py, pz, hw, hh, hl); @@ -78,8 +73,8 @@ export class AABB { * clone a new AABB * @zh * 克隆一个 AABB。 - * @param a - 克隆的目标。 - * @returns 克隆出的 AABB。 + * @param a @zh 克隆的目标。 @en Target object. + * @returns @zh 克隆出的 AABB。@en The new AABB. */ public static clone (a: AABB | Readonly) { return new AABB(a.center.x, a.center.y, a.center.z, @@ -91,9 +86,9 @@ export class AABB { * copy the values from one AABB to another * @zh * 将从一个 AABB 的值复制到另一个 AABB。 - * @param {AABB} out 接受操作的 AABB。 - * @param {AABB} a 被复制的 AABB。 - * @return {AABB} out 接受操作的 AABB。 + * @param out @zh 接受操作的 AABB。 @en The output AABB, copy destination. + * @param a @zh 被复制的 AABB。 @en Source object of copy operation. + * @returns @zh 接受操作的 AABB。 @en The reference of the first parameter `dst`, the new AABB. */ public static copy (out: AABB, a: AABB | Readonly): AABB { Vec3.copy(out.center, a.center); @@ -104,13 +99,13 @@ export class AABB { /** * @en - * create a new AABB from two corner points + * Construct a new AABB from two corner points * @zh * 从两个点创建一个新的 AABB。 - * @param out - 接受操作的 AABB。 - * @param minPos - AABB 的最小点。 - * @param maxPos - AABB 的最大点。 - * @returns {AABB} out 接受操作的 AABB。 + * @param out @zh 接受操作的 AABB。 @en The output AABB + * @param minPos @zh AABB 的最小点。 @en Minimum point of the axis-aligned 3d bounding box. + * @param maxPos @zh AABB 的最大点。 @en Maximum point of the axis-aligned 3d bounding box. + * @returns @zh out 接受操作的 AABB。 @en The new AABB */ public static fromPoints (out: AABB, minPos: IVec3, maxPos: IVec3): AABB { Vec3.add(_v3_tmp, maxPos, minPos); @@ -125,14 +120,14 @@ export class AABB { * Set the components of a AABB to the given values * @zh * 将 AABB 的属性设置为给定的值。 - * @param {AABB} out 接受操作的 AABB。 - * @param px - AABB 的原点的 X 坐标。 - * @param py - AABB 的原点的 Y 坐标。 - * @param pz - AABB 的原点的 Z 坐标。 - * @param hw - AABB 宽度的一半。 - * @param hh - AABB 高度的一半。 - * @param hl - AABB 长度度的一半。 - * @return {AABB} out 接受操作的 AABB。 + * @param @zh out 接受操作的 AABB。 @en The output AABB to set. + * @param px @zh - AABB 的原点的 X 坐标。 @en The x coordinate of the origin of the AABB. + * @param py @zh - AABB 的原点的 Y 坐标。 @en The y coordinate of the origin of the AABB. + * @param pz @zh - AABB 的原点的 Z 坐标。 @en The z coordinate of the origin of the AABB. + * @param hw @zh - AABB 宽度的一半。 @en Half the width of the AABB. + * @param hh @zh - AABB 高度的一半。 @en Half the height of the AABB. + * @param hl @zh - AABB 长度度的一半。 @en Half the length of the AABB. + * @returns @zh out 接受操作的 AABB。 @en The reference fo the first parameter `out`. */ public static set (out: AABB, px: number, py: number, pz: number, hw: number, hh: number, hl: number): AABB { out.center.set(px, py, pz); @@ -142,13 +137,13 @@ export class AABB { /** * @en - * Merge tow AABB. + * Merge two AABB into one. * @zh * 合并两个 AABB 到 out。 - * @param out 接受操作的 AABB。 - * @param a 输入的 AABB。 - * @param b 输入的 AABB。 - * @returns {AABB} out 接受操作的 AABB。 + * @param out @zh 接受操作的 AABB。 @en The output AABB to storge merge result. + * @param a @zh 输入的 AABB。 @en The first AABB to be merged. + * @param b @zh 输入的 AABB。 @en The second AABB to be merged. + * @returns @zh out 接受操作的 AABB。 @en The reference of the first parameter `out`. */ public static merge (out: AABB, a: AABB | Readonly, b: AABB | Readonly): AABB { Vec3.subtract(_v3_tmp, a.center, a.halfExtents); @@ -162,11 +157,12 @@ export class AABB { /** * @en - * AABB to sphere + * Convert AABB to sphere. * @zh * 包围盒转包围球 - * @param out 接受操作的 sphere。 - * @param a 输入的 AABB。 + * @param out @zh 接受操作的 sphere。 @en The output sphere. + * @param a @zh 输入的 AABB。 @en The input AABB. + * @returns @zh out 接受的 Sphere @en The reference of the first parameter `out`. */ public static toBoundingSphere (out: Sphere, a: AABB | Readonly) { out.center.set(a.center); @@ -179,10 +175,10 @@ export class AABB { * Transform this AABB. * @zh * 变换一个 AABB 到 out 中。 - * @param out 接受操作的 AABB。 - * @param a 输入的源 AABB。 - * @param matrix 矩阵。 - * @returns {AABB} out 接受操作的 AABB。 + * @param out @zh 接受操作的 AABB。 @en The output AABB. + * @param a @zh 输入的源 AABB。 @en The input AABB. + * @param matrix @zh 矩阵。 @en The transformation matrix. + * @returns @zh {AABB} out 接受操作的 AABB。 @en The reference of the first parameter `out`. */ public static transform (out: AABB, a: AABB | Readonly, matrix: Mat4 | Readonly): AABB { Vec3.transformMat4(out.center, a.center, matrix); @@ -191,12 +187,16 @@ export class AABB { } /** + * @en + * The origin point of the AABB * @zh * 本地坐标的中心点。 */ public center: Vec3; /** + * @en + * Half the size of the AABB * @zh * 长宽高的一半。 */ @@ -225,8 +225,8 @@ export class AABB { * Get the bounding points of this shape * @zh * 获取 AABB 的最小点和最大点。 - * @param {Vec3} minPos 最小点。 - * @param {Vec3} maxPos 最大点。 + * @param minPos @zh 最小点。 @en Minimum position of the axis-aligned 3d bounding box. + * @param maxPos @zh 最大点。 @en Maximum position of the axis-aligned 3d bounding box. */ public getBoundary (minPos: IVec3Like, maxPos: IVec3Like) { Vec3.subtract(minPos, this.center, this.halfExtents); @@ -238,11 +238,11 @@ export class AABB { * Transform this shape * @zh * 将 out 根据这个 AABB 的数据进行变换。 - * @param m 变换的矩阵。 - * @param pos 变换的位置部分。 - * @param rot 变换的旋转部分。 - * @param scale 变换的缩放部分。 - * @param out 变换的目标。 + * @param m @zh 变换的矩阵。 @en The transform matrix. + * @param pos @zh 变换的位置部分。 @en 3d-vector translation. + * @param rot @zh 变换的旋转部分。 @en Quaternion rotation . + * @param scale @zh 变换的缩放部分。 @en 3d-vector scale. + * @param out @zh 变换的目标。 @en The output AABB. */ public transform (m: Mat4, pos: Vec3 | null, rot: Quat | null, scale: Vec3 | null, out: AABB) { Vec3.transformMat4(out.center, this.center, m); @@ -250,19 +250,23 @@ export class AABB { } /** + * @en + * Clones the AABB * @zh * 获得克隆。 - * @returns {AABB} + * @returns @zh {AABB} @en A copy of the object. */ public clone (): AABB { return AABB.clone(this); } /** + * @en + * Copy the input to the receiver object. * @zh * 拷贝对象。 - * @param a 拷贝的目标。 - * @returns {AABB} + * @param a @zh 拷贝的目标。 @en Copy target + * @returns @zh This object @en The reference of this. */ public copy (a: AABB | Readonly): AABB { return AABB.copy(this, a); @@ -271,7 +275,7 @@ export class AABB { /** * @en AABB and point merge. * @zh AABB包围盒合并一个顶点。 - * @param point - 某一个位置的顶点。 + * @param point @zh - 某一个位置的顶点。 @en A point in 3d space. */ public mergePoint (point: IVec3) { // _v3_tmp is min pos @@ -291,10 +295,10 @@ export class AABB { } /** - * @en AABB and points merge. - * @zh AABB包围盒合并一系列顶点。 - * @param points - 某一个位置的顶点。 - */ + * @en AABB and points merge. + * @zh AABB包围盒合并一系列顶点。 + * @param points @zh - 某一个位置的顶点。 @en A list of points in 3d space. + */ public mergePoints (points: IVec3[]) { if (points.length < 1) { return; } for (let i = 0; i < points.length; i++) { @@ -305,7 +309,7 @@ export class AABB { /** * @en AABB and frustum merge. * @zh Frustum 合并到 AABB。 - * @param frustum 输入的 Frustum。 + * @param frustum @zh 输入的 Frustum。 @en The frustum object. */ public mergeFrustum (frustum: Frustum | Readonly) { return this.mergePoints(frustum.vertices); diff --git a/cocos/core/geometry/capsule.ts b/cocos/core/geometry/capsule.ts index 0351275a40..bc8bdd8b67 100644 --- a/cocos/core/geometry/capsule.ts +++ b/cocos/core/geometry/capsule.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module geometry - */ - import { Vec3, Quat, Mat4, absMaxComponent } from '../math'; import enums from './enums'; import { IVec3Like, IQuatLike } from '../math/type-define'; @@ -91,8 +86,14 @@ export class Capsule { */ readonly rotation: Quat; - /** cache, local center of ellipse */ + /** + * @internal + * cache, local center of ellipse + **/ readonly ellipseCenter0: Vec3; + /** + * @internal + */ readonly ellipseCenter1: Vec3; constructor (radius = 0.5, halfHeight = 0.5, axis = 1) { @@ -154,6 +155,8 @@ export class Capsule { this.ellipseCenter0.set(0, 0, halfHeight); this.ellipseCenter1.set(0, 0, -halfHeight); break; + default: + break; } } } diff --git a/cocos/core/geometry/curve.ts b/cocos/core/geometry/curve.ts index 0d0242df21..8dddaebb6b 100644 --- a/cocos/core/geometry/curve.ts +++ b/cocos/core/geometry/curve.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module geometry - */ - import { CCClass } from '../data/class'; import { clamp, inverseLerp, pingPong, repeat } from '../math/utils'; import { WrapModeMask } from '../animation/types'; @@ -120,7 +115,7 @@ export class AnimationCurve { /** * For internal usage only. - * @legacyPublic + * @internal */ get _internalCurve () { return this._curve; @@ -157,9 +152,9 @@ export class AnimationCurve { /** * @en - * Loop mode [[WrapMode]] when the sampling time exceeds the left end. + * Loop mode [[AnimationClip.WrapMode]] when the sampling time exceeds the left end. * @zh - * 当采样时间超出左端时采用的循环模式[[WrapMode]]。 + * 当采样时间超出左端时采用的循环模式[[AnimationClip.WrapMode]]。 */ get preWrapMode () { return toLegacyWrapMode(this._curve.preExtrapolation); @@ -171,9 +166,9 @@ export class AnimationCurve { /** * @en - * Cycle mode [[WrapMode]] when the sampling time exceeds the right end. + * Cycle mode [[AnimationClip.WrapMode]] when the sampling time exceeds the right end. * @zh - * 当采样时间超出右端时采用的循环模式[[WrapMode]]。 + * 当采样时间超出右端时采用的循环模式[[AnimationClip.WrapMode]]。 */ get postWrapMode () { return toLegacyWrapMode(this._curve.postExtrapolation); @@ -186,8 +181,9 @@ export class AnimationCurve { private cachedKey: OptimizedKey; /** - * 构造函数。 - * @param keyFrames 关键帧。 + * @en Construct a curve with key frames + * @zh 通过关键帧构造一条曲线。 + * @param keyFrames @zh 关键帧 @en Key frames */ constructor (keyFrames: Keyframe[] | null | RealCurve = null) { if (keyFrames instanceof RealCurve) { @@ -219,7 +215,7 @@ export class AnimationCurve { * Add a keyframe. * @zh * 添加一个关键帧。 - * @param keyFrame 关键帧。 + * @param keyFrame @en A keyframe. @zh 关键帧。 */ public addKey (keyFrame: Keyframe | null) { if (!keyFrame) { @@ -247,7 +243,7 @@ export class AnimationCurve { * Calculate the curve interpolation at a given point in time. * @zh * 计算给定时间点的曲线插值。 - * @param time 时间。 + * @param time @en The time. @zh 时间。 */ public evaluate (time: number) { const { cachedKey, _curve: curve } = this; diff --git a/cocos/core/geometry/deprecated-3.0.0.ts b/cocos/core/geometry/deprecated-3.0.0.ts index ef0d56040f..55432581fb 100644 --- a/cocos/core/geometry/deprecated-3.0.0.ts +++ b/cocos/core/geometry/deprecated-3.0.0.ts @@ -151,8 +151,12 @@ function deprecatedClassMessage (oldClassName: string, newClassName) { } /** - * Alias of [[Line]] - * @deprecated Since v3.0 + * @en + * Alias of [[geometry.Line]] + * @zh + * [[geometry.Line]] 别名类 + * + * @deprecated Since v3.0, please use Line instead */ export class line extends Line { constructor () { @@ -162,8 +166,13 @@ export class line extends Line { } /** - * Alias of [[Plane]] - * @deprecated Since v3.0 + * @en + * Alias of [[geometry.Plane]] + * + * @zh + * [[geometry.Plane]] 别名类 + * + * @deprecated Since v3.0, please use Plane instead */ export class plane extends Plane { constructor () { @@ -173,8 +182,11 @@ export class plane extends Plane { } /** - * Alias of [[Ray]] - * @deprecated Since v3.0 + * @en + * Alias of [[geometry.Ray]] + * @zh + * [[geometry.Ray]] 别名类 + * @deprecated Since v3.0, please use Ray instead */ export class ray extends Ray { constructor () { @@ -184,8 +196,12 @@ export class ray extends Ray { } /** - * Alias of [[Triangle]] - * @deprecated Since v3.0 + * @en + * Alias of [[geometry.Triangle]] + * + * @zh + * [[geometry.Triangle]] 别名类 + * @deprecated Since v3.0, please use Triangle instead */ export class triangle extends Triangle { constructor () { @@ -195,8 +211,12 @@ export class triangle extends Triangle { } /** - * Alias of [[Sphere]] - * @deprecated Since v3.0 + * @en + * Alias of [[geometry.Sphere]] + * + * @zh + * [[geometry.Sphere]] 别名类 + * @deprecated Since v3.0, please use Sphere instead */ export class sphere extends Sphere { constructor () { @@ -206,8 +226,12 @@ export class sphere extends Sphere { } /** - * Alias of [[AABB]] - * @deprecated Since v3.0 + * @en + * Alias of [[geometry.AABB]] + * + * @zh + * [[geometry.AABB]] 别名类 + * @deprecated Since v3.0, please use AABB instead */ export class aabb extends AABB { constructor () { @@ -217,8 +241,12 @@ export class aabb extends AABB { } /** - * Alias of [[OBB]] - * @deprecated Since v3.0 + * @en + * Alias of [[geometry.OBB]] + * + * @zh + * [[geometry.OBB]] 别名类 + * @deprecated Since v3.0, please use OBB instead */ export class obb extends OBB { constructor () { @@ -228,8 +256,12 @@ export class obb extends OBB { } /** - * Alias of [[Capsule]] - * @deprecated Since v3.0 + * @en + * Alias of [[geometry.Capsule]] + * + * @zh + * [[geometry.Capsule]] 别名类 + * @deprecated Since v3.0, please use Capsule instead */ export class capsule extends Capsule { constructor () { @@ -239,8 +271,12 @@ export class capsule extends Capsule { } /** - * Alias of [[Frustum]] - * @deprecated Since v3.0 + * @en + * Alias of [[geometry.Frustum]] + * + * @zh + * [[geometry.Frustum]] 别名类 + * @deprecated Since v3.0, please use Frustum instead */ export class frustum extends Frustum { constructor () { diff --git a/cocos/core/geometry/deprecated.ts b/cocos/core/geometry/deprecated.ts index 91c1f0a51d..4d993a79d4 100644 --- a/cocos/core/geometry/deprecated.ts +++ b/cocos/core/geometry/deprecated.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { replaceProperty, removeProperty } from '../utils/x-deprecated'; import { Line } from './line'; import intersect from './intersect'; diff --git a/cocos/core/geometry/distance.ts b/cocos/core/geometry/distance.ts index 322b9385cc..468b847c20 100644 --- a/cocos/core/geometry/distance.ts +++ b/cocos/core/geometry/distance.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module geometry - */ - import { Vec3 } from '../math'; import { AABB } from './aabb'; import { OBB } from './obb'; @@ -47,9 +42,9 @@ const e = new Array(3); * the distance between a point and a plane * @zh * 计算点和平面之间的距离。 - * @param {Vec3} point 点。 - * @param {Plane} plane 平面。 - * @return 距离。 + * @param {Vec3} point @en Target point @zh 目标点。 + * @param {Plane} plane @en Target plane @zh 目标平面。 + * @return @en The distance in between @zh 距离。 */ export function point_plane (point: Vec3, plane_: Plane) { return Vec3.dot(plane_.n, point) - plane_.d; @@ -60,10 +55,10 @@ export function point_plane (point: Vec3, plane_: Plane) { * the closest point on plane to a given point * @zh * 计算平面上最接近给定点的点。 - * @param out 最近点。 - * @param point 给定点。 - * @param plane 平面。 - * @return 最近点。 + * @param out @en The closest point, as a result @zh 最近点。 + * @param point @en The given point @zh 给定点。 + * @param plane @en Target plane @zh 平面。 + * @return @en The closest point, same as out @zh 最近点。 */ export function pt_point_plane (out: Vec3, point: Vec3, plane_: Plane) { const t = point_plane(point, plane_); @@ -75,10 +70,10 @@ export function pt_point_plane (out: Vec3, point: Vec3, plane_: Plane) { * the closest point on aabb to a given point * @zh * 计算 aabb 上最接近给定点的点。 - * @param {Vec3} out 最近点。 - * @param {Vec3} point 给定点。 - * @param {AABB} aabb 轴对齐包围盒。 - * @return {Vec3} 最近点。 + * @param {Vec3} out @en The closest point, as a result @zh 最近点。 + * @param {Vec3} point @en The given point @zh 给定点。 + * @param {AABB} aabb @en Target aabb to calculate @zh 轴对齐包围盒。 + * @return {Vec3} @en The closest point, same as out @zh 最近点。 */ export function pt_point_aabb (out: Vec3, point: Vec3, aabb_: AABB): Vec3 { Vec3.copy(out, point); @@ -100,10 +95,10 @@ export function pt_point_aabb (out: Vec3, point: Vec3, aabb_: AABB): Vec3 { * the closest point on obb to a given point * @zh * 计算 obb 上最接近给定点的点。 - * @param {Vec3} out 最近点。 - * @param {Vec3} point 给定点。 - * @param {OBB} obb 方向包围盒。 - * @return {Vec3} 最近点。 + * @param {Vec3} out @en The closest point, as a result @zh 最近点。 + * @param {Vec3} point @en The given point @zh 给定点。 + * @param {OBB} obb @en Target obb to calculate @zh 方向包围盒。 + * @return {Vec3} @en The closest point, same as out @zh 最近点。 */ export function pt_point_obb (out: Vec3, point: Vec3, obb_: OBB): Vec3 { Vec3.set(X, obb_.orientation.m00, obb_.orientation.m01, obb_.orientation.m02); @@ -146,13 +141,13 @@ export function pt_point_obb (out: Vec3, point: Vec3, obb_: OBB): Vec3 { /** * @en - * Calculate the nearest point on the line to the given point. + * Calculate the nearest point on the line, which is from A to B, to the given point * @zh - * 计算给定点距离直线上最近的一点。 - * @param out 最近点 - * @param point 给定点 - * @param linePointA 线上的某点 A - * @param linePointB 线上的某点 B + * 计算给定点距离线段上最近的一点。线段从A到B。 + * @param out @en The closest point, as a result @zh 最近点 + * @param point @en The given point @zh 给定点 + * @param linePointA @en Point A on the line @zh 线上的某点 A + * @param linePointB @en Point B on the line @zh 线上的某点 B */ export function pt_point_line (out: Vec3, point: Vec3, linePointA: Vec3, linePointB: Vec3) { Vec3.subtract(X, linePointA, linePointB); diff --git a/cocos/core/geometry/enums.ts b/cocos/core/geometry/enums.ts index e954a0e541..de211f3cc8 100644 --- a/cocos/core/geometry/enums.ts +++ b/cocos/core/geometry/enums.ts @@ -45,4 +45,5 @@ export default { SHAPE_FRUSTUM: (1 << 7), SHAPE_FRUSTUM_ACCURATE: (1 << 8), SHAPE_CAPSULE: (1 << 9), + SHAPE_SPLINE: (1 << 10), }; diff --git a/cocos/core/geometry/frustum.ts b/cocos/core/geometry/frustum.ts index a9c02fae07..0415c871b2 100644 --- a/cocos/core/geometry/frustum.ts +++ b/cocos/core/geometry/frustum.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module geometry - */ - import { Mat4, Vec3 } from '../math'; import { Camera } from '../renderer/scene'; import enums from './enums'; @@ -58,26 +53,16 @@ const _temp_v3 = new Vec3(); export class Frustum { /** * @en - * Set whether to use accurate intersection testing function on this frustum. - * @zh - * 设置是否在此截锥体上使用精确的相交测试函数。 - */ - set accurate (b: boolean) { - this._type = b ? enums.SHAPE_FRUSTUM_ACCURATE : enums.SHAPE_FRUSTUM; - } - - /** - * @en - * Create a ortho frustum. + * Create an orthogonal frustum. * @zh * 创建一个正交视锥体。 - * @param out 正交视锥体。 - * @param width 正交视锥体的宽度。 - * @param height 正交视锥体的高度。 - * @param near 正交视锥体的近平面值。 - * @param far 正交视锥体的远平面值。 - * @param transform 正交视锥体的变换矩阵。 - * @return {Frustum} frustum. + * @param out @en The result orthogonal frustum. @zh 输出的正交视锥体。 + * @param width @en The width of the frustum. @zh 正交视锥体的宽度。 + * @param height @en The height of the frustum. @zh 正交视锥体的高度。 + * @param near @en The near plane of the frustum. @zh 正交视锥体的近平面值。 + * @param far @en The far plane of the frustum. @zh 正交视锥体的远平面值。 + * @param transform @en The transform matrix of the frustum. @zh 正交视锥体的变换矩阵。 + * @return @en The out object @zh 返回正交视锥体. */ public static createOrtho = (() => (out: Frustum, width: number, height: number, near: number, far: number, transform: Mat4) => { const halfWidth = width / 2; @@ -110,9 +95,9 @@ export class Frustum { /** * @en Create a frustum from an AABB box. * @zh 从 AABB 包围盒中创建一个视锥体。 - * @param out 视锥体。 - * @param aabb AABB 包围盒。 - * @return {Frustum} frustum. + * @param out @en The result frustum @zh 输出的视锥体对象。 + * @param aabb @en The AABB bounding box of the frustum @zh AABB 包围盒。 + * @return @en The out object @zh 返回视锥体. */ public static createFromAABB (out: Frustum, aabb: AABB | Readonly) : Frustum { const vec3_min = new Vec3(); const vec3_max = new Vec3(); @@ -138,14 +123,14 @@ export class Frustum { } /** - * @en create a new frustum. + * @en Calculate the splitted frustum. * @zh 创建一个新的截锥体。 - * @param out 返回新截锥体 - * @param camera 相机参数 - * @param m 变换矩阵 - * @param start 分割开始位置 - * @param end 分割末尾位置 - * @return {Frustum} 返回新截锥体. + * @param out @en The output frustum @zh 输出的新截锥体 + * @param camera @en The camera of the frustum @zh 相机参数 + * @param m @en The transform matrix @zh 变换矩阵 + * @param start @en The split start position @zh 分割开始位置 + * @param end @en The split end position @zh 分割末尾位置 + * @return @en The out object @zh 返回新截锥体. */ public static split (out: Frustum, camera: Camera, m: Mat4, start: number, end: number): Frustum { // 0: cameraNear 1:cameraFar @@ -181,10 +166,10 @@ export class Frustum { /** * @en - * create a new frustum. + * Create a new frustum. * @zh * 创建一个新的截锥体。 - * @return {Frustum} frustum. + * @return @en An empty frustum. @zh 一个空截椎体 */ public static create (): Frustum { return new Frustum(); @@ -195,6 +180,8 @@ export class Frustum { * Clone a frustum. * @zh * 克隆一个截锥体。 + * @param f @en The frustum to clone from @zh 用于克隆的截锥体 + * @return @en The cloned frustum @zh 克隆出的新截锥体 */ public static clone (f: Frustum): Frustum { return Frustum.copy(new Frustum(), f); @@ -204,10 +191,13 @@ export class Frustum { * @en * Copy the values from one frustum to another. * @zh - * 从一个截锥体拷贝到另一个截锥体。 + * 从一个视锥体拷贝到另一个视锥体。 + * @param out @en The result frustum @zh 用于存储拷贝数据的截锥体 + * @param f @en The frustum to copy from @zh 用于克隆的截锥体 + * @return @en The out object @zh 传入的 out 对象 */ - public static copy (out: Frustum, f: Frustum): Frustum { - out._type = f._type; + public static copy (out: Frustum, f: Readonly): Frustum { + out._type = f.type; for (let i = 0; i < 6; ++i) { Plane.copy(out.planes[i], f.planes[i]); } @@ -217,21 +207,32 @@ export class Frustum { return out; } + /** + * @en + * Set whether to use accurate intersection testing function on this frustum. + * @zh + * 设置是否在此截锥体上使用精确的相交测试函数。 + */ + set accurate (b: boolean) { + this._type = b ? enums.SHAPE_FRUSTUM_ACCURATE : enums.SHAPE_FRUSTUM; + } + /** * @en * Gets the type of the shape. * @zh * 获取形状的类型。 + * @readonly */ get type () { return this._type; } - protected _type: number; - public planes: Plane[]; public vertices: Vec3[]; + protected _type: number; + constructor () { this._type = enums.SHAPE_FRUSTUM; this.planes = new Array(6); @@ -250,8 +251,8 @@ export class Frustum { * Note that the resulting planes are not normalized under normal mode. * @zh * 根据给定的变换矩阵更新截锥体信息,注意得到的平面不是在标准模式下归一化的。 - * @param {Mat4} m the view-projection matrix - * @param {Mat4} inv the inverse view-projection matrix + * @param m @en The view-projection matrix @zh 视图投影矩阵 + * @param inv @en The inverse view-projection matrix @zh 视图投影逆矩阵 */ public update (m: Mat4, inv: Mat4) { // RTR4, ch. 22.14.1, p. 983 @@ -296,8 +297,8 @@ export class Frustum { * @en * Transform this frustum. * @zh - * 变换此截锥体。 - * @param mat 变换矩阵。 + * 变换此视锥体。 + * @param mat @en The transform matrix @zh 变换矩阵 */ public transform (mat: Mat4) { if (this._type !== enums.SHAPE_FRUSTUM_ACCURATE) { @@ -306,14 +307,24 @@ export class Frustum { for (let i = 0; i < 8; i++) { Vec3.transformMat4(this.vertices[i], this.vertices[i], mat); } - Plane.fromPoints(this.planes[0], this.vertices[1], this.vertices[6], this.vertices[5]); - Plane.fromPoints(this.planes[1], this.vertices[3], this.vertices[4], this.vertices[7]); - Plane.fromPoints(this.planes[2], this.vertices[6], this.vertices[3], this.vertices[7]); - Plane.fromPoints(this.planes[3], this.vertices[0], this.vertices[5], this.vertices[4]); - Plane.fromPoints(this.planes[4], this.vertices[2], this.vertices[0], this.vertices[3]); - Plane.fromPoints(this.planes[5], this.vertices[7], this.vertices[5], this.vertices[6]); + this.updatePlanes(); } + /** + * @en Initialize the frustum + * @zh 初始化视锥体 + */ + public zero () { + for (let i = 0; i < 8; i++) { + this.vertices[i].set(0.0, 0.0, 0.0); + } + this.updatePlanes(); + } + + /** + * @en Update all six planes of the frustum + * @zh 更新视锥体的所有面数据 + */ public updatePlanes () { // left plane Plane.fromPoints(this.planes[0], this.vertices[1], this.vertices[6], this.vertices[5]); diff --git a/cocos/core/geometry/index.ts b/cocos/core/geometry/index.ts index 9a52a0b768..f813ef18cc 100644 --- a/cocos/core/geometry/index.ts +++ b/cocos/core/geometry/index.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module geometry - */ - import * as distance from './distance'; import './deprecated'; @@ -45,5 +40,6 @@ export { OBB } from './obb'; export { Capsule } from './capsule'; export { Frustum } from './frustum'; export { Keyframe, AnimationCurve } from './curve'; +export { SplineMode, Spline } from './spline'; export * from './spec'; export * from './deprecated-3.0.0'; diff --git a/cocos/core/geometry/intersect.ts b/cocos/core/geometry/intersect.ts index 2a5d217d31..bdbee3b91f 100644 --- a/cocos/core/geometry/intersect.ts +++ b/cocos/core/geometry/intersect.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module geometry - */ - import { EPSILON, Mat3, Vec3, Mat4 } from '../math'; import { AABB } from './aabb'; import { Capsule } from './capsule'; @@ -52,9 +47,9 @@ import { scene } from '../renderer'; * ray-plane intersect detect. * @zh * 射线与平面的相交性检测。 - * @param {Ray} ray 射线 - * @param {Plane} plane 平面 - * @return {number} 0 或 非0 + * @param ray @zh 射线 @en The ray to test + * @param plane @zh 平面 @en The plane to test + * @return @zh 0 或 非0 @en 0 or not 0, 0 indicates there is no intersection */ const rayPlane = (function () { const pt = new Vec3(0, 0, 0); @@ -75,10 +70,10 @@ const rayPlane = (function () { * ray-triangle intersect detect. * @zh * 射线与三角形的相交性检测。 - * @param {Ray} ray 射线 - * @param {Triangle} triangle 三角形 - * @param {boolean} doubleSided 三角形是否为双面 - * @return {number} 0 或 非0 + * @param ray @zh 射线 @en The ray to test + * @param triangle @zh 三角形 @en The triangle to test + * @param doubleSided @zh 三角形是否为双面 @en Indicates whether it is double sided + * @return @zh 0 或 非0 @en 0 or not 0, 0 indicates there is no intersection */ const rayTriangle = (function () { const ab = new Vec3(0, 0, 0); @@ -115,9 +110,9 @@ const rayTriangle = (function () { * ray-sphere intersect detect. * @zh * 射线和球的相交性检测。 - * @param {Ray} ray 射线 - * @param {Sphere} sphere 球 - * @return {number} 0 或 非0 + * @param ray @zh 射线 @en The ray to test + * @param sphere @zh 球 @en The sphere to test + * @return @zh 0 或 非0 @en 0 or not 0, 0 indicates there is no intersection */ const raySphere = (function () { const e = new Vec3(0, 0, 0); @@ -146,9 +141,9 @@ const raySphere = (function () { * ray-aabb intersect detect. * @zh * 射线和轴对齐包围盒的相交性检测。 - * @param {Ray} ray 射线 - * @param {AABB} aabb 轴对齐包围盒 - * @return {number} 0 或 非0 + * @param ray @zh 射线 @en The ray to test + * @param aabb @zh 轴对齐包围盒 @en The aabb to test + * @return @zh 0 或 非0 @en 0 or not 0, 0 indicates there is no intersection */ const rayAABB = (function () { const min = new Vec3(); @@ -180,9 +175,9 @@ function rayAABB2 (ray: Ray, min: IVec3Like, max: IVec3Like) { * ray-obb intersect detect. * @zh * 射线和方向包围盒的相交性检测。 - * @param {Ray} ray 射线 - * @param {OBB} obb 方向包围盒 - * @return {number} 0 或 非0 + * @param ray @zh 射线 @en The ray + * @param obb @zh 方向包围盒 @en The obb to test + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ const rayOBB = (function () { let center = new Vec3(); @@ -260,9 +255,9 @@ const rayOBB = (function () { * ray-capsule intersect detect. * @zh * 射线和胶囊体的相交性检测。 - * @param {Ray} ray 射线 - * @param {Capsule} capsule 胶囊体 - * @return {number} 0 或 非0 + * @param ray @zh 射线 @en The ray to test + * @param capsule @zh 胶囊体 @en The capsule to test + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ const rayCapsule = (function () { const v3_0 = new Vec3(); @@ -346,10 +341,10 @@ const rayCapsule = (function () { * ray-subMesh intersect detect, in model space. * @zh * 在模型空间中,射线和子三角网格的相交性检测。 - * @param {Ray} ray - * @param {RenderingSubMesh} subMesh - * @param {IRaySubMeshOptions} options - * @return {number} 0 or !0 + * @param ray @zh 射线 @en The ray to test + * @param subMesh @zh 子网格 @en The sub mesh to test + * @param options @zh 额外选项 @en Optional params + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ const raySubMesh = (function () { const tri = Triangle.create(); @@ -442,10 +437,10 @@ const raySubMesh = (function () { * ray-mesh intersect detect, in model space. * @zh * 在模型空间中,射线和三角网格资源的相交性检测。 - * @param {Ray} ray - * @param {Mesh} mesh - * @param {IRayMeshOptions} options - * @return {number} 0 or !0 + * @param ray @zh 射线 @en The ray to test + * @param mesh @zh 网格 @en The mesh to test + * @param options @zh 可选参数 @en Optional param + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ const rayMesh = (function () { let minDis = 0; @@ -491,10 +486,10 @@ const rayMesh = (function () { * ray-model intersect detect, in world space. * @zh * 在世界空间中,射线和渲染模型的相交性检测。 - * @param ray - * @param model - * @param options - * @return 0 or !0 + * @param ray @zh 射线 @en The ray to test + * @param model @zh model @en The model to test + * @param options @zh 可选参数 @en Optional param + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ const rayModel = (function () { let minDis = 0; @@ -547,9 +542,9 @@ const rayModel = (function () { * line-plane intersect detect. * @zh * 线段与平面的相交性检测。 - * @param {line} line 线段 - * @param {Plane} plane 平面 - * @return {number} 0 或 非0 + * @param line @zh 线段 @en The line to test + * @param plane @zh 平面 @en The plane to test + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ const linePlane = (function () { const ab = new Vec3(0, 0, 0); @@ -567,10 +562,10 @@ const linePlane = (function () { * line-triangle intersect detect. * @zh * 线段与三角形的相交性检测。 - * @param {line} line 线段 - * @param {Triangle} triangle 三角形 - * @param {Vec3} outPt 可选,相交点 - * @return {number} 0 或 非0 + * @param line @zh 线段 @en The line to test + * @param triangle @zh 三角形 @en The triangle to test + * @param outPt @zh 可选,相交点 @en Optional out param, indicates the intersection point + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ const lineTriangle = (function () { const ab = new Vec3(0, 0, 0); @@ -632,9 +627,9 @@ const r_t = new Ray(); * line-aabb intersect detect. * @zh * 线段与轴对齐包围盒的相交性检测 - * @param line 线段 - * @param aabb 轴对齐包围盒 - * @return {number} 0 或 非0 + * @param line @zh 线段 @en The line to test + * @param aabb @zh 轴对齐包围盒 @en The aabb to test + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ function lineAABB (line: Line, aabb: AABB): number { r_t.o.set(line.s); @@ -654,9 +649,9 @@ function lineAABB (line: Line, aabb: AABB): number { * line-obb intersect detect. * @zh * 线段与方向包围盒的相交性检测 - * @param line 线段 - * @param obb 方向包围盒 - * @return {number} 0 或 非0 + * @param line @zh 线段 @en The line to test + * @param obb @zh 方向包围盒 @en The obb + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ function lineOBB (line: Line, obb: OBB): number { r_t.o.set(line.s); @@ -676,9 +671,9 @@ function lineOBB (line: Line, obb: OBB): number { * line-sphere intersect detect. * @zh * 线段与球的相交性检测 - * @param line 线段 - * @param sphere 球 - * @return {number} 0 或 非0 + * @param line @zh 线段 @en The line to test + * @param sphere @zh 球 @en The sphere to test + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ function lineSphere (line: Line, sphere: Sphere): number { r_t.o.set(line.s); @@ -698,9 +693,9 @@ function lineSphere (line: Line, sphere: Sphere): number { * aabb-aabb intersect detect. * @zh * 轴对齐包围盒和轴对齐包围盒的相交性检测。 - * @param {AABB} aabb1 轴对齐包围盒1 - * @param {AABB} aabb2 轴对齐包围盒2 - * @return {number} 0 或 非0 + * @param aabb1 @zh 轴对齐包围盒1 @en aabb 1 to test + * @param aabb2 @zh 轴对齐包围盒2 @en aabb 2 to test + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ const aabbWithAABB = (function () { const aMin = new Vec3(); @@ -779,9 +774,9 @@ function getInterval (vertices: any[] | Vec3[], axis: Vec3) { * aabb-obb intersect detect. * @zh * 轴对齐包围盒和方向包围盒的相交性检测。 - * @param {AABB} aabb 轴对齐包围盒 - * @param {OBB} obb 方向包围盒 - * @return {number} 0 或 非0 + * @param aabb @zh 轴对齐包围盒 @en The aabb to test + * @param obb @zh 方向包围盒 @en The obb to test + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ const aabbWithOBB = (function () { const test = new Array(15); @@ -832,9 +827,9 @@ const aabbWithOBB = (function () { * aabb-plane intersect detect. * @zh * 轴对齐包围盒和平面的相交性检测。 - * @param {AABB} aabb 轴对齐包围盒 - * @param {Plane} plane 平面 - * @return {number} inside(back) = -1, outside(front) = 0, intersect = 1 + * @param aabb @zh 轴对齐包围盒 @en The aabb to test + * @param plane @zh 平面 @en The plane to test + * @return @zh 检测结果, 包含为 -1, 不包含为 0, 相交为 1 @en Test result, inside(back) = -1, outside(front) = 0, intersect = 1 */ const aabbPlane = function (aabb: AABB, plane: Plane): number { const r = aabb.halfExtents.x * Math.abs(plane.n.x) @@ -850,11 +845,11 @@ const aabbPlane = function (aabb: AABB, plane: Plane): number { * aabb-frustum intersect detect, faster but has false positive corner cases. * @zh * 轴对齐包围盒和锥台相交性检测,速度快,但有错误情况。 - * @param {AABB} aabb 轴对齐包围盒 - * @param {Frustum} frustum 锥台 - * @return {number} 0 或 非0 + * @param aabb @zh 轴对齐包围盒 @en The aabb to test + * @param frustum @zh 锥台 @en The frustum to test + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ -const aabbFrustum = function (aabb: AABB, frustum: Frustum): number { +const aabbFrustum = function (aabb: AABB, frustum: Readonly): number { for (let i = 0; i < frustum.planes.length; i++) { // frustum plane normal points to the inside if (aabbPlane(aabb, frustum.planes[i]) === -1) { @@ -864,15 +859,34 @@ const aabbFrustum = function (aabb: AABB, frustum: Frustum): number { return 1; }; +/** + * @en + * aabb-frustum intersect detect, faster but false while frustum is completely inside the aabb. + * @zh + * 轴对齐包围盒和锥台的相交性检测。速度快,但是当锥台完全在aabb中时就会判断出错。 + * @param {AABB} aabb 轴对齐包围盒 + * @param {Frustum} frustum 锥台 + * @return {number} aabb completely inside the frustum = 1, otherwise = 0 + */ +const aabbFrustumCompletelyInside = function (aabb: AABB, frustum: Readonly): number { + for (let i = 0; i < frustum.planes.length; i++) { + // frustum plane normal points to the inside + if (aabbPlane(aabb, frustum.planes[i]) !== 0) { + return 0; + } + } // completely inside + return 1; +}; + // https://cesium.com/blog/2017/02/02/tighter-frustum-culling-and-why-you-may-want-to-disregard-it/ /** * @en * aabb-frustum intersect, handles most of the false positives correctly. * @zh * 轴对齐包围盒和锥台相交性检测,正确处理大多数错误情况。 - * @param {AABB} aabb 轴对齐包围盒 - * @param {Frustum} frustum 锥台 - * @return {number} + * @param aabb @zh 轴对齐包围盒 @en The aabb to test + * @param frustum @zh 锥台 @en The frustum to test + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ const aabbFrustumAccurate = (function () { const tmp = new Array(8); @@ -919,9 +933,9 @@ const aabbFrustumAccurate = (function () { * obb contains the point. * @zh * 方向包围盒和点的相交性检测。 - * @param {OBB} obb 方向包围盒 - * @param {Vec3} point 点 - * @return {boolean} true or false + * @param obb @zh 方向包围盒 @en The obb to test + * @param point @zh 点 @en The point to test + * @return @zh 布尔值 @en The value indicates if there is a intersection */ const obbPoint = (function () { const tmp = new Vec3(0, 0, 0); const m3 = new Mat3(); @@ -938,9 +952,9 @@ const obbPoint = (function () { * obb-plane intersect detect. * @zh * 方向包围盒和平面的相交性检测。 - * @param {OBB} obb 方向包围盒 - * @param {Plane} plane 平面 - * @return {number} inside(back) = -1, outside(front) = 0, intersect = 1 + * @param obb @zh 方向包围盒 @en The obb to test + * @param plane @zh 平面 @en The plane to test + * @return @zh 检测结果, 包含为 -1, 不包含为 0, 相交为 1 @en Test result, inside(back) = -1, outside(front) = 0, intersect = 1 */ const obbPlane = (function () { const absDot = function (n: Vec3, x: number, y: number, z: number) { @@ -963,9 +977,9 @@ const obbPlane = (function () { * obb-frustum intersect, faster but has false positive corner cases. * @zh * 方向包围盒和锥台相交性检测,速度快,但有错误情况。 - * @param {OBB} obb 方向包围盒 - * @param {Frustum} frustum 锥台 - * @return {number} 0 或 非0 + * @param obb @zh 方向包围盒 @en The obb to test + * @param frustum @zh 锥台 @en The frustum to test + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ const obbFrustum = function (obb: OBB, frustum: Frustum): number { for (let i = 0; i < frustum.planes.length; i++) { @@ -983,9 +997,9 @@ const obbFrustum = function (obb: OBB, frustum: Frustum): number { * obb-frustum intersect, handles most of the false positives correctly. * @zh * 方向包围盒和锥台相交性检测,正确处理大多数错误情况。 - * @param {OBB} obb 方向包围盒 - * @param {Frustum} frustum 锥台 - * @return {number} 0 或 非0 + * @param obb @zh 方向包围盒 @en The obb to test + * @param frustum @zh 锥台 @en The frustum to test + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ const obbFrustumAccurate = (function () { const tmp = new Array(8); @@ -1038,9 +1052,9 @@ const obbFrustumAccurate = (function () { * obb-obb intersect detect. * @zh * 方向包围盒和方向包围盒的相交性检测。 - * @param {OBB} obb1 方向包围盒1 - * @param {OBB} obb2 方向包围盒2 - * @return {number} 0 或 非0 + * @param obb1 @zh 方向包围盒1 @en Obb 1 to test + * @param obb2 @zh 方向包围盒2 @en Obb 2 to test + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ const obbWithOBB = (function () { const test = new Array(15); @@ -1090,8 +1104,9 @@ const obbWithOBB = (function () { * obb-capsule intersect detect. * @zh * 方向包围盒和胶囊体的相交性检测。 - * @param obb 方向包围盒 - * @param capsule 胶囊体 + * @param obb @zh 方向包围盒 @en The obb to test + * @param capsule @zh 胶囊体 @en The capsule to test + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ const obbCapsule = (function () { const sphere_0 = new Sphere(); @@ -1155,9 +1170,9 @@ const obbCapsule = (function () { * plane normal to factor out the unnomalized plane distance. * @zh * 球与平面的相交性检测。 - * @param {Sphere} sphere 球 - * @param {Plane} plane 平面 - * @return {number} inside(back) = -1, outside(front) = 0, intersect = 1 + * @param sphere @zh 球 @en The sphere to test + * @param plane @zh 平面 @en The plane to test + * @return @zh 检测结果, 包含为 -1, 不包含为 0, 相交为 1 @en Test result, inside(back) = -1, outside(front) = 0, intersect = 1 */ const spherePlane = function (sphere: Sphere, plane: Plane): number { const dot = Vec3.dot(plane.n, sphere.center); @@ -1171,9 +1186,9 @@ const spherePlane = function (sphere: Sphere, plane: Plane): number { * sphere-frustum intersect, faster but has false positive corner cases. * @zh * 球和锥台的相交性检测,速度快,但有错误情况。 - * @param {Sphere} sphere 球 - * @param {Frustum} frustum 锥台 - * @return {number} 0 或 非0 + * @param sphere @zh 球 @en The sphere to test + * @param frustum @zh 锥台 @en The frustum to test + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ const sphereFrustum = function (sphere: Sphere, frustum: Frustum): number { for (let i = 0; i < frustum.planes.length; i++) { @@ -1191,9 +1206,9 @@ const sphereFrustum = function (sphere: Sphere, frustum: Frustum): number { * sphere-frustum intersect, handles the false positives correctly. * @zh * 球和锥台的相交性检测,正确处理大多数错误情况。 - * @param {Sphere} sphere 球 - * @param {Frustum} frustum 锥台 - * @return {number} 0 或 非0 + * @param sphere @zh 球 @en The sphere to test + * @param frustum @zh 锥台 @en The frustum to test + * @return @zh 0 或非 0 @en 0 or not 0, 0 indicates there is no intersection */ const sphereFrustumAccurate = (function () { const pt = new Vec3(0, 0, 0); const map = [1, -1, 1, -1, 1, -1]; @@ -1224,9 +1239,9 @@ const sphereFrustumAccurate = (function () { * sphere-sphere intersect detect. * @zh * 球和球的相交性检测。 - * @param {Sphere} sphere0 球0 - * @param {Sphere} sphere1 球1 - * @return {boolean} true or false + * @param sphere0 @zh 球 0 @en The sphere A to test + * @param sphere1 @zh 球 1 @en The sphere B to test + * @return @zh 是否发生碰撞 @en true or false which indicates if there is a intersection */ const sphereWithSphere = function (sphere0: Sphere, sphere1: Sphere): boolean { const r = sphere0.radius + sphere1.radius; @@ -1238,9 +1253,9 @@ const sphereWithSphere = function (sphere0: Sphere, sphere1: Sphere): boolean { * sphere-aabb intersect detect. * @zh * 球和轴对齐包围盒的相交性检测。 - * @param {Sphere} sphere 球 - * @param {AABB} aabb 轴对齐包围盒 - * @return {boolean} true or false + * @param sphere @zh 球 @en The sphere to test + * @param aabb @zh 轴对齐包围盒 @en The aabb to test + * @return @zh 是否发生碰撞 @en true or false which indicates if there is a intersection */ const sphereAABB = (function () { const pt = new Vec3(); @@ -1255,9 +1270,9 @@ const sphereAABB = (function () { * sphere-obb intersect detect. * @zh * 球和方向包围盒的相交性检测。 - * @param {Sphere} sphere 球 - * @param {OBB} obb 方向包围盒 - * @return {boolean} true or false + * @param sphere @zh 球 @en The sphere to test + * @param obb @zh 方向包围盒 @en The obb to test + * @return @zh 是否发生碰撞 @en true or false which indicates if there is a intersection */ const sphereOBB = (function () { const pt = new Vec3(); @@ -1272,6 +1287,9 @@ const sphereOBB = (function () { * sphere-capsule intersect detect. * @zh * 球和胶囊体的相交性检测。 + * @param sphere @zh 球 @en The sphere to test + * @param capsule @zh 胶囊体 @en The capsule to test + * @return @zh 是否发生碰撞 @en true or false which indicates if there is a intersection */ const sphereCapsule = (function () { const v3_0 = new Vec3(); @@ -1304,6 +1322,9 @@ const sphereCapsule = (function () { * capsule-capsule intersect detect. * @zh * 胶囊体和胶囊体的相交性检测。 + * @param capsuleA @zh 胶囊体 A @en The capsule A to test + * @param capsuleB @zh 胶囊体 B @en The capsule B to test + * @return @zh 是否发生碰撞 @en true or false which indicates if there is a intersection */ const capsuleWithCapsule = (function () { const v3_0 = new Vec3(); @@ -1428,15 +1449,17 @@ const intersect = { obbFrustumAccurate, obbPoint, obbCapsule, + aabbFrustumCompletelyInside, capsuleWithCapsule, /** - * @zh - * g1 和 g2 的相交性检测,可填入基础几何中的形状。 - * @param g1 几何1 - * @param g2 几何2 - * @param outPt 可选,相交点。(注:仅部分形状的检测带有这个返回值) + * @en Check intersection between two geometries, it accept all basic geometry types in [[geometry]] module. + * @zh 两个几何体的相交性检测,可填入 [[geometry]] 模块中的基础几何形状。 + * @param g1 @en The first geometry. @zh 第一个几何体。 + * @param g2 @en The second geometry. @zh 第二个几何体。 + * @param outPt @en A 3d point to store the intersection point result, only part of the geometries support this. + * @zh 可选,用于保存相交点的输出对象。(注:仅部分形状的检测带有这个返回值) */ resolve (g1: any, g2: any, outPt = null) { const type1 = g1._type; const type2 = g2._type; diff --git a/cocos/core/geometry/line.ts b/cocos/core/geometry/line.ts index b1c4518d28..c7ae915578 100644 --- a/cocos/core/geometry/line.ts +++ b/cocos/core/geometry/line.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module geometry - */ - import { Vec3 } from '../math'; import enums from './enums'; @@ -37,19 +32,18 @@ import enums from './enums'; * @zh * 基础几何 line。 */ - export class Line { /** * @en * create a new line * @zh * 创建一个新的 line。 - * @param sx 起点的 x 部分。 - * @param sy 起点的 y 部分。 - * @param sz 起点的 z 部分。 - * @param ex 终点的 x 部分。 - * @param ey 终点的 y 部分。 - * @param ez 终点的 z 部分。 + * @param sx @en Start position x @zh 起点的 x 坐标。 + * @param sy @en Start position y @zh 起点的 y 坐标。 + * @param sz @en Start position z @zh 起点的 z 坐标。 + * @param ex @en End position x @zh 终点的 x 坐标。 + * @param ey @en End position y @zh 终点的 y 坐标。 + * @param ez @en End position z @zh 终点的 z 坐标。 * @return */ public static create (sx: number, sy: number, sz: number, ex: number, ey: number, ez: number) { @@ -61,8 +55,8 @@ export class Line { * Creates a new Line initialized with values from an existing Line * @zh * 克隆一个新的 line。 - * @param a 克隆的来源。 - * @return 克隆出的对象。 + * @param a @en The line to clone from @zh 克隆的来源 Line 对象。 + * @return @en The new line cloned @zh 克隆出的新 Line 对象 */ public static clone (a: Line) { return new Line( @@ -76,9 +70,9 @@ export class Line { * Copy the values from one Line to another * @zh * 复制一个线的值到另一个。 - * @param out 接受操作的对象。 - * @param a 复制的来源。 - * @return 接受操作的对象。 + * @param out @en The output line to store the copied data @zh 用来存储拷贝数据的 Line 对象 + * @param a @en The line to copy from @zh 从这个 Line 对象拷贝信息。 + * @return @en The out object @zh 会直接返回传入的 out 对象 */ public static copy (out: Line, a: Line) { Vec3.copy(out.s, a.s); @@ -92,10 +86,10 @@ export class Line { * create a line from two points * @zh * 用两个点创建一个线。 - * @param out 接受操作的对象。 - * @param start 起点。 - * @param end 终点。 - * @return out 接受操作的对象。 + * @param out @en The output line @zh 接受新数据的 Line 对象 + * @param start @en The start point @zh 起点 + * @param end @en The end point @zh 终点 + * @return @en The out object @zh 会直接返回传入的 out 对象 */ public static fromPoints (out: Line, start: Vec3, end: Vec3) { Vec3.copy(out.s, start); @@ -108,14 +102,14 @@ export class Line { * Set the components of a Vec3 to the given values * @zh * 将给定线的属性设置为给定值。 - * @param out 接受操作的对象。 - * @param sx 起点的 x 部分。 - * @param sy 起点的 y 部分。 - * @param sz 起点的 z 部分。 - * @param ex 终点的 x 部分。 - * @param ey 终点的 y 部分。 - * @param ez 终点的 z 部分。 - * @return out 接受操作的对象。 + * @param out @en The output line to set properties to @zh 接受新数据的 Line 对象 + * @param sx @en Start position x @zh 起点到 x 坐标 + * @param sy @en Start position y @zh 起点到 y 坐标 + * @param sz @en Start position z @zh 起点到 z 坐标 + * @param ex @en End position x @zh 终点到 x 坐标 + * @param ey @en End position y @zh 终点到 y 坐标 + * @param ez @en End position z @zh 终点到 z 坐标 + * @return @en The out object @zh 会直接返回传入的 out 对象 */ public static set (out: Line, sx: number, sy: number, sz: number, ex: number, ey: number, ez: number) { out.s.x = sx; @@ -129,32 +123,30 @@ export class Line { } /** - * @zh - * 计算线的长度。 - * @param a 要计算的线。 - * @return 长度。 + * @en Calculate the length of the given line + * @zh 计算线的长度。 + * @param a @en The line @zh 用于计算长度的线段 + * @return @en The length of the given line @zh 线段的长度 */ public static len (a: Line) { return Vec3.distance(a.s, a.e); } /** - * @zh - * 起点。 + * @en Start point + * @zh 起点。 */ public s: Vec3; /** - * @zh - * 终点。 + * @en End point + * @zh 终点。 */ public e: Vec3; /** - * @en - * Gets the type of the shape. - * @zh - * 获取形状的类型。 + * @en Gets the type of the shape. + * @zh 获取形状的类型。 */ get type () { return this._type; @@ -163,13 +155,14 @@ export class Line { private readonly _type: number; /** - * 构造一条线。 - * @param sx 起点的 x 部分。 - * @param sy 起点的 y 部分。 - * @param sz 起点的 z 部分。 - * @param ex 终点的 x 部分。 - * @param ey 终点的 y 部分。 - * @param ez 终点的 z 部分。 + * @en Constructor of the line + * @zh 构造一条线。 + * @param sx @en Start position x @zh 起点的 x 坐标 + * @param sy @en Start position y @zh 起点的 y 坐标 + * @param sz @en Start position z @zh 起点的 z 坐标 + * @param ex @en End position x @zh 终点的 x 坐标 + * @param ey @en End position y @zh 终点的 y 坐标 + * @param ez @en End position z @zh 终点的 z 坐标 */ constructor (sx = 0, sy = 0, sz = 0, ex = 0, ey = 0, ez = -1) { this._type = enums.SHAPE_LINE; @@ -178,10 +171,9 @@ export class Line { } /** - * @zh - * 计算线的长度。 - * @param a 要计算的线。 - * @return 长度。 + * @en Calculate the length of the line + * @zh 计算线的长度。 + * @return @en The length @zh 线段的长度 */ public length () { return Vec3.distance(this.s, this.e); diff --git a/cocos/core/geometry/obb.ts b/cocos/core/geometry/obb.ts index 8554726d1c..433ac6de44 100644 --- a/cocos/core/geometry/obb.ts +++ b/cocos/core/geometry/obb.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module geometry - */ - import { Mat3, Mat4, Quat, Vec3 } from '../math'; import enums from './enums'; @@ -56,22 +51,22 @@ export class OBB { * create a new obb * @zh * 创建一个新的 obb 实例。 - * @param cx 形状的相对于原点的 X 坐标。 - * @param cy 形状的相对于原点的 Y 坐标。 - * @param cz 形状的相对于原点的 Z 坐标。 - * @param hw - obb 宽度的一半。 - * @param hh - obb 高度的一半。 - * @param hl - obb 长度的一半。 - * @param ox_1 方向矩阵参数。 - * @param ox_2 方向矩阵参数。 - * @param ox_3 方向矩阵参数。 - * @param oy_1 方向矩阵参数。 - * @param oy_2 方向矩阵参数。 - * @param oy_3 方向矩阵参数。 - * @param oz_1 方向矩阵参数。 - * @param oz_2 方向矩阵参数。 - * @param oz_3 方向矩阵参数。 - * @return 返回一个 obb。 + * @param cx @zh 形状的相对于原点的 X 坐标。 @en The x coordinate of origin. + * @param cy @zh 形状的相对于原点的 Y 坐标。 @en The y coordinate of origin. + * @param cz @zh 形状的相对于原点的 Z 坐标。 @en The z coordinate of origin. + * @param hw @zh - obb 宽度的一半。 @en Half the width of the OBB. + * @param hh @zh - obb 高度的一半。 @en Half the height of the OBB. + * @param hl @zh - obb 长度的一半。 @en Half the length of the OBB. + * @param ox_1 @zh 方向矩阵参数。 @en The x component of the one axis of the OBB. + * @param ox_2 @zh 方向矩阵参数。 @en The x component of the second axis of the OBB. + * @param ox_3 @zh 方向矩阵参数。 @en The x component of the third axis of the OBB. + * @param oy_1 @zh 方向矩阵参数。 @en The y component of the one axis of the OBB. + * @param oy_2 @zh 方向矩阵参数。 @en The y component of the second axis of the OBB. + * @param oy_3 @zh 方向矩阵参数。 @en The y component of the third axis of the OBB. + * @param oz_1 @zh 方向矩阵参数。 @en The z component of the one axis of the OBB. + * @param oz_2 @zh 方向矩阵参数。 @en The z component of the second axis of the OBB. + * @param oz_3 @zh 方向矩阵参数。 @en The z component of the third axis of the OBB. + * @return @zh 返回一个 obb。 @en A new OBB. */ public static create ( cx: number, cy: number, cz: number, @@ -88,8 +83,8 @@ export class OBB { * clone a new obb * @zh * 克隆一个 obb。 - * @param a 克隆的目标。 - * @returns 克隆出的新对象。 + * @param a @zh 克隆的目标。 @en The input OBB. + * @returns @zh The new OBB. @en 克隆出的新对象。 */ public static clone (a: OBB) { return new OBB(a.center.x, a.center.y, a.center.z, @@ -104,9 +99,9 @@ export class OBB { * copy the values from one obb to another * @zh * 将从一个 obb 的值复制到另一个 obb。 - * @param {OBB} out 接受操作的 obb。 - * @param {OBB} a 被复制的 obb。 - * @return {OBB} out 接受操作的 obb。 + * @param out @zh 接受操作的 obb。 @en The output OBB. + * @param a @zh 被复制的 obb。 @en The input OBB. + * @returns @zh out 接受操作的 obb。 @en The reference of the first parameter `out`. */ public static copy (out: OBB, a: OBB): OBB { Vec3.copy(out.center, a.center); @@ -121,10 +116,10 @@ export class OBB { * create a new obb from two corner points * @zh * 用两个点创建一个新的 obb。 - * @param out - 接受操作的 obb。 - * @param minPos - obb 的最小点。 - * @param maxPos - obb 的最大点。 - * @returns {OBB} out 接受操作的 obb。 + * @param out @zh - 接受操作的 obb。 @en The output OBB. + * @param minPos @zh - obb 的最小点。 @en The minimum position of the AABB. + * @param maxPos @zh - obb 的最大点。 @en The maximum position of the AABB. + * @returns @zh {OBB} out 接受操作的 obb。 @en The reference of the first parameter `out`. */ public static fromPoints (out: OBB, minPos: Vec3, maxPos: Vec3): OBB { Vec3.multiplyScalar(out.center, Vec3.add(_v3_tmp, minPos, maxPos), 0.5); @@ -138,22 +133,23 @@ export class OBB { * Set the components of a obb to the given values * @zh * 将给定 obb 的属性设置为给定的值。 - * @param cx - obb 的原点的 X 坐标。 - * @param cy - obb 的原点的 Y 坐标。 - * @param cz - obb 的原点的 Z 坐标。 - * @param hw - obb 宽度的一半。 - * @param hh - obb 高度的一半。 - * @param hl - obb 长度的一半。 - * @param ox_1 方向矩阵参数。 - * @param ox_2 方向矩阵参数。 - * @param ox_3 方向矩阵参数。 - * @param oy_1 方向矩阵参数。 - * @param oy_2 方向矩阵参数。 - * @param oy_3 方向矩阵参数。 - * @param oz_1 方向矩阵参数。 - * @param oz_2 方向矩阵参数。 - * @param oz_3 方向矩阵参数。 - * @return {OBB} out + * @param out @zh 目标 OBB @en The output OBB. + * @param cx @zh 形状的相对于原点的 X 坐标。 @en The x coordinate of origin. + * @param cy @zh 形状的相对于原点的 Y 坐标。 @en The y coordinate of origin. + * @param cz @zh 形状的相对于原点的 Z 坐标。 @en The z coordinate of origin. + * @param hw @zh - obb 宽度的一半。 @en Half the width of the OBB. + * @param hh @zh - obb 高度的一半。 @en Half the height of the OBB. + * @param hl @zh - obb 长度的一半。 @en Half the length of the OBB. + * @param ox_1 @zh 方向矩阵参数。 @en The x component of the one axis of the OBB. + * @param ox_2 @zh 方向矩阵参数。 @en The x component of the second axis of the OBB. + * @param ox_3 @zh 方向矩阵参数。 @en The x component of the third axis of the OBB. + * @param oy_1 @zh 方向矩阵参数。 @en The y component of the one axis of the OBB. + * @param oy_2 @zh 方向矩阵参数。 @en The y component of the second axis of the OBB. + * @param oy_3 @zh 方向矩阵参数。 @en The y component of the third axis of the OBB. + * @param oz_1 @zh 方向矩阵参数。 @en The z component of the one axis of the OBB. + * @param oz_2 @zh 方向矩阵参数。 @en The z component of the second axis of the OBB. + * @param oz_3 @zh 方向矩阵参数。 @en The z component of the third axis of the OBB. + * @returns @zh out 接受操作的 OBB @en The reference of the first parameter `out`. */ public static set ( out: OBB, @@ -170,18 +166,24 @@ export class OBB { } /** + * @en + * Center point of the OBB. * @zh * 本地坐标的中心点。 */ public center: Vec3; /** + * @en + * Half the distance across the OBB in each local axis. * @zh * 长宽高的一半。 */ public halfExtents: Vec3; /** + * @en + * Orientation matrix. * @zh * 方向矩阵。 */ @@ -215,8 +217,8 @@ export class OBB { * Get the bounding points of this shape * @zh * 获取 obb 的最小点和最大点。 - * @param {Vec3} minPos 最小点。 - * @param {Vec3} maxPos 最大点。 + * @param minPos @zh 最小点。 @en The out minimum position of the OBB. + * @param maxPos @zh 最大点。 @en The out maximum position of the OBB. */ public getBoundary (minPos: Vec3, maxPos: Vec3) { transform_extent_m3(_v3_tmp, this.halfExtents, this.orientation); @@ -225,14 +227,15 @@ export class OBB { } /** + * @en * Transform this shape * @zh * 将 out 根据这个 obb 的数据进行变换。 - * @param m 变换的矩阵。 - * @param pos 变换的位置部分。 - * @param rot 变换的旋转部分。 - * @param scale 变换的缩放部分。 - * @param out 变换的目标。 + * @param m @zh 变换的矩阵。 @en The transform matrix + * @param pos @zh 变换的位置部分。 @en 3d-vector translation. + * @param rot @zh 变换的旋转部分。 @en Quaternion rotation. + * @param scale @zh 变换的缩放部分。 @en 3d-vector scale. + * @param out @zh 变换的目标。 @en The output OBB. */ public transform (m: Mat4, pos: Vec3, rot: Quat, scale: Vec3, out: OBB) { Vec3.transformMat4(out.center, this.center, m); @@ -242,11 +245,13 @@ export class OBB { } /** + * @en + * Transform by matrix and rotation. * @zh * 将 out 根据这个 obb 的数据进行变换。 - * @param m 变换的矩阵。 - * @param rot 变换的旋转部分。 - * @param out 变换的目标。 + * @param m @zh 变换的矩阵。 @en The transform matrix. + * @param rot @zh 变换的旋转部分。 @en Quaternion rotation. + * @param out @zh 变换的目标。 @en The output OBB. */ public translateAndRotate (m: Mat4, rot: Quat, out: OBB) { Vec3.transformMat4(out.center, this.center, m); @@ -255,10 +260,12 @@ export class OBB { } /** + * @en + * Scale OBB by a 3d-vector. * @zh * 将 out 根据这个 obb 的数据进行缩放。 - * @param scale 缩放值。 - * @param out 缩放的目标。 + * @param scale @zh 缩放值。 @en 3d-vector scale. + * @param out @zh 缩放的目标。 @en The output OBB. */ public setScale (scale: Vec3, out: OBB) { Vec3.multiply(out.halfExtents, this.halfExtents, scale); diff --git a/cocos/core/geometry/plane.ts b/cocos/core/geometry/plane.ts index c506dad59d..31ed2299a4 100644 --- a/cocos/core/geometry/plane.ts +++ b/cocos/core/geometry/plane.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module geometry - */ - import { Mat4, Vec3, Vec4 } from '../math'; import enums from './enums'; import { legacyCC } from '../global-exports'; @@ -50,10 +45,10 @@ export class Plane { * create a new plane * @zh * 创建一个新的 plane。 - * @param nx 法向分量的 x 部分。 - * @param ny 法向分量的 y 部分。 - * @param nz 法向分量的 z 部分。 - * @param d 与原点的距离。 + * @param nx @en The x component of normal vector. @zh 法向分量的 x 部分。 + * @param ny @en The y component of normal vector. @zh 法向分量的 y 部分。 + * @param nz @en The z component of normal vector. @zh 法向分量的 z 部分。 + * @param d @en The distance between normal vector and the origin. @zh 与原点的距离。 * @return */ public static create (nx: number, ny: number, nz: number, d: number) { @@ -65,8 +60,8 @@ export class Plane { * clone a new plane * @zh * 克隆一个新的 plane。 - * @param p 克隆的来源。 - * @return 克隆出的对象。 + * @param p @en The Plane object to be cloned from. @zh 克隆的来源。 + * @return @en Cloned objects @zh 克隆出的对象。 */ public static clone (p: Plane) { return new Plane(p.n.x, p.n.y, p.n.z, p.d); @@ -77,9 +72,9 @@ export class Plane { * copy the values from one plane to another * @zh * 复制一个平面的值到另一个。 - * @param out 接受操作的对象。 - * @param p 复制的来源。 - * @return 接受操作的对象。 + * @param out @en The object to be operated on. @zh 接受操作的对象。 + * @param p @en The source of replication. @zh 复制的来源。 + * @return @en The object to be operated on. @zh 接受操作的对象。 */ public static copy (out: Plane, p: Plane) { Vec3.copy(out.n, p.n); @@ -93,11 +88,11 @@ export class Plane { * create a plane from three points * @zh * 用三个点创建一个平面。 - * @param out 接受操作的对象。 - * @param a 点 a。 - * @param b 点 b。 - * @param c 点 c。 - * @return out 接受操作的对象。 + * @param out @en The object to be operated on. @zh 接受操作的对象。 + * @param a @en Point a. @zh 点 a。 + * @param b @en Point b. @zh 点 b。 + * @param c @en Point c. @zh 点 c。 + * @return out @en The object to be operated on. @zh 接受操作的对象。 */ public static fromPoints (out: Plane, a: Vec3, b: Vec3, c: Vec3) { Vec3.subtract(v1, b, a); @@ -114,12 +109,12 @@ export class Plane { * Set the components of a plane to the given values * @zh * 将给定平面的属性设置为给定值。 - * @param out 接受操作的对象。 - * @param nx 法向分量的 x 部分。 - * @param ny 法向分量的 y 部分。 - * @param nz 法向分量的 z 部分。 - * @param d 与原点的距离。 - * @return out 接受操作的对象。 + * @param out @en The object to be operated on. @zh 接受操作的对象。 + * @param nx @en The x component of normal vector. @zh 法向分量的 x 部分。 + * @param ny @en The y component of normal vector. @zh 法向分量的 y 部分。 + * @param nz @en The z component of normal vector. @zh 法向分量的 z 部分。 + * @param d @en The distance between normal vector and the origin. @zh 与原点的距离。 + * @return out @en The object to be operated on. @zh 接受操作的对象。 */ public static set (out: Plane, nx: number, ny: number, nz: number, d: number) { out.n.x = nx; @@ -135,10 +130,10 @@ export class Plane { * create plane from normal and point * @zh * 用一条法线和一个点创建平面。 - * @param out 接受操作的对象。 - * @param normal 平面的法线。 - * @param point 平面上的一点。 - * @return out 接受操作的对象。 + * @param out @en The object to be operated on. @zh 接受操作的对象。 + * @param normal @en Normal of the plane. @zh 平面的法线。 + * @param point @en A point in the plane. @zh 平面上的一点。 + * @return out @en The object to be operated on. @zh 接受操作的对象。 */ public static fromNormalAndPoint (out: Plane, normal: Vec3, point: Vec3) { Vec3.copy(out.n, normal); @@ -152,9 +147,9 @@ export class Plane { * normalize a plane * @zh * 归一化一个平面。 - * @param out 接受操作的对象。 - * @param a 操作的源数据。 - * @return out 接受操作的对象。 + * @param out @en The object to be operated on. @zh 接受操作的对象。 + * @param a @en Source data for the operation. @zh 操作的源数据。 + * @return out @en The object to be operated on. @zh 接受操作的对象。 */ public static normalize (out: Plane, a: Plane) { const len = a.n.length(); @@ -208,10 +203,10 @@ export class Plane { * Construct a plane. * @zh * 构造一个平面。 - * @param nx 法向分量的 x 部分。 - * @param ny 法向分量的 y 部分。 - * @param nz 法向分量的 z 部分。 - * @param d 与原点的距离。 + * @param nx @en The x component of normal vector. @zh 法向分量的 x 部分。 + * @param ny @en The y component of normal vector. @zh 法向分量的 y 部分。 + * @param nz @en The z component of normal vector. @zh 法向分量的 z 部分。 + * @param d @en The distance between normal vector and the origin. @zh 与原点的距离。 */ constructor (nx = 0, ny = 1, nz = 0, d = 0) { this._type = enums.SHAPE_PLANE; diff --git a/cocos/core/geometry/ray.ts b/cocos/core/geometry/ray.ts index 7c5c3fac39..65de5c49be 100644 --- a/cocos/core/geometry/ray.ts +++ b/cocos/core/geometry/ray.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module geometry - */ - import { Vec3 } from '../math'; import enums from './enums'; import { IVec3Like } from '../math/type-define'; @@ -45,13 +40,13 @@ export class Ray { * create a new ray * @zh * 创建一条射线。 - * @param {number} ox 起点的 x 部分。 - * @param {number} oy 起点的 y 部分。 - * @param {number} oz 起点的 z 部分。 - * @param {number} dx 方向的 x 部分。 - * @param {number} dy 方向的 y 部分。 - * @param {number} dz 方向的 z 部分。 - * @return {Ray} 射线。 + * @param {number} ox @en x component of start point @zh 起点的 x 部分。 + * @param {number} oy @en y component of start point @zh 起点的 y 部分。 + * @param {number} oz @en z component of start point @zh 起点的 z 部分。 + * @param {number} dx @en Point in the x direction @zh 方向的 x 部分。 + * @param {number} dy @en Point in the y direction @zh 方向的 y 部分。 + * @param {number} dz @en Point in the z direction @zh 方向的 z 部分。 + * @return {Ray} @en Ray object @zh 射线。 */ public static create (ox = 0, oy = 0, oz = 0, dx = 0, dy = 0, dz = 1): Ray { return new Ray(ox, oy, oz, dx, dy, dz); @@ -62,8 +57,8 @@ export class Ray { * Creates a new ray initialized with values from an existing ray * @zh * 从一条射线克隆出一条新的射线。 - * @param {Ray} a 克隆的目标。 - * @return {Ray} 克隆出的新对象。 + * @param {Ray} a @en The Ray object to be cloned from @zh 克隆的目标。 + * @return {Ray} @en Clone new ray object @zh 克隆出的新对象。 */ public static clone (a: Ray): Ray { return new Ray( @@ -77,9 +72,9 @@ export class Ray { * Copy the values from one ray to another * @zh * 将从一个 ray 的值复制到另一个 ray。 - * @param {Ray} out 接受操作的 ray。 - * @param {Ray} a 被复制的 ray。 - * @return {Ray} out 接受操作的 ray。 + * @param {Ray} out @en The ray object to be modified @zh 接受操作的 ray。 + * @param {Ray} a @en The copied ray object @zh 被复制的 ray。 + * @return {Ray} @en Ray object @zh out 接受操作的 ray。 */ public static copy (out: Ray, a: Ray): Ray { Vec3.copy(out.o, a.o); @@ -93,10 +88,10 @@ export class Ray { * create a ray from two points * @zh * 用两个点创建一条射线。 - * @param {Ray} out 接受操作的射线。 - * @param {Vec3} origin 射线的起点。 - * @param {Vec3} target 射线上的一点。 - * @return {Ray} out 接受操作的射线。 + * @param {Ray} out @en The ray object to be modified @zh 接受操作的射线。 + * @param {Vec3} origin @en Starting point of the ray @zh 射线的起点。 + * @param {Vec3} target @en point on the ray @zh 射线上的一点。 + * @return {Ray} @en Ray object @zh out 接受操作的射线。 */ public static fromPoints (out: Ray, origin: Vec3, target: Vec3): Ray { Vec3.copy(out.o, origin); @@ -109,14 +104,14 @@ export class Ray { * Set the components of a ray to the given values * @zh * 将给定射线的属性设置为给定的值。 - * @param {Ray} out 接受操作的射线。 - * @param {number} ox 起点的 x 部分。 - * @param {number} oy 起点的 y 部分。 - * @param {number} oz 起点的 z 部分。 - * @param {number} dx 方向的 x 部分。 - * @param {number} dy 方向的 y 部分。 - * @param {number} dz 方向的 z 部分。 - * @return {Ray} out 接受操作的射线。 + * @param {Ray} out @en The ray object to be modified @zh 接受操作的射线。 + * @param {number} ox @en x component of start point @zh 起点的 x 部分。 + * @param {number} oy @en y component of start point @zh 起点的 y 部分。 + * @param {number} oz @en z component of start point @zh 起点的 z 部分。 + * @param {number} dx @en Point in the x direction @zh 方向的 x 部分。 + * @param {number} dy @en Point in the y direction @zh 方向的 y 部分。 + * @param {number} dz @en Point in the z direction @zh 方向的 z 部分。 + * @return {Ray} @en Ray object @zh out 接受操作的射线。 */ public static set (out: Ray, ox: number, oy: number, oz: number, dx: number, dy: number, dz: number): Ray { out.o.x = ox; @@ -162,12 +157,12 @@ export class Ray { * Construct a ray; * @zh * 构造一条射线。 - * @param {number} ox 起点的 x 部分。 - * @param {number} oy 起点的 y 部分。 - * @param {number} oz 起点的 z 部分。 - * @param {number} dx 方向的 x 部分。 - * @param {number} dy 方向的 y 部分。 - * @param {number} dz 方向的 z 部分。 + * @param {number} ox @en x component of start point @zh 起点的 x 部分。 + * @param {number} oy @en y component of start point @zh 起点的 y 部分。 + * @param {number} oz @en z component of start point @zh 起点的 z 部分。 + * @param {number} dx @en Point in the x direction @zh 方向的 x 部分。 + * @param {number} dy @en Point in the y direction @zh 方向的 y 部分。 + * @param {number} dz @en Point in the z direction @zh 方向的 z 部分。 */ constructor (ox = 0, oy = 0, oz = 0, dx = 0, dy = 0, dz = -1) { @@ -181,8 +176,8 @@ export class Ray { * Compute a point with the distance between the origin. * @zh * 根据给定距离计算出射线上的一点。 - * @param out 射线上的另一点。 - * @param distance 给定距离。 + * @param out @en Another point on the ray @zh 射线上的另一点。 + * @param distance @en Given distance @zh 给定距离。 */ public computeHit (out: IVec3Like, distance: number) { Vec3.normalize(out, this.d); diff --git a/cocos/core/geometry/spec.ts b/cocos/core/geometry/spec.ts index df68bcdb66..4d8e526d3c 100644 --- a/cocos/core/geometry/spec.ts +++ b/cocos/core/geometry/spec.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module geometry - */ - /** * @en * The raycast mode. diff --git a/cocos/core/geometry/sphere.ts b/cocos/core/geometry/sphere.ts index f056d2baa8..923ef493a4 100644 --- a/cocos/core/geometry/sphere.ts +++ b/cocos/core/geometry/sphere.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module geometry - */ - import { Mat4, Quat, Vec3 } from '../math'; import enums from './enums'; import { AABB } from './aabb'; @@ -51,11 +46,11 @@ export class Sphere { * create a new sphere * @zh * 创建一个新的 sphere 实例。 - * @param cx 形状的相对于原点的 X 坐标。 - * @param cy 形状的相对于原点的 Y 坐标。 - * @param cz 形状的相对于原点的 Z 坐标。 - * @param r 球体的半径 - * @return {Sphere} 返回一个 sphere。 + * @param cx @en X-Coordinate of center point relative to the origin. @zh 中心点的相对于原点的 X 坐标。 + * @param cy @en Y-Coordinate of center point relative to the origin. @zh 中心点的相对于原点的 Y 坐标。 + * @param cz @en Z-Coordinate of center point relative to the origin. @zh 中心点的相对于原点的 Z 坐标。 + * @param r @en Radius of the sphere. @zh 球体的半径 + * @return @en return a new sphere. @zh 返回一个 sphere。 */ public static create (cx: number, cy: number, cz: number, r: number): Sphere { return new Sphere(cx, cy, cz, r); @@ -66,8 +61,8 @@ export class Sphere { * clone a new sphere * @zh * 克隆一个新的 sphere 实例。 - * @param {Sphere} p 克隆的目标。 - * @return {Sphere} 克隆出的示例。 + * @param p @en The sphere object to clone from. @zh 克隆的目标。 + * @return @en The sphere object to clone to. @zh 克隆出的示例。 */ public static clone (p: Sphere): Sphere { return new Sphere(p.center.x, p.center.y, p.center.z, p.radius); @@ -78,9 +73,9 @@ export class Sphere { * copy the values from one sphere to another * @zh * 将从一个 sphere 的值复制到另一个 sphere。 - * @param {Sphere} out 接受操作的 sphere。 - * @param {Sphere} a 被复制的 sphere。 - * @return {Sphere} out 接受操作的 sphere。 + * @param out @en The sphere object to copy to. @zh 接受操作的 sphere。 + * @param a @en The sphere object to copy from. @zh 被复制的 sphere。 + * @return @en The sphere object to copy to. @zh 接受操作的 sphere。 */ public static copy (out: Sphere, p: Sphere): Sphere { Vec3.copy(out.center, p.center); @@ -94,10 +89,10 @@ export class Sphere { * create a new bounding sphere from two corner points * @zh * 从两个点创建一个新的 sphere。 - * @param out - 接受操作的 sphere。 - * @param minPos - sphere 的最小点。 - * @param maxPos - sphere 的最大点。 - * @returns {Sphere} out 接受操作的 sphere。 + * @param out - @en Sphere created from points. @zh 接受操作的 sphere。 + * @param minPos - @en Lower point of the sphere. @zh sphere 的较小点。 + * @param maxPos - @en Upper point of the sphere. @zh sphere 的较大点。 + * @returns @en The output sphere object to save the created sphere data. @zh 接受操作的 sphere。 */ public static fromPoints (out: Sphere, minPos: Vec3, maxPos: Vec3): Sphere { Vec3.multiplyScalar(out.center, Vec3.add(_v3_tmp, minPos, maxPos), 0.5); @@ -110,12 +105,12 @@ export class Sphere { * Set the components of a sphere to the given values * @zh * 将球体的属性设置为给定的值。 - * @param {Sphere} out 接受操作的 sphere。 - * @param cx 形状的相对于原点的 X 坐标。 - * @param cy 形状的相对于原点的 Y 坐标。 - * @param cz 形状的相对于原点的 Z 坐标。 - * @param {number} r 半径。 - * @return {Sphere} out 接受操作的 sphere。 + * @param out @en The sphere to set properties to. @zh 接受操作的 sphere。 + * @param cx @en X-Coordinate of center point relative to the origin. @zh 中心点的相对于原点的 X 坐标。 + * @param cy @en Y-Coordinate of center point relative to the origin. @zh 中心点的相对于原点的 Y 坐标。 + * @param cz @en Z-Coordinate of center point relative to the origin. @zh 中心点的相对于原点的 Z 坐标。 + * @param r @en Radius of the sphere. @zh 半径。 + * @return @en Sphere which the properties will be set to. @zh 接受操作的 sphere。 * @function */ public static set (out: Sphere, cx: number, cy: number, cz: number, r: number): Sphere { @@ -134,11 +129,11 @@ export class Sphere { * 本地坐标的中心点。 */ protected _center: Vec3 = new Vec3(0, 0, 0); - get center () : Vec3 { + get center (): Vec3 { return this._center; } - set center (val:Vec3) { + set center (val: Vec3) { this._center = val; } @@ -150,7 +145,7 @@ export class Sphere { * @zh * 半径。 */ - get radius () : number { + get radius (): number { return this._radius; } @@ -175,10 +170,10 @@ export class Sphere { * Construct a sphere. * @zh * 构造一个球。 - * @param cx 该球的世界坐标的 X 坐标。 - * @param cy 该球的世界坐标的 Y 坐标。 - * @param cz 该球的世界坐标的 Z 坐标。 - * @param {number} r 半径。 + * @param cx @en The X-Coordinate of the sphere. @zh 该球的世界坐标的 X 坐标。 + * @param cy @en The Y-Coordinate of the sphere. @zh 该球的世界坐标的 Y 坐标。 + * @param cz @en The Z-Coordinate of the sphere. @zh 该球的世界坐标的 Z 坐标。 + * @param r @en The radius. @zh 半径。 */ constructor (cx = 0, cy = 0, cz = 0, r = 1) { this._type = enums.SHAPE_SPHERE; @@ -204,7 +199,7 @@ export class Sphere { * Copy a sphere. * @zh * 拷贝对象。 - * @param a 拷贝的目标。 + * @param a @en The sphere to copy from. @zh 拷贝的目标。 */ public copy (a: Sphere) { return Sphere.copy(this, a); @@ -215,8 +210,8 @@ export class Sphere { * Get the bounding points of this shape * @zh * 获取此形状的边界点。 - * @param {Vec3} minPos 最小点。 - * @param {Vec3} maxPos 最大点。 + * @param minPos @en The point with maximum coordinates of the sphere. @zh 最小点。 + * @param maxPos @en The point with minimum coordinates of the sphere. @zh 最大点。 */ public getBoundary (minPos: Vec3, maxPos: Vec3) { Vec3.set(minPos, this.center.x - this.radius, this.center.y - this.radius, this.center.z - this.radius); @@ -228,11 +223,11 @@ export class Sphere { * Transform this shape * @zh * 将 out 根据这个 sphere 的数据进行变换。 - * @param m 变换的矩阵。 - * @param pos 变换的位置部分。 - * @param rot 变换的旋转部分。 - * @param scale 变换的缩放部分。 - * @param out 变换的目标。 + * @param m @en The transform matrix. @zh 变换的矩阵。 + * @param pos @en The position. @zh 变换的位置部分。 + * @param rot @en The rotation. @zh 变换的旋转部分。 + * @param scale @en The scale. @zh 变换的缩放部分。 + * @param out @en The sphere which the transform will be applied to. @zh 变换的目标。 */ public transform (m: Mat4, pos: Vec3, rot: Quat, scale: Vec3, out: Sphere) { Vec3.transformMat4(out.center, this.center, m); @@ -244,9 +239,9 @@ export class Sphere { * Translate and rotate this sphere. * @zh * 将 out 根据这个 sphere 的数据进行变换。 - * @param m 变换的矩阵。 - * @param rot 变换的旋转部分。 - * @param out 变换的目标。 + * @param m @en The transform matrix. @zh 变换的矩阵。 + * @param rot @en The rotation. @zh 变换的旋转部分。 + * @param out @en The sphere which the transform will be applied to. @zh 变换的目标。 */ public translateAndRotate (m: Mat4, rot: Quat, out: Sphere) { Vec3.transformMat4(out.center, this.center, m); @@ -257,17 +252,17 @@ export class Sphere { * Scaling this sphere. * @zh * 将 out 根据这个 sphere 的数据进行缩放。 - * @param scale 缩放值。 - * @param out 缩放的目标。 + * @param scale @en The scale. @zh 缩放值。 + * @param out @en The sphere which the scale will be applied to. @zh 缩放的目标。 */ public setScale (scale: Vec3, out: Sphere) { out.radius = this.radius * maxComponent(scale); } /** - * @en Sphere and point merge. + * @en The point to be merged. * @zh 球跟点合并 - * @param point 点 + * @param point @en The point to be merged. @zh 点 */ public mergePoint (point: Vec3) { // if sphere.radius Less than 0, @@ -290,9 +285,9 @@ export class Sphere { } /** - * @en Sphere and points merge. + * @en The sphere and points to be merged. * @zh 球跟一系列点合并 - * @param points 一系列点 + * @param points @en The point to be merged. @zh 一系列点 */ public mergePoints (points: Vec3[]) { const length = points.length; @@ -307,9 +302,9 @@ export class Sphere { } /** - * @en Sphere and AABB merge. + * @en The axis-aligned bounding box to be merged. * @zh 球跟立方体合并 - * @param a 立方体 + * @param a @en Cube. @zh 立方体 */ public mergeAABB (a: AABB) { a.getBoundary(_min, _max); diff --git a/cocos/core/geometry/spline.ts b/cocos/core/geometry/spline.ts new file mode 100644 index 0000000000..0802426541 --- /dev/null +++ b/cocos/core/geometry/spline.ts @@ -0,0 +1,286 @@ +/* + 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 { assertIsTrue } from '../data/utils/asserts'; +import { clamp, Vec3 } from '../math'; +import { warnID } from '../platform/debug'; +import enums from './enums'; + +export enum SplineMode { + /** + * Broken line: + * Each knot is connected with a straight line from the beginning to the end to form a curve. At least two knots. + */ + LINEAR = 0, + + /** + * Piecewise Bezier curve: + * Every four knots form a curve. Total knots number must be a multiple of 4. + * Each curve passes only the first and fourth knots, and does not pass through the middle two control knots. + * + * If you need a whole continuous curve: + * (1) Suppose the four knots of the previous curve are A, B, C, D + * (2) The four knots of the next curve must be D, E, F, G + * (3) C and E need to be symmetrical about D + */ + BEZIER = 1, + + /** + * Catmull Rom curve: + * All knots(including start & end knots) form a whole continuous curve. At least two knots. + * The whole curve passes through all knots. + */ + CATMULL_ROM = 2 +} + +const SPLINE_WHOLE_INDEX = 0xffffffff; + +const _v0 = new Vec3(); +const _v1 = new Vec3(); +const _v2 = new Vec3(); +const _v3 = new Vec3(); + +/** + * @en + * Basic Geometry: Spline. + * @zh + * 基础几何 Spline + */ + +export class Spline { + private readonly _type: number; + private _mode: SplineMode = SplineMode.CATMULL_ROM; + private _knots: Vec3[] = []; + + private constructor (mode: SplineMode = SplineMode.CATMULL_ROM, knots: Readonly = []) { + this._type = enums.SHAPE_SPLINE; + this._mode = mode; + + for (let i = 0; i < knots.length; i++) { + this._knots[i] = new Vec3(knots[i]); + } + } + + public static create (mode: SplineMode, knots: Vec3[] = []) { + return new Spline(mode, knots); + } + + public static clone (s: Spline) { + return new Spline(s.mode, s.knots); + } + + public static copy (out: Spline, s: Spline) { + out._mode = s.mode; + out._knots.length = 0; + + const knots = s.knots; + const length = knots.length; + for (let i = 0; i < length; i++) { + out._knots[i] = new Vec3(knots[i]); + } + + return out; + } + + get type () { + return this._type; + } + + get mode () { + return this._mode; + } + + get knots (): Readonly { + return this._knots; + } + + public setModeAndKnots (mode: SplineMode, knots: Vec3[]) { + this._mode = mode; + this._knots.length = 0; + + for (let i = 0; i < knots.length; i++) { + this._knots[i] = new Vec3(knots[i]); + } + } + + public clearKnots () { + this._knots.length = 0; + } + + public getKnotCount () { + return this._knots.length; + } + + public addKnot (knot: Vec3) { + this._knots.push(new Vec3(knot)); + } + + public insertKnot (index: number, knot: Vec3) { + const item = new Vec3(knot); + if (index >= this._knots.length) { + this._knots.push(item); + return; + } + + this._knots.splice(index, 0, item); + } + + public removeKnot (index: number) { + assertIsTrue(index >= 0 && index < this._knots.length, 'Spline: invalid index'); + + this._knots.splice(index, 1); + } + + public setKnot (index: number, knot: Vec3) { + assertIsTrue(index >= 0 && index < this._knots.length, 'Spline: invalid index'); + + this._knots[index].set(knot); + } + + public getKnot (index: number): Readonly { + assertIsTrue(index >= 0 && index < this._knots.length, 'Spline: invalid index'); + + return this._knots[index]; + } + + // get a point at t with repect to the `index` segment of curve or the whole curve. + public getPoint (t: number, index: number = SPLINE_WHOLE_INDEX) { + t = clamp(t, 0.0, 1.0); + + const segments = this.getSegments(); + if (segments == 0) { + return new Vec3(0.0, 0.0, 0.0); + } + + if (index == SPLINE_WHOLE_INDEX) { + const deltaT = 1.0 / segments; + + index = Math.floor(t / deltaT); + t = (t % deltaT) / deltaT; + } + + if (index >= segments) { + return new Vec3(this._knots[this._knots.length - 1]); + } + + switch (this._mode) { + case SplineMode.LINEAR: + return Spline.calcLinear(this._knots[index], this._knots[index + 1], t); + case SplineMode.BEZIER: + return Spline.calcBezier(this._knots[index * 4], this._knots[index * 4 + 1], this._knots[index * 4 + 2], this._knots[index * 4 + 3], t); + case SplineMode.CATMULL_ROM: { + const v0 = index > 0 ? this._knots[index - 1] : this._knots[index]; + const v3 = index + 2 < this._knots.length ? this._knots[index + 2] : this._knots[index + 1]; + return Spline.calcCatmullRom(v0, this._knots[index], this._knots[index + 1], v3, t); + } + default: + return new Vec3(0.0, 0.0, 0.0); + } + } + + // get num points from 0 to 1 uniformly with repect to the `index` segment of curve or the whole curve + public getPoints (num: number, index: number = SPLINE_WHOLE_INDEX): Vec3[] { + if (num == 0) { + return []; + } + + if (num == 1) { + const point = this.getPoint(0.0, index); + return [point]; + } + + const points: Vec3[] = []; + const deltaT = 1.0 / (num - 1.0); + + for (let i = 0; i < num; i++) { + const t = i * deltaT; + const point = this.getPoint(t, index); + + points.push(point); + } + + return points; + } + + private getSegments () { + const count = this._knots.length; + switch (this._mode) { + case SplineMode.LINEAR: + case SplineMode.CATMULL_ROM: + if (count < 2) { + warnID(14300); + return 0; + } + + return count - 1; + case SplineMode.BEZIER: + if (count < 4 || count % 4 != 0) { + warnID(14301); + return 0; + } + + return count / 4; + default: + assertIsTrue(false, 'Spline error: invalid mode'); + } + } + + private static calcLinear (v0: Vec3, v1: Vec3, t: number) { + const result = new Vec3(); + Vec3.multiplyScalar(_v0, v0, (1.0 - t)); + Vec3.multiplyScalar(_v1, v1, t); + Vec3.add(result, _v0, _v1); + + return result; + } + + private static calcBezier (v0: Vec3, v1: Vec3, v2: Vec3, v3: Vec3, t: number) { + const result = new Vec3(); + const s = 1.0 - t; + Vec3.multiplyScalar(_v0, v0, s * s * s); + Vec3.multiplyScalar(_v1, v1, 3.0 * t * s * s); + Vec3.multiplyScalar(_v2, v2, 3.0 * t * t * s); + Vec3.multiplyScalar(_v3, v3, t * t * t); + Vec3.add(_v0, _v0, _v1); + Vec3.add(_v2, _v2, _v3); + Vec3.add(result, _v0, _v2); + + return result; + } + private static calcCatmullRom (v0: Vec3, v1: Vec3, v2: Vec3, v3: Vec3, t: number) { + const result = new Vec3(); + const t2 = t * t; + const t3 = t2 * t; + Vec3.multiplyScalar(_v0, v0, -0.5 * t3 + t2 - 0.5 * t); + Vec3.multiplyScalar(_v1, v1, 1.5 * t3 - 2.5 * t2 + 1.0); + Vec3.multiplyScalar(_v2, v2, -1.5 * t3 + 2.0 * t2 + 0.5 * t); + Vec3.multiplyScalar(_v3, v3, 0.5 * t3 - 0.5 * t2); + Vec3.add(_v0, _v0, _v1); + Vec3.add(_v2, _v2, _v3); + Vec3.add(result, _v0, _v2); + + return result; + } +} diff --git a/cocos/core/geometry/triangle.ts b/cocos/core/geometry/triangle.ts index 6cc942545f..1bd73c1620 100644 --- a/cocos/core/geometry/triangle.ts +++ b/cocos/core/geometry/triangle.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module geometry - */ - import { Vec3 } from '../math'; import enums from './enums'; @@ -44,16 +39,16 @@ export class Triangle { * create a new triangle * @zh * 创建一个新的 triangle。 - * @param {number} ax a 点的 x 部分。 - * @param {number} ay a 点的 y 部分。 - * @param {number} az a 点的 z 部分。 - * @param {number} bx b 点的 x 部分。 - * @param {number} by b 点的 y 部分。 - * @param {number} bz b 点的 z 部分。 - * @param {number} cx c 点的 x 部分。 - * @param {number} cy c 点的 y 部分。 - * @param {number} cz c 点的 z 部分。 - * @return {Triangle} 一个新的 triangle。 + * @param {number} ax @en x component of point a @zh a 点的 x 部分。 + * @param {number} ay @en y component of point a @zh a 点的 y 部分。 + * @param {number} az @en z component of point a @zh a 点的 z 部分。 + * @param {number} bx @en x component of point b @zh b 点的 x 部分。 + * @param {number} by @en y component of point b @zh b 点的 y 部分。 + * @param {number} bz @en z component of point b @zh b 点的 z 部分。 + * @param {number} cx @en x component of point c @zh c 点的 x 部分。 + * @param {number} cy @en y component of point c @zh c 点的 y 部分。 + * @param {number} cz @en z component of point c @zh c 点的 z 部分。 + * @return {Triangle} @en A new triangle. @zh 一个新的 triangle。 */ public static create (ax = 1, ay = 0, az = 0, bx = 0, by = 0, bz = 0, @@ -66,8 +61,8 @@ export class Triangle { * clone a new triangle * @zh * 克隆一个新的 triangle。 - * @param {Triangle} t 克隆的目标。 - * @return {Triangle} 克隆出的新对象。 + * @param {Triangle} @en Triangle object to be cloned from. @zh t 克隆的目标。 + * @return {Triangle} @en A new cloned Triangle object. @zh 克隆出的新对象。 */ public static clone (t: Triangle): Triangle { return new Triangle( @@ -82,9 +77,9 @@ export class Triangle { * copy the values from one triangle to another * @zh * 将一个 triangle 的值复制到另一个 triangle。 - * @param {Triangle} out 接受操作的 triangle。 - * @param {Triangle} t 被复制的 triangle。 - * @return {Triangle} out 接受操作的 triangle。 + * @param {Triangle} out @en Target Triangle object to be copied to. @zh 接受操作的 triangle。 + * @param {Triangle} t @en A Triangle object to be copied from. @zh 被复制的 triangle。 + * @return {Triangle} @en The same as out. @zh out 接受操作的 triangle。 */ public static copy (out: Triangle, t: Triangle): Triangle { Vec3.copy(out.a, t.a); @@ -99,11 +94,11 @@ export class Triangle { * Create a triangle from three points * @zh * 用三个点创建一个 triangle。 - * @param {Triangle} out 接受操作的 triangle。 - * @param {Vec3} a a 点。 - * @param {Vec3} b b 点。 - * @param {Vec3} c c 点。 - * @return {Triangle} out 接受操作的 triangle。 + * @param {Triangle} out @en The Triangle object to be modified. @zh 接受操作的 triangle。 + * @param {Vec3} a @en The point value to set out.a. @zh a 点。 + * @param {Vec3} b @en The point value to set out.b. @zh b 点。 + * @param {Vec3} c @en The point value to set out.c. @zh c 点。 + * @return {Triangle} @en The same as out. @zh 接受操作的 triangle。 */ public static fromPoints (out: Triangle, a: Vec3, b: Vec3, c: Vec3): Triangle { Vec3.copy(out.a, a); @@ -117,17 +112,17 @@ export class Triangle { * Set the components of a triangle to the given values * @zh * 将给定三角形的属性设置为给定值。 - * @param {Triangle} out 给定的三角形。 - * @param {number} ax a 点的 x 部分。 - * @param {number} ay a 点的 y 部分。 - * @param {number} az a 点的 z 部分。 - * @param {number} bx b 点的 x 部分。 - * @param {number} by b 点的 y 部分。 - * @param {number} bz b 点的 z 部分。 - * @param {number} cx c 点的 x 部分。 - * @param {number} cy c 点的 y 部分。 - * @param {number} cz c 点的 z 部分。 - * @return {Triangle} + * @param {Triangle} out @en The Triangle object to be set. @zh 被修改的三角形。 + * @param {number} ax @en The value to set out.a.x. @zh a 点的 x 部分。 + * @param {number} ay @en The value to set out.a.y. @zh a 点的 y 部分。 + * @param {number} az @en The value to set out.a.z. @zh a 点的 z 部分。 + * @param {number} bx @en The value to set out.b.x. @zh b 点的 x 部分。 + * @param {number} by @en The value to set out.b.y. @zh b 点的 y 部分。 + * @param {number} bz @en The value to set out.b.z. @zh b 点的 z 部分。 + * @param {number} cx @en The value to set out.c.x. @zh c 点的 x 部分。 + * @param {number} cy @en The value to set out.c.y. @zh c 点的 y 部分。 + * @param {number} cz @en The value to set out.c.z. @zh c 点的 z 部分。 + * @return {Triangle} @en The same as out. @zh 传入的 out 对象。 * @function */ public static set (out: Triangle, @@ -190,15 +185,15 @@ export class Triangle { * Construct a triangle. * @zh * 构造一个三角形。 - * @param {number} ax a 点的 x 部分。 - * @param {number} ay a 点的 y 部分。 - * @param {number} az a 点的 z 部分。 - * @param {number} bx b 点的 x 部分。 - * @param {number} by b 点的 y 部分。 - * @param {number} bz b 点的 z 部分。 - * @param {number} cx c 点的 x 部分。 - * @param {number} cy c 点的 y 部分。 - * @param {number} cz c 点的 z 部分。 + * @param {number} ax @en x component of point a. @zh a 点的 x 部分。 + * @param {number} ay @en y component of point a. @zh a 点的 y 部分。 + * @param {number} az @en z component of point a. @zh a 点的 z 部分。 + * @param {number} bx @en x component of point b. @zh b 点的 x 部分。 + * @param {number} by @en y component of point b. @zh b 点的 y 部分。 + * @param {number} bz @en z component of point b. @zh b 点的 z 部分。 + * @param {number} cx @en x component of point c. @zh c 点的 x 部分。 + * @param {number} cy @en y component of point c. @zh c 点的 y 部分。 + * @param {number} cz @en z component of point c. @zh c 点的 z 部分。 */ constructor (ax = 0, ay = 0, az = 0, bx = 1, by = 0, bz = 0, diff --git a/cocos/core/gfx/base/buffer.ts b/cocos/core/gfx/base/buffer.ts index 92f29b93df..683f2cc0dc 100644 --- a/cocos/core/gfx/base/buffer.ts +++ b/cocos/core/gfx/base/buffer.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import { BufferFlagBit, BufferFlags, diff --git a/cocos/core/gfx/base/command-buffer.ts b/cocos/core/gfx/base/command-buffer.ts index 2caeb098d9..176b64d102 100644 --- a/cocos/core/gfx/base/command-buffer.ts +++ b/cocos/core/gfx/base/command-buffer.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import { Buffer } from './buffer'; import { DescriptorSet } from './descriptor-set'; import { Framebuffer } from './framebuffer'; @@ -46,6 +41,7 @@ import { } from './define'; import { GeneralBarrier } from './states/general-barrier'; import { TextureBarrier } from './states/texture-barrier'; +import { BufferBarrier } from './states/buffer-barrier'; /** * @en GFX command buffer. @@ -267,6 +263,9 @@ export abstract class CommandBuffer extends GFXObject { * @param barrier The global memory barrier to apply. * @param textureBarriers The texture memory barriers to apply. */ - public abstract pipelineBarrier (barrier: Readonly | null, textureBarriers?: Readonly, + public abstract pipelineBarrier (barrier: Readonly | null, + bufferBarriers?: Readonly, + buffers?: Readonly, + textureBarriers?: Readonly, textures?: Readonly): void; } diff --git a/cocos/core/gfx/base/define.ts b/cocos/core/gfx/base/define.ts index 78066526e6..69d9da2964 100644 --- a/cocos/core/gfx/base/define.ts +++ b/cocos/core/gfx/base/define.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import { Queue } from './queue'; import { Buffer } from './buffer'; import { Texture } from './texture'; @@ -37,10 +32,11 @@ import { DescriptorSetLayout } from './descriptor-set-layout'; import { Sampler } from './states/sampler'; import { GeneralBarrier } from './states/general-barrier'; +import { GCObject } from '../../data/gc-object'; -interface ICopyable { copy(info: ICopyable): ICopyable; } +interface ICopyable { copy (info: ICopyable): ICopyable; } -const deepCopy = (target: T[], source: T[], Ctor: Constructor) => { +const deepCopy = (target: T[], source: T[], Ctor: Constructor) => { for (let i = 0; i < source.length; ++i) { if (target.length <= i) target.push(new Ctor()); target[i].copy(source[i]); @@ -49,13 +45,17 @@ const deepCopy = (target: T[], source: T[], Ctor: Construct }; /** - * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= - * The following section is auto-generated from native/cocos/renderer/core/gfx/GFXDef-common.h - * by the script native/tools/gfx-define-generator/generate.js. - * Changes to these public interfaces should be made there first and synced back. - * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= - */ + * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= + * The following section is auto-generated from native/cocos/renderer/core/gfx/GFXDef-common.h + * by the script native/tools/gfx-define-generator/generate.js. + * Changes to these public interfaces should be made there first and synced back. + * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= + */ +/** + * @en Graphics object type + * @zh 图形API对象的类型 + */ export enum ObjectType { UNKNOWN, SWAPCHAIN, @@ -348,14 +348,14 @@ export enum Type { } export enum BufferUsageBit { - NONE = 0, + NONE = 0, TRANSFER_SRC = 0x1, TRANSFER_DST = 0x2, - INDEX = 0x4, - VERTEX = 0x8, - UNIFORM = 0x10, - STORAGE = 0x20, - INDIRECT = 0x40, + INDEX = 0x4, + VERTEX = 0x8, + UNIFORM = 0x10, + STORAGE = 0x20, + INDIRECT = 0x40, } export enum BufferFlagBit { @@ -363,16 +363,16 @@ export enum BufferFlagBit { } export enum MemoryAccessBit { - NONE = 0, - READ_ONLY = 0x1, + NONE = 0, + READ_ONLY = 0x1, WRITE_ONLY = 0x2, READ_WRITE = READ_ONLY | WRITE_ONLY, } export enum MemoryUsageBit { - NONE = 0, + NONE = 0, DEVICE = 0x1, // for rarely-updated resources, use MemoryUsageBit::DEVICE - HOST = 0x2, // for frequently-updated resources, use MemoryUsageBit::DEVICE | MemoryUsageBit::HOST + HOST = 0x2, // for frequently-updated resources, use MemoryUsageBit::DEVICE | MemoryUsageBit::HOST } export enum TextureType { @@ -385,28 +385,28 @@ export enum TextureType { } export enum TextureUsageBit { - NONE = 0, - TRANSFER_SRC = 0x1, - TRANSFER_DST = 0x2, - SAMPLED = 0x4, - STORAGE = 0x8, - COLOR_ATTACHMENT = 0x10, + NONE = 0, + TRANSFER_SRC = 0x1, + TRANSFER_DST = 0x2, + SAMPLED = 0x4, + STORAGE = 0x8, + COLOR_ATTACHMENT = 0x10, DEPTH_STENCIL_ATTACHMENT = 0x20, - INPUT_ATTACHMENT = 0x40, + INPUT_ATTACHMENT = 0x40, } export enum TextureFlagBit { - NONE = 0, - GEN_MIPMAP = 0x1, // Generate mipmaps using bilinear filter + NONE = 0, + GEN_MIPMAP = 0x1, // Generate mipmaps using bilinear filter GENERAL_LAYOUT = 0x2, // For inout framebuffer attachments } export enum FormatFeatureBit { - NONE = 0, - RENDER_TARGET = 0x1, // Allow usages as render pass attachments - SAMPLED_TEXTURE = 0x2, // Allow sampled reads in shaders - LINEAR_FILTER = 0x4, // Allow linear filtering when sampling in shaders or blitting - STORAGE_TEXTURE = 0x8, // Allow storage reads & writes in shaders + NONE = 0, + RENDER_TARGET = 0x1, // Allow usages as render pass attachments + SAMPLED_TEXTURE = 0x2, // Allow sampled reads in shaders + LINEAR_FILTER = 0x4, // Allow linear filtering when sampling in shaders or blitting + STORAGE_TEXTURE = 0x8, // Allow storage reads & writes in shaders VERTEX_ATTRIBUTE = 0x10, // Allow usages as vertex input attributes } @@ -505,22 +505,22 @@ export enum BlendOp { export enum ColorMask { NONE = 0x0, - R = 0x1, - G = 0x2, - B = 0x4, - A = 0x8, - ALL = R | G | B | A, + R = 0x1, + G = 0x2, + B = 0x4, + A = 0x8, + ALL = R | G | B | A, } export enum ShaderStageFlagBit { - NONE = 0x0, - VERTEX = 0x1, - CONTROL = 0x2, + NONE = 0x0, + VERTEX = 0x1, + CONTROL = 0x2, EVALUATION = 0x4, - GEOMETRY = 0x8, - FRAGMENT = 0x10, - COMPUTE = 0x20, - ALL = 0x3f, + GEOMETRY = 0x8, + FRAGMENT = 0x10, + COMPUTE = 0x20, + ALL = 0x3f, } export enum LoadOp { @@ -538,35 +538,35 @@ export enum AccessFlagBit { NONE = 0, // Read accesses - INDIRECT_BUFFER = 1 << 0, // Read as an indirect buffer for drawing or dispatch - INDEX_BUFFER = 1 << 1, // Read as an index buffer for drawing - VERTEX_BUFFER = 1 << 2, // Read as a vertex buffer for drawing - VERTEX_SHADER_READ_UNIFORM_BUFFER = 1 << 3, // Read as a uniform buffer in a vertex shader - VERTEX_SHADER_READ_TEXTURE = 1 << 4, // Read as a sampled image/uniform texel buffer in a vertex shader - VERTEX_SHADER_READ_OTHER = 1 << 5, // Read as any other resource in a vertex shader - FRAGMENT_SHADER_READ_UNIFORM_BUFFER = 1 << 6, // Read as a uniform buffer in a fragment shader - FRAGMENT_SHADER_READ_TEXTURE = 1 << 7, // Read as a sampled image/uniform texel buffer in a fragment shader - FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT = 1 << 8, // Read as an input attachment with a color format in a fragment shader - FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT = 1 << 9, // Read as an input attachment with a depth/stencil format in a fragment shader - FRAGMENT_SHADER_READ_OTHER = 1 << 10, // Read as any other resource in a fragment shader - COLOR_ATTACHMENT_READ = 1 << 11, // Read by standard blending/logic operations or subpass load operations - DEPTH_STENCIL_ATTACHMENT_READ = 1 << 12, // Read by depth/stencil tests or subpass load operations - COMPUTE_SHADER_READ_UNIFORM_BUFFER = 1 << 13, // Read as a uniform buffer in a compute shader - COMPUTE_SHADER_READ_TEXTURE = 1 << 14, // Read as a sampled image/uniform texel buffer in a compute shader - COMPUTE_SHADER_READ_OTHER = 1 << 15, // Read as any other resource in a compute shader - TRANSFER_READ = 1 << 16, // Read as the source of a transfer operation - HOST_READ = 1 << 17, // Read on the host - PRESENT = 1 << 18, // Read by the presentation engine + INDIRECT_BUFFER = 1 << 0, // Read as an indirect buffer for drawing or dispatch + INDEX_BUFFER = 1 << 1, // Read as an index buffer for drawing + VERTEX_BUFFER = 1 << 2, // Read as a vertex buffer for drawing + VERTEX_SHADER_READ_UNIFORM_BUFFER = 1 << 3, // Read as a uniform buffer in a vertex shader + VERTEX_SHADER_READ_TEXTURE = 1 << 4, // Read as a sampled image/uniform texel buffer in a vertex shader + VERTEX_SHADER_READ_OTHER = 1 << 5, // Read as any other resource in a vertex shader + FRAGMENT_SHADER_READ_UNIFORM_BUFFER = 1 << 6, // Read as a uniform buffer in a fragment shader + FRAGMENT_SHADER_READ_TEXTURE = 1 << 7, // Read as a sampled image/uniform texel buffer in a fragment shader + FRAGMENT_SHADER_READ_COLOR_INPUT_ATTACHMENT = 1 << 8, // Read as an input attachment with a color format in a fragment shader + FRAGMENT_SHADER_READ_DEPTH_STENCIL_INPUT_ATTACHMENT = 1 << 9, // Read as an input attachment with a depth/stencil format in a fragment shader + FRAGMENT_SHADER_READ_OTHER = 1 << 10, // Read as any other resource in a fragment shader + COLOR_ATTACHMENT_READ = 1 << 11, // Read by standard blending/logic operations or subpass load operations + DEPTH_STENCIL_ATTACHMENT_READ = 1 << 12, // Read by depth/stencil tests or subpass load operations + COMPUTE_SHADER_READ_UNIFORM_BUFFER = 1 << 13, // Read as a uniform buffer in a compute shader + COMPUTE_SHADER_READ_TEXTURE = 1 << 14, // Read as a sampled image/uniform texel buffer in a compute shader + COMPUTE_SHADER_READ_OTHER = 1 << 15, // Read as any other resource in a compute shader + TRANSFER_READ = 1 << 16, // Read as the source of a transfer operation + HOST_READ = 1 << 17, // Read on the host + PRESENT = 1 << 18, // Read by the presentation engine // Write accesses - VERTEX_SHADER_WRITE = 1 << 19, // Written as any resource in a vertex shader - FRAGMENT_SHADER_WRITE = 1 << 20, // Written as any resource in a fragment shader - COLOR_ATTACHMENT_WRITE = 1 << 21, // Written as a color attachment during rendering, or via a subpass store op + VERTEX_SHADER_WRITE = 1 << 19, // Written as any resource in a vertex shader + FRAGMENT_SHADER_WRITE = 1 << 20, // Written as any resource in a fragment shader + COLOR_ATTACHMENT_WRITE = 1 << 21, // Written as a color attachment during rendering, or via a subpass store op DEPTH_STENCIL_ATTACHMENT_WRITE = 1 << 22, // Written as a depth/stencil attachment during rendering, or via a subpass store op - COMPUTE_SHADER_WRITE = 1 << 23, // Written as any resource in a compute shader - TRANSFER_WRITE = 1 << 24, // Written as the destination of a transfer operation - HOST_PREINITIALIZED = 1 << 25, // Data pre-filled by host before device access starts - HOST_WRITE = 1 << 26, // Written on the host + COMPUTE_SHADER_WRITE = 1 << 23, // Written as any resource in a compute shader + TRANSFER_WRITE = 1 << 24, // Written as the destination of a transfer operation + HOST_PREINITIALIZED = 1 << 25, // Data pre-filled by host before device access starts + HOST_WRITE = 1 << 26, // Written on the host } export enum ResolveMode { @@ -619,32 +619,32 @@ export enum CullMode { } export enum DynamicStateFlagBit { - NONE = 0x0, - LINE_WIDTH = 0x1, - DEPTH_BIAS = 0x2, - BLEND_CONSTANTS = 0x4, - DEPTH_BOUNDS = 0x8, - STENCIL_WRITE_MASK = 0x10, + NONE = 0x0, + LINE_WIDTH = 0x1, + DEPTH_BIAS = 0x2, + BLEND_CONSTANTS = 0x4, + DEPTH_BOUNDS = 0x8, + STENCIL_WRITE_MASK = 0x10, STENCIL_COMPARE_MASK = 0x20, } export enum StencilFace { FRONT = 0x1, - BACK = 0x2, - ALL = 0x3, + BACK = 0x2, + ALL = 0x3, } export enum DescriptorType { - UNKNOWN = 0, - UNIFORM_BUFFER = 0x1, + UNKNOWN = 0, + UNIFORM_BUFFER = 0x1, DYNAMIC_UNIFORM_BUFFER = 0x2, - STORAGE_BUFFER = 0x4, + STORAGE_BUFFER = 0x4, DYNAMIC_STORAGE_BUFFER = 0x8, - SAMPLER_TEXTURE = 0x10, - SAMPLER = 0x20, - TEXTURE = 0x40, - STORAGE_IMAGE = 0x80, - INPUT_ATTACHMENT = 0x100, + SAMPLER_TEXTURE = 0x10, + SAMPLER = 0x20, + TEXTURE = 0x40, + STORAGE_IMAGE = 0x80, + INPUT_ATTACHMENT = 0x100, } export enum QueueType { @@ -665,12 +665,18 @@ export enum CommandBufferType { } export enum ClearFlagBit { - NONE = 0, - COLOR = 0x1, - DEPTH = 0x2, - STENCIL = 0x4, + NONE = 0, + COLOR = 0x1, + DEPTH = 0x2, + STENCIL = 0x4, DEPTH_STENCIL = DEPTH | STENCIL, - ALL = COLOR | DEPTH | STENCIL, + ALL = COLOR | DEPTH | STENCIL, +} + +export enum BarrierType { + FULL, + SPLIT_BEGIN, + SPLIT_END, } export type BufferUsage = BufferUsageBit; @@ -894,6 +900,7 @@ export class BufferTextureCopy { declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object constructor ( + public buffOffset: number = 0, public buffStride: number = 0, public buffTexHeight: number = 0, public texOffset: Offset = new Offset(), @@ -902,6 +909,7 @@ export class BufferTextureCopy { ) {} public copy (info: Readonly) { + this.buffOffset = info.buffOffset; this.buffStride = info.buffStride; this.buffTexHeight = info.buffTexHeight; this.texOffset.copy(info.texOffset); @@ -953,21 +961,6 @@ export class Color { } } -/** - * For non-vulkan backends, to maintain compatibility and maximize - * descriptor cache-locality, descriptor-set-based binding numbers need - * to be mapped to backend-specific bindings based on maximum limit - * of available descriptor slots in each set. - * - * The GFX layer assumes the binding numbers for each descriptor type inside each set - * are guaranteed to be consecutive, so the mapping procedure is reduced - * to a simple shifting operation. This data structure specifies the - * capacity for each descriptor type in each set. - * - * The `setIndices` field defines the binding ordering between different sets. - * The last set index is treated as the 'flexible set', whose capacity is dynamically - * assigned based on the total available descriptor slots on the runtime device. - */ export class BindingMappingInfo { declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object @@ -1578,11 +1571,13 @@ export class GeneralBarrierInfo { constructor ( public prevAccesses: AccessFlags = AccessFlagBit.NONE, public nextAccesses: AccessFlags = AccessFlagBit.NONE, + public type: BarrierType = BarrierType.FULL, ) {} public copy (info: Readonly) { this.prevAccesses = info.prevAccesses; this.nextAccesses = info.nextAccesses; + this.type = info.type; return this; } } @@ -1593,6 +1588,11 @@ export class TextureBarrierInfo { constructor ( public prevAccesses: AccessFlags = AccessFlagBit.NONE, public nextAccesses: AccessFlags = AccessFlagBit.NONE, + public type: BarrierType = BarrierType.FULL, + public baseMipLevel: number = 0, + public levelCount: number = 1, + public baseSlice: number = 0, + public sliceCount: number = 1, public discardContents: boolean = false, public srcQueue: Queue | null = null, public dstQueue: Queue | null = null, @@ -1601,6 +1601,38 @@ export class TextureBarrierInfo { public copy (info: Readonly) { this.prevAccesses = info.prevAccesses; this.nextAccesses = info.nextAccesses; + this.type = info.type; + this.baseMipLevel = info.baseMipLevel; + this.levelCount = info.levelCount; + this.baseSlice = info.baseSlice; + this.sliceCount = info.sliceCount; + this.discardContents = info.discardContents; + this.srcQueue = info.srcQueue; + this.dstQueue = info.dstQueue; + return this; + } +} + +export class BufferBarrierInfo { + declare private _token: never; // to make sure all usages must be an instance of this exact class, not assembled from plain object + + constructor ( + public prevAccesses: AccessFlags = AccessFlagBit.NONE, + public nextAccesses: AccessFlags = AccessFlagBit.NONE, + public type: BarrierType = BarrierType.FULL, + public offset: number = 0, + public size: number = 0, + public discardContents: boolean = false, + public srcQueue: Queue | null = null, + public dstQueue: Queue | null = null, + ) {} + + public copy (info: Readonly) { + this.prevAccesses = info.prevAccesses; + this.nextAccesses = info.nextAccesses; + this.type = info.type; + this.offset = info.offset; + this.size = info.size; this.discardContents = info.discardContents; this.srcQueue = info.srcQueue; this.dstQueue = info.dstQueue; @@ -1824,18 +1856,18 @@ export class DynamicStates { } /** - * ========================= !DO NOT CHANGE THE ABOVE SECTION MANUALLY! ========================= - * The above section is auto-generated from native/cocos/renderer/core/gfx/GFXDef-common.h - * by the script native/tools/gfx-define-generator/generate.js. - * Changes to these public interfaces should be made there first and synced back. - * ========================= !DO NOT CHANGE THE ABOVE SECTION MANUALLY! ========================= - */ + * ========================= !DO NOT CHANGE THE ABOVE SECTION MANUALLY! ========================= + * The above section is auto-generated from native/cocos/renderer/core/gfx/GFXDef-common.h + * by the script native/tools/gfx-define-generator/generate.js. + * Changes to these public interfaces should be made there first and synced back. + * ========================= !DO NOT CHANGE THE ABOVE SECTION MANUALLY! ========================= + */ /** - * @en GFX base object. - * @zh GFX 基类对象。 - */ -export class GFXObject { + * @en GFX base object. + * @zh GFX 基类对象。 + */ +export class GFXObject extends GCObject { public get objectType (): ObjectType { return this._objectType; } @@ -1855,6 +1887,7 @@ export class GFXObject { private static _idTable = Array(ObjectType.COUNT).fill(1 << 16); constructor (objectType: ObjectType) { + super(); this._objectType = objectType; this._objectID = GFXObject._idTable[ObjectType.UNKNOWN]++; this._typedID = GFXObject._idTable[objectType]++; @@ -2025,10 +2058,10 @@ export const FormatInfos = Object.freeze([ ]); export const DESCRIPTOR_BUFFER_TYPE = DescriptorType.UNIFORM_BUFFER | DescriptorType.DYNAMIC_UNIFORM_BUFFER - | DescriptorType.STORAGE_BUFFER | DescriptorType.DYNAMIC_STORAGE_BUFFER; + | DescriptorType.STORAGE_BUFFER | DescriptorType.DYNAMIC_STORAGE_BUFFER; export const DESCRIPTOR_SAMPLER_TYPE = DescriptorType.SAMPLER_TEXTURE | DescriptorType.SAMPLER | DescriptorType.TEXTURE - | DescriptorType.STORAGE_IMAGE | DescriptorType.INPUT_ATTACHMENT; + | DescriptorType.STORAGE_IMAGE | DescriptorType.INPUT_ATTACHMENT; export const DESCRIPTOR_DYNAMIC_TYPE = DescriptorType.DYNAMIC_STORAGE_BUFFER | DescriptorType.DYNAMIC_UNIFORM_BUFFER; @@ -2041,13 +2074,13 @@ export function IsPowerOf2 (x: number): boolean { } /** - * @en Get memory size of the specified fomat. - * @zh 获取指定格式对应的内存大小。 - * @param format The target format. - * @param width The target width. - * @param height The target height. - * @param depth The target depth. - */ + * @en Get memory size of the specified fomat. + * @zh 获取指定格式对应的内存大小。 + * @param format The target format. + * @param width The target width. + * @param height The target height. + * @param depth The target depth. + */ export function FormatSize (format: Format, width: number, height: number, depth: number): number { if (!FormatInfos[format].isCompressed) { return (width * height * depth * FormatInfos[format].size); @@ -2089,11 +2122,12 @@ export function FormatSize (format: Format, width: number, height: number, depth case Format.PVRTC_RGB2: case Format.PVRTC_RGBA2: case Format.PVRTC2_2BPP: - return Math.ceil(Math.max(width, 16) * Math.max(height, 8) / 4) * depth; + 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(Math.max(width, 8) * Math.max(height, 8) / 2) * depth; + return Math.ceil(width / 4) * Math.ceil(height / 4) * 8 * depth; case Format.ASTC_RGBA_4X4: case Format.ASTC_SRGBA_4X4: @@ -2146,14 +2180,14 @@ export function FormatSize (format: Format, width: number, height: number, depth } /** - * @en Get memory size of the specified surface. - * @zh GFX 格式表面内存大小。 - * @param format The target format. - * @param width The target width. - * @param height The target height. - * @param depth The target depth. - * @param mips The target mip levels. - */ + * @en Get memory size of the specified surface. + * @zh GFX 格式表面内存大小。 + * @param format The target format. + * @param width The target width. + * @param height The target height. + * @param depth The target depth. + * @param mips The target mip levels. + */ export function FormatSurfaceSize ( format: Format, width: number, height: number, depth: number, mips: number, @@ -2205,15 +2239,18 @@ const _type2size = [ ]; /** - * @en Get the memory size of the specified type. - * @zh 得到 GFX 数据类型的大小。 - * @param type The target type. - */ + * @en Get the memory size of the specified type. + * @zh 得到 GFX 数据类型的大小。 + * @param type The target type. + */ export function GetTypeSize (type: Type): number { return _type2size[type] || 0; } export function getTypedArrayConstructor (info: FormatInfo): TypedArrayConstructor { + if (info.isCompressed) { + return Uint8Array; + } const stride = info.size / info.count; switch (info.type) { case FormatType.UNORM: @@ -2223,8 +2260,8 @@ export function getTypedArrayConstructor (info: FormatInfo): TypedArrayConstruct case 2: return Uint16Array; case 4: return Uint32Array; default: + return Uint8Array; } - break; } case FormatType.SNORM: case FormatType.INT: { @@ -2233,8 +2270,8 @@ export function getTypedArrayConstructor (info: FormatInfo): TypedArrayConstruct case 2: return Int16Array; case 4: return Int32Array; default: + return Int8Array; } - break; } case FormatType.FLOAT: { return Float32Array; @@ -2243,3 +2280,99 @@ export function getTypedArrayConstructor (info: FormatInfo): TypedArrayConstruct } return Float32Array; } + +export interface FormatAlignment { + width: number, // default 1 + height: number, // default 1 +} + +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.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.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 { + return Math.ceil(size / alignment) * alignment; +} diff --git a/cocos/core/gfx/base/descriptor-set-layout.ts b/cocos/core/gfx/base/descriptor-set-layout.ts index d7b9c8e819..afd53e3b17 100644 --- a/cocos/core/gfx/base/descriptor-set-layout.ts +++ b/cocos/core/gfx/base/descriptor-set-layout.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import { GFXObject, ObjectType, DescriptorSetLayoutBinding, DescriptorSetLayoutInfo } from './define'; /** diff --git a/cocos/core/gfx/base/descriptor-set.ts b/cocos/core/gfx/base/descriptor-set.ts index 909c61f114..2fc14bbd38 100644 --- a/cocos/core/gfx/base/descriptor-set.ts +++ b/cocos/core/gfx/base/descriptor-set.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import { Buffer } from './buffer'; import { DescriptorSetLayout } from './descriptor-set-layout'; import { Sampler } from './states/sampler'; diff --git a/cocos/core/gfx/base/device.ts b/cocos/core/gfx/base/device.ts index 3339a0b742..4374963815 100644 --- a/cocos/core/gfx/base/device.ts +++ b/cocos/core/gfx/base/device.ts @@ -23,17 +23,12 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import { API, Feature, MemoryStatus, CommandBufferInfo, BufferInfo, BufferViewInfo, TextureInfo, TextureViewInfo, SamplerInfo, DescriptorSetInfo, ShaderInfo, InputAssemblerInfo, RenderPassInfo, FramebufferInfo, DescriptorSetLayoutInfo, PipelineLayoutInfo, - QueueInfo, BufferTextureCopy, DeviceInfo, DeviceCaps, GeneralBarrierInfo, TextureBarrierInfo, SwapchainInfo, - BindingMappingInfo, Format, FormatFeature, + QueueInfo, BufferTextureCopy, DeviceInfo, DeviceCaps, GeneralBarrierInfo, TextureBarrierInfo, BufferBarrierInfo, + SwapchainInfo, BindingMappingInfo, Format, FormatFeature, } from './define'; import { Buffer } from './buffer'; import { CommandBuffer } from './command-buffer'; @@ -50,6 +45,7 @@ import { Shader } from './shader'; import { Texture } from './texture'; import { GeneralBarrier } from './states/general-barrier'; import { TextureBarrier } from './states/texture-barrier'; +import { BufferBarrier } from './states/buffer-barrier'; import { Swapchain } from './swapchain'; /** @@ -161,6 +157,7 @@ export abstract class Device { protected _samplers = new Map(); protected _generalBarrierss = new Map(); protected _textureBarriers = new Map(); + protected _bufferBarriers = new Map(); public static canvas: HTMLCanvasElement; // Hack for WebGL device initialization process @@ -298,6 +295,13 @@ export abstract class Device { */ public abstract getTextureBarrier (info: Readonly): TextureBarrier; + /** + * @en Create buffer barrier. + * @zh 创建buffer内存屏障。 + * @param info GFX buffer barrier description info. + */ + public abstract getBufferBarrier (info: Readonly): BufferBarrier; + /** * @en Copy buffers to texture. * @zh 拷贝缓冲到纹理。 diff --git a/cocos/core/gfx/base/framebuffer.ts b/cocos/core/gfx/base/framebuffer.ts index 515b507c18..b5e89ac207 100644 --- a/cocos/core/gfx/base/framebuffer.ts +++ b/cocos/core/gfx/base/framebuffer.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import { RenderPass } from './render-pass'; import { Texture } from './texture'; import { GFXObject, ObjectType, FramebufferInfo } from './define'; diff --git a/cocos/core/gfx/base/input-assembler.ts b/cocos/core/gfx/base/input-assembler.ts index f008ab80bd..9f21f956e4 100644 --- a/cocos/core/gfx/base/input-assembler.ts +++ b/cocos/core/gfx/base/input-assembler.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import { Buffer } from './buffer'; import { murmurhash2_32_gc } from '../../utils/murmurhash2_gc'; import { Attribute, GFXObject, ObjectType, InputAssemblerInfo, DrawInfo } from './define'; diff --git a/cocos/core/gfx/base/pipeline-layout.ts b/cocos/core/gfx/base/pipeline-layout.ts index 3b6a401d03..413ef52ae3 100644 --- a/cocos/core/gfx/base/pipeline-layout.ts +++ b/cocos/core/gfx/base/pipeline-layout.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import { DescriptorSetLayout } from './descriptor-set-layout'; import { GFXObject, ObjectType, PipelineLayoutInfo } from './define'; diff --git a/cocos/core/gfx/pipeline-state.jsb.ts b/cocos/core/gfx/base/pipeline-state.jsb.ts similarity index 99% rename from cocos/core/gfx/pipeline-state.jsb.ts rename to cocos/core/gfx/base/pipeline-state.jsb.ts index 616f962468..30adc71ece 100644 --- a/cocos/core/gfx/pipeline-state.jsb.ts +++ b/cocos/core/gfx/base/pipeline-state.jsb.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - declare const gfx: any; declare type RecursivePartial = { @@ -47,7 +42,7 @@ import { ShadeModel, StencilOp, Color, -} from './base/define'; +} from './define'; export class RasterizerState { protected _nativeObj; protected _isDiscard: boolean = false; @@ -554,7 +549,6 @@ function watchArrayElementsField (self: S, list: T[], eleField: string, ca } } - export class BlendState { private targets: BlendTarget[]; private _blendColor: Color; @@ -568,7 +562,7 @@ export class BlendState { const CACHED_FIELD_NAME = `$__nativeObj`; this._syncTargetsToNativeObj(CACHED_FIELD_NAME); - // watch target[i]._nativeObj fields update + // watch target[i]._nativeObj fields update watchArrayElementsField(this, this.targets, "_nativeObj", CACHED_FIELD_NAME, (self, _idx, _originTarget, _prop, _value) => { self._syncTargetsToNativeObj(CACHED_FIELD_NAME); }); @@ -659,3 +653,7 @@ export class BlendState { export const PipelineState = gfx.PipelineState; export const PipelineStateInfo = gfx.PipelineStateInfo; + + + + diff --git a/cocos/core/gfx/base/pipeline-state.ts b/cocos/core/gfx/base/pipeline-state.ts index 39efa296e0..983d0a0e90 100644 --- a/cocos/core/gfx/base/pipeline-state.ts +++ b/cocos/core/gfx/base/pipeline-state.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import { PipelineLayout } from './pipeline-layout'; import { RenderPass } from './render-pass'; import { Shader } from './shader'; diff --git a/cocos/core/gfx/base/queue.ts b/cocos/core/gfx/base/queue.ts index d41fcf36e9..c1e1256d8b 100644 --- a/cocos/core/gfx/base/queue.ts +++ b/cocos/core/gfx/base/queue.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import { CommandBuffer } from './command-buffer'; import { GFXObject, ObjectType, QueueType, QueueInfo } from './define'; diff --git a/cocos/core/gfx/base/render-pass.ts b/cocos/core/gfx/base/render-pass.ts index 5b23e302cb..ad401ef710 100644 --- a/cocos/core/gfx/base/render-pass.ts +++ b/cocos/core/gfx/base/render-pass.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import { murmurhash2_32_gc } from '../../utils/murmurhash2_gc'; import { GFXObject, diff --git a/cocos/core/gfx/base/shader.ts b/cocos/core/gfx/base/shader.ts index 84df250ae6..0367cf74a1 100644 --- a/cocos/core/gfx/base/shader.ts +++ b/cocos/core/gfx/base/shader.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import { GFXObject, ObjectType, ShaderInfo, ShaderStage, UniformBlock, UniformSampler, Attribute } from './define'; /** diff --git a/native/cocos/renderer/pipeline/custom/RenderCompilerReflection.h b/cocos/core/gfx/base/states/buffer-barrier.ts similarity index 53% rename from native/cocos/renderer/pipeline/custom/RenderCompilerReflection.h rename to cocos/core/gfx/base/states/buffer-barrier.ts index df95cfba8a..34761a5b53 100644 --- a/native/cocos/renderer/pipeline/custom/RenderCompilerReflection.h +++ b/cocos/core/gfx/base/states/buffer-barrier.ts @@ -1,7 +1,7 @@ -/**************************************************************************** - Copyright (c) 2021-2022 Xiamen Yaji Software Co., Ltd. +/* + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. - http://www.cocos.com + 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, @@ -21,17 +21,37 @@ 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 { murmurhash2_32_gc } from '../../../utils/murmurhash2_gc'; +import { GFXObject, ObjectType, BufferBarrierInfo } from '../define'; /** - * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= - * The following section is auto-generated. - * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= + * @en GFX buffer barrier. + * @zh GFX buffer内存屏障。 */ -// clang-format off -#pragma once -#include "cocos/renderer/pipeline/custom/LayoutGraphReflection.h" -#include "cocos/renderer/pipeline/custom/RenderCompilerFwd.h" -#include "cocos/renderer/pipeline/custom/RenderGraphReflection.h" +export class BufferBarrier extends GFXObject { + get info (): Readonly { return this._info; } + get hash (): number { return this._hash; } -// clang-format on + protected _info: BufferBarrierInfo = new BufferBarrierInfo(); + protected _hash = 0; + + constructor (info: Readonly, hash: number) { + super(ObjectType.BUFFER_BARRIER); + this._info.copy(info); + this._hash = hash; + } + + static computeHash (info: Readonly) { + let res = `${info.prevAccesses} ${info.nextAccesses}`; + res += info.type; + res += info.offset; + res += info.size; + res += info.discardContents; + res += info.srcQueue ? info.srcQueue.type : 0; + res += info.dstQueue ? info.dstQueue.type : 0; + + return murmurhash2_32_gc(res, 666); + } +} diff --git a/cocos/core/gfx/base/states/general-barrier.ts b/cocos/core/gfx/base/states/general-barrier.ts index 5b6359e096..ad6094c52c 100644 --- a/cocos/core/gfx/base/states/general-barrier.ts +++ b/cocos/core/gfx/base/states/general-barrier.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import { murmurhash2_32_gc } from '../../../utils/murmurhash2_gc'; import { GFXObject, ObjectType, GeneralBarrierInfo } from '../define'; @@ -49,6 +44,6 @@ export class GeneralBarrier extends GFXObject { } static computeHash (info: Readonly) { - return murmurhash2_32_gc(`${info.prevAccesses} ${info.nextAccesses}`, 666); + return murmurhash2_32_gc(`${info.prevAccesses} ${info.nextAccesses} ${info.type}`, 666); } } diff --git a/cocos/core/gfx/base/states/sampler.ts b/cocos/core/gfx/base/states/sampler.ts index abbaa4f21c..c161170409 100644 --- a/cocos/core/gfx/base/states/sampler.ts +++ b/cocos/core/gfx/base/states/sampler.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import { GFXObject, ObjectType, SamplerInfo } from '../define'; /** diff --git a/cocos/core/gfx/base/states/texture-barrier.ts b/cocos/core/gfx/base/states/texture-barrier.ts index 40ef82d234..457ac62fbd 100644 --- a/cocos/core/gfx/base/states/texture-barrier.ts +++ b/cocos/core/gfx/base/states/texture-barrier.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import { murmurhash2_32_gc } from '../../../utils/murmurhash2_gc'; import { GFXObject, ObjectType, TextureBarrierInfo } from '../define'; @@ -50,6 +45,11 @@ export class TextureBarrier extends GFXObject { static computeHash (info: Readonly) { let res = `${info.prevAccesses} ${info.nextAccesses}`; + res += info.type; + res += info.baseMipLevel; + res += info.levelCount; + res += info.baseSlice; + res += info.sliceCount; res += info.discardContents; res += info.srcQueue ? info.srcQueue.type : 0; res += info.dstQueue ? info.dstQueue.type : 0; diff --git a/cocos/core/gfx/base/swapchain.ts b/cocos/core/gfx/base/swapchain.ts index 489aa0e6cd..f44f4f46d6 100644 --- a/cocos/core/gfx/base/swapchain.ts +++ b/cocos/core/gfx/base/swapchain.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import { GFXObject, ObjectType, SurfaceTransform, SwapchainInfo } from './define'; import { Texture } from './texture'; diff --git a/cocos/core/gfx/base/texture.ts b/cocos/core/gfx/base/texture.ts index 5f05486ecb..aa405017f6 100644 --- a/cocos/core/gfx/base/texture.ts +++ b/cocos/core/gfx/base/texture.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import { Format, GFXObject, diff --git a/cocos/core/gfx/category.json b/cocos/core/gfx/category.json new file mode 100644 index 0000000000..dbb440f001 --- /dev/null +++ b/cocos/core/gfx/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "图形后端抽象", + "en": "GFX" + }, + "description": { + "zh": "图形后端抽象类,用于抹平不同渲染后端 API 差异", + "en": "Graphical backend abstraction classes for unifying APIs of different rendering backends" + } +} \ No newline at end of file diff --git a/cocos/core/gfx/deprecated-3.0.0.ts b/cocos/core/gfx/deprecated-3.0.0.ts index 405a9f4939..cc86babf67 100644 --- a/cocos/core/gfx/deprecated-3.0.0.ts +++ b/cocos/core/gfx/deprecated-3.0.0.ts @@ -23,7 +23,6 @@ THE SOFTWARE. */ - import { replaceProperty, removeProperty } from '../utils/x-deprecated'; import { legacyCC } from '../global-exports'; diff --git a/cocos/core/gfx/deprecated-3.5.0.ts b/cocos/core/gfx/deprecated-3.5.0.ts index 5618c55c8a..74e33a4477 100644 --- a/cocos/core/gfx/deprecated-3.5.0.ts +++ b/cocos/core/gfx/deprecated-3.5.0.ts @@ -23,7 +23,6 @@ THE SOFTWARE. */ - import { removeProperty, replaceProperty } from '../utils/x-deprecated'; import { Device } from './base/device'; import { Feature, ColorAttachment, DepthStencilAttachment } from './base/define'; diff --git a/cocos/core/gfx/device-manager.ts b/cocos/core/gfx/device-manager.ts new file mode 100644 index 0000000000..797a8ceb97 --- /dev/null +++ b/cocos/core/gfx/device-manager.ts @@ -0,0 +1,196 @@ +/* + 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 { JSB } from 'internal:constants'; +import { legacyCC } from '../global-exports'; +import { error, getError } from '../platform/debug'; +import { sys } from '../platform/sys'; +import { BindingMappingInfo, DeviceInfo, SwapchainInfo } from './base/define'; +import { Device } from './base/device'; +import { Swapchain } from './base/swapchain'; +import { BrowserType } from '../../../pal/system-info/enum-type'; +import { screen } from '../platform/screen'; +import { Settings, settings } from '../settings'; + +/** + * @en + * Sets the renderer type, only useful on web + * + * @zh + * 渲染模式。 + * 设置渲染器类型,仅适用于 web 端 + * @internal + */ +export enum LegacyRenderMode { + /** + * @en + * Automatically chosen by engine. + * @zh + * 通过引擎自动选择。 + */ + AUTO = 0, + /** + * @en + * Forced to use canvas renderer. + * @zh + * 强制使用 canvas 渲染。 + */ + CANVAS = 1, + /** + * @en + * Forced to use WebGL renderer, but this will be ignored on mobile browsers. + * @zh + * 强制使用 WebGL 渲染,但是在部分 Android 浏览器中这个选项会被忽略。 + */ + WEBGL = 2, + /** + * @en + * Use Headless Renderer, which is useful in test or server env, only for internal use by cocos team for now + * @zh + * 使用空渲染器,可以用于测试和服务器端环境,目前暂时用于 Cocos 内部测试使用。 + */ + HEADLESS = 3 +} + +/** + * @internal + */ +export enum RenderType { + UNKNOWN = -1, + CANVAS = 0, + WEBGL = 1, + OPENGL = 2, + HEADLESS = 3, +} + +/** + * @internal + */ +export class DeviceManager { + private initialized = false; + private _gfxDevice!: Device; + private _canvas: HTMLCanvasElement | null = null; + private _swapchain!: Swapchain; + private _renderType: RenderType = RenderType.UNKNOWN; + + public get gfxDevice () { + return this._gfxDevice; + } + + public get swapchain () { + return this._swapchain; + } + + public init (canvas: HTMLCanvasElement | null, bindingMappingInfo: BindingMappingInfo) { + // Avoid setup to be called twice. + if (this.initialized) { return; } + const renderMode = settings.querySettings(Settings.Category.RENDERING, 'renderMode'); + this._canvas = canvas; + + this._renderType = this._determineRenderType(renderMode); + + // WebGL context created successfully + if (this._renderType === RenderType.WEBGL) { + const deviceInfo = new DeviceInfo(bindingMappingInfo); + + if (JSB && window.gfx) { + this._gfxDevice = gfx.DeviceManager.create(deviceInfo); + } else { + let useWebGL2 = (!!window.WebGL2RenderingContext); + const userAgent = window.navigator.userAgent.toLowerCase(); + if (userAgent.indexOf('safari') !== -1 && userAgent.indexOf('chrome') === -1 + || sys.browserType === BrowserType.UC // UC browser implementation doesn't conform to WebGL2 standard + ) { + useWebGL2 = false; + } + + const deviceCtors: Constructor[] = []; + if (useWebGL2 && legacyCC.WebGL2Device) { + deviceCtors.push(legacyCC.WebGL2Device); + } + if (legacyCC.WebGLDevice) { + deviceCtors.push(legacyCC.WebGLDevice); + } + if (legacyCC.EmptyDevice) { + deviceCtors.push(legacyCC.EmptyDevice); + } + + Device.canvas = canvas!; + for (let i = 0; i < deviceCtors.length; i++) { + this._gfxDevice = new deviceCtors[i](); + if (this._gfxDevice.initialize(deviceInfo)) { break; } + } + } + } else if (this._renderType === RenderType.HEADLESS && legacyCC.EmptyDevice) { + this._gfxDevice = new legacyCC.EmptyDevice(); + this._gfxDevice.initialize(new DeviceInfo(bindingMappingInfo)); + } + + if (!this._gfxDevice) { + // todo fix here for wechat game + error('can not support canvas rendering in 3D'); + this._renderType = RenderType.UNKNOWN; + return; + } + + const swapchainInfo = new SwapchainInfo(this._canvas!); + const windowSize = screen.windowSize; + swapchainInfo.width = windowSize.width; + swapchainInfo.height = windowSize.height; + this._swapchain = this._gfxDevice.createSwapchain(swapchainInfo); + + if (this._canvas) { this._canvas.oncontextmenu = () => false; } + } + + private _determineRenderType (renderMode: LegacyRenderMode): RenderType { + if (typeof renderMode !== 'number' || renderMode > RenderType.HEADLESS || renderMode < LegacyRenderMode.AUTO) { + renderMode = LegacyRenderMode.AUTO; + } + // Determine RenderType + let renderType = RenderType.CANVAS; + let supportRender = false; + + if (renderMode === LegacyRenderMode.CANVAS) { + renderType = RenderType.CANVAS; + supportRender = true; + } else if (renderMode === LegacyRenderMode.AUTO || renderMode === LegacyRenderMode.WEBGL) { + renderType = RenderType.WEBGL; + supportRender = true; + } else if (renderMode === LegacyRenderMode.HEADLESS) { + renderType = RenderType.HEADLESS; + supportRender = true; + } + + if (!supportRender) { + throw new Error(getError(3820, renderMode)); + } + return renderType; + } +} + +/** + * @internal + */ +export const deviceManager = new DeviceManager(); diff --git a/cocos/core/gfx/empty/empty-command-buffer.ts b/cocos/core/gfx/empty/empty-command-buffer.ts index a06920d284..32397ccf22 100644 --- a/cocos/core/gfx/empty/empty-command-buffer.ts +++ b/cocos/core/gfx/empty/empty-command-buffer.ts @@ -33,6 +33,7 @@ import { Texture } from '../base/texture'; import { RenderPass } from '../base/render-pass'; import { GeneralBarrier } from '../base/states/general-barrier'; import { TextureBarrier } from '../base/states/texture-barrier'; +import { BufferBarrier } from '../base/states/buffer-barrier'; import { StencilFace, BufferSource, CommandBufferInfo, BufferTextureCopy, Color, Rect, Viewport, DrawInfo } from '../base/define'; export class EmptyCommandBuffer extends CommandBuffer { @@ -61,5 +62,8 @@ export class EmptyCommandBuffer extends CommandBuffer { public updateBuffer (buffer: Buffer, data: Readonly, size?: number) {} public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly) {} public execute (cmdBuffs: Readonly, count: number) {} - public pipelineBarrier (GeneralBarrier: Readonly, textureBarriers: Readonly) {} + public pipelineBarrier (GeneralBarrier: Readonly, bufferBarriers?: Readonly, + buffers?: Readonly, + textureBarriers?: Readonly, + textures?: Readonly) {} } diff --git a/cocos/core/gfx/empty/empty-device.ts b/cocos/core/gfx/empty/empty-device.ts index c198983779..f1b799e6e5 100644 --- a/cocos/core/gfx/empty/empty-device.ts +++ b/cocos/core/gfx/empty/empty-device.ts @@ -42,10 +42,11 @@ import { ShaderInfo, QueueInfo, CommandBufferInfo, DescriptorSetInfo, DescriptorSetLayoutInfo, FramebufferInfo, InputAssemblerInfo, PipelineLayoutInfo, RenderPassInfo, SamplerInfo, TextureInfo, TextureViewInfo, BufferInfo, BufferViewInfo, DeviceInfo, TextureBarrierInfo, GeneralBarrierInfo, - QueueType, API, BufferTextureCopy, SwapchainInfo, + BufferBarrierInfo, QueueType, API, BufferTextureCopy, SwapchainInfo, } from '../base/define'; import { GeneralBarrier } from '../base/states/general-barrier'; import { TextureBarrier } from '../base/states/texture-barrier'; +import { BufferBarrier } from '../base/states/buffer-barrier'; import { Swapchain } from '../base/swapchain'; import { EmptyDescriptorSet } from './empty-descriptor-set'; import { EmptyBuffer } from './empty-buffer'; @@ -194,6 +195,14 @@ export class EmptyDevice extends Device { return this._textureBarriers.get(hash)!; } + public getBufferBarrier (info: Readonly) { + const hash = BufferBarrier.computeHash(info); + if (!this._bufferBarriers.has(hash)) { + this._bufferBarriers.set(hash, new BufferBarrier(info, hash)); + } + return this._bufferBarriers.get(hash)!; + } + public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly) {} public copyTextureToBuffers (texture: Readonly, buffers: ArrayBufferView[], regions: Readonly) {} public copyTexImagesToTexture (texImages: Readonly, texture: Texture, regions: Readonly) {} diff --git a/cocos/core/gfx/index.jsb.ts b/cocos/core/gfx/index.jsb.ts index e45f202bb6..57602173d1 100644 --- a/cocos/core/gfx/index.jsb.ts +++ b/cocos/core/gfx/index.jsb.ts @@ -23,16 +23,11 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - declare const gfx: any; import { legacyCC } from '../global-exports'; import * as defines from './base/define'; -import * as pso from './pipeline-state.jsb'; +import * as pso from './base/pipeline-state'; export * from './base/descriptor-set'; export * from './base/buffer'; @@ -44,6 +39,7 @@ export * from './base/framebuffer'; export * from './base/input-assembler'; export * from './base/descriptor-set-layout'; export * from './base/pipeline-layout'; +export * from './base/pipeline-state'; export * from './base/queue'; export * from './base/render-pass'; export * from './base/shader'; @@ -51,6 +47,7 @@ export * from './base/texture'; export * from './base/states/sampler'; export * from './base/states/general-barrier'; export * from './base/states/texture-barrier'; +export * from './device-manager'; const polyfillCC: Record = Object.assign({}, defines); polyfillCC.Device = gfx.Device; @@ -70,14 +67,6 @@ polyfillCC.CommandBuffer = gfx.CommandBuffer; polyfillCC.Queue = gfx.Queue; legacyCC.gfx = polyfillCC; -// TODO: remove these after state info refactor -export const BlendTarget = pso.BlendTarget; -export const BlendState = pso.BlendState; -export const RasterizerState = pso.RasterizerState; -export const DepthStencilState = pso.DepthStencilState; -export const PipelineState = pso.PipelineState; -export const PipelineStateInfo = pso.PipelineStateInfo; - polyfillCC.BlendTarget = pso.BlendTarget; polyfillCC.BlendState = pso.BlendState; polyfillCC.RasterizerState = pso.RasterizerState; diff --git a/cocos/core/gfx/index.ts b/cocos/core/gfx/index.ts index d88bdd7ad5..c84acd727d 100644 --- a/cocos/core/gfx/index.ts +++ b/cocos/core/gfx/index.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module gfx - */ - import './polyfill-legacy-cc'; import './deprecated-3.0.0'; import './deprecated-3.5.0'; @@ -50,3 +45,4 @@ export * from './base/shader'; export * from './base/texture'; export * from './base/states/general-barrier'; export * from './base/states/texture-barrier'; +export * from './device-manager'; diff --git a/cocos/core/gfx/polyfill-legacy-cc.ts b/cocos/core/gfx/polyfill-legacy-cc.ts index e4485f0b4f..9d95f5c672 100644 --- a/cocos/core/gfx/polyfill-legacy-cc.ts +++ b/cocos/core/gfx/polyfill-legacy-cc.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { Buffer } from './base/buffer'; import { CommandBuffer } from './base/command-buffer'; import { Device } from './base/device'; @@ -42,6 +40,7 @@ import { Shader } from './base/shader'; import { Texture } from './base/texture'; import { GeneralBarrier } from './base/states/general-barrier'; import { TextureBarrier } from './base/states/texture-barrier'; +import { BufferBarrier } from './base/states/buffer-barrier'; import { legacyCC } from '../global-exports'; import * as defines from './base/define'; @@ -63,6 +62,7 @@ const polyfills: Record = { Queue, GeneralBarrier, TextureBarrier, + BufferBarrier, RasterizerState, BlendState, diff --git a/cocos/core/gfx/webgl/webgl-command-buffer.ts b/cocos/core/gfx/webgl/webgl-command-buffer.ts index 8e06ffd00b..a8b87f6fa6 100644 --- a/cocos/core/gfx/webgl/webgl-command-buffer.ts +++ b/cocos/core/gfx/webgl/webgl-command-buffer.ts @@ -46,6 +46,7 @@ import { WebGLCmd, WebGLCmdBeginRenderPass, WebGLCmdBindStates, WebGLCmdCopyBuff WebGLCmdDraw, WebGLCmdPackage, WebGLCmdUpdateBuffer } from './webgl-commands'; import { GeneralBarrier } from '../base/states/general-barrier'; import { TextureBarrier } from '../base/states/texture-barrier'; +import { BufferBarrier } from '../base/states/buffer-barrier'; import { WebGLDeviceManager } from './webgl-define'; export class WebGLCommandBuffer extends CommandBuffer { @@ -399,7 +400,9 @@ export class WebGLCommandBuffer extends CommandBuffer { } } - public pipelineBarrier (GeneralBarrier: Readonly | null, textureBarriers?: Readonly, + public pipelineBarrier (GeneralBarrier: Readonly, bufferBarriers?: Readonly, + buffers?: Readonly, + textureBarriers?: Readonly, textures?: Readonly) {} protected bindStates () { diff --git a/cocos/core/gfx/webgl/webgl-commands.ts b/cocos/core/gfx/webgl/webgl-commands.ts index 9a5a37b75f..0dd803f568 100644 --- a/cocos/core/gfx/webgl/webgl-commands.ts +++ b/cocos/core/gfx/webgl/webgl-commands.ts @@ -35,7 +35,7 @@ import { import { BufferUsageBit, ClearFlagBit, ClearFlags, ColorMask, CullMode, Format, BufferTextureCopy, Color, Rect, FormatInfos, FormatSize, LoadOp, MemoryUsageBit, ShaderStageFlagBit, UniformSamplerTexture, - TextureFlagBit, TextureType, Type, FormatInfo, DynamicStateFlagBit, BufferSource, DrawInfo, IndirectBuffer, DynamicStates, + TextureFlagBit, TextureType, Type, FormatInfo, DynamicStateFlagBit, BufferSource, DrawInfo, IndirectBuffer, DynamicStates, Extent, getTypedArrayConstructor, formatAlignment, Offset, alignTo, } from '../base/define'; export function GFXFormatToWebGLType (format: Format, gl: WebGLRenderingContext): GLenum { @@ -2702,6 +2702,41 @@ export function WebGLCmdFuncCopyTexImagesToTexture ( } } +let stagingBuffer = new Uint8Array(1); +function pixelBufferPick (buffer: ArrayBufferView, + format: Format, + offset: number, + stride: Extent, + extent: Extent): ArrayBufferView { + const blockHeight = formatAlignment(format).height; + + const bufferSize = FormatSize(format, extent.width, extent.height, extent.depth); + const rowStride = FormatSize(format, stride.width, 1, 1); + const sliceStride = FormatSize(format, stride.width, stride.height, 1); + const chunkSize = FormatSize(format, extent.width, 1, 1); + + const ArrayBufferCtor: TypedArrayConstructor = getTypedArrayConstructor(FormatInfos[format]); + + if (stagingBuffer.byteLength < bufferSize) { + stagingBuffer = new Uint8Array(bufferSize); + } + + let destOffset = 0; + let bufferOffset = offset; + + for (let i = 0; i < extent.depth; i++) { + bufferOffset = offset + sliceStride * i; + for (let j = 0; j < extent.height; j += blockHeight) { + stagingBuffer.subarray(destOffset, destOffset + chunkSize).set( + new Uint8Array(buffer.buffer, buffer.byteOffset + bufferOffset, chunkSize), + ); + destOffset += chunkSize; + bufferOffset += rowStride; + } + } + return new ArrayBufferCtor(stagingBuffer.buffer); +} + export function WebGLCmdFuncCopyBuffersToTexture ( device: WebGLDevice, buffers: Readonly, @@ -2716,58 +2751,106 @@ export function WebGLCmdFuncCopyBuffersToTexture ( } let n = 0; - let w = 1; - let h = 1; let f = 0; - const fmtInfo: FormatInfo = FormatInfos[gpuTexture.format]; + const ArrayBufferCtor : TypedArrayConstructor = getTypedArrayConstructor(fmtInfo); const { isCompressed } = fmtInfo; + + const blockSize = formatAlignment(gpuTexture.format); + + const extent: Extent = new Extent(); + const offset: Offset = new Offset(); + const stride: Extent = new Extent(); + switch (gpuTexture.glTarget) { case gl.TEXTURE_2D: { for (let i = 0; i < regions.length; i++) { const region = regions[i]; - w = region.texExtent.width; - h = region.texExtent.height; - // console.debug('Copying buffer to texture 2D: ' + w + ' x ' + h); + const mipLevel = region.texSubres.mipLevel; + + offset.x = region.texOffset.x === 0 ? 0 : alignTo(region.texOffset.x, blockSize.width); + offset.y = region.texOffset.y === 0 ? 0 : alignTo(region.texOffset.y, blockSize.height); + extent.width = region.texExtent.width < blockSize.width ? region.texExtent.width : alignTo(region.texExtent.width, blockSize.width); + extent.height = region.texExtent.height < blockSize.height ? region.texExtent.width + : alignTo(region.texExtent.height, blockSize.height); + stride.width = region.buffStride > 0 ? region.buffStride : extent.width; + stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height; + + const destWidth = (region.texExtent.width + offset.x === (gpuTexture.width >> mipLevel)) ? region.texExtent.width : extent.width; + const destHeight = (region.texExtent.height + offset.y === (gpuTexture.height >> mipLevel)) ? region.texExtent.height : extent.height; + + let pixels : ArrayBufferView; + const buffer = buffers[n++]; + if (stride.width === extent.width && stride.height === extent.height) { + pixels = new ArrayBufferCtor(buffer.buffer, buffer.byteOffset + region.buffOffset); + } else { + pixels = pixelBufferPick(buffer, gpuTexture.format, region.buffOffset, stride, extent); + } - const pixels = buffers[n++]; if (!isCompressed) { - gl.texSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, gpuTexture.glType, pixels); + gl.texSubImage2D(gl.TEXTURE_2D, mipLevel, + offset.x, offset.y, + destWidth, destHeight, + gpuTexture.glFormat, gpuTexture.glType, + pixels); } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL && !device.extensions.noCompressedTexSubImage2D) { - gl.compressedTexSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, pixels); + gl.compressedTexSubImage2D(gl.TEXTURE_2D, mipLevel, + offset.x, offset.y, + destWidth, destHeight, + gpuTexture.glFormat, + pixels); } else { // WEBGL_compressed_texture_etc1 - gl.compressedTexImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, - gpuTexture.glInternalFmt, w, h, 0, pixels); + gl.compressedTexImage2D(gl.TEXTURE_2D, mipLevel, + gpuTexture.glInternalFmt, + destWidth, destHeight, 0, + pixels); } } - break; } case gl.TEXTURE_CUBE_MAP: { for (let i = 0; i < regions.length; i++) { const region = regions[i]; + const mipLevel = region.texSubres.mipLevel; + + offset.x = region.texOffset.x === 0 ? 0 : alignTo(region.texOffset.x, blockSize.width); + offset.y = region.texOffset.y === 0 ? 0 : alignTo(region.texOffset.y, blockSize.height); + extent.width = region.texExtent.width < blockSize.width ? region.texExtent.width : alignTo(region.texExtent.width, blockSize.width); + extent.height = region.texExtent.height < blockSize.height ? region.texExtent.width + : alignTo(region.texExtent.height, blockSize.height); + stride.width = region.buffStride > 0 ? region.buffStride : extent.width; + stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height; + + const destWidth = (region.texExtent.width + offset.x === (gpuTexture.width >> mipLevel)) ? region.texExtent.width : extent.width; + const destHeight = (region.texExtent.height + offset.y === (gpuTexture.height >> mipLevel)) ? region.texExtent.height : extent.height; + const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { - w = region.texExtent.width; - h = region.texExtent.height; - // console.debug('Copying buffer to texture cube: ' + w + ' x ' + h); + let pixels: ArrayBufferView; + const buffer = buffers[n++]; + if (stride.width === extent.width && stride.height === extent.height) { + pixels = new ArrayBufferCtor(buffer.buffer, buffer.byteOffset + region.buffOffset); + } else { + pixels = pixelBufferPick(buffer, gpuTexture.format, region.buffOffset, stride, extent); + } - const pixels = buffers[n++]; if (!isCompressed) { - gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, gpuTexture.glType, pixels); + gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, mipLevel, + offset.x, offset.y, + destWidth, destHeight, + gpuTexture.glFormat, gpuTexture.glType, + pixels); } else if (gpuTexture.glInternalFmt !== WebGLEXT.COMPRESSED_RGB_ETC1_WEBGL && !device.extensions.noCompressedTexSubImage2D) { - gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, pixels); + gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, mipLevel, + offset.x, offset.y, + destWidth, destHeight, + gpuTexture.glFormat, + pixels); } else { // WEBGL_compressed_texture_etc1 - gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, - gpuTexture.glInternalFmt, w, h, 0, pixels); + gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, mipLevel, + gpuTexture.glInternalFmt, + destWidth, destHeight, 0, + pixels); } } } diff --git a/cocos/core/gfx/webgl/webgl-device.ts b/cocos/core/gfx/webgl/webgl-device.ts index b038786ec1..4a27a6c226 100644 --- a/cocos/core/gfx/webgl/webgl-device.ts +++ b/cocos/core/gfx/webgl/webgl-device.ts @@ -56,11 +56,12 @@ import { CommandBufferType, ShaderInfo, QueueInfo, CommandBufferInfo, DescriptorSetInfo, DescriptorSetLayoutInfo, FramebufferInfo, InputAssemblerInfo, PipelineLayoutInfo, RenderPassInfo, SamplerInfo, TextureInfo, TextureViewInfo, BufferInfo, BufferViewInfo, DeviceInfo, TextureBarrierInfo, GeneralBarrierInfo, - QueueType, API, Feature, BufferTextureCopy, SwapchainInfo, FormatFeature, FormatFeatureBit, Format, + BufferBarrierInfo, QueueType, API, Feature, BufferTextureCopy, SwapchainInfo, FormatFeature, FormatFeatureBit, Format, } from '../base/define'; import { WebGLCmdFuncCopyBuffersToTexture, WebGLCmdFuncCopyTextureToBuffers, WebGLCmdFuncCopyTexImagesToTexture } from './webgl-commands'; import { GeneralBarrier } from '../base/states/general-barrier'; import { TextureBarrier } from '../base/states/texture-barrier'; +import { BufferBarrier } from '../base/states/buffer-barrier'; import { debug } from '../../platform/debug'; import { Swapchain } from '../base/swapchain'; import { IWebGLExtensions, WebGLDeviceManager } from './webgl-define'; @@ -514,6 +515,14 @@ export class WebGLDevice extends Device { return this._textureBarriers.get(hash)!; } + public getBufferBarrier (info: Readonly) { + const hash = BufferBarrier.computeHash(info); + if (!this._bufferBarriers.has(hash)) { + this._bufferBarriers.set(hash, new BufferBarrier(info, hash)); + } + return this._bufferBarriers.get(hash)!; + } + public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly) { WebGLCmdFuncCopyBuffersToTexture( this, diff --git a/cocos/core/gfx/webgl2/webgl2-command-buffer.ts b/cocos/core/gfx/webgl2/webgl2-command-buffer.ts index f93bf6914f..33656f5182 100644 --- a/cocos/core/gfx/webgl2/webgl2-command-buffer.ts +++ b/cocos/core/gfx/webgl2/webgl2-command-buffer.ts @@ -58,6 +58,7 @@ import { RenderPass } from '../base/render-pass'; import { WebGL2RenderPass } from './webgl2-render-pass'; import { GeneralBarrier } from '../base/states/general-barrier'; import { TextureBarrier } from '../base/states/texture-barrier'; +import { BufferBarrier } from '../base/states/buffer-barrier'; import { WebGL2DeviceManager } from './webgl2-define'; export class WebGL2CommandBuffer extends CommandBuffer { @@ -407,7 +408,9 @@ export class WebGL2CommandBuffer extends CommandBuffer { } } - public pipelineBarrier (GeneralBarrier: Readonly | null, textureBarriers?: Readonly, + public pipelineBarrier (GeneralBarrier: Readonly, bufferBarriers?: Readonly, + buffers?: Readonly, + textureBarriers?: Readonly, textures?: Readonly) {} protected bindStates () { diff --git a/cocos/core/gfx/webgl2/webgl2-commands.ts b/cocos/core/gfx/webgl2/webgl2-commands.ts index 5cdc2665ff..eca17610e6 100644 --- a/cocos/core/gfx/webgl2/webgl2-commands.ts +++ b/cocos/core/gfx/webgl2/webgl2-commands.ts @@ -30,6 +30,11 @@ import { FormatInfos, FormatSize, LoadOp, MemoryUsageBit, SampleCount, ShaderStageFlagBit, TextureFlagBit, Color, Rect, BufferTextureCopy, BufferSource, DrawInfo, IndirectBuffer, UniformBlock, DynamicStates, UniformSamplerTexture, + alignTo, + Extent, + formatAlignment, + getTypedArrayConstructor, + Offset, } from '../base/define'; import { WebGL2EXT } from './webgl2-define'; import { WebGL2CommandAllocator } from './webgl2-command-allocator'; @@ -2625,6 +2630,41 @@ export function WebGL2CmdFuncCopyTexImagesToTexture ( } } +let stagingBuffer = new Uint8Array(1); +function pixelBufferPick (buffer: ArrayBufferView, + format: Format, + offset: number, + stride: Extent, + extent: Extent): ArrayBufferView { + const blockHeight = formatAlignment(format).height; + + const bufferSize = FormatSize(format, extent.width, extent.height, extent.depth); + const rowStrideSize = FormatSize(format, stride.width, 1, 1); + const sliceStrideSize = FormatSize(format, stride.width, stride.height, 1); + const destRowSize = FormatSize(format, extent.width, 1, 1); + + const ArrayBufferCtor: TypedArrayConstructor = getTypedArrayConstructor(FormatInfos[format]); + + if (stagingBuffer.byteLength < bufferSize) { + stagingBuffer = new Uint8Array(bufferSize); + } + + let destOffset = 0; + let bufferOffset = offset; + + for (let i = 0; i < extent.depth; i++) { + bufferOffset = offset + sliceStrideSize * i; + for (let j = 0; j < extent.height; j += blockHeight) { + stagingBuffer.subarray(destOffset, destOffset + destRowSize).set( + new Uint8Array(buffer.buffer, buffer.byteOffset + bufferOffset, destRowSize), + ); + destOffset += destRowSize; + bufferOffset += rowStrideSize; + } + } + return new ArrayBufferCtor(stagingBuffer.buffer); +} + export function WebGL2CmdFuncCopyBuffersToTexture ( device: WebGL2Device, buffers: Readonly, @@ -2639,30 +2679,157 @@ export function WebGL2CmdFuncCopyBuffersToTexture ( } let n = 0; - let w = 1; - let h = 1; let f = 0; const fmtInfo: FormatInfo = FormatInfos[gpuTexture.format]; + const ArrayBufferCtor: TypedArrayConstructor = getTypedArrayConstructor(fmtInfo); const { isCompressed } = fmtInfo; + const blockSize = formatAlignment(gpuTexture.format); + + const extent: Extent = new Extent(); + const offset: Offset = new Offset(); + const stride: Extent = new Extent(); + switch (gpuTexture.glTarget) { case gl.TEXTURE_2D: { for (let k = 0; k < regions.length; k++) { const region = regions[k]; - w = region.texExtent.width; - h = region.texExtent.height; - const pixels = buffers[n++]; + const mipLevel = region.texSubres.mipLevel; + + offset.x = region.texOffset.x === 0 ? 0 : alignTo(region.texOffset.x, blockSize.width); + offset.y = region.texOffset.y === 0 ? 0 : alignTo(region.texOffset.y, blockSize.height); + extent.width = region.texExtent.width < blockSize.width ? region.texExtent.width : alignTo(region.texExtent.width, blockSize.width); + extent.height = region.texExtent.height < blockSize.height ? region.texExtent.width + : alignTo(region.texExtent.height, blockSize.height); + stride.width = region.buffStride > 0 ? region.buffStride : extent.width; + stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height; + + const destWidth = (region.texExtent.width + offset.x === (gpuTexture.width >> mipLevel)) ? region.texExtent.width : extent.width; + const destHeight = (region.texExtent.height + offset.y === (gpuTexture.height >> mipLevel)) ? region.texExtent.height : extent.height; + + let pixels: ArrayBufferView; + const buffer = buffers[n++]; + if (stride.width === extent.width && stride.height === extent.height) { + pixels = new ArrayBufferCtor(buffer.buffer, buffer.byteOffset + region.buffOffset); + } else { + pixels = pixelBufferPick(buffer, gpuTexture.format, region.buffOffset, stride, extent); + } + if (!isCompressed) { - gl.texSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, gpuTexture.glType, pixels); + gl.texSubImage2D(gl.TEXTURE_2D, mipLevel, + offset.x, offset.y, + destWidth, destHeight, + gpuTexture.glFormat, gpuTexture.glType, + pixels); } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) { - gl.compressedTexSubImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, pixels); + gl.compressedTexSubImage2D(gl.TEXTURE_2D, mipLevel, + offset.x, offset.y, + destWidth, destHeight, + gpuTexture.glFormat, + pixels); } else { // WEBGL_compressed_texture_etc1 - gl.compressedTexImage2D(gl.TEXTURE_2D, region.texSubres.mipLevel, - gpuTexture.glInternalFmt, w, h, 0, pixels); + gl.compressedTexImage2D(gl.TEXTURE_2D, mipLevel, + gpuTexture.glInternalFmt, + destWidth, destHeight, 0, + pixels); + } + } + break; + } + case gl.TEXTURE_2D_ARRAY: { + for (let k = 0; k < regions.length; k++) { + const region = regions[k]; + const mipLevel = region.texSubres.mipLevel; + + offset.x = region.texOffset.x === 0 ? 0 : alignTo(region.texOffset.x, blockSize.width); + offset.y = region.texOffset.y === 0 ? 0 : alignTo(region.texOffset.y, blockSize.height); + extent.width = region.texExtent.width < blockSize.width ? region.texExtent.width : alignTo(region.texExtent.width, blockSize.width); + extent.height = region.texExtent.height < blockSize.height ? region.texExtent.width + : alignTo(region.texExtent.height, blockSize.height); + extent.depth = 1; + stride.width = region.buffStride > 0 ? region.buffStride : extent.width; + stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height; + + const destWidth = (region.texExtent.width + offset.x === (gpuTexture.width >> mipLevel)) ? region.texExtent.width : extent.width; + const destHeight = (region.texExtent.height + offset.y === (gpuTexture.height >> mipLevel)) ? region.texExtent.height : extent.height; + + const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; + for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { + offset.z = f; + + let pixels: ArrayBufferView; + const buffer = buffers[n++]; + if (stride.width === extent.width && stride.height === extent.height) { + pixels = new ArrayBufferCtor(buffer.buffer, buffer.byteOffset + region.buffOffset); + } else { + pixels = pixelBufferPick(buffer, gpuTexture.format, region.buffOffset, stride, extent); + } + + if (!isCompressed) { + gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, mipLevel, + offset.x, offset.y, offset.z, + destWidth, destHeight, extent.depth, + gpuTexture.glFormat, gpuTexture.glType, + pixels); + } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) { + gl.compressedTexSubImage3D(gl.TEXTURE_2D_ARRAY, mipLevel, + offset.x, offset.y, offset.z, + destWidth, destHeight, extent.depth, + gpuTexture.glFormat, + pixels); + } else { // WEBGL_compressed_texture_etc1 + gl.compressedTexImage3D(gl.TEXTURE_2D_ARRAY, mipLevel, + gpuTexture.glInternalFmt, + destWidth, destHeight, extent.depth, 0, + pixels); + } + } + } + break; + } + case gl.TEXTURE_3D: { + for (let k = 0; k < regions.length; k++) { + const region = regions[k]; + const mipLevel = region.texSubres.mipLevel; + + offset.x = region.texOffset.x === 0 ? 0 : alignTo(region.texOffset.x, blockSize.width); + offset.y = region.texOffset.y === 0 ? 0 : alignTo(region.texOffset.y, blockSize.height); + offset.z = region.texOffset.z; + extent.width = region.texExtent.width < blockSize.width ? region.texExtent.width : alignTo(region.texExtent.width, blockSize.width); + extent.height = region.texExtent.height < blockSize.height ? region.texExtent.width + : alignTo(region.texExtent.height, blockSize.height); + extent.depth = region.texExtent.depth; + stride.width = region.buffStride > 0 ? region.buffStride : extent.width; + stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height; + + const destWidth = (region.texExtent.width + offset.x === (gpuTexture.width >> mipLevel)) ? region.texExtent.width : extent.width; + const destHeight = (region.texExtent.height + offset.y === (gpuTexture.height >> mipLevel)) ? region.texExtent.height : extent.height; + + let pixels: ArrayBufferView; + const buffer = buffers[n++]; + if (stride.width === extent.width && stride.height === extent.height) { + pixels = new ArrayBufferCtor(buffer.buffer, buffer.byteOffset + region.buffOffset); + } else { + pixels = pixelBufferPick(buffer, gpuTexture.format, region.buffOffset, stride, extent); + } + + if (!isCompressed) { + gl.texSubImage3D(gl.TEXTURE_2D_ARRAY, mipLevel, + offset.x, offset.y, offset.z, + destWidth, destHeight, extent.depth, + gpuTexture.glFormat, gpuTexture.glType, + pixels); + } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) { + gl.compressedTexSubImage3D(gl.TEXTURE_2D_ARRAY, mipLevel, + offset.x, offset.y, offset.z, + destWidth, destHeight, extent.depth, + gpuTexture.glFormat, + pixels); + } else { // WEBGL_compressed_texture_etc1 + gl.compressedTexImage3D(gl.TEXTURE_2D_ARRAY, mipLevel, + gpuTexture.glInternalFmt, + destWidth, destHeight, extent.depth, 0, + pixels); } } break; @@ -2670,24 +2837,46 @@ export function WebGL2CmdFuncCopyBuffersToTexture ( case gl.TEXTURE_CUBE_MAP: { for (let k = 0; k < regions.length; k++) { const region = regions[k]; + const mipLevel = region.texSubres.mipLevel; + + offset.x = region.texOffset.x === 0 ? 0 : alignTo(region.texOffset.x, blockSize.width); + offset.y = region.texOffset.y === 0 ? 0 : alignTo(region.texOffset.y, blockSize.height); + extent.width = region.texExtent.width < blockSize.width ? region.texExtent.width : alignTo(region.texExtent.width, blockSize.width); + extent.height = region.texExtent.height < blockSize.height ? region.texExtent.width + : alignTo(region.texExtent.height, blockSize.height); + stride.width = region.buffStride > 0 ? region.buffStride : extent.width; + stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height; + + const destWidth = (region.texExtent.width + offset.x === (gpuTexture.width >> mipLevel)) ? region.texExtent.width : extent.width; + const destHeight = (region.texExtent.height + offset.y === (gpuTexture.height >> mipLevel)) ? region.texExtent.height : extent.height; + const fcount = region.texSubres.baseArrayLayer + region.texSubres.layerCount; for (f = region.texSubres.baseArrayLayer; f < fcount; ++f) { - w = region.texExtent.width; - h = region.texExtent.height; - - const pixels = buffers[n++]; + let pixels: ArrayBufferView; + const buffer = buffers[n++]; + if (stride.width === extent.width && stride.height === extent.height) { + pixels = new ArrayBufferCtor(buffer.buffer, buffer.byteOffset + region.buffOffset); + } else { + pixels = pixelBufferPick(buffer, gpuTexture.format, region.buffOffset, stride, extent); + } if (!isCompressed) { - gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, gpuTexture.glType, pixels); + gl.texSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, mipLevel, + offset.x, offset.y, + destWidth, destHeight, + gpuTexture.glFormat, gpuTexture.glType, + pixels); } else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL) { - gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, - region.texOffset.x, region.texOffset.y, w, h, - gpuTexture.glFormat, pixels); + gl.compressedTexSubImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, mipLevel, + offset.x, offset.y, + destWidth, destHeight, + gpuTexture.glFormat, + pixels); } else { // WEBGL_compressed_texture_etc1 - gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, region.texSubres.mipLevel, - gpuTexture.glInternalFmt, w, h, 0, pixels); + gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + f, mipLevel, + gpuTexture.glInternalFmt, + destWidth, destHeight, 0, + pixels); } } } diff --git a/cocos/core/gfx/webgl2/webgl2-device.ts b/cocos/core/gfx/webgl2/webgl2-device.ts index ec51c2985d..77c84fddeb 100644 --- a/cocos/core/gfx/webgl2/webgl2-device.ts +++ b/cocos/core/gfx/webgl2/webgl2-device.ts @@ -56,11 +56,12 @@ import { CommandBufferType, DescriptorSetLayoutInfo, DescriptorSetInfo, PipelineLayoutInfo, BufferViewInfo, CommandBufferInfo, BufferInfo, FramebufferInfo, InputAssemblerInfo, QueueInfo, RenderPassInfo, SamplerInfo, ShaderInfo, TextureInfo, TextureViewInfo, DeviceInfo, GeneralBarrierInfo, TextureBarrierInfo, - QueueType, API, Feature, BufferTextureCopy, SwapchainInfo, FormatFeature, Format, FormatFeatureBit, + BufferBarrierInfo, QueueType, API, Feature, BufferTextureCopy, SwapchainInfo, FormatFeature, Format, FormatFeatureBit, } from '../base/define'; import { WebGL2CmdFuncCopyTextureToBuffers, WebGL2CmdFuncCopyBuffersToTexture, WebGL2CmdFuncCopyTexImagesToTexture } from './webgl2-commands'; import { GeneralBarrier } from '../base/states/general-barrier'; import { TextureBarrier } from '../base/states/texture-barrier'; +import { BufferBarrier } from '../base/states/buffer-barrier'; import { debug } from '../../platform/debug'; import { Swapchain } from '../base/swapchain'; import { IWebGL2Extensions, WebGL2DeviceManager } from './webgl2-define'; @@ -290,8 +291,7 @@ export class WebGL2Device extends Device { this._formatFeatures[Format.RGB16F] = tempFeature; this._formatFeatures[Format.RGBA16F] = tempFeature; - tempFeature = FormatFeatureBit.RENDER_TARGET | FormatFeatureBit.STORAGE_TEXTURE - | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.VERTEX_ATTRIBUTE; + tempFeature = FormatFeatureBit.STORAGE_TEXTURE | FormatFeatureBit.SAMPLED_TEXTURE | FormatFeatureBit.VERTEX_ATTRIBUTE; this._formatFeatures[Format.R32F] = tempFeature; this._formatFeatures[Format.RG32F] = tempFeature; @@ -369,6 +369,10 @@ export class WebGL2Device extends Device { this._textureExclusive[Format.DEPTH_STENCIL] = false; if (exts.EXT_color_buffer_float) { + this._formatFeatures[Format.R32F] |= FormatFeatureBit.RENDER_TARGET; + this._formatFeatures[Format.RG32F] |= FormatFeatureBit.RENDER_TARGET; + this._formatFeatures[Format.RGBA32F] |= FormatFeatureBit.RENDER_TARGET; + this._textureExclusive[Format.R32F] = false; this._textureExclusive[Format.RG32F] = false; this._textureExclusive[Format.RGBA32F] = false; @@ -565,6 +569,14 @@ export class WebGL2Device extends Device { return this._textureBarriers.get(hash)!; } + public getBufferBarrier (info: Readonly) { + const hash = BufferBarrier.computeHash(info); + if (!this._bufferBarriers.has(hash)) { + this._bufferBarriers.set(hash, new BufferBarrier(info, hash)); + } + return this._bufferBarriers.get(hash)!; + } + public copyBuffersToTexture (buffers: Readonly, texture: Texture, regions: Readonly) { WebGL2CmdFuncCopyBuffersToTexture( this, diff --git a/cocos/core/global-exports.ts b/cocos/core/global-exports.ts index 2f0b621123..39aa7ba926 100644 --- a/cocos/core/global-exports.ts +++ b/cocos/core/global-exports.ts @@ -23,33 +23,7 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ - -import { - ALIPAY, - BAIDU, - BUILD, - COCOSPLAY, - DEBUG, - DEV, - EDITOR, - JSB, - MINIGAME, - PREVIEW, - RUNTIME_BASED, - SUPPORT_JIT, - TEST, - BYTEDANCE, - WECHAT, - XIAOMI, - HUAWEI, - OPPO, - VIVO, - EXPORT_TO_GLOBAL, -} from 'internal:constants'; +import { DEV } from 'internal:constants'; const _global = typeof window === 'undefined' ? global : window; @@ -69,106 +43,6 @@ export const legacyCC: Record & { // For internal usage legacyCC.internal = {}; -if (EXPORT_TO_GLOBAL) { - // Supports dynamically access from external scripts such as adapters and debugger. - // So macros should still defined in global even if inlined in engine. - /** - * @en The pre-compilation constant for code tree shaking: CC_BUILD (Available for built package) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_BUILD(在构建后生效) - */ - _global.CC_BUILD = BUILD; - /** - * @en The pre-compilation constant for code tree shaking: CC_TEST (Available for ci test environment) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_TEST(在 CI 测试环境下生效) - */ - _global.CC_TEST = TEST; - /** - * @en The pre-compilation constant for code tree shaking: CC_EDITOR (Available for editor environment) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_EDITOR(在编辑器环境下生效) - */ - _global.CC_EDITOR = EDITOR; - /** - * @en The pre-compilation constant for code tree shaking: CC_PREVIEW (Available for preview) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_PREVIEW(预览时生效) - */ - _global.CC_PREVIEW = PREVIEW; - /** - * @en The pre-compilation constant for code tree shaking: CC_DEV (Internal) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_DEV(内部使用) - */ - _global.CC_DEV = DEV; - /** - * @en The pre-compilation constant for code tree shaking: CC_DEBUG (Available for debug environment) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_DEBUG(在调试模式下生效) - */ - _global.CC_DEBUG = DEBUG; - /** - * @en The pre-compilation constant for code tree shaking: CC_JSB (Available for native application environment) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_JSB(在原生应用环境下生效) - */ - _global.CC_JSB = JSB; - /** - * @en The pre-compilation constant for code tree shaking: CC_BYTEDANCE (Available for Bytedance platform) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_BYTEDANCE(在字节平台上生效) - */ - _global.CC_BYTEDANCE = BYTEDANCE; - /** - * @en The pre-compilation constant for code tree shaking: CC_WECHAT (Available for Wechat mini game platform) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_WECHAT(在微信小游戏平台上生效) - */ - _global.CC_WECHAT = WECHAT; - /** - * @en The pre-compilation constant for code tree shaking: CC_ALIPAY (Available for Alipay mini game platform) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_ALIPAY(在支付宝小游戏平台上生效) - */ - _global.CC_ALIPAY = ALIPAY; - /** - * @en The pre-compilation constant for code tree shaking: CC_XIAOMI (Available for MI mini game platform) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_XIAOMI(在小米小游戏平台上生效) - */ - _global.CC_XIAOMI = XIAOMI; - /** - * @en The pre-compilation constant for code tree shaking: CC_BAIDU (Available for Baidu mini game platform) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_BAIDU(在百度小游戏平台上生效) - */ - _global.CC_BAIDU = BAIDU; - /** - * @en The pre-compilation constant for code tree shaking: CC_COCOSPLAY (Available for Cocos Play platform) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_COCOSPLAY(在 CocosPlay 小游戏平台上生效) - */ - _global.CC_COCOSPLAY = COCOSPLAY; - /** - * @en The pre-compilation constant for code tree shaking: CC_HUAWEI (Available for Huawei mini game platform) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_HUAWEI(在华为快游戏平台上生效) - */ - _global.CC_HUAWEI = HUAWEI; - /** - * @en The pre-compilation constant for code tree shaking: CC_OPPO (Available for OPPO mini game platform) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_OPPO(在 OPPO 小游戏平台上生效) - */ - _global.CC_OPPO = OPPO; - /** - * @en The pre-compilation constant for code tree shaking: CC_VIVO (Available for Vivo mini game platform) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_VIVO(在 Vivo 小游戏平台上生效) - */ - _global.CC_VIVO = VIVO; - /** - * @en The pre-compilation constant for code tree shaking: CC_MINIGAME (Available for general mini game platforms) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_MINIGAME(在各个小游戏平台上生效) - */ - _global.CC_MINIGAME = MINIGAME; - /** - * @en The pre-compilation constant for code tree shaking: CC_RUNTIME_BASED (Available for Huawei, OPPO, Vivo and Cocos Play) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_RUNTIME_BASED(在华为、OPPO、Vivo 和 CocosPlay 平台上生效) - */ - _global.CC_RUNTIME_BASED = RUNTIME_BASED; - /** - * @en The pre-compilation constant for code tree shaking: CC_SUPPORT_JIT (Available for platforms support JIT) - * @zh 预编译宏变量,通常用来做平台或环境相关自动代码剔除:CC_SUPPORT_JIT(在支持 JIT 的平台上生效) - */ - _global.CC_SUPPORT_JIT = SUPPORT_JIT; -} - if (DEV) { legacyCC._Test = {}; } diff --git a/cocos/core/index.ts b/cocos/core/index.ts index c42480ff17..308a71d09f 100644 --- a/cocos/core/index.ts +++ b/cocos/core/index.ts @@ -23,10 +23,7 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ + import { legacyCC, VERSION } from './global-exports'; import * as geometry from './geometry'; @@ -51,6 +48,7 @@ export * from './event'; export * from './assets'; export * from './platform'; export * from './game'; +export { Root } from './root'; export * from './scheduler'; export * from './director'; @@ -61,3 +59,4 @@ export * from './scene-graph'; export * from './components'; export * from './builtin'; export * from './curves'; +export * from './settings'; diff --git a/cocos/core/legacy.ts b/cocos/core/legacy.ts index 9813310f6b..756b1aab93 100644 --- a/cocos/core/legacy.ts +++ b/cocos/core/legacy.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import * as debug from './platform/debug'; import { _normalize, basename, changeBasename, changeExtname, dirname, extname, getSeperator, join, mainFileName, stripSep } from './utils/path'; import { legacyCC } from './global-exports'; diff --git a/cocos/core/math/affine-transform.ts b/cocos/core/math/affine-transform.ts index 7f9d03f60f..e810dc1cc0 100644 --- a/cocos/core/math/affine-transform.ts +++ b/cocos/core/math/affine-transform.ts @@ -25,11 +25,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core/math - */ - import { Mat4 } from './mat4'; import { Rect } from './rect'; import { Size } from './size'; diff --git a/cocos/core/math/bits.ts b/cocos/core/math/bits.ts index 4b76fd9202..4ab94bba59 100644 --- a/cocos/core/math/bits.ts +++ b/cocos/core/math/bits.ts @@ -23,12 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * 数学库 - * @module core/math/bits - */ - /** * Bit twiddling hacks for JavaScript. * @@ -38,9 +32,26 @@ * http://graphics.stanford.edu/~seander/bithacks.html */ -// Number of bits in an integer +/** + * @en + * Number of bits in an integer + * @zh + * 整型类型的 bit 数 + */ export const INT_BITS = 32; +/** + * @en + * The maximal signed integer number + * @zh + * 最大有符号整型数 + */ export const INT_MAX = 0x7fffffff; +/** + * @en + * The minimal signed integer number + * @zh + * 最小有符号整型数 + */ export const INT_MIN = -1 << (INT_BITS - 1); /** @@ -109,8 +120,8 @@ export function log10 (v: number) { } /** - * @zh Counts number of bits. - * @en 计算传入数字二进制表示中 1 的数量。 + * @en Counts number of bits. + * @zh 计算传入数字二进制表示中 1 的数量。 */ export function popCount (v: number) { v -= ((v >>> 1) & 0x55555555); @@ -261,8 +272,8 @@ export function interleave3 (x: number, y: number, z: number) { } /** - * @zh Extracts nth interleaved component of a 3-tuple. - * @en 提取三个数字中的第n个交错分量。 + * @en Extracts nth interleaved component of a 3-tuple. + * @zh 提取三个数字中的第n个交错分量。 */ export function deinterleave3 (v: number, n: number) { v = (v >>> n) & 1227133513; diff --git a/cocos/core/math/category.json b/cocos/core/math/category.json index 563e1aff78..5d59f0d3bb 100644 --- a/cocos/core/math/category.json +++ b/cocos/core/math/category.json @@ -4,7 +4,7 @@ "en": "Math" }, "description": { - "zh": "数学", - "en": "Math" + "zh": "数学库,包含 2D 与 3D 维度下的向量和矩阵运算,与其他一些相关数学类型", + "en": "Mathematical library, including vector and matrix operations in two dimensions and three dimensions, also including some other mathematic related classes." } } \ No newline at end of file diff --git a/cocos/core/math/color.ts b/cocos/core/math/color.ts index bf89638994..1a5f826ffb 100644 --- a/cocos/core/math/color.ts +++ b/cocos/core/math/color.ts @@ -24,18 +24,12 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core/math - */ - import { CCClass } from '../data/class'; import { ValueType } from '../value-types/value-type'; import { IColorLike } from './type-define'; import { clamp, EPSILON } from './utils'; import { legacyCC } from '../global-exports'; import { mixin } from '../utils/js-typed'; -import { JSB } from '../default-constants'; const toFloat = 1 / 255; @@ -303,7 +297,7 @@ export class Color extends ValueType { set w (value) { this.a = value * 255; } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _val = 0; @@ -654,7 +648,7 @@ export class Color extends ValueType { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _set_r_unsafe (red) { this._val = ((this._val & 0xffffff00) | red) >>> 0; @@ -662,7 +656,7 @@ export class Color extends ValueType { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _set_g_unsafe (green) { this._val = ((this._val & 0xffff00ff) | (green << 8)) >>> 0; @@ -670,7 +664,7 @@ export class Color extends ValueType { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _set_b_unsafe (blue) { this._val = ((this._val & 0xff00ffff) | (blue << 16)) >>> 0; @@ -678,7 +672,7 @@ export class Color extends ValueType { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _set_a_unsafe (alpha) { this._val = ((this._val & 0x00ffffff) | (alpha << 24)) >>> 0; diff --git a/cocos/core/math/deprecated.ts b/cocos/core/math/deprecated.ts index 134f6bc58d..55b3bf8a4e 100644 --- a/cocos/core/math/deprecated.ts +++ b/cocos/core/math/deprecated.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { removeProperty, replaceProperty } from '../utils/x-deprecated'; import { Color } from './color'; import { Mat3 } from './mat3'; diff --git a/cocos/core/math/index.ts b/cocos/core/math/index.ts index d2bc048233..0568754fcd 100644 --- a/cocos/core/math/index.ts +++ b/cocos/core/math/index.ts @@ -24,8 +24,6 @@ THE SOFTWARE. */ - - import * as bits from './bits'; import './deprecated'; diff --git a/cocos/core/math/mat3.ts b/cocos/core/math/mat3.ts index 802c538e7a..4120097593 100644 --- a/cocos/core/math/mat3.ts +++ b/cocos/core/math/mat3.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core/math - */ - import { CCClass } from '../data/class'; import { ValueType } from '../value-types/value-type'; import { Quat } from './quat'; @@ -726,7 +721,7 @@ export class Mat3 extends ValueType { * @param other Specified matrix * @return this */ - public set (other: Mat3); + public set (other: Mat3): Mat3; /** * @en Set the matrix with values of all elements @@ -735,7 +730,7 @@ export class Mat3 extends ValueType { */ public set (m00?: number, m01?: number, m02?: number, m03?: number, m04?: number, m05?: number, - m06?: number, m07?: number, m08?: number); + m06?: number, m07?: number, m08?: number): Mat3; public set (m00: number | Mat3 = 1, m01 = 0, m02 = 0, m03 = 0, m04 = 1, m05 = 0, diff --git a/cocos/core/math/mat4.ts b/cocos/core/math/mat4.ts index 60aad5b1e5..64c32e5f9b 100644 --- a/cocos/core/math/mat4.ts +++ b/cocos/core/math/mat4.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core/math - */ - import { CCClass } from '../data/class'; import { ValueType } from '../value-types/value-type'; import { Mat3 } from './mat3'; @@ -325,7 +320,6 @@ export class Mat4 extends ValueType { * @zh 在给定矩阵变换基础上加入新位移变换 */ public static translate (out: Out, a: Out, v: VecLike) { - console.warn('function changed'); if (a === out) { out.m12 += v.x; out.m13 += v.y; @@ -1549,7 +1543,7 @@ export class Mat4 extends ValueType { * @param other Specified matrix. * @return this */ - public set (other: Mat4); + public set (other: Mat4): Mat4; /** * @en Set the matrix with values of all elements @@ -1560,7 +1554,7 @@ export class Mat4 extends ValueType { m00?: number, m01?: number, m02?: number, m03?: number, m04?: number, m05?: number, m06?: number, m07?: number, m08?: number, m09?: number, m10?: number, m11?: number, - m12?: number, m13?: number, m14?: number, m15?: number); + m12?: number, m13?: number, m14?: number, m15?: number): Mat4; public set (m00: Mat4 | number = 1, m01 = 0, m02 = 0, m03 = 0, m04 = 0, m05 = 1, m06 = 0, m07 = 0, @@ -1905,7 +1899,6 @@ export class Mat4 extends ValueType { * @param vec vector to translate by */ public translate (vec: Vec3) { - console.warn('function changed'); this.m12 += vec.x; this.m13 += vec.y; this.m14 += vec.z; diff --git a/cocos/core/math/quat.ts b/cocos/core/math/quat.ts index d6965d89d3..7595124822 100644 --- a/cocos/core/math/quat.ts +++ b/cocos/core/math/quat.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core/math - */ - import { CCClass } from '../data/class'; import { ValueType } from '../value-types/value-type'; import { Mat3 } from './mat3'; diff --git a/cocos/core/math/rect.ts b/cocos/core/math/rect.ts index bc57640aa4..25f20c306a 100644 --- a/cocos/core/math/rect.ts +++ b/cocos/core/math/rect.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core/math - */ - import { CCClass } from '../data/class'; import { ValueType } from '../value-types/value-type'; import { Mat4 } from './mat4'; @@ -200,7 +195,7 @@ export class Rect extends ValueType { } /** - * @en Returns a new {{Vec2}} object representing the position of the rectangle + * @en Returns a new [[Vec2]] object representing the position of the rectangle * @zh 获取或设置矩形的 x 和 y 坐标。 */ get origin () { @@ -213,7 +208,7 @@ export class Rect extends ValueType { } /** - * @en Returns a new {{Size}} object represents the width and height of the rectangle + * @en Returns a new [[Size]] object represents the width and height of the rectangle * @zh 获取或设置矩形的尺寸。 */ get size () { @@ -447,7 +442,16 @@ export class Rect extends ValueType { } /** + * @en + * Applies a matrix transformation to the current rectangle and outputs the result to the four vertices. + * @zh * 应用矩阵变换到当前矩形,并将结果输出到四个顶点上。 + * + * @param mat The mat4 to apply + * @param out_lb The left bottom point + * @param out_lt The left top point + * @param out_rb The right bottom point + * @param out_rt The right top point */ public transformMat4ToPoints (mat: Mat4, out_lb: Vec2, out_lt: Vec2, out_rt: Vec2, out_rb: Vec2) { const ol = this.x; diff --git a/cocos/core/math/size.ts b/cocos/core/math/size.ts index 96252a29cf..9e8a88587b 100644 --- a/cocos/core/math/size.ts +++ b/cocos/core/math/size.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core/math - */ - import { CCClass } from '../data/class'; import { ValueType } from '../value-types/value-type'; import { ISizeLike } from './type-define'; diff --git a/cocos/core/math/type-define.ts b/cocos/core/math/type-define.ts index 9d630682ac..430fcea15a 100644 --- a/cocos/core/math/type-define.ts +++ b/cocos/core/math/type-define.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core/math - */ - export interface IColorLike { r: number; g: number; diff --git a/cocos/core/math/utils.ts b/cocos/core/math/utils.ts index c3af8a4322..b5fc723ce9 100644 --- a/cocos/core/math/utils.ts +++ b/cocos/core/math/utils.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core/math - */ - import { ValueType } from '../value-types'; import { IVec3Like } from './type-define'; @@ -146,7 +141,10 @@ export function randomRangeInt (min: number, max: number) { } /** - * Linear congruential generator using Hull-Dobell Theorem. + * @en + * Linear congruence generator using Hull-Dobell Theorem. + * @zh + * 使用 Hull-Dobell 算法的线性同余生成器构造伪随机数 * * @param seed The random seed. * @return The pseudo random. @@ -157,7 +155,10 @@ export function pseudoRandom (seed: number) { } /** + * @en * Returns a floating-point pseudo-random number between min (inclusive) and max (exclusive). + * @zh + * 返回一个在范围内的浮点伪随机数,注意,不包含边界值 * * @param seed * @param min @@ -181,18 +182,21 @@ export function pseudoRandomRangeInt (seed: number, min: number, max: number) { } /** + * @en * Returns the next power of two for the value.
+ * @zh + * 返回下一个最接近的 2 的幂 * * @param val * @return The the next power of two. */ export function nextPow2 (val: number) { --val; - val = (val >> 1) | val; - val = (val >> 2) | val; - val = (val >> 4) | val; - val = (val >> 8) | val; - val = (val >> 16) | val; + val |= (val >> 1); + val |= (val >> 2); + val |= (val >> 4); + val |= (val >> 8); + val |= (val >> 16); ++val; return val; } @@ -209,7 +213,10 @@ export function repeat (t: number, length: number) { } /** + * @en * Returns time wrapped in ping-pong mode. + * @zh + * 返回乒乓模式下的相对时间 * * @param t Time start at 0. * @param length Time of one cycle. @@ -234,9 +241,10 @@ export function inverseLerp (from: number, to: number, value: number) { } /** + * @en Compare the absolute values of all components and the component with the largest absolute value will be returned. * @zh 对所有分量的绝对值进行比较大小,返回绝对值最大的分量。 - * @param v 类 Vec3 结构 - * @returns 绝对值最大的分量 + * @param v vec3 like value + * @returns max absolute component */ export function absMaxComponent (v: IVec3Like) { if (Math.abs(v.x) > Math.abs(v.y)) { @@ -253,6 +261,7 @@ export function absMaxComponent (v: IVec3Like) { } /** + * @en Compare the absolute value of two values and return the value with the largest absolute value * @zh 对 a b 的绝对值进行比较大小,返回绝对值最大的值。 * @param a number * @param b number diff --git a/cocos/core/math/vec2.ts b/cocos/core/math/vec2.ts index af98a4c2eb..daff1dcde5 100644 --- a/cocos/core/math/vec2.ts +++ b/cocos/core/math/vec2.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core/math - */ - import { CCClass } from '../data/class'; import { ValueType } from '../value-types/value-type'; import { Mat4 } from './mat4'; @@ -475,7 +470,7 @@ export class Vec2 extends ValueType { * @param other Specified vector * @return `this` */ - public set (other: Vec2); + public set (other: Vec2): Vec2; /** * @en Set the value of each component of the current vector. @@ -484,7 +479,7 @@ export class Vec2 extends ValueType { * @param y y value * @return `this` */ - public set (x?: number, y?: number); + public set (x?: number, y?: number): Vec2; public set (x?: number | Vec2, y?: number) { if (x && typeof x === 'object') { diff --git a/cocos/core/math/vec3.ts b/cocos/core/math/vec3.ts index 3ad6f48342..e02b052f99 100644 --- a/cocos/core/math/vec3.ts +++ b/cocos/core/math/vec3.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core/math - */ - import { CCClass } from '../data/class'; import { ValueType } from '../value-types/value-type'; import { Mat4 } from './mat4'; @@ -719,7 +714,7 @@ export class Vec3 extends ValueType { * @param other Specified vector * @returns `this` */ - public set (other: Vec3); + public set (other: Vec3): Vec3; /** * @en Set the value of each component of the current vector. @@ -729,7 +724,7 @@ export class Vec3 extends ValueType { * @param z z value * @returns `this` */ - public set (x?: number, y?: number, z?: number); + public set (x?: number, y?: number, z?: number): Vec3; public set (x?: number | Vec3, y?: number, z?: number) { if (x && typeof x === 'object') { diff --git a/cocos/core/math/vec4.ts b/cocos/core/math/vec4.ts index 59334889e5..5023669a68 100644 --- a/cocos/core/math/vec4.ts +++ b/cocos/core/math/vec4.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core/math - */ - import { CCClass } from '../data/class'; import { ValueType } from '../value-types/value-type'; import { Mat4 } from './mat4'; @@ -538,7 +533,7 @@ export class Vec4 extends ValueType { * @param other Specified vector * @returns `this` */ - public set (other: Vec4); + public set (other: Vec4): Vec4; /** * @en Set the value of each component of the current vector. @@ -549,7 +544,7 @@ export class Vec4 extends ValueType { * @param w w value * @returns `this` */ - public set (x?: number, y?: number, z?: number, w?: number); + public set (x?: number, y?: number, z?: number, w?: number): Vec4; public set (x?: number | Vec4, y?: number, z?: number, w?: number) { if (x && typeof x === 'object') { diff --git a/cocos/core/memop/cached-array.ts b/cocos/core/memop/cached-array.ts index 2409b299da..1bfda8ce54 100644 --- a/cocos/core/memop/cached-array.ts +++ b/cocos/core/memop/cached-array.ts @@ -25,11 +25,6 @@ import { ScalableContainer } from './scalable-container'; -/** - * @packageDocumentation - * @module memop - */ - /** * @en * Cached array is a data structure for objects cache, it's designed for persistent data. diff --git a/cocos/core/memop/index.ts b/cocos/core/memop/index.ts index 0a18e3d10a..95c67962de 100644 --- a/cocos/core/memop/index.ts +++ b/cocos/core/memop/index.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - export * from './pool'; export * from './recycle-pool'; export * from './cached-array'; diff --git a/cocos/core/memop/pool.ts b/cocos/core/memop/pool.ts index 1a8572c06e..3aac1723b5 100644 --- a/cocos/core/memop/pool.ts +++ b/cocos/core/memop/pool.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module memop - */ - import { warnID } from '../platform/debug'; import { ScalableContainer } from './scalable-container'; diff --git a/cocos/core/memop/recycle-pool.ts b/cocos/core/memop/recycle-pool.ts index 85e8643fd0..7ba42726e5 100644 --- a/cocos/core/memop/recycle-pool.ts +++ b/cocos/core/memop/recycle-pool.ts @@ -25,11 +25,6 @@ import { ScalableContainer } from './scalable-container'; -/** - * @packageDocumentation - * @module memop - */ - /** * @en Recyclable object pool. It's designed to be entirely reused each time. * There is no put and get method, each time you get the [[data]], you can use all elements as new. diff --git a/cocos/core/memop/scalable-container.ts b/cocos/core/memop/scalable-container.ts index dcb4786f9a..1ddf85db25 100644 --- a/cocos/core/memop/scalable-container.ts +++ b/cocos/core/memop/scalable-container.ts @@ -22,11 +22,12 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ + import { containerManager } from './container-manager'; export abstract class ScalableContainer { /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _poolHandle = -1; constructor () { diff --git a/cocos/core/pipeline/batched-buffer.ts b/cocos/core/pipeline/batched-buffer.ts index 2849992d96..a2799763c9 100644 --- a/cocos/core/pipeline/batched-buffer.ts +++ b/cocos/core/pipeline/batched-buffer.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { BufferUsageBit, Format, MemoryUsageBit, Device, DescriptorSet, InputAssembler, InputAssemblerInfo, Attribute, Buffer, BufferInfo, Shader } from '../gfx'; import { Mat4 } from '../math'; diff --git a/cocos/core/pipeline/category.json b/cocos/core/pipeline/category.json new file mode 100644 index 0000000000..e454152422 --- /dev/null +++ b/cocos/core/pipeline/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "渲染管线", + "en": "Render Pipeline" + }, + "description": { + "zh": "RenderPipeline 用于控制场景的渲染流程,包括光照管理、物体剔除、渲染物体排序、渲染目标切换等。由于每个阶段对于不同项目来说可以有不同的优化处理方式,所以用统一的方法来处理不同类型项目的渲染流程很难达到最优化的结果。可定制化的渲染管线用于对渲染场景中的每个阶段进行更灵活的控制,可以针对不同的项目做更深层次的优化方案。", + "en": "RenderPipeline is used to control the rendering process of a scene, including lighting management, object culling, render object sorting, render target switching, etc. Since each stage can be handled differently and optimized for different projects, it is difficult to achieve optimal results with one uniform rendering process for different types of projects. The customizable render pipeline is used to provide more flexible control over each stage in the rendering process, allowing for deeper optimization solutions for different projects." + } +} \ No newline at end of file diff --git a/cocos/core/pipeline/custom/compiler.ts b/cocos/core/pipeline/custom/compiler.ts index 74c275850e..57c2a8b161 100644 --- a/cocos/core/pipeline/custom/compiler.ts +++ b/cocos/core/pipeline/custom/compiler.ts @@ -175,22 +175,19 @@ class CompilerContext { export class Compiler { private _resourceGraph: ResourceGraph; private _pipeline: Pipeline; - private _renderGraph: RenderGraph; private _layoutGraph: LayoutGraphData; constructor (pipeline: Pipeline, resGraph: ResourceGraph, - renderGraph: RenderGraph, layoutGraph: LayoutGraphData) { this._pipeline = pipeline; this._resourceGraph = resGraph; - this._renderGraph = renderGraph; this._layoutGraph = layoutGraph; } - compile () { + compile (rg: RenderGraph) { const context = new CompilerContext( this._pipeline, this._resourceGraph, - this._renderGraph, + rg, this._layoutGraph, ); const resVisitor = new ResourceVisitor(context); diff --git a/cocos/core/pipeline/custom/effect.ts b/cocos/core/pipeline/custom/effect.ts new file mode 100644 index 0000000000..d9d56a830d --- /dev/null +++ b/cocos/core/pipeline/custom/effect.ts @@ -0,0 +1,80 @@ +import { legacyCC } from '../../global-exports'; +import { EffectAsset } from '../../assets'; +import { 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'; + +function descriptorBlock2Flattened (block: DescriptorBlock, flattened: DescriptorBlockFlattened): void { + block.descriptors.forEach((value, key) => { + const name: string = key; + const d: Descriptor = value; + flattened.descriptorNames.push(name); + flattened.descriptors.push(d); + }); + block.uniformBlocks.forEach((value, key) => { + const name: string = key; + const u: UniformBlock = value; + flattened.uniformBlockNames.push(name); + flattened.uniformBlocks.push(u); + }); + flattened.count = block.count; + 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; + + for (const v of graph.vertices()) { + const db: DescriptorDB = graph.getDescriptors(v); + let vid = 0; + if (graph.id(v) === LayoutGraphValue.RenderStage) { + vid = lgData.addRenderStage(graph.getName(v)); + } + if (graph.id(v) === LayoutGraphValue.RenderPhase) { + vid = lgData.addRenderPhase(graph.getName(v), graph.getParent(v)); + const phase = graph.getRenderPhase(vid); + for (const shaderName of phase.shaders) { + lgData.addShader(shaderName, vid); + } + } + + db.blocks.forEach((value, key) => { + const index: DescriptorBlockIndex = JSON.parse(key) as DescriptorBlockIndex; + const block: DescriptorBlock = value; + if (block.capacity > 0) { + const flattened = new DescriptorBlockFlattened(); + descriptorBlock2Flattened(block, flattened); + lgData.addDescriptorBlock(vid, index, flattened); + } + }); + } + + lgData.compile(); + console.log(lgData.print()); + + EffectAsset.setLayoutValid(); + console.log('rebuildLayoutGraph end'); +} diff --git a/cocos/core/pipeline/custom/executor.ts b/cocos/core/pipeline/custom/executor.ts index 4cb38f5dd9..57730554de 100644 --- a/cocos/core/pipeline/custom/executor.ts +++ b/cocos/core/pipeline/custom/executor.ts @@ -30,23 +30,23 @@ */ /* eslint-disable max-len */ import { getPhaseID, InstancedBuffer, PipelineStateManager } from '..'; -import { Buffer, Color, ColorAttachment, CommandBuffer, DepthStencilAttachment, Device, Format, Framebuffer, - FramebufferInfo, PipelineState, Rect, RenderPass, RenderPassInfo, Swapchain, Texture, TextureInfo, +import { AccessFlagBit, Buffer, ClearFlagBit, Color, ColorAttachment, CommandBuffer, DepthStencilAttachment, Device, deviceManager, Format, Framebuffer, + FramebufferInfo, GeneralBarrierInfo, LoadOp, PipelineState, Rect, RenderPass, RenderPassInfo, StoreOp, Swapchain, Texture, TextureInfo, TextureType, TextureUsageBit, Viewport } from '../../gfx'; import { legacyCC } from '../../global-exports'; -import { assert } from '../../platform'; import { BatchingSchemes } from '../../renderer'; -import { Camera } from '../../renderer/scene/camera'; +import { Camera, SKYBOX_FLAG } from '../../renderer/scene/camera'; import { Root } from '../../root'; import { BatchedBuffer } from '../batched-buffer'; import { SetIndex } from '../define'; import { PipelineSceneData } from '../pipeline-scene-data'; import { Pipeline, SceneVisitor } from './pipeline'; import { AccessType, AttachmentType, Blit, ComputePass, CopyPass, Dispatch, ManagedResource, MovePass, PresentPass, - RasterPass, RaytracePass, RenderGraph, RenderGraphValue, RenderGraphVisitor, RenderQueue, RenderSwapchain, ResourceDesc, + RasterPass, RaytracePass, RenderGraph, RenderGraphVisitor, RenderQueue, RenderSwapchain, ResourceDesc, ResourceGraph, ResourceGraphVisitor, ResourceTraits, SceneData } from './render-graph'; import { QueueHint, ResourceDimension, ResourceFlags } from './types'; -import { RenderInfo, RenderObject, WebSceneTask } from './web-scene'; +import { PipelineUBO } from './ubos'; +import { RenderInfo, RenderObject, WebSceneTask, WebSceneTransversal } from './web-scene'; import { WebSceneVisitor } from './web-scene-visitor'; class DeviceResource { @@ -127,24 +127,43 @@ class DeviceBuffer extends DeviceResource { } } class DeviceRenderQueue { + private _preSceneTasks: DevicePreSceneTask[] = []; private _sceneTasks: DeviceSceneTask[] = []; + private _postSceneTasks: DevicePostSceneTask[] = []; private _devicePass: DeviceRenderPass; private _hint: QueueHint = QueueHint.NONE; + private _phaseID = getPhaseID('default'); + protected _transversal: DeviceSceneTransversal | null = null; + get phaseID (): number { return this._phaseID; } + + private _sceneVisitor: WebSceneVisitor; constructor (devicePass: DeviceRenderPass) { this._devicePass = devicePass; + this._sceneVisitor = new WebSceneVisitor(this._devicePass.context.commandBuffer, + this._devicePass.context.pipeline.pipelineSceneData); } addSceneTask (scene: SceneData) { - const task = new DeviceSceneTask(this, scene.camera!, - new WebSceneVisitor(this._devicePass.context.commandBuffer, - this._devicePass.context.pipeline.pipelineSceneData)); - this._sceneTasks.push(task); + if (!this._transversal) { + this._transversal = new DeviceSceneTransversal(this, this.devicePass.context.pipelineSceneData, scene.camera!); + } + this._preSceneTasks.push(this._transversal.preRenderPass(this._sceneVisitor)); + this._sceneTasks.push(this._transversal.transverse(this._sceneVisitor)); } clearTasks () { this._sceneTasks.length = 0; } + get sceneTasks () { return this._sceneTasks; } set queueHint (value: QueueHint) { this._hint = value; } get queueHint () { return this._hint; } get devicePass () { return this._devicePass; } + preRecord () { + for (const task of this._preSceneTasks) { + task.start(); + task.join(); + task.submit(); + } + } + record () { for (const task of this._sceneTasks) { task.start(); @@ -152,27 +171,48 @@ class DeviceRenderQueue { task.submit(); } } + + postRecord () { + for (const task of this._postSceneTasks) { + task.start(); + task.join(); + task.submit(); + } + } +} + +class SubmitInfo { + public instances = new Set(); + public batches = new Set(); + public opaqueList: RenderInfo[] = []; + public transparentList: RenderInfo[] = []; } class DeviceRenderPass { protected _renderPass: RenderPass; protected _framebuffer: Framebuffer; protected _clearColor: Color[] = []; - protected _sceneTasks: DeviceSceneTask[] = []; protected _deviceQueues: DeviceRenderQueue[] = []; protected _clearDepth = 1; protected _clearStencil = 0; protected _context: ExecutorContext; private _rasterPass: RasterPass; + public submitMap: Map = new Map(); constructor (context: ExecutorContext, rasterPass: RasterPass) { this._context = context; this._rasterPass = rasterPass; + const device = context.device; const depthStencilAttachment = new DepthStencilAttachment(); depthStencilAttachment.format = Format.DEPTH_STENCIL; + 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; - const device = context.device; let swapchain: Swapchain | null = null; let framebuffer: Framebuffer | null = null; for (const [resName, rasterV] of rasterPass.rasterViews) { @@ -187,26 +227,41 @@ class DeviceRenderPass { resTex = context.deviceTextures.get(resName)!; if (!swapchain) swapchain = resTex.swapchain; if (!framebuffer) framebuffer = resTex.framebuffer; + const clearFlag = rasterV.clearFlags & 0xffffffff; switch (rasterV.attachmentType) { case AttachmentType.RENDER_TARGET: - colorTexs.push(resTex.swapchain ? resTex.swapchain.colorTexture : resTex.texture!); - this._clearColor.push(rasterV.clearColor); - colors.push(new ColorAttachment( - resTex.description!.format, - resTex.description!.sampleCount, - rasterV.loadOp, - rasterV.storeOp, - )); + { + if (!resTex.swapchain && !resTex.framebuffer) colorTexs.push(resTex.texture!); + 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, + )); + } + } + this._clearColor.push(rasterV.clearColor); + colors.push(colorAttachment); + } break; case AttachmentType.DEPTH_STENCIL: - depthTex = resTex.swapchain ? resTex.swapchain.depthStencilTexture : resTex.texture!; + 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; - depthStencilAttachment.format = resTex.description!.format; - depthStencilAttachment.depthLoadOp = rasterV.loadOp; - depthStencilAttachment.depthStoreOp = rasterV.storeOp; - depthStencilAttachment.stencilLoadOp = rasterV.loadOp; - depthStencilAttachment.stencilStoreOp = rasterV.storeOp; break; default: } @@ -229,7 +284,9 @@ class DeviceRenderPass { )); } this._renderPass = device.createRenderPass(new RenderPassInfo(colors, depthStencilAttachment)); - this._framebuffer = framebuffer || device.createFramebuffer(new FramebufferInfo(this._renderPass, colorTexs, depthTex)); + this._framebuffer = framebuffer || device.createFramebuffer(new FramebufferInfo(this._renderPass, + swapchain ? [swapchain.colorTexture] : colorTexs, + swapchain ? swapchain.depthStencilTexture : depthTex)); } get context () { return this._context; } get renderPass () { return this._renderPass; } @@ -240,10 +297,16 @@ class DeviceRenderPass { get deviceQueues () { return this._deviceQueues; } get rasterPass () { return this._rasterPass; } addQueue (queue: DeviceRenderQueue) { this._deviceQueues.push(queue); } + prePass () { + for (const queue of this._deviceQueues) { + queue.preRecord(); + } + } // record common buffer record () { const cmdBuff = this._context.commandBuffer; - cmdBuff.beginRenderPass(this.renderPass, this.framebuffer, new Rect(), + const tex = this.framebuffer.colorTextures[0]!; + cmdBuff.beginRenderPass(this.renderPass, this.framebuffer, new Rect(0, 0, tex.width, tex.height), this.clearColor, this.clearDepth, this.clearStencil); cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, this._context.pipeline.globalDSManager.globalDescriptorSet); @@ -252,78 +315,70 @@ class DeviceRenderPass { } cmdBuff.endRenderPass(); } + postPass () { + this.submitMap.clear(); + for (const queue of this._deviceQueues) { + queue.postRecord(); + } + } } -class DeviceSceneTask extends WebSceneTask { +class DeviceSceneTransversal extends WebSceneTransversal { protected _currentQueue: DeviceRenderQueue; - private _phaseID = getPhaseID('default'); - protected _instances = new Set(); - protected _batches = new Set(); - protected _opaqueList: RenderInfo[] = []; - protected _transparentList: RenderInfo[] = []; - protected _renderPass: RenderPass; - constructor (quque: DeviceRenderQueue, camera: Camera, visitor: SceneVisitor) { - super(camera, visitor); + constructor (quque: DeviceRenderQueue, sceneData: PipelineSceneData, camera: Camera) { + super(camera, sceneData); this._currentQueue = quque; + } + public preRenderPass (visitor: WebSceneVisitor): DevicePreSceneTask { + return new DevicePreSceneTask(this._currentQueue, this._camera, visitor); + } + public transverse (visitor: WebSceneVisitor): DeviceSceneTask { + return new DeviceSceneTask(this._currentQueue, this._camera, visitor); + } + public postRenderPass (visitor: WebSceneVisitor): DevicePostSceneTask { + return new DevicePostSceneTask(this._sceneData, this._camera, visitor); + } +} + +class DevicePreSceneTask extends WebSceneTask { + protected _currentQueue: DeviceRenderQueue; + protected _renderPass: RenderPass; + protected _submitInfo: SubmitInfo | null = null; + private _cmdBuff: CommandBuffer; + constructor (queue: DeviceRenderQueue, camera: Camera, visitor: SceneVisitor) { + super(queue.devicePass.context.pipelineSceneData, camera, visitor); + this._currentQueue = queue; this._renderPass = this._currentQueue.devicePass.renderPass; + this._cmdBuff = this._currentQueue.devicePass.context.commandBuffer; } - protected _insertRenderList (ro: RenderObject, subModelIdx: number, passIdx: number, isTransparent = false) { - const subModel = ro.model.subModels[subModelIdx]; - const pass = subModel.passes[passIdx]; - const shader = subModel.shaders[passIdx]; - const currTransparent = pass.blendState.targets[0].blend; - const phases = getPhaseID('default') | getPhaseID('planarShadow'); - if (currTransparent !== isTransparent || !(pass.phase & (isTransparent ? phases : this._phaseID))) { - return; - } - const hash = (0 << 30) | pass.priority << 16 | subModel.priority << 8 | passIdx; - const rp = new RenderInfo(); - rp.hash = hash; - rp.depth = ro.depth || 0; - rp.shaderId = shader.typedID; - rp.subModel = subModel; - rp.passIdx = passIdx; - if (isTransparent) this._transparentList.push(rp); - else this._opaqueList.push(rp); - } - protected _clear () { - this._instances.clear(); - this._batches.clear(); - this._opaqueList.length = 0; - this._transparentList.length = 0; - } - /** - * @en Comparison sorting function. Opaque objects are sorted by priority -> depth front to back -> shader ID. - * @zh 比较排序函数。不透明对象按优先级 -> 深度由前向后 -> Shader ID 顺序排序。 - */ - protected _opaqueCompareFn (a: RenderInfo, b: RenderInfo) { - return (a.hash - b.hash) || (a.depth - b.depth) || (a.shaderId - b.shaderId); - } - /** - * @en Comparison sorting function. Transparent objects are sorted by priority -> depth back to front -> shader ID. - * @zh 比较排序函数。半透明对象按优先级 -> 深度由后向前 -> Shader ID 顺序排序。 - */ - protected _transparentCompareFn (a: RenderInfo, b: RenderInfo) { - return (a.hash - b.hash) || (b.depth - a.depth) || (a.shaderId - b.shaderId); - } + public start () { - super.start(); - this._clear(); + const submitMap = this._currentQueue.devicePass.submitMap; + if (submitMap.has(this.camera)) { + this._submitInfo = submitMap.get(this.camera)!; + } else { + // culling + super.start(); + this._submitInfo = new SubmitInfo(); + } for (const ro of this.sceneData.renderObjects) { const subModels = ro.model.subModels; for (const submodel of subModels) { const passes = submodel.passes; for (const p of passes) { - if (p.phase !== this._phaseID) continue; + if (p.phase !== this._currentQueue.phaseID) continue; const batchingScheme = p.batchingScheme; - if (batchingScheme === BatchingSchemes.INSTANCING) { + // If the size of instances is not 0, it has been added + if (batchingScheme === BatchingSchemes.INSTANCING + && !this._submitInfo.instances.size) { const instancedBuffer = p.getInstancedBuffer(); instancedBuffer.merge(submodel, ro.model.instancedAttributes, passes.indexOf(p)); - this._instances.add(instancedBuffer); - } else if (batchingScheme === BatchingSchemes.VB_MERGING) { + this._submitInfo.instances.add(instancedBuffer); + } else if (batchingScheme === BatchingSchemes.VB_MERGING + && !this._submitInfo.batches.size) { const batchedBuffer = p.getBatchedBuffer(); batchedBuffer.merge(submodel, passes.indexOf(p), ro.model); - this._batches.add(batchedBuffer); + this._submitInfo.batches.add(batchedBuffer); } else { switch (this._currentQueue.queueHint) { case QueueHint.NONE: @@ -343,17 +398,100 @@ class DeviceSceneTask extends WebSceneTask { } } } - this._opaqueList.sort(this._opaqueCompareFn); - this._transparentList.sort(this._transparentCompareFn); + + 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]; + const pass = subModel.passes[passIdx]; + const shader = subModel.shaders[passIdx]; + const currTransparent = pass.blendState.targets[0].blend; + const phases = getPhaseID('default') | getPhaseID('planarShadow'); + if (currTransparent !== isTransparent || !(pass.phase & (isTransparent ? phases : this._currentQueue.phaseID))) { + return; + } + const hash = (0 << 30) | pass.priority << 16 | subModel.priority << 8 | passIdx; + const rp = new RenderInfo(); + rp.priority = ro.model.priority; + rp.hash = hash; + rp.depth = ro.depth || 0; + rp.shaderId = shader.typedID; + rp.subModel = subModel; + rp.passIdx = passIdx; + if (isTransparent) this._submitInfo!.transparentList.push(rp); + else this._submitInfo!.opaqueList.push(rp); + } + + /** + * @en Comparison sorting function. Opaque objects are sorted by priority -> depth front to back -> shader ID. + * @zh 比较排序函数。不透明对象按优先级 -> 深度由前向后 -> Shader ID 顺序排序。 + */ + protected _opaqueCompareFn (a: RenderInfo, b: RenderInfo) { + return (a.hash - b.hash) || (a.depth - b.depth) || (a.shaderId - b.shaderId); + } + /** + * @en Comparison sorting function. Transparent objects are sorted by priority -> depth back to front -> shader ID. + * @zh 比较排序函数。半透明对象按优先级 -> 深度由后向前 -> Shader ID 顺序排序。 + */ + protected _transparentCompareFn (a: RenderInfo, b: RenderInfo) { + return (a.priority - b.priority) || (a.hash - b.hash) || (b.depth - a.depth) || (a.shaderId - b.shaderId); + } + + private _uploadInstanceBuffers () { + const it = this._submitInfo!.instances.values(); let res = it.next(); + while (!res.done) { + if (res.value.hasPendingModels) res.value.uploadBuffers(this._cmdBuff); + res = it.next(); + } + } + + private _uploadBatchedBuffers () { + const it = this._submitInfo!.batches.values(); let res = it.next(); + while (!res.done) { + for (let b = 0; b < res.value.batches.length; ++b) { + const batch = res.value.batches[b]; + if (!batch.mergeCount) { continue; } + for (let v = 0; v < batch.vbs.length; ++v) { + batch.vbs[v].update(batch.vbDatas[v]); + } + this._cmdBuff.updateBuffer(batch.vbIdx, batch.vbIdxData.buffer); + this._cmdBuff.updateBuffer(batch.ubo, batch.uboData); + } + res = it.next(); + } + } + + public submit () { + const ubo = this._currentQueue.devicePass.context.ubo; + ubo.updateGlobalUBO(this.camera.window); + ubo.updateCameraUBO(this.camera); + ubo.updateShadowUBO(this.camera); + + this._uploadInstanceBuffers(); + this._uploadBatchedBuffers(); + } +} + +class DeviceSceneTask extends WebSceneTask { + protected _currentQueue: DeviceRenderQueue; + protected _renderPass: RenderPass; + constructor (queue: DeviceRenderQueue, camera: Camera, visitor: SceneVisitor) { + super(queue.devicePass.context.pipelineSceneData, camera, visitor); + this._currentQueue = queue; + this._renderPass = this._currentQueue.devicePass.renderPass; + } + public start () {} protected _recordRenderList (isTransparent: boolean) { - const renderList = isTransparent ? this._transparentList : this._opaqueList; + const submitMap = this._currentQueue.devicePass.submitMap; + 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; const pass = subModel.passes[passIdx]; const shader = subModel.shaders[passIdx]; - const pso = PipelineStateManager.getOrCreatePipelineState(legacyCC.director.root.device, + const pso = PipelineStateManager.getOrCreatePipelineState(deviceManager.gfxDevice, pass, shader, this._renderPass, inputAssembler); this.visitor.bindPipelineState(pso); this.visitor.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); @@ -366,7 +504,8 @@ class DeviceSceneTask extends WebSceneTask { this._recordRenderList(false); } protected _recordInstences () { - const it = this._instances.values(); let res = it.next(); + const submitMap = this._currentQueue.devicePass.submitMap; + const it = submitMap.get(this.camera)!.instances.values(); let res = it.next(); while (!res.done) { const { instances, pass, hasPendingModels } = res.value; if (hasPendingModels) { @@ -375,9 +514,9 @@ class DeviceSceneTask extends WebSceneTask { for (let b = 0; b < instances.length; ++b) { const instance = instances[b]; if (!instance.count) { continue; } - const shader = instance.shader; - const pso = PipelineStateManager.getOrCreatePipelineState(legacyCC.director.root.device, pass, - shader!, this._renderPass, instance.ia); + const shader = instance.shader!; + const pso = PipelineStateManager.getOrCreatePipelineState(deviceManager.gfxDevice, pass, + shader, this._renderPass, instance.ia); if (lastPSO !== pso) { this.visitor.bindPipelineState(pso); lastPSO = pso; @@ -392,7 +531,8 @@ class DeviceSceneTask extends WebSceneTask { } } protected _recordBatches () { - const it = this._batches.values(); let res = it.next(); + const submitMap = this._currentQueue.devicePass.submitMap; + 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) { @@ -400,7 +540,7 @@ class DeviceSceneTask extends WebSceneTask { if (!batch.mergeCount) { continue; } if (!boundPSO) { const shader = batch.shader!; - const pso = PipelineStateManager.getOrCreatePipelineState(legacyCC.director.root.device, batch.pass, + const pso = PipelineStateManager.getOrCreatePipelineState(deviceManager.gfxDevice, batch.pass, shader, this._renderPass, batch.ia); this.visitor.bindPipelineState(pso); this.visitor.bindDescriptorSet(SetIndex.MATERIAL, batch.pass.descriptorSet); @@ -414,6 +554,33 @@ class DeviceSceneTask extends WebSceneTask { res = it.next(); } } + protected _recordUI () { + 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) { + visible = true; + } + + if (!visible) continue; + // shaders.length always equals actual used passes.length + const count = batch.shaders.length; + for (let j = 0; j < count; j++) { + const pass = batch.passes[j]; + if (pass.phase !== this._currentQueue.phaseID) continue; + const shader = batch.shaders[j]; + const inputAssembler: any = batch.inputAssembler!; + const pso = PipelineStateManager.getOrCreatePipelineState(deviceManager.gfxDevice, pass, shader, this._renderPass, inputAssembler); + this.visitor.bindPipelineState(pso); + this.visitor.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); + const ds = batch.descriptorSet!; + this.visitor.bindDescriptorSet(SetIndex.LOCAL, ds); + this.visitor.bindInputAssembler(inputAssembler); + this.visitor.draw(inputAssembler); + } + } + } protected _recordTransparentList () { this._recordRenderList(true); } @@ -436,11 +603,15 @@ class DeviceSceneTask extends WebSceneTask { this._recordInstences(); this._recordBatches(); this._recordTransparentList(); + this._recordUI(); } } +class DevicePostSceneTask extends WebSceneTask {} + class ExecutorContext { constructor (pipeline: Pipeline, + ubo: PipelineUBO, device: Device, resourceGraph: ResourceGraph, renderGraph: RenderGraph) { @@ -451,6 +622,7 @@ class ExecutorContext { this.resourceGraph = resourceGraph; this.renderGraph = renderGraph; this.root = legacyCC.director.root; + this.ubo = ubo; } readonly device: Device; readonly pipeline: Pipeline; @@ -461,6 +633,7 @@ class ExecutorContext { readonly deviceTextures: Map = new Map(); readonly renderGraph: RenderGraph; readonly root: Root; + readonly ubo: PipelineUBO; } class ResourceVisitor implements ResourceGraphVisitor { @@ -515,7 +688,9 @@ class PassVisitor implements RenderGraphVisitor { rg.visitVertex(this, queueID); } } + this._currPass.prePass(); this._currPass.record(); + this._currPass.postPass(); } compute (pass: ComputePass) { @@ -555,10 +730,12 @@ class PassVisitor implements RenderGraphVisitor { 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; } @@ -566,10 +743,13 @@ export class Executor { execute (rg: RenderGraph) { const context = new ExecutorContext( this._pipeline, + this._ubo, this._device, this._resourceGraph, rg, ); + const cmdBuff = context.commandBuffer; + cmdBuff.begin(); const passVisitor = new PassVisitor(context); for (const vertID of rg.vertices()) { if (rg.numParents(vertID) === 0) { @@ -578,9 +758,12 @@ export class Executor { rg.visitVertex(passVisitor, vertID); } } + cmdBuff.end(); + context.device.queue.submit([cmdBuff]); } - private readonly _pipeline: Pipeline - private readonly _device: Device - private readonly _commandBuffer: CommandBuffer - private readonly _resourceGraph: ResourceGraph + private readonly _pipeline: Pipeline; + private readonly _device: Device; + private readonly _commandBuffer: CommandBuffer; + private readonly _resourceGraph: ResourceGraph; + private readonly _ubo: PipelineUBO; } diff --git a/cocos/core/pipeline/custom/index.jsb.ts b/cocos/core/pipeline/custom/index.jsb.ts index f834ce4fae..7d82f809fc 100644 --- a/cocos/core/pipeline/custom/index.jsb.ts +++ b/cocos/core/pipeline/custom/index.jsb.ts @@ -23,19 +23,19 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module custom-pipeline - */ - declare const render: any; -import { DescriptorHierarchy, Pipeline } from './pipeline'; +import { Pipeline } from './pipeline'; +import { rebuildLayoutGraph } from './effect'; +import { legacyCC } from '../../global-exports'; export function createCustomPipeline (): Pipeline { return render.Factory.createPipeline(); } -export function createDescriptorHierarchy (): DescriptorHierarchy { - return render.Factory.createDescriptorHierarchy(); +export function registerRebuildLayoutGraph() { + const director = legacyCC.director; + if (director.root.usesCustomPipeline) { + director.on(legacyCC.Director.EVENT_BEFORE_DRAW, rebuildLayoutGraph); + } } diff --git a/cocos/core/pipeline/custom/index.ts b/cocos/core/pipeline/custom/index.ts index 41643a0d54..26d09084e4 100644 --- a/cocos/core/pipeline/custom/index.ts +++ b/cocos/core/pipeline/custom/index.ts @@ -23,18 +23,8 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module custom-pipeline - */ - -import { DescriptorHierarchy, Pipeline } from './pipeline'; +import { Pipeline } from './pipeline'; import { WebPipeline } from './web-pipeline'; -import { WebDescriptorHierarchy } from './web-descriptor-hierarchy'; - -export function createDescriptorHierarchy (): DescriptorHierarchy { - return new WebDescriptorHierarchy(); -} export function createCustomPipeline (): Pipeline { return new WebPipeline(); diff --git a/cocos/core/pipeline/custom/layout-graph.ts b/cocos/core/pipeline/custom/layout-graph.ts index 3c8044a121..e354b2f0c8 100644 --- a/cocos/core/pipeline/custom/layout-graph.ts +++ b/cocos/core/pipeline/custom/layout-graph.ts @@ -30,21 +30,44 @@ */ /* eslint-disable max-len */ import * as impl from './graph'; -import { ShaderStageFlagBit, Type, Uniform } from '../../gfx'; +import { DescriptorSet, DescriptorSetLayout, ShaderStageFlagBit, Type, UniformBlock } from '../../gfx'; import { ParameterType, UpdateFrequency } from './types'; -export const enum DescriptorIndex { - UNIFORM_BLOCK, +export const enum DescriptorTypeOrder { + UNIFORM_BUFFER, + DYNAMIC_UNIFORM_BUFFER, SAMPLER_TEXTURE, SAMPLER, TEXTURE, STORAGE_BUFFER, - STORAGE_TEXTURE, - SUBPASS_INPUT, + DYNAMIC_STORAGE_BUFFER, + STORAGE_IMAGE, + INPUT_ATTACHMENT, } -export class UniformBlockDB { - readonly values: Map = new Map(); +export function getDescriptorTypeOrderName (e: DescriptorTypeOrder): string { + switch (e) { + case DescriptorTypeOrder.UNIFORM_BUFFER: + return 'UNIFORM_BUFFER'; + case DescriptorTypeOrder.DYNAMIC_UNIFORM_BUFFER: + return 'DYNAMIC_UNIFORM_BUFFER'; + case DescriptorTypeOrder.SAMPLER_TEXTURE: + return 'SAMPLER_TEXTURE'; + case DescriptorTypeOrder.SAMPLER: + return 'SAMPLER'; + case DescriptorTypeOrder.TEXTURE: + return 'TEXTURE'; + case DescriptorTypeOrder.STORAGE_BUFFER: + return 'STORAGE_BUFFER'; + case DescriptorTypeOrder.DYNAMIC_STORAGE_BUFFER: + return 'DYNAMIC_STORAGE_BUFFER'; + case DescriptorTypeOrder.STORAGE_IMAGE: + return 'STORAGE_IMAGE'; + case DescriptorTypeOrder.INPUT_ATTACHMENT: + return 'INPUT_ATTACHMENT'; + default: + return ''; + } } export class Descriptor { @@ -57,15 +80,22 @@ export class Descriptor { export class DescriptorBlock { readonly descriptors: Map = new Map(); - readonly uniformBlocks: Map = new Map(); - readonly merged: Map = new Map(); + readonly uniformBlocks: Map = new Map(); + capacity = 0; + count = 0; +} + +export class DescriptorBlockFlattened { + readonly descriptorNames: string[] = []; + readonly uniformBlockNames: string[] = []; + readonly descriptors: Descriptor[] = []; + readonly uniformBlocks: UniformBlock[] = []; capacity = 0; - start = 0; count = 0; } export class DescriptorBlockIndex { - constructor (updateFrequency: UpdateFrequency = UpdateFrequency.PER_INSTANCE, parameterType: ParameterType = ParameterType.CONSTANTS, descriptorType: DescriptorIndex = DescriptorIndex.UNIFORM_BLOCK, visibility: ShaderStageFlagBit = ShaderStageFlagBit.NONE) { + constructor (updateFrequency: UpdateFrequency = UpdateFrequency.PER_INSTANCE, parameterType: ParameterType = ParameterType.CONSTANTS, descriptorType: DescriptorTypeOrder = DescriptorTypeOrder.UNIFORM_BUFFER, visibility: ShaderStageFlagBit = ShaderStageFlagBit.NONE) { this.updateFrequency = updateFrequency; this.parameterType = parameterType; this.descriptorType = descriptorType; @@ -73,23 +103,10 @@ export class DescriptorBlockIndex { } updateFrequency: UpdateFrequency; parameterType: ParameterType; - descriptorType: DescriptorIndex; + descriptorType: DescriptorTypeOrder; visibility: ShaderStageFlagBit; } -export class DescriptorBlockIndexDx { - constructor (updateFrequency: UpdateFrequency = UpdateFrequency.PER_INSTANCE, parameterType: ParameterType = ParameterType.CONSTANTS, visibility: ShaderStageFlagBit = ShaderStageFlagBit.NONE, descriptorType: DescriptorIndex = DescriptorIndex.UNIFORM_BLOCK) { - this.updateFrequency = updateFrequency; - this.parameterType = parameterType; - this.visibility = visibility; - this.descriptorType = descriptorType; - } - updateFrequency: UpdateFrequency; - parameterType: ParameterType; - visibility: ShaderStageFlagBit; - descriptorType: DescriptorIndex; -} - export class DescriptorDB { readonly blocks: Map = new Map(); } @@ -250,6 +267,13 @@ export class LayoutGraph implements impl.BidirectionalGraph } //----------------------------------------------------------------- // MutableGraph + clear (): void { + // ComponentGraph + this._names.length = 0; + this._descriptors.length = 0; + // Graph Vertices + this._vertices.length = 0; + } addVertex ( id: LayoutGraphValue, object: LayoutGraphValueType[T], @@ -610,38 +634,46 @@ export class UniformBlockData { } export class DescriptorData { - constructor (descriptorID = 0xFFFFFFFF, type: Type = Type.UNKNOWN) { + constructor (descriptorID = 0) { this.descriptorID = descriptorID; - this.type = type; } descriptorID: number; - type: Type; count = 1; } export class DescriptorBlockData { - constructor (type: DescriptorIndex = DescriptorIndex.UNIFORM_BLOCK, capacity = 0) { + constructor (type: DescriptorTypeOrder = DescriptorTypeOrder.UNIFORM_BUFFER, visibility: ShaderStageFlagBit = ShaderStageFlagBit.NONE, capacity = 0) { this.type = type; + this.visibility = visibility; this.capacity = capacity; } - type: DescriptorIndex; + type: DescriptorTypeOrder; + visibility: ShaderStageFlagBit; + offset = 0; capacity: number; readonly descriptors: DescriptorData[] = []; +} + +export class DescriptorSetLayoutData { + constructor (slot = 0xFFFFFFFF, capacity = 0) { + this.slot = slot; + this.capacity = capacity; + } + slot: number; + capacity: number; + readonly descriptorBlocks: DescriptorBlockData[] = []; readonly uniformBlocks: Map = new Map(); } -export class DescriptorTableData { - constructor (tableID = 0xFFFFFFFF, capacity = 0) { - this.tableID = tableID; - this.capacity = capacity; - } - tableID: number; - capacity: number; - readonly descriptorBlocks: DescriptorBlockData[] = []; -} - export class DescriptorSetData { - readonly tables: Map = new Map(); + constructor (descriptorSetLayoutData: DescriptorSetLayoutData, descriptorSetLayout: DescriptorSetLayout | null, descriptorSet: DescriptorSet | null) { + this.descriptorSetLayoutData = descriptorSetLayoutData; + this.descriptorSetLayout = descriptorSetLayout; + this.descriptorSet = descriptorSet; + } + readonly descriptorSetLayoutData: DescriptorSetLayoutData; + /*object*/ descriptorSetLayout: DescriptorSetLayout | null; + /*object*/ descriptorSet: DescriptorSet | null; } export class PipelineLayoutData { @@ -652,6 +684,10 @@ export class ShaderProgramData { readonly layout: PipelineLayoutData = new PipelineLayoutData(); } +export class RenderStageData { + readonly descriptorVisibility: Map = new Map(); +} + export class RenderPhaseData { rootSignature = ''; readonly shaderPrograms: ShaderProgramData[] = []; @@ -668,16 +704,16 @@ export const enum LayoutGraphDataValue { } interface LayoutGraphDataValueType { - [LayoutGraphDataValue.RenderStage]: number + [LayoutGraphDataValue.RenderStage]: RenderStageData [LayoutGraphDataValue.RenderPhase]: RenderPhaseData } export interface LayoutGraphDataVisitor { - renderStage(value: number): unknown; + renderStage(value: RenderStageData): unknown; renderPhase(value: RenderPhaseData): unknown; } -type LayoutGraphDataObject = number | RenderPhaseData; +type LayoutGraphDataObject = RenderStageData | RenderPhaseData; //----------------------------------------------------------------- // Graph Concept @@ -823,6 +859,19 @@ export class LayoutGraphData implements impl.BidirectionalGraph } //----------------------------------------------------------------- // MutableGraph + clear (): void { + // Members + this.valueNames.length = 0; + this.attributeIndex.clear(); + this.constantIndex.clear(); + this.shaderLayoutIndex.clear(); + // ComponentGraph + this._names.length = 0; + this._updateFrequencies.length = 0; + this._layouts.length = 0; + // Graph Vertices + this._vertices.length = 0; + } addVertex ( id: LayoutGraphDataValue, object: LayoutGraphDataValueType[T], @@ -1026,16 +1075,16 @@ export class LayoutGraphData implements impl.BidirectionalGraph const vert = this._vertices[v]; switch (vert._id) { case LayoutGraphDataValue.RenderStage: - return visitor.renderStage(vert._object as number); + return visitor.renderStage(vert._object as RenderStageData); case LayoutGraphDataValue.RenderPhase: return visitor.renderPhase(vert._object as RenderPhaseData); default: throw Error('polymorphic type not found'); } } - getRenderStage (v: number): number { + getRenderStage (v: number): RenderStageData { if (this._vertices[v]._id === LayoutGraphDataValue.RenderStage) { - return this._vertices[v]._object as number; + return this._vertices[v]._object as RenderStageData; } else { throw Error('value id not match'); } @@ -1047,9 +1096,9 @@ export class LayoutGraphData implements impl.BidirectionalGraph throw Error('value id not match'); } } - tryGetRenderStage (v: number): number | null { + tryGetRenderStage (v: number): RenderStageData | null { if (this._vertices[v]._id === LayoutGraphDataValue.RenderStage) { - return this._vertices[v]._object as number; + return this._vertices[v]._object as RenderStageData; } else { return null; } @@ -1176,4 +1225,8 @@ export class LayoutGraphData implements impl.BidirectionalGraph readonly _names: string[] = []; readonly _updateFrequencies: UpdateFrequency[] = []; readonly _layouts: PipelineLayoutData[] = []; + readonly valueNames: string[] = []; + readonly attributeIndex: Map = new Map(); + readonly constantIndex: Map = new Map(); + readonly shaderLayoutIndex: Map = new Map(); } diff --git a/cocos/core/pipeline/custom/pipeline.ts b/cocos/core/pipeline/custom/pipeline.ts index 4662759465..09e6c7bf19 100644 --- a/cocos/core/pipeline/custom/pipeline.ts +++ b/cocos/core/pipeline/custom/pipeline.ts @@ -29,18 +29,19 @@ * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= */ /* eslint-disable max-len */ -import { EffectAsset } 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 { 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, TaskType } from './types'; +import { QueueHint, ResourceResidency, SceneFlags, TaskType, UpdateFrequency } from './types'; import { ComputeView, CopyPair, MovePair, RasterView } from './render-graph'; -import { RenderScene } from '../../renderer/scene/render-scene'; +import { RenderScene } from '../../renderer/core/render-scene'; import { RenderWindow } from '../../renderer/core/render-window'; -import { Model } from '../../renderer/scene'; +import { Light, Model } from '../../renderer/scene'; export abstract class PipelineRuntime { public abstract activate(swapchain: Swapchain): boolean; @@ -52,17 +53,17 @@ export abstract class PipelineRuntime { public abstract get constantMacros(): string; public abstract get profiler(): Model | null; public abstract set profiler(profiler: Model | null); + public abstract get geometryRenderer(): GeometryRenderer | null; public abstract get shadingScale(): number; public abstract set shadingScale(scale: number); + public abstract setMacroString(name: string, value: string): void; + public abstract setMacroInt(name: string, value: number): void; + public abstract setMacroBool(name: string, value: boolean): void; public abstract onGlobalPipelineStateChanged(): void; public abstract get macros(): MacroRecord; } -export abstract class DescriptorHierarchy { - public abstract addEffect(asset: EffectAsset): void; -} - export abstract class Setter { public abstract setMat4(name: string, mat: Mat4): void; public abstract setQuaternion(name: string, quat: Quat): void; @@ -78,9 +79,9 @@ export abstract class Setter { } export abstract class RasterQueueBuilder extends Setter { - public abstract addSceneOfCamera(camera: Camera, name: string): void; - public abstract addSceneOfCamera(camera: Camera): void; - public abstract addScene(name: string): void; + 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 addScene(name: string, sceneFlags: SceneFlags): void; public abstract addFullscreenQuad(shader: string, name: string): void; public abstract addFullscreenQuad(shader: string): void; } @@ -143,6 +144,17 @@ export abstract class SceneTransversal { public abstract transverse(visitor: SceneVisitor): SceneTask; } +export abstract class LayoutGraphBuilder { + public abstract clear(): void; + public abstract addRenderStage(name: string): number; + 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 reserveDescriptorBlock(nodeID: number, index: DescriptorBlockIndex, block: DescriptorBlockFlattened): void; + public abstract compile(): number; + public abstract print(): string; +} + export abstract class Pipeline extends PipelineRuntime { 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; @@ -157,6 +169,8 @@ export abstract class Pipeline extends PipelineRuntime { public abstract addCopyPass(name: string): CopyPassBuilder; public abstract presentAll(): void; public abstract createSceneTransversal(camera: Camera, scene: RenderScene): SceneTransversal; + public abstract get layoutGraphBuilder(): LayoutGraphBuilder; + public abstract getDescriptorSetLayout(shaderName: string, freq: UpdateFrequency): DescriptorSetLayout | null; } export class Factory { diff --git a/cocos/core/pipeline/custom/render-graph.ts b/cocos/core/pipeline/custom/render-graph.ts index 43fdb919b9..b7e5a3dcaf 100644 --- a/cocos/core/pipeline/custom/render-graph.ts +++ b/cocos/core/pipeline/custom/render-graph.ts @@ -32,7 +32,8 @@ import * as impl from './graph'; 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 } from './types'; +import { QueueHint, ResourceDimension, ResourceFlags, ResourceResidency, SceneFlags } from './types'; +import { Light } from '../../renderer/scene'; export class ResourceDesc { dimension: ResourceDimension = ResourceDimension.BUFFER; @@ -260,6 +261,17 @@ export class ResourceGraph implements impl.BidirectionalGraph } //----------------------------------------------------------------- // MutableGraph + clear (): void { + // UuidGraph + this._valueIndex.clear(); + // ComponentGraph + this._names.length = 0; + this._descs.length = 0; + this._traits.length = 0; + this._states.length = 0; + // Graph Vertices + this._vertices.length = 0; + } addVertex ( id: ResourceGraphValue, object: ResourceGraphValueType[T], @@ -587,12 +599,36 @@ export const enum AttachmentType { 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 = '', @@ -625,6 +661,17 @@ export const enum ClearValueType { 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; @@ -760,6 +807,13 @@ export class SubpassGraph implements impl.BidirectionalGraph } //----------------------------------------------------------------- // MutableGraph + clear (): void { + // ComponentGraph + this._names.length = 0; + this._subpasses.length = 0; + // Graph Vertices + this._vertices.length = 0; + } addVertex ( name: string, subpass: RasterSubpass, @@ -924,6 +978,8 @@ export class RasterPass { readonly rasterViews: Map = new Map(); readonly computeViews: Map = new Map(); readonly subpassGraph: SubpassGraph = new SubpassGraph(); + width = 0; + height = 0; } export class ComputePass { @@ -1013,11 +1069,14 @@ export class RenderQueue { } export class SceneData { - constructor (name = '') { + constructor (name = '', flags: SceneFlags = SceneFlags.NONE) { this.name = name; + this.flags = flags; } name: string; camera: Camera | null = null; + light: Light | null = null; + flags: SceneFlags; readonly scenes: string[] = []; } @@ -1058,7 +1117,7 @@ export class RenderData { readonly constants: Map = new Map(); readonly buffers: Map = new Map(); readonly textures: Map = new Map(); - readonly samplers: Map = new Map(); + readonly samplers: Map = new Map(); } //================================================================= @@ -1273,6 +1332,17 @@ export class RenderGraph implements impl.BidirectionalGraph } //----------------------------------------------------------------- // MutableGraph + clear (): void { + // Members + this.index.clear(); + // ComponentGraph + this._names.length = 0; + this._layoutNodes.length = 0; + this._data.length = 0; + this._valid.length = 0; + // Graph Vertices + this._vertices.length = 0; + } addVertex ( id: RenderGraphValue, object: RenderGraphValueType[T], diff --git a/cocos/core/pipeline/custom/types.ts b/cocos/core/pipeline/custom/types.ts index cc17f1e0ef..571136effb 100644 --- a/cocos/core/pipeline/custom/types.ts +++ b/cocos/core/pipeline/custom/types.ts @@ -37,6 +37,23 @@ export const enum UpdateFrequency { COUNT, } +export function getUpdateFrequencyName (e: UpdateFrequency): string { + switch (e) { + case UpdateFrequency.PER_INSTANCE: + return 'PER_INSTANCE'; + case UpdateFrequency.PER_BATCH: + return 'PER_BATCH'; + case UpdateFrequency.PER_QUEUE: + return 'PER_QUEUE'; + case UpdateFrequency.PER_PASS: + return 'PER_PASS'; + case UpdateFrequency.COUNT: + return 'COUNT'; + default: + return ''; + } +} + export const enum ParameterType { CONSTANTS, CBV, @@ -46,6 +63,25 @@ export const enum ParameterType { SSV, } +export function getParameterTypeName (e: ParameterType): string { + switch (e) { + case ParameterType.CONSTANTS: + return 'CONSTANTS'; + case ParameterType.CBV: + return 'CBV'; + case ParameterType.UAV: + return 'UAV'; + case ParameterType.SRV: + return 'SRV'; + case ParameterType.TABLE: + return 'TABLE'; + case ParameterType.SSV: + return 'SSV'; + default: + return ''; + } +} + export const enum ResourceResidency { MANAGED, MEMORYLESS, @@ -54,6 +90,23 @@ export const enum ResourceResidency { BACKBUFFER, } +export function getResourceResidencyName (e: ResourceResidency): string { + switch (e) { + case ResourceResidency.MANAGED: + return 'MANAGED'; + case ResourceResidency.MEMORYLESS: + return 'MEMORYLESS'; + case ResourceResidency.PERSISTENT: + return 'PERSISTENT'; + case ResourceResidency.EXTERNAL: + return 'EXTERNAL'; + case ResourceResidency.BACKBUFFER: + return 'BACKBUFFER'; + default: + return ''; + } +} + export const enum QueueHint { NONE, RENDER_OPAQUE, @@ -61,6 +114,21 @@ export const enum QueueHint { RENDER_TRANSPARENT, } +export function getQueueHintName (e: QueueHint): string { + switch (e) { + case QueueHint.NONE: + return 'NONE'; + case QueueHint.RENDER_OPAQUE: + return 'RENDER_OPAQUE'; + case QueueHint.RENDER_CUTOUT: + return 'RENDER_CUTOUT'; + case QueueHint.RENDER_TRANSPARENT: + return 'RENDER_TRANSPARENT'; + default: + return ''; + } +} + export const enum ResourceDimension { BUFFER, TEXTURE1D, @@ -68,6 +136,21 @@ export const enum ResourceDimension { TEXTURE3D, } +export function getResourceDimensionName (e: ResourceDimension): string { + switch (e) { + case ResourceDimension.BUFFER: + return 'BUFFER'; + case ResourceDimension.TEXTURE1D: + return 'TEXTURE1D'; + case ResourceDimension.TEXTURE2D: + return 'TEXTURE2D'; + case ResourceDimension.TEXTURE3D: + return 'TEXTURE3D'; + default: + return ''; + } +} + export const enum ResourceFlags { NONE = 0, UNIFORM = 0x1, @@ -83,3 +166,23 @@ export const enum TaskType { SYNC, ASYNC, } + +export function getTaskTypeName (e: TaskType): string { + switch (e) { + case TaskType.SYNC: + return 'SYNC'; + case TaskType.ASYNC: + return 'ASYNC'; + default: + return ''; + } +} + +export const enum SceneFlags { + NONE = 0, + OPAQUE_OBJECT = 0x1, + CUTOUT_OBJECT = 0x2, + TRANSPARENT_OBJECT = 0x4, + SHADOW_CASTER = 0x8, + ALL = 0xFFFFFFFF, +} diff --git a/cocos/core/pipeline/custom/ubos.ts b/cocos/core/pipeline/custom/ubos.ts index e860dfea76..840a2cb698 100644 --- a/cocos/core/pipeline/custom/ubos.ts +++ b/cocos/core/pipeline/custom/ubos.ts @@ -24,20 +24,20 @@ */ import { UBOGlobal, UBOShadow, UBOCamera, UNIFORM_SHADOWMAP_BINDING, - supportsR32FloatTexture, UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING, -} from '../define'; + 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 { ShadowType } from '../../renderer/scene/shadows'; +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(); @@ -47,7 +47,8 @@ const _lightDir = new Vec4(0.0, 0.0, 1.0, 0.0); export class PipelineUBO { public static updateGlobalUBOView (window: RenderWindow, bufferView: Float32Array) { - const root = legacyCC.director.root; + const director = legacyCC.director; + const root = director.root; const fv = bufferView; const shadingWidth = Math.floor(window.width); @@ -56,7 +57,7 @@ export class PipelineUBO { // update UBOGlobal fv[UBOGlobal.TIME_OFFSET] = root.cumulativeTime; fv[UBOGlobal.TIME_OFFSET + 1] = root.frameTime; - fv[UBOGlobal.TIME_OFFSET + 2] = legacyCC.director.getTotalFrames(); + fv[UBOGlobal.TIME_OFFSET + 2] = director.getTotalFrames(); fv[UBOGlobal.SCREEN_SIZE_OFFSET] = shadingWidth; fv[UBOGlobal.SCREEN_SIZE_OFFSET + 1] = shadingHeight; @@ -67,6 +68,23 @@ export class PipelineUBO { 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, @@ -129,7 +147,8 @@ export class PipelineUBO { 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; - cv[UBOCamera.AMBIENT_GROUND_OFFSET + 3] = ambient.mipmapCount; + 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); @@ -164,59 +183,100 @@ export class PipelineUBO { cv[UBOCamera.VIEW_PORT_OFFSET + 3] = sceneData.shadingScale * camera.window.height * camera.viewport.w; } - public static updateShadowUBOView (pipeline: WebPipeline, bufferView: Float32Array, camera: Camera) { + 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 sv = bufferView; + const csmLayers = sceneData.csmLayers; + const sv = shadowBufferView; + const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; - if (shadowInfo.enabled) { - if (mainLight && shadowInfo.type === ShadowType.ShadowMap) { - let near = 0.1; - let far = 0; - const matShadowView = shadowInfo.matShadowView; - const matShadowProj = shadowInfo.matShadowProj; - const matShadowViewProj = shadowInfo.matShadowViewProj; - if (mainLight.shadowFixedArea) { - near = mainLight.shadowNear; - far = mainLight.shadowFar; - } else { - near = 0.1; - far = shadowInfo.shadowCameraFar; + 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); } - - Mat4.toArray(bufferView, 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(bufferView, matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); - - const linear = 0.0; - const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; - sv[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 0] = near; - sv[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 1] = far; - sv[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 2] = linear; - sv[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 3] = 1.0 - mainLight.shadowSaturation; - - sv[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x; - sv[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 1] = shadowInfo.size.y; - sv[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 2] = mainLight.shadowPcf; - sv[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 3] = mainLight.shadowBias; - - sv[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 0] = 0.0; - sv[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing; - sv[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = mainLight.shadowNormalBias; - sv[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0; - } else if (mainLight && shadowInfo.type === ShadowType.Planar) { + } else { updatePlanarPROJ(shadowInfo, mainLight, sv); updatePlanarNormalAndDistance(shadowInfo, sv); } @@ -225,50 +285,74 @@ export class PipelineUBO { } } - public static updateShadowUBOLightView (pipeline: WebPipeline, bufferView: Float32Array, light: Light) { + public static updateShadowUBOLightView (pipeline: WebPipeline, shadowBufferView: Float32Array, light: Light, level: number) { const device = pipeline.device; - const shadowInfo = pipeline.pipelineSceneData.shadows; - const sv = bufferView; - const linear = 0.0; + const sceneData = pipeline.pipelineSceneData; + const shadowInfo = sceneData.shadows; + const csmLayers = sceneData.csmLayers; + const sv = shadowBufferView; const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; - let near = 0.1; - let far = 0; - const matShadowView = shadowInfo.matShadowView; - const matShadowProj = shadowInfo.matShadowProj; - const matShadowViewProj = shadowInfo.matShadowViewProj; switch (light.type) { case LightType.DIRECTIONAL: { const mainLight = light as DirectionalLight; - if (mainLight.shadowFixedArea) { - near = mainLight.shadowNear; - far = mainLight.shadowFar; - } else { - near = 0.1; - far = shadowInfo.shadowCameraFar; + 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); + } } - - Mat4.toArray(bufferView, 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(bufferView, matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); - - _vec4ShadowInfo.set(near, far, linear, 1.0 - mainLight.shadowSaturation); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); - - _vec4ShadowInfo.set(0.0, packing, mainLight.shadowNormalBias, 0.0); - 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: { @@ -276,19 +360,19 @@ 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, (light as any).aspect, 0.001, (light as any).range); + 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, linear, 0.0); + _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(1.0, packing, spotLight.shadowNormalBias, 0.0); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_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: @@ -395,10 +479,10 @@ export class PipelineUBO { cmdBuffer.updateBuffer(ds.getBuffer(UBOShadow.BINDING), this._shadowUBO); } - public updateShadowUBOLight (globalDS: DescriptorSet, light: Light) { - PipelineUBO.updateShadowUBOLightView(this._pipeline, this._shadowUBO, light); + 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_LIGHTING_MAP_TEXTURE_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); } diff --git a/cocos/core/pipeline/custom/web-descriptor-hierarchy.ts b/cocos/core/pipeline/custom/web-descriptor-hierarchy.ts index 561e08c929..b587f56664 100644 --- a/cocos/core/pipeline/custom/web-descriptor-hierarchy.ts +++ b/cocos/core/pipeline/custom/web-descriptor-hierarchy.ts @@ -25,19 +25,17 @@ ****************************************************************************/ import { EffectAsset } from '../../assets'; -import { DescriptorHierarchy } from './pipeline'; -import { Descriptor, DescriptorBlock, DescriptorBlockIndex, DescriptorDB, DescriptorIndex, LayoutGraph, LayoutGraphValue, RenderPhase, UniformBlockDB } from './layout-graph'; -import { ShaderStageFlagBit, Type, Uniform } from '../../gfx'; +import { Descriptor, DescriptorBlock, DescriptorBlockIndex, DescriptorDB, DescriptorTypeOrder, LayoutGraph, LayoutGraphValue, 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'; -export class WebDescriptorHierarchy extends DescriptorHierarchy { +export class WebDescriptorHierarchy { constructor () { - super(); this._layoutGraph = new LayoutGraph(); } - private getLayoutBlock (freq: UpdateFrequency, paraType: ParameterType, descType: DescriptorIndex, vis: ShaderStageFlagBit, descriptorDB: DescriptorDB): DescriptorBlock { + private 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) { @@ -60,17 +58,17 @@ export class WebDescriptorHierarchy extends DescriptorHierarchy { return descriptorDB.blocks.get(key) as DescriptorBlock; } - private getUniformBlock (blockName: string, targetBlock: DescriptorBlock): UniformBlockDB { + private getUniformBlock (blockName: string, targetBlock: DescriptorBlock): UniformBlock { if (targetBlock.uniformBlocks.get(blockName) === undefined) { - const uniformDB: UniformBlockDB = new UniformBlockDB(); + const uniformDB: UniformBlock = new UniformBlock(); targetBlock.uniformBlocks.set(blockName, uniformDB); } - return targetBlock.uniformBlocks.get(blockName) as UniformBlockDB; + return targetBlock.uniformBlocks.get(blockName) as UniformBlock; } - private setUniform (uniformDB: UniformBlockDB, name: string, type: Type, count: number) { + private setUniform (uniformDB: UniformBlock, name: string, type: Type, count: number) { const uniform: Uniform = new Uniform(name, type, count); - uniformDB.values.set(uniform.name, uniform); + // uniformDB.values.set(uniform.name, uniform); } private setDescriptor (targetBlock: DescriptorBlock, name: string, type: Type) { @@ -99,13 +97,14 @@ export class WebDescriptorHierarchy extends DescriptorHierarchy { if (count > 0) { const mergedDescriptor: Descriptor = new Descriptor(type); mergedDescriptor.count = count; - block.merged.set(type, mergedDescriptor); + // block.merged.set(type, mergedDescriptor); } } } } private mergeDBs (descriptorDBs: DescriptorDB[], target: DescriptorDB) { + /* for (let i = 0; i < descriptorDBs.length; ++i) { const db: DescriptorDB = descriptorDBs[i]; for (const e of db.blocks) { @@ -132,6 +131,7 @@ export class WebDescriptorHierarchy extends DescriptorHierarchy { } } } + */ } private sort (descriptorDB: DescriptorDB) { @@ -142,17 +142,9 @@ export class WebDescriptorHierarchy extends DescriptorHierarchy { } } - public addEffect (asset: EffectAsset): void { + public addEffect (asset: EffectAsset, parent: number): void { const sz = asset.shaders.length; - let hasCCGlobal = false; - let hasCCCamera = false; - let hasCCShadow = false; - let hasShadowmap = false; - let hasEnv = false; - let hasDiffuse = false; - let hasSpot = false; - const dbsToMerge: DescriptorDB[] = []; for (let i = 0; i !== sz; ++i) { @@ -163,104 +155,106 @@ export class WebDescriptorHierarchy extends DescriptorHierarchy { for (let k = 0; k < shader.blocks.length; ++k) { const blockInfo: EffectAsset.IBlockInfo = shader.blocks[k]; const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_INSTANCE, - ParameterType.TABLE, DescriptorIndex.UNIFORM_BLOCK, blockInfo.stageFlags, queueDB); - const uniformDB: UniformBlockDB = this.getUniformBlock(blockInfo.name, targetBlock); + ParameterType.TABLE, DescriptorTypeOrder.UNIFORM_BUFFER, blockInfo.stageFlags, queueDB); + const uniformDB: UniformBlock = this.getUniformBlock(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.values.set(uniform.name, uniform); } } for (let k = 0; k < shader.buffers.length; ++k) { const bufferInfo: EffectAsset.IBufferInfo = shader.buffers[k]; - const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_QUEUE, - ParameterType.TABLE, DescriptorIndex.STORAGE_BUFFER, bufferInfo.stageFlags, queueDB); + const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, + ParameterType.TABLE, DescriptorTypeOrder.STORAGE_BUFFER, bufferInfo.stageFlags, queueDB); this.setDescriptor(targetBlock, bufferInfo.name, Type.UNKNOWN); } for (let k = 0; k < shader.images.length; ++k) { const imageInfo: EffectAsset.IImageInfo = shader.images[k]; - const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_QUEUE, - ParameterType.TABLE, DescriptorIndex.STORAGE_TEXTURE, imageInfo.stageFlags, queueDB); + const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, + ParameterType.TABLE, DescriptorTypeOrder.STORAGE_IMAGE, imageInfo.stageFlags, queueDB); this.setDescriptor(targetBlock, imageInfo.name, imageInfo.type); } for (let k = 0; k < shader.samplerTextures.length; ++k) { const samplerTexInfo: EffectAsset.ISamplerTextureInfo = shader.samplerTextures[k]; const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, - ParameterType.TABLE, DescriptorIndex.SAMPLER_TEXTURE, samplerTexInfo.stageFlags, queueDB); + ParameterType.TABLE, DescriptorTypeOrder.SAMPLER_TEXTURE, samplerTexInfo.stageFlags, queueDB); this.setDescriptor(targetBlock, samplerTexInfo.name, samplerTexInfo.type); } for (let k = 0; k < shader.samplers.length; ++k) { const samplerInfo: EffectAsset.ISamplerInfo = shader.samplers[k]; - const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_QUEUE, - ParameterType.TABLE, DescriptorIndex.SAMPLER, samplerInfo.stageFlags, queueDB); + const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, + ParameterType.TABLE, DescriptorTypeOrder.SAMPLER, samplerInfo.stageFlags, queueDB); this.setDescriptor(targetBlock, samplerInfo.name, Type.SAMPLER); } for (let k = 0; k < shader.textures.length; ++k) { const texInfo: EffectAsset.ITextureInfo = shader.textures[k]; - const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_QUEUE, - ParameterType.TABLE, DescriptorIndex.TEXTURE, texInfo.stageFlags, queueDB); + const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, + ParameterType.TABLE, DescriptorTypeOrder.TEXTURE, texInfo.stageFlags, queueDB); this.setDescriptor(targetBlock, texInfo.name, texInfo.type); } for (let k = 0; k < shader.subpassInputs.length; ++k) { const subpassInfo: EffectAsset.IInputAttachmentInfo = shader.subpassInputs[k]; const targetBlock: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_QUEUE, - ParameterType.TABLE, DescriptorIndex.SUBPASS_INPUT, subpassInfo.stageFlags, queueDB); + ParameterType.TABLE, DescriptorTypeOrder.INPUT_ATTACHMENT, subpassInfo.stageFlags, queueDB); this.setDescriptor(targetBlock, subpassInfo.name, Type.SUBPASS_INPUT); } // Add queue layout from define.ts const localUniformTarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_INSTANCE, - ParameterType.TABLE, DescriptorIndex.UNIFORM_BLOCK, ShaderStageFlagBit.VERTEX, queueDB); - const localLightTarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_QUEUE, - ParameterType.TABLE, DescriptorIndex.UNIFORM_BLOCK, ShaderStageFlagBit.FRAGMENT, queueDB); + ParameterType.TABLE, DescriptorTypeOrder.UNIFORM_BUFFER, ShaderStageFlagBit.VERTEX, queueDB); + const localLightTarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, + ParameterType.TABLE, DescriptorTypeOrder.DYNAMIC_UNIFORM_BUFFER, ShaderStageFlagBit.FRAGMENT, queueDB); + const localUITarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_INSTANCE, + ParameterType.TABLE, DescriptorTypeOrder.DYNAMIC_UNIFORM_BUFFER, ShaderStageFlagBit.VERTEX, queueDB); const localModelTarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_INSTANCE, - ParameterType.TABLE, DescriptorIndex.UNIFORM_BLOCK, ShaderStageFlagBit.VERTEX | ShaderStageFlagBit.COMPUTE, queueDB); + ParameterType.TABLE, DescriptorTypeOrder.UNIFORM_BUFFER, ShaderStageFlagBit.VERTEX | ShaderStageFlagBit.COMPUTE, queueDB); const localSamplerVertTarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, - ParameterType.TABLE, DescriptorIndex.SAMPLER_TEXTURE, ShaderStageFlagBit.VERTEX, queueDB); + ParameterType.TABLE, DescriptorTypeOrder.SAMPLER_TEXTURE, ShaderStageFlagBit.VERTEX, queueDB); const localSamplerFragTarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, - ParameterType.TABLE, DescriptorIndex.SAMPLER_TEXTURE, ShaderStageFlagBit.FRAGMENT, queueDB); + ParameterType.TABLE, DescriptorTypeOrder.SAMPLER_TEXTURE, ShaderStageFlagBit.FRAGMENT, queueDB); const localSamplerCompTarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_BATCH, - ParameterType.TABLE, DescriptorIndex.SAMPLER_TEXTURE, ShaderStageFlagBit.COMPUTE, queueDB); + ParameterType.TABLE, DescriptorTypeOrder.SAMPLER_TEXTURE, ShaderStageFlagBit.COMPUTE, queueDB); 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: UniformBlockDB = this.getUniformBlock('CCMorph', localUniformTarget); + const morphDB: UniformBlock = this.getUniformBlock('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: UniformBlockDB = this.getUniformBlock('CCSkinningTexture', localUniformTarget); + const skinningTexDB: UniformBlock = this.getUniformBlock('CCSkinningTexture', localUniformTarget); this.setUniform(skinningTexDB, 'cc_jointTextureInfo', Type.FLOAT4, 1); } else if (blockName === 'CCSkinningAnimation') { - const skinningAnimDB: UniformBlockDB = this.getUniformBlock('CCSkinningAnimation', localUniformTarget); + const skinningAnimDB: UniformBlock = this.getUniformBlock('CCSkinningAnimation', localUniformTarget); this.setUniform(skinningAnimDB, 'cc_jointAnimInfo', Type.FLOAT4, 1); } else if (blockName === 'CCSkinning') { - const skinningDB: UniformBlockDB = this.getUniformBlock('CCSkinning', localUniformTarget); + const skinningDB: UniformBlock = this.getUniformBlock('CCSkinning', localUniformTarget); this.setUniform(skinningDB, 'cc_joints', Type.FLOAT4, JOINT_UNIFORM_CAPACITY * 3); } else if (blockName === 'CCUILocal') { - const uiDB: UniformBlockDB = this.getUniformBlock('CCUILocal', localUniformTarget); + const uiDB: UniformBlock = this.getUniformBlock('CCUILocal', localUITarget); this.setUniform(uiDB, 'cc_local_data', Type.FLOAT4, 1); } else if (blockName === 'CCForwardLight') { - const lightDB: UniformBlockDB = this.getUniformBlock('CCForwardLight', localLightTarget); + const lightDB: UniformBlock = this.getUniformBlock('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: UniformBlockDB = this.getUniformBlock('CCLocal', localModelTarget); + const localDB: UniformBlock = this.getUniformBlock('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: UniformBlockDB = this.getUniformBlock('CCLocalBatched', localModelTarget); + const batchDB: UniformBlock = this.getUniformBlock('CCLocalBatched', localModelTarget); this.setUniform(batchDB, 'cc_matWorlds', Type.MAT4, UBOLocalBatched.BATCHING_COUNT); } else if (blockName === 'CCWorldBound') { - const boundDB: UniformBlockDB = this.getUniformBlock('CCWorldBound', localModelTarget); + const boundDB: UniformBlock = this.getUniformBlock('CCWorldBound', localModelTarget); this.setUniform(boundDB, 'cc_worldBoundCenter', Type.FLOAT4, 1); this.setUniform(boundDB, 'cc_worldBoundHalfExtents', Type.FLOAT4, 1); } @@ -294,53 +288,33 @@ export class WebDescriptorHierarchy extends DescriptorHierarchy { const phase: RenderPhase = new RenderPhase(); phase.shaders.add(shader.name); - this._layoutGraph.addVertex(LayoutGraphValue.RenderPhase, phase, shader.name, queueDB); - - for (let k = 0; k < shader.builtins.globals.blocks.length; ++k) { - const blockName = shader.builtins.globals.blocks[k].name; - if (blockName === 'CCGlobal') { - hasCCGlobal = true; - } else if (blockName === 'CCCamera') { - hasCCCamera = true; - } else if (blockName === 'CCShadow') { - hasCCShadow = true; - } - } - - for (let k = 0; k < shader.builtins.globals.samplerTextures.length; ++k) { - const samplerName = shader.builtins.globals.samplerTextures[k].name; - if (samplerName === 'cc_shadowMap') { - hasShadowmap = true; - } else if (samplerName === 'cc_environment') { - hasEnv = true; - } else if (samplerName === 'cc_diffuseMap') { - hasDiffuse = true; - } else if (samplerName === 'cc_spotLightingMap') { - hasSpot = true; - } - } + this._layoutGraph.addVertex(LayoutGraphValue.RenderPhase, phase, shader.name, queueDB, parent); this.merge(queueDB); this.sort(queueDB); dbsToMerge.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, - ParameterType.TABLE, DescriptorIndex.UNIFORM_BLOCK, ShaderStageFlagBit.ALL, passDB); + ParameterType.TABLE, DescriptorTypeOrder.UNIFORM_BUFFER, ShaderStageFlagBit.ALL, passDB); const globalSamplerTexTarget: DescriptorBlock = this.getLayoutBlock(UpdateFrequency.PER_PASS, - ParameterType.TABLE, DescriptorIndex.SAMPLER_TEXTURE, ShaderStageFlagBit.FRAGMENT, passDB); + ParameterType.TABLE, DescriptorTypeOrder.SAMPLER_TEXTURE, ShaderStageFlagBit.FRAGMENT, passDB); if (hasCCGlobal) { - const globalDB: UniformBlockDB = this.getUniformBlock('CCGlobal', globalUniformTarget); + const globalDB: UniformBlock = this.getUniformBlock('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); } if (hasCCCamera) { - const cameraDB: UniformBlockDB = this.getUniformBlock('CCCamera', globalUniformTarget); + const cameraDB: UniformBlock = this.getUniformBlock('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); @@ -363,7 +337,7 @@ export class WebDescriptorHierarchy extends DescriptorHierarchy { } if (hasCCShadow) { - const shadowDB: UniformBlockDB = this.getUniformBlock('CCShadow', globalUniformTarget); + const shadowDB: UniformBlock = this.getUniformBlock('CCShadow', globalUniformTarget); this.setUniform(shadowDB, 'cc_matLightPlaneProj', Type.MAT4, 1); this.setUniform(shadowDB, 'cc_matLightView', Type.MAT4, 1); this.setUniform(shadowDB, 'cc_matLightViewProj', Type.MAT4, 1); @@ -386,14 +360,18 @@ export class WebDescriptorHierarchy extends DescriptorHierarchy { this.setDescriptor(globalSamplerTexTarget, 'cc_diffuseMap', Type.SAMPLER_CUBE); } if (hasSpot) { - this.setDescriptor(globalSamplerTexTarget, 'cc_spotLightingMap', Type.SAMPLER2D); + this.setDescriptor(globalSamplerTexTarget, 'cc_spotShadowMap', Type.SAMPLER2D); } - this._layoutGraph.addVertex(LayoutGraphValue.RenderStage, LayoutGraphValue.RenderStage, asset.name, passDB); + const vid = this._layoutGraph.addVertex(LayoutGraphValue.RenderStage, LayoutGraphValue.RenderStage, vName, passDB); - this.mergeDBs(dbsToMerge, passDB); + //this.mergeDBs(dbsToMerge, passDB); + this.merge(passDB); this.sort(passDB); + + return vid; } + private _layoutGraph: LayoutGraph; public get layoutGraph () { diff --git a/cocos/core/pipeline/custom/web-layout-graph.ts b/cocos/core/pipeline/custom/web-layout-graph.ts new file mode 100644 index 0000000000..2c98b15234 --- /dev/null +++ b/cocos/core/pipeline/custom/web-layout-graph.ts @@ -0,0 +1,269 @@ +// eslint-disable-next-line max-len +import { DescriptorSetInfo, DescriptorSetLayout, DescriptorSetLayoutBinding, DescriptorSetLayoutInfo, DescriptorType, Device, ShaderStageFlagBit } from '../../gfx'; +// 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 { LayoutGraphBuilder } from './pipeline'; +import { getUpdateFrequencyName, UpdateFrequency } from './types'; + +export class WebLayoutGraphBuilder extends LayoutGraphBuilder { + private _data: LayoutGraphData; + private _device: Device; + + constructor (deviceIn: Device, dataIn: LayoutGraphData) { + super(); + this._device = deviceIn; + 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: + return DescriptorType.UNIFORM_BUFFER; + case DescriptorTypeOrder.DYNAMIC_UNIFORM_BUFFER: + return DescriptorType.DYNAMIC_UNIFORM_BUFFER; + case DescriptorTypeOrder.SAMPLER_TEXTURE: + return DescriptorType.SAMPLER_TEXTURE; + case DescriptorTypeOrder.SAMPLER: + return DescriptorType.SAMPLER; + case DescriptorTypeOrder.TEXTURE: + return DescriptorType.TEXTURE; + case DescriptorTypeOrder.STORAGE_BUFFER: + return DescriptorType.STORAGE_BUFFER; + case DescriptorTypeOrder.DYNAMIC_STORAGE_BUFFER: + return DescriptorType.DYNAMIC_STORAGE_BUFFER; + case DescriptorTypeOrder.STORAGE_IMAGE: + return DescriptorType.STORAGE_IMAGE; + case DescriptorTypeOrder.INPUT_ATTACHMENT: + return DescriptorType.INPUT_ATTACHMENT; + default: + console.error('DescriptorType not found'); + return null; + } + } + + 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) { + const block = layoutData.descriptorBlocks[i]; + let slot = block.offset; + for (let j = 0; j < block.descriptors.length; ++j) { + const d = block.descriptors[j]; + const binding: DescriptorSetLayoutBinding = new DescriptorSetLayoutBinding(); + binding.binding = slot; + if (this.getGfxType(block.type)) { + binding.descriptorType = this.getGfxType(block.type) as DescriptorType; + } + binding.count = d.count; + binding.stageFlags = block.visibility; + binding.immutableSamplers = []; + info.bindings.push(binding); + slot += d.count; + } + } + + return this._device.createDescriptorSetLayout(info); + } + + public clear (): void { + this._data.clear(); + } + + public addRenderStage (name: string): number { + return this.add_vertex(this._data, LayoutGraphDataValue.RenderStage, new RenderStageData(), name); + } + + public addRenderPhase (name: string, parentID: number): number { + return this.add_vertex(this._data, LayoutGraphDataValue.RenderPhase, new RenderPhaseData(), name, parentID); + } + + public addShader (name: string, parentPhaseID: number): void { + this._data.shaderLayoutIndex.set(name, parentPhaseID); + } + + public addDescriptorBlock (nodeID: number, index: DescriptorBlockIndex, block: DescriptorBlockFlattened): void { + const g: LayoutGraphData = this._data; + const ppl: PipelineLayoutData = g.getLayout(nodeID); + if (block.capacity <= 0) { + console.error('empty block'); + return; + } + if (block.descriptorNames.length !== block.descriptors.length) { + console.error('error descriptor'); + return; + } + if (block.uniformBlockNames.length !== block.uniformBlocks.length) { + console.error('error uniform'); + return; + } + 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); + } + layout.capacity += block.capacity; + } else { + console.error('no layout'); + } + } + + public reserveDescriptorBlock (nodeID: number, index: DescriptorBlockIndex, block: DescriptorBlockFlattened): void { + const g: LayoutGraphData = this._data; + const ppl: PipelineLayoutData = g.getLayout(nodeID); + if (block.capacity <= 0) { + console.error('empty block'); + return; + } + + const layout: DescriptorSetLayoutData | undefined = ppl.descriptorSets.get(index.updateFrequency)?.descriptorSetLayoutData; + if (layout !== undefined) { + layout.descriptorBlocks.push(new DescriptorBlockData(index.descriptorType, index.visibility, block.capacity)); + const dstBlock = layout.descriptorBlocks[layout.descriptorBlocks.length - 1]; + dstBlock.offset = layout.capacity; + dstBlock.capacity = block.capacity; + layout.capacity += block.capacity; + } else { + console.error('no layout'); + } + } + + public compile (): number { + const g: LayoutGraphData = this._data; + for (let i = 0; i < g._layouts.length; ++i) { + const ppl: PipelineLayoutData = g.getLayout(i); + ppl.descriptorSets.forEach((value, key) => { + const level = value; + const layoutData = level.descriptorSetLayoutData; + const layout: DescriptorSetLayout = this.createDescriptorSetLayout(layoutData); + level.descriptorSetLayout = (layout); + level.descriptorSet = (this._device.createDescriptorSet(new DescriptorSetInfo(layout))); + }); + } + + 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; + } + + public get data () { + return this._data; + } +} diff --git a/cocos/core/pipeline/custom/web-pipeline-impl.ts b/cocos/core/pipeline/custom/web-pipeline-impl.ts deleted file mode 100644 index 77202b1316..0000000000 --- a/cocos/core/pipeline/custom/web-pipeline-impl.ts +++ /dev/null @@ -1,34 +0,0 @@ -/**************************************************************************** - Copyright (c) 2021-2022 Xiamen Yaji Software Co., Ltd. - - http://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. -****************************************************************************/ - -/** - * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= - * The following section is auto-generated. - * ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! ========================= - */ -/* eslint-disable max-len */ -export class WebImplExample { - name = ''; -} diff --git a/cocos/core/pipeline/custom/web-pipeline.ts b/cocos/core/pipeline/custom/web-pipeline.ts index af591e8a65..513867c09f 100644 --- a/cocos/core/pipeline/custom/web-pipeline.ts +++ b/cocos/core/pipeline/custom/web-pipeline.ts @@ -25,27 +25,31 @@ /* eslint-disable max-len */ import { systemInfo } from 'pal/system-info'; -import { Color, Buffer, DescriptorSetLayout, Device, Feature, Format, FormatFeatureBit, Sampler, Swapchain, Texture, StoreOp, LoadOp, ClearFlagBit } from '../../gfx/index'; +import { Color, Buffer, DescriptorSetLayout, Device, Feature, Format, FormatFeatureBit, Sampler, Swapchain, Texture, StoreOp, LoadOp, ClearFlagBit, DescriptorSet, deviceManager } from '../../gfx/index'; import { Mat4, Quat, Vec2, Vec4 } from '../../math'; -import { QueueHint, ResourceDimension, ResourceFlags, ResourceResidency, TaskType } from './types'; +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, MovePassBuilder, Pipeline, RasterPassBuilder, RasterQueueBuilder, SceneTask, SceneTransversal, SceneVisitor, Setter } from './pipeline'; +import { ComputePassBuilder, ComputeQueueBuilder, CopyPassBuilder, LayoutGraphBuilder, MovePassBuilder, Pipeline, RasterPassBuilder, RasterQueueBuilder, SceneTask, SceneTransversal, SceneVisitor, Setter } from './pipeline'; import { PipelineSceneData } from '../pipeline-scene-data'; -import { Model, RenderScene, Camera, SKYBOX_FLAG, Light, LightType, ShadowType, DirectionalLight, Shadows } from '../../renderer/scene'; +import { Model, Camera, SKYBOX_FLAG, Light, LightType, ShadowType, DirectionalLight, Shadows } from '../../renderer/scene'; import { legacyCC } from '../../global-exports'; import { LayoutGraphData } from './layout-graph'; import { Executor } from './executor'; -import { WebImplExample } from './web-pipeline-impl'; import { RenderWindow } from '../../renderer/core/render-window'; -import { assert, macro } from '../../platform'; +import { assert } from '../../platform/debug'; +import { macro } from '../../platform/macro'; import { WebSceneTransversal } from './web-scene'; -import { MacroRecord } from '../../renderer'; +import { MacroRecord, RenderScene } from '../../renderer'; import { GlobalDSManager } from '../global-descriptor-set-manager'; -import { supportsR32FloatTexture } from '../define'; +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 { builtinResMgr } from '../../builtin/builtin-res-mgr'; +import { Texture2D } from '../../assets/texture-2d'; +import { WebLayoutGraphBuilder } from './web-layout-graph'; +import { GeometryRenderer } from '../geometry-renderer'; export class WebSetter { constructor (data: RenderData) { @@ -129,17 +133,18 @@ export class WebRasterQueueBuilder extends WebSetter implements RasterQueueBuild this._queue = queue; this._pipeline = pipeline; } - addSceneOfCamera (camera: Camera, name = 'Camera'): void { - const sceneData = new SceneData(name); + addSceneOfCamera (camera: Camera, light: Light | null, sceneFlags: SceneFlags, name = 'Camera'): void { + const sceneData = new SceneData(name, sceneFlags); sceneData.camera = camera; + sceneData.light = light; this._renderGraph.addVertex( RenderGraphValue.Scene, sceneData, name, '', new RenderData(), false, this._vertID, ); setCameraValues(this, camera, this._pipeline, camera.scene ? camera.scene : legacyCC.director.getScene().renderScene); } - addScene (sceneName: string): void { - const sceneData = new SceneData(sceneName); + addScene (sceneName: string, sceneFlags: SceneFlags): void { + const sceneData = new SceneData(sceneName, sceneFlags); this._renderGraph.addVertex( RenderGraphValue.Scene, sceneData, sceneName, '', new RenderData(), false, this._vertID, ); @@ -326,7 +331,7 @@ export class WebPipeline extends Pipeline { } public activate (swapchain: Swapchain): boolean { - this._device = legacyCC.director.root.device; + this._device = deviceManager.gfxDevice; this._globalDSManager = new GlobalDSManager(this._device); this._macros.CC_USE_HDR = this._pipelineSceneData.isHDR; this._generateConstantMacros(false); @@ -334,6 +339,12 @@ export class WebPipeline extends Pipeline { const descH = new WebDescriptorHierarchy(); //descH.addEffect(new EffectAsset()); this._pipelineUBO.activate(this._device, this); + 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(); return true; } public destroy (): boolean { @@ -350,6 +361,9 @@ export class WebPipeline extends Pipeline { public get descriptorSetLayout (): DescriptorSetLayout { return this._globalDSManager.descriptorSetLayout; } + public get descriptorSet (): DescriptorSet { + return this._globalDSManager.globalDescriptorSet; + } public get pipelineSceneData (): PipelineSceneData { return this._pipelineSceneData; } @@ -362,12 +376,24 @@ export class WebPipeline extends Pipeline { public set profiler (profiler: Model | null) { this._profiler = profiler; } + public get geometryRenderer (): GeometryRenderer | null { + throw new Error('Method not implemented.'); + } public get shadingScale (): number { return this._pipelineSceneData.shadingScale; } public set shadingScale (scale: number) { this._pipelineSceneData.shadingScale = scale; } + public setMacroString (name: string, value: string): void { + this._macros[name] = value; + } + public setMacroInt (name: string, value: number): void { + this._macros[name] = value; + } + public setMacroBool (name: string, value: boolean): void { + this._macros[name] = value; + } public get device () { return this._device; } @@ -452,9 +478,9 @@ export class WebPipeline extends Pipeline { throw new Error('RenderGraph cannot be built without being created'); } if (!this._compiler) { - this._compiler = new Compiler(this, this._resourceGraph, this._renderGraph, this._layoutGraph); + this._compiler = new Compiler(this, this._resourceGraph, this._layoutGraph); } - this._compiler.compile(); + this._compiler.compile(this._renderGraph); } execute () { @@ -462,7 +488,7 @@ export class WebPipeline extends Pipeline { throw new Error('Cannot run without creating rendergraph'); } if (!this._executor) { - this._executor = new Executor(this, this._device, this._resourceGraph); + this._executor = new Executor(this, this._pipelineUBO, this._device, this._resourceGraph); } this._executor.execute(this._renderGraph); } @@ -484,8 +510,9 @@ export class WebPipeline extends Pipeline { LoadOp.CLEAR, StoreOp.STORE, ClearFlagBit.COLOR, new Color(0, 0, 0, 0))); - const queue = pass.addQueue(QueueHint.NONE); - queue.addScene(`${passName}_shadowScene`); + 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); } } @@ -497,7 +524,7 @@ export class WebPipeline extends Pipeline { if (!shadows.enabled || shadows.type !== ShadowType.ShadowMap) { return; } - const castShadowObjects = pplScene.castShadowObjects; + const castShadowObjects = pplScene.csmLayers.castShadowObjects; const validPunctualLights = pplScene.validPunctualLights; // force clean up @@ -537,70 +564,57 @@ export class WebPipeline extends Pipeline { if (cameras.length === 0) { return; } + cameras.forEach((camera) => { + if (!this._cameras.includes(camera)) { + this._cameras.push(camera); + } + }); // build graph this.beginFrame(); for (let i = 0; i < cameras.length; i++) { const camera = cameras[i]; if (camera.scene) { - this._pipelineUBO.updateGlobalUBO(camera.window); - this._pipelineUBO.updateCameraUBO(camera); + const idx = this._cameras.indexOf(camera); this._buildShadowPasses(this, this._validLights, camera.scene.mainLight, this._pipelineSceneData, - `Camera${i.toString()}`); + `Camera${idx}`); const window = camera.window; const width = Math.floor(window.width); const height = Math.floor(window.height); - const forwardPassRTName = `dsForwardPassColorCamera${i}`; - const forwardPassDSName = `dsForwardPassDSCamera${i}`; + const forwardPassRTName = `dsForwardPassColorCamera${idx}`; + const forwardPassDSName = `dsForwardPassDSCamera${idx}`; if (!this.resourceGraph.contains(forwardPassRTName)) { this.addRenderTexture(forwardPassRTName, Format.RGBA8, width, height, camera.window); - this.addRenderTarget(forwardPassDSName, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); + this.addDepthStencil(forwardPassDSName, Format.DEPTH_STENCIL, width, height, ResourceResidency.MANAGED); } - const forwardPass = this.addRasterPass(width, height, '_', `CameraForwardPass${i.toString()}`); + 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, 0))); + new Color(0, 0, 0, 1))); } const passView = new RasterView('_', AccessType.WRITE, AttachmentType.RENDER_TARGET, LoadOp.CLEAR, StoreOp.STORE, - ClearFlagBit.NONE, - new Color(0, 0, 0, 0)); - if (!(camera.clearFlag & ClearFlagBit.COLOR)) { - if (camera.clearFlag & SKYBOX_FLAG) { - passView.loadOp = LoadOp.DISCARD; - } else { - passView.loadOp = LoadOp.LOAD; - passView.accessType = AccessType.READ_WRITE; - } - } else { - passView.clearColor.x = camera.clearColor.x; - passView.clearColor.y = camera.clearColor.y; - passView.clearColor.z = camera.clearColor.z; - passView.clearColor.w = camera.clearColor.w; - } + 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, - ClearFlagBit.DEPTH_STENCIL, + camera.clearFlag, new Color(1, 0, 0, 0)); - if ((camera.clearFlag & ClearFlagBit.DEPTH_STENCIL) !== ClearFlagBit.DEPTH_STENCIL) { - if (!(camera.clearFlag & ClearFlagBit.DEPTH)) passDSView.loadOp = LoadOp.LOAD; - if (!(camera.clearFlag & ClearFlagBit.STENCIL)) passDSView.loadOp = LoadOp.LOAD; - } forwardPass.addRasterView(forwardPassRTName, passView); forwardPass.addRasterView(forwardPassDSName, passDSView); forwardPass .addQueue(QueueHint.RENDER_OPAQUE) - .addSceneOfCamera(camera); + .addSceneOfCamera(camera, null, SceneFlags.OPAQUE_OBJECT | SceneFlags.CUTOUT_OBJECT); forwardPass .addQueue(QueueHint.RENDER_TRANSPARENT) - .addSceneOfCamera(camera); + .addSceneOfCamera(camera, null, SceneFlags.TRANSPARENT_OBJECT); } } this.compile(); @@ -642,7 +656,17 @@ export class WebPipeline extends Pipeline { this._renderGraph!.addVertex(RenderGraphValue.Present, pass, '', '', new RenderData(), false); } createSceneTransversal (camera: Camera, scene: RenderScene): SceneTransversal { - return new WebSceneTransversal(camera); + 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)!; + const pplLayout = lg.getLayout(phaseID); + const setLayout = pplLayout.descriptorSets.get(freq)!; + return setLayout.descriptorSetLayout!; } get renderGraph () { return this._renderGraph; @@ -650,7 +674,9 @@ export class WebPipeline extends Pipeline { get resourceGraph () { return this._resourceGraph; } - get layoutGraph () { return this._layoutGraph; } + get layoutGraph () { + return this._layoutGraph; + } protected _updateRasterPassConstants (pass: Setter, width: number, height: number) { const shadingWidth = width; const shadingHeight = height; @@ -670,6 +696,7 @@ export class WebPipeline extends Pipeline { private _constantMacros = ''; private _profiler: Model | null = null; private _pipelineUBO: PipelineUBO = new PipelineUBO(); + private _cameras: Camera[] = []; private readonly _layoutGraph: LayoutGraphData = new LayoutGraphData(); private readonly _resourceGraph: ResourceGraph = new ResourceGraph(); diff --git a/cocos/core/pipeline/custom/web-scene.ts b/cocos/core/pipeline/custom/web-scene.ts index 594c673448..17877e73dc 100644 --- a/cocos/core/pipeline/custom/web-scene.ts +++ b/cocos/core/pipeline/custom/web-scene.ts @@ -23,14 +23,16 @@ THE SOFTWARE. ****************************************************************************/ -import { AABB, Frustum, intersect, Sphere } from '../../geometry'; +import { intersect, Sphere } from '../../geometry'; import { legacyCC } from '../../global-exports'; -import { Mat4, Vec2, Vec3 } from '../../math'; -import { Camera, DirectionalLight, Model, RenderScene, Shadows, ShadowType, SKYBOX_FLAG, SubModel } from '../../renderer/scene'; +import { Mat4, Vec3, Color } 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 { PipelineSceneData } from '../pipeline-scene-data'; import { SceneTask, SceneTransversal, SceneVisitor } from './pipeline'; import { TaskType } from './types'; +import { ShadowLayerVolume } from '../shadow/csm-layers'; export class RenderObject implements IRenderObject { public model: Model; @@ -41,6 +43,7 @@ export class RenderObject implements IRenderObject { } } export class RenderInfo implements IRenderPass { + public priority = 0; public hash = -1; public depth = -1; public shaderId = -1; @@ -48,18 +51,45 @@ export class RenderInfo implements IRenderPass { public passIdx = -1; } export class WebSceneTask extends SceneTask { - constructor (camera: Camera, visitor: SceneVisitor) { + constructor (scneData: PipelineSceneData, camera: Camera, visitor: SceneVisitor) { super(); this._scene = camera.scene!; this._camera = camera; this._visitor = visitor; + this._sceneData = scneData; } 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 = WebSceneTask._sceneData.shadows; + const shadows = this._sceneData.shadows; const dir = light.direction; const n = shadows.normal; const d = shadows.distance + 0.001; // avoid z-fighting @@ -85,134 +115,6 @@ export class WebSceneTask extends SceneTask { m.m15 = 1; } - protected _getCameraWorldMatrix (out: Mat4, camera: Camera) { - if (!camera.node) { return; } - - const cameraNode = camera.node; - const position = cameraNode.getWorldPosition(); - const rotation = cameraNode.getWorldRotation(); - - Mat4.fromRT(out, rotation, position); - out.m08 *= -1.0; - out.m09 *= -1.0; - out.m10 *= -1.0; - } - - protected _quantizeDirLightShadowCamera (out: Frustum, dirLight: DirectionalLight, - camera: Camera, shadowInfo: Shadows) { - const device = legacyCC.director.root.device; - const _dirLightFrustum = new Frustum(); - const _matShadowTrans = new Mat4(); - const _matShadowView = new Mat4(); - const _matShadowViewInv = new Mat4(); - const _matShadowProj = new Mat4(); - const _matShadowViewProj = new Mat4(); - const _matShadowViewProjArbitaryPos = new Mat4(); - const _matShadowViewProjArbitaryPosInv = new Mat4(); - const _mat4_trans = new Mat4(); - const _validFrustum = new Frustum(); - _validFrustum.accurate = true; - let _lightViewFrustum = new Frustum(); - _lightViewFrustum.accurate = true; - const _castLightViewBounds = new AABB(); - const _shadowPos = new Vec3(); - const _cameraBoundingSphere = new Sphere(); - const _projPos = new Vec3(); - const _texelSize = new Vec2(); - const _projSnap = new Vec3(); - const _snap = new Vec3(); - const _focus = new Vec3(0, 0, 0); - if (dirLight.shadowFixedArea) { - const x = dirLight.shadowOrthoSize; - const y = dirLight.shadowOrthoSize; - const near = dirLight.shadowNear; - const far = dirLight.shadowFar; - Mat4.fromRT(_matShadowTrans, dirLight.node!.getWorldRotation(), dirLight.node!.getWorldPosition()); - Mat4.invert(_matShadowView, _matShadowTrans); - Mat4.ortho(_matShadowProj, -x, x, -y, y, near, far, - device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY); - Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); - Mat4.invert(_matShadowViewInv, _matShadowView); - shadowInfo.matShadowView = _matShadowView; - shadowInfo.matShadowProj = _matShadowProj; - shadowInfo.matShadowViewProj = _matShadowViewProj; - - Frustum.createOrtho(out, x * 2.0, y * 2.0, near, far, _matShadowViewInv); - } else { - const invisibleOcclusionRange = dirLight.shadowInvisibleOcclusionRange; - const shadowMapWidth = shadowInfo.size.x; - - // Raw data - this._getCameraWorldMatrix(_mat4_trans, camera); - Frustum.split(_validFrustum, camera, _mat4_trans, 0.1, dirLight.shadowDistance); - _lightViewFrustum = Frustum.clone(_validFrustum); - - // view matrix with range back - Mat4.fromRT(_matShadowTrans, dirLight.node!.rotation, _focus); - Mat4.invert(_matShadowView, _matShadowTrans); - Mat4.invert(_matShadowViewInv, _matShadowView); - - const shadowViewArbitaryPos = _matShadowView.clone(); - _lightViewFrustum.transform(_matShadowView); - // bounding box in light space - AABB.fromPoints(_castLightViewBounds, new Vec3(10000000, 10000000, 10000000), new Vec3(-10000000, -10000000, -10000000)); - _castLightViewBounds.mergeFrustum(_lightViewFrustum); - - const r = _castLightViewBounds.halfExtents.z * 2.0; - _shadowPos.set(_castLightViewBounds.center.x, _castLightViewBounds.center.y, - _castLightViewBounds.center.z + _castLightViewBounds.halfExtents.z + invisibleOcclusionRange); - Vec3.transformMat4(_shadowPos, _shadowPos, _matShadowViewInv); - - Mat4.fromRT(_matShadowTrans, dirLight.node!.rotation, _shadowPos); - Mat4.invert(_matShadowView, _matShadowTrans); - Mat4.invert(_matShadowViewInv, _matShadowView); - - // calculate projection matrix params - // min value may lead to some shadow leaks - const orthoSizeMin = Vec3.distance(_validFrustum.vertices[0], _validFrustum.vertices[6]); - // max value is accurate but poor usage for shadowmap - _cameraBoundingSphere.center.set(0, 0, 0); - _cameraBoundingSphere.radius = -1.0; - _cameraBoundingSphere.mergePoints(_validFrustum.vertices); - const orthoSizeMax = _cameraBoundingSphere.radius * 2.0; - // use lerp(min, accurate_max) to save shadowmap usage - const orthoSize = orthoSizeMin * 0.8 + orthoSizeMax * 0.2; - shadowInfo.shadowCameraFar = r + invisibleOcclusionRange; - - // snap to whole texels - const halfOrthoSize = orthoSize * 0.5; - Mat4.ortho(_matShadowProj, -halfOrthoSize, halfOrthoSize, -halfOrthoSize, halfOrthoSize, 0.1, shadowInfo.shadowCameraFar, - device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY); - - if (shadowMapWidth > 0.0) { - Mat4.multiply(_matShadowViewProjArbitaryPos, _matShadowProj, shadowViewArbitaryPos); - Vec3.transformMat4(_projPos, _shadowPos, _matShadowViewProjArbitaryPos); - const invActualSize = 2.0 / shadowMapWidth; - _texelSize.set(invActualSize, invActualSize); - const modX = _projPos.x % _texelSize.x; - const modY = _projPos.y % _texelSize.y; - _projSnap.set(_projPos.x - modX, _projPos.y - modY, _projPos.z); - Mat4.invert(_matShadowViewProjArbitaryPosInv, _matShadowViewProjArbitaryPos); - Vec3.transformMat4(_snap, _projSnap, _matShadowViewProjArbitaryPosInv); - - Mat4.fromRT(_matShadowTrans, dirLight.node!.rotation, _snap); - Mat4.invert(_matShadowView, _matShadowTrans); - Mat4.invert(_matShadowViewInv, _matShadowView); - Frustum.createOrtho(out, orthoSize, orthoSize, 0.1, shadowInfo.shadowCameraFar, _matShadowViewInv); - } else { - for (let i = 0; i < 8; i++) { - out.vertices[i].set(0.0, 0.0, 0.0); - } - out.updatePlanes(); - } - - Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); - shadowInfo.matShadowView = _matShadowView; - shadowInfo.matShadowProj = _matShadowProj; - shadowInfo.matShadowViewProj = _matShadowViewProj; - } - } - protected _getRenderObject (model: Model, camera: Camera) { let depth = 0; if (model.node) { @@ -228,30 +130,21 @@ export class WebSceneTask extends SceneTask { const scene = this._scene; const camera = this._camera; const mainLight = scene.mainLight; - const sceneData = WebSceneTask._sceneData; + 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 = sceneData.castShadowObjects; + const castShadowObjects = csmLayers.castShadowObjects; castShadowObjects.length = 0; - let dirShadowObjects: IRenderObject[] | null = null; + if (shadows.enabled) { if (shadows.type === ShadowType.ShadowMap) { - dirShadowObjects = sceneData.dirShadowObjects; - dirShadowObjects.length = 0; - - // update dirLightFrustum - if (mainLight && mainLight.node) { - this._quantizeDirLightShadowCamera(this._dirLightFrustum, mainLight, camera, shadows); - } else { - for (let i = 0; i < 8; i++) { - this._dirLightFrustum.vertices[i].set(0.0, 0.0, 0.0); - } - this._dirLightFrustum.updatePlanes(); - } + // update lightFrustum + csmLayers.update(sceneData, camera); } } @@ -279,14 +172,6 @@ export class WebSceneTask extends SceneTask { if (model.node && ((visibility & model.node.layer) === model.node.layer) || (visibility & model.visFlags)) { - // shadow render Object - if (dirShadowObjects != null && model.castShadow && model.worldBounds) { - // frustum culling - // eslint-disable-next-line no-lonely-if - if (intersect.aabbFrustum(model.worldBounds, this._dirLightFrustum)) { - dirShadowObjects.push(this._getRenderObject(model, camera)); - } - } // frustum culling if (model.worldBounds && !intersect.aabbFrustum(model.worldBounds, camera.frustum)) { continue; @@ -312,27 +197,30 @@ export class WebSceneTask extends SceneTask { return this._scene; } get visitor () { return this._visitor; } - get dirLightFrustum () { return this._dirLightFrustum; } - static GetSceneData () { - return this._sceneData; - } - get sceneData () { return WebSceneTask._sceneData; } + get sceneData (): PipelineSceneData { return this._sceneData; } private _scene: RenderScene; private _camera: Camera; private _visitor: SceneVisitor; - private static _sceneData: PipelineSceneData = new PipelineSceneData(); - private _dirLightFrustum = new Frustum(); + private _sceneData: PipelineSceneData; } export class WebSceneTransversal extends SceneTransversal { - constructor (camera: Camera) { + public preRenderPass (visitor: SceneVisitor): SceneTask { + return new WebSceneTask(this._sceneData, this._camera, visitor); + } + public postRenderPass (visitor: SceneVisitor): SceneTask { + return new WebSceneTask(this._sceneData, this._camera, visitor); + } + constructor (camera: Camera, sceneData: PipelineSceneData) { super(); this._camera = camera; this._scene = camera.scene!; + this._sceneData = sceneData; } public transverse (visitor: SceneVisitor): SceneTask { - return new WebSceneTask(this._camera, visitor); + return new WebSceneTask(this._sceneData, this._camera, visitor); } - private _scene: RenderScene; - private _camera: Camera; + protected _scene: RenderScene; + protected _camera: Camera; + protected _sceneData: PipelineSceneData; } diff --git a/cocos/core/pipeline/debug-view.ts b/cocos/core/pipeline/debug-view.ts new file mode 100644 index 0000000000..7a84e920f6 --- /dev/null +++ b/cocos/core/pipeline/debug-view.ts @@ -0,0 +1,282 @@ +/* + 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 { JSB } from 'internal:constants'; +import { legacyCC } from '../global-exports'; +import { Root } from '../root'; +import { Enum } from '../value-types'; +import { director } from '..'; + +const enum RenderingDebugViewType { + NONE, + SINGLE, + COMPOSITE_AND_MISC, +} + +/** + * @zh + * 渲染单项调试模式 + * @en + * Rendering single debug mode + * @readonly + */ +export const enum DebugViewSingleType { + NONE, + VERTEX_COLOR, + VERTEX_NORMAL, + VERTEX_TANGENT, + WORLD_POS, + VERTEX_MIRROR, + FACE_SIDE, + UV0, + UV1, + UV_LIGHTMAP, + PROJ_DEPTH, + LINEAR_DEPTH, + + FRAGMENT_NORMAL, + FRAGMENT_TANGENT, + FRAGMENT_BINORMAL, + BASE_COLOR, + DIFFUSE_COLOR, + SPECULAR_COLOR, + TRANSPARENCY, + METALLIC, + ROUGHNESS, + SPECULAR_INTENSITY, + + DIRECT_DIFFUSE, + DIRECT_SPECULAR, + DIRECT_ALL, + ENV_DIFFUSE, + ENV_SPECULAR, + ENV_ALL, + EMISSIVE, + LIGHT_MAP, + SHADOW, + AO, + + FOG, +} + +/** + * @zh + * 渲染组合调试模式 + * @en + * Rendering composite debug mode + * @readonly + */ +export const enum DebugViewCompositeType { + DIRECT_DIFFUSE = 0, + DIRECT_SPECULAR, + ENV_DIFFUSE, + ENV_SPECULAR, + EMISSIVE, + LIGHT_MAP, + SHADOW, + AO, + + NORMAL_MAP, + FOG, + + TONE_MAPPING, + GAMMA_CORRECTION, + MAX_BIT_COUNT +} + +/** + * @en Rendering debug view control class + * @zh 渲染调试控制类 + */ +export class DebugView { + /** + * @en Toggle rendering single debug mode. + * @zh 设置渲染单项调试模式。 + */ + public get singleMode () : DebugViewSingleType { + return this._singleMode; + } + public set singleMode (val : DebugViewSingleType) { + this._singleMode = val; + this._updatePipeline(); + + if (JSB && this._nativeConfig) { + this._nativeConfig.singleMode = this._singleMode; + } + } + + /** + * @en Toggle normal / pure lighting mode. + * @zh 切换正常光照和仅光照模式。 + */ + public get lightingWithAlbedo () : boolean { + return this._lightingWithAlbedo; + } + public set lightingWithAlbedo (val : boolean) { + this._lightingWithAlbedo = val; + this._updatePipeline(); + + if (JSB && this._nativeConfig) { + this._nativeConfig.lightingWithAlbedo = this._lightingWithAlbedo; + } + } + + /** + * @en Toggle CSM layer coloration mode. + * @zh 切换级联阴影染色调试模式。 + */ + public get csmLayerColoration () : boolean { + return this._csmLayerColoration; + } + public set csmLayerColoration (val : boolean) { + this._csmLayerColoration = val; + this._updatePipeline(); + + if (JSB && this._nativeConfig) { + this._nativeConfig.csmLayerColoration = this._csmLayerColoration; + } + } + + protected _singleMode = DebugViewSingleType.NONE; + protected _compositeModeValue = 0; + protected _lightingWithAlbedo = true; + protected _csmLayerColoration = false; + protected _nativeConfig: any = null; + + constructor () { + this._activate(); + if (JSB && this._nativeConfig === null) { + // @ts-expect-error jsb object access + this._nativeConfig = new jsb.DebugViewConfig(); + this._nativeConfig.compositeModeBitCount = DebugViewCompositeType.MAX_BIT_COUNT; + } + } + + /** + * @en Whether enabled with specified rendering composite debug mode. + * @zh 获取指定的渲染组合调试模式是否开启。 + * @param Specified composite type. + */ + public isCompositeModeEnabled (val : number) : boolean { + const mode = this._compositeModeValue & (1 << val); + return mode !== 0; + } + /** + * @en Toggle specified rendering composite debug mode. + * @zh 开关指定的渲染组合调试模式。 + * @param Specified composite type, enable or disable. + */ + public enableCompositeMode (val: DebugViewCompositeType, enable: boolean) { + this._enableCompositeMode(val, enable); + this._updatePipeline(); + } + + /** + * @en Toggle all rendering composite debug mode. + * @zh 开关所有的渲染组合调试模式。 + */ + public enableAllCompositeMode (enable: boolean) { + this._enableAllCompositeMode(enable); + this._updatePipeline(); + } + + /** + * @en Get rendering debug view on / off state. + * @zh 查询当前是否开启了渲染调试模式。 + */ + public isEnabled () { + return this._getType() !== RenderingDebugViewType.NONE; + } + + /** + * @internal + */ + protected _activate () { + this._singleMode = DebugViewSingleType.NONE; + this._enableAllCompositeMode(true); + this._lightingWithAlbedo = true; + this._csmLayerColoration = false; + + if (JSB && this._nativeConfig) { + this._nativeConfig.singleMode = this._singleMode; + this._nativeConfig.compositeModeValue = this._compositeModeValue; + this._nativeConfig.lightingWithAlbedo = this._lightingWithAlbedo; + this._nativeConfig.csmLayerColoration = this._csmLayerColoration; + } + } + + protected _updatePipeline () { + const root = legacyCC.director.root as Root; + const pipeline = root.pipeline; + + const useDebugView = this._getType(); + + if (pipeline.macros.CC_USE_DEBUG_VIEW !== useDebugView) { + pipeline.macros.CC_USE_DEBUG_VIEW = useDebugView; + root.onGlobalPipelineStateChanged(); + } + } + + private _enableCompositeMode (val: DebugViewCompositeType, enable: boolean) { + if (enable) { + this._compositeModeValue |= (1 << val); + } else { + this._compositeModeValue &= (~(1 << val)); + } + + if (JSB && this._nativeConfig) { + this._nativeConfig.compositeModeValue = this._compositeModeValue; + } + } + + private _enableAllCompositeMode (enable: boolean) { + for (let i = 0; i < DebugViewCompositeType.MAX_BIT_COUNT; i++) { + if (enable) { + this._compositeModeValue |= (1 << i); + } else { + this._compositeModeValue &= (~(1 << i)); + } + + if (JSB && this._nativeConfig) { + this._nativeConfig.compositeModeValue = this._compositeModeValue; + } + } + } + + private _getType () : RenderingDebugViewType { + if (this._singleMode !== DebugViewSingleType.NONE) { + return RenderingDebugViewType.SINGLE; + } else if (this._lightingWithAlbedo !== true || this._csmLayerColoration !== false) { + return RenderingDebugViewType.COMPOSITE_AND_MISC; + } else { + for (let i = 0; i < DebugViewCompositeType.MAX_BIT_COUNT; i++) { + if (!this.isCompositeModeEnabled(i)) { + return RenderingDebugViewType.COMPOSITE_AND_MISC; + } + } + } + return RenderingDebugViewType.NONE; + } +} diff --git a/cocos/core/pipeline/deferred/deferred-pipeline-scene-data.ts b/cocos/core/pipeline/deferred/deferred-pipeline-scene-data.ts index 87d1e813f2..60e3a24aaf 100644 --- a/cocos/core/pipeline/deferred/deferred-pipeline-scene-data.ts +++ b/cocos/core/pipeline/deferred/deferred-pipeline-scene-data.ts @@ -127,14 +127,14 @@ export class DeferredPipelineSceneData extends PipelineSceneData { // builtin deferred material const deferredMat = new Material(); deferredMat._uuid = 'builtin-deferred-material'; - deferredMat.initialize({ effectName: 'deferred-lighting' }); + deferredMat.initialize({ effectName: 'pipeline/deferred-lighting' }); for (let i = 0; i < deferredMat.passes.length; ++i) { deferredMat.passes[i].tryCompile(); } this._deferredLightingMaterial = deferredMat; const bloomMat = new Material(); bloomMat._uuid = 'builtin-bloom-material'; - bloomMat.initialize({ effectName: 'bloom' }); + bloomMat.initialize({ effectName: 'pipeline/bloom' }); for (let i = 0; i < bloomMat.passes.length; ++i) { bloomMat.passes[i].tryCompile(); } @@ -146,7 +146,7 @@ export class DeferredPipelineSceneData extends PipelineSceneData { this._antiAliasing = AntiAliasing.FXAA; } postMat.initialize({ - effectName: 'post-process', + effectName: 'pipeline/post-process', defines: { // Anti-aliasing type, currently only fxaa, so 1 means fxaa ANTIALIAS_TYPE: this._antiAliasing, @@ -193,9 +193,7 @@ export class DeferredPipelineSceneData extends PipelineSceneData { if (!this._deferredLightingMaterial) return; // It's temporary solution for main light shadowmap - if (this.shadows.enabled) { - legacyCC.director.root.pipeline.macros.CC_RECEIVE_SHADOW = 1; - } + legacyCC.director.root.pipeline.macros.CC_RECEIVE_SHADOW = 1; const passLit = this._deferredLightingMaterial.passes[0]; passLit.beginChangeStatesSilently(); diff --git a/cocos/core/pipeline/deferred/deferred-pipeline.ts b/cocos/core/pipeline/deferred/deferred-pipeline.ts index dd5f388bd2..97b3d304c9 100644 --- a/cocos/core/pipeline/deferred/deferred-pipeline.ts +++ b/cocos/core/pipeline/deferred/deferred-pipeline.ts @@ -39,7 +39,7 @@ import { Format, StoreOp, ColorAttachment, DepthStencilAttachment, RenderPass, LoadOp, RenderPassInfo, Texture, AccessFlagBit, Framebuffer, TextureInfo, TextureType, TextureUsageBit, FramebufferInfo, Swapchain, GeneralBarrierInfo } from '../../gfx'; -import { UBOGlobal, UBOCamera, UBOShadow, UNIFORM_SHADOWMAP_BINDING, UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING } from '../define'; +import { UBOGlobal, UBOCamera, UBOShadow, UNIFORM_SHADOWMAP_BINDING, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING } from '../define'; import { Camera } from '../../renderer/scene'; import { errorID } from '../../platform/debug'; import { DeferredPipelineSceneData } from './deferred-pipeline-scene-data'; @@ -140,8 +140,8 @@ export class DeferredPipeline extends RenderPipeline { const sampler = this.globalDSManager.pointSampler; this._descriptorSet.bindSampler(UNIFORM_SHADOWMAP_BINDING, sampler); this._descriptorSet.bindTexture(UNIFORM_SHADOWMAP_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); - this._descriptorSet.bindSampler(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING, sampler); - this._descriptorSet.bindTexture(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); + this._descriptorSet.bindSampler(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, sampler); + this._descriptorSet.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, builtinResMgr.get('default-texture').getGFXTexture()!); this._descriptorSet.update(); let inputAssemblerDataOffscreen = new PipelineInputAssemblerData(); @@ -227,7 +227,7 @@ export class DeferredPipeline extends RenderPipeline { this._descriptorSet.getBuffer(UBOShadow.BINDING).destroy(); this._descriptorSet.getBuffer(UBOCamera.BINDING).destroy(); this._descriptorSet.getTexture(UNIFORM_SHADOWMAP_BINDING).destroy(); - this._descriptorSet.getTexture(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING).destroy(); + this._descriptorSet.getTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING).destroy(); } } @@ -310,12 +310,14 @@ export class DeferredPipeline extends RenderPipeline { data.outputRenderTargets, null, )); + + data.sampler = this.globalDSManager.pointSampler; + // Listens when the attachment texture is scaled this.on(PipelineEventType.ATTACHMENT_SCALE_CAHNGED, (val: number) => { data.sampler = val < 1 ? this.globalDSManager.pointSampler : this.globalDSManager.linearSampler; this.applyFramebufferRatio(data.gbufferFrameBuffer); this.applyFramebufferRatio(data.outputFrameBuffer); }); - data.sampler = this.globalDSManager.linearSampler; } } diff --git a/cocos/core/pipeline/deferred/lighting-stage.ts b/cocos/core/pipeline/deferred/lighting-stage.ts index a2cd0bbad2..b8d451cfe3 100644 --- a/cocos/core/pipeline/deferred/lighting-stage.ts +++ b/cocos/core/pipeline/deferred/lighting-stage.ts @@ -29,7 +29,7 @@ import { ccclass, displayOrder, type, serializable } from 'cc.decorator'; import { Camera } from '../../renderer/scene'; -import { localDescriptorSetLayout, UBODeferredLight, SetIndex, UBOForwardLight } from '../define'; +import { UBODeferredLight, SetIndex, UBOForwardLight, UBOLocal } from '../define'; import { getPhaseID } from '../pass-phase'; import { Color, Rect, Buffer, BufferUsageBit, MemoryUsageBit, BufferInfo, BufferViewInfo, DescriptorSet, DescriptorSetLayoutInfo, DescriptorSetLayout, DescriptorSetInfo, PipelineState, ClearFlagBit } from '../../gfx'; @@ -46,6 +46,7 @@ import { DeferredPipelineSceneData } from './deferred-pipeline-scene-data'; import { renderQueueClearFunc, RenderQueue, convertRenderQueue, renderQueueSortFunc } from '../render-queue'; import { RenderQueueDesc } from '../pipeline-serialization'; import { UIPhase } from '../ui-phase'; +import { Pass } from '../../renderer/core/pass'; const colors: Color[] = [new Color(0, 0, 0, 1)]; @@ -183,16 +184,8 @@ export class LightingStage extends RenderStage { cmdBuff.updateBuffer(this._deferredLitsBufs, this._lightBufferData); } - public activate (pipeline: DeferredPipeline, flow: MainFlow) { - super.activate(pipeline, flow); - this._uiPhase.activate(pipeline); - const device = pipeline.device; - - // activate queue - for (let i = 0; i < this.renderQueues.length; i++) { - this._renderQueues[i] = convertRenderQueue(this.renderQueues[i]); - } - + protected _createStageDescriptor (pass: Pass) { + const device = this._pipeline.device; let totalSize = Float32Array.BYTES_PER_ELEMENT * 4 * 4 * this._maxDeferredLights; totalSize = Math.ceil(totalSize / device.capabilities.uboOffsetAlignment) * device.capabilities.uboOffsetAlignment; @@ -206,11 +199,27 @@ export class LightingStage extends RenderStage { const deferredLitsBufView = device.createBuffer(new BufferViewInfo(this._deferredLitsBufs, 0, totalSize)); this._lightBufferData = new Float32Array(totalSize / Float32Array.BYTES_PER_ELEMENT); - const layoutInfo = new DescriptorSetLayoutInfo(localDescriptorSetLayout.bindings); - this._descriptorSetLayout = device.createDescriptorSetLayout(layoutInfo); - this._descriptorSet = device.createDescriptorSet(new DescriptorSetInfo(this._descriptorSetLayout)); + this._descriptorSet = device.createDescriptorSet(new DescriptorSetInfo(pass.localSetLayout)); this._descriptorSet.bindBuffer(UBOForwardLight.BINDING, deferredLitsBufView); + const _localUBO = device.createBuffer(new BufferInfo( + BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.DEVICE, + UBOLocal.SIZE, + UBOLocal.SIZE, + )); + this._descriptorSet.bindBuffer(UBOLocal.BINDING, _localUBO); + } + + public activate (pipeline: DeferredPipeline, flow: MainFlow) { + super.activate(pipeline, flow); + this._uiPhase.activate(pipeline); + + // activate queue + for (let i = 0; i < this.renderQueues.length; i++) { + this._renderQueues[i] = convertRenderQueue(this.renderQueues[i]); + } + this._planarQueue = new PlanarShadowQueue(this._pipeline as DeferredPipeline); if (this._deferredMaterial) { (pipeline.pipelineSceneData as DeferredPipelineSceneData).deferredLightingMaterial = this._deferredMaterial; } @@ -221,7 +230,6 @@ export class LightingStage extends RenderStage { this._deferredLitsBufs = null!; this._descriptorSet = null!; } - public render (camera: Camera) { const pipeline = this._pipeline as DeferredPipeline; const device = pipeline.device; @@ -230,36 +238,11 @@ export class LightingStage extends RenderStage { const sceneData = pipeline.pipelineSceneData; const renderObjects = sceneData.renderObjects; - // light信息 - this.gatherLights(camera); - this._descriptorSet.update(); this._planarQueue.gatherShadowPasses(camera, cmdBuff); - const dynamicOffsets: number[] = [0]; - cmdBuff.bindDescriptorSet(SetIndex.LOCAL, this._descriptorSet, dynamicOffsets); - pipeline.generateRenderArea(camera, this._renderArea); - - if (camera.clearFlag & ClearFlagBit.COLOR) { - colors[0].x = camera.clearColor.x; - colors[0].y = camera.clearColor.y; - colors[0].z = camera.clearColor.z; - } - - colors[0].w = 0; - const deferredData = pipeline.getPipelineRenderData(); - const framebuffer = deferredData.outputFrameBuffer; - const renderPass = framebuffer.renderPass; - - pipeline.pipelineUBO.updateShadowUBO(camera); - - cmdBuff.beginRenderPass(renderPass, framebuffer, this._renderArea, - colors, camera.clearDepth, camera.clearStencil); - cmdBuff.setScissor(pipeline.generateScissor(camera)); - cmdBuff.setViewport(pipeline.generateViewport(camera)); - cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet); - // Lighting + const deferredData = pipeline.getPipelineRenderData(); const lightingMat = (sceneData as DeferredPipelineSceneData).deferredLightingMaterial; const pass = lightingMat.passes[0]; const shader = pass.getShaderVariant(); @@ -271,8 +254,30 @@ export class LightingStage extends RenderStage { pass.descriptorSet.bindTexture(3, deferredData.outputDepth); pass.descriptorSet.bindSampler(3, deferredData.sampler); pass.descriptorSet.update(); + if (!this._descriptorSet) { + this._createStageDescriptor(pass); + } + // light信息 + this.gatherLights(camera); - cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); + if (camera.clearFlag & ClearFlagBit.COLOR) { + colors[0].x = camera.clearColor.x; + colors[0].y = camera.clearColor.y; + colors[0].z = camera.clearColor.z; + } + + colors[0].w = 0; + + const framebuffer = deferredData.outputFrameBuffer; + const renderPass = framebuffer.renderPass; + + pipeline.pipelineUBO.updateShadowUBO(camera); + + cmdBuff.beginRenderPass(renderPass, framebuffer, this._renderArea, + colors, camera.clearDepth, camera.clearStencil); + cmdBuff.setScissor(pipeline.generateScissor(camera)); + cmdBuff.setViewport(pipeline.generateViewport(camera)); + cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet); const inputAssembler = pipeline.quadIAOffscreen; let pso:PipelineState|null = null; @@ -281,7 +286,10 @@ export class LightingStage extends RenderStage { } if (pso != null) { + this._descriptorSet.update(); cmdBuff.bindPipelineState(pso); + cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); + cmdBuff.bindDescriptorSet(SetIndex.LOCAL, this._descriptorSet); cmdBuff.bindInputAssembler(inputAssembler); cmdBuff.draw(inputAssembler); } @@ -314,7 +322,7 @@ export class LightingStage extends RenderStage { // planarQueue this._planarQueue.recordCommandBuffer(device, renderPass, cmdBuff); } - camera.geometryRenderer.render(renderPass, cmdBuff, pipeline.pipelineSceneData); + camera.geometryRenderer?.render(renderPass, cmdBuff, pipeline.pipelineSceneData); this._uiPhase.render(camera, renderPass); cmdBuff.endRenderPass(); } diff --git a/cocos/core/pipeline/deferred/postprocess-stage.ts b/cocos/core/pipeline/deferred/postprocess-stage.ts index eca7019df1..83ecd7ce8a 100644 --- a/cocos/core/pipeline/deferred/postprocess-stage.ts +++ b/cocos/core/pipeline/deferred/postprocess-stage.ts @@ -28,8 +28,8 @@ */ import { ccclass, displayOrder, type, serializable } from 'cc.decorator'; import { Camera } from '../../renderer/scene'; -import { SetIndex } from '../define'; -import { Color, Rect, PipelineState, ClearFlagBit } from '../../gfx'; +import { SetIndex, UBOLocal } from '../define'; +import { Color, Rect, PipelineState, ClearFlagBit, DescriptorSetInfo, BufferInfo, BufferUsageBit, MemoryUsageBit } from '../../gfx'; import { IRenderStageInfo, RenderStage } from '../render-stage'; import { CommonStagePriority } from '../enum'; import { Material } from '../../assets/material'; @@ -66,7 +66,8 @@ export class PostProcessStage extends RenderStage { private _renderArea = new Rect(); private declare _uiPhase: UIPhase; - + private _stageDesc; + private _localUBO; constructor () { super(); this._uiPhase = new UIPhase(); @@ -85,7 +86,6 @@ export class PostProcessStage extends RenderStage { public destroy () { } - public render (camera: Camera) { const pipeline = this._pipeline; const device = pipeline.device; @@ -126,8 +126,6 @@ export class PostProcessStage extends RenderStage { pass.descriptorSet.bindSampler(0, renderData.sampler); pass.descriptorSet.update(); - cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); - const inputAssembler = camera.window.swapchain ? pipeline.quadIAOnscreen : pipeline.quadIAOffscreen; let pso: PipelineState | null = null; if (pass != null && shader != null && inputAssembler != null) { @@ -136,7 +134,20 @@ export class PostProcessStage extends RenderStage { const renderObjects = pipeline.pipelineSceneData.renderObjects; if (pso != null && renderObjects.length > 0) { + if (!this._stageDesc) { + this._stageDesc = device.createDescriptorSet(new DescriptorSetInfo(pass.localSetLayout)); + this._localUBO = device.createBuffer(new BufferInfo( + BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.DEVICE, + UBOLocal.SIZE, + UBOLocal.SIZE, + )); + this._stageDesc.bindBuffer(UBOLocal.BINDING, this._localUBO); + } + this._stageDesc.update(); cmdBuff.bindPipelineState(pso); + cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet); + cmdBuff.bindDescriptorSet(SetIndex.LOCAL, this._stageDesc); cmdBuff.bindInputAssembler(inputAssembler); cmdBuff.draw(inputAssembler); } diff --git a/cocos/core/pipeline/define.ts b/cocos/core/pipeline/define.ts index 5089d91387..d78b7b2b85 100644 --- a/cocos/core/pipeline/define.ts +++ b/cocos/core/pipeline/define.ts @@ -23,19 +23,13 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline - */ - import { Pass } from '../renderer/core/pass'; import { Model } from '../renderer/scene/model'; import { SubModel } from '../renderer/scene/submodel'; import { Layers } from '../scene-graph/layers'; import { legacyCC } from '../global-exports'; -import { BindingMappingInfo, DescriptorType, Type, ShaderStageFlagBit, UniformStorageBuffer, - DescriptorSetLayoutBinding, Uniform, UniformBlock, UniformSamplerTexture, UniformStorageImage, Device, - Feature, API, FormatFeatureBit, Format, +import { BindingMappingInfo, DescriptorType, Type, ShaderStageFlagBit, UniformStorageBuffer, DescriptorSetLayoutBinding, + Uniform, UniformBlock, UniformSamplerTexture, UniformStorageImage, Device, FormatFeatureBit, Format, } from '../gfx'; export const PIPELINE_FLOW_MAIN = 'MainFlow'; @@ -78,6 +72,7 @@ export interface IRenderObject { * @zh 渲染过程接口。 */ export interface IRenderPass { + priority: number; hash: number; depth: number; shaderId: number; @@ -122,7 +117,7 @@ export enum PipelineGlobalBindings { 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 - SAMPLER_SPOT_LIGHTING_MAP, + SAMPLER_SPOT_SHADOW_MAP, SAMPLER_DIFFUSEMAP, COUNT, @@ -177,9 +172,15 @@ export const bindingMappingInfo = new BindingMappingInfo( */ export class UBOGlobal { public static readonly TIME_OFFSET = 0; - public static readonly NATIVE_SIZE_OFFSET = UBOGlobal.TIME_OFFSET + 4; - public static readonly SCREEN_SIZE_OFFSET = UBOGlobal.NATIVE_SIZE_OFFSET + 4; - public static readonly COUNT = UBOGlobal.SCREEN_SIZE_OFFSET + 4; + public static readonly SCREEN_SIZE_OFFSET = UBOGlobal.TIME_OFFSET + 4; + public static readonly NATIVE_SIZE_OFFSET = UBOGlobal.SCREEN_SIZE_OFFSET + 4; + + public static readonly DEBUG_VIEW_MODE_OFFSET = UBOGlobal.NATIVE_SIZE_OFFSET + 4; + public static readonly DEBUG_VIEW_COMPOSITE_PACK_1_OFFSET = UBOGlobal.DEBUG_VIEW_MODE_OFFSET + 4; + public static readonly DEBUG_VIEW_COMPOSITE_PACK_2_OFFSET = UBOGlobal.DEBUG_VIEW_COMPOSITE_PACK_1_OFFSET + 4; + public static readonly DEBUG_VIEW_COMPOSITE_PACK_3_OFFSET = UBOGlobal.DEBUG_VIEW_COMPOSITE_PACK_2_OFFSET + 4; + + public static readonly COUNT = UBOGlobal.DEBUG_VIEW_COMPOSITE_PACK_3_OFFSET + 4; public static readonly SIZE = UBOGlobal.COUNT * 4; public static readonly NAME = 'CCGlobal'; @@ -189,6 +190,11 @@ export class UBOGlobal { new Uniform('cc_time', Type.FLOAT4, 1), new Uniform('cc_screenSize', Type.FLOAT4, 1), new Uniform('cc_nativeSize', Type.FLOAT4, 1), + + new Uniform('cc_debug_view_mode', Type.FLOAT, 4), + new Uniform('cc_debug_view_composite_pack_1', Type.FLOAT, 4), + new Uniform('cc_debug_view_composite_pack_2', Type.FLOAT, 4), + new Uniform('cc_debug_view_composite_pack_3', Type.FLOAT, 4), ], 1); } globalDescriptorSetLayout.layouts[UBOGlobal.NAME] = UBOGlobal.LAYOUT; @@ -251,9 +257,10 @@ globalDescriptorSetLayout.bindings[UBOCamera.BINDING] = UBOCamera.DESCRIPTOR; /** * @en The uniform buffer object for shadow - * @zh 阴影 UBO。 + * @zh 给阴影对象使用的 UBO */ 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_PROJ_OFFSET = UBOShadow.MAT_LIGHT_VIEW_OFFSET + 16; @@ -265,7 +272,14 @@ 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 COUNT: number = UBOShadow.PLANAR_NORMAL_DISTANCE_INFO_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 SIZE = UBOShadow.COUNT * 4; public static readonly NAME = 'CCShadow'; public static readonly BINDING = PipelineGlobalBindings.UBO_SHADOW; @@ -282,6 +296,13 @@ 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; @@ -291,7 +312,7 @@ globalDescriptorSetLayout.bindings[UBOShadow.BINDING] = UBOShadow.DESCRIPTOR; /** * @en The sampler for Main light shadow map - * @zn 主光源阴影纹理采样器 + * @zh 主光源阴影纹理采样器 */ const UNIFORM_SHADOWMAP_NAME = 'cc_shadowMap'; export const UNIFORM_SHADOWMAP_BINDING = PipelineGlobalBindings.SAMPLER_SHADOWMAP; @@ -316,14 +337,14 @@ globalDescriptorSetLayout.bindings[UNIFORM_DIFFUSEMAP_BINDING] = UNIFORM_DIFFUSE /** * @en The sampler for spot light shadow map - * @zn 聚光灯阴影纹理采样器 + * @zh 聚光灯阴影纹理采样器 */ -const UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_NAME = 'cc_spotLightingMap'; -export const UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING = PipelineGlobalBindings.SAMPLER_SPOT_LIGHTING_MAP; -const UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT); -const UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.GLOBAL, UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING, UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_NAME, Type.SAMPLER2D, 1); -globalDescriptorSetLayout.layouts[UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_NAME] = UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_LAYOUT; -globalDescriptorSetLayout.bindings[UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING] = UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_DESCRIPTOR; +const UNIFORM_SPOT_SHADOW_MAP_TEXTURE_NAME = 'cc_spotShadowMap'; +export const UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING = PipelineGlobalBindings.SAMPLER_SPOT_SHADOW_MAP; +const UNIFORM_SPOT_SHADOW_MAP_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.FRAGMENT); +const UNIFORM_SPOT_SHADOW_MAP_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.GLOBAL, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_NAME, Type.SAMPLER2D, 1); +globalDescriptorSetLayout.layouts[UNIFORM_SPOT_SHADOW_MAP_TEXTURE_NAME] = UNIFORM_SPOT_SHADOW_MAP_TEXTURE_LAYOUT; +globalDescriptorSetLayout.bindings[UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING] = UNIFORM_SPOT_SHADOW_MAP_TEXTURE_DESCRIPTOR; /** * @en The local uniform buffer object @@ -458,19 +479,39 @@ localDescriptorSetLayout.bindings[UBOSkinningAnimation.BINDING] = UBOSkinningAni export const INST_JOINT_ANIM_INFO = 'a_jointAnimInfo'; export class UBOSkinning { - public static readonly JOINTS_OFFSET = 0; - public static readonly COUNT = UBOSkinning.JOINTS_OFFSET + JOINT_UNIFORM_CAPACITY * 12; - public static readonly SIZE = UBOSkinning.COUNT * 4; + private static _jointUniformCapacity = 0; + public static get JOINT_UNIFORM_CAPACITY () { return UBOSkinning._jointUniformCapacity; } + private static _count = 0; + public static get COUNT () { return UBOSkinning._count; } + private static _size = 0; + public static get SIZE () { return UBOSkinning._size; } public static readonly NAME = 'CCSkinning'; public static readonly BINDING = ModelLocalBindings.UBO_SKINNING_TEXTURE; public static readonly DESCRIPTOR = new DescriptorSetLayoutBinding(UBOSkinning.BINDING, DescriptorType.UNIFORM_BUFFER, 1, ShaderStageFlagBit.VERTEX); public static readonly LAYOUT = new UniformBlock(SetIndex.LOCAL, UBOSkinning.BINDING, UBOSkinning.NAME, [ - new Uniform('cc_joints', Type.FLOAT4, JOINT_UNIFORM_CAPACITY * 3), + new Uniform('cc_joints', Type.FLOAT4, 1), ], 1); + + /** + * @internal This method only used init UBOSkinning configure. + */ + public static initLayout (capacity: number) { + UBOSkinning._jointUniformCapacity = capacity; + UBOSkinning._count = capacity * 12; + UBOSkinning._size = UBOSkinning._count * 4; + UBOSkinning.LAYOUT.members[0].count = capacity * 3; + } +} + +/** + * @internal This method only used to init localDescriptorSetLayout.layouts[UBOSkinning.NAME] +*/ +export function localDescriptorSetLayout_ResizeMaxJoints (maxCount: number) { + UBOSkinning.initLayout(maxCount); + localDescriptorSetLayout.layouts[UBOSkinning.NAME] = UBOSkinning.LAYOUT; + localDescriptorSetLayout.bindings[UBOSkinning.BINDING] = UBOSkinning.DESCRIPTOR; } -localDescriptorSetLayout.layouts[UBOSkinning.NAME] = UBOSkinning.LAYOUT; -localDescriptorSetLayout.bindings[UBOSkinning.BINDING] = UBOSkinning.DESCRIPTOR; /** * @en The uniform buffer object for morph setting @@ -519,6 +560,17 @@ const UNIFORM_JOINT_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, U localDescriptorSetLayout.layouts[UNIFORM_JOINT_TEXTURE_NAME] = UNIFORM_JOINT_TEXTURE_LAYOUT; localDescriptorSetLayout.bindings[UNIFORM_JOINT_TEXTURE_BINDING] = UNIFORM_JOINT_TEXTURE_DESCRIPTOR; +/** + * @en The sampler for real-time joint texture + * @zh 实时骨骼纹理采样器。 + */ +const UNIFORM_REALTIME_JOINT_TEXTURE_NAME = 'cc_realtimeJoint'; +export const UNIFORM_REALTIME_JOINT_TEXTURE_BINDING = ModelLocalBindings.SAMPLER_JOINTS; +const UNIFORM_REALTIME_JOINT_TEXTURE_DESCRIPTOR = new DescriptorSetLayoutBinding(UNIFORM_REALTIME_JOINT_TEXTURE_BINDING, DescriptorType.SAMPLER_TEXTURE, 1, ShaderStageFlagBit.VERTEX); +const UNIFORM_REALTIME_JOINT_TEXTURE_LAYOUT = new UniformSamplerTexture(SetIndex.LOCAL, UNIFORM_REALTIME_JOINT_TEXTURE_BINDING, UNIFORM_REALTIME_JOINT_TEXTURE_NAME, Type.SAMPLER2D, 1); +localDescriptorSetLayout.layouts[UNIFORM_REALTIME_JOINT_TEXTURE_NAME] = UNIFORM_REALTIME_JOINT_TEXTURE_LAYOUT; +localDescriptorSetLayout.bindings[UNIFORM_REALTIME_JOINT_TEXTURE_BINDING] = UNIFORM_REALTIME_JOINT_TEXTURE_DESCRIPTOR; + /** * @en The sampler for morph texture of position * @zh 位置形变纹理采样器。 diff --git a/native/cocos/bindings/jswrapper/jsc/PlatformUtils.h b/cocos/core/pipeline/deprecated.ts similarity index 74% rename from native/cocos/bindings/jswrapper/jsc/PlatformUtils.h rename to cocos/core/pipeline/deprecated.ts index f14838906b..f97e0c6d0e 100644 --- a/native/cocos/bindings/jswrapper/jsc/PlatformUtils.h +++ b/cocos/core/pipeline/deprecated.ts @@ -1,8 +1,7 @@ -/**************************************************************************** - Copyright (c) 2016 Chukong Technologies Inc. - Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. +/* + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. - http://www.cocos.com + 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, @@ -22,13 +21,15 @@ 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. -****************************************************************************/ + */ -#pragma once +import { markAsWarning } from '../utils'; +import { RenderPipeline } from './render-pipeline'; -namespace se { - -bool isSupportTypedArrayAPI(); -bool isSupportArrayTestAPI(); - -} // namespace se +// deprecate RenderPipeline API +markAsWarning(RenderPipeline.prototype, 'RenderPipeline.prototype', [ + { + name: 'geometryRenderer', + suggest: 'please use camera.geometryRenderer instead.', + }, +]); diff --git a/cocos/core/pipeline/enum.ts b/cocos/core/pipeline/enum.ts index 67e9c387d6..8526744713 100644 --- a/cocos/core/pipeline/enum.ts +++ b/cocos/core/pipeline/enum.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline - */ - export enum CommonStagePriority { BLOOM = 18, POST_PROCESS = 19, diff --git a/cocos/core/pipeline/forward/forward-flow.ts b/cocos/core/pipeline/forward/forward-flow.ts index 88099eac42..dd23aea696 100644 --- a/cocos/core/pipeline/forward/forward-flow.ts +++ b/cocos/core/pipeline/forward/forward-flow.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline - */ - import { ccclass } from 'cc.decorator'; import { PIPELINE_FLOW_FORWARD } from '../define'; import { IRenderFlowInfo, RenderFlow } from '../render-flow'; diff --git a/cocos/core/pipeline/forward/forward-pipeline.ts b/cocos/core/pipeline/forward/forward-pipeline.ts index b91d4e3a7e..3183edc61c 100644 --- a/cocos/core/pipeline/forward/forward-pipeline.ts +++ b/cocos/core/pipeline/forward/forward-pipeline.ts @@ -23,18 +23,13 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline - */ - import { ccclass, displayOrder, type, serializable } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { RenderPipeline, IRenderPipelineInfo } from '../render-pipeline'; import { ForwardFlow } from './forward-flow'; import { RenderTextureConfig } from '../pipeline-serialization'; import { ShadowFlow } from '../shadow/shadow-flow'; -import { UBOGlobal, UBOShadow, UBOCamera, UNIFORM_SHADOWMAP_BINDING, UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING } from '../define'; +import { UBOGlobal, UBOShadow, UBOCamera, UNIFORM_SHADOWMAP_BINDING, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING } from '../define'; import { Swapchain, RenderPass } from '../../gfx'; import { builtinResMgr } from '../../builtin'; import { Texture2D } from '../../assets/texture-2d'; @@ -132,8 +127,8 @@ export class ForwardPipeline extends RenderPipeline { 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_LIGHTING_MAP_TEXTURE_BINDING, shadowMapSampler); - this._descriptorSet.bindTexture(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_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(); return true; @@ -145,7 +140,7 @@ export class ForwardPipeline extends RenderPipeline { this._descriptorSet.getBuffer(UBOShadow.BINDING).destroy(); this._descriptorSet.getBuffer(UBOCamera.BINDING).destroy(); this._descriptorSet.getTexture(UNIFORM_SHADOWMAP_BINDING).destroy(); - this._descriptorSet.getTexture(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING).destroy(); + this._descriptorSet.getTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING).destroy(); } } } diff --git a/cocos/core/pipeline/forward/forward-stage.ts b/cocos/core/pipeline/forward/forward-stage.ts index 54c08305d4..e5ca638eee 100644 --- a/cocos/core/pipeline/forward/forward-stage.ts +++ b/cocos/core/pipeline/forward/forward-stage.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline - */ - import { ccclass, displayOrder, type, serializable } from 'cc.decorator'; import { SetIndex } from '../define'; import { getPhaseID } from '../pass-phase'; @@ -153,6 +148,7 @@ export class ForwardStage extends RenderStage { } } + this._instancedQueue.sort(); this._renderQueues.forEach(renderQueueSortFunc); const cmdBuff = pipeline.commandBuffers[0]; @@ -185,7 +181,7 @@ export class ForwardStage extends RenderStage { cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet); this._planarQueue.recordCommandBuffer(device, renderPass, cmdBuff); this._renderQueues[1].recordCommandBuffer(device, renderPass, cmdBuff); - camera.geometryRenderer.render(renderPass, cmdBuff, pipeline.pipelineSceneData); + camera.geometryRenderer?.render(renderPass, cmdBuff, pipeline.pipelineSceneData); this._uiPhase.render(camera, renderPass); renderProfiler(device, renderPass, cmdBuff, pipeline.profiler, camera); cmdBuff.endRenderPass(); diff --git a/cocos/core/pipeline/geometry-renderer.ts b/cocos/core/pipeline/geometry-renderer.ts index 0f3b099e78..ea24ee628d 100644 --- a/cocos/core/pipeline/geometry-renderer.ts +++ b/cocos/core/pipeline/geometry-renderer.ts @@ -24,6 +24,7 @@ */ import { AABB } from '../geometry/aabb'; +import { Spline } from '../geometry/spline'; import { Color } from '../math/color'; import { Mat4 } from '../math/mat4'; import { Vec3 } from '../math/vec3'; @@ -36,8 +37,8 @@ import { Attribute, AttributeName, Buffer, BufferInfo, BufferUsageBit, import { warnID } from '../platform/debug'; import { Frustum } from '../geometry/frustum'; import { toRadian } from '../math/utils'; -import { Camera } from '../renderer/scene/camera'; import { PipelineSceneData } from './pipeline-scene-data'; +import { legacyCC } from '../global-exports'; const _min = new Vec3(); const _max = new Vec3(); @@ -60,7 +61,7 @@ const GEOMETRY_NO_DEPTH_TEST_PASS_NUM = 1; const GEOMETRY_DEPTH_TEST_PASS_NUM = 2; const GEOMETRY_VERTICES_PER_LINE = 2; const GEOMETRY_VERTICES_PER_TRIANGLE = 3; -const GEOMETRY_MAX_LINES = 100000; +const GEOMETRY_MAX_LINES = 30000; const GEOMETRY_MAX_DASHED_LINES = 10000; const GEOMETRY_MAX_TRIANGLES = 10000; @@ -72,27 +73,27 @@ enum GeometryType { class GeometryVertexBuffer { /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _maxVertices = 0; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _vertexCount = 0; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _stride = 0; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _vertices!: Float32Array; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _buffer!: Buffer; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _inputAssembler!: InputAssembler; @@ -101,12 +102,12 @@ class GeometryVertexBuffer { this._vertexCount = 0; this._stride = stride; this._vertices = new Float32Array(maxVertices * stride / Float32Array.BYTES_PER_ELEMENT); - this._buffer = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, + this._buffer = device.createBuffer(new BufferInfo(BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.DEVICE, maxVertices * stride, stride)); this._inputAssembler = device.createInputAssembler(new InputAssemblerInfo(attributes, [this._buffer], null)); } - public getCount() { return Math.min(this._vertexCount, this._maxVertices); } + public getCount () { return Math.min(this._vertexCount, this._maxVertices); } public empty (): boolean { return this._vertexCount === 0; } public reset () { this._vertexCount = 0; } @@ -185,8 +186,6 @@ export class GeometryRenderer { } public render (renderPass: RenderPass, cmdBuff: CommandBuffer, sceneData: PipelineSceneData) { - this.update(); - const passes = sceneData.geometryRendererPasses; const shaders = sceneData.geometryRendererShaders; @@ -265,6 +264,18 @@ export class GeometryRenderer { } } + public empty () { + for (let i = 0; i < GEOMETRY_DEPTH_TYPE_COUNT; i++) { + if (!this._buffers.lines[i].empty() + || !this._buffers.dashedLines[i].empty() + || !this._buffers.triangles[i].empty()) { + return false; + } + } + + return true; + } + public update () { for (let i = 0; i < GEOMETRY_DEPTH_TYPE_COUNT; i++) { this._buffers.lines[i].update(); @@ -897,6 +908,25 @@ export class GeometryRenderer { } } + public addSpline (spline: Spline, color: Color, index = 0xffffffff, knotSize = 0.5, segments = 32, depthTest = true) { + const numPoints = segments + 1; + const points = spline.getPoints(numPoints, index); + + for (let i = 0; i < segments; i++) { + this.addLine(points[i], points[i + 1], color, depthTest); + } + + if (knotSize > 0.0 && index === 0xffffffff) { + const crossColor = new Color(255 - color.r, 255 - color.g, 255 - color.b, color.a); + const numKnots = spline.getKnotCount(); + const knots = spline.knots; + + for (let i = 0; i < numKnots; i++) { + this.addCross(knots[i], knotSize, crossColor, depthTest); + } + } + } + public addMesh (center: Vec3, vertices: Array, color: Color, depthTest = true, useTransform = false, transform = new Mat4()) { for (let i = 0; i < vertices.length; i += 3) { const v0 = new Vec3(center.x + vertices[i].x, center.y + vertices[i].y, center.z + vertices[i].z); @@ -934,3 +964,5 @@ export class GeometryRenderer { } } } + +legacyCC.internal.GeometryRenderer = GeometryRenderer; diff --git a/cocos/core/pipeline/global-descriptor-set-manager.ts b/cocos/core/pipeline/global-descriptor-set-manager.ts index 4859a72da1..2f329b6f64 100644 --- a/cocos/core/pipeline/global-descriptor-set-manager.ts +++ b/cocos/core/pipeline/global-descriptor-set-manager.ts @@ -23,13 +23,9 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline - */ - import { Device, BufferUsageBit, MemoryUsageBit, BufferInfo, Filter, Address, Sampler, DescriptorSet, DescriptorSetInfo, Buffer, Texture, DescriptorSetLayoutInfo, DescriptorSetLayout, SamplerInfo } from '../gfx'; +import { Light } from '../renderer/scene'; import { UBOShadow, globalDescriptorSetLayout, PipelineGlobalBindings } from './define'; const _samplerLinearInfo = new SamplerInfo( @@ -52,7 +48,7 @@ const _samplerPointInfo = new SamplerInfo( export class GlobalDSManager { private _device: Device; - private _descriptorSetMap: Map = new Map(); + private _descriptorSetMap: Map = new Map(); private _globalDescriptorSet: DescriptorSet; private _descriptorSetLayout: DescriptorSetLayout; private _linearSampler: Sampler; @@ -164,14 +160,14 @@ export class GlobalDSManager { * @param idx Specify index creation * @return descriptorSet */ - public getOrCreateDescriptorSet (idx: number) { + public getOrCreateDescriptorSet (light: Light) { const device = this._device; // The global descriptorSet is managed by the pipeline and binds the buffer - if (!this._descriptorSetMap.has(idx)) { + if (!this._descriptorSetMap.has(light)) { const globalDescriptorSet = this._globalDescriptorSet; const descriptorSet = device.createDescriptorSet(new DescriptorSetInfo(this._descriptorSetLayout)); - this._descriptorSetMap.set(idx, descriptorSet); + this._descriptorSetMap.set(light, descriptorSet); // Create & Sync ALL UBO Buffer, Texture, Sampler for (let i = PipelineGlobalBindings.UBO_GLOBAL; i < PipelineGlobalBindings.COUNT; i++) { @@ -191,7 +187,7 @@ export class GlobalDSManager { descriptorSet.update(); } - return this._descriptorSetMap.get(idx); + return this._descriptorSetMap.get(light); } public destroy () { diff --git a/cocos/core/pipeline/index.jsb.ts b/cocos/core/pipeline/index.jsb.ts index 4672ad5cd7..26d7b5ac80 100644 --- a/cocos/core/pipeline/index.jsb.ts +++ b/cocos/core/pipeline/index.jsb.ts @@ -30,6 +30,7 @@ import { setClassName } from '../../core/utils/js'; import { PipelineEventType } from './pipeline-event'; import * as pipeline from './define'; export { pipeline }; + nr.getPhaseID = getPhaseID; export const RenderPipeline = nr.RenderPipeline; @@ -48,7 +49,6 @@ export const LightingStage = nr.LightingStage; export const PostProcessStage = nr.PostProcessStage; export const GbufferStage = nr.GbufferStage; export const BloomStage = nr.BloomStage; -export const GeometryRenderer = nr.GeometryRenderer; export { PipelineEventType } from './pipeline-event'; let getOrCreatePipelineState = nr.PipelineStateManager.getOrCreatePipelineState; diff --git a/cocos/core/pipeline/index.ts b/cocos/core/pipeline/index.ts index 6ee314435f..63743e5d30 100644 --- a/cocos/core/pipeline/index.ts +++ b/cocos/core/pipeline/index.ts @@ -23,11 +23,7 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline - */ - +import './deprecated'; import * as pipeline from './define'; import { ForwardPipeline } from './forward/forward-pipeline'; @@ -39,7 +35,6 @@ export { RenderPipeline } from './render-pipeline'; export { RenderFlow } from './render-flow'; export { RenderStage } from './render-stage'; export { PipelineSceneData } from './pipeline-scene-data'; -export { GeometryRenderer } from './geometry-renderer'; export { ForwardPipeline } from './forward/forward-pipeline'; export { ForwardFlow } from './forward/forward-flow'; @@ -57,6 +52,7 @@ export { InstancedBuffer } from './instanced-buffer'; export { PipelineStateManager } from './pipeline-state-manager'; export { PipelineEventProcessor, PipelineEventType } from './pipeline-event'; +export { DebugView } from './debug-view'; export function createDefaultPipeline () { const rppl = new ForwardPipeline(); diff --git a/cocos/core/pipeline/instanced-buffer.ts b/cocos/core/pipeline/instanced-buffer.ts index 6501086b95..a238225418 100644 --- a/cocos/core/pipeline/instanced-buffer.ts +++ b/cocos/core/pipeline/instanced-buffer.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { Pass } from '../renderer'; import { IInstancedAttributeBlock, SubModel } from '../renderer/scene'; import { UNIFORM_LIGHTMAP_TEXTURE_BINDING } from './define'; diff --git a/cocos/core/pipeline/pass-phase.ts b/cocos/core/pipeline/pass-phase.ts index 4b0c06c044..3ff6f54157 100644 --- a/cocos/core/pipeline/pass-phase.ts +++ b/cocos/core/pipeline/pass-phase.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - export const getPhaseID = (() => { const phases: Map = new Map(); let phaseNum = 0; diff --git a/cocos/core/pipeline/pipeline-funcs.ts b/cocos/core/pipeline/pipeline-funcs.ts index 4079859d59..2fecd03de5 100644 --- a/cocos/core/pipeline/pipeline-funcs.ts +++ b/cocos/core/pipeline/pipeline-funcs.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline - */ - import { CommandBuffer, Device, Rect, RenderPass, Swapchain, Viewport } from '../gfx'; import { IVec4Like } from '../math'; import { PipelineStateManager } from './pipeline-state-manager'; diff --git a/cocos/core/pipeline/pipeline-scene-data.ts b/cocos/core/pipeline/pipeline-scene-data.ts index cc3383238b..bc7a8f549f 100644 --- a/cocos/core/pipeline/pipeline-scene-data.ts +++ b/cocos/core/pipeline/pipeline-scene-data.ts @@ -30,6 +30,7 @@ import { Device, Framebuffer, InputAssembler, InputAssemblerInfo, Buffer, Buffer import { Light } from '../renderer/scene/light'; import { Material } from '../assets'; import { Pass } from '../renderer/core/pass'; +import { CSMLayers } from './shadow/csm-layers'; const GEOMETRY_RENDERER_TECHNIQUE_COUNT = 6; @@ -58,6 +59,7 @@ export class PipelineSceneData { public ambient: Ambient = new Ambient(); public skybox: Skybox = new Skybox(); public shadows: Shadows = new Shadows(); + public csmLayers: CSMLayers = new CSMLayers(); public octree: Octree = new Octree(); /** @@ -71,8 +73,6 @@ export class PipelineSceneData { * @zh 渲染对象数组,仅在当前帧的场景剔除完成后有效。 */ public renderObjects: IRenderObject[] = []; - public castShadowObjects: IRenderObject[] = []; - public dirShadowObjects: IRenderObject[] = []; public shadowFrameBufferMap: Map = new Map(); protected declare _device: Device; protected _geometryRendererMaterials: Material[] = []; @@ -104,7 +104,7 @@ export class PipelineSceneData { for (let tech = 0; tech < GEOMETRY_RENDERER_TECHNIQUE_COUNT; tech++) { this._geometryRendererMaterials[tech] = new Material(); this._geometryRendererMaterials[tech]._uuid = `geometry-renderer-material-${tech}`; - this._geometryRendererMaterials[tech].initialize({ effectName: 'geometry-renderer', technique: tech }); + this._geometryRendererMaterials[tech].initialize({ effectName: 'builtin-geometry-renderer', technique: tech }); for (let pass = 0; pass < this._geometryRendererMaterials[tech].passes.length; ++pass) { this._geometryRendererPasses[offset] = this._geometryRendererMaterials[tech].passes[pass]; @@ -130,14 +130,16 @@ export class PipelineSceneData { if (!this._occlusionQueryMaterial) { const mat = new Material(); mat._uuid = 'default-occlusion-query-material'; - mat.initialize({ effectName: 'occlusion-query' }); + mat.initialize({ effectName: 'builtin-occlusion-query' }); this._occlusionQueryMaterial = mat; - this._occlusionQueryShader = mat.passes[0].getShaderVariant(); + if (mat.passes.length > 0) { + this._occlusionQueryShader = mat.passes[0].getShaderVariant(); + } } } public getOcclusionQueryPass (): Pass | null { - if (this._occlusionQueryMaterial) { + if (this._occlusionQueryMaterial && this._occlusionQueryMaterial.passes.length > 0) { return this._occlusionQueryMaterial.passes[0]; } @@ -149,6 +151,7 @@ export class PipelineSceneData { public destroy () { this.shadows.destroy(); + this.csmLayers.destroy(); this.validPunctualLights.length = 0; this._occlusionQueryInputAssembler?.destroy(); this._occlusionQueryInputAssembler = null; diff --git a/cocos/core/pipeline/pipeline-serialization.ts b/cocos/core/pipeline/pipeline-serialization.ts index 1401f5e3d0..ee87e3fb13 100644 --- a/cocos/core/pipeline/pipeline-serialization.ts +++ b/cocos/core/pipeline/pipeline-serialization.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline - */ - import { ccclass, type, serializable, editable } from 'cc.decorator'; import { CCString } from '../data/utils/attribute'; import { AccessFlagBit, Format, LoadOp, StoreOp, TextureType, TextureUsageBit } from '../gfx'; diff --git a/cocos/core/pipeline/pipeline-state-manager.ts b/cocos/core/pipeline/pipeline-state-manager.ts index 4f1e8072e3..030cdab8b1 100644 --- a/cocos/core/pipeline/pipeline-state-manager.ts +++ b/cocos/core/pipeline/pipeline-state-manager.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { Shader, RenderPass, InputAssembler, Device, PipelineState, InputState, PipelineStateInfo } from '../gfx'; import { Pass } from '../renderer/core/pass'; diff --git a/cocos/core/pipeline/pipeline-ubo.ts b/cocos/core/pipeline/pipeline-ubo.ts index 525b0b58e0..a36e2856b1 100644 --- a/cocos/core/pipeline/pipeline-ubo.ts +++ b/cocos/core/pipeline/pipeline-ubo.ts @@ -24,20 +24,20 @@ */ import { UBOGlobal, UBOShadow, UBOCamera, UNIFORM_SHADOWMAP_BINDING, - supportsR32FloatTexture, UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING, -} from './define'; -import { Device, BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet } from '../gfx'; + supportsR32FloatTexture, UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING } from './define'; +import { Device, BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet, API } from '../gfx'; import { Camera } from '../renderer/scene/camera'; import { Mat4, Vec3, Vec4, Color } from '../math'; import { RenderPipeline } from './render-pipeline'; import { legacyCC } from '../global-exports'; -import { ShadowType } from '../renderer/scene/shadows'; +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(); @@ -47,7 +47,8 @@ const _lightDir = new Vec4(0.0, 0.0, 1.0, 0.0); export class PipelineUBO { public static updateGlobalUBOView (window: RenderWindow, bufferView: Float32Array) { - const root = legacyCC.director.root; + const director = legacyCC.director; + const root = director.root; const fv = bufferView; const shadingWidth = Math.floor(window.width); @@ -56,7 +57,7 @@ export class PipelineUBO { // update UBOGlobal fv[UBOGlobal.TIME_OFFSET] = root.cumulativeTime; fv[UBOGlobal.TIME_OFFSET + 1] = root.frameTime; - fv[UBOGlobal.TIME_OFFSET + 2] = legacyCC.director.getTotalFrames(); + fv[UBOGlobal.TIME_OFFSET + 2] = director.getTotalFrames(); fv[UBOGlobal.SCREEN_SIZE_OFFSET] = shadingWidth; fv[UBOGlobal.SCREEN_SIZE_OFFSET + 1] = shadingHeight; @@ -67,6 +68,23 @@ export class PipelineUBO { 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: RenderPipeline, bufferView: Float32Array, @@ -75,6 +93,7 @@ export class PipelineUBO { const mainLight = scene.mainLight; const sceneData = pipeline.pipelineSceneData; const ambient = sceneData.ambient; + const skybox = sceneData.skybox; const fog = sceneData.fog; const shadowInfo = sceneData.shadows; const cv = bufferView; @@ -129,7 +148,7 @@ export class PipelineUBO { 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; - cv[UBOCamera.AMBIENT_GROUND_OFFSET + 3] = ambient.mipmapCount; + 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); @@ -166,59 +185,100 @@ export class PipelineUBO { cv[UBOCamera.VIEW_PORT_OFFSET + 3] = sceneData.shadingScale * camera.window.height * camera.viewport.w; } - public static updateShadowUBOView (pipeline: RenderPipeline, bufferView: Float32Array, camera: Camera) { + 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: RenderPipeline, shadowBufferView: Float32Array, camera: Camera) { const device = pipeline.device; const mainLight = camera.scene!.mainLight; const sceneData = pipeline.pipelineSceneData; const shadowInfo = sceneData.shadows; - const sv = bufferView; + const csmLayers = sceneData.csmLayers; + const sv = shadowBufferView; + const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; - if (shadowInfo.enabled) { - if (mainLight && shadowInfo.type === ShadowType.ShadowMap) { - let near = 0.1; - let far = 0; - const matShadowView = shadowInfo.matShadowView; - const matShadowProj = shadowInfo.matShadowProj; - const matShadowViewProj = shadowInfo.matShadowViewProj; - if (mainLight.shadowFixedArea) { - near = mainLight.shadowNear; - far = mainLight.shadowFar; - } else { - near = 0.1; - far = shadowInfo.shadowCameraFar; + if (mainLight && shadowInfo.enabled) { + 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); } - - Mat4.toArray(bufferView, 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(bufferView, matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); - - const linear = 0.0; - const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; - sv[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 0] = near; - sv[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 1] = far; - sv[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 2] = linear; - sv[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 3] = 1.0 - mainLight.shadowSaturation; - - sv[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x; - sv[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 1] = shadowInfo.size.y; - sv[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 2] = mainLight.shadowPcf; - sv[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 3] = mainLight.shadowBias; - - sv[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 0] = 0.0; - sv[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing; - sv[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = mainLight.shadowNormalBias; - sv[UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0; - } else if (mainLight && shadowInfo.type === ShadowType.Planar) { + } else { updatePlanarPROJ(shadowInfo, mainLight, sv); updatePlanarNormalAndDistance(shadowInfo, sv); } @@ -227,70 +287,96 @@ export class PipelineUBO { } } - public static updateShadowUBOLightView (pipeline: RenderPipeline, bufferView: Float32Array, light: Light) { + public static updateShadowUBOLightView (pipeline: RenderPipeline, shadowBufferView: Float32Array, light: Light, level: number) { const device = pipeline.device; - const shadowInfo = pipeline.pipelineSceneData.shadows; - const sv = bufferView; - const linear = 0.0; + const sceneData = pipeline.pipelineSceneData; + const shadowInfo = sceneData.shadows; + const csmLayers = sceneData.csmLayers; + const sv = shadowBufferView; const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; - let near = 0.1; - let far = 0; - const matShadowView = shadowInfo.matShadowView; - const matShadowProj = shadowInfo.matShadowProj; - const matShadowViewProj = shadowInfo.matShadowViewProj; switch (light.type) { case LightType.DIRECTIONAL: { const mainLight = light as DirectionalLight; - if (mainLight.shadowFixedArea) { - near = mainLight.shadowNear; - far = mainLight.shadowFar; - } else { - near = 0.1; - far = shadowInfo.shadowCameraFar; + 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); + } } - - Mat4.toArray(bufferView, 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(bufferView, matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); - - _vec4ShadowInfo.set(near, far, linear, 1.0 - mainLight.shadowSaturation); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET); - - _vec4ShadowInfo.set(0.0, packing, mainLight.shadowNormalBias, 0.0); - 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); + if (shadowInfo.enabled && spotLight && spotLight.shadowEnabled) { + Mat4.invert(_matShadowView, (light as any).node.getWorldMatrix()); + Mat4.toArray(sv, _matShadowView, UBOShadow.MAT_LIGHT_VIEW_OFFSET); - Mat4.perspective(_matShadowProj, (light as any).angle, (light as any).aspect, 0.001, (light as any).range); + 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); + Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); + Mat4.toArray(sv, _matShadowViewProj, UBOShadow.MAT_LIGHT_VIEW_PROJ_OFFSET); - _vec4ShadowInfo.set(0.01, (light as SpotLight).range, linear, 0.0); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_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(1.0, packing, spotLight.shadowNormalBias, 0.0); - Vec4.toArray(sv, _vec4ShadowInfo, UBOShadow.SHADOW_LIGHT_PACKING_NBIAS_NULL_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(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: @@ -397,10 +483,10 @@ export class PipelineUBO { cmdBuffer[0].updateBuffer(ds.getBuffer(UBOShadow.BINDING), this._shadowUBO); } - public updateShadowUBOLight (globalDS: DescriptorSet, light: Light) { - PipelineUBO.updateShadowUBOLightView(this._pipeline, this._shadowUBO, light); + 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_LIGHTING_MAP_TEXTURE_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); } diff --git a/cocos/core/pipeline/render-additive-light-queue.ts b/cocos/core/pipeline/render-additive-light-queue.ts index ae398e8060..1416d82419 100644 --- a/cocos/core/pipeline/render-additive-light-queue.ts +++ b/cocos/core/pipeline/render-additive-light-queue.ts @@ -23,10 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline - */ import { BatchingSchemes, Pass } from '../renderer/core/pass'; import { RenderPipeline } from './render-pipeline'; import { Model } from '../renderer/scene/model'; @@ -44,7 +40,7 @@ import { SubModel } from '../renderer/scene/submodel'; import { getPhaseID } from './pass-phase'; import { Light, LightType } from '../renderer/scene/light'; import { SetIndex, UBOForwardLight, UBOShadow, UNIFORM_SHADOWMAP_BINDING, - UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING, supportsR32FloatTexture } from './define'; + 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'; @@ -53,7 +49,7 @@ interface IAdditiveLightPass { subModel: SubModel; passIdx: number; dynamicOffsets: number[]; - lights: number[]; + lights: Light[]; } const _lightPassPool = new Pool(() => ({ subModel: null!, passIdx: -1, dynamicOffsets: [], lights: [] }), 16); @@ -93,6 +89,24 @@ function getLightPassIndices (subModels: SubModel[], lightPassIndices: number[]) return hasValidLightPass; } +function isInstancedOrBatched (model: Model) { + const subModels = model.subModels; + for (let m = 0; m < subModels.length; ++m) { + const passes = subModels[m].passes; + for (let p = 0; p < passes.length; ++p) { + const pass = passes[p]; + const batchingScheme = pass.batchingScheme; + if (batchingScheme === BatchingSchemes.INSTANCING) { + return true; + } + if (batchingScheme === BatchingSchemes.VB_MERGING) { + return true; + } + } + } + return false; +} + /** * @zh 叠加光照队列。 */ @@ -100,6 +114,8 @@ export class RenderAdditiveLightQueue { private _pipeline: RenderPipeline; private _device: Device; private _lightPasses: IAdditiveLightPass[] = []; + private _instancedLightPassPool = _lightPassPool.alloc(); + private _batchedLightPassPool = _lightPassPool.alloc(); private _shadowUBO = new Float32Array(UBOShadow.COUNT); private _lightBufferCount = 16; private _lightBufferStride: number; @@ -144,6 +160,11 @@ export class RenderAdditiveLightQueue { } _lightPassPool.freeArray(this._lightPasses); this._lightPasses.length = 0; + + this._instancedLightPassPool.dynamicOffsets.length = 0; + this._instancedLightPassPool.lights.length = 0; + this._batchedLightPassPool.dynamicOffsets.length = 0; + this._batchedLightPassPool.lights.length = 0; } public destroy () { @@ -156,7 +177,7 @@ export class RenderAdditiveLightQueue { if (descriptorSet) { descriptorSet.getBuffer(UBOShadow.BINDING).destroy(); descriptorSet.getTexture(UNIFORM_SHADOWMAP_BINDING).destroy(); - descriptorSet.getTexture(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING).destroy(); + descriptorSet.getTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING).destroy(); descriptorSet.destroy(); } descriptorSetMap.delete(key); @@ -200,15 +221,35 @@ export class RenderAdditiveLightQueue { this._addRenderQueue(pass, subModel, model, lightPassIdx); } } + + // only for instanced and batched, no light culling applied + for (let l = 0; l < validPunctualLights.length; l++) { + const light = validPunctualLights[l]; + this._instancedLightPassPool.lights.push(light); + this._instancedLightPassPool.dynamicOffsets.push(this._lightBufferStride * l); + this._batchedLightPassPool.lights.push(light); + this._batchedLightPassPool.dynamicOffsets.push(this._lightBufferStride * l); + } this._instancedQueue.uploadBuffers(cmdBuff); this._batchedQueue.uploadBuffers(cmdBuff); } public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer) { - this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff); - this._batchedQueue.recordCommandBuffer(device, renderPass, cmdBuff); - const globalDSManager: GlobalDSManager = this._pipeline.globalDSManager; + for (let j = 0; j < this._instancedLightPassPool.lights.length; ++j) { + const light = this._instancedLightPassPool.lights[j]; + _dynamicOffsets[0] = this._instancedLightPassPool.dynamicOffsets[j]; + const descriptorSet = globalDSManager.getOrCreateDescriptorSet(light); + this._instancedQueue.recordCommandBuffer(device, renderPass, cmdBuff, descriptorSet, _dynamicOffsets); + } + + for (let j = 0; j < this._batchedLightPassPool.lights.length; ++j) { + const light = this._batchedLightPassPool.lights[j]; + _dynamicOffsets[0] = this._batchedLightPassPool.dynamicOffsets[j]; + const descriptorSet = globalDSManager.getOrCreateDescriptorSet(light); + this._batchedQueue.recordCommandBuffer(device, renderPass, cmdBuff, descriptorSet, _dynamicOffsets); + } + for (let i = 0; i < this._lightPasses.length; i++) { const { subModel, passIdx, dynamicOffsets, lights } = this._lightPasses[i]; const pass = subModel.passes[passIdx]; @@ -235,15 +276,16 @@ export class RenderAdditiveLightQueue { // light culling protected _lightCulling (model:Model, validPunctualLights: Light[]) { + let isCulled = false; + const isNeedCulling = !isInstancedOrBatched(model); for (let l = 0; l < validPunctualLights.length; l++) { const light = validPunctualLights[l]; - let isCulled = false; switch (light.type) { case LightType.SPHERE: - isCulled = cullSphereLight(light as SphereLight, model); + if (isNeedCulling) { isCulled = cullSphereLight(light as SphereLight, model); } break; case LightType.SPOT: - isCulled = cullSpotLight(light as SpotLight, model); + if (isNeedCulling) { isCulled = cullSpotLight(light as SpotLight, model); } break; default: } @@ -255,33 +297,28 @@ export class RenderAdditiveLightQueue { // add renderQueue protected _addRenderQueue (pass: Pass, subModel: SubModel, model: Model, lightPassIdx: number) { + const validPunctualLights = this._pipeline.pipelineSceneData.validPunctualLights; const { batchingScheme } = pass; if (batchingScheme === BatchingSchemes.INSTANCING) { // instancing - for (let l = 0; l < _lightIndices.length; l++) { - const idx = _lightIndices[l]; - const buffer = pass.getInstancedBuffer(idx); - buffer.merge(subModel, model.instancedAttributes, lightPassIdx); - buffer.dynamicOffsets[0] = this._lightBufferStride * idx; - this._instancedQueue.queue.add(buffer); - } + const buffer = pass.getInstancedBuffer(); + buffer.merge(subModel, model.instancedAttributes, lightPassIdx); + buffer.dynamicOffsets[0] = this._lightBufferStride; + this._instancedQueue.queue.add(buffer); } else if (batchingScheme === BatchingSchemes.VB_MERGING) { // vb-merging - for (let l = 0; l < _lightIndices.length; l++) { - const idx = _lightIndices[l]; - const buffer = pass.getBatchedBuffer(idx); - buffer.merge(subModel, lightPassIdx, model); - buffer.dynamicOffsets[0] = this._lightBufferStride * idx; - this._batchedQueue.queue.add(buffer); - } + const buffer = pass.getBatchedBuffer(); + buffer.merge(subModel, lightPassIdx, model); + buffer.dynamicOffsets[0] = this._lightBufferStride; + this._batchedQueue.queue.add(buffer); } else { // standard draw const lp = _lightPassPool.alloc(); lp.subModel = subModel; lp.passIdx = lightPassIdx; for (let l = 0; l < _lightIndices.length; l++) { - const idx = _lightIndices[l]; - lp.lights.push(idx); - lp.dynamicOffsets.push(this._lightBufferStride * idx); + const lightIdx = _lightIndices[l]; + const light = validPunctualLights[lightIdx]; + lp.lights.push(light); + lp.dynamicOffsets.push(this._lightBufferStride * lightIdx); } - this._lightPasses.push(lp); } } @@ -293,14 +330,13 @@ export class RenderAdditiveLightQueue { const shadowInfo = sceneData.shadows; const shadowFrameBufferMap = sceneData.shadowFrameBufferMap; const mainLight = camera.scene!.mainLight; - const linear = 0.0; const packing = supportsR32FloatTexture(device) ? 0.0 : 1.0; const globalDSManager: GlobalDSManager = this._pipeline.globalDSManager; const validPunctualLights = sceneData.validPunctualLights; for (let i = 0; i < validPunctualLights.length; i++) { const light = validPunctualLights[i]; - const descriptorSet = globalDSManager.getOrCreateDescriptorSet(i); + const descriptorSet = globalDSManager.getOrCreateDescriptorSet(light); if (!descriptorSet) { continue; } let matShadowProj : Mat4; let matShadowInvProj : Mat4; @@ -339,7 +375,7 @@ export class RenderAdditiveLightQueue { Mat4.invert(_matShadowView, (light as SpotLight).node!.getWorldMatrix()); // light proj - Mat4.perspective(_matShadowViewProj, (light as SpotLight).angle, (light as SpotLight).aspect, 0.001, (light as SpotLight).range); + Mat4.perspective(_matShadowViewProj, (light as SpotLight).angle, 1.0, 0.001, (light as SpotLight).range); matShadowProj = _matShadowViewProj.clone(); matShadowInvProj = _matShadowViewProj.clone().invert(); @@ -351,7 +387,7 @@ export class RenderAdditiveLightQueue { this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 0] = 0.01; this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 1] = (light as SpotLight).range; - this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 2] = linear; + this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 2] = 0.0; this._shadowUBO[UBOShadow.SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET + 3] = 0.0; this._shadowUBO[UBOShadow.SHADOW_WIDTH_HEIGHT_PCF_BIAS_INFO_OFFSET + 0] = shadowInfo.size.x; @@ -385,7 +421,7 @@ export class RenderAdditiveLightQueue { if (shadowFrameBufferMap.has(light)) { const texture = shadowFrameBufferMap.get(light)?.colorTextures[0]; if (texture) { - descriptorSet.bindTexture(UNIFORM_SPOT_LIGHTING_MAP_TEXTURE_BINDING, texture); + descriptorSet.bindTexture(UNIFORM_SPOT_SHADOW_MAP_TEXTURE_BINDING, texture); } } break; @@ -454,7 +490,7 @@ export class RenderAdditiveLightQueue { _vec4Array[0] = (light as SpotLight).size; _vec4Array[1] = (light as SpotLight).range; _vec4Array[2] = (light as SpotLight).spotAngle; - _vec4Array[3] = ((light as SpotLight).shadowEnabled && shadowInfo.type === ShadowType.ShadowMap) ? 1 : 0; + _vec4Array[3] = (shadowInfo.enabled && (light as SpotLight).shadowEnabled && shadowInfo.type === ShadowType.ShadowMap) ? 1 : 0; this._lightBufferData.set(_vec4Array, offset + UBOForwardLight.LIGHT_SIZE_RANGE_ANGLE_OFFSET); Vec3.toArray(_vec4Array, (light as SpotLight).direction); diff --git a/cocos/core/pipeline/render-batched-queue.ts b/cocos/core/pipeline/render-batched-queue.ts index ec74f25ee6..3393077192 100644 --- a/cocos/core/pipeline/render-batched-queue.ts +++ b/cocos/core/pipeline/render-batched-queue.ts @@ -23,14 +23,9 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline - */ - import { BatchedBuffer } from './batched-buffer'; import { PipelineStateManager } from './pipeline-state-manager'; -import { RenderPass, Device, CommandBuffer } from '../gfx'; +import { RenderPass, Device, CommandBuffer, DescriptorSet } from '../gfx'; import { SetIndex } from './define'; /** @@ -78,7 +73,8 @@ export class RenderBatchedQueue { * @zh 记录命令缓冲。 * @param cmdBuff The command buffer to store the result */ - public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer) { + public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer, + descriptorSet: DescriptorSet | null = null, dynamicOffsets?: Readonly) { const it = this.queue.values(); let res = it.next(); while (!res.done) { let boundPSO = false; @@ -92,7 +88,12 @@ export class RenderBatchedQueue { cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, batch.pass.descriptorSet); boundPSO = true; } - cmdBuff.bindDescriptorSet(SetIndex.LOCAL, batch.descriptorSet, res.value.dynamicOffsets); + if (descriptorSet) cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, descriptorSet); + if (dynamicOffsets) { + cmdBuff.bindDescriptorSet(SetIndex.LOCAL, batch.descriptorSet, dynamicOffsets); + } else { + cmdBuff.bindDescriptorSet(SetIndex.LOCAL, batch.descriptorSet, res.value.dynamicOffsets); + } cmdBuff.bindInputAssembler(batch.ia); cmdBuff.draw(batch.ia); } diff --git a/cocos/core/pipeline/render-flow.ts b/cocos/core/pipeline/render-flow.ts index 6c244904f0..fa44f7e7b0 100644 --- a/cocos/core/pipeline/render-flow.ts +++ b/cocos/core/pipeline/render-flow.ts @@ -23,10 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline - */ import { ccclass, displayOrder, serializable, type } from 'cc.decorator'; import { RenderStage } from './render-stage'; import { RenderPipeline } from './render-pipeline'; diff --git a/cocos/core/pipeline/render-instanced-queue.ts b/cocos/core/pipeline/render-instanced-queue.ts index 1beae719de..414b0fe780 100644 --- a/cocos/core/pipeline/render-instanced-queue.ts +++ b/cocos/core/pipeline/render-instanced-queue.ts @@ -23,13 +23,8 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline - */ - import { InstancedBuffer } from './instanced-buffer'; -import { Device, RenderPass, PipelineState, CommandBuffer } from '../gfx'; +import { Device, RenderPass, PipelineState, CommandBuffer, DescriptorSet } from '../gfx'; import { PipelineStateManager } from './pipeline-state-manager'; import { SetIndex } from './define'; @@ -44,6 +39,8 @@ export class RenderInstancedQueue { */ public queue = new Set(); + private _renderQueue : InstancedBuffer[] = []; + /** * @en Clear the render queue * @zh 清空渲染队列。 @@ -54,9 +51,29 @@ export class RenderInstancedQueue { res.value.clear(); res = it.next(); } + this._renderQueue = []; this.queue.clear(); } + public sort () { + let it = this.queue.values(); + let res = it.next(); + while (!res.done) { + if (!(res.value.pass.blendState.targets[0].blend)) { + this._renderQueue.push(res.value); + } + res = it.next(); + } + it = this.queue.values(); + res = it.next(); + while (!res.done) { + if (res.value.pass.blendState.targets[0].blend) { + this._renderQueue.push(res.value); + } + res = it.next(); + } + } + public uploadBuffers (cmdBuff: CommandBuffer) { const it = this.queue.values(); let res = it.next(); while (!res.done) { @@ -70,8 +87,11 @@ export class RenderInstancedQueue { * @zh 记录命令缓冲。 * @param cmdBuff The command buffer to store the result */ - public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer) { - const it = this.queue.values(); let res = it.next(); + public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer, + descriptorSet: DescriptorSet | null = null, dynamicOffsets?: Readonly) { + const it = this._renderQueue.length === 0 ? this.queue.values() : this._renderQueue.values(); + let res = it.next(); + while (!res.done) { const { instances, pass, hasPendingModels } = res.value; if (hasPendingModels) { @@ -86,7 +106,12 @@ export class RenderInstancedQueue { cmdBuff.bindPipelineState(pso); lastPSO = pso; } - cmdBuff.bindDescriptorSet(SetIndex.LOCAL, instance.descriptorSet, res.value.dynamicOffsets); + if (descriptorSet) cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, descriptorSet); + if (dynamicOffsets) { + cmdBuff.bindDescriptorSet(SetIndex.LOCAL, instance.descriptorSet, dynamicOffsets); + } else { + cmdBuff.bindDescriptorSet(SetIndex.LOCAL, instance.descriptorSet, res.value.dynamicOffsets); + } cmdBuff.bindInputAssembler(instance.ia); cmdBuff.draw(instance.ia); } diff --git a/cocos/core/pipeline/render-pipeline.ts b/cocos/core/pipeline/render-pipeline.ts index a9a28e0dd8..ff07bf5052 100644 --- a/cocos/core/pipeline/render-pipeline.ts +++ b/cocos/core/pipeline/render-pipeline.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline - */ - import { ccclass, displayOrder, serializable, type } from 'cc.decorator'; import { systemInfo } from 'pal/system-info'; import { sceneCulling, validPunctualLightsCulling } from './scene-culling'; @@ -35,7 +30,7 @@ import { Asset } from '../assets/asset'; import { AccessFlagBit, Attribute, Buffer, BufferInfo, BufferUsageBit, ClearFlagBit, ClearFlags, ColorAttachment, CommandBuffer, DepthStencilAttachment, DescriptorSet, Device, Feature, Format, FormatFeatureBit, Framebuffer, FramebufferInfo, InputAssembler, InputAssemblerInfo, LoadOp, MemoryUsageBit, Rect, RenderPass, RenderPassInfo, Sampler, StoreOp, SurfaceTransform, Swapchain, - Texture, TextureInfo, TextureType, TextureUsageBit, Viewport, GeneralBarrierInfo, + Texture, TextureInfo, TextureType, TextureUsageBit, Viewport, GeneralBarrierInfo, deviceManager, } from '../gfx'; import { legacyCC } from '../global-exports'; import { MacroRecord } from '../renderer/core/pass-utils'; @@ -44,6 +39,7 @@ import { Camera, SKYBOX_FLAG } from '../renderer/scene/camera'; import { Model } from '../renderer/scene/model'; import { Root } from '../root'; import { GlobalDSManager } from './global-descriptor-set-manager'; +import { GeometryRenderer } from './geometry-renderer'; import { PipelineSceneData } from './pipeline-scene-data'; import { PipelineUBO } from './pipeline-ubo'; import { RenderFlow } from './render-flow'; @@ -51,6 +47,7 @@ import { IPipelineEvent, PipelineEventProcessor, PipelineEventType } from './pip import { decideProfilerCamera } from './pipeline-funcs'; import { OS } from '../../../pal/system-info/enum-type'; import { macro } from '../platform/macro'; +import { UBOSkinning } from './define'; import { PipelineRuntime } from './custom/pipeline'; /** @@ -226,6 +223,13 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi return this._profiler; } + /** + * @deprecated since v3.6, please use camera.geometryRenderer instead. + */ + get geometryRenderer () { + return this._geometryRenderer; + } + set clusterEnabled (value) { this._clusterEnabled = value; } @@ -250,6 +254,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi protected _macros: MacroRecord = {}; protected _constantMacros = ''; protected _profiler: Model | null = null; + protected _geometryRenderer: GeometryRenderer | null = null; protected declare _pipelineSceneData: PipelineSceneData; protected _pipelineRenderData: PipelineRenderData | null = null; protected _renderPasses = new Map(); @@ -381,6 +386,18 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi } } + public setMacroString (name: string, value: string): void { + this._macros[name] = value; + } + + public setMacroInt (name: string, value: number): void { + this._macros[name] = value; + } + + public setMacroBool (name: string, value: boolean): void { + this._macros[name] = value; + } + /** * @en Activate the render pipeline after loaded, it mainly activate the flows * @zh 当渲染管线资源加载完成后,启用管线,主要是启用管线内的 flow @@ -388,14 +405,14 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi * after deferred pipeline can handle multiple swapchains */ public activate (swapchain: Swapchain): boolean { - const root = legacyCC.director.root as Root; - this._device = root.device; + this._device = deviceManager.gfxDevice; this._generateConstantMacros(); this._globalDSManager = new GlobalDSManager(this._device); this._descriptorSet = this._globalDSManager.globalDescriptorSet; this._pipelineUBO.activate(this._device, this); // update global defines in advance here for deferred pipeline may tryCompile shaders. this._macros.CC_USE_HDR = this._pipelineSceneData.isHDR; + this._macros.CC_USE_DEBUG_VIEW = 0; this._generateConstantMacros(); this._pipelineSceneData.activate(this._device); @@ -417,6 +434,7 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi if (cameras.length === 0) { return; } + this.updateGeometryRenderer(cameras); // for capability this._commandBuffers[0].begin(); this.emit(PipelineEventType.RENDER_FRAME_BEGIN, cameras); this._ensureEnoughSize(cameras); @@ -668,9 +686,29 @@ export abstract class RenderPipeline extends Asset implements IPipelineEvent, Pi str += `#define CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT ${this.device.hasFeature(Feature.INPUT_ATTACHMENT_BENEFIT) ? 1 : 0}\n`; str += `#define CC_PLATFORM_ANDROID_AND_WEBGL ${systemInfo.os === OS.ANDROID && systemInfo.isBrowser ? 1 : 0}\n`; str += `#define CC_ENABLE_WEBGL_HIGHP_STRUCT_VALUES ${macro.ENABLE_WEBGL_HIGHP_STRUCT_VALUES ? 1 : 0}\n`; + + const jointUniformCapacity = UBOSkinning.JOINT_UNIFORM_CAPACITY; + str += `#define CC_JOINT_UNIFORM_CAPACITY ${jointUniformCapacity}\n`; + this._constantMacros = str; } + protected updateGeometryRenderer (cameras: Camera[]) { + if (this._geometryRenderer) { + return; + } + + // Query the first camera rendering to swapchain. + for (let i = 0; i < cameras.length; i++) { + const camera = cameras[i]; + if (camera && camera.window && camera.window.swapchain) { + camera.initGeometryRenderer(); + this._geometryRenderer = camera.geometryRenderer; + return; + } + } + } + public generateBloomRenderData () { if (this._pipelineRenderData!.bloom != null) return; diff --git a/cocos/core/pipeline/render-queue.ts b/cocos/core/pipeline/render-queue.ts index 6f2cd1d934..6d64a658df 100644 --- a/cocos/core/pipeline/render-queue.ts +++ b/cocos/core/pipeline/render-queue.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline - */ - import { RecyclePool } from '../memop'; import { CachedArray } from '../memop/cached-array'; import { IRenderObject, IRenderPass, IRenderQueueDesc, SetIndex } from './define'; @@ -49,7 +44,7 @@ export function opaqueCompareFn (a: IRenderPass, b: IRenderPass) { * @zh 比较排序函数。半透明对象按优先级 -> 深度由后向前 -> Shader ID 顺序排序。 */ export function transparentCompareFn (a: IRenderPass, b: IRenderPass) { - return (a.hash - b.hash) || (b.depth - a.depth) || (a.shaderId - b.shaderId); + return (a.priority - b.priority) || (a.hash - b.hash) || (b.depth - a.depth) || (a.shaderId - b.shaderId); } /** @@ -74,6 +69,7 @@ export class RenderQueue { constructor (desc: IRenderQueueDesc) { this._passDesc = desc; this._passPool = new RecyclePool(() => ({ + priority: 0, hash: 0, depth: 0, shaderId: 0, @@ -110,6 +106,7 @@ export class RenderQueue { } const hash = (0 << 30) | pass.priority << 16 | subModel.priority << 8 | passIdx; const rp = this._passPool.add(); + rp.priority = renderObj.model.priority; rp.hash = hash; rp.depth = renderObj.depth || 0; rp.shaderId = shader.typedID; diff --git a/cocos/core/pipeline/render-shadow-map-batched-queue.ts b/cocos/core/pipeline/render-shadow-map-batched-queue.ts index 5e67a35d22..56febd8d64 100644 --- a/cocos/core/pipeline/render-shadow-map-batched-queue.ts +++ b/cocos/core/pipeline/render-shadow-map-batched-queue.ts @@ -23,33 +23,21 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline - */ - import { SubModel } from '../renderer/scene/submodel'; import { SetIndex } from './define'; -import { Device, RenderPass, Shader, CommandBuffer, DescriptorSet } from '../gfx'; +import { Device, RenderPass, Shader, CommandBuffer } from '../gfx'; import { getPhaseID } from './pass-phase'; import { PipelineStateManager } from './pipeline-state-manager'; import { Pass, BatchingSchemes } from '../renderer/core/pass'; import { RenderInstancedQueue } from './render-instanced-queue'; -import { InstancedBuffer } from './instanced-buffer'; import { RenderBatchedQueue } from './render-batched-queue'; -import { BatchedBuffer } from './batched-buffer'; import { ShadowType } from '../renderer/scene/shadows'; import { Light, LightType } from '../renderer/scene/light'; -import { AABB, intersect } from '../geometry'; +import { intersect } from '../geometry'; import { Model } from '../renderer/scene/model'; import { RenderPipeline } from './render-pipeline'; -import { Camera } from '../renderer/scene'; -import { Mat4 } from '../math'; - -const _matShadowView = new Mat4(); -const _matShadowProj = new Mat4(); -const _matShadowViewProj = new Mat4(); -const _ab = new AABB(); +import { Camera, DirectionalLight, SpotLight } from '../renderer/scene'; +import { shadowCulling } from './scene-culling'; const _phaseID = getPhaseID('shadow-caster'); const _shadowPassIndices: number[] = []; @@ -89,38 +77,50 @@ export class RenderShadowMapBatchedQueue { this._batchedQueue = new RenderBatchedQueue(); } - public gatherLightPasses (globalDS: DescriptorSet, camera: Camera, light: Light, cmdBuff: CommandBuffer) { + public gatherLightPasses (camera: Camera, light: Light, cmdBuff: CommandBuffer, level = 0) { this.clear(); - const pipelineSceneData = this._pipeline.pipelineSceneData; - const shadowInfo = pipelineSceneData.shadows; + const sceneData = this._pipeline.pipelineSceneData; + const shadowInfo = sceneData.shadows; if (light && shadowInfo.enabled && shadowInfo.type === ShadowType.ShadowMap) { - const dirShadowObjects = pipelineSceneData.dirShadowObjects; - const castShadowObjects = pipelineSceneData.castShadowObjects; - switch (light.type) { case LightType.DIRECTIONAL: - 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); + // eslint-disable-next-line no-case-declarations + const dirLight = light as DirectionalLight; + if (dirLight.shadowEnabled) { + const csmLayers = sceneData.csmLayers; + let layer; + if (dirLight.shadowFixedArea) { + layer = csmLayers.specialLayer; + } else { + layer = csmLayers.layers[level]; + } + shadowCulling(camera, sceneData, layer); + const dirShadowObjects = layer.shadowObjects; + 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); + } } + break; case LightType.SPOT: - Mat4.invert(_matShadowView, light.node!.getWorldMatrix()); - Mat4.perspective(_matShadowProj, (light as any).angle, (light as any).aspect, 0.001, (light as any).range); - Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); - 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) { - AABB.transform(_ab, model.worldBounds, _matShadowViewProj); - if (!intersect.aabbFrustum(_ab, camera.frustum)) { continue; } - } + // eslint-disable-next-line no-case-declarations + const spotLight = light as SpotLight; + if (spotLight.shadowEnabled) { + const castShadowObjects = sceneData.csmLayers.castShadowObjects; + 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, _shadowPassIndices); + } } break; default: @@ -148,6 +148,7 @@ export class RenderShadowMapBatchedQueue { for (let j = 0; j < subModels.length; j++) { const subModel = subModels[j]; const shadowPassIdx = _shadowPassIndices[j]; + if (shadowPassIdx < 0) { return; } const pass = subModel.passes[shadowPassIdx]; const batchingScheme = pass.batchingScheme; diff --git a/cocos/core/pipeline/render-stage.ts b/cocos/core/pipeline/render-stage.ts index 32483aa74c..802cdf44f0 100644 --- a/cocos/core/pipeline/render-stage.ts +++ b/cocos/core/pipeline/render-stage.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline - */ - import { ccclass, displayOrder, serializable } from 'cc.decorator'; import { legacyCC } from '../global-exports'; import { RenderPipeline } from './render-pipeline'; @@ -47,10 +42,10 @@ export interface IRenderStageInfo { } /** - * @en The render stage actually renders render objects to the output window or other GFX [[FrameBuffer]]. + * @en The render stage actually renders render objects to the output window or other GFX [[gfx.Framebuffer]]. * Typically, a render stage collects render objects it's responsible for, clear the camera, * record and execute command buffer, and at last present the render result. - * @zh 渲染阶段是实质上的渲染执行者,它负责收集渲染数据并执行渲染将渲染结果输出到屏幕或其他 GFX [[FrameBuffer]] 中。 + * @zh 渲染阶段是实质上的渲染执行者,它负责收集渲染数据并执行渲染将渲染结果输出到屏幕或其他 GFX [[gfx.Framebuffer]] 中。 * 典型的渲染阶段会收集它所管理的渲染对象,按照 [[Camera]] 的清除标记进行清屏,记录并执行渲染指令缓存,并最终呈现渲染结果。 */ @ccclass('RenderStage') diff --git a/cocos/core/pipeline/scene-culling.ts b/cocos/core/pipeline/scene-culling.ts index 991e77e0c3..b2b28f419a 100644 --- a/cocos/core/pipeline/scene-culling.ts +++ b/cocos/core/pipeline/scene-culling.ts @@ -23,47 +23,22 @@ THE SOFTWARE. */ - - import { AABB, Frustum, intersect, Sphere } from '../geometry'; import { Model } from '../renderer/scene/model'; import { Camera, SKYBOX_FLAG } from '../renderer/scene/camera'; -import { Vec2, Vec3, Mat4, Quat, Vec4 } from '../math'; +import { Vec3, Mat4, Color } from '../math'; import { RenderPipeline } from './render-pipeline'; import { Pool } from '../memop'; import { IRenderObject, UBOShadow } from './define'; -import { ShadowType, Shadows } from '../renderer/scene/shadows'; -import { SphereLight, DirectionalLight, Light } from '../renderer/scene'; +import { ShadowType, Shadows, CSMLevel, CSMOptimizationMode } from '../renderer/scene/shadows'; +import { SphereLight, DirectionalLight } from '../renderer/scene'; +import { PipelineSceneData } from './pipeline-scene-data'; +import { ShadowLayerVolume } from './shadow/csm-layers'; const _tempVec3 = new Vec3(); -const _dir_negate = new Vec3(); -const _vec3_p = new Vec3(); -const _shadowPos = new Vec3(); -const _mat4_trans = new Mat4(); -const _castLightViewBounds = new AABB(); const _sphere = Sphere.create(0, 0, 0, 1); -const _cameraBoundingSphere = new Sphere(); -const _validFrustum = new Frustum(); -_validFrustum.accurate = true; -let _lightViewFrustum = new Frustum(); -_lightViewFrustum.accurate = true; -const _dirLightFrustum = new Frustum(); -const _matShadowTrans = new Mat4(); -const _matShadowView = new Mat4(); -const _matShadowViewInv = new Mat4(); -const _matShadowProj = new Mat4(); -const _matShadowViewProj = new Mat4(); -const _matShadowViewProjArbitaryPos = new Mat4(); -const _matShadowViewProjArbitaryPosInv = new Mat4(); -const _projPos = new Vec3(); -const _texelSize = new Vec2(); -const _projSnap = new Vec3(); -const _snap = new Vec3(); -const _focus = new Vec3(0, 0, 0); const roPool = new Pool(() => ({ model: null!, depth: 0 }), 128); -const dirShadowPool = new Pool(() => ({ model: null!, depth: 0 }), 128); -const castShadowPool = new Pool(() => ({ model: null!, depth: 0 }), 128); function getRenderObject (model: Model, camera: Camera) { let depth = 0; @@ -77,43 +52,6 @@ function getRenderObject (model: Model, camera: Camera) { return ro; } -function getDirShadowRenderObject (model: Model, camera: Camera) { - let depth = 0; - if (model.node) { - Vec3.subtract(_tempVec3, model.node.worldPosition, camera.position); - depth = Vec3.dot(_tempVec3, camera.forward); - } - const ro = dirShadowPool.alloc(); - ro.model = model; - ro.depth = depth; - return ro; -} - -function getCastShadowRenderObject (model: Model, camera: Camera) { - let depth = 0; - if (model.node) { - Vec3.subtract(_tempVec3, model.node.worldPosition, camera.position); - depth = Vec3.dot(_tempVec3, camera.forward); - } - const ro = castShadowPool.alloc(); - ro.model = model; - ro.depth = depth; - return ro; -} - -export function getShadowWorldMatrix (pipeline: RenderPipeline, rotation: Quat, dir: Vec3, out: Vec3) { - const shadows = pipeline.pipelineSceneData.shadows; - Vec3.negate(_dir_negate, dir); - const distance: number = shadows.fixedSphere.radius * Shadows.COEFFICIENT_OF_EXPANSION; - Vec3.multiplyScalar(_vec3_p, _dir_negate, distance); - Vec3.add(_vec3_p, _vec3_p, shadows.fixedSphere.center); - out.set(_vec3_p); - - Mat4.fromRT(_mat4_trans, rotation, _vec3_p); - - return _mat4_trans; -} - function updateSphereLight (pipeline: RenderPipeline, light: SphereLight) { const shadows = pipeline.pipelineSceneData.shadows; @@ -237,112 +175,41 @@ export function validPunctualLightsCulling (pipeline: RenderPipeline, camera: Ca } } } +export function shadowCulling (camera: Camera, sceneData: PipelineSceneData, layer: ShadowLayerVolume) { + const scene = camera.scene!; + const mainLight = scene.mainLight!; + const csmLayers = sceneData.csmLayers; + const csmLayerObjects = csmLayers.layerObjects; + const dirLightFrustum = layer.validFrustum; + const dirShadowObjects = layer.shadowObjects; + dirShadowObjects.length = 0; + const visibility = camera.visibility; -export function getCameraWorldMatrix (out: Mat4, camera: Camera) { - if (!camera.node) { return; } - - const cameraNode = camera.node; - const position = cameraNode.getWorldPosition(); - const rotation = cameraNode.getWorldRotation(); - - Mat4.fromRT(out, rotation, position); - out.m08 *= -1.0; - out.m09 *= -1.0; - out.m10 *= -1.0; -} - -export function QuantizeDirLightShadowCamera (out: Frustum, pipeline: RenderPipeline, - dirLight: DirectionalLight, camera: Camera, shadowInfo: Shadows) { - const device = pipeline.device; - - if (dirLight.shadowFixedArea) { - const x = dirLight.shadowOrthoSize; - const y = dirLight.shadowOrthoSize; - const near = dirLight.shadowNear; - const far = dirLight.shadowFar; - Mat4.fromRT(_matShadowTrans, dirLight.node!.getWorldRotation(), dirLight.node!.getWorldPosition()); - Mat4.invert(_matShadowView, _matShadowTrans); - Mat4.ortho(_matShadowProj, -x, x, -y, y, near, far, - device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY); - Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); - Mat4.invert(_matShadowViewInv, _matShadowView); - shadowInfo.matShadowView = _matShadowView; - shadowInfo.matShadowProj = _matShadowProj; - shadowInfo.matShadowViewProj = _matShadowViewProj; - - Frustum.createOrtho(out, x * 2.0, y * 2.0, near, far, _matShadowViewInv); - } else { - const invisibleOcclusionRange = dirLight.shadowInvisibleOcclusionRange; - const shadowMapWidth = shadowInfo.size.x; - - // Raw data - getCameraWorldMatrix(_mat4_trans, camera); - Frustum.split(_validFrustum, camera, _mat4_trans, 0.1, dirLight.shadowDistance); - _lightViewFrustum = Frustum.clone(_validFrustum); - - // view matrix with range back - Mat4.fromRT(_matShadowTrans, dirLight.node!.rotation, _focus); - Mat4.invert(_matShadowView, _matShadowTrans); - Mat4.invert(_matShadowViewInv, _matShadowView); - - const shadowViewArbitaryPos = _matShadowView.clone(); - _lightViewFrustum.transform(_matShadowView); - // bounding box in light space - AABB.fromPoints(_castLightViewBounds, new Vec3(10000000, 10000000, 10000000), new Vec3(-10000000, -10000000, -10000000)); - _castLightViewBounds.mergeFrustum(_lightViewFrustum); - - const r = _castLightViewBounds.halfExtents.z * 2.0; - _shadowPos.set(_castLightViewBounds.center.x, _castLightViewBounds.center.y, - _castLightViewBounds.center.z + _castLightViewBounds.halfExtents.z + invisibleOcclusionRange); - Vec3.transformMat4(_shadowPos, _shadowPos, _matShadowViewInv); - - Mat4.fromRT(_matShadowTrans, dirLight.node!.rotation, _shadowPos); - Mat4.invert(_matShadowView, _matShadowTrans); - Mat4.invert(_matShadowViewInv, _matShadowView); - - // calculate projection matrix params - // min value may lead to some shadow leaks - const orthoSizeMin = Vec3.distance(_validFrustum.vertices[0], _validFrustum.vertices[6]); - // max value is accurate but poor usage for shadowmap - _cameraBoundingSphere.center.set(0, 0, 0); - _cameraBoundingSphere.radius = -1.0; - _cameraBoundingSphere.mergePoints(_validFrustum.vertices); - const orthoSizeMax = _cameraBoundingSphere.radius * 2.0; - // use lerp(min, accurate_max) to save shadowmap usage - const orthoSize = orthoSizeMin * 0.8 + orthoSizeMax * 0.2; - shadowInfo.shadowCameraFar = r + invisibleOcclusionRange; - - // snap to whole texels - const halfOrthoSize = orthoSize * 0.5; - Mat4.ortho(_matShadowProj, -halfOrthoSize, halfOrthoSize, -halfOrthoSize, halfOrthoSize, 0.1, shadowInfo.shadowCameraFar, - device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY); - - if (shadowMapWidth > 0.0) { - Mat4.multiply(_matShadowViewProjArbitaryPos, _matShadowProj, shadowViewArbitaryPos); - Vec3.transformMat4(_projPos, _shadowPos, _matShadowViewProjArbitaryPos); - const invActualSize = 2.0 / shadowMapWidth; - _texelSize.set(invActualSize, invActualSize); - const modX = _projPos.x % _texelSize.x; - const modY = _projPos.y % _texelSize.y; - _projSnap.set(_projPos.x - modX, _projPos.y - modY, _projPos.z); - Mat4.invert(_matShadowViewProjArbitaryPosInv, _matShadowViewProjArbitaryPos); - Vec3.transformMat4(_snap, _projSnap, _matShadowViewProjArbitaryPosInv); - - Mat4.fromRT(_matShadowTrans, dirLight.node!.rotation, _snap); - Mat4.invert(_matShadowView, _matShadowTrans); - Mat4.invert(_matShadowViewInv, _matShadowView); - Frustum.createOrtho(out, orthoSize, orthoSize, 0.1, shadowInfo.shadowCameraFar, _matShadowViewInv); - } else { - for (let i = 0; i < 8; i++) { - out.vertices[i].set(0.0, 0.0, 0.0); + for (let i = csmLayerObjects.length - 1; i >= 0; i--) { + const csmLayerObject = csmLayerObjects.array[i]; + if (csmLayerObject) { + const model = csmLayerObject.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 + const accurate = intersect.aabbFrustum(model.worldBounds, dirLightFrustum); + if (accurate) { + dirShadowObjects.push(csmLayerObject); + if (layer.level < mainLight.csmLevel) { + if (mainLight.csmOptimizationMode === CSMOptimizationMode.RemoveDuplicates + && intersect.aabbFrustumCompletelyInside(model.worldBounds, dirLightFrustum)) { + csmLayerObjects.fastRemove(i); + } + } + } + } + } } - out.updatePlanes(); } - - Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); - shadowInfo.matShadowView = _matShadowView; - shadowInfo.matShadowProj = _matShadowProj; - shadowInfo.matShadowViewProj = _matShadowViewProj; } } @@ -352,27 +219,22 @@ export function sceneCulling (pipeline: RenderPipeline, camera: Camera) { const sceneData = pipeline.pipelineSceneData; const shadows = sceneData.shadows; const skybox = sceneData.skybox; + const csmLayers = sceneData.csmLayers; const renderObjects = sceneData.renderObjects; roPool.freeArray(renderObjects); renderObjects.length = 0; - const castShadowObjects = sceneData.castShadowObjects; - castShadowPool.freeArray(castShadowObjects); castShadowObjects.length = 0; - let dirShadowObjects: IRenderObject[] | null = null; + const castShadowObjects = csmLayers.castShadowObjects; + castShadowObjects.length = 0; + const csmLayerObjects = csmLayers.layerObjects; + csmLayerObjects.clear(); + if (shadows.enabled) { pipeline.pipelineUBO.updateShadowUBORange(UBOShadow.SHADOW_COLOR_OFFSET, shadows.shadowColor); if (shadows.type === ShadowType.ShadowMap) { - dirShadowObjects = pipeline.pipelineSceneData.dirShadowObjects; - dirShadowPool.freeArray(dirShadowObjects); dirShadowObjects.length = 0; - - // update dirLightFrustum + // update CSM layers if (mainLight && mainLight.node) { - QuantizeDirLightShadowCamera(_dirLightFrustum, pipeline, mainLight, camera, shadows); - } else { - for (let i = 0; i < 8; i++) { - _dirLightFrustum.vertices[i].set(0.0, 0.0, 0.0); - } - _dirLightFrustum.updatePlanes(); + csmLayers.update(sceneData, camera); } } } @@ -396,19 +258,12 @@ export function sceneCulling (pipeline: RenderPipeline, camera: Camera) { // filter model by view visibility if (model.enabled) { if (model.castShadow) { - castShadowObjects.push(getCastShadowRenderObject(model, camera)); + castShadowObjects.push(getRenderObject(model, camera)); + csmLayerObjects.push(getRenderObject(model, camera)); } if (model.node && ((visibility & model.node.layer) === model.node.layer) || (visibility & model.visFlags)) { - // 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(getDirShadowRenderObject(model, camera)); - } - } // frustum culling if (model.worldBounds && !intersect.aabbFrustum(model.worldBounds, camera.frustum)) { continue; diff --git a/cocos/core/pipeline/shadow/csm-layers.ts b/cocos/core/pipeline/shadow/csm-layers.ts new file mode 100644 index 0000000000..ed024f4e10 --- /dev/null +++ b/cocos/core/pipeline/shadow/csm-layers.ts @@ -0,0 +1,422 @@ +/* + 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 { DirectionalLight, Camera, Shadows, CSMLevel, CSMOptimizationMode } from '../../renderer/scene'; +import { Mat4, Vec3, Vec2, Quat } from '../../math'; +import { Frustum, AABB } from '../../geometry'; +import { IRenderObject } from '../define'; +import { legacyCC } from '../../global-exports'; +import { PipelineSceneData } from '../pipeline-scene-data'; +import { CachedArray } from '../../memop/cached-array'; + +const _mat4Trans = new Mat4(); +const _matShadowTrans = new Mat4(); +const _matShadowView = new Mat4(); +const _matShadowProj = new Mat4(); +const _matShadowViewProj = new Mat4(); +const _matShadowViewProjArbitaryPos = new Mat4(); +const _matShadowViewProjArbitaryPosInv = new Mat4(); + +const _focus = new Vec3(0, 0, 0); +const _projPos = new Vec3(); +const _texelSize = new Vec2(); +const _projSnap = new Vec3(); +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; + +export class ShadowLayerVolume { + protected _shadowObjects: IRenderObject[] = []; + + protected _shadowCameraFar = 0; + // Level is a vector, Indicates the location.range: [0 ~ 3] + protected _level: number; + + protected _matShadowView: Mat4 = new Mat4(); + protected _matShadowProj: Mat4 = new Mat4(); + protected _matShadowViewProj: Mat4 = new Mat4(); + + protected _validFrustum: Frustum = new Frustum(); + + // geometry renderer value + protected _splitFrustum: Frustum = new Frustum(); + protected _lightViewFrustum: Frustum = new Frustum(); + protected _castLightViewBoundingBox: AABB = new AABB(); + + constructor (level: number) { + this._level = level; + this._validFrustum.accurate = true; + this._splitFrustum.accurate = true; + this._lightViewFrustum.accurate = true; + } + + get level () { return this._level; } + + get shadowObjects () { + return this._shadowObjects; + } + + get shadowCameraFar () { + return this._shadowCameraFar; + } + set shadowCameraFar (val) { + this._shadowCameraFar = val; + } + + get matShadowView () { + return this._matShadowView; + } + set matShadowView (val) { + this._matShadowView = val; + } + + get matShadowProj () { + return this._matShadowProj; + } + set matShadowProj (val) { + this._matShadowProj = val; + } + + get matShadowViewProj () { + return this._matShadowViewProj; + } + set matShadowViewProj (val) { + this._matShadowViewProj = val; + } + + get validFrustum (): Readonly { + return this._validFrustum; + } + + get splitFrustum (): Readonly { + return this._splitFrustum; + } + + get lightViewFrustum (): Readonly { + return this._lightViewFrustum; + } + + get castLightViewBoundingBox (): Readonly { + return this._castLightViewBoundingBox; + } + + public copyToValidFrustum (validFrustum: Readonly) { + Frustum.copy(this._validFrustum, validFrustum); + } + + public calculateValidFrustumOrtho (width: number, height: number, near: number, far: number, transform: Mat4) { + Frustum.createOrtho(this._validFrustum, width, height, near, far, transform); + } + + public calculateSplitFrustum (camera: Camera, m: Mat4, start: number, end: number) { + Frustum.split(this._splitFrustum, camera, m, start, end); + } + + public destroy () { + this._shadowObjects.length = 0; + } + + public createMatrix (dirLight: DirectionalLight, shadowMapWidth: number, onlyForCulling: boolean) { + const device = legacyCC.director.root.device; + const invisibleOcclusionRange = dirLight.shadowInvisibleOcclusionRange; + Frustum.copy(this._lightViewFrustum, this._splitFrustum); + + // view matrix with range back + Mat4.fromRT(_matShadowTrans, dirLight.node!.rotation, _focus); + Mat4.invert(_matShadowView, _matShadowTrans); + const shadowViewArbitaryPos = _matShadowView.clone(); + this._lightViewFrustum.transform(_matShadowView); + + // bounding box in light space + AABB.fromPoints(this._castLightViewBoundingBox, _maxVec3, _minVec3); + this._castLightViewBoundingBox.mergeFrustum(this._lightViewFrustum); + let orthoSizeWidth; + let orthoSizeHeight; + if (dirLight.csmOptimizationMode === CSMOptimizationMode.DisableRotationFix) { + orthoSizeWidth = this._castLightViewBoundingBox.halfExtents.x * 2.0; + orthoSizeHeight = this._castLightViewBoundingBox.halfExtents.y * 2.0; + } else { + orthoSizeWidth = orthoSizeHeight = Vec3.distance(this._lightViewFrustum.vertices[0], this._lightViewFrustum.vertices[6]); + } + + if (dirLight.csmLevel > 1 && dirLight.csmOptimizationMode + === CSMOptimizationMode.RemoveDuplicates) { + if (this._level >= dirLight.csmLevel - 1) { + _maxLayerFarPlane = this._castLightViewBoundingBox.halfExtents.z; + _maxLayerPosz = this._castLightViewBoundingBox.center.z; + } else { + const alignFarPlaneDist = Math.abs(this._castLightViewBoundingBox.center.z - _maxLayerPosz) + _maxLayerFarPlane; + this._castLightViewBoundingBox.halfExtents.z = Math.max(this._castLightViewBoundingBox.center.z, alignFarPlaneDist); + } + } + + const r = this._castLightViewBoundingBox.halfExtents.z; + this._shadowCameraFar = r * 2 + invisibleOcclusionRange; + const center = this._castLightViewBoundingBox.center; + _shadowPos.set(center.x, center.y, center.z + r + invisibleOcclusionRange); + Vec3.transformMat4(_shadowPos, _shadowPos, _matShadowTrans); + + Mat4.fromRT(_matShadowTrans, dirLight.node!.rotation, _shadowPos); + Mat4.invert(_matShadowView, _matShadowTrans); + + if (!onlyForCulling) { + // snap to whole texels + const halfOrthoSizeWidth = orthoSizeWidth * 0.5; + const halfOrthoSizeHeight = orthoSizeHeight * 0.5; + Mat4.ortho(_matShadowProj, -halfOrthoSizeWidth, halfOrthoSizeWidth, -halfOrthoSizeHeight, halfOrthoSizeHeight, + 0.1, this._shadowCameraFar, device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY); + + Mat4.multiply(_matShadowViewProjArbitaryPos, _matShadowProj, shadowViewArbitaryPos); + Vec3.transformMat4(_projPos, _shadowPos, _matShadowViewProjArbitaryPos); + const invActualSize = 2.0 / shadowMapWidth; + _texelSize.set(invActualSize, invActualSize); + const modX = _projPos.x % _texelSize.x; + const modY = _projPos.y % _texelSize.y; + _projSnap.set(_projPos.x - modX, _projPos.y - modY, _projPos.z); + Mat4.invert(_matShadowViewProjArbitaryPosInv, _matShadowViewProjArbitaryPos); + Vec3.transformMat4(_snap, _projSnap, _matShadowViewProjArbitaryPosInv); + + Mat4.fromRT(_matShadowTrans, dirLight.node!.rotation, _snap); + Mat4.invert(_matShadowView, _matShadowTrans); + + // fill data + Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); + Mat4.copy(this._matShadowView, _matShadowView); + Mat4.copy(this._matShadowProj, _matShadowProj); + Mat4.copy(this._matShadowViewProj, _matShadowViewProj); + } + + Frustum.createOrtho(this._validFrustum, orthoSizeWidth, orthoSizeHeight, + 0.1, this._shadowCameraFar, _matShadowTrans); + } +} +export class CSMShadowLayer extends ShadowLayerVolume { + protected _splitCameraNear = 0; + protected _splitCameraFar = 0; + + protected _matShadowAtlas: Mat4 = new Mat4(); + protected _matShadowViewProjAtlas: Mat4 = new Mat4(); + + constructor (level: number) { + super(level); + this._calculateAtlas(level); + } + + get splitCameraNear () { + return this._splitCameraNear; + } + set splitCameraNear (val) { + this._splitCameraNear = val; + } + + get splitCameraFar () { + return this._splitCameraFar; + } + set splitCameraFar (val) { + this._splitCameraFar = val; + } + + get matShadowAtlas () { + return this._matShadowAtlas; + } + set matShadowViewAtlas (val) { + this._matShadowAtlas = val; + } + + get matShadowViewProjAtlas () { + return this._matShadowViewProjAtlas; + } + set matShadowViewProjAtlas (val) { + this._matShadowViewProjAtlas = val; + } + + public destroy () { + super.destroy(); + } + + private _calculateAtlas (level: number) { + 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); + } +} + +/** + * @en Shadow CSM layer manager + * @zh CSM阴影图层管理 + */ +export class CSMLayers { + protected _castShadowObjects: IRenderObject[] = []; + protected _layerObjects = new CachedArray(64); + + protected _layers: CSMShadowLayer[] = []; + // LevelCount is a scalar, Indicates the number. + protected _levelCount = 0; + // The ShadowTransformInfo object for 'fixed area shadow' || 'maximum clipping info' || 'CSM layers = 1'. + protected _specialLayer: ShadowLayerVolume = new ShadowLayerVolume(1); + protected _shadowDistance = 0; + + get castShadowObjects () { + return this._castShadowObjects; + } + + get layerObjects () { + return this._layerObjects; + } + + get layers () { + return this._layers; + } + + get specialLayer () { + return this._specialLayer; + } + + public constructor () { + for (let i = 0; i < CSMLevel.LEVEL_4; i++) { + this._layers[i] = new CSMShadowLayer(i); + } + } + + public update (sceneData: PipelineSceneData, camera: Camera) { + const scene = camera.scene!; + const dirLight = scene.mainLight; + if (dirLight === null) { return; } + + const shadowInfo = sceneData.shadows; + const levelCount = dirLight.csmLevel; + const shadowDistance = dirLight.shadowDistance; + + if (!shadowInfo.enabled || !dirLight.shadowEnabled) { return; } + + if (dirLight.shadowFixedArea) { + this._updateFixedArea(dirLight); + } else { + if (dirLight.csmNeedUpdate || this._levelCount !== levelCount + || this._shadowDistance !== shadowDistance) { + this._splitFrustumLevels(dirLight); + this._levelCount = levelCount; + this._shadowDistance = shadowDistance; + } + + this._calculateCSM(camera, dirLight, shadowInfo); + } + } + + public destroy () { + this._castShadowObjects.length = 0; + for (let i = 0; i < this._layers.length; i++) { + this._layers[i].destroy(); + } + this._layers.length = 0; + } + + private _updateFixedArea (dirLight: DirectionalLight) { + const device = legacyCC.director.root.device; + const x = dirLight.shadowOrthoSize; + const y = dirLight.shadowOrthoSize; + const near = dirLight.shadowNear; + const far = dirLight.shadowFar; + Mat4.fromRT(_matShadowTrans, dirLight.node!.getWorldRotation(), dirLight.node!.getWorldPosition()); + Mat4.invert(_matShadowView, _matShadowTrans); + Mat4.ortho(_matShadowProj, -x, x, -y, y, near, far, + device.capabilities.clipSpaceMinZ, device.capabilities.clipSpaceSignY); + Mat4.multiply(_matShadowViewProj, _matShadowProj, _matShadowView); + this._specialLayer.matShadowView = _matShadowView; + this._specialLayer.matShadowProj = _matShadowProj; + this._specialLayer.matShadowViewProj = _matShadowViewProj; + + this._specialLayer.calculateValidFrustumOrtho(x * 2.0, y * 2.0, near, far, _matShadowTrans); + } + + private _splitFrustumLevels (dirLight: DirectionalLight) { + const nd = 0.1; + const fd = dirLight.shadowDistance; + const ratio = fd / nd; + const level = dirLight.csmLevel; + const lambda = dirLight.csmLayerLambda; + this._layers[0].splitCameraNear = nd; + for (let i = 1; i < level; i++) { + // i ÷ numbers of level + const si = i / level; + // eslint-disable-next-line no-restricted-properties + const preNear = lambda * (nd * Math.pow(ratio, si)) + (1 - lambda) * (nd + (fd - nd) * si); + // Slightly increase the overlap to avoid fracture + const nextFar = preNear * 1.005; + this._layers[i].splitCameraNear = preNear; + this._layers[i - 1].splitCameraFar = nextFar; + } + // numbers of level - 1 + this._layers[level - 1].splitCameraFar = fd; + + dirLight.csmNeedUpdate = false; + } + + private _calculateCSM (camera: Camera, dirLight: DirectionalLight, shadowInfo: Shadows) { + const level = dirLight.csmLevel; + const shadowMapWidth = level > 1 ? shadowInfo.size.x * 0.5 : shadowInfo.size.x; + + if (shadowMapWidth < 0.0) { return; } + + this._getCameraWorldMatrix(_mat4Trans, camera); + for (let i = level - 1; i >= 0; i--) { + const csmLayer = this._layers[i]; + const near = csmLayer.splitCameraNear; + 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) { + this._specialLayer.shadowCameraFar = this._layers[0].shadowCameraFar; + Mat4.copy(this._specialLayer.matShadowView, this._layers[0].matShadowView); + Mat4.copy(this._specialLayer.matShadowProj, this._layers[0].matShadowProj); + Mat4.copy(this._specialLayer.matShadowViewProj, this._layers[0].matShadowViewProj); + this._specialLayer.copyToValidFrustum(this._layers[0].validFrustum); + } else { + this._specialLayer.calculateSplitFrustum(camera, _mat4Trans, 0.1, dirLight.shadowDistance); + this._specialLayer.createMatrix(dirLight, shadowMapWidth, true); + } + } + + private _getCameraWorldMatrix (out: Mat4, camera: Camera) { + if (!camera.node) { return; } + + const cameraNode = camera.node; + const position = cameraNode.getWorldPosition(); + const rotation = cameraNode.getWorldRotation(); + + Mat4.fromRT(out, rotation, position); + out.m08 *= -1.0; + out.m09 *= -1.0; + out.m10 *= -1.0; + } +} diff --git a/cocos/core/pipeline/shadow/shadow-flow.ts b/cocos/core/pipeline/shadow/shadow-flow.ts index 21c278f776..562b4a531c 100644 --- a/cocos/core/pipeline/shadow/shadow-flow.ts +++ b/cocos/core/pipeline/shadow/shadow-flow.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline.forward - */ - import { ccclass } from 'cc.decorator'; import { PIPELINE_FLOW_SHADOW, supportsR32FloatTexture } from '../define'; import { IRenderFlowInfo, RenderFlow } from '../render-flow'; @@ -35,13 +30,15 @@ import { ForwardFlowPriority } from '../enum'; import { ShadowStage } from './shadow-stage'; import { RenderPass, LoadOp, StoreOp, Format, Texture, TextureType, TextureUsageBit, ColorAttachment, - DepthStencilAttachment, RenderPassInfo, TextureInfo, FramebufferInfo, Swapchain } from '../../gfx'; + DepthStencilAttachment, RenderPassInfo, TextureInfo, FramebufferInfo, Swapchain, + Framebuffer, DescriptorSet, API } from '../../gfx'; import { RenderFlowTag } from '../pipeline-serialization'; import { ForwardPipeline } from '../forward/forward-pipeline'; import { RenderPipeline } from '..'; import { ShadowType } from '../../renderer/scene/shadows'; import { Light, LightType } from '../../renderer/scene/light'; import { Camera } from '../../renderer/scene'; +import { SpotLight } from '../../renderer/scene/spot-light'; const _validLights: Light[] = []; @@ -75,11 +72,26 @@ export class ShadowFlow extends RenderFlow { return true; } + public activate (pipeline: RenderPipeline) { + super.activate(pipeline); + + // 0: SHADOWMAP_FLOAT, 1: SHADOWMAP_RGBE. + const isRGBE = supportsR32FloatTexture(pipeline.device) ? 0 : 1; + pipeline.macros.CC_SHADOWMAP_FORMAT = isRGBE; + + // 0: SHADOWMAP_LINER_DEPTH_OFF, 1: SHADOWMAP_LINER_DEPTH_ON. + const isLinear = pipeline.device.gfxAPI === API.WEBGL ? 1 : 0; + pipeline.macros.CC_SHADOWMAP_USE_LINEAR_DEPTH = isLinear; + + pipeline.onGlobalPipelineStateChanged(); + } + public render (camera: Camera) { const pipeline = this._pipeline as ForwardPipeline; const shadowInfo = pipeline.pipelineSceneData.shadows; + const csmLayers = pipeline.pipelineSceneData.csmLayers; const shadowFrameBufferMap = pipeline.pipelineSceneData.shadowFrameBufferMap; - const castShadowObjects = pipeline.pipelineSceneData.castShadowObjects; + const castShadowObjects = csmLayers.castShadowObjects; const validPunctualLights = this._pipeline.pipelineSceneData.validPunctualLights; if (!shadowInfo.enabled || shadowInfo.type !== ShadowType.ShadowMap) { return; } @@ -88,8 +100,11 @@ export class ShadowFlow extends RenderFlow { for (;n < shadowInfo.maxReceived && m < validPunctualLights.length;) { const light = validPunctualLights[m]; if (light.type === LightType.SPOT) { - _validLights.push(light); - n++; + const spotLight = light as SpotLight; + if (spotLight.shadowEnabled) { + _validLights.push(light); + n++; + } } m++; } @@ -102,34 +117,32 @@ export class ShadowFlow extends RenderFlow { if (shadowInfo.shadowMapDirty) { this.resizeShadowMap(); } const { mainLight } = camera.scene!; - if (mainLight) { + if (mainLight && mainLight.shadowEnabled) { const globalDS = pipeline.descriptorSet; if (!shadowFrameBufferMap.has(mainLight)) { this._initShadowFrameBuffer(pipeline, mainLight, camera.window.swapchain); } const shadowFrameBuffer = shadowFrameBufferMap.get(mainLight); - for (let i = 0; i < this._stages.length; i++) { - const shadowStage = this._stages[i] as ShadowStage; - shadowStage.setUsage(globalDS, mainLight, shadowFrameBuffer!); - shadowStage.render(camera); + if (mainLight.shadowFixedArea) { + this._renderStage(camera, mainLight, shadowFrameBuffer!, globalDS); + } else { + for (let i = 0; i < mainLight.csmLevel; i++) { + this._renderStage(camera, mainLight, shadowFrameBuffer!, globalDS, i); + } } } for (let l = 0; l < _validLights.length; l++) { const light = _validLights[l]; - const globalDS = pipeline.globalDSManager.getOrCreateDescriptorSet(l)!; + const ds = pipeline.globalDSManager.getOrCreateDescriptorSet(light)!; if (!shadowFrameBufferMap.has(light)) { this._initShadowFrameBuffer(pipeline, light, camera.window.swapchain); } const shadowFrameBuffer = shadowFrameBufferMap.get(light); - for (let i = 0; i < this._stages.length; i++) { - const shadowStage = this._stages[i] as ShadowStage; - shadowStage.setUsage(globalDS, light, shadowFrameBuffer!); - shadowStage.render(camera); - } + this._renderStage(camera, light, shadowFrameBuffer!, ds); } _validLights.length = 0; @@ -164,7 +177,7 @@ export class ShadowFlow extends RenderFlow { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _initShadowFrameBuffer (pipeline: RenderPipeline, light: Light, swapchain: Swapchain) { const { device } = pipeline; @@ -219,6 +232,14 @@ export class ShadowFlow extends RenderFlow { shadowFrameBufferMap.set(light, shadowFrameBuffer); } + private _renderStage (camera: Camera, light: Light, shadowFrameBuffer: Framebuffer, globalDS: DescriptorSet, level = 0) { + for (let i = 0; i < this._stages.length; i++) { + const shadowStage = this._stages[i] as ShadowStage; + shadowStage.setUsage(globalDS, light, shadowFrameBuffer, level); + shadowStage.render(camera); + } + } + private clearShadowMap (validLights: Light[], camera: Camera) { const pipeline = this._pipeline; const scene = pipeline.pipelineSceneData; @@ -234,20 +255,21 @@ export class ShadowFlow extends RenderFlow { for (let i = 0; i < this._stages.length; i++) { const shadowStage = this._stages[i] as ShadowStage; shadowStage.setUsage(globalDS, mainLight, shadowFrameBuffer!); - shadowStage.render(camera); + shadowStage.clearFramebuffer(camera); } } for (let l = 0; l < validLights.length; l++) { const light = validLights[l]; + const ds = pipeline.globalDSManager.getOrCreateDescriptorSet(light)!; + if (!scene.shadowFrameBufferMap.has(light)) { + this._initShadowFrameBuffer(this._pipeline, light, camera.window.swapchain); + } + const shadowFrameBuffer = scene.shadowFrameBufferMap.get(light); - const globalDS = pipeline.globalDSManager.getOrCreateDescriptorSet(l)!; - - if (!scene.shadowFrameBufferMap.has(light)) { continue; } - for (let i = 0; i < this._stages.length; i++) { const shadowStage = this._stages[i] as ShadowStage; - shadowStage.setUsage(globalDS, light, shadowFrameBuffer!); + shadowStage.setUsage(ds, light, shadowFrameBuffer!); shadowStage.clearFramebuffer(camera); } } diff --git a/cocos/core/pipeline/shadow/shadow-stage.ts b/cocos/core/pipeline/shadow/shadow-stage.ts index 1f55f4c3cb..65770cd4ca 100644 --- a/cocos/core/pipeline/shadow/shadow-stage.ts +++ b/cocos/core/pipeline/shadow/shadow-stage.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module pipeline.forward - */ - import { ccclass } from 'cc.decorator'; import { Color, Rect, Framebuffer, DescriptorSet } from '../../gfx'; import { IRenderStageInfo, RenderStage } from '../render-stage'; @@ -35,9 +30,9 @@ import { ForwardStagePriority } from '../enum'; import { RenderShadowMapBatchedQueue } from '../render-shadow-map-batched-queue'; import { ForwardPipeline } from '../forward/forward-pipeline'; import { SetIndex } from '../define'; -import { Light } from '../../renderer/scene/light'; +import { Light, LightType } from '../../renderer/scene/light'; import { ShadowFlow } from './shadow-flow'; -import { Camera } from '../../renderer/scene'; +import { Camera, CSMLevel, DirectionalLight } from '../../renderer/scene'; const colors: Color[] = [new Color(1, 1, 1, 1)]; @@ -58,15 +53,17 @@ export class ShadowStage extends RenderStage { }; /** - * @en Sets the frame buffer for shadow map - * @zh 设置阴影渲染的 FrameBuffer + * @en Sets the render shadow map info + * @zh 设置阴影渲染信息 * @param light * @param shadowFrameBuffer + * @param level 层级 */ - public setUsage (globalDS: DescriptorSet, light: Light, shadowFrameBuffer: Framebuffer) { + public setUsage (globalDS: DescriptorSet, light: Light, shadowFrameBuffer: Framebuffer, level = 0) { this._globalDS = globalDS; this._light = light; this._shadowFrameBuffer = shadowFrameBuffer; + this._level = level; } private _additiveShadowQueue!: RenderShadowMapBatchedQueue; @@ -74,6 +71,7 @@ export class ShadowStage extends RenderStage { private _renderArea = new Rect(); private _light: Light | null = null; private _globalDS: DescriptorSet | null = null; + private _level = 0; public destroy () { this._shadowFrameBuffer = null; @@ -85,8 +83,18 @@ export class ShadowStage extends RenderStage { public clearFramebuffer (camera: Camera) { if (!this._light || !this._shadowFrameBuffer) { return; } + colors[0].w = camera.clearColor.w; const pipeline = this._pipeline as ForwardPipeline; + const pipelineSceneData = pipeline.pipelineSceneData; + const shadingScale = pipelineSceneData.shadingScale; + const shadowInfo = pipelineSceneData.shadows; + const vp = camera.viewport; + const shadowMapSize = shadowInfo.size; + this._renderArea.x = vp.x * shadowMapSize.x; + this._renderArea.y = vp.y * shadowMapSize.y; + this._renderArea.width = vp.width * shadowMapSize.x * shadingScale; + this._renderArea.height = vp.height * shadowMapSize.y * shadingScale; const cmdBuff = pipeline.commandBuffers[0]; const renderPass = this._shadowFrameBuffer.renderPass; @@ -99,20 +107,40 @@ export class ShadowStage extends RenderStage { const pipeline = this._pipeline; const pipelineSceneData = pipeline.pipelineSceneData; const shadowInfo = pipelineSceneData.shadows; - const shadingScale = pipelineSceneData.shadingScale; const descriptorSet = this._globalDS!; const cmdBuff = pipeline.commandBuffers[0]; + const level = this._level; if (!this._light || !this._shadowFrameBuffer) { return; } - this._pipeline.pipelineUBO.updateShadowUBOLight(descriptorSet, this._light); - this._additiveShadowQueue.gatherLightPasses(descriptorSet, camera, this._light, cmdBuff); + this._pipeline.pipelineUBO.updateShadowUBOLight(descriptorSet, this._light, level); + this._additiveShadowQueue.gatherLightPasses(camera, this._light, cmdBuff, level); - const vp = camera.viewport; const shadowMapSize = shadowInfo.size; - this._renderArea.x = vp.x * shadowMapSize.x; - this._renderArea.y = vp.y * shadowMapSize.y; - this._renderArea.width = vp.width * shadowMapSize.x * shadingScale; - this._renderArea.height = vp.height * shadowMapSize.y * shadingScale; + switch (this._light.type) { + case LightType.DIRECTIONAL: { + const mainLight = this._light as DirectionalLight; + if (mainLight.shadowFixedArea || mainLight.csmLevel === CSMLevel.LEVEL_1) { + this._renderArea.x = 0; + this._renderArea.y = 0; + this._renderArea.width = shadowMapSize.x; + this._renderArea.height = shadowMapSize.y; + } else { + this._renderArea.x = level % 2 * 0.5 * shadowMapSize.x; + this._renderArea.y = (1 - Math.floor(level / 2)) * 0.5 * shadowMapSize.y; + this._renderArea.width = 0.5 * shadowMapSize.x; + this._renderArea.height = 0.5 * shadowMapSize.y; + } + break; + } + case LightType.SPOT: { + this._renderArea.x = 0; + this._renderArea.y = 0; + this._renderArea.width = shadowMapSize.x; + this._renderArea.height = shadowMapSize.y; + break; + } + default: + } const device = pipeline.device; const renderPass = this._shadowFrameBuffer.renderPass; diff --git a/cocos/core/platform/debug.ts b/cocos/core/platform/debug.ts index c10384a818..8d4bf85f3f 100644 --- a/cocos/core/platform/debug.ts +++ b/cocos/core/platform/debug.ts @@ -22,13 +22,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ /* eslint-disable no-console */ - import { EDITOR, JSB, DEV, DEBUG } from 'internal:constants'; import debugInfos from '../../../DebugInfos'; import { legacyCC } from '../global-exports'; @@ -370,6 +365,7 @@ export function getError (errorId: number, ...param: any[]): string { /** * @en Returns whether or not to display the FPS and debug information. * @zh 是否显示 FPS 信息和部分调试信息。 + * @deprecated Since v3.6, Please use profiler.isShowingStates instead */ export function isDisplayStats (): boolean { // eslint-disable-next-line @typescript-eslint/no-unsafe-return @@ -379,10 +375,10 @@ export function isDisplayStats (): boolean { /** * @en Sets whether display the FPS and debug informations on the bottom-left corner. * @zh 设置是否在左下角显示 FPS 和部分调试。 + * @deprecated Since v3.6, Please use profiler.showStats instead */ export function setDisplayStats (displayStats: boolean) { if (legacyCC.profiler) { displayStats ? legacyCC.profiler.showStats() : legacyCC.profiler.hideStats(); - legacyCC.game.config.showFPS = !!displayStats; } } diff --git a/cocos/core/platform/deprecated.ts b/cocos/core/platform/deprecated.ts index be479caf75..83fd91c54d 100644 --- a/cocos/core/platform/deprecated.ts +++ b/cocos/core/platform/deprecated.ts @@ -23,13 +23,11 @@ THE SOFTWARE. */ -import { screenAdapter } from 'pal/screen-adapter'; import { markAsWarning, removeProperty, replaceProperty } from '../utils'; import { sys } from './sys'; import { View } from './view'; import { legacyCC } from '../global-exports'; import { screen } from './screen'; -import { Size } from '../math'; // #region deprecation on view removeProperty(View.prototype, 'View.prototype', [ @@ -82,6 +80,9 @@ markAsWarning(View.prototype, 'View.prototype', [ { name: 'isRetinaEnabled', }, + { + name: 'setRealPixelResolution', + }, ]); markAsWarning(legacyCC, 'cc', [ { diff --git a/cocos/core/platform/index.ts b/cocos/core/platform/index.ts index 833ae01e29..428c40e543 100644 --- a/cocos/core/platform/index.ts +++ b/cocos/core/platform/index.ts @@ -24,7 +24,6 @@ THE SOFTWARE. */ - import './deprecated'; export * from './sys'; diff --git a/cocos/core/platform/macro.ts b/cocos/core/platform/macro.ts index bd998773cb..9d3e319b92 100644 --- a/cocos/core/platform/macro.ts +++ b/cocos/core/platform/macro.ts @@ -25,12 +25,9 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ - +import { EDITOR, MINIGAME, NATIVE, PREVIEW, RUNTIME_BASED } from 'internal:constants'; import { legacyCC } from '../global-exports'; +import { Settings, settings } from '../settings'; const SUPPORT_TEXTURE_FORMATS = ['.astc', '.pkm', '.pvr', '.webp', '.jpg', '.jpeg', '.bmp', '.png']; @@ -845,103 +842,90 @@ const KEY = { */ dpadCenter: 1005, }; - /** * @en - * Predefined constants + * Predefined constants, see [[Macro]] for detailed contents. * @zh - * 预定义常量。 + * 预定义常量,具体内容参考 [[Macro]] 文档。 */ -const macro = { +/** + * @en Interface declaration for predefined constants, for usage you should be importing [[macro]] directly. + * @zh 预定义常量的接口声明,实际使用应该直接导入 [[macro]]。 + */ +interface Macro { /** * @en - * The image format supported by the engine defaults, and the supported formats may differ in different build platforms and device types. - * Currently all platform and device support ['.webp', '.jpg', '.jpeg', '.bmp', '.png'], ios mobile platform + * The image format supported by the engine, the actual supported formats may differ in different build platforms and device types. + * Currently contains ['.astc', '.pkm', '.pvr', '.webp', '.jpg', '.jpeg', '.bmp', '.png']. * @zh - * 引擎默认支持的图片格式,支持的格式可能在不同的构建平台和设备类型上有所差别。 - * 目前所有平台和设备支持的格式有 ['.webp', '.jpg', '.jpeg', '.bmp', '.png']. The iOS mobile platform also supports the PVR format。 + * 引擎默认支持的图片格式,实际运行时支持的格式可能在不同的构建平台和设备类型上有所差别。 + * 目前包含的格式有 ['.astc', '.pkm', '.pvr', '.webp', '.jpg', '.jpeg', '.bmp', '.png']。 */ - SUPPORT_TEXTURE_FORMATS, + SUPPORT_TEXTURE_FORMATS: string[]; /** * @en Key map for keyboard event * @zh 键盘事件的按键值。 * @example {@link cocos/core/platform/CCCommon/KEY.js} - * @deprecated since v3.3 please use KeyCode instead + * @deprecated since v3.3 please use [[KeyCode]] instead */ - KEY, + KEY: typeof KEY; /** - * PI / 180 + * @en One angle in radian, equals to PI / 180 + * @zh 弧度制中的单位角度,等同于 PI / 180 */ - RAD: Math.PI / 180, + RAD: number; /** - * One degree + * @en One radian in angle, equals to 180 / PI + * @zh 角度制中的单位弧度,等同于 180 / PI */ - DEG: 180 / Math.PI, + DEG: number; /** - * A maximum value of number + * @en A maximum value of number representing infinity repeat times + * @zh 重复执行的最大值,实际取值为数字的最大值 */ - REPEAT_FOREVER: (Number.MAX_VALUE - 1), + REPEAT_FOREVER: number; /** - * A minimal float value + * @en A float value for representing a minimum error in comparison + * @zh 用于比较时可忽略的浮点误差值 */ - FLT_EPSILON: 0.0000001192092896, + FLT_EPSILON: number; // Possible device orientations /** * @en Oriented vertically * @zh 竖屏朝向 */ - ORIENTATION_PORTRAIT: 1, + ORIENTATION_PORTRAIT: number; /** * @en Oriented horizontally * @zh 横屏朝向 */ - ORIENTATION_LANDSCAPE: 2, + ORIENTATION_LANDSCAPE: number; /** * @en Oriented automatically * @zh 自动适配朝向 */ - ORIENTATION_AUTO: 3, - - /** - *

- * If enabled, the texture coordinates will be calculated by using this formula:
- * - texCoord.left = (rect.x*2+1) / (texture.wide*2);
- * - texCoord.right = texCoord.left + (rect.width*2-2)/(texture.wide*2);
- *
- * The same for bottom and top.
- *
- * This formula prevents artifacts by using 99% of the texture.
- * The "correct" way to prevent artifacts is by expand the texture's border with the same color by 1 pixel
- *
- * Affected component:
- * - TMXLayer
- *
- * Enabled by default. To disabled set it to 0.
- * To modify it, in Web engine please refer to CCMacro.js, in JSB please refer to CCConfig.h - *

- * Currently not useful in 3D engine - */ - // FIX_ARTIFACTS_BY_STRECHING_TEXEL_TMX: true, + ORIENTATION_AUTO: number; /** * @en * Whether or not enabled tiled map auto culling. If you set the TiledMap skew or rotation, * then need to manually disable this, otherwise, the rendering will be wrong. - * Currently not useful in 3D engine + * Currently not used in 3D engine * @zh * 是否开启瓦片地图的自动裁减功能。瓦片地图如果设置了 skew, rotation 的话,需要手动关闭,否则渲染会出错。 * 在 3D 引擎中暂时无效。 * @default true + * @deprecated since v3.0 */ - ENABLE_TILEDMAP_CULLING: true, + ENABLE_TILEDMAP_CULLING: boolean; /** * @en @@ -951,7 +935,8 @@ const macro = { * no touch cancel event is triggered, and the touch will be considered active forever. * After multiple times of this action, our maximum touches number will be reached and all new touches will be ignored. * So this new mechanism can remove the touch that should be inactive if it's not updated during the last 5000 milliseconds. - * Though it might remove a real touch if it's just not moving for the last 5 seconds which is not easy with the sensibility of mobile touch screen. + * Though it might remove a real touch if it's just not moving for the last 5 seconds, + * which is not easy with the sensibility of mobile touch screen. * You can modify this value to have a better behavior if you find it's not enough. * @zh * 用于甄别一个触点对象是否已经失效并且可以被移除的延时时长 @@ -963,21 +948,21 @@ const macro = { * 你可以修改这个值来获得你需要的效果,默认值是 5000 毫秒。 * @default 5000 */ - TOUCH_TIMEOUT: 5000, + TOUCH_TIMEOUT: number; /** * @en * Boolean that indicates if the canvas contains an alpha channel, default sets to false for better performance. * Though if you want to make your canvas background transparent and show other dom elements at the background, - * you can set it to true before {{game.init}}. + * you can set it to true before [[game.init]]. * Web only. * @zh * 用于设置 Canvas 背景是否支持 alpha 通道,默认为 false,这样可以有更高的性能表现。 - * 如果你希望 Canvas 背景是透明的,并显示背后的其他 DOM 元素,你可以在 {{game.init}} 之前将这个值设为 true。 + * 如果你希望 Canvas 背景是透明的,并显示背后的其他 DOM 元素,你可以在 [[game.init]] 之前将这个值设为 true。 * 仅支持 Web * @default false */ - ENABLE_TRANSPARENT_CANVAS: false, + ENABLE_TRANSPARENT_CANVAS: boolean; /** * @en @@ -987,36 +972,36 @@ const macro = { * device with retina display usually have good detail on graphics with or without this option, * you probably don't want antialias if your game style is pixel art based. * Also, it could have great performance impact with some browser / device using software MSAA. - * You can set it to true before {{game.init}}. + * You can set it to true before [[game.init]]. * Only affect OpenGL ES and WebGL backend * @zh * 用于设置在创建 GL Context 时是否开启抗锯齿选项,默认值是 false。 * 将这个选项设置为 true 会让你的游戏画面稍稍平滑一些,比如旋转硬边贴图时的锯齿。是否开启这个选项很大程度上取决于你的游戏和面向的平台。 * 在大多数拥有 retina 级别屏幕的设备上用户往往无法区分这个选项带来的变化;如果你的游戏选择像素艺术风格,你也多半不会想开启这个选项。 * 同时,在少部分使用软件级别抗锯齿算法的设备或浏览器上,这个选项会对性能产生比较大的影响。 - * 你可以在 {{game.init}} 之前设置这个值,否则它不会生效。 + * 你可以在 [[game.init]] 之前设置这个值,否则它不会生效。 * 仅影响 WebGL 后端 * @default true */ - ENABLE_WEBGL_ANTIALIAS: true, + ENABLE_WEBGL_ANTIALIAS: boolean; /** * @en - * Used to set fxaa post-processing anti-aliasing, the default value is false. + * Used to set FXAA post-processing anti-aliasing, the default value is false. * @zh - * 用于开启fxaa后处理抗锯齿, 默认值为false。 + * 用于开启 FXAA 后处理抗锯齿, 默认值为 false。 * @default false */ - ENABLE_ANTIALIAS_FXAA: false, + ENABLE_ANTIALIAS_FXAA: boolean; /** * @en * Used to set bloom, the default value is false. * @zh - * 用于开启 bloom, 默认值为false。 + * 用于开启 bloom, 默认值为 false。 * @default false */ - ENABLE_BLOOM: false, + ENABLE_BLOOM: boolean; /** * @en @@ -1034,16 +1019,16 @@ const macro = { * 在 3D 引擎中暂时无效。 * @default false */ - CLEANUP_IMAGE_CACHE: false, + CLEANUP_IMAGE_CACHE: boolean; /** - * @en - * Whether to enable multi-touch. - * @zh - * 是否开启多点触摸 - * @default true - */ - ENABLE_MULTI_TOUCH: true, + * @en + * Whether to enable multi-touch. + * @zh + * 是否开启多点触摸 + * @default true + */ + ENABLE_MULTI_TOUCH: boolean; /** * @en @@ -1052,7 +1037,7 @@ const macro = { * Label 使用的 canvas pool 的最大大小,请根据项目同场景的 label 数量进行调整 * @default 20 */ - MAX_LABEL_CANVAS_POOL_SIZE: 20, + MAX_LABEL_CANVAS_POOL_SIZE: number; /** * @en @@ -1068,7 +1053,7 @@ const macro = { * 仅影响 WebGL 后端 * @default false */ - ENABLE_WEBGL_HIGHP_STRUCT_VALUES: false, + ENABLE_WEBGL_HIGHP_STRUCT_VALUES: boolean; /** * @zh Batcher2D 中内存增量的大小(KB) @@ -1084,9 +1069,60 @@ const macro = { * you can user larger buffer size to increase the elements count per 2d draw batch. * @default 144 KB */ + BATCHER2D_MEM_INCREMENT: number; + + /** + * @internal + */ + init (): void; +} + +/** + * @en + * Predefined constants, see [[Macro]] for detailed contents. + * @zh + * 预定义常量,具体内容参考 [[Macro]] 文档。 + */ +const macro: Macro = { + SUPPORT_TEXTURE_FORMATS, + KEY, + RAD: Math.PI / 180, + DEG: 180 / Math.PI, + REPEAT_FOREVER: (Number.MAX_VALUE - 1), + FLT_EPSILON: 0.0000001192092896, + ORIENTATION_PORTRAIT: 1, + ORIENTATION_LANDSCAPE: 2, + ORIENTATION_AUTO: 3, + ENABLE_TILEDMAP_CULLING: true, + TOUCH_TIMEOUT: 5000, + ENABLE_TRANSPARENT_CANVAS: false, + ENABLE_WEBGL_ANTIALIAS: true, + ENABLE_ANTIALIAS_FXAA: false, + ENABLE_BLOOM: false, + CLEANUP_IMAGE_CACHE: false, + ENABLE_MULTI_TOUCH: true, + MAX_LABEL_CANVAS_POOL_SIZE: 20, + ENABLE_WEBGL_HIGHP_STRUCT_VALUES: false, BATCHER2D_MEM_INCREMENT: 144, + init () { + if (NATIVE || MINIGAME || RUNTIME_BASED) { + this.CLEANUP_IMAGE_CACHE = true; + } + const defaultValues = settings.querySettings(Settings.Category.ENGINE, 'macros'); + if (defaultValues) { + for (const key in defaultValues) { + macro[key] = defaultValues[key]; + } + } + if (PREVIEW || EDITOR) { + this.ENABLE_WEBGL_ANTIALIAS = true; + } + if (EDITOR) { + this.ENABLE_TRANSPARENT_CANVAS = false; + } + }, }; legacyCC.macro = macro; - export { macro }; +export type { Macro }; diff --git a/cocos/core/platform/screen.ts b/cocos/core/platform/screen.ts index 42e606d744..99b586c83c 100644 --- a/cocos/core/platform/screen.ts +++ b/cocos/core/platform/screen.ts @@ -24,14 +24,11 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ -import { ConfigOrientation, IScreenOptions, screenAdapter } from 'pal/screen-adapter'; +import { IScreenOptions, screenAdapter } from 'pal/screen-adapter'; import { legacyCC } from '../global-exports'; -import { Size, Vec2 } from '../math'; +import { Size } from '../math'; +import { Settings, settings } from '../settings'; import { warnID } from './debug'; /** @@ -39,8 +36,13 @@ import { warnID } from './debug'; * @zh screen 单例对象提供简单的方法来做屏幕管理相关的工作。 */ class Screen { - private _init (options: IScreenOptions) { - screenAdapter.init(options, () => { + /** + * @internal + */ + public init () { + const exactFitScreen = settings.querySettings(Settings.Category.SCREEN, 'exactFitScreen') ?? true; + const orientation = settings.querySettings(Settings.Category.SCREEN, 'orientation') ?? 'auto'; + screenAdapter.init({ exactFitScreen, configOrientation: orientation }, () => { const director = legacyCC.director; if (!director.root?.pipeline) { warnID(1220); diff --git a/cocos/core/platform/sys.ts b/cocos/core/platform/sys.ts index f1d9b2b032..28cd500bf4 100644 --- a/cocos/core/platform/sys.ts +++ b/cocos/core/platform/sys.ts @@ -24,18 +24,14 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ import { systemInfo } from 'pal/system-info'; import { screenAdapter } from 'pal/screen-adapter'; import { WECHAT } from 'internal:constants'; import { legacyCC } from '../global-exports'; import { Rect } from '../math/rect'; +import { Vec2 } from '../math/vec2'; import { warnID, log } from './debug'; import { NetworkType, Language, OS, Platform, BrowserType, Feature } from '../../../pal/system-info/enum-type'; -import { Vec2 } from '../math'; import { screen } from './screen'; export declare namespace sys { @@ -51,7 +47,6 @@ export declare namespace sys { /** * @en A set of system related variables * @zh 一系列系统相关环境变量 - * @main */ export const sys = { Feature, @@ -59,7 +54,7 @@ export const sys = { /** * @en * Returns if the specified platform related feature is supported. - * @zn + * @zh * 返回指定的平台相关的特性是否支持。 */ hasFeature (feature: sys.Feature): boolean { @@ -283,6 +278,39 @@ export const sys = { systemInfo.openURL(url); }, + /** + * @internal + */ + init () { + try { + let localStorage: Storage | null = sys.localStorage = window.localStorage; + localStorage.setItem('storage', ''); + localStorage.removeItem('storage'); + localStorage = null; + } catch (e) { + const warn = function () { + warnID(5200); + }; + this.localStorage = { + // @ts-expect-error Type '() => void' is not assignable to type '(key: string) => string | null' + getItem: warn, + setItem: warn, + clear: warn, + removeItem: warn, + }; + } + + if (WECHAT) { + // @ts-expect-error HACK: this private property only needed on web & wechat JIT + this.__isWebIOS14OrIPadOS14Env = (sys.os === OS.IOS || sys.os === OS.OSX) && GameGlobal?.isIOSHighPerformanceMode + && /(OS 1((4\.[0-9])|(5\.[0-3])))|(Version\/1((4\.[0-9])|(5\.[0-3])))/.test(window.navigator.userAgent); + } else { + // @ts-expect-error HACK: this private property only needed on web & wechat JIT + this.__isWebIOS14OrIPadOS14Env = (sys.os === OS.IOS || sys.os === OS.OSX) && systemInfo.isBrowser + && /(OS 14)|(Version\/14)/.test(window.navigator.userAgent); + } + }, + /** * @en Get the current time in milliseconds * @zh 获取当前时间(毫秒为单位) @@ -330,34 +358,4 @@ export const sys = { }, }; -(function initSys () { - try { - let localStorage: Storage | null = sys.localStorage = window.localStorage; - localStorage.setItem('storage', ''); - localStorage.removeItem('storage'); - localStorage = null; - } catch (e) { - const warn = function () { - warnID(5200); - }; - sys.localStorage = { - // @ts-expect-error Type '() => void' is not assignable to type '(key: string) => string | null' - getItem: warn, - setItem: warn, - clear: warn, - removeItem: warn, - }; - } - - if (WECHAT) { - // @ts-expect-error HACK: this private property only needed on web & wechat JIT - sys.__isWebIOS14OrIPadOS14Env = (sys.os === OS.IOS || sys.os === OS.OSX) && GameGlobal?.isIOSHighPerformanceMode - && /(OS 1[4-9])|(Version\/1[4-9])/.test(window.navigator.userAgent); - } else { - // @ts-expect-error HACK: this private property only needed on web & wechat JIT - sys.__isWebIOS14OrIPadOS14Env = (sys.os === OS.IOS || sys.os === OS.OSX) && systemInfo.isBrowser - && /(OS 14)|(Version\/14)/.test(window.navigator.userAgent); - } -}()); - legacyCC.sys = sys; diff --git a/cocos/core/platform/view.ts b/cocos/core/platform/view.ts index d6d63a3030..f2419d341d 100644 --- a/cocos/core/platform/view.ts +++ b/cocos/core/platform/view.ts @@ -25,24 +25,20 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ - import '../data/class'; -import { EDITOR, MINIGAME, JSB, RUNTIME_BASED } from 'internal:constants'; +import { MINIGAME, JSB, RUNTIME_BASED, EDITOR } from 'internal:constants'; import { screenAdapter } from 'pal/screen-adapter'; -import { systemInfo } from 'pal/system-info'; -import { EventTarget } from '../event'; +import { Eventify, EventTarget } from '../event'; import { Rect, Size, Vec2 } from '../math'; import visibleRect from './visible-rect'; import { legacyCC } from '../global-exports'; -import { logID, errorID } from './debug'; +import { errorID } from './debug'; import { screen } from './screen'; import { macro } from './macro'; import { Orientation } from '../../../pal/screen-adapter/enum-type'; -import { game } from '../game'; +import { director } from '../director'; +import { System } from '../components'; +import { Settings, settings } from '../settings'; /** * @en View represents the game window.
@@ -51,14 +47,14 @@ import { game } from '../game'; * - Provide interaction with the window, like resize event on web, retina display support, etc...
* - Manage the scale and translation of canvas related to the frame on Web
*
- * With {{view}} as its singleton initialized by the engine, you don't need to call any constructor or create functions,
+ * With [[view]] as its singleton initialized by the engine, you don't need to call any constructor or create functions,
* the standard way to use it is by calling:
* - view.methodName();
* @zh View 代表游戏窗口视图,它的核心功能包括: * - 对所有 UI Canvas 进行设计分辨率适配。 * - 提供窗口视图的交互,比如监听 resize 事件,控制 retina 屏幕适配,等等。 * - 控制 Canvas 节点相对于外层 DOM 节点的缩放和偏移。 - * 引擎会自动初始化它的单例对象 {{view}},所以你不需要实例化任何 View,只需要直接使用 `view.methodName();` + * 引擎会自动初始化它的单例对象 [[view]],所以你不需要实例化任何 View,只需要直接使用 `view.methodName();` */ const localWinSize = new Size(); @@ -69,10 +65,10 @@ const orientationMap = { [macro.ORIENTATION_PORTRAIT]: Orientation.PORTRAIT, }; -export class View extends EventTarget { +export class View extends Eventify(System) { public static instance: View; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _designResolutionSize: Size; @@ -138,6 +134,15 @@ export class View extends EventTarget { visibleRect.init(this._visibleRect); } + if (!EDITOR) { + this.resizeWithBrowserSize(true); + const designResolution = settings.querySettings(Settings.Category.SCREEN, 'designResolution'); + if (designResolution) { + this.setDesignResolutionSize(Number(designResolution.width), Number(designResolution.height), + designResolution.policy || ResolutionPolicy.FIXED_HEIGHT); + } + } + // For now, the engine UI is adapted to resolution size, instead of window size. screenAdapter.on('window-resize', this._updateAdaptResult, this); screenAdapter.on('orientation-change', this._updateAdaptResult, this); @@ -381,7 +386,7 @@ export class View extends EventTarget { /** * @en Returns the current resolution policy * @zh 返回当前分辨率方案 - * @see {{ResolutionPolicy}} + * @see [[ResolutionPolicy]] */ public getResolutionPolicy (): ResolutionPolicy { return this._resolutionPolicy; @@ -413,7 +418,7 @@ export class View extends EventTarget { /** * @en Sets the current resolution policy * @zh 设置当前分辨率模式 - * @see {{ResolutionPolicy}} + * @see [[ResolutionPolicy]] */ public setResolutionPolicy (resolutionPolicy: ResolutionPolicy|number) { this._updateResolutionPolicy(resolutionPolicy); @@ -507,6 +512,8 @@ export class View extends EventTarget { * @param width Design resolution width. * @param height Design resolution height. * @param resolutionPolicy The resolution policy desired + * + * @deprecated since v3.6.0 */ public setRealPixelResolution (width: number, height: number, resolutionPolicy: ResolutionPolicy|number) { if (!JSB && !RUNTIME_BASED && !MINIGAME) { @@ -651,7 +658,8 @@ class ContainerStrategy { } protected _setupCanvas () { - const locCanvas = game.canvas; + // TODO: need to figure out why set width and height of canvas + const locCanvas = legacyCC.game.canvas; if (locCanvas) { const windowSize = screen.windowSize; locCanvas.width = windowSize.width; @@ -718,7 +726,7 @@ class ContentStrategy { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _buildResult (containerW, containerH, contentW, contentH, scaleX, scaleY): AdaptResult { // Makes content fit better the canvas @@ -883,41 +891,60 @@ class ContentStrategy { })(); /** - * ResolutionPolicy class is the root strategy class of scale strategy, - * its main task is to maintain the compatibility with Cocos2d-x

+ * @en ResolutionPolicy class is the root strategy class of scale strategy, + * its main task is to maintain the compatibility with Cocos2d-x. + * + * @zh ResolutionPolicy 类是适配策略的根策略类,它的主要任务是保持与 Cocos2d-x 的兼容性。 */ export class ResolutionPolicy { /** - * The entire application is visible in the specified area without trying to preserve the original aspect ratio.
+ * @en The entire application is visible in the specified area without trying to preserve the original aspect ratio. * Distortion can occur, and the application may appear stretched or compressed. + * + * @zh 整个应用程序在指定区域可见,无需尝试保留原始纵横比, + * 可能会发生变形,出现画面拉伸或压缩。 */ public static EXACT_FIT = 0; /** - * The entire application fills the specified area, without distortion but possibly with some cropping,
+ * @en The entire application fills the specified area, without distortion but possibly with some cropping, * while maintaining the original aspect ratio of the application. + * + * @zh 整个应用程序填充指定区域,没有变形,但可能有一些裁剪, + * 同时保持画面的原始纵横比。 */ public static NO_BORDER = 1; /** - * The entire application is visible in the specified area without distortion while maintaining the original
+ * @en The entire application is visible in the specified area without distortion while maintaining the original * aspect ratio of the application. Borders can appear on two sides of the application. + * + * @zh 整个应用程序在指定区域可见,没有变形,同时保持原始纵横比, + * 边框可能出现在画面的旁侧。 */ public static SHOW_ALL = 2; /** - * The application takes the height of the design resolution size and modifies the width of the internal
- * canvas so that it fits the aspect ratio of the device
- * no distortion will occur however you must make sure your application works on different
+ * @en The application takes the height of the design resolution size and modifies the width of the internal + * canvas so that it fits the aspect ratio of the device + * no distortion will occur however you must make sure your application works on different * aspect ratios + * + * @zh 该应用程序采用设计分辨率大小的高度并修改内部画布的宽度,使其适合设备的纵横比,不会发生变形, + * 但是您必须确保您的应用程序在不同的纵横比的设备下工作。 */ public static FIXED_HEIGHT = 3; /** - * The application takes the width of the design resolution size and modifies the height of the internal
- * canvas so that it fits the aspect ratio of the device
- * no distortion will occur however you must make sure your application works on different
+ * @en The application takes the width of the design resolution size and modifies the height of the internal + * canvas so that it fits the aspect ratio of the device + * no distortion will occur however you must make sure your application works on different * aspect ratios + * + * @zh 该应用程序采用设计分辨率大小的宽度并修改内部画布的高度,使其适合设备的纵横比,不会发生变形 + * 但是您必须确保您的应用程序在不同的纵横比的设备下工作。 */ public static FIXED_WIDTH = 4; /** - * Unknown policy + * @en Unknown policy + * + * @zh 未知的策略 */ public static UNKNOWN = 5; public static ContainerStrategy: typeof ContainerStrategy = ContainerStrategy; @@ -1005,6 +1032,7 @@ legacyCC.ResolutionPolicy = ResolutionPolicy; * @zh view 是全局的视图单例对象。 */ export const view = View.instance = legacyCC.view = new View(); +director.registerSystem('view', view, 0); /** * @en winSize is the alias object for the size of the current game window. diff --git a/cocos/core/platform/visible-rect.ts b/cocos/core/platform/visible-rect.ts index 6ef4460747..d66ffd3848 100644 --- a/cocos/core/platform/visible-rect.ts +++ b/cocos/core/platform/visible-rect.ts @@ -24,8 +24,6 @@ THE SOFTWARE. */ - - import { Rect } from '../math'; import { legacyCC } from '../global-exports'; diff --git a/cocos/core/renderer/config.ts b/cocos/core/renderer/config.ts index 0984cfb415..4b1a9bba57 100644 --- a/cocos/core/renderer/config.ts +++ b/cocos/core/renderer/config.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - let _stageOffset = 0; const _name2stageID = {}; diff --git a/cocos/core/renderer/core/constants.ts b/cocos/core/renderer/core/constants.ts index e210a47ac0..c3bdb5ac45 100644 --- a/cocos/core/renderer/core/constants.ts +++ b/cocos/core/renderer/core/constants.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - export enum RenderQueue { OPAQUE = 0, TRANSPARENT = 1, diff --git a/cocos/core/renderer/core/material-instance.jsb.ts b/cocos/core/renderer/core/material-instance.jsb.ts index 7b6e7ab4a1..32e13c0346 100644 --- a/cocos/core/renderer/core/material-instance.jsb.ts +++ b/cocos/core/renderer/core/material-instance.jsb.ts @@ -22,14 +22,8 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import { ccclass, editable, serializable } from 'cc.decorator'; -import { - _applyDecoratedDescriptor, - _assertThisInitialized, - _initializerDefineProperty, -} from '../data/utils/decorator-jsb-utils'; import { Material } from '../../assets'; -import { RenderableComponent } from '../../components'; +import { Renderer } from '../../components/renderer'; export const MaterialInstance = jsb.MaterialInstance; export type MaterialInstance = jsb.MaterialInstance; @@ -38,7 +32,7 @@ const materialInstanceProto: any = jsb.MaterialInstance.prototype; export interface IMaterialInstanceInfo { parent: Material; - owner?: RenderableComponent; + owner?: Renderer; subModelIdx?: number; } @@ -75,10 +69,3 @@ materialInstanceProto._onRebuildPSO = function () { this._owner._onRebuildPSO(this._subModelIdx, this); } }; - -const clsDecorator = ccclass('cc.MaterialInstance'); - -// TODO: -// _applyDecoratedDescriptor - -clsDecorator(MaterialInstance); diff --git a/cocos/core/renderer/core/material-instance.ts b/cocos/core/renderer/core/material-instance.ts index 9c51ab0aae..b9e027f1d4 100644 --- a/cocos/core/renderer/core/material-instance.ts +++ b/cocos/core/renderer/core/material-instance.ts @@ -23,20 +23,15 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module material - */ - -import { RenderableComponent } from '../../components/renderable-component'; import { Material } from '../../assets/material'; import { PassInstance } from './pass-instance'; import { MacroRecord } from './pass-utils'; import { PassOverrides } from './pass'; +import { Renderer } from '../../components/renderer'; export interface IMaterialInstanceInfo { parent: Material; - owner?: RenderableComponent; + owner?: Renderer; subModelIdx?: number; } @@ -56,7 +51,7 @@ export class MaterialInstance extends Material { protected _passes: PassInstance[] = []; private _parent: Material; - private _owner: RenderableComponent | null; + private _owner: Renderer | null; private _subModelIdx = 0; constructor (info: IMaterialInstanceInfo) { diff --git a/cocos/core/renderer/core/memory-pools.ts b/cocos/core/renderer/core/memory-pools.ts index 64888b18b2..cabd2ea341 100644 --- a/cocos/core/renderer/core/memory-pools.ts +++ b/cocos/core/renderer/core/memory-pools.ts @@ -23,8 +23,7 @@ THE SOFTWARE. */ - - +import { PolygonShape } from '@cocos/box2d'; import { DEBUG } from 'internal:constants'; import { NativeBufferPool } from './native-pools'; @@ -187,11 +186,38 @@ export enum PoolType { // buffers NODE, PASS, - AABB + AABB, + RENDER2D } export const NULL_HANDLE = 0 as unknown as IHandle; +export type Render2dHandle = IHandle; + +export enum Render2dView { + POSITION, // Vec3 + UV = 3, // Vec2 + COLOR = 5, // Vec4 + COUNT = 9 +} + +const Render2dViewDataType: BufferDataTypeManifest = { + [Render2dView.POSITION]: BufferDataType.FLOAT32, + [Render2dView.UV]: BufferDataType.FLOAT32, + [Render2dView.COLOR]: BufferDataType.UINT32, + [Render2dView.COUNT]: BufferDataType.NEVER, +}; + +const Render2dViewDataMembers: BufferDataMembersManifest = { + [Render2dView.POSITION]: Render2dView.UV - Render2dView.POSITION, + [Render2dView.UV]: Render2dView.COLOR - Render2dView.UV, + [Render2dView.COLOR]: Render2dView.COUNT - Render2dView.COLOR, + [Render2dView.COUNT]: 1, +}; + +export const Render2dPool = new BufferPool(PoolType.RENDER2D, Render2dViewDataType, Render2dViewDataMembers, Render2dView); + export type NodeHandle = IHandle; export enum NodeView { diff --git a/cocos/core/renderer/core/native-pools.jsb.ts b/cocos/core/renderer/core/native-pools.jsb.ts index 49b79129e0..82cacca2a8 100644 --- a/cocos/core/renderer/core/native-pools.jsb.ts +++ b/cocos/core/renderer/core/native-pools.jsb.ts @@ -23,7 +23,6 @@ THE SOFTWARE. */ - declare const jsb: any; export const NativeBufferPool = jsb.NativeBufferPool; diff --git a/cocos/core/renderer/core/native-pools.ts b/cocos/core/renderer/core/native-pools.ts index e87cf8f57e..b846ae14fc 100644 --- a/cocos/core/renderer/core/native-pools.ts +++ b/cocos/core/renderer/core/native-pools.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - export class NativeBufferPool { private _arrayBuffers: ArrayBuffer[] = []; private _chunkSize: number; diff --git a/cocos/core/renderer/core/pass-instance.ts b/cocos/core/renderer/core/pass-instance.ts index c428265233..f5c063d262 100644 --- a/cocos/core/renderer/core/pass-instance.ts +++ b/cocos/core/renderer/core/pass-instance.ts @@ -23,19 +23,14 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module material - */ - import { EffectAsset } from '../../assets/effect-asset'; import { MaterialInstance } from './material-instance'; import { BatchingSchemes, Pass, PassOverrides } from './pass'; import { overrideMacros, MacroRecord } from './pass-utils'; /** - * @en A pass instance defines an variant version of the [[Pass]] - * @zh 表示 [[Pass]] 的一种特殊实例 + * @en A pass instance defines an variant version of the [[renderer.Pass]] + * @zh 表示 [[renderer.Pass]] 的一种特殊实例 */ export class PassInstance extends Pass { /** diff --git a/cocos/core/renderer/core/pass-utils.ts b/cocos/core/renderer/core/pass-utils.ts index d65e226f9a..48f38709c8 100644 --- a/cocos/core/renderer/core/pass-utils.ts +++ b/cocos/core/renderer/core/pass-utils.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module material - */ - import { Type } from '../../gfx'; import { Color, Mat3, Mat4, Vec2, Vec3, Vec4, Quat, IVec2Like, IVec3Like, IVec4Like, IMat3Like, IMat4Like } from '../../math'; diff --git a/cocos/core/renderer/core/pass.jsb.ts b/cocos/core/renderer/core/pass.jsb.ts index 2c61e82d83..d22d9151e4 100644 --- a/cocos/core/renderer/core/pass.jsb.ts +++ b/cocos/core/renderer/core/pass.jsb.ts @@ -22,12 +22,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import { ccclass, editable, serializable } from 'cc.decorator'; -import { - _applyDecoratedDescriptor, - _assertThisInitialized, - _initializerDefineProperty, -} from '../data/utils/decorator-jsb-utils'; import { MacroRecord } from "./pass-utils"; import { EffectAsset } from '../../assets/effect-asset'; @@ -52,10 +46,3 @@ export enum BatchingSchemes { export const Pass = jsb.Pass; export type Pass = jsb.Pass; - -const clsDecorator = ccclass('cc.Pass'); - -//TODO: -// _applyDecoratedDescriptor - -clsDecorator(Pass); diff --git a/cocos/core/renderer/core/pass.ts b/cocos/core/renderer/core/pass.ts index 65ec4d8032..267fd023f4 100644 --- a/cocos/core/renderer/core/pass.ts +++ b/cocos/core/renderer/core/pass.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module material - */ - import { EDITOR } from 'internal:constants'; import { Root } from '../../root'; import { TextureBase } from '../../assets/texture-base'; @@ -36,7 +31,7 @@ import { getPhaseID } from '../../pipeline/pass-phase'; import { murmurhash2_32_gc } from '../../utils/murmurhash2_gc'; import { BufferUsageBit, DynamicStateFlagBit, DynamicStateFlags, Feature, GetTypeSize, MemoryUsageBit, PrimitiveMode, Type, Color, BlendState, BlendTarget, Buffer, BufferInfo, BufferViewInfo, DepthStencilState, DescriptorSet, - DescriptorSetInfo, DescriptorSetLayout, Device, RasterizerState, Sampler, Texture, Shader, PipelineLayout, + DescriptorSetInfo, DescriptorSetLayout, Device, RasterizerState, Sampler, Texture, Shader, PipelineLayout, deviceManager, } from '../../gfx'; import { EffectAsset } from '../../assets/effect-asset'; import { IProgramInfo, programLib } from './program-lib'; @@ -147,8 +142,8 @@ export class Pass { } /** - * @en Get pass hash value by [[Pass]] hash information. - * @zh 根据 [[Pass]] 的哈希信息获取哈希值。 + * @en Get pass hash value by [[renderer.Pass]] hash information. + * @zh 根据 [[renderer.Pass]] 的哈希信息获取哈希值。 * * @param hPass Handle of the pass info used to compute hash value. */ @@ -200,7 +195,7 @@ export class Pass { constructor (root: Root) { this._root = root; - this._device = root.device; + this._device = deviceManager.gfxDevice; } /** @@ -302,8 +297,8 @@ export class Pass { } /** - * @en Bind a GFX [[Texture]] the the given uniform binding - * @zh 绑定实际 GFX [[Texture]] 到指定 binding。 + * @en Bind a GFX [[gfx.Texture]] the the given uniform binding + * @zh 绑定实际 GFX [[gfx.Texture]] 到指定 binding。 * @param binding The binding for target uniform of texture type * @param value Target texture */ @@ -312,8 +307,8 @@ export class Pass { } /** - * @en Bind a GFX [[Sampler]] the the given uniform binding - * @zh 绑定实际 GFX [[Sampler]] 到指定 binding。 + * @en Bind a GFX [[gfx.Sampler]] the the given uniform binding + * @zh 绑定实际 GFX [[gfx.Sampler]] 到指定 binding。 * @param binding The binding for target uniform of sampler type * @param value Target sampler */ @@ -440,8 +435,8 @@ export class Pass { const samplerInfo = info && info.samplerHash !== undefined ? Sampler.unpackFromHash(info.samplerHash) : textureBase && textureBase.getSamplerInfo(); const sampler = this._device.getSampler(samplerInfo); - this._descriptorSet.bindSampler(binding, sampler, index); - this._descriptorSet.bindTexture(binding, texture, index); + this._descriptorSet.bindSampler(binding, sampler, index || 0); + this._descriptorSet.bindTexture(binding, texture, index || 0); } /** diff --git a/cocos/core/renderer/core/program-lib.ts b/cocos/core/renderer/core/program-lib.ts index 26aa1ea199..fa4499856b 100644 --- a/cocos/core/renderer/core/program-lib.ts +++ b/cocos/core/renderer/core/program-lib.ts @@ -23,14 +23,9 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module material - */ - import { EffectAsset } from '../../assets/effect-asset'; import { SetIndex, IDescriptorSetLayoutInfo, globalDescriptorSetLayout, localDescriptorSetLayout } from '../../pipeline/define'; -import { PipelineRuntime } from '../../pipeline/custom/pipeline'; +import { Pipeline, PipelineRuntime } from '../../pipeline/custom/pipeline'; import { genHandle, MacroRecord } from './pass-utils'; import { legacyCC } from '../../global-exports'; import { PipelineLayoutInfo, Device, Attribute, UniformBlock, ShaderInfo, @@ -39,6 +34,7 @@ import { PipelineLayoutInfo, Device, Attribute, UniformBlock, ShaderInfo, DescriptorType, GetTypeSize, ShaderStageFlagBit, API, UniformSamplerTexture, PipelineLayout, Shader, UniformStorageBuffer, UniformStorageImage, UniformSampler, UniformTexture, UniformInputAttachment } from '../../gfx'; import { debug } from '../../platform/debug'; +import { UpdateFrequency } from '../../pipeline/custom/types'; const _dsLayoutInfo = new DescriptorSetLayoutInfo(); @@ -447,9 +443,28 @@ class ProgramLib { const tmpl = this._templates[name]; const tmplInfo = this._templateInfos[tmpl.hash]; if (!tmplInfo.pipelineLayout) { - this.getDescriptorSetLayout(device, name); // ensure set layouts have been created - insertBuiltinBindings(tmpl, tmplInfo, globalDescriptorSetLayout, 'globals'); - tmplInfo.setLayouts[SetIndex.GLOBAL] = pipeline.descriptorSetLayout; + 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; + } tmplInfo.pipelineLayout = device.createPipelineLayout(new PipelineLayoutInfo(tmplInfo.setLayouts)); } diff --git a/cocos/core/renderer/scene/render-scene.jsb.ts b/cocos/core/renderer/core/render-scene.jsb.ts similarity index 81% rename from cocos/core/renderer/scene/render-scene.jsb.ts rename to cocos/core/renderer/core/render-scene.jsb.ts index d6fce2fc21..70043a4608 100644 --- a/cocos/core/renderer/scene/render-scene.jsb.ts +++ b/cocos/core/renderer/core/render-scene.jsb.ts @@ -41,16 +41,4 @@ export interface IRaycastResult { distance: number; } -const renderSceneProto = jsb.RenderScene.prototype; - -const oldAddBatch = renderSceneProto.addBatch; -renderSceneProto.addBatch = function (batch: DrawBatch2D) { - oldAddBatch.call(this, batch.native); -}; - -const oldRemoveBatch = renderSceneProto.removeBatch; -renderSceneProto.removeBatch = function (batch: DrawBatch2D) { - oldRemoveBatch.call(this, batch.native); -}; - export const RenderScene = jsb.RenderScene; diff --git a/cocos/core/renderer/scene/render-scene.ts b/cocos/core/renderer/core/render-scene.ts similarity index 57% rename from cocos/core/renderer/scene/render-scene.ts rename to cocos/core/renderer/core/render-scene.ts index acd2160acf..7d576c2179 100644 --- a/cocos/core/renderer/scene/render-scene.ts +++ b/cocos/core/renderer/core/render-scene.ts @@ -24,11 +24,11 @@ */ import { Root } from '../../root'; import { Node } from '../../scene-graph'; -import { Camera } from './camera'; -import { DirectionalLight } from './directional-light'; -import { Model } from './model'; -import { SphereLight } from './sphere-light'; -import { SpotLight } from './spot-light'; +import { Camera } from '../scene/camera'; +import { DirectionalLight } from '../scene/directional-light'; +import { Model } from '../scene/model'; +import { SphereLight } from '../scene/sphere-light'; +import { SpotLight } from '../scene/spot-light'; import { TransformBit } from '../../scene-graph/node-enum'; import { DrawBatch2D } from '../../../2d/renderer/draw-batch'; @@ -42,48 +42,91 @@ export interface ISceneNodeInfo { // parent: Node; } +/** + * @en The result of one raycast operation + * @zh 一次射线检测的结果 + */ export interface IRaycastResult { node: Node; distance: number; } +/** + * @en The render scene which is created by the [[Root]] and provides all basic render scene elements for the render process. + * It manages: + * 1. [[Camera]]s + * 2. [[Light]]s + * 3. Renderable objects: [[Model]]s and [[DrawBatch2D]]s + * @zh 渲染场景,由 [[Root]] 创建,并提供用于渲染流程的所有场景基础元素。它管理: + * 1. [[Camera]]s:相机 + * 2. [[Light]]s:光源 + * 3. 渲染元素:[[Model]]s 和 [[DrawBatch2D]]s + */ export class RenderScene { + /** + * @en The root manager of the renderer + * @zh 基础渲染管理器 + */ get root (): Root { return this._root; } + /** + * @en The name of the render scene + * @zh 渲染场景的名称 + */ get name (): string { return this._name; } + /** + * @en All cameras of the render scene + * @zh 渲染场景管理的所有相机 + */ get cameras (): Camera[] { return this._cameras; } + /** + * @en The main directional light source of the render scene + * @zh 渲染场景管理的主方向光源 + */ get mainLight (): DirectionalLight | null { return this._mainLight; } + /** + * @en All sphere light sources of the render scene + * @zh 渲染场景管理的所有球面光源 + */ get sphereLights (): SphereLight[] { return this._sphereLights; } + /** + * @en All spot light sources of the render scene + * @zh 渲染场景管理的所有聚光灯光源 + */ get spotLights (): SpotLight[] { return this._spotLights; } + /** + * @en All active models of the render scene + * @zh 渲染场景管理的所有模型 + */ get models (): Model[] { return this._models; } + /** + * @en All active 2d draw batches of the render scene + * @zh 渲染场景管理的所有 2D 渲染批次对象 + */ get batches () { return this._batches; } - public static registerCreateFunc (root: Root) { - root._createSceneFun = (_root: Root): RenderScene => new RenderScene(_root); - } - private _root: Root; private _name = ''; private _cameras: Camera[] = []; @@ -95,15 +138,34 @@ export class RenderScene { private _mainLight: DirectionalLight | null = null; private _modelId = 0; + /** + * Register the creation function of the render scene to root. + * @internal + */ + public static registerCreateFunc (root: Root) { + root._createSceneFun = (_root: Root): RenderScene => new RenderScene(_root); + } + constructor (root: Root) { this._root = root; } + /** + * @en Initialize the render scene + * @zh 初始化渲染场景 + * @returns Successful + */ public initialize (info: IRenderSceneInfo): boolean { this._name = info.name; return true; } + /** + * @en The update process of the render scene, it updates all rendering related data for the lights and the models. + * @zh 渲染场景的更新流程,会更新所有光源和模型的渲染相关数据。 + * @param stamp The update time stamp + * @returns void + */ public update (stamp: number) { const mainLight = this._mainLight; if (mainLight) { @@ -133,6 +195,10 @@ export class RenderScene { } } + /** + * @en Destroy the render scene, dangerous, please do not invoke manually. + * @zh 销毁渲染场景,请不要手动销毁,会造成未知行为。 + */ public destroy () { this.removeCameras(); this.removeSphereLights(); @@ -140,11 +206,19 @@ export class RenderScene { this.removeModels(); } + /** + * @en Attach a camera to the render scene + * @zh 向渲染场景挂载一个相机 + */ public addCamera (cam: Camera) { cam.attachToScene(this); this._cameras.push(cam); } + /** + * @en Detach a camera to the render scene + * @zh 从渲染场景移除一个相机 + */ public removeCamera (camera: Camera) { for (let i = 0; i < this._cameras.length; ++i) { if (this._cameras[i] === camera) { @@ -155,6 +229,10 @@ export class RenderScene { } } + /** + * @en Detach all cameras to the render scene + * @zh 从渲染场景移除所有相机 + */ public removeCameras () { for (const camera of this._cameras) { camera.detachFromScene(); @@ -162,10 +240,20 @@ export class RenderScene { this._cameras.splice(0); } + /** + * @en Sets the main light source for the render scene + * @zh 给渲染场景设置主光源 + * @param dl The main directional light source + */ public setMainLight (dl: DirectionalLight | null) { this._mainLight = dl; } + /** + * @en Remove the main light source from the render scene + * @zh 从渲染场景移除主光源 + * @param dl The main directional light source, if it's not the actual main light, nothing happens. + */ public unsetMainLight (dl: DirectionalLight) { if (this._mainLight === dl) { const dlList = this._directionalLights; @@ -180,11 +268,21 @@ export class RenderScene { } } + /** + * @en Add a directional light source, only one directional light is active and act as the main light source. + * @zh 增加一个方向光源,场景中只会有一个方向光是起效的,并且会作为主光源。 + * @param dl The directional light. + */ public addDirectionalLight (dl: DirectionalLight) { dl.attachToScene(this); this._directionalLights.push(dl); } + /** + * @en Remove a directional light source. + * @zh 删除一个方向光源。 + * @param dl The directional light. + */ public removeDirectionalLight (dl: DirectionalLight) { for (let i = 0; i < this._directionalLights.length; ++i) { if (this._directionalLights[i] === dl) { @@ -195,11 +293,21 @@ export class RenderScene { } } + /** + * @en Add a sphere light source. + * @zh 增加一个球面光源。 + * @param pl The sphere light. + */ public addSphereLight (pl: SphereLight) { pl.attachToScene(this); this._sphereLights.push(pl); } + /** + * @en Remove a sphere light source. + * @zh 删除一个球面光源。 + * @param pl The sphere light. + */ public removeSphereLight (pl: SphereLight) { for (let i = 0; i < this._sphereLights.length; ++i) { if (this._sphereLights[i] === pl) { @@ -211,11 +319,21 @@ export class RenderScene { } } + /** + * @en Add a spot light source. + * @zh 增加一个聚光灯光源。 + * @param sl The spot light. + */ public addSpotLight (sl: SpotLight) { sl.attachToScene(this); this._spotLights.push(sl); } + /** + * @en Remove a spot light source. + * @zh 删除一个聚光灯光源。 + * @param sl The spot light. + */ public removeSpotLight (sl: SpotLight) { for (let i = 0; i < this._spotLights.length; ++i) { if (this._spotLights[i] === sl) { @@ -227,6 +345,10 @@ export class RenderScene { } } + /** + * @en Remove all sphere light sources. + * @zh 删除所有球面光源。 + */ public removeSphereLights () { for (let i = 0; i < this._sphereLights.length; ++i) { this._sphereLights[i].detachFromScene(); @@ -234,6 +356,10 @@ export class RenderScene { this._sphereLights.length = 0; } + /** + * @en Remove all spot light sources. + * @zh 删除所有聚光灯光源。 + */ public removeSpotLights () { for (let i = 0; i < this._spotLights.length; ++i) { this._spotLights[i].detachFromScene(); @@ -241,11 +367,21 @@ export class RenderScene { this._spotLights = []; } + /** + * @en Add a model, all models attached to the render scene will be submitted for rendering. + * @zh 增加一个模型,渲染场景上挂载的所有模型都会被提交渲染。 + * @param m The model. + */ public addModel (m: Model) { m.attachToScene(this); this._models.push(m); } + /** + * @en Remove a model, model removed will no longer be submitted for rendering. + * @zh 删除一个模型,移除的模型将不再被提交渲染。 + * @param m The model. + */ public removeModel (model: Model) { for (let i = 0; i < this._models.length; ++i) { if (this._models[i] === model) { @@ -257,6 +393,10 @@ export class RenderScene { } } + /** + * @en Remove all models. + * @zh 删除所有模型。 + */ public removeModels () { for (const m of this._models) { m.detachFromScene(); @@ -265,10 +405,20 @@ export class RenderScene { this._models.length = 0; } + /** + * @en Add a draw batch of 2d objects, all draw batches attached to the render scene will be submitted for rendering. + * @zh 增加一个 2D 渲染批次,渲染场景上挂载的所有 2D 渲染批次都会被提交渲染。 + * @param batch The draw batch. + */ public addBatch (batch: DrawBatch2D) { this._batches.push(batch); } + /** + * @en Remove a draw batch of 2d objects, draw batch removed will no longer be submitted for rendering. + * @zh 删除一个 2D 渲染批次,移除的 2D 渲染批次将不再被提交渲染。 + * @param batch The draw batch. + */ public removeBatch (batch: DrawBatch2D) { for (let i = 0; i < this._batches.length; ++i) { if (this._batches[i] === batch) { @@ -278,16 +428,29 @@ export class RenderScene { } } + /** + * @en Remove all 2d draw batches. + * @zh 删除所有 2D 渲染批次。 + */ public removeBatches () { this._batches.length = 0; } + /** + * @en Notify all models that the global pipeline state have been updated so that they can update their render data and states. + * @zh 通知所有模型全局管线状态已更新,需要更新自身状态。 + */ public onGlobalPipelineStateChanged () { for (const m of this._models) { m.onGlobalPipelineStateChanged(); } } + /** + * @en Generate a new model id. + * @zh 生成一个新的模型 ID + * @returns The model id + */ public generateModelId (): number { return this._modelId++; } diff --git a/cocos/core/renderer/core/render-window.jsb.ts b/cocos/core/renderer/core/render-window.jsb.ts index 9e75de60aa..d1944dbbb7 100644 --- a/cocos/core/renderer/core/render-window.jsb.ts +++ b/cocos/core/renderer/core/render-window.jsb.ts @@ -22,8 +22,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import { ccclass } from 'cc.decorator'; - export interface IRenderWindowInfo { title?: string; width: number; @@ -36,10 +34,3 @@ declare const jsb: any; export const RenderWindow = jsb.RenderWindow; // @ts-ignore export type RenderWindow = jsb.RenderWindow; - -const clsDecorator = ccclass('cc.RenderWindow'); - -//TODO: -// _applyDecoratedDescriptor - -clsDecorator(RenderWindow); diff --git a/cocos/core/renderer/core/render-window.ts b/cocos/core/renderer/core/render-window.ts index 3f82a0fdfd..bd8b7d1872 100644 --- a/cocos/core/renderer/core/render-window.ts +++ b/cocos/core/renderer/core/render-window.ts @@ -54,8 +54,8 @@ const orientationMap: Record = { export class RenderWindow { /** * @en Get window width. Pre-rotated (i.e. rotationally invariant, always in identity/portrait mode) if possible. - * If you want to get oriented size instead, you should use [[Camera.width]] which corresponds to the current screen rotation. - * @zh 获取窗口宽度。如果支持交换链预变换,返回值将始终处于单位旋转(竖屏)坐标系下。如果需要获取旋转后的尺寸,请使用 [[Camera.width]]。 + * If you want to get oriented size instead, you should use [[renderer.scene.Camera.width]] which corresponds to the current screen rotation. + * @zh 获取窗口宽度。如果支持交换链预变换,返回值将始终处于单位旋转(竖屏)坐标系下。如果需要获取旋转后的尺寸,请使用 [[renderer.scene.Camera.width]]。 */ get width (): number { return this._width; @@ -63,8 +63,8 @@ export class RenderWindow { /** * @en Get window height. Pre-rotated (i.e. rotationally invariant, always in identity/portrait mode) if possible. - * If you want to get oriented size instead, you should use [[Camera.width]] which corresponds to the current screen rotation. - * @zh 获取窗口高度。如果支持交换链预变换,返回值将始终处于单位旋转(竖屏)坐标系下。如果需要获取旋转后的尺寸,请使用 [[Camera.height]]。 + * If you want to get oriented size instead, you should use [[renderer.scene.Camera.width]] which corresponds to the current screen rotation. + * @zh 获取窗口高度。如果支持交换链预变换,返回值将始终处于单位旋转(竖屏)坐标系下。如果需要获取旋转后的尺寸,请使用 [[renderer.scene.Camera.height]]。 */ get height (): number { return this._height; @@ -90,13 +90,6 @@ export class RenderWindow { return this._cameras; } - /** - * @private - */ - public static registerCreateFunc (root: Root) { - root._createWindowFun = (_root: Root): RenderWindow => new RenderWindow(_root); - } - protected _title = ''; protected _width = 1; protected _height = 1; @@ -109,9 +102,15 @@ export class RenderWindow { protected _hasOffScreenAttachments = false; protected _framebuffer: Framebuffer | null = null; - private constructor (root: Root) { + /** + * @private + */ + public static registerCreateFunc (root: Root) { + root._createWindowFun = (_root: Root): RenderWindow => new RenderWindow(_root); } + private constructor (root: Root) {} + public initialize (device: Device, info: IRenderWindowInfo): boolean { if (info.title !== undefined) { this._title = info.title; @@ -217,6 +216,12 @@ export class RenderWindow { } } + /** + * @en Extract all render cameras attached to the render window to the output cameras list + * @zh 将所有挂载到当前渲染窗口的摄像机存储到输出列表参数中 + * @param cameras @en The output cameras list, should be empty before invoke this function + * @zh 输出相机列表参数,传入时应该为空 + */ public extractRenderCameras (cameras: Camera[]) { for (let j = 0; j < this._cameras.length; j++) { const camera = this._cameras[j]; @@ -228,9 +233,9 @@ export class RenderWindow { } /** - * @zh - * 添加渲染相机 - * @param camera 渲染相机 + * @en Attach a new camera to the render window + * @zh 添加渲染相机 + * @param camera @en The camera to attach @zh 要挂载的相机 */ public attachCamera (camera: Camera) { for (let i = 0; i < this._cameras.length; i++) { @@ -243,9 +248,9 @@ export class RenderWindow { } /** - * @zh - * 移除渲染相机 - * @param camera 相机 + * @en Detach a camera from the render window + * @zh 移除场景中的渲染相机 + * @param camera @en The camera to detach @zh 要移除的相机 */ public detachCamera (camera: Camera) { for (let i = 0; i < this._cameras.length; ++i) { @@ -257,13 +262,17 @@ export class RenderWindow { } /** - * @zh - * 销毁全部渲染相机 + * @en Clear all attached cameras + * @zh 清空全部渲染相机 */ public clearCameras () { this._cameras.length = 0; } + /** + * @en Sort all attached cameras with priority + * @zh 按照优先级对所有挂载的相机排序 + */ public sortCameras () { this._cameras.sort((a: Camera, b: Camera) => a.priority - b.priority); } diff --git a/cocos/core/renderer/core/sampler-lib.jsb.ts b/cocos/core/renderer/core/sampler-lib.jsb.ts index 2752cb528b..ef30f56c9a 100644 --- a/cocos/core/renderer/core/sampler-lib.jsb.ts +++ b/cocos/core/renderer/core/sampler-lib.jsb.ts @@ -22,19 +22,9 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -import { ccclass, editable, serializable } from 'cc.decorator'; -import { - _applyDecoratedDescriptor, - _assertThisInitialized, - _initializerDefineProperty, -} from '../data/utils/decorator-jsb-utils'; import { legacyCC } from "../../global-exports"; const SamplerLib = nr.SamplerLib; -const clsDecorator = ccclass('cc.SamplerLib'); - -clsDecorator(SamplerLib); - export const samplerLib = new SamplerLib(); legacyCC.samplerLib = samplerLib; diff --git a/cocos/core/renderer/core/texture-buffer-pool.ts b/cocos/core/renderer/core/texture-buffer-pool.ts index 0fe05ef773..3052dc8dd3 100644 --- a/cocos/core/renderer/core/texture-buffer-pool.ts +++ b/cocos/core/renderer/core/texture-buffer-pool.ts @@ -23,10 +23,8 @@ THE SOFTWARE. */ - - import { getTypedArrayConstructor, Format, FormatInfos, TextureType, TextureUsageBit, - TextureFlagBit, Texture, TextureInfo, Device, BufferTextureCopy } from '../../gfx'; + Texture, TextureInfo, Device, BufferTextureCopy } from '../../gfx'; import { debug } from '../../platform/debug'; export function nearestPOT (num: number): number { diff --git a/cocos/core/renderer/scene/deprecated.ts b/cocos/core/renderer/deprecated.ts similarity index 91% rename from cocos/core/renderer/scene/deprecated.ts rename to cocos/core/renderer/deprecated.ts index 96b5e91f7d..76ff0dc3a1 100644 --- a/cocos/core/renderer/scene/deprecated.ts +++ b/cocos/core/renderer/deprecated.ts @@ -23,13 +23,14 @@ THE SOFTWARE. */ -import { replaceProperty, removeProperty, markAsWarning } from '../../utils/x-deprecated'; -import { RenderScene } from './render-scene'; -import { Layers } from '../../scene-graph/layers'; -import { legacyCC } from '../../global-exports'; -import { Pass } from '../core/pass'; -import { Camera } from './camera'; -import { Shadows } from './shadows'; +import { replaceProperty, removeProperty } from '../utils/x-deprecated'; +import { RenderScene } from './core/render-scene'; +import { Layers } from '../scene-graph/layers'; +import { legacyCC } from '../global-exports'; +import { Pass } from './core/pass'; +import { Camera } from './scene/camera'; +import { Shadows } from './scene/shadows'; +import { SpotLight } from './scene'; removeProperty(RenderScene.prototype, 'RenderScene.prototype', [ { name: 'raycastUI2DNode' }, @@ -224,3 +225,9 @@ removeProperty(Shadows.prototype, 'Shadows.prototype', [ name: 'saturation', }, ]); + +removeProperty(SpotLight.prototype, 'SpotLight.prototype', [ + { + name: 'aspect', + }, +]); diff --git a/cocos/core/renderer/index.ts b/cocos/core/renderer/index.ts index fbe9744874..90494f7070 100644 --- a/cocos/core/renderer/index.ts +++ b/cocos/core/renderer/index.ts @@ -27,8 +27,6 @@ import config from './config'; import * as scene from './scene'; -import './scene/deprecated'; - export { createIA } from './utils'; const addStage = config.addStage; @@ -42,4 +40,7 @@ export * from './core/texture-buffer-pool'; export * from './core/material-instance'; export * from './core/pass-instance'; export * from './core/memory-pools'; +export * from './core/render-scene'; +export * from './deprecated'; + export { scene }; diff --git a/cocos/core/renderer/scene/ambient.ts b/cocos/core/renderer/scene/ambient.ts index 9c568352ef..6e99d0c8d3 100644 --- a/cocos/core/renderer/scene/ambient.ts +++ b/cocos/core/renderer/scene/ambient.ts @@ -27,8 +27,22 @@ import { Vec4 } from '../../math'; import { legacyCC } from '../../global-exports'; import { AmbientInfo } from '../../scene-graph/scene-globals'; +/** + * @en Ambient lighting representation in the render scene. + * The initial data is setup in [[SceneGlobals.ambient]]. + * @zh 渲染场景中的环境光照设置。 + * 初始值是由 [[SceneGlobals.ambient]] 设置的。 + */ export class Ambient { + /** + * @en Default sun illuminance + * @zh 默认太阳亮度 + */ public static SUN_ILLUM = 65000.0; + /** + * @en Default sky illuminance + * @zh 默认天空亮度 + */ public static SKY_ILLUM = 20000.0; /** @@ -53,7 +67,6 @@ export class Ambient { return this._skyColorLDR; } } - set skyColor (color: Vec4) { const isHDR = (legacyCC.director.root).pipeline.pipelineSceneData.isHDR; if (isHDR) { @@ -75,7 +88,6 @@ export class Ambient { return this._skyIllumLDR; } } - set skyIllum (illum: number) { const isHDR = (legacyCC.director.root).pipeline.pipelineSceneData.isHDR; if (isHDR) { @@ -96,7 +108,6 @@ export class Ambient { return this._groundAlbedoLDR; } } - set groundAlbedo (color: Vec4) { const isHDR = (legacyCC.director.root).pipeline.pipelineSceneData.isHDR; if (isHDR) { @@ -106,14 +117,6 @@ export class Ambient { } } - get mipmapCount (): number { - return this._mipmapCount; - } - - set mipmapCount (count : number) { - this._mipmapCount = count; - } - protected _groundAlbedoHDR = new Vec4(0.2, 0.2, 0.2, 1.0); protected _skyColorHDR = new Vec4(0.2, 0.5, 0.8, 1.0); protected _skyIllumHDR = 0; diff --git a/cocos/core/renderer/scene/camera.jsb.ts b/cocos/core/renderer/scene/camera.jsb.ts index 3e7d73f08e..b3374451f1 100644 --- a/cocos/core/renderer/scene/camera.jsb.ts +++ b/cocos/core/renderer/scene/camera.jsb.ts @@ -25,9 +25,11 @@ import { Ray } from '../../geometry'; import { RenderWindow } from '../core/render-window'; import { ClearFlagBit } from '../../gfx'; -import { _tempFloatArray } from '../../scene-graph/node.jsb'; +import { _tempFloatArray, fillMat4WithTempFloatArray } from '../../scene-graph/utils.jsb'; import { Mat4, Vec3 } from '../../math'; +declare const jsb: any; + export enum CameraFOVAxis { VERTICAL, HORIZONTAL, @@ -118,6 +120,67 @@ Object.defineProperty(Camera, "standardLightMeterScale", { }, }); +Object.defineProperty(cameraProto, 'matView', { + configurable: true, + enumerable: true, + get () { + this.getMatView(); + fillMat4WithTempFloatArray(this._matView); + return this._matView; + } +}); + +Object.defineProperty(cameraProto, 'matProj', { + configurable: true, + enumerable: true, + get () { + this.getMatProj(); + fillMat4WithTempFloatArray(this._matProj); + return this._matProj; + } +}); + +Object.defineProperty(cameraProto, 'matProjInv', { + configurable: true, + enumerable: true, + get () { + this.getMatProjInv(); + fillMat4WithTempFloatArray(this._matProjInv); + return this._matProjInv; + } +}); + +Object.defineProperty(cameraProto, 'matViewProj', { + configurable: true, + enumerable: true, + get () { + this.getMatViewProj(); + fillMat4WithTempFloatArray(this._matViewProj); + return this._matViewProj; + } +}); + +Object.defineProperty(cameraProto, 'matViewProjInv', { + configurable: true, + enumerable: true, + get () { + this.getMatViewProjInv(); + fillMat4WithTempFloatArray(this._matViewProjInv); + return this._matViewProjInv; + } +}); + +const oldInitialize = cameraProto.initialize; + +cameraProto.initialize = function initialize () { + oldInitialize.apply(this, arguments); + this._matView = new Mat4(); + this._matProj = new Mat4(); + this._matProjInv = new Mat4(); + this._matViewProj = new Mat4(); + this._matViewProjInv = new Mat4(); +}; + const oldScreenPointToRay = cameraProto.screenPointToRay; const oldScreenToWorld = cameraProto.screenToWorld; const oldWorldToScreen = cameraProto.worldToScreen; @@ -181,12 +244,7 @@ cameraProto.worldMatrixToScreen = function worldMatrixToScreen (out: Mat4, world _tempFloatArray[17] = height; oldWorldMatrixToScreen.call(this); - Mat4.set(out, - _tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2], _tempFloatArray[3], - _tempFloatArray[4], _tempFloatArray[5], _tempFloatArray[6], _tempFloatArray[7], - _tempFloatArray[8], _tempFloatArray[9], _tempFloatArray[10], _tempFloatArray[11], - _tempFloatArray[12], _tempFloatArray[13], _tempFloatArray[14], _tempFloatArray[15] - ); + fillMat4WithTempFloatArray(out); return out; }; diff --git a/cocos/core/renderer/scene/camera.ts b/cocos/core/renderer/scene/camera.ts index 9464908e24..c8c41c3197 100644 --- a/cocos/core/renderer/scene/camera.ts +++ b/cocos/core/renderer/scene/camera.ts @@ -25,12 +25,10 @@ import { EDITOR } from 'internal:constants'; import { Frustum, Ray } from '../../geometry'; import { SurfaceTransform, ClearFlagBit, Device, Color, ClearFlags } from '../../gfx'; -import { - lerp, Mat4, Rect, toRadian, Vec3, IVec4Like, -} from '../../math'; +import { lerp, Mat4, Rect, toRadian, Vec3, IVec4Like } from '../../math'; import { CAMERA_DEFAULT_MASK } from '../../pipeline/define'; import { Node } from '../../scene-graph'; -import { RenderScene } from './render-scene'; +import { RenderScene } from '../core/render-scene'; import { legacyCC } from '../../global-exports'; import { RenderWindow } from '../core/render-window'; import { preTransforms } from '../../math/mat4'; @@ -119,8 +117,409 @@ export const SKYBOX_FLAG = ClearFlagBit.STENCIL << 1; const correctionMatrices: Mat4[] = []; +/** + * @en The render camera representation in the render scene, it's managed by [[Camera]] + * @zh 渲染场景中的相机对象,由项目层的 [[Camera]] 管理。 + */ export class Camera { + /** + * @en This exposure value corresponding to default standard camera exposure parameters. + * @zh 默认相机的曝光值。 + */ + public static get standardExposureValue () { + return 1.0 / 38400.0; + } + + /** + * @en The luminance unit scale used by area lights. + * @zh 默认局部光源使用的亮度单位缩放。 + */ + public static get standardLightMeterScale () { + return 10000.0; + } + + /** + * @en The name of the camera + * @zh 相机的名称 + */ + get name () { + return this._name; + } + + /** + * @en The render scene to which the camera is attached + * @zh 相机所挂载的场景 + */ + get scene () { + return this._scene; + } + + /** + * @en The node of the camera which determines its transform in world space. + * @zh 相机绑定的节点,决定了它在世界空间的变换矩阵 + */ + set node (val: Node) { + this._node = val; + } + get node () { + return this._node!; + } + + /** + * @en The render window of the camera + * @zh 相机关联的渲染窗口 + */ + set window (val) { + this._window = val; + } + get window () { + return this._window!; + } + + /** + * @en Whether the camera is enabled, a disabled camera won't be processed in the render pipeline. + * @zh 相机是否启用,未启用的相机不会被渲染 + */ + set enabled (val) { + this._enabled = val; + } + get enabled () { + return this._enabled; + } + + /** + * @en Visibility mask of the camera, declaring a set of node layers that will be visible to this camera. + * @zh 相机的可见性掩码,声明在当前相机中可见的节点层级集合。 + */ + set visibility (vis: number) { + this._visibility = vis; + } + get visibility (): number { + return this._visibility; + } + + /** + * @en Render priority of the camera. Cameras with higher depth are rendered after cameras with lower depth. + * @zh 相机的渲染优先级,值越小越优先渲染。 + */ + get priority (): number { + return this._priority; + } + + set priority (val: number) { + this._priority = val; + } + + /** + * @en The width of the camera's view size + * @zh 相机的视图宽度 + */ + get width () { + return this._width; + } + + /** + * @en The height of the camera's view size + * @zh 相机的视图高度 + */ + get height () { + return this._height; + } + + /** + * @en The world position of the camera + * @zh 相机的世界坐标 + */ + set position (val) { + this._position = val; + } + get position () { + return this._position; + } + + /** + * @en The forward vector of the camera's look direction + * @zh 指向相机观察方向的向量 + */ + set forward (val) { + this._forward = val; + } + get forward () { + return this._forward; + } + + /** + * @en Camera aperture, controls the exposure parameter. + * @zh 相机光圈,影响相机的曝光参数。 + */ + set aperture (val: CameraAperture) { + this._aperture = val; + this._apertureValue = FSTOPS[this._aperture]; + this.updateExposure(); + } + get aperture (): CameraAperture { + return this._aperture; + } + + /** + * @en Camera aperture value. + * @zh 相机光圈值。 + */ + get apertureValue (): number { + return this._apertureValue; + } + + /** + * @en Camera shutter, controls the exposure parameter. + * @zh 相机快门,影响相机的曝光参数。 + */ + set shutter (val: CameraShutter) { + this._shutter = val; + this._shutterValue = SHUTTERS[this._shutter]; + this.updateExposure(); + } + get shutter (): CameraShutter { + return this._shutter; + } + + /** + * @en Camera shutter value. + * @zh 相机快门值。 + */ + get shutterValue (): number { + return this._shutterValue; + } + + /** + * @en Camera ISO, controls the exposure parameter. + * @zh 相机感光度,影响相机的曝光参数。 + */ + set iso (val: CameraISO) { + this._iso = val; + this._isoValue = ISOS[this._iso]; + this.updateExposure(); + } + get iso (): CameraISO { + return this._iso; + } + + /** + * @en Camera ISO value. + * @zh 相机感光度值。 + */ + get isoValue (): number { + return this._isoValue; + } + + /** + * @en The calculated exposure of the camera + * @zh 相机的曝光参数 + */ + get exposure (): number { + return this._exposure; + } + + /** + * @en Clearing flags of the camera, specifies which part of the framebuffer will be actually cleared every frame. + * @zh 相机的缓冲清除标志位,指定帧缓冲的哪部分要每帧清除。 + */ + get clearFlag () : ClearFlags { + return this._clearFlag; + } + set clearFlag (flag: ClearFlags) { + this._clearFlag = flag; + } + + /** + * @en Clearing color of the camera. + * @zh 相机的颜色缓冲默认值。 + */ + set clearColor (val) { + this._clearColor.x = val.x; + this._clearColor.y = val.y; + this._clearColor.z = val.z; + this._clearColor.w = val.w; + } + get clearColor () { + return this._clearColor as IVec4Like; + } + + /** + * @en Clearing depth of the camera. + * @zh 相机的深度缓冲默认值。 + */ + get clearDepth () : number { + return this._clearDepth; + } + set clearDepth (depth: number) { + this._clearDepth = depth; + } + + /** + * @en Clearing stencil of the camera. + * @zh 相机的模板缓冲默认值。 + */ + get clearStencil () : number { + return this._clearStencil; + } + set clearStencil (stencil: number) { + this._clearStencil = stencil; + } + + /** + * @en The projection type of the camera. + * @zh 相机的投影类型。 + */ + set projectionType (val) { + this._proj = val; + this._isProjDirty = true; + } + get projectionType () { + return this._proj; + } + + /** + * @en The aspect ratio of the camera + * @zh 相机视图的长宽比 + */ + get aspect () { + return this._aspect; + } + + /** + * @en The viewport height of the orthogonal type camera. + * @zh 正交相机的视角高度。 + */ + set orthoHeight (val) { + this._orthoHeight = val; + this._isProjDirty = true; + } + get orthoHeight () { + return this._orthoHeight; + } + + /** + * @en The axis on which the FOV would be fixed regardless of screen aspect changes. + * @zh 指定视角的固定轴向,在此轴上不会跟随屏幕长宽比例变化。 + */ + set fovAxis (axis) { + this._fovAxis = axis; + this._isProjDirty = true; + } + get fovAxis () { + return this._fovAxis; + } + + /** + * @en Field of view of the camera. + * @zh 相机的视角大小。 + */ + set fov (fov) { + this._fov = fov; + this._isProjDirty = true; + } + get fov () { + return this._fov; + } + + /** + * @en Near clipping distance of the camera, should be as large as possible within acceptable range. + * @zh 相机的近裁剪距离,应在可接受范围内尽量取最大。 + */ + set nearClip (nearClip) { + this._nearClip = nearClip; + this._isProjDirty = true; + } + get nearClip () { + return this._nearClip; + } + + /** + * @en Far clipping distance of the camera, should be as small as possible within acceptable range. + * @zh 相机的远裁剪距离,应在可接受范围内尽量取最小。 + */ + set farClip (farClip) { + this._farClip = farClip; + this._isProjDirty = true; + } + get farClip () { + return this._farClip; + } + + /** + * @en The viewport rect of the camera, pre-rotated (i.e. always in identity/portrait mode) if possible. + * @zh 相机的视口矩形,如果设备允许的话,这个视口会永远保持竖屏状态,由渲染流程保障旋转的正确。 + */ + get viewport () { + return this._viewport; + } + set viewport (val) { + warnID(8302); + this.setViewportInOrientedSpace(val); + } + + /** + * @en The view frustum of the camera + * @zh 相机的视锥体 + */ + set frustum (val) { + this._frustum = val; + } + get frustum () { + return this._frustum; + } + + /** + * @en The view matrix of the camera + * @zh 相机的视图矩阵 + */ + get matView () { + return this._matView; + } + + /** + * @en The projection matrix of the camera + * @zh 相机的投影矩阵 + */ + get matProj () { + return this._matProj; + } + + /** + * @en The inverse of the projection matrix of the camera + * @zh 相机的逆投影矩阵 + */ + get matProjInv () { + return this._matProjInv; + } + + /** + * @en The view projection matrix of the camera + * @zh 相机的视图投影矩阵 + */ + get matViewProj () { + return this._matViewProj; + } + + /** + * @en The inverse of the view projection matrix of the camera + * @zh 相机的逆视图投影矩阵 + */ + get matViewProjInv () { + return this._matViewProjInv; + } + + /** + * @en Whether the camera is fixed size or matching the window size. + * @zh 相机是固定尺寸还是跟随屏幕尺寸 + */ public isWindowSize = true; + + /** + * @en Scale of the internal buffer size, + * set to 1 to keep the same with the canvas size. + * @zh 相机内部缓冲尺寸的缩放值, 1 为与 canvas 尺寸相同。 + */ public screenScale: number; private _device: Device; @@ -155,7 +554,6 @@ export class Camera { private _shutterValue = 0.0; private _iso: CameraISO = CameraISO.ISO100; private _isoValue = 0.0; - private _ec = 0.0; private _window: RenderWindow | null = null; private _width = 1; private _height = 1; @@ -164,7 +562,7 @@ export class Camera { private _visibility = CAMERA_DEFAULT_MASK; private _exposure = 0; private _clearStencil = 0; - private _geometryRenderer = new GeometryRenderer(); + private _geometryRenderer: GeometryRenderer | null = null; constructor (device: Device) { this._device = device; @@ -174,7 +572,6 @@ export class Camera { this._aspect = this.screenScale = 1; this._frustum.accurate = true; - this._geometryRenderer.activate(device); if (!correctionMatrices.length) { const ySign = device.capabilities.clipSpaceSignY; @@ -197,19 +594,9 @@ export class Camera { } /** - * this exposure value corresponding to default standard camera exposure parameters + * @en Initialize the camera, normally you shouldn't invoke this function, it's managed automatically. + * @zh 初始化相机,开发者通常不应该使用这个方法,初始化流程是自动管理的。 */ - public static get standardExposureValue () { - return 1.0 / 38400.0; - } - - /** - * luminance unit scale used by area lights - */ - public static get standardLightMeterScale () { - return 10000.0; - } - public initialize (info: ICameraInfo) { this.node = info.node; this._width = 1; @@ -225,26 +612,47 @@ export class Camera { this.changeTargetWindow(info.window); } + /** + * @en Destroy the camera, you shouldn't invoke this function, it's managed by the render scene. + * @zh 销毁相机,开发者不应该使用这个方法,销毁流程是由 RenderScene 管理的。 + */ public destroy () { + this._node = null; + this.detachFromScene(); if (this._window) { this._window.detachCamera(this); this.window = null!; } this._name = null; - this._geometryRenderer.destroy(); + this._geometryRenderer?.destroy(); } + /** + * @en Attach the camera to the given render scene so that it will be rendered in it. + * @zh 将相机添加到相关的渲染场景中,以便可以被渲染器渲染。 + * @param scene @en The render scene @zh 渲染场景 + */ public attachToScene (scene: RenderScene) { this._enabled = true; this._scene = scene; } + /** + * @en Detach the camera from previously attached render scene. It will no longer be rendered. + * @zh 将相机从之前设置的渲染场景移除,之后将不会再被渲染。 + */ public detachFromScene () { this._enabled = false; this._scene = null; } - public resize (width: number, height: number) { + /** + * @en Resize the view size of the camera. + * @zh 重置相机视图尺寸 + * @param width The width of the view size + * @param height The height of the view size + */ + public resize (width: number, height: number): void { if (!this._window) return; this._width = width; @@ -254,6 +662,12 @@ export class Camera { this._isProjDirty = true; } + /** + * @en Set a fixed size for the camera view. + * @zh 设置固定相机视图尺寸 + * @param width The width of the view size + * @param height The height of the view size + */ public setFixedSize (width: number, height: number) { this._width = width; this._height = height; @@ -261,7 +675,10 @@ export class Camera { this.isWindowSize = false; } - // Editor specific gizmo camera logic + /** + * Editor specific gizmo camera logic + * @internal + */ public syncCameraEditor (camera) { if (EDITOR) { this.position = camera.position; @@ -273,7 +690,12 @@ export class Camera { } } - public update (forceUpdate = false) { // for lazy eval situations like the in-editor preview + /** + * @en Update the camera's builtin matrixes + * @zh 更新相机的视图、投影等矩阵 + * @param forceUpdate If force update, then dirty flag will be ignored + */ + public update (forceUpdate = false): void { // for lazy eval situations like the in-editor preview if (!this._node) return; let viewProjDirty = false; @@ -283,6 +705,8 @@ export class Camera { this._forward.x = -this._matView.m02; this._forward.y = -this._matView.m06; this._forward.z = -this._matView.m10; + // Remove scale + Mat4.multiply(this._matView, new Mat4().scale(this._node.worldScale), this._matView); this._node.getWorldPosition(this._position); viewProjDirty = true; } @@ -316,105 +740,13 @@ export class Camera { } } - set node (val: Node) { - this._node = val; - } - - get node () { - return this._node!; - } - - set enabled (val) { - this._enabled = val; - } - - get enabled () { - return this._enabled; - } - - set orthoHeight (val) { - this._orthoHeight = val; - this._isProjDirty = true; - } - - get orthoHeight () { - return this._orthoHeight; - } - - set projectionType (val) { - this._proj = val; - this._isProjDirty = true; - } - - get projectionType () { - return this._proj; - } - - set fovAxis (axis) { - this._fovAxis = axis; - this._isProjDirty = true; - } - - get fovAxis () { - return this._fovAxis; - } - - set fov (fov) { - this._fov = fov; - this._isProjDirty = true; - } - - get fov () { - return this._fov; - } - - set nearClip (nearClip) { - this._nearClip = nearClip; - this._isProjDirty = true; - } - - get nearClip () { - return this._nearClip; - } - - set farClip (farClip) { - this._farClip = farClip; - this._isProjDirty = true; - } - - get farClip () { - return this._farClip; - } - - get surfaceTransform() { + get surfaceTransform () { return this._curTransform; } - set clearColor (val) { - this._clearColor.x = val.x; - this._clearColor.y = val.y; - this._clearColor.z = val.z; - this._clearColor.w = val.w; - } - - get clearColor () { - return this._clearColor as IVec4Like; - } - /** - * Pre-rotated (i.e. always in identity/portrait mode) if possible. - */ - get viewport () { - return this._viewport; - } - - set viewport (val) { - warnID(8302); - this.setViewportInOrientedSpace(val); - } - - /** - * Set the viewport in oriented space (local to screen rotations) + * @en Set the viewport in oriented space (equal to the actual screen rotation) + * @zh 在目标朝向空间(实际屏幕朝向)内设置相机视口 */ public setViewportInOrientedSpace (val: Rect) { const { x, width, height } = val; @@ -459,175 +791,31 @@ export class Camera { this.resize(this.width, this.height); } - get scene () { - return this._scene; - } - - get name () { - return this._name; - } - - get width () { - return this._width; - } - - get height () { - return this._height; - } - - get aspect () { - return this._aspect; - } - - get matView () { - return this._matView; - } - - get matProj () { - return this._matProj; - } - - get matProjInv () { - return this._matProjInv; - } - - get matViewProj () { - return this._matViewProj; - } - - get matViewProjInv () { - return this._matViewProjInv; - } - - set frustum (val) { - this._frustum = val; - } - - get frustum () { - return this._frustum; - } - - set window (val) { - this._window = val; - } - - get window () { - return this._window!; - } - - set forward (val) { - this._forward = val; - } - - get forward () { - return this._forward; - } - - set position (val) { - this._position = val; - } - - get position () { - return this._position; - } - - set visibility (vis: number) { - this._visibility = vis; - } - get visibility (): number { - return this._visibility; - } - - get priority (): number { - return this._priority; - } - - set priority (val: number) { - this._priority = val; - } - - set aperture (val: CameraAperture) { - this._aperture = val; - this._apertureValue = FSTOPS[this._aperture]; - this.updateExposure(); - } - - get aperture (): CameraAperture { - return this._aperture; - } - - get apertureValue (): number { - return this._apertureValue; - } - - set shutter (val: CameraShutter) { - this._shutter = val; - this._shutterValue = SHUTTERS[this._shutter]; - this.updateExposure(); - } - - get shutter (): CameraShutter { - return this._shutter; - } - - get shutterValue (): number { - return this._shutterValue; - } - - set iso (val: CameraISO) { - this._iso = val; - this._isoValue = ISOS[this._iso]; - this.updateExposure(); - } - - get iso (): CameraISO { - return this._iso; - } - - get isoValue (): number { - return this._isoValue; - } - - set ec (val: number) { - this._ec = val; - } - - get ec (): number { - return this._ec; - } - - get exposure (): number { - return this._exposure; - } - - get clearFlag () : ClearFlags { - return this._clearFlag; - } - - set clearFlag (flag: ClearFlags) { - this._clearFlag = flag; - } - - get clearDepth () : number { - return this._clearDepth; - } - - set clearDepth (depth: number) { - this._clearDepth = depth; - } - - get clearStencil () : number { - return this._clearStencil; - } - - set clearStencil (stencil: number) { - this._clearStencil = stencil; + /** + * @en create geometry renderer for this camera + * @zh 创建这个摄像机的几何体渲染器 + */ + public initGeometryRenderer() { + if (!this._geometryRenderer) { + this._geometryRenderer = legacyCC.internal.GeometryRenderer ? new legacyCC.internal.GeometryRenderer() : null; + this._geometryRenderer?.activate(this._device); + } } + /** + * @en get geometry renderer of this camera + * @zh 获取这个摄像机的几何体渲染器 + * @returns @en return the geometry renderer @zh 返回几何体渲染器 + */ get geometryRenderer () { return this._geometryRenderer; } + /** + * @en Change the target render window to another one + * @zh 修改相机的目标渲染窗口 + * @param window The target render window, could be null + */ public changeTargetWindow (window: RenderWindow | null = null) { if (this._window) { this._window.detachCamera(this); @@ -645,6 +833,10 @@ export class Camera { } } + /** + * @en Detach camera from the render window + * @zh 将 camera 从渲染窗口移除 + */ public detachCamera () { if (this._window) { this._window.detachCamera(this); @@ -652,7 +844,12 @@ export class Camera { } /** - * transform a screen position (in oriented space) to a world space ray + * @en Transform a screen position (in oriented space) to a world space ray + * @zh 将一个屏幕空间(在实际朝向下)点转换到世界空间的射线 + * @param out the resulting ray + * @param x the screen x of the position + * @param y the screen y of the position + * @returns the resulting ray */ public screenPointToRay (out: Ray, x: number, y: number): Ray { if (!this._node) return null!; @@ -687,7 +884,11 @@ export class Camera { } /** - * transform a screen position (in oriented space) to world space + * @en Transform a screen position (in oriented space) to world space + * @zh 将一个屏幕空间(在实际朝向下)位置转换到世界空间 + * @param out the resulting vector + * @param screenPos the screen position to be transformed + * @returns the resulting vector */ public screenToWorld (out: Vec3, screenPos: Vec3): Vec3 { const width = this.width; @@ -733,7 +934,11 @@ export class Camera { } /** - * transform a world space position to screen space + * @en Transform a world space position to screen space rendered by the camera + * @zh 将一个世界空间位置转换到相机渲染后的屏幕空间 + * @param out the resulting vector + * @param worldPos the world position to be transformed + * @returns the resulting vector */ public worldToScreen (out: Vec3, worldPos: Vec3 | Readonly): Vec3 { const ySign = this._device.capabilities.clipSpaceSignY; @@ -760,12 +965,13 @@ export class Camera { } /** - * transform a world space matrix to screen space - * @param {Mat4} out the resulting vector - * @param {Mat4} worldMatrix the world space matrix to be transformed - * @param {number} width framebuffer width - * @param {number} height framebuffer height - * @returns {Mat4} the resulting vector + * @en Transform a world space matrix to screen space rendered by the camera + * @zh 将一个世界空间矩阵转换到相机渲染后的屏幕空间 + * @param out the resulting matrix + * @param worldMatrix the world space matrix to be transformed + * @param width framebuffer width + * @param height framebuffer height + * @returns the resulting matrix */ public worldMatrixToScreen (out: Mat4, worldMatrix: Mat4, width: number, height: number) { Mat4.multiply(out, this._matViewProj, worldMatrix); @@ -782,6 +988,11 @@ export class Camera { return out; } + /** + * @en Set exposure with actual value. + * @zh 设置相机的曝光值 + * @param ev100 + */ protected setExposure (ev100) { this._exposure = 0.833333 / (2.0 ** ev100); } diff --git a/cocos/core/renderer/scene/directional-light.ts b/cocos/core/renderer/scene/directional-light.ts index 0c3793fcd6..85c7728935 100644 --- a/cocos/core/renderer/scene/directional-light.ts +++ b/cocos/core/renderer/scene/directional-light.ts @@ -27,11 +27,16 @@ import { legacyCC } from '../../global-exports'; import { Vec3 } from '../../math'; import { Ambient } from './ambient'; import { Light, LightType } from './light'; -import { PCFType, Shadows } from './shadows'; +import { CSMLevel, CSMOptimizationMode, PCFType, Shadows } from './shadows'; const _forward = new Vec3(0, 0, -1); const _v3 = new Vec3(); +/** + * @en The directional light representation in the render scene, it acts as the main light source in a scene. + * As main light, only one directional light can be created in a scene, it can generate realtime shadows with configuration. + * @zh 渲染场景中的方向光抽象,这是场景中的主光源。作为主光源,每个场景只能有一个方向光,它也包含阴影配置,用来生成实时阴影。 + */ export class DirectionalLight extends Light { protected _dir: Vec3 = new Vec3(1.0, -1.0, -1.0); protected _illuminanceHDR: number = Ambient.SUN_ILLUM; @@ -45,8 +50,12 @@ export class DirectionalLight extends Light { protected _shadowBias = 0.00001; protected _shadowNormalBias = 0.0; protected _shadowSaturation = 1.0; - protected _shadowDistance = 100; + protected _shadowDistance = 50; protected _shadowInvisibleOcclusionRange = 200; + protected _csmLevel = CSMLevel.LEVEL_4; + protected _csmNeedUpdate = false; + protected _csmLayerLambda = 0.75; + protected _csmOptimizationMode = CSMOptimizationMode.DisableRotationFix; // fixed area properties protected _shadowFixedArea = false; @@ -54,6 +63,10 @@ export class DirectionalLight extends Light { protected _shadowFar = 10.0; protected _shadowOrthoSize = 5; + /** + * @en The direction vector of the light + * @zh 光源的方向 + */ set direction (dir: Vec3) { Vec3.normalize(this._dir, dir); } @@ -62,7 +75,10 @@ export class DirectionalLight extends Light { return this._dir; } - // in Lux(lx) + /** + * @en The illuminance of the light in Lux(lx) + * @zh 光源的辐照度,单位是 Lux(lx) + */ get illuminance (): number { const isHDR = (legacyCC.director.root).pipeline.pipelineSceneData.isHDR; if (isHDR) { @@ -80,6 +96,10 @@ export class DirectionalLight extends Light { } } + /** + * @en The illuminance of the light in HDR mode + * @zh HDR 模式下光源的辐照度 + */ get illuminanceHDR () { return this._illuminanceHDR; } @@ -87,6 +107,10 @@ export class DirectionalLight extends Light { this._illuminanceHDR = value; } + /** + * @en The illuminance of the light in LDR mode + * @zh LDR 模式下光源的辐照度 + */ get illuminanceLDR () { return this._illuminanceLDR; } @@ -106,9 +130,9 @@ export class DirectionalLight extends Light { } /** - * @en get or set shadow pcf. - * @zh 获取或者设置阴影pcf等级。 - */ + * @en get or set shadow pcf. + * @zh 获取或者设置阴影pcf等级。 + */ get shadowPcf () { return this._shadowPcf; } @@ -117,9 +141,9 @@ export class DirectionalLight extends Light { } /** - * @en get or set shadow map sampler offset - * @zh 获取或者设置阴影纹理偏移值 - */ + * @en get or set shadow map sampler offset + * @zh 获取或者设置阴影纹理偏移值 + */ get shadowBias () { return this._shadowBias; } @@ -128,9 +152,9 @@ export class DirectionalLight extends Light { } /** - * @en get or set normal bias. - * @zh 设置或者获取法线偏移。 - */ + * @en get or set normal bias. + * @zh 设置或者获取法线偏移。 + */ get shadowNormalBias () { return this._shadowNormalBias; } @@ -139,9 +163,9 @@ export class DirectionalLight extends Light { } /** - * @en Shadow color saturation - * @zh 阴影颜色饱和度 - */ + * @en Shadow color saturation + * @zh 阴影颜色饱和度 + */ get shadowSaturation () { return this._shadowSaturation; } @@ -150,9 +174,9 @@ export class DirectionalLight extends Light { } /** - * @en get or set shadow camera far - * @zh 获取或者设置潜在阴影产生的范围 - */ + * @en get or set shadow camera far + * @zh 获取或者设置潜在阴影产生的范围 + */ get shadowDistance () { return this._shadowDistance; } @@ -161,8 +185,8 @@ export class DirectionalLight extends Light { } /** - * @en get or set shadow camera far - * @zh 获取或者设置潜在阴影产生的范围 + * @en get or set shadow camera far + * @zh 获取或者设置潜在阴影产生的范围 */ get shadowInvisibleOcclusionRange () { return this._shadowInvisibleOcclusionRange; @@ -172,9 +196,53 @@ export class DirectionalLight extends Light { } /** - * @en get or set fixed area shadow - * @zh 是否是固定区域阴影 - */ + * @en get or set shadow CSM level + * @zh 获取或者设置级联阴影层数 + */ + get csmLevel () { + return this._csmLevel; + } + set csmLevel (val) { + this._csmLevel = val; + } + + /** + * @en is CSM need update + * @zh 获取或者设置级联阴影是否需要更新 + */ + get csmNeedUpdate () { + return this._csmNeedUpdate; + } + set csmNeedUpdate (val) { + this._csmNeedUpdate = val; + } + + /** + * @en get or set shadow CSM level ratio + * @zh 获取或者设置级联阴影层数系数 + */ + get csmLayerLambda () { + return this._csmLayerLambda; + } + set csmLayerLambda (val) { + this._csmLayerLambda = val; + } + + /** + * @en get or set shadow CSM performance optimization mode + * @zh 获取或者设置级联阴影性能优化模式 + */ + get csmOptimizationMode () { + return this._csmOptimizationMode; + } + set csmOptimizationMode (val) { + this._csmOptimizationMode = val; + } + + /** + * @en get or set fixed area shadow + * @zh 是否是固定区域阴影 + */ get shadowFixedArea () { return this._shadowFixedArea; } @@ -183,9 +251,9 @@ export class DirectionalLight extends Light { } /** - * @en get or set shadow camera near - * @zh 获取或者设置阴影相机近裁剪面 - */ + * @en The near clip plane of the shadow camera + * @zh 获取或者设置阴影相机近裁剪面 + */ get shadowNear () { return this._shadowNear; } @@ -194,9 +262,9 @@ export class DirectionalLight extends Light { } /** - * @en get or set shadow camera far - * @zh 获取或者设置阴影相机远裁剪面 - */ + * @en The far clip plane of the shadow camera + * @zh 获取或者设置阴影相机远裁剪面 + */ get shadowFar () { return this._shadowFar; } @@ -205,9 +273,9 @@ export class DirectionalLight extends Light { } /** - * @en get or set shadow camera orthoSize - * @zh 获取或者设置阴影相机正交大小 - */ + * @en get or set shadow camera orthoSize + * @zh 获取或者设置阴影相机正交大小 + */ get shadowOrthoSize () { return this._shadowOrthoSize; } @@ -227,6 +295,10 @@ export class DirectionalLight extends Light { this.direction = new Vec3(1.0, -1.0, -1.0); } + /** + * @en Update the direction + * @zh 更新方向 + */ public update () { if (this._node && this._node.hasChangedFlags) { this.direction = Vec3.transformQuat(_v3, _forward, this._node.worldRotation); diff --git a/cocos/core/renderer/scene/fog.ts b/cocos/core/renderer/scene/fog.ts index 51670cda92..408c816fd9 100644 --- a/cocos/core/renderer/scene/fog.ts +++ b/cocos/core/renderer/scene/fog.ts @@ -76,6 +76,10 @@ export const FogType = Enum({ const FOG_TYPE_NONE = FogType.LAYERED + 1; +/** + * @en The fog representation in the render scene. + * @zh 渲染场景中的全局雾效配置 + */ export class Fog { /** * @zh 是否启用全局雾效 @@ -226,8 +230,10 @@ export class Fog { protected _fogAtten = 5; protected _fogTop = 1.5; protected _fogRange = 1.2; + protected _activated = false; public initialize (fogInfo : FogInfo) { + this._activated = false; this.fogColor = fogInfo.fogColor; this._enabled = fogInfo.enabled; this._type = this.enabled ? fogInfo.type : FOG_TYPE_NONE; @@ -242,6 +248,7 @@ export class Fog { public activate () { this._updatePipeline(); + this._activated = true; } protected _updatePipeline () { @@ -254,7 +261,9 @@ export class Fog { } pipeline.macros.CC_USE_FOG = value; pipeline.macros.CC_USE_ACCURATE_FOG = accurateValue; - root.onGlobalPipelineStateChanged(); + if (this._activated) { + root.onGlobalPipelineStateChanged(); + } } } diff --git a/cocos/core/renderer/scene/index.jsb.ts b/cocos/core/renderer/scene/index.jsb.ts index fa86f9c6d9..0244a815a6 100644 --- a/cocos/core/renderer/scene/index.jsb.ts +++ b/cocos/core/renderer/scene/index.jsb.ts @@ -23,6 +23,7 @@ THE SOFTWARE. */ import { legacyCC } from '../../global-exports'; +import { Vec3 } from '../../math'; import { Enum } from '../../value-types'; export type Ambient = jsb.Ambient; @@ -187,19 +188,101 @@ export const PCFType = Enum({ HARD: 0, /** - * @zh 软阴影 - * @en soft shadow + * @zh x4 次采样 + * @en x4 times * @readonly */ SOFT: 1, /** - * @zh 软阴影 - * @en soft shadow + * @zh x9 次采样 + * @en x9 times * @readonly */ SOFT_2X: 2, }); +export const CSMLevel = Enum({ + /** + * @zh 1 个层级 + * @en level 1 + * @readonly + */ + LEVEL_1: 1, + + /** + * @zh 2 个层级 + * @en level 2 + * @readonly + */ + LEVEL_2: 2, + + /** + * @zh 3 个层级 + * @en level 3 + * @readonly + */ + LEVEL_3: 3, + + /** + * @zh 4 个层级 + * @en level 4 + * @readonly + */ + LEVEL_4: 4, +}); +/** + * @zh 级联阴影性能优化模式。 + * @en The CSM performance optimization mode + * @enum Shadows.CSMOptimizationMode + */ + export const CSMOptimizationMode = Enum({ + /** + * @zh 没有性能优化 + * @en has no performance optimization + * @readonly + */ + NONE: 1, + + /** + * @zh 2 个层级 + * @en level 2 + * @readonly + */ + RemoveDuplicates: 2, + + /** + * @zh 3 个层级 + * @en level 3 + * @readonly + */ + DisableRotaitonFix: 3, +}); +export const EnvironmentLightingType = Enum({ + /** + * @zh + * 半球漫反射 + * @en + * hemisphere diffuse + * @readonly + */ + HEMISPHERE_DIFFUSE: 0, + /** + * @zh + * 半球漫反射和环境反射 + * @en + * hemisphere diffuse and Environment reflection + * @readonly + */ + AUTOGEN_HEMISPHERE_DIFFUSE_WITH_REFLECTION: 1, + /** + * @zh + * 漫反射卷积图和环境反射 + * @en + * diffuse convolution map and environment reflection + * @readonly + */ + DIFFUSEMAP_WITH_REFLECTION: 2, +}); export const ShadowsInfo = jsb.ShadowsInfo; export type ShadowsInfo = jsb.ShadowsInfo; export const Shadows = jsb.Shadow; @@ -211,7 +294,5 @@ export type Skybox = jsb.Skybox; legacyCC.Skybox = Skybox; export * from './model'; - -export * from './render-scene'; export * from './submodel'; export * from './camera'; diff --git a/cocos/core/renderer/scene/index.ts b/cocos/core/renderer/scene/index.ts index e30c1ef1ff..c488c1063d 100644 --- a/cocos/core/renderer/scene/index.ts +++ b/cocos/core/renderer/scene/index.ts @@ -23,16 +23,15 @@ THE SOFTWARE. */ -export * from './ambient'; -export * from './octree'; export * from './camera'; -export * from './deprecated'; -export * from './directional-light'; -export * from './light'; export * from './model'; -export * from './shadows'; -export * from './render-scene'; +export * from './submodel'; +export * from './ambient'; export * from './skybox'; +export * from './shadows'; +export * from './fog'; +export * from './octree'; +export * from './light'; +export * from './directional-light'; export * from './sphere-light'; export * from './spot-light'; -export * from './submodel'; diff --git a/cocos/core/renderer/scene/light.ts b/cocos/core/renderer/scene/light.ts index 01c31e8e21..a345172ab5 100644 --- a/cocos/core/renderer/scene/light.ts +++ b/cocos/core/renderer/scene/light.ts @@ -25,7 +25,7 @@ import { Vec3 } from '../../math'; import { TransformBit } from '../../scene-graph/node-enum'; -import { RenderScene } from './render-scene'; +import { RenderScene } from '../core/render-scene'; import { Node } from '../../scene-graph'; // Color temperature (in Kelvin) to RGB @@ -55,6 +55,10 @@ export function ColorTemperatureToRGB (rgb: Vec3, kelvin: number) { rgb.z = 0.0556434 * X + -0.2040259 + 1.0572252 * Z; } +/** + * @en The light type enumeration. + * @zh 光源类型枚举。 + */ export enum LightType { DIRECTIONAL, SPHERE, @@ -64,7 +68,15 @@ export enum LightType { export const nt2lm = (size: number) => 4 * Math.PI * Math.PI * size * size; +/** + * @en The abstract light class of the render scene + * @zh 渲染场景中的光源基类 + */ export class Light { + /** + * @en Whether it's a baked light source, baked light will be ignored in real time lighting pass + * @zh 是否是烘焙光源,烘焙光源会在实时光照计算中被忽略 + */ get baked () { return this._baked; } @@ -73,6 +85,10 @@ export class Light { this._baked = val; } + /** + * @en The color of the light + * @zh 光源的颜色 + */ set color (color: Vec3) { this._color.set(color); } @@ -81,6 +97,10 @@ export class Light { return this._color; } + /** + * @en Whether to use color temperature + * @zh 是否使用光源的色温 + */ set useColorTemperature (enable: boolean) { this._useColorTemperature = enable; } @@ -89,6 +109,10 @@ export class Light { return this._useColorTemperature; } + /** + * @en The color temperature of the light + * @zh 光源的色温 + */ set colorTemperature (val: number) { this._colorTemp = val; ColorTemperatureToRGB(this._colorTempRGB, this._colorTemp); @@ -98,6 +122,10 @@ export class Light { return this._colorTemp; } + /** + * @en The float RGB value of the color temperature, each channel is from 0 to 1 + * @zh 色温的浮点数颜色值,每个通道都是从 0 到 1 + */ get colorTemperatureRGB (): Vec3 { return this._colorTempRGB; } @@ -109,14 +137,26 @@ export class Light { } } + /** + * @en The node which owns the light source + * @zh 光源归属的节点 + */ get node () { return this._node; } + /** + * @en The type of the light source, e.g. directional light, spot light, etc + * @zh 光源的类型,比如方向光、聚光灯等 + */ get type () : LightType { return this._type; } + /** + * @en The name of the light source + * @zh 光源的名字 + */ get name () { return this._name; } @@ -125,6 +165,10 @@ export class Light { this._name = n; } + /** + * @en The render scene which owns the current light + * @zh 光源所属的渲染场景 + */ get scene () { return this._scene; } @@ -152,10 +196,19 @@ export class Light { this.colorTemperature = 6550.0; } + /** + * @en Attach the light to a render scene + * @zh 将光源挂载到渲染场景上 + * @param scene @en The render scene @zh 渲染场景 + */ public attachToScene (scene: RenderScene) { this._scene = scene; } + /** + * @en Detach the light from the render scene + * @zh 将光源从渲染场景上移除 + */ public detachFromScene () { this._scene = null; } diff --git a/cocos/core/renderer/scene/model.jsb.ts b/cocos/core/renderer/scene/model.jsb.ts index a6cb362a74..1b3c28552c 100644 --- a/cocos/core/renderer/scene/model.jsb.ts +++ b/cocos/core/renderer/scene/model.jsb.ts @@ -23,9 +23,8 @@ THE SOFTWARE. */ -import { Attribute } from '../../gfx'; +import { Attribute, deviceManager } from '../../gfx'; import { Vec3 } from '../../math'; -import { legacyCC } from '../../global-exports'; export interface IInstancedAttributeBlock { buffer: Uint8Array; @@ -47,7 +46,7 @@ export const Model = jsb.Model; const modelProto: any = Model.prototype; modelProto._ctor = function () { - this._device = legacyCC.director.root.device; + this._device = deviceManager.gfxDevice; }; const oldCreateBoundingShape = modelProto.createBoundingShape; diff --git a/cocos/core/renderer/scene/model.ts b/cocos/core/renderer/scene/model.ts index 587f18300b..def7906764 100644 --- a/cocos/core/renderer/scene/model.ts +++ b/cocos/core/renderer/scene/model.ts @@ -30,14 +30,14 @@ import { RenderingSubMesh } from '../../assets/rendering-sub-mesh'; import { AABB } from '../../geometry/aabb'; import { Node } from '../../scene-graph'; import { Layers } from '../../scene-graph/layers'; -import { RenderScene } from './render-scene'; +import { RenderScene } from '../core/render-scene'; import { Texture2D } from '../../assets/texture-2d'; import { SubModel } from './submodel'; import { Pass, IMacroPatch, BatchingSchemes } from '../core/pass'; import { legacyCC } from '../../global-exports'; import { Mat4, Vec3, Vec4 } from '../../math'; import { Attribute, DescriptorSet, Device, Buffer, BufferInfo, getTypedArrayConstructor, - BufferUsageBit, FormatInfos, MemoryUsageBit, Filter, Address, Feature, SamplerInfo } from '../../gfx'; + BufferUsageBit, FormatInfos, MemoryUsageBit, Filter, Address, Feature, SamplerInfo, deviceManager } from '../../gfx'; import { INST_MAT_WORLD, UBOLocal, UBOWorldBound, UNIFORM_LIGHTMAP_TEXTURE_BINDING } from '../../pipeline/define'; const m4_1 = new Mat4(); @@ -46,6 +46,10 @@ const shadowMapPatches: IMacroPatch[] = [ { name: 'CC_RECEIVE_SHADOW', value: true }, ]; +const lightMapPatches: IMacroPatch[] = [ + { name: 'CC_USE_LIGHTMAP', value: true }, +]; + export interface IInstancedAttributeBlock { buffer: Uint8Array; views: TypedArray[]; @@ -86,41 +90,86 @@ const lightmapSamplerWithMipHash = new SamplerInfo( ); /** - * A representation of a model + * @en A representation of a model instance + * The base model class, which is the core component of [[MeshRenderer]], + * adds its own Model to the rendered scene for rendering submissions when [[MeshRenderer]] is enabled. + * This type of object represents a rendering instance in a scene, and it can contain multiple sub models, + * each of which corresponds to a material. These sub models share the same location and form a complete object. + * Each sub model references a sub mesh resource, which provides vertex and index buffers for rendering. + * @zh 代表一个模型实例 + * 基础模型类,它是 [[MeshRenderer]] 的核心组成部分,在 [[MeshRenderer]] 启用时会将自己的 Model 添加到渲染场景中用于提交渲染。 + * 此类型对象代表一个场景中的渲染实例,它可以包含多个子模型,每个子模型对应一个材质。这些子模型共享同样的位置,组成一个完整的物体。 + * 每个子模型引用一个子网格资源,后者提供渲染所用的顶点与索引缓冲。 */ export class Model { + /** + * @en Sub models of the current model + * @zh 获取所有子模型 + */ get subModels () { return this._subModels; } + /** + * @en Whether the model is initialized + * @zh 是否初始化 + */ get inited (): boolean { return this._inited; } + /** + * @en The axis-aligned bounding box of the model in the world space + * @zh 获取世界空间包围盒 + */ get worldBounds () { return this._worldBounds!; } + /** + * @en The axis-aligned bounding box of the model in the model space + * @zh 获取模型空间包围盒 + */ get modelBounds () { return this._modelBounds; } + /** + * @en The ubo buffer of the model + * @zh 获取模型的 ubo 缓冲 + */ get localBuffer () { return this._localBuffer; } + /** + * @en The world bound ubo buffer + * @zh 获取世界包围盒 ubo 缓冲 + */ get worldBoundBuffer () { return this._worldBoundBuffer; } + /** + * @en The time stamp of last update + * @zh 获取上次更新时间戳 + */ get updateStamp () { return this._updateStamp; } + /** + * @en Whether GPU instancing is enabled for the current model + * @zh 是否开启实例化渲染 + */ get isInstancingEnabled () { return this._instMatWorldIdx >= 0; } + /** + * @en Model level shadow bias + * @zh 阴影偏移值 + */ get shadowBias () { return this._shadowBias; } @@ -129,6 +178,10 @@ export class Model { this._shadowBias = val; } + /** + * @en Model level shadow normal bias + * @zh 阴影法线偏移值 + */ get shadowNormalBias () { return this._shadowNormalBias; } @@ -137,6 +190,10 @@ export class Model { this._shadowNormalBias = val; } + /** + * @en Whether the model should receive shadow + * @zh 是否接收阴影 + */ get receiveShadow () { return this._receiveShadow; } @@ -146,6 +203,10 @@ export class Model { this.onMacroPatchesStateChanged(); } + /** + * @en Whether the model should cast shadow + * @zh 是否投射阴影 + */ get castShadow () { return this._castShadow; } @@ -154,6 +215,10 @@ export class Model { this._castShadow = val; } + /** + * @en The node to which the model belongs + * @zh 模型所在的节点 + */ get node () : Node { return this._node; } @@ -162,6 +227,10 @@ export class Model { this._node = n; } + /** + * @en Model's transform + * @zh 模型的变换 + */ get transform () : Node { return this._transform; } @@ -170,6 +239,13 @@ export class Model { this._transform = n; } + /** + * @en Model's visibility tag + * Model's visibility flags, it's different from [[Node.layer]], + * but it will also be compared with [[Camera.visibility]] during culling process. + * @zh 模型的可见性标志 + * 模型的可见性标志与 [[Node.layer]] 不同,它会在剔除阶段与 [[Camera.visibility]] 进行比较 + */ get visFlags () : number { return this._visFlags; } @@ -178,6 +254,10 @@ export class Model { this._visFlags = val; } + /** + * @en Whether the model is enabled in the render scene so that it will be rendered + * @zh 模型是否在渲染场景中启用并被渲染 + */ get enabled () : boolean { return this._enabled; } @@ -186,45 +266,189 @@ export class Model { this._enabled = val; } + /** + * @en Rendering priority in the transparent queue of model. + * @zh Model 在透明队列中的渲染排序优先级 + */ + get priority () : number { + return this._priority; + } + + set priority (val: number) { + this._priority = val; + } + + /** + * @en The type of the model + * @zh 模型类型 + */ public type = ModelType.DEFAULT; + + /** + * @en The render scene to which the model belongs + * @zh 模型所在的场景 + */ public scene: RenderScene | null = null; + + /** + * @en Whether dynamic batching is enabled for model + * @zh 是否动态合批 + */ public isDynamicBatching = false; + + /** + * @en The instance attributes + * @zh 实例化属性 + */ public instancedAttributes: IInstancedAttributeBlock = { buffer: null!, views: [], attributes: [] }; + /** + * @en The world axis-aligned bounding box + * @zh 世界空间包围盒 + */ protected _worldBounds: AABB | null = null; + + /** + * @en The model axis-aligned bounding box + * @zh 模型空间包围盒 + */ protected _modelBounds: AABB | null = null; + + /** + * @en Sub models + * @zh 子模型 + */ protected _subModels: SubModel[] = []; + + /** + * @en The node to which the model belongs + * @zh 模型所在的节点 + */ protected _node: Node = null!; + + /** + * @en Model's transform + * @zh 子模型的变换 + */ protected _transform: Node = null!; + /** + * @en Current gfx device + * @zh 当前 GFX 设备 + */ protected _device: Device; + + /** + * @en Whether the model is initialized + * @zh 是否初始化过 + */ protected _inited = false; + + /** + * @en Descriptor set count + * @zh 描述符集合个数 + */ protected _descriptorSetCount = 1; + + /** + * @en Time stamp for last update + * @zh 更新时间戳 + */ protected _updateStamp = -1; + + /** + * @en Local ubo data dirty flag + * @zh 本地 ubo 数据是否修改过 + */ protected _localDataUpdated = true; + /** + * @en Local ubo data + * @zh 本地 ubo 数据 + */ protected _localData = new Float32Array(UBOLocal.COUNT); + + /** + * @en Local ubo buffer + * @zh 本地 ubo 缓冲 + */ protected _localBuffer: Buffer | null = null; + + /** + * @en Instance matrix id + * @zh 实例矩阵索引 + */ private _instMatWorldIdx = -1; private _lightmap: Texture2D | null = null; private _lightmapUVParam: Vec4 = new Vec4(); + /** + * @en World AABB buffer + * @zh 世界空间包围盒缓冲 + */ protected _worldBoundBuffer: Buffer | null = null; + /** + * @en Whether the model should receive shadow + * @zh 是否接收阴影 + */ protected _receiveShadow = false; - protected _castShadow = false; - protected _shadowBias = 0; - protected _shadowNormalBias = 0; - protected _enabled = true; - protected _visFlags = Layers.Enum.NONE; /** - * Setup a default empty model + * @en Whether the model should cast shadow + * @zh 是否投射阴影 + */ + protected _castShadow = false; + + /** + * @en Shadow bias + * @zh 阴影偏移 + */ + protected _shadowBias = 0; + + /** + * @en Shadow normal bias + * @zh 阴影法线偏移 + */ + protected _shadowNormalBias = 0; + + /** + * @en Whether the model is enabled in the render scene so that it will be rendered + * @zh 模型是否在渲染场景中启用并被渲染 + */ + protected _enabled = true; + + /** + * @en The visibility flags + * @zh 可见性标志位 + */ + protected _visFlags = Layers.Enum.NONE; + + protected _priority = 0; + + /** + * @internal + * @en native object + * @zh 原生对象 + */ + + /** + * @internal + * @en return native object + * @zh 返回原生对象 + */ + /** + * @en Constructor to create an empty model + * @zh 创建一个空模型 */ constructor () { - this._device = legacyCC.director.root.device; + this._device = deviceManager.gfxDevice; } + /** + * @en Initialize the model + * @zh 初始化模型 + */ public initialize () { if (this._inited) { return; @@ -236,6 +460,10 @@ export class Model { this._inited = true; } + /** + * @en Destroy the model + * @zh 销毁模型 + */ public destroy () { const subModels = this._subModels; for (let i = 0; i < subModels.length; i++) { @@ -259,15 +487,29 @@ export class Model { this.isDynamicBatching = false; } + /** + * @en Attach the model to a [[renderer.RenderScene]] + * @zh 添加模型到渲染场景 [[renderer.RenderScene]] 中 + * @param scene destination scene + */ public attachToScene (scene: RenderScene) { this.scene = scene; this._localDataUpdated = true; } + /** + * @en Detach the model from its render scene + * @zh 移除场景中的模型 + */ public detachFromScene () { this.scene = null; } + /** + * @en Update the model's transform + * @zh 更新模型的变换 + * @param stamp time stamp + */ public updateTransform (stamp: number) { const node = this.transform; // @ts-expect-error TS2445 @@ -282,6 +524,10 @@ export class Model { } } + /** + * @en Update the model's world AABB + * @zh 更新模型的世界空间包围盒 + */ public updateWorldBound () { const node = this.transform; if (node !== null) { @@ -295,6 +541,11 @@ export class Model { } } + /** + * @en Update the model's ubo + * @zh 更新模型的 ubo + * @param stamp time stamp + */ public updateUBOs (stamp: number) { const subModels = this._subModels; for (let i = 0; i < subModels.length; i++) { @@ -321,9 +572,10 @@ export class Model { } /** - * Create the bounding shape of this model - * @param minPos the min position of the model - * @param maxPos the max position of the model + * @en Create the model's AABB + * @zh 创建模型的包围盒 + * @param minPos min position of the AABB + * @param maxPos max position of the AABB */ public createBoundingShape (minPos?: Vec3, maxPos?: Vec3) { if (!minPos || !maxPos) { return; } @@ -335,6 +587,13 @@ export class Model { return new SubModel(); } + /** + * @en Initialize a sub model with the sub mesh data and the material. + * @zh 用子网格数据和材质初始化一个子模型。 + * @param idx sub model's index + * @param subMeshData sub mesh + * @param mat sub material + */ public initSubModel (idx: number, subMeshData: RenderingSubMesh, mat: Material) { this.initialize(); @@ -355,17 +614,33 @@ export class Model { this._updateAttributesAndBinding(idx); } + /** + * @en Set material for a given sub model + * @zh 为指定的子模型设置材质 + * @param idx sub model's index + * @param subMesh sub mesh + */ public setSubModelMesh (idx: number, subMesh: RenderingSubMesh) { if (!this._subModels[idx]) { return; } this._subModels[idx].subMesh = subMesh; } + /** + * @en Set a sub material + * @zh 设置一个子材质 + * @param idx sub model's index + * @param mat sub material + */ public setSubModelMaterial (idx: number, mat: Material) { if (!this._subModels[idx]) { return; } this._subModels[idx].passes = mat.passes; this._updateAttributesAndBinding(idx); } + /** + * @en Pipeline changed callback + * @zh 管线更新回调 + */ public onGlobalPipelineStateChanged () { const subModels = this._subModels; for (let i = 0; i < subModels.length; i++) { @@ -373,6 +648,10 @@ export class Model { } } + /** + * @en Shader macro changed callback + * @zh Shader 宏更新回调 + */ public onMacroPatchesStateChanged () { const subModels = this._subModels; for (let i = 0; i < subModels.length; i++) { @@ -387,12 +666,31 @@ export class Model { } } + /** + * @internal + * If the model has lighting map + * initialize lighting map info before model initializing + * because the lighting map will influence the shader + */ + public initLightingmap (texture: Texture2D | null, uvParam: Vec4) { + this._lightmap = texture; + this._lightmapUVParam = uvParam; + } + + /** + * @en Update the light map info + * @zh 更新光照贴图信息 + * @param texture light map + * @param uvParam uv coordinate + */ public updateLightingmap (texture: Texture2D | null, uvParam: Vec4) { Vec4.toArray(this._localData, uvParam, UBOLocal.LIGHTINGMAP_UVPARAM); this._localDataUpdated = true; this._lightmap = texture; this._lightmapUVParam = uvParam; + this.onMacroPatchesStateChanged(); + if (texture === null) { texture = builtinResMgr.get('empty-texture'); } @@ -403,8 +701,6 @@ export class Model { const subModels = this._subModels; for (let i = 0; i < subModels.length; i++) { const { descriptorSet } = subModels[i]; - // TODO: should manage lightmap macro switches automatically - // USE_LIGHTMAP -> CC_USE_LIGHTMAP descriptorSet.bindTexture(UNIFORM_LIGHTMAP_TEXTURE_BINDING, gfxTexture); descriptorSet.bindSampler(UNIFORM_LIGHTMAP_TEXTURE_BINDING, sampler); descriptorSet.update(); @@ -412,6 +708,10 @@ export class Model { } } + /** + * @en Update the shadow bias + * @zh 更新阴影偏移 + */ public updateLocalShadowBias () { const sv = this._localData; sv[UBOLocal.LOCAL_SHADOW_BIAS + 0] = this._shadowBias; @@ -421,8 +721,17 @@ export class Model { this._localDataUpdated = true; } + /** + * @en Return shader's macro patches + * @zh 获取 shader 宏 + * @param subModelIndex sub model's index + */ public getMacroPatches (subModelIndex: number): IMacroPatch[] | null { - return this.receiveShadow ? shadowMapPatches : null; + let patches = this.receiveShadow ? shadowMapPatches : null; + if (this._lightmap != null) { + patches = patches ? patches.concat(lightMapPatches) : lightMapPatches; + } + return patches; } protected _updateAttributesAndBinding (subModelIndex: number) { @@ -433,7 +742,10 @@ export class Model { this._updateLocalDescriptors(subModelIndex, subModel.descriptorSet); this._initWorldBoundDescriptors(subModelIndex); - this._updateWorldBoundDescriptors(subModelIndex, subModel.worldBoundDescriptorSet); + + if (subModel.worldBoundDescriptorSet) { + this._updateWorldBoundDescriptors(subModelIndex, subModel.worldBoundDescriptorSet); + } const shader = subModel.passes[0].getShaderVariant(subModel.patches)!; this._updateInstancedAttributes(shader.attributes, subModel.passes[0]); diff --git a/cocos/core/renderer/scene/octree.ts b/cocos/core/renderer/scene/octree.ts index 65cb838427..4f67dd7970 100644 --- a/cocos/core/renderer/scene/octree.ts +++ b/cocos/core/renderer/scene/octree.ts @@ -26,9 +26,13 @@ import { Vec3 } from '../../math/vec3'; import { OctreeInfo } from '../../scene-graph/scene-globals'; +/** + * @en The octree culling configuration of the render scene + * @zh 渲染场景的八叉树剔除配置 + */ export class Octree { /** - * @en enable octree + * @en Whether octree culling is enabled in the render scene * @zh 是否开启八叉树加速剔除 */ set enabled (val: boolean) { @@ -39,7 +43,7 @@ export class Octree { } /** - * @en min pos of scene bounding box + * @en Minimum position of the scene's bounding box * @zh 场景包围盒最小值 */ get minPos (): Vec3 { @@ -50,7 +54,7 @@ export class Octree { } /** - * @en max pos of scene bounding box + * @en Maximum position of the scene's bounding box * @zh 场景包围盒最大值 */ get maxPos (): Vec3 { @@ -61,7 +65,7 @@ export class Octree { } /** - * @en depth of octree + * @en The depth of the octree * @zh 八叉树深度 */ get depth (): number { diff --git a/cocos/core/renderer/scene/shadows.ts b/cocos/core/renderer/scene/shadows.ts index 303b1c83bd..ec37aedbb4 100644 --- a/cocos/core/renderer/scene/shadows.ts +++ b/cocos/core/renderer/scene/shadows.ts @@ -28,7 +28,7 @@ import { Sphere } from '../../geometry'; import { Color, Mat4, Vec3, Vec2 } from '../../math'; import { legacyCC } from '../../global-exports'; import { Enum } from '../../value-types'; -import { ShadowsInfo } from '../../scene-graph/scene-globals'; +import type { ShadowsInfo } from '../../scene-graph/scene-globals'; import { IMacroPatch } from '../core/pass'; import { Shader } from '../../gfx'; @@ -106,22 +106,96 @@ export const PCFType = Enum({ HARD: 0, /** - * @zh 软阴影 - * @en soft shadow + * @zh x4 次采样 + * @en x4 times * @readonly */ SOFT: 1, /** - * @zh 软阴影 - * @en soft shadow + * @zh x9 次采样 + * @en x9 times * @readonly */ SOFT_2X: 2, + + /** + * @zh x16 次采样 + * @en x16 times + * @readonly + */ + SOFT_4X: 3, +}); + +/** + * @zh 级联阴影贴图层级。 + * @en The CSM shadow level + * @enum Shadows.CSMLevel + */ +export const CSMLevel = Enum({ + /** + * @zh 1 个层级 + * @en level 1 + * @readonly + */ + LEVEL_1: 1, + + /** + * @zh 2 个层级 + * @en level 2 + * @readonly + */ + LEVEL_2: 2, + + /** + * @zh 3 个层级 + * @en level 3 + * @readonly + */ + LEVEL_3: 3, + + /** + * @zh 4 个层级 + * @en level 4 + * @readonly + */ + LEVEL_4: 4, +}); + +/** + * @zh 级联阴影性能优化模式。 + * @en The CSM performance optimization mode + * @enum Shadows.CSMOptimizationMode + */ +export const CSMOptimizationMode = Enum({ + /** + * @zh 没有性能优化 + * @en has no performance optimization + * @readonly + */ + NONE: 1, + + /** + * @zh 剔除层与层之间重复物体 + * @en Eliminate duplicate objects between layers + * @readonly + */ + RemoveDuplicates: 2, + + /** + * @zh 取消稳抖 + * @en Disable rotation fix + * @readonly + */ + DisableRotationFix: 3, }); const SHADOW_TYPE_NONE = ShadowType.ShadowMap + 1; +/** + * @en The global shadow's configuration of the render scene + * @zh 渲染场景的全局阴影配置 + */ export class Shadows { /** * @en MAX_FAR. This is shadow camera max far. @@ -218,6 +292,10 @@ export class Shadows { this._shadowMapDirty = val; } + /** + * @en The transform matrix of the light source + * @zh 光源的变换矩阵 + */ public get matLight () { return this._matLight; } @@ -243,10 +321,6 @@ export class Shadows { public maxReceived = 4; // local set - public shadowCameraFar = 0; - public matShadowView = new Mat4(); - public matShadowProj = new Mat4(); - public matShadowViewProj = new Mat4(); protected _matLight = new Mat4(); protected _material: Material | null = null; protected _instancingMaterial: Material | null = null; @@ -257,22 +331,34 @@ export class Shadows { protected _distance = 0; protected _normal = new Vec3(0, 1, 0); protected _shadowColor = new Color(0, 0, 0, 76); - protected _size: Vec2 = new Vec2(512, 512); + protected _size: Vec2 = new Vec2(1024, 1024); protected _shadowMapDirty = false; + /** + * @en Get the shader for the planar shadow with macro patches + * @zh 通过指定宏获取平面阴影的 Shader 对象 + * @param patches The macro patches for the shader + * @returns The shader for the planar shadow + */ public getPlanarShader (patches: IMacroPatch[] | null): Shader | null { if (!this._material) { this._material = new Material(); - this._material.initialize({ effectName: 'planar-shadow' }); + this._material.initialize({ effectName: 'pipeline/planar-shadow' }); } return this._material.passes[0].getShaderVariant(patches); } + /** + * @en Get the shader which support instancing draw for the planar shadow with macro patches + * @zh 通过指定宏获取支持实例化渲染的平面阴影的 Shader 对象 + * @param patches The macro patches for the shader + * @returns The shader for the planar shadow + */ public getPlanarInstanceShader (patches: IMacroPatch[] | null): Shader | null { if (!this._instancingMaterial) { this._instancingMaterial = new Material(); - this._instancingMaterial.initialize({ effectName: 'planar-shadow', defines: { USE_INSTANCING: true } }); + this._instancingMaterial.initialize({ effectName: 'pipeline/planar-shadow', defines: { USE_INSTANCING: true } }); } return this._instancingMaterial.passes[0].getShaderVariant(patches); @@ -286,7 +372,10 @@ export class Shadows { this.distance = shadowsInfo.planeHeight; this.shadowColor = shadowsInfo.shadowColor; this.maxReceived = shadowsInfo.maxReceived; - this.size = shadowsInfo.size; + if (shadowsInfo.shadowMapSize !== this._size.x) { + this.size.set(shadowsInfo.shadowMapSize, shadowsInfo.shadowMapSize); + this._shadowMapDirty = true; + } } public activate () { @@ -300,11 +389,11 @@ export class Shadows { protected _updatePlanarInfo () { if (!this._material) { this._material = new Material(); - this._material.initialize({ effectName: 'planar-shadow' }); + this._material.initialize({ effectName: 'pipeline/planar-shadow' }); } if (!this._instancingMaterial) { this._instancingMaterial = new Material(); - this._instancingMaterial.initialize({ effectName: 'planar-shadow', defines: { USE_INSTANCING: true } }); + this._instancingMaterial.initialize({ effectName: 'pipeline/planar-shadow', defines: { USE_INSTANCING: true } }); } } diff --git a/cocos/core/renderer/scene/skybox.ts b/cocos/core/renderer/scene/skybox.ts index e409dec41a..cc684368da 100644 --- a/cocos/core/renderer/scene/skybox.ts +++ b/cocos/core/renderer/scene/skybox.ts @@ -31,10 +31,10 @@ import { UNIFORM_ENVIRONMENT_BINDING, UNIFORM_DIFFUSEMAP_BINDING } from '../../p import { MaterialInstance } from '../core/material-instance'; import { Model } from './model'; import { legacyCC } from '../../global-exports'; -import { SkyboxInfo } from '../../scene-graph/scene-globals'; +import type { SkyboxInfo } from '../../scene-graph/scene-globals'; import { Root } from '../../root'; import { GlobalDSManager } from '../../pipeline/global-descriptor-set-manager'; -import { Device } from '../../gfx'; +import { Device, deviceManager } from '../../gfx'; import { Enum } from '../../value-types'; let skybox_mesh: Mesh | null = null; @@ -67,7 +67,16 @@ export const EnvironmentLightingType = Enum({ DIFFUSEMAP_WITH_REFLECTION: 2, }); +/** + * @en The skybox configuration of the render scene, + * currently some rendering options like hdr and ibl lighting configuration is also here. + * @zh 渲染场景的天空盒配置,目前一些渲染配置,比如 HDR 模式和环境光照配置也在 Skybox 中。 + */ export class Skybox { + /** + * @en The Model object of the skybox + * @zh 天空盒的 Model 对象 + */ get model (): Model | null { return this._model; } @@ -84,8 +93,9 @@ export class Skybox { this._enabled = val; if (val) this.activate(); else this._updatePipeline(); } + /** - * @en HDR + * @en Whether HDR mode is enabled * @zh 是否启用HDR? */ get useHDR (): boolean { @@ -98,7 +108,7 @@ export class Skybox { } /** - * @en Whether use IBL + * @en Whether use image based lighting for PBR materials * @zh 是否启用IBL? */ get useIBL (): boolean { @@ -120,7 +130,7 @@ export class Skybox { set useDiffuseMap (val: boolean) { this._useDiffuseMap = val; - this.setDiffuseMaps(null, null); + this._updatePipeline(); } /** @@ -135,6 +145,18 @@ export class Skybox { } } + /** + * @en Whether to use offline baked convolutional maps + * @zh 是否使用离线烘焙的卷积图? + */ + get useConvolutionMap (): boolean { + if (this.envmap) { + return this.envmap.isUsingOfflineMipmaps(); + } else { + return false; + } + } + /** * @en The texture cube used for the skybox * @zh 使用的立方体贴图 @@ -178,6 +200,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 }); + } else { + this._editableMaterial = null; + } + this._updatePipeline(); + } protected _envmapLDR: TextureCube | null = null; protected _envmapHDR: TextureCube | null = null; protected _diffuseMapLDR: TextureCube | null = null; @@ -189,32 +220,37 @@ export class Skybox { protected _useIBL = false; protected _useHDR = true; protected _useDiffuseMap = false; + protected _editableMaterial: MaterialInstance | null = null; + protected _activated = false; public initialize (skyboxInfo: SkyboxInfo) { + this._activated = false; this._enabled = skyboxInfo.enabled; this._useIBL = skyboxInfo.useIBL; this._useDiffuseMap = skyboxInfo.applyDiffuseMap; this._useHDR = skyboxInfo.useHDR; } + /** + * @en Set the environment maps for HDR and LDR mode + * @zh 为 HDR 和 LDR 模式设置环境贴图 + * @param envmapHDR @en Environment map for HDR mode @zh HDR 模式下的环境贴图 + * @param envmapLDR @en Environment map for LDR mode @zh LDR 模式下的环境贴图 + */ public setEnvMaps (envmapHDR: TextureCube | null, envmapLDR: TextureCube | null) { this._envmapHDR = envmapHDR; this._envmapLDR = envmapLDR; - const root = legacyCC.director.root as Root; - const isHDR = root.pipeline.pipelineSceneData.isHDR; - if (isHDR) { - if (envmapHDR) { - root.pipeline.pipelineSceneData.ambient.mipmapCount = envmapHDR.mipmapLevel; - } - } else if (envmapLDR) { - root.pipeline.pipelineSceneData.ambient.mipmapCount = envmapLDR.mipmapLevel; - } - this._updateGlobalBinding(); this._updatePipeline(); } + /** + * @en Set the diffuse maps + * @zh 设置环境光漫反射贴图 + * @param diffuseMapHDR @en Diffuse map for HDR mode @zh HDR 模式下的漫反射贴图 + * @param diffuseMapLDR @en Diffuse map for LDR mode @zh LDR 模式下的漫反射贴图 + */ public setDiffuseMaps (diffuseMapHDR: TextureCube | null, diffuseMapLDR: TextureCube | null) { this._diffuseMapHDR = diffuseMapHDR; this._diffuseMapLDR = diffuseMapLDR; @@ -235,13 +271,15 @@ export class Skybox { this._model._initWorldBoundDescriptors = () => {}; } let isRGBE = this._default.isRGBE; + let isUseConvolutionMap = this._default.isUsingOfflineMipmaps(); if (this.envmap) { isRGBE = this.envmap.isRGBE; + isUseConvolutionMap = this.envmap.isUsingOfflineMipmaps(); } if (!skybox_material) { const mat = new Material(); - mat.initialize({ effectName: 'skybox', defines: { USE_RGBE_CUBEMAP: isRGBE } }); + mat.initialize({ effectName: 'pipeline/skybox', defines: { USE_RGBE_CUBEMAP: isRGBE } }); skybox_material = new MaterialInstance({ parent: mat }); } @@ -249,7 +287,11 @@ export class Skybox { if (!skybox_mesh) { skybox_mesh = legacyCC.utils.createMesh(legacyCC.primitives.box({ width: 2, height: 2, length: 2 })) as Mesh; } - this._model.initSubModel(0, skybox_mesh.renderingSubMeshes[0], skybox_material); + if (this._editableMaterial) { + this._model.initSubModel(0, skybox_mesh.renderingSubMeshes[0], this._editableMaterial); + } else { + this._model.initSubModel(0, skybox_mesh.renderingSubMeshes[0], skybox_material); + } } if (!this.envmap) { @@ -262,6 +304,8 @@ export class Skybox { this._updateGlobalBinding(); this._updatePipeline(); + + this._activated = true; } protected _updatePipeline () { @@ -271,29 +315,42 @@ export class Skybox { const useIBLValue = this.useIBL ? (this.isRGBE ? 2 : 1) : 0; const useDiffuseMapValue = (this.useIBL && this.useDiffuseMap && this.diffuseMap) ? (this.isRGBE ? 2 : 1) : 0; const useHDRValue = this.useHDR; + const useConvMapValue = this.useConvolutionMap; if (pipeline.macros.CC_USE_IBL !== useIBLValue || pipeline.macros.CC_USE_DIFFUSEMAP !== useDiffuseMapValue - || pipeline.macros.CC_USE_HDR !== useHDRValue) { + || pipeline.macros.CC_USE_HDR !== useHDRValue + || pipeline.macros.CC_IBL_CONVOLUTED !== useConvMapValue) { pipeline.macros.CC_USE_IBL = useIBLValue; pipeline.macros.CC_USE_DIFFUSEMAP = useDiffuseMapValue; pipeline.macros.CC_USE_HDR = useHDRValue; + pipeline.macros.CC_IBL_CONVOLUTED = useConvMapValue; - root.onGlobalPipelineStateChanged(); + if (this._activated) { + root.onGlobalPipelineStateChanged(); + } } - if (this.enabled && skybox_material) { - skybox_material.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE }); + if (this.enabled) { + if (this._editableMaterial) { + this._editableMaterial.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE }); + } else if (skybox_material) { + skybox_material.recompileShaders({ USE_RGBE_CUBEMAP: this.isRGBE }); + } } if (this._model) { - this._model.setSubModelMaterial(0, skybox_material!); + if (this._editableMaterial) { + this._model.setSubModelMaterial(0, this._editableMaterial); + } else { + this._model.setSubModelMaterial(0, skybox_material!); + } } } protected _updateGlobalBinding () { if (this._globalDSManager) { - const device = legacyCC.director.root.device as Device; + const device = deviceManager.gfxDevice; const envmap = this.envmap ? this.envmap : this._default; if (envmap) { diff --git a/cocos/core/renderer/scene/sphere-light.ts b/cocos/core/renderer/scene/sphere-light.ts index 26f6230eed..f87ce08692 100644 --- a/cocos/core/renderer/scene/sphere-light.ts +++ b/cocos/core/renderer/scene/sphere-light.ts @@ -28,11 +28,24 @@ import { legacyCC } from '../../global-exports'; import { Vec3 } from '../../math'; import { Light, LightType, nt2lm } from './light'; +/** + * @en The sphere light representation in the render scene, it will light up a spherical area in the scene. + * It doesn't support shadow generation currently. + * @zh 渲染场景中的球面光抽象,可以照亮场景中的一个球形区域,目前还不支持生成阴影。 + */ export class SphereLight extends Light { + /** + * @en The world position of the light source + * @zh 光源中心点的世界坐标 + */ get position () { return this._pos; } + /** + * @en The size of the light source + * @zh 球面光源的尺寸 + */ set size (size: number) { this._size = size; } @@ -41,6 +54,10 @@ export class SphereLight extends Light { return this._size; } + /** + * @en The lighting range of the light source + * @zh 球面光源的光照范围 + */ set range (range: number) { this._range = range; @@ -51,6 +68,10 @@ export class SphereLight extends Light { return this._range; } + /** + * @en The luminance of the light source + * @zh 光源的亮度 + */ get luminance (): number { const isHDR = (legacyCC.director.root).pipeline.pipelineSceneData.isHDR; if (isHDR) { @@ -68,6 +89,10 @@ export class SphereLight extends Light { } } + /** + * @en The luminance of the light source in HDR mode + * @zh HDR 模式下光源的亮度 + */ get luminanceHDR () { return this._luminanceHDR; } @@ -75,10 +100,18 @@ export class SphereLight extends Light { this._luminanceHDR = value; } + /** + * @en The luminance of the light source in LDR mode + * @zh LDR 模式下光源的亮度 + */ set luminanceLDR (value: number) { this._luminanceLDR = value; } + /** + * @en The AABB bounding box of the lighting area + * @zh 受光源影响范围的 AABB 包围盒 + */ get aabb () { return this._aabb; } @@ -108,6 +141,10 @@ export class SphereLight extends Light { this.luminanceLDR = 1.0; } + /** + * @en Update the lighting area + * @zh 更新光源影响范围 + */ public update () { if (this._node && (this._node.hasChangedFlags || this._needUpdate)) { this._node.getWorldPosition(this._pos); diff --git a/cocos/core/renderer/scene/spot-light.ts b/cocos/core/renderer/scene/spot-light.ts index 1ff2100037..ca1fbe3501 100644 --- a/cocos/core/renderer/scene/spot-light.ts +++ b/cocos/core/renderer/scene/spot-light.ts @@ -36,15 +36,15 @@ const _matProj = new Mat4(); const _matViewProj = new Mat4(); const _matViewProjInv = new Mat4(); +/** + * @en The spot light representation in the render scene, it will light up a cone area in the direction of the light, it supports shadow generation. + * @zh 渲染场景中的聚光灯抽象,可以照亮光源方向上的一个锥形区域,支持生成阴影。 + */ export class SpotLight extends Light { protected _dir: Vec3 = new Vec3(1.0, -1.0, -1.0); protected _range = 5.0; - /** - * @en Cached uniform variables. - * @zh 缓存下来的 uniform 变量。 - */ protected _spotAngle: number = Math.cos(Math.PI / 6); protected _pos: Vec3; @@ -67,18 +67,24 @@ export class SpotLight extends Light { protected _luminanceLDR = 0; - protected _aspect = 0; - // Shadow map properties protected _shadowEnabled = false; protected _shadowPcf = PCFType.HARD; protected _shadowBias = 0.00001; protected _shadowNormalBias = 0.0; + /** + * @en The world position of the light source + * @zh 光源的世界坐标 + */ get position () { return this._pos; } + /** + * @en The size of the spot light source + * @zh 聚光灯的光源尺寸 + */ set size (size: number) { this._size = size; } @@ -87,6 +93,10 @@ export class SpotLight extends Light { return this._size; } + /** + * @en The lighting range of the spot light + * @zh 聚光灯的光照范围 + */ set range (range: number) { this._range = range; @@ -97,6 +107,10 @@ export class SpotLight extends Light { return this._range; } + /** + * @en The luminance of the light source + * @zh 光源的亮度 + */ get luminance (): number { const isHDR = (legacyCC.director.root).pipeline.pipelineSceneData.isHDR; if (isHDR) { @@ -114,6 +128,10 @@ export class SpotLight extends Light { } } + /** + * @en The luminance of the light source in HDR mode + * @zh HDR 模式下光源的亮度 + */ get luminanceHDR () { return this._luminanceHDR; } @@ -121,6 +139,10 @@ export class SpotLight extends Light { this._luminanceHDR = value; } + /** + * @en The luminance of the light source in LDR mode + * @zh LDR 模式下光源的亮度 + */ get luminanceLDR () { return this._luminanceLDR; } @@ -128,16 +150,25 @@ export class SpotLight extends Light { this._luminanceLDR = value; } + /** + * @en The direction of the spot light + * @zh 聚光灯的照明方向 + */ get direction (): Vec3 { return this._dir; } - // 获取 cache 下来的 cos(angle / 2) 属性值,uniform 里需要 + /** + * @en The setter will take the value as the cone angle, + * but the getter will give you the cosine value of the half cone angle: `cos(angle / 2)`. + * As the in-consistence is not acceptable for a property, please do not use it. + * @zh 赋值时这个属性会把输入值当做聚光灯光照区域的锥角,但是获取时返回的是 cos(angle / 2)。 + * 由于这种不一致性,请不要使用这个属性。 + * @internal + */ get spotAngle () { return this._spotAngle; } - - // 设置用户指定的全角弧度,同时计算 cache 下来的 cos(angle / 2) 属性值,uniform 里需要。 set spotAngle (val: number) { this._angle = val; this._spotAngle = Math.cos(val * 0.5); @@ -145,30 +176,28 @@ export class SpotLight extends Light { this._needUpdate = true; } + /** + * @en The cone angle of the lighting area + * @zh 聚光灯锥角 + */ get angle () { return this._angle; } - set aspect (val: number) { - this._aspect = val; - - this._needUpdate = true; - } - - get aspect (): number { - return this._aspect; - } - get aabb () { return this._aabb; } + /** + * @en The frustum of the lighting area + * @zh 受光源影响范围的截椎体 + */ get frustum () { return this._frustum; } /** - * @en Whether activate shadow + * @en Whether shadow casting is enabled * @zh 是否启用阴影? */ get shadowEnabled () { @@ -179,9 +208,9 @@ export class SpotLight extends Light { } /** - * @en get or set shadow pcf. - * @zh 获取或者设置阴影pcf等级。 - */ + * @en The pcf level of the shadow generation. + * @zh 获取或者设置阴影 pcf 等级。 + */ get shadowPcf () { return this._shadowPcf; } @@ -190,9 +219,9 @@ export class SpotLight extends Light { } /** - * @en get or set shadow map sampler offset - * @zh 获取或者设置阴影纹理偏移值 - */ + * @en The depth offset of shadow to avoid moire pattern artifacts + * @zh 阴影的深度偏移, 可以减弱跨像素导致的条纹状失真 + */ get shadowBias () { return this._shadowBias; } @@ -201,7 +230,7 @@ export class SpotLight extends Light { } /** - * @en get or set normal bias. + * @en The normal bias of the shadow map. * @zh 设置或者获取法线偏移。 */ get shadowNormalBias () { @@ -224,7 +253,6 @@ export class SpotLight extends Light { const size = 0.15; this.size = size; - this.aspect = 1.0; this.luminanceHDR = 1700 / nt2lm(size); this.luminanceLDR = 1.0; this.range = Math.cos(Math.PI / 6); diff --git a/cocos/core/renderer/scene/submodel.ts b/cocos/core/renderer/scene/submodel.ts index 3a0f3bd2f8..2513081cd1 100644 --- a/cocos/core/renderer/scene/submodel.ts +++ b/cocos/core/renderer/scene/submodel.ts @@ -27,7 +27,7 @@ import { RenderingSubMesh } from '../../assets/rendering-sub-mesh'; import { RenderPriority, UNIFORM_REFLECTION_TEXTURE_BINDING, UNIFORM_REFLECTION_STORAGE_BINDING } from '../../pipeline/define'; import { BatchingSchemes, IMacroPatch, Pass } from '../core/pass'; import { DescriptorSet, DescriptorSetInfo, Device, InputAssembler, Texture, TextureType, TextureUsageBit, TextureInfo, - Format, Sampler, Filter, Address, Shader, SamplerInfo } from '../../gfx'; + Format, Sampler, Filter, Address, Shader, SamplerInfo, deviceManager } from '../../gfx'; import { legacyCC } from '../../global-exports'; import { errorID } from '../../platform/debug'; import { getPhaseID } from '../../pipeline/pass-phase'; @@ -35,6 +35,13 @@ import { Root } from '../../root'; const _dsInfo = new DescriptorSetInfo(null!); const MAX_PASS_COUNT = 8; + +/** + * @en A sub part of the model, it describes how to render a specific sub mesh. + * It contains geometry information in [[RenderingSubMesh]] and all sort of rendering configuration like shaders, macro patches, passes etc. + * @zh 组成模型对象的子模型,它用来描述如何渲染模型的一个子网格。 + * 它包含 [[RenderingSubMesh]] 代表的几何网格信息和所有渲染需要的数据,比如着色器程序,着色器宏定义,渲染 pass,等。 + */ export class SubModel { protected _device: Device | null = null; protected _passes: Pass[] | null = null; @@ -50,6 +57,17 @@ export class SubModel { protected _reflectionTex: Texture | null = null; protected _reflectionSampler: Sampler | null = null; + /** + * @en + * sub model's passes + * @zh + * 子模型的 passes + * @param passes @en The passes @zh 设置的 passes + */ + /** + * @en Render passes for the sub-model + * @zh 子模型的渲染 pass + */ set passes (passes) { const passLengh = passes.length; if (passLengh > MAX_PASS_COUNT) { @@ -74,10 +92,18 @@ export class SubModel { return this._passes!; } + /** + * @en Shaders for the sub-model, each shader corresponds to one of the [[passes]] + * @zh 子模型的着色器程序列表,每个着色器程序对应其中一个渲染 [[passes]] + */ get shaders (): Shader[] { return this._shaders!; } + /** + * @en The rendering sub mesh for the sub-model, each sub-model can only have one sub mesh. + * @zh 用于渲染的子网格对象,每个子模型只能包含一个子网格。 + */ set subMesh (subMesh) { this._inputAssembler!.destroy(); this._inputAssembler!.initialize(subMesh.iaInfo); @@ -89,6 +115,10 @@ export class SubModel { return this._subMesh!; } + /** + * @en The rendering priority of the sub-model + * @zh 子模型的渲染优先级 + */ set priority (val) { this._priority = val; } @@ -97,43 +127,79 @@ export class SubModel { return this._priority; } + /** + * @en The low level input assembler which contains geometry data + * @zh 底层渲染用的输入汇集器,包含几何信息 + */ get inputAssembler (): InputAssembler { return this._inputAssembler!; } + /** + * @en The descriptor set used for sub-model rendering + * @zh 底层渲染子模型用的描述符集组 + */ get descriptorSet (): DescriptorSet { return this._descriptorSet!; } - get worldBoundDescriptorSet (): DescriptorSet { - return this._worldBoundDescriptorSet!; + /** + * @en The descriptor set for world bound + * @zh 用于存储世界包围盒的描述符集组 + */ + get worldBoundDescriptorSet (): DescriptorSet | null { + return this._worldBoundDescriptorSet; } + /** + * @en The macro patches for the shaders + * @zh 着色器程序所用的宏定义组合 + */ get patches (): IMacroPatch[] | null { return this._patches; } + /** + * @en The shader for rendering the planar shadow, instancing draw version. + * @zh 用于渲染平面阴影的着色器,适用于实例化渲染(instancing draw) + */ get planarInstanceShader (): Shader | null { return this._planarInstanceShader; } + /** + * @en The shader for rendering the planar shadow. + * @zh 用于渲染平面阴影的着色器。 + */ get planarShader (): Shader | null { return this._planarShader; } + /** + * @en + * init sub model + * @zh + * 子模型初始化 + * @param subMesh @en The sub mesh @zh 子网格资源 + * @param passes @en The passes @zh 渲染的 passes + * @param patches @en The shader's macro @zh 着色器的宏定义 + */ public initialize (subMesh: RenderingSubMesh, passes: Pass[], patches: IMacroPatch[] | null = null): void { const root = legacyCC.director.root as Root; - this._device = root.device; + this._device = deviceManager.gfxDevice; _dsInfo.layout = passes[0].localSetLayout; this._inputAssembler = this._device.createInputAssembler(subMesh.iaInfo); this._descriptorSet = this._device.createDescriptorSet(_dsInfo); const pipeline = (legacyCC.director.root as Root).pipeline; - const occlusionPass = pipeline.pipelineSceneData.getOcclusionQueryPass()!; - const occlusionDSInfo = new DescriptorSetInfo(null!); - occlusionDSInfo.layout = occlusionPass.localSetLayout; - this._worldBoundDescriptorSet = this._device.createDescriptorSet(occlusionDSInfo); + const occlusionPass = pipeline.pipelineSceneData.getOcclusionQueryPass(); + if (occlusionPass) { + const occlusionDSInfo = new DescriptorSetInfo(null!); + occlusionDSInfo.layout = occlusionPass.localSetLayout; + this._worldBoundDescriptorSet = this._device.createDescriptorSet(occlusionDSInfo); + } + this._subMesh = subMesh; this._patches = patches; this._passes = passes; @@ -182,22 +248,39 @@ export class SubModel { } } - // This is a temporary solution - // It should not be written in a fixed way, or modified by the user + /** + * @en + * init planar shadow's shader + * @zh + * 平面阴影着色器初始化 + */ public initPlanarShadowShader () { const pipeline = (legacyCC.director.root as Root).pipeline; const shadowInfo = pipeline.pipelineSceneData.shadows; this._planarShader = shadowInfo.getPlanarShader(this._patches); } - // This is a temporary solution - // It should not be written in a fixed way, or modified by the user + /** + * @en + * init planar shadow's instance shader + * @zh + * 平面阴影实例着色器初始化 + */ + /** + * @internal + */ public initPlanarShadowInstanceShader () { const pipeline = (legacyCC.director.root as Root).pipeline; const shadowInfo = pipeline.pipelineSceneData.shadows; this._planarInstanceShader = shadowInfo.getPlanarInstanceShader(this._patches); } + /** + * @en + * destroy sub model + * @zh + * 销毁子模型 + */ public destroy (): void { this._descriptorSet!.destroy(); this._descriptorSet = null; @@ -205,7 +288,7 @@ export class SubModel { this._inputAssembler!.destroy(); this._inputAssembler = null; - this._worldBoundDescriptorSet!.destroy(); + this._worldBoundDescriptorSet?.destroy(); this._worldBoundDescriptorSet = null; this.priority = RenderPriority.DEFAULT; @@ -221,15 +304,25 @@ export class SubModel { this._reflectionSampler = null; } + /** + * @en + * update sub model + * @zh + * 更新子模型 + */ public update (): void { for (let i = 0; i < this._passes!.length; ++i) { const pass = this._passes![i]; pass.update(); } this._descriptorSet!.update(); - this._worldBoundDescriptorSet!.update(); + this._worldBoundDescriptorSet?.update(); } + /** + * @en Pipeline changed callback + * @zh 管线更新回调 + */ public onPipelineStateChanged (): void { const passes = this._passes; if (!passes) { return; } @@ -244,6 +337,10 @@ export class SubModel { this._flushPassInfo(); } + /** + * @en Shader macro changed callback + * @zh Shader 宏更新回调 + */ public onMacroPatchesStateChanged (patches: IMacroPatch[] | null): void { this._patches = patches; @@ -260,6 +357,12 @@ export class SubModel { this._flushPassInfo(); } + /** + * @en + * geometry changed callback + * @zh + * 几何数据改变后的回调 + */ public onGeometryChanged (): void { if (!this._subMesh) { return; diff --git a/cocos/core/renderer/utils.ts b/cocos/core/renderer/utils.ts index 364a77fdf0..4652bab06d 100644 --- a/cocos/core/renderer/utils.ts +++ b/cocos/core/renderer/utils.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { Attribute, Buffer, BufferInfo, Device, InputAssemblerInfo, AttributeName, BufferUsageBit, Format, MemoryUsageBit } from '../gfx'; import { IGeometry } from '../../primitive/define'; diff --git a/cocos/core/root.jsb.ts b/cocos/core/root.jsb.ts index 1c09b49bf5..af8290a8ec 100644 --- a/cocos/core/root.jsb.ts +++ b/cocos/core/root.jsb.ts @@ -1,9 +1,10 @@ import { Pool } from './memop'; -import { warnID } from './platform'; -import { Batcher2D } from '../2d/renderer/batcher-2d'; +import { warnID } from './platform/debug'; import legacyCC from '../../predefine'; import { DataPoolManager } from '../3d/skeletal-animation/data-pool-manager'; -import { Device } from './gfx'; +import { Device, deviceManager } from './gfx'; +import { registerRebuildLayoutGraph } from './pipeline/custom/index.jsb'; +import { DebugView } from './pipeline/debug-view'; declare const nr: any; declare const jsb: any; @@ -27,10 +28,22 @@ export interface IRootInfo { const rootProto: any = Root.prototype; +rootProto._createBatcher2D = function () { + if (!this._batcher && legacyCC.internal.Batcher2D) { + this._batcher = new legacyCC.internal.Batcher2D(this); + if (!this._batcher!.initialize()) { + this._batcher = null; + this.destroy(); + return; + } + this._batcher._nativeObj = this.getBatcher2D(); + } +} + Object.defineProperty(rootProto, 'batcher2D', { configurable: true, enumerable: true, - get(): Batcher2D { + get() { return this._batcher; }, }); @@ -51,6 +64,14 @@ Object.defineProperty(rootProto, 'pipelineEvent', { } }); +Object.defineProperty(rootProto, 'debugView', { + configurable: true, + enumerable: true, + get () { + return this._debugView; + } +}); + class DummyPipelineEvent { on (type: any, callback: any, target?: any, once?: boolean) {} once (type: any, callback: any, target?: any) {} @@ -68,12 +89,14 @@ rootProto._ctor = function (device: Device) { this._lightPools = new Map(); this._batcher = null; this._pipelineEvent = new DummyPipelineEvent(); + this._debugView = new DebugView(); + this.setDebugViewConfig(this._debugView._nativeConfig); this._registerListeners(); }; rootProto.initialize = function (info: IRootInfo) { // TODO: - this._initialize(legacyCC.game._swapchain); + this._initialize(deviceManager.swapchain); }; rootProto.createModel = function (ModelCtor) { @@ -112,47 +135,46 @@ rootProto.createLight = function (LightCtor) { }; rootProto.destroyLight = function (l) { - const p = this._lightPools.get(l.constructor); + if (l.scene) { + switch (l.type) { + case LightType.DIRECTIONAL: + l.scene.removeDirectionalLight(l); + break; + case LightType.SPHERE: + l.scene.removeSphereLight(l); + break; + case LightType.SPOT: + l.scene.removeSpotLight(l); + break; + default: + break; + } + } l.destroy(); +}; + +rootProto.recycleLight = function (l) { + const p = this._lightPools.get(l.constructor); if (p) { p.free(l); if (l.scene) { switch (l.type) { - case LightType.SPHERE: - l.scene.removeSphereLight(l); - break; - case LightType.SPOT: - l.scene.removeSpotLight(l); - break; - default: - break; + case LightType.DIRECTIONAL: + l.scene.removeDirectionalLight(l); + break; + case LightType.SPHERE: + l.scene.removeSphereLight(l); + break; + case LightType.SPOT: + l.scene.removeSpotLight(l); + break; + default: + break; } } } }; -rootProto._onBatch2DInit = function () { - if (!this._batcher && legacyCC.internal.Batcher2D) { - this._batcher = new legacyCC.internal.Batcher2D(this); - if (!this._batcher!.initialize()) { - this.destroy(); - return false; - } - } -}; - -rootProto._onBatch2DUpdate = function () { - if (this._batcher) this._batcher.update(); -}; - -rootProto._onBatch2DUploadBuffers = function () { - if (this._batcher) this._batcher.uploadBuffers(); -}; - -rootProto._onBatch2DReset = function () { - if (this._batcher) this._batcher.reset(); -}; - rootProto._onDirectorBeforeCommit = function () { legacyCC.director.emit(legacyCC.Director.EVENT_BEFORE_COMMIT); }; @@ -164,14 +186,20 @@ rootProto.frameMove = function (deltaTime: number) { const oldSetPipeline = rootProto.setRenderPipeline; rootProto.setRenderPipeline = function (pipeline) { - if (this.usesCustomPipeline()) { - return oldSetPipeline.call(this, null); + let ppl; + if (this.usesCustomPipeline) { + ppl = oldSetPipeline.call(this, null); + registerRebuildLayoutGraph(); + } else { if (!pipeline) { // pipeline should not be created in C++, ._ctor need to be triggered pipeline = new nr.ForwardPipeline(); pipeline.init(); } - return oldSetPipeline.call(this, pipeline); + ppl = oldSetPipeline.call(this, pipeline); } + + this._createBatcher2D(); + return ppl; } diff --git a/cocos/core/root.ts b/cocos/core/root.ts index ad0edc4b6d..2e82d53f87 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -23,69 +23,66 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ - -import { builtinResMgr } from './builtin'; import { Pool } from './memop'; import { RenderPipeline, createDefaultPipeline, DeferredPipeline } from './pipeline'; +import { DebugView } from './pipeline/debug-view'; import { Camera, Light, Model } from './renderer/scene'; import type { DataPoolManager } from '../3d/skeletal-animation/data-pool-manager'; import { LightType } from './renderer/scene/light'; -import { IRenderSceneInfo, RenderScene } from './renderer/scene/render-scene'; +import { IRenderSceneInfo, RenderScene } from './renderer/core/render-scene'; +import { DirectionalLight } from './renderer/scene/directional-light'; import { SphereLight } from './renderer/scene/sphere-light'; import { SpotLight } from './renderer/scene/spot-light'; import { legacyCC } from './global-exports'; import { RenderWindow, IRenderWindowInfo } from './renderer/core/render-window'; -import { ColorAttachment, DepthStencilAttachment, RenderPassInfo, StoreOp, Device, Swapchain, Feature } from './gfx'; -import { warnID } from './platform/debug'; +import { ColorAttachment, DepthStencilAttachment, RenderPassInfo, StoreOp, Device, Swapchain, Feature, deviceManager } from './gfx'; +import { warn, warnID } from './platform/debug'; import { Pipeline, PipelineRuntime } from './pipeline/custom/pipeline'; -import { createCustomPipeline } from './pipeline/custom'; import { Batcher2D } from '../2d/renderer/batcher-2d'; import { IPipelineEvent } from './pipeline/pipeline-event'; +import { settings, Settings } from './settings'; +import { localDescriptorSetLayout_ResizeMaxJoints } from './pipeline/define'; /** - * @zh - * Root描述信息 + * @en Initialization information for the Root + * @zh Root 初始化描述信息 */ export interface IRootInfo { enableHDR?: boolean; } /** - * @zh - * 场景描述信息 + * @en Creation information for the Root + * @zh 场景创建描述信息 */ export interface ISceneInfo { name: string; } /** - * @zh - * Root类 + * @en The root manager of the renderer which manages all device resources and the render pipeline. + * @zh 基础渲染器管理类,管理所有设备相关的资源创建以及渲染管线。 */ export class Root { /** - * @zh - * GFX 设备 + * @en The GFX device + * @zh GFX 设备 */ public get device (): Device { return this._device; } /** - * @zh - * 主窗口 + * @en The main window + * @zh 主窗口 */ public get mainWindow (): RenderWindow | null { return this._mainWindow; } /** - * @zh - * 当前窗口 + * @en The current active window + * @zh 当前激活的窗口 */ public set curWindow (window: RenderWindow | null) { this._curWindow = window; @@ -96,8 +93,9 @@ export class Root { } /** - * @zh - * 临时窗口(用于数据传输) + * @e The temporary window for data transmission + * @zh 临时窗口(用于数据传输) + * @internal */ public set tempWindow (window: RenderWindow | null) { this._tempWindow = window; @@ -108,8 +106,8 @@ export class Root { } /** - * @zh - * 窗口列表 + * @en The windows list + * @zh 窗口列表 */ public get windows (): RenderWindow[] { return this._windows; @@ -124,73 +122,88 @@ export class Root { } /** - * @zh - * 渲染管线 + * @en The render pipeline + * @zh 渲染管线 */ public get pipeline (): PipelineRuntime { return this._pipeline!; } /** - * @zh - * 渲染管线事件 + * @en The custom render pipeline + * @zh 自定义渲染管线 + */ + public get customPipeline (): Pipeline { + return this._customPipeline!; + } + + /** + * @en The pipeline events + * @zh 渲染管线事件 */ public get pipelineEvent (): IPipelineEvent { return this._pipelineEvent!; } /** - * @zh - * UI实例 - * 引擎内部使用,用户无需调用此接口 + * @en The draw batch manager for 2D UI, for engine internal usage, user do not need to use this. + * @zh 2D UI 渲染合批管理器,引擎内部使用,用户无需使用此接口 */ public get batcher2D (): Batcher2D { return this._batcher as Batcher2D; } /** - * @zh - * 场景列表 + * @en Render scenes list + * @zh 渲染场景列表 */ public get scenes (): RenderScene[] { return this._scenes; } /** - * @zh - * 累计时间(秒) + * @en The debug view manager for rendering + * @zh 渲染调试管理器 + */ + public get debugView (): DebugView { + return this._debugView; + } + + /** + * @en The time cumulated in seconds since the game began running. + * @zh 累计时间(秒)。 */ public get cumulativeTime (): number { return this._cumulativeTime; } /** - * @zh - * 帧时间(秒) + * @en The current frame time in seconds. + * @zh 帧时间(秒)。 */ public get frameTime (): number { return this._frameTime; } /** - * @zh - * 一秒内的累计帧数 + * @en The frame count during the last second + * @zh 一秒内的累计帧数 */ public get frameCount (): number { return this._frameCount; } /** - * @zh - * 每秒帧率 + * @en The recent frame rate for the last second + * @zh 当前每秒帧率 */ public get fps (): number { return this._fps; } /** - * @zh - * 每秒固定帧率 + * @en The wanted frame rate set by user + * @zh 每秒设定帧率 */ public set fixedFPS (fps: number) { if (fps > 0) { @@ -205,20 +218,27 @@ export class Root { return this._fixedFPS; } + /** + * @internal + */ public get dataPoolManager () { return this._dataPoolMgr; } - get useDeferredPipeline () : boolean { + /** + * @en Whether the built-in deferred pipeline is used. + * @zh 是否启用内置延迟渲染管线 + */ + public get useDeferredPipeline () : boolean { return this._useDeferredPipeline; } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _createSceneFun: (root: Root) => RenderScene = null!; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _createWindowFun: (root: Root) => RenderWindow = null!; @@ -238,6 +258,7 @@ export class Root { private _modelPools = new Map, Pool>(); private _cameraPool: Pool | null = null; private _lightPools = new Map, Pool>(); + private _debugView = new DebugView(); private _fpsTime = 0; private _frameCount = 0; private _fps = 0; @@ -249,8 +270,9 @@ export class Root { private declare _naitveObj: any; /** - * 构造函数 - * @param device GFX 设备 + * @en The constructor of the root, user shouldn't create the root instance, it's managed by the [[Director]]. + * @zh 构造函数,用户不应该自己创建任何 Root 对象,它是由 [[Director]] 管理的。 + * @param device GFX device */ constructor (device: Device) { this._device = device; @@ -263,12 +285,12 @@ export class Root { } /** - * @zh - * 初始化函数 - * @param info Root描述信息 + * @en The initialization function, user shouldn't initialize the root, it's managed by the [[Director]]. + * @zh 初始化函数,用户不应该自己初始化 Root,它是由 [[Director]] 管理的。 + * @param info Root initialization information */ public initialize (info: IRootInfo) { - const swapchain: Swapchain = legacyCC.game._swapchain; + const swapchain: Swapchain = deviceManager.swapchain; const colorAttachment = new ColorAttachment(); colorAttachment.format = swapchain.colorTexture.format; const depthStencilAttachment = new DepthStencilAttachment(); @@ -285,8 +307,15 @@ export class Root { swapchain, }); this._curWindow = this._mainWindow; + const customJointTextureLayouts = settings.querySettings(Settings.Category.ANIMATION, 'customJointTextureLayouts') || []; + this._dataPoolMgr?.jointTexturePool.registerCustomTextureLayouts(customJointTextureLayouts); + this._resizeMaxJointForDS(); } + /** + * @en Destroy the root, user shouldn't invoke this function, it will cause undefined behavior. + * @zh 销毁 Root,用户不应该调用此方法,会造成未知行为。 + */ public destroy () { this.destroyScenes(); @@ -307,10 +336,10 @@ export class Root { } /** - * @zh - * 重置大小 - * @param width 屏幕宽度 - * @param height 屏幕高度 + * @en Resize the on-screen render windows. + * @zh 重置在屏窗口的大小。 + * @param width The new width of the window. + * @param height The new height of the window. */ public resize (width: number, height: number) { for (const window of this._windows) { @@ -320,7 +349,13 @@ export class Root { } } - public setRenderPipeline (rppl: RenderPipeline): boolean { + /** + * @en Setup the render pipeline + * @zh 设置渲染管线 + * @param rppl The render pipeline + * @returns The setup is successful or not + */ + public setRenderPipeline (rppl?: RenderPipeline): boolean { //----------------------------------------------- // prepare classic pipeline //----------------------------------------------- @@ -344,14 +379,15 @@ export class Root { //----------------------------------------------- // choose pipeline //----------------------------------------------- - if (this.usesCustomPipeline) { - this._customPipeline = createCustomPipeline(); + if (this.usesCustomPipeline && legacyCC.internal.createCustomPipeline) { + this._customPipeline = legacyCC.internal.createCustomPipeline(); isCreateDefaultPipeline = true; this._pipeline = this._customPipeline!; } else { this._classicPipeline = rppl; this._pipeline = this._classicPipeline; this._pipelineEvent = this._classicPipeline; + this._usesCustomPipeline = false; } if (!this._pipeline.activate(this._mainWindow!.swapchain)) { @@ -386,6 +422,10 @@ export class Root { return true; } + /** + * @en Notify the pipeline and all scenes that the global pipeline state have been updated so that they can update their render data and states. + * @zh 通知渲染管线和所有场景全局管线状态已更新,需要更新自身状态。 + */ public onGlobalPipelineStateChanged () { for (let i = 0; i < this._scenes.length; i++) { this._scenes[i].onGlobalPipelineStateChanged(); @@ -395,26 +435,26 @@ export class Root { } /** - * @zh - * 激活指定窗口为当前窗口 - * @param window GFX 窗口 + * @en Active the render window as the [[curWindow]] + * @zh 激活指定窗口为当前窗口 [[curWindow]] + * @param window The render window to be activated */ public activeWindow (window: RenderWindow) { this._curWindow = window; } /** - * @zh - * 重置累计时间 + * @en Reset the time cumulated + * @zh 重置累计时间 */ public resetCumulativeTime () { this._cumulativeTime = 0; } /** - * @zh - * 每帧执行函数 - * @param deltaTime 间隔时间 + * @en The entry function of the render process for every frame. + * @zh 用于每帧执行渲染流程的入口函数 + * @param deltaTime @en The delta time since last update. @zh 距离上一帧间隔时间 */ public frameMove (deltaTime: number) { this._frameTime = deltaTime; @@ -450,7 +490,7 @@ export class Root { } if (this._pipeline && cameraList.length > 0) { - this._device.acquire([legacyCC.game._swapchain]); + this._device.acquire([deviceManager.swapchain]); const scenes = this._scenes; const stamp = legacyCC.director.getTotalFrames(); if (this._batcher) { @@ -464,6 +504,10 @@ export class Root { legacyCC.director.emit(legacyCC.Director.EVENT_BEFORE_COMMIT); cameraList.sort((a: Camera, b: Camera) => a.priority - b.priority); + + for (let i = 0; i < cameraList.length; ++i) { + cameraList[i].geometryRenderer?.update(); + } this._pipeline.render(cameraList); this._device.present(); } @@ -472,9 +516,9 @@ export class Root { } /** - * @zh - * 创建窗口 - * @param info GFX 窗口描述信息 + * @en Create a render window + * @zh 创建一个新的窗口 + * @param info @en The window creation information @zh 窗口描述信息 */ public createWindow (info: IRenderWindowInfo): RenderWindow | null { const window = this._createWindowFun(this); @@ -484,9 +528,9 @@ export class Root { } /** - * @zh - * 销毁指定的窗口 - * @param window GFX 窗口 + * @en Destroy a render window + * @zh 销毁指定的窗口 + * @param window The render window to be destroyed */ public destroyWindow (window: RenderWindow) { for (let i = 0; i < this._windows.length; ++i) { @@ -499,8 +543,8 @@ export class Root { } /** - * @zh - * 销毁全部窗口 + * @en Destroy all render windows + * @zh 销毁全部窗口 */ public destroyWindows () { for (const window of this._windows) { @@ -510,9 +554,9 @@ export class Root { } /** - * @zh - * 创建渲染场景 - * @param info 渲染场景描述信息 + * @en Create a render scene + * @zh 创建渲染场景 + * @param info @en The creation information for render scene @zh 渲染场景描述信息 */ public createScene (info: IRenderSceneInfo): RenderScene { const scene: RenderScene = this._createSceneFun(this); @@ -522,9 +566,9 @@ export class Root { } /** - * @zh - * 销毁指定的渲染场景 - * @param scene 渲染场景 + * @en Destroy the given render scene + * @zh 销毁指定的渲染场景 + * @param scene @en The render scene to be destroyed. @zh 要销毁的渲染场景 */ public destroyScene (scene: RenderScene) { for (let i = 0; i < this._scenes.length; ++i) { @@ -537,8 +581,8 @@ export class Root { } /** - * @zh - * 销毁全部场景 + * @en Destroy all render scenes. + * @zh 销毁全部场景。 */ public destroyScenes () { for (const scene of this._scenes) { @@ -547,6 +591,12 @@ export class Root { this._scenes.length = 0; } + /** + * @en Create a model + * @zh 创建模型 + * @param ModelCtor @en The class of the model @zh 模型的类 + * @returns The model created + */ public createModel (ModelCtor: typeof Model): T { let p = this._modelPools.get(ModelCtor); if (!p) { @@ -558,6 +608,11 @@ export class Root { return model; } + /** + * @en Destroy the given model + * @zh 销毁指定的模型 + * @param m @en The model to be destroyed @zh 要销毁的模型 + */ public destroyModel (m: Model) { const p = this._modelPools.get(m.constructor as Constructor); if (p) { @@ -571,10 +626,21 @@ export class Root { m.destroy(); } + /** + * @en Create a camera + * @zh 创建一个相机 + * @returns The camera created. + */ public createCamera (): Camera { return this._cameraPool!.alloc(); } + /** + * @en Create a light source + * @zh 创建光源 + * @param LightCtor @en The class of the light @zh 光源的类 + * @returns The light created + */ public createLight (LightCtor: new () => T): T { let l = this._lightPools.get(LightCtor); if (!l) { @@ -586,12 +652,44 @@ export class Root { return light; } + /** + * @en Destroy the given light + * @zh 销毁指定的光源 + * @param l @en The light to be destroyed @zh 要销毁的光源 + */ public destroyLight (l: Light) { + if (l.scene) { + switch (l.type) { + case LightType.DIRECTIONAL: + l.scene.removeDirectionalLight(l as DirectionalLight); + break; + case LightType.SPHERE: + l.scene.removeSphereLight(l as SphereLight); + break; + case LightType.SPOT: + l.scene.removeSpotLight(l as SpotLight); + break; + default: + break; + } + } + l.destroy(); + } + + /** + * @en recycle the given light to light object pool + * @zh 回收指定的光源到对象池 + * @param l @en The light to be recycled @zh 要回收的光源 + */ + public recycleLight (l: Light) { const p = this._lightPools.get(l.constructor as Constructor); if (p) { p.free(l); if (l.scene) { switch (l.type) { + case LightType.DIRECTIONAL: + l.scene.removeDirectionalLight(l as DirectionalLight); + break; case LightType.SPHERE: l.scene.removeSphereLight(l as SphereLight); break; @@ -603,7 +701,12 @@ export class Root { } } } - l.destroy(); + } + + private _resizeMaxJointForDS () { + let maxJoints = Math.floor((deviceManager.gfxDevice.capabilities.maxVertexUniformVectors - 38) / 3); + maxJoints = maxJoints < 256 ? maxJoints : 256; + localDescriptorSetLayout_ResizeMaxJoints(maxJoints); } } diff --git a/cocos/core/scene-graph/base-node-dev.ts b/cocos/core/scene-graph/base-node-dev.ts index bccb8ed588..0377b84386 100644 --- a/cocos/core/scene-graph/base-node-dev.ts +++ b/cocos/core/scene-graph/base-node-dev.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { EDITOR, DEV, TEST } from 'internal:constants'; import { CCObject } from '../data/object'; import * as js from '../utils/js'; diff --git a/cocos/core/scene-graph/base-node.jsb.ts b/cocos/core/scene-graph/base-node.jsb.ts index 8f627123f6..ef09eaa9ca 100644 --- a/cocos/core/scene-graph/base-node.jsb.ts +++ b/cocos/core/scene-graph/base-node.jsb.ts @@ -23,10 +23,8 @@ THE SOFTWARE. */ -import { ccclass, editable, serializable } from 'cc.decorator'; -import { property } from '../data/decorators/property'; +import { ccclass } from '../data/decorators'; import { legacyCC } from '../global-exports'; -import { _applyDecoratedDescriptor } from '../data/utils/decorator-jsb-utils'; import { baseNodePolyfill } from './base-node-dev'; const baseNodeProto: any = jsb.BaseNode.prototype; @@ -35,66 +33,6 @@ baseNodeProto.createNode = null!; export type BaseNode = jsb.BaseNode; export const BaseNode = jsb.BaseNode; -const clsDecorator = ccclass('cc.BaseNode'); - -// const _class2$u = BaseNode; -// -// _applyDecoratedDescriptor(_class2$u.prototype, '_persistNode', [property], Object.getOwnPropertyDescriptor(_class2$u.prototype, '_persistNode'), _class2$u.prototype); -// _applyDecoratedDescriptor(_class2$u.prototype, 'name', [editable], Object.getOwnPropertyDescriptor(_class2$u.prototype, 'name'), _class2$u.prototype); -// _applyDecoratedDescriptor(_class2$u.prototype, 'children', [editable], Object.getOwnPropertyDescriptor(_class2$u.prototype, 'children'), _class2$u.prototype); -// _applyDecoratedDescriptor(_class2$u.prototype, 'active', [editable], Object.getOwnPropertyDescriptor(_class2$u.prototype, 'active'), _class2$u.prototype); -// _applyDecoratedDescriptor(_class2$u.prototype, 'activeInHierarchy', [editable], Object.getOwnPropertyDescriptor(_class2$u.prototype, 'activeInHierarchy'), _class2$u.prototype); -// _applyDecoratedDescriptor(_class2$u.prototype, 'parent', [editable], Object.getOwnPropertyDescriptor(_class2$u.prototype, 'parent'), _class2$u.prototype); -// -// const _descriptor$o = _applyDecoratedDescriptor(_class2$u.prototype, '_parent', [serializable], { -// configurable: true, -// enumerable: true, -// writable: true, -// initializer: function initializer () { -// return null; -// }, -// }); -// const _descriptor2$h = _applyDecoratedDescriptor(_class2$u.prototype, '_children', [serializable], { -// configurable: true, -// enumerable: true, -// writable: true, -// initializer: function initializer () { -// return []; -// }, -// }); -// const _descriptor3$b = _applyDecoratedDescriptor(_class2$u.prototype, '_active', [serializable], { -// configurable: true, -// enumerable: true, -// writable: true, -// initializer: function initializer () { -// return true; -// }, -// }); -// const _descriptor4$9 = _applyDecoratedDescriptor(_class2$u.prototype, '_components', [serializable], { -// configurable: true, -// enumerable: true, -// writable: true, -// initializer: function initializer () { -// return []; -// }, -// }); -// const _descriptor5$6 = _applyDecoratedDescriptor(_class2$u.prototype, '_prefab', [serializable], { -// configurable: true, -// enumerable: true, -// writable: true, -// initializer: function initializer () { -// return null; -// }, -// }); -// -baseNodeProto._ctor = function () { -// // _initializerDefineProperty(_this, "_parent", _descriptor$o, _assertThisInitialized(_this)); -// // _initializerDefineProperty(_this, "_children", _descriptor2$h, _assertThisInitialized(_this)); -// // _initializerDefineProperty(_this, "_active", _descriptor3$b, _assertThisInitialized(_this)); -// // _initializerDefineProperty(_this, "_components", _descriptor4$9, _assertThisInitialized(_this)); -// // _initializerDefineProperty(_this, "_prefab", _descriptor5$6, _assertThisInitialized(_this)); -}; - -clsDecorator(BaseNode); baseNodePolyfill(BaseNode); -legacyCC._BaseNode = jsb.BaseNode; +legacyCC._BaseNode = BaseNode; +ccclass('cc.BaseNode')(BaseNode); \ No newline at end of file diff --git a/cocos/core/scene-graph/base-node.ts b/cocos/core/scene-graph/base-node.ts index 60011dc640..2627deaf18 100644 --- a/cocos/core/scene-graph/base-node.ts +++ b/cocos/core/scene-graph/base-node.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module scene-graph - */ - import { ccclass, editable, serializable } from 'cc.decorator'; import { DEV, DEBUG, EDITOR } from 'internal:constants'; import { Component } from '../components/component'; @@ -55,7 +50,7 @@ export const TRANSFORM_ON = 1 << 0; const idGenerator = new IdGenerator('Node'); -function getConstructor (typeOrClassName: string | Constructor): Constructor | null | undefined { +function getConstructor (typeOrClassName: string | Constructor | AbstractedConstructor): Constructor | AbstractedConstructor | null | undefined { if (!typeOrClassName) { errorID(3804); return null; @@ -95,7 +90,7 @@ export class BaseNode extends CCObject implements ISchedulable { * @zh 如果为true,则该节点是一个常驻节点,不会在场景转换期间被销毁。 * 如果为false,节点将在加载新场景时自动销毁。默认为 false。 * @default false - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @property get _persistNode (): boolean { @@ -142,8 +137,9 @@ export class BaseNode extends CCObject implements ISchedulable { * @readOnly */ @editable - get children () { - return this._children; + get children (): Node[] { + // @ts-expect-error force cast + return this._children as Node[]; } /** @@ -219,23 +215,34 @@ export class BaseNode extends CCObject implements ISchedulable { return this._eventProcessor; } + /** + * @internal + */ protected static idGenerator = idGenerator; - // For walk + /** + * for walk + * @internal + */ protected static _stacks: Array> = [[]]; + /** + * @internal + */ protected static _stackId = 0; /** * Call `_updateScene` of specified node. + * @internal * @param node The node. */ protected static _setScene (node: BaseNode) { node._updateScene(); } - protected static _findComponent (node: BaseNode, constructor: Constructor): T | null { - const cls = constructor as any; + protected static _findComponent (node: BaseNode, constructor: Constructor | AbstractedConstructor): T | null { + const cls = constructor; const comps = node._components; + // @ts-expect-error internal rtti property if (cls._sealed) { for (let i = 0; i < comps.length; ++i) { const comp = comps[i]; @@ -254,9 +261,10 @@ export class BaseNode extends CCObject implements ISchedulable { return null; } - protected static _findComponents (node: BaseNode, constructor: Constructor, components: Component[]) { - const cls = constructor as any; + protected static _findComponents (node: BaseNode, constructor: Constructor | AbstractedConstructor, components: Component[]) { + const cls = constructor; const comps = node._components; + // @ts-expect-error internal rtti property if (cls._sealed) { for (let i = 0; i < comps.length; ++i) { const comp = comps[i]; @@ -274,7 +282,7 @@ export class BaseNode extends CCObject implements ISchedulable { } } - protected static _findChildComponent (children: BaseNode[], constructor: Constructor): T | null { + protected static _findChildComponent (children: BaseNode[], constructor: Constructor | AbstractedConstructor): T | null { for (let i = 0; i < children.length; ++i) { const node = children[i]; let comp = BaseNode._findComponent(node, constructor); @@ -332,14 +340,18 @@ export class BaseNode extends CCObject implements ISchedulable { protected _siblingIndex = 0; /** + * @en * record scene's id when set this node as persist node - * @legacyPublic + * @zh + * 当设置节点为常驻节点时记录场景的 id + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _originalSceneId = ''; /** * Set `_scene` field of this node. * The derived `Scene` overrides this method to behavior differently. + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ protected _updateScene () { if (this._parent == null) { @@ -469,7 +481,7 @@ export class BaseNode extends CCObject implements ISchedulable { * @param uuid - The uuid to find the child node. * @return a Node whose uuid equals to the input parameter */ - public getChildByUuid (uuid: string) { + public getChildByUuid (uuid: string): Node | null { if (!uuid) { log('Invalid uuid'); return null; @@ -478,7 +490,8 @@ export class BaseNode extends CCObject implements ISchedulable { const locChildren = this._children; for (let i = 0, len = locChildren.length; i < len; i++) { if (locChildren[i]._id === uuid) { - return locChildren[i]; + // @ts-expect-error force cast + return locChildren[i] as Node; } } return null; @@ -494,7 +507,7 @@ export class BaseNode extends CCObject implements ISchedulable { * var child = node.getChildByName("Test Node"); * ``` */ - public getChildByName (name: string) { + public getChildByName (name: string): Node | null { if (!name) { log('Invalid name'); return null; @@ -503,7 +516,8 @@ export class BaseNode extends CCObject implements ISchedulable { const locChildren = this._children; for (let i = 0, len = locChildren.length; i < len; i++) { if (locChildren[i]._name === name) { - return locChildren[i]; + // @ts-expect-error force cast + return locChildren[i] as Node; } } return null; @@ -519,10 +533,10 @@ export class BaseNode extends CCObject implements ISchedulable { * var child = node.getChildByPath("subNode/Test Node"); * ``` */ - public getChildByPath (path: string) { + public getChildByPath (path: string): Node | null { const segments = path.split('/'); // eslint-disable-next-line @typescript-eslint/no-this-alias - let lastNode: this = this; + let lastNode: BaseNode = this; for (let i = 0; i < segments.length; ++i) { const segment = segments[i]; if (segment.length === 0) { @@ -534,7 +548,7 @@ export class BaseNode extends CCObject implements ISchedulable { } lastNode = next; } - return lastNode; + return lastNode as Node; } /** @@ -542,8 +556,8 @@ export class BaseNode extends CCObject implements ISchedulable { * @zh 添加一个子节点。 * @param child - the child node to be added */ - public addChild (child: this | Node): void { - (child as this).setParent(this); + public addChild (child: Node): void { + (child as BaseNode).setParent(this); } /** @@ -556,8 +570,8 @@ export class BaseNode extends CCObject implements ISchedulable { * node.insertChild(child, 2); * ``` */ - public insertChild (child: this | Node, siblingIndex: number) { - child.parent = this; + public insertChild (child: Node, siblingIndex: number) { + (child as BaseNode).setParent(this); child.setSiblingIndex(siblingIndex); } @@ -780,7 +794,7 @@ export class BaseNode extends CCObject implements ISchedulable { * var sprite = node.getComponent(Sprite); * ``` */ - public getComponent (classConstructor: Constructor): T | null; + public getComponent (classConstructor: Constructor | AbstractedConstructor): T | null; /** * @en @@ -798,7 +812,7 @@ export class BaseNode extends CCObject implements ISchedulable { */ public getComponent (className: string): Component | null; - public getComponent (typeOrClassName: string | Constructor) { + public getComponent (typeOrClassName: string | Constructor | AbstractedConstructor) { const constructor = getConstructor(typeOrClassName); if (constructor) { return BaseNode._findComponent(this, constructor); @@ -811,7 +825,7 @@ export class BaseNode extends CCObject implements ISchedulable { * @zh 返回节点上指定类型的所有组件。 * @param classConstructor The class of the target component */ - public getComponents (classConstructor: Constructor): T[]; + public getComponents (classConstructor: Constructor | AbstractedConstructor): T[]; /** * @en Returns all components of given type in the node. @@ -820,7 +834,7 @@ export class BaseNode extends CCObject implements ISchedulable { */ public getComponents (className: string): Component[]; - public getComponents (typeOrClassName: string | Constructor) { + public getComponents (typeOrClassName: string | Constructor | AbstractedConstructor) { const constructor = getConstructor(typeOrClassName); const components: Component[] = []; if (constructor) { @@ -838,7 +852,7 @@ export class BaseNode extends CCObject implements ISchedulable { * var sprite = node.getComponentInChildren(Sprite); * ``` */ - public getComponentInChildren (classConstructor: Constructor): T | null; + public getComponentInChildren (classConstructor: Constructor | AbstractedConstructor): T | null; /** * @en Returns the component of given type in any of its children using depth first search. @@ -851,7 +865,7 @@ export class BaseNode extends CCObject implements ISchedulable { */ public getComponentInChildren (className: string): Component | null; - public getComponentInChildren (typeOrClassName: string | Constructor) { + public getComponentInChildren (typeOrClassName: string | Constructor | AbstractedConstructor) { const constructor = getConstructor(typeOrClassName); if (constructor) { return BaseNode._findChildComponent(this._children, constructor); @@ -868,7 +882,7 @@ export class BaseNode extends CCObject implements ISchedulable { * var sprites = node.getComponentsInChildren(Sprite); * ``` */ - public getComponentsInChildren (classConstructor: Constructor): T[]; + public getComponentsInChildren (classConstructor: Constructor | AbstractedConstructor): T[]; /** * @en Returns all components of given type in self or any of its children. @@ -881,7 +895,7 @@ export class BaseNode extends CCObject implements ISchedulable { */ public getComponentsInChildren (className: string): Component[]; - public getComponentsInChildren (typeOrClassName: string | Constructor) { + public getComponentsInChildren (typeOrClassName: string | Constructor | AbstractedConstructor) { const constructor = getConstructor(typeOrClassName); const components: Component[] = []; if (constructor) { @@ -987,6 +1001,7 @@ export class BaseNode extends CCObject implements ISchedulable { EditorExtends.Component.add(component._id, component); } } + this.emit(NodeEventType.COMPONENT_ADDED, component); if (this._activeInHierarchy) { legacyCC.director._nodeActivator.activateComp(component); } @@ -1008,7 +1023,7 @@ export class BaseNode extends CCObject implements ISchedulable { * node.removeComponent(Sprite); * ``` */ - public removeComponent (classConstructor: Constructor): void; + public removeComponent (classConstructor: Constructor | AbstractedConstructor): void; /** * @en @@ -1070,7 +1085,7 @@ export class BaseNode extends CCObject implements ISchedulable { * 同时您可以将事件派发到父节点或者通过调用 stopPropagation 拦截它。 * 你也可以注册自定义事件到节点上,并通过 emit 方法触发此类事件,对于这类事件,不会发生捕获冒泡阶段,只会直接派发给注册在该节点上的监听器 * 你可以通过在 emit 方法调用时在 type 之后传递额外的参数作为事件回调的参数列表 - * @param type - A string representing the event type to listen for.
See {{#crossLink "Node/EventType/POSITION_CHANGED"}}Node Events{{/crossLink}} for all builtin events. + * @param type - A string representing the event type to listen for.
See [[Node.EventType.POSITION_CHANGED]] for all builtin events. * @param callback - The callback that will be invoked when the event is dispatched. The callback is ignored if it is a duplicate (the callbacks are unique). * @param target - The target (this object) to invoke the callback, can be null * @param useCapture - When set to true, the listener will be triggered at capturing phase which is ahead of the final target emit, otherwise it will be triggered during bubbling phase. @@ -1225,7 +1240,7 @@ export class BaseNode extends CCObject implements ISchedulable { /** * Do remove component, only used internally. - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _removeComponent (component: Component) { if (!component) { @@ -1240,6 +1255,7 @@ export class BaseNode extends CCObject implements ISchedulable { if (EDITOR && EditorExtends.Component) { EditorExtends.Component.remove(component._id); } + this.emit(NodeEventType.COMPONENT_REMOVED, component); } else if (component.node !== (this as unknown as BaseNode)) { errorID(3815); } @@ -1247,7 +1263,7 @@ export class BaseNode extends CCObject implements ISchedulable { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _updateSiblingIndex () { for (let i = 0; i < this._children.length; ++i) { @@ -1273,7 +1289,7 @@ export class BaseNode extends CCObject implements ISchedulable { protected _onBatchCreated (dontSyncChildPrefab: boolean) { if (this._parent) { - this._siblingIndex = this._parent.children.indexOf(this); + this._siblingIndex = this._parent._children.indexOf(this); } } @@ -1403,7 +1419,10 @@ export class BaseNode extends CCObject implements ISchedulable { protected _onSiblingIndexChanged? (siblingIndex: number): void; /** + * @en * Ensures that this node has already had the specified component(s). If not, this method throws. + * @zh + * 检查节点已经包含对应的组件,如果没有,则抛出异常 * @param constructor Constructor of the component. * @throws If one or more component of same type have been existed in this node. */ diff --git a/cocos/core/scene-graph/category.json b/cocos/core/scene-graph/category.json new file mode 100644 index 0000000000..ae9ab1fbc6 --- /dev/null +++ b/cocos/core/scene-graph/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "场景图", + "en": "Scene Graph" + }, + "description": { + "zh": "游戏是由各种各样的场景组成的,而场景是有节点组成的。节点之间是树状的组织关系,每个节点可以有多个子节点。", + "en": "The game is composed of various scenes, and the scenes are composed of nodes. The nodes are organized in a tree-like relationship, and each node can have multiple children." + } +} \ No newline at end of file diff --git a/cocos/core/scene-graph/component-scheduler.ts b/cocos/core/scene-graph/component-scheduler.ts index 077e77a48e..f93cfac86b 100644 --- a/cocos/core/scene-graph/component-scheduler.ts +++ b/cocos/core/scene-graph/component-scheduler.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module scene-graph - */ - import { EDITOR, SUPPORT_JIT, DEV, TEST } from 'internal:constants'; import { CCObject } from '../data/object'; import { MutableForwardIterator } from '../utils/array'; @@ -369,7 +364,7 @@ export class ComponentScheduler { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _onEnabled (comp) { legacyCC.director.getScheduler().resumeTarget(comp); @@ -384,7 +379,7 @@ export class ComponentScheduler { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _onDisabled (comp) { legacyCC.director.getScheduler().pauseTarget(comp); @@ -480,7 +475,7 @@ export class ComponentScheduler { /** * @en Process update phase for registered components * @zh 为当前注册的组件执行 update 阶段任务 - * @param dt 距离上一帧的时间 + * @param dt @en Time passed after the last frame in seconds @zh 距离上一帧的时间,以秒计算 */ public updatePhase (dt:number) { this.updateInvoker.invoke(dt); @@ -489,7 +484,7 @@ export class ComponentScheduler { /** * @en Process late update phase for registered components * @zh 为当前注册的组件执行 late update 阶段任务 - * @param dt 距离上一帧的时间 + * @param dt @en Time passed after the last frame in seconds @zh 距离上一帧的时间,以秒计算 */ public lateUpdatePhase (dt:number) { this.lateUpdateInvoker.invoke(dt); diff --git a/cocos/core/scene-graph/deprecated.ts b/cocos/core/scene-graph/deprecated.ts index d36177633d..d8b15e1e7f 100644 --- a/cocos/core/scene-graph/deprecated.ts +++ b/cocos/core/scene-graph/deprecated.ts @@ -23,9 +23,7 @@ THE SOFTWARE. */ - - -import { EDITOR } from 'internal:constants'; +import { EDITOR, JSB } from 'internal:constants'; import { ccclass } from 'cc.decorator'; import { BaseNode } from './base-node'; import { replaceProperty, removeProperty } from '../utils/x-deprecated'; @@ -37,7 +35,6 @@ import { legacyCC } from '../global-exports'; import { CCObject } from '../data/object'; import { warnID } from '../platform/debug'; import { SceneGlobals } from './scene-globals'; -import { JSB } from '../default-constants'; import { SystemEventType } from '../../input/types'; import { SystemEvent } from '../../input'; import { NodeUIProperties } from './node-ui-properties'; @@ -205,6 +202,10 @@ replaceProperty(SceneGlobals.prototype, 'SceneGlobals.prototype', [ name: 'normal', newName: 'planeDirection', }, + { + name: 'size', + newName: 'shadowMapSize', + }, ]); removeProperty(Node.prototype, 'Node.prototype', [ @@ -313,6 +314,10 @@ removeProperty(Layers.BitMask, 'Layers.BitMask', [ const HideInHierarchy = CCObject.Flags.HideInHierarchy; const DontSave = CCObject.Flags.DontSave; +/** + * @internal + * @deprecated since v3.5 + */ @ccclass('cc.PrivateNode') export class PrivateNode extends Node { constructor (name?: string) { diff --git a/cocos/core/scene-graph/find.ts b/cocos/core/scene-graph/find.ts index f24a598568..9d5f244fc1 100644 --- a/cocos/core/scene-graph/find.ts +++ b/cocos/core/scene-graph/find.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module scene-graph - */ - import { DEV } from 'internal:constants'; import { warnID } from '../platform/debug'; import { Node } from './node'; diff --git a/cocos/core/scene-graph/index.jsb.ts b/cocos/core/scene-graph/index.jsb.ts index a8bf012231..ec5cc4cdf6 100644 --- a/cocos/core/scene-graph/index.jsb.ts +++ b/cocos/core/scene-graph/index.jsb.ts @@ -1,8 +1,10 @@ +import './node-event-processor'; + export * from './node'; export * from './scene'; - export { Layers } from './layers'; export * from './deprecated'; export * from './scene-globals'; export * from './find'; export { default as NodeActivator } from './node-activator'; +export * from './node-event'; diff --git a/cocos/core/scene-graph/index.ts b/cocos/core/scene-graph/index.ts index a85d2b48f7..c44a0bac8e 100644 --- a/cocos/core/scene-graph/index.ts +++ b/cocos/core/scene-graph/index.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module scene-graph - */ - import './node-event-processor'; import './deprecated'; @@ -36,5 +31,8 @@ export { Node } from './node'; export { Scene } from './scene'; export { Layers } from './layers'; export { find } from './find'; +export * from './node-enum'; +export * from './node-event'; +export * from './scene-globals'; export * from './deprecated'; export { default as NodeActivator } from './node-activator'; diff --git a/cocos/core/scene-graph/layers.ts b/cocos/core/scene-graph/layers.ts index b794c883af..807334f888 100644 --- a/cocos/core/scene-graph/layers.ts +++ b/cocos/core/scene-graph/layers.ts @@ -23,17 +23,13 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module scene-graph - */ - import { BitMask, Enum } from '../value-types'; import { legacyCC } from '../global-exports'; import { log2 } from '../math/bits'; import { js } from '../utils/js'; import { assertIsTrue } from '../data/utils/asserts'; import { getError } from '../platform/debug'; +import { Settings, settings } from '../settings'; // built-in layers, users can use 0~19 bits, 20~31 are system preserve bits. const layerList = { @@ -50,6 +46,11 @@ const layerList = { ALL: 0xffffffff, }; +export interface LayerItem { + name: string; + bit: number; +} + /** * @zh 节点层管理器,层数据是以掩码数据方式存储在 [[Node.layer]] 中,用于射线检测、物理碰撞和用户自定义脚本逻辑。 * 每个节点可属于一个或多个层,可通过 “包含式” 或 “排除式” 两种检测器进行层检测。 @@ -70,6 +71,18 @@ export class Layers { */ public static BitMask = BitMask({ ...layerList }); + /** + * @internal + */ + public static init () { + const userLayers = settings.querySettings(Settings.Category.ENGINE, 'customLayers'); + if (!userLayers) return; + for (let i = 0; i < userLayers.length; i++) { + const layer = userLayers[i]; + Layers.addLayer(layer.name, layer.bit); + } + } + /** * @en * Make a layer mask accepting nothing but the listed layers diff --git a/cocos/core/scene-graph/node-activator.ts b/cocos/core/scene-graph/node-activator.ts index 3bcbb1f4a2..45ac0d4fe3 100644 --- a/cocos/core/scene-graph/node-activator.ts +++ b/cocos/core/scene-graph/node-activator.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module scene-graph - */ - import { EDITOR, DEV, TEST, SUPPORT_JIT, DEBUG } from 'internal:constants'; import { CCObject, isValid } from '../data/object'; import { array, Pool } from '../utils/js'; diff --git a/cocos/core/scene-graph/node-enum.ts b/cocos/core/scene-graph/node-enum.ts index 8d365f6c0e..e185265d90 100644 --- a/cocos/core/scene-graph/node-enum.ts +++ b/cocos/core/scene-graph/node-enum.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module scene-graph - */ - import { legacyCC } from '../global-exports'; /** @@ -45,35 +40,39 @@ export enum NodeSpace { */ export enum TransformBit { /** - * @zh - * 无改变 + * @en No change + * @zh 无改变 */ NONE = 0, /** - * @zh - * 节点位置改变 + * @en Translation changed + * @zh 节点位置改变 */ POSITION = (1 << 0), /** - * @zh - * 节点旋转 + * @en Rotation changed + * @zh 节点旋转 */ ROTATION = (1 << 1), /** - * @zh - * 节点缩放 + * @en Scale changed + * @zh 节点缩放 */ SCALE = (1 << 2), /** - * @zh - * 节点旋转及缩放 + * @en Rotation or scale changed + * @zh 节点旋转及缩放 */ RS = TransformBit.ROTATION | TransformBit.SCALE, /** - * @zh - * 节点平移,旋转及缩放 + * @en Translation, rotation or scale changed + * @zh 节点平移,旋转及缩放 */ TRS = TransformBit.POSITION | TransformBit.ROTATION | TransformBit.SCALE, + /** + * @en Invert mask of [[TRS]] + * @zh [[TRS]] 的反向掩码 + */ TRS_MASK = ~TransformBit.TRS, } diff --git a/cocos/core/scene-graph/node-event-processor.ts b/cocos/core/scene-graph/node-event-processor.ts index b6bdb106e0..4f3b3d0e18 100644 --- a/cocos/core/scene-graph/node-event-processor.ts +++ b/cocos/core/scene-graph/node-event-processor.ts @@ -23,10 +23,8 @@ THE SOFTWARE. */ - - import { CallbacksInvoker } from '../event/callbacks-invoker'; -import { Event, EventMouse, EventTouch } from '../../input/types'; +import { Event, EventMouse, EventTouch, Touch } from '../../input/types'; import { Vec2 } from '../math/vec2'; import { BaseNode } from './base-node'; import { Node } from './node'; @@ -37,7 +35,7 @@ import { InputEventType, SystemEventTypeUnion } from '../../input/types/event-en const _cachedArray = new Array(16); let _currentHovered: BaseNode | null = null; -let pos = new Vec2(); +const pos = new Vec2(); const _touchEvents = [ NodeEventType.TOUCH_START, @@ -67,39 +65,34 @@ export enum DispatcherEventType { } /** - * @zh - * 节点事件类。 + * @en The event processor for Node + * @zh 节点事件类。 */ export class NodeEventProcessor { + /** + * @internal + */ public static _maskComp: Constructor | null = null; + /** + * @internal + */ public static callbacksInvoker = new CallbacksInvoker(); - private _isEnabled = false; + /** + * Whether the node event is enabled + */ public get isEnabled () { return this._isEnabled; } - public setEnabled (value: boolean, recursive = false) { - if (this._isEnabled === value) { - return; - } - this._isEnabled = value; - const node = this.node; - const children = node.children; - if (value) { - this._attachMask(); - } - NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.MARK_LIST_DIRTY); - if (recursive && children.length > 0) { - for (let i = 0; i < children.length; ++i) { - const child = children[i]; - // @ts-expect-error child._eventProcessor is a protected property. - child._eventProcessor.setEnabled(value, true); - } - } - } + /** + * The list of claimed touch ids + */ public claimedTouchIdList: number[] = []; + /** + * The masks in the parent chain of the node + */ public maskList: IMask[] | null = null; /** @@ -138,41 +131,39 @@ export class NodeEventProcessor { */ public shouldHandleEventTouch = false; + // Whether dispatch cancel event when node is destroyed. + private _dispatchingTouch: Touch | null = null; + private _isEnabled = false; private _node: Node; constructor (node: Node) { this._node = node; } - private _searchComponentsInParent (ctor: Constructor | null) { - const node = this.node; - if (ctor) { - let index = 0; - let list: IMask[] = []; - for (let curr: Node | null = node; curr && Node.isNode(curr); curr = curr.parent, ++index) { - const comp = curr.getComponent(ctor); - if (comp) { - const next = { - index, - comp, - }; - - if (list) { - list.push(next); - } else { - list = [next]; - } - } - } - - return list.length > 0 ? list : null; + /** + * Set enable state of the node event processor + * @param value Enable state + * @param recursive Recursively set the state or not + * @returns void + */ + public setEnabled (value: boolean, recursive = false) { + if (this._isEnabled === value) { + return; + } + this._isEnabled = value; + const node = this.node; + const children = node.children; + if (value) { + this._attachMask(); + } + NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.MARK_LIST_DIRTY); + if (recursive && children.length > 0) { + for (let i = 0; i < children.length; ++i) { + const child = children[i]; + // @ts-expect-error child._eventProcessor is a protected property. + child._eventProcessor.setEnabled(value, true); + } } - - return null; - } - - private _attachMask () { - this.maskList = this._searchComponentsInParent(NodeEventProcessor._maskComp); } public reattach (): void { @@ -193,79 +184,13 @@ export class NodeEventProcessor { if (this.capturingTarget) this.capturingTarget.clear(); if (this.bubblingTarget) this.bubblingTarget.clear(); NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.REMOVE_POINTER_EVENT_PROCESSOR, this); - } - - private _isTouchEvent (type: NodeEventType) { - const index = _touchEvents.indexOf(type); - return index !== -1; - } - - private _isMouseEvent (type: NodeEventType) { - const index = _mouseEvents.indexOf(type); - return index !== -1; - } - - private _hasTouchListeners () { - for (let i = 0; i < _touchEvents.length; ++i) { - const eventType = _touchEvents[i]; - if (this.hasEventListener(eventType)) { - return true; - } + if (this._dispatchingTouch) { + // Dispatch touch cancel event when node is destroyed. + const cancelEvent = new EventTouch([this._dispatchingTouch], true, InputEventType.TOUCH_CANCEL); + cancelEvent.touch = this._dispatchingTouch; + this.dispatchEvent(cancelEvent); + this._dispatchingTouch = null; } - return false; - } - - private _hasMouseListeners () { - for (let i = 0; i < _mouseEvents.length; ++i) { - const eventType = _mouseEvents[i]; - if (this.hasEventListener(eventType)) { - return true; - } - } - return false; - } - - private _hasPointerListeners () { - const has = this._hasTouchListeners(); - if (has) { - return true; - } - return this._hasMouseListeners(); - } - - private _tryEmittingAddEvent (typeToAdd: NodeEventType) { - const isTouchEvent = this._isTouchEvent(typeToAdd); - const isMouseEvent = this._isMouseEvent(typeToAdd); - if (isTouchEvent) { - this.shouldHandleEventTouch = true; - } else if (isMouseEvent) { - this.shouldHandleEventMouse = true; - } - if ((isTouchEvent || isMouseEvent) && !this._hasPointerListeners()) { - NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.ADD_POINTER_EVENT_PROCESSOR, this); - } - } - - /** - * Fix when reigster 'once' event callback, `this.off` method isn't be invoked after event is emitted. - * We need to inject some nodeEventProcessor's logic into the `callbacksInvoker.off` method. - * @returns {CallbacksInvoker} decorated callbacks invoker - */ - private _newCallbacksInvoker (): CallbacksInvoker { - const callbacksInvoker = new CallbacksInvoker(); - // @ts-expect-error Property '_registerOffCallback' is private - callbacksInvoker._registerOffCallback(() => { - if (this.shouldHandleEventTouch && !this._hasTouchListeners()) { - this.shouldHandleEventTouch = false; - } - if (this.shouldHandleEventMouse && !this._hasMouseListeners()) { - this.shouldHandleEventMouse = false; - } - if (!this._hasPointerListeners()) { - NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.REMOVE_POINTER_EVENT_PROCESSOR, this); - } - }); - return callbacksInvoker; } public on (type: NodeEventType, callback: AnyFunction, target?: unknown, useCapture?: boolean) { @@ -434,6 +359,110 @@ export class NodeEventProcessor { } } + private _searchComponentsInParent (ctor: Constructor | null) { + const node = this.node; + if (ctor) { + let index = 0; + let list: IMask[] = []; + for (let curr: Node | null = node; curr && Node.isNode(curr); curr = curr.parent, ++index) { + const comp = curr.getComponent(ctor); + if (comp) { + const next = { + index, + comp, + }; + + if (list) { + list.push(next); + } else { + list = [next]; + } + } + } + + return list.length > 0 ? list : null; + } + + return null; + } + + private _attachMask () { + this.maskList = this._searchComponentsInParent(NodeEventProcessor._maskComp); + } + + private _isTouchEvent (type: NodeEventType) { + const index = _touchEvents.indexOf(type); + return index !== -1; + } + + private _isMouseEvent (type: NodeEventType) { + const index = _mouseEvents.indexOf(type); + return index !== -1; + } + + private _hasTouchListeners () { + for (let i = 0; i < _touchEvents.length; ++i) { + const eventType = _touchEvents[i]; + if (this.hasEventListener(eventType)) { + return true; + } + } + return false; + } + + private _hasMouseListeners () { + for (let i = 0; i < _mouseEvents.length; ++i) { + const eventType = _mouseEvents[i]; + if (this.hasEventListener(eventType)) { + return true; + } + } + return false; + } + + private _hasPointerListeners () { + const has = this._hasTouchListeners(); + if (has) { + return true; + } + return this._hasMouseListeners(); + } + + private _tryEmittingAddEvent (typeToAdd: NodeEventType) { + const isTouchEvent = this._isTouchEvent(typeToAdd); + const isMouseEvent = this._isMouseEvent(typeToAdd); + if (isTouchEvent) { + this.shouldHandleEventTouch = true; + } else if (isMouseEvent) { + this.shouldHandleEventMouse = true; + } + if ((isTouchEvent || isMouseEvent) && !this._hasPointerListeners()) { + NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.ADD_POINTER_EVENT_PROCESSOR, this); + } + } + + /** + * Fix when reigster 'once' event callback, `this.off` method isn't be invoked after event is emitted. + * We need to inject some nodeEventProcessor's logic into the `callbacksInvoker.off` method. + * @returns {CallbacksInvoker} decorated callbacks invoker + */ + private _newCallbacksInvoker (): CallbacksInvoker { + const callbacksInvoker = new CallbacksInvoker(); + // @ts-expect-error Property '_registerOffCallback' is private + callbacksInvoker._registerOffCallback(() => { + if (this.shouldHandleEventTouch && !this._hasTouchListeners()) { + this.shouldHandleEventTouch = false; + } + if (this.shouldHandleEventMouse && !this._hasMouseListeners()) { + this.shouldHandleEventMouse = false; + } + if (!this._hasPointerListeners()) { + NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.REMOVE_POINTER_EVENT_PROCESSOR, this); + } + }); + return callbacksInvoker; + } + // #region handle mouse event private _handleEventMouse (eventMouse: EventMouse): boolean { @@ -571,6 +600,7 @@ export class NodeEventProcessor { if (node._uiProps.uiTransformComp.hitTest(pos)) { event.type = NodeEventType.TOUCH_START; event.bubbles = true; + this._dispatchingTouch = event.touch; node.dispatchEvent(event); return true; } @@ -586,6 +616,7 @@ export class NodeEventProcessor { event.type = NodeEventType.TOUCH_MOVE; event.bubbles = true; + this._dispatchingTouch = event.touch; node.dispatchEvent(event); return true; } @@ -605,6 +636,7 @@ export class NodeEventProcessor { } event.bubbles = true; node.dispatchEvent(event); + this._dispatchingTouch = null; } private _handleTouchCancel (event: EventTouch) { diff --git a/cocos/core/scene-graph/node-event.ts b/cocos/core/scene-graph/node-event.ts index 5f86ba748d..2123b5a021 100644 --- a/cocos/core/scene-graph/node-event.ts +++ b/cocos/core/scene-graph/node-event.ts @@ -1,3 +1,32 @@ +/* + Copyright (c) 2019-2022 Xiamen Yaji Software Co., Ltd. + + http://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. +*/ + +/** + * @en All event types which [[Node]] could emit + * @zh 所有 [[Node]] 可能派发的事件类型 + */ export enum NodeEventType { /** * @en @@ -115,10 +144,10 @@ export enum NodeEventType { /** * @en - * The event type for position, rotation, scale changed.Use the type parameter as [[Node.TransformBit]] to check which part is changed + * The event type for position, rotation, scale changed.Use the type parameter as `Node.TransformBit` to check which part is changed * * @zh - * 节点改变位置、旋转或缩放事件。如果具体需要判断是哪一个事件,可通过判断回调的第一个参数类型是 [[Node.TransformBit]] 中的哪一个来获取 + * 节点改变位置、旋转或缩放事件。如果具体需要判断是哪一个事件,可通过判断回调的第一个参数类型是 `Node.TransformBit` 中的哪一个来获取 * @example * ``` * this.node.on(Node.EventType.TRANSFORM_CHANGED, (type)=>{ @@ -222,4 +251,20 @@ export enum NodeEventType { * 注意:此节点激活时,此事件仅从最顶部的节点发出。 */ ACTIVE_IN_HIERARCHY_CHANGED = 'active-in-hierarchy-changed', + + /** + * @en + * The event occur when node add a new component. + * @zh + * 当节点上增加组件时触发的事件 + */ + COMPONENT_ADDED = 'component-added', + + /** + * @en + * The event occur when node remove a component. + * @zh + * 当节点上移除组件时触发的事件 + */ + COMPONENT_REMOVED = 'component-removed', } diff --git a/cocos/core/scene-graph/node-ui-properties.ts b/cocos/core/scene-graph/node-ui-properties.ts index fa43713bf2..f5b4b27103 100644 --- a/cocos/core/scene-graph/node-ui-properties.ts +++ b/cocos/core/scene-graph/node-ui-properties.ts @@ -23,13 +23,7 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module scene-graph - */ - -import { JSB } from 'internal:constants'; -import { Renderable2D } from '../../2d/framework/renderable-2d'; +import { UIRenderer } from '../../2d/framework/ui-renderer'; import { UITransform } from '../../2d/framework/ui-transform'; import { warnID } from '../platform/debug'; import { UIMeshRenderer } from '../../2d'; @@ -61,7 +55,7 @@ export class NodeUIProperties { get uiComp () { return this._uiComp; } - set uiComp (comp: UIMeshRenderer | Renderable2D | null) { + set uiComp (comp: UIMeshRenderer | UIRenderer | null) { if (this._uiComp && comp) { warnID(12002); return; @@ -69,7 +63,7 @@ export class NodeUIProperties { this._uiComp = comp; } - private _uiComp: UIMeshRenderer | Renderable2D | null = null; + private _uiComp: UIMeshRenderer | UIRenderer | null = null; /** * @en The opacity of the UI node for final rendering @@ -93,26 +87,8 @@ export class NodeUIProperties { protected _uiTransformComp: UITransform | null = null; private _node: any; - public declare uiTransformDirty: boolean; - private declare _uiTransformDirty: Uint32Array; - constructor (node: any) { this._node = node; - - if (JSB) { - this._uiTransformDirty = new Uint32Array((jsb as any).createExternalArrayBuffer(4)); - Object.defineProperty(this, 'uiTransformDirty', - { - get (): boolean { - return this._uiTransformDirty[0] !== 0; - }, - set (val: boolean) { - this._uiTransformDirty[0] = val ? 1 : 0; - }, - }); - } else { - this.uiTransformDirty = false; - } } /** diff --git a/cocos/core/scene-graph/node.jsb.ts b/cocos/core/scene-graph/node.jsb.ts index be9a1a121c..f49bcdb8f6 100644 --- a/cocos/core/scene-graph/node.jsb.ts +++ b/cocos/core/scene-graph/node.jsb.ts @@ -19,13 +19,8 @@ THE SOFTWARE. */ -import { ccclass, editable, serializable, type } from 'cc.decorator'; -import { - _applyDecoratedDescriptor, - _assertThisInitialized, - _initializerDefineProperty, -} from '../data/utils/decorator-jsb-utils'; - +import { EDITOR } from 'internal:constants'; +import { ccclass, editable, serializable, type } from 'cc.decorator' import { legacyCC } from '../global-exports'; import { errorID, getError } from '../platform/debug'; import { Component } from '../components/component'; @@ -34,20 +29,15 @@ import { CCObject } from '../data/object'; import { NodeUIProperties } from './node-ui-properties'; import { NodeSpace, TransformBit } from './node-enum'; import { Mat4, Quat, Vec3 } from '../math'; -import { NodeEventProcessor } from './node-event-processor'; import { Layers } from './layers'; -import { SerializationContext, SerializationOutput, serializeTag } from '../data'; -import { EDITOR } from '../default-constants'; -import { - applyMountedChildren, - applyMountedComponents, applyPropertyOverrides, - applyRemovedComponents, applyTargetOverrides, - createNodeWithPrefab, - generateTargetMap, -} from '../utils/prefab/utils'; +import { editorExtrasTag, SerializationContext, SerializationOutput, serializeTag } from '../data'; +import { _tempFloatArray, fillMat4WithTempFloatArray } from './utils.jsb'; import { getClassByName, isChildClassOf } from '../utils/js-typed'; import { syncNodeValues } from "../utils/jsb-utils"; -import { BaseNode } from "./base-node.jsb"; +import { property } from '../data/class-decorator'; +import './base-node'; + +const reserveContentsForAllSyncablePrefabTag = Symbol('ReserveContentsForAllSyncablePrefab'); declare const jsb: any; @@ -56,8 +46,6 @@ export const Node = jsb.Node; export type Node = jsb.Node; legacyCC.Node = Node; -const clsDecorator = ccclass('cc.Node'); - const NodeCls: any = Node; /** * @en Event types emitted by Node @@ -84,14 +72,12 @@ NodeCls.TransformDirtyBit = TransformBit; */ NodeCls.TransformBit = TransformBit; +const TRANSFORMBIT_TRS = TransformBit.TRS; + const nodeProto: any = jsb.Node.prototype; export const TRANSFORM_ON = 1 << 0; const Destroying = CCObject.Flags.Destroying; -// For optimize getPosition, getRotation, getScale -export const _tempFloatArray = new Float32Array(jsb.createExternalArrayBuffer(20 * 4)); -// - Node._setTempFloatArray(_tempFloatArray.buffer); function getConstructor (typeOrClassName) { @@ -200,6 +186,7 @@ nodeProto.addComponent = function (typeOrClassName) { EditorExtends.Component.add(component._id, component); } } + this.emit(NodeEventType.COMPONENT_ADDED, component); if (this._activeInHierarchy) { legacyCC.director._nodeActivator.activateComp(component); } @@ -233,9 +220,7 @@ const REGISTERED_EVENT_MASK_SIBLING_ORDER_CHANGED_CHANGED = (1 << 5); nodeProto.on = function (type, callback, target, useCapture: any = false) { switch (type) { case NodeEventType.TRANSFORM_CHANGED: - - // this._eventMask |= TRANSFORM_ON; - this.setEventMask(this.getEventMask() | ~TRANSFORM_ON); + this._eventMask |= TRANSFORM_ON; if (!(this._registeredNodeEventTypeMask & REGISTERED_EVENT_MASK_TRANSFORM_CHANGED)) { this._registerOnTransformChanged(); this._registeredNodeEventTypeMask |= REGISTERED_EVENT_MASK_TRANSFORM_CHANGED; @@ -285,8 +270,7 @@ nodeProto.off = function (type: string, callback?, target?, useCapture = false) if (!hasListeners) { switch (type) { case NodeEventType.TRANSFORM_CHANGED: - // this._eventMask &= ~TRANSFORM_ON; - this.setEventMask(this.getEventMask() & ~TRANSFORM_ON); + this._eventMask &= ~TRANSFORM_ON; break; default: break; @@ -312,10 +296,8 @@ nodeProto.hasEventListener = function (type: string, callback?, target?: unknown nodeProto.targetOff = function (target: string | unknown) { // Check for event mask reset - const eventMask = this.getEventMask(); - if ((eventMask & TRANSFORM_ON) && !this._eventProcessor.hasEventListener(NodeEventType.TRANSFORM_CHANGED)) { - // this._eventMask &= ~TRANSFORM_ON; - this.setEventMask(eventMask & ~TRANSFORM_ON); + if ((this._eventMask & TRANSFORM_ON) && !this._eventProcessor.hasEventListener(NodeEventType.TRANSFORM_CHANGED)) { + this._eventMask &= ~TRANSFORM_ON; } }; @@ -332,6 +314,7 @@ nodeProto._removeComponent = function (component: Component) { if (EDITOR && EditorExtends.Component) { EditorExtends.Component.remove(component._id); } + this.emit(NodeEventType.COMPONENT_REMOVED, component); } else if (component.node !== this) { errorID(3815); } @@ -413,16 +396,53 @@ nodeProto._onChildAdded = function (child) { nodeProto._onNodeDestroyed = function () { this.emit(NodeEventType.NODE_DESTROYED, this); + // destroy children + const children = this._children; + for (let i = 0; i < children.length; ++i) { + // destroy immediate so its _onPreDestroy can be called + children[i]._destroyImmediate(); + } +}; + +const oldPreDestroy = nodeProto._onPreDestroy; +nodeProto._onPreDestroy = function _onPreDestroy () { + const ret = oldPreDestroy.call(this); + + // emit node destroy event (this should before event processor destroy) + this.emit(NodeEventType.NODE_DESTROYED, this); + + // Destroy node event processor + this._eventProcessor.destroy(); + + // destroy children + const children = this._children; + for (let i = 0; i < children.length; ++i) { + // destroy immediate so its _onPreDestroy can be called + children[i]._destroyImmediate(); + } + + // destroy self components + const comps = this._components; + for (let i = 0; i < comps.length; ++i) { + // destroy immediate so its _onPreDestroy can be called + // TO DO + comps[i]._destroyImmediate(); + } + + return ret; +}; + +nodeProto.destroyAllChildren = function destroyAllChildren () { + const children = this._children; + for (let i = 0, len = children.length; i < len; ++i) { + children[i].destroy(); + } }; nodeProto._onSiblingOrderChanged = function () { this.emit(NodeEventType.SIBLING_ORDER_CHANGED); }; -nodeProto._onUiTransformDirty = function () { - this._uiProps.uiTransformDirty = true; -}; - nodeProto._onActivateNode = function (shouldActiveNow) { legacyCC.director._nodeActivator.activateNode(this, shouldActiveNow); }; @@ -527,28 +547,11 @@ NodeCls.isNode = function (obj: unknown): obj is jsb.Node { return obj instanceof jsb.Node && (obj.constructor === jsb.Node || !(obj instanceof legacyCC.Scene)); }; -const oldGetPosition = nodeProto.getPosition; -const oldSetPosition = nodeProto.setPosition; -const oldGetRotation = nodeProto.getRotation; -const oldSetRotation = nodeProto.setRotation; -const oldSetRotationFromEuler = nodeProto.setRotationFromEuler; -const oldGetScale = nodeProto.getScale; -const oldSetScale = nodeProto.setScale; -const oldGetWorldPosition = nodeProto.getWorldPosition; -const oldGetWorldRotation = nodeProto.getWorldRotation; -const oldGetWorldScale = nodeProto.getWorldScale; -const oldEulerAngles = nodeProto.getEulerAngles; -const oldGetWorldMatrix = nodeProto.getWorldMatrix; -const oldGetForward = nodeProto.getForward; -const oldGetUp = nodeProto.getUp; -const oldGetRight = nodeProto.getRight; -const oldSetRTS = nodeProto.setRTS; let _tempQuat = new Quat(); - -nodeProto.setRTS = function (rot?: Quat | Vec3, pos?: Vec3, scale?: Vec3) { +nodeProto.setRTS = function setRTS (rot?: Quat | Vec3, pos?: Vec3, scale?: Vec3) { if (rot) { let val = _tempQuat; - if (rot as Quat) { + if (rot instanceof Quat) { val = rot as Quat; } else { Quat.fromEuler(val, rot.x, rot.y, rot.z); @@ -581,23 +584,14 @@ nodeProto.setRTS = function (rot?: Quat | Vec3, pos?: Vec3, scale?: Vec3) { } else { _tempFloatArray[9] = 0; } - oldSetRTS.call(this); + this._setRTS(); }; -nodeProto.getPosition = function (out?: Vec3): Vec3 { - // oldGetPosition.call(this); - // if (out) { - // return Vec3.set(out, _tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2]); - // } - // const pos = this._positionCache; - // pos.x = _tempFloatArray[0]; - // pos.y = _tempFloatArray[1]; - // pos.z = _tempFloatArray[2]; - // return pos; +nodeProto.getPosition = function getPosition (out?: Vec3): Vec3 { if (out) { return Vec3.set(out, this._lpos.x, this._lpos.y, this._lpos.z); } - return Vec3.copy(this._positionCache, this._lpos); + return Vec3.copy(new Vec3(), this._lpos); }; nodeProto.setPosition = function setPosition (val: Readonly | number, y?: number, z?: number) { @@ -617,18 +611,18 @@ nodeProto.setPosition = function setPosition (val: Readonly | number, y?: this._lpos.y = _tempFloatArray[2] = y as number; this._lpos.z = _tempFloatArray[3] = z as number; } - oldSetPosition.call(this); + this._setPosition(); }; -nodeProto.getRotation = function (out?: Quat): Quat { +nodeProto.getRotation = function getRotation (out?: Quat): Quat { const lrot = this._lrot; if (out) { return Quat.set(out, lrot.x, lrot.y, lrot.z, lrot.w); } - return Quat.copy(this._rotationCache, lrot); + return Quat.copy(new Quat(), lrot); }; -nodeProto.setRotation = function (val: Readonly | number, y?: number, z?: number, w?: number): void { +nodeProto.setRotation = function setRotation (val: Readonly | number, y?: number, z?: number, w?: number): void { if (y === undefined || z === undefined || w === undefined) { const rot = val as Readonly; this._lrot.x = _tempFloatArray[0] = rot.x; @@ -642,10 +636,10 @@ nodeProto.setRotation = function (val: Readonly | number, y?: number, z?: this._lrot.w = _tempFloatArray[3] = w; } - oldSetRotation.call(this); + this._setRotation(); }; -nodeProto.setRotationFromEuler = function (val: Vec3 | number, y?: number, zOpt?: number): void { +nodeProto.setRotationFromEuler = function setRotationFromEuler (val: Vec3 | number, y?: number, zOpt?: number): void { const z = zOpt === undefined ? this._euler.z : zOpt; if (y === undefined) { @@ -659,23 +653,17 @@ nodeProto.setRotationFromEuler = function (val: Vec3 | number, y?: number, zOpt? this._euler.z = _tempFloatArray[2] = z; } - oldSetRotationFromEuler.call(this); + this._setRotationFromEuler(); }; -nodeProto.getScale = function (out?: Vec3): Vec3 { - // const r = oldGetScale.call(this); - // if (out) { - // return Vec3.set(out, r.x, r.y, r.z); - // } - // return Vec3.copy(this._scaleCache || (this._scaleCache = new Vec3()), r); - +nodeProto.getScale = function getScale (out?: Vec3): Vec3 { if (out) { return Vec3.set(out, this._lscale.x, this._lscale.y, this._lscale.z); } - return Vec3.copy(this._scaleCache, this._lscale); + return Vec3.copy(new Vec3(), this._lscale); }; -nodeProto.setScale = function (val: Readonly | number, y?: number, z?: number) { +nodeProto.setScale = function setScale (val: Readonly | number, y?: number, z?: number) { if (y === undefined && z === undefined) { _tempFloatArray[0] = 3; const scale = val as Vec3; @@ -692,75 +680,81 @@ nodeProto.setScale = function (val: Readonly | number, y?: number, z?: num this._lscale.y = _tempFloatArray[2] = y as number; this._lscale.z = _tempFloatArray[3] = z; } - oldSetScale.call(this); + this._setScale(); }; -nodeProto.getWorldPosition = function (out?: Vec3): Vec3 { - const r = oldGetWorldPosition.call(this); - if (out) { - return Vec3.copy(out, r); - } - return Vec3.copy(this._worldPositionCache, r); +nodeProto.getWorldPosition = function getWorldPosition (out?: Vec3): Vec3 { + this._getWorldPosition(); + out = out || new Vec3(); + return out.set(_tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2]); }; -nodeProto.getWorldRotation = function (out?: Quat): Quat { - const r = oldGetWorldRotation.call(this); - if (out) { - return Quat.copy(out, r); - } - return Quat.copy(this._worldRotationCache, r); +nodeProto.getWorldRotation = function getWorldRotation (out?: Quat): Quat { + this._getWorldRotation(); + out = out || new Quat(); + return out.set(_tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2], _tempFloatArray[3]); }; -nodeProto.getWorldScale = function (out?: Vec3): Vec3 { - const r = oldGetWorldScale.call(this); - if (out) { - return Vec3.copy(out, r); - } - return Vec3.copy(this._worldScaleCache, r); +nodeProto.getWorldScale = function getWorldScale (out?: Vec3): Vec3 { + this._getWorldScale(); + out = out || new Vec3(); + return out.set(_tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2]); }; nodeProto.getWorldMatrix = function getWorldMatrix (out?: Mat4): Mat4 { - oldGetWorldMatrix.call(this); - const target = out || this._worldMatrixCache; - target.set( - _tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2], _tempFloatArray[3], - _tempFloatArray[4], _tempFloatArray[5], _tempFloatArray[6], _tempFloatArray[7], - _tempFloatArray[8], _tempFloatArray[9], _tempFloatArray[10], _tempFloatArray[11], - _tempFloatArray[12], _tempFloatArray[13], _tempFloatArray[14], _tempFloatArray[15], - ); - return target; + this._getWorldMatrix(); + out = out || new Mat4(); + fillMat4WithTempFloatArray(out); + return out; }; -nodeProto.getEulerAngles = function (out?: Vec3): Vec3 { - const r = oldEulerAngles.call(this); - if (out) { - return Vec3.copy(out, r); - } - return Vec3.copy(this._eulerAnglesCache, r); +nodeProto.getEulerAngles = function getEulerAngles (out?: Vec3): Vec3 { + this._getEulerAngles(); + out = out || new Vec3(); + return out.set(_tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2]); }; -nodeProto.getForward = function (out?: Vec3): Vec3 { - const r = oldGetForward.call(this); - if (out) { - return Vec3.copy(out, r); - } - return Vec3.copy(this._forwardCache, r); +nodeProto.getForward = function getForward (out?: Vec3): Vec3 { + this._getForward(); + out = out || new Vec3(); + return out.set(_tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2]); }; -nodeProto.getUp = function (out?: Vec3): Vec3 { - const r = oldGetUp.call(this); - if (out) { - return Vec3.copy(out, r); - } - return Vec3.copy(this._upCache, r); +nodeProto.getUp = function getUp (out?: Vec3): Vec3 { + this._getUp(); + out = out || new Vec3(); + return out.set(_tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2]); }; -nodeProto.getRight = function (out?: Vec3): Vec3 { - const r = oldGetRight.call(this); - if (out) { - return Vec3.copy(out, r); - } - return Vec3.copy(this._rightCache, r); +nodeProto.getRight = function getRight (out?: Vec3): Vec3 { + this._getRight(); + out = out || new Vec3(); + return out.set(_tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2]); +}; + +nodeProto.inverseTransformPoint = function inverseTransformPoint (out: Vec3, p: Vec3) : Vec3 { + _tempFloatArray[0] = p.x; + _tempFloatArray[1] = p.y; + _tempFloatArray[2] = p.z; + this._inverseTransformPoint(); + out.x = _tempFloatArray[0]; + out.y = _tempFloatArray[1]; + out.z = _tempFloatArray[2]; + return out; +}; + +nodeProto.getWorldRT = function getWorldRT (out?: Mat4): Mat4 { + out = out || new Mat4(); + this._getWorldRT(); + fillMat4WithTempFloatArray(out); + return out; +}; + +nodeProto.getWorldRS = function getWorldRS (out?: Mat4): Mat4 { + out = out || new Mat4(); + this._getWorldRS(); + fillMat4WithTempFloatArray(out); + return out; }; Object.defineProperty(nodeProto, 'position', { @@ -884,10 +878,10 @@ Object.defineProperty(nodeProto, 'activeInHierarchy', { configurable: true, enumerable: true, get (): Readonly { - return this._activeInHierarchyArr[0] != 0; + return this._sharedUint8Arr[0] != 0; // Uint8, 0: activeInHierarchy }, set (v) { - this._activeInHierarchyArr[0] = (v ? 1 : 0); + this._sharedUint8Arr[0] = (v ? 1 : 0); // Uint8, 0: activeInHierarchy }, }); @@ -895,10 +889,10 @@ Object.defineProperty(nodeProto, '_activeInHierarchy', { configurable: true, enumerable: true, get (): Readonly { - return this._activeInHierarchyArr[0] != 0; + return this._sharedUint8Arr[0] != 0; // Uint8, 0: activeInHierarchy }, set (v) { - this._activeInHierarchyArr[0] = (v ? 1 : 0); + this._sharedUint8Arr[0] = (v ? 1 : 0); // Uint8, 0: activeInHierarchy }, }); @@ -906,10 +900,10 @@ Object.defineProperty(nodeProto, 'layer', { configurable: true, enumerable: true, get () { - return this._layerArr[0]; + return this._sharedUint32Arr[1]; // Uint32, 1: layer }, set (v) { - this._layerArr[0] = v; + this._sharedUint32Arr[1] = v; // Uint32, 1: layer if (this._uiProps && this._uiProps.uiComp) { this._uiProps.uiComp.setNodeDirty(); this._uiProps.uiComp.markForUpdateRenderData(); @@ -922,10 +916,80 @@ Object.defineProperty(nodeProto, '_layer', { configurable: true, enumerable: true, get () { - return this._layerArr[0]; + return this._sharedUint32Arr[1]; // Uint32, 1: layer }, set (v) { - this._layerArr[0] = v; + this._sharedUint32Arr[1] = v; // Uint32, 1: layer + }, +}); + +Object.defineProperty(nodeProto, '_eventMask', { + configurable: true, + enumerable: true, + get () { + return this._sharedUint32Arr[0]; // Uint32, 0: eventMask + }, + set (v) { + this._sharedUint32Arr[0] = v; // Uint32, 0: eventMask + }, +}); + +Object.defineProperty(nodeProto, '_siblingIndex', { + configurable: true, + enumerable: true, + get () { + return this._sharedInt32Arr[0]; // Int32, 0: siblingIndex + }, + set (v) { + this._sharedInt32Arr[0] = v; // Int32, 0: siblingIndex + }, +}); + +nodeProto.getSiblingIndex = function getSiblingIndex() { + return this._sharedInt32Arr[0]; // Int32, 0: siblingIndex +}; + +Object.defineProperty(nodeProto, '_dirtyFlags', { + configurable: true, + enumerable: true, + get () { + return this._sharedUint32Arr[2]; // Uint32, 2: dirtyFlags + }, + set (v) { + this._sharedUint32Arr[2] = v; // Uint32, 2: dirtyFlags + }, +}); + +Object.defineProperty(nodeProto, '_active', { + configurable: true, + enumerable: true, + get (): Readonly { + return this._sharedUint8Arr[1] != 0; // Uint8, 1: active + }, + set (v) { + this._sharedUint8Arr[1] = (v ? 1 : 0); // Uint8, 1: active + }, +}); + +Object.defineProperty(nodeProto, 'active', { + configurable: true, + enumerable: true, + get (): Readonly { + return this._sharedUint8Arr[1] != 0; // Uint8, 1: active + }, + set (v) { + this.setActive(!!v); + }, +}); + +Object.defineProperty(nodeProto, '_static', { + configurable: true, + enumerable: true, + get (): Readonly { + return this._sharedUint8Arr[2] != 0; + }, + set (v) { + this._sharedUint8Arr[2] = (v ? 1 : 0); }, }); @@ -959,7 +1023,7 @@ Object.defineProperty(nodeProto, 'right', { Object.defineProperty(nodeProto, 'eventProcessor', { configurable: true, enumerable: true, - get (): NodeEventProcessor { + get () { return this._eventProcessor; }, }); @@ -1026,7 +1090,7 @@ nodeProto.rotate = function (rot: Quat, ns?: NodeSpace): void { } else { _tempFloatArray[0] = 4; } - this.rotateForJS(); + this._rotateForJS(); const lrot = this._lrot; lrot.x = _tempFloatArray[0]; lrot.y = _tempFloatArray[1]; @@ -1043,35 +1107,41 @@ nodeProto.insertChild = function (child: Node, siblingIndex: number) { child.setSiblingIndex(siblingIndex); }; -// nodeProto.removeFromParent = function () { -// if (this._parent) { -// this._parent.removeChild(this); -// } -// }; -// -// const oldRemoveChild = nodeProto.removeChild; -// nodeProto.removeChild = function (child: Node) { -// oldRemoveChild.call(this, child); -// jsb.unregisterNativeRef(this, child); -// }; -// -// const oldRemoveAllChildren = nodeProto.removeAllChildren; -// nodeProto.removeAllChildren = function () { -// oldRemoveAllChildren.call(this); -// // cjh TODO: need to improve performance -// const children = this.children; -// for (let i = children.length - 1; i >= 0; i--) { -// const node = children[i]; -// if (node) { -// jsb.unregisterNativeRef(this, node); -// } -// } -// }; - nodeProto[serializeTag] = function (serializationOutput: SerializationOutput, context: SerializationContext) { if (!EDITOR) { serializationOutput.writeThis(); } + + // Detects if this node is mounted node of `PrefabInstance` + // TODO: optimize + const isMountedChild = () => !!(this[editorExtrasTag] as any)?.mountedRoot; + // Returns if this node is under `PrefabInstance` + // eslint-disable-next-line arrow-body-style + const isSyncPrefab = () => { + // 1. Under `PrefabInstance`, but not mounted + // 2. If the mounted node is a `PrefabInstance`, it's also a "sync prefab". + return this._prefab?.root?._prefab?.instance && (this?._prefab?.instance || !isMountedChild()); + }; + const canDiscardByPrefabRoot = () => !(context.customArguments[(reserveContentsForAllSyncablePrefabTag) as any] + || !isSyncPrefab() || context.root === this); + if (canDiscardByPrefabRoot()) { + // discard props disallow to synchronize + const isRoot = this._prefab?.root === this; + if (isRoot) { + serializationOutput.writeProperty('_objFlags', this._objFlags); + serializationOutput.writeProperty('_parent', this._parent); + serializationOutput.writeProperty('_prefab', this._prefab); + if (context.customArguments.keepNodeUuid) { + serializationOutput.writeProperty('_id', this._id); + } + // TODO: editorExtrasTag may be a symbol in the future + serializationOutput.writeProperty(editorExtrasTag, this[editorExtrasTag]); + } else { + // should not serialize child node of synchronizable prefab + } + } else { + serializationOutput.writeThis(); + } }; nodeProto._onActiveNode = function (shouldActiveNow: boolean) { @@ -1079,13 +1149,15 @@ nodeProto._onActiveNode = function (shouldActiveNow: boolean) { }; nodeProto._onBatchCreated = function (dontSyncChildPrefab: boolean) { - this.hasChangedFlags = TransformBit.TRS; - this._dirtyFlags |= TransformBit.TRS; + this.hasChangedFlags = TRANSFORMBIT_TRS; + this._dirtyFlags |= TRANSFORMBIT_TRS; const children = this._children; const len = children.length; + let child; for (let i = 0; i < len; ++i) { - children[i]._siblingIndex = i; - children[i]._onBatchCreated(dontSyncChildPrefab); + child = children[i]; + child._siblingIndex = i; + child._onBatchCreated(dontSyncChildPrefab); } // Sync node _lpos, _lrot, _lscale to native @@ -1165,129 +1237,8 @@ nodeProto._instantiate = function (cloned: Node, isSyncedNode: boolean) { return cloned; }; -// Deserialization -const _class2$u = Node; - -// cjh FIXME: replace object.ts with object.jsb.ts -// _applyDecoratedDescriptor(_class2$u.prototype, '_name', [serializable], { -// configurable: true, -// enumerable: true, -// writable: true, -// initializer: function initializer () { -// return ''; -// }, -// }); - -// _applyDecoratedDescriptor(_class2$u.prototype, '_objFlags', [serializable], { -// configurable: true, -// enumerable: true, -// writable: true, -// initializer: function initializer () { -// return 0; -// }, -// }); -// - -const _descriptor$o = _applyDecoratedDescriptor(_class2$u.prototype, '_parent', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return null; - }, -}); - -const _descriptor2$h = _applyDecoratedDescriptor(_class2$u.prototype, '_children', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return []; - }, -}); - -const _descriptor3$b = _applyDecoratedDescriptor(_class2$u.prototype, '_active', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return true; - }, -}); - -const _descriptor4$9 = _applyDecoratedDescriptor(_class2$u.prototype, '_components', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return []; - }, -}); - -const _descriptor5$6 = _applyDecoratedDescriptor(_class2$u.prototype, '_prefab', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return null; - }, -}); - -// Node -const _class2$v = Node; -const _descriptor$p = _applyDecoratedDescriptor(_class2$v.prototype, '_lpos', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return new Vec3(); - }, -}); - -const _descriptor2$i = _applyDecoratedDescriptor(_class2$v.prototype, '_lrot', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return new Quat(); - }, -}); - -const _descriptor3$c = _applyDecoratedDescriptor(_class2$v.prototype, '_lscale', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return new Vec3(1, 1, 1); - }, -}); - -const _descriptor4$a = _applyDecoratedDescriptor(_class2$v.prototype, '_layer', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return Layers.Enum.DEFAULT; - }, -}); - -const _descriptor5$7 = _applyDecoratedDescriptor(_class2$v.prototype, '_euler', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return new Vec3(); - }, -}); - -const _dec2$i = type(Vec3); -_applyDecoratedDescriptor(_class2$v.prototype, 'eulerAngles', [_dec2$i], Object.getOwnPropertyDescriptor(_class2$v.prototype, 'eulerAngles'), _class2$v.prototype); -_applyDecoratedDescriptor(_class2$v.prototype, 'angle', [editable], Object.getOwnPropertyDescriptor(_class2$v.prototype, 'angle'), _class2$v.prototype); -_applyDecoratedDescriptor(_class2$v.prototype, 'layer', [editable], Object.getOwnPropertyDescriptor(_class2$v.prototype, 'layer'), _class2$v.prototype); - // nodeProto._ctor = function (name?: string) { - BaseNode.prototype._ctor.apply(this, arguments); this.__nativeRefs = {}; this.__jsb_ref_id = undefined; this._iN$t = null; @@ -1296,48 +1247,23 @@ nodeProto._ctor = function (name?: string) { this._components = []; this._eventProcessor = new legacyCC.NodeEventProcessor(this); this._uiProps = new NodeUIProperties(this); - this._activeInHierarchyArr = new Uint8Array(jsb.createExternalArrayBuffer(1)); - this._layerArr = new Uint32Array(jsb.createExternalArrayBuffer(4)); - this._layerArr[0] = Layers.Enum.DEFAULT; + + const sharedArrayBuffer = this._getSharedArrayBufferObject(); + // Uint32Array with 3 elements: eventMask, layer, dirtyFlags + this._sharedUint32Arr = new Uint32Array(sharedArrayBuffer, 0, 3); + // Int32Array with 1 element: siblingIndex + this._sharedInt32Arr = new Int32Array(sharedArrayBuffer, 12, 1); + // Uint8Array with 3 elements: activeInHierarchy, active, static + this._sharedUint8Arr = new Uint8Array(sharedArrayBuffer, 16, 3); + // + + this._sharedUint32Arr[1] = Layers.Enum.DEFAULT; // this._sharedUint32Arr[1] is layer this._scene = null; this._prefab = null; // record scene's id when set this node as persist node this._originalSceneId = ''; this._registerListeners(); - // // for deserialization - // // eslint-disable-next-line @typescript-eslint/no-this-alias - // const _this = this; - // // baseNode properties - // _initializerDefineProperty(_this, "_parent", _descriptor$o, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, "_children", _descriptor2$h, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, "_active", _descriptor3$b, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, "_components", _descriptor4$9, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, "_prefab", _descriptor5$6, _assertThisInitialized(_this)); - // // Node properties - // _initializerDefineProperty(_this, "_lpos", _descriptor$p, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, "_lrot", _descriptor2$i, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, "_lscale", _descriptor3$c, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, "_layer", _descriptor4$a, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, "_euler", _descriptor5$7, _assertThisInitialized(_this)); - // // - // defineArrayProxy({ - // owner: this, - // arrElementType: "object", - // arrPropertyName: "_children", - // getArrayElementCB(index: number) { - // return this._getChild(index); - // }, - // getArraySizeCB(): number { - // return this._getChildrenSize(); - // }, - // setArrayElementCB(index: number, val: any): void { - // this._setChild(index, val); - // }, - // setArraySizeCB(size: number): void { - // this._setChildrenSize(size); - // }, - // }); this._children = []; // this._isChildrenRedefined = false; @@ -1347,24 +1273,6 @@ nodeProto._ctor = function (name?: string) { this._lscale = new Vec3(1, 1, 1); this._euler = new Vec3(); - // inner use properties - // FIXME: The following variables for cache will cost more memory per node. - // Do we really need to achieve it in this way? - this._positionCache = new Vec3(); - this._rotationCache = new Quat(); - this._scaleCache = new Vec3(); - - this._worldPositionCache = new Vec3(); - this._worldRotationCache = new Quat(); - this._worldScaleCache = new Vec3(); - this._worldMatrixCache = new Mat4(); - this._eulerAnglesCache = new Vec3(); - this._forwardCache = new Vec3(); - this._upCache = new Vec3(); - this._rightCache = new Vec3(); - this._worldRTCache = new Mat4(); - // - this._registeredNodeEventTypeMask = 0; this.on(NodeEventType.CHILD_ADDED, (child) => { @@ -1394,13 +1302,35 @@ nodeProto._ctor = function (name?: string) { } } }; -// -clsDecorator(Node); -const oldGetWorldRT = nodeProto.getWorldRT; -nodeProto.getWorldRT = function (out?: Mat4) { - const worldRT = oldGetWorldRT.call(this); - const target = out || this._worldRTCache; - Mat4.copy(target, worldRT); - return target; -}; +// handle meta data, it is generated automatically +const NodeProto = Node.prototype; +const _persistNodeDescriptor = Object.getOwnPropertyDescriptor(NodeProto, '_persistNode'); +property(NodeProto, '_persistNode', _persistNodeDescriptor); +const nameDescriptor = Object.getOwnPropertyDescriptor(NodeProto, 'name'); +editable(NodeProto, 'name', nameDescriptor); +const childrenDescriptor = Object.getOwnPropertyDescriptor(NodeProto, 'children'); +editable(NodeProto, 'children', childrenDescriptor); +const activeDescriptor = Object.getOwnPropertyDescriptor(NodeProto, 'active'); +editable(NodeProto, 'active', activeDescriptor); +const activeInHierarchyDescriptor = Object.getOwnPropertyDescriptor(NodeProto, 'activeInHierarchy'); +editable(NodeProto, 'activeInHierarchy', activeInHierarchyDescriptor); +const parentDescriptor = Object.getOwnPropertyDescriptor(NodeProto, 'parent'); +editable(NodeProto, 'parent', parentDescriptor); +serializable(NodeProto, '_parent'); +serializable(NodeProto, '_children'); +serializable(NodeProto, '_active'); +serializable(NodeProto, '_components'); +serializable(NodeProto, '_prefab'); +serializable(NodeProto, '_lpos'); +serializable(NodeProto, '_lrot'); +serializable(NodeProto, '_lscale'); +serializable(NodeProto, '_layer'); +serializable(NodeProto, '_euler'); +const eulerAnglesDescriptor = Object.getOwnPropertyDescriptor(NodeProto, 'eulerAngles'); +type(Vec3)(NodeProto, 'eulerAngles', eulerAnglesDescriptor); +const angleDescriptor = Object.getOwnPropertyDescriptor(NodeProto, 'angle'); +editable(NodeProto, 'angle', angleDescriptor); +const layerDescriptor = Object.getOwnPropertyDescriptor(NodeProto, 'layer'); +editable(NodeProto, 'layer', layerDescriptor); +ccclass('cc.Node')(Node); diff --git a/cocos/core/scene-graph/node.ts b/cocos/core/scene-graph/node.ts index 104e45b454..20335dcbc0 100644 --- a/cocos/core/scene-graph/node.ts +++ b/cocos/core/scene-graph/node.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module scene-graph - */ - import { ccclass, editable, serializable, type, } from 'cc.decorator'; @@ -50,61 +45,9 @@ const m3_1 = new Mat3(); const m3_scaling = new Mat3(); const m4_1 = new Mat4(); const dirtyNodes: any[] = []; -const view_tmp:[Uint32Array, number] = [] as any; -class BookOfChange { - private _chunks: Uint32Array[] = []; - private _freelists: number[][] = []; - - // these should match with native: cocos/renderer/pipeline/helper/SharedMemory.h Node.getHasChangedFlags - private static CAPACITY_PER_CHUNK = 256; - - constructor () { - this._createChunk(); - } - - public alloc () { - const chunkCount = this._freelists.length; - for (let i = 0; i < chunkCount; ++i) { - if (!this._freelists[i].length) continue; - return this._createView(i); - } - this._createChunk(); - return this._createView(chunkCount); - } - - public free (view: Uint32Array, idx: number) { - const chunkCount = this._freelists.length; - for (let i = 0; i < chunkCount; ++i) { - if (this._chunks[i] !== view) continue; - this._freelists[i].push(idx); - return; - } - } - - public clear () { - const chunkCount = this._chunks.length; - for (let i = 0; i < chunkCount; ++i) { - this._chunks[i].fill(0); - } - } - - private _createChunk () { - this._chunks.push(new Uint32Array(BookOfChange.CAPACITY_PER_CHUNK)); - const freelist: number[] = []; - for (let i = BookOfChange.CAPACITY_PER_CHUNK - 1; i >= 0; i--) freelist.push(i); - this._freelists.push(freelist); - } - - private _createView (chunkIdx: number): [Uint32Array, number] { - view_tmp[0] = this._chunks[chunkIdx]; - view_tmp[1] = this._freelists[chunkIdx].pop()!; - return view_tmp; - } -} - -const bookOfChange = new BookOfChange(); const reserveContentsForAllSyncablePrefabTag = Symbol('ReserveContentsForAllSyncablePrefab'); +let globalFlagChangeVersion = 0; /** * @zh @@ -156,12 +99,12 @@ export class Node extends BaseNode implements CustomSerializable { public static TransformBit = TransformBit; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public static reserveContentsForAllSyncablePrefabTag = reserveContentsForAllSyncablePrefabTag; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _uiProps = new NodeUIProperties(this); @@ -173,7 +116,7 @@ export class Node extends BaseNode implements CustomSerializable { private static ClearRound = 1000; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _static = false; @@ -205,19 +148,12 @@ export class Node extends BaseNode implements CustomSerializable { private _dirtyFlags = TransformBit.NONE; // does the world transform need to update? protected _eulerDirty = false; - protected declare _hasChangedFlagsChunk: Uint32Array; // has the transform been updated in this frame? - protected declare _hasChangedFlagsOffset: number; - protected declare _hasChangedFlags: Uint32Array; + + protected _flagChangeVersion = 0; + protected _hasChangedFlags = 0; constructor (name?: string) { super(name); - - const [chunk, offset] = bookOfChange.alloc(); - this._hasChangedFlagsChunk = chunk; - this._hasChangedFlagsOffset = offset; - const flagBuffer = new Uint32Array(chunk.buffer, chunk.byteOffset + offset * 4, 1); - this._hasChangedFlags = flagBuffer; - this._pos = new Vec3(); this._rot = new Quat(); this._scale = new Vec3(1, 1, 1); @@ -233,9 +169,7 @@ export class Node extends BaseNode implements CustomSerializable { } protected _onPreDestroy () { - const result = this._onPreDestroyBase(); - bookOfChange.free(this._hasChangedFlagsChunk, this._hasChangedFlagsOffset); - return result; + return this._onPreDestroyBase(); } /** @@ -434,13 +368,17 @@ export class Node extends BaseNode implements CustomSerializable { * @zh 这个节点的空间变换信息在当前帧内是否有变过? */ get hasChangedFlags () { - return this._hasChangedFlagsChunk[this._hasChangedFlagsOffset] as TransformBit; + return this._flagChangeVersion === globalFlagChangeVersion ? this._hasChangedFlags : 0; } set hasChangedFlags (val: number) { - this._hasChangedFlagsChunk[this._hasChangedFlagsOffset] = val; + this._flagChangeVersion = globalFlagChangeVersion; + this._hasChangedFlags = val; } + /** + * @internal + */ public [serializeTag] (serializationOutput: SerializationOutput, context: SerializationContext) { if (!EDITOR) { serializationOutput.writeThis(); @@ -469,6 +407,9 @@ export class Node extends BaseNode implements CustomSerializable { serializationOutput.writeProperty('_objFlags', this._objFlags); serializationOutput.writeProperty('_parent', this._parent); serializationOutput.writeProperty('_prefab', this._prefab); + if (context.customArguments.keepNodeUuid) { + serializationOutput.writeProperty('_id', this._id); + } // TODO: editorExtrasTag may be a symbol in the future serializationOutput.writeProperty(editorExtrasTag, this[editorExtrasTag]); } else { @@ -495,7 +436,7 @@ export class Node extends BaseNode implements CustomSerializable { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _onSetParent (oldParent: this | null, keepWorldTransform: boolean) { super._onSetParent(oldParent, keepWorldTransform); @@ -528,7 +469,7 @@ export class Node extends BaseNode implements CustomSerializable { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _onBatchCreated (dontSyncChildPrefab: boolean) { this.hasChangedFlags = TransformBit.TRS; @@ -541,7 +482,7 @@ export class Node extends BaseNode implements CustomSerializable { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _onBeforeSerialize () { // eslint-disable-next-line @typescript-eslint/no-unused-expressions @@ -549,7 +490,7 @@ export class Node extends BaseNode implements CustomSerializable { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _onPostActivated (active: boolean) { if (active) { // activated @@ -644,10 +585,6 @@ export class Node extends BaseNode implements CustomSerializable { this.setWorldRotation(q_a); } - protected _setDirtyNode (idx: number, currNode: this) { - dirtyNodes[idx] = currNode; - } - /** * @en Invalidate the world transform information * for this node and all its children recursively @@ -659,45 +596,24 @@ export class Node extends BaseNode implements CustomSerializable { let j = 0; let l = 0; let cur: this; - let c : this; - let flag = 0; let children:this[]; let hasChangedFlags = 0; const childDirtyBit = dirtyBit | TransformBit.POSITION; - // NOTE: inflate function - // ``` - // this._setDirtyNode(0, this); - // ``` dirtyNodes[0] = this; while (i >= 0) { cur = dirtyNodes[i--]; - hasChangedFlags = cur._hasChangedFlags[0]; - flag = cur._dirtyFlags; - if (cur.isValid && (flag & hasChangedFlags & dirtyBit) !== dirtyBit) { - // NOTE: inflate procedure - // ``` - // cur._dirtyFlags |= dirtyBit; - // ``` - flag |= dirtyBit; - cur._dirtyFlags = flag; + hasChangedFlags = cur.hasChangedFlags; + if (cur.isValid && (cur._dirtyFlags & hasChangedFlags & dirtyBit) !== dirtyBit) { + cur._dirtyFlags |= dirtyBit; - // NOTE: inflate attribute accessor - // ``` - // cur.hasChangedFlags = hasChangedFlags | dirtyBit; - // ``` - cur._hasChangedFlags[0] = hasChangedFlags | dirtyBit; + cur.hasChangedFlags = hasChangedFlags | dirtyBit; children = cur._children; l = children.length; for (j = 0; j < l; j++) { - c = children[j]; - // NOTE: inflate function - // ``` - // this._setDirtyNode(0, c); - // ``` - dirtyNodes[++i] = c; + dirtyNodes[++i] = children[j]; } } dirtyBit = childDirtyBit; @@ -716,7 +632,7 @@ export class Node extends BaseNode implements CustomSerializable { let i = 0; while (cur && cur._dirtyFlags) { // top level node - this._setDirtyNode(i++, cur); + dirtyNodes[i++] = cur; cur = cur._parent; } let child: this; let dirtyBits = 0; @@ -815,15 +731,17 @@ export class Node extends BaseNode implements CustomSerializable { } /** - * @en Set rotation in local coordinate system with a quaternion representing the rotation - * @zh 用四元数设置本地旋转 + * @en Set rotation in local coordinate system with a quaternion representing the rotation. + * Please make sure the rotation is normalized. + * @zh 用四元数设置本地旋转, 请确保设置的四元数已归一化。 * @param rotation Rotation in quaternion */ public setRotation (rotation: Readonly): void; /** - * @en Set rotation in local coordinate system with a quaternion representing the rotation - * @zh 用四元数设置本地旋转 + * @en Set rotation in local coordinate system with a quaternion representing the rotation. + * Please make sure the rotation is normalized. + * @zh 用四元数设置本地旋转, 请确保设置的四元数已归一化。 * @param x X value in quaternion * @param y Y value in quaternion * @param z Z value in quaternion @@ -950,7 +868,7 @@ export class Node extends BaseNode implements CustomSerializable { let cur = this; let i = 0; while (cur._parent) { - this._setDirtyNode(i++, cur); + dirtyNodes[i++] = cur; cur = cur._parent; } while (i >= 0) { @@ -1258,7 +1176,7 @@ export class Node extends BaseNode implements CustomSerializable { * 清除所有节点的脏标记。 */ public static resetHasChangedFlags () { - bookOfChange.clear(); + globalFlagChangeVersion += 1; } /** diff --git a/cocos/core/scene-graph/scene-globals.jsb.ts b/cocos/core/scene-graph/scene-globals.jsb.ts index 0239b97d8a..c2177c6920 100644 --- a/cocos/core/scene-graph/scene-globals.jsb.ts +++ b/cocos/core/scene-graph/scene-globals.jsb.ts @@ -20,10 +20,10 @@ */ import { - ccclass, displayName, + displayName, editable, formerlySerializedAs, - help, range, + range, readOnly, serializable, tooltip, @@ -31,16 +31,13 @@ import { visible // @ts-ignore } from 'cc.decorator'; -import { - _applyDecoratedDescriptor, - _assertThisInitialized, - _initializerDefineProperty, -} from '../data/utils/decorator-jsb-utils'; import { legacyCC } from '../global-exports'; -import { Color, Vec2, Vec3 } from '../math'; import { CCFloat, CCInteger } from '../data'; import { TextureCube } from '../assets/texture-cube'; import { Enum } from '../value-types'; +import { ccclass, displayOrder, rangeMin, rangeStep, slide } from '../data/decorators'; +import { EnvironmentLightingType } from '../renderer/scene'; +import { Material } from '../assets/material'; /** * @zh @@ -144,445 +141,33 @@ export const ShadowType = Enum({ ShadowMap: 1, }); -/** - * @en Environment lighting information in the Scene - * @zh 场景的环境光照相关信息 - */ // @ts-ignore export const AmbientInfo = jsb.AmbientInfo; legacyCC.AmbientInfo = AmbientInfo; -(function () { - const ambientInfoProto: any = AmbientInfo.prototype; - const ambientInfoDecorator = ccclass('cc.AmbientInfo'); - const _class2$w = AmbientInfo; - const _descriptor$q = _applyDecoratedDescriptor(_class2$w.prototype, '_skyColor', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return new Color(51, 128, 204, 1.0); - }, - }); - - const _descriptor2$j = _applyDecoratedDescriptor(_class2$w.prototype, '_skyIllum', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return 20000.0; // cjh FIXME: Ambient.SKY_ILLUM; - }, - }); - - const _descriptor3$d = _applyDecoratedDescriptor(_class2$w.prototype, '_groundAlbedo', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return new Color(51, 51, 51, 255); - }, - }); - - const _dec2$j = type(CCFloat); - - _applyDecoratedDescriptor(_class2$w.prototype, 'skyColor', [editable], Object.getOwnPropertyDescriptor(_class2$w.prototype, 'skyColor'), _class2$w.prototype); - _applyDecoratedDescriptor(_class2$w.prototype, 'skyIllum', [editable, _dec2$j], Object.getOwnPropertyDescriptor(_class2$w.prototype, 'skyIllum'), _class2$w.prototype); - _applyDecoratedDescriptor(_class2$w.prototype, 'groundAlbedo', [editable], Object.getOwnPropertyDescriptor(_class2$w.prototype, 'groundAlbedo'), _class2$w.prototype); - - ambientInfoProto._ctor = function () { - // _initializerDefineProperty(this, "_skyColor", _descriptor$q, this); - // _initializerDefineProperty(this, "_skyIllum", _descriptor2$j, this); - // _initializerDefineProperty(this, "_groundAlbedo", _descriptor3$d, this); - }; - - ambientInfoDecorator(AmbientInfo); - -})(); - -/** - * @en Skybox related information - * @zh 天空盒相关信息 - */ // @ts-ignore export const SkyboxInfo = jsb.SkyboxInfo; legacyCC.SkyboxInfo = SkyboxInfo; -(function () { - const skyboxInfoProto: any = SkyboxInfo.prototype; - const skyboxInfoDecorator = ccclass('cc.SkyboxInfo'); - const _dec16$1 = type(TextureCube); - const _dec14$1 = type(TextureCube); - const _dec17$1 = type(TextureCube); - const _dec18$1 = type(TextureCube); - const _dec15$1 = formerlySerializedAs('_envmap'); - const _dec19$1 = visible(); - const _dec20$1 = tooltip(); - const _dec21$1 = tooltip(); - const _dec22$1 = tooltip(); - const _dec23$1 = tooltip(); - const _dec24$1 = type(TextureCube); - const _dec25$1 = tooltip(); - const _dec26$1 = visible(); - const _dec27$1 = type(TextureCube); - const _class5$2 = SkyboxInfo; - - const _descriptor7$2 = _applyDecoratedDescriptor(_class5$2.prototype, "_applyDiffuseMap", [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return false; - } - }); - - const _descriptor8$1 = _applyDecoratedDescriptor(_class5$2.prototype, "_envmap", [serializable, _dec14$1, _dec15$1], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return null; - } - }); - - const _descriptor8$2 = _applyDecoratedDescriptor(_class5$2.prototype, "_envmapHDR", [serializable, _dec14$1, _dec15$1], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return null; - } - }); - - const _descriptor9$1 = _applyDecoratedDescriptor(_class5$2.prototype, "_envmapLDR", [serializable, _dec16$1], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return null; - } - }); - - const _descriptor10$1 = _applyDecoratedDescriptor(_class5$2.prototype, "_diffuseMapHDR", [serializable, _dec17$1], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return null; - } - }); - - const _descriptor11$1 = _applyDecoratedDescriptor(_class5$2.prototype, "_diffuseMapLDR", [serializable, _dec18$1], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return null; - } - }); - - const _descriptor12$1 = _applyDecoratedDescriptor(_class5$2.prototype, "_enabled", [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return false; - } - }); - - const _descriptor13$1 = _applyDecoratedDescriptor(_class5$2.prototype, "_useIBL", [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return false; - } - }); - - const _descriptor14$1 = _applyDecoratedDescriptor(_class5$2.prototype, "_useHDR", [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return true; - } - }); - - _applyDecoratedDescriptor(_class5$2.prototype, "applyDiffuseMap", [_dec19$1, editable, _dec20$1], Object.getOwnPropertyDescriptor(_class5$2.prototype, "applyDiffuseMap"), _class5$2.prototype); - _applyDecoratedDescriptor(_class5$2.prototype, "enabled", [editable, _dec21$1], Object.getOwnPropertyDescriptor(_class5$2.prototype, "enabled"), _class5$2.prototype); - _applyDecoratedDescriptor(_class5$2.prototype, "useIBL", [editable, _dec22$1], Object.getOwnPropertyDescriptor(_class5$2.prototype, "useIBL"), _class5$2.prototype); - _applyDecoratedDescriptor(_class5$2.prototype, "useHDR", [editable, _dec23$1], Object.getOwnPropertyDescriptor(_class5$2.prototype, "useHDR"), _class5$2.prototype); - _applyDecoratedDescriptor(_class5$2.prototype, "envmap", [editable, _dec24$1, _dec25$1], Object.getOwnPropertyDescriptor(_class5$2.prototype, "envmap"), _class5$2.prototype); - _applyDecoratedDescriptor(_class5$2.prototype, "diffuseMap", [_dec26$1, editable, readOnly, _dec27$1], Object.getOwnPropertyDescriptor(_class5$2.prototype, "diffuseMap"), _class5$2.prototype); - - - skyboxInfoProto._ctor = function () { - // _initializerDefineProperty(this, "_envmap", _descriptor4$b, this); - // _initializerDefineProperty(this, "_isRGBE", _descriptor5$8, this); - // _initializerDefineProperty(this, "_enabled", _descriptor6$3, this); - // _initializerDefineProperty(this, "_useIBL", _descriptor7$3, this); - }; - - skyboxInfoDecorator(SkyboxInfo); - -})(); - -/** - * @zh 全局雾相关信息 - * @en Global fog info - */ // @ts-ignore export const FogInfo = jsb.FogInfo; legacyCC.FogInfo = FogInfo; -(function () { - const fogInfoProto: any = FogInfo.prototype; - const fogInfoDecorator = ccclass('cc.FogInfo'); - const _class8$1 = FogInfo; - - _applyDecoratedDescriptor(_class8$1.prototype, '_type', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return FogType.LINEAR; - }, - }); - _applyDecoratedDescriptor(_class8$1.prototype, '_fogColor', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return new Color('#C8C8C8'); - }, - }); - _applyDecoratedDescriptor(_class8$1.prototype, '_enabled', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return false; - }, - }); - - _applyDecoratedDescriptor(_class8$1.prototype, '_fogDensity', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return 0.3; - }, - }); - _applyDecoratedDescriptor(_class8$1.prototype, '_fogStart', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return 0.5; - }, - }); - _applyDecoratedDescriptor(_class8$1.prototype, '_fogEnd', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return 300; - }, - }); - _applyDecoratedDescriptor(_class8$1.prototype, '_fogAtten', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return 5; - }, - }); - _applyDecoratedDescriptor(_class8$1.prototype, '_fogTop', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return 1.5; - }, - }); - _applyDecoratedDescriptor(_class8$1.prototype, '_fogRange', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return 1.2; - }, - }); - - // , _dec8$1 = visible(), _dec9$1 = type(CCFloat), _dec10$1 = range(), _dec11$1 = rangeStep(), _dec12$1 = displayOrder(), _dec13$1 = visible(), _dec14$1 = type(CCFloat), _dec15$1 = rangeStep(), _dec16$1 = displayOrder(), _dec17$1 = visible(), _dec18$1 = type(CCFloat), _dec19$1 = rangeStep(), _dec20$1 = displayOrder(), _dec21$1 = visible(), _dec22$1 = type(CCFloat), _dec23$1 = rangeMin(), _dec24$1 = rangeStep(), _dec25$1 = displayOrder(), _dec26$1 = visible(), _dec27$1 = type(CCFloat), _dec28$1 = rangeStep(), _dec29$1 = displayOrder(), _dec30$1 = visible(), _dec31$1 = type(CCFloat), _dec32 = rangeStep(), _dec33 = displayOrder() - - // _applyDecoratedDescriptor(_class8$1.prototype, "enabled", [editable], Object.getOwnPropertyDescriptor(_class8$1.prototype, "enabled"), _class8$1.prototype); - // _applyDecoratedDescriptor(_class8$1.prototype, "fogColor", [editable], Object.getOwnPropertyDescriptor(_class8$1.prototype, "fogColor"), _class8$1.prototype); - // _applyDecoratedDescriptor(_class8$1.prototype, "type", [editable, _dec7$1], Object.getOwnPropertyDescriptor(_class8$1.prototype, "type"), _class8$1.prototype); - // _applyDecoratedDescriptor(_class8$1.prototype, "fogDensity", [_dec8$1, _dec9$1, _dec10$1, _dec11$1, slide, _dec12$1], Object.getOwnPropertyDescriptor(_class8$1.prototype, "fogDensity"), _class8$1.prototype); - // _applyDecoratedDescriptor(_class8$1.prototype, "fogStart", [_dec13$1, _dec14$1, _dec15$1, _dec16$1], Object.getOwnPropertyDescriptor(_class8$1.prototype, "fogStart"), _class8$1.prototype); - // _applyDecoratedDescriptor(_class8$1.prototype, "fogEnd", [_dec17$1, _dec18$1, _dec19$1, _dec20$1], Object.getOwnPropertyDescriptor(_class8$1.prototype, "fogEnd"), _class8$1.prototype); - // _applyDecoratedDescriptor(_class8$1.prototype, "fogAtten", [_dec21$1, _dec22$1, _dec23$1, _dec24$1, _dec25$1], Object.getOwnPropertyDescriptor(_class8$1.prototype, "fogAtten"), _class8$1.prototype); - // _applyDecoratedDescriptor(_class8$1.prototype, "fogTop", [_dec26$1, _dec27$1, _dec28$1, _dec29$1], Object.getOwnPropertyDescriptor(_class8$1.prototype, "fogTop"), _class8$1.prototype), _applyDecoratedDescriptor(_class8$1.prototype, "fogRange", [_dec30$1, _dec31$1, _dec32, _dec33], Object.getOwnPropertyDescriptor(_class8$1.prototype, "fogRange"), _class8$1.prototype)), _class8$1)) || _class7$1); - - fogInfoDecorator(FogInfo); -})(); - -/** - * @en Scene level planar shadow related information - * @zh 平面阴影相关信息 - */ // @ts-ignore export const ShadowsInfo = jsb.ShadowsInfo; legacyCC.ShadowsInfo = ShadowsInfo; -(function () { - const shadowInfoDecorator = ccclass('cc.ShadowsInfo'); - - const _class11$1 = ShadowsInfo; - const _descriptor17$1 = _applyDecoratedDescriptor(_class11$1.prototype, '_type', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return ShadowType.Planar; - }, - }); - const _descriptor18$1 = _applyDecoratedDescriptor(_class11$1.prototype, '_enabled', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return false; - }, - }); - - const _descriptor19$1 = _applyDecoratedDescriptor(_class11$1.prototype, '_normal', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return new Vec3(0, 1, 0); - }, - }); - - const _descriptor20$1 = _applyDecoratedDescriptor(_class11$1.prototype, '_distance', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return 0; - }, - }); - - const _descriptor21$1 = _applyDecoratedDescriptor(_class11$1.prototype, '_shadowColor', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return new Color(0, 0, 0, 76); - }, - }); - - const _descriptor29$1 = _applyDecoratedDescriptor(_class11$1.prototype, '_maxReceived', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return 4; - }, - }); - - const _descriptor30$11 = _applyDecoratedDescriptor(_class11$1.prototype, '_size', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return new Vec2(512, 512); - }, - }); - - shadowInfoDecorator(ShadowsInfo); - -})(); - -// OctreeInfo // @ts-ignore export const OctreeInfo = jsb.OctreeInfo; legacyCC.OctreeInfo = OctreeInfo; -(function () { - const octreeInfoDecorator = ccclass('cc.OctreeInfo'); - const _class14$1 = OctreeInfo; - var DEFAULT_WORLD_MIN_POS = new Vec3(-1024.0, -1024.0, -1024.0); - var DEFAULT_WORLD_MAX_POS = new Vec3(1024.0, 1024.0, 1024.0); - var DEFAULT_OCTREE_DEPTH = 8; - - const _dec116 = help(); - const _dec117 = tooltip(); - const _dec118 = tooltip(); - const _dec119 = displayName(); - const _dec120 = tooltip(); - const _dec121 = displayName(); - const _dec122 = range(); - const _dec123 = type(CCInteger); - const _dec124 = tooltip(); - - const _descriptor43 = _applyDecoratedDescriptor(_class14$1.prototype, "_enabled", [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return false; - } - }); - - const _descriptor44 = _applyDecoratedDescriptor(_class14$1.prototype, "_minPos", [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return new Vec3(DEFAULT_WORLD_MIN_POS); - } - }); - - const _descriptor45 = _applyDecoratedDescriptor(_class14$1.prototype, "_maxPos", [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return new Vec3(DEFAULT_WORLD_MAX_POS); - } - }); - - const _descriptor46 = _applyDecoratedDescriptor(_class14$1.prototype, "_depth", [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return DEFAULT_OCTREE_DEPTH; - } - }); - - _applyDecoratedDescriptor(_class14$1.prototype, "enabled", [editable, _dec117], Object.getOwnPropertyDescriptor(_class14$1.prototype, "enabled"), _class14$1.prototype); - _applyDecoratedDescriptor(_class14$1.prototype, "minPos", [editable, _dec118, _dec119], Object.getOwnPropertyDescriptor(_class14$1.prototype, "minPos"), _class14$1.prototype); - _applyDecoratedDescriptor(_class14$1.prototype, "maxPos", [editable, _dec120, _dec121], Object.getOwnPropertyDescriptor(_class14$1.prototype, "maxPos"), _class14$1.prototype); - _applyDecoratedDescriptor(_class14$1.prototype, "depth", [editable, _dec122, _dec123, _dec124], Object.getOwnPropertyDescriptor(_class14$1.prototype, "depth"), _class14$1.prototype); - - octreeInfoDecorator(OctreeInfo); -})(); - -/** - * @en All scene related global parameters, it affects all content in the corresponding scene - * @zh 各类场景级别的渲染参数,将影响全场景的所有物体 - */ // @ts-ignore export const SceneGlobals = jsb.SceneGlobals; legacyCC.SceneGlobals = SceneGlobals; (function () { const sceneGlobalsProto: any = SceneGlobals.prototype; - const sceneGlobalsDecorator = ccclass('cc.SceneGlobals'); sceneGlobalsProto._ctor = function () { this._ambientRef = null; @@ -663,42 +248,206 @@ legacyCC.SceneGlobals = SceneGlobals; this.setOctreeInfo(v); }, }); - - const _class14$1 = SceneGlobals; - const _descriptor32$1 = _applyDecoratedDescriptor(_class14$1.prototype, 'ambient', [serializable, editable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return new AmbientInfo(); - }, - }); - const _descriptor33$1 = _applyDecoratedDescriptor(_class14$1.prototype, 'shadows', [serializable, editable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return new ShadowsInfo(); - }, - }); - const _descriptor34$1 = _applyDecoratedDescriptor(_class14$1.prototype, '_skybox', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return new SkyboxInfo(); - }, - }); - const _descriptor35$1 = _applyDecoratedDescriptor(_class14$1.prototype, 'fog', [editable, serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return new FogInfo(); - }, - }); - - // _applyDecoratedDescriptor(_class14$1.prototype, "skybox", [editable, _dec62], Object.getOwnPropertyDescriptor(_class14$1.prototype, "skybox"), _class14$1.prototype); - - sceneGlobalsDecorator(SceneGlobals); })(); + +// handle meta data, it is generated automatically + +const SceneGlobalsProto = SceneGlobals.prototype; +editable(SceneGlobalsProto, 'ambient'); +serializable(SceneGlobalsProto, 'ambient'); +editable(SceneGlobalsProto, 'shadows'); +serializable(SceneGlobalsProto, 'shadows'); +serializable(SceneGlobalsProto, '_skybox'); +serializable(SceneGlobalsProto, 'fog'); +editable(SceneGlobalsProto, 'fog'); +const skyboxDescriptor = Object.getOwnPropertyDescriptor(SceneGlobalsProto, 'skybox'); +type(SkyboxInfo)(SceneGlobalsProto, 'skybox', skyboxDescriptor); +editable(SceneGlobalsProto, 'skybox', skyboxDescriptor); +serializable(SceneGlobalsProto, 'octree'); +editable(SceneGlobalsProto, 'octree'); +ccclass('cc.SceneGlobals')(SceneGlobals); + +const OctreeInfoProto = OctreeInfo.prototype; +serializable(OctreeInfoProto, '_enabled'); +serializable(OctreeInfoProto, '_minPos'); +serializable(OctreeInfoProto, '_maxPos'); +serializable(OctreeInfoProto, '_depth'); +const enabledDescriptor = Object.getOwnPropertyDescriptor(OctreeInfoProto, 'enabled'); +tooltip('i18n:octree_culling.enabled')(OctreeInfoProto, 'enabled', enabledDescriptor); +editable(OctreeInfoProto, 'enabled', enabledDescriptor); +const minPosDescriptor = Object.getOwnPropertyDescriptor(OctreeInfoProto, 'minPos'); +displayName('World MinPos')(OctreeInfoProto, 'minPos', minPosDescriptor); +tooltip('i18n:octree_culling.minPos')(OctreeInfoProto, 'minPos', minPosDescriptor); +editable(OctreeInfoProto, 'minPos', minPosDescriptor); +const maxPosDescriptor = Object.getOwnPropertyDescriptor(OctreeInfoProto, 'maxPos'); +displayName('World MaxPos')(OctreeInfoProto, 'maxPos', maxPosDescriptor); +tooltip('i18n:octree_culling.maxPos')(OctreeInfoProto, 'maxPos', maxPosDescriptor); +editable(OctreeInfoProto, 'maxPos', maxPosDescriptor); +const depthDescriptor = Object.getOwnPropertyDescriptor(OctreeInfoProto, 'depth'); +tooltip('i18n:octree_culling.depth')(OctreeInfoProto, 'depth', depthDescriptor); +type(CCInteger)(OctreeInfoProto, 'depth', depthDescriptor); +slide(OctreeInfoProto, 'depth', depthDescriptor); +range([4, 12, 1])(OctreeInfoProto, 'depth', depthDescriptor); +editable(OctreeInfoProto, 'depth', depthDescriptor); +ccclass('cc.OctreeInfo')(OctreeInfo); + +const ShadowsInfoProto = ShadowsInfo.prototype; +serializable(ShadowsInfoProto, '_enabled'); +serializable(ShadowsInfoProto, '_type'); +serializable(ShadowsInfoProto, '_normal'); +serializable(ShadowsInfoProto, '_distance'); +serializable(ShadowsInfoProto, '_shadowColor'); +serializable(ShadowsInfoProto, '_maxReceived'); +serializable(ShadowsInfoProto, '_size'); +const shadowEnabledDescriptor = Object.getOwnPropertyDescriptor(ShadowsInfoProto, 'enabled'); +tooltip('i18n:shadow.enabled')(ShadowsInfoProto, 'enabled', shadowEnabledDescriptor); +editable(ShadowsInfoProto, 'enabled', shadowEnabledDescriptor); +const typeDescriptor = Object.getOwnPropertyDescriptor(ShadowsInfoProto, 'type'); +type(ShadowType)(ShadowsInfoProto, 'type', typeDescriptor); +editable(ShadowsInfoProto, 'type', typeDescriptor); +const shadowColorDescriptor = Object.getOwnPropertyDescriptor(ShadowsInfoProto, 'shadowColor'); +visible(function (this) { /* Need to copy source code */ })(ShadowsInfoProto, 'shadowColor', shadowColorDescriptor); +const planeDirectionDescriptor = Object.getOwnPropertyDescriptor(ShadowsInfoProto, 'planeDirection'); +tooltip('i18n:shadow.planeDirection')(ShadowsInfoProto, 'planeDirection', planeDirectionDescriptor); +visible(function (this) { /* Need to copy source code */ })(ShadowsInfoProto, 'planeDirection', planeDirectionDescriptor); +const planeHeightDescriptor = Object.getOwnPropertyDescriptor(ShadowsInfoProto, 'planeHeight'); +tooltip('i18n:shadow.planeHeight')(ShadowsInfoProto, 'planeHeight', planeHeightDescriptor); +visible(function (this) { /* Need to copy source code */ })(ShadowsInfoProto, 'planeHeight', planeHeightDescriptor); +type(CCFloat)(ShadowsInfoProto, 'planeHeight', planeHeightDescriptor); +editable(ShadowsInfoProto, 'planeHeight', planeHeightDescriptor); +const maxReceivedDescriptor = Object.getOwnPropertyDescriptor(ShadowsInfoProto, 'maxReceived'); +visible(function (this) { /* Need to copy source code */ })(ShadowsInfoProto, 'maxReceived', maxReceivedDescriptor); +tooltip('i18n:shadow.maxReceived')(ShadowsInfoProto, 'maxReceived', maxReceivedDescriptor); +type(CCInteger)(ShadowsInfoProto, 'maxReceived', maxReceivedDescriptor); +const shadowMapSizeDescriptor = Object.getOwnPropertyDescriptor(ShadowsInfoProto, 'shadowMapSize'); +visible(function (this) { /* Need to copy source code */ })(ShadowsInfoProto, 'shadowMapSize', shadowMapSizeDescriptor); +tooltip('i18n:shadow.shadowMapSize')(ShadowsInfoProto, 'shadowMapSize', shadowMapSizeDescriptor); +type(ShadowSize)(ShadowsInfoProto, 'shadowMapSize', shadowMapSizeDescriptor); +ccclass('cc.ShadowsInfo')(ShadowsInfo); + +const FogInfoProto = FogInfo.prototype; +serializable(FogInfoProto, '_type'); +serializable(FogInfoProto, '_fogColor'); +serializable(FogInfoProto, '_enabled'); +serializable(FogInfoProto, '_fogDensity'); +serializable(FogInfoProto, '_fogStart'); +serializable(FogInfoProto, '_fogEnd'); +serializable(FogInfoProto, '_fogAtten'); +serializable(FogInfoProto, '_fogTop'); +serializable(FogInfoProto, '_fogRange'); +serializable(FogInfoProto, '_accurate'); +const fogEnabledDescriptor = Object.getOwnPropertyDescriptor(FogInfoProto, 'enabled'); +displayOrder(0)(FogInfoProto, 'enabled', fogEnabledDescriptor); +tooltip('i18n:fog.enabled')(FogInfoProto, 'enabled', fogEnabledDescriptor); +editable(FogInfoProto, 'enabled', fogEnabledDescriptor); +const accurateDescriptor = Object.getOwnPropertyDescriptor(FogInfoProto, 'accurate'); +displayOrder(0)(FogInfoProto, 'accurate', accurateDescriptor); +tooltip('i18n:fog.accurate')(FogInfoProto, 'accurate', accurateDescriptor); +editable(FogInfoProto, 'accurate', accurateDescriptor); +const fogColorDescriptor = Object.getOwnPropertyDescriptor(FogInfoProto, 'fogColor'); +tooltip('i18n:fog.fogColor')(FogInfoProto, 'fogColor', fogColorDescriptor); +editable(FogInfoProto, 'fogColor', fogColorDescriptor); +const fogTypeDescriptor = Object.getOwnPropertyDescriptor(FogInfoProto, 'type'); +tooltip('i18n:fog.type')(FogInfoProto, 'type', fogTypeDescriptor); +displayOrder(1)(FogInfoProto, 'type', fogTypeDescriptor); +type(FogType)(FogInfoProto, 'type', fogTypeDescriptor); +editable(FogInfoProto, 'type', fogTypeDescriptor); +const fogDensityDescriptor = Object.getOwnPropertyDescriptor(FogInfoProto, 'fogDensity'); +tooltip('i18n:fog.fogDensity')(FogInfoProto, 'fogDensity', fogDensityDescriptor); +slide(FogInfoProto, 'fogDensity', fogDensityDescriptor); +rangeStep(0.01)(FogInfoProto, 'fogDensity', fogDensityDescriptor); +range([0, 1])(FogInfoProto, 'fogDensity', fogDensityDescriptor); +type(CCFloat)(FogInfoProto, 'fogDensity', fogDensityDescriptor); +visible(function (this) { /* Need to copy source code */ })(FogInfoProto, 'fogDensity', fogDensityDescriptor); +const fogStartDescriptor = Object.getOwnPropertyDescriptor(FogInfoProto, 'fogStart'); +tooltip('i18n:fog.fogStart')(FogInfoProto, 'fogStart', fogStartDescriptor); +rangeStep(0.01)(FogInfoProto, 'fogStart', fogStartDescriptor); +type(CCFloat)(FogInfoProto, 'fogStart', fogStartDescriptor); +visible(function (this) { /* Need to copy source code */ })(FogInfoProto, 'fogStart', fogStartDescriptor); +const fogEndDescriptor = Object.getOwnPropertyDescriptor(FogInfoProto, 'fogEnd'); +tooltip('i18n:fog.fogEnd')(FogInfoProto, 'fogEnd', fogEndDescriptor); +rangeStep(0.01)(FogInfoProto, 'fogEnd', fogEndDescriptor); +type(CCFloat)(FogInfoProto, 'fogEnd', fogEndDescriptor); +visible(function (this) { /* Need to copy source code */ })(FogInfoProto, 'fogEnd', fogEndDescriptor); +const fogAttenDescriptor = Object.getOwnPropertyDescriptor(FogInfoProto, 'fogAtten'); +tooltip('i18n:fog.fogAtten')(FogInfoProto, 'fogAtten', fogAttenDescriptor); +rangeStep(0.01)(FogInfoProto, 'fogAtten', fogAttenDescriptor); +rangeMin(0.01)(FogInfoProto, 'fogAtten', fogAttenDescriptor); +type(CCFloat)(FogInfoProto, 'fogAtten', fogAttenDescriptor); +visible(function (this) { /* Need to copy source code */ })(FogInfoProto, 'fogAtten', fogAttenDescriptor); +const fogTopDescriptor = Object.getOwnPropertyDescriptor(FogInfoProto, 'fogTop'); +tooltip('i18n:fog.fogTop')(FogInfoProto, 'fogTop', fogTopDescriptor); +rangeStep(0.01)(FogInfoProto, 'fogTop', fogTopDescriptor); +type(CCFloat)(FogInfoProto, 'fogTop', fogTopDescriptor); +visible(function (this) { /* Need to copy source code */ })(FogInfoProto, 'fogTop', fogTopDescriptor); +const fogRangeDescriptor = Object.getOwnPropertyDescriptor(FogInfoProto, 'fogRange'); +tooltip('i18n:fog.fogRange')(FogInfoProto, 'fogRange', fogRangeDescriptor); +rangeStep(0.01)(FogInfoProto, 'fogRange', fogRangeDescriptor); +type(CCFloat)(FogInfoProto, 'fogRange', fogRangeDescriptor); +visible(function (this) { /* Need to copy source code */ })(FogInfoProto, 'fogRange', fogRangeDescriptor); +ccclass('cc.FogInfo')(FogInfo); + +const SkyboxInfoProto = SkyboxInfo.prototype; +serializable(SkyboxInfoProto, '_envLightingType'); +formerlySerializedAs('_envmap')(SkyboxInfoProto, '_envmapHDR'); +type(TextureCube)(SkyboxInfoProto, '_envmapHDR'); +serializable(SkyboxInfoProto, '_envmapHDR'); +type(TextureCube)(SkyboxInfoProto, '_envmapLDR'); +serializable(SkyboxInfoProto, '_envmapLDR'); +type(TextureCube)(SkyboxInfoProto, '_diffuseMapHDR'); +serializable(SkyboxInfoProto, '_diffuseMapHDR'); +type(TextureCube)(SkyboxInfoProto, '_diffuseMapLDR'); +serializable(SkyboxInfoProto, '_diffuseMapLDR'); +serializable(SkyboxInfoProto, '_enabled'); +serializable(SkyboxInfoProto, '_useHDR'); +type(Material)(SkyboxInfoProto, '_editableMaterial'); +serializable(SkyboxInfoProto, '_editableMaterial'); +const skyboxEnabledDescriptor = Object.getOwnPropertyDescriptor(SkyboxInfoProto, 'enabled'); +tooltip('i18n:skybox.enabled')(SkyboxInfoProto, 'enabled', skyboxEnabledDescriptor); +editable(SkyboxInfoProto, 'enabled', skyboxEnabledDescriptor); +const envLightingTypeDescriptor = Object.getOwnPropertyDescriptor(SkyboxInfoProto, 'envLightingType'); +tooltip('i18n:skybox.EnvironmentLightingType')(SkyboxInfoProto, 'envLightingType', envLightingTypeDescriptor); +type(EnvironmentLightingType)(SkyboxInfoProto, 'envLightingType', envLightingTypeDescriptor); +editable(SkyboxInfoProto, 'envLightingType', envLightingTypeDescriptor); +const useHDRDescriptor = Object.getOwnPropertyDescriptor(SkyboxInfoProto, 'useHDR'); +tooltip('i18n:skybox.useHDR')(SkyboxInfoProto, 'useHDR', useHDRDescriptor); +editable(SkyboxInfoProto, 'useHDR', useHDRDescriptor); +const envmapDescriptor = Object.getOwnPropertyDescriptor(SkyboxInfoProto, 'envmap'); +tooltip('i18n:skybox.envmap')(SkyboxInfoProto, 'envmap', envmapDescriptor); +type(TextureCube)(SkyboxInfoProto, 'envmap', envmapDescriptor); +editable(SkyboxInfoProto, 'envmap', envmapDescriptor); +const diffuseMapDescriptor = Object.getOwnPropertyDescriptor(SkyboxInfoProto, 'diffuseMap'); +displayOrder(100)(SkyboxInfoProto, 'diffuseMap', diffuseMapDescriptor); +type(TextureCube)(SkyboxInfoProto, 'diffuseMap', diffuseMapDescriptor); +readOnly(SkyboxInfoProto, 'diffuseMap', diffuseMapDescriptor); +editable(SkyboxInfoProto, 'diffuseMap', diffuseMapDescriptor); +visible(function (this) { /* Need to copy source code */ })(SkyboxInfoProto, 'diffuseMap', diffuseMapDescriptor); +const skyboxMaterialDescriptor = Object.getOwnPropertyDescriptor(SkyboxInfoProto, 'skyboxMaterial'); +tooltip('i18n:skybox.material')(SkyboxInfoProto, 'skyboxMaterial', skyboxMaterialDescriptor); +type(Material)(SkyboxInfoProto, 'skyboxMaterial', skyboxMaterialDescriptor); +editable(SkyboxInfoProto, 'skyboxMaterial', skyboxMaterialDescriptor); +ccclass('cc.SkyboxInfo')(SkyboxInfo); + +const AmbientInfoProto = AmbientInfo.prototype; +formerlySerializedAs('_skyColor')(AmbientInfoProto, '_skyColorHDR'); +serializable(AmbientInfoProto, '_skyColorHDR'); +formerlySerializedAs('_skyIllum')(AmbientInfoProto, '_skyIllumHDR'); +serializable(AmbientInfoProto, '_skyIllumHDR'); +formerlySerializedAs('_groundAlbedo')(AmbientInfoProto, '_groundAlbedoHDR'); +serializable(AmbientInfoProto, '_groundAlbedoHDR'); +serializable(AmbientInfoProto, '_skyColorLDR'); +serializable(AmbientInfoProto, '_skyIllumLDR'); +serializable(AmbientInfoProto, '_groundAlbedoLDR'); +const skyLightingColorDescriptor = Object.getOwnPropertyDescriptor(AmbientInfoProto, 'skyLightingColor'); +tooltip('i18n:ambient.skyLightingColor')(AmbientInfoProto, 'skyLightingColor', skyLightingColorDescriptor); +editable(AmbientInfoProto, 'skyLightingColor', skyLightingColorDescriptor); +visible(() => { /* Need to copy source code */ })(AmbientInfoProto, 'skyLightingColor', skyLightingColorDescriptor); +const skyIllumDescriptor = Object.getOwnPropertyDescriptor(AmbientInfoProto, 'skyIllum'); +tooltip('i18n:ambient.skyIllum')(AmbientInfoProto, 'skyIllum', skyIllumDescriptor); +type(CCFloat)(AmbientInfoProto, 'skyIllum', skyIllumDescriptor); +editable(AmbientInfoProto, 'skyIllum', skyIllumDescriptor); +const groundLightingColorDescriptor = Object.getOwnPropertyDescriptor(AmbientInfoProto, 'groundLightingColor'); +tooltip('i18n:ambient.groundLightingColor')(AmbientInfoProto, 'groundLightingColor', groundLightingColorDescriptor); +editable(AmbientInfoProto, 'groundLightingColor', groundLightingColorDescriptor); +visible(() => { /* Need to copy source code */ })(AmbientInfoProto, 'groundLightingColor', groundLightingColorDescriptor); +ccclass('cc.AmbientInfo')(AmbientInfo); diff --git a/cocos/core/scene-graph/scene-globals.ts b/cocos/core/scene-graph/scene-globals.ts index 82cf781998..cfed18f5ed 100644 --- a/cocos/core/scene-graph/scene-globals.ts +++ b/cocos/core/scene-graph/scene-globals.ts @@ -19,24 +19,22 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module scene-graph - */ - -import { ccclass, visible, type, displayOrder, readOnly, slide, range, rangeStep, editable, serializable, rangeMin, tooltip, formerlySerializedAs, displayName, help } from 'cc.decorator'; -import { BAIDU, EDITOR } from 'internal:constants'; +import { ccclass, visible, type, displayOrder, readOnly, slide, range, rangeStep, + editable, serializable, rangeMin, tooltip, formerlySerializedAs, displayName } from 'cc.decorator'; +import { BAIDU } from 'internal:constants'; import { TextureCube } from '../assets/texture-cube'; -import { CCFloat, CCBoolean, CCInteger } from '../data/utils/attribute'; +import { CCFloat, CCInteger } from '../data/utils/attribute'; import { Color, Quat, Vec3, Vec2, Vec4 } from '../math'; import { Ambient } from '../renderer/scene/ambient'; -import { Shadows, ShadowType, PCFType, ShadowSize } from '../renderer/scene/shadows'; +import { Shadows, ShadowType, ShadowSize } from '../renderer/scene/shadows'; import { Skybox, EnvironmentLightingType } from '../renderer/scene/skybox'; import { Octree } from '../renderer/scene/octree'; import { Fog, FogType } from '../renderer/scene/fog'; import { Node } from './node'; import { legacyCC } from '../global-exports'; import { Root } from '../root'; +import { warnID } from '../platform/debug'; +import { Material } from '../assets/material'; const _up = new Vec3(0, 1, 0); const _v3 = new Vec3(); @@ -54,50 +52,55 @@ const normalizeHDRColor = (color : Vec4) => { } }; /** - * @en Environment lighting information in the Scene - * @zh 场景的环境光照相关信息 + * @en Environment lighting configuration in the Scene + * @zh 场景的环境光照相关配置 */ @ccclass('cc.AmbientInfo') export class AmbientInfo { - @serializable - @formerlySerializedAs('_skyColor') - protected _skyColorHDR = new Vec4(0.2, 0.5, 0.8, 1.0); - @serializable - @formerlySerializedAs('_skyIllum') - protected _skyIllumHDR = Ambient.SKY_ILLUM; - @serializable - @formerlySerializedAs('_groundAlbedo') - protected _groundAlbedoHDR = new Vec4(0.2, 0.2, 0.2, 1.0); - - @serializable - protected _skyColorLDR = new Vec4(0.2, 0.5, 0.8, 1.0); - @serializable - protected _skyIllumLDR = Ambient.SKY_ILLUM; - @serializable - protected _groundAlbedoLDR = new Vec4(0.2, 0.2, 0.2, 1.0); - - protected _resource: Ambient | null = null; - + /** + * @en The sky color in HDR mode + * @zh HDR 模式下的天空光照色 + */ get skyColorHDR () : Readonly { return this._skyColorHDR; } + /** + * @en The ground color in HDR mode + * @zh HDR 模式下的地面光照色 + */ get groundAlbedoHDR () : Readonly { return this._groundAlbedoHDR; } + /** + * @en Sky illuminance in HDR mode + * @zh HDR 模式下的天空亮度 + */ get skyIllumHDR () { return this._skyIllumHDR; } + /** + * @en The sky color in LDR mode + * @zh LDR 模式下的天空光照色 + */ get skyColorLDR () : Readonly { return this._skyColorLDR; } + /** + * @en The ground color in LDR mode + * @zh LDR 模式下的地面光照色 + */ get groundAlbedoLDR () : Readonly { return this._groundAlbedoLDR; } + /** + * @en Sky illuminance in LDR mode + * @zh LDR 模式下的天空亮度 + */ get skyIllumLDR () { return this._skyIllumLDR; } @@ -133,6 +136,9 @@ export class AmbientInfo { return _col.set(_v4.x * 255, _v4.y * 255, _v4.z * 255, 255); } + /** + * @internal + */ set skyColor (val: Vec4) { if ((legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR) { this._skyColorHDR.set(val); @@ -197,6 +203,9 @@ export class AmbientInfo { return _col.set(_v4.x * 255, _v4.y * 255, _v4.z * 255, 255); } + /** + * @internal + */ set groundAlbedo (val: Vec4) { if ((legacyCC.director.root as Root).pipeline.pipelineSceneData.isHDR) { this._groundAlbedoHDR.set(val); @@ -206,6 +215,30 @@ export class AmbientInfo { if (this._resource) { this._resource.groundAlbedo.set(val); } } + @serializable + @formerlySerializedAs('_skyColor') + protected _skyColorHDR = new Vec4(0.2, 0.5, 0.8, 1.0); + @serializable + @formerlySerializedAs('_skyIllum') + protected _skyIllumHDR = Ambient.SKY_ILLUM; + @serializable + @formerlySerializedAs('_groundAlbedo') + protected _groundAlbedoHDR = new Vec4(0.2, 0.2, 0.2, 1.0); + + @serializable + protected _skyColorLDR = new Vec4(0.2, 0.5, 0.8, 1.0); + @serializable + protected _skyIllumLDR = Ambient.SKY_ILLUM; + @serializable + protected _groundAlbedoLDR = new Vec4(0.2, 0.2, 0.2, 1.0); + + protected _resource: Ambient | null = null; + + /** + * @en Activate the ambient lighting configuration in the render scene, no need to invoke manually. + * @zh 在渲染场景中启用环境光照设置,不需要手动调用 + * @param resource The ambient configuration object in the render scene + */ public activate (resource: Ambient) { this._resource = resource; this._resource.initialize(this); @@ -214,33 +247,11 @@ export class AmbientInfo { legacyCC.AmbientInfo = AmbientInfo; /** - * @en Skybox related information - * @zh 天空盒相关信息 + * @en Skybox related configuration + * @zh 天空盒相关配置 */ @ccclass('cc.SkyboxInfo') export class SkyboxInfo { - @serializable - protected _envLightingType = EnvironmentLightingType.HEMISPHERE_DIFFUSE; - @serializable - @type(TextureCube) - @formerlySerializedAs('_envmap') - protected _envmapHDR: TextureCube | null = null; - @serializable - @type(TextureCube) - protected _envmapLDR: TextureCube | null = null; - @serializable - @type(TextureCube) - protected _diffuseMapHDR: TextureCube | null = null; - @serializable - @type(TextureCube) - protected _diffuseMapLDR: TextureCube | null = null; - @serializable - protected _enabled = false; - @serializable - protected _useHDR = true; - - protected _resource: Skybox | null = null; - /** * @en Whether to use diffuse convolution map. Enabled -> Will use map specified. Disabled -> Will revert to hemispheric lighting * @zh 是否为IBL启用漫反射卷积图?不启用的话将使用默认的半球光照 @@ -282,16 +293,24 @@ export class SkyboxInfo { @type(EnvironmentLightingType) @tooltip('i18n:skybox.EnvironmentLightingType') set envLightingType (val) { - if (EnvironmentLightingType.HEMISPHERE_DIFFUSE === val) { + if (!this.envmap && EnvironmentLightingType.HEMISPHERE_DIFFUSE !== val) { this.useIBL = false; - } else if (EnvironmentLightingType.AUTOGEN_HEMISPHERE_DIFFUSE_WITH_REFLECTION === val) { - this.useIBL = true; this.applyDiffuseMap = false; - } else if (EnvironmentLightingType.DIFFUSEMAP_WITH_REFLECTION === val) { - this.useIBL = true; - this.applyDiffuseMap = true; + this._envLightingType = EnvironmentLightingType.HEMISPHERE_DIFFUSE; + warnID(15001); + } else { + if (EnvironmentLightingType.HEMISPHERE_DIFFUSE === val) { + this.useIBL = false; + this.applyDiffuseMap = false; + } else if (EnvironmentLightingType.AUTOGEN_HEMISPHERE_DIFFUSE_WITH_REFLECTION === val) { + this.useIBL = true; + this.applyDiffuseMap = false; + } else if (EnvironmentLightingType.DIFFUSEMAP_WITH_REFLECTION === val) { + this.useIBL = true; + this.applyDiffuseMap = true; + } + this._envLightingType = val; } - this._envLightingType = val; } get envLightingType () { return this._envLightingType; @@ -324,13 +343,16 @@ export class SkyboxInfo { // Switch UI to and from LDR/HDR textures depends on HDR state if (this._resource) { - if (this._resource.envmap) { - this.envmap = this._resource.envmap; - } + this.envmap = this._resource.envmap; this.diffuseMap = this._resource.diffuseMap; - if (this.diffuseMap == null) { - this.applyDiffuseMap = false; + if (this.envLightingType === EnvironmentLightingType.DIFFUSEMAP_WITH_REFLECTION) { + if (this.diffuseMap === null) { + this.envLightingType = EnvironmentLightingType.AUTOGEN_HEMISPHERE_DIFFUSE_WITH_REFLECTION; + warnID(15000); + } else if (this.diffuseMap.isDefault) { + warnID(15002); + } } } @@ -356,13 +378,15 @@ export class SkyboxInfo { this._envmapLDR = val; } if (!val) { - this._diffuseMapHDR = null; - this._diffuseMapLDR = null; - this._envmapHDR = null; - this._envmapLDR = null; + if (isHDR) { + this._diffuseMapHDR = null; + } else { + this._diffuseMapLDR = null; + } this.applyDiffuseMap = false; this.useIBL = false; this.envLightingType = EnvironmentLightingType.HEMISPHERE_DIFFUSE; + warnID(15001); } if (this._resource) { @@ -416,45 +440,73 @@ export class SkyboxInfo { } } + /** + * @en Use custom skybox material + * @zh 使用自定义的天空盒材质 + */ + @editable + @type(Material) + @tooltip('i18n:skybox.material') + set skyboxMaterial (val: Material | null) { + this._editableMaterial = val; + if (this._resource) { + this._resource.setSkyboxMaterial(this._editableMaterial); + } + } + get skyboxMaterial () { + return this._editableMaterial; + } + + @serializable + protected _envLightingType = EnvironmentLightingType.HEMISPHERE_DIFFUSE; + @serializable + @type(TextureCube) + @formerlySerializedAs('_envmap') + protected _envmapHDR: TextureCube | null = null; + @serializable + @type(TextureCube) + protected _envmapLDR: TextureCube | null = null; + @serializable + @type(TextureCube) + protected _diffuseMapHDR: TextureCube | null = null; + @serializable + @type(TextureCube) + protected _diffuseMapLDR: TextureCube | null = null; + @serializable + protected _enabled = false; + @serializable + protected _useHDR = true; + @serializable + @type(Material) + protected _editableMaterial: Material | null = null; + + protected _resource: Skybox | null = null; + + /** + * @en Activate the skybox configuration in the render scene, no need to invoke manually. + * @zh 在渲染场景中启用天空盒设置,不需要手动调用 + * @param resource The skybox configuration object in the render scene + */ public activate (resource: Skybox) { this.envLightingType = this._envLightingType; this._resource = resource; this._resource.initialize(this); this._resource.setEnvMaps(this._envmapHDR, this._envmapLDR); this._resource.setDiffuseMaps(this._diffuseMapHDR, this._diffuseMapLDR); + this._resource.setSkyboxMaterial(this._editableMaterial); this._resource.activate(); // update global DS first } } legacyCC.SkyboxInfo = SkyboxInfo; /** - * @zh 全局雾相关信息 - * @en Global fog info + * @zh 全局雾相关配置 + * @en Global fog configuration */ @ccclass('cc.FogInfo') export class FogInfo { public static FogType = FogType; - @serializable - protected _type = FogType.LINEAR; - @serializable - protected _fogColor = new Color('#C8C8C8'); - @serializable - protected _enabled = false; - @serializable - protected _fogDensity = 0.3; - @serializable - protected _fogStart = 0.5; - @serializable - protected _fogEnd = 300; - @serializable - protected _fogAtten = 5; - @serializable - protected _fogTop = 1.5; - @serializable - protected _fogRange = 1.2; - @serializable - protected _accurate = false; - protected _resource: Fog | null = null; + /** * @zh 是否启用全局雾效 * @en Enable global fog @@ -638,6 +690,33 @@ export class FogInfo { if (this._resource) { this._resource.fogRange = val; } } + @serializable + protected _type = FogType.LINEAR; + @serializable + protected _fogColor = new Color('#C8C8C8'); + @serializable + protected _enabled = false; + @serializable + protected _fogDensity = 0.3; + @serializable + protected _fogStart = 0.5; + @serializable + protected _fogEnd = 300; + @serializable + protected _fogAtten = 5; + @serializable + protected _fogTop = 1.5; + @serializable + protected _fogRange = 1.2; + @serializable + protected _accurate = false; + protected _resource: Fog | null = null; + + /** + * @en Activate the fog configuration in the render scene, no need to invoke manually. + * @zh 在渲染场景中启用雾效设置,不需要手动调用 + * @param resource The fog configuration object in the render scene + */ public activate (resource: Fog) { this._resource = resource; this._resource.initialize(this); @@ -646,28 +725,11 @@ export class FogInfo { } /** - * @en Scene level planar shadow related information - * @zh 平面阴影相关信息 + * @en Scene level shadow related configuration + * @zh 场景级别阴影相关的配置 */ @ccclass('cc.ShadowsInfo') export class ShadowsInfo { - @serializable - protected _enabled = false; - @serializable - protected _type = ShadowType.Planar; - @serializable - protected _normal = new Vec3(0, 1, 0); - @serializable - protected _distance = 0; - @serializable - protected _shadowColor = new Color(0, 0, 0, 76); - @serializable - protected _maxReceived = 4; - @serializable - protected _size = new Vec2(512, 512); - - protected _resource: Shadows | null = null; - /** * @en Whether activate planar shadow * @zh 是否启用平面阴影? @@ -693,6 +755,10 @@ export class ShadowsInfo { return this._enabled; } + /** + * @en The type of the shadow + * @zh 阴影渲染的类型 + */ @editable @type(ShadowType) set type (val) { @@ -778,9 +844,23 @@ export class ShadowsInfo { get shadowMapSize () { return this._size.x; } - get size () : Readonly { - return this._size; - } + + @serializable + protected _enabled = false; + @serializable + protected _type = ShadowType.Planar; + @serializable + protected _normal = new Vec3(0, 1, 0); + @serializable + protected _distance = 0; + @serializable + protected _shadowColor = new Color(0, 0, 0, 76); + @serializable + protected _maxReceived = 4; + @serializable + protected _size = new Vec2(1024, 1024); + + protected _resource: Shadows | null = null; /** * @en Set plane which receives shadow with the given node's world transformation @@ -794,6 +874,11 @@ export class ShadowsInfo { this.planeHeight = Vec3.dot(this._normal, _v3); } + /** + * @en Activate the shadow configuration in the render scene, no need to invoke manually. + * @zh 在渲染场景中启用阴影设置,不需要手动调用 + * @param resource The shadow configuration object in the render scene + */ public activate (resource: Shadows) { this._resource = resource; this._resource.initialize(this); @@ -802,30 +887,18 @@ export class ShadowsInfo { } legacyCC.ShadowsInfo = ShadowsInfo; -/** - * @en Scene level octree related information - * @zh 场景八叉树相关信息 - */ - export const DEFAULT_WORLD_MIN_POS = new Vec3(-1024.0, -1024.0, -1024.0); export const DEFAULT_WORLD_MAX_POS = new Vec3(1024.0, 1024.0, 1024.0); export const DEFAULT_OCTREE_DEPTH = 8; +/** + * @en Scene management and culling configuration based on octree + * @zh 基于八叉树的场景剔除配置 + */ @ccclass('cc.OctreeInfo') export class OctreeInfo { - @serializable - protected _enabled = false; - @serializable - protected _minPos = new Vec3(DEFAULT_WORLD_MIN_POS); - @serializable - protected _maxPos = new Vec3(DEFAULT_WORLD_MAX_POS); - @serializable - protected _depth = DEFAULT_OCTREE_DEPTH; - - protected _resource: Octree | null = null; - /** - * @en Whether activate octree + * @en Whether activate scene culling based on octree * @zh 是否启用八叉树加速剔除? */ @editable @@ -841,6 +914,11 @@ export class OctreeInfo { return this._enabled; } + /** + * @en The minimal position of the scene bounding box. + * Objects entirely outside the bounding box will be culled, other objects will be managed dynamically. + * @zh 场景包围盒的最小位置,完全超出包围盒的物体会被剔除,其他物体根据情况被动态剔除。 + */ @editable @tooltip('i18n:octree_culling.minPos') @displayName('World MinPos') @@ -852,6 +930,11 @@ export class OctreeInfo { return this._minPos; } + /** + * @en The maximum position of the scene bounding box. + * Objects entirely outside the bounding box will be culled, other objects will be managed dynamically. + * @zh 场景包围盒的最大位置,完全超出包围盒的物体会被剔除,其他物体根据情况被动态剔除。 + */ @editable @tooltip('i18n:octree_culling.maxPos') @displayName('World MaxPos') @@ -863,6 +946,10 @@ export class OctreeInfo { return this._maxPos; } + /** + * @en The depth of the octree. + * @zh 八叉树的深度。 + */ @editable @range([4, 12, 1]) @slide @@ -876,6 +963,22 @@ export class OctreeInfo { return this._depth; } + @serializable + protected _enabled = false; + @serializable + protected _minPos = new Vec3(DEFAULT_WORLD_MIN_POS); + @serializable + protected _maxPos = new Vec3(DEFAULT_WORLD_MAX_POS); + @serializable + protected _depth = DEFAULT_OCTREE_DEPTH; + + protected _resource: Octree | null = null; + + /** + * @en Activate the octree configuration in the render scene, no need to invoke manually. + * @zh 在渲染场景中启用八叉树设置,不需要手动调用 + * @param resource The octree configuration object in the render scene + */ public activate (resource: Octree) { this._resource = resource; this._resource.initialize(this); @@ -889,31 +992,35 @@ export class OctreeInfo { @ccclass('cc.SceneGlobals') export class SceneGlobals { /** - * @en The environment light information - * @zh 场景的环境光照相关信息 + * @en The environment lighting configuration + * @zh 场景的环境光照相关配置 */ @serializable @editable public ambient = new AmbientInfo(); /** - * @en Scene level planar shadow related information - * @zh 平面阴影相关信息 + * @en Scene level shadow related configuration + * @zh 平面阴影相关配置 */ @serializable @editable public shadows = new ShadowsInfo(); /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @serializable public _skybox = new SkyboxInfo(); + /** + * @en Global fog configuration + * @zh 全局雾相关配置 + */ @editable @serializable public fog = new FogInfo(); /** - * @en Skybox related information - * @zh 天空盒相关信息 + * @en Skybox related configuration + * @zh 天空盒相关配置 */ @editable @type(SkyboxInfo) @@ -925,13 +1032,17 @@ export class SceneGlobals { } /** - * @en Octree related information - * @zh 八叉树相关信息 + * @en Octree related configuration + * @zh 八叉树相关配置 */ @editable @serializable public octree = new OctreeInfo(); + /** + * @en Activate and initialize the global configurations of the scene, no need to invoke manually. + * @zh 启用和初始化场景全局配置,不需要手动调用 + */ public activate () { const sceneData = (legacyCC.director.root as Root).pipeline.pipelineSceneData; this.skybox.activate(sceneData.skybox); @@ -940,6 +1051,9 @@ export class SceneGlobals { this.shadows.activate(sceneData.shadows); this.fog.activate(sceneData.fog); this.octree.activate(sceneData.octree); + + const root = legacyCC.director.root as Root; + root.onGlobalPipelineStateChanged(); } } legacyCC.SceneGlobals = SceneGlobals; diff --git a/cocos/core/scene-graph/scene.jsb.ts b/cocos/core/scene-graph/scene.jsb.ts index 9bcc406917..83698fa30f 100644 --- a/cocos/core/scene-graph/scene.jsb.ts +++ b/cocos/core/scene-graph/scene.jsb.ts @@ -20,26 +20,18 @@ */ import { ccclass, editable, serializable } from 'cc.decorator'; -import { - _applyDecoratedDescriptor, - _assertThisInitialized, - _initializerDefineProperty, -} from '../data/utils/decorator-jsb-utils'; +import { EDITOR, TEST } from "internal:constants"; import { legacyCC } from '../global-exports'; -import { SceneGlobals } from './scene-globals'; import { Node } from './node'; import { applyTargetOverrides, expandNestedPrefabInstanceNode } from "../utils/prefab/utils"; -import { EDITOR, TEST } from "../default-constants"; import { assert } from "../platform/debug"; import { updateChildrenForDeserialize } from '../utils/jsb-utils'; export const Scene = jsb.Scene; export type Scene = jsb.Scene; - -const clsDecorator = ccclass('cc.Scene'); +legacyCC.Scene = Scene; const sceneProto: any = Scene.prototype; -const _class2$x = Scene; Object.defineProperty(sceneProto, '_globals', { enumerable: true, @@ -83,35 +75,12 @@ Object.defineProperty(sceneProto, 'renderScene', { } }); -_applyDecoratedDescriptor(_class2$x.prototype, 'globals', [editable], Object.getOwnPropertyDescriptor(_class2$x.prototype, 'globals'), _class2$x.prototype); -const _descriptor$r = _applyDecoratedDescriptor(_class2$x.prototype, 'autoReleaseAssets', [serializable, editable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return false; - }, -}); - -const _descriptor2$k = _applyDecoratedDescriptor(_class2$x.prototype, '_globals', [serializable], { - configurable: true, - enumerable: true, - writable: true, - initializer: function initializer () { - return new SceneGlobals(); - }, -}); - sceneProto._ctor = function () { Node.prototype._ctor.apply(this, arguments); this._inited = false; this._renderSceneInternal = null; this._globalRef = null; this._prefabSyncedInLiveReload = false; - // eslint-disable-next-line @typescript-eslint/no-this-alias - // const _this = this; - // _initializerDefineProperty(_this, "autoReleaseAssets", _descriptor$r, _assertThisInitialized(_this)); - // _initializerDefineProperty(_this, "_globals", _descriptor2$k, _assertThisInitialized(_this)); }; sceneProto._onBatchCreated = function (dontSyncChildPrefab: boolean) { @@ -145,7 +114,6 @@ sceneProto._load = function () { oldLoad.call(this); }; -const oldActivate = sceneProto._activate; sceneProto._activate = function (active: boolean) { active = (active !== false); if (EDITOR) { @@ -162,5 +130,11 @@ sceneProto._activate = function (active: boolean) { } }; -clsDecorator(Scene); -legacyCC.Scene = Scene; +// handle meta data, it is generated automatically +const SceneProto = Scene.prototype; +const globalsDescriptor = Object.getOwnPropertyDescriptor(SceneProto, 'globals'); +editable(SceneProto, 'globals', globalsDescriptor); +editable(SceneProto, 'autoReleaseAssets'); +serializable(SceneProto, 'autoReleaseAssets'); +serializable(SceneProto, '_globals'); +ccclass('cc.Scene')(Scene); diff --git a/cocos/core/scene-graph/scene.ts b/cocos/core/scene-graph/scene.ts index ec9023bb45..65be90ba01 100644 --- a/cocos/core/scene-graph/scene.ts +++ b/cocos/core/scene-graph/scene.ts @@ -23,17 +23,12 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module scene-graph - */ - import { ccclass, serializable, editable } from 'cc.decorator'; import { EDITOR, TEST } from 'internal:constants'; import { CCObject } from '../data/object'; import { Mat4, Quat, Vec3 } from '../math'; import { assert, getError } from '../platform/debug'; -import { RenderScene } from '../renderer/scene/render-scene'; +import { RenderScene } from '../renderer/core/render-scene'; import { BaseNode } from './base-node'; import { legacyCC } from '../global-exports'; import { Component } from '../components/component'; @@ -75,7 +70,7 @@ export class Scene extends BaseNode { * @en Per-scene level rendering info * @zh 场景级别的渲染信息 * - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @serializable public _globals = new SceneGlobals(); @@ -151,18 +146,18 @@ export class Scene extends BaseNode { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _onHierarchyChanged () { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _onBatchCreated (dontSyncChildPrefab: boolean) { super._onBatchCreated(dontSyncChildPrefab); const len = this._children.length; for (let i = 0; i < len; ++i) { - this.children[i]._siblingIndex = i; + this._children[i]._siblingIndex = i; this._children[i]._onBatchCreated(dontSyncChildPrefab); } } @@ -170,92 +165,146 @@ export class Scene extends BaseNode { // transform helpers /** + * @en * Refer to [[Node.getPosition]] + * @zh + * 参考 [[Node.getPosition]] */ public getPosition (out?: Vec3): Vec3 { return Vec3.copy(out || new Vec3(), Vec3.ZERO); } /** + * @en * Refer to [[Node.getRotation]] + * @zh + * 参考 [[Node.getRotation]] */ public getRotation (out?: Quat): Quat { return Quat.copy(out || new Quat(), Quat.IDENTITY); } /** + * @en * Refer to [[Node.getScale]] + * @zh + * 参考 [[Node.getScale]] */ public getScale (out?: Vec3): Vec3 { return Vec3.copy(out || new Vec3(), Vec3.ONE); } /** + * @en * Refer to [[Node.getWorldPosition]] + * @zh + * 参考 [[Node.getWorldPosition]] */ public getWorldPosition (out?: Vec3) { return Vec3.copy(out || new Vec3(), Vec3.ZERO); } /** + * @en * Refer to [[Node.getWorldRotation]] + * @zh + * 参考 [[Node.getWorldRotation]] */ public getWorldRotation (out?: Quat) { return Quat.copy(out || new Quat(), Quat.IDENTITY); } /** + * @en * Refer to [[Node.getWorldScale]] + * @zh + * 参考 [[Node.getWorldScale]] */ public getWorldScale (out?: Vec3) { return Vec3.copy(out || new Vec3(), Vec3.ONE); } /** + * @en * Refer to [[Node.getWorldMatrix]] + * @zh + * 参考 [[Node.getWorldMatrix]] */ public getWorldMatrix (out?: Mat4): Mat4 { return Mat4.copy(out || new Mat4(), Mat4.IDENTITY); } /** + * @en * Refer to [[Node.getWorldRS]] + * @zh + * 参考 [[Node.getWorldRS]] */ public getWorldRS (out?: Mat4): Mat4 { return Mat4.copy(out || new Mat4(), Mat4.IDENTITY); } /** + * @en * Refer to [[Node.getWorldRT]] + * @zh + * 参考 [[Node.getWorldRT]] */ public getWorldRT (out?: Mat4): Mat4 { return Mat4.copy(out || new Mat4(), Mat4.IDENTITY); } /** + * @en * Refer to [[Node.position]] + * @zh + * 参考 [[Node.position]] */ public get position (): Readonly { return Vec3.ZERO; } /** + * @en * Refer to [[Node.worldPosition]] + * @zh + * 参考 [[Node.worldPosition]] */ public get worldPosition (): Readonly { return Vec3.ZERO; } /** + * @en * Refer to [[Node.rotation]] + * @zh + * 参考 [[Node.rotation]] */ public get rotation (): Readonly { return Quat.IDENTITY; } /** + * @en * Refer to [[Node.worldRotation]] + * @zh + * 参考 [[Node.worldRotation]] */ public get worldRotation (): Readonly { return Quat.IDENTITY; } /** + * @en * Refer to [[Node.scale]] + * @zh + * 参考 [[Node.scale]] */ public get scale (): Readonly { return Vec3.ONE; } /** + * @en * Refer to [[Node.worldScale]] + * @zh + * 参考 [[Node.worldScale]] */ public get worldScale (): Readonly { return Vec3.ONE; } /** + * @en * Refer to [[Node.eulerAngles]] + * @zh + * 参考 [[Node.eulerAngles]] */ public get eulerAngles (): Readonly { return Vec3.ZERO; } /** + * @en * Refer to [[Node.worldMatrix]] + * @zh + * 参考 [[Node.worldMatrix]] */ public get worldMatrix (): Readonly { return Mat4.IDENTITY; } /** + * @en * Refer to [[Node.updateWorldTransform]] + * @zh + * 参考 [[Node.updateWorldTransform]] */ public updateWorldTransform () {} diff --git a/native/cocos/core/builtin/shader-sources/glsl4.cpp.in b/cocos/core/scene-graph/utils.jsb.ts similarity index 59% rename from native/cocos/core/builtin/shader-sources/glsl4.cpp.in rename to cocos/core/scene-graph/utils.jsb.ts index cbb5ee3d88..dd1ccf25a8 100644 --- a/native/cocos/core/builtin/shader-sources/glsl4.cpp.in +++ b/cocos/core/scene-graph/utils.jsb.ts @@ -1,7 +1,7 @@ -/**************************************************************************** - Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. +/* + Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. - http://www.cocos.com + 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, @@ -21,15 +21,21 @@ 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. -****************************************************************************/ + */ -// clang-format off -#include "core/builtin/shader-sources/glsl4.h" +import { IMat4Like, Mat4 } from '../math'; -namespace cc { +declare const jsb: any; -ShaderSource builtinGLSL4{ -${PLACE_HOLDER} +// For optimize getPosition, getRotation, getScale +export const _tempFloatArray = new Float32Array(jsb.createExternalArrayBuffer(20 * 4)); + +export const fillMat4WithTempFloatArray = function fillMat4WithTempFloatArray (out: IMat4Like) { + Mat4.set(out, + _tempFloatArray[0], _tempFloatArray[1], _tempFloatArray[2], _tempFloatArray[3], + _tempFloatArray[4], _tempFloatArray[5], _tempFloatArray[6], _tempFloatArray[7], + _tempFloatArray[8], _tempFloatArray[9], _tempFloatArray[10], _tempFloatArray[11], + _tempFloatArray[12], _tempFloatArray[13], _tempFloatArray[14], _tempFloatArray[15] + ); }; - -} +// diff --git a/cocos/core/scheduler.ts b/cocos/core/scheduler.ts index e6187f1f53..5264c0c20f 100644 --- a/cocos/core/scheduler.ts +++ b/cocos/core/scheduler.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ - import IdGenerator from './utils/id-generator'; import { createMap } from './utils/js'; import System from './components/system'; @@ -138,7 +133,6 @@ class HashUpdateEntry { /** * @en Hash Element used for "selectors with interval" * @zh “用于间隔选择”的哈希元素 - * @class HashTimerEntry * @param timers * @param target hash key (retained) * @param timerIndex @@ -332,8 +326,6 @@ class CallbackTimer { * - update 定时器:每一帧都会触发。您可以自定义优先级。
* - 自定义定时器:自定义定时器可以每一帧或者自定义的时间间隔触发。
* 如果希望每帧都触发,应该使用 update 定时器,使用 update 定时器更快,而且消耗更少的内存。 - * - * @class Scheduler */ export class Scheduler extends System { public static ID = 'scheduler'; @@ -350,9 +342,9 @@ export class Scheduler extends System { private _arrayForTimers: any; /** - * @en This method should be called for any target which needs to schedule tasks, and this method should be called before any scheduler API usage. + * @en This method should be called for any target which needs to schedule tasks, and this method should be called before any scheduler API usage. * This method will add a `id` property if it doesn't exist. - * @zh 任何需要用 Scheduler 管理任务的对象主体都应该调用这个方法,并且应该在调用任何 Scheduler API 之前调用这个方法。 + * @zh 任何需要用 Scheduler 管理任务的对象主体都应该调用这个方法,并且应该在调用任何 Scheduler API 之前调用这个方法。 * 这个方法会给对象添加一个 `id` 属性,如果这个属性不存在的话。 * @param target */ diff --git a/cocos/core/settings.ts b/cocos/core/settings.ts new file mode 100644 index 0000000000..cc397149b4 --- /dev/null +++ b/cocos/core/settings.ts @@ -0,0 +1,174 @@ +/* + Copyright (c) 2022 Xiamen Yaji Software Co., Ltd. + + http://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 { HTML5 } from 'internal:constants'; +import { legacyCC } from './global-exports'; + +declare const fsUtils: any; + +/** + * @zh + * Settings 中的默认分组,通常与模块一一对应。 + * + * @en + * The default grouping in Settings, which usually corresponds to the module. + */ +enum Category { + PATH = 'path', + ENGINE = 'engine', + ASSETS = 'assets', + SCRIPTING = 'scripting', + PHYSICS = 'physics', + RENDERING = 'rendering', + LAUNCH = 'launch', + SCREEN = 'screen', + SPLASH_SCREEN = 'splashScreen', + ANIMATION = 'animation', + PROFILING = 'profiling', + PLUGINS = 'plugins', +} + +/** + * @zh + * 配置模块用于获取 settings.json 配置文件中的配置信息,同时你可以覆盖一些配置从而影响引擎的启动和运行,可参考 [game.init] 的参数选项说明。你可以通过 [settings] 访问此模块单例。 + * @en + * The Settings module is used to get the configuration information in the settings.json configuration file, + * and you can override some of the configuration to affect the launch and running of the engine, as described in the [game.init] parameter options. + * You can access this single instance of the module via [settings]. + */ +export class Settings { + static Category = Category; + + /** + * Initialization + * @internal + */ + init (path = '', overrides: Record = {}): Promise { + for (const categoryName in overrides) { + const category = overrides[categoryName]; + if (category) { + for (const name in category) { + this.overrideSettings(categoryName, name, category[name]); + } + } + } + if (!path) return Promise.resolve(); + return new Promise((resolve, reject) => { + if (!HTML5 && !path.startsWith('http')) { + const result = fsUtils.readJsonSync(path); + if (result instanceof Error) { + reject(result); + } else { + this._settings = result; + resolve(); + } + } else { + const xhr = new XMLHttpRequest(); + xhr.open('GET', path); + xhr.responseType = 'text'; + xhr.onload = () => { + this._settings = JSON.parse(xhr.response); + resolve(); + }; + xhr.onerror = () => { + reject(new Error('request settings failed!')); + }; + xhr.send(null); + } + }); + } + + /** + * @zh + * 覆盖一部分配置数据。 + * + * @en + * Override some configuration info in Settings module. + * + * @param category @en The category you want to override. @zh 想要覆盖的分组。 + * @param name @en The name of the configuration in the category you want to override. @zh 分组中想要覆盖的具体配置名称。 + * @param value @en The value of the configuration you want to override. @zh 想要覆盖的具体值。 + * + * @example + * ```ts + * console.log(settings.querySettings(Settings.Category.ASSETS, 'server')); // print https://www.cocos.com + * settings.overrideSettings(Settings.Category.ASSETS, 'server', 'http://www.test.com'); + * console.log(settings.querySettings(Settings.Category.ASSETS, 'server')); // print http://www.test.com + * ``` + */ + overrideSettings (category: Category | string, name: string, value: T) { + if (!(category in this._override)) { + this._override[category] = {}; + } + this._override[category][name] = value; + } + + /** + * @zh + * 查询配置模块中具体分组中的具体配置值。 + * + * @en + * Query specific configuration values in specific category in the settings module. + * + * @param category @en The name of category to query. @zh 想要查询的分组名称。 + * @param name @en The name of configuration in category to query. @zh 分组中想要查询的具体的配置名称。 + * @returns @en The value of configuration to query. @zh 想要查询的具体配置值。 + * + * @example + * ```ts + * console.log(settings.querySettings(Settings.Category.ENGINE, 'debug')); // print false + * ``` + */ + querySettings (category: Category | string, name: string): T | null { + if (category in this._override) { + const categorySettings = this._override[category]; + if (categorySettings && name in categorySettings) { + return categorySettings[name] as T; + } + } + if (category in this._settings) { + const categorySettings = this._settings[category]; + if (categorySettings && name in categorySettings) { + return categorySettings[name] as T; + } + } + return null; + } + + private _settings: Record = {}; + private _override: Record = {}; +} + +export declare namespace Settings { + export type Category = typeof Category; +} + +/** + * @zh + * Settings 模块单例,你能通过此单例访问 settings.json 中的配置数据。 + * @en + * Settings module singleton, through this you can access the configuration data in settings.json. + */ +export const settings = new Settings(); +legacyCC.settings = settings; diff --git a/cocos/core/splash-screen.ts b/cocos/core/splash-screen.ts index ca8c264c28..8a8bd2e27c 100644 --- a/cocos/core/splash-screen.ts +++ b/cocos/core/splash-screen.ts @@ -23,8 +23,7 @@ THE SOFTWARE. */ - - +import { EDITOR, NATIVE, PREVIEW } from 'internal:constants'; import * as easing from './easing/easing'; import { Material } from './assets/material'; import { clamp01 } from './math/utils'; @@ -35,43 +34,27 @@ import { } from './gfx'; import { PipelineStateManager } from './pipeline'; import { legacyCC } from './global-exports'; -import { Root } from './root'; import { SetIndex } from './pipeline/define'; -import { error } from './platform/debug'; import { Mat4, Vec2 } from './math'; +import { Settings, settings } from './settings'; const v2_0 = new Vec2(); type SplashEffectType = 'NONE' | 'FADE-INOUT'; interface ISplashSetting { - readonly totalTime: number; - readonly base64src: string; - readonly effect: SplashEffectType; - readonly clearColor: Color; - readonly displayRatio: number; - readonly displayWatermark: boolean; + enabled: boolean; + totalTime: number; + base64src: string; + effect: SplashEffectType; + clearColor: Color; + displayRatio: number; + displayWatermark: boolean; } type Writable = { -readonly [K in keyof T]: T[K] }; export class SplashScreen { - private set splashFinish (v: boolean) { - this._splashFinish = v; - this._tryToStart(); - } - public set loadFinish (v: boolean) { - this._loadFinish = v; - this._tryToStart(); - } - - private handle = 0; private settings!: ISplashSetting; - private callBack: (() => void) | null = null; - private cancelAnimate = false; - private startTime = -1; - private isPause = false; - private _splashFinish = false; - private _loadFinish = false; - private _directCall = false; + private _curTime = 0; private device!: Device; private swapchain!: Swapchain; @@ -93,88 +76,52 @@ export class SplashScreen { private watermarkMat!: Material; private watermarkTexture!: Texture; - public pauseRendering () { - this.isPause = true; + public get isFinished () { + return this._curTime >= this.settings.totalTime; } - public resumeRendering () { - this.isPause = false; + set curTime (val) { + this._curTime = val; } - public main (root: Root) { - if (root == null) { - error('RENDER ROOT IS NULL.'); - return; - } + get curTime () { + return this._curTime; + } - if (window._CCSettings && window._CCSettings.splashScreen) { - const setting: Writable = this.settings = window._CCSettings.splashScreen; - setting.totalTime = this.settings.totalTime != null ? this.settings.totalTime : 3000; - setting.base64src = this.settings.base64src || ''; - setting.effect = this.settings.effect || 'FADE-INOUT'; - setting.clearColor = this.settings.clearColor || new Color(0.88, 0.88, 0.88, 1); - setting.displayRatio = this.settings.displayRatio != null ? this.settings.displayRatio : 0.4; - setting.displayWatermark = this.settings.displayWatermark != null ? this.settings.displayWatermark : true; + public init (): Promise | undefined { + this.settings = { + enabled: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'enabled') ?? true, + totalTime: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'totalTime') ?? 3000, + base64src: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'base64src') ?? '', + effect: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'effect') ?? 'FADE-INOUT', + clearColor: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'clearColor') ?? new Color(0.88, 0.88, 0.88, 1), + displayRatio: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'displayRatio') ?? 0.4, + displayWatermark: settings.querySettings(Settings.Category.SPLASH_SCREEN, 'displayWatermark') ?? true, + }; + this._curTime = 0; + + if (EDITOR || (PREVIEW && !NATIVE) || !this.settings.enabled || this.settings.base64src === '' || this.settings.totalTime <= 0) { + this.settings.totalTime = 0; } else { - this.settings = { - totalTime: 3000, - base64src: '', - effect: 'FADE-INOUT', - clearColor: new Color(0.88, 0.88, 0.88, 1), - displayRatio: 0.4, - displayWatermark: true, - }; - } - - if (this.settings.base64src === '' || this.settings.totalTime <= 0) { - if (this.callBack) { this.callBack(); } - this.callBack = null; - (this.settings as any) = null; - this._directCall = true; - } else { - legacyCC.view.resizeWithBrowserSize(true); - const designRes = window._CCSettings.designResolution; - if (designRes) { - legacyCC.view.setDesignResolutionSize(designRes.width, designRes.height, designRes.policy); - } else { - legacyCC.view.setDesignResolutionSize(960, 640, 4); - } - this.device = root.device; - this.swapchain = root.mainWindow!.swapchain; - this.framebuffer = root.mainWindow!.framebuffer; - legacyCC.game.once(legacyCC.Game.EVENT_GAME_INITED, () => { - legacyCC.director._lateUpdate = performance.now(); - }, legacyCC.director); - - this.callBack = null; - this.cancelAnimate = false; - this.startTime = -1; + this.device = legacyCC.director.root!.device; + this.swapchain = legacyCC.director.root!.mainWindow!.swapchain; + this.framebuffer = legacyCC.director.root!.mainWindow!.framebuffer; this.preInit(); - this.logoImage = new Image(); - this.logoImage.onload = this.init.bind(this); - this.logoImage.src = this.settings.base64src; - } - } - - public setOnFinish (cb: () => void) { - if (this._directCall) { - if (cb) { - SplashScreen._ins = undefined; - cb(); return; - } - } - this.callBack = cb; - } - - private _tryToStart () { - if (this._splashFinish && this._loadFinish) { - if (this.callBack) { - this.callBack(); - this.hide(); - legacyCC.game.resume(); - } + if (this.settings.displayWatermark) this.initWarterMark(); + return new Promise((resolve, reject) => { + this.logoImage = new Image(); + this.logoImage.onload = () => { + this.initLogo(); + resolve(); + }; + this.logoImage.onerror = () => { + reject(); + }; + this.logoImage.src = this.settings.base64src; + }); } + return Promise.resolve(); } private preInit () { @@ -219,79 +166,60 @@ export class SplashScreen { device.capabilities.clipSpaceSignY, swapchain.surfaceTransform); } - private init () { - this.initLogo(); - if (this.settings.displayWatermark) this.initWarterMark(); - const animate = (time: number) => { - if (this.cancelAnimate) return; - const settings = this.settings; - const { device, swapchain } = this; - Mat4.ortho(this.projection, -1, 1, -1, 1, -1, 1, device.capabilities.clipSpaceMinZ, - device.capabilities.clipSpaceSignY, swapchain.surfaceTransform); - const dw = swapchain.width; const dh = swapchain.height; - const refW = dw < dh ? dw : dh; - // update logo uniform - if (this.startTime < 0) this.startTime = time; - const elapsedTime = time - this.startTime; - const percent = clamp01(elapsedTime / settings.totalTime); - let u_p = easing.cubicOut(percent); - if (settings.effect === 'NONE') u_p = 1.0; - const logoTW = this.logoTexture.width; const logoTH = this.logoTexture.height; - const logoW = refW * settings.displayRatio; - let scaleX = logoW * logoTW / logoTH; - let scaleY = logoW; + public update (deltaTime: number) { + const settings = this.settings; + const { device, swapchain } = this; + Mat4.ortho(this.projection, -1, 1, -1, 1, -1, 1, device.capabilities.clipSpaceMinZ, + device.capabilities.clipSpaceSignY, swapchain.surfaceTransform); + const dw = swapchain.width; const dh = swapchain.height; + const refW = dw < dh ? dw : dh; + // update logo uniform + this._curTime += deltaTime * 1000; + const percent = clamp01(this._curTime / settings.totalTime); + let u_p = easing.cubicOut(percent); + if (settings.effect === 'NONE') u_p = 1.0; + const logoTW = this.logoTexture.width; const logoTH = this.logoTexture.height; + const logoW = refW * settings.displayRatio; + let scaleX = logoW * logoTW / logoTH; + let scaleY = logoW; + if (swapchain.surfaceTransform === SurfaceTransform.ROTATE_90 + || swapchain.surfaceTransform === SurfaceTransform.ROTATE_270) { + scaleX = logoW * dw / dh; + scaleY = logoW * logoTH / logoTW * dh / dw; + } + this.logoMat.setProperty('resolution', v2_0.set(dw, dh), 0); + this.logoMat.setProperty('scale', v2_0.set(scaleX, scaleY), 0); + this.logoMat.setProperty('translate', v2_0.set(dw * 0.5, dh * 0.5), 0); + this.logoMat.setProperty('percent', u_p); + this.logoMat.setProperty('u_projection', this.projection); + this.logoMat.passes[0].update(); + + // update wartermark uniform + if (settings.displayWatermark && this.watermarkMat) { + const wartermarkW = refW * 0.5; + const wartermarkTW = this.watermarkTexture.width; const wartermarkTH = this.watermarkTexture.height; + let scaleX = wartermarkW; + let scaleY = wartermarkW * wartermarkTH / wartermarkTW; if (swapchain.surfaceTransform === SurfaceTransform.ROTATE_90 || swapchain.surfaceTransform === SurfaceTransform.ROTATE_270) { - scaleX = logoW * dw / dh; - scaleY = logoW * logoTH / logoTW * dh / dw; + scaleX = wartermarkW * 0.5; + scaleY = wartermarkW * dw / dh * 0.5; } - this.logoMat.setProperty('resolution', v2_0.set(dw, dh), 0); - this.logoMat.setProperty('scale', v2_0.set(scaleX, scaleY), 0); - this.logoMat.setProperty('translate', v2_0.set(dw * 0.5, dh * 0.5), 0); - this.logoMat.setProperty('percent', u_p); - this.logoMat.setProperty('u_projection', this.projection); - this.logoMat.passes[0].update(); - - // update wartermark uniform - if (settings.displayWatermark && this.watermarkMat) { - const wartermarkW = refW * 0.5; - const wartermarkTW = this.watermarkTexture.width; const wartermarkTH = this.watermarkTexture.height; - let scaleX = wartermarkW; - let scaleY = wartermarkW * wartermarkTH / wartermarkTW; - if (swapchain.surfaceTransform === SurfaceTransform.ROTATE_90 - || swapchain.surfaceTransform === SurfaceTransform.ROTATE_270) { - scaleX = wartermarkW * 0.5; - scaleY = wartermarkW * dw / dh * 0.5; - } - this.watermarkMat.setProperty('resolution', v2_0.set(dw, dh), 0); - this.watermarkMat.setProperty('scale', v2_0.set(scaleX, scaleY), 0); - this.watermarkMat.setProperty('translate', v2_0.set(dw * 0.5, dh * 0.1), 0); - this.watermarkMat.setProperty('percent', u_p); - this.watermarkMat.setProperty('u_projection', this.projection); - this.watermarkMat.passes[0].update(); - } - if (!this.isPause) { - this.frame(); - if (elapsedTime > settings.totalTime) this.splashFinish = true; - } - requestAnimationFrame(animate); - }; - legacyCC.game.pause(); - this.handle = requestAnimationFrame(animate); - } - - private hide () { - cancelAnimationFrame(this.handle); - this.cancelAnimate = true; - // The reason for delay destroy here is that immediate destroy input assmebler in ios will be crash - setTimeout(this.destroy.bind(this)); + this.watermarkMat.setProperty('resolution', v2_0.set(dw, dh), 0); + this.watermarkMat.setProperty('scale', v2_0.set(scaleX, scaleY), 0); + this.watermarkMat.setProperty('translate', v2_0.set(dw * 0.5, dh * 0.1), 0); + this.watermarkMat.setProperty('percent', u_p); + this.watermarkMat.setProperty('u_projection', this.projection); + this.watermarkMat.passes[0].update(); + } + this.frame(); } private initLogo () { const device = this.device; this.logoMat = new Material(); - this.logoMat.initialize({ effectName: 'splash-screen' }); + this.logoMat.initialize({ effectName: 'util/splash-screen' }); const samplerInfo = new SamplerInfo(); samplerInfo.addressU = Address.CLAMP; @@ -344,7 +272,7 @@ export class SplashScreen { this.device.copyTexImagesToTexture([wartemarkImg], this.watermarkTexture, [region]); // create material this.watermarkMat = new Material(); - this.watermarkMat.initialize({ effectName: 'splash-screen' }); + this.watermarkMat.initialize({ effectName: 'util/splash-screen' }); const pass = this.watermarkMat.passes[0]; const binding = pass.getBinding('mainTexture'); pass.bindTexture(binding, this.watermarkTexture); @@ -391,7 +319,6 @@ export class SplashScreen { } private destroy () { - this.callBack = null; this.device = null!; this.swapchain = null!; this.clearColors = null!; @@ -422,7 +349,6 @@ export class SplashScreen { } this.settings = null!; - SplashScreen._ins = undefined; } private static _ins?: SplashScreen; diff --git a/cocos/core/utils/array.ts b/cocos/core/utils/array.ts index a1b51e4f2e..2c597e8bed 100644 --- a/cocos/core/utils/array.ts +++ b/cocos/core/utils/array.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ - import { logID } from '../platform/debug'; export { default as MutableForwardIterator } from './mutable-forward-iterator'; diff --git a/cocos/core/utils/coordinates-converts-utils.ts b/cocos/core/utils/coordinates-converts-utils.ts index 6783091989..3e44ab9722 100644 --- a/cocos/core/utils/coordinates-converts-utils.ts +++ b/cocos/core/utils/coordinates-converts-utils.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ - import { Camera } from '../components/camera-component'; import { Vec3 } from '../math'; import { Node } from '../scene-graph'; @@ -41,11 +36,11 @@ const _vec3 = new Vec3(); * Conversion of non-UI nodes to UI Node (Local) Space coordinate system. * @zh * 非 UI 节点转换到 UI 节点(局部) 空间坐标系。 - * @deprecated 将在 1.2 移除,请使用 Camera 的 `convertToUINode`。 - * @param mainCamera 主相机。 - * @param wpos 世界空间位置。 - * @param uiNode UI节点。 - * @param out 返回局部坐标。 + * @deprecated since Cocos Creator 3D v1.2, please use [[Camera.convertToUINode]] + * @param mainCamera @en The main camera @zh 主相机 + * @param wpos @en The world space location. @zh 世界空间位置。 + * @param uiNode @en The UI node. @zh UI 节点。 + * @param out @en The output local position in UI @zh 返回 UI 节点局部坐标。 */ export function WorldNode3DToLocalNodeUI (mainCamera: Camera, wpos: Vec3, uiNode: Node, out?: Vec3) { if (!out) { @@ -62,11 +57,11 @@ export function WorldNode3DToLocalNodeUI (mainCamera: Camera, wpos: Vec3, uiNode * @en * Conversion of non-UI nodes to UI Node (World) Space coordinate system. * @zh - * 非 UI 节点转换到 UI 节点(世界) 空间坐标系。 - * @deprecated 将在 1.2 移除,请使用 Camera 的 `convertToUINode`。 - * @param mainCamera 主相机。 - * @param wpos 世界空间位置。 - * @param out 返回世界坐标。 + * 非 UI 节点转换到 UI 节点(世界)空间坐标系。 + * @deprecated since Cocos Creator 3D v1.2, please use [[Camera.convertToUINode]] + * @param mainCamera @en The main camera @zh 主相机 + * @param wpos @en The world space location. @zh 世界空间位置。 + * @param out @en The output world position in UI @zh 返回 UI 空间世界坐标。 */ export function WorldNode3DToWorldNodeUI (mainCamera: Camera, wpos: Vec3, out?: Vec3) { if (!out) { @@ -82,7 +77,7 @@ export function WorldNode3DToWorldNodeUI (mainCamera: Camera, wpos: Vec3, out?: /** * @en It will be removed in v1.2. Please use [[Camera.convertToUINode]]。 * @zh 将在 v1.2 移除,请使用 Camera 的 `convertToUINode`。 - * @deprecated + * @deprecated since Cocos Creator 3D v1.2 */ const convertUtils = { WorldNode3DToLocalNodeUI, @@ -102,6 +97,7 @@ replaceProperty(legacyCC.pipelineUtils, 'cc.pipelineUtils', [ const out = args[3] || _vec3; camera.convertToUINode(args[1], args[2], out); out.add(args[2].position); + // eslint-disable-next-line @typescript-eslint/no-unsafe-return return args[3] || out.clone(); }, }, diff --git a/cocos/core/utils/decode-uuid.ts b/cocos/core/utils/decode-uuid.ts index 9e3f63282f..4d21bd16da 100644 --- a/cocos/core/utils/decode-uuid.ts +++ b/cocos/core/utils/decode-uuid.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ - import { TEST } from 'internal:constants'; import { BASE64_VALUES } from './misc'; import { legacyCC } from '../global-exports'; diff --git a/cocos/core/utils/deprecated-3.6.0.ts b/cocos/core/utils/deprecated-3.6.0.ts new file mode 100644 index 0000000000..9f44ff1908 --- /dev/null +++ b/cocos/core/utils/deprecated-3.6.0.ts @@ -0,0 +1,20 @@ +import { deprecateModuleExportedName } from './x-deprecated'; + +deprecateModuleExportedName({ + replaceProperty: { + since: '3.6.0', + removed: false, + }, + removeProperty: { + since: '3.6.0', + removed: false, + }, + markAsWarning: { + since: '3.6.0', + removed: false, + }, + setDefaultLogTimes: { + since: '3.6.0', + removed: false, + }, +}); diff --git a/cocos/core/utils/id-generator.ts b/cocos/core/utils/id-generator.ts index 87c5aa1406..a584ccf9c4 100644 --- a/cocos/core/utils/id-generator.ts +++ b/cocos/core/utils/id-generator.ts @@ -23,22 +23,25 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ - import { EDITOR } from 'internal:constants'; const NonUuidMark = '.'; /** + * @en * ID generator for runtime. + * + * @zh + * 运行时 ID 生成器 */ export default class IDGenerator { - /* + /** + * @en * The global id generator might have a conflict problem once every 365 days, * if the game runs at 60 FPS and each frame 4760273 counts of new id are requested. + * + * @zh + * 全局的 id 生成器,如果游戏以 60 FPS 运行,每帧获取 4760273 个新 id, 则可能在 365 天后发生冲突。 */ public static global = new IDGenerator('global'); @@ -47,7 +50,10 @@ export default class IDGenerator { public prefix: string; /** - * @param [category] You can specify a unique category to avoid id collision with other instance of IdGenerator. + * @en Construct a new id generator + * @zh 构造一个新的 id 生成器 + * + * @param [category] @en You can specify a unique category to avoid id collision with other instance of IdGenerator. @zh 你能指定一个唯一的标识用于避免与其他 id 生成器冲突 */ constructor (category?: string) { // Tnit with a random id to emphasize that the returns id should not be stored in persistence data. diff --git a/cocos/core/utils/index.ts b/cocos/core/utils/index.ts index 0319292f7b..a795370949 100644 --- a/cocos/core/utils/index.ts +++ b/cocos/core/utils/index.ts @@ -24,6 +24,7 @@ THE SOFTWARE. */ +import './deprecated-3.6.0'; import * as js from './js'; /** diff --git a/cocos/core/utils/js-typed.ts b/cocos/core/utils/js-typed.ts index 6c046cbf75..83ec47f175 100644 --- a/cocos/core/utils/js-typed.ts +++ b/cocos/core/utils/js-typed.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ - import { EDITOR, DEV, TEST } from 'internal:constants'; import { warnID, error, errorID } from '../platform/debug'; import IDGenerator from './id-generator'; @@ -39,25 +34,38 @@ const classNameTag = '__classname__'; const classIdTag = '__cid__'; /** + * @en * Check the object whether is number or not * If a number is created by using 'new Number(10086)', the typeof it will be "object"... * Then you can use this function if you care about this case. + * @zh + * 检查对象是否是 number 类型,如果通过 'new Number(10086)' 创建了一个数字,则使用 typeof 判断此数字时,将返回 'object' 类型,此时你可以通过此方法来进行判断 + * @param object object to be checked + * @return whether this object is number or not */ export function isNumber (object: any) { return typeof object === 'number' || object instanceof Number; } /** + * @en * Check the object whether is string or not. * If a string is created by using 'new String("blabla")', the typeof it will be "object"... * Then you can use this function if you care about this case. + * @zh + * 检查对象是否是 string 类型,如果通过 'new String("blabla")' 创建了一个字符串,则使用 typeof 判断此字符串时,将返回 'object' 类型,此时你可以通过此方法来进行判断 + * @param object object to be checked + * @return whether this object is string or not */ export function isString (object: any) { return typeof object === 'string' || object instanceof String; } /** + * @en * Checks if the object `obj` does not have one or more enumerable properties (including properties from proto chain). + * @zh + * 检查此对象是否为空对象 * @param obj The object. * @returns The result. Note that if the `obj` is not of type `'object'`, `true` is returned. */ @@ -69,8 +77,12 @@ export function isEmptyObject (obj: any) { } /** + * @en * Define value, just help to call Object.defineProperty.
* The configurable will be true. + * @zh + * 定义值,帮助调用 Object.defineProperty. + * 该属性默认可读写 * @param [writable=false] * @param [enumerable=false] */ @@ -81,7 +93,7 @@ export const value = (() => { writable: false, configurable: true, }; - return (object: Object, propertyName: string, value_: any, writable?: boolean, enumerable?: boolean) => { + return (object: Record, propertyName: string, value_: any, writable?: boolean, enumerable?: boolean) => { descriptor.value = value_; descriptor.writable = writable; descriptor.enumerable = enumerable; @@ -91,7 +103,10 @@ export const value = (() => { })(); /** + * @en * Define get set accessor, just help to call Object.defineProperty(...). + * @zh + * 定义 get set 访问器,帮助调用 Object.defineProperty() * @param [setter=null] * @param [enumerable=false] * @param [configurable=false] @@ -102,7 +117,7 @@ export const getset = (() => { set: undefined, enumerable: false, }; - return (object: {}, propertyName: string, getter: Getter, setter?: Setter | boolean, enumerable = false, configurable = false) => { + return (object: Record, propertyName: string, getter: Getter, setter?: Setter | boolean, enumerable = false, configurable = false) => { if (typeof setter === 'boolean') { enumerable = setter; setter = undefined; @@ -118,7 +133,10 @@ export const getset = (() => { })(); /** + * @en * Define get accessor, just help to call Object.defineProperty(...). + * @zh + * 定义 get 访问器,帮助调用 Object.defineProperty() * @param [enumerable=false] * @param [configurable=false] */ @@ -128,7 +146,7 @@ export const get = (() => { enumerable: false, configurable: false, }; - return (object: Object, propertyName: string, getter: Getter, enumerable?: boolean, configurable?: boolean) => { + return (object: Record, propertyName: string, getter: Getter, enumerable?: boolean, configurable?: boolean) => { descriptor.get = getter; descriptor.enumerable = enumerable; descriptor.configurable = configurable; @@ -138,7 +156,10 @@ export const get = (() => { })(); /** - * Define set accessor, just help to call Object.defineProperty(...). + * @en + * Define set accessor, just help to call Object.defineProperty(...) + * @zh + * 定义 set 访问器,帮助调用 Object.defineProperty * @param [enumerable=false] * @param [configurable=false] */ @@ -148,7 +169,7 @@ export const set = (() => { enumerable: false, configurable: false, }; - return (object: Object, propertyName: string, setter: Setter, enumerable?: boolean, configurable?: boolean) => { + return (object: Record, propertyName: string, setter: Setter, enumerable?: boolean, configurable?: boolean) => { descriptor.set = setter; descriptor.enumerable = enumerable; descriptor.configurable = configurable; @@ -186,15 +207,19 @@ export function createMap (forceDictMode?: boolean): any { } /** + * @en * Get class name of the object, if object is just a {} (and which class named 'Object'), it will return "". * (modified from the code from this stackoverflow post) + * @zh + * 获取对象的类型名称,如果对象是 {} 字面量,将会返回 "" * @param objOrCtor instance or constructor */ -export function getClassName (objOrCtor: Object | Function): string { +export function getClassName (objOrCtor: any): string { if (typeof objOrCtor === 'function') { const prototype = objOrCtor.prototype; + // eslint-disable-next-line no-prototype-builtins if (prototype && prototype.hasOwnProperty(classNameTag) && prototype[classNameTag]) { - return prototype[classNameTag]; + return prototype[classNameTag] as string; } let retval = ''; // for browsers which have name property in the constructor of the object, such as chrome @@ -206,10 +231,12 @@ export function getClassName (objOrCtor: Object | Function): string { const str = objOrCtor.toString(); if (str.charAt(0) === '[') { // str is "[object objectClass]" - arr = str.match(/\[\w+\s*(\w+)\]/); + // eslint-disable-next-line @typescript-eslint/prefer-regexp-exec + arr = /\[\w+\s*(\w+)\]/.exec(str); } else { // str is function objectClass () {} for IE Firefox - arr = str.match(/function\s*(\w+)/); + // eslint-disable-next-line @typescript-eslint/prefer-regexp-exec + arr = /function\s*(\w+)/.exec(str); } if (arr && arr.length === 2) { retval = arr[1]; @@ -223,7 +250,10 @@ export function getClassName (objOrCtor: Object | Function): string { } /** + * @en * Defines a polyfill field for obsoleted codes. + * @zh + * 为废弃代码定义一个填充字段 * @param object - YourObject or YourClass.prototype * @param obsoleted - "OldParam" or "YourClass.OldParam" * @param newExpr - "NewParam" or "YourClass.NewParam" @@ -237,7 +267,7 @@ export function obsolete (object: any, obsoleted: string, newExpr: string, writa if (DEV) { warnID(5400, obsoleted, newExpr); } - return this[newProp]; + return this[newProp] as unknown; } function setter (this: any, value_: any) { if (DEV) { @@ -254,7 +284,10 @@ export function obsolete (object: any, obsoleted: string, newExpr: string, writa } /** + * @en * Defines all polyfill fields for obsoleted codes corresponding to the enumerable properties of props. + * @zh + * 为所有可废弃属性定义填充字段 * @param obj - YourObject or YourClass.prototype * @param objName - "YourObject" or "YourClass" * @param props @@ -271,7 +304,10 @@ const REGEXP_NUM_OR_STR = /(%d)|(%s)/; const REGEXP_STR = /%s/; /** + * @en * A string tool to construct a string with format string. + * @zh + * 通过格式字符串构造一个字符串 * @param msg - A JavaScript string containing zero or more substitution strings (%s). * @param subst - JavaScript objects with which to replace substitution strings within msg. * This gives you additional control over the format of the output. @@ -282,7 +318,7 @@ const REGEXP_STR = /%s/; * js.formatStr(a, b, c); * ``` */ -export function formatStr (msg: string | any, ...subst: any[]) { +export function formatStr (msg: string, ...subst: any[]) { if (arguments.length === 0) { return ''; } @@ -316,6 +352,7 @@ export function shiftArguments () { for (let i = 0; i < len; ++i) { args[i] = arguments[i + 1]; } + // eslint-disable-next-line @typescript-eslint/no-unsafe-return return args; } @@ -340,13 +377,28 @@ function _copyprop (name: string, source: any, target: any) { } } +export function copyAllProperties (source: any, target: any, excepts: Array) { + const propertyNames: Array = Object.getOwnPropertyNames(source); + for (let i = 0, len = propertyNames.length; i < len; ++i) { + const propertyName: string = propertyNames[i]; + if (excepts.indexOf(propertyName) !== -1) { + continue; + } + + _copyprop(propertyName, source, target); + } +} + /** + * @en * Copy all properties not defined in object from arguments[1...n]. + * @zh + * 如果目标对象上没有该属性,则将源对象属性拷贝到目标对象上 * @param object Object to extend its properties. * @param sources Source object to copy properties from. * @return The result object. */ -export function addon (object?: any, ...sources: any[]) { +export function addon (object?: Record, ...sources: any[]) { object = object || {}; for (const source of sources) { if (source) { @@ -365,10 +417,13 @@ export function addon (object?: any, ...sources: any[]) { } /** + * @en * Copy all properties from arguments[1...n] to object. + * @zh + * 拷贝源对象所有属性到目标对象上,如果有属性冲突,则以源对象为准 * @return The result object. */ -export function mixin (object?: any, ...sources: any[]) { +export function mixin (object?: Record, ...sources: any[]) { object = object || {}; for (const source of sources) { if (source) { @@ -385,12 +440,17 @@ export function mixin (object?: any, ...sources: any[]) { } /** + * @en * Derive the class from the supplied base class. * Both classes are just native javascript constructors, not created by `Class`, so - * usually you will want to inherit using [[Class]] instead. + * usually you will want to inherit using [[CCClass]] instead. + * @zh + * 将一个类型继承另一个类型 + * 两个类型都需要是 javascript 的构建函数,而不是 `Class`, 所以你通常可以用 [[CCClass]] 来代替 * @param base The baseclass to inherit. * @return The result class. */ +// eslint-disable-next-line @typescript-eslint/ban-types export function extend (cls: Function, base: Function) { if (DEV) { if (!base) { @@ -405,6 +465,7 @@ export function extend (cls: Function, base: Function) { errorID(5406); } } + // eslint-disable-next-line no-prototype-builtins for (const p in base) { if (base.hasOwnProperty(p)) { cls[p] = base[p]; } } cls.prototype = Object.create(base.prototype, { constructor: { @@ -413,21 +474,33 @@ export function extend (cls: Function, base: Function) { configurable: true, }, }); + // eslint-disable-next-line consistent-return return cls; } /** + * @en * Get super class. + * @zh + * 获取父类 * @param constructor The constructor of subclass. */ +// eslint-disable-next-line @typescript-eslint/ban-types export function getSuper (constructor: Function) { const proto = constructor.prototype; // binded function do not have prototype const dunderProto = proto && Object.getPrototypeOf(proto); + // eslint-disable-next-line @typescript-eslint/no-unsafe-return return dunderProto && dunderProto.constructor; } /** + * @en * Checks whether subclass is child of superclass or equals to superclass. + * @zh + * 判断一类型是否是另一类型的子类或本身 + * @param subclass sub class to be checked + * @param superclass super class to be checked + * @return whether subclass is child of superclass */ export function isChildClassOf (subclass: unknown, superclass: unknown) { if (subclass && superclass) { @@ -444,6 +517,7 @@ export function isChildClassOf (subclass: unknown, superclass: unknown) { return true; } for (; ;) { + // eslint-disable-next-line @typescript-eslint/ban-types subclass = getSuper(subclass as Function); if (!subclass) { return false; @@ -457,9 +531,12 @@ export function isChildClassOf (subclass: unknown, superclass: unknown) { } /** + * @en * Removes all enumerable properties from object. + * @zh + * 移除对象中所有可枚举属性 */ -export function clear (object: {}) { +export function clear (object: Record) { for (const key of Object.keys(object)) { delete object[key]; } @@ -471,17 +548,18 @@ function isTempClassId (id) { // id registration /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ export const _idToClass: Record = createMap(true); /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ export const _nameToClass: Record = createMap(true); -function setup (tag: string, table: object) { +function setup (tag: string, table: Record, allowExist: boolean) { return function (id: string, constructor: Constructor) { // deregister old + // eslint-disable-next-line no-prototype-builtins if (constructor.prototype.hasOwnProperty(tag)) { delete table[constructor.prototype[tag]]; } @@ -489,9 +567,10 @@ function setup (tag: string, table: object) { // register class if (id) { const registered = table[id]; - if (registered && registered !== constructor) { + if (!allowExist && registered && registered !== constructor) { let err = `A Class already exists with the same ${tag} : "${id}".`; if (TEST) { + // eslint-disable-next-line no-multi-str err += ' (This may be caused by error of unit test.) \ If you dont need serialization, you can set class id to "". You can also call \ js.unregisterClass to remove the id of unused class'; @@ -508,18 +587,24 @@ js.unregisterClass to remove the id of unused class'; } /** + * @en * Register the class by specified id, if its classname is not defined, the class name will also be set. + * @zh + * 通过 id 注册类型 * @method _setClassId * @param classId * @param constructor - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ -export const _setClassId = setup('__cid__', _idToClass); +export const _setClassId = setup('__cid__', _idToClass, false); -const doSetClassName = setup('__classname__', _nameToClass); +const doSetClassName = setup('__classname__', _nameToClass, true); /** + * @en * Register the class by specified name manually + * @zh + * 通过指定的名称手动注册类型 * @method setClassName * @param className * @param constructor @@ -527,6 +612,7 @@ const doSetClassName = setup('__classname__', _nameToClass); export function setClassName (className: string, constructor: Constructor) { doSetClassName(className, constructor); // auto set class id + // eslint-disable-next-line no-prototype-builtins if (!constructor.prototype.hasOwnProperty(classIdTag)) { const id = className || tempCIDGenerator.getNewId(); if (id) { @@ -543,8 +629,8 @@ export function setClassName (className: string, constructor: Constructor) { * @zh 为类设置别名。 * 当 `setClassAlias(target, alias)` 后, * `alias` 将作为类 `target`的“单向 ID” 和“单向名称”。 - * 因此,`_getClassById(alias)` 和 `getClassByName(alias)` 都会得到 `target`。 - * 这种映射是单向的,意味着 `getClassName(target)` 和 `_getClassId(target)` 将不会是 `alias`。 + * 因此,`getClassById(alias)` 和 `getClassByName(alias)` 都会得到 `target`。 + * 这种映射是单向的,意味着 `getClassName(target)` 和 `getClassId(target)` 将不会是 `alias`。 * @param target Constructor of target class. * @param alias Alias to set. The name shall not have been set as class name or alias of another class. */ @@ -573,13 +659,18 @@ export function setClassAlias (target: Constructor, alias: string) { } /** - * Unregister a class from fireball. + * @en + * Unregister a class from cocos. * - * If you dont need a registered class anymore, you should unregister the class so that Fireball will not keep its reference anymore. + * If you dont need a registered class anymore, you should unregister the class so that cocos will not keep its reference anymore. * Please note that its still your responsibility to free other references to the class. + * @zh + * 取消注册类型,如果你不再需要一个注册的类,你应该取消注册这个类,这样 cocos 就不会再保留它的引用。 + * 请注意,你仍然有责任释放对该类的其他引用。 * * @param ...constructor - the class you will want to unregister, any number of classes can be added */ +// eslint-disable-next-line @typescript-eslint/ban-types export function unregisterClass (...constructors: Function[]) { for (const constructor of constructors) { const p = constructor.prototype; @@ -603,17 +694,35 @@ export function unregisterClass (...constructors: Function[]) { } /** + * @en * Get the registered class by id + * @zh + * 通过 id 获取已注册的类型 * @param classId * @return constructor - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ export function _getClassById (classId) { + return getClassById(classId); +} + +/** + * @en + * Get the registered class by id + * @zh + * 通过 id 获取已注册的类型 + * @param classId + * @return constructor + */ +export function getClassById (classId) { return _idToClass[classId]; } /** + * @en * Get the registered class by name + * @zh + * 通过名字获取已注册的类型 * @param classname * @return constructor of the class */ @@ -622,31 +731,49 @@ export function getClassByName (classname) { } /** + * @en * Get class id of the object + * @zh + * 获取对象的 class id * @param obj - instance or constructor * @param [allowTempId = true] - can return temp id in editor * @return - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ export function _getClassId (obj, allowTempId?: boolean) { + return getClassId(obj, allowTempId); +} + +/** + * @en + * Get class id of the object + * @zh + * 获取对象的 class id + * @param obj - instance or constructor + * @param [allowTempId = true] - can return temp id in editor + * @return + */ +export function getClassId (obj, allowTempId?: boolean) { allowTempId = (typeof allowTempId !== 'undefined' ? allowTempId : true); let res; + // eslint-disable-next-line no-prototype-builtins if (typeof obj === 'function' && obj.prototype.hasOwnProperty(classIdTag)) { res = obj.prototype[classIdTag]; if (!allowTempId && (DEV || EDITOR) && isTempClassId(res)) { return ''; } - return res; + return res as string; } if (obj && obj.constructor) { const prototype = obj.constructor.prototype; + // eslint-disable-next-line no-prototype-builtins if (prototype && prototype.hasOwnProperty(classIdTag)) { res = obj[classIdTag]; if (!allowTempId && (DEV || EDITOR) && isTempClassId(res)) { return ''; } - return res; + return res as string; } } return ''; diff --git a/cocos/core/utils/js.ts b/cocos/core/utils/js.ts index f97945f798..36097e7e6c 100644 --- a/cocos/core/utils/js.ts +++ b/cocos/core/utils/js.ts @@ -40,7 +40,9 @@ import { formatStr, get, getClassByName, + getClassById, getClassName, + getClassId, getPropertyDescriptor, getset, getSuper, @@ -90,10 +92,11 @@ export const js = { setClassName, setClassAlias, getClassByName, + getClassById, /** * @en All classes registered in the engine, indexed by name. * @zh 引擎中已注册的所有类型,通过名称进行索引。 - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. * @example * ``` * import { js } from 'cc'; @@ -107,7 +110,7 @@ export const js = { * js._registeredClassNames = builtinClassNames; * ``` * - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ get _registeredClassNames (): typeof _nameToClass { return { ..._nameToClass }; @@ -132,7 +135,7 @@ export const js = { * js._registeredClassNames = builtinClassNames; * ``` * - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ get _registeredClassIds (): typeof _idToClass { return { ..._idToClass }; @@ -142,15 +145,16 @@ export const js = { Object.assign(_idToClass, value); }, /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ _getClassId, + getClassId, /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ _setClassId, /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ _getClassById, obsolete, diff --git a/cocos/core/utils/jsb-utils.ts b/cocos/core/utils/jsb-utils.ts index 9e73734ae3..4e013dc7e6 100644 --- a/cocos/core/utils/jsb-utils.ts +++ b/cocos/core/utils/jsb-utils.ts @@ -110,26 +110,25 @@ export function updateChildrenForDeserialize (node: Node) { if (!node) { return; } + // @ts-expect-error: jsb related codes. - node._setChildren(node._children); + const children = node._children; + if (!children) { + return; + } + + const len = children.length; + if (!len) { + return; + } + // @ts-expect-error: jsb related codes. - for (let i = 0, len = node._children.length; i < len; ++i) { - // @ts-expect-error: jsb related codes. - const child = node._children[i]; - // jsb.registerNativeRef(node, child); + node._setChildren(children); + + for (let i = 0; i < len; ++i) { + const child = children[i]; updateChildrenForDeserialize(child); } - // Object.defineProperty(node, '_children', { - // enumerable: true, - // configurable: true, - // get () { - // return this.getChildren(); - // }, - // set (v) { - // this._setChildren(v); - // }, - // }); - // node._isChildrenRedefined = true; } // export function updateChildren (node: Node) { diff --git a/cocos/core/utils/misc.ts b/cocos/core/utils/misc.ts index 4566ce0f33..31bdf6d601 100644 --- a/cocos/core/utils/misc.ts +++ b/cocos/core/utils/misc.ts @@ -24,8 +24,6 @@ THE SOFTWARE. */ - - /* eslint-disable no-new-func */ import { EDITOR, DEV } from 'internal:constants'; @@ -45,6 +43,7 @@ for (let i = 0; i < 64; ++i) { values[BASE64_KEYS.charCodeAt(i)] = i; } export const BASE64_VALUES = values; /** + * @engineInternal * @param ctor * @param sameNameGetSets * @param diffNameGetSets @@ -159,15 +158,18 @@ export function isPlainEmptyObj_DEV (obj) { } /** - * @en Clamp a value between from and to. + * @en Clamp a value between from and to.
+ * if the original value is larger than max_inclusive, return max_inclusive.
+ * if the original value is smaller than min_inclusive, return min_inclusive.
+ * else return the original value. * @zh 限定浮点数的最大最小值。
* 数值大于 max_inclusive 则返回 max_inclusive。
* 数值小于 min_inclusive 则返回 min_inclusive。
* 否则返回自身。 - * @param value 目标值 - * @param min_inclusive 最小值 - * @param max_inclusive 最大值 - * @return {Number} + * @param value @en Original value @zh 初始值 + * @param min_inclusive @en Minimum value in between @zh 最小值 + * @param max_inclusive @en Maximum value in between @zh 最大值 + * @return {Number} @en The value clamped @zh 目标值 * @example * var v1 = clampf(20, 0, 20); // 20; * var v2 = clampf(-1, 0, 20); // 0; @@ -185,8 +187,8 @@ export function clampf (value: number, min_inclusive: number, max_inclusive: num /** * @en converts degrees to radians * @zh 角度转弧度 - * @param angle 角度 - * @return {Number} + * @param angle @en The degree to convert @zh 角度 + * @return {Number} The radian. @zh 弧度 */ export function degreesToRadians (angle: number) { return angle * macro.RAD; @@ -195,8 +197,8 @@ export function degreesToRadians (angle: number) { /** * @en converts radians to degrees * @zh 弧度转角度 - * @param angle 弧度 - * @return {Number} + * @param angle @en The radian to convert @zh 弧度 + * @return {Number} @en The degree @zh 角度 */ export function radiansToDegrees (angle) { return angle * macro.DEG; diff --git a/cocos/core/utils/murmurhash2_gc.ts b/cocos/core/utils/murmurhash2_gc.ts index 5465c92b27..18824abd12 100644 --- a/cocos/core/utils/murmurhash2_gc.ts +++ b/cocos/core/utils/murmurhash2_gc.ts @@ -36,8 +36,6 @@ * @return {number} 32-bit positive integer hash */ - - const getUint8ForString = String.prototype.charCodeAt; function getUint8ForArray (this: Uint8Array, idx: number) { return this[idx]; } diff --git a/cocos/core/utils/mutable-forward-iterator.ts b/cocos/core/utils/mutable-forward-iterator.ts index 0c7760513c..f324c709e2 100644 --- a/cocos/core/utils/mutable-forward-iterator.ts +++ b/cocos/core/utils/mutable-forward-iterator.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ - /** * @example * ``` diff --git a/cocos/core/utils/path.ts b/cocos/core/utils/path.ts index 725e0d0299..cdc452d327 100644 --- a/cocos/core/utils/path.ts +++ b/cocos/core/utils/path.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ - import { systemInfo } from 'pal/system-info'; import { OS } from '../../../pal/system-info/enum-type'; diff --git a/cocos/core/utils/pool.ts b/cocos/core/utils/pool.ts index 784eaa5ffb..7a75264bfa 100644 --- a/cocos/core/utils/pool.ts +++ b/cocos/core/utils/pool.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core - */ - type CleanUpFunction = (value: T) => boolean | void; /** @@ -139,7 +134,7 @@ export default class Pool { * @zh * 获取对象池中的对象,如果对象池没有可用对象,则返回空。 * - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _get () { if (this.count > 0) { diff --git a/cocos/core/utils/prefab-link.ts b/cocos/core/utils/prefab-link.ts index ebf6b6aeb1..68583191bd 100644 --- a/cocos/core/utils/prefab-link.ts +++ b/cocos/core/utils/prefab-link.ts @@ -1,4 +1,4 @@ -import { ccclass, menu, serializable, type, visible } from '../data/decorators'; +import { ccclass, serializable, type, visible } from '../data/decorators'; import { Component } from '../components/component'; import { Prefab } from '../assets/prefab'; diff --git a/cocos/core/utils/prefab/prefab-info.ts b/cocos/core/utils/prefab/prefab-info.ts index c2d937ba5c..4d817b22a4 100644 --- a/cocos/core/utils/prefab/prefab-info.ts +++ b/cocos/core/utils/prefab/prefab-info.ts @@ -6,7 +6,7 @@ import { CCObject } from '../../data'; import { Component } from '../../components'; import { Node } from '../../scene-graph'; -function compareStringArray (array1: string[]|undefined, array2: string[]|undefined) { +function compareStringArray(array1: string[] | undefined, array2: string[] | undefined) { if (!array1 || !array2) { return false; } @@ -28,20 +28,20 @@ export class TargetInfo { export class TargetOverrideInfo { @serializable @type(CCObject) - public source: Component|Node|null = null; + public source: Component | Node | null = null; // if owner is in a prefab, use TargetInfo to index it @serializable @type(TargetInfo) - public sourceInfo: TargetInfo|null = null; + public sourceInfo: TargetInfo | null = null; @serializable public propertyPath: string[] = []; @serializable @type(Node) - public target: Node|null = null; + public target: Node | null = null; // if target is in a prefab, use TargetInfo to index it @serializable @type(TargetInfo) - public targetInfo: TargetInfo|null = null; + public targetInfo: TargetInfo | null = null; } @ccclass('cc.CompPrefabInfo') @@ -56,17 +56,17 @@ export class CompPrefabInfo { export class PropertyOverrideInfo { @serializable @type(TargetInfo) - public targetInfo: TargetInfo|null = null; + public targetInfo: TargetInfo | null = null; @serializable public propertyPath: string[] = []; @serializable public value: any; // eslint-disable-next-line consistent-return - public isTarget (localID: string[], propPath: string[]) { + public isTarget(localID: string[], propPath: string[]) { if (EDITOR) { return compareStringArray(this.targetInfo?.localID, localID) - && compareStringArray(this.propertyPath, propPath); + && compareStringArray(this.propertyPath, propPath); } } } @@ -75,13 +75,13 @@ export class PropertyOverrideInfo { export class MountedChildrenInfo { @serializable @type(TargetInfo) - public targetInfo: TargetInfo|null = null; + public targetInfo: TargetInfo | null = null; @serializable @type([Node]) public nodes: Node[] = []; // eslint-disable-next-line consistent-return - public isTarget (localID: string[]) { + public isTarget(localID: string[]) { if (EDITOR) { return compareStringArray(this.targetInfo?.localID, localID); } @@ -92,13 +92,13 @@ export class MountedChildrenInfo { export class MountedComponentsInfo { @serializable @type(TargetInfo) - public targetInfo: TargetInfo|null = null; + public targetInfo: TargetInfo | null = null; @serializable @type([Component]) public components: Component[] = []; // eslint-disable-next-line consistent-return - public isTarget (localID: string[]) { + public isTarget(localID: string[]) { if (EDITOR) { return compareStringArray(this.targetInfo?.localID, localID); } @@ -107,6 +107,7 @@ export class MountedComponentsInfo { /** * Prefab实例类 + * @internal */ @ccclass('cc.PrefabInstance') export class PrefabInstance { @@ -140,8 +141,14 @@ export class PrefabInstance { public targetMap: Record = {}; + /** + * make sure prefab instance expand only once + * @internal + */ + public expanded = false; + // eslint-disable-next-line consistent-return - public findPropertyOverride (localID: string[], propPath: string[]) { + public findPropertyOverride(localID: string[], propPath: string[]) { if (EDITOR) { for (let i = 0; i < this.propertyOverrides.length; i++) { const propertyOverride = this.propertyOverrides[i]; @@ -153,7 +160,7 @@ export class PrefabInstance { } } - public removePropertyOverride (localID: string[], propPath: string[]) { + public removePropertyOverride(localID: string[], propPath: string[]) { if (EDITOR) { for (let i = 0; i < this.propertyOverrides.length; i++) { const propertyOverride = this.propertyOverrides[i]; diff --git a/cocos/core/utils/prefab/utils.ts b/cocos/core/utils/prefab/utils.ts index e140b49b6c..962a1fa561 100644 --- a/cocos/core/utils/prefab/utils.ts +++ b/cocos/core/utils/prefab/utils.ts @@ -24,8 +24,6 @@ THE SOFTWARE. */ - - import { EDITOR, SUPPORT_JIT } from 'internal:constants'; import { legacyCC } from '../../global-exports'; import type { Node } from '../../scene-graph/node'; @@ -62,7 +60,7 @@ export function createNodeWithPrefab (node: Node) { } // save root's preserved props to avoid overwritten by prefab - const _objFlags = node._objFlags; + const _objFlags = node._objFlags; // @ts-expect-error: private member access const _parent = node._parent; // @ts-expect-error: private member access @@ -150,7 +148,7 @@ export function getTarget (localID: string[], targetMap: any) { return null; } - let target: Component|Node|null = null; + let target: Component | Node | null = null; let targetIter: any = targetMap; for (let i = 0; i < localID.length; i++) { if (!targetIter) { @@ -188,7 +186,8 @@ export function applyMountedChildren (node: Node, mountedChildren: MountedChildr for (let i = 0; i < childInfo.nodes.length; i++) { const childNode = childInfo.nodes[i]; - if (!childNode) { + // @ts-expect-error private member access + if (!childNode || target._children.includes(childNode)) { continue; } @@ -335,10 +334,10 @@ export function applyTargetOverrides (node: BaseNode) { // @ts-expect-error private member access const targetOverrides = node._prefab?.targetOverrides; if (targetOverrides) { - for (let i = 0; i < targetOverrides.length; i++) { + for (let i = 0; i < targetOverrides.length; i++) { const targetOverride = targetOverrides[i]; - let source: Node|Component|null = targetOverride.source; + let source: Node | Component | null = targetOverride.source; const sourceInfo = targetOverride.sourceInfo; if (sourceInfo) { // @ts-expect-error private member access @@ -353,7 +352,7 @@ export function applyTargetOverrides (node: BaseNode) { continue; } - let target: Node|Component|null = null; + let target: Node | Component | null = null; const targetInfo = targetOverride.targetInfo; if (!targetInfo) { continue; @@ -400,20 +399,28 @@ export function expandPrefabInstanceNode (node: Node, recursively = false) { // @ts-expect-error private member access const prefabInfo = node._prefab; const prefabInstance = prefabInfo?.instance; - if (prefabInstance) { + if (prefabInstance && !prefabInstance.expanded) { createNodeWithPrefab(node); + // nested prefab should expand before parent(property override order) + if (recursively) { + if (node && node.children) { + node.children.forEach((child) => { + expandPrefabInstanceNode(child, true); + }); + } + } + // nested prefab children's id will be the same: 3dtask#12511 + // applyNodeAndComponentId(node, node.uuid); const targetMap: Record = {}; prefabInstance.targetMap = targetMap; generateTargetMap(node, targetMap, true); - applyMountedChildren(node, prefabInstance.mountedChildren, targetMap); applyRemovedComponents(node, prefabInstance.removedComponents, targetMap); applyMountedComponents(node, prefabInstance.mountedComponents, targetMap); applyPropertyOverrides(node, prefabInstance.propertyOverrides, targetMap); - } - - if (recursively) { + prefabInstance.expanded = true; + } else if (recursively) { if (node && node.children) { node.children.forEach((child) => { expandPrefabInstanceNode(child, true); @@ -432,3 +439,17 @@ export function expandNestedPrefabInstanceNode (node: BaseNode) { }); } } + +export function applyNodeAndComponentId (node: Node, rootId: string) { + const { components, children } = node; + for (let i = 0; i < components.length; i++) { + const comp = components[i]; + comp._id = `${rootId}${comp.__prefab?.fileId}`; + } + for (let i = 0; i < children.length; i++) { + const child = children[i]; + // @ts-expect-error private member access + child._id = `${rootId}${child._prefab?.fileId}`; + applyNodeAndComponentId(child, rootId); + } +} diff --git a/cocos/core/utils/x-deprecated.ts b/cocos/core/utils/x-deprecated.ts index b99565671a..1f06c27e87 100644 --- a/cocos/core/utils/x-deprecated.ts +++ b/cocos/core/utils/x-deprecated.ts @@ -29,10 +29,13 @@ /* eslint-disable @typescript-eslint/no-unsafe-return */ /* eslint-disable prefer-const */ -import { error, warn } from '../platform/debug'; +import { error, errorID, warn, warnID } from '../platform/debug'; let defaultLogTimes = 10; +/** + * @deprecated since v3.6.0, this is an engine private interface that will be removed in the future. + */ export function setDefaultLogTimes (times: number): void { if (times > 0) { defaultLogTimes = times; @@ -78,10 +81,19 @@ interface IMarkItem { suggest?: string; } +/** + * @deprecated since v3.6.0, this is an engine private interface that will be removed in the future. + */ export let replaceProperty: (owner: object, ownerName: string, properties: IReplacement[]) => void; +/** + * @deprecated since v3.6.0, this is an engine private interface that will be removed in the future. + */ export let removeProperty: (owner: object, ownerName: string, properties: IRemoveItem[]) => void; +/** + * @deprecated since v3.6.0, this is an engine private interface that will be removed in the future. + */ export let markAsWarning: (owner: object, ownerName: string, properties: IMarkItem[]) => void; let replacePropertyLog: (n: string, dp: string, n2: string, newp: string, f: Function, id: number, s: string) => void; @@ -283,3 +295,110 @@ markAsWarning = (owner: object, ownerName: string, properties: IMarkItem[]) => { // removePropertyLog = () => { }; // markAsWarningLog = () => { }; // } + +/** + * @engineInternal + */ +interface IDeprecateInfo { + newName?: string; + since: string; + removed: boolean, +} + +/** + * @engineInternal + */ +interface TopLevelDeprecateList { + [name: string]: IDeprecateInfo | undefined; +} + +const topLevelDeprecateList: TopLevelDeprecateList = { +}; + +/** + * This is an internal method to register the deprecate info of module exported binding name. + * DO NOT USE THIS INTERFACE. + * + * @example + * ```ts + * deprecateModuleExportedName({ + * ButtonComponent: { + * newName: 'Button', + * since: '1.2.0', + * removed: false, + * }, + * }); + * ``` + * @engineInternal + */ +export function deprecateModuleExportedName (deprecateList: TopLevelDeprecateList) { + for (let deprecateName in deprecateList) { + const deprecateInfo = deprecateList[deprecateName]; + topLevelDeprecateList[deprecateName] = deprecateInfo; + } +} + +function _checkObsoleteByName (checkName: string) { + const deprecateInfo = topLevelDeprecateList[checkName]; + if (!deprecateInfo) { + return; + } + const { newName, since, removed } = deprecateInfo; + if (removed) { + if (newName) { + errorID(16003, checkName, since, newName); + } else { + errorID(16002, checkName, since); + } + } else if (newName) { + warnID(16001, checkName, since, newName); + } else { + warnID(16000, checkName, since); + } +} + +/** + * An internal method to check whether the top level interface is deprecated. + * DO NOT USE THIS INTERFACE. + * + * @example + * ```ts + * // print deprecate info of ButtonComponent and ToggleComponent + * import { ButtonComponent, ToggleComponent } from 'cc'; + * ``` + * @engineInternal + */ +export function __checkObsolete__ (checkList: string[]) { + for (let checkName of checkList) { + _checkObsoleteByName(checkName); + } +} + +let _cachedProxy; +/** + * An internal method to check whether the top level interface is deprecated in namespace. + * DO NOT USE THIS INTERFACE. + * + * @example + * ```ts + * import * as cc from 'cc'; + * console.log(cc.ButtonComponent); // print deprecate info of ButtonComponent + * ``` + * @engineInternal + */ +export function __checkObsoleteInNamespace__ (ccNamespace: object) { + if (!_cachedProxy) { + if (typeof Proxy === 'undefined') { + _cachedProxy = {}; + } else { + _cachedProxy = new Proxy(ccNamespace, { + get (target, name, receiver) { + // @ts-expect-error name could be a symbol + _checkObsoleteByName(name); + return Reflect.get(target, name, receiver); + }, + }); + } + } + return _cachedProxy; +} diff --git a/cocos/core/value-types/bitmask.ts b/cocos/core/value-types/bitmask.ts index f81741cce2..acacd57a41 100644 --- a/cocos/core/value-types/bitmask.ts +++ b/cocos/core/value-types/bitmask.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core/value-types - */ - import { EDITOR, TEST } from 'internal:constants'; import { value } from '../utils/js'; import { legacyCC } from '../global-exports'; @@ -38,8 +33,10 @@ import { errorID } from '../platform/debug'; * Define an BitMask type. * @zh * 定义一个位掩码类型。 - * @param obj A JavaScript literal object containing BitMask names and values - * @return The defined BitMask type + * @param obj + * @en A JavaScript literal object containing BitMask names and values. + * @zh 包含 BitMask 名称和值的 JavaScript 文字对象。 + * @return @en The defined BitMask type @zh 定义的位掩码类型。 */ export function BitMask (obj: T): T { if ('__bitmask__' in obj) { diff --git a/cocos/core/value-types/enum.ts b/cocos/core/value-types/enum.ts index 9b40a4a47d..9d53f730a2 100644 --- a/cocos/core/value-types/enum.ts +++ b/cocos/core/value-types/enum.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core/value-types - */ - import { EDITOR, TEST, DEV } from 'internal:constants'; import { value } from '../utils/js'; import { legacyCC } from '../global-exports'; @@ -45,8 +40,10 @@ import { assertIsTrue } from '../data/utils/asserts'; * 定义一个枚举类型。
* 用户可以把枚举值设为任意的整数,如果设为 -1,系统将会分配为上一个枚举值 + 1。 * - * @param obj - a JavaScript literal object containing enum names and values, or a TypeScript enum type - * @return the defined enum type + * @param obj + * @en A JavaScript literal object containing enum names and values, or a TypeScript enum type. + * @zh 包含枚举名和值的 JavaScript literal 对象,或者是一个 TypeScript enum 类型。 + * @return @en The defined enum type. @zh 定义的枚举类型。 */ export function Enum (obj: T): T { if ('__enums__' in obj) { @@ -61,7 +58,7 @@ export function Enum (obj: T): T { * Update the enum object properties. * @zh * 更新枚举对象的属性列表。 - * @param obj + * @param obj @en The enum object to update. @zh 需要更新的枚举对象。 */ Enum.update = (obj: T): T => { let lastIndex = -1; @@ -115,7 +112,7 @@ interface EnumExtras { /** * Determines if the object is an enum type. - * @param enumType The object to judge. + * @param enumType @en The object to judge. @zh 需要判断的对象。 */ Enum.isEnum = (enumType: EnumT) => enumType && enumType.hasOwnProperty('__enums__'); @@ -125,7 +122,7 @@ function assertIsEnum (enumType: EnumT): asserts enumType is /** * Get the enumerators from the enum type. - * @param enumType An enum type. + * @param enumType @en An enum type. @zh 枚举类型。 */ Enum.getList = (enumType: EnumT): readonly Enum.Enumerator[] => { assertIsEnum(enumType); @@ -139,7 +136,7 @@ Enum.getList = (enumType: EnumT): readonly Enum.Enumerator (enumType: EnumT): readonly Enum.Enumerator[] { @@ -176,7 +173,9 @@ if (DEV) { * Formally, as a result of invocation on this function with enum type `enumType`: * - `Enum.isEnum(enumType)` returns `true`; * - `Enum.getList(enumType)` returns the enumerators of `enumType`. - * @param enumType An enum type, eg, a kind of type with similar semantic defined by TypeScript. + * @param + * @en enumType An enum type, eg, a kind of type with similar semantic defined by TypeScript. + * @zh 枚举类型,例如 TypeScript 中定义的类型。 */ export function ccenum (enumType: EnumT) { if (!('__enums__' in enumType)) { diff --git a/cocos/core/value-types/index.ts b/cocos/core/value-types/index.ts index a79dbb7e4b..364cfe807f 100644 --- a/cocos/core/value-types/index.ts +++ b/cocos/core/value-types/index.ts @@ -24,8 +24,6 @@ THE SOFTWARE. */ - - export { BitMask } from './bitmask'; export { Enum, ccenum } from './enum'; export { ValueType } from './value-type'; diff --git a/cocos/core/value-types/value-type.ts b/cocos/core/value-types/value-type.ts index c51809b105..530002a576 100644 --- a/cocos/core/value-types/value-type.ts +++ b/cocos/core/value-types/value-type.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module core/value-types - */ - import { errorID } from '../platform/debug'; import * as js from '../utils/js'; import { legacyCC } from '../global-exports'; @@ -40,14 +35,15 @@ import { legacyCC } from '../global-exports'; export class ValueType { /** * @en - * Clone the current object. The clone result of the object should be equal to the current object, i.e. satisfy `this.equals(this, value.clone())`. + * Clone the current object. The clone result of the object should be equal to the current object, + * i.e. satisfy `this.equals(this, value.clone())`. * The base version of this method do nothing and returns `this'. * The derived class **must** rewrite this method and the returned object should not be `this`, i.e. satisfy `this !== this.clone()`. * @zh * 克隆当前值。克隆的结果值应与当前值相等,即满足 `this.equals(this, value.clone())`。 * 本方法的基类版本简单地返回 `this`; * 派生类**必须**重写本方法,并且返回的对象不应当为 `this`,即满足 `this !== this.clone()`。 - * @returns The cloned object + * @returns @en The cloned object. @zh 克隆的对象。 */ public clone (): ValueType { errorID(100, `${js.getClassName(this)}.clone`); @@ -62,8 +58,8 @@ export class ValueType { * @zh * 判断当前值是否与指定值相等。此判断应当具有交换性,即满足 `this.equals(other) === other.equals(this)`。 * 本方法的基类版本简单地返回 `false`。 - * @param other 相比较的值。 - * @returns 相等则返回 `true`,否则返回 `false`。 + * @param other @en The other object @zh 指定值。 + * @returns @en `true` if equal, otherwise returns `false` @zh 如果相等,则返回 `true`,否则返回 `false`。 */ public equals (other: this) { // errorID(100, js.getClassName(this) + '.equals'); @@ -77,7 +73,7 @@ export class ValueType { * @zh * 赋值当前值使其与指定值相等。 * 本方法的基类版本简单地返回 `this`,派生类**必须**重写本方法。 - * @param other The other object + * @param other @en The other object. @zh 指定值。 */ public set (other: this) { errorID(100, `${js.getClassName(this)}.set`); @@ -90,10 +86,10 @@ export class ValueType { * @zh * 返回当前值的字符串表示。 * 本方法的基类版本返回空字符串。 - * @returns The string representation of the current object + * @returns @en The string representation of the current value. @zh 当前值的字符串表示。 */ public toString () { - return `${{}}`; + return `${''}`; } } js.setClassName('cc.ValueType', ValueType); diff --git a/cocos/dragon-bones/ArmatureCache.ts b/cocos/dragon-bones/ArmatureCache.ts index 1485a57c0e..67ecf6457f 100644 --- a/cocos/dragon-bones/ArmatureCache.ts +++ b/cocos/dragon-bones/ArmatureCache.ts @@ -1,6 +1,26 @@ -/** - * @packageDocumentation - * @module dragonBones +/* + Copyright (c) 2020-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 { Armature, BlendMode, Matrix } from '@cocos/dragonbones-js'; diff --git a/cocos/dragon-bones/ArmatureDisplay.ts b/cocos/dragon-bones/ArmatureDisplay.ts index c203ce0c68..90c378c13e 100644 --- a/cocos/dragon-bones/ArmatureDisplay.ts +++ b/cocos/dragon-bones/ArmatureDisplay.ts @@ -1,16 +1,36 @@ -/** - * @packageDocumentation - * @module dragonBones +/* + Copyright (c) 2020-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 { EDITOR } from 'internal:constants'; +import { EDITOR, JSB } from 'internal:constants'; import { Armature, Bone, EventObject } from '@cocos/dragonbones-js'; import { ccclass, executeInEditMode, help, menu } from '../core/data/class-decorator'; -import { Renderable2D } from '../2d/framework/renderable-2d'; +import { UIRenderer } from '../2d/framework/ui-renderer'; import { Node, CCClass, Color, Enum, ccenum, errorID, Texture2D, Material, RecyclePool, js, CCObject } from '../core'; import { EventTarget } from '../core/event'; import { BlendFactor } from '../core/gfx'; -import { displayName, editable, override, serializable, tooltip, type, visible } from '../core/data/decorators'; +import { displayName, displayOrder, editable, override, serializable, tooltip, type, visible } from '../core/data/decorators'; import { AnimationCache, ArmatureCache, ArmatureFrame } from './ArmatureCache'; import { AttachUtil } from './AttachUtil'; import { CCFactory } from './CCFactory'; @@ -22,6 +42,9 @@ import { MaterialInstance } from '../core/renderer/core/material-instance'; import { legacyCC } from '../core/global-exports'; import { ArmatureSystem } from './ArmatureSystem'; import { Batcher2D } from '../2d/renderer/batcher-2d'; +import { RenderEntity, RenderEntityType } from '../2d/renderer/render-entity'; +import { RenderDrawInfo } from '../2d/renderer/render-draw-info'; +import { director } from '../core/director'; enum DefaultArmaturesEnum { default = -1, @@ -134,7 +157,7 @@ interface BoneIndex extends Number { @help('i18n:dragonBones.ArmatureDisplay') @menu('DragonBones/ArmatureDisplay') @executeInEditMode -export class ArmatureDisplay extends Renderable2D { +export class ArmatureDisplay extends UIRenderer { static AnimationCacheMode = AnimationCacheMode; /** @@ -158,7 +181,7 @@ export class ArmatureDisplay extends Renderable2D { this._dragonAsset = value; this.destroyRenderData(); this._refresh(); - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { this._defaultArmatureIndex = 0; this._animationIndex = 0; } @@ -193,7 +216,7 @@ export class ArmatureDisplay extends Renderable2D { const animNames = this.getAnimationNames(this._armatureName); if (!this.animationName || animNames.indexOf(this.animationName) < 0) { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { this.animationName = animNames[0]; } else { // Not use default animation name at runtime @@ -367,19 +390,6 @@ export class ArmatureDisplay extends Renderable2D { this._debugBones = value; this._updateDebugDraw(); } - /** - * @en Enabled batch model, if skeleton is complex, do not enable batch, or will lower performance. - * @zh 开启合批,如果渲染大量相同纹理,且结构简单的骨骼动画,开启合批可以降低drawcall,否则请不要开启,cpu消耗会上升。 - * @property {Boolean} enableBatch - * @default false - */ - // @editable - // @tooltip('i18n:COMPONENT.dragon_bones.enabled_batch') - // get enableBatch () { return this._enableBatch; } - // set enableBatch (value) { - // this._enableBatch = value; - // this._updateBatch(); - // } /** * @en @@ -437,12 +447,6 @@ export class ArmatureDisplay extends Renderable2D { protected _debugBones = false; /* protected */ _debugDraw: Graphics | null = null; - /** - * @legacyPublic - */ - @serializable - public _enableBatch = false; - // DragonBones data store key. /** * @internal @@ -509,6 +513,14 @@ export class ArmatureDisplay extends Renderable2D { protected _sockets: DragonBoneSocket[] = []; private _inited; + 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]; + } constructor () { super(); @@ -531,6 +543,7 @@ export class ArmatureDisplay extends Renderable2D { } onLoad () { + super.onLoad(); // Adapt to old code,remove unuse child which is created by old code. // This logic can be remove after 2.2 or later. const children = this.node.children; @@ -573,7 +586,11 @@ export class ArmatureDisplay extends Renderable2D { owner: this, }; inst = new MaterialInstance(matInfo); - inst.recompileShaders({ USE_LOCAL: true }, 0); // TODO: not supported by ui + 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 + } this._materialCache[key] = inst; inst.overridePipelineStates({ blendState: { @@ -585,9 +602,23 @@ export class ArmatureDisplay extends Renderable2D { return inst; } + @override + @type(Material) + @displayOrder(0) + @displayName('CustomMaterial') + get customMaterial () { + return this._customMaterial; + } + set customMaterial (val) { + this._customMaterial = val; + this._cleanMaterialCache(); + this.setMaterial(this._customMaterial, 0); + this.markForUpdateRenderData(); + } + protected _render (batcher: Batcher2D) { - if (this._renderData && this._drawList) { - const rd = this._renderData; + if (this.renderData && this._drawList) { + const rd = this.renderData; const chunk = rd.chunk; const accessor = chunk.vertexAccessor; const meshBuffer = rd.getMeshBuffer()!; @@ -610,44 +641,13 @@ export class ArmatureDisplay extends Renderable2D { } } - // if change use batch mode, just clear material cache - _updateBatch () { - // const baseMaterial = this.getMaterial(0); - // if (baseMaterial) { - // baseMaterial.define('CC_USE_MODEL', !this.enableBatch); - // } - this._materialCache = {}; - this.markForUpdateRenderData(); - } - - // override base class _updateMaterial to set define value and clear material cache - _updateMaterial () { - // const baseMaterial = this.getMaterial(0); - // if (baseMaterial) { - // baseMaterial.define('CC_USE_MODEL', !this.enableBatch); - // baseMaterial.define('USE_TEXTURE', true); - - // const srcBlendFactor = this.premultipliedAlpha ? cc.gfx.BLEND_ONE : cc.gfx.BLEND_SRC_ALPHA; - // const dstBlendFactor = cc.gfx.BLEND_ONE_MINUS_SRC_ALPHA; - - // baseMaterial.setBlend( - // true, - // ccBLEND_FUNC_ADD, - // srcBlendFactor, srcBlendFactor, - // cc.gfx.BLEND_FUNC_ADD, - // dstBlendFactor, dstBlendFactor - // ); - // } - this.markForUpdateRenderData(); - } - __preload () { super.__preload(); this._init(); } _init () { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { const Flags = CCObject.Flags; this._objFlags |= (Flags.IsAnchorLocked | Flags.IsSizeLocked); // this._refreshInspector(); @@ -724,7 +724,7 @@ export class ArmatureDisplay extends Renderable2D { * @return {Boolean} */ isAnimationCached () { - if (EDITOR) return false; + if (EDITOR && !legacyCC.GAME_VIEW) return false; return this._cacheMode !== AnimationCacheMode.REALTIME; } @@ -774,14 +774,14 @@ export class ArmatureDisplay extends Renderable2D { frameCache.updateToFrame(); this._curFrame = frames[frames.length - 1]; // Update render data size if needed - if (this._renderData - && (this._renderData.vertexCount < frameCache.maxVertexCount - || this._renderData.indexCount < frameCache.maxIndexCount)) { + if (this.renderData + && (this.renderData.vertexCount < frameCache.maxVertexCount + || this.renderData.indexCount < frameCache.maxIndexCount)) { this.maxVertexCount = frameCache.maxVertexCount > this.maxVertexCount ? frameCache.maxVertexCount : this.maxVertexCount; this.maxIndexCount = frameCache.maxIndexCount > this.maxIndexCount ? frameCache.maxIndexCount : this.maxIndexCount; - this._renderData.resize(this.maxVertexCount, this.maxIndexCount); - if (!this._renderData.indices || this.maxIndexCount > this._renderData.indices.length) { - this._renderData.indices = new Uint16Array(this.maxIndexCount); + this.renderData.resize(this.maxVertexCount, this.maxIndexCount); + if (!this.renderData.indices || this.maxIndexCount > this.renderData.indices.length) { + this.renderData.indices = new Uint16Array(this.maxIndexCount); } } } @@ -802,14 +802,14 @@ export class ArmatureDisplay extends Renderable2D { if (!frameCache.isCompleted) { frameCache.updateToFrame(frameIdx); // Update render data size if needed - if (this._renderData - && (this._renderData.vertexCount < frameCache.maxVertexCount - || this._renderData.indexCount < frameCache.maxIndexCount)) { + if (this.renderData + && (this.renderData.vertexCount < frameCache.maxVertexCount + || this.renderData.indexCount < frameCache.maxIndexCount)) { this.maxVertexCount = frameCache.maxVertexCount > this.maxVertexCount ? frameCache.maxVertexCount : this.maxVertexCount; this.maxIndexCount = frameCache.maxIndexCount > this.maxIndexCount ? frameCache.maxIndexCount : this.maxIndexCount; - this._renderData.resize(this.maxVertexCount, this.maxIndexCount); - if (!this._renderData.indices || this.maxIndexCount > this._renderData.indices.length) { - this._renderData.indices = new Uint16Array(this.maxIndexCount); + this.renderData.resize(this.maxVertexCount, this.maxIndexCount); + if (!this.renderData.indices || this.maxIndexCount > this.renderData.indices.length) { + this.renderData.indices = new Uint16Array(this.maxIndexCount); } } } @@ -839,7 +839,7 @@ export class ArmatureDisplay extends Renderable2D { this._materialInstances = this._materialInstances.filter((instance) => !!instance); this._inited = false; - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { if (this._cacheMode === AnimationCacheMode.PRIVATE_CACHE) { this._armatureCache!.dispose(); this._armatureCache = null; @@ -884,7 +884,7 @@ export class ArmatureDisplay extends Renderable2D { // Switch Asset or Atlas or cacheMode will rebuild armature. if (this._armature) { // dispose pre build armature - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { if (this._preCacheMode === AnimationCacheMode.PRIVATE_CACHE) { this._armatureCache!.dispose(); } else if (this._preCacheMode === AnimationCacheMode.REALTIME) { @@ -903,7 +903,7 @@ export class ArmatureDisplay extends Renderable2D { this._preCacheMode = -1; } - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { if (this._cacheMode === AnimationCacheMode.SHARED_CACHE) { this._armatureCache = ArmatureCache.sharedCache; } else if (this._cacheMode === AnimationCacheMode.PRIVATE_CACHE) { @@ -924,7 +924,7 @@ export class ArmatureDisplay extends Renderable2D { } this._preCacheMode = this._cacheMode; - if (EDITOR || this._cacheMode === AnimationCacheMode.REALTIME) { + if (EDITOR && !legacyCC.GAME_VIEW || this._cacheMode === AnimationCacheMode.REALTIME) { this._displayProxy = this._factory!.buildArmatureDisplay(this.armatureName, this._armatureKey, '', atlasUUID) as CCArmatureDisplay; if (!this._displayProxy) return; this._displayProxy._ccNode = this.node; @@ -945,8 +945,6 @@ export class ArmatureDisplay extends Renderable2D { const aabb = armatureData.aabb; this.node._uiProps.uiTransformComp!.setContentSize(aabb.width, aabb.height); } - - this._updateBatch(); this.attachUtil.init(this); if (this.animationName) { @@ -993,7 +991,7 @@ export class ArmatureDisplay extends Renderable2D { _refresh () { this._buildArmature(); this._indexBoneSockets(); - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { // update inspector this._updateArmatureEnum(); this._updateAnimEnum(); @@ -1304,9 +1302,9 @@ export class ArmatureDisplay extends Renderable2D { } if (this._armature && this._assembler) { this._renderData = this._assembler.createData(this); - if (this._renderData) { - this.maxVertexCount = this._renderData.vertexCount; - this.maxIndexCount = this._renderData.indexCount; + if (this.renderData) { + this.maxVertexCount = this.renderData.vertexCount; + this.maxIndexCount = this.renderData.indexCount; } this.markForUpdateRenderData(); this._updateColor(); @@ -1341,6 +1339,17 @@ export class ArmatureDisplay extends Renderable2D { } } } + + private _cleanMaterialCache () { + for (const val in this._materialCache) { + this._materialCache[val].destroy(); + } + this._materialCache = {}; + } + + protected createRenderEntity () { + return new RenderEntity(RenderEntityType.DYNAMIC); + } } legacyCC.internal.ArmatureDisplay = ArmatureDisplay; diff --git a/cocos/dragon-bones/ArmatureSystem.ts b/cocos/dragon-bones/ArmatureSystem.ts index f14e016e43..058c6510a2 100644 --- a/cocos/dragon-bones/ArmatureSystem.ts +++ b/cocos/dragon-bones/ArmatureSystem.ts @@ -1,8 +1,32 @@ +/* + Copyright (c) 2020-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 { director } from '../core/director'; import { System } from '../core/components'; import { ArmatureDisplay } from './ArmatureDisplay'; import { legacyCC } from '../core/global-exports'; -import { errorID } from '../core'; export class ArmatureSystem extends System { /** @@ -57,6 +81,15 @@ export class ArmatureSystem extends System { armature.updateAnimation(dt); }); } + + public prepareRenderData () { + if (!this._armatures) { + return; + } + this._armatures.forEach((armature) => { + armature.markForUpdateRenderData(); + }); + } } legacyCC.internal.ArmatureSystem = ArmatureSystem; diff --git a/cocos/dragon-bones/AttachUtil.ts b/cocos/dragon-bones/AttachUtil.ts index 4c002333d7..715286ee82 100644 --- a/cocos/dragon-bones/AttachUtil.ts +++ b/cocos/dragon-bones/AttachUtil.ts @@ -1,6 +1,26 @@ -/** - * @packageDocumentation - * @module dragonBones +/* + Copyright (c) 2020-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 { Armature, Matrix } from '@cocos/dragonbones-js'; diff --git a/cocos/dragon-bones/CCArmatureDisplay.ts b/cocos/dragon-bones/CCArmatureDisplay.ts index 56ad1746d9..a41a164c93 100644 --- a/cocos/dragon-bones/CCArmatureDisplay.ts +++ b/cocos/dragon-bones/CCArmatureDisplay.ts @@ -1,18 +1,40 @@ /* eslint-disable @typescript-eslint/no-unsafe-return */ +/* + Copyright (c) 2020-2022 Xiamen Yaji Software Co., Ltd. -/** - * @packageDocumentation - * @module dragonBones + 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 { Armature, DisplayData, IEventDispatcher, Slot } from '@cocos/dragonbones-js'; import { ccclass } from '../core/data/class-decorator'; -import { Vec2, Node, Vec3 } from '../core'; +import { Node, Vec3 } from '../core'; import { EventTarget } from '../core/event'; // eslint-disable-next-line import/named import { CCSlot } from './CCSlot'; import { ArmatureDisplay } from './ArmatureDisplay'; +/** +* @deprecated since v3.5.1, this is an engine private interface that will be removed in the future. +*/ @ccclass('dragonBones.CCArmatureDisplay') export class CCArmatureDisplay extends DisplayData implements IEventDispatcher { get node () { return this; } diff --git a/cocos/dragon-bones/CCFactory.ts b/cocos/dragon-bones/CCFactory.ts index a4fab5295b..89010aabe2 100644 --- a/cocos/dragon-bones/CCFactory.ts +++ b/cocos/dragon-bones/CCFactory.ts @@ -1,6 +1,26 @@ -/** - * @packageDocumentation - * @module dragonBones +/* + Copyright (c) 2020-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 { EDITOR } from 'internal:constants'; @@ -12,22 +32,29 @@ import { TextureBase } from '../core/assets/texture-base'; import { CCSlot } from './CCSlot'; import { ArmatureDisplay } from './ArmatureDisplay'; import { CCArmatureDisplay } from './CCArmatureDisplay'; +import { legacyCC } from '../core/global-exports'; /** * DragonBones factory * @class CCFactory * @extends BaseFactory + * @deprecated since v3.5.1, this is an engine private interface that will be removed in the future. */ @ccclass('CCFactory') export class CCFactory extends BaseFactory implements ISchedulable { + static _factory: CCFactory | null = null; + /** + * @en + * Get an CCFactory instance + * @zh + * 获取一个 CCFactory 实例 * @method getInstance * @return {CCFactory} * @static * @example * let factory = CCFactory.getInstance(); */ - static _factory: CCFactory | null = null; static getInstance () { if (!CCFactory._factory) { CCFactory._factory = new CCFactory(); @@ -45,7 +72,7 @@ export class CCFactory extends BaseFactory implements ISchedulable { const eventManager = new CCArmatureDisplay(); this._dragonBones = new DragonBones(eventManager); - if (!EDITOR && director.getScheduler()) { + if (director.getScheduler()) { game.on(Game.EVENT_RESTART, this.onRestart, this); this.initUpdate(); } @@ -63,6 +90,7 @@ export class CCFactory extends BaseFactory implements ISchedulable { } update (dt: number) { + if (EDITOR && !legacyCC.GAME_VIEW) return; this._dragonBones.advanceTime(dt); } @@ -71,7 +99,7 @@ export class CCFactory extends BaseFactory implements ISchedulable { return dataParser.parseDragonBonesData(rawData, 1.0); } - // Build new aramture with a new display. + // Build new armature with a new display. buildArmatureDisplay (armatureName: string, dragonBonesName?: string, skinName?: string, textureAtlasName?: string) { const armature = this.buildArmature(armatureName, dragonBonesName, skinName, textureAtlasName); return armature ? armature._display : null; diff --git a/cocos/dragon-bones/CCSlot.ts b/cocos/dragon-bones/CCSlot.ts index 16fc45c9d0..4c742628c5 100644 --- a/cocos/dragon-bones/CCSlot.ts +++ b/cocos/dragon-bones/CCSlot.ts @@ -1,6 +1,26 @@ -/** - * @packageDocumentation - * @module dragonBones +/* + Copyright (c) 2020-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 { BoneType, BinaryOffset, Slot } from '@cocos/dragonbones-js'; @@ -9,7 +29,9 @@ import { ccclass } from '../core/data/class-decorator'; import { CCTextureData } from './CCTextureData'; // @skipLibCheck - +/** +* @deprecated since v3.5.1, this is an engine private interface that will be removed in the future. +*/ @ccclass('dragonBones.CCSlot') export class CCSlot extends Slot { static toString () { @@ -17,28 +39,39 @@ export class CCSlot extends Slot { } /** - * @legacyPublic + * @en Vertices in local coordinate system. + * @zh 局部坐标顶点数据 + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ _localVertices: number[]; /** - * @legacyPublic + * @en Indices array of vertex data + * @zh 顶点数组索引 + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ _indices: number[]; /** - * @legacyPublic + * @en Local transformation matrix + * @zh 局部坐标系变换矩阵 + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ _matrix: Mat4; /** - * @legacyPublic + * @en World transformation matrix + * @zh 世界坐标系变换矩阵 + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _worldMatrix: Mat4; + protected _worldMatrixDirty: boolean; /** - * @legacyPublic + * @en Color setting on a slot + * @zh 设置在 Slot 上的颜色 + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ _color: Color; diff --git a/cocos/dragon-bones/CCTextureData.ts b/cocos/dragon-bones/CCTextureData.ts index 78762e6848..50f0e70e1d 100644 --- a/cocos/dragon-bones/CCTextureData.ts +++ b/cocos/dragon-bones/CCTextureData.ts @@ -1,15 +1,37 @@ -/** - * @packageDocumentation - * @module dragonBones +/* + Copyright (c) 2020-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 { BaseObject, TextureAtlasData, TextureData } from '@cocos/dragonbones-js'; -import { Size, Vec2 } from '../core'; import { SpriteFrame } from '../2d'; import { TextureBase } from '../core/assets/texture-base'; import { ccclass } from '../core/data/decorators'; import { Rect } from '../core/math/rect'; +/** +* @deprecated since v3.5.1, this is an engine private interface that will be removed in the future. +*/ @ccclass('dragonBones.CCTextureAtlasData') export class CCTextureAtlasData extends TextureAtlasData { get renderTexture () { @@ -63,6 +85,9 @@ export class CCTextureAtlasData extends TextureAtlasData { } } +/** +* @deprecated since v3.5.1, this is an engine private interface that will be removed in the future. +*/ @ccclass('dragonBones.CCTextureData') export class CCTextureData extends TextureData { spriteFrame: SpriteFrame | null = null diff --git a/cocos/dragon-bones/DragonBonesAsset.ts b/cocos/dragon-bones/DragonBonesAsset.ts index 99b6c8aaeb..9eddfce0d8 100644 --- a/cocos/dragon-bones/DragonBonesAsset.ts +++ b/cocos/dragon-bones/DragonBonesAsset.ts @@ -1,18 +1,34 @@ -/* eslint-disable @typescript-eslint/no-unsafe-return */ +/* + Copyright (c) 2020-2022 Xiamen Yaji Software Co., Ltd. -/** - * @packageDocumentation - * @module dragonBones + 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 { EDITOR } from 'internal:constants'; -import { BinaryDataParser, DragonBonesData } from '@cocos/dragonbones-js'; import { Asset } from '../core/assets'; import { ccclass, serializable } from '../core/data/decorators'; import { ArmatureCache } from './ArmatureCache'; -import { Enum, JsonAsset, Node } from '../core'; +import { Enum, Node } from '../core'; import { CCFactory } from './CCFactory'; -import { property } from '../core/data/class-decorator'; import { legacyCC } from '../core/global-exports'; /** @@ -24,8 +40,10 @@ import { legacyCC } from '../core/global-exports'; @ccclass('dragonBones.DragonBonesAsset') export class DragonBonesAsset extends Asset { /** - * @en See http://developer.egret.com/cn/github/egret-docs/DB/dbLibs/dataFormat/index.html - * @zh 可查看 DragonBones 官方文档 http://developer.egret.com/cn/github/egret-docs/DB/dbLibs/dataFormat/index.html + * @en + * See http://developer.egret.com/cn/github/egret-docs/DB/dbLibs/dataFormat/index.html + * @zh + * 可查看 DragonBones 官方文档 http://developer.egret.com/cn/github/egret-docs/DB/dbLibs/dataFormat/index.html * @property {string} dragonBonesJson */ @serializable @@ -60,17 +78,13 @@ export class DragonBonesAsset extends Asset { reset () { this._clear(); - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { this._armaturesEnum = null; } } init (factory?: CCFactory, atlasUUID?: string) { - if (EDITOR) { - this._factory = factory || new CCFactory(); - } else { - this._factory = factory!; - } + this._factory = factory || CCFactory.getInstance(); if (!this._dragonBonesJsonData && this.dragonBonesJson) { this._dragonBonesJsonData = JSON.parse(this.dragonBonesJson); diff --git a/cocos/dragon-bones/DragonBonesAtlasAsset.ts b/cocos/dragon-bones/DragonBonesAtlasAsset.ts index 440a302c6e..bf6eeb5d4d 100644 --- a/cocos/dragon-bones/DragonBonesAtlasAsset.ts +++ b/cocos/dragon-bones/DragonBonesAtlasAsset.ts @@ -1,7 +1,28 @@ -/** - * @packageDocumentation - * @module dragonBones +/* + Copyright (c) 2020-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 { JSB } from 'internal:constants'; import { TextureAtlasData } from '@cocos/dragonbones-js'; import { Asset, Texture2D, Node } from '../core'; diff --git a/cocos/dragon-bones/assembler/index.ts b/cocos/dragon-bones/assembler/index.ts index 37e90a9ffa..63e7c389e6 100644 --- a/cocos/dragon-bones/assembler/index.ts +++ b/cocos/dragon-bones/assembler/index.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module dragonBones - */ + import { IAssemblerManager } from '../../2d/renderer/base'; import { ArmatureDisplay } from '../ArmatureDisplay'; diff --git a/cocos/dragon-bones/assembler/simple.ts b/cocos/dragon-bones/assembler/simple.ts index f111751ae3..867c4b76e9 100644 --- a/cocos/dragon-bones/assembler/simple.ts +++ b/cocos/dragon-bones/assembler/simple.ts @@ -1,10 +1,30 @@ -/** - * @packageDocumentation - * @module dragonBones +/* + Copyright (c) 2020-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 { Armature, BlendMode } from '@cocos/dragonbones-js'; -import { Color, Mat4, Node, Texture2D, Vec3, director } from '../../core'; +import { Color, Mat4, Node, Texture2D, director } from '../../core'; import { BlendFactor } from '../../core/gfx'; import { TextureBase } from '../../core/assets/texture-base'; import { vfmtPosUvColor } from '../../2d/renderer/vertex-format'; @@ -12,7 +32,7 @@ import { MaterialInstance } from '../../core/renderer/core/material-instance'; import { IAssembler } from '../../2d/renderer/base'; import { Batcher2D } from '../../2d/renderer/batcher-2d'; import { ArmatureFrame } from '../ArmatureCache'; -import { ArmatureDisplay, ArmatureDisplayDrawData } from '../ArmatureDisplay'; +import { ArmatureDisplay } from '../ArmatureDisplay'; import { CCSlot } from '../CCSlot'; import { legacyCC } from '../../core/global-exports'; import { StaticVBAccessor } from '../../2d/renderer/static-vb-accessor'; @@ -94,8 +114,6 @@ function _getSlotMaterial (tex: TextureBase | null, blendMode: BlendMode) { dst = BlendFactor.ONE_MINUS_SRC_ALPHA; break; } - - // const useModel = !_comp!.enableBatch; _comp!.setBlendHash(); return _comp!.getMaterialForBlend(src, dst); } @@ -426,11 +444,6 @@ function updateComponentRenderData (comp: ArmatureDisplay, batcher: Batcher2D) { } let worldMat: Mat4 | undefined; - if (_comp._enableBatch) { - worldMat = _node.worldMatrix as Mat4; - _mustFlush = false; - _handleVal |= NEED_BATCH; - } _vertexFloatCount = 0; _vertexOffset = 0; diff --git a/cocos/dragon-bones/category.json b/cocos/dragon-bones/category.json new file mode 100644 index 0000000000..c99291e5bf --- /dev/null +++ b/cocos/dragon-bones/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "DragonBones", + "en": "DragonBones" + }, + "description": { + "zh": "ArmatureDisplay 组件可以对 DragonBones(龙骨)资源进行渲染和播放。", + "en": "The ArmatureDisplay component can render and play DragonBones assets." + } +} \ No newline at end of file diff --git a/native/cocos/bindings/manual/jsb_extension_manual.h b/cocos/dragon-bones/deprecated.ts similarity index 76% rename from native/cocos/bindings/manual/jsb_extension_manual.h rename to cocos/dragon-bones/deprecated.ts index 3182338209..f1e1704c1a 100644 --- a/native/cocos/bindings/manual/jsb_extension_manual.h +++ b/cocos/dragon-bones/deprecated.ts @@ -1,7 +1,7 @@ -/**************************************************************************** - Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. +/* + Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. - http://www.cocos.com + 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, @@ -21,12 +21,14 @@ 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. -****************************************************************************/ + */ -#pragma once +import { removeProperty } from '../core/utils/x-deprecated'; +import { ArmatureDisplay } from './ArmatureDisplay'; -namespace se { -class Object; -} - -bool register_all_cocos2dx_extension_manual(se::Object *obj); +removeProperty(ArmatureDisplay.prototype, 'ArmatureDisplay', [ + { + name: '_enableBatch', + suggest: 'Not support batch render mode', + }, +]); diff --git a/cocos/dragon-bones/index.jsb.ts b/cocos/dragon-bones/index.jsb.ts index 47d2fa86de..193e2a6dfc 100644 --- a/cocos/dragon-bones/index.jsb.ts +++ b/cocos/dragon-bones/index.jsb.ts @@ -1,3 +1,28 @@ +/* + Copyright (c) 2020-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. + */ + export enum ExtensionType { FFD = 0, AdjustColor = 10, diff --git a/cocos/dragon-bones/index.ts b/cocos/dragon-bones/index.ts index 8c1099d428..f61305b53b 100644 --- a/cocos/dragon-bones/index.ts +++ b/cocos/dragon-bones/index.ts @@ -1,45 +1,28 @@ -/** - * @packageDocumentation - * @module dragonBones +/* + Copyright (c) 2020-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 { EDITOR } from 'internal:constants'; - -/** - * @en - * The global time scale of DragonBones. - * @zh - * DragonBones 全局时间缩放率。 - * @example - * dragonBones.timeScale = 0.8; - */ -// const _timeScale = 1.0; - -// TODO timescale -// Object.defineProperty(dragonBones, 'timeScale', { -// get () { -// return this._timeScale; -// }, -// set (value) { -// this._timeScale = value; -// const factory = this.CCFactory.getInstance(); -// factory._dragonBones.clock.timeScale = value; -// }, -// configurable: true, -// }); - -// export enum DisplayType { -// Image = 0, -// Armature = 1, -// Mesh = 2 -// } - -// export enum ArmatureType { -// Armature = 0, -// MovieClip = 1, -// Stage = 2 -// } - export enum ExtensionType { FFD = 0, AdjustColor = 10, @@ -89,5 +72,6 @@ export * from './DragonBonesAtlasAsset'; export * from './ArmatureDisplay'; export * from './AttachUtil'; export * from './assembler'; +export * from './deprecated'; export * from '@cocos/dragonbones-js'; diff --git a/cocos/input/category.json b/cocos/input/category.json new file mode 100644 index 0000000000..f83550c41d --- /dev/null +++ b/cocos/input/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "输入系统", + "en": "Input System" + }, + "description": { + "zh": "输入系统是玩家与游戏之间交互的桥梁,通过输入系统,开发者可以获取到玩家在设备上的所有操作,并做出相应反馈", + "en": "The input system is the bridge between the player and the game, through the input system, the developer can get all the actions of the player on the device and make the corresponding feedback" + } +} \ No newline at end of file diff --git a/cocos/input/deprecated-3.3.0.ts b/cocos/input/deprecated-3.3.0.ts new file mode 100644 index 0000000000..076adb430f --- /dev/null +++ b/cocos/input/deprecated-3.3.0.ts @@ -0,0 +1,9 @@ +import { deprecateModuleExportedName } from '../core/utils/x-deprecated'; + +deprecateModuleExportedName({ + SystemEventType: { + newName: 'Input.EventType', + since: '3.3.0', + removed: false, + }, +}); diff --git a/cocos/input/deprecated-3.4.0.ts b/cocos/input/deprecated-3.4.0.ts new file mode 100644 index 0000000000..ddd9001a10 --- /dev/null +++ b/cocos/input/deprecated-3.4.0.ts @@ -0,0 +1,14 @@ +import { deprecateModuleExportedName } from '../core/utils/x-deprecated'; + +deprecateModuleExportedName({ + SystemEvent: { + newName: 'Input', + since: '3.4.0', + removed: false, + }, + systemEvent: { + newName: 'input', + since: '3.4.0', + removed: false, + }, +}); diff --git a/cocos/input/deprecated.ts b/cocos/input/deprecated.ts index cb6a79ca0d..922682b314 100644 --- a/cocos/input/deprecated.ts +++ b/cocos/input/deprecated.ts @@ -23,7 +23,8 @@ THE SOFTWARE. */ - +import './deprecated-3.3.0'; +import './deprecated-3.4.0'; import { markAsWarning, replaceProperty } from '../core/utils/x-deprecated'; import { Event, EventKeyboard, EventMouse, EventTouch, SystemEventType } from './types'; import { SystemEvent } from './system-event'; diff --git a/cocos/input/input.ts b/cocos/input/input.ts index feb294a8d2..97176ceb94 100644 --- a/cocos/input/input.ts +++ b/cocos/input/input.ts @@ -24,8 +24,6 @@ THE SOFTWARE. */ - - import { EDITOR, NATIVE } from 'internal:constants'; import { TouchInputSource, MouseInputSource, KeyboardInputSource, AccelerometerInputSource } from 'pal/input'; import { touchManager } from '../../pal/input/touch-manager'; @@ -33,6 +31,7 @@ import { sys } from '../core/platform/sys'; import { EventTarget } from '../core/event/event-target'; import { Event, EventAcceleration, EventKeyboard, EventMouse, EventTouch, Touch } from './types'; import { InputEventType } from './types/event-enum'; +import { legacyCC } from '../core/global-exports'; export enum EventDispatcherPriority { GLOBAL = 0, @@ -146,6 +145,32 @@ export class Input { this._registerEventDispatcher(this._inputEventDispatcher); } + /** + * This should be a private method, but it's exposed for Editor Only. + */ + private _dispatchMouseDownEvent (nativeMouseEvent: any) { this._mouseInput.dispatchMouseDownEvent?.(nativeMouseEvent); } + /** + * This should be a private method, but it's exposed for Editor Only. + */ + private _dispatchMouseMoveEvent (nativeMouseEvent: any) { this._mouseInput.dispatchMouseMoveEvent?.(nativeMouseEvent); } + /** + * This should be a private method, but it's exposed for Editor Only. + */ + private _dispatchMouseUpEvent (nativeMouseEvent: any) { this._mouseInput.dispatchMouseUpEvent?.(nativeMouseEvent); } + /** + * This should be a private method, but it's exposed for Editor Only. + */ + private _dispatchMouseScrollEvent (nativeMouseEvent: any) { this._mouseInput.dispatchScrollEvent?.(nativeMouseEvent); } + + /** + * This should be a private method, but it's exposed for Editor Only. + */ + private _dispatchKeyboardDownEvent (nativeKeyboardEvent: any) { this._keyboardInput.dispatchKeyboardDownEvent?.(nativeKeyboardEvent); } + /** + * This should be a private method, but it's exposed for Editor Only. + */ + private _dispatchKeyboardUpEvent (nativeKeyboardEvent: any) { this._keyboardInput.dispatchKeyboardUpEvent?.(nativeKeyboardEvent); } + /** * @en * Register a callback of a specific input event type. @@ -157,9 +182,6 @@ export class Input { * @param target - The event listener's target and callee */ public on (eventType: K, callback: InputEventMap[K], target?: any) { - if (EDITOR) { - return callback; - } this._eventTarget.on(eventType, callback, target); return callback; } @@ -175,9 +197,6 @@ export class Input { * @param target - The event listener's target and callee */ public once (eventType: K, callback: InputEventMap[K], target?: any) { - if (EDITOR) { - return callback; - } this._eventTarget.once(eventType, callback, target); return callback; } @@ -193,7 +212,7 @@ export class Input { * @param target - The event listener's target and callee */ public off (eventType: K, callback?: InputEventMap[K], target?: any) { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { return; } this._eventTarget.off(eventType, callback, target); @@ -206,7 +225,7 @@ export class Input { * 是否启用加速度计事件。 */ public setAccelerometerEnabled (isEnable: boolean) { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { return; } if (isEnable) { @@ -224,7 +243,7 @@ export class Input { * 设置加速度计间隔值。 */ public setAccelerometerInterval (intervalInMileSeconds: number): void { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { return; } this._accelerometerInput.setInterval(intervalInMileSeconds); diff --git a/cocos/input/system-event.ts b/cocos/input/system-event.ts index 8c34b1d550..710d0a4337 100644 --- a/cocos/input/system-event.ts +++ b/cocos/input/system-event.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module event - */ - import { EventTarget } from '../core/event'; import { EventAcceleration, EventKeyboard, EventMouse, EventTouch, SystemEventType, Touch } from './types'; import { input, Input } from './input'; diff --git a/cocos/input/types/event-enum.ts b/cocos/input/types/event-enum.ts index e4a84d6ee4..8248ce8d8e 100644 --- a/cocos/input/types/event-enum.ts +++ b/cocos/input/types/event-enum.ts @@ -23,10 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module event - */ import { legacyCC } from '../../core/global-exports'; import { NodeEventType } from '../../core/scene-graph/node-event'; @@ -34,7 +30,7 @@ import { NodeEventType } from '../../core/scene-graph/node-event'; * @en The event type supported by SystemEvent and Node events * @zh SystemEvent 支持的事件类型以及节点事件类型 * - * @deprecated since v3.3, please use SystemEvent.EventType instead + * @deprecated since v3.3.0, please use Input.EventType instead */ export enum SystemEventType { /** @@ -104,7 +100,7 @@ export enum SystemEventType { * @en * The event type for mouse wheel events * - * @zh 手指开始触摸事件 + * @zh 当滚动鼠标滚轮或操作其它类似输入设备时会触发滚轮事件。 */ MOUSE_WHEEL = 'mouse-wheel', diff --git a/cocos/input/types/event/event-keyboard.ts b/cocos/input/types/event/event-keyboard.ts index 77340bcd16..682cfd0c29 100644 --- a/cocos/input/types/event/event-keyboard.ts +++ b/cocos/input/types/event/event-keyboard.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module event - */ - import { Event } from './event'; import { SystemEventTypeUnion, SystemEventType } from '../event-enum'; import { KeyCode } from '../key-code'; diff --git a/cocos/input/types/event/event.ts b/cocos/input/types/event/event.ts index 550ef8e024..8361218363 100644 --- a/cocos/input/types/event/event.ts +++ b/cocos/input/types/event/event.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module event - */ - import { legacyCC } from '../../../core/global-exports'; import { SystemEventTypeUnion } from '../event-enum'; diff --git a/cocos/input/types/touch.ts b/cocos/input/types/touch.ts index ca8f675ce9..ad9c3b8944 100644 --- a/cocos/input/types/touch.ts +++ b/cocos/input/types/touch.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module event - */ - import { Vec2 } from '../../core/math'; import { legacyCC } from '../../core/global-exports'; diff --git a/cocos/native-binding/category.json b/cocos/native-binding/category.json new file mode 100644 index 0000000000..f5aabbaead --- /dev/null +++ b/cocos/native-binding/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "原生接口", + "en": "Native Interface" + }, + "description": { + "zh": "该模块提供由原生绑定出来的 JavaScript 接口,包括文件,反射接口等", + "en": "This module provides JavaScript interface bound from native, including file, reflection interface etc." + } +} \ No newline at end of file diff --git a/cocos/native-binding/impl.ts b/cocos/native-binding/impl.ts new file mode 100644 index 0000000000..2e76019e99 --- /dev/null +++ b/cocos/native-binding/impl.ts @@ -0,0 +1,9 @@ +const globalJsb = globalThis.jsb ?? {}; + +export const native = { + DownloaderHints: globalJsb.DownloaderHints, + Downloader: globalJsb.Downloader, + zipUtils: globalJsb.ZipUtils, + fileUtils: globalJsb.fileUtils, + DebugRenderer: globalJsb.DebugRenderer, +}; diff --git a/cocos/native-binding/index.ts b/cocos/native-binding/index.ts new file mode 100644 index 0000000000..629c15dec2 --- /dev/null +++ b/cocos/native-binding/index.ts @@ -0,0 +1,858 @@ +/* eslint-disable @typescript-eslint/no-namespace */ + +import type { Color } from '../core/math/color'; +import type { Vec2 } from '../core/math/vec2'; + +// @ts-expect-error this is a virtual module +export * from 'internal:native'; + +/** + * @zh 该对象提供由原生绑定出来的 JavaScript 接口。 + * 注意:全局作用域下的 `jsb` 对象已经废弃,我们更推荐使用由 `cc` 模块下导出的 `native` 对象。 + * 该对象是前者的子集,我们开放了一些开发者真正需要的原生接口,例如文件,反射等接口。 + * 使用之前需要先通过 `NATIVE` 宏判断该接口在平台上是否支持。 + * + * @en This object provides the JavaScript interface bound from the native. + * Note: `jsb` object in global scope is deprecated, we recommend using the exported `native` object from `cc` module. + * This object is a subset of the former, we open some interfaces that the developer really needs, such as file, reflection, etc. + * Before using, you need to check whether the interface is supported on the platform with the `NATIVE` constant. + * + * @example + * ```ts + * import { native } from 'cc'; + * import { NATIVE } from 'cc/env'; + * + * if (NATIVE) { + * native.reflection.callStaticMethod( ...args ); + * } + * ``` + */ +export declare namespace native { + /** + * @en DownloaderTask @zh 下载任务对象 + * @param requestURL @en Request download resource URL @zh 请求下载资源的URL + * @param storagePath @en Storage path for downloaded file @zh 下载文件存储路径 + * @param identifier @en identifier @zh 标识符 + */ + export type DownloaderTask = { requestURL: string, storagePath: string, identifier: string }; + + /** + * @en DownloaderHints @zh 下载任务的配置接口 + * @param countOfMaxProcessingTasks + * @en Maximum number of download tasks processed at the same time, optional, default is 6 + * @zh 同时处理的最大下载任务数量, 可选, 默认值为6 + * @param timeoutInSeconds @en Download request timeout, optional, default is 45 seconds @zh 下载请求的超时时间, 可选, 默认值为45秒 + * @param tempFileNameSuffix @en Temporary file suffix generated during download, optional, default is .tmp @zh 下载时产生的临时文件后缀, 可选, 默认值为.tmp + */ + export interface DownloaderHints { + countOfMaxProcessingTasks?: number; + timeoutInSeconds?: number; + tempFileNameSuffix?: string; + } + + /** + * @en Downloader class for task download + * @zh Downloader 任务下载类 + */ + export class Downloader { + /** + * @en Downloader default constructor, constructed by the default value of DownloaderHints. + * @zh Downloader的默认构造函数, 通过DownloaderHints的默认值构造. + * @example + * ```ts + * let downloader = new native.Downloader(); // create a Downloader object by default constructor + */ + constructor(); + + /** + * @en Downloader constructor with parameter, constructed by DownloaderHints. + * @zh Downloader的有参构造函数, 通过传递的DownloaderHints去构造. + * @example + * ```ts + * const hints: native.DownloaderHints = { // create a DownloaderHints interface + * countOfMaxProcessingTasks: 6, + * timeoutInSeconds: 100, + * tempFileNameSuffix: ".tmp" + * }; + * let downloader = new native.Downloader(hints); // create a Downloader object with DownloaderHints + */ + constructor (hints: DownloaderHints); + + /** + * @en create a download task. The maximum size for a single download file is 4GB. + * @zh 创建一个下载任务. 单个下载文件最大为4GB. + * @param requestURL @en Request download resource URL @zh 请求下载资源的URL + * @param storagePath @en Storage path for downloaded file @zh 下载文件存储路径 + * @param identifier @en identifier @zh 标识符 + * @return @en DownloaderTask @zh 下载任务对象 + * @example + * ```ts + * let task = downloader.createDownloadTask('https://example.com/exampleFile.zip', native.fileUtils.getWritablePath()); + */ + createDownloadTask (requestURL:string, storagePath:string, identifier?:string): DownloaderTask; + + /** + * @en setter for the callback function after download success + * @zh 任务成功下载后的回调函数的修改器 + * @param task @en download task @zh 下载的任务 + * @example + * ```ts + * // set a download success callback + * downloader.onSuccess = (task) => { + * console.log('Success!'); // call when task download success + * }; + */ + onSuccess: (task: DownloaderTask) => void | undefined; + + /** + * @en setter for the callback function while download. + * @zh 任务下载过程中的回调函数的修改器. + * @param task @en download task @zh 下载任务 + * @param bytesReceived @en received bytes in current call @zh 此次接收到的字节 + * @param totalBytesReceived @en total bytes have been received @zh 已接收到的所有字节 + * @param totalBytesExpected @en total bytes expected to receive @zh 预计接收的所有字节 + * @example + * ```ts + * // setter for the callback for download progress prompt + * downloader.onProgress = (task, bytesReceived, totalBytesReceived, totalBytesExpected) => { + * 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; + + /** + * @en setter for the callback function when download error + * @zh 任务下载发生错误时的回调函数的修改器 + * @param task @en download task @zh 下载任务 + * @param errorCode @en error code @zh 错误码 + * @param errorCodeInternal @en internal error code @zh 内部错误码 + * @param errorStr @en error info string @zh 错误信息 + * @example + * ```ts + * // set a download error callback + * downloader.onError = (task, errorCode, errorCodeInternal, errorStr) => { + * console.log('Error:', errorStr); + * }; + */ + onError: (task: DownloaderTask, errorCode: number, errorCodeInternal: number, errorStr: string) => void | undefined; + + /** + * @deprecated since v3.6.0, please use `createDownloadTask` to instead. + * @en create a download task. The maximum size for a single download file is 4GB. + * @zh 创建一个下载任务. 单个下载文件最大为4GB. + * @param requestURL @en Request download resource URL @zh 请求下载资源的URL + * @param storagePath @en Storage path for downloaded file @zh 下载文件存储路径 + * @param identifier @en identifier @zh 标识符 + * @return @en DownloaderTask @zh 下载任务对象 + * @example + * ```ts + * let task = downloader.createDownloadFileTask('https://example.com/exampleFile.zip', native.fileUtils.getWritablePath()); + */ + createDownloadFileTask (requestURL:string, storagePath:string, identifier?:string): DownloaderTask; + + /** + * @deprecated since v3.6.0, please use setter `onSuccess` to instead. + * @en set callback function after download success + * @zh 设置任务成功下载后的回调函数 + * @param onSucceed @en Download success callback @zh 下载成功后的回调函数 + * @example + * ```ts + * // set a download success callback + * downloader.setOnFileTaskSuccess((task)=>{ + * console.log('Success!'); // call when task download success + * }); + */ + setOnFileTaskSuccess (onSucceed: (task: DownloaderTask) => void): void; + + /** + * @deprecated since v3.6.0, please use setter `onProgress` to instead. + * @en set callback function while download. + * @zh 设置任务下载过程中的回调函数. + * @param onProgress @en Download progress callback @zh 下载过程中的回调函数 + * @example + * ```ts + * // set a callback for download progress prompt + * downloader.setOnTaskProgress((task, bytesReceived, totalBytesReceived, totalBytesExpected)=>{ + * 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; + /** + * @deprecated since v3.6.0, please use setter `onError` to instead. + * @en set callback function when download error + * @zh 设置任务下载发生错误时的回调函数 + * @param onError @en Download error callback @zh 下载发生错误时的回调函数 + * @example + * ```ts + * // set a download error callback + * downloader.setOnTaskError((task, errorCode, errorCodeInternal, errorStr)=>{ + * console.log('Error:', errorStr); + * }); + */ + setOnTaskError (onError: (task: DownloaderTask, errorCode: number, errorCodeInternal: number, errorStr: string) => void): void; + } + + /** + * @en ZipUtils Helper class to handle unzip related operations. + * @zh ZipUtils 对解压操作的辅助类。 + */ + export namespace zipUtils{ + /** + * @en + * Inflates either zlib or gzip deflated memory. The inflated memory is expected to be freed by the caller. + * It will allocate 256k for the destination buffer. + * If it is not enough it will multiply the previous buffer size per 2, until there is enough memory. + * + * @zh + * 对 zlib 或 gzip 压缩的内存进行解压缩。解压后的数据需要在调用方中进行内存释放。 + * 它会给目标内存分配 256k 大小的空间。如果不足以解压,它将会将目标空间扩大 2 倍直到足够大。 + * + * @param input @en input data @zh 要解压的数据 + * @param outLengthHint @en It is assumed to be the needed room to allocate the inflated buffer, which is optional. @zh 预计解压后的数据长度,可选。 + * + * @return @en The deflated buffer. @zh 解压后的数据缓存区 + */ + export function inflateMemory(input:string | ArrayBuffer | TypedArray, outLengthHint?: number): ArrayBuffer | null; + + /** + * @en Inflates a GZip file into memory. + * @zh 将 GZip 压缩文件解压缩到内存中。 + * + * @param path @en The GZip file path. @zh GZip 文件的路径 + * + * @return @en The deflated buffer. @zh 解压后的数据缓存区 + */ + export function inflateGZipFile(path:string): ArrayBuffer | null; + + /** + * @en Test a file is a GZip format file or not. + * @zh 判断一个文件是否是 GZip 格式。 + * + * @param path @en The file path. @zh 文件的路径 + * + * @return @en True is a GZip format file. false is not. @zh true GZip 格式文件,否则不是。 + */ + export function isGZipFile(path:string): boolean; + + /** + * @en Test the buffer is GZip format or not. + * @zh 判断一个缓存区的数据是否是 GZip 格式。 + * + * @param buffer @en The buffer. @zh 数据缓存区 + * + * @return @en True is GZip format. false is not. @zh 返回true表示是 GZip 格式,否则不是。 + */ + export function isGZipBuffer(buffer:string | ArrayBuffer | TypedArray): boolean; + + /** + * @en Inflates a CCZ file into memory. + * @zh 将 CCZ 格式压缩文件解压缩到内存中。 + * + * @param path @en The CCZ file path. @zh CCZ 文件的路径 + * @return @en The deflated buffer. @zh 解压后的数据缓存区 + */ + export function inflateCCZFile(path:string): ArrayBuffer | null; + + /** + * @en Inflates a buffer with CCZ format into memory. + * @zh 将 CCZ 格式的内存块解压到内存中。 + * + * @param buffer @en The buffer. @zh 数据缓存区 + * + * @return @en The deflated buffer. @zh 解压后的数据缓存区 + */ + export function inflateCCZBuffer(buffer:string | ArrayBuffer | TypedArray): ArrayBuffer | null; + + /** + * @en Test a file is a CCZ format file or not. + * @zh 判断一个文件是否是 CCZ 格式。 + * + * @return @en True is a CCZ format file. false is not. @zh 返回true表示是 CCZ 格式,否则不是。 + */ + export function isCCZFile(path:string): boolean; + + /** + * @en Test the buffer is CCZ format or not. + * @zh 判断一个缓存区的数据是否是 CCZ 格式。 + * + * @ param @en The buffer. @zh 数据缓存区 + * + * @return @en True is CCZ format. false is not. @zh 返回true表示是 CCZ 格式,否则不是。 + */ + export function isCCZBuffer(buffer:string | ArrayBuffer | TypedArray): boolean; + + /** + * @en + * Sets the pvr.ccz encryption key parts separately for added security. + * + * Example: If the key used to encrypt the pvr.ccz file is + * 0xaaaaaaaabbbbbbbbccccccccdddddddd you will call this function 4 + * different times, preferably from 4 different source files, as follows + * + * setPvrEncryptionKeyPart(0, 0xaaaaaaaa); + * setPvrEncryptionKeyPart(1, 0xbbbbbbbb); + * setPvrEncryptionKeyPart(2, 0xcccccccc); + * setPvrEncryptionKeyPart(3, 0xdddddddd); + * + * Splitting the key into 4 parts and calling the function from 4 different source + * files increases the difficulty to reverse engineer the encryption key. + * Be aware that encryption is *never* 100% secure and the key code + * can be cracked by knowledgeable persons. + * + * IMPORTANT: Be sure to call setPvrEncryptionKey or + * setPvrEncryptionKeyPart with all of the key parts *before* loading + * the sprite sheet or decryption will fail and the sprite sheet + * will fail to load. + * + * @zh + * 设置 pvr.ccz 加密密钥的部分,以增加安全性。 + * + * 例如:如果使用来加密 pvr.ccz 文件的密钥为 0xaaaaaaaabbbbbbbbccccccccdddddddd, + * 则你可以调用此函数 4 次,至少来自 4 个不同的源文件,如下所示: + * + * setPvrEncryptionKeyPart(0, 0xaaaaaaaa); + * setPvrEncryptionKeyPart(1, 0xbbbbbbbb); + * setPvrEncryptionKeyPart(2, 0xcccccccc); + * setPvrEncryptionKeyPart(3, 0xdddddddd); + * + * 将密钥分成 4 个部分并调用此函数来自 4 个不同的源文件增加解密密钥的难度。 + * 请注意,加密是从不完全安全的,密钥码可以被知道的人破解。 + * + * 注意:调用 setPvrEncryptionKey 或 setPvrEncryptionKeyPart 函数之前, + * 请确保已经调用了 setPvrEncryptionKeyPart 函数,否则解密将失败,并且加载精灵图集将失败。 + * + * @param index @en Part of the key [0..3]. @zh 密钥[0..3]的部分。 + * @param value @en Value of the key part. @zh 密钥部分的值。 + */ + export function setPvrEncryptionKeyPart(index:number, value:number): void; + + /** + * @en + * Sets the pvr.ccz encryption key. + * Example: If the key used to encrypt the pvr.ccz file is + * 0xaaaaaaaabbbbbbbbccccccccdddddddd you will call this function with + * the key split into 4 parts as follows + * + * setPvrEncryptionKey(0xaaaaaaaa, 0xbbbbbbbb, 0xcccccccc, 0xdddddddd); + * + * Note that using this function makes it easier to reverse engineer and discover + * the complete key because the key parts are present in one function call. + * + * IMPORTANT: Be sure to call setPvrEncryptionKey or setPvrEncryptionKeyPart + * with all of the key parts *before* loading the sprite sheet or decryption + * will fail and the sprite sheet will fail to load. + * + * @zh + * 设置 pvr.ccz 加密密钥。 + * 例如:如果使用来加密 pvr.ccz 文件的密钥为 0xaaaaaaaabbbbbbbbccccccccdddddddd, + * 则你可以调用此函数,将密钥分成 4 个部分如下: + * + * setPvrEncryptionKey(0xaaaaaaaa, 0xbbbbbbbb, 0xcccccccc, 0xdddddddd); + * + * 注意:确保在加载精灵图集之前通过所有的密钥部分调用 setPvrEncryptionKey 或 setPvrEncryptionKeyPart,否则解密将失败,并且加载精灵图集将失败。 + * + * @param keyPart1 @en The key value part 1. @zh 密钥部分 1 的值。 + * @param keyPart2 @en The key value part 2. @zh 密钥部分 2 的值。 + * @param keyPart3 @en The key value part 3. @zh 密钥部分 3 的值。 + * @param keyPart4 @en The key value part 4. @zh 密钥部分 4 的值。 + */ + export function setPvrEncryptionKey(keyPart1:number, keyPart2:number, keyPart3:number, keyPart4:number): void; + } + + /** + * FileUtils Helper class to handle file operations. + */ + export namespace fileUtils { + /** + * @en + * Checks whether the path is an absolute path. + * + * @zh + * 判断文件是否是绝对路径 + * @note On Android, if the parameter passed in is relative to "@assets/", this method will treat it as an absolute path. + * Also on Blackberry, path starts with "app/native/Resources/" is treated as an absolute path. + * + * @param path The path that needs to be checked. + * @return True if it's an absolute path, false if not. + */ + export function isAbsolutePath (path:string):boolean; + /** + * @en + * Returns the fullpath for a given filename. + * + First it will try to get a new filename from the "filenameLookup" dictionary. + If a new filename can't be found on the dictionary, it will use the original filename. + Then it will try to obtain the full path of the filename using the FileUtils search rules: resolutions, and search paths. + The file search is based on the array element order of search paths and resolution directories. + + For instance: + + We set two elements("/mnt/sdcard/", "internal_dir/") to search paths vector by setSearchPaths, + and set three elements("resources-ipadhd/", "resources-ipad/", "resources-iphonehd") + to resolutions vector by setSearchResolutionsOrder. The "internal_dir" is relative to "Resources/". + + If we have a file named 'sprite.png', the mapping in fileLookup dictionary contains `key: sprite.png -> value: sprite.pvr.gz`. + Firstly, it will replace 'sprite.png' with 'sprite.pvr.gz', then searching the file sprite.pvr.gz as follows: + + /mnt/sdcard/resources-ipadhd/sprite.pvr.gz (if not found, search next) + /mnt/sdcard/resources-ipad/sprite.pvr.gz (if not found, search next) + /mnt/sdcard/resources-iphonehd/sprite.pvr.gz (if not found, search next) + /mnt/sdcard/sprite.pvr.gz (if not found, search next) + internal_dir/resources-ipadhd/sprite.pvr.gz (if not found, search next) + internal_dir/resources-ipad/sprite.pvr.gz (if not found, search next) + internal_dir/resources-iphonehd/sprite.pvr.gz (if not found, search next) + internal_dir/sprite.pvr.gz (if not found, return "sprite.png") + + If the filename contains relative path like "gamescene/uilayer/sprite.png", + and the mapping in fileLookup dictionary contains `key: gamescene/uilayer/sprite.png -> value: gamescene/uilayer/sprite.pvr.gz`. + The file search order will be: + + /mnt/sdcard/gamescene/uilayer/resources-ipadhd/sprite.pvr.gz (if not found, search next) + /mnt/sdcard/gamescene/uilayer/resources-ipad/sprite.pvr.gz (if not found, search next) + /mnt/sdcard/gamescene/uilayer/resources-iphonehd/sprite.pvr.gz (if not found, search next) + /mnt/sdcard/gamescene/uilayer/sprite.pvr.gz (if not found, search next) + internal_dir/gamescene/uilayer/resources-ipadhd/sprite.pvr.gz (if not found, search next) + internal_dir/gamescene/uilayer/resources-ipad/sprite.pvr.gz (if not found, search next) + internal_dir/gamescene/uilayer/resources-iphonehd/sprite.pvr.gz (if not found, search next) + internal_dir/gamescene/uilayer/sprite.pvr.gz (if not found, return "gamescene/uilayer/sprite.png") + + If the new file can't be found on the file system, it will return the parameter filename directly. + + This method was added to simplify multiplatform support. + Whether you are using cocos2d-js or any cross-compilation toolchain like StellaSDK or Apportable, + you might need to load different resources for a given file in the different platforms. + * @zh + * 通过文件名获取绝对路径 + * @since v2.1 + */ + export function fullPathForFilename (filename:string):string; + /** + * + * @en + * Gets string from a file. + * + * @zh + * 读取文件里的字符串 + * + */ + export function getStringFromFile (filename:string):string; + /** + * @en + * Removes a file. + * + * @zh + * 删除文件 + * + * @param filepath The full path of the file, it must be an absolute path. + * @return True if the file have been removed successfully, false if not. + */ + export function removeFile (filepath:string):boolean; + /** + * @en + * Checks whether the path is a directory. + * + * @zh + * 检测目录是否存在 + * + * @param dirPath The path of the directory, it could be a relative or an absolute path. + * @return True if the directory exists, false if not. + */ + export function isDirectoryExist (dirPath:string):boolean; + /** + * @en + * Normalize: remove . and .. + * + * @zh + * 标准化:去除'.' 和 '..' + * + * @param filepath + */ + export function normalizePath (filepath:string):string; + /** + * @en + * Gets the array of search paths. + * + * @zh + * 获取默认资源根路径 + * + */ + export function getDefaultResourceRootPath ():string; + + /** + * @en + * Converts the contents of a file to a ValueVector. + * This method is used internally. + * + * @zh + * 将文件的内容转换为 ValueVector + * 这个方法是内部使用的 + */ + export function getValueVectorFromFile (filepath:string):Array; + /** + * @en + * Gets the array of search paths. + * + * @zh + * 获取所有的搜索路径 + * + * @return The array of search paths which may contain the prefix of default resource root path. + * @note In best practise, getter function should return the value of setter function passes in. + * But since we should not break the compatibility, we keep using the old logic. + * Therefore, If you want to get the original search paths, please call 'getOriginalSearchPaths()' instead. + * @see fullPathForFilename (const char*). + * @lua NA + */ + export function getSearchPaths ():Array; + /** + * @en + * Get the directory where the file is located by the file path. + * + * @zh + * 通过文件路径获取文件所在目录 + * @param filepath + */ + export function getFileDir (filepath:string):string; + /** + * @en + * write a ValueMap into a plist file. + * + * @zh + * 将 ValueMap 写入 plist 文件 + * + * @param dict the ValueMap want to save (key,value) + * @return bool + */ + export function writeToFile (valueMap:any):boolean; + /** + * @en + * Gets the original search path array set by 'setSearchPaths' or 'addSearchPath'. + * + * @zh + * 获取由“setSearchPaths”或“addSearchPath”设置的原始搜索路径数组。 + * + * @return The array of the original search paths + */ + export function getOriginalSearchPaths ():Array; + /** + * @en + * List all files in a directory + * + * @zh + * 在文件夹中列出所有文件 + * + * @param dirPath The path of the directory, it could be a relative or an absolute path. + * @return File paths in a string vector + */ + export function listFiles (filepath:string):Array; + /** + * @en + * Converts the contents of a file to a ValueMap. + * + * @zh + * 转换文件内容为ValueMap + * + * @param filename The filename of the file to gets content. + * @return ValueMap of the file contents. + * @note This method is used internally. + */ + export function getValueMapFromFile (filepath:string):any; + /** + * @en + * Retrieve the file size. + * + * @zh + * 获取文件大小 + * @note If a relative path was passed in, it will be inserted a default root path at the beginning. + * @param filepath The path of the file, it could be a relative or absolute path. + * @return The file size. + */ + export function getFileSize (filepath:string):number; + + /** + * @en + * Converts the contents of a file to a ValueMap. + * This method is used internally. + * + * @zh + * 转换文件内容为ValueMap + * 这个方法是内部使用的 + * + */ + export function getValueMapFromData (filedata:string, filesize:number):any; + /** + * + * @en + * Removes a directory.. + * + * @zh + * 删除一个目录 + * + * @param dirPath The full path of the directory, it must be an absolute path. + * @return True if the directory have been removed successfully, false if not. + */ + export function removeDirectory (dirPath:string):boolean; + /** + * @en + * Sets the array of search paths. + * + * You can use this array to modify the search path of the resources. + * If you want to use "themes" or search resources in the "cache", you can do it easily by adding new entries in this array. + * + * @note This method could access relative path and absolute path. + * If the relative path was passed to the vector, FileUtils will add the default resource directory before the relative path. + * For instance: + * On Android, the default resource root path is "@assets/". + * If "/mnt/sdcard/" and "resources-large" were set to the search paths vector, + * "resources-large" will be converted to "@assets/resources-large" since it was a relative path. + * @zh + * 设置一系列的搜索路径 + * 通过这个数组可以修改资源的搜索路径。例如如果你想使用在cache里的主题资源,你需要尽早的添加到这个数组里 + * + * @param searchPaths The array contains search paths. + * @see fullPathForFilename (const char*) + * @since v2.1 + * In js:var setSearchPaths(var jsval); + * @lua NA + */ + export function setSearchPaths (searchPath:Array):void; + /** + * @en + * write a string into a file. + * + * @zh + * 写字符串到文件里 + * + * @param dataStr the string want to save + * @param fullPath The full path to the file you want to save a string + * @return bool True if write success + */ + export function writeStringToFile (dataStr:string, fullPath:string):boolean; + + /** + * @en + * Add search path. + * + * @zh + * 添加文件的搜索路径 + * + * @since v2.1 + */ + export function addSearchPath (path:string, front:boolean):void; + /** + * + * @en + * write ValueVector into a plist file + * + * @zh + * 将 ValueVector 写入 plist 文件 + * + *@param vecData the ValueVector want to save + *@param fullPath The full path to the file you want to save a string + *@return bool + */ + export function writeValueVectorToFile (vecData:Array, fullPath:string):boolean; + /** + * @en + * Checks whether a file exists. + * + * @zh + * 检测路径是否存在 + * + * @note If a relative path was passed in, it will be inserted a default root path at the beginning. + * @param filename The path of the file, it could be a relative or absolute path. + * @return True if the file exists, false if not. + */ + export function isFileExist (filename:string):boolean; + /** + * + * @en + * Purges full path caches. + * + * @zh + * 清除路径缓存 + */ + export function purgeCachedEntries ():void; + /** + * @en + * Gets full path from a file name and the path of the relative file. + * + * @zh + * 通过文件名或者相对路径转换成绝对路径 + * + * @param filename The file name. + * @param relativeFile The path of the relative file. + * @return The full path. + * e.g. filename: hello.png, pszRelativeFile: /User/path1/path2/hello.plist + * Return: /User/path1/path2/hello.pvr (If there a a key(hello.png)-value(hello.pvr) in FilenameLookup dictionary. ) + * + */ + export function fullPathFromRelativeFile (filename:string, relativeFile:string):string; + /** + * @en + * Windows fopen can't support UTF-8 filename + * Need convert all parameters fopen and other 3rd-party libs + * + * @zh + * windows的fopen函数不支持utf-8编码的文件 + * 需要转换所有的参数给fopen或者其他的第三方的库使用 + * @param filenameUtf8 std::string name file for conversion from utf-8 + * @return std::string ansi filename in current locale + */ + export function getSuitableFOpen (filenameUtf8:string):string; + /** + * + * @en + * write ValueMap into a plist file + * + * @zh + * 将 ValueMap 写入 plist 文件 + * @param dict the ValueMap want to save + * @param fullPath The full path to the file you want to save a string + * @return bool + */ + export function writeValueMapToFile (dict:any, fullPath:string):string; + /** + * @en + * Gets filename extension is a suffix (separated from the base filename by a dot) in lower case. + * Examples of filename extensions are .png, .jpeg, .exe, .dmg and .txt. + * + * @zh + * 获取文件的扩展名(使用'.'做分割符),返回的都是小写 + * 例如:返回.png, .jpeg, .exe, .dmg等 + * @param filePath The path of the file, it could be a relative or absolute path. + * @return suffix for filename in lower case or empty if a dot not found. + */ + export function getFileExtension (filePath:string):string; + /** + * @en + * Sets writable path. + * + * @zh + * 设置有可写权限的目录 + * + * @param writablePath The path of the directory. + */ + export function setWritablePath (writablePath:string):void; + /** + * @en + * Set default resource root path. + * + * @zh + * 设置默认的资源根目录 + * + * @param dirPath The path of the directory. + */ + export function setDefaultResourceRootPath (dirPath:string):void; + + /** + * @en + * Creates a directory. + * + * @zh + * 创建一个目录 + * + * @param dirPath The path of the directory, it must be an absolute path. + * @return True if the directory have been created successfully, false if not. + */ + export function createDirectory (dirPath:string):string; + /** + * @en + * List all files recursively in a directory. + * + * @zh + * 在一个目录里递归搜索所有的文件 + * + * @param dirPath The path of the directory, it could be a relative or an absolute path. + * @return File paths in a string vector + */ + export function listFilesRecursively (dirPath:string, files:Array):void; + /** + * Gets the writable path. + * @return The path that can be write/read a file in + */ + export function getWritablePath():string; + + /** + * @en + * Renames a file under the given directory. + * + * @zh + * 文件(包含路径)重命名 + * + * @param oldFullpath The current fullpath of the file. Includes path and name. + * @param newFullPath The new fullpath of the file. Includes path and name. + * @return True if the file have been renamed successfully, false if not. + */ + export function renameFile(oldFullpath: string, newFullPath: string):boolean; + + /** + * @en + * Read binary data from a file. + * + * @zh + * 从文件中读取二进制数据 + * Creates binary data from a file. + * @param fullpath The current fullpath of the file. Includes path and name. + * @return A data object. + */ + export function getDataFromFile(fullpath: string):ArrayBuffer; + + /** + * @en + * write Data into a file + * + * @zh + * 把数据写入文件内 + * + * @param data the data want to save + * @param fullpath The full path to the file you want to save a string + * @return bool + */ + export function writeDataToFile(buffer: ArrayBuffer, fullpath: string):boolean; + } + + /** + * @en DebugTextInfo @zh 调试文本的配置接口 + * @param color @en text color @zh 文本颜色 + * @param bold @en bold text @zh 粗体 + * @param italic @en italic text @zh 斜体 + * @param shadow @en shadow effect @zh 阴影效果 + * @param shadowThickness @en shadow thickness @zh 阴影宽度 + * @param shadowColor @en shadow color @zh 阴影颜色 + * @param scale @en scale @zh 缩放比例 + */ + export interface DebugTextInfo { + color: Color; + bold: boolean; + italic: boolean; + shadow: boolean; + shadowThickness: number; + shadowColor: Color; + scale: number; + } + + /** + * @en DebugRenderer class used to output debug text on screen + * @zh 用于输出屏幕调试文字的调试渲染器类 + */ + export class DebugRenderer { + /** + * @en get DebugRenderer instance + * @zh 获取调试渲染器实例 + * @return @en the DebugRenderer instance @zh 返回的调试渲染器实例 + */ + static getInstance(): DebugRenderer; + + /** + * @en output a text + * @zh 输出一个文本 + * @param text @en the output text @zh 输出的文本 + * @param screenPos @en the output screen position @zh 输出的屏幕位置 + * @param info @en the output text information @zh 输出的文本属性 + */ + addText(text:string, screenPos: Vec2, info?: DebugTextInfo): void; + } +} diff --git a/cocos/particle-2d/category.json b/cocos/particle-2d/category.json new file mode 100644 index 0000000000..ea8e04da79 --- /dev/null +++ b/cocos/particle-2d/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "2D 粒子系统", + "en": "Particle System 2D" + }, + "description": { + "zh": "粒子系统的 2D 版本,用于在 2D 世界下进行特效的开发", + "en": "2D version of the particle system for developing effects in the 2D world" + } +} \ No newline at end of file diff --git a/cocos/particle-2d/define.ts b/cocos/particle-2d/define.ts index c1aac418a0..fd2b508e24 100644 --- a/cocos/particle-2d/define.ts +++ b/cocos/particle-2d/define.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle2d - */ - import { Enum } from '../core/value-types'; /** diff --git a/cocos/particle-2d/index.ts b/cocos/particle-2d/index.ts index 2e76f65e12..609a833f94 100644 --- a/cocos/particle-2d/index.ts +++ b/cocos/particle-2d/index.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle2d - */ - import { ParticleSystem2D } from './particle-system-2d'; import { MotionStreak } from './motion-streak-2d'; import { MotionStreakAssemblerManager } from './motion-streak-2d-assembler'; diff --git a/cocos/particle-2d/motion-streak-2d-assembler.ts b/cocos/particle-2d/motion-streak-2d-assembler.ts index 35443128d6..024132786e 100644 --- a/cocos/particle-2d/motion-streak-2d-assembler.ts +++ b/cocos/particle-2d/motion-streak-2d-assembler.ts @@ -24,11 +24,7 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle2d - */ - +import { JSB } from 'internal:constants'; import { IAssembler, IAssemblerManager } from '../2d/renderer/base'; import { MotionStreak } from './motion-streak-2d'; import { Vec2, Color } from '../core/math'; @@ -39,6 +35,7 @@ const _tangent = new Vec2(); // const _miter = new Vec2(); const _normal = new Vec2(); const _vec2 = new Vec2(); +let QUAD_INDICES; function normal (out:Vec2, dir:Vec2) { // get perpendicular @@ -179,7 +176,56 @@ export const MotionStreakAssembler: IAssembler = { indexCount = vertexCount <= 2 ? 0 : (vertexCount - 2) * 3; - renderData.resize(vertexCount, indexCount); + renderData.resize(vertexCount, indexCount); // resize + if (JSB) { + const indexCount = renderData.indexCount; + this.createQuadIndices(comp, indexCount); + renderData.chunk.setIndexBuffer(QUAD_INDICES); + + // Fill all dataList to vData + this.updateWorldVertexAllData(comp); + + renderData.updateRenderData(comp, comp.texture!); + // No need update WorldMatrix, so change dirty flag + // A dirty hack + renderData.renderDrawInfo.setVertDirty(false); + comp.node.hasChangedFlags = 0; + } + }, + + updateWorldVertexAllData (comp: MotionStreak) { + const renderData = comp.renderData!; + const stride = renderData.floatStride; + const dataList = renderData.data; + const vData = renderData.chunk.vb; + for (let i = 0; i < dataList.length; i++) { + const offset = i * stride; + vData[offset + 0] = dataList[i].x; + vData[offset + 1] = dataList[i].y; + vData[offset + 2] = dataList[i].z; + vData[offset + 3] = dataList[i].u; + vData[offset + 4] = dataList[i].v; + Color.toArray(vData, dataList[i].color, offset + 5); + } + }, + + createQuadIndices (comp, indexCount) { + const renderData = comp.renderData!; + const chunk = renderData.chunk; + const vid = 0; + const meshBuffer = chunk.meshBuffer; + let indexOffset = meshBuffer.indexOffset; + QUAD_INDICES = null; + QUAD_INDICES = new Uint16Array(indexCount); + for (let i = 0, l = indexCount; i < l; i += 2) { + const start = vid + i; + QUAD_INDICES[indexOffset++] = start; + QUAD_INDICES[indexOffset++] = start + 2; + QUAD_INDICES[indexOffset++] = start + 1; + QUAD_INDICES[indexOffset++] = start + 1; + QUAD_INDICES[indexOffset++] = start + 2; + QUAD_INDICES[indexOffset++] = start + 3; + } }, updateRenderDataCache (comp: MotionStreak, renderData: RenderData) { diff --git a/cocos/particle-2d/motion-streak-2d.ts b/cocos/particle-2d/motion-streak-2d.ts index 6c65f8c3bb..b8406572fe 100644 --- a/cocos/particle-2d/motion-streak-2d.ts +++ b/cocos/particle-2d/motion-streak-2d.ts @@ -24,17 +24,13 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle2d - */ - import { ccclass, executeInEditMode, serializable, playOnFocus, menu, help, editable, type } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; -import { Renderable2D } from '../2d/framework'; +import { UIRenderer } from '../2d/framework'; import { Texture2D } from '../core/assets/texture-2d'; import { IBatcher } from '../2d/renderer/i-batcher'; import { Vec2 } from '../core'; +import { legacyCC } from '../core/global-exports'; class Point { public point = new Vec2(); @@ -74,7 +70,7 @@ class Point { @playOnFocus @menu('Effects/MotionStreak') @help('i18n:COMPONENT.help_url.motionStreak') -export class MotionStreak extends Renderable2D { +export class MotionStreak extends UIRenderer { public static Point = Point; /** @@ -192,10 +188,11 @@ export class MotionStreak extends Renderable2D { this._assembler = assembler; } - if (!this._renderData) { + if (!this.renderData) { if (this._assembler && this._assembler.createData) { this._renderData = this._assembler.createData(this); - this._renderData!.material = this.material; + this.renderData!.material = this.material; + this._updateColor(); } } } @@ -221,16 +218,16 @@ export class MotionStreak extends Renderable2D { */ public reset () { this._points.length = 0; - if (this._renderData) this._renderData.clear(); + if (this.renderData) this.renderData.clear(); } public lateUpdate (dt) { - if (EDITOR && !this._preview) return; + if (EDITOR && !legacyCC.GAME_VIEW && !this._preview) return; if (this._assembler) this._assembler.update(this, dt); } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _render (render: IBatcher) { render.commitComp(this, this.renderData, this._texture, this._assembler, null); diff --git a/cocos/particle-2d/particle-asset.ts b/cocos/particle-2d/particle-asset.ts index 9e6a246541..ee2eee667a 100644 --- a/cocos/particle-2d/particle-asset.ts +++ b/cocos/particle-2d/particle-asset.ts @@ -24,18 +24,14 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset - */ - import { ccclass, serializable, editable } from '../core/data/decorators'; import { Asset } from '../core/assets/asset'; import { SpriteFrame } from '../2d/assets/sprite-frame'; import { legacyCC } from '../core/global-exports'; /** - * Class for particle asset handling. + * @en Class for 2D particle asset handling. + * @zh 2D 粒子资产 * @class ParticleAsset * @extends Asset */ diff --git a/cocos/particle-2d/particle-simulator-2d.ts b/cocos/particle-2d/particle-simulator-2d.ts index 05bfd0eaf6..5a75f5cde3 100644 --- a/cocos/particle-2d/particle-simulator-2d.ts +++ b/cocos/particle-2d/particle-simulator-2d.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle2d - */ - import { Vec2, Color } from '../core/math'; import Pool from '../core/utils/pool'; import { clampf, degreesToRadians, radiansToDegrees } from '../core/utils/misc'; @@ -466,6 +461,10 @@ export class Simulator { } } + this.renderData.material = this.sys.getRenderMaterial(0); // hack + this.renderData.frame = this.sys._renderSpriteFrame; // hack + renderData.setRenderDrawInfoAttributes(); + if (particles.length === 0 && !this.active && !this.readyToPlay) { this.finished = true; psys._finishedSimulation(); @@ -487,4 +486,9 @@ export class Simulator { buffer[offset++] = vId + 2; } } + + public initDrawInfo () { + const renderData = this.renderData; + renderData.setRenderDrawInfoAttributes(); + } } diff --git a/cocos/particle-2d/particle-system-2d-assembler.ts b/cocos/particle-2d/particle-system-2d-assembler.ts index ca898159f9..fc3f37f9a1 100644 --- a/cocos/particle-2d/particle-system-2d-assembler.ts +++ b/cocos/particle-2d/particle-system-2d-assembler.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle2d - */ - import { IAssembler, IAssemblerManager } from '../2d/renderer/base'; import { ParticleSystem2D } from './particle-system-2d'; import { MeshRenderData } from '../2d/renderer/render-data'; diff --git a/cocos/particle-2d/particle-system-2d.ts b/cocos/particle-2d/particle-system-2d.ts index 02cb794b24..6de9f68e90 100644 --- a/cocos/particle-2d/particle-system-2d.ts +++ b/cocos/particle-2d/particle-system-2d.ts @@ -24,14 +24,10 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle2d - */ - -import { ccclass, editable, type, displayOrder, menu, executeInEditMode, serializable, playOnFocus, tooltip, visible, formerlySerializedAs } from 'cc.decorator'; +import { ccclass, editable, type, displayOrder, menu, + executeInEditMode, serializable, playOnFocus, tooltip, visible, formerlySerializedAs } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; -import { Renderable2D } from '../2d/framework/renderable-2d'; +import { UIRenderer } from '../2d/framework/ui-renderer'; import { Color, Vec2 } from '../core/math'; import { warnID, errorID, error } from '../core/platform/debug'; import { Simulator } from './particle-simulator-2d'; @@ -47,6 +43,7 @@ import { IBatcher } from '../2d/renderer/i-batcher'; import { assetManager } from '../core/asset-manager'; import { PositionType, EmitterMode, DURATION_INFINITY, START_RADIUS_EQUAL_TO_END_RADIUS, START_SIZE_EQUAL_TO_END_SIZE } from './define'; import { builtinResMgr } from '../core'; +import { legacyCC } from '../core/global-exports'; /** * Image formats @@ -142,50 +139,38 @@ function getParticleComponents (node): ParticleSystem2D[] { } /** - * Particle System base class.
- * Attributes of a Particle System:
- * - emmision rate of the particles
- * - Gravity Mode (Mode A):
- * - gravity
- * - direction
- * - speed +- variance
- * - tangential acceleration +- variance
- * - radial acceleration +- variance
- * - Radius Mode (Mode B):
- * - startRadius +- variance
- * - endRadius +- variance
- * - rotate +- variance
- * - Properties common to all modes:
- * - life +- life variance
- * - start spin +- variance
- * - end spin +- variance
- * - start size +- variance
- * - end size +- variance
- * - start color +- variance
- * - end color +- variance
- * - life +- variance
- * - blending function
- * - texture
- *
- * cocos2d also supports particles generated by Particle Designer (http://particledesigner.71squared.com/).
- * 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d,
- * cocos2d uses a another approach, but the results are almost identical.
- * cocos2d supports all the variables used by Particle Designer plus a bit more:
- * - spinning particles (supported when using ParticleSystem)
- * - tangential acceleration (Gravity mode)
- * - radial acceleration (Gravity mode)
- * - radius direction (Radius mode) (Particle Designer supports outwards to inwards direction only)
- * It is possible to customize any of the above mentioned properties in runtime. Example:
- * - * @example + * @en Particle System base class. + * cocos2d also supports particles generated by Particle Designer (http://particledesigner.71squared.com/). + * 'Radius Mode' in Particle Designer uses a fixed emit rate of 30 hz. Since that can't be guarateed in cocos2d, + * cocos2d uses a another approach, but the results are almost identical. + * cocos2d supports all the variables used by Particle Designer plus a bit more: + * - spinning particles (supported when using ParticleSystem) + * - tangential acceleration (Gravity mode) + * - radial acceleration (Gravity mode) + * - radius direction (Radius mode) (Particle Designer supports outwards to inwards direction only) + * It is possible to customize any of the above mentioned properties in runtime. Example: * emitter.radialAccel = 15; * emitter.startSpin = 0; + * + * @zh 2D 粒子基础类型 + * cocos2d 同样支 Particle Designer (http://particledesigner.71squared.com/) 生成的粒子 + * 粒子设计器中的 半径模式 使用 30 hz 的固定发射率。由于 cocos2d 无法保证, + * cocos2d 使用了另一种方法,但结果几乎相同。 + * cocos2d 支持 Particle Designer 使用的所有变量,还有: + * -旋转粒子(使用粒子系统时支持) + * -切向加速度(重力模式) + * -径向加速度(重力模式) + * -半径方向(半径模式)(Particle Designer 仅支持向外到向内的方向) + * 可以在运行时自定义上述任何属性。例如: + * emitter.radialAccel = 15; + * emitter.startSpin = 0; + * */ @ccclass('cc.ParticleSystem2D') @menu('Effects/ParticleSystem2D') @playOnFocus @executeInEditMode -export class ParticleSystem2D extends Renderable2D { +export class ParticleSystem2D extends UIRenderer { static EmitterMode = EmitterMode; static PositionType = PositionType; static readonly DURATION_INFINITY = DURATION_INFINITY; @@ -193,7 +178,7 @@ export class ParticleSystem2D extends Renderable2D { static readonly START_RADIUS_EQUAL_TO_END_RADIUS = START_RADIUS_EQUAL_TO_END_RADIUS; /** - * @en If set custom to true, then use custom properties insteadof read particle file. + * @en If set custom to true, then use custom properties instead of read particle file. * @zh 是否自定义粒子属性。 */ @editable @@ -203,7 +188,7 @@ export class ParticleSystem2D extends Renderable2D { return this._custom; } public set custom (value) { - if (EDITOR && !value && !this._file) { + if (EDITOR && !legacyCC.GAME_VIEW && !value && !this._file) { warnID(6000); return; } @@ -658,7 +643,7 @@ export class ParticleSystem2D extends Renderable2D { public endRadiusVar = 0; /** - * @en Number of degress to rotate a particle around the source pos per second. Only available in 'Radius' mode. + * @en Number of degrees to rotate a particle around the source pos per second. Only available in 'Radius' mode. * @zh 粒子每秒围绕起始点的旋转角度,只有在半径模式下可用。 */ @serializable @@ -667,7 +652,7 @@ export class ParticleSystem2D extends Renderable2D { public rotatePerS = 0; /** - * @en Variation of the degress to rotate a particle around the source pos per second. + * @en Variation of the degrees to rotate a particle around the source pos per second. * @zh 粒子每秒围绕起始点的旋转角度变化范围。 */ @serializable @@ -698,11 +683,11 @@ export class ParticleSystem2D extends Renderable2D { public aspectRatio = 1; /** * The temporary SpriteFrame object used for the renderer. Because there is no corresponding asset, it can't be serialized. - * @legacyPublic + * @internal since v3.5.0, this is an engine private interface that will be removed in the future. */ public declare _renderSpriteFrame: SpriteFrame | null; /** - * @legacyPublic + * @internal since v3.5.0, this is an engine private interface that will be removed in the future. */ public declare _simulator: Simulator; @@ -838,7 +823,7 @@ export class ParticleSystem2D extends Renderable2D { } // auto play - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { if (this.playOnLoad) { this.resetSystem(); } @@ -851,9 +836,10 @@ export class ParticleSystem2D extends Renderable2D { if (this._assembler !== assembler) { this._assembler = assembler; } - if (this._assembler && this._assembler.createData) { this._simulator.renderData = this._assembler.createData(this); + this._simulator.renderData.particleInitRenderDrawInfo(this.renderEntity); // 确保 renderEntity 和 renderData 都是 simulator 上的 + this._simulator.initDrawInfo(); } } @@ -896,7 +882,7 @@ export class ParticleSystem2D extends Renderable2D { public resetSystem () { this._stopped = false; this._simulator.reset(); - this._renderFlag = this._canRender(); + this.markForUpdateRenderData(); } /** @@ -909,7 +895,7 @@ export class ParticleSystem2D extends Renderable2D { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _applyFile () { const file = this._file; @@ -941,7 +927,7 @@ export class ParticleSystem2D extends Renderable2D { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _initTextureWithDictionary (dict: any) { if (dict.spriteFrameUuid) { @@ -1025,7 +1011,7 @@ export class ParticleSystem2D extends Renderable2D { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _initWithDictionary (dict: any) { this.totalParticles = parseInt(dict.maxParticles || 0); @@ -1140,7 +1126,7 @@ export class ParticleSystem2D extends Renderable2D { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _syncAspect () { if (this._renderSpriteFrame) { @@ -1150,7 +1136,7 @@ export class ParticleSystem2D extends Renderable2D { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _applySpriteFrame () { this._renderSpriteFrame = this._renderSpriteFrame || this._spriteFrame; @@ -1160,7 +1146,7 @@ export class ParticleSystem2D extends Renderable2D { this._syncAspect(); this._updateMaterial(); this._stopped = false; - this._renderFlag = this._canRender(); + this.markForUpdateRenderData(); } } else { this.resetSystem(); @@ -1168,14 +1154,14 @@ export class ParticleSystem2D extends Renderable2D { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _getTexture () { return (this._renderSpriteFrame && this._renderSpriteFrame.texture); } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _updateMaterial () { const mat = this.getMaterialInstance(0); @@ -1183,10 +1169,10 @@ export class ParticleSystem2D extends Renderable2D { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _finishedSimulation () { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { if (this._preview && this._focused && !this.active /* && !cc.engine.isPlaying */) { this.resetSystem(); } @@ -1194,7 +1180,7 @@ export class ParticleSystem2D extends Renderable2D { } this.resetSystem(); this.stopSystem(); - this._renderFlag = this._canRender(); + this.markForUpdateRenderData(); if (this.autoRemoveOnFinish && this._stopped) { this.node.destroy(); } diff --git a/cocos/particle-2d/png-reader.ts b/cocos/particle-2d/png-reader.ts index 51d3624ffe..2e25d14e23 100644 --- a/cocos/particle-2d/png-reader.ts +++ b/cocos/particle-2d/png-reader.ts @@ -26,11 +26,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle2d - */ - import { getError } from '../core/platform/debug'; import zlib from '../../external/compression/zlib.min'; diff --git a/cocos/particle-2d/tiff-reader.ts b/cocos/particle-2d/tiff-reader.ts index deaf428a61..1becc22e60 100644 --- a/cocos/particle-2d/tiff-reader.ts +++ b/cocos/particle-2d/tiff-reader.ts @@ -29,11 +29,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle2d - */ - import { getError, logID } from '../core/platform/debug'; interface IFile { diff --git a/cocos/particle/animator/color-overtime.ts b/cocos/particle/animator/color-overtime.ts index c28dce1c93..1e26c461b0 100644 --- a/cocos/particle/animator/color-overtime.ts +++ b/cocos/particle/animator/color-overtime.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle - */ - import { ccclass, displayOrder, type, serializable } from 'cc.decorator'; import { pseudoRandom } from '../../core/math'; import { Particle, PARTICLE_MODULE_NAME, ParticleModuleBase } from '../particle'; diff --git a/cocos/particle/animator/curve-range.ts b/cocos/particle/animator/curve-range.ts index 479c336815..88b93bdd89 100644 --- a/cocos/particle/animator/curve-range.ts +++ b/cocos/particle/animator/curve-range.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { ccclass, type, serializable, editable, formerlySerializedAs } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { lerp } from '../../core/math'; @@ -165,7 +163,7 @@ export default class CurveRange { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _onBeforeSerialize (props) { // eslint-disable-next-line @typescript-eslint/no-unsafe-return diff --git a/cocos/particle/animator/force-overtime.ts b/cocos/particle/animator/force-overtime.ts index 8ea5277737..2b7d4fe05b 100644 --- a/cocos/particle/animator/force-overtime.ts +++ b/cocos/particle/animator/force-overtime.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle - */ - import { ccclass, tooltip, displayOrder, range, type, serializable } from 'cc.decorator'; import { pseudoRandom, Quat, Vec3 } from '../../core/math'; import { Space, ModuleRandSeed } from '../enum'; diff --git a/cocos/particle/animator/gradient-range.ts b/cocos/particle/animator/gradient-range.ts index bb2a181440..0770f58186 100644 --- a/cocos/particle/animator/gradient-range.ts +++ b/cocos/particle/animator/gradient-range.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { ccclass, type, serializable, editable } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { Color } from '../../core/math'; @@ -32,6 +30,7 @@ import { Enum } from '../../core/value-types'; import Gradient, { AlphaKey, ColorKey } from './gradient'; import { Texture2D } from '../../core'; import { PixelFormat, Filter, WrapMode } from '../../core/assets/asset-enum'; +import { legacyCC } from '../../core/global-exports'; const SerializableTable = EDITOR && [ ['_mode', 'color'], @@ -60,7 +59,7 @@ export default class GradientRange { } set mode (m) { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { if (m === Mode.RandomColor) { if (this.gradient.colorKeys.length === 0) { this.gradient.colorKeys.push(new ColorKey()); @@ -139,7 +138,7 @@ export default class GradientRange { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _onBeforeSerialize (props: any): any { return SerializableTable[this._mode]; diff --git a/cocos/particle/animator/gradient.ts b/cocos/particle/animator/gradient.ts index 17f9d89c07..7fa987bc72 100644 --- a/cocos/particle/animator/gradient.ts +++ b/cocos/particle/animator/gradient.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { ccclass, serializable, editable } from 'cc.decorator'; import { CCClass } from '../../core/data/class'; import { Color, lerp, repeat } from '../../core/math'; diff --git a/cocos/particle/animator/limit-velocity-overtime.ts b/cocos/particle/animator/limit-velocity-overtime.ts index d36e7b0bbe..9e4f572a7d 100644 --- a/cocos/particle/animator/limit-velocity-overtime.ts +++ b/cocos/particle/animator/limit-velocity-overtime.ts @@ -23,12 +23,7 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle - */ - -import { ccclass, tooltip, displayOrder, range, type, serializable } from 'cc.decorator'; +import { ccclass, tooltip, displayOrder, range, type, serializable, visible } from 'cc.decorator'; import { lerp, pseudoRandom, Vec3, Mat4, Quat } from '../../core/math'; import { Space, ModuleRandSeed } from '../enum'; import { Particle, ParticleModuleBase, PARTICLE_MODULE_NAME } from '../particle'; @@ -67,6 +62,9 @@ export default class LimitVelocityOvertimeModule extends ParticleModuleBase { @range([-1, 1]) @displayOrder(4) @tooltip('i18n:limitVelocityOvertimeModule.limitX') + @visible(function (this: LimitVelocityOvertimeModule): boolean { + return this.separateAxes; + }) public limitX = new CurveRange(); /** @@ -77,6 +75,9 @@ export default class LimitVelocityOvertimeModule extends ParticleModuleBase { @range([-1, 1]) @displayOrder(5) @tooltip('i18n:limitVelocityOvertimeModule.limitY') + @visible(function (this: LimitVelocityOvertimeModule): boolean { + return this.separateAxes; + }) public limitY = new CurveRange(); /** @@ -87,6 +88,9 @@ export default class LimitVelocityOvertimeModule extends ParticleModuleBase { @range([-1, 1]) @displayOrder(6) @tooltip('i18n:limitVelocityOvertimeModule.limitZ') + @visible(function (this: LimitVelocityOvertimeModule): boolean { + return this.separateAxes; + }) public limitZ = new CurveRange(); /** @@ -97,6 +101,9 @@ export default class LimitVelocityOvertimeModule extends ParticleModuleBase { @range([-1, 1]) @displayOrder(3) @tooltip('i18n:limitVelocityOvertimeModule.limit') + @visible(function (this: LimitVelocityOvertimeModule): boolean { + return !this.separateAxes; + }) public limit = new CurveRange(); /** diff --git a/cocos/particle/animator/noise-module.ts b/cocos/particle/animator/noise-module.ts new file mode 100644 index 0000000000..1e8251d68a --- /dev/null +++ b/cocos/particle/animator/noise-module.ts @@ -0,0 +1,263 @@ +/* + 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 { ccclass, displayOrder, type, serializable } from 'cc.decorator'; +import { CCFloat, CCInteger } from '../../core'; +import { range, rangeStep, slide, visible } from '../../core/data/decorators/editable'; +import { Vec3 } from '../../core/math'; +import { ParticleNoise } from '../noise'; +import { Particle, PARTICLE_MODULE_NAME, ParticleModuleBase } from '../particle'; + +@ccclass('cc.NoiseModule') +export class NoiseModule extends ParticleModuleBase { + @serializable + _enable = false; + /** + * @zh 是否启用。 + */ + @displayOrder(0) + public get enable () { + return this._enable; + } + + public set enable (val) { + if (this._enable === val) return; + this._enable = val; + if (!this.target) return; + this.target.enableModule(this.name, val, this); + } + + @type(CCFloat) + @range([0, 100]) + @displayOrder(16) + @slide + get strengthX () { + return this._strengthX; + } + set strengthX (value: number) { + this._strengthX = value; + } + @serializable + private _strengthX = 10; + + @type(CCFloat) + @range([0, 100]) + @displayOrder(16) + @slide + get strengthY () { + return this._strengthY; + } + set strengthY (value: number) { + this._strengthY = value; + } + @serializable + private _strengthY = 10; + + @type(CCFloat) + @range([0, 100]) + @displayOrder(16) + @slide + get strengthZ () { + return this._strengthZ; + } + set strengthZ (value: number) { + this._strengthZ = value; + } + @serializable + private _strengthZ = 10; + + @type(CCFloat) + @range([0, 100]) + @slide + @displayOrder(16) + get noiseSpeedX () { + return this._noiseSpeedX; + } + set noiseSpeedX (value: number) { + this._noiseSpeedX = value; + } + @serializable + private _noiseSpeedX = 0; + + @type(CCFloat) + @range([0, 100]) + @displayOrder(16) + @slide + get noiseSpeedY () { + return this._noiseSpeedY; + } + set noiseSpeedY (value: number) { + this._noiseSpeedY = value; + } + @serializable + private _noiseSpeedY = 0; + + @type(CCFloat) + @range([0, 100]) + @displayOrder(16) + @slide + get noiseSpeedZ () { + return this._noiseSpeedZ; + } + set noiseSpeedZ (value: number) { + this._noiseSpeedZ = value; + } + @serializable + private _noiseSpeedZ = 0; + + @type(CCFloat) + @range([0, 100]) + @rangeStep(0.1) + @displayOrder(16) + @slide + get noiseFrequency () { + return this._noiseFrequency; + } + set noiseFrequency (value: number) { + this._noiseFrequency = value; + } + @serializable + private _noiseFrequency = 1; + + @visible(false) + @type(CCFloat) + @range([0, 1]) + @rangeStep(0.1) + @displayOrder(16) + @slide + get remapX () { + return this._remapX; + } + set remapX (value: number) { + this._remapX = value; + } + @serializable + private _remapX = 0; + + @visible(false) + @type(CCFloat) + @range([0, 1]) + @rangeStep(0.1) + @displayOrder(16) + @slide + get remapY () { + return this._remapY; + } + set remapY (value: number) { + this._remapY = value; + } + @serializable + private _remapY = 0; + + @visible(false) + @type(CCFloat) + @range([0, 1]) + @rangeStep(0.1) + @displayOrder(16) + @slide + get remapZ () { + return this._remapZ; + } + set remapZ (value: number) { + this._remapZ = value; + } + @serializable + private _remapZ = 0; + + @type(CCInteger) + @range([1, 4]) + @rangeStep(1) + @displayOrder(16) + @slide + get octaves () { + return this._octaves; + } + set octaves (value: number) { + this._octaves = value; + } + @serializable + private _octaves = 1; + + // eslint-disable-next-line func-names + @visible(function (this: NoiseModule) { return this._octaves > 1; }) + @type(CCFloat) + @range([0, 1]) + @rangeStep(0.1) + @displayOrder(16) + get octaveMultiplier () { + return this._octaveMultiplier; + } + set octaveMultiplier (value: number) { + this._octaveMultiplier = value; + } + @serializable + private _octaveMultiplier = 0.5; + + // eslint-disable-next-line func-names + @visible(function (this: NoiseModule) { return this._octaves > 1; }) + @type(CCFloat) + @range([1, 4]) + @rangeStep(0.1) + @displayOrder(16) + get octaveScale () { + return this._octaveScale; + } + set octaveScale (value: number) { + this._octaveScale = value; + } + @serializable + private _octaveScale = 2; + + public name = PARTICLE_MODULE_NAME.NOISE; + + private noise: ParticleNoise = new ParticleNoise(); + + public animate (particle: Particle, dt: number) { + this.noise.setTime(particle.particleSystem.time); + this.noise.setSpeed(this.noiseSpeedX, this.noiseSpeedY, this.noiseSpeedZ); + this.noise.setFrequency(this.noiseFrequency); + this.noise.setAbs(this.remapX, this.remapY, this.remapZ); + this.noise.setAmplititude(this.strengthX, this.strengthY, this.strengthZ); + this.noise.setOctaves(this.octaves, this.octaveMultiplier, this.octaveScale); + this.noise.setSamplePoint(particle.position); + this.noise.getNoiseParticle(); + + const noisePosition: Vec3 = this.noise.getResult(); + noisePosition.multiply3f(Math.random(), Math.random(), Math.random()); + Vec3.add(particle.position, particle.position, noisePosition.multiplyScalar(dt)); + } + + public getNoisePreview (out: number[], ps, width: number, height: number) { + this.noise.setTime(ps.time); + this.noise.setSpeed(this.noiseSpeedX, this.noiseSpeedY, this.noiseSpeedZ); + this.noise.setFrequency(this.noiseFrequency); + this.noise.setAbs(this.remapX, this.remapY, this.remapZ); + this.noise.setAmplititude(this.strengthX, this.strengthY, this.strengthZ); + this.noise.setOctaves(this.octaves, this.octaveMultiplier, this.octaveScale); + this.noise.getNoiseParticle(); + + this.noise.getPreview(out, width, height); + } +} diff --git a/cocos/particle/animator/optimized-curve.ts b/cocos/particle/animator/optimized-curve.ts index 7442361073..88f996350c 100644 --- a/cocos/particle/animator/optimized-curve.ts +++ b/cocos/particle/animator/optimized-curve.ts @@ -23,14 +23,9 @@ THE SOFTWARE. */ - - - import { repeat } from '../../core/math'; import { AnimationCurve, evalOptCurve, OptimizedKey } from '../../core/geometry/curve'; - - const CURVE_MODE_CONSTANT = 0; const CURVE_MODE_RANDOM_CONSTANT = 1; const CURVE_MODE_CURVE = 2; diff --git a/cocos/particle/animator/rotation-overtime.ts b/cocos/particle/animator/rotation-overtime.ts index 0e65acbc97..413135fa7b 100644 --- a/cocos/particle/animator/rotation-overtime.ts +++ b/cocos/particle/animator/rotation-overtime.ts @@ -24,12 +24,7 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle - */ - -import { ccclass, tooltip, displayOrder, range, type, radian, serializable } from 'cc.decorator'; +import { ccclass, tooltip, displayOrder, range, type, radian, serializable, visible } from 'cc.decorator'; import { Mat4, pseudoRandom, Quat, Vec4, Vec3 } from '../../core/math'; import { Particle, ParticleModuleBase, PARTICLE_MODULE_NAME } from '../particle'; import CurveRange from './curve-range'; @@ -81,6 +76,7 @@ export default class RotationOvertimeModule extends ParticleModuleBase { @radian @displayOrder(2) @tooltip('i18n:rotationOvertimeModule.x') + @visible(function (this: RotationOvertimeModule): boolean { return this.separateAxes; }) public x = new CurveRange(); /** @@ -92,6 +88,7 @@ export default class RotationOvertimeModule extends ParticleModuleBase { @radian @displayOrder(3) @tooltip('i18n:rotationOvertimeModule.y') + @visible(function (this: RotationOvertimeModule): boolean { return this.separateAxes; }) public y = new CurveRange(); /** diff --git a/cocos/particle/animator/size-overtime.ts b/cocos/particle/animator/size-overtime.ts index c9f687a841..78cd371029 100644 --- a/cocos/particle/animator/size-overtime.ts +++ b/cocos/particle/animator/size-overtime.ts @@ -23,12 +23,7 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle - */ - -import { ccclass, tooltip, displayOrder, type, serializable, range } from 'cc.decorator'; +import { ccclass, tooltip, displayOrder, type, serializable, range, visible } from 'cc.decorator'; import { pseudoRandom, Vec3 } from '../../core/math'; import { Particle, ParticleModuleBase, PARTICLE_MODULE_NAME } from '../particle'; import CurveRange from './curve-range'; @@ -71,6 +66,7 @@ export default class SizeOvertimeModule extends ParticleModuleBase { @range([0, 1]) @displayOrder(2) @tooltip('i18n:sizeOvertimeModule.size') + @visible(function (this: SizeOvertimeModule): boolean { return !this.separateAxes; }) public size = new CurveRange(); /** @@ -81,6 +77,7 @@ export default class SizeOvertimeModule extends ParticleModuleBase { @range([0, 1]) @displayOrder(3) @tooltip('i18n:sizeOvertimeModule.x') + @visible(function (this: SizeOvertimeModule): boolean { return this.separateAxes; }) public x = new CurveRange(); /** @@ -91,6 +88,7 @@ export default class SizeOvertimeModule extends ParticleModuleBase { @range([0, 1]) @displayOrder(4) @tooltip('i18n:sizeOvertimeModule.y') + @visible(function (this: SizeOvertimeModule): boolean { return this.separateAxes; }) public y = new CurveRange(); /** @@ -101,6 +99,7 @@ export default class SizeOvertimeModule extends ParticleModuleBase { @range([0, 1]) @displayOrder(5) @tooltip('i18n:sizeOvertimeModule.z') + @visible(function (this: SizeOvertimeModule): boolean { return this.separateAxes; }) public z = new CurveRange(); public name = PARTICLE_MODULE_NAME.SIZE; diff --git a/cocos/particle/animator/texture-animation.ts b/cocos/particle/animator/texture-animation.ts index 8654b42954..c7402e0c1a 100644 --- a/cocos/particle/animator/texture-animation.ts +++ b/cocos/particle/animator/texture-animation.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle - */ - import { ccclass, tooltip, displayOrder, type, formerlySerializedAs, serializable, range } from 'cc.decorator'; import { lerp, pseudoRandom, repeat } from '../../core/math'; import { Enum } from '../../core/value-types'; diff --git a/cocos/particle/animator/velocity-overtime.ts b/cocos/particle/animator/velocity-overtime.ts index fb8b5350eb..d3dad9a701 100644 --- a/cocos/particle/animator/velocity-overtime.ts +++ b/cocos/particle/animator/velocity-overtime.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle - */ - import { ccclass, tooltip, displayOrder, range, type, serializable } from 'cc.decorator'; import { Mat4, pseudoRandom, Quat, Vec3 } from '../../core/math'; import { Space, ModuleRandSeed } from '../enum'; diff --git a/cocos/particle/billboard.ts b/cocos/particle/billboard.ts index b3f60b4571..da8bb4aa29 100644 --- a/cocos/particle/billboard.ts +++ b/cocos/particle/billboard.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle - */ - import { ccclass, help, executeInEditMode, menu, tooltip, type, serializable } from 'cc.decorator'; import { builtinResMgr } from '../core/builtin'; import { createMesh } from '../3d/misc'; diff --git a/cocos/particle/burst.ts b/cocos/particle/burst.ts index fb23c80453..f95b32531e 100644 --- a/cocos/particle/burst.ts +++ b/cocos/particle/burst.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { ccclass, type, serializable, editable, range } from 'cc.decorator'; import { repeat } from '../core/math'; import CurveRange from './animator/curve-range'; diff --git a/cocos/particle/category.json b/cocos/particle/category.json index 7914fe20f6..5e481782be 100644 --- a/cocos/particle/category.json +++ b/cocos/particle/category.json @@ -4,7 +4,7 @@ "en": "Particle System" }, "description": { - "zh": "粒子系统", - "en": "Particle System" + "zh": "粒子系统是游戏引擎特效表现的基础,它可以用于模拟的火、烟、水、云、雪、落叶等自然现象,也可用于模拟发光轨迹、速度线等抽象视觉效果。", + "en": "The particle system is the basis of the game engine's special effects. It can be used to simulate natural phenomena such as fire, smoke, water, clouds, snow, and fallen leaves. It can also be used to simulate abstract visual effects such as luminous tracks and speed lines." } } \ No newline at end of file diff --git a/cocos/particle/deprecated.ts b/cocos/particle/deprecated.ts index d04d3e275f..d5f342d5df 100644 --- a/cocos/particle/deprecated.ts +++ b/cocos/particle/deprecated.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle - */ - import { removeProperty, replaceProperty } from '../core/utils/x-deprecated'; import Burst from './burst'; import { ParticleSystem } from './particle-system'; diff --git a/cocos/particle/emitter/shape-module.ts b/cocos/particle/emitter/shape-module.ts index ed644539f1..54c54f22c4 100644 --- a/cocos/particle/emitter/shape-module.ts +++ b/cocos/particle/emitter/shape-module.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle - */ - import { ccclass, tooltip, displayOrder, type, formerlySerializedAs, serializable, visible, range } from 'cc.decorator'; import { Mat4, Quat, Vec2, Vec3, clamp, pingPong, random, randomRange, repeat, toDegree, toRadian } from '../../core/math'; @@ -40,6 +35,16 @@ import { ParticleSystem } from '../particle-system'; const _intermediVec = new Vec3(0, 0, 0); const _intermediArr: number[] = []; const _unitBoxExtent = new Vec3(0.5, 0.5, 0.5); +function getShapeTypeEnumName(enumValue: number): keyof typeof ShapeType { + let enumName = ''; + for (const key in ShapeType) { + if (ShapeType[key] === enumValue) { + enumName = key; + break; + } + } + return enumName as keyof typeof ShapeType; +} @ccclass('cc.ShapeModule') export default class ShapeModule { @@ -87,7 +92,12 @@ export default class ShapeModule { */ @displayOrder(6) @tooltip('i18n:shapeModule.arc') - get arc () { + @visible(function (this: ShapeModule) { + const subset: Array = ['Cone', 'Circle']; + const enumName = getShapeTypeEnumName(this.shapeType); + return subset.includes(enumName); + }) + get arc() { return toDegree(this._arc); } @@ -101,7 +111,12 @@ export default class ShapeModule { */ @displayOrder(5) @tooltip('i18n:shapeModule.angle') - get angle () { + @visible(function (this: ShapeModule) { + const subset: Array = ['Cone']; + const enumName = getShapeTypeEnumName(this.shapeType); + return subset.includes(enumName); + }) + get angle() { return Math.round(toDegree(this._angle) * 100) / 100; } @@ -126,7 +141,7 @@ export default class ShapeModule { /** * @zh 粒子发射器类型 [[ShapeType]]。 * - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @type(ShapeType) @formerlySerializedAs('shapeType') @@ -170,6 +185,11 @@ export default class ShapeModule { @serializable @displayOrder(2) @tooltip('i18n:shapeModule.emitFrom') + @visible(function (this: ShapeModule) { + const subset: Array = ['Box', 'Cone', 'Sphere', 'Hemisphere']; + const enumName = getShapeTypeEnumName(this.shapeType); + return subset.includes(enumName); + }) public emitFrom = EmitLocation.Volume; /** @@ -210,6 +230,11 @@ export default class ShapeModule { @serializable @displayOrder(3) @tooltip('i18n:shapeModule.radius') + @visible(function (this: ShapeModule) { + const subset: Array = ['Circle', 'Cone', 'Sphere', 'Hemisphere']; + const enumName = getShapeTypeEnumName(this.shapeType); + return subset.includes(enumName); + }) public radius = 1; /** @@ -221,6 +246,11 @@ export default class ShapeModule { @serializable @displayOrder(4) @tooltip('i18n:shapeModule.radiusThickness') + @visible(function (this: ShapeModule) { + const subset: Array = ['Circle', 'Cone', 'Sphere', 'Hemisphere']; + const enumName = getShapeTypeEnumName(this.shapeType); + return subset.includes(enumName); + }) public radiusThickness = 1; /** @@ -230,6 +260,11 @@ export default class ShapeModule { @serializable @displayOrder(7) @tooltip('i18n:shapeModule.arcMode') + @visible(function (this: ShapeModule) { + const subset: Array = ['Cone', 'Circle']; + const enumName = getShapeTypeEnumName(this.shapeType); + return subset.includes(enumName); + }) public arcMode = ArcMode.Random; /** @@ -239,6 +274,11 @@ export default class ShapeModule { @serializable @displayOrder(9) @tooltip('i18n:shapeModule.arcSpread') + @visible(function (this: ShapeModule) { + const subset: Array = ['Cone', 'Circle']; + const enumName = getShapeTypeEnumName(this.shapeType); + return subset.includes(enumName); + }) public arcSpread = 0; /** @@ -250,6 +290,11 @@ export default class ShapeModule { @serializable @displayOrder(10) @tooltip('i18n:shapeModule.arcSpeed') + @visible(function (this: ShapeModule) { + const subset: Array = ['Cone', 'Circle']; + const enumName = getShapeTypeEnumName(this.shapeType); + return subset.includes(enumName); + }) public arcSpeed = new CurveRange(); /** @@ -259,6 +304,11 @@ export default class ShapeModule { @serializable @displayOrder(11) @tooltip('i18n:shapeModule.length') + @visible(function (this: ShapeModule) { + const subset: Array = ['Cone']; + const enumName = getShapeTypeEnumName(this.shapeType); + return subset.includes(enumName); + }) public length = 5; /** @@ -267,6 +317,11 @@ export default class ShapeModule { @serializable @displayOrder(12) @tooltip('i18n:shapeModule.boxThickness') + @visible(function (this: ShapeModule) { + const subset: Array = ['Box']; + const enumName = getShapeTypeEnumName(this.shapeType); + return subset.includes(enumName); + }) public boxThickness = new Vec3(0, 0, 0); @serializable diff --git a/cocos/particle/enum.ts b/cocos/particle/enum.ts index 1f2e05effc..b16a9d8129 100644 --- a/cocos/particle/enum.ts +++ b/cocos/particle/enum.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle - */ - import { Enum } from '../core/value-types'; export const Space = Enum({ diff --git a/cocos/particle/index.ts b/cocos/particle/index.ts index c79f7f9012..d741bb3165 100644 --- a/cocos/particle/index.ts +++ b/cocos/particle/index.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { Billboard } from './billboard'; import { Line } from './line'; import { ParticleSystem } from './particle-system'; diff --git a/cocos/particle/line.ts b/cocos/particle/line.ts index d7871742c4..c43627c142 100644 --- a/cocos/particle/line.ts +++ b/cocos/particle/line.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle - */ - import { ccclass, help, executeInEditMode, menu, tooltip, displayOrder, type, serializable, range } from 'cc.decorator'; import { Material, Texture2D } from '../core/assets'; import { Component } from '../core/components'; @@ -103,7 +98,8 @@ export class Line extends Component { private _positions = []; /** - * 每段折线的拐点坐标。 + * @en Inflection point positions of each polyline + * @zh 每段折线的拐点坐标。 */ @type([Vec3]) @displayOrder(2) diff --git a/cocos/particle/models/line-model.ts b/cocos/particle/models/line-model.ts index e429e374f8..ee52baf780 100644 --- a/cocos/particle/models/line-model.ts +++ b/cocos/particle/models/line-model.ts @@ -23,8 +23,7 @@ THE SOFTWARE. */ - - +import { JSB } from 'internal:constants'; import { RenderingSubMesh } from '../../core/assets/rendering-sub-mesh'; import { DRAW_INFO_SIZE, Buffer, IndirectBuffer, Attribute, BufferInfo, DrawInfo, AttributeName, BufferUsageBit, Format, FormatInfos, MemoryUsageBit, PrimitiveMode } from '../../core/gfx'; @@ -33,7 +32,6 @@ import { scene } from '../../core/renderer'; import CurveRange from '../animator/curve-range'; import GradientRange from '../animator/gradient-range'; import { Material } from '../../core/assets'; -import { JSB } from '../../core/default-constants'; const _vertex_attrs = [ new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), // xyz:position diff --git a/cocos/particle/models/particle-batch-model.ts b/cocos/particle/models/particle-batch-model.ts index 2dcac3cdeb..a28eb9fd4c 100644 --- a/cocos/particle/models/particle-batch-model.ts +++ b/cocos/particle/models/particle-batch-model.ts @@ -1,3 +1,4 @@ +/* eslint-disable max-len */ /* Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. @@ -23,16 +24,15 @@ THE SOFTWARE. */ - - +import { JSB } from 'internal:constants'; import { Mesh } from '../../3d/assets/mesh'; import { AttributeName, BufferUsageBit, FormatInfos, MemoryUsageBit, PrimitiveMode, - Attribute, DRAW_INFO_SIZE, Buffer, IndirectBuffer, BufferInfo, DrawInfo } from '../../core/gfx'; + Attribute, DRAW_INFO_SIZE, Buffer, IndirectBuffer, BufferInfo, DrawInfo, Feature, deviceManager } from '../../core/gfx'; import { Color } from '../../core/math/color'; import { scene } from '../../core/renderer'; import { Particle } from '../particle'; import { Material, RenderingSubMesh } from '../../core/assets'; -import { JSB } from '../../core/default-constants'; +import { legacyCC } from '../../core/global-exports'; const _uvs = [ 0, 0, // bottom-left @@ -41,10 +41,17 @@ const _uvs = [ 1, 1, // top-right ]; +const _uvs_ins = [ + 0, 0, 0, // bottom-left + 1, 0, 0, // bottom-right + 0, 1, 0, // top-left + 1, 1, 0, // top-right +]; + export default class ParticleBatchModel extends scene.Model { private _capacity: number; private _vertAttrs: Attribute[] | null; - private _vertSize: number; + private _vertAttribSize: number; private _vBuffer: ArrayBuffer | null; private _vertAttrsFloatCount: number; private _vdataF32: Float32Array | null; @@ -59,6 +66,12 @@ export default class ParticleBatchModel extends scene.Model { private _lifeTimeOffset = 0; private _material: Material | null = null; + private _vertAttribSizeStatic: number; + private _vertStaticAttrsFloatCount: number; + private _insBuffers: Buffer[]; + private _insIndices: Buffer | null; + private _useInstance: boolean; + constructor () { super(); if (JSB) { @@ -68,11 +81,23 @@ export default class ParticleBatchModel extends scene.Model { this.type = scene.ModelType.PARTICLE_BATCH; this._capacity = 0; this._vertAttrs = null; - this._vertSize = 0; + + this._vertAttribSize = 0; this._vBuffer = null; this._vertAttrsFloatCount = 0; this._vdataF32 = null; this._vdataUint32 = null; + + this._vertAttribSizeStatic = 0; + this._vertStaticAttrsFloatCount = 0; + this._insBuffers = []; + this._insIndices = null; + if (!deviceManager.gfxDevice.hasFeature(Feature.INSTANCED_ARRAYS)) { + this._useInstance = false; + } else { + this._useInstance = true; + } + this._iaInfo = new IndirectBuffer([new DrawInfo()]); this._iaInfoBuffer = this._device.createBuffer(new BufferInfo( BufferUsageBit.INDIRECT, @@ -93,17 +118,44 @@ export default class ParticleBatchModel extends scene.Model { } public setVertexAttributes (mesh: Mesh | null, attrs: Attribute[]) { + if (!this._useInstance) { + if (this._mesh === mesh && this._vertAttrs === attrs) { + return; + } + this._mesh = mesh; + this._vertAttrs = attrs; + this._vertAttribSize = 0; + for (const a of this._vertAttrs) { + (a as any).offset = this._vertAttribSize; + this._vertAttribSize += FormatInfos[a.format].size; + } + this._vertAttrsFloatCount = this._vertAttribSize / 4; // number of float + // rebuid + this.rebuild(); + } else { + this.setVertexAttributesIns(mesh, attrs); + } + } + + private setVertexAttributesIns (mesh: Mesh | null, attrs: Attribute[]) { if (this._mesh === mesh && this._vertAttrs === attrs) { return; } this._mesh = mesh; this._vertAttrs = attrs; - this._vertSize = 0; + this._vertAttribSize = 0; + this._vertAttribSizeStatic = 0; for (const a of this._vertAttrs) { - (a as any).offset = this._vertSize; - this._vertSize += FormatInfos[a.format].size; + if (a.stream === 0) { + (a as any).offset = this._vertAttribSize; + this._vertAttribSize += FormatInfos[a.format].size; + } else if (a.stream === 1) { + (a as any).offset = this._vertAttribSizeStatic; + this._vertAttribSizeStatic += FormatInfos[a.format].size; + } } - this._vertAttrsFloatCount = this._vertSize / 4; // number of float + this._vertAttrsFloatCount = this._vertAttribSize / 4; // number of float + this._vertStaticAttrsFloatCount = this._vertAttribSizeStatic / 4; // rebuid this.rebuild(); } @@ -120,20 +172,20 @@ export default class ParticleBatchModel extends scene.Model { const vertexBuffer = this._device.createBuffer(new BufferInfo( BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, - this._vertSize * this._capacity * this._vertCount, - this._vertSize, + this._vertAttribSize * this._capacity * this._vertCount, + this._vertAttribSize, )); - const vBuffer: ArrayBuffer = new ArrayBuffer(this._vertSize * this._capacity * this._vertCount); + const vBuffer: ArrayBuffer = new ArrayBuffer(this._vertAttribSize * this._capacity * this._vertCount); if (this._mesh && this._capacity > 0) { let vOffset = (this._vertAttrs![this._vertAttrs!.findIndex((val) => val.name === AttributeName.ATTR_TEX_COORD)] as any).offset; - this._mesh.copyAttribute(0, AttributeName.ATTR_TEX_COORD, vBuffer, this._vertSize, vOffset); // copy mesh uv to ATTR_TEX_COORD + this._mesh.copyAttribute(0, AttributeName.ATTR_TEX_COORD, vBuffer, this._vertAttribSize, vOffset); // copy mesh uv to ATTR_TEX_COORD let vIdx = this._vertAttrs!.findIndex((val) => val.name === AttributeName.ATTR_TEX_COORD3); vOffset = (this._vertAttrs![vIdx++] as any).offset; - this._mesh.copyAttribute(0, AttributeName.ATTR_POSITION, vBuffer, this._vertSize, vOffset); // copy mesh position to ATTR_TEX_COORD3 + this._mesh.copyAttribute(0, AttributeName.ATTR_POSITION, vBuffer, this._vertAttribSize, vOffset); // copy mesh position to ATTR_TEX_COORD3 vOffset = (this._vertAttrs![vIdx++] as any).offset; - this._mesh.copyAttribute(0, AttributeName.ATTR_NORMAL, vBuffer, this._vertSize, vOffset); // copy mesh normal to ATTR_NORMAL + this._mesh.copyAttribute(0, AttributeName.ATTR_NORMAL, vBuffer, this._vertAttribSize, vOffset); // copy mesh normal to ATTR_NORMAL vOffset = (this._vertAttrs![vIdx++] as any).offset; - if (!this._mesh.copyAttribute(0, AttributeName.ATTR_COLOR, vBuffer, this._vertSize, vOffset)) { // copy mesh color to ATTR_COLOR1 + if (!this._mesh.copyAttribute(0, AttributeName.ATTR_COLOR, vBuffer, this._vertAttribSize, vOffset)) { // copy mesh color to ATTR_COLOR1 const vb = new Uint32Array(vBuffer); for (let iVertex = 0; iVertex < this._vertCount; ++iVertex) { vb[iVertex * this._vertAttrsFloatCount + vOffset / 4] = Color.WHITE._val; @@ -141,7 +193,7 @@ export default class ParticleBatchModel extends scene.Model { } const vbFloatArray = new Float32Array(vBuffer); for (let i = 1; i < this._capacity; i++) { - vbFloatArray.copyWithin(i * this._vertSize * this._vertCount / 4, 0, this._vertSize * this._vertCount / 4); + vbFloatArray.copyWithin(i * this._vertAttribSize * this._vertCount / 4, 0, this._vertAttribSize * this._vertCount / 4); } } vertexBuffer.update(vBuffer); @@ -193,41 +245,120 @@ export default class ParticleBatchModel extends scene.Model { return vBuffer; } + private createSubMeshDataInsDynamic (): ArrayBuffer { + this.destroySubMeshData(); + + const vertexBuffer = this._device.createBuffer(new BufferInfo( + BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, + this._vertAttribSize * this._capacity, + this._vertAttribSize, + )); + + const vBuffer: ArrayBuffer = new ArrayBuffer(this._vertAttribSize * this._capacity); + vertexBuffer.update(vBuffer); + + this._insBuffers.push(vertexBuffer); + + return vBuffer; + } + + private createSubMeshDataInsStatic () { + this._vertCount = 4; + this._indexCount = 6; + if (this._mesh) { + this._vertCount = this._mesh.struct.vertexBundles[this._mesh.struct.primitives[0].vertexBundelIndices[0]].view.count; + this._indexCount = this._mesh.struct.primitives[0].indexView!.count; + } + + const vertexBuffer = this._device.createBuffer(new BufferInfo( + BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, + this._vertAttribSizeStatic * this._vertCount, + this._vertAttribSizeStatic, + )); + + const vBuffer: ArrayBuffer = new ArrayBuffer(this._vertAttribSizeStatic * this._vertCount); + if (this._mesh) { + let vIdx = this._vertAttrs!.findIndex((val) => val.name === AttributeName.ATTR_TEX_COORD); // find ATTR_TEX_COORD index + let vOffset = (this._vertAttrs![vIdx] as any).offset; // find ATTR_TEX_COORD offset + this._mesh.copyAttribute(0, AttributeName.ATTR_TEX_COORD, vBuffer, this._vertAttribSizeStatic, vOffset); // copy mesh uv to ATTR_TEX_COORD + vIdx = this._vertAttrs!.findIndex((val) => val.name === AttributeName.ATTR_TEX_COORD3); // find ATTR_TEX_COORD3 index + vOffset = (this._vertAttrs![vIdx++] as any).offset; // find ATTR_TEX_COORD3 offset + this._mesh.copyAttribute(0, AttributeName.ATTR_POSITION, vBuffer, this._vertAttribSizeStatic, vOffset); // copy mesh position to ATTR_TEX_COORD3 + vOffset = (this._vertAttrs![vIdx++] as any).offset; + this._mesh.copyAttribute(0, AttributeName.ATTR_NORMAL, vBuffer, this._vertAttribSizeStatic, vOffset); // copy mesh normal to ATTR_NORMAL + vOffset = (this._vertAttrs![vIdx++] as any).offset; + if (!this._mesh.copyAttribute(0, AttributeName.ATTR_COLOR, vBuffer, this._vertAttribSizeStatic, vOffset)) { // copy mesh color to ATTR_COLOR1 + const vb = new Uint32Array(vBuffer); + for (let iVertex = 0; iVertex < this._vertCount; ++iVertex) { + vb[iVertex * this._vertStaticAttrsFloatCount + vOffset / 4] = Color.WHITE._val; + } + } + } else { + const vbFloatArray = new Float32Array(vBuffer); + for (let i = 0; i < _uvs_ins.length; ++i) { + vbFloatArray[i] = _uvs_ins[i]; + } + } + vertexBuffer.update(vBuffer); + + const indices: Uint16Array = new Uint16Array(this._indexCount); + if (this._mesh) { + this._mesh.copyIndices(0, indices); + } else { + indices[0] = 0; + indices[1] = 1; + indices[2] = 2; + indices[3] = 3; + indices[4] = 2; + indices[5] = 1; + } + + const indexBuffer: Buffer = this._device.createBuffer(new BufferInfo( + BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.DEVICE, + this._indexCount * Uint16Array.BYTES_PER_ELEMENT, + Uint16Array.BYTES_PER_ELEMENT, + )); + + indexBuffer.update(indices); + this._insIndices = indexBuffer; + + this._iaInfo.drawInfos[0].vertexCount = this._vertCount; + this._iaInfo.drawInfos[0].indexCount = this._indexCount; + if (!this._iaInfoBuffer) { + this._iaInfoBuffer = this._device.createBuffer(new BufferInfo( + BufferUsageBit.INDIRECT, + MemoryUsageBit.HOST | MemoryUsageBit.DEVICE, + DRAW_INFO_SIZE, + DRAW_INFO_SIZE, + )); + } + this._iaInfoBuffer.update(this._iaInfo); + + this._insBuffers.push(vertexBuffer); + } + + private createInsSubmesh () { + this._subMeshData = new RenderingSubMesh(this._insBuffers, this._vertAttrs!, PrimitiveMode.TRIANGLE_LIST, this._insIndices, this._iaInfoBuffer); + this.initSubModel(0, this._subMeshData, this._material!); + } + public updateMaterial (mat: Material) { this._material = mat; this.setSubModelMaterial(0, mat); } public addParticleVertexData (index: number, pvdata: any[]) { - if (!this._mesh) { - let offset: number = index * this._vertAttrsFloatCount; - this._vdataF32![offset++] = pvdata[0].x; // position - this._vdataF32![offset++] = pvdata[0].y; - this._vdataF32![offset++] = pvdata[0].z; - this._vdataF32![offset++] = pvdata[1].x; // uv - this._vdataF32![offset++] = pvdata[1].y; - this._vdataF32![offset++] = pvdata[1].z; // frame idx - this._vdataF32![offset++] = pvdata[2].x; // size - this._vdataF32![offset++] = pvdata[2].y; - this._vdataF32![offset++] = pvdata[2].z; - this._vdataF32![offset++] = pvdata[3].x; // rotation - this._vdataF32![offset++] = pvdata[3].y; - this._vdataF32![offset++] = pvdata[3].z; - this._vdataUint32![offset++] = pvdata[4]; // color - if (pvdata[5]) { - this._vdataF32![offset++] = pvdata[5].x; // velocity - this._vdataF32![offset++] = pvdata[5].y; - this._vdataF32![offset++] = pvdata[5].z; - } - } else { - for (let i = 0; i < this._vertCount; i++) { - let offset: number = (index * this._vertCount + i) * this._vertAttrsFloatCount; + if (!this._useInstance) { + if (!this._mesh) { + let offset: number = index * this._vertAttrsFloatCount; this._vdataF32![offset++] = pvdata[0].x; // position this._vdataF32![offset++] = pvdata[0].y; this._vdataF32![offset++] = pvdata[0].z; - offset += 2; - // this._vdataF32![offset++] = index; - // this._vdataF32![offset++] = pvdata[1].y; + this._vdataF32![offset++] = pvdata[1].x; // uv + this._vdataF32![offset++] = pvdata[1].y; this._vdataF32![offset++] = pvdata[1].z; // frame idx this._vdataF32![offset++] = pvdata[2].x; // size this._vdataF32![offset++] = pvdata[2].y; @@ -236,47 +367,174 @@ export default class ParticleBatchModel extends scene.Model { this._vdataF32![offset++] = pvdata[3].y; this._vdataF32![offset++] = pvdata[3].z; this._vdataUint32![offset++] = pvdata[4]; // color + if (pvdata[5]) { + this._vdataF32![offset++] = pvdata[5].x; // velocity + this._vdataF32![offset++] = pvdata[5].y; + this._vdataF32![offset++] = pvdata[5].z; + } + } else { + for (let i = 0; i < this._vertCount; i++) { + let offset: number = (index * this._vertCount + i) * this._vertAttrsFloatCount; + this._vdataF32![offset++] = pvdata[0].x; // position + this._vdataF32![offset++] = pvdata[0].y; + this._vdataF32![offset++] = pvdata[0].z; + offset += 2; + // this._vdataF32![offset++] = index; + // this._vdataF32![offset++] = pvdata[1].y; + this._vdataF32![offset++] = pvdata[1].z; // frame idx + this._vdataF32![offset++] = pvdata[2].x; // size + this._vdataF32![offset++] = pvdata[2].y; + this._vdataF32![offset++] = pvdata[2].z; + this._vdataF32![offset++] = pvdata[3].x; // rotation + this._vdataF32![offset++] = pvdata[3].y; + this._vdataF32![offset++] = pvdata[3].z; + this._vdataUint32![offset++] = pvdata[4]; // color + } } + } else { + this.addParticleVertexDataIns(index, pvdata); + } + } + + private addParticleVertexDataIns (index: number, pvdata: any[]) { + let offset: number = index * this._vertAttrsFloatCount; + if (!this._mesh) { + this._vdataF32![offset++] = pvdata[0].x; // position + this._vdataF32![offset++] = pvdata[0].y; + this._vdataF32![offset++] = pvdata[0].z; + this._vdataF32![offset++] = pvdata[1].z; // frame idx + + this._vdataF32![offset++] = pvdata[2].x; // size + this._vdataF32![offset++] = pvdata[2].y; + this._vdataF32![offset++] = pvdata[2].z; + + this._vdataF32![offset++] = pvdata[3].x; // rotation + this._vdataF32![offset++] = pvdata[3].y; + this._vdataF32![offset++] = pvdata[3].z; + + this._vdataUint32![offset++] = pvdata[4]; // color + if (pvdata[5]) { + this._vdataF32![offset++] = pvdata[5].x; // velocity + this._vdataF32![offset++] = pvdata[5].y; + this._vdataF32![offset++] = pvdata[5].z; + } + } else { + this._vdataF32![offset++] = pvdata[0].x; // position + this._vdataF32![offset++] = pvdata[0].y; + this._vdataF32![offset++] = pvdata[0].z; + this._vdataF32![offset++] = pvdata[1].z; // frame idx + + this._vdataF32![offset++] = pvdata[2].x; // size + this._vdataF32![offset++] = pvdata[2].y; + this._vdataF32![offset++] = pvdata[2].z; + + this._vdataF32![offset++] = pvdata[3].x; // rotation + this._vdataF32![offset++] = pvdata[3].y; + this._vdataF32![offset++] = pvdata[3].z; + + this._vdataUint32![offset++] = pvdata[4]; // color } } public addGPUParticleVertexData (p: Particle, num: number, time:number) { - let offset = num * this._vertAttrsFloatCount * this._vertCount; - for (let i = 0; i < this._vertCount; i++) { - let idx = offset; - this._vdataF32![idx++] = p.position.x; - this._vdataF32![idx++] = p.position.y; - this._vdataF32![idx++] = p.position.z; - this._vdataF32![idx++] = time; + if (!this._useInstance) { + let offset = num * this._vertAttrsFloatCount * this._vertCount; + for (let i = 0; i < this._vertCount; i++) { + let idx = offset; + this._vdataF32![idx++] = p.position.x; + this._vdataF32![idx++] = p.position.y; + this._vdataF32![idx++] = p.position.z; + this._vdataF32![idx++] = time; - this._vdataF32![idx++] = p.startSize.x; - this._vdataF32![idx++] = p.startSize.y; - this._vdataF32![idx++] = p.startSize.z; - this._vdataF32![idx++] = _uvs[2 * i]; + this._vdataF32![idx++] = p.startSize.x; + this._vdataF32![idx++] = p.startSize.y; + this._vdataF32![idx++] = p.startSize.z; + this._vdataF32![idx++] = _uvs[2 * i]; - this._vdataF32![idx++] = p.rotation.x; - this._vdataF32![idx++] = p.rotation.y; - this._vdataF32![idx++] = p.rotation.z; - this._vdataF32![idx++] = _uvs[2 * i + 1]; + this._vdataF32![idx++] = p.rotation.x; + this._vdataF32![idx++] = p.rotation.y; + this._vdataF32![idx++] = p.rotation.z; + this._vdataF32![idx++] = _uvs[2 * i + 1]; - this._vdataF32![idx++] = p.startColor.r / 255.0; - this._vdataF32![idx++] = p.startColor.g / 255.0; - this._vdataF32![idx++] = p.startColor.b / 255.0; - this._vdataF32![idx++] = p.startColor.a / 255.0; + this._vdataF32![idx++] = p.startColor.r / 255.0; + this._vdataF32![idx++] = p.startColor.g / 255.0; + this._vdataF32![idx++] = p.startColor.b / 255.0; + this._vdataF32![idx++] = p.startColor.a / 255.0; - this._vdataF32![idx++] = p.velocity.x; - this._vdataF32![idx++] = p.velocity.y; - this._vdataF32![idx++] = p.velocity.z; - this._vdataF32![idx++] = p.startLifetime; + this._vdataF32![idx++] = p.velocity.x; + this._vdataF32![idx++] = p.velocity.y; + this._vdataF32![idx++] = p.velocity.z; + this._vdataF32![idx++] = p.startLifetime; - this._vdataF32![idx++] = p.randomSeed; + this._vdataF32![idx++] = p.randomSeed; - offset += this._vertAttrsFloatCount; + offset += this._vertAttrsFloatCount; + } + } else { + this.addGPUParticleVertexDataIns(p, num, time); } } + private addGPUParticleVertexDataIns (p: Particle, num: number, time:number) { + let offset = num * this._vertAttrsFloatCount; + let idx = offset; + this._vdataF32![idx++] = p.position.x; + this._vdataF32![idx++] = p.position.y; + this._vdataF32![idx++] = p.position.z; + this._vdataF32![idx++] = time; + + this._vdataF32![idx++] = p.startSize.x; + this._vdataF32![idx++] = p.startSize.y; + this._vdataF32![idx++] = p.startSize.z; + this._vdataF32![idx++] = p.frameIndex; + + this._vdataF32![idx++] = p.rotation.x; + this._vdataF32![idx++] = p.rotation.y; + this._vdataF32![idx++] = p.rotation.z; + + this._vdataF32![idx++] = p.startColor.r / 255.0; + this._vdataF32![idx++] = p.startColor.g / 255.0; + this._vdataF32![idx++] = p.startColor.b / 255.0; + this._vdataF32![idx++] = p.startColor.a / 255.0; + + this._vdataF32![idx++] = p.velocity.x; + this._vdataF32![idx++] = p.velocity.y; + this._vdataF32![idx++] = p.velocity.z; + this._vdataF32![idx++] = p.startLifetime; + + this._vdataF32![idx++] = p.randomSeed; + + offset += this._vertAttrsFloatCount; + } + public updateGPUParticles (num: number, time: number, dt: number) { - const pSize = this._vertAttrsFloatCount * this._vertCount; + if (!this._useInstance) { + const pSize = this._vertAttrsFloatCount * this._vertCount; + let pBaseIndex = 0; + let startTime = 0; + let lifeTime = 0; + let lastBaseIndex = 0; + let interval = 0; + for (let i = 0; i < num; ++i) { + pBaseIndex = i * pSize; + startTime = this._vdataF32![pBaseIndex + this._startTimeOffset]; + lifeTime = this._vdataF32![pBaseIndex + this._lifeTimeOffset]; + interval = time - startTime; + if (lifeTime - interval < dt) { + lastBaseIndex = --num * pSize; + this._vdataF32!.copyWithin(pBaseIndex, lastBaseIndex, lastBaseIndex + pSize); + i--; + } + } + + return num; + } else { + return this.updateGPUParticlesIns(num, time, dt); + } + } + + private updateGPUParticlesIns (num: number, time: number, dt: number) { + const pSize = this._vertAttrsFloatCount; let pBaseIndex = 0; let startTime = 0; let lifeTime = 0; @@ -310,42 +568,102 @@ export default class ParticleBatchModel extends scene.Model { } public updateIA (count: number) { + if (!this._useInstance) { + if (count <= 0) { + return; + } + const ia = this._subModels[0].inputAssembler; + ia.vertexBuffers[0].update(this._vdataF32!); + this._iaInfo.drawInfos[0].firstIndex = 0; + this._iaInfo.drawInfos[0].indexCount = this._indexCount * count; + this._iaInfoBuffer!.update(this._iaInfo); + } else { + this.updateIAIns(count); + } + } + + private updateIAIns (count: number) { if (count <= 0) { return; } const ia = this._subModels[0].inputAssembler; - ia.vertexBuffers[0].update(this._vdataF32!); + ia.vertexBuffers[0].update(this._vdataF32!); // update dynamic buffer + ia.instanceCount = count; this._iaInfo.drawInfos[0].firstIndex = 0; - this._iaInfo.drawInfos[0].indexCount = this._indexCount * count; + this._iaInfo.drawInfos[0].indexCount = this._indexCount; + this._iaInfo.drawInfos[0].instanceCount = count; this._iaInfoBuffer!.update(this._iaInfo); } public clear () { - this._subModels[0].inputAssembler.indexCount = 0; + if (!this._useInstance) { + this._subModels[0].inputAssembler.indexCount = 0; + } else { + this.clearIns(); + } + } + + private clearIns () { + this._subModels[0].inputAssembler.instanceCount = 0; } public destroy () { super.destroy(); + this.doDestroy(); + } + + public doDestroy () { this._vBuffer = null; this._vdataF32 = null; + this._vdataUint32 = null; + + this._insBuffers = []; + this._insIndices = null; + + this._vertAttrs = null; + this._material = null; + this._mesh = null; this.destroySubMeshData(); - if (this._iaInfoBuffer) { - this._iaInfoBuffer.destroy(); - this._iaInfoBuffer = null; - } } private rebuild () { - this._vBuffer = this.createSubMeshData(); + if (!this._useInstance) { + this._vBuffer = this.createSubMeshData(); + this._vdataF32 = new Float32Array(this._vBuffer); + this._vdataUint32 = new Uint32Array(this._vBuffer); + } else { + this.rebuildIns(); + } + } + + private rebuildIns () { + this._vBuffer = this.createSubMeshDataInsDynamic(); this._vdataF32 = new Float32Array(this._vBuffer); this._vdataUint32 = new Uint32Array(this._vBuffer); + + this.createSubMeshDataInsStatic(); + + this.createInsSubmesh(); } private destroySubMeshData () { if (this._subMeshData) { this._subMeshData.destroy(); this._subMeshData = null; + } + if (this._iaInfoBuffer) { + // this._iaInfoBuffer.destroy(); // Already destroied in _subMeshData this._iaInfoBuffer = null; } } + + public set useInstance (value: boolean) { + if (this._useInstance !== value) { + this._useInstance = value; + } + } + + public get useInstance (): boolean { + return this._useInstance; + } } diff --git a/cocos/particle/noise.ts b/cocos/particle/noise.ts new file mode 100644 index 0000000000..905d1d5c69 --- /dev/null +++ b/cocos/particle/noise.ts @@ -0,0 +1,190 @@ +/* + 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 { Vec2, Vec3 } from '../core/math'; + +export class ParticleNoise { + private permutation: number[] = [151, 160, 137, 91, 90, 15, + 131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23, + 190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33, + 88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166, + 77, 146, 158, 231, 83, 111, 229, 122, 60, 211, 133, 230, 220, 105, 92, 41, 55, 46, 245, 40, 244, + 102, 143, 54, 65, 25, 63, 161, 1, 216, 80, 73, 209, 76, 132, 187, 208, 89, 18, 169, 200, 196, + 135, 130, 116, 188, 159, 86, 164, 100, 109, 198, 173, 186, 3, 64, 52, 217, 226, 250, 124, 123, + 5, 202, 38, 147, 118, 126, 255, 82, 85, 212, 207, 206, 59, 227, 47, 16, 58, 17, 182, 189, 28, 42, + 223, 183, 170, 213, 119, 248, 152, 2, 44, 154, 163, 70, 221, 153, 101, 155, 167, 43, 172, 9, + 129, 22, 39, 253, 19, 98, 108, 110, 79, 113, 224, 232, 178, 185, 112, 104, 218, 246, 97, 228, + 251, 34, 242, 193, 238, 210, 144, 12, 191, 179, 162, 241, 81, 51, 145, 235, 249, 14, 239, 107, + 49, 192, 214, 31, 181, 199, 106, 157, 184, 84, 204, 176, 115, 121, 50, 45, 127, 4, 150, 254, + 138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180, + ]; + + constructor (permutation ? : number[]) { + if (permutation) { + this.permutation = permutation; + } + } + + public noise (x: number, y: number, z: number, min = 0, max = 1): number { + const p: number[] = new Array(512); + for (let i = 0; i < 256; i++) { p[256 + i] = p[i] = this.permutation[i]; } + + const X = Math.floor(x) & 255; // FIND UNIT CUBE THAT + const Y = Math.floor(y) & 255; // CONTAINS POINT. + const Z = Math.floor(z) & 255; + x -= Math.floor(x); // FIND RELATIVE X,Y,Z + y -= Math.floor(y); // OF POINT IN CUBE. + z -= Math.floor(z); + const u = this.fade(x); // COMPUTE FADE CURVES + const v = this.fade(y); // FOR EACH OF X,Y,Z. + const w = this.fade(z); + const A = p[X] + Y; + const AA = p[A] + Z; + const AB = p[A + 1] + Z; // HASH COORDINATES OF + const B = p[X + 1] + Y; + const BA = p[B] + Z; + const BB = p[B + 1] + Z; // THE 8 CUBE CORNERS, + + // The perlin noise value 0 -> 1 + const val = this.scale(this.lerp(w, this.lerp(v, this.lerp(u, this.grad(p[AA], x, y, z), // AND ADD + this.grad(p[BA], x - 1, y, z)), // BLENDED + this.lerp(u, this.grad(p[AB], x, y - 1, z), // RESULTS + this.grad(p[BB], x - 1, y - 1, z))), // FROM 8 + this.lerp(v, this.lerp(u, this.grad(p[AA + 1], x, y, z - 1), // CORNERS + this.grad(p[BA + 1], x - 1, y, z - 1)), // OF CUBE + this.lerp(u, this.grad(p[AB + 1], x, y - 1, z - 1), + this.grad(p[BB + 1], x - 1, y - 1, z - 1))))); + + return min + val * (max - min); + } + private fade (t: number): number { + return t * t * t * (t * (t * 6 - 15) + 10); + } + private lerp (t: number, a: number, b: number): number { + return a + t * (b - a); + } + private grad (hash: number, x: number, y: number, z: number): number { + const h = hash & 15; // CONVERT LO 4 BITS OF HASH CODE + const u = h < 8 ? x : y; // INTO 12 this.gradIENT DIRECTIONS. + const v = h < 4 ? y : h === 12 || h === 14 ? x : z; + return ((h & 1) === 0 ? u : -u) + ((h & 2) === 0 ? v : -v); + } + private scale (n: number): number { + return (1 + n) / 2; + } + + private accSpeed: Vec3 = new Vec3(); + private noiseSpeed: Vec3 = new Vec3(); + private noiseFrequency = 0.0; + private noiseAbs: Vec3 = new Vec3(); + private noiseAmplitude: Vec3 = new Vec3(); + private octaves: Vec3 = new Vec3(); + private dt = 0.0; + private point: Vec3 = new Vec3(); + private result: Vec3 = new Vec3(); + private mixOut: Vec2 = new Vec2(); + + public setSpeed (x, y, z) { + this.noiseSpeed.set(x, y, z); + } + + public setFrequency (f) { + this.noiseFrequency = f; + } + + public setAbs (x, y, z) { + this.noiseAbs.set(x, y, z); + } + + public setAmplititude (x, y, z) { + this.noiseAmplitude.set(x, y, z); + } + + public setOctaves (x, y, z) { + this.octaves.set(x, y, z); + } + + public setTime (t) { + this.dt = t; + } + + public setSamplePoint (p: Vec3) { + this.point.set(p); + } + + public getResult (): Vec3 { + return this.result; + } + + private getNoise (sx: number, sy: number, sz: number, time: number, offset: Vec3, noiseFrequency: number, octaves: Vec3): number { + let frequency = noiseFrequency; + let sum = 0.0; + sum += this.noise(sx * frequency, sy * frequency, sz * frequency, -1.0, 1.0); + if (octaves.x === 1) { + return sum; + } + + let amplitude = 1.0; + let range = 1.0; + for (let i = 1; i < octaves.x; ++i) { + amplitude *= octaves.y; + frequency *= octaves.z; + range += amplitude; + + sum += this.noise(sx * frequency, sy * frequency, sz * frequency, -1.0, 1.0) * amplitude; + } + return sum / range; + } + + private getNoiseMix (out: Vec2, point: Vec3, time: number, offSpeed: Vec3, noiseFrequency: number, octaves: Vec3) { + out.x = this.getNoise(point.x, point.y, point.z, time, offSpeed, noiseFrequency, octaves); + out.y = this.getNoise(point.y, point.z, point.x, time, offSpeed, noiseFrequency, octaves); + } + + public getNoiseParticle () { + this.accSpeed.set(this.noiseSpeed.x * this.dt, this.noiseSpeed.y * this.dt, this.noiseSpeed.z * this.dt); + + const axisOffset = 1000.0; + // eslint-disable-next-line max-len + const sampX = this.getNoise(this.point.z + this.accSpeed.x, this.point.y, this.point.x, this.dt, this.accSpeed, this.noiseFrequency, this.octaves); + // eslint-disable-next-line max-len + const sampY = this.getNoise(this.point.x + axisOffset, this.point.z + this.accSpeed.y, this.point.y, this.dt, this.accSpeed, this.noiseFrequency, this.octaves); + // eslint-disable-next-line max-len + const sampZ = this.getNoise(this.point.y, this.point.x + axisOffset, this.point.z + this.accSpeed.z, this.dt, this.accSpeed, this.noiseFrequency, this.octaves); + + this.result.set(sampX * this.noiseAmplitude.x, sampY * this.noiseAmplitude.y, sampZ * this.noiseAmplitude.z); + } + + public getPreview (out: number[], width: number, height: number) { + for (let h = 0; h < height; ++h) { + for (let w = 0; w < width; ++w) { + const sampx = (w - width * 0.5) / width + this.noiseSpeed.x * this.dt; + const sampy = (h - height * 0.5) / height + this.noiseSpeed.y * this.dt; + const pix = this.getNoise(sampx, sampy, 0.0, this.dt, this.accSpeed, this.noiseFrequency, this.octaves); + out[h * width + w] = (pix + 1.0) * 0.5; + } + } + } +} diff --git a/cocos/particle/particle-culler.ts b/cocos/particle/particle-culler.ts index 2a692b3315..9fccdaa948 100644 --- a/cocos/particle/particle-culler.ts +++ b/cocos/particle/particle-culler.ts @@ -1,5 +1,3 @@ -/* eslint-disable @typescript-eslint/restrict-plus-operands */ -/* eslint-disable max-len */ /* Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. @@ -25,22 +23,17 @@ THE SOFTWARE. */ -import { EDITOR } from 'internal:constants'; import { IParticleModule, Particle, PARTICLE_MODULE_ORDER } from './particle'; import { Node } from '../core/scene-graph/node'; import { TransformBit } from '../core/scene-graph/node-enum'; import { RenderMode, Space } from './enum'; -import { Color, Mat4, Material, pseudoRandom, Quat, randomRangeInt, RenderingSubMesh, Vec3, Vec4 } from '../core'; +import { Mat4, pseudoRandom, Quat, randomRangeInt, Vec3, Vec4 } from '../core'; import { INT_MAX } from '../core/math/bits'; import { particleEmitZAxis } from './particle-general-function'; import { IParticleSystemRenderer } from './renderer/particle-system-renderer-base'; import { Mesh } from '../3d'; import { AABB } from '../core/geometry'; -import { scene } from '../core/renderer'; -import { BlendFactor } from '../core/gfx'; -import { Primitive } from '../primitive/primitive'; -import { Root } from '../core/root'; -import { legacyCC } from '../core/global-exports'; +import type { ParticleSystem } from './particle-system'; const _node_mat = new Mat4(); const _node_rol = new Quat(); @@ -57,7 +50,7 @@ const _anim_module = [ ]; export class ParticleCuller { - private _particleSystem: any; + private _particleSystem: ParticleSystem; private _processor: IParticleSystemRenderer; private _node: Node; private _particlesAll: Particle[]; @@ -96,7 +89,7 @@ export class ParticleCuller { this._updateBoundingNode(); } - public setBoundingBoxCenter (px, py, pz) { + public setBoundingBoxCenter (px: number, py: number, pz: number) { this.maxPos.x = px + this._nodeSize.x * 0.5; this.maxPos.y = py + this._nodeSize.y * 0.5; this.maxPos.z = pz + this._nodeSize.z * 0.5; @@ -264,13 +257,14 @@ export class ParticleCuller { } } + const worldMat = this._particleSystem.node.worldMatrix; for (let i = 0; i < this._particlesAll.length; ++i) { const p: Particle = this._particlesAll[i]; Vec3.multiply(size, _node_scale, p.size); Vec3.multiply(size, size, meshSize); position.set(p.position); if (this._particleSystem.simulationSpace !== Space.World) { - Vec3.transformMat4(position, position, this._particleSystem.node._mat); + Vec3.transformMat4(position, position, worldMat); } if (isInit && i === 0) { Vec3.subtract(this.minPos, position, size); diff --git a/cocos/particle/particle-general-function.ts b/cocos/particle/particle-general-function.ts index ad0c0550f6..c82a86f3db 100644 --- a/cocos/particle/particle-general-function.ts +++ b/cocos/particle/particle-general-function.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { Mat4, Quat, random, randomRange, randomRangeInt, Vec2, Vec3 } from '../core/math'; import { sign } from '../core/math/bits'; import { Space } from './enum'; diff --git a/cocos/particle/particle-system.ts b/cocos/particle/particle-system.ts index 430b00a7a9..0111cd98c1 100644 --- a/cocos/particle/particle-system.ts +++ b/cocos/particle/particle-system.ts @@ -1,4 +1,3 @@ -/* eslint-disable max-len */ /* Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. @@ -24,19 +23,13 @@ THE SOFTWARE. */ -// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. - -/** - * @packageDocumentation - * @module particle - */ - // eslint-disable-next-line max-len -import { ccclass, help, executeInEditMode, executionOrder, menu, tooltip, displayOrder, type, range, displayName, formerlySerializedAs, override, radian, serializable, inspector, boolean, visible } from 'cc.decorator'; +import { ccclass, help, executeInEditMode, executionOrder, menu, tooltip, displayOrder, type, range, displayName, formerlySerializedAs, override, radian, serializable, visible } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; -import { RenderableComponent } from '../core/components/renderable-component'; +import { Renderer } from '../core/components/renderer'; +import { ModelRenderer } from '../core/components/model-renderer'; import { Material } from '../core/assets/material'; -import { Mat4, pseudoRandom, Quat, randomRangeInt, Vec2, Vec3, Vec4 } from '../core/math'; +import { Mat4, pseudoRandom, Quat, randomRangeInt, Vec2, Vec3 } from '../core/math'; import { INT_MAX } from '../core/math/bits'; import { scene } from '../core/renderer'; import ColorOverLifetimeModule from './animator/color-overtime'; @@ -50,29 +43,31 @@ import TextureAnimationModule from './animator/texture-animation'; import VelocityOvertimeModule from './animator/velocity-overtime'; import Burst from './burst'; import ShapeModule from './emitter/shape-module'; -import { CullingMode, RenderMode, Space } from './enum'; +import { CullingMode, Space } from './enum'; import { particleEmitZAxis } from './particle-general-function'; import ParticleSystemRenderer from './renderer/particle-system-renderer-data'; import TrailModule from './renderer/trail'; import { IParticleSystemRenderer } from './renderer/particle-system-renderer-base'; -import { Particle, PARTICLE_MODULE_PROPERTY } from './particle'; +import { PARTICLE_MODULE_PROPERTY } from './particle'; import { legacyCC } from '../core/global-exports'; import { TransformBit } from '../core/scene-graph/node-enum'; import { AABB, intersect } from '../core/geometry'; import { Camera } from '../core/renderer/scene'; import { ParticleCuller } from './particle-culler'; +import { NoiseModule } from './animator/noise-module'; +import { CCBoolean, CCFloat } from '../core'; const _world_mat = new Mat4(); const _world_rol = new Quat(); -const superMaterials = Object.getOwnPropertyDescriptor(RenderableComponent.prototype, 'sharedMaterials')!; +const superMaterials = Object.getOwnPropertyDescriptor(Renderer.prototype, 'sharedMaterials')!; @ccclass('cc.ParticleSystem') @help('i18n:cc.ParticleSystem') @menu('Effects/ParticleSystem') @executionOrder(99) @executeInEditMode -export class ParticleSystem extends RenderableComponent { +export class ParticleSystem extends ModelRenderer { /** * @zh 粒子系统能生成的最大粒子数量。 */ @@ -130,6 +125,7 @@ export class ParticleSystem extends RenderableComponent { @range([0, 1]) @displayOrder(10) @tooltip('i18n:particle_system.startSizeY') + @visible(function (this: ParticleSystem): boolean { return this.startSize3D; }) public startSizeY = new CurveRange(); /** @@ -140,6 +136,7 @@ export class ParticleSystem extends RenderableComponent { @range([0, 1]) @displayOrder(10) @tooltip('i18n:particle_system.startSizeZ') + @visible(function (this: ParticleSystem): boolean { return this.startSize3D; }) public startSizeZ = new CurveRange(); /** @@ -166,6 +163,7 @@ export class ParticleSystem extends RenderableComponent { @radian @displayOrder(12) @tooltip('i18n:particle_system.startRotationX') + @visible(function (this: ParticleSystem): boolean { return this.startRotation3D; }) public startRotationX = new CurveRange(); /** @@ -177,6 +175,7 @@ export class ParticleSystem extends RenderableComponent { @radian @displayOrder(12) @tooltip('i18n:particle_system.startRotationY') + @visible(function (this: ParticleSystem): boolean { return this.startRotation3D; }) public startRotationY = new CurveRange(); /** @@ -188,6 +187,7 @@ export class ParticleSystem extends RenderableComponent { @radian @displayOrder(12) @tooltip('i18n:particle_system.startRotationZ') + @visible(function (this: ParticleSystem): boolean { return this.startRotation3D; }) public startRotationZ = new CurveRange(); /** @@ -323,7 +323,7 @@ export class ParticleSystem extends RenderableComponent { * @en Enable particle culling switch. Open it to enable particle culling. If enabled will generate emitter bounding box and emitters outside the frustum will be culled. * @zh 粒子剔除开关,如果打开将会生成一个发射器包围盒,包围盒在相机外发射器将被剔除。 */ - @type(Boolean) + @type(CCBoolean) @displayOrder(27) @tooltip('i18n:particle_system.renderCulling') set renderCulling (value: boolean) { @@ -367,7 +367,7 @@ export class ParticleSystem extends RenderableComponent { * @en Particle bounding box half width. * @zh 粒子包围盒半宽。 */ - @type(Number) + @type(CCFloat) @displayOrder(17) @tooltip('i18n:particle_system.aabbHalfX') get aabbHalfX () { @@ -390,7 +390,7 @@ export class ParticleSystem extends RenderableComponent { * @en Particle bounding box half height. * @zh 粒子包围盒半高。 */ - @type(Number) + @type(CCFloat) @displayOrder(17) @tooltip('i18n:particle_system.aabbHalfY') get aabbHalfY () { @@ -413,7 +413,7 @@ export class ParticleSystem extends RenderableComponent { * @en Particle bounding box half depth. * @zh 粒子包围盒半深。 */ - @type(Number) + @type(CCFloat) @displayOrder(17) @tooltip('i18n:particle_system.aabbHalfZ') get aabbHalfZ () { @@ -476,7 +476,7 @@ export class ParticleSystem extends RenderableComponent { @displayOrder(23) @tooltip('i18n:particle_system.colorOverLifetimeModule') public get colorOverLifetimeModule () { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { if (!this._colorOverLifetimeModule) { this._colorOverLifetimeModule = new ColorOverLifetimeModule(); this._colorOverLifetimeModule.bindTarget(this.processor); @@ -500,7 +500,7 @@ export class ParticleSystem extends RenderableComponent { @displayOrder(17) @tooltip('i18n:particle_system.shapeModule') public get shapeModule () { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { if (!this._shapeModule) { this._shapeModule = new ShapeModule(); this._shapeModule.onInit(this); @@ -524,7 +524,7 @@ export class ParticleSystem extends RenderableComponent { @displayOrder(21) @tooltip('i18n:particle_system.sizeOvertimeModule') public get sizeOvertimeModule () { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { if (!this._sizeOvertimeModule) { this._sizeOvertimeModule = new SizeOvertimeModule(); this._sizeOvertimeModule.bindTarget(this.processor); @@ -548,7 +548,7 @@ export class ParticleSystem extends RenderableComponent { @displayOrder(18) @tooltip('i18n:particle_system.velocityOvertimeModule') public get velocityOvertimeModule () { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { if (!this._velocityOvertimeModule) { this._velocityOvertimeModule = new VelocityOvertimeModule(); this._velocityOvertimeModule.bindTarget(this.processor); @@ -572,7 +572,7 @@ export class ParticleSystem extends RenderableComponent { @displayOrder(19) @tooltip('i18n:particle_system.forceOvertimeModule') public get forceOvertimeModule () { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { if (!this._forceOvertimeModule) { this._forceOvertimeModule = new ForceOvertimeModule(); this._forceOvertimeModule.bindTarget(this.processor); @@ -597,7 +597,7 @@ export class ParticleSystem extends RenderableComponent { @displayOrder(20) @tooltip('i18n:particle_system.limitVelocityOvertimeModule') public get limitVelocityOvertimeModule () { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { if (!this._limitVelocityOvertimeModule) { this._limitVelocityOvertimeModule = new LimitVelocityOvertimeModule(); this._limitVelocityOvertimeModule.bindTarget(this.processor); @@ -621,7 +621,7 @@ export class ParticleSystem extends RenderableComponent { @displayOrder(22) @tooltip('i18n:particle_system.rotationOvertimeModule') public get rotationOvertimeModule () { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { if (!this._rotationOvertimeModule) { this._rotationOvertimeModule = new RotationOvertimeModule(); this._rotationOvertimeModule.bindTarget(this.processor); @@ -645,7 +645,7 @@ export class ParticleSystem extends RenderableComponent { @displayOrder(24) @tooltip('i18n:particle_system.textureAnimationModule') public get textureAnimationModule () { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { if (!this._textureAnimationModule) { this._textureAnimationModule = new TextureAnimationModule(); this._textureAnimationModule.bindTarget(this.processor); @@ -659,6 +659,27 @@ export class ParticleSystem extends RenderableComponent { this._textureAnimationModule = val; } + // noise module + @type(NoiseModule) + private _noiseModule: NoiseModule | null = null; + + @type(NoiseModule) + @displayOrder(24) + public get noiseModule () { + if (EDITOR) { + if (!this._noiseModule) { + this._noiseModule = new NoiseModule(); + this._noiseModule.bindTarget(this.processor); + } + } + return this._noiseModule; + } + + public set noiseModule (val) { + if (!val) return; + this._noiseModule = val; + } + // trail module @type(TrailModule) _trailModule: TrailModule | null = null; @@ -669,7 +690,7 @@ export class ParticleSystem extends RenderableComponent { @displayOrder(25) @tooltip('i18n:particle_system.trailModule') public get trailModule () { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { if (!this._trailModule) { this._trailModule = new TrailModule(); this._trailModule.onInit(this); @@ -718,6 +739,8 @@ export class ParticleSystem extends RenderableComponent { private _subEmitters: any[]; // array of { emitter: ParticleSystem, type: 'birth', 'collision' or 'death'} + private _needAttach: boolean; + @serializable private _prewarm = false; @@ -743,6 +766,7 @@ export class ParticleSystem extends RenderableComponent { this._isStopped = true; this._isEmitting = false; this._needRefresh = true; + this._needAttach = false; this._time = 0.0; // playback position in seconds. this._emitRateTimeCounter = 0.0; @@ -779,7 +803,7 @@ export class ParticleSystem extends RenderableComponent { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _onMaterialModified (index: number, material: Material) { if (this.processor !== null) { @@ -788,14 +812,14 @@ export class ParticleSystem extends RenderableComponent { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _onRebuildPSO (index: number, material: Material) { this.processor.onRebuildPSO(index, material); } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _collectModels (): scene.Model[] { this._models.length = 0; @@ -836,6 +860,7 @@ export class ParticleSystem extends RenderableComponent { if (this._limitVelocityOvertimeModule) this._limitVelocityOvertimeModule.bindTarget(this.processor); if (this._velocityOvertimeModule) this._velocityOvertimeModule.bindTarget(this.processor); if (this._textureAnimationModule) this._textureAnimationModule.bindTarget(this.processor); + if (this._noiseModule) this._noiseModule.bindTarget(this.processor); } // TODO: Fast forward current particle system by simulating particles over given period of time, then pause it. @@ -844,7 +869,8 @@ export class ParticleSystem extends RenderableComponent { // } /** - * 播放粒子效果。 + * @en play particle system + * @zh 播放粒子效果。 */ public play () { if (this._isPaused) { @@ -877,7 +903,8 @@ export class ParticleSystem extends RenderableComponent { } /** - * 暂停播放粒子效果。 + * @en pause particle system + * @zh 暂停播放粒子效果。 */ public pause () { if (this._isStopped) { @@ -892,7 +919,16 @@ export class ParticleSystem extends RenderableComponent { } /** - * 停止播放粒子。 + * @zh 停止发射粒子。 + * @en Stop emitting particles. + */ + public stopEmitting () { + this._isEmitting = false; + } + + /** + * @en stop particle system + * @zh 停止播放粒子。 */ public stop () { if (this._isPlaying || this._isPaused) { @@ -904,6 +940,9 @@ export class ParticleSystem extends RenderableComponent { if (this._isPaused) { this._isPaused = false; } + if (this._isEmitting) { + this._isEmitting = false; + } this._time = 0.0; this._emitRateTimeCounter = 0.0; @@ -919,9 +958,9 @@ export class ParticleSystem extends RenderableComponent { } } - // remove all particles from current particle system. /** - * 将所有粒子从粒子系统中清除。 + * @en remove all particles from current particle system. + * @zh 将所有粒子从粒子系统中清除。 */ public clear () { if (this.enabledInHierarchy) { @@ -962,8 +1001,9 @@ export class ParticleSystem extends RenderableComponent { } protected onEnable () { + super.onEnable(); legacyCC.director.on(legacyCC.Director.EVENT_BEFORE_COMMIT, this.beforeRender, this); - if (this.playOnAwake) { + if (this.playOnAwake && (!EDITOR || legacyCC.GAME_VIEW)) { this.play(); } this.processor.onEnable(); @@ -1063,7 +1103,7 @@ export class ParticleSystem extends RenderableComponent { const camera:Camera = cameraLst[i]; const visibility = camera.visibility; if ((visibility & this.node.layer) === this.node.layer) { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { if (camera.name === 'Editor Camera' && intersect.aabbFrustum(this._boundingBox, camera.frustum)) { culled = false; break; @@ -1130,6 +1170,22 @@ export class ParticleSystem extends RenderableComponent { if (this._trailModule && this._trailModule.enable) { this._trailModule.updateRenderData(); } + + if (this._needAttach) { // Check whether this particle model should be reattached + if (this.getParticleCount() > 0) { + if (!this._isCulled) { + if (!this.processor.getModel()?.scene) { + this.processor.attachToScene(); + } + if (this._trailModule && this._trailModule.enable) { + if (!this._trailModule.getModel()?.scene) { + this._trailModule._attachToScene(); + } + } + this._needAttach = false; + } + } + } } protected beforeRender () { @@ -1138,6 +1194,18 @@ export class ParticleSystem extends RenderableComponent { if (this._trailModule && this._trailModule.enable) { this._trailModule.beforeRender(); } + + if (this.getParticleCount() <= 0) { + if (this.processor.getModel()?.scene) { + this.processor.detachFromScene(); + if (this._trailModule && this._trailModule.enable) { + this._trailModule._detachFromScene(); + } + this._needAttach = false; + } + } else if (!this.processor.getModel()?.scene) { + this._needAttach = true; + } } protected _onVisibilityChange (val) { @@ -1254,13 +1322,14 @@ export class ParticleSystem extends RenderableComponent { // this._emitRateDistanceCounter = 0.0; if (!this.loop) { this._isEmitting = false; - return; } } + if (!this._isEmitting) return; + // emit by rateOverTime this._emitRateTimeCounter += this.rateOverTime.evaluate(this._time / this.duration, 1)! * dt; - if (this._emitRateTimeCounter > 1 && this._isEmitting) { + if (this._emitRateTimeCounter > 1) { const emitNum = Math.floor(this._emitRateTimeCounter); this._emitRateTimeCounter -= emitNum; this.emit(emitNum, dt); @@ -1272,7 +1341,7 @@ export class ParticleSystem extends RenderableComponent { Vec3.copy(this._oldWPos, this._curWPos); this._emitRateDistanceCounter += distance * this.rateOverDistance.evaluate(this._time / this.duration, 1)!; - if (this._emitRateDistanceCounter > 1 && this._isEmitting) { + if (this._emitRateDistanceCounter > 1) { const emitNum = Math.floor(this._emitRateDistanceCounter); this._emitRateDistanceCounter -= emitNum; this.emit(emitNum, dt); @@ -1366,10 +1435,18 @@ export class ParticleSystem extends RenderableComponent { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _onBeforeSerialize (props) { // eslint-disable-next-line @typescript-eslint/no-unsafe-return return this.dataCulling ? props.filter((p) => !PARTICLE_MODULE_PROPERTY.includes(p) || (this[p] && this[p].enable)) : props; } + + public getNoisePreview (width: number, height: number): number[] { + const out: number[] = []; + if (this.processor) { + this.processor.getNoisePreview(out, width, height); + } + return out; + } } diff --git a/cocos/particle/particle-utils.ts b/cocos/particle/particle-utils.ts index a80c619e9b..2aef3a267f 100644 --- a/cocos/particle/particle-utils.ts +++ b/cocos/particle/particle-utils.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { instantiate } from '../core/data'; import { CCObject } from '../core/data/object'; import { Director, director } from '../core/director'; @@ -34,7 +32,8 @@ import { ParticleSystem } from './particle-system'; export class ParticleUtils { /** - * instantiate + * @en instantiate particle system from prefab + * @zh 从 prefab 实例化粒子系统 */ public static instantiate (prefab) { if (!this.registeredSceneEvent) { @@ -42,6 +41,7 @@ export class ParticleUtils { this.registeredSceneEvent = true; } if (!this.particleSystemPool.has(prefab._uuid)) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-return this.particleSystemPool.set(prefab._uuid, new Pool(() => instantiate(prefab) || new Node(), 1, (prefab) => prefab.destroy())); } return this.particleSystemPool.get(prefab._uuid)!.alloc(); diff --git a/cocos/particle/particle.ts b/cocos/particle/particle.ts index 7ce67bd8a2..a7e2e9c09a 100644 --- a/cocos/particle/particle.ts +++ b/cocos/particle/particle.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { Color, Vec3, Mat4, Quat } from '../core/math'; import { ParticleSystem } from './particle-system'; import { IParticleSystemRenderer } from './renderer/particle-system-renderer-base'; @@ -112,6 +110,7 @@ export const PARTICLE_MODULE_NAME = { SIZE: 'sizeModule', VELOCITY: 'velocityModule', TEXTURE: 'textureModule', + NOISE: 'noiseModule', }; export const PARTICLE_MODULE_ORDER = [ @@ -122,6 +121,7 @@ export const PARTICLE_MODULE_ORDER = [ 'limitModule', 'rotationModule', 'textureModule', + 'noiseModule', ]; export const PARTICLE_MODULE_PROPERTY = [ @@ -133,6 +133,7 @@ export const PARTICLE_MODULE_PROPERTY = [ '_limitVelocityOvertimeModule', '_rotationOvertimeModule', '_textureAnimationModule', + '_noiseModule', '_trailModule', ]; diff --git a/cocos/particle/renderer/particle-system-renderer-base.ts b/cocos/particle/renderer/particle-system-renderer-base.ts index fab35522c7..e5b8fa4a6c 100644 --- a/cocos/particle/renderer/particle-system-renderer-base.ts +++ b/cocos/particle/renderer/particle-system-renderer-base.ts @@ -24,7 +24,7 @@ */ import { Component } from '../../core'; -import { Attribute } from '../../core/gfx'; +import { Attribute, deviceManager, Feature } from '../../core/gfx'; import ParticleBatchModel from '../models/particle-batch-model'; import ParticleSystemRenderer from './particle-system-renderer-data'; import { Material } from '../../core/assets'; @@ -60,6 +60,9 @@ export interface IParticleSystemRenderer { updateTrailMaterial (): void; getDefaultTrailMaterial (): any; beforeRender (): void; + setUseInstance (value: boolean): void; + getUseInstance (): boolean; + getNoisePreview (out: number[], width: number, height: number): void; } export abstract class ParticleSystemRendererBase implements IParticleSystemRenderer { @@ -67,9 +70,19 @@ export abstract class ParticleSystemRendererBase implements IParticleSystemRende protected _model: ParticleBatchModel | null = null; protected _renderInfo: ParticleSystemRenderer | null = null; protected _vertAttrs: Attribute[] = []; + protected _useInstance: boolean; constructor (info: ParticleSystemRenderer) { this._renderInfo = info; + if (!deviceManager.gfxDevice.hasFeature(Feature.INSTANCED_ARRAYS)) { + this._useInstance = false; + } else { + this._useInstance = true; + } + } + + public getUseInstance (): boolean { + return this._useInstance; } public getInfo () { @@ -155,4 +168,6 @@ export abstract class ParticleSystemRendererBase implements IParticleSystemRende public abstract updateRenderData (): void; public abstract enableModule (name: string, val: boolean, pm: IParticleModule): void; public abstract beforeRender (): void; + public abstract setUseInstance (value: boolean): void; + public abstract getNoisePreview (out: number[], width: number, height: number): void; } diff --git a/cocos/particle/renderer/particle-system-renderer-cpu.ts b/cocos/particle/renderer/particle-system-renderer-cpu.ts index fd9becb2ef..83502a5184 100644 --- a/cocos/particle/renderer/particle-system-renderer-cpu.ts +++ b/cocos/particle/renderer/particle-system-renderer-cpu.ts @@ -27,16 +27,19 @@ import { EDITOR } from 'internal:constants'; import { builtinResMgr } from '../../core/builtin'; import { Material } from '../../core/assets'; import { AttributeName, Format, Attribute } from '../../core/gfx'; -import { Mat4, Vec2, Vec3, Vec4, pseudoRandom, Quat } from '../../core/math'; +import { Mat4, Vec2, Vec3, Vec4, pseudoRandom, Quat, random } from '../../core/math'; import { RecyclePool } from '../../core/memop'; import { MaterialInstance, IMaterialInstanceInfo } from '../../core/renderer/core/material-instance'; import { MacroRecord } from '../../core/renderer/core/pass-utils'; import { AlignmentSpace, RenderMode, Space } from '../enum'; -import { Particle, IParticleModule, PARTICLE_MODULE_ORDER } from '../particle'; +import { Particle, IParticleModule, PARTICLE_MODULE_ORDER, PARTICLE_MODULE_NAME } from '../particle'; import { ParticleSystemRendererBase } from './particle-system-renderer-base'; import { Component } from '../../core'; import { Camera } from '../../core/renderer/scene/camera'; import { Pass } from '../../core/renderer'; +import { ParticleNoise } from '../noise'; +import { NoiseModule } from '../animator/noise-module'; +import { legacyCC } from '../../core/global-exports'; const _tempAttribUV = new Vec3(); const _tempWorldTrans = new Mat4(); @@ -51,6 +54,7 @@ const _anim_module = [ '_limitVelocityOvertimeModule', '_rotationOvertimeModule', '_textureAnimationModule', + '_noiseModule', ]; const _uvs = [ @@ -64,6 +68,7 @@ const CC_USE_WORLD_SPACE = 'CC_USE_WORLD_SPACE'; const CC_RENDER_MODE = 'CC_RENDER_MODE'; const ROTATION_OVER_TIME_MODULE_ENABLE = 'ROTATION_OVER_TIME_MODULE_ENABLE'; +const INSTANCE_PARTICLE = 'CC_INSTANCE_PARTICLE'; const RENDER_MODE_BILLBOARD = 0; const RENDER_MODE_STRETCHED_BILLBOARD = 1; const RENDER_MODE_HORIZONTAL_BILLBOARD = 2; @@ -98,6 +103,34 @@ const _vertex_attrs_mesh = [ new Attribute(AttributeName.ATTR_COLOR1, Format.RGBA8, true), // mesh color ]; +const _vertex_attrs_ins = [ + new Attribute(AttributeName.ATTR_TEX_COORD4, Format.RGBA32F, false, 0, true), // position,frame idx + new Attribute(AttributeName.ATTR_TEX_COORD1, Format.RGB32F, false, 0, true), // size + new Attribute(AttributeName.ATTR_TEX_COORD2, Format.RGB32F, false, 0, true), // rotation + new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true, 0, true), // color + new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGB32F, false, 1), // uv +]; + +const _vertex_attrs_stretch_ins = [ + new Attribute(AttributeName.ATTR_TEX_COORD4, Format.RGBA32F, false, 0, true), // position,frame idx + new Attribute(AttributeName.ATTR_TEX_COORD1, Format.RGB32F, false, 0, true), // size + new Attribute(AttributeName.ATTR_TEX_COORD2, Format.RGB32F, false, 0, true), // rotation + new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true, 0, true), // color + new Attribute(AttributeName.ATTR_COLOR1, Format.RGB32F, false, 0, true), // particle velocity + new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGB32F, false, 1), // uv +]; + +const _vertex_attrs_mesh_ins = [ + new Attribute(AttributeName.ATTR_TEX_COORD4, Format.RGBA32F, false, 0, true), // particle position,frame idx + new Attribute(AttributeName.ATTR_TEX_COORD1, Format.RGB32F, false, 0, true), // size + new Attribute(AttributeName.ATTR_TEX_COORD2, Format.RGB32F, false, 0, true), // rotation + new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true, 0, true), // particle color + new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGB32F, false, 1), // mesh uv + new Attribute(AttributeName.ATTR_TEX_COORD3, Format.RGB32F, false, 1), // mesh position + new Attribute(AttributeName.ATTR_NORMAL, Format.RGB32F, false, 1), // mesh normal + new Attribute(AttributeName.ATTR_COLOR1, Format.RGBA8, true, 1), // mesh color +]; + const _matInsInfo: IMaterialInstanceInfo = { parent: null!, owner: null!, @@ -134,7 +167,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas this._frameTile_velLenScale = new Vec4(1, 1, 0, 0); this._tmp_velLenScale = this._frameTile_velLenScale.clone(); this._node_scale = new Vec4(); - this._attrs = new Array(5); + this._attrs = new Array(7); this._defines = { CC_USE_WORLD_SPACE: true, CC_USE_BILLBOARD: true, @@ -179,6 +212,11 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas this.setVertexAttributes(); } + public onDestroy (): void { + this._particles?.destroy(); + super.onDestroy(); + } + public getFreeParticle (): Particle | null { if (this._particles!.length >= this._particleSystem.capacity) { return null; @@ -246,7 +284,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas this._alignSpace = space; } - public getDefaultMaterial(): Material | null { + public getDefaultMaterial (): Material | null { return this._defaultMat; } @@ -274,7 +312,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas for (let i = 0; i < cameraLst?.length; ++i) { const camera:Camera = cameraLst[i]; // eslint-disable-next-line max-len - const checkCamera: boolean = !EDITOR ? (camera.visibility & this._particleSystem.node.layer) === this._particleSystem.node.layer : camera.name === 'Editor Camera'; + const checkCamera: boolean = (!EDITOR || legacyCC.GAME_VIEW) ? (camera.visibility & this._particleSystem.node.layer) === this._particleSystem.node.layer : camera.name === 'Editor Camera'; if (checkCamera) { Quat.fromViewUp(_node_rot, camera.forward); break; @@ -307,6 +345,8 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas pass.setUniform(this._uScaleHandle, this._node_scale); } + private noise: ParticleNoise = new ParticleNoise(); + public updateParticles (dt: number) { const ps = this._particleSystem; if (!ps) { @@ -380,6 +420,15 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas return this._particles!.length; } + public getNoisePreview (out: number[], width: number, height: number) { + this._runAnimateList.forEach((value) => { + if (value.name === PARTICLE_MODULE_NAME.NOISE) { + const m = value as NoiseModule; + m.getNoisePreview(out, this._particleSystem, width, height); + } + }); + } + // internal function public updateRenderData () { // update vertex buffer @@ -449,46 +498,95 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas } private _fillStrecthedData (p: Particle, idx: number, fi: number) { - for (let j = 0; j < 4; ++j) { // four verts per particle. - this._attrs[0] = p.position; - _tempAttribUV.x = _uvs[2 * j]; - _tempAttribUV.y = _uvs[2 * j + 1]; - _tempAttribUV.z = fi; - this._attrs[1] = _tempAttribUV; - this._attrs[2] = p.size; - this._attrs[3] = p.rotation; - this._attrs[4] = p.color._val; - this._attrs[5] = p.ultimateVelocity; - this._attrs[6] = null; - this._model!.addParticleVertexData(idx++, this._attrs); + if (!this._useInstance) { + for (let j = 0; j < 4; ++j) { // four verts per particle. + this._attrs[0] = p.position; + _tempAttribUV.x = _uvs[2 * j]; + _tempAttribUV.y = _uvs[2 * j + 1]; + _tempAttribUV.z = fi; + this._attrs[1] = _tempAttribUV; + this._attrs[2] = p.size; + this._attrs[3] = p.rotation; + this._attrs[4] = p.color._val; + this._attrs[5] = p.ultimateVelocity; + this._attrs[6] = null; + this._model!.addParticleVertexData(idx++, this._attrs); + } + } else { + this._fillStrecthedDataIns(p, idx, fi); } } + private _fillStrecthedDataIns (p: Particle, idx: number, fi: number) { + const i = idx / 4; + this._attrs[0] = p.position; + _tempAttribUV.z = fi; + this._attrs[1] = _tempAttribUV; + this._attrs[2] = p.size; + this._attrs[3] = p.rotation; + this._attrs[4] = p.color._val; + this._attrs[5] = p.ultimateVelocity; + this._model!.addParticleVertexData(i, this._attrs); + } + private _fillNormalData (p: Particle, idx: number, fi: number) { - for (let j = 0; j < 4; ++j) { // four verts per particle. - this._attrs[0] = p.position; - _tempAttribUV.x = _uvs[2 * j]; - _tempAttribUV.y = _uvs[2 * j + 1]; - _tempAttribUV.z = fi; - this._attrs[1] = _tempAttribUV; - this._attrs[2] = p.size; - this._attrs[3] = p.rotation; - this._attrs[4] = p.color._val; - this._attrs[5] = null; - this._model!.addParticleVertexData(idx++, this._attrs); + if (!this._useInstance) { + for (let j = 0; j < 4; ++j) { // four verts per particle. + this._attrs[0] = p.position; + _tempAttribUV.x = _uvs[2 * j]; + _tempAttribUV.y = _uvs[2 * j + 1]; + _tempAttribUV.z = fi; + this._attrs[1] = _tempAttribUV; + this._attrs[2] = p.size; + this._attrs[3] = p.rotation; + this._attrs[4] = p.color._val; + this._attrs[5] = null; + this._model!.addParticleVertexData(idx++, this._attrs); + } + } else { + this._fillNormalDataIns(p, idx, fi); } } + private _fillNormalDataIns (p: Particle, idx: number, fi: number) { + const i = idx / 4; + this._attrs[0] = p.position; + _tempAttribUV.z = fi; + this._attrs[1] = _tempAttribUV; + this._attrs[2] = p.size; + this._attrs[3] = p.rotation; + this._attrs[4] = p.color._val; + this._attrs[5] = null; + this._model!.addParticleVertexData(i, this._attrs); + } + private _setVertexAttrib () { + if (!this._useInstance) { + switch (this._renderInfo!.renderMode) { + case RenderMode.StrecthedBillboard: + this._vertAttrs = _vertex_attrs_stretch.slice(); + break; + case RenderMode.Mesh: + this._vertAttrs = _vertex_attrs_mesh.slice(); + break; + default: + this._vertAttrs = _vertex_attrs.slice(); + } + } else { + this._setVertexAttribIns(); + } + } + + private _setVertexAttribIns () { switch (this._renderInfo!.renderMode) { case RenderMode.StrecthedBillboard: - this._vertAttrs = _vertex_attrs_stretch.slice(); + this._vertAttrs = _vertex_attrs_stretch_ins.slice(); break; case RenderMode.Mesh: - this._vertAttrs = _vertex_attrs_mesh.slice(); + this._vertAttrs = _vertex_attrs_mesh_ins.slice(); break; default: - this._vertAttrs = _vertex_attrs.slice(); + this._vertAttrs = _vertex_attrs_ins.slice(); } } @@ -503,7 +601,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas const effectName = shareMaterial._effectAsset._name; this._renderInfo!.mainTexture = shareMaterial.getProperty('mainTexture', 0); // reset material - if (effectName.indexOf('particle') === -1 || effectName.indexOf('particle-gpu') !== -1) { + if (effectName.indexOf('builtin-particle') === -1 || effectName.indexOf('builtin-particle-gpu') !== -1) { ps.setMaterial(null, 0); } } @@ -562,6 +660,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas const roationModule = this._particleSystem._rotationOvertimeModule; enable = roationModule && roationModule.enable; this._defines[ROTATION_OVER_TIME_MODULE_ENABLE] = enable; + this._defines[INSTANCE_PARTICLE] = this._useInstance; mat.recompileShaders(this._defines); if (this._model) { @@ -596,4 +695,16 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas trailModule.updateMaterial(); } } + + public setUseInstance (value: boolean) { + if (this._useInstance === value) { + return; + } + this._useInstance = value; + if (this._model) { + this._model.useInstance = value; + this._model.doDestroy(); + } + this.updateRenderMode(); + } } diff --git a/cocos/particle/renderer/particle-system-renderer-data.ts b/cocos/particle/renderer/particle-system-renderer-data.ts index c07d71e89f..7c25be4fad 100644 --- a/cocos/particle/renderer/particle-system-renderer-data.ts +++ b/cocos/particle/renderer/particle-system-renderer-data.ts @@ -23,7 +23,7 @@ THE SOFTWARE. */ -import { ccclass, tooltip, displayOrder, type, serializable } from 'cc.decorator'; +import { ccclass, tooltip, displayOrder, type, serializable, disallowAnimation, visible } from 'cc.decorator'; import { Mesh } from '../../3d'; import { Material, Texture2D } from '../../core/assets'; import { AlignmentSpace, RenderMode, Space } from '../enum'; @@ -136,6 +136,8 @@ export default class ParticleSystemRenderer { */ @type(Material) @displayOrder(8) + @disallowAnimation + @visible(false) @tooltip('i18n:particleSystemRenderer.particleMaterial') public get particleMaterial () { if (!this._particleSystem) { @@ -151,10 +153,69 @@ export default class ParticleSystemRenderer { } /** + * @en particle cpu material + * @zh 粒子使用的cpu材质。 + */ + @type(Material) + @displayOrder(8) + @disallowAnimation + @visible(function (this: ParticleSystemRenderer): boolean { return !this._useGPU; }) + public get cpuMaterial () { + return this._cpuMaterial; + } + + public set cpuMaterial (val: Material | null) { + if (val === null) { + return; + } else { + const effectName = val.effectName; + if (effectName.indexOf('particle') === -1 || effectName.indexOf('particle-gpu') !== -1) { + return; + } + } + this._cpuMaterial = val; + this.particleMaterial = this._cpuMaterial; + } + + @serializable + private _cpuMaterial: Material | null = null; + + /** + * @en particle gpu material + * @zh 粒子使用的gpu材质。 + */ + @type(Material) + @displayOrder(8) + @disallowAnimation + @visible(function (this: ParticleSystemRenderer): boolean { return this._useGPU; }) + public get gpuMaterial () { + return this._gpuMaterial; + } + + public set gpuMaterial (val: Material | null) { + if (val === null) { + return; + } else { + const effectName = val.effectName; + if (effectName.indexOf('particle-gpu') === -1) { + return; + } + } + this._gpuMaterial = val; + this.particleMaterial = this._gpuMaterial; + } + + @serializable + private _gpuMaterial: Material | null = null; + + /** + * @en particle trail material * @zh 拖尾使用的材质。 */ @type(Material) @displayOrder(9) + @disallowAnimation + @visible(function (this: ParticleSystemRenderer): boolean { return !this._useGPU; }) @tooltip('i18n:particleSystemRenderer.trailMaterial') public get trailMaterial () { if (!this._particleSystem) { @@ -246,6 +307,11 @@ export default class ParticleSystemRenderer { } else { errorID(6034); } + if (!this._useGPU) { + this.cpuMaterial = this.particleMaterial; + } else { + this.gpuMaterial = this.particleMaterial; + } } private _switchProcessor () { @@ -257,6 +323,12 @@ export default class ParticleSystemRenderer { this._particleSystem.processor.clear(); this._particleSystem.processor = null!; } + if (!this._useGPU && this.cpuMaterial) { + this.particleMaterial = this.cpuMaterial; + } + if (this._useGPU && this.gpuMaterial) { + this.particleMaterial = this.gpuMaterial; + } this._particleSystem.processor = this._useGPU ? new ParticleSystemRendererGPU(this) : new ParticleSystemRendererCPU(this); this._particleSystem.processor.updateAlignSpace(this.alignSpace); this._particleSystem.processor.onInit(this._particleSystem); diff --git a/cocos/particle/renderer/particle-system-renderer-gpu.ts b/cocos/particle/renderer/particle-system-renderer-gpu.ts index ea881ded04..d8dd3d19fd 100644 --- a/cocos/particle/renderer/particle-system-renderer-gpu.ts +++ b/cocos/particle/renderer/particle-system-renderer-gpu.ts @@ -28,7 +28,7 @@ import { builtinResMgr } from '../../core/builtin'; import { Material } from '../../core/assets'; import { Texture2D } from '../../core'; import { Component } from '../../core/components'; -import { AttributeName, Format, Attribute, API } from '../../core/gfx'; +import { AttributeName, Format, Attribute, API, deviceManager } from '../../core/gfx'; import { Mat4, Vec2, Vec4, Quat, Vec3 } from '../../core/math'; import { MaterialInstance, IMaterialInstanceInfo } from '../../core/renderer/core/material-instance'; import { MacroRecord } from '../../core/renderer/core/pass-utils'; @@ -66,6 +66,7 @@ const VELOCITY_OVER_TIME_MODULE_ENABLE = 'VELOCITY_OVER_TIME_MODULE_ENABLE'; const FORCE_OVER_TIME_MODULE_ENABLE = 'FORCE_OVER_TIME_MODULE_ENABLE'; const TEXTURE_ANIMATION_MODULE_ENABLE = 'TEXTURE_ANIMATION_MODULE_ENABLE'; const USE_VK_SHADER = 'USE_VK_SHADER'; +const INSTANCE_PARTICLE = 'CC_INSTANCE_PARTICLE'; const _vert_attr_name = { POSITION_STARTTIME: 'a_position_starttime', @@ -74,6 +75,9 @@ const _vert_attr_name = { COLOR: 'a_color', DIR_LIFE: 'a_dir_life', RANDOM_SEED: 'a_rndSeed', + VERT_SIZE_FID: 'a_size_fid', + VERT_ROTATION: 'a_rotation', + VERT_UV: 'a_uv', }; const _gpu_vert_attr = [ @@ -98,6 +102,29 @@ const _gpu_vert_attr_mesh = [ new Attribute(AttributeName.ATTR_COLOR1, Format.RGBA8, true), // mesh color ]; +const _gpu_vert_attr_ins = [ + new Attribute(_vert_attr_name.POSITION_STARTTIME, Format.RGBA32F, false, 0, true), + new Attribute(_vert_attr_name.VERT_SIZE_FID, Format.RGBA32F, false, 0, true), + new Attribute(_vert_attr_name.VERT_ROTATION, Format.RGB32F, false, 0, true), + new Attribute(_vert_attr_name.COLOR, Format.RGBA32F, false, 0, true), + new Attribute(_vert_attr_name.DIR_LIFE, Format.RGBA32F, false, 0, true), + new Attribute(_vert_attr_name.RANDOM_SEED, Format.R32F, false, 0, true), + new Attribute(_vert_attr_name.VERT_UV, Format.RGB32F, false, 1), +]; + +const _gpu_vert_attr_mesh_ins = [ + new Attribute(_vert_attr_name.POSITION_STARTTIME, Format.RGBA32F, false, 0, true), + new Attribute(_vert_attr_name.VERT_SIZE_FID, Format.RGBA32F, false, 0, true), + new Attribute(_vert_attr_name.VERT_ROTATION, Format.RGB32F, false, 0, true), + new Attribute(_vert_attr_name.COLOR, Format.RGBA32F, false, 0, true), + new Attribute(_vert_attr_name.DIR_LIFE, Format.RGBA32F, false, 0, true), + new Attribute(_vert_attr_name.RANDOM_SEED, Format.R32F, false, 0, true), + new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGB32F, false, 1), // mesh uv + new Attribute(AttributeName.ATTR_TEX_COORD3, Format.RGB32F, false, 1), // mesh position + new Attribute(AttributeName.ATTR_NORMAL, Format.RGB32F, false, 1), // mesh normal + new Attribute(AttributeName.ATTR_COLOR1, Format.RGBA8, true, 1), // mesh color +]; + const _matInsInfo: IMaterialInstanceInfo = { parent: null!, owner: null!, @@ -207,7 +234,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas this._particleNum++; } - public getDefaultMaterial(): Material | null { + public getDefaultMaterial (): Material | null { return this._defaultMat; } @@ -235,7 +262,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas for (let i = 0; i < cameraLst?.length; ++i) { const camera:Camera = cameraLst[i]; // eslint-disable-next-line max-len - const checkCamera: boolean = !EDITOR ? (camera.visibility & this._particleSystem.node.layer) === this._particleSystem.node.layer : camera.name === 'Editor Camera'; + const checkCamera: boolean = (!EDITOR || legacyCC.GAME_VIEW) ? (camera.visibility & this._particleSystem.node.layer) === this._particleSystem.node.layer : camera.name === 'Editor Camera'; if (checkCamera) { Quat.fromViewUp(_node_rot, camera.forward); break; @@ -269,7 +296,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } public updateParticles (dt: number) { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { const mat: Material | null = this._particleSystem.getMaterialInstance(0) || this._defaultMat; this._particleSystem.node.getWorldMatrix(_tempWorldTrans); @@ -442,7 +469,8 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas pass.setUniform(infoHandle, _tempVec4); } - this._defines[USE_VK_SHADER] = legacyCC.game._gfxDevice.gfxAPI === API.VULKAN; + this._defines[USE_VK_SHADER] = deviceManager.gfxDevice.gfxAPI === API.VULKAN; + this._defines[INSTANCE_PARTICLE] = this._useInstance; } public getParticleCount (): number { @@ -463,15 +491,32 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } private _setVertexAttrib () { + if (!this._useInstance) { + switch (this._renderInfo!.renderMode) { + case RenderMode.StrecthedBillboard: + this._vertAttrs = _gpu_vert_attr.slice(); + break; + case RenderMode.Mesh: + this._vertAttrs = _gpu_vert_attr_mesh.slice(); + break; + default: + this._vertAttrs = _gpu_vert_attr.slice(); + } + } else { + this._setVertexAttribIns(); + } + } + + private _setVertexAttribIns () { switch (this._renderInfo!.renderMode) { case RenderMode.StrecthedBillboard: - this._vertAttrs = _gpu_vert_attr.slice(); + this._vertAttrs = _gpu_vert_attr_ins.slice(); break; case RenderMode.Mesh: - this._vertAttrs = _gpu_vert_attr_mesh.slice(); + this._vertAttrs = _gpu_vert_attr_mesh_ins.slice(); break; default: - this._vertAttrs = _gpu_vert_attr.slice(); + this._vertAttrs = _gpu_vert_attr_ins.slice(); } } @@ -484,7 +529,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas if (shareMaterial !== null) { const effectName = shareMaterial._effectAsset._name; this._renderInfo!.mainTexture = shareMaterial.getProperty('mainTexture', 0); - if (effectName.indexOf('particle-gpu') === -1) { + if (effectName.indexOf('builtin-particle-gpu') === -1) { this._renderInfo!.mainTexture = shareMaterial.getProperty('mainTexture', 0); // reset material this._particleSystem.setMaterial(null, 0); @@ -546,4 +591,20 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas this._model.updateMaterial(mat!); } } + + public setUseInstance (value: boolean) { + if (this._useInstance === value) { + return; + } + this._useInstance = value; + if (this._model) { + this._model.useInstance = value; + this._model.doDestroy(); + } + this.updateRenderMode(); + } + + public getNoisePreview (out: number[], width: number, height: number) { + + } } diff --git a/cocos/particle/renderer/trail.ts b/cocos/particle/renderer/trail.ts index 03e80fc1a5..8e601e27aa 100644 --- a/cocos/particle/renderer/trail.ts +++ b/cocos/particle/renderer/trail.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module particle - */ - import { ccclass, tooltip, displayOrder, type, serializable, range } from 'cc.decorator'; import { Material } from '../../core/assets/material'; import { RenderingSubMesh } from '../../core/assets/rendering-sub-mesh'; @@ -129,6 +124,7 @@ class TrailSegment { return this.trailElements[newEleLoc]; } + // eslint-disable-next-line max-len public iterateElement (target: TrailModule, f: (target: TrailModule, e: ITrailElement, p: Particle, dt: number) => boolean, p: Particle, dt: number) { const end = this.start >= this.end ? this.end + this.trailElements.length : this.end; for (let i = this.start; i < end; i++) { @@ -200,7 +196,7 @@ export default class TrailModule { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @serializable public _enable = false; @@ -225,7 +221,7 @@ export default class TrailModule { public lifeTime = new CurveRange(); /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @serializable public _minParticleDistance = 0.1; @@ -306,6 +302,15 @@ export default class TrailModule { @tooltip('i18n:trailSegment.colorOvertime') public colorOvertime = new GradientRange(); + /** + * @en Get trail model + * @zh 获取拖尾模型 + * @return Model of this trail and type is scene.Model + */ + public getModel () { + return this._trailModel; + } + /** * 轨迹设定时的坐标系。 */ @@ -380,7 +385,7 @@ export default class TrailModule { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _attachToScene () { if (this._trailModel) { @@ -392,7 +397,7 @@ export default class TrailModule { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _detachFromScene () { if (this._trailModel && this._trailModel.scene) { diff --git a/cocos/physics-2d/box2d/physics-world.ts b/cocos/physics-2d/box2d/physics-world.ts index e95ee127ef..5dfc3771b7 100644 --- a/cocos/physics-2d/box2d/physics-world.ts +++ b/cocos/physics-2d/box2d/physics-world.ts @@ -16,6 +16,7 @@ import { PhysicsContact, b2ContactExtends } from './physics-contact'; import { Contact2DType, Collider2D, RaycastResult2D } from '../framework'; import { b2Shape2D } from './shapes/shape-2d'; import { PhysicsDebugDraw } from './platform/physics-debug-draw'; +import { legacyCC } from '../../core/global-exports'; const tempVec3 = new Vec3(); const tempVec2_1 = new Vec2(); @@ -64,7 +65,7 @@ export class b2PhysicsWorld implements IPhysicsWorld { return this._debugDrawFlags; } set debugDrawFlags (v) { - if (EDITOR) return; + if (EDITOR && !legacyCC.GAME_VIEW) return; if (!v) { if (this._debugGraphics) { @@ -76,7 +77,7 @@ export class b2PhysicsWorld implements IPhysicsWorld { } _checkDebugDrawValid () { - if (EDITOR) return; + if (EDITOR && !legacyCC.GAME_VIEW) return; if (!this._debugGraphics || !this._debugGraphics.isValid) { let canvas = find('Canvas'); if (!canvas) { diff --git a/cocos/physics-2d/builtin/builtin-world.ts b/cocos/physics-2d/builtin/builtin-world.ts index 32767513ae..68b838788b 100644 --- a/cocos/physics-2d/builtin/builtin-world.ts +++ b/cocos/physics-2d/builtin/builtin-world.ts @@ -10,6 +10,7 @@ import { BuiltinPolygonShape } from './shapes/polygon-shape-2d'; import { EPhysics2DDrawFlags, Contact2DType, ERaycast2DType, RaycastResult2D } from '../framework/physics-types'; import { PhysicsSystem2D, Collider2D } from '../framework'; import { BuiltinContact } from './builtin-contact'; +import { legacyCC } from '../../core/global-exports'; const contactResults: BuiltinContact[] = []; const testIntersectResults: Collider2D[] = []; @@ -167,7 +168,7 @@ export class BuiltinPhysicsWorld implements IPhysicsWorld { } private _checkDebugDrawValid () { - if (EDITOR) return; + if (EDITOR && !legacyCC.GAME_VIEW) return; if (!this._debugGraphics || !this._debugGraphics.isValid) { let canvas = find('Canvas'); if (!canvas) { diff --git a/cocos/physics-2d/category.json b/cocos/physics-2d/category.json new file mode 100644 index 0000000000..dd81fd9cf9 --- /dev/null +++ b/cocos/physics-2d/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "2D 物理系统", + "en": "Physics System 2D" + }, + "description": { + "zh": "物理系统的 2D 版本,用于在 2D 世界下模拟物理", + "en": "2D version of the physics system, used to simulate physics in a 2D world" + } +} \ No newline at end of file diff --git a/cocos/physics-2d/framework/components/colliders/box-collider-2d.ts b/cocos/physics-2d/framework/components/colliders/box-collider-2d.ts index 225ce71611..29eb2acb6d 100644 --- a/cocos/physics-2d/framework/components/colliders/box-collider-2d.ts +++ b/cocos/physics-2d/framework/components/colliders/box-collider-2d.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module physics2d - */ + import { ccclass, property, menu } from '../../../../core/data/class-decorator'; import { Vec2, Size } from '../../../../core'; diff --git a/cocos/physics-2d/framework/components/colliders/circle-collider-2d.ts b/cocos/physics-2d/framework/components/colliders/circle-collider-2d.ts index 9413ed66c5..4116e003da 100644 --- a/cocos/physics-2d/framework/components/colliders/circle-collider-2d.ts +++ b/cocos/physics-2d/framework/components/colliders/circle-collider-2d.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module physics2d - */ + import { ccclass, property, menu } from '../../../../core/data/class-decorator'; import { Component, Vec2, Size } from '../../../../core'; diff --git a/cocos/physics-2d/framework/components/colliders/collider-2d.ts b/cocos/physics-2d/framework/components/colliders/collider-2d.ts index 580d772451..83b1c9bd63 100644 --- a/cocos/physics-2d/framework/components/colliders/collider-2d.ts +++ b/cocos/physics-2d/framework/components/colliders/collider-2d.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module physics2d - */ + import { EDITOR } from 'internal:constants'; @@ -15,6 +12,7 @@ import { RigidBody2D } from '../rigid-body-2d'; import { createShape } from '../../instance'; import { ECollider2DType } from '../../physics-types'; import { IBaseShape } from '../../../spec/i-physics-shape'; +import { legacyCC } from '../../../../core/global-exports'; @ccclass('cc.Collider2D') export class Collider2D extends Eventify(Component) { @@ -128,7 +126,7 @@ export class Collider2D extends Eventify(Component) { /// COMPONENT LIFECYCLE /// protected onLoad () { - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { this._shape = createShape(this.TYPE); this._shape.initialize(this); diff --git a/cocos/physics-2d/framework/components/colliders/polygon-collider-2d.ts b/cocos/physics-2d/framework/components/colliders/polygon-collider-2d.ts index bbbaa454f4..af8e27b76f 100644 --- a/cocos/physics-2d/framework/components/colliders/polygon-collider-2d.ts +++ b/cocos/physics-2d/framework/components/colliders/polygon-collider-2d.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module physics2d - */ + import { ccclass, property, menu } from '../../../../core/data/class-decorator'; import { Component, Vec2, Size } from '../../../../core'; diff --git a/cocos/physics-2d/framework/components/joints/distance-joint-2d.ts b/cocos/physics-2d/framework/components/joints/distance-joint-2d.ts index cfa5275d2c..88c7074bb4 100644 --- a/cocos/physics-2d/framework/components/joints/distance-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/distance-joint-2d.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module physics2d - */ + import { Joint2D } from './joint-2d'; import { ccclass, property, menu, type } from '../../../../core/data/class-decorator'; import { IDistanceJoint } from '../../../spec/i-physics-joint'; diff --git a/cocos/physics-2d/framework/components/joints/fixed-joint-2d.ts b/cocos/physics-2d/framework/components/joints/fixed-joint-2d.ts index 883d25da5d..63e3b1decc 100644 --- a/cocos/physics-2d/framework/components/joints/fixed-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/fixed-joint-2d.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module physics2d - */ + import { Joint2D } from './joint-2d'; import { ccclass, property, menu, type } from '../../../../core/data/class-decorator'; import { IFixedJoint } from '../../../spec/i-physics-joint'; diff --git a/cocos/physics-2d/framework/components/joints/hinge-joint-2d.ts b/cocos/physics-2d/framework/components/joints/hinge-joint-2d.ts index efd14ec174..16bf9874f3 100644 --- a/cocos/physics-2d/framework/components/joints/hinge-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/hinge-joint-2d.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module physics2d - */ + import { Joint2D } from './joint-2d'; import { ccclass, property, menu, type } from '../../../../core/data/class-decorator'; diff --git a/cocos/physics-2d/framework/components/joints/joint-2d.ts b/cocos/physics-2d/framework/components/joints/joint-2d.ts index 72c531c377..b14a12f79a 100644 --- a/cocos/physics-2d/framework/components/joints/joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/joint-2d.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module physics2d - */ + import { EDITOR } from 'internal:constants'; import { Component, Vec2 } from '../../../../core'; @@ -10,6 +7,7 @@ import { RigidBody2D } from '../rigid-body-2d'; import { IJoint2D } from '../../../spec/i-physics-joint'; import { EJoint2DType } from '../../physics-types'; import { createJoint } from '../../instance'; +import { legacyCC } from '../../../../core/global-exports'; @ccclass('cc.Joint2D') export class Joint2D extends Component { @@ -39,7 +37,7 @@ export class Joint2D extends Component { TYPE = EJoint2DType.None; protected onLoad () { - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { this._joint = createJoint(this.TYPE); this._joint.initialize(this); diff --git a/cocos/physics-2d/framework/components/joints/mouse-joint-2d.ts b/cocos/physics-2d/framework/components/joints/mouse-joint-2d.ts index 4eb0083860..267ea8d054 100644 --- a/cocos/physics-2d/framework/components/joints/mouse-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/mouse-joint-2d.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module physics2d - */ + import { Joint2D } from './joint-2d'; import { ccclass, property, menu, type } from '../../../../core/data/class-decorator'; diff --git a/cocos/physics-2d/framework/components/joints/relative-joint-2d.ts b/cocos/physics-2d/framework/components/joints/relative-joint-2d.ts index cece817c06..76c711abb5 100644 --- a/cocos/physics-2d/framework/components/joints/relative-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/relative-joint-2d.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module physics2d - */ + import { Joint2D } from './joint-2d'; import { ccclass, property, menu, type } from '../../../../core/data/class-decorator'; diff --git a/cocos/physics-2d/framework/components/joints/slider-joint-2d.ts b/cocos/physics-2d/framework/components/joints/slider-joint-2d.ts index dc0040685d..daec80b3d2 100644 --- a/cocos/physics-2d/framework/components/joints/slider-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/slider-joint-2d.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module physics2d - */ + import { Joint2D } from './joint-2d'; import { ccclass, property, menu, type } from '../../../../core/data/class-decorator'; diff --git a/cocos/physics-2d/framework/components/joints/spring-joint-2d.ts b/cocos/physics-2d/framework/components/joints/spring-joint-2d.ts index ea6bb011dd..06e4b06790 100644 --- a/cocos/physics-2d/framework/components/joints/spring-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/spring-joint-2d.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module physics2d - */ + import { Joint2D } from './joint-2d'; import { ccclass, property, menu, type } from '../../../../core/data/class-decorator'; diff --git a/cocos/physics-2d/framework/components/joints/wheel-joint-2d.ts b/cocos/physics-2d/framework/components/joints/wheel-joint-2d.ts index 2c95afcb30..c4a97248c3 100644 --- a/cocos/physics-2d/framework/components/joints/wheel-joint-2d.ts +++ b/cocos/physics-2d/framework/components/joints/wheel-joint-2d.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module physics2d - */ + import { Joint2D } from './joint-2d'; import { ccclass, property, menu, type } from '../../../../core/data/class-decorator'; diff --git a/cocos/physics-2d/framework/components/rigid-body-2d.ts b/cocos/physics-2d/framework/components/rigid-body-2d.ts index 1d0135103a..cd33184db5 100644 --- a/cocos/physics-2d/framework/components/rigid-body-2d.ts +++ b/cocos/physics-2d/framework/components/rigid-body-2d.ts @@ -1,8 +1,3 @@ -/** - * @packageDocumentation - * @module physics2d - */ - import { EDITOR } from 'internal:constants'; import { IRigidBody2D } from '../../spec/i-rigid-body'; import { _decorator, Vec2, Component, error, Layers, IVec2Like } from '../../../core'; @@ -11,6 +6,7 @@ import { ccclass } from '../../../core/data/class-decorator'; import { createRigidBody } from '../instance'; import { Joint2D } from './joints/joint-2d'; import { PhysicsGroup } from '../../../physics/framework/physics-enum'; +import { legacyCC } from '../../../core/global-exports'; const { property, type, menu } = _decorator; @@ -499,7 +495,7 @@ export class RigidBody2D extends Component { /// COMPONENT LIFECYCLE /// protected onLoad () { - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { this._body = createRigidBody(); this._body.initialize(this); } diff --git a/cocos/physics-2d/framework/instance.ts b/cocos/physics-2d/framework/instance.ts index f0124f84f5..37e4d5e12b 100644 --- a/cocos/physics-2d/framework/instance.ts +++ b/cocos/physics-2d/framework/instance.ts @@ -11,7 +11,7 @@ import { IJoint2D, IDistanceJoint, ISpringJoint, IFixedJoint, IMouseJoint, IRela const FUNC = (...v: any) => 0 as any; export function checkPhysicsModule (obj: any) { - if (DEBUG && !TEST && !EDITOR && obj == null) { + if (DEBUG && !TEST && (!EDITOR || legacyCC.GAME_VIEW) && obj == null) { errorID(9600); return true; } diff --git a/cocos/physics-2d/framework/physics-system.ts b/cocos/physics-2d/framework/physics-system.ts index 6cfc9e5c62..1d9d5bd292 100644 --- a/cocos/physics-2d/framework/physics-system.ts +++ b/cocos/physics-2d/framework/physics-system.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module physics2d - */ + import { EDITOR, DEBUG } from 'internal:constants'; import { System, Vec2, director, Director, game, error, IVec2Like, Rect, Eventify, Enum } from '../../core'; @@ -13,8 +10,11 @@ import { IPhysicsConfig, ICollisionMatrix } from '../../physics/framework/physic import { CollisionMatrix } from '../../physics/framework/collision-matrix'; import { ERaycast2DType, RaycastResult2D, PHYSICS_2D_PTM_RATIO, PhysicsGroup } from './physics-types'; import { Collider2D } from './components/colliders/collider-2d'; +import { legacyCC } from '../../core/global-exports'; +import { Settings, settings } from '../../core/settings'; let instance: PhysicsSystem2D | null = null; +legacyCC.internal.PhysicsGroup2D = PhysicsGroup; export class PhysicsSystem2D extends Eventify(System) { /** @@ -41,7 +41,7 @@ export class PhysicsSystem2D extends Eventify(System) { } set allowSleep (v: boolean) { this._allowSleep = v; - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { this.physicsWorld.setAllowSleep(v); } } @@ -57,7 +57,7 @@ export class PhysicsSystem2D extends Eventify(System) { } set gravity (gravity: Vec2) { this._gravity.set(gravity); - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { this.physicsWorld.setGravity(new Vec2(gravity.x / PHYSICS_2D_PTM_RATIO, gravity.y / PHYSICS_2D_PTM_RATIO)); } } @@ -203,30 +203,30 @@ export class PhysicsSystem2D extends Eventify(System) { private constructor () { super(); - const config = game.config ? game.config.physics as IPhysicsConfig : null; - if (config) { - Vec2.copy(this._gravity, config.gravity as IVec2Like); + const gravity = settings.querySettings(Settings.Category.PHYSICS, 'gravity'); + if (gravity) { + Vec2.copy(this._gravity, gravity as IVec2Like); this._gravity.multiplyScalar(PHYSICS_2D_PTM_RATIO); - - this._allowSleep = config.allowSleep as boolean; - this._fixedTimeStep = config.fixedTimeStep as number; - this._maxSubSteps = config.maxSubSteps as number; - this._autoSimulation = config.autoSimulation as boolean; - - if (config.collisionMatrix) { - for (const i in config.collisionMatrix) { - const bit = parseInt(i); - const value = 1 << parseInt(i); - this.collisionMatrix[`${value}`] = config.collisionMatrix[bit]; - } + } + this._allowSleep = settings.querySettings(Settings.Category.PHYSICS, 'allowSleep') ?? this._allowSleep; + this._fixedTimeStep = settings.querySettings(Settings.Category.PHYSICS, 'fixedTimeStep') ?? this._fixedTimeStep; + this._maxSubSteps = settings.querySettings(Settings.Category.PHYSICS, 'maxSubSteps') ?? this._maxSubSteps; + this._autoSimulation = settings.querySettings(Settings.Category.PHYSICS, 'autoSimulation') ?? this._autoSimulation; + const collisionMatrix = settings.querySettings(Settings.Category.PHYSICS, 'collisionMatrix'); + if (collisionMatrix) { + for (const i in collisionMatrix) { + const bit = parseInt(i); + const value = 1 << parseInt(i); + this.collisionMatrix[`${value}`] = collisionMatrix[bit]; } + } - if (config.collisionGroups) { - const cg = config.collisionGroups; - if (cg instanceof Array) { - cg.forEach((v) => { PhysicsGroup[v.name] = 1 << v.index; }); - Enum.update(PhysicsGroup); - } + const collisionGroups = settings.querySettings>(Settings.Category.PHYSICS, 'collisionGroups'); + if (collisionGroups) { + const cg = collisionGroups; + if (cg instanceof Array) { + cg.forEach((v) => { PhysicsGroup[v.name] = 1 << v.index; }); + Enum.update(PhysicsGroup); } } @@ -353,7 +353,7 @@ director.once(Director.EVENT_INIT, () => { }); function initPhysicsSystem () { - if (!PhysicsSystem2D.PHYSICS_NONE && !EDITOR) { + if (!PhysicsSystem2D.PHYSICS_NONE && (!EDITOR || legacyCC.GAME_VIEW)) { director.registerSystem(PhysicsSystem2D.ID, PhysicsSystem2D.instance, System.Priority.LOW); } } diff --git a/cocos/physics-2d/framework/physics-types.ts b/cocos/physics-2d/framework/physics-types.ts index 39ca0f34f5..9a2a1718fd 100644 --- a/cocos/physics-2d/framework/physics-types.ts +++ b/cocos/physics-2d/framework/physics-types.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module physics2d - */ + import { Enum, Vec2 } from '../../core'; import { Collider2D } from './components/colliders/collider-2d'; diff --git a/cocos/physics-2d/framework/utils/polygon-separator.ts b/cocos/physics-2d/framework/utils/polygon-separator.ts index b5777fee67..715c196c22 100644 --- a/cocos/physics-2d/framework/utils/polygon-separator.ts +++ b/cocos/physics-2d/framework/utils/polygon-separator.ts @@ -202,6 +202,12 @@ function Right (a: number | IVec2Like, b: IVec2Like | IVec2Like[], c?: IVec2Like a = At(i - 1, vertices); b = At(i, vertices); c = At(i + 1, vertices); + if (typeof a === 'undefined') { + a = b; + } + if (typeof c === 'undefined') { + c = b; + } } return Area(a as IVec2Like, b as IVec2Like, c) < 0; diff --git a/cocos/physics-2d/spec/i-physics-contact.ts b/cocos/physics-2d/spec/i-physics-contact.ts index 9d6eb6c70e..dd22d36b2f 100644 --- a/cocos/physics-2d/spec/i-physics-contact.ts +++ b/cocos/physics-2d/spec/i-physics-contact.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module physics2d - */ + import { Vec2 } from '../../core'; import { Collider2D } from '../framework/components/colliders/collider-2d'; diff --git a/cocos/physics-2d/spec/i-physics-joint.ts b/cocos/physics-2d/spec/i-physics-joint.ts index 5af415f0a9..d01d507047 100644 --- a/cocos/physics-2d/spec/i-physics-joint.ts +++ b/cocos/physics-2d/spec/i-physics-joint.ts @@ -1,7 +1,4 @@ -/** - * @packageDocumentation - * @module physics2d - */ + import { IVec2Like } from '../../core'; import { ILifecycle } from '../../physics/spec/i-lifecycle'; diff --git a/cocos/physics/bullet/bullet-cache.ts b/cocos/physics/bullet/bullet-cache.ts index a036d6442c..4401224134 100644 --- a/cocos/physics/bullet/bullet-cache.ts +++ b/cocos/physics/bullet/bullet-cache.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { Collider, TriggerEventType, CollisionEventType, IContactEquation } from '../../../exports/physics-framework'; import { Vec3, Quat } from '../../core'; import { bt } from './instantiated'; diff --git a/cocos/physics/bullet/bullet-contact-data.ts b/cocos/physics/bullet/bullet-contact-data.ts index 0ecfe5a7f6..b371def21f 100644 --- a/cocos/physics/bullet/bullet-contact-data.ts +++ b/cocos/physics/bullet/bullet-contact-data.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { IContactEquation, ICollisionEvent } from '../framework'; import { IVec3Like, Vec3, Quat } from '../../core'; import { BulletShape } from './shapes/bullet-shape'; diff --git a/cocos/physics/bullet/bullet-enum.ts b/cocos/physics/bullet/bullet-enum.ts index 492be73950..83eaa26b57 100644 --- a/cocos/physics/bullet/bullet-enum.ts +++ b/cocos/physics/bullet/bullet-enum.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - export enum EBtSharedBodyDirty { BODY_RE_ADD = 1, GHOST_RE_ADD = 2, diff --git a/cocos/physics/bullet/bullet-env.ts b/cocos/physics/bullet/bullet-env.ts index c92a64040f..0d6c22b729 100644 --- a/cocos/physics/bullet/bullet-env.ts +++ b/cocos/physics/bullet/bullet-env.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - // Wasm Memory Page Size is 65536 export const pageSize = 65536; // 64KiB diff --git a/cocos/physics/bullet/bullet-interface.ts b/cocos/physics/bullet/bullet-interface.ts index 4689e8d3d1..d17692ab6a 100644 --- a/cocos/physics/bullet/bullet-interface.ts +++ b/cocos/physics/bullet/bullet-interface.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { BulletShape } from './shapes/bullet-shape'; export interface IBulletBodyStruct { diff --git a/cocos/physics/bullet/bullet-rigid-body.ts b/cocos/physics/bullet/bullet-rigid-body.ts index 63915ee472..051fe085a4 100644 --- a/cocos/physics/bullet/bullet-rigid-body.ts +++ b/cocos/physics/bullet/bullet-rigid-body.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { Vec3 } from '../../core'; import { BulletWorld } from './bullet-world'; import { cocos2BulletVec3, bullet2CocosVec3 } from './bullet-utils'; diff --git a/cocos/physics/bullet/bullet-shared-body.ts b/cocos/physics/bullet/bullet-shared-body.ts index 9c0f0efde5..76b79bf111 100644 --- a/cocos/physics/bullet/bullet-shared-body.ts +++ b/cocos/physics/bullet/bullet-shared-body.ts @@ -38,8 +38,6 @@ import { fastRemoveAt } from '../../core/utils/array'; import { bt } from './instantiated'; import { BulletConstraint } from './constraints/bullet-constraint'; - - const v3_0 = CC_V3_0; const quat_0 = CC_QUAT_0; let IDCounter = 0; diff --git a/cocos/physics/bullet/bullet-utils.ts b/cocos/physics/bullet/bullet-utils.ts index 4948ef61e8..1a668b94b8 100644 --- a/cocos/physics/bullet/bullet-utils.ts +++ b/cocos/physics/bullet/bullet-utils.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { IVec3Like, IQuatLike } from '../../core/math/type-define'; import { Mesh } from '../../3d'; import { PrimitiveMode } from '../../core/gfx'; diff --git a/cocos/physics/bullet/bullet-world.ts b/cocos/physics/bullet/bullet-world.ts index 8115c5966c..fc7faff2d2 100644 --- a/cocos/physics/bullet/bullet-world.ts +++ b/cocos/physics/bullet/bullet-world.ts @@ -24,8 +24,6 @@ THE SOFTWARE. */ - - import { BulletSharedBody } from './bullet-shared-body'; import { BulletRigidBody } from './bullet-rigid-body'; import { BulletShape } from './shapes/bullet-shape'; diff --git a/cocos/physics/bullet/constraints/bullet-constraint.ts b/cocos/physics/bullet/constraints/bullet-constraint.ts index 999823a769..853b8a4745 100644 --- a/cocos/physics/bullet/constraints/bullet-constraint.ts +++ b/cocos/physics/bullet/constraints/bullet-constraint.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - /* eslint-disable new-cap */ import { IBaseConstraint } from '../../spec/i-physics-constraint'; import { Constraint, RigidBody } from '../../framework'; diff --git a/cocos/physics/bullet/constraints/bullet-hinge-constraint.ts b/cocos/physics/bullet/constraints/bullet-hinge-constraint.ts index 251842450e..130ed292c4 100644 --- a/cocos/physics/bullet/constraints/bullet-hinge-constraint.ts +++ b/cocos/physics/bullet/constraints/bullet-hinge-constraint.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - /* eslint-disable new-cap */ import { BulletConstraint } from './bullet-constraint'; import { IHingeConstraint } from '../../spec/i-physics-constraint'; diff --git a/cocos/physics/bullet/constraints/bullet-p2p-constraint.ts b/cocos/physics/bullet/constraints/bullet-p2p-constraint.ts index eb1532535e..0c6b9e5a57 100644 --- a/cocos/physics/bullet/constraints/bullet-p2p-constraint.ts +++ b/cocos/physics/bullet/constraints/bullet-p2p-constraint.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - /* eslint-disable new-cap */ import { BulletConstraint } from './bullet-constraint'; import { IPointToPointConstraint } from '../../spec/i-physics-constraint'; diff --git a/cocos/physics/bullet/instantiate.ts b/cocos/physics/bullet/instantiate.ts index 0812a076f9..7ee8e3c1fe 100644 --- a/cocos/physics/bullet/instantiate.ts +++ b/cocos/physics/bullet/instantiate.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { Game, game } from '../../core'; import { selector } from '../framework/physics-selector'; import { BulletRigidBody } from './bullet-rigid-body'; @@ -41,7 +39,7 @@ import { BulletPlaneShape } from './shapes/bullet-plane-shape'; import { BulletP2PConstraint } from './constraints/bullet-p2p-constraint'; import { BulletHingeConstraint } from './constraints/bullet-hinge-constraint'; -game.once(Game.EVENT_ENGINE_INITED, () => { +game.once(Game.EVENT_PRE_SUBSYSTEM_INIT, () => { selector.register('bullet', { PhysicsWorld: BulletWorld, RigidBody: BulletRigidBody, diff --git a/cocos/physics/bullet/instantiated.ts b/cocos/physics/bullet/instantiated.ts index 1a60ad5a5f..133297500f 100644 --- a/cocos/physics/bullet/instantiated.ts +++ b/cocos/physics/bullet/instantiated.ts @@ -23,12 +23,12 @@ THE SOFTWARE. */ - - // eslint-disable-next-line import/no-extraneous-dependencies import bulletModule, { bulletType } from '@cocos/bullet'; import { WECHAT } from 'internal:constants'; import { physics } from '../../../exports/physics-framework'; +import { game } from '../../core/game'; +import { sys } from '../../core/platform'; import { pageSize, pageCount, importFunc } from './bullet-env'; let bulletLibs: any = bulletModule; @@ -48,9 +48,15 @@ export const bt: instanceExt = {} as any; globalThis.Bullet = bt; bt.BODY_CACHE_NAME = 'body'; -export function waitForAmmoInstantiation (dirRoot: string) { +export function waitForAmmoInstantiation () { // refer https://stackoverflow.com/questions/47879864/how-can-i-check-if-a-browser-supports-webassembly const supported = (() => { + // iOS 15.4 has some wasm memory issue, can not use wasm for bullet + const isiOS15_4 = (sys.os === sys.OS.IOS || sys.os === sys.OS.OSX) && sys.isBrowser + && /(OS 15_4)|(Version\/15.4)/.test(window.navigator.userAgent); + if (isiOS15_4) { + return false; + } try { if (typeof WebAssembly === 'object' && typeof WebAssembly.instantiate === 'function') { @@ -91,7 +97,7 @@ export function waitForAmmoInstantiation (dirRoot: string) { if (WECHAT) { // eslint-disable-next-line @typescript-eslint/restrict-template-expressions - const wasmFilePath = `${dirRoot}${module}` as any; + const wasmFilePath = `cocos-js/${module}` as any; instantiateWasm(wasmFilePath); } else { fetch(module).then((response) => { @@ -113,3 +119,5 @@ export function waitForAmmoInstantiation (dirRoot: string) { } }); } + +game.onPostInfrastructureInitDelegate.add(waitForAmmoInstantiation); diff --git a/cocos/physics/bullet/shapes/bullet-box-shape.ts b/cocos/physics/bullet/shapes/bullet-box-shape.ts index 0f69b07ea3..66f2af7174 100644 --- a/cocos/physics/bullet/shapes/bullet-box-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-box-shape.ts @@ -24,8 +24,6 @@ THE SOFTWARE. */ - - import { BulletShape } from './bullet-shape'; import { Vec3 } from '../../../core'; import { BoxCollider, PhysicsSystem } from '../../../../exports/physics-framework'; diff --git a/cocos/physics/bullet/shapes/bullet-capsule-shape.ts b/cocos/physics/bullet/shapes/bullet-capsule-shape.ts index c5da24b4ad..db7e6db079 100644 --- a/cocos/physics/bullet/shapes/bullet-capsule-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-capsule-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { absMax } from '../../../core'; import { BulletShape } from './bullet-shape'; import { CapsuleCollider } from '../../../../exports/physics-framework'; diff --git a/cocos/physics/bullet/shapes/bullet-cone-shape.ts b/cocos/physics/bullet/shapes/bullet-cone-shape.ts index c974d8539d..53ae7c4ca0 100644 --- a/cocos/physics/bullet/shapes/bullet-cone-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-cone-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { BulletShape } from './bullet-shape'; import { ConeCollider } from '../../../../exports/physics-framework'; import { ICylinderShape } from '../../spec/i-physics-shape'; diff --git a/cocos/physics/bullet/shapes/bullet-cylinder-shape.ts b/cocos/physics/bullet/shapes/bullet-cylinder-shape.ts index b649aa365e..ea39974116 100644 --- a/cocos/physics/bullet/shapes/bullet-cylinder-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-cylinder-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { BulletShape } from './bullet-shape'; import { CylinderCollider } from '../../../../exports/physics-framework'; import { ICylinderShape } from '../../spec/i-physics-shape'; diff --git a/cocos/physics/bullet/shapes/bullet-plane-shape.ts b/cocos/physics/bullet/shapes/bullet-plane-shape.ts index d519dad3ab..e940e80a96 100644 --- a/cocos/physics/bullet/shapes/bullet-plane-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-plane-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { BulletShape } from './bullet-shape'; import { PlaneCollider } from '../../../../exports/physics-framework'; import { cocos2BulletVec3 } from '../bullet-utils'; diff --git a/cocos/physics/bullet/shapes/bullet-shape.ts b/cocos/physics/bullet/shapes/bullet-shape.ts index 9d96d69aeb..c49f312cd0 100644 --- a/cocos/physics/bullet/shapes/bullet-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { Vec3 } from '../../../core/math'; import { Collider, PhysicsMaterial, PhysicsSystem } from '../../../../exports/physics-framework'; import { BulletWorld } from '../bullet-world'; diff --git a/cocos/physics/bullet/shapes/bullet-simplex-shape.ts b/cocos/physics/bullet/shapes/bullet-simplex-shape.ts index f996c6cba2..b873355f17 100644 --- a/cocos/physics/bullet/shapes/bullet-simplex-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-simplex-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { BulletShape } from './bullet-shape'; import { SimplexCollider } from '../../../../exports/physics-framework'; import { cocos2BulletVec3 } from '../bullet-utils'; diff --git a/cocos/physics/bullet/shapes/bullet-terrain-shape.ts b/cocos/physics/bullet/shapes/bullet-terrain-shape.ts index 83814e2b50..2621a19c79 100644 --- a/cocos/physics/bullet/shapes/bullet-terrain-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-terrain-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { BulletShape } from './bullet-shape'; import { Vec3, warn } from '../../../core'; import { TerrainCollider } from '../../../../exports/physics-framework'; diff --git a/cocos/physics/bullet/shapes/bullet-trimesh-shape.ts b/cocos/physics/bullet/shapes/bullet-trimesh-shape.ts index 4cf40dbfaa..f129d2ccbb 100644 --- a/cocos/physics/bullet/shapes/bullet-trimesh-shape.ts +++ b/cocos/physics/bullet/shapes/bullet-trimesh-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { BulletShape } from './bullet-shape'; import { warnID } from '../../../core'; import { Mesh } from '../../../3d/assets'; diff --git a/cocos/physics/cannon/cannon-contact-equation.ts b/cocos/physics/cannon/cannon-contact-equation.ts index 3acea14a05..da77ad78fd 100644 --- a/cocos/physics/cannon/cannon-contact-equation.ts +++ b/cocos/physics/cannon/cannon-contact-equation.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { IContactEquation, ICollisionEvent } from '../framework'; import { IVec3Like, Quat, Vec3 } from '../../core'; import { CannonShape } from './shapes/cannon-shape'; diff --git a/cocos/physics/cannon/cannon-rigid-body.ts b/cocos/physics/cannon/cannon-rigid-body.ts index d6eec05f1c..ecb446bb42 100644 --- a/cocos/physics/cannon/cannon-rigid-body.ts +++ b/cocos/physics/cannon/cannon-rigid-body.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import CANNON from '@cocos/cannon'; import { Vec3 } from '../../core/math'; import { IRigidBody } from '../spec/i-rigid-body'; diff --git a/cocos/physics/cannon/cannon-shared-body.ts b/cocos/physics/cannon/cannon-shared-body.ts index 7784b3644c..b10d45fb69 100644 --- a/cocos/physics/cannon/cannon-shared-body.ts +++ b/cocos/physics/cannon/cannon-shared-body.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import CANNON from '@cocos/cannon'; import { Quat, Vec3 } from '../../core/math'; import { ERigidBodyType, PhysicsGroup } from '../framework/physics-enum'; diff --git a/cocos/physics/cannon/cannon-util.ts b/cocos/physics/cannon/cannon-util.ts index c79757871c..1f80015edc 100644 --- a/cocos/physics/cannon/cannon-util.ts +++ b/cocos/physics/cannon/cannon-util.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import CANNON from '@cocos/cannon'; import { getWrap } from '../utils/util'; import { IBaseShape } from '../spec/i-physics-shape'; diff --git a/cocos/physics/cannon/cannon-world.ts b/cocos/physics/cannon/cannon-world.ts index afd430b042..ddaf03419e 100644 --- a/cocos/physics/cannon/cannon-world.ts +++ b/cocos/physics/cannon/cannon-world.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import CANNON from '@cocos/cannon'; import { Vec3, Quat } from '../../core/math'; import { fillRaycastResult, toCannonRaycastOptions } from './cannon-util'; diff --git a/cocos/physics/cannon/constraints/cannon-constraint.ts b/cocos/physics/cannon/constraints/cannon-constraint.ts index 6052d0f682..7983727c39 100644 --- a/cocos/physics/cannon/constraints/cannon-constraint.ts +++ b/cocos/physics/cannon/constraints/cannon-constraint.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import CANNON from '@cocos/cannon'; import { IBaseConstraint } from '../../spec/i-physics-constraint'; import { Constraint, RigidBody } from '../../framework'; diff --git a/cocos/physics/cannon/constraints/cannon-hinge-constraint.ts b/cocos/physics/cannon/constraints/cannon-hinge-constraint.ts index e0591a26c3..ca8e8ff102 100644 --- a/cocos/physics/cannon/constraints/cannon-hinge-constraint.ts +++ b/cocos/physics/cannon/constraints/cannon-hinge-constraint.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import CANNON from '@cocos/cannon'; import { CannonConstraint } from './cannon-constraint'; import { IHingeConstraint } from '../../spec/i-physics-constraint'; diff --git a/cocos/physics/cannon/constraints/cannon-point-to-point-constraint.ts b/cocos/physics/cannon/constraints/cannon-point-to-point-constraint.ts index 1c0c34d389..8d3f1911f5 100644 --- a/cocos/physics/cannon/constraints/cannon-point-to-point-constraint.ts +++ b/cocos/physics/cannon/constraints/cannon-point-to-point-constraint.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import CANNON from '@cocos/cannon'; import { CannonConstraint } from './cannon-constraint'; import { IPointToPointConstraint } from '../../spec/i-physics-constraint'; diff --git a/cocos/physics/cannon/instantiate.ts b/cocos/physics/cannon/instantiate.ts index 7404a4f237..8f7652a1b3 100644 --- a/cocos/physics/cannon/instantiate.ts +++ b/cocos/physics/cannon/instantiate.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { selector } from '../framework/physics-selector'; import { CannonRigidBody } from './cannon-rigid-body'; @@ -43,7 +41,7 @@ import { CannonPointToPointConstraint } from './constraints/cannon-point-to-poin import { CannonHingeConstraint } from './constraints/cannon-hinge-constraint'; import { Game, game } from '../../core'; -game.once(Game.EVENT_ENGINE_INITED, () => { +game.once(Game.EVENT_PRE_SUBSYSTEM_INIT, () => { selector.register('cannon.js', { PhysicsWorld: CannonWorld, RigidBody: CannonRigidBody, diff --git a/cocos/physics/cannon/shapes/cannon-box-shape.ts b/cocos/physics/cannon/shapes/cannon-box-shape.ts index 4250625894..0f820941ae 100644 --- a/cocos/physics/cannon/shapes/cannon-box-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-box-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import CANNON from '@cocos/cannon'; import { clamp, Vec3 } from '../../../core/math'; import { commitShapeUpdates } from '../cannon-util'; diff --git a/cocos/physics/cannon/shapes/cannon-cone-shape.ts b/cocos/physics/cannon/shapes/cannon-cone-shape.ts index 1895daa3e4..9f0e8161ca 100644 --- a/cocos/physics/cannon/shapes/cannon-cone-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-cone-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import CANNON from '@cocos/cannon'; import { Vec3 } from '../../../core/math'; import { CannonShape } from './cannon-shape'; diff --git a/cocos/physics/cannon/shapes/cannon-cylinder-shape.ts b/cocos/physics/cannon/shapes/cannon-cylinder-shape.ts index 9c00475d46..5f44172b8b 100644 --- a/cocos/physics/cannon/shapes/cannon-cylinder-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-cylinder-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import CANNON from '@cocos/cannon'; import { Vec3 } from '../../../core/math'; import { CannonShape } from './cannon-shape'; diff --git a/cocos/physics/cannon/shapes/cannon-plane-shape.ts b/cocos/physics/cannon/shapes/cannon-plane-shape.ts index 58187d976a..4f50ea5161 100644 --- a/cocos/physics/cannon/shapes/cannon-plane-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-plane-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import CANNON from '@cocos/cannon'; import { Vec3, Quat } from '../../../core/math'; import { commitShapeUpdates } from '../cannon-util'; diff --git a/cocos/physics/cannon/shapes/cannon-shape.ts b/cocos/physics/cannon/shapes/cannon-shape.ts index 57c3c70706..c66b52c413 100644 --- a/cocos/physics/cannon/shapes/cannon-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import CANNON from '@cocos/cannon'; import { Vec3, Quat } from '../../../core/math'; import { getWrap, setWrap } from '../../utils/util'; diff --git a/cocos/physics/cannon/shapes/cannon-simplex-shape.ts b/cocos/physics/cannon/shapes/cannon-simplex-shape.ts index 9ea4e177af..6530bc866d 100644 --- a/cocos/physics/cannon/shapes/cannon-simplex-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-simplex-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - /* eslint-disable func-names */ import CANNON from '@cocos/cannon'; import { Vec3 } from '../../../core/math'; diff --git a/cocos/physics/cannon/shapes/cannon-sphere-shape.ts b/cocos/physics/cannon/shapes/cannon-sphere-shape.ts index b8d056378a..6f7b7febc6 100644 --- a/cocos/physics/cannon/shapes/cannon-sphere-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-sphere-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import CANNON from '@cocos/cannon'; import { absMaxComponent, clamp, Vec3 } from '../../../core/math'; import { commitShapeUpdates } from '../cannon-util'; diff --git a/cocos/physics/cannon/shapes/cannon-terrain-shape.ts b/cocos/physics/cannon/shapes/cannon-terrain-shape.ts index 73c2ff69e4..2a0001bbcc 100644 --- a/cocos/physics/cannon/shapes/cannon-terrain-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-terrain-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import CANNON from '@cocos/cannon'; import { CannonShape } from './cannon-shape'; import { TerrainCollider } from '../../framework'; diff --git a/cocos/physics/cannon/shapes/cannon-trimesh-shape.ts b/cocos/physics/cannon/shapes/cannon-trimesh-shape.ts index d6ac57a845..2d0c8eafc2 100644 --- a/cocos/physics/cannon/shapes/cannon-trimesh-shape.ts +++ b/cocos/physics/cannon/shapes/cannon-trimesh-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import CANNON from '@cocos/cannon'; import { CannonShape } from './cannon-shape'; import { MeshCollider } from '../../framework'; diff --git a/cocos/physics/category.json b/cocos/physics/category.json index 375f6317c3..d0ef6152eb 100644 --- a/cocos/physics/category.json +++ b/cocos/physics/category.json @@ -4,7 +4,7 @@ "en": "Physics System" }, "description": { - "zh": "物理系统", - "en": "Physics System" + "zh": "物理系统用于让游戏世界的物体按照现实世界进行基于物理的模拟与更新,这对于提升游戏的真实感极为重要", + "en": "The physics system is used to allow objects in the game world to be simulated and updated in accordance with the real world based on physics, which is extremely important to enhance the realism of the game." } } \ No newline at end of file diff --git a/cocos/physics/cocos/builtin-interface.ts b/cocos/physics/cocos/builtin-interface.ts index 482463d26f..c424f9c9d6 100644 --- a/cocos/physics/cocos/builtin-interface.ts +++ b/cocos/physics/cocos/builtin-interface.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { Mat4, Quat, Vec3 } from '../../core/math'; import { IVec3Like, IQuatLike } from '../../core/math/type-define'; diff --git a/cocos/physics/cocos/builtin-rigid-body.ts b/cocos/physics/cocos/builtin-rigid-body.ts index 8ef6df1f20..e9e3383e19 100644 --- a/cocos/physics/cocos/builtin-rigid-body.ts +++ b/cocos/physics/cocos/builtin-rigid-body.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { IRigidBody } from '../spec/i-rigid-body'; import { IVec3Like } from '../../core'; import { RigidBody, PhysicsSystem, ERigidBodyType } from '../framework'; diff --git a/cocos/physics/cocos/builtin-shared-body.ts b/cocos/physics/cocos/builtin-shared-body.ts index 02a5bf529b..59ded5c221 100644 --- a/cocos/physics/cocos/builtin-shared-body.ts +++ b/cocos/physics/cocos/builtin-shared-body.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { Mat4, Quat, Vec3 } from '../../core/math'; import { intersect } from '../../core/geometry'; import { BuiltInWorld } from './builtin-world'; diff --git a/cocos/physics/cocos/builtin-world.ts b/cocos/physics/cocos/builtin-world.ts index bb13048c64..1956381f29 100644 --- a/cocos/physics/cocos/builtin-world.ts +++ b/cocos/physics/cocos/builtin-world.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { Vec3 } from '../../core/math'; import { PhysicsRayResult } from '../framework/physics-ray-result'; import { BuiltinSharedBody } from './builtin-shared-body'; diff --git a/cocos/physics/cocos/instantiate.ts b/cocos/physics/cocos/instantiate.ts index d0d7003959..768acba28b 100644 --- a/cocos/physics/cocos/instantiate.ts +++ b/cocos/physics/cocos/instantiate.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { selector } from '../framework/physics-selector'; import { BuiltInWorld } from './builtin-world'; import { BuiltinRigidBody } from './builtin-rigid-body'; @@ -33,7 +31,7 @@ import { BuiltinSphereShape } from './shapes/builtin-sphere-shape'; import { BuiltinCapsuleShape } from './shapes/builtin-capsule-shape'; import { Game, game } from '../../core'; -game.once(Game.EVENT_ENGINE_INITED, () => { +game.once(Game.EVENT_PRE_SUBSYSTEM_INIT, () => { selector.register('builtin', { RigidBody: BuiltinRigidBody, BoxShape: BuiltinBoxShape, diff --git a/cocos/physics/cocos/object/builtin-object.ts b/cocos/physics/cocos/object/builtin-object.ts index 15b0e052f1..1f08600bd5 100644 --- a/cocos/physics/cocos/object/builtin-object.ts +++ b/cocos/physics/cocos/object/builtin-object.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { PhysicsSystem } from '../../framework'; export class BuiltinObject { diff --git a/cocos/physics/framework/assets/physics-material.ts b/cocos/physics/framework/assets/physics-material.ts index 0ff3fc7f67..f7250b2b21 100644 --- a/cocos/physics/framework/assets/physics-material.ts +++ b/cocos/physics/framework/assets/physics-material.ts @@ -25,11 +25,6 @@ // @ts-check -/** - * @packageDocumentation - * @module physics - */ - import { ccclass, editable, serializable } from 'cc.decorator'; import { Asset } from '../../../core/assets/asset'; import { math } from '../../../core'; diff --git a/cocos/physics/framework/collision-matrix.ts b/cocos/physics/framework/collision-matrix.ts index 344501f746..642aef313f 100644 --- a/cocos/physics/framework/collision-matrix.ts +++ b/cocos/physics/framework/collision-matrix.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { PhysicsGroup } from './physics-enum'; export class CollisionMatrix { diff --git a/cocos/physics/framework/components/colliders/box-collider.ts b/cocos/physics/framework/components/colliders/box-collider.ts index 1e114abcc7..d8a0f34ba0 100644 --- a/cocos/physics/framework/components/colliders/box-collider.ts +++ b/cocos/physics/framework/components/colliders/box-collider.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { ccclass, help, diff --git a/cocos/physics/framework/components/colliders/capsule-collider.ts b/cocos/physics/framework/components/colliders/capsule-collider.ts index ae2074501e..2bacea503d 100644 --- a/cocos/physics/framework/components/colliders/capsule-collider.ts +++ b/cocos/physics/framework/components/colliders/capsule-collider.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { ccclass, help, diff --git a/cocos/physics/framework/components/colliders/collider.ts b/cocos/physics/framework/components/colliders/collider.ts index dc0e085828..77b8c62fe5 100644 --- a/cocos/physics/framework/components/colliders/collider.ts +++ b/cocos/physics/framework/components/colliders/collider.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { ccclass, tooltip, displayOrder, displayName, readOnly, type, serializable } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { Eventify } from '../../../../core/event'; @@ -149,7 +144,7 @@ export class Collider extends Eventify(Component) { * @en * Gets or sets the collider is trigger, this will be always trigger if using builtin. * @zh - * 获取或设置碰撞器是否为触发器。(builtin中无论真假都为触发器) + * 获取或设置碰撞器是否为触发器。(builtin 中无论真假都为触发器) */ @displayOrder(0) @tooltip('i18n:physics3d.collider.isTrigger') @@ -312,7 +307,7 @@ export class Collider extends Eventify(Component) { * Gets the group value. * @zh * 获取分组值。 - * @returns 整数,范围为 2 的 0 次方 到 2 的 31 次方 + * @returns @zh 分组值,为 32 位整数,范围为 [2^0, 2^31] @en Group value which is a 32-bits integer, the range is [2^0, 2^31] */ public getGroup (): number { if (this._isInitialized) { @@ -326,7 +321,7 @@ export class Collider extends Eventify(Component) { * Sets the group value. * @zh * 设置分组值。 - * @param v - 整数,范围为 2 的 0 次方 到 2 的 31 次方 + * @param v @zh 分组值,为 32 位整数,范围为 [2^0, 2^31] @en Group value which is a 32-bits integer, the range is [2^0, 2^31] */ public setGroup (v: number): void { if (this._isInitialized) { @@ -339,7 +334,7 @@ export class Collider extends Eventify(Component) { * Add a grouping value to fill in the group you want to join. * @zh * 添加分组值,可填要加入的 group。 - * @param v - 整数,范围为 2 的 0 次方 到 2 的 31 次方 + * @param v @zh 分组值,为 32 位整数,范围为 [2^0, 2^31] @en Group value which is a 32-bits integer, the range is [2^0, 2^31] */ public addGroup (v: number) { if (this._isInitialized) { @@ -352,7 +347,7 @@ export class Collider extends Eventify(Component) { * Subtract the grouping value to fill in the group to be removed. * @zh * 减去分组值,可填要移除的 group。 - * @param v - 整数,范围为 2 的 0 次方 到 2 的 31 次方 + * @param v @zh 分组值,为 32 位整数,范围为 [2^0, 2^31] @en Group value which is a 32-bits integer, the range is [2^0, 2^31] */ public removeGroup (v: number) { if (this._isInitialized) { @@ -365,7 +360,7 @@ export class Collider extends Eventify(Component) { * Gets the mask value. * @zh * 获取掩码值。 - * @returns 整数,范围为 2 的 0 次方 到 2 的 31 次方 + * @returns @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ public getMask (): number { if (this._isInitialized) { @@ -379,7 +374,7 @@ export class Collider extends Eventify(Component) { * Sets the mask value. * @zh * 设置掩码值。 - * @param v - 整数,范围为 2 的 0 次方 到 2 的 31 次方 + * @param v @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ public setMask (v: number) { if (this._isInitialized) { @@ -392,7 +387,7 @@ export class Collider extends Eventify(Component) { * Add mask values to fill in groups that need to be checked. * @zh * 添加掩码值,可填入需要检查的 group。 - * @param v - 整数,范围为 2 的 0 次方 到 2 的 31 次方 + * @param v @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ public addMask (v: number) { if (this._isInitialized) { @@ -405,7 +400,7 @@ export class Collider extends Eventify(Component) { * Subtract the mask value to fill in the group that does not need to be checked. * @zh * 减去掩码值,可填入不需要检查的 group。 - * @param v - 整数,范围为 2 的 0 次方 到 2 的 31 次方 + * @param v @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ public removeMask (v: number) { if (this._isInitialized) { diff --git a/cocos/physics/framework/components/colliders/cone-collider.ts b/cocos/physics/framework/components/colliders/cone-collider.ts index ee4830a166..c4a1157a76 100644 --- a/cocos/physics/framework/components/colliders/cone-collider.ts +++ b/cocos/physics/framework/components/colliders/cone-collider.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { ccclass, help, diff --git a/cocos/physics/framework/components/colliders/cylinder-collider.ts b/cocos/physics/framework/components/colliders/cylinder-collider.ts index 3c5595e737..83a917f0b2 100644 --- a/cocos/physics/framework/components/colliders/cylinder-collider.ts +++ b/cocos/physics/framework/components/colliders/cylinder-collider.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { ccclass, help, diff --git a/cocos/physics/framework/components/colliders/mesh-collider.ts b/cocos/physics/framework/components/colliders/mesh-collider.ts index 01bf50f03f..daf7c09ec8 100644 --- a/cocos/physics/framework/components/colliders/mesh-collider.ts +++ b/cocos/physics/framework/components/colliders/mesh-collider.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { ccclass, help, diff --git a/cocos/physics/framework/components/colliders/plane-collider.ts b/cocos/physics/framework/components/colliders/plane-collider.ts index d985735b7b..cf329e5ddd 100644 --- a/cocos/physics/framework/components/colliders/plane-collider.ts +++ b/cocos/physics/framework/components/colliders/plane-collider.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { ccclass, help, diff --git a/cocos/physics/framework/components/colliders/simplex-collider.ts b/cocos/physics/framework/components/colliders/simplex-collider.ts index 5f9fd905b8..88a2735936 100644 --- a/cocos/physics/framework/components/colliders/simplex-collider.ts +++ b/cocos/physics/framework/components/colliders/simplex-collider.ts @@ -25,11 +25,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { ccclass, help, diff --git a/cocos/physics/framework/components/colliders/sphere-collider.ts b/cocos/physics/framework/components/colliders/sphere-collider.ts index b20f476487..c938d8b0ce 100644 --- a/cocos/physics/framework/components/colliders/sphere-collider.ts +++ b/cocos/physics/framework/components/colliders/sphere-collider.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { ccclass, help, diff --git a/cocos/physics/framework/components/colliders/terrain-collider.ts b/cocos/physics/framework/components/colliders/terrain-collider.ts index 0def7a1c8e..5dcc6f9440 100644 --- a/cocos/physics/framework/components/colliders/terrain-collider.ts +++ b/cocos/physics/framework/components/colliders/terrain-collider.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { ccclass, help, diff --git a/cocos/physics/framework/components/constant-force.ts b/cocos/physics/framework/components/constant-force.ts index 0f6fd8abbd..785816a6d6 100644 --- a/cocos/physics/framework/components/constant-force.ts +++ b/cocos/physics/framework/components/constant-force.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { ccclass, help, @@ -43,6 +38,7 @@ import { EDITOR } from 'internal:constants'; import { Component } from '../../../core/components/component'; import { RigidBody } from './rigid-body'; import { Vec3 } from '../../../core/math/vec3'; +import { legacyCC } from '../../../core/global-exports'; /** * @en @@ -150,7 +146,7 @@ export class ConstantForce extends Component { } public lateUpdate (dt: number) { - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { if (this._rigidBody != null && this._mask !== 0) { if (this._mask & 1) this._rigidBody.applyForce(this._force); if (this._mask & 2) this._rigidBody.applyLocalForce(this.localForce); diff --git a/cocos/physics/framework/components/constraints/constraint.ts b/cocos/physics/framework/components/constraints/constraint.ts index 7af7ba655a..98c95a1a9c 100644 --- a/cocos/physics/framework/components/constraints/constraint.ts +++ b/cocos/physics/framework/components/constraints/constraint.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { ccclass, requireComponent, displayOrder, type, readOnly, serializable } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { Component } from '../../../../core'; @@ -37,6 +32,7 @@ import { Eventify } from '../../../../core/event'; import { IBaseConstraint } from '../../../spec/i-physics-constraint'; import { selector, createConstraint } from '../../physics-selector'; import { EConstraintType } from '../../physics-enum'; +import { legacyCC } from '../../../../core/global-exports'; /** * @en @@ -82,7 +78,7 @@ export class Constraint extends Eventify(Component) { set connectedBody (v: RigidBody | null) { this._connectedBody = v; - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { if (this._constraint) this._constraint.setConnectedBody(v); } } @@ -100,7 +96,7 @@ export class Constraint extends Eventify(Component) { set enableCollision (v) { this._enableCollision = v; - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { if (this._constraint) this._constraint.setEnableCollision(v); } } diff --git a/cocos/physics/framework/components/constraints/hinge-constraint.ts b/cocos/physics/framework/components/constraints/hinge-constraint.ts index dd0279d4fb..d13a317412 100644 --- a/cocos/physics/framework/components/constraints/hinge-constraint.ts +++ b/cocos/physics/framework/components/constraints/hinge-constraint.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { ccclass, help, @@ -41,6 +36,7 @@ import { Constraint } from './constraint'; import { IVec3Like, Vec3 } from '../../../../core'; import { EConstraintType } from '../../physics-enum'; import { IHingeConstraint } from '../../../spec/i-physics-constraint'; +import { legacyCC } from '../../../../core/global-exports'; @ccclass('cc.HingeConstraint') @help('i18n:cc.HingeConstraint') @@ -59,7 +55,7 @@ export class HingeConstraint extends Constraint { set pivotA (v: Vec3) { Vec3.copy(this._pivotA, v); - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { this.constraint.setPivotA(this._pivotA); } } @@ -77,7 +73,7 @@ export class HingeConstraint extends Constraint { set pivotB (v: Vec3) { Vec3.copy(this._pivotB, v); - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { this.constraint.setPivotB(this._pivotB); } } @@ -95,7 +91,7 @@ export class HingeConstraint extends Constraint { set axis (v: Vec3) { Vec3.copy(this._axis, v); - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { this.constraint.setAxis(this._axis); } } diff --git a/cocos/physics/framework/components/constraints/point-to-point-constraint.ts b/cocos/physics/framework/components/constraints/point-to-point-constraint.ts index 238e152b0e..c772254e54 100644 --- a/cocos/physics/framework/components/constraints/point-to-point-constraint.ts +++ b/cocos/physics/framework/components/constraints/point-to-point-constraint.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { ccclass, help, @@ -41,6 +36,7 @@ import { Constraint } from './constraint'; import { Vec3, IVec3Like } from '../../../../core'; import { EConstraintType } from '../../physics-enum'; import { IPointToPointConstraint } from '../../../spec/i-physics-constraint'; +import { legacyCC } from '../../../../core/global-exports'; @ccclass('cc.PointToPointConstraint') @help('i18n:cc.PointToPointConstraint') @@ -59,7 +55,7 @@ export class PointToPointConstraint extends Constraint { set pivotA (v: IVec3Like) { Vec3.copy(this._pivotA, v); - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { this.constraint.setPivotA(this._pivotA); } } @@ -77,7 +73,7 @@ export class PointToPointConstraint extends Constraint { set pivotB (v: IVec3Like) { Vec3.copy(this._pivotB, v); - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { this.constraint.setPivotB(this._pivotB); } } diff --git a/cocos/physics/framework/components/rigid-body.ts b/cocos/physics/framework/components/rigid-body.ts index 5479144ba3..4f2f6f116a 100644 --- a/cocos/physics/framework/components/rigid-body.ts +++ b/cocos/physics/framework/components/rigid-body.ts @@ -25,11 +25,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { ccclass, help, @@ -440,8 +435,8 @@ export class RigidBody extends Component { * Apply force to a world point. This could, for example, be a point on the Body surface. * @zh * 在世界空间中,相对于刚体的质心的某点上对刚体施加作用力。 - * @param force - 作用力 - * @param relativePoint - 作用点,相对于刚体的质心 + * @param force @zh 作用力 @en The force applied + * @param relativePoint @zh 作用点,相对于刚体的质心 @en The point to apply the force on, relative to the center of mass of the rigid body */ public applyForce (force: Vec3, relativePoint?: Vec3) { if (this._isInitialized) this._body!.applyForce(force, relativePoint); @@ -452,8 +447,8 @@ export class RigidBody extends Component { * Apply force to a local point. This could, for example, be a point on the Body surface. * @zh * 在本地空间中,相对于刚体的质心的某点上对刚体施加作用力。 - * @param force - 作用力 - * @param localPoint - 作用点 + * @param force @zh 作用力 @en The force applied + * @param localPoint @zh 作用点 @en The point to apply the force on */ public applyLocalForce (force: Vec3, localPoint?: Vec3) { if (this._isInitialized) this._body!.applyLocalForce(force, localPoint); @@ -464,8 +459,8 @@ export class RigidBody extends Component { * In world space, impulse is applied to the rigid body at some point relative to the center of mass of the rigid body. * @zh * 在世界空间中,相对于刚体的质心的某点上对刚体施加冲量。 - * @param impulse - 冲量 - * @param relativePoint - 作用点,相对于刚体的中心点 + * @param impulse @zh 冲量 @en The impulse applied + * @param relativePoint @zh 作用点,相对于刚体的中心点 @en The point to apply the impulse, relative to the center of mass of the rigid body */ public applyImpulse (impulse: Vec3, relativePoint?: Vec3) { if (this._isInitialized) this._body!.applyImpulse(impulse, relativePoint); @@ -476,8 +471,8 @@ export class RigidBody extends Component { * In local space, impulse is applied to the rigid body at some point relative to the center of mass of the rigid body. * @zh * 在本地空间中,相对于刚体的质心的某点上对刚体施加冲量。 - * @param impulse - 冲量 - * @param localPoint - 作用点 + * @param impulse @zh 冲量 @en The impulse applied + * @param localPoint @zh 作用点 @en The point to apply the impulse */ public applyLocalImpulse (impulse: Vec3, localPoint?: Vec3) { if (this._isInitialized) this._body!.applyLocalImpulse(impulse, localPoint); @@ -488,7 +483,7 @@ export class RigidBody extends Component { * In world space, torque is applied to the rigid body. * @zh * 在世界空间中,对刚体施加扭矩。 - * @param torque - 扭矩 + * @param torque @zh 扭矩 @en The torque applied */ public applyTorque (torque: Vec3) { if (this._isInitialized) this._body!.applyTorque(torque); @@ -497,7 +492,9 @@ export class RigidBody extends Component { /** * @zh * 在本地空间中,对刚体施加扭矩。 - * @param torque - 扭矩 + * @zh + * In local space, torque is applied to the rigid body. + * @param torque @zh 扭矩 @en The torque applied */ public applyLocalTorque (torque: Vec3) { if (this._isInitialized) this._body!.applyLocalTorque(torque); @@ -558,7 +555,7 @@ export class RigidBody extends Component { * Gets the linear velocity. * @zh * 获取线性速度。 - * @param out 速度 Vec3 + * @param out @zh 速度向量 @en The velocity vector */ public getLinearVelocity (out: Vec3) { if (this._isInitialized) this._body!.getLinearVelocity(out); @@ -569,7 +566,7 @@ export class RigidBody extends Component { * Sets the linear velocity. * @zh * 设置线性速度。 - * @param value 速度 Vec3 + * @param value @zh 速度向量 @en The velocity vector */ public setLinearVelocity (value: Vec3): void { if (this._isInitialized) this._body!.setLinearVelocity(value); @@ -580,7 +577,7 @@ export class RigidBody extends Component { * Gets the angular velocity. * @zh * 获取旋转速度。 - * @param out 速度 Vec3 + * @param out @zh 角速度向量 @en The angular velocity vector */ public getAngularVelocity (out: Vec3) { if (this._isInitialized) this._body!.getAngularVelocity(out); @@ -591,7 +588,7 @@ export class RigidBody extends Component { * Sets the angular velocity. * @zh * 设置旋转速度。 - * @param value 速度 Vec3 + * @param value @zh 角速度向量 @en The angular velocity vector */ public setAngularVelocity (value: Vec3): void { if (this._isInitialized) this._body!.setAngularVelocity(value); @@ -604,7 +601,7 @@ export class RigidBody extends Component { * Gets the group value. * @zh * 获取分组值。 - * @returns 整数,范围为 2 的 0 次方 到 2 的 31 次方 + * @returns @zh 分组值,为 32 位整数,范围为 [2^0, 2^31] @en Group value which is a 32-bits integer, the range is [2^0, 2^31] */ public getGroup (): number { if (this._isInitialized) return this._body!.getGroup(); @@ -616,7 +613,7 @@ export class RigidBody extends Component { * Sets the group value. * @zh * 设置分组值。 - * @param v - 整数,范围为 2 的 0 次方 到 2 的 31 次方 + * @param v @zh 分组值,为 32 位整数,范围为 [2^0, 2^31] @en Group value which is a 32-bits integer, the range is [2^0, 2^31] */ public setGroup (v: number): void { if (this._isInitialized) this._body!.setGroup(v); @@ -627,7 +624,7 @@ export class RigidBody extends Component { * Add a grouping value to fill in the group you want to join. * @zh * 添加分组值,可填要加入的 group。 - * @param v - 整数,范围为 2 的 0 次方 到 2 的 31 次方 + * @param v @zh 分组值,为 32 位整数,范围为 [2^0, 2^31] @en Group value which is a 32-bits integer, the range is [2^0, 2^31] */ public addGroup (v: number) { if (this._isInitialized) this._body!.addGroup(v); @@ -638,7 +635,7 @@ export class RigidBody extends Component { * Subtract the grouping value to fill in the group to be removed. * @zh * 减去分组值,可填要移除的 group。 - * @param v - 整数,范围为 2 的 0 次方 到 2 的 31 次方 + * @param v @zh 分组值,为 32 位整数,范围为 [2^0, 2^31] @en Group value which is a 32-bits integer, the range is [2^0, 2^31] */ public removeGroup (v: number) { if (this._isInitialized) this._body!.removeGroup(v); @@ -649,7 +646,7 @@ export class RigidBody extends Component { * Gets the mask value. * @zh * 获取掩码值。 - * @returns 整数,范围为 2 的 0 次方 到 2 的 31 次方 + * @returns {number} @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ public getMask (): number { if (this._isInitialized) return this._body!.getMask(); @@ -661,7 +658,7 @@ export class RigidBody extends Component { * Sets the mask value. * @zh * 设置掩码值。 - * @param v - 整数,范围为 2 的 0 次方 到 2 的 31 次方 + * @param v @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ public setMask (v: number) { if (this._isInitialized) this._body!.setMask(v); @@ -672,7 +669,7 @@ export class RigidBody extends Component { * Add mask values to fill in groups that need to be checked. * @zh * 添加掩码值,可填入需要检查的 group。 - * @param v - 整数,范围为 2 的 0 次方 到 2 的 31 次方 + * @param v @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ public addMask (v: number) { if (this._isInitialized) this._body!.addMask(v); @@ -683,7 +680,7 @@ export class RigidBody extends Component { * Subtract the mask value to fill in the group that does not need to be checked. * @zh * 减去掩码值,可填入不需要检查的 group。 - * @param v - 整数,范围为 2 的 0 次方 到 2 的 31 次方 + * @param v @zh 掩码值,为 32 位整数,范围为 [2^0, 2^31] @en Mask value which is a 32-bits integer, the range is [2^0, 2^31] */ public removeMask (v: number) { if (this._isInitialized) this._body!.removeMask(v); diff --git a/cocos/physics/framework/deprecated.ts b/cocos/physics/framework/deprecated.ts index 78a79e0188..b0e75b5517 100644 --- a/cocos/physics/framework/deprecated.ts +++ b/cocos/physics/framework/deprecated.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { PhysicsSystem } from './physics-system'; import { replaceProperty, removeProperty } from '../../core/utils/x-deprecated'; import { BoxCollider } from './components/colliders/box-collider'; diff --git a/cocos/physics/framework/index.ts b/cocos/physics/framework/index.ts index 8742da8740..530128cbd5 100644 --- a/cocos/physics/framework/index.ts +++ b/cocos/physics/framework/index.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { PhysicsSystem } from './physics-system'; import { PhysicsMaterial } from './assets/physics-material'; import { PhysicsRayResult } from './physics-ray-result'; diff --git a/cocos/physics/framework/physics-config.ts b/cocos/physics/framework/physics-config.ts index 3aced326d5..090262d963 100644 --- a/cocos/physics/framework/physics-config.ts +++ b/cocos/physics/framework/physics-config.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { IVec3Like } from '../../core'; export interface ICollisionMatrix { diff --git a/cocos/physics/framework/physics-enum.ts b/cocos/physics/framework/physics-enum.ts index d02925c897..579de3f6d2 100644 --- a/cocos/physics/framework/physics-enum.ts +++ b/cocos/physics/framework/physics-enum.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { Enum } from '../../core'; export enum ERigidBodyType { diff --git a/cocos/physics/framework/physics-interface.ts b/cocos/physics/framework/physics-interface.ts index 43291f3ce0..f785d31b07 100644 --- a/cocos/physics/framework/physics-interface.ts +++ b/cocos/physics/framework/physics-interface.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { IVec3Like } from '../../core/math'; import { Collider } from './components/colliders/collider'; diff --git a/cocos/physics/framework/physics-ray-result.ts b/cocos/physics/framework/physics-ray-result.ts index 72cffd1855..177afdceed 100644 --- a/cocos/physics/framework/physics-ray-result.ts +++ b/cocos/physics/framework/physics-ray-result.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { Vec3 } from '../../core/math'; import { Collider } from '../../../exports/physics-framework'; import { IVec3Like } from '../../core/math/type-define'; @@ -90,7 +85,7 @@ export class PhysicsRayResult { * @zh * 设置射线,此方法由引擎内部使用,请勿在外部脚本调用。 * - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _assign (hitPoint: IVec3Like, distance: number, collider: Collider, hitNormal: IVec3Like) { Vec3.copy(this._hitPoint, hitPoint); diff --git a/cocos/physics/framework/physics-selector.ts b/cocos/physics/framework/physics-selector.ts index 6682b9b925..284a98d27c 100644 --- a/cocos/physics/framework/physics-selector.ts +++ b/cocos/physics/framework/physics-selector.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - /* eslint-disable import/no-mutable-exports */ /* eslint-disable @typescript-eslint/restrict-template-expressions */ /* eslint-disable @typescript-eslint/no-unsafe-return */ diff --git a/cocos/physics/framework/physics-system.ts b/cocos/physics/framework/physics-system.ts index a1fe60ae68..1bf94dd628 100644 --- a/cocos/physics/framework/physics-system.ts +++ b/cocos/physics/framework/physics-system.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module physics - */ - import { EDITOR } from 'internal:constants'; import { Vec3 } from '../../core/math'; import { IRaycastOptions } from '../spec/i-physics-world'; @@ -42,6 +37,7 @@ import { CollisionMatrix } from './collision-matrix'; import { PhysicsGroup } from './physics-enum'; import { constructDefaultWorld, IWorldInitData, selector } from './physics-selector'; import { legacyCC } from '../../core/global-exports'; +import { Settings, settings } from '../../core/settings'; legacyCC.internal.PhysicsGroup = PhysicsGroup; @@ -285,7 +281,7 @@ export class PhysicsSystem extends System implements IWorldInitData { } postUpdate (deltaTime: number) { - if (EDITOR && !this._executeInEditMode && !selector.runInEditor) return; + if (EDITOR && !legacyCC.GAME_VIEW && !this._executeInEditMode && !selector.runInEditor) return; if (!this.physicsWorld) return; @@ -322,36 +318,42 @@ export class PhysicsSystem extends System implements IWorldInitData { * 重置物理配置。 */ resetConfiguration (config?: IPhysicsConfig) { - const con = config || (game.config ? game.config.physics : null); - if (con) { - if (typeof con.allowSleep === 'boolean') this._allowSleep = con.allowSleep; - if (typeof con.fixedTimeStep === 'number') this._fixedTimeStep = con.fixedTimeStep; - if (typeof con.maxSubSteps === 'number') this._maxSubSteps = con.maxSubSteps; - if (typeof con.sleepThreshold === 'number') this._sleepThreshold = con.sleepThreshold; - if (typeof con.autoSimulation === 'boolean') this.autoSimulation = con.autoSimulation; - if (con.gravity) Vec3.copy(this._gravity, con.gravity); + const allowSleep = config ? config.allowSleep : settings.querySettings(Settings.Category.PHYSICS, 'allowSleep'); + if (typeof allowSleep === 'boolean') this._allowSleep = allowSleep; + const fixedTimeStep = config ? config.fixedTimeStep : settings.querySettings(Settings.Category.PHYSICS, 'fixedTimeStep'); + if (typeof fixedTimeStep === 'number') this._fixedTimeStep = fixedTimeStep; + const maxSubSteps = config ? config.maxSubSteps : settings.querySettings(Settings.Category.PHYSICS, 'maxSubSteps'); + if (typeof maxSubSteps === 'number') this._maxSubSteps = maxSubSteps; + const sleepThreshold = config ? config.sleepThreshold : settings.querySettings(Settings.Category.PHYSICS, 'sleepThreshold'); + if (typeof sleepThreshold === 'number') this._sleepThreshold = sleepThreshold; + const autoSimulation = config ? config.autoSimulation : settings.querySettings(Settings.Category.PHYSICS, 'autoSimulation'); + if (typeof autoSimulation === 'boolean') this.autoSimulation = autoSimulation; - if (con.defaultMaterial) { - this._material.setValues( - con.defaultMaterial.friction, - con.defaultMaterial.rollingFriction, - con.defaultMaterial.spinningFriction, - con.defaultMaterial.restitution, - ); + 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 collisionMatrix = config ? config.collisionMatrix : settings.querySettings(Settings.Category.PHYSICS, 'collisionMatrix'); + if (collisionMatrix) { + for (const i in collisionMatrix) { + this.collisionMatrix[`${1 << parseInt(i)}`] = collisionMatrix[i]; } - - if (con.collisionMatrix) { - for (const i in con.collisionMatrix) { - this.collisionMatrix[`${1 << parseInt(i)}`] = con.collisionMatrix[i]; - } - } - - if (con.collisionGroups) { - const cg = con.collisionGroups; - if (cg instanceof Array) { - cg.forEach((v) => { PhysicsGroup[v.name] = 1 << v.index; }); - Enum.update(PhysicsGroup); - } + } + const collisionGroups = config ? config.collisionGroups : settings.querySettings>(Settings.Category.PHYSICS, 'collisionGroups'); + if (collisionGroups) { + const cg = collisionGroups; + if (cg instanceof Array) { + cg.forEach((v) => { PhysicsGroup[v.name] = 1 << v.index; }); + Enum.update(PhysicsGroup); } } @@ -408,11 +410,12 @@ export class PhysicsSystem extends System implements IWorldInitData { * Collision detect all collider, and record all the detected results, through PhysicsSystem.Instance.RaycastResults access to the results. * @zh * 检测所有的碰撞盒,并记录所有被检测到的结果,通过 PhysicsSystem.instance.raycastResults 访问结果。 - * @param worldRay 世界空间下的一条射线 - * @param mask 掩码,默认为 0xffffffff - * @param maxDistance 最大检测距离,默认为 10000000,目前请勿传入 Infinity 或 Number.MAX_VALUE - * @param queryTrigger 是否检测触发器 - * @return boolean 表示是否有检测到碰撞盒 + * @param worldRay @zh 世界空间下的一条射线 @en A ray in world space + * @param mask @zh 掩码,默认为 0xffffffff @en Mask, default value is 0xffffffff + * @param maxDistance @zh 最大检测距离,默认为 10000000,目前请勿传入 Infinity 或 Number.MAX_VALUE + * @en Maximum detection distance, default value is 10000000, do not pass Infinity or Number.MAX_VALUE for now + * @param queryTrigger @zh 是否检测触发器 @en Whether to detect triggers + * @return {boolean} @zh 表示是否有检测到碰撞 @en Indicates whether a collision has been detected */ raycast (worldRay: Ray, mask = 0xffffffff, maxDistance = 10000000, queryTrigger = true): boolean { if (!this.physicsWorld) return false; @@ -430,11 +433,12 @@ export class PhysicsSystem extends System implements IWorldInitData { * by PhysicsSystem.Instance.RaycastClosestResult access to the results. * @zh * 检测所有的碰撞盒,并记录与射线距离最短的检测结果,通过 PhysicsSystem.instance.raycastClosestResult 访问结果。 - * @param worldRay 世界空间下的一条射线 - * @param mask 掩码,默认为 0xffffffff - * @param maxDistance 最大检测距离,默认为 10000000,目前请勿传入 Infinity 或 Number.MAX_VALUE - * @param queryTrigger 是否检测触发器 - * @return boolean 表示是否有检测到碰撞盒 + * @param worldRay @zh 世界空间下的一条射线 @en A ray in world space + * @param mask @zh 掩码,默认为 0xffffffff @en Mask, default value is 0xffffffff + * @param maxDistance @zh 最大检测距离,默认为 10000000,目前请勿传入 Infinity 或 Number.MAX_VALUE + * @en Maximum detection distance, default value is 10000000, do not pass Infinity or Number.MAX_VALUE for now + * @param queryTrigger @zh 是否检测触发器 @en Whether to detect triggers + * @return {boolean} @zh 表示是否有检测到碰撞 @en Indicates whether a collision has been detected */ raycastClosest (worldRay: Ray, mask = 0xffffffff, maxDistance = 10000000, queryTrigger = true): boolean { if (!this.physicsWorld) return false; diff --git a/cocos/physics/physx/instantiate.jsb.ts b/cocos/physics/physx/instantiate.jsb.ts index d8ba7b2fa8..f5325cc416 100644 --- a/cocos/physics/physx/instantiate.jsb.ts +++ b/cocos/physics/physx/instantiate.jsb.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - /** * hack for jsb, shoule be refactor in futrue */ diff --git a/cocos/physics/physx/instantiate.ts b/cocos/physics/physx/instantiate.ts index 10856d1a60..be3e908902 100644 --- a/cocos/physics/physx/instantiate.ts +++ b/cocos/physics/physx/instantiate.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { selector } from '../framework/physics-selector'; import { PhysXWorld } from './physx-world'; @@ -44,7 +42,7 @@ import { PhysXDistanceJoint } from './joints/physx-distance-joint'; import { PhysXRevoluteJoint } from './joints/physx-revolute-joint'; import { Game, game } from '../../core'; -game.once(Game.EVENT_ENGINE_INITED, () => { +game.once(Game.EVENT_PRE_SUBSYSTEM_INIT, () => { selector.register('physx', { PhysicsWorld: PhysXWorld, RigidBody: PhysXRigidBody, diff --git a/cocos/physics/physx/joints/physx-distance-joint.ts b/cocos/physics/physx/joints/physx-distance-joint.ts index d006710098..743fb3777e 100644 --- a/cocos/physics/physx/joints/physx-distance-joint.ts +++ b/cocos/physics/physx/joints/physx-distance-joint.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { IVec3Like, Quat, Vec3 } from '../../../core'; import { PointToPointConstraint } from '../../framework'; import { IPointToPointConstraint } from '../../spec/i-physics-constraint'; diff --git a/cocos/physics/physx/joints/physx-fixed-joint.ts b/cocos/physics/physx/joints/physx-fixed-joint.ts index 2faa80ac1d..1af6df9159 100644 --- a/cocos/physics/physx/joints/physx-fixed-joint.ts +++ b/cocos/physics/physx/joints/physx-fixed-joint.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { IVec3Like } from '../../../core'; import { PointToPointConstraint } from '../../framework'; import { IPointToPointConstraint } from '../../spec/i-physics-constraint'; diff --git a/cocos/physics/physx/joints/physx-joint.ts b/cocos/physics/physx/joints/physx-joint.ts index 5d9e995cd5..53eddb1b8d 100644 --- a/cocos/physics/physx/joints/physx-joint.ts +++ b/cocos/physics/physx/joints/physx-joint.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - /* eslint-disable @typescript-eslint/no-unsafe-return */ import { Constraint, RigidBody } from '../../framework'; import { IBaseConstraint } from '../../spec/i-physics-constraint'; diff --git a/cocos/physics/physx/joints/physx-revolute-joint.ts b/cocos/physics/physx/joints/physx-revolute-joint.ts index 248a0fbc20..8110e588f2 100644 --- a/cocos/physics/physx/joints/physx-revolute-joint.ts +++ b/cocos/physics/physx/joints/physx-revolute-joint.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { IVec3Like, Quat, Vec3 } from '../../../core'; import { HingeConstraint } from '../../framework'; import { IHingeConstraint } from '../../spec/i-physics-constraint'; diff --git a/cocos/physics/physx/physx-adapter.ts b/cocos/physics/physx/physx-adapter.ts index ca00724b78..b858cc572a 100644 --- a/cocos/physics/physx/physx-adapter.ts +++ b/cocos/physics/physx/physx-adapter.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - /* eslint-disable import/no-mutable-exports */ /* eslint-disable no-console */ /* eslint-disable @typescript-eslint/restrict-template-expressions */ @@ -35,7 +33,7 @@ import { PhysX } from './physx.asmjs'; import { BYTEDANCE, DEBUG, EDITOR, TEST } from 'internal:constants'; -import { Director, director, Game, game, IQuatLike, IVec3Like, Node, Quat, RecyclePool, Vec3 } from '../../core'; +import { Director, director, game, IQuatLike, IVec3Like, Node, Quat, RecyclePool, Vec3 } from '../../core'; import { shrinkPositions } from '../utils/util'; import { legacyCC } from '../../core/global-exports'; import { AABB, Ray } from '../../core/geometry'; @@ -45,6 +43,7 @@ import { PhysXWorld } from './physx-world'; import { PhysXInstance } from './physx-instance'; import { PhysXShape } from './shapes/physx-shape'; import { PxHitFlag, PxPairFlag, PxQueryFlag, EFilterDataWord3 } from './physx-enum'; +import { Settings, settings } from '../../core/settings'; export const PX = {} as any; const globalThis = legacyCC._global; @@ -53,9 +52,9 @@ const USE_BYTEDANCE = BYTEDANCE && globalThis.nativePhysX; const USE_EXTERNAL_PHYSX = !!globalThis.PHYSX; // Init physx libs when engine init. -game.onEngineInitedAsync(InitPhysXLibs); +game.onPostInfrastructureInitDelegate.add(InitPhysXLibs); -function InitPhysXLibs () { +export function InitPhysXLibs () { if (USE_BYTEDANCE) { if (!EDITOR && !TEST) console.info('[PHYSICS]:', `Use PhysX Libs in BYTEDANCE.`); Object.assign(PX, globalThis.nativePhysX); @@ -740,11 +739,12 @@ interface IPhysicsConfigEXT extends IPhysicsConfig { } function initConfigForByteDance () { - if (game.config.physics && (game.config.physics as IPhysicsConfigEXT).physX) { - const settings = (game.config.physics as IPhysicsConfigEXT).physX; - PX.EPSILON = settings.epsilon; - PX.MULTI_THREAD = settings.multiThread; - PX.SUB_THREAD_COUNT = settings.subThreadCount; + const physX = settings.querySettings(Settings.Category.PHYSICS, 'physX'); + if (physX) { + const { epsilon, multiThread, subThreadCount } = physX; + PX.EPSILON = epsilon; + PX.MULTI_THREAD = multiThread; + PX.SUB_THREAD_COUNT = subThreadCount; } } diff --git a/cocos/physics/physx/physx-contact-equation.ts b/cocos/physics/physx/physx-contact-equation.ts index baa478cdf2..33016b59f7 100644 --- a/cocos/physics/physx/physx-contact-equation.ts +++ b/cocos/physics/physx/physx-contact-equation.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { IVec3Like, Vec3, Quat } from '../../core'; import { IContactEquation, ICollisionEvent, Collider } from '../framework'; import { getContactNormal, getContactPosition } from './physx-adapter'; diff --git a/cocos/physics/physx/physx-enum.ts b/cocos/physics/physx/physx-enum.ts index 8d52dae220..4b1cb94037 100644 --- a/cocos/physics/physx/physx-enum.ts +++ b/cocos/physics/physx/physx-enum.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - /* eslint-disable max-len */ /* eslint-disable no-tabs */ diff --git a/cocos/physics/physx/physx-rigid-body.ts b/cocos/physics/physx/physx-rigid-body.ts index 93746c7dad..3420a5f7ed 100644 --- a/cocos/physics/physx/physx-rigid-body.ts +++ b/cocos/physics/physx/physx-rigid-body.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - /* eslint-disable @typescript-eslint/no-unsafe-return */ import { IVec3Like, Vec3 } from '../../core'; import { ERigidBodyType, PhysicsSystem, RigidBody } from '../framework'; diff --git a/cocos/physics/physx/physx-shared-body.ts b/cocos/physics/physx/physx-shared-body.ts index 09b7611050..3c9ec0a9c2 100644 --- a/cocos/physics/physx/physx-shared-body.ts +++ b/cocos/physics/physx/physx-shared-body.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - /* eslint-disable @typescript-eslint/no-unsafe-return */ import { Node, Quat, Vec3 } from '../../core'; import { PhysXRigidBody } from './physx-rigid-body'; @@ -341,6 +339,7 @@ export class PhysXSharedBody { } setGroup (v: number): void { + v >>>= 0; //convert to unsigned int(32bit) for physx this._filterData.word0 = v; this.updateFilterData(); } @@ -350,17 +349,19 @@ export class PhysXSharedBody { } addGroup (v: number): void { + v >>>= 0; //convert to unsigned int(32bit) for physx this._filterData.word0 |= v; this.updateFilterData(); } removeGroup (v: number): void { + v >>>= 0; //convert to unsigned int(32bit) for physx this._filterData.word0 &= ~v; this.updateFilterData(); } setMask (v: number): void { - if (v === -1) v = 0xffffffff; + v >>>= 0; //convert to unsigned int(32bit) for physx this._filterData.word1 = v; this.updateFilterData(); } @@ -370,11 +371,13 @@ export class PhysXSharedBody { } addMask (v: number): void { + v >>>= 0; //convert to unsigned int(32bit) for physx this._filterData.word1 |= v; this.updateFilterData(); } removeMask (v: number): void { + v >>>= 0; //convert to unsigned int(32bit) for physx this._filterData.word1 &= ~v; this.updateFilterData(); } diff --git a/cocos/physics/physx/physx-world.ts b/cocos/physics/physx/physx-world.ts index 09ca294eae..fe7beb2248 100644 --- a/cocos/physics/physx/physx-world.ts +++ b/cocos/physics/physx/physx-world.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - /* eslint-disable @typescript-eslint/no-unsafe-return */ import { Ray } from '../../core/geometry'; import { IPhysicsWorld, IRaycastOptions } from '../spec/i-physics-world'; @@ -71,6 +69,7 @@ export class PhysXWorld extends PhysXInstance implements IPhysicsWorld { } step (deltaTime: number, _timeSinceLastCalled?: number, _maxSubStep = 0): void { + if (this.wrappedBodies.length === 0) return; this._simulate(deltaTime); if (!PX.MULTI_THREAD) { this._fetchResults(); diff --git a/cocos/physics/physx/physx.asmjs.ts b/cocos/physics/physx/physx.asmjs.ts index 0fb16c86be..d01c92ab25 100644 --- a/cocos/physics/physx/physx.asmjs.ts +++ b/cocos/physics/physx/physx.asmjs.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - /** * export PhysX from internal module */ diff --git a/cocos/physics/physx/physx.null.ts b/cocos/physics/physx/physx.null.ts index 0e42db1ac4..adb72452f7 100644 --- a/cocos/physics/physx/physx.null.ts +++ b/cocos/physics/physx/physx.null.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - /** * export null for module elimination */ diff --git a/cocos/physics/physx/shapes/physx-box-shape.ts b/cocos/physics/physx/shapes/physx-box-shape.ts index 523409ce09..2f7413224e 100644 --- a/cocos/physics/physx/shapes/physx-box-shape.ts +++ b/cocos/physics/physx/shapes/physx-box-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { BoxCollider } from '../../framework'; import { absolute, VEC3_0 } from '../../utils/util'; import { IBoxShape } from '../../spec/i-physics-shape'; diff --git a/cocos/physics/physx/shapes/physx-capsule-shape.ts b/cocos/physics/physx/shapes/physx-capsule-shape.ts index 57239c768e..81ae841e76 100644 --- a/cocos/physics/physx/shapes/physx-capsule-shape.ts +++ b/cocos/physics/physx/shapes/physx-capsule-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { absMax, Quat } from '../../../core'; import { CapsuleCollider, EAxisDirection } from '../../framework'; import { ICapsuleShape } from '../../spec/i-physics-shape'; diff --git a/cocos/physics/physx/shapes/physx-cone-shape.ts b/cocos/physics/physx/shapes/physx-cone-shape.ts index 62d51ef88e..50ac6746f3 100644 --- a/cocos/physics/physx/shapes/physx-cone-shape.ts +++ b/cocos/physics/physx/shapes/physx-cone-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { Quat, Vec3 } from '../../../core'; import cylinder from '../../../primitive/cylinder'; import { ConeCollider, EAxisDirection } from '../../framework'; diff --git a/cocos/physics/physx/shapes/physx-cylinder-shape.ts b/cocos/physics/physx/shapes/physx-cylinder-shape.ts index b12a830949..8fa0240212 100644 --- a/cocos/physics/physx/shapes/physx-cylinder-shape.ts +++ b/cocos/physics/physx/shapes/physx-cylinder-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { Quat, Vec3 } from '../../../core'; import cylinder from '../../../primitive/cylinder'; import { CylinderCollider, EAxisDirection } from '../../framework'; diff --git a/cocos/physics/physx/shapes/physx-plane-shape.ts b/cocos/physics/physx/shapes/physx-plane-shape.ts index c0f06ad04d..28ea3e2f6f 100644 --- a/cocos/physics/physx/shapes/physx-plane-shape.ts +++ b/cocos/physics/physx/shapes/physx-plane-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { IVec3Like, Quat, Vec3 } from '../../../core'; import { PlaneCollider } from '../../framework'; import { IPlaneShape } from '../../spec/i-physics-shape'; diff --git a/cocos/physics/physx/shapes/physx-shape.ts b/cocos/physics/physx/shapes/physx-shape.ts index a2b9cf2684..9f1cb4f9f0 100644 --- a/cocos/physics/physx/shapes/physx-shape.ts +++ b/cocos/physics/physx/shapes/physx-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - /* eslint-disable @typescript-eslint/no-unsafe-return */ import { IVec3Like, Quat, Vec3 } from '../../../core'; import { AABB, Sphere } from '../../../core/geometry'; diff --git a/cocos/physics/physx/shapes/physx-sphere-shape.ts b/cocos/physics/physx/shapes/physx-sphere-shape.ts index 017cdbf5a7..2799023623 100644 --- a/cocos/physics/physx/shapes/physx-sphere-shape.ts +++ b/cocos/physics/physx/shapes/physx-sphere-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { absMaxComponent } from '../../../core'; import { SphereCollider } from '../../framework'; import { ISphereShape } from '../../spec/i-physics-shape'; diff --git a/cocos/physics/physx/shapes/physx-terrain-shape.ts b/cocos/physics/physx/shapes/physx-terrain-shape.ts index 10c233f3a7..3a8fb9d4b4 100644 --- a/cocos/physics/physx/shapes/physx-terrain-shape.ts +++ b/cocos/physics/physx/shapes/physx-terrain-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { IVec3Like } from '../../../core'; import { PhysicsMaterial, TerrainCollider } from '../../framework'; import { ITerrainAsset } from '../../spec/i-external'; diff --git a/cocos/physics/physx/shapes/physx-trimesh-shape.ts b/cocos/physics/physx/shapes/physx-trimesh-shape.ts index 780f4c07ea..51a049e05b 100644 --- a/cocos/physics/physx/shapes/physx-trimesh-shape.ts +++ b/cocos/physics/physx/shapes/physx-trimesh-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { IVec3Like, Quat, Vec3 } from '../../../core'; import { Mesh } from '../../../3d/assets'; diff --git a/cocos/physics/spec/i-external.ts b/cocos/physics/spec/i-external.ts index 0b2a9a4634..7ce0bb3c8d 100644 --- a/cocos/physics/spec/i-external.ts +++ b/cocos/physics/spec/i-external.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - export interface ITerrainAsset { _uuid: string; tileSize: number; diff --git a/cocos/physics/spec/i-group-mask.ts b/cocos/physics/spec/i-group-mask.ts index 0bbc11c7e4..439698f353 100644 --- a/cocos/physics/spec/i-group-mask.ts +++ b/cocos/physics/spec/i-group-mask.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - export interface IGroupMask { setGroup (v: number): void; getGroup (): number; diff --git a/cocos/physics/spec/i-lifecycle.ts b/cocos/physics/spec/i-lifecycle.ts index 98322c5736..6b9c740925 100644 --- a/cocos/physics/spec/i-lifecycle.ts +++ b/cocos/physics/spec/i-lifecycle.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - export interface ILifecycle { /** * @en Update is called every frame, if the Component is enabled.
diff --git a/cocos/physics/spec/i-physics-constraint.ts b/cocos/physics/spec/i-physics-constraint.ts index 37c07964a1..8141bffa26 100644 --- a/cocos/physics/spec/i-physics-constraint.ts +++ b/cocos/physics/spec/i-physics-constraint.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { ILifecycle } from './i-lifecycle'; import { Constraint, RigidBody } from '../framework'; import { IVec3Like } from '../../core'; diff --git a/cocos/physics/spec/i-physics-shape.ts b/cocos/physics/spec/i-physics-shape.ts index 4875aa5d5f..8c218b1382 100644 --- a/cocos/physics/spec/i-physics-shape.ts +++ b/cocos/physics/spec/i-physics-shape.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { ILifecycle } from './i-lifecycle'; import { IGroupMask } from './i-group-mask'; import { IVec3Like } from '../../core/math/type-define'; diff --git a/cocos/physics/spec/i-physics-world.ts b/cocos/physics/spec/i-physics-world.ts index 722bcf1578..22544ffb57 100644 --- a/cocos/physics/spec/i-physics-world.ts +++ b/cocos/physics/spec/i-physics-world.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { IVec3Like } from '../../core/math/type-define'; import { PhysicsRayResult } from '../framework/physics-ray-result'; import { Ray } from '../../core/geometry'; diff --git a/cocos/physics/spec/i-rigid-body.ts b/cocos/physics/spec/i-rigid-body.ts index 1bf988460d..6300f27336 100644 --- a/cocos/physics/spec/i-rigid-body.ts +++ b/cocos/physics/spec/i-rigid-body.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - import { ILifecycle } from './i-lifecycle'; import { IGroupMask } from './i-group-mask'; import { IVec3Like } from '../../core/math/type-define'; diff --git a/cocos/physics/utils/array-collision-matrix.ts b/cocos/physics/utils/array-collision-matrix.ts index 0369b87f29..11e06373a1 100644 --- a/cocos/physics/utils/array-collision-matrix.ts +++ b/cocos/physics/utils/array-collision-matrix.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - /** * Collision "matrix". It's actually a triangular-shaped array of whether two bodies are touching this step, for reference next step * @class ArrayCollisionMatrix diff --git a/cocos/physics/utils/object-collision-matrix.ts b/cocos/physics/utils/object-collision-matrix.ts index 723755ceaf..3272e226f4 100644 --- a/cocos/physics/utils/object-collision-matrix.ts +++ b/cocos/physics/utils/object-collision-matrix.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - /** * Records what objects are colliding with each other * @class ObjectCollisionMatrix diff --git a/cocos/physics/utils/tuple-dictionary.ts b/cocos/physics/utils/tuple-dictionary.ts index ad491139fb..f89ff816b4 100644 --- a/cocos/physics/utils/tuple-dictionary.ts +++ b/cocos/physics/utils/tuple-dictionary.ts @@ -23,8 +23,6 @@ THE SOFTWARE. */ - - /** * @class TupleDictionary * @constructor diff --git a/cocos/physics/utils/util.ts b/cocos/physics/utils/util.ts index 03a2978bf1..c306656d06 100644 --- a/cocos/physics/utils/util.ts +++ b/cocos/physics/utils/util.ts @@ -23,7 +23,6 @@ THE SOFTWARE. */ - import { equals, Vec3 } from '../../core'; import { IVec3Like, IQuatLike } from '../../core/math/type-define'; import { Collider, CollisionEventType, IContactEquation, TriggerEventType } from '../framework'; diff --git a/cocos/primitive/box.ts b/cocos/primitive/box.ts index 8131865676..1ae25ee575 100644 --- a/cocos/primitive/box.ts +++ b/cocos/primitive/box.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module 3d/primitive - */ - import { Vec3 } from '../core/math'; import { IGeometry, IGeometryOptions } from './define'; @@ -93,7 +88,7 @@ interface IBoxOptions extends RecursivePartial { * but may be repositioned through the `center` option. * @zh * 生成一个立方体,其大小是定义的范围且中心在原点。 - * @param options 参数选项。 + * @param options @zh 参数选项。@en The optional creation parameters of the box */ export default function box (options?: IBoxOptions): IGeometry { options = options || {}; diff --git a/cocos/primitive/capsule.ts b/cocos/primitive/capsule.ts index d2047faa9d..38a5cdc586 100644 --- a/cocos/primitive/capsule.ts +++ b/cocos/primitive/capsule.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module 3d/primitive - */ - import { Vec3 } from '../core/math'; /** @@ -51,9 +46,9 @@ const temp2 = new Vec3(0, 0, 0); * but may be repositioned through the `center` option. * @zh * 生成一个胶囊体。 - * @param radiusTop 顶部半径。 - * @param radiusBottom 底部半径。 - * @param opts 胶囊体参数选项。 + * @param radiusTop @zh 顶部半径。 @en The radius of top sphere + * @param radiusBottom @zh 底部半径。@en The radius of bottom sphere + * @param opts @zh 胶囊体参数选项。@en The optional creation parameters of the capsule */ export default function capsule (radiusTop = 0.5, radiusBottom = 0.5, height = 2, opts: RecursivePartial = {}) { const torsoHeight = height - radiusTop - radiusBottom; diff --git a/cocos/primitive/category.json b/cocos/primitive/category.json new file mode 100644 index 0000000000..b8dd4d833f --- /dev/null +++ b/cocos/primitive/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "基础图元", + "en": "Primitive" + }, + "description": { + "zh": "一些可参数化生成的基础图元", + "en": "Some parametric generated primitive" + } +} \ No newline at end of file diff --git a/cocos/primitive/circle.ts b/cocos/primitive/circle.ts index 56733c742e..f9a51bbd8e 100644 --- a/cocos/primitive/circle.ts +++ b/cocos/primitive/circle.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module 3d/primitive - */ - import { PrimitiveMode } from '../core/gfx'; import { applyDefaultGeometryOptions, IGeometry, IGeometryOptions } from './define'; @@ -59,7 +54,7 @@ function applyDefaultCircleOptions (options?: RecursivePartial): * but may be repositioned through the `center` option. * @zh * 生成一个圆,其半径是单位1,中心点在原点。 - * @param options 参数选项。 + * @param options @zh 参数选项。 @en The optional creation parameters of the circle */ export default function circle (options?: RecursivePartial | ICircleOptions): IGeometry { const normalizedOptions = applyDefaultCircleOptions(options); diff --git a/cocos/primitive/cone.ts b/cocos/primitive/cone.ts index bfcf3160ef..433ef823e1 100644 --- a/cocos/primitive/cone.ts +++ b/cocos/primitive/cone.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module 3d/primitive - */ - import cylinder, { ICylinderOptions } from './cylinder'; import { IGeometry } from './define'; @@ -39,9 +34,9 @@ type IConeOptions = ICylinderOptions; * but may be repositioned through the `center` option. * @zh * 生成一个圆锥。 - * @param radius 圆锥半径。 - * @param height 圆锥高度。 - * @param opts 圆锥参数选项。 + * @param radius @zh 圆锥半径。 @en The radius of cone + * @param height @zh 圆锥高度。 @en The height of cone + * @param opts @zh 圆锥参数选项。@en The optional creation parameters of the cone */ export default function cone ( radius = 0.5, diff --git a/cocos/primitive/cylinder.ts b/cocos/primitive/cylinder.ts index 7701d837ca..4947cb8090 100644 --- a/cocos/primitive/cylinder.ts +++ b/cocos/primitive/cylinder.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module 3d/primitive - */ - import { Vec3 } from '../core/math'; import { IGeometry, IGeometryOptions } from './define'; @@ -38,10 +33,10 @@ import { IGeometry, IGeometryOptions } from './define'; * 圆柱参数选项。 */ export interface ICylinderOptions extends IGeometryOptions { - radialSegments: number; - heightSegments: number; - capped: boolean; - arc: number; + radialSegments: number; + heightSegments: number; + capped: boolean; + arc: number; } const temp1 = new Vec3(0, 0, 0); @@ -53,9 +48,10 @@ const temp2 = new Vec3(0, 0, 0); * but may be repositioned through the `center` option. * @zh * 生成一个圆柱。 - * @param radiusTop 顶部半径。 - * @param radiusBottom 底部半径。 - * @param opts 圆柱参数选项。 + * @param radiusTop @en Radius of top plane. @zh 顶部半径。 + * @param radiusBottom @en Radius of bottom plane. @zh 底部半径。 + * @param height @en The cylinder height. @zh 圆柱的高 + * @param opts @en The optional creation parameters of the cylinder. @zh 圆柱参数选项。 */ export default function cylinder (radiusTop = 0.5, radiusBottom = 0.5, height = 2, opts: RecursivePartial = {}): IGeometry { const halfHeight = height * 0.5; diff --git a/cocos/primitive/define.ts b/cocos/primitive/define.ts index e6a57a13ef..f45b70b78f 100644 --- a/cocos/primitive/define.ts +++ b/cocos/primitive/define.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module 3d/primitive - */ - import { PrimitiveMode, Attribute } from '../core/gfx'; /** diff --git a/cocos/primitive/index.ts b/cocos/primitive/index.ts index baa6739a8b..77608aad3a 100644 --- a/cocos/primitive/index.ts +++ b/cocos/primitive/index.ts @@ -23,13 +23,6 @@ THE SOFTWARE. */ -/** - * @en A basic module for creating vertex data for 3D objects. - * @zh 一个创建 3D 物体顶点数据的基础模块。 - * @packageDocumentation - * @module 3d/primitive - */ - export * from './utils'; export * from './define'; export { default as box } from './box'; diff --git a/cocos/primitive/plane.ts b/cocos/primitive/plane.ts index 9ba2558ae5..a2de1dac33 100644 --- a/cocos/primitive/plane.ts +++ b/cocos/primitive/plane.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module 3d/primitive - */ - import { Vec3 } from '../core/math'; import { applyDefaultGeometryOptions, IGeometry, IGeometryOptions } from './define'; @@ -86,7 +81,7 @@ const c01 = new Vec3(0, 0, 0); * This function generates a plane on XOZ plane with positive Y direction. * @zh * 生成一个平面,其位于XOZ平面,方向为Y轴正方向。 - * @param options 平面参数选项。 + * @param options @zh 平面参数选项。@en The optional creation parameters of the plane */ export default function plane (options?: IPlaneOptions): IGeometry { const normalizedOptions = applyDefaultPlaneOptions(options); diff --git a/cocos/primitive/primitive.ts b/cocos/primitive/primitive.ts index 4c41c3d7b8..286c2b31d4 100644 --- a/cocos/primitive/primitive.ts +++ b/cocos/primitive/primitive.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module 3d/primitive - */ - import { ccclass, type, serializable, editable } from 'cc.decorator'; import { createMesh } from '../3d/misc'; import { Mesh } from '../3d/assets/mesh'; diff --git a/cocos/primitive/quad.ts b/cocos/primitive/quad.ts index af22fa826d..94337a53bb 100644 --- a/cocos/primitive/quad.ts +++ b/cocos/primitive/quad.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module 3d/primitive - */ - import { applyDefaultGeometryOptions, IGeometry, IGeometryOptions } from './define'; /** @@ -35,7 +30,7 @@ import { applyDefaultGeometryOptions, IGeometry, IGeometryOptions } from './defi * Generate a quad with width and height both to 1, centered at origin. * @zh * 生成一个四边形,宽高都为1,中心在原点。 - * @param options 参数选项。 + * @param options @zh 参数选项。 @en The optional creation parameters of the quad */ export default function quad (options?: IGeometryOptions): IGeometry { const normalizedOptions = applyDefaultGeometryOptions(options); diff --git a/cocos/primitive/sphere.ts b/cocos/primitive/sphere.ts index 254f95c416..0398b16b8d 100644 --- a/cocos/primitive/sphere.ts +++ b/cocos/primitive/sphere.ts @@ -23,17 +23,14 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module 3d/primitive - */ - import { Vec3 } from '../core/math'; import { IGeometry, IGeometryOptions } from './define'; /** * @zh * 球参数选项。 + * @en + * The options of sphere */ interface ISphereOptions extends IGeometryOptions { segments: number; @@ -44,8 +41,8 @@ interface ISphereOptions extends IGeometryOptions { * Generate a shpere with radius 0.5. * @zh * 生成一个球。 - * @param radius 球半径。 - * @param options 参数选项。 + * @param radius @en The radius. @zh 球半径。 + * @param options @en The sphere creation options. @zh 参数选项。 */ export default function sphere (radius = 0.5, opts: RecursivePartial = {}): IGeometry { const segments = opts.segments !== undefined ? opts.segments : 32; diff --git a/cocos/primitive/torus.ts b/cocos/primitive/torus.ts index 03187c15b1..62fa6dd4b7 100644 --- a/cocos/primitive/torus.ts +++ b/cocos/primitive/torus.ts @@ -23,32 +23,29 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module 3d/primitive - */ - import { Vec3 } from '../core/math'; import { IGeometryOptions } from './define'; /** * @zh * 环面参数选项。 + * @en + * The options about torus */ interface ITorusOptions extends IGeometryOptions { - radialSegments: number; - tubularSegments: number; - arc: number; + radialSegments: number; + tubularSegments: number; + arc: number; } /** * @en - * Generate a torus with raidus 0.4, tube 0.1 and centered at origin. + * Generate a torus with radius 0.4, tube 0.1 and centered at origin. * @zh * 生成一个环面。 - * @param radius 环面半径。 - * @param tube 管形大小。 - * @param opts 参数选项。 + * @param radius @zh 环面半径。@en The radius fo torus + * @param tube @zh 管形大小。@en The radius of tube + * @param opts @zh 参数选项。@en The optional creation parameters of the torus */ export default function torus (radius = 0.4, tube = 0.1, opts: RecursivePartial = {}) { const radialSegments = opts.radialSegments || 32; diff --git a/cocos/primitive/transform.ts b/cocos/primitive/transform.ts index 428e80ae6f..58ddca1bde 100644 --- a/cocos/primitive/transform.ts +++ b/cocos/primitive/transform.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module 3d/primitive - */ - import { PrimitiveMode } from '../core/gfx'; import { IGeometry } from './define'; @@ -36,8 +31,8 @@ import { IGeometry } from './define'; * Translate the geometry. * @zh * 平移几何体。 - * @param geometry 几何体信息。 - * @param offset 偏移量。 + * @param geometry @zh 几何体信息。@en The geometry to be translated + * @param offset @zh 偏移量。@en The translation */ export function translate (geometry: IGeometry, offset: { x?: number; y?: number; z?: number; }) { const x = offset.x || 0; @@ -70,8 +65,8 @@ export function translate (geometry: IGeometry, offset: { x?: number; y?: number * Scale the geometry. * @zh * 缩放几何体。 - * @param geometry 几何体信息。 - * @param value 缩放量。 + * @param geometry @zh 几何体信息。 @en The geometry to be scaled + * @param value @zh 缩放量。@en The scaling size */ export function scale (geometry: IGeometry, value: { x?: number; y?: number; z?: number }) { const x = value.x || 0; @@ -105,7 +100,7 @@ export function scale (geometry: IGeometry, value: { x?: number; y?: number; z?: * Converts geometry to wireframe mode. Only geometry with triangle topology is supported. * @zh * 将几何体转换为线框模式,仅支持三角形拓扑的几何体。 - * @param geometry 几何体信息。 + * @param geometry @zh 几何体信息。@en The geometry to be converted to wireframe */ export function wireframed (geometry: IGeometry) { const { indices } = geometry; diff --git a/cocos/primitive/utils.ts b/cocos/primitive/utils.ts index 0b7f200d4e..de5a311e6b 100644 --- a/cocos/primitive/utils.ts +++ b/cocos/primitive/utils.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module 3d/primitive - */ - import { PrimitiveMode } from '../core/gfx'; import { IGeometry } from './define'; diff --git a/cocos/profiler/category.json b/cocos/profiler/category.json new file mode 100644 index 0000000000..afbe63b76f --- /dev/null +++ b/cocos/profiler/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "性能监控", + "en": "Profiler" + }, + "description": { + "zh": "用于查看游戏运行时性能信息", + "en": "Used to observe game runtime performance information" + } +} \ No newline at end of file diff --git a/cocos/profiler/profiler.ts b/cocos/profiler/profiler.ts index fa9c641bea..985f8f233c 100644 --- a/cocos/profiler/profiler.ts +++ b/cocos/profiler/profiler.ts @@ -28,7 +28,7 @@ import { TEST, EDITOR } from 'internal:constants'; import { MeshRenderer } from '../3d/framework/mesh-renderer'; import { createMesh } from '../3d/misc'; import { Material } from '../core/assets/material'; -import { Format, TextureType, TextureUsageBit, Texture, TextureInfo, Device, BufferTextureCopy, Swapchain } from '../core/gfx'; +import { Format, TextureType, TextureUsageBit, Texture, TextureInfo, Device, BufferTextureCopy, Swapchain, deviceManager } from '../core/gfx'; import { Layers } from '../core/scene-graph'; import { Node } from '../core/scene-graph/node'; import { ICounterOption } from './counter'; @@ -36,9 +36,10 @@ import { PerfCounter } from './perf-counter'; import { legacyCC } from '../core/global-exports'; import { Pass } from '../core/renderer'; import { preTransforms } from '../core/math/mat4'; -import { JSB } from '../core/default-constants'; import { Root } from '../core/root'; import { PipelineRuntime } from '../core/pipeline/custom/pipeline'; +import { director, System } from '../core'; +import { Settings, settings } from '../core/settings'; const _characters = '0123456789. '; @@ -92,12 +93,11 @@ const _constants = { textureHeight: 256, }; -export class Profiler { +export class Profiler extends System { /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _stats: IProfilerState | null = null; - public id = '__Profiler__'; private _showFPS = false; @@ -128,6 +128,7 @@ export class Profiler { private lastTime = 0; // update use time constructor () { + super(); if (!TEST) { this._canvas = document.createElement('canvas'); this._ctx = this._canvas.getContext('2d')!; @@ -135,33 +136,13 @@ export class Profiler { } } - public reset () { - this._stats = null; - - this._showFPS = false; - - this._rootNode = null; - this._device = null; - this._swapchain = null; - this._pipeline = null!; - if (this._meshRenderer) { - this._meshRenderer.destroy(); + init () { + const showFPS = !!settings.querySettings(Settings.Category.PROFILING, 'showFPS'); + if (showFPS) { + this.showStats(); + } else { + this.hideStats(); } - this._meshRenderer = null!; - this.digitsData = null!; - this.offsetData = null!; - this.pass = null!; - - this._canvasDone = false; - this._statsDone = false; - this._inited = false; - - this._lineHeight = _constants.textureHeight / (Object.keys(_profileInfo).length + 1); - this._wordHeight = 0; - this._eachNumWidth = 0; - this._totalLines = 0; // total lines to display - - this.lastTime = 0; // update use time } public isShowingStats () { @@ -181,7 +162,7 @@ export class Profiler { legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_DRAW, this.beforeDraw, this); legacyCC.director.off(legacyCC.Director.EVENT_AFTER_DRAW, this.afterDraw, this); this._showFPS = false; - this._pipeline.profiler = null; + director.root!.pipeline.profiler = null; legacyCC.game.config.showFPS = false; } } @@ -190,16 +171,17 @@ export class Profiler { if (!this._showFPS) { if (!this._device) { const root = legacyCC.director.root as Root; - this._device = root.device; + this._device = deviceManager.gfxDevice; this._swapchain = root.mainWindow!.swapchain; this._pipeline = root.pipeline; } - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { this.generateCanvas(); } this.generateStats(); - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { legacyCC.game.once(legacyCC.Game.EVENT_ENGINE_INITED, this.generateNode, this); + legacyCC.game.on(legacyCC.Game.EVENT_RESTART, this.generateNode, this); } else { this._inited = true; } @@ -265,13 +247,13 @@ export class Profiler { let i = 0; for (const id in _profileInfo) { const element = _profileInfo[id]; - if (!EDITOR) this._ctx.fillText(element.desc, 0, i * this._lineHeight); + if (!EDITOR || legacyCC.GAME_VIEW) this._ctx.fillText(element.desc, 0, i * this._lineHeight); element.counter = new PerfCounter(id, element, now); i++; } this._totalLines = i; this._wordHeight = this._totalLines * this._lineHeight / this._canvas.height; - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { for (let j = 0; j < _characters.length; ++j) { const offset = this._ctx.measureText(_characters[j]).width; this._eachNumWidth = Math.max(this._eachNumWidth, offset); @@ -284,7 +266,7 @@ export class Profiler { this._stats = _profileInfo as IProfilerState; this._canvasArr[0] = this._canvas; - if (!EDITOR) this._device!.copyTexImagesToTexture(this._canvasArr, this._texture!, this._regionArr); + if (!EDITOR || legacyCC.GAME_VIEW) this._device!.copyTexImagesToTexture(this._canvasArr, this._texture!, this._regionArr); } public generateNode () { @@ -293,6 +275,7 @@ export class Profiler { } this._rootNode = new Node('PROFILER_NODE'); + this._rootNode._objFlags = legacyCC.Object.Flags.DontSave | legacyCC.Object.Flags.HideInHierarchy; legacyCC.game.addPersistRootNode(this._rootNode); const managerNode = new Node('Profiler_Root'); @@ -346,7 +329,7 @@ export class Profiler { }); const _material = new Material(); - _material.initialize({ effectName: 'profiler' }); + _material.initialize({ effectName: 'util/profiler' }); const pass = this.pass = _material.passes[0]; const hTexture = pass.getBinding('mainTexture'); @@ -409,7 +392,7 @@ export class Profiler { return; } - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { const surfaceTransform = this._swapchain!.surfaceTransform; const clipSpaceSignY = this._device!.capabilities.clipSpaceSignY; if (surfaceTransform !== this.offsetData[3]) { @@ -425,7 +408,11 @@ export class Profiler { this.pass._rootBufferDirty = true; } - if (this._meshRenderer.model) this._pipeline.profiler = this._meshRenderer.model; + if (this._meshRenderer.model) { + director.root!.pipeline.profiler = this._meshRenderer.model; + } else { + director.root!.pipeline.profiler = null; + } const now = performance.now(); (this._stats.render.counter as PerfCounter).start(now); @@ -454,7 +441,7 @@ export class Profiler { (this._stats.tricount.counter as PerfCounter).value = device.numTris; let i = 0; - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { const view = this.digitsData; for (const id in this._stats) { const stat = this._stats[id] as ICounterOption; @@ -474,4 +461,5 @@ export class Profiler { } export const profiler = new Profiler(); +director.registerSystem('profiler', profiler, 0); legacyCC.profiler = profiler; diff --git a/cocos/spine/assembler/simple.ts b/cocos/spine/assembler/simple.ts index a5608d863a..951c115e5b 100644 --- a/cocos/spine/assembler/simple.ts +++ b/cocos/spine/assembler/simple.ts @@ -1,4 +1,27 @@ +/* + Copyright (c) 2020-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 spine from '../lib/spine-core.js'; import { IAssembler } from '../../2d/renderer/base'; @@ -14,10 +37,8 @@ import { legacyCC } from '../../core/global-exports'; import { StaticVBAccessor, StaticVBChunk } from '../../2d/renderer/static-vb-accessor'; import { RenderData } from '../../2d/renderer/render-data'; -const FLAG_BATCH = 0x10; const FLAG_TWO_COLOR = 0x01; -let _handleVal = 0x00; const _quadTriangles = [0, 1, 2, 2, 3, 0]; const _slotColor = new Color(0, 0, 255, 255); const _boneColor = new Color(255, 0, 0, 255); @@ -87,6 +108,7 @@ let _needColor: boolean; let _vertexEffect: spine.VertexEffect | null = null; let _currentMaterial: MaterialInstance | null = null; let _currentTexture: Texture2D | null = null; +const _inv255 = 1.0 / 255.0; function _getSlotMaterial (blendMode: spine.BlendMode) { let src: BlendFactor; @@ -116,7 +138,7 @@ function _getSlotMaterial (blendMode: spine.BlendMode) { function _handleColor (color: FrameColor) { // temp rgb has multiply 255, so need divide 255; _fa = color.fa * _nodeA; - _multiplier = _premultipliedAlpha ? _fa / 255 : 1; + _multiplier = _premultipliedAlpha ? _fa * _inv255 : 1; _r = _nodeR * _multiplier; _g = _nodeG * _multiplier; _b = _nodeB * _multiplier; @@ -124,27 +146,27 @@ function _handleColor (color: FrameColor) { _fr = color.fr * _r; _fg = color.fg * _g; _fb = color.fb * _b; - _finalColor32[0] = _fr / 255.0; - _finalColor32[1] = _fg / 255.0; - _finalColor32[2] = _fb / 255.0; - _finalColor32[3] = _fa / 255.0; + _finalColor32[0] = _fr * _inv255; + _finalColor32[1] = _fg * _inv255; + _finalColor32[2] = _fb * _inv255; + _finalColor32[3] = _fa * _inv255; _dr = color.dr * _r; _dg = color.dg * _g; _db = color.db * _b; _da = _premultipliedAlpha ? 255 : 0; - _darkColor32[0] = _dr / 255.0; - _darkColor32[1] = _dg / 255.0; - _darkColor32[2] = _db / 255.0; - _darkColor32[3] = _da / 255.0; + _darkColor32[0] = _dr * _inv255; + _darkColor32[1] = _dg * _inv255; + _darkColor32[2] = _db * _inv255; + _darkColor32[3] = _da * _inv255; } const _tmpColor4 = new Float32Array(4); function _spineColorToFloat32Array4 (spineColor: spine.Color) { - _tmpColor4[0] = spineColor.r / 255.0; - _tmpColor4[1] = spineColor.g / 255.0; - _tmpColor4[2] = spineColor.b / 255.0; - _tmpColor4[3] = spineColor.a / 255.0; + _tmpColor4[0] = spineColor.r * _inv255; + _tmpColor4[1] = spineColor.g * _inv255; + _tmpColor4[2] = spineColor.b * _inv255; + _tmpColor4[3] = spineColor.a * _inv255; return _tmpColor4; } @@ -241,9 +263,9 @@ function updateComponentRenderData (comp: Skeleton, batcher: Batcher2D) { if (!comp._skeleton) return; const nodeColor = comp.color; - _nodeR = nodeColor.r / 255; - _nodeG = nodeColor.g / 255; - _nodeB = nodeColor.b / 255; + _nodeR = nodeColor.r * _inv255; + _nodeG = nodeColor.g * _inv255; + _nodeB = nodeColor.b * _inv255; _nodeA = comp.node._uiProps.opacity; _useTint = comp.useTint || comp.isAnimationCached(); @@ -261,7 +283,6 @@ function updateComponentRenderData (comp: Skeleton, batcher: Batcher2D) { _mustFlush = true; _premultipliedAlpha = comp.premultipliedAlpha; _multiplier = 1.0; - _handleVal = 0x00; _needColor = false; _vertexEffect = comp._effectDelegate && comp._effectDelegate._vertexEffect as any; @@ -269,23 +290,12 @@ function updateComponentRenderData (comp: Skeleton, batcher: Batcher2D) { _needColor = true; } - if (_useTint) { - _handleVal |= FLAG_TWO_COLOR; - } - - let worldMat: Mat4 | undefined; - if (_comp.enableBatch) { - worldMat = _node.worldMatrix as Mat4; - _mustFlush = false; - _handleVal |= FLAG_BATCH; - } - if (comp.isAnimationCached()) { // Traverse input assembler. - cacheTraverse(worldMat); + cacheTraverse(); } else { if (_vertexEffect) _vertexEffect.begin(comp._skeleton); - realTimeTraverse(batcher, worldMat); + realTimeTraverse(batcher); if (_vertexEffect) _vertexEffect.end(); } // Ensure mesh buffer update @@ -357,7 +367,91 @@ function fillVertices (skeletonColor: spine.Color, } _darkColor.a = _premultipliedAlpha ? 255 : 0; - if (!clipper.isClipping()) { + if (_useTint) { + if (!clipper.isClipping()) { + if (_vertexEffect) { + for (let v = _vertexFloatOffset, n = _vertexFloatOffset + _vertexFloatCount; v < n; v += _perVertexSize) { + _tempPos.x = _vbuf[v]; + _tempPos.y = _vbuf[v + 1]; + _tempUv.x = _vbuf[v + 3]; + _tempUv.y = _vbuf[v + 4]; + _vertexEffect.transform(_tempPos, _tempUv, _finalColor, _darkColor); + + _vbuf[v] = _tempPos.x; // x + _vbuf[v + 1] = _tempPos.y; // y + _vbuf[v + 3] = _tempUv.x; // u + _vbuf[v + 4] = _tempUv.y; // v + + _vbuf.set(_spineColorToFloat32Array4(_finalColor), v + 5); + _vbuf.set(_spineColorToFloat32Array4(_darkColor), v + 9); // dark color + } + } else { + _finalColor32.set(_spineColorToFloat32Array4(_finalColor)); + _darkColor32.set(_spineColorToFloat32Array4(_darkColor)); + + for (let v = _vertexFloatOffset, n = _vertexFloatOffset + _vertexFloatCount; v < n; v += _perVertexSize) { + _vbuf.set(_finalColor32, v + 5); // light color + _vbuf.set(_darkColor32, v + 9); // dark color + } + } + } else { + _perClipVertexSize = _useTint ? 12 : 8; // const + const vertices = _vbuf.subarray(_vertexFloatOffset); + const uvs = _vbuf.subarray(_vertexFloatOffset + 3); + + clipper.clipTriangles(vertices, _vertexFloatCount, + _ibuf.subarray(_indexOffset), _indexCount, uvs, _finalColor, _darkColor, _useTint, + _perVertexSize); + const clippedVertices = clipper.clippedVertices; + const clippedTriangles = clipper.clippedTriangles; + + // Update vertex and index count, reallocate vertex buffer chunk if needed + updateChunkForClip(clippedVertices, clippedTriangles); + + // fill indices + if (clippedTriangles.length > 0) { + _ibuf.set(clippedTriangles, _indexOffset); + } + + // fill vertices contain x y u v light color dark color + if (_vertexEffect) { + for (let v = 0, n = clippedVertices.length, offset = _vertexFloatOffset; v < n; v += _perClipVertexSize, offset += _perVertexSize) { + _tempPos.x = clippedVertices[v]; + _tempPos.y = clippedVertices[v + 1]; + _finalColor.set(clippedVertices[v + 2], clippedVertices[v + 3], clippedVertices[v + 4], clippedVertices[v + 5]); + _tempUv.x = clippedVertices[v + 6]; + _tempUv.y = clippedVertices[v + 7]; + _darkColor.set(clippedVertices[v + 8], clippedVertices[v + 9], clippedVertices[v + 10], clippedVertices[v + 11]); + _vertexEffect.transform(_tempPos, _tempUv, _finalColor, _darkColor); + + _vbuf[offset] = _tempPos.x; // x + _vbuf[offset + 1] = _tempPos.y; // y + _vbuf[offset + 3] = _tempUv.x; // u + _vbuf[offset + 4] = _tempUv.y; // v + _vbuf.set(_spineColorToFloat32Array4(_finalColor), offset + 5); + _vbuf.set(_spineColorToFloat32Array4(_darkColor), offset + 9); + } + } else { + // x y r g b a u v (rr gg bb aa) + for (let v = 0, n = clippedVertices.length, offset = _vertexFloatOffset; v < n; v += _perClipVertexSize, offset += _perVertexSize) { + _vbuf[offset] = clippedVertices[v]; // x + _vbuf[offset + 1] = clippedVertices[v + 1]; // y + _vbuf[offset + 3] = clippedVertices[v + 6]; // u + _vbuf[offset + 4] = clippedVertices[v + 7]; // v + + _vbuf[offset + 5] = clippedVertices[v + 2] * _inv255; + _vbuf[offset + 6] = clippedVertices[v + 3] * _inv255; + _vbuf[offset + 7] = clippedVertices[v + 4] * _inv255; + _vbuf[offset + 8] = clippedVertices[v + 5] * _inv255; + + _vbuf[offset + 9] = clippedVertices[v + 8] * _inv255; + _vbuf[offset + 10] = clippedVertices[v + 9] * _inv255; + _vbuf[offset + 11] = clippedVertices[v + 10] * _inv255; + _vbuf[offset + 12] = clippedVertices[v + 11] * _inv255; + } + } + } + } else if (!clipper.isClipping()) { if (_vertexEffect) { for (let v = _vertexFloatOffset, n = _vertexFloatOffset + _vertexFloatCount; v < n; v += _perVertexSize) { _tempPos.x = _vbuf[v]; @@ -372,9 +466,6 @@ function fillVertices (skeletonColor: spine.Color, _vbuf[v + 4] = _tempUv.y; // v _vbuf.set(_spineColorToFloat32Array4(_finalColor), v + 5); - if (_useTint) { - _vbuf.set(_spineColorToFloat32Array4(_darkColor), v + 9); // dark color - } } } else { _finalColor32.set(_spineColorToFloat32Array4(_finalColor)); @@ -382,9 +473,6 @@ function fillVertices (skeletonColor: spine.Color, for (let v = _vertexFloatOffset, n = _vertexFloatOffset + _vertexFloatCount; v < n; v += _perVertexSize) { _vbuf.set(_finalColor32, v + 5); // light color - if (_useTint) { - _vbuf.set(_darkColor32, v + 9); // dark color - } } } } else { @@ -414,11 +502,7 @@ function fillVertices (skeletonColor: spine.Color, _finalColor.set(clippedVertices[v + 2], clippedVertices[v + 3], clippedVertices[v + 4], clippedVertices[v + 5]); _tempUv.x = clippedVertices[v + 6]; _tempUv.y = clippedVertices[v + 7]; - if (_useTint) { - _darkColor.set(clippedVertices[v + 8], clippedVertices[v + 9], clippedVertices[v + 10], clippedVertices[v + 11]); - } else { - _darkColor.set(0, 0, 0, 0); - } + _darkColor.set(0, 0, 0, 0); _vertexEffect.transform(_tempPos, _tempUv, _finalColor, _darkColor); _vbuf[offset] = _tempPos.x; // x @@ -426,9 +510,6 @@ function fillVertices (skeletonColor: spine.Color, _vbuf[offset + 3] = _tempUv.x; // u _vbuf[offset + 4] = _tempUv.y; // v _vbuf.set(_spineColorToFloat32Array4(_finalColor), offset + 5); - if (_useTint) { - _vbuf.set(_spineColorToFloat32Array4(_darkColor), offset + 9); - } } } else { // x y r g b a u v (rr gg bb aa) @@ -438,23 +519,16 @@ function fillVertices (skeletonColor: spine.Color, _vbuf[offset + 3] = clippedVertices[v + 6]; // u _vbuf[offset + 4] = clippedVertices[v + 7]; // v - _vbuf[offset + 5] = clippedVertices[v + 2] / 255.0; - _vbuf[offset + 6] = clippedVertices[v + 3] / 255.0; - _vbuf[offset + 7] = clippedVertices[v + 4] / 255.0; - _vbuf[offset + 8] = clippedVertices[v + 5] / 255.0; - - if (_useTint) { - _vbuf[offset + 9] = clippedVertices[v + 8] / 255.0; - _vbuf[offset + 10] = clippedVertices[v + 9] / 255.0; - _vbuf[offset + 11] = clippedVertices[v + 10] / 255.0; - _vbuf[offset + 12] = clippedVertices[v + 11] / 255.0; - } + _vbuf[offset + 5] = clippedVertices[v + 2] * _inv255; + _vbuf[offset + 6] = clippedVertices[v + 3] * _inv255; + _vbuf[offset + 7] = clippedVertices[v + 4] * _inv255; + _vbuf[offset + 8] = clippedVertices[v + 5] * _inv255; } } } } -function realTimeTraverse (batcher: Batcher2D, worldMat?: Mat4) { +function realTimeTraverse (batcher: Batcher2D) { const rd = _renderData!; _vbuf = rd.chunk.vb; _ibuf = rd.indices!; @@ -637,21 +711,6 @@ function realTimeTraverse (batcher: Batcher2D, worldMat?: Mat4) { for (let ii = _indexOffset, nn = _indexOffset + _indexCount; ii < nn; ii++) { _ibuf[ii] += _vertexOffset + chunkOffset; } - - if (worldMat) { - _m00 = worldMat.m00; - _m04 = worldMat.m04; - _m12 = worldMat.m12; - _m01 = worldMat.m01; - _m05 = worldMat.m05; - _m13 = worldMat.m13; - for (let ii = _vertexFloatOffset, nn = _vertexFloatOffset + _vertexFloatCount; ii < nn; ii += _perVertexSize) { - _x = _vbuf[ii]; - _y = _vbuf[ii + 1]; - _vbuf[ii] = _x * _m00 + _y * _m04 + _m12; - _vbuf[ii + 1] = _x * _m01 + _y * _m05 + _m13; - } - } } _vertexFloatOffset += _vertexFloatCount; _vertexOffset += _vertexCount; @@ -694,7 +753,7 @@ function realTimeTraverse (batcher: Batcher2D, worldMat?: Mat4) { } } -function cacheTraverse (worldMat?: Mat4) { +function cacheTraverse () { const frame = _comp!._curFrame; if (!frame) return; @@ -715,18 +774,6 @@ function cacheTraverse (worldMat?: Mat4) { let frameVFOffset = 0; let frameIndexOffset = 0; let segVFCount = 0; - if (worldMat) { - _m00 = worldMat.m00; - _m01 = worldMat.m01; - _m04 = worldMat.m04; - _m05 = worldMat.m05; - _m12 = worldMat.m12; - _m13 = worldMat.m13; - } - - const justTranslate = _m00 === 1 && _m01 === 0 && _m04 === 0 && _m05 === 1; - const needBatch = (_handleVal & FLAG_BATCH); - const calcTranslate = needBatch && justTranslate; const colors = frame.colors; let colorOffset = 0; @@ -769,21 +816,6 @@ function cacheTraverse (worldMat?: Mat4) { segVFCount = segInfo.vfCount; vbuf.set(vertices.subarray(frameVFOffset, frameVFOffset + segVFCount), frameVFOffset); - // Update local position to world position - if (calcTranslate) { - for (let ii = frameVFOffset, il = frameVFOffset + segVFCount; ii < il; ii += _perVertexSize) { - vbuf[ii] += _m12; - vbuf[ii + 1] += _m13; - } - } else if (needBatch) { - for (let ii = frameVFOffset, il = frameVFOffset + segVFCount; ii < il; ii += _perVertexSize) { - _x = vbuf[ii]; - _y = vbuf[ii + 1]; - vbuf[ii] = _x * _m00 + _y * _m04 + _m12; - vbuf[ii + 1] = _x * _m01 + _y * _m05 + _m13; - } - } - // Update color if (_needColor) { // handle color diff --git a/cocos/spine/attach-util.ts b/cocos/spine/attach-util.ts index ef5a4445d4..22c215085e 100644 --- a/cocos/spine/attach-util.ts +++ b/cocos/spine/attach-util.ts @@ -1,9 +1,29 @@ -/** - * @packageDocumentation - * @module spine +/* + Copyright (c) 2020-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 { Mat4, Vec3, Node } from '../core'; +import { Mat4, Node } from '../core'; import { Skeleton } from './skeleton'; import spine from './lib/spine-core.js'; import { FrameBoneInfo } from './skeleton-cache'; diff --git a/cocos/spine/category.json b/cocos/spine/category.json new file mode 100644 index 0000000000..bc9e08b52f --- /dev/null +++ b/cocos/spine/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "Spine", + "en": "Spine" + }, + "description": { + "zh": "Spine Skeleton 组件支持 Spine 官方工具导出的数据格式,并对 Spine(骨骼动画)资源进行渲染和播放。", + "en": "The Spine Skeleton components support the data format exported by the official Spine tools, and renders and plays Spine assets." + } +} \ No newline at end of file diff --git a/native/cocos/core/builtin/Effects.h b/cocos/spine/deprecated.ts similarity index 77% rename from native/cocos/core/builtin/Effects.h rename to cocos/spine/deprecated.ts index 8ddbcd097d..ab8bf92610 100644 --- a/native/cocos/core/builtin/Effects.h +++ b/cocos/spine/deprecated.ts @@ -1,7 +1,7 @@ -/**************************************************************************** - Copyright (c) 2021 Xiamen Yaji Software Co., Ltd. +/* + Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. - http://www.cocos.com + 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, @@ -21,13 +21,14 @@ 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. -****************************************************************************/ + */ -#pragma once +import { removeProperty } from '../core/utils/x-deprecated'; +import { Skeleton } from './skeleton'; -#include "cocos/base/StringUtil.h" -namespace cc { - -extern const GzipedString BUILTIN_EFFECTS; - -} +removeProperty(Skeleton.prototype, 'Skeleton', [ + { + name: 'enableBatch', + suggest: 'Not support batch render mode', + }, +]); diff --git a/cocos/spine/index.jsb.ts b/cocos/spine/index.jsb.ts index 72cf3e9ce3..bf974f52ad 100644 --- a/cocos/spine/index.jsb.ts +++ b/cocos/spine/index.jsb.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module spine - */ - import { ccenum } from '../core'; import { legacyCC } from '../core/global-exports'; diff --git a/cocos/spine/index.ts b/cocos/spine/index.ts index 048f1455c8..bd25ed13d3 100644 --- a/cocos/spine/index.ts +++ b/cocos/spine/index.ts @@ -1,6 +1,26 @@ -/** - * @packageDocumentation - * @module spine +/* + Copyright (c) 2020-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 { ccenum } from '../core'; @@ -29,19 +49,16 @@ export * from './skeleton-data'; export * from './skeleton-texture'; export * from './vertex-effect-delegate'; export * from './assembler'; +export * from './deprecated'; export { spine }; /** * @en - * The global time scale of Spine. + * The attachment type of spine. It contains three type: REGION(0), BOUNDING_BOX(1), MESH(2) and SKINNED_MESH * @zh - * Spine 全局时间缩放率。 - * @example - * sp.timeScale = 0.8; + * Attachment 类型枚举。类型包括 REGION,BOUNDING_BOX,MESH,SKINNED_MESH */ - -// The attachment type of spine. It contains three type: REGION(0), BOUNDING_BOX(1), MESH(2) and SKINNED_MESH. export enum ATTACHMENT_TYPE { REGION = 0, BOUNDING_BOX = 1, diff --git a/cocos/spine/skeleton-cache.ts b/cocos/spine/skeleton-cache.ts index f55f1469d2..525c332dc5 100644 --- a/cocos/spine/skeleton-cache.ts +++ b/cocos/spine/skeleton-cache.ts @@ -1,6 +1,26 @@ -/** - * @packageDocumentation - * @module spine +/* + Copyright (c) 2020-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 { TrackEntryListeners } from './track-entry-listeners'; @@ -100,7 +120,7 @@ export class AnimationCache { public maxIndexCount = 0; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _privateMode = false; protected _inited = false; diff --git a/cocos/spine/skeleton-data.ts b/cocos/spine/skeleton-data.ts index bbc0d0e07d..1d3063231b 100644 --- a/cocos/spine/skeleton-data.ts +++ b/cocos/spine/skeleton-data.ts @@ -1,6 +1,26 @@ -/** - * @packageDocumentation - * @module spine +/* + Copyright (c) 2020-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 { EDITOR } from 'internal:constants'; @@ -21,7 +41,9 @@ import { legacyCC } from '../core/global-exports'; @ccclass('sp.SkeletonData') export class SkeletonData extends Asset { /** - * @legacyPublic + * @en See http://en.esotericsoftware.com/spine-json-format + * @zh 可查看 Spine 官方文档 http://zh.esotericsoftware.com/spine-json-format + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ @serializable public _skeletonJson: spine.SkeletonJson | null = null; @@ -67,6 +89,8 @@ export class SkeletonData extends Asset { } /** + * @en Texture array + * @zh 纹理数组 * @property {Texture2D[]} textures */ @@ -98,7 +122,7 @@ export class SkeletonData extends Asset { public scale = 1; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ get _nativeAsset (): ArrayBuffer { return this._buffer!; @@ -141,14 +165,14 @@ export class SkeletonData extends Asset { public reset () { this._skeletonCache = null; this._atlasCache = null; - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { this._skinsEnum = null; this._animsEnum = null; } } public resetEnums () { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { this._skinsEnum = null; this._animsEnum = null; } diff --git a/cocos/spine/skeleton-system.ts b/cocos/spine/skeleton-system.ts index 9ca4ec82e4..60a3bcd5a3 100644 --- a/cocos/spine/skeleton-system.ts +++ b/cocos/spine/skeleton-system.ts @@ -1,7 +1,32 @@ +/* + Copyright (c) 2020-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 { director } from '../core/director'; import { System } from '../core/components'; import { Skeleton } from './skeleton'; -import { errorID } from '../core'; +import { legacyCC } from '../core/global-exports'; export class SkeletonSystem extends System { /** @@ -56,4 +81,14 @@ export class SkeletonSystem extends System { skeleton.updateAnimation(dt); }); } + + public prepareRenderData () { + if (!this._skeletons) { + return; + } + this._skeletons.forEach((skeleton) => { + skeleton.markForUpdateRenderData(); + }); + } } +legacyCC.internal.SpineSkeletonSystem = SkeletonSystem; diff --git a/cocos/spine/skeleton-texture.ts b/cocos/spine/skeleton-texture.ts index fdd7bdcc99..e2e6e47361 100644 --- a/cocos/spine/skeleton-texture.ts +++ b/cocos/spine/skeleton-texture.ts @@ -1,6 +1,26 @@ -/** - * @packageDocumentation - * @module spine +/* + Copyright (c) 2020-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 { Material, Texture2D } from '../core'; diff --git a/cocos/spine/skeleton.ts b/cocos/spine/skeleton.ts index 52b7d50915..964e64a7ea 100644 --- a/cocos/spine/skeleton.ts +++ b/cocos/spine/skeleton.ts @@ -1,15 +1,35 @@ -/** - * @packageDocumentation - * @module spine +/* + Copyright (c) 2020-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 { EDITOR } from 'internal:constants'; +import { EDITOR, JSB } from 'internal:constants'; import { TrackEntryListeners } from './track-entry-listeners'; import spine from './lib/spine-core.js'; import SkeletonCache, { AnimationCache, AnimationFrame } from './skeleton-cache'; import { AttachUtil } from './attach-util'; import { ccclass, executeInEditMode, help, menu } from '../core/data/class-decorator'; -import { Renderable2D } from '../2d/framework/renderable-2d'; +import { UIRenderer } from '../2d/framework/ui-renderer'; import { Node, CCClass, CCObject, Color, Enum, Material, Texture2D, builtinResMgr, ccenum, errorID, logID, warn, RecyclePool } from '../core'; import { displayName, displayOrder, editable, override, serializable, tooltip, type, visible } from '../core/data/decorators'; import { SkeletonData } from './skeleton-data'; @@ -21,6 +41,9 @@ import { BlendFactor, BlendOp } from '../core/gfx'; import { legacyCC } from '../core/global-exports'; import { SkeletonSystem } from './skeleton-system'; import { Batcher2D } from '../2d/renderer/batcher-2d'; +import { RenderEntity, RenderEntityType } from '../2d/renderer/render-entity'; +import { RenderDrawInfo } from '../2d/renderer/render-draw-info'; +import { director } from '../core/director'; export const timeScale = 1.0; @@ -125,13 +148,13 @@ js.setClassAlias(SpineSocket, 'sp.Skeleton.SpineSocket'); * 多个 Skeleton 可以使用相同的骨骼数据,其中包括所有的动画,皮肤和 attachments。 * * @class Skeleton - * @extends Renderable2D + * @extends UIRenderer */ @ccclass('sp.Skeleton') @help('i18n:sp.Skeleton') @menu('Spine/Skeleton') @executeInEditMode -export class Skeleton extends Renderable2D { +export class Skeleton extends UIRenderer { public static SpineSocket = SpineSocket; public static AnimationCacheMode = AnimationCacheMode; @@ -147,6 +170,8 @@ export class Skeleton extends Renderable2D { set customMaterial (val) { this._customMaterial = val; this._cleanMaterialCache(); + this.setMaterial(this._customMaterial, 0); + this.markForUpdateRenderData(); } /** @@ -187,7 +212,7 @@ export class Skeleton extends Renderable2D { this._needUpdateSkeltonData = true; this.defaultSkin = ''; this.defaultAnimation = ''; - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { this._refreshInspector(); } this._updateSkeletonData(); @@ -257,7 +282,7 @@ export class Skeleton extends Renderable2D { if (skinName !== undefined) { this.defaultSkin = skinName; this.setSkin(this.defaultSkin); - if (EDITOR /* && !cc.engine.isPlaying */) { + if (EDITOR && !legacyCC.GAME_VIEW /* && !cc.engine.isPlaying */) { this._refreshInspector(); this.markForUpdateRenderData(); } @@ -274,7 +299,7 @@ export class Skeleton extends Renderable2D { @type(DefaultAnimsEnum) @tooltip('i18n:COMPONENT.skeleton.animation') get _animationIndex () { - const animationName = EDITOR ? this.defaultAnimation : this.animation; + const animationName = EDITOR && !legacyCC.GAME_VIEW ? this.defaultAnimation : this.animation; if (this.skeletonData) { if (animationName) { const animsEnum = this.skeletonData.getAnimsEnum(); @@ -306,7 +331,7 @@ export class Skeleton extends Renderable2D { const animName = animsEnum[value]; if (animName !== undefined) { this.animation = animName; - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { this.defaultAnimation = animName; this._refreshInspector(); } else { @@ -432,7 +457,7 @@ export class Skeleton extends Renderable2D { } set sockets (val: SpineSocket[]) { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { this._verifySockets(val); } this._sockets = val; @@ -441,24 +466,6 @@ export class Skeleton extends Renderable2D { } get socketNodes () { return this._socketNodes; } - - /* - * @en Enabled batch model, if skeleton is complex, do not enable batch, or will lower performance. - * @zh 开启合批,如果渲染大量相同纹理,且结构简单的骨骼动画,开启合批可以降低drawcall,否则请不要开启,cpu消耗会上升。 - */ - // @tooltip('i18n:COMPONENT.skeleton.enabled_batch') - // get enableBatch () { return this._enableBatch; } - // set enableBatch (value) { - // if (value != this._enableBatch) { - // this._enableBatch = value; - // this._updateBatch(); - // } - // } - - // @serializable - // private _enableBatch: boolean = true; - - public enableBatch = false; // Frame cache /** * @internal @@ -574,8 +581,10 @@ export class Skeleton extends Renderable2D { // 由于 spine 的 skin 是无法二次替换的,所以只能设置默认的 skin /** - * @en The name of default skin. - * @zh 默认的皮肤名称。 + * @en + * The name of default skin. + * @zh + * 默认的皮肤名称。 * @property {String} defaultSkin */ @serializable @@ -583,8 +592,10 @@ export class Skeleton extends Renderable2D { protected defaultSkin = ''; /** - * @en The name of default animation. - * @zh 默认的动画名称。 + * @en + * The name of default animation. + * @zh + * 默认的动画名称。 * @property {String} defaultAnimation */ @visible(false) @@ -609,7 +620,15 @@ export class Skeleton extends Renderable2D { protected _socketNodes: Map = new Map(); protected _cachedSockets: Map = new Map(); + 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]; + } // CONSTRUCTOR constructor () { super(); @@ -645,7 +664,7 @@ export class Skeleton extends Renderable2D { uiTrans.setContentSize(skeletonData.width, skeletonData.height); } - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { if (this._cacheMode === AnimationCacheMode.SHARED_CACHE) { this._skeletonCache = SkeletonCache.sharedCache; } else if (this._cacheMode === AnimationCacheMode.PRIVATE_CACHE) { @@ -708,7 +727,7 @@ export class Skeleton extends Renderable2D { // IMPLEMENT public __preload () { super.__preload(); - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { const Flags = CCObject.Flags; this._objFlags |= (Flags.IsAnchorLocked | Flags.IsSizeLocked); // this._refreshInspector(); @@ -728,7 +747,7 @@ export class Skeleton extends Renderable2D { this._indexBoneSockets(); this._updateSocketBindings(); - if (EDITOR) { this._refreshInspector(); } + if (EDITOR && !legacyCC.GAME_VIEW) { this._refreshInspector(); } } /** @@ -758,13 +777,13 @@ export class Skeleton extends Renderable2D { * @zh 当前是否处于缓存模式。 */ public isAnimationCached () { - if (EDITOR) return false; + if (EDITOR && !legacyCC.GAME_VIEW) return false; return this._cacheMode !== AnimationCacheMode.REALTIME; } public updateAnimation (dt: number) { this.markForUpdateRenderData(); - if (EDITOR) return; + if (EDITOR && !legacyCC.GAME_VIEW) return; if (this.paused) return; dt *= this._timeScale * timeScale; @@ -1143,7 +1162,7 @@ export class Skeleton extends Renderable2D { warn('\'clearTrack\' interface can not be invoked in cached mode.'); } else if (this._state) { this._state.clearTrack(trackIndex); - if (EDITOR/* && !cc.engine.isPlaying */) { + if (EDITOR && !legacyCC.GAME_VIEW/* && !cc.engine.isPlaying */) { this._state.update(0); } } @@ -1359,7 +1378,11 @@ export class Skeleton extends Renderable2D { }], }, }); - inst.recompileShaders({ TWO_COLORED: useTwoColor, USE_LOCAL: true }); + if (JSB) { + inst.recompileShaders({ TWO_COLORED: useTwoColor, USE_LOCAL: false }); + } else { + inst.recompileShaders({ TWO_COLORED: useTwoColor, USE_LOCAL: true }); + } return inst; } @@ -1367,7 +1390,6 @@ export class Skeleton extends Renderable2D { // call markForUpdateRenderData to make sure renderData will be re-built. public onRestore () { this.updateMaterial(); - this._renderFlag = this._canRender(); this.markForUpdateRenderData(); } @@ -1410,8 +1432,8 @@ export class Skeleton extends Renderable2D { } protected _render (batcher: Batcher2D) { - if (this._renderData && this._drawList) { - const rd = this._renderData; + if (this.renderData && this._drawList) { + const rd = this.renderData; const chunk = rd.chunk; const accessor = chunk.vertexAccessor; const meshBuffer = rd.getMeshBuffer()!; @@ -1483,14 +1505,14 @@ export class Skeleton extends Renderable2D { if (!frameCache.isCompleted) { frameCache.updateToFrame(frameIdx); // Update render data size if needed - if (this._renderData - && (this._renderData.vertexCount < frameCache.maxVertexCount - || this._renderData.indexCount < frameCache.maxIndexCount)) { + if (this.renderData + && (this.renderData.vertexCount < frameCache.maxVertexCount + || this.renderData.indexCount < frameCache.maxIndexCount)) { this.maxVertexCount = frameCache.maxVertexCount > this.maxVertexCount ? frameCache.maxVertexCount : this.maxVertexCount; this.maxIndexCount = frameCache.maxIndexCount > this.maxIndexCount ? frameCache.maxIndexCount : this.maxIndexCount; - this._renderData.resize(this.maxVertexCount, this.maxIndexCount); - if (!this._renderData.indices || this.maxIndexCount > this._renderData.indices.length) { - this._renderData.indices = new Uint16Array(this.maxIndexCount); + this.renderData.resize(this.maxVertexCount, this.maxIndexCount); + if (!this.renderData.indices || this.maxIndexCount > this.renderData.indices.length) { + this.renderData.indices = new Uint16Array(this.maxIndexCount); } } } @@ -1720,6 +1742,10 @@ export class Skeleton extends Renderable2D { } this._materialCache = {}; } + + protected createRenderEntity () { + return new RenderEntity(RenderEntityType.DYNAMIC); + } } legacyCC.internal.SpineSkeleton = Skeleton; diff --git a/cocos/spine/track-entry-listeners.ts b/cocos/spine/track-entry-listeners.ts index c9bc4fdfec..c2af46bd42 100644 --- a/cocos/spine/track-entry-listeners.ts +++ b/cocos/spine/track-entry-listeners.ts @@ -1,6 +1,26 @@ -/** - * @packageDocumentation - * @module spine +/* + Copyright (c) 2020-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 spine from './lib/spine-core.js'; diff --git a/cocos/spine/vertex-effect-delegate.ts b/cocos/spine/vertex-effect-delegate.ts index c1f38ee4c0..d642564fa7 100644 --- a/cocos/spine/vertex-effect-delegate.ts +++ b/cocos/spine/vertex-effect-delegate.ts @@ -1,6 +1,26 @@ -/** - * @packageDocumentation - * @module spine +/* + Copyright (c) 2020-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 spine from './lib/spine-core.js'; diff --git a/cocos/terrain/category.json b/cocos/terrain/category.json index e84e2cc83d..2a739d5ccf 100644 --- a/cocos/terrain/category.json +++ b/cocos/terrain/category.json @@ -4,7 +4,7 @@ "en": "Terrain" }, "description": { - "zh": "地形", - "en": "Terrain" + "zh": "地形系统以一种高效的方式来展示大自然的山川地貌。开发者可以很方便的使用画刷来雕刻出盆地、山脉、峡谷、平原等地貌。", + "en": "The terrain system displays the mountainous landscape of nature in an efficient way. Developers can easily use a brush to sculpt basins, mountains, valleys, plains and other landforms." } } \ No newline at end of file diff --git a/cocos/terrain/height-field.ts b/cocos/terrain/height-field.ts index f232694a59..2f2176afb6 100644 --- a/cocos/terrain/height-field.ts +++ b/cocos/terrain/height-field.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module terrain - */ - import { clamp } from '../core/math'; export class HeightField { diff --git a/cocos/terrain/terrain-asset.ts b/cocos/terrain/terrain-asset.ts index eaaaf9f8af..d37cc1191a 100644 --- a/cocos/terrain/terrain-asset.ts +++ b/cocos/terrain/terrain-asset.ts @@ -23,13 +23,8 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module terrain - */ import { ccclass, serializable } from 'cc.decorator'; import { Asset, Texture2D } from '../core/assets'; -import { legacyCC } from '../core/global-exports'; export const TERRAIN_MAX_LEVELS = 4; export const TERRAIN_MAX_BLEND_LAYERS = 4; @@ -251,7 +246,7 @@ export class TerrainAsset extends Asset { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ get _nativeAsset (): ArrayBuffer { return this._data!.buffer; @@ -408,14 +403,14 @@ export class TerrainAsset extends Asset { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _setNativeData (_nativeData: Uint8Array) { this._data = _nativeData; } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _loadNativeData (_nativeData: Uint8Array) { if (!_nativeData || _nativeData.length === 0) { @@ -489,7 +484,7 @@ export class TerrainAsset extends Asset { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _exportNativeData (): Uint8Array { const stream = new TerrainBuffer(); @@ -551,7 +546,7 @@ export class TerrainAsset extends Asset { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _exportDefaultNativeData (): Uint8Array { const stream = new TerrainBuffer(); diff --git a/cocos/terrain/terrain-lod.ts b/cocos/terrain/terrain-lod.ts index bab34745e0..02bab8ca67 100644 --- a/cocos/terrain/terrain-lod.ts +++ b/cocos/terrain/terrain-lod.ts @@ -63,19 +63,19 @@ export class TerrainLod { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _bodyIndexPool: TerrainIndexPool[]; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _connecterIndexPool: TerrainIndexPool[]; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _indexMap: TerrainIndexData[] = []; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _indexBuffer: Uint16Array = new Uint16Array(); diff --git a/cocos/terrain/terrain.ts b/cocos/terrain/terrain.ts index f2c5eafe2d..393986e16c 100644 --- a/cocos/terrain/terrain.ts +++ b/cocos/terrain/terrain.ts @@ -23,14 +23,10 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module terrain - */ import { ccclass, disallowMultiple, executeInEditMode, help, visible, type, serializable, editable, disallowAnimation } from 'cc.decorator'; import { JSB } from 'internal:constants'; import { builtinResMgr } from '../core/builtin'; -import { RenderableComponent } from '../core/components/renderable-component'; +import { ModelRenderer } from '../core/components/model-renderer'; import { EffectAsset, Texture2D } from '../core/assets'; import { Filter, PixelFormat, WrapMode } from '../core/assets/asset-enum'; import { Material } from '../core/assets/material'; @@ -38,7 +34,7 @@ import { RenderingSubMesh } from '../core/assets/rendering-sub-mesh'; import { Component } from '../core/components'; import { CCObject, isValid } from '../core/data/object'; import { director } from '../core/director'; -import { AttributeName, BufferUsageBit, Format, MemoryUsageBit, PrimitiveMode, Device, Attribute, Buffer, BufferInfo } from '../core/gfx'; +import { AttributeName, BufferUsageBit, Format, MemoryUsageBit, PrimitiveMode, Device, Attribute, Buffer, BufferInfo, deviceManager } from '../core/gfx'; import { clamp, Rect, Size, Vec2, Vec3, Vec4 } from '../core/math'; import { MacroRecord } from '../core/renderer/core/pass-utils'; import { Pass, scene } from '../core/renderer'; @@ -178,29 +174,29 @@ export class TerrainLayer { * @en Terrain renderable * @zh 地形渲染组件 */ -class TerrainRenderable extends RenderableComponent { +class TerrainRenderable extends ModelRenderer { /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _model: scene.Model | null = null; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _meshData: RenderingSubMesh | null = null; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _brushPass: Pass | null = null; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _brushMaterial: Material | null = null; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _currentMaterial: Material | null = null; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _currentMaterialLayers = 0; @@ -215,7 +211,7 @@ class TerrainRenderable extends RenderableComponent { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _destroyModel () { // this._invalidMaterial(); @@ -226,7 +222,7 @@ class TerrainRenderable extends RenderableComponent { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _invalidMaterial () { if (this._currentMaterial == null) { @@ -243,7 +239,7 @@ class TerrainRenderable extends RenderableComponent { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _updateMaterial (block: TerrainBlock, init: boolean) { if (this._meshData == null || this._model == null) { @@ -289,7 +285,7 @@ class TerrainRenderable extends RenderableComponent { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _onMaterialModified (idx: number, mtl: Material|null) { if (this._model == null) { @@ -397,7 +393,7 @@ export class TerrainBlock { ]; this._renderable._meshData = new RenderingSubMesh([vertexBuffer], gfxAttributes, - PrimitiveMode.TRIANGLE_LIST, this._terrain._getSharedIndexBuffer()); + PrimitiveMode.TRIANGLE_LIST, this._terrain._getSharedIndexBuffer(), null, false); this._renderable._model = (legacyCC.director.root as Root).createModel(scene.Model); this._renderable._model.createBoundingShape(this._bbMin, this._bbMax); this._renderable._model.node = this._renderable._model.transform = this._node; @@ -695,8 +691,8 @@ export class TerrainBlock { } /** - * @en 地形块的可见性 - * @zh block visible + * @zh 地形块的可见性 + * @en The visibility of the block */ set visible (val) { if (this._renderable._model !== null) { @@ -792,7 +788,7 @@ export class TerrainBlock { public _getMaterialDefines (nlayers: number): MacroRecord { return { LAYERS: nlayers + 1, - USE_LIGHTMAP: this.lightmap !== null ? 1 : 0, + CC_USE_LIGHTMAP: this.lightmap !== null ? 1 : 0, USE_NORMALMAP: this._terrain.useNormalMap ? 1 : 0, USE_PBR: this._terrain.usePBR ? 1 : 0, // CC_RECEIVE_SHADOW: this._terrain.receiveShadow ? 1 : 0, @@ -869,7 +865,7 @@ export class TerrainBlock { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _updateLightmap (info: TerrainBlockLightmapInfo) { this._lightmapInfo = info; @@ -877,7 +873,7 @@ export class TerrainBlock { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _updateLod () { const key = new TerrainLodKey(); @@ -928,7 +924,7 @@ export class TerrainBlock { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _resetLod () { const key = new TerrainLodKey(); @@ -947,7 +943,7 @@ export class TerrainBlock { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _updateIndexBuffer () { if (this._renderable._meshData === null) { @@ -1221,7 +1217,7 @@ export class Terrain extends Component { } // Ensure device is created - if (legacyCC.director.root.device) { + if (deviceManager.gfxDevice) { // rebuild this._buildImp(); } @@ -1229,7 +1225,7 @@ export class Terrain extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public get _asset () { return this.__asset; @@ -1462,6 +1458,9 @@ export class Terrain extends Component { } this._blocks = []; + // reset lightmap + this._resetLightmap(false); + // build layer buffer this._rebuildLayerBuffer(info); @@ -1577,7 +1576,7 @@ export class Terrain extends Component { public getEffectAsset () { if (this._effectAsset === null) { - return legacyCC.EffectAsset.get('terrain') as EffectAsset; + return legacyCC.EffectAsset.get('builtin-terrain') as EffectAsset; } return this._effectAsset; @@ -1778,7 +1777,7 @@ export class Terrain extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _setNormal (i: number, j: number, n: Vec3) { const index = j * this.vertexCount[0] + i; @@ -2091,33 +2090,42 @@ export class Terrain extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.1, this is an engine private interface that will be removed in the future. + */ + public _createSharedIndexBuffer () { + // initialize shared index buffer + const gfxDevice = deviceManager.gfxDevice; + const gfxBuffer = gfxDevice.createBuffer(new BufferInfo( + BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.DEVICE, + Uint16Array.BYTES_PER_ELEMENT * this._lod._indexBuffer.length, + Uint16Array.BYTES_PER_ELEMENT, + )); + gfxBuffer.update(this._lod._indexBuffer); + + return gfxBuffer; + } + + /** + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _getSharedIndexBuffer () { if (this._sharedIndexBuffer == null) { - // initialize shared index buffer - const gfxDevice = legacyCC.director.root.device as Device; - this._sharedIndexBuffer = gfxDevice.createBuffer(new BufferInfo( - BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, - MemoryUsageBit.DEVICE, - Uint16Array.BYTES_PER_ELEMENT * this._lod._indexBuffer.length, - Uint16Array.BYTES_PER_ELEMENT, - )); - this._sharedIndexBuffer.update(this._lod._indexBuffer); + this._sharedIndexBuffer = this._createSharedIndexBuffer(); } return this._sharedIndexBuffer; } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _getIndexData (key: TerrainLodKey) { return this._lod.getIndexData(key); } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _resetLightmap (enble: boolean) { this._lightmapInfos.length = 0; @@ -2129,7 +2137,7 @@ export class Terrain extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _updateLightmap (blockId: number, tex: Texture2D|null, uOff: number, vOff: number, uScale: number, vScale: number) { this._lightmapInfos[blockId].texture = tex; @@ -2141,7 +2149,7 @@ export class Terrain extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _getLightmapInfo (i: number, j: number) { const index = j * this._blockCount[0] + i; @@ -2149,7 +2157,7 @@ export class Terrain extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _calcNormal (x: number, z: number) { let flip = 1; @@ -2184,7 +2192,7 @@ export class Terrain extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _buildNormals () { let index = 0; @@ -2206,7 +2214,7 @@ export class Terrain extends Component { } const terrainAsset = this.__asset; - if (this._buitinAsset != terrainAsset) { + if (this._buitinAsset !== terrainAsset) { this._buitinAsset = terrainAsset; } diff --git a/cocos/tiledmap/assembler/simple.ts b/cocos/tiledmap/assembler/simple.ts index 2334097516..05ae0ad5f3 100644 --- a/cocos/tiledmap/assembler/simple.ts +++ b/cocos/tiledmap/assembler/simple.ts @@ -23,18 +23,17 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui-assembler - */ - +import { JSB } from 'internal:constants'; import { Mat4, Size, Vec3 } from '../../core/math'; import { IAssembler } from '../../2d/renderer/base'; -import { MeshRenderData } from '../../2d/renderer/render-data'; import { IBatcher } from '../../2d/renderer/i-batcher'; -import { TiledLayer, TiledMeshData, TiledTile } from '..'; +import { TiledLayer, TiledRenderData, TiledTile } from '..'; import { GID, MixedGID, RenderOrder, TiledGrid, TileFlag } from '../tiled-types'; -import { Texture2D, Node } from '../../core'; +import { Texture2D, Node, director, Director } from '../../core'; +import { StaticVBAccessor } from '../../2d/renderer/static-vb-accessor'; +import { vfmtPosUvColor } from '../../2d/renderer/vertex-format'; +import { RenderData } from '../../2d/renderer/render-data'; +import { RenderDrawInfoType } from '../../2d/renderer/render-draw-info'; const MaxGridsLimit = Math.ceil(65535 / 6); @@ -51,39 +50,74 @@ let _uvb = { x: 0, y: 0 }; let _uvc = { x: 0, y: 0 }; let _uvd = { x: 0, y: 0 }; -let _renderData: { renderData: MeshRenderData, texture: Texture2D | null } | null; -let _fillGrids = 0; let _vfOffset = 0; let _moveX = 0; let _moveY = 0; +let _fillCount = 0; +let _curTexture : Texture2D | null = null; +let _tempBuffers : Float32Array; +let _curLayer: TiledLayer; + let flipTexture: (grid: TiledGrid, gid: MixedGID) => void; +let _accessor: StaticVBAccessor = null!; /** * simple 组装器 * 可通过 `UI.simple` 获取该组装器。 */ export const simple: IAssembler = { - createData (layer: TiledLayer) { - const renderData = layer.requestMeshRenderData(); - const maxGrids = layer.rightTop.col * layer.rightTop.row; - if (maxGrids * 4 > 65535) { - console.error('Vertex count exceeds 65535'); + ensureAccessor () { + if (!_accessor) { + const device = director.root!.device; + const batcher = director.root!.batcher2D; + _accessor = new StaticVBAccessor(device, vfmtPosUvColor, this.vCount); + //batcher.registerBufferAccessor(Number.parseInt('TILED-MAP', 36), _accessor); + director.on(Director.EVENT_BEFORE_DRAW, () => { + _accessor.reset(); + }); } - return renderData; }, - updateRenderData (comp: TiledLayer, ui: IBatcher) { + createData (layer: TiledLayer) { + if (JSB) { + this.ensureAccessor(); + } + }, + + fillBuffers (layer: TiledLayer, renderer: IBatcher) { + if (!layer || layer.tiledDataArray.length === 0) return; + + const dataArray = layer.tiledDataArray; + + // 当前渲染的数据 + const data = dataArray[layer._tiledDataArrayIdx] as TiledRenderData; + const renderData = data.renderData!; + const iBuf = renderData.chunk.meshBuffer.iData; + + let indexOffset = renderData.chunk.meshBuffer.indexOffset; + let vertexId = renderData.chunk.vertexOffset; + const quadCount = renderData.vertexCount / 4; + for (let i = 0; i < quadCount; i += 1) { + iBuf[indexOffset] = vertexId; + iBuf[indexOffset + 1] = vertexId + 1; + iBuf[indexOffset + 2] = vertexId + 2; + iBuf[indexOffset + 3] = vertexId + 2; + iBuf[indexOffset + 4] = vertexId + 1; + iBuf[indexOffset + 5] = vertexId + 3; + indexOffset += 6; + vertexId += 4; + } + renderData.chunk.meshBuffer.indexOffset = indexOffset; + }, + + updateRenderData (comp: TiledLayer) { comp.updateCulling(); - const renderData = comp.requestMeshRenderData(); _moveX = comp.leftDownToCenterX; _moveY = comp.leftDownToCenterY; - _renderData = renderData; - if (comp.colorChanged || comp.isCullingDirty() || comp.isUserNodeDirty() || comp.hasAnimation() || comp.hasTiledNode() || comp.node.hasChangedFlags) { comp.colorChanged = false; - comp.destroyRenderData(); let leftDown: { col: number, row: number }; @@ -119,8 +153,9 @@ export const simple: IAssembler = { comp.setCullingDirty(false); comp.setUserNodeDirty(false); } - - _renderData = null; + if (JSB) { + comp.prepareDrawData(); + } }, updateColor (tiled: TiledLayer) { @@ -130,43 +165,16 @@ export const simple: IAssembler = { colorV[1] = color.g / 255; colorV[2] = color.b / 255; colorV[3] = color.a / 255; - const rs = tiled.meshRenderDataArray; - if (rs) { - for (const r of rs) { - if (!(r as any).renderData) continue; - const renderData = (r as any).renderData; - const vs = renderData.vData; - for (let i = renderData.vertexStart, l = renderData.vertexCount; i < l; i++) { - vs.set(colorV, i * 9 + 5); - } + const rs = tiled.tiledDataArray; + for (const r of rs) { + if (!(r as any).renderData) continue; + const renderData = (r as any).renderData; + const vs = renderData.vData; + for (let i = renderData.vertexStart, l = renderData.vertexCount; i < l; i++) { + vs.set(colorV, i * 9 + 5); } } }, - - fillBuffers (layer: TiledLayer, renderer: IBatcher) { - if (!layer || !layer.meshRenderDataArray) return; - - const dataArray = layer.meshRenderDataArray; - - // 当前渲染的数据 - const data = dataArray[layer._meshRenderDataArrayIdx] as TiledMeshData; - const renderData = data.renderData; - const iBuf = renderData.iData; - - let indexOffset = 0; - let vertexId = 0; - const quadCount = renderData.vertexCount / 4; - for (let i = 0; i < quadCount; i += 1) { - iBuf[indexOffset] = vertexId; - iBuf[indexOffset + 1] = vertexId + 1; - iBuf[indexOffset + 2] = vertexId + 2; - iBuf[indexOffset + 3] = vertexId + 2; - iBuf[indexOffset + 4] = vertexId + 1; - iBuf[indexOffset + 5] = vertexId + 3; - indexOffset += 6; - vertexId += 4; - } - }, }; /* @@ -292,15 +300,26 @@ function _flipDiamondTileTexture (inGrid: TiledGrid, gid: MixedGID) { } } -function switchRenderData (curTexIdx: Texture2D | null, grid: TiledGrid, comp: TiledLayer) { - // need flush - if (!curTexIdx) curTexIdx = grid.texture; - if (!_renderData!.texture) { - _renderData!.texture = curTexIdx; +function packRenderData () { + if (_fillCount < 1 || !_curTexture) return; + + const vbCount = 4 * _fillCount; + const ibCount = 6 * _fillCount; + const tiledData = _curLayer.requestTiledRenderData(); + if (JSB) { + tiledData.renderData = RenderData.add(vfmtPosUvColor, _accessor); + tiledData.renderData.drawInfoType = RenderDrawInfoType.IA; + } else { + tiledData.renderData = RenderData.add(vfmtPosUvColor); } - // update material - _renderData = comp.requestMeshRenderData() as any; - _renderData!.texture = grid.texture; + tiledData.texture = _curTexture; + const rd = tiledData.renderData; + rd.resize(vbCount, ibCount); + const vb = rd.chunk.vb; + vb.set(_tempBuffers.subarray(0, vbCount * 9), 0); + + _fillCount = 0; + _curTexture = null; } // rowMoveDir is -1 or 1, -1 means decrease, 1 means increase @@ -308,18 +327,11 @@ function switchRenderData (curTexIdx: Texture2D | null, grid: TiledGrid, comp: T function traverseGrids (leftDown: { col: number, row: number }, rightTop: { col: number, row: number }, rowMoveDir: number, colMoveDir: number, comp: TiledLayer) { // show nothing - if (!_renderData || rightTop.row < 0 || rightTop.col < 0) return; + if (rightTop.row < 0 || rightTop.col < 0) return; - if (!_renderData.renderData) { - _renderData = comp.requestMeshRenderData(); - } - - let vertexBuf: Float32Array = _renderData.renderData.vData; - // let idxBuf: Uint16Array = _renderData!.renderData.iData; + _curLayer = comp; const matrix = comp.node.worldMatrix; - - _fillGrids = 0; _vfOffset = 0; const tiledTiles = comp.tiledTiles; @@ -346,9 +358,8 @@ function traverseGrids (leftDown: { col: number, row: number }, rightTop: { col: let right = 0; let top = 0; // x, y let tiledNode: TiledTile | null; - let curTexIdx: Texture2D | null = null; let colNodesCount = 0; - let checkColRange = true; + let isCheckColRange = true; const diamondTile = false; // TODO:comp._diamondTile; @@ -368,19 +379,24 @@ function traverseGrids (leftDown: { col: number, row: number }, rightTop: { col: rows = rightTop.row; } + const _tempRows = Math.abs(leftDown.row - rightTop.row) + 1; + const _tempClos = Math.abs(rightTop.col - leftDown.col) + 1; + _tempBuffers = new Float32Array(_tempRows * _tempClos * 9 * 4); + _fillCount = 0; + const vertexBuf = _tempBuffers; // traverse row for (; (rows - row) * rowMoveDir >= 0; row += rowMoveDir) { rowData = vertices[row]; colNodesCount = comp.getNodesCountByRow(row); - checkColRange = rowData && colNodesCount === 0; + isCheckColRange = rowData && colNodesCount === 0; // limit min col and max col if (colMoveDir === 1) { - col = checkColRange && leftDown.col < rowData.minCol ? rowData.minCol : leftDown.col; - cols = checkColRange && rightTop.col > rowData.maxCol ? rowData.maxCol : rightTop.col; + col = isCheckColRange && leftDown.col < rowData.minCol ? rowData.minCol : leftDown.col; + cols = isCheckColRange && rightTop.col > rowData.maxCol ? rowData.maxCol : rightTop.col; } else { - col = checkColRange && rightTop.col > rowData.maxCol ? rowData.maxCol : rightTop.col; - cols = checkColRange && leftDown.col < rowData.minCol ? rowData.minCol : leftDown.col; + col = isCheckColRange && rightTop.col > rowData.maxCol ? rowData.maxCol : rightTop.col; + cols = isCheckColRange && leftDown.col < rowData.minCol ? rowData.minCol : leftDown.col; } // traverse col @@ -388,12 +404,11 @@ function traverseGrids (leftDown: { col: number, row: number }, rightTop: { col: colData = rowData && rowData[col]; if (colNodesCount > 0) { + packRenderData(); 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; - curTexIdx = null; - _renderData = comp.requestMeshRenderData() as any; } } @@ -407,9 +422,9 @@ function traverseGrids (leftDown: { col: number, row: number }, rightTop: { col: if (!grid) continue; // check init or new material - if (curTexIdx !== grid.texture) { - switchRenderData(curTexIdx, grid, comp); - curTexIdx = grid.texture; + if (_curTexture !== grid.texture) { + packRenderData(); + _curTexture = grid.texture; } tileSize = grid.tileset._tileSize; @@ -423,10 +438,8 @@ function traverseGrids (leftDown: { col: number, row: number }, rightTop: { col: // begin to fill vertex buffer tiledNode = tiledTiles[colData.index]; - const renderData = _renderData!.renderData; - renderData.reserve(4, 0); - _vfOffset = renderData.vertexCount * 9; - vertexBuf = renderData.vData; + _vfOffset = _fillCount * 4 * 9; + if (!tiledNode) { if (diamondTile) { const centerX = (left + right) / 2; @@ -510,21 +523,15 @@ function traverseGrids (leftDown: { col: number, row: number }, rightTop: { col: vertexBuf[_vfOffset + vertStep3 + 3] = _uvd.x; vertexBuf[_vfOffset + vertStep3 + 4] = _uvd.y; - _fillGrids++; - - renderData.request(4, 6); - renderData.resize(renderData.vertexCount, renderData.indexCount); - - // check render users node - // if (colNodesCount > 0) _renderNodes(row, col); + _fillCount++; // vertices count exceed 66635, buffer must be switched - if (_fillGrids >= MaxGridsLimit) { - switchRenderData(curTexIdx, grid, comp); - curTexIdx = grid.texture; + if (_fillCount >= MaxGridsLimit) { + packRenderData(); } } } + packRenderData(); } function fillByTiledNode (tiledNode: Node, color: Float32Array, vbuf: Float32Array, diff --git a/cocos/tiledmap/category.json b/cocos/tiledmap/category.json new file mode 100644 index 0000000000..93c702b348 --- /dev/null +++ b/cocos/tiledmap/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "瓦片地图", + "en": "Tiled Map" + }, + "description": { + "zh": "TiledMap(地图)用于在游戏中显示 TMX 格式的地图。", + "en": "TiledMap is used to display a map in TMX format in the game." + } +} \ No newline at end of file diff --git a/cocos/tiledmap/index.ts b/cocos/tiledmap/index.ts index 238caccfc5..9c4b8315d3 100644 --- a/cocos/tiledmap/index.ts +++ b/cocos/tiledmap/index.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module tiledmap - */ - export * from './tiled-map'; export * from './tiled-map-asset'; export * from './tiled-layer'; diff --git a/cocos/tiledmap/tiled-layer.ts b/cocos/tiledmap/tiled-layer.ts index d8c389ca1e..df74c36afa 100644 --- a/cocos/tiledmap/tiled-layer.ts +++ b/cocos/tiledmap/tiled-layer.ts @@ -25,28 +25,26 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module tiledmap - */ - import { ccclass } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; -import { Renderable2D } from '../2d/framework/renderable-2d'; +import { UIRenderer } from '../2d/framework/ui-renderer'; import { SpriteFrame } from '../2d/assets/sprite-frame'; import { Component } from '../core/components'; import { TMXMapInfo } from './tmx-xml-parser'; import { Color, IVec2Like, Mat4, Size, Texture2D, Vec2, Vec3, Node, warn, logID, CCBoolean, director } from '../core'; import { TiledTile } from './tiled-tile'; -import { MeshRenderData } from '../2d/renderer/render-data'; +import { RenderData } from '../2d/renderer/render-data'; import { IBatcher } from '../2d/renderer/i-batcher.js'; import { MixedGID, GID, Orientation, TiledTextureGrids, TMXTilesetInfo, RenderOrder, StaggerAxis, StaggerIndex, TileFlag, - GIDFlags, TiledGrid, TiledAnimationType, PropertiesInfo, TMXLayerInfo, + GIDFlags, TiledAnimationType, PropertiesInfo, TMXLayerInfo, } from './tiled-types'; import { fillTextureGrids } from './tiled-utils'; import { NodeEventType } from '../core/scene-graph/node-event'; +import { legacyCC } from '../core/global-exports'; +import { RenderEntity, RenderEntityType } from '../2d/renderer/render-entity'; +import { RenderDrawInfo, RenderDrawInfoType } from '../2d/renderer/render-draw-info'; const _mat4_temp = new Mat4(); const _vec2_temp = new Vec2(); @@ -65,8 +63,8 @@ export class TiledUserNodeData extends Component { } } -export interface TiledMeshData { - renderData: MeshRenderData; +export interface TiledRenderData { + renderData: RenderData | null; texture: Texture2D | null; } @@ -74,16 +72,16 @@ interface TiledSubNodeData { subNodes: (null | TiledUserNodeData)[]; } -type TiledMeshDataArray = (TiledMeshData | TiledSubNodeData)[]; + type TiledDataArray = (TiledRenderData | TiledSubNodeData)[]; /** - * @en Render the TMX layer. - * @zh 渲染 TMX layer。 - * @class TiledLayer - * @extends Component - */ + * @en Render the TMX layer. + * @zh 渲染 TMX layer。 + * @class TiledLayer + * @extends Component + */ @ccclass('cc.TiledLayer') -export class TiledLayer extends Renderable2D { +export class TiledLayer extends UIRenderer { // [row][col] = {count: 0, nodesList: []}; protected _userNodeGrid: { [key: number]: { count: number;[key: number]: { count: number, list: (TiledUserNodeData | null)[] } } } = {}; protected _userNodeMap: { [key: string]: TiledUserNodeData } = {};// [id] = node; @@ -170,12 +168,21 @@ export class TiledLayer extends Renderable2D { protected _vertexZvalue?: number; protected _offset?: Vec2; - protected _meshRenderDataArray: TiledMeshDataArray | null = null; + protected _tiledDataArray: TiledDataArray = []; - get meshRenderDataArray () { return this._meshRenderDataArray; } + get tiledDataArray () { return this._tiledDataArray; } get leftDownToCenterX () { return this._leftDownToCenterX; } get leftDownToCenterY () { return this._leftDownToCenterY; } + private _drawInfoList : RenderDrawInfo[] = []; + private requestDrawInfo (idx: number) { + if (!this._drawInfoList[idx]) { + this._drawInfoList[idx] = new RenderDrawInfo(); + this._drawInfoList[idx].setDrawInfoType(RenderDrawInfoType.IA); + } + return this._drawInfoList[idx]; + } + constructor () { super(); } @@ -189,11 +196,11 @@ export class TiledLayer extends Renderable2D { } /** - * @en enable or disable culling - * @zh 开启或关闭裁剪。 - * @method enableCulling - * @param value - */ + * @en enable or disable culling + * @zh 开启或关闭裁剪。 + * @method enableCulling + * @param value + */ set enableCulling (value: boolean) { if (this._enableCulling !== value) { this._enableCulling = value; @@ -204,12 +211,12 @@ export class TiledLayer extends Renderable2D { get enableCulling () { return this._enableCulling!; } /** - * @en Adds user's node into layer. - * @zh 添加用户节点。 - * @method addUserNode - * @param {cc.Node} node - * @return {Boolean} - */ + * @en Adds user's node into layer. + * @zh 添加用户节点。 + * @method addUserNode + * @param {cc.Node} node + * @return {Boolean} + */ public addUserNode (node: Node) { let dataComp = node.getComponent(TiledUserNodeData); if (dataComp) { @@ -236,12 +243,12 @@ export class TiledLayer extends Renderable2D { } /** - * @en Removes user's node. - * @zh 移除用户节点。 - * @method removeUserNode - * @param {cc.Node} node - * @return {Boolean} - */ + * @en Removes user's node. + * @zh 移除用户节点。 + * @method removeUserNode + * @param {cc.Node} node + * @return {Boolean} + */ public removeUserNode (node: Node) { const dataComp = node.getComponent(TiledUserNodeData); if (!dataComp) { @@ -260,11 +267,11 @@ export class TiledLayer extends Renderable2D { } /** - * @en Destroy user's node. - * @zh 销毁用户节点。 - * @method destroyUserNode - * @param {cc.Node} node - */ + * @en Destroy user's node. + * @zh 销毁用户节点。 + * @method destroyUserNode + * @param {cc.Node} node + */ public destroyUserNode (node: Node) { this.removeUserNode(node); node.destroy(); @@ -425,57 +432,57 @@ export class TiledLayer extends Renderable2D { } /** - * @en Gets the layer name. - * @zh 获取层的名称。 - * @method getLayerName - * @return {String} - * @example - * let layerName = tiledLayer.getLayerName(); - * cc.log(layerName); - */ + * @en Gets the layer name. + * @zh 获取层的名称。 + * @method getLayerName + * @return {String} + * @example + * let layerName = tiledLayer.getLayerName(); + * cc.log(layerName); + */ public getLayerName (): string { return this._layerName; } /** - * @en Set the layer name. - * @zh 设置层的名称 - * @method setLayerName - * @param {String} layerName - * @example - * tiledLayer.setLayerName("New Layer"); - */ + * @en Set the layer name. + * @zh 设置层的名称 + * @method setLayerName + * @param {String} layerName + * @example + * tiledLayer.setLayerName("New Layer"); + */ public setLayerName (layerName: string) { this._layerName = layerName; } /** - * @en Return the value for the specific property name. - * @zh 获取指定属性名的值。 - * @method getProperty - * @param {String} propertyName - * @return {*} - * @example - * let property = tiledLayer.getProperty("info"); - * cc.log(property); - */ + * @en Return the value for the specific property name. + * @zh 获取指定属性名的值。 + * @method getProperty + * @param {String} propertyName + * @return {*} + * @example + * let property = tiledLayer.getProperty("info"); + * cc.log(property); + */ public getProperty (propertyName: string) { return this._properties![propertyName]; } /** - * @en Returns the position in pixels of a given tile coordinate. - * @zh 获取指定 tile 的像素坐标。 - * @method getPositionAt - * @param {Vec2|Number} pos position or x - * @param {Number} [y] - * @return {Vec2} - * @example - * let pos = tiledLayer.getPositionAt(cc.v2(0, 0)); - * cc.log("Pos: " + pos); - * let pos = tiledLayer.getPositionAt(0, 0); - * cc.log("Pos: " + pos); - */ + * @en Returns the position in pixels of a given tile coordinate. + * @zh 获取指定 tile 的像素坐标。 + * @method getPositionAt + * @param {Vec2|Number} pos position or x + * @param {Number} [y] + * @return {Vec2} + * @example + * let pos = tiledLayer.getPositionAt(cc.v2(0, 0)); + * cc.log("Pos: " + pos); + * let pos = tiledLayer.getPositionAt(0, 0); + * cc.log("Pos: " + pos); + */ public getPositionAt (pos: IVec2Like | number, y?: number): Vec2 | null { let x; if (y !== undefined) { @@ -580,18 +587,18 @@ export class TiledLayer extends Renderable2D { } /** - * @en - * Sets the tiles gid (gid = tile global id) at a given tiles rect. - * @zh - * 设置给定区域的 tile 的 gid (gid = tile 全局 id), - * @method setTilesGIDAt - * @param {Array} gids an array contains gid - * @param {Number} beginCol begin col number - * @param {Number} beginRow begin row number - * @param {Number} totalCols count of column - * @example - * tiledLayer.setTilesGIDAt([1, 1, 1, 1], 10, 10, 2) - */ + * @en + * Sets the tiles gid (gid = tile global id) at a given tiles rect. + * @zh + * 设置给定区域的 tile 的 gid (gid = tile 全局 id), + * @method setTilesGIDAt + * @param {Array} gids an array contains gid + * @param {Number} beginCol begin col number + * @param {Number} beginRow begin row number + * @param {Number} totalCols count of column + * @example + * tiledLayer.setTilesGIDAt([1, 1, 1, 1], 10, 10, 2) + */ public setTilesGIDAt (gids: number[], beginCol: number, beginRow: number, totalCols: number) { if (!gids || gids.length === 0 || totalCols <= 0) return; if (beginRow < 0) beginRow = 0; @@ -608,22 +615,22 @@ export class TiledLayer extends Renderable2D { } /** - * @en - * Sets the tile gid (gid = tile global id) at a given tile coordinate.
- * The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor . Tileset Mgr +1.
- * If a tile is already placed at that position, then it will be removed. - * @zh - * 设置给定坐标的 tile 的 gid (gid = tile 全局 id), - * tile 的 GID 可以使用方法 “tileGIDAt” 来获得。
- * 如果一个 tile 已经放在那个位置,那么它将被删除。 - * @method setTileGIDAt - * @param {Number} gid - * @param {Vec2|Number} posOrX position or x - * @param {Number} flagsOrY flags or y - * @param {Number} [flags] - * @example - * tiledLayer.setTileGIDAt(1001, 10, 10, 1) - */ + * @en + * Sets the tile gid (gid = tile global id) at a given tile coordinate.
+ * The Tile GID can be obtained by using the method "tileGIDAt" or by using the TMX editor . Tileset Mgr +1.
+ * If a tile is already placed at that position, then it will be removed. + * @zh + * 设置给定坐标的 tile 的 gid (gid = tile 全局 id), + * tile 的 GID 可以使用方法 “tileGIDAt” 来获得。
+ * 如果一个 tile 已经放在那个位置,那么它将被删除。 + * @method setTileGIDAt + * @param {Number} gid + * @param {Vec2|Number} posOrX position or x + * @param {Number} flagsOrY flags or y + * @param {Number} [flags] + * @example + * tiledLayer.setTileGIDAt(1001, 10, 10, 1) + */ public setTileGIDAt (gid: MixedGID, x: number, y: number, flags?: number) { const ugid = ((gid as unknown as number) & TileFlag.FLIPPED_MASK) >>> 0; @@ -665,18 +672,18 @@ export class TiledLayer extends Renderable2D { } /** - * @en - * Returns the tile gid at a given tile coordinate.
- * if it returns 0, it means that the tile is empty.
- * @zh - * 通过给定的 tile 坐标、flags(可选)返回 tile 的 GID.
- * 如果它返回 0,则表示该 tile 为空。
- * @method getTileGIDAt - * @param {Vec2} pos - * @return {Number} - * @example - * let tileGid = tiledLayer.getTileGIDAt(0, 0); - */ + * @en + * Returns the tile gid at a given tile coordinate.
+ * if it returns 0, it means that the tile is empty.
+ * @zh + * 通过给定的 tile 坐标、flags(可选)返回 tile 的 GID.
+ * 如果它返回 0,则表示该 tile 为空。
+ * @method getTileGIDAt + * @param {Vec2} pos + * @return {Number} + * @example + * let tileGid = tiledLayer.getTileGIDAt(0, 0); + */ public getTileGIDAt (x: number, y: number): number | null { if (this.isInvalidPosition(x, y)) { throw new Error('cc.TiledLayer.getTileGIDAt(): invalid position'); @@ -693,18 +700,18 @@ export class TiledLayer extends Renderable2D { return ((tile & TileFlag.FLIPPED_MASK) >>> 0); } /** - * @en - * Returns the tile flags at a given tile coordinate.
- * @zh - * 通过给定的 tile 坐标, 返回 tile 的 flags.
- * 如果它返回 null,则表示该 tile 为空。
- * @method getTileGIDAt - * @param {number}} x - * @param {number}} y - * @return {Number} - * @example - * let tileGid = tiledLayer.getTileGIDAt(0, 0); - */ + * @en + * Returns the tile flags at a given tile coordinate.
+ * @zh + * 通过给定的 tile 坐标, 返回 tile 的 flags.
+ * 如果它返回 null,则表示该 tile 为空。
+ * @method getTileGIDAt + * @param {number}} x + * @param {number}} y + * @return {Number} + * @example + * let tileGid = tiledLayer.getTileGIDAt(0, 0); + */ public getTileFlagsAt (x: number, y: number) { if (this.isInvalidPosition(x, y)) { throw new Error('TiledLayer.getTileFlagsAt: invalid position'); @@ -733,9 +740,9 @@ export class TiledLayer extends Renderable2D { // 'width, height' is the size of viewPort. public updateViewPort (x: number, y: number, width: number, height: number): void { if (this._viewPort.width === width - && this._viewPort.height === height - && this._viewPort.x === x - && this._viewPort.y === y) { + && this._viewPort.height === height + && this._viewPort.x === x + && this._viewPort.y === y) { return; } this._viewPort.x = x; @@ -845,7 +852,7 @@ export class TiledLayer extends Renderable2D { } public updateCulling () { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { this.enableCulling = false; } else if (this._enableCulling) { this.node.updateWorldTransform(); @@ -870,27 +877,27 @@ export class TiledLayer extends Renderable2D { } /** - * @en Layer orientation, which is the same as the map orientation. - * @zh 获取 Layer 方向(同地图方向)。 - * @method getLayerOrientation - * @return {Number} - * @example - * let orientation = tiledLayer.getLayerOrientation(); - * cc.log("Layer Orientation: " + orientation); - */ + * @en Layer orientation, which is the same as the map orientation. + * @zh 获取 Layer 方向(同地图方向)。 + * @method getLayerOrientation + * @return {Number} + * @example + * let orientation = tiledLayer.getLayerOrientation(); + * cc.log("Layer Orientation: " + orientation); + */ public getLayerOrientation () { return this._layerOrientation; } /** - * @en properties from the layer. They can be added using Tiled. - * @zh 获取 layer 的属性,可以使用 Tiled 编辑器添加属性。 - * @method getProperties - * @return {Object} - * @example - * let properties = tiledLayer.getProperties(); - * cc.log("Properties: " + properties); - */ + * @en properties from the layer. They can be added using Tiled. + * @zh 获取 layer 的属性,可以使用 Tiled 编辑器添加属性。 + * @method getProperties + * @return {Object} + * @example + * let properties = tiledLayer.getProperties(); + * cc.log("Properties: " + properties); + */ public getProperties () { return this._properties; } @@ -1084,24 +1091,24 @@ export class TiledLayer extends Renderable2D { } /** - * @en - * Get the TiledTile with the tile coordinate.
- * If there is no tile in the specified coordinate and forceCreate parameter is true,
- * then will create a new TiledTile at the coordinate. - * The renderer will render the tile with the rotation, scale, position and color property of the TiledTile. - * @zh - * 通过指定的 tile 坐标获取对应的 TiledTile。
- * 如果指定的坐标没有 tile,并且设置了 forceCreate 那么将会在指定的坐标创建一个新的 TiledTile 。
- * 在渲染这个 tile 的时候,将会使用 TiledTile 的节点的旋转、缩放、位移、颜色属性。
- * @method getTiledTileAt - * @param {Integer} x - * @param {Integer} y - * @param {Boolean} forceCreate - * @return {cc.TiledTile} - * @example - * let tile = tiledLayer.getTiledTileAt(100, 100, true); - * cc.log(tile); - */ + * @en + * Get the TiledTile with the tile coordinate.
+ * If there is no tile in the specified coordinate and forceCreate parameter is true,
+ * then will create a new TiledTile at the coordinate. + * The renderer will render the tile with the rotation, scale, position and color property of the TiledTile. + * @zh + * 通过指定的 tile 坐标获取对应的 TiledTile。
+ * 如果指定的坐标没有 tile,并且设置了 forceCreate 那么将会在指定的坐标创建一个新的 TiledTile 。
+ * 在渲染这个 tile 的时候,将会使用 TiledTile 的节点的旋转、缩放、位移、颜色属性。
+ * @method getTiledTileAt + * @param {Integer} x + * @param {Integer} y + * @param {Boolean} forceCreate + * @return {cc.TiledTile} + * @example + * let tile = tiledLayer.getTiledTileAt(100, 100, true); + * cc.log(tile); + */ public getTiledTileAt (x: number, y: number, forceCreate?: boolean) { if (this.isInvalidPosition(x, y)) { throw new Error('TiledLayer.getTiledTileAt: invalid position'); @@ -1127,16 +1134,16 @@ export class TiledLayer extends Renderable2D { } /** - * @en - * Change tile to TiledTile at the specified coordinate. - * @zh - * 将指定的 tile 坐标替换为指定的 TiledTile。 - * @method setTiledTileAt - * @param {Integer} x - * @param {Integer} y - * @param {cc.TiledTile} tiledTile - * @return {cc.TiledTile} - */ + * @en + * Change tile to TiledTile at the specified coordinate. + * @zh + * 将指定的 tile 坐标替换为指定的 TiledTile。 + * @method setTiledTileAt + * @param {Integer} x + * @param {Integer} y + * @param {cc.TiledTile} tiledTile + * @return {cc.TiledTile} + */ public setTiledTileAt (x: number, y: number, tiledTile: TiledTile | null): TiledTile | null { if (this.isInvalidPosition(x, y)) { throw new Error('TiledLayer.setTiledTileAt: invalid position'); @@ -1160,12 +1167,12 @@ export class TiledLayer extends Renderable2D { } /** - * @en Return texture. - * @zh 获取纹理。 - * @method getTexture - * @param index The index of textures - * @return {Texture2D} - */ + * @en Return texture. + * @zh 获取纹理。 + * @method getTexture + * @param index The index of textures + * @return {Texture2D} + */ public getTexture (index?: number): SpriteFrame | null { index = index || 0; if (this._textures && index >= 0 && this._textures.length > index) { @@ -1175,69 +1182,69 @@ export class TiledLayer extends Renderable2D { } /** - * @en Return texture. - * @zh 获取纹理。 - * @method getTextures - * @return {Texture2D} - */ + * @en Return texture. + * @zh 获取纹理。 + * @method getTextures + * @return {Texture2D} + */ public getTextures () { return this._textures; } /** - * @en Set the texture. - * @zh 设置纹理。 - * @method setTexture - * @param {SpriteFrame} texture - */ + * @en Set the texture. + * @zh 设置纹理。 + * @method setTexture + * @param {SpriteFrame} texture + */ public setTexture (texture: SpriteFrame) { this.setTextures([texture]); } /** - * @en Set the texture. - * @zh 设置纹理。 - * @method setTexture - * @param {SpriteFrame} textures - */ + * @en Set the texture. + * @zh 设置纹理。 + * @method setTexture + * @param {SpriteFrame} textures + */ public setTextures (textures: SpriteFrame[]) { this._textures = textures; this.markForUpdateRenderData(); } /** - * @en Gets layer size. - * @zh 获得层大小。 - * @method getLayerSize - * @return {Size} - * @example - * let size = tiledLayer.getLayerSize(); - * cc.log("layer size: " + size); - */ + * @en Gets layer size. + * @zh 获得层大小。 + * @method getLayerSize + * @return {Size} + * @example + * let size = tiledLayer.getLayerSize(); + * cc.log("layer size: " + size); + */ public getLayerSize (): Size { return this._layerSize!; } /** - * @en Size of the map's tile (could be different from the tile's size). - * @zh 获取 tile 的大小( tile 的大小可能会有所不同)。 - * @method getMapTileSize - * @return {Size} - * @example - * let mapTileSize = tiledLayer.getMapTileSize(); - * cc.log("MapTile size: " + mapTileSize); - */ + * @en Size of the map's tile (could be different from the tile's size). + * @zh 获取 tile 的大小( tile 的大小可能会有所不同)。 + * @method getMapTileSize + * @return {Size} + * @example + * let mapTileSize = tiledLayer.getMapTileSize(); + * cc.log("MapTile size: " + mapTileSize); + */ public getMapTileSize (): Size { return this._mapTileSize!; } /** - * @en Gets Tile set first information for the layer. - * @zh 获取 layer 索引位置为0的 Tileset 信息。 - * @method getTileSet - * @param index The index of tilesets - * @return {TMXTilesetInfo} - */ + * @en Gets Tile set first information for the layer. + * @zh 获取 layer 索引位置为0的 Tileset 信息。 + * @method getTileSet + * @param index The index of tilesets + * @return {TMXTilesetInfo} + */ public getTileSet (index: number): TMXTilesetInfo | null { index = index || 0; if (this._tilesets && index >= 0 && this._tilesets.length > index) { @@ -1247,31 +1254,31 @@ export class TiledLayer extends Renderable2D { } /** - * @en Gets tile set all information for the layer. - * @zh 获取 layer 所有的 Tileset 信息。 - * @method getTileSet - * @return {TMXTilesetInfo} - */ + * @en Gets tile set all information for the layer. + * @zh 获取 layer 所有的 Tileset 信息。 + * @method getTileSet + * @return {TMXTilesetInfo} + */ public getTileSets (): TMXTilesetInfo[] { return this._tilesets; } /** - * @en Sets tile set information for the layer. - * @zh 设置 layer 的 tileset 信息。 - * @method setTileSet - * @param {TMXTilesetInfo} tileset - */ + * @en Sets tile set information for the layer. + * @zh 设置 layer 的 tileset 信息。 + * @method setTileSet + * @param {TMXTilesetInfo} tileset + */ public setTileSet (tileset: TMXTilesetInfo) { this.setTileSets([tileset]); } /** - * @en Sets Tile set information for the layer. - * @zh 设置 layer 的 Tileset 信息。 - * @method setTileSets - * @param {TMXTilesetInfo} tilesets - */ + * @en Sets Tile set information for the layer. + * @zh 设置 layer 的 Tileset 信息。 + * @method setTileSets + * @param {TMXTilesetInfo} tilesets + */ public setTileSets (tilesets: TMXTilesetInfo[]) { this._tilesets = tilesets; const textures: SpriteFrame[] = this._textures = []; @@ -1372,57 +1379,25 @@ export class TiledLayer extends Renderable2D { this._updateAllUserNode(); } - public requestMeshRenderData () { - if (!this._meshRenderDataArray) { - this._meshRenderDataArray = []; - } - const arr = this._meshRenderDataArray 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 TiledMeshData; - } - } - - const renderData = MeshRenderData.add(); - const comb = { renderData, texture: null }; - renderData.material = this.getRenderMaterial(0); - this._meshRenderDataArray.push(comb); - return comb; + public requestTiledRenderData () { + const comb = { renderData: null, texture: null }; + this._tiledDataArray.push(comb); + return (comb as TiledRenderData); } public requestSubNodesData () { - if (!this._meshRenderDataArray) { - this._meshRenderDataArray = []; - } - const arr = this._meshRenderDataArray as any[]; - // TODO temporary fix for shield node test case - // while (arr.length > 0 && arr[arr.length - 1].renderData && arr[arr.length - 1].renderData.vertexCount === 0) { - // arr.pop(); - // } - 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._meshRenderDataArray.push(comb); + this._tiledDataArray.push(comb); return comb; } public destroyRenderData () { - if (this._meshRenderDataArray) { - this._meshRenderDataArray.forEach((rd) => { - const renderData = (rd as TiledMeshData).renderData; - if (renderData) MeshRenderData.remove(renderData); - }); - this._meshRenderDataArray.length = 0; - } + this._tiledDataArray.forEach((rd) => { + const renderData = (rd as TiledRenderData).renderData; + if (renderData) RenderData.remove(renderData); + }); + this._tiledDataArray.length = 0; super.destroyRenderData(); } @@ -1430,36 +1405,93 @@ export class TiledLayer extends Renderable2D { const assembler = TiledLayer.Assembler.getAssembler(this); if (this._assembler !== assembler) { this._assembler = assembler; + this._assembler.createData(this); } - if (!this._meshRenderDataArray) { - if (this._assembler && this._assembler.createData) { - this._assembler.createData(this); - this.markForUpdateRenderData(); - this._updateColor(); - } + if (this._tiledDataArray.length === 0) { + this.markForUpdateRenderData(); + this._updateColor(); } } /** - * @legacyPublic - */ - public _meshRenderDataArrayIdx = 0; + * @en + * Index of mesh render data array + * @zh + * 网格渲染数据数组的索引 + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. + */ + public _tiledDataArrayIdx = 0; protected _render (ui: IBatcher) { - if (this._meshRenderDataArray) { - for (let i = 0; i < this._meshRenderDataArray.length; i++) { - this._meshRenderDataArrayIdx = i; - const m = this._meshRenderDataArray[i]; - if ((m as TiledSubNodeData).subNodes) { - // 提前处理 User Nodes - (m as TiledSubNodeData).subNodes.forEach((c) => { - if (c) ui.walk(c.node); - }); - } else if ((m as TiledMeshData).texture) { + for (let i = 0; i < this._tiledDataArray.length; i++) { + this._tiledDataArrayIdx = i; + const m = this._tiledDataArray[i]; + if ((m as TiledSubNodeData).subNodes) { + // 提前处理 User Nodes + (m as TiledSubNodeData).subNodes.forEach((c) => { + if (c) ui.walk(c.node); + }); + } else { + const td = m as TiledRenderData; + if (td.texture) { // NOTE: 由于 commitComp 只支持单张纹理, 故分多次提交 - ui.commitComp(this, (m as TiledMeshData).renderData, (m as TiledMeshData).texture, this._assembler, null); + ui.commitComp(this, td.renderData, td.texture, this._assembler, null); + } + } + } + this.node._static = true; + } + + protected createRenderEntity () { + return new RenderEntity(RenderEntityType.DYNAMIC); + } + + private fillIndicesBuffer (renderData: RenderData, drawInfo: RenderDrawInfo) { + const iBuf = renderData.chunk.meshBuffer.iData; + + let indexOffset = renderData.chunk.meshBuffer.indexOffset; + drawInfo.setIndexOffset(indexOffset); + let vertexId = renderData.chunk.vertexOffset; + const quadCount = renderData.vertexCount / 4; + for (let i = 0; i < quadCount; i += 1) { + iBuf[indexOffset] = vertexId; + iBuf[indexOffset + 1] = vertexId + 1; + iBuf[indexOffset + 2] = vertexId + 2; + iBuf[indexOffset + 3] = vertexId + 2; + iBuf[indexOffset + 4] = vertexId + 1; + iBuf[indexOffset + 5] = vertexId + 3; + indexOffset += 6; + vertexId += 4; + } + renderData.chunk.meshBuffer.indexOffset = indexOffset; + drawInfo.setIBCount(quadCount * 6); + } + + public prepareDrawData () { + 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; + if ((m as TiledSubNodeData).subNodes) { + // 提前处理 User Nodes + // (m as TiledSubNodeData).subNodes.forEach((c) => { + // if (c) batch2d.walk(c.node); + // }); + } else { + const td = m as TiledRenderData; + if (td.texture) { + const drawInfo = this.requestDrawInfo(i); + 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); } } - this.node._static = true; } } } diff --git a/cocos/tiledmap/tiled-map-asset.ts b/cocos/tiledmap/tiled-map-asset.ts index 8cc4cb3aab..84f673a0db 100644 --- a/cocos/tiledmap/tiled-map-asset.ts +++ b/cocos/tiledmap/tiled-map-asset.ts @@ -24,17 +24,16 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module tiledmap - */ - import { ccclass, type, serializable } from 'cc.decorator'; import { Asset } from '../core/assets/asset'; import { CCString, Size, TextAsset } from '../core'; import { SpriteFrame } from '../2d/assets'; + /** + * @en * Class for tiled map asset handling. + * @zh + * 用于获取 tiled map 资源类 * @class TiledMapAsset * @extends Asset * @@ -53,13 +52,20 @@ export class TiledMapAsset extends Asset { tsxFileNames: string[] = []; /** - * @zh s + * @en + * SpriteFrame array + * @zh + * SpriteFrame 数组 */ @serializable @type([SpriteFrame]) spriteFrames: SpriteFrame[] = []; /** + * @en + * ImageLayerSpriteFrame array + * @zh + * ImageLayerSpriteFrame 数组 * @property {SpriteFrame[]} imageLayerSpriteFrame */ @serializable @@ -67,6 +73,10 @@ export class TiledMapAsset extends Asset { imageLayerSpriteFrame: SpriteFrame[] = [] /** + * @en + * Name of each object in imageLayerSpriteFrame + * @zh + * 每个 imageLayerSpriteFrame 名称 * @property {String[]} imageLayerTextureNames */ @serializable @@ -74,6 +84,10 @@ export class TiledMapAsset extends Asset { imageLayerSpriteFrameNames: string[] = []; /** + * @en + * Name of each object in spriteFrames + * @zh + * 每个 SpriteFrame 名称 * @property {String[]} spriteFrameNames */ @serializable @@ -81,6 +95,10 @@ export class TiledMapAsset extends Asset { spriteFrameNames: string[] = []; /** + * @en + * Size of each object in spriteFrames + * @zh + * 每个 SpriteFrame 的大小 * @property {Size[]} spriteFrameSizes */ @serializable diff --git a/cocos/tiledmap/tiled-map.ts b/cocos/tiledmap/tiled-map.ts index 9452ac36e0..308c632d38 100644 --- a/cocos/tiledmap/tiled-map.ts +++ b/cocos/tiledmap/tiled-map.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module tiledmap - */ - import { ccclass, displayOrder, executeInEditMode, help, menu, requireComponent, type, serializable, editable } from 'cc.decorator'; import { EDITOR, JSB } from 'internal:constants'; import { Component } from '../core/components'; @@ -79,8 +74,6 @@ export class TiledMap extends Component { _mapSize: Size = new Size(0, 0); _tileSize: Size = new Size(0, 0); - _preloaded = false; - _mapOrientation = Orientation.ORTHO; static Orientation = Orientation; @@ -91,6 +84,8 @@ export class TiledMap extends Component { static TMXObjectType = TMXObjectType; static RenderOrder = RenderOrder; + private _isApplied = false; + @serializable _tmxFile: TiledMapAsset | null = null; /** @@ -109,9 +104,8 @@ export class TiledMap extends Component { set tmxAsset (value: TiledMapAsset) { if (this._tmxFile !== value || EDITOR) { this._tmxFile = value; - if (this._preloaded || EDITOR) { - this._applyFile(); - } + this._applyFile(); + this._isApplied = true; } } @@ -306,13 +300,13 @@ export class TiledMap extends Component { } __preload () { - this._preloaded = true; - if (!this._tmxFile) { return; } - - this._applyFile(); + if (this._isApplied === false) { + this._applyFile(); + this._isApplied = true; + } } onEnable () { diff --git a/cocos/tiledmap/tiled-object-group.ts b/cocos/tiledmap/tiled-object-group.ts index 7e69ae49ba..c4400cf52f 100644 --- a/cocos/tiledmap/tiled-object-group.ts +++ b/cocos/tiledmap/tiled-object-group.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module tiledmap - */ - import { ccclass, help, type, requireComponent } from 'cc.decorator'; import { Component } from '../core/components'; import { Sprite } from '../2d/components/sprite'; @@ -160,7 +155,7 @@ export class TiledObjectGroup extends Component { protected _objects: TMXObject[] = []; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _init (groupInfo: TMXObjectGroupInfo, mapInfo: TMXMapInfo, texGrids: TiledTextureGrids) { const FLIPPED_MASK = TileFlag.FLIPPED_MASK; diff --git a/cocos/tiledmap/tiled-tile.ts b/cocos/tiledmap/tiled-tile.ts index 97ee500181..b15b399b02 100644 --- a/cocos/tiledmap/tiled-tile.ts +++ b/cocos/tiledmap/tiled-tile.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module tiledmap - */ - /** * @en TiledTile can control the specified map tile. * It will apply the node rotation, scale, translate to the map tile. diff --git a/cocos/tiledmap/tiled-types.ts b/cocos/tiledmap/tiled-types.ts index ec42f45690..4fee9256f3 100644 --- a/cocos/tiledmap/tiled-types.ts +++ b/cocos/tiledmap/tiled-types.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module tiledmap - */ - import { Color, Rect, Size, Texture2D, Vec2 } from '../core'; import { SpriteFrame } from '../2d/assets'; import { ccenum } from '../core/value-types/enum'; diff --git a/cocos/tiledmap/tiled-utils.ts b/cocos/tiledmap/tiled-utils.ts index 38b0378731..0522b1dd32 100644 --- a/cocos/tiledmap/tiled-utils.ts +++ b/cocos/tiledmap/tiled-utils.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module tiledmap - */ - import { SpriteFrame } from '../2d/assets'; import { Rect, Texture2D } from '../core'; import { GID, TiledGrid, TiledTextureGrids, TMXTilesetInfo } from './tiled-types'; diff --git a/cocos/tiledmap/tmx-xml-parser.ts b/cocos/tiledmap/tmx-xml-parser.ts index d125701f74..c4de98b48a 100644 --- a/cocos/tiledmap/tmx-xml-parser.ts +++ b/cocos/tiledmap/tmx-xml-parser.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module tiledmap - */ - import { Label, HorizontalTextAlignment, VerticalTextAlignment } from '../2d/components/label'; import codec from '../../external/compression/ZipUtils.js'; import zlib from '../../external/compression/zlib.min.js'; diff --git a/cocos/tween/actions/action-instant.ts b/cocos/tween/actions/action-instant.ts index 82f7cd8fe9..0c6244808c 100644 --- a/cocos/tween/actions/action-instant.ts +++ b/cocos/tween/actions/action-instant.ts @@ -26,7 +26,7 @@ */ import { FiniteTimeAction, Action } from './action'; -import { RenderableComponent } from '../../core/components/renderable-component'; +import { ModelRenderer } from '../../core/components/model-renderer'; /** * @en Instant actions are immediate actions. They don't have a duration like the ActionInterval actions. @@ -70,7 +70,7 @@ export class ActionInstant extends FiniteTimeAction { */ export class Show extends ActionInstant { update (dt: any) { - const _renderComps = this.target!.getComponentsInChildren(RenderableComponent); + const _renderComps = this.target!.getComponentsInChildren(ModelRenderer); for (let i = 0; i < _renderComps.length; ++i) { const render = _renderComps[i]; render.enabled = true; @@ -106,7 +106,7 @@ export function show (): ActionInstant { */ export class Hide extends ActionInstant { update (dt: any) { - const _renderComps = this.target!.getComponentsInChildren(RenderableComponent); + const _renderComps = this.target!.getComponentsInChildren(ModelRenderer); for (let i = 0; i < _renderComps.length; ++i) { const render = _renderComps[i]; render.enabled = false; @@ -142,7 +142,7 @@ export function hide (): ActionInstant { */ export class ToggleVisibility extends ActionInstant { update (dt: any) { - const _renderComps = this.target!.getComponentsInChildren(RenderableComponent); + const _renderComps = this.target!.getComponentsInChildren(ModelRenderer); for (let i = 0; i < _renderComps.length; ++i) { const render = _renderComps[i]; render.enabled = !render.enabled; diff --git a/cocos/tween/actions/action-interval.ts b/cocos/tween/actions/action-interval.ts index bda182cf95..7ff1598cd1 100644 --- a/cocos/tween/actions/action-interval.ts +++ b/cocos/tween/actions/action-interval.ts @@ -222,7 +222,10 @@ export class ActionInterval extends FiniteTimeAction { } /** + * @en * Get this action speed. + * @zh + * 返回此动作速度 * @return {Number} */ getSpeed (): number { @@ -230,7 +233,10 @@ export class ActionInterval extends FiniteTimeAction { } /** + * @en * Set this action speed. + * @zh + * 设置此动作速度 * @param {Number} speed * @returns {ActionInterval} */ diff --git a/cocos/tween/actions/action-manager.ts b/cocos/tween/actions/action-manager.ts index a900c2b4ea..4bf6247889 100644 --- a/cocos/tween/actions/action-manager.ts +++ b/cocos/tween/actions/action-manager.ts @@ -30,6 +30,7 @@ import { errorID, logID, assertID } from '../../core/platform/debug'; import { Action } from './action'; import { Node, CCObject } from '../../core'; import { legacyCC } from '../../core/global-exports'; +import { isCCObject } from '../../core/data/object'; let ID_COUNTER = 0; @@ -457,8 +458,8 @@ export class ActionManager { locCurrTarget = this._currentTarget; const target = locCurrTarget.target; - if (target instanceof CCObject && !target.isValid) { - this.removeAllActionsFromTarget(target as any); + if (isCCObject(target) && !target.isValid) { + this.removeAllActionsFromTarget(target); elt--; continue; } diff --git a/cocos/tween/category.json b/cocos/tween/category.json new file mode 100644 index 0000000000..827c37ef3d --- /dev/null +++ b/cocos/tween/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "缓动系统", + "en": "Tween" + }, + "description": { + "zh": "缓动系统是一个较为简易的 API 级别的动画系统,用于在一定时间内对对象的属性进行变化", + "en": "Tween system is simpler API-level animation system for changing the properties of an object over a period of time" + } +} \ No newline at end of file diff --git a/cocos/tween/export-api.ts b/cocos/tween/export-api.ts index e08dbd1e4a..7fcc90a0e7 100644 --- a/cocos/tween/export-api.ts +++ b/cocos/tween/export-api.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module tween - */ - /** * @en * Built-in string value definition for the cache function. @@ -66,7 +61,7 @@ export interface ITweenOption { /** * @en - * Interpolation functin, you can pass in a custom function. + * Interpolation function, you can pass in a custom function. * @zh * 插值函数,参数的意义 start:起始值,end:目标值,current:当前值,ratio:当前进度 */ diff --git a/cocos/tween/tween-system.ts b/cocos/tween/tween-system.ts index 2acb285156..8d827b1b45 100644 --- a/cocos/tween/tween-system.ts +++ b/cocos/tween/tween-system.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module tween - */ - import { EDITOR } from 'internal:constants'; import { System, Director, director } from '../core'; import { ActionManager } from './actions/action-manager'; @@ -70,10 +65,10 @@ export class TweenSystem extends System { /** * @en - * The update will auto execute after all compnents update. + * The update will auto execute after all components update. * @zh * 此方法会在组件 update 之后自动执行。 - * @param dt 间隔时间 + * @param dt @en The delta time @zh 间隔时间 */ update (dt: number) { if (!EDITOR || legacyCC.GAME_VIEW || this._executeInEditMode) { diff --git a/cocos/tween/tween.ts b/cocos/tween/tween.ts index 3068b2980b..2275b9b29f 100644 --- a/cocos/tween/tween.ts +++ b/cocos/tween/tween.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module tween - */ - import { TweenSystem } from './tween-system'; import { warn } from '../core'; import { ActionInterval, sequence, repeat, repeatForever, reverseTime, delayTime, spawn } from './actions/action-interval'; @@ -52,7 +47,7 @@ type ConstructorType = OmitType; * @zh * Tween 提供了一个简单灵活的方法来缓动目标,从 creator 移植而来。 * @class Tween - * @param {Object} [target] + * @param [target] * @example * tween(this.node) * .to(1, {scale: new Vec3(2, 2, 2), position: new Vec3(5, 5, 5)}) @@ -73,6 +68,8 @@ export class Tween { /** * @en Sets tween tag * @zh 设置缓动的标签 + * @method tag + * @param tag @en The tag set for this tween @zh 为当前缓动设置的标签 */ tag (tag: number) { this._tag = tag; @@ -84,6 +81,8 @@ export class Tween { * Insert an action or tween to this sequence. * @zh * 插入一个 tween 到队列中。 + * @method then + * @param other @en The rear tween of this tween @zh 当前缓动的后置缓动 */ then (other: Tween): Tween { if (other instanceof Action) { @@ -99,6 +98,8 @@ export class Tween { * Sets tween target. * @zh * 设置 tween 的 target。 + * @method target + * @param target @en The target of this tween @zh 当前缓动的目标对象 */ target (target: T): Tween { this._target = target; @@ -143,6 +144,8 @@ export class Tween { * Clone a tween. * @zh * 克隆当前 tween。 + * @method clone + * @param target @en The target of clone tween @zh 克隆缓动的目标对象 */ clone (target: T): Tween { const action = this._union(); @@ -168,11 +171,11 @@ export class Tween { * @zh * 添加一个对属性进行绝对值计算的 action。 * @method to - * @param {number} duration 缓动时间,单位为秒 - * @param {Object} props 缓动的属性列表 - * @param {Object} [opts] 可选的缓动功能 - * @param {Function} [opts.progress] - * @param {Function|String} [opts.easing] + * @param duration @en Tween time, in seconds @zh 缓动时间,单位为秒 + * @param props @en List of properties of tween @zh 缓动的属性列表 + * @param opts @en Optional functions of tween @zh 可选的缓动功能 + * @param opts.progress @en Interpolation function @zh 缓动的速度插值函数 + * @param opts.easing @en Tween function or a lambda @zh 缓动的曲线函数或lambda表达式 */ to (duration: number, props: ConstructorType, opts?: ITweenOption): Tween { opts = opts || Object.create(null); @@ -188,11 +191,11 @@ export class Tween { * @zh * 添加一个对属性进行相对值计算的 action。 * @method by - * @param {number} duration 缓动时间,单位为秒 - * @param {Object} props 缓动的属性列表 - * @param {Object} [opts] 可选的缓动功能 - * @param {Function} [opts.progress] - * @param {Function|String} [opts.easing] + * @param duration @en Tween time, in seconds @zh 缓动时间,单位为秒 + * @param props @en List of properties of tween @zh 缓动的属性列表 + * @param opts @en Optional functions of tween @zh 可选的缓动功能 + * @param [opts.progress] + * @param [opts.easing] * @return {Tween} */ by (duration: number, props: ConstructorType, opts?: ITweenOption): Tween { @@ -209,7 +212,7 @@ export class Tween { * @zh * 直接设置 target 的属性。 * @method set - * @param {Object} props + * @param props @en List of properties of tween @zh 缓动的属性列表 * @return {Tween} */ set (props: ConstructorType): Tween { @@ -224,7 +227,7 @@ export class Tween { * @zh * 添加一个延时 action。 * @method delay - * @param {number} duration + * @param duration @en Delay time of this tween @zh 当前缓动的延迟时间 * @return {Tween} */ delay (duration: number): Tween { @@ -239,7 +242,7 @@ export class Tween { * @zh * 添加一个回调 action。 * @method call - * @param {Function} callback + * @param callback @en Callback function at the end of this tween @zh 当前缓动结束时的回调函数 * @return {Tween} */ // eslint-disable-next-line @typescript-eslint/ban-types @@ -254,6 +257,8 @@ export class Tween { * Add an sequence action. * @zh * 添加一个队列 action。 + * @method sequence + * @param args @en All tween that make up the sequence @zh 组成队列的所有缓动 */ sequence (...args: Tween[]): Tween { const action = Tween._wrappedSequence(...args); @@ -266,6 +271,8 @@ export class Tween { * Add an parallel action. * @zh * 添加一个并行 action。 + * @method parallel + * @param args @en The tween parallel to this tween @zh 与当前缓动并行的缓动 */ parallel (...args: Tween[]): Tween { const action = Tween._wrappedParallel(...args); @@ -279,8 +286,8 @@ export class Tween { * This action will integrate before actions to a sequence action as their parameters. * @zh * 添加一个重复 action,这个 action 会将前一个动作作为他的参数。 - * @param {number} repeatTimes 重复次数 - * @param {Tween} embedTween 可选,嵌入 Tween + * @param repeatTimes @en The repeat times of this tween @zh 重复次数 + * @param embedTween @en Optional, embedded tween of this tween @zh 可选,嵌入缓动 */ repeat (repeatTimes: number, embedTween?: Tween): Tween { /** adapter */ @@ -308,7 +315,7 @@ export class Tween { * @zh * 添加一个永久重复 action,这个 action 会将前一个动作作为他的参数。 * @method repeatForever - * @param {Tween} embedTween 可选,嵌入 Tween + * @param embedTween @en Optional, embedded tween of this tween @zh 可选,嵌入缓动 */ repeatForever (embedTween?: Tween): Tween { const actions = this._actions; @@ -331,7 +338,7 @@ export class Tween { * @zh * 添加一个倒置时间 action,这个 action 会将前一个动作作为他的参数。 * @method reverseTime - * @param {Tween} embedTween 可选,嵌入 Tween + * @param embedTween @en Optional, embedded tween of this tween @zh 可选,嵌入缓动 */ reverseTime (embedTween?: Tween): Tween { const actions = this._actions; @@ -464,7 +471,7 @@ legacyCC.Tween = Tween; * tween is a utility function that helps instantiate Tween instances. * @zh * tween 是一个工具函数,帮助实例化 Tween 实例。 - * @param target 缓动的目标 + * @param target @en The target of the result tween @zh 缓动的目标 * @returns Tween 实例 * @example * tween(this.node) diff --git a/cocos/ui/block-input-events.ts b/cocos/ui/block-input-events.ts index f9b4fd751b..1450772f11 100644 --- a/cocos/ui/block-input-events.ts +++ b/cocos/ui/block-input-events.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module event - */ - import { ccclass, help, menu } from 'cc.decorator'; import { Component } from '../core/components/component'; import { Event } from '../input/types'; diff --git a/cocos/ui/button.ts b/cocos/ui/button.ts index 75dcf202c3..e03c808ed3 100644 --- a/cocos/ui/button.ts +++ b/cocos/ui/button.ts @@ -24,16 +24,11 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, executionOrder, menu, requireComponent, tooltip, displayOrder, type, rangeMin, rangeMax, serializable, executeInEditMode } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { SpriteFrame } from '../2d/assets'; import { Component, EventHandler as ComponentEventHandler } from '../core/components'; -import { UITransform, Renderable2D } from '../2d/framework'; +import { UITransform, UIRenderer } from '../2d/framework'; import { EventMouse, EventTouch } from '../input/types'; import { Color, Vec3 } from '../core/math'; import { ccenum } from '../core/value-types/enum'; @@ -643,7 +638,7 @@ export class Button extends Component { } if (this._transition === Transition.COLOR) { - const renderComp = target._uiProps.uiComp as Renderable2D; + const renderComp = target._uiProps.uiComp as UIRenderer; Color.lerp(_tempColor, this._fromColor, this._toColor, ratio); if (renderComp) { renderComp.color = _tempColor; @@ -680,7 +675,7 @@ export class Button extends Component { } const transition = this._transition; if (transition === Transition.COLOR && this._interactable) { - const renderComp = target.getComponent(Renderable2D); + const renderComp = target.getComponent(UIRenderer); if (renderComp) { renderComp.color = this._normalColor; } @@ -919,7 +914,7 @@ export class Button extends Component { protected _updateColorTransition (state: string) { const color = this[`${state}Color`]; - const renderComp = this.target?.getComponent(Renderable2D); + const renderComp = this.target?.getComponent(UIRenderer); if (!renderComp) { return; } diff --git a/cocos/ui/category.json b/cocos/ui/category.json new file mode 100644 index 0000000000..ac4e2a66f0 --- /dev/null +++ b/cocos/ui/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "用户界面", + "en": "UI" + }, + "description": { + "zh": "Cocos Creator 中强大而灵活的 UI(用户界面)系统,通过组合不同 UI 组件来生产能够适配多种分辨率屏幕的、通过数据动态生成和更新显示内容,以及支持多种排版布局方式的 UI 界面。", + "en": "The powerful and flexible UI (User Interface) system in Cocos Creator. By assembling different UI components to produce UI interfaces that can be adapted to multiple screen resolutions, dynamically generate and update display content from data, and support multiple layout styles." + } +} \ No newline at end of file diff --git a/cocos/ui/deprecated-1.2.0.ts b/cocos/ui/deprecated-1.2.0.ts new file mode 100644 index 0000000000..5e2d805b46 --- /dev/null +++ b/cocos/ui/deprecated-1.2.0.ts @@ -0,0 +1,79 @@ +import { deprecateModuleExportedName } from '../core/utils/x-deprecated'; + +deprecateModuleExportedName({ + ButtonComponent: { + newName: 'Button', + since: '1.2.0', + removed: false, + }, + EditBoxComponent: { + newName: 'EditBox', + since: '1.2.0', + removed: false, + }, + LayoutComponent: { + newName: 'Layout', + since: '1.2.0', + removed: false, + }, + ProgressBarComponent: { + newName: 'ProgressBar', + since: '1.2.0', + removed: false, + }, + ScrollViewComponent: { + newName: 'ScrollView', + since: '1.2.0', + removed: false, + }, + ScrollBarComponent: { + newName: 'ScrollBar', + since: '1.2.0', + removed: false, + }, + SliderComponent: { + newName: 'Slider', + since: '1.2.0', + removed: false, + }, + ToggleComponent: { + newName: 'Toggle', + since: '1.2.0', + removed: false, + }, + ToggleContainerComponent: { + newName: 'ToggleContainer', + since: '1.2.0', + removed: false, + }, + WidgetComponent: { + newName: 'Widget', + since: '1.2.0', + removed: false, + }, + PageViewComponent: { + newName: 'PageView', + since: '1.2.0', + removed: false, + }, + PageViewIndicatorComponent: { + newName: 'PageViewIndicator', + since: '1.2.0', + removed: false, + }, + SafeAreaComponent: { + newName: 'SafeArea', + since: '1.2.0', + removed: false, + }, + UICoordinateTrackerComponent: { + newName: 'UICoordinateTracker', + since: '1.2.0', + removed: false, + }, + BlockInputEventsComponent: { + newName: 'BlockInputEvents', + since: '1.2.0', + removed: false, + }, +}); diff --git a/cocos/ui/deprecated.ts b/cocos/ui/deprecated.ts index f0b87d59cd..6a5eb2b7dc 100644 --- a/cocos/ui/deprecated.ts +++ b/cocos/ui/deprecated.ts @@ -23,10 +23,7 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ +import './deprecated-1.2.0'; import { UICoordinateTracker } from './ui-coordinate-tracker'; import { BlockInputEvents } from './block-input-events'; import { Button } from './button'; diff --git a/cocos/ui/editbox/edit-box-impl-base.ts b/cocos/ui/editbox/edit-box-impl-base.ts index d83d7fd5b6..79cafb19b5 100644 --- a/cocos/ui/editbox/edit-box-impl-base.ts +++ b/cocos/ui/editbox/edit-box-impl-base.ts @@ -30,11 +30,11 @@ import { EditBox } from './edit-box'; export class EditBoxImplBase { /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _editing = false; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _delegate: EditBox | null = null; diff --git a/cocos/ui/editbox/edit-box-impl.ts b/cocos/ui/editbox/edit-box-impl.ts index a27520464a..dc79eca4b4 100644 --- a/cocos/ui/editbox/edit-box-impl.ts +++ b/cocos/ui/editbox/edit-box-impl.ts @@ -60,35 +60,35 @@ let _domCount = 0; export class EditBoxImpl extends EditBoxImplBase { /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _delegate: EditBox | null = null; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _inputMode: InputMode = -1; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _inputFlag: InputFlag = -1; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _returnType: KeyboardReturnType = -1; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public __eventListeners: any = {}; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public __autoResize = false; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public __orientationChanged: any; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _edTxt: HTMLInputElement | HTMLTextAreaElement | null = null; private _isTextArea = false; @@ -182,33 +182,20 @@ export class EditBoxImpl extends EditBoxImplBase { } private _addDomToGameContainer () { - if (legacyCC.GAME_VIEW && this._edTxt) { - legacyCC.gameView.container.appendChild(this._edTxt); - legacyCC.gameView.head.appendChild(this._placeholderStyleSheet!); - } else if (game.container && this._edTxt) { + if (game.container && this._edTxt) { game.container.appendChild(this._edTxt); document.head.appendChild(this._placeholderStyleSheet!); } } private _removeDomFromGameContainer () { - const hasElem = legacyCC.GAME_VIEW ? contains(legacyCC.gameView.container, this._edTxt) - : contains(game.container, this._edTxt); + const hasElem = contains(game.container, this._edTxt); if (hasElem && this._edTxt) { - if (legacyCC.GAME_VIEW) { - legacyCC.gameView.container.removeChild(this._edTxt); - } else { - game.container!.removeChild(this._edTxt); - } + game.container!.removeChild(this._edTxt); } - const hasStyleSheet = legacyCC.GAME_VIEW ? contains(legacyCC.gameView.head, this._placeholderStyleSheet) - : contains(document.head, this._placeholderStyleSheet); + const hasStyleSheet = contains(document.head, this._placeholderStyleSheet); if (hasStyleSheet) { - if (legacyCC.GAME_VIEW) { - legacyCC.gameView.head.removeChild(this._placeholderStyleSheet); - } else { - document.head.removeChild(this._placeholderStyleSheet!); - } + document.head.removeChild(this._placeholderStyleSheet!); } this._edTxt = null; @@ -286,14 +273,6 @@ export class EditBoxImpl extends EditBoxImplBase { const node = this._delegate!.node; let scaleX = view.getScaleX(); let scaleY = view.getScaleY(); - let widthRatio = 1; - let heightRatio = 1; - if (legacyCC.GAME_VIEW) { - widthRatio = legacyCC.gameView.canvas.width / legacyCC.game.canvas.width; - heightRatio = legacyCC.gameView.canvas.height / legacyCC.game.canvas.height; - } - scaleX *= widthRatio; - scaleY *= heightRatio; const viewport = view.getViewportRect(); // TODO: implement editBox in PAL const dpr = screenAdapter.devicePixelRatio; @@ -325,14 +304,14 @@ export class EditBoxImpl extends EditBoxImplBase { scaleX /= dpr; scaleY /= dpr; - const container = legacyCC.GAME_VIEW ? legacyCC.gameView.container : game.container; + const container = game.container; const a = _matrix_temp.m00 * scaleX; const b = _matrix.m01; const c = _matrix.m04; const d = _matrix_temp.m05 * scaleY; let offsetX = parseInt((container && container.style.paddingLeft) || '0'); - offsetX += viewport.x * widthRatio / dpr; + offsetX += viewport.x / dpr; let offsetY = parseInt((container && container.style.paddingBottom) || '0'); offsetY += viewport.y / dpr; const tx = _matrix_temp.m12 * scaleX + offsetX; @@ -461,10 +440,11 @@ export class EditBoxImpl extends EditBoxImplBase { const elem = this._edTxt; if (elem && delegate) { elem.value = delegate.string; - elem.placeholder = delegate.placeholder; - this._updateTextLabel(delegate.textLabel); - this._updatePlaceholderLabel(delegate.placeholderLabel); + + // NOTE: we don't show placeholder any more when editBox is editing + // elem.placeholder = delegate.placeholder; + // this._updatePlaceholderLabel(delegate.placeholderLabel); } } diff --git a/cocos/ui/editbox/edit-box.ts b/cocos/ui/editbox/edit-box.ts index 9866c831d9..7587a133eb 100644 --- a/cocos/ui/editbox/edit-box.ts +++ b/cocos/ui/editbox/edit-box.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, executeInEditMode, executionOrder, menu, requireComponent, tooltip, displayOrder, type, serializable } from 'cc.decorator'; import { EDITOR, JSB, MINIGAME, RUNTIME_BASED } from 'internal:constants'; import { UITransform } from '../../2d/framework'; @@ -364,11 +359,11 @@ export class EditBox extends Component { public editingReturn: ComponentEventHandler[] = []; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _impl: EditBoxImplBase | null = null; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _background: Sprite | null = null; @@ -472,7 +467,7 @@ export class EditBox extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _editBoxEditingDidBegan () { ComponentEventHandler.emitEvents(this.editingDidBegan, this); @@ -480,7 +475,7 @@ export class EditBox extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _editBoxEditingDidEnded () { ComponentEventHandler.emitEvents(this.editingDidEnded, this); @@ -488,7 +483,7 @@ export class EditBox extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _editBoxTextChanged (text: string) { text = this._updateLabelStringStyle(text, true); @@ -498,7 +493,7 @@ export class EditBox extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _editBoxEditingReturn () { ComponentEventHandler.emitEvents(this.editingReturn, this); @@ -506,7 +501,7 @@ export class EditBox extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _showLabels () { this._isLabelVisible = true; @@ -514,7 +509,7 @@ export class EditBox extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _hideLabels () { this._isLabelVisible = false; @@ -622,7 +617,6 @@ export class EditBox extends Component { const transform = this._placeholderLabel!.node._uiProps.uiTransformComp; transform!.setAnchorPoint(0, 1); if (this._inputMode === InputMode.ANY) { - placeholderLabel.verticalAlign = VerticalTextAlignment.TOP; placeholderLabel.enableWrapText = true; } else { placeholderLabel.enableWrapText = false; @@ -742,9 +736,6 @@ export class EditBox extends Component { placeholderLabel.node._uiProps.uiTransformComp!.setContentSize(size.width - LEFT_PADDING, size.height); placeholderLabel.lineHeight = size.height; placeholderLabel.node.setPosition(offX + LEFT_PADDING, offY + size.height, placeholderLabel.node.position.z); - if (this._inputMode === InputMode.ANY) { - placeholderLabel.verticalAlign = VerticalTextAlignment.TOP; - } placeholderLabel.enableWrapText = this._inputMode === InputMode.ANY; } } diff --git a/cocos/ui/layout.ts b/cocos/ui/layout.ts index 77c882539e..e7464c24f3 100644 --- a/cocos/ui/layout.ts +++ b/cocos/ui/layout.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, executeInEditMode, executionOrder, menu, requireComponent, tooltip, type, displayOrder, serializable, visible, displayName } from 'cc.decorator'; import { Component } from '../core/components/component'; import { Rect, Size, Vec2, Vec3 } from '../core/math'; diff --git a/cocos/ui/page-view-indicator.ts b/cocos/ui/page-view-indicator.ts index 30e9003afe..42aab6467e 100644 --- a/cocos/ui/page-view-indicator.ts +++ b/cocos/ui/page-view-indicator.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, executionOrder, menu, tooltip, type, serializable } from 'cc.decorator'; import { SpriteFrame } from '../2d/assets'; import { Component } from '../core/components'; @@ -38,7 +33,7 @@ import { Node } from '../core/scene-graph'; import { Layout } from './layout'; import { PageView } from './page-view'; import { Sprite } from '../2d/components/sprite'; -import { Renderable2D } from '../2d/framework/renderable-2d'; +import { UIRenderer } from '../2d/framework/ui-renderer'; import { legacyCC } from '../core/global-exports'; const _color = new Color(); @@ -106,7 +101,7 @@ export class PageViewIndicator extends Component { * @zh * 页面标记摆放方向 * - * @param direction 摆放方向 + * @param direction @en The direction of the PageViewIndicator @zh 页面标记的摆放方向 */ @type(Direction) @tooltip('i18n:pageview_indicator.direction') @@ -174,7 +169,7 @@ export class PageViewIndicator extends Component { * @zh * 设置页面视图 * - * @param target 页面视图对象 + * @param target @en The page view which is attached with this indicator @zh 当前标记对象附着到的页面视图对象 */ public setPageView (target: PageView) { this._pageView = target; @@ -182,7 +177,7 @@ export class PageViewIndicator extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _updateLayout () { this._layout = this.getComponent(Layout); @@ -202,7 +197,7 @@ export class PageViewIndicator extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _createIndicator () { const node = new Node(); @@ -216,7 +211,7 @@ export class PageViewIndicator extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _changedState () { const indicators = this._indicators; @@ -229,14 +224,14 @@ export class PageViewIndicator extends Component { continue; } - const uiComp = node._uiProps.uiComp as Renderable2D; + const uiComp = node._uiProps.uiComp as UIRenderer; _color.set(uiComp.color); _color.a = 255 / 2; uiComp.color = _color; } if (indicators[idx]._uiProps.uiComp) { - const comp = indicators[idx]._uiProps.uiComp as Renderable2D; + const comp = indicators[idx]._uiProps.uiComp as UIRenderer; _color.set(comp.color); _color.a = 255; comp.color = _color; @@ -244,7 +239,7 @@ export class PageViewIndicator extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _refresh () { if (!this._pageView) { return; } diff --git a/cocos/ui/page-view.ts b/cocos/ui/page-view.ts index a99a74ada8..f6cbb0659f 100644 --- a/cocos/ui/page-view.ts +++ b/cocos/ui/page-view.ts @@ -23,10 +23,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ import { ccclass, help, executionOrder, menu, tooltip, type, slide, range, visible, override, serializable, editable } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; @@ -354,7 +350,7 @@ export class PageView extends ScrollView { * @zh * 返回当前页面索引。 * - * @returns 当前页面索引。 + * @returns @en Current page index of this page view @zh 当前页面索引。 */ public getCurrentPageIndex () { return this._curPageIdx; @@ -366,7 +362,7 @@ export class PageView extends ScrollView { * * @zh * 设置当前页面索引。 - * @param index 索引。 + * @param index @en The page index to scroll to @zh 需要滚动到的页面索引 */ public setCurrentPageIndex (index: number) { this.scrollToPage(index, 1); @@ -379,7 +375,7 @@ export class PageView extends ScrollView { * @zh * 返回视图中的所有页面。 * - * @returns 输=视图所有页面。 + * @returns @en return all pages of this page view @zh 返回当前视图所有页面 */ public getPages () { return this._pages; @@ -392,7 +388,7 @@ export class PageView extends ScrollView { * @zh * 在当前页面视图的尾部插入一个新视图。 * - * @param page 新视图。 + * @param page @en New page to add to this page view @zh 新加入的视图 */ public addPage (page: Node) { if (!page || this._pages.indexOf(page) !== -1 || !this.content) { @@ -414,8 +410,8 @@ export class PageView extends ScrollView { * @zh * 将页面插入指定位置中。 * - * @param page 新视图。 - * @param index 指定位置。 + * @param page @en New page to insert to this page view @zh 新插入的视图 + * @param index @en The index of new page to be inserted @zh 新插入视图的索引 */ public insertPage (page: Node, index: number) { if (index < 0 || !page || this._pages.indexOf(page) !== -1 || !this.content) { @@ -442,7 +438,7 @@ export class PageView extends ScrollView { * @zh * 移除指定页面。 * - * @param page 指定页面。 + * @param page @en The page to be removed @zh 将被移除的页面 */ public removePage (page: Node) { if (!page || !this.content) { return; } @@ -461,7 +457,7 @@ export class PageView extends ScrollView { * @zh * 移除指定下标的页面。 * - * @param index 页面下标。 + * @param index @en The index of the page to be removed @zh 将被移除界面的页面下标 */ public removePageAtIndex (index: number) { const pageList = this._pages; @@ -497,8 +493,8 @@ export class PageView extends ScrollView { * @zh * 滚动到指定页面 * - * @param idx index of page. - * @param timeInSecond scrolling time. + * @param idx @en The index of page to be scroll to @zh 希望滚动到的页面下标 + * @param timeInSecond @en How long time to scroll to the page, in seconds @zh 滚动到指定页面所需时间,单位:秒 */ public scrollToPage (idx: number, timeInSecond = 0.3) { if (idx < 0 || idx >= this._pages.length) { @@ -776,8 +772,8 @@ export class PageView extends ScrollView { * @zh * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 * @event page-turning - * @param {Event.EventCustom} event - * @param {PageView} pageView - The PageView component. + * @param event + * @param pageView - The PageView component. */ legacyCC.PageView = PageView; diff --git a/cocos/ui/progress-bar.ts b/cocos/ui/progress-bar.ts index ef330d5b6d..fb2735a993 100644 --- a/cocos/ui/progress-bar.ts +++ b/cocos/ui/progress-bar.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, executionOrder, menu, requireComponent, tooltip, type, range, slide, serializable } from 'cc.decorator'; import { Component } from '../core/components/component'; import { UITransform } from '../2d/framework'; diff --git a/cocos/ui/safe-area.ts b/cocos/ui/safe-area.ts index 200ecb4f5a..5a1d6e51e2 100644 --- a/cocos/ui/safe-area.ts +++ b/cocos/ui/safe-area.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, executionOrder, menu, executeInEditMode, requireComponent } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { screenAdapter } from 'pal/screen-adapter'; diff --git a/cocos/ui/scroll-bar.ts b/cocos/ui/scroll-bar.ts index c9cf59ad17..30ca96321d 100644 --- a/cocos/ui/scroll-bar.ts +++ b/cocos/ui/scroll-bar.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, executionOrder, menu, requireComponent, tooltip, displayOrder, type, serializable } from 'cc.decorator'; import { Component } from '../core/components/component'; import { UITransform } from '../2d/framework'; @@ -229,7 +224,7 @@ export class ScrollBar extends Component { * @zh * 重置滚动条位置。 * - * @param outOfBoundary - 滚动位移。 + * @param outOfBoundary @en Rolling displacement @zh 滚动位移。 */ public onScroll (outOfBoundary: Vec2 | Readonly) { if (!this._scrollView) { @@ -289,10 +284,13 @@ export class ScrollBar extends Component { } /** + * @en + * Sets the scroll view. + * * @zh * 滚动视窗设置。 * - * @param scrollView - 滚动视窗。 + * @param scrollView @en The scroll view which is attached with this scroll bar @zh 当前滚动条附着的滚动视窗 */ public setScrollView (scrollView: ScrollView) { this._scrollView = scrollView; diff --git a/cocos/ui/scroll-view.ts b/cocos/ui/scroll-view.ts index 3728b1fbe9..636fe2c4aa 100644 --- a/cocos/ui/scroll-view.ts +++ b/cocos/ui/scroll-view.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, executionOrder, menu, requireComponent, tooltip, displayOrder, range, type, serializable } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { EventHandler as ComponentEventHandler } from '../core/components/component-event-handler'; @@ -447,8 +442,9 @@ export class ScrollView extends ViewGroup { * @zh * 视图内容将在规定时间内滚动到视图底部。 * - * @param timeInSecond - 滚动时间(s)。 如果超时,内容将立即跳到底部边界。 - * @param attenuated - 滚动加速是否衰减,默认为 true。 + * @param timeInSecond + * @en The rolling time(in seconds). If time is up, the content will slide to the bottom border. @zh 滚动时间(s)。 如果超时,内容将立即跳到底部边界。 + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true * @example * ```ts * // Scroll to the bottom of the view. @@ -476,8 +472,9 @@ export class ScrollView extends ViewGroup { * @zh * 视图内容将在规定时间内滚动到视图顶部。 * - * @param timeInSecond - 滚动时间(s)。 如果超时,内容将立即跳到顶部边界。 - * @param attenuated - 滚动加速是否衰减,默认为 true。 + * @param timeInSecond + * @en The rolling time(in seconds). If time is up, the content will slide to the bottom border. @zh 滚动时间(s)。 如果超时,内容将立即跳到底部边界。 + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true * @example * ```ts * // Scroll to the top of the view. @@ -505,8 +502,9 @@ export class ScrollView extends ViewGroup { * @zh * 视图内容将在规定时间内滚动到视图左边。 * - * @param timeInSecond - 滚动时间(s)。 如果超时,内容将立即跳到左边边界。 - * @param attenuated - 滚动加速是否衰减,默认为 true。 + * @param timeInSecond + * @en The rolling time(in seconds). If time is up, the content will slide to the bottom border. @zh 滚动时间(s)。 如果超时,内容将立即跳到底部边界。 + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true * @example * ```ts * // Scroll to the left of the view. @@ -534,8 +532,9 @@ export class ScrollView extends ViewGroup { * @zh * 视图内容将在规定时间内滚动到视图右边。 * - * @param timeInSecond - 滚动时间(s)。 如果超时,内容将立即跳到右边边界。 - * @param attenuated - 滚动加速是否衰减,默认为 true。 + * @param timeInSecond + * @en The rolling time(in seconds). If time is up, the content will slide to the bottom border. @zh 滚动时间(s)。 如果超时,内容将立即跳到底部边界。 + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true * @example * ```ts * // Scroll to the right of the view. @@ -563,8 +562,9 @@ export class ScrollView extends ViewGroup { * @zh * 视图内容将在规定时间内滚动到视图左上角。 * - * @param timeInSecond - 滚动时间(s)。 如果超时,内容将立即跳到左上边边界。 - * @param attenuated - 滚动加速是否衰减,默认为 true。 + * @param timeInSecond + * @en The rolling time(in seconds). If time is up, the content will slide to the bottom border. @zh 滚动时间(s)。 如果超时,内容将立即跳到底部边界。 + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true * @example * ```ts * // Scroll to the upper left corner of the view. @@ -592,8 +592,9 @@ export class ScrollView extends ViewGroup { * @zh * 视图内容将在规定时间内滚动到视图右上角。 * - * @param timeInSecond - 滚动时间(s)。 如果超时,内容将立即跳到右上边界。 - * @param attenuated - 滚动加速是否衰减,默认为 true。 + * @param timeInSecond + * @en The rolling time(in seconds). If time is up, the content will slide to the bottom border. @zh 滚动时间(s)。 如果超时,内容将立即跳到底部边界。 + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true * @example * ```ts * // Scroll to the top right corner of the view. @@ -621,8 +622,9 @@ export class ScrollView extends ViewGroup { * @zh * 视图内容将在规定时间内滚动到视图左下角。 * - * @param timeInSecond - 滚动时间(s)。 如果超时,内容将立即跳到左下边界。 - * @param attenuated - 滚动加速是否衰减,默认为 true。 + * @param timeInSecond + * @en The rolling time(in seconds). If time is up, the content will slide to the bottom border. @zh 滚动时间(s)。 如果超时,内容将立即跳到底部边界。 + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true * @example * ```ts * // Scroll to the lower left corner of the view. @@ -650,8 +652,9 @@ export class ScrollView extends ViewGroup { * @zh * 视图内容将在规定时间内滚动到视图右下角。 * - * @param timeInSecond - 滚动时间(s)。 如果超时,内容将立即跳到右边下边界。 - * @param attenuated - 滚动加速是否衰减,默认为 true。 + * @param timeInSecond + * @en The rolling time(in seconds). If time is up, the content will slide to the bottom border. @zh 滚动时间(s)。 如果超时,内容将立即跳到底部边界。 + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true * @example * ```ts * // Scroll to the lower right corner of the view. @@ -674,14 +677,17 @@ export class ScrollView extends ViewGroup { /** * @en - * Scroll with an offset related to the ScrollView's top left origin, if timeInSecond is omitted, then it will jump to the specific offset immediately. + * Scroll with an offset related to the ScrollView's top left origin, if timeInSecond is omitted, + * then it will jump to the specific offset immediately. * * @zh * 视图内容在规定时间内将滚动到 ScrollView 相对左上角原点的偏移位置, 如果 timeInSecond 参数不传,则立即滚动到指定偏移位置。 * - * @param offset - 滚动视图后,视图内容(content)相对于视图窗口(viewport)的位置。 - * @param timeInSecond - 滚动时间(s)。 如果超时,内容将立即跳到指定偏移量处。 - * @param attenuated - 滚动加速是否衰减,默认为 true。 + * @param offset + * @en After scrolling the view, the position of the view content relative to the view window. @zh 滚动视图后,视图内容(content)相对于视图窗口(viewport)的位置。 + * @param timeInSecond + * @en Scroll time (s). If it times out, the content immediately jumps to the specified offset. @zh 滚动时间(s)。 如果超时,内容将立即跳到指定偏移量处。 + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true * @example * ```ts * // Scroll to middle position in 0.1 second in x-axis @@ -716,7 +722,7 @@ export class ScrollView extends ViewGroup { * @zh * 获取滚动视图相对于视图窗口左上角原点的位置。 * - * @return - 当前滚动偏移量。 + * @return @en Current rolling offset @zh 当前滚动偏移量 */ public getScrollOffset () { const topDelta = this._getContentTopBoundary() - this._topBoundary; @@ -732,7 +738,7 @@ export class ScrollView extends ViewGroup { * @zh * 获取滚动视图最大可以滚动的偏移量。 * - * @return - 最大可滚动偏移量。 + * @return @en Maximum scrollable offset @zh 最大可滚动偏移量 */ public getMaxScrollOffset () { if (!this._content || !this.view) { @@ -754,9 +760,11 @@ export class ScrollView extends ViewGroup { * @zh * 视图内容在规定时间内将滚动到 ScrollView 水平方向的百分比位置上。 * - * @param percent - 0 - 之间的百分比。 - * @param timeInSecond - 滚动时间(s)。 如果超时,内容将立即跳到指定水平百分比位置。 - * @param attenuated - 滚动加速是否衰减,默认为 true。 + * @param percent + * @en Scroll to the destination which is located at the percent interpolation from left border to the right border @zh 滚动到从左到右指定百分比插值的位置 + * @param timeInSecond + * @en Scroll time (s). If it times out, the content immediately jumps to the specified offset. @zh 滚动时间(s)。 如果超时,内容将立即跳到指定偏移量处。 + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true * @example * ```ts * // Scroll to middle position. @@ -784,9 +792,12 @@ export class ScrollView extends ViewGroup { * @zh * 视图内容在规定时间内进行垂直方向和水平方向的滚动,并且滚动到指定百分比位置上。 * - * @param anchor - 在 new Vec2(0,0) and new Vec2(1,1) 上取差值的一个点。 - * @param timeInSecond - 滚动时间(s)。 如果超时,内容将立即跳到指定水平或垂直百分比位置。 - * @param attenuated - 滚动加速是否衰减,默认为 true。 + * @param anchor + * @en Scroll to the destination which is located at the anchor interpolation from left/top border to the right/bottom border + * @zh 滚动到从左/上到右/下指定锚点对应分量插值的位置 + * @param timeInSecond + * @en Scroll time (s). If it times out, the content immediately jumps to the specified offset. @zh 滚动时间(s)。 如果超时,内容将立即跳到指定偏移量处。 + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true * @example * ```ts * // Vertical scroll to the bottom of the view. @@ -817,9 +828,11 @@ export class ScrollView extends ViewGroup { * @zh * 视图内容在规定时间内滚动到 ScrollView 垂直方向的百分比位置上。 * - * @param percent - 0 - 1 之间的百分比。 - * @param timeInSecond - 滚动时间(s)。 如果超时,内容将立即跳到指定垂直百分比位置。 - * @param attenuated - 滚动加速是否衰减,默认为 true。 + * @param percent + * @en Scroll to the destination which is located at the percent interpolation from top border to the bottom border @zh 滚动到从上到下指定百分比插值的位置 + * @param timeInSecond + * @en Scroll time (s). If it times out, the content immediately jumps to the specified offset. @zh 滚动时间(s)。 如果超时,内容将立即跳到指定偏移量处。 + * @param attenuated @en Whether the rolling acceleration is attenuated(The default is true) @zh 滚动加速是否衰减,默认为 true * @example * ```ts * scrollView.scrollToPercentVertical(0.5, 0.1); @@ -858,7 +871,7 @@ export class ScrollView extends ViewGroup { * @zh * 设置当前视图内容的坐标点。 * - * @param position - current content position. + * @param position @en Current content position @zh 希望设置内容框体的位置 * @deprecated Since 3.1.0, setContentPosition is deprecated, please use scrollToOffset instead. */ public setContentPosition (position: Vec3) { @@ -1639,7 +1652,7 @@ export class ScrollView extends ViewGroup { if (!this._autoScrollCurrentlyOutOfBoundary) { this._autoScrollCurrentlyOutOfBoundary = true; this._autoScrollBraking = true; - this._autoScrollBrakingStartPosition = this._getContentPosition(); + Vec3.copy(this._autoScrollBrakingStartPosition, this._getContentPosition()); return true; } } else { diff --git a/cocos/ui/slider.ts b/cocos/ui/slider.ts index f6ee21d7f4..81c9c801a7 100644 --- a/cocos/ui/slider.ts +++ b/cocos/ui/slider.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, executionOrder, menu, requireComponent, tooltip, type, slide, range, serializable } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { Component, EventHandler } from '../core/components'; diff --git a/cocos/ui/sub-context-view.ts b/cocos/ui/sub-context-view.ts index 54f4500531..eb1083ec21 100644 --- a/cocos/ui/sub-context-view.ts +++ b/cocos/ui/sub-context-view.ts @@ -23,13 +23,8 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component - */ - import { ccclass, help, menu, executionOrder, requireComponent, tooltip, serializable } from 'cc.decorator'; -import { EDITOR } from 'internal:constants'; +import { EDITOR, WECHAT } from 'internal:constants'; import { minigame } from 'pal/minigame'; import { screenAdapter } from 'pal/screen-adapter'; import { Component } from '../core/components/component'; @@ -156,8 +151,22 @@ export class SubContextView extends Component { private _initSharedCanvas () { if (this._openDataContext) { const sharedCanvas = this._openDataContext.canvas; - sharedCanvas.width = this._designResolutionSize.width; - sharedCanvas.height = this._designResolutionSize.height; + let designWidth = this._designResolutionSize.width; + let designHeight = this._designResolutionSize.height; + if (WECHAT) { + // HACK: on WeChat platform, at least one side of the width and height of sharedCanvas is greater than 513 + // When the sharedCanvas is smaller than this size, the rendering doesn't work. + const minimumSize = 513; + if (designWidth <= minimumSize && designHeight <= minimumSize) { + const scaleWidth = minimumSize / designWidth; + const scaleHeight = minimumSize / designHeight; + const targetScale = scaleWidth < scaleHeight ? scaleWidth : scaleHeight; + designWidth *= targetScale; + designHeight *= targetScale; + } + } + sharedCanvas.width = designWidth; + sharedCanvas.height = designHeight; } } diff --git a/cocos/ui/toggle-container.ts b/cocos/ui/toggle-container.ts index fb80222f8f..4077dac0d9 100644 --- a/cocos/ui/toggle-container.ts +++ b/cocos/ui/toggle-container.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, executeInEditMode, executionOrder, menu, tooltip, type, serializable } from 'cc.decorator'; import { Component, EventHandler as ComponentEventHandler } from '../core/components'; import { Toggle } from './toggle'; @@ -127,8 +122,8 @@ export class ToggleContainer extends Component { * @zh * 刷新管理的 toggle 状态。 * - * @param toggle - 需要被更新的 toggle。 - * @param emitEvent - 是否需要触发事件 + * @param toggle @en The toggle to be updated @zh 需要被更新的切换键 + * @param emitEvent @en Whether events are needed to be emitted @zh 是否需要触发事件 */ public notifyToggleCheck (toggle: Toggle, emitEvent = true) { if (!this.enabledInHierarchy) { return; } diff --git a/cocos/ui/toggle.ts b/cocos/ui/toggle.ts index 7d5672bef8..a2a54329af 100644 --- a/cocos/ui/toggle.ts +++ b/cocos/ui/toggle.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, requireComponent, executionOrder, menu, tooltip, displayOrder, type, serializable } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { EventHandler as ComponentEventHandler } from '../core/components/component-event-handler'; @@ -104,7 +99,7 @@ export class Toggle extends Button { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ get _toggleContainer () { const parent = this.node.parent!; @@ -169,7 +164,7 @@ export class Toggle extends Button { * @zh * 设置 isChecked 而不调用 checkEvents 回调。 * - * @param value - 是否被按下 + * @param value @en Whether this toggle is pressed @zh 是否被按下 */ public setIsCheckedWithoutNotify (value: boolean) { this._set(value, false); @@ -212,8 +207,8 @@ export class Toggle extends Button { * @zh * 注意:此事件是从该组件所属的 Node 上面派发出来的,需要用 node.on 来监听。 * @event toggle - * @param {Event.EventCustom} event - * @param {Toggle} toggle - The Toggle component. + * @param event @en The event when toggle is pressed up or down @zh 切换键被按下或抬起时发送的事件 + * @param toggle @en The Toggle component @zh 切换键组件 */ legacyCC.Toggle = Toggle; diff --git a/cocos/ui/ui-coordinate-tracker.ts b/cocos/ui/ui-coordinate-tracker.ts index d2fded3bb8..c52aabf8c7 100644 --- a/cocos/ui/ui-coordinate-tracker.ts +++ b/cocos/ui/ui-coordinate-tracker.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component - */ - import { ccclass, help, menu, executionOrder, tooltip, type, serializable } from 'cc.decorator'; import { Component } from '../core/components/component'; import { EventHandler } from '../core/components/component-event-handler'; diff --git a/cocos/ui/view-group.ts b/cocos/ui/view-group.ts index 4d29937e82..6e0c86e8c6 100644 --- a/cocos/ui/view-group.ts +++ b/cocos/ui/view-group.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - /** * @en * Handling touch events in a ViewGroup takes special care, diff --git a/cocos/ui/widget.ts b/cocos/ui/widget.ts index a6733a8055..8731a549f4 100644 --- a/cocos/ui/widget.ts +++ b/cocos/ui/widget.ts @@ -24,11 +24,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module ui - */ - import { ccclass, help, executeInEditMode, executionOrder, menu, requireComponent, tooltip, type, editorOnly, editable, serializable, visible } from 'cc.decorator'; import { EDITOR, DEV } from 'internal:constants'; import { Component } from '../core/components'; @@ -727,19 +722,19 @@ export class Widget extends Component { public static AlignMode = AlignMode; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _lastPos = new Vec3(); /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _lastSize = new Size(); /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _dirty = true; /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _hadAlignOnce = false; @@ -805,7 +800,7 @@ export class Widget extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _validateTargetInDEV () { if (!DEV) { @@ -846,23 +841,23 @@ export class Widget extends Component { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _adjustWidgetToAllowMovingInEditor (eventType: TransformBit) {} /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _adjustWidgetToAllowResizingInEditor () {} /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _adjustWidgetToAnchorChanged () { this.setDirty(); } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ public _adjustTargetToParentChanged (oldParent: Node) { if (oldParent) { diff --git a/cocos/video/assets/video-clip.ts b/cocos/video/assets/video-clip.ts index e689636d03..2fb407cab0 100644 --- a/cocos/video/assets/video-clip.ts +++ b/cocos/video/assets/video-clip.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component/video - */ - import { ccclass, serializable } from 'cc.decorator'; import { Asset } from '../../core/assets'; @@ -48,7 +43,7 @@ export class VideoClip extends Asset { } /** - * @legacyPublic + * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. */ set _nativeAsset (clip: HTMLVideoElement | null) { this._video = clip; diff --git a/cocos/video/category.json b/cocos/video/category.json new file mode 100644 index 0000000000..e13098db8c --- /dev/null +++ b/cocos/video/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "视频", + "en": "Video" + }, + "description": { + "zh": "VideoPlayer 是一种视频播放组件,可通过该组件播放本地和远程视频。", + "en": "VideoPlayer is a component for playing videos, you could use this component for playing local video and remote videos." + } +} \ No newline at end of file diff --git a/cocos/video/video-downloader.ts b/cocos/video/video-downloader.ts index 3b71887f67..8a838cdd70 100644 --- a/cocos/video/video-downloader.ts +++ b/cocos/video/video-downloader.ts @@ -23,10 +23,6 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ -/** - * @packageDocumentation - * @module asset-manager - */ import downloader from '../core/asset-manager/downloader'; import factory from '../core/asset-manager/factory'; diff --git a/cocos/video/video-player-enums.ts b/cocos/video/video-player-enums.ts index c78636c3c8..c4e1065327 100644 --- a/cocos/video/video-player-enums.ts +++ b/cocos/video/video-player-enums.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component/video - */ - /** * @en Enum for video resource type. * @zh 视频来源 diff --git a/cocos/video/video-player-impl-manager.ts b/cocos/video/video-player-impl-manager.ts index 3379916b91..4a1e653d86 100644 --- a/cocos/video/video-player-impl-manager.ts +++ b/cocos/video/video-player-impl-manager.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component/video - */ - import { legacyCC } from '../core/global-exports'; import { VideoPlayer } from './video-player'; import { VideoPlayerImplWeb } from './video-player-impl-web'; diff --git a/cocos/video/video-player-impl-web.ts b/cocos/video/video-player-impl-web.ts index e65f3411f2..f2de1f58ff 100644 --- a/cocos/video/video-player-impl-web.ts +++ b/cocos/video/video-player-impl-web.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component/video - */ - import { screenAdapter } from 'pal/screen-adapter'; import { mat4 } from '../core/math'; import { sys, screen, warn } from '../core/platform'; diff --git a/cocos/video/video-player-impl.ts b/cocos/video/video-player-impl.ts index 909e798dbe..dc9f11bfc0 100644 --- a/cocos/video/video-player-impl.ts +++ b/cocos/video/video-player-impl.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component/video - */ - import { legacyCC } from '../core/global-exports'; import { UITransform } from '../2d/framework'; import { VideoPlayer } from './video-player'; diff --git a/cocos/video/video-player.ts b/cocos/video/video-player.ts index 1df5bf06c5..c4943ee519 100644 --- a/cocos/video/video-player.ts +++ b/cocos/video/video-player.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component/video - */ - import { ccclass, displayOrder, executeInEditMode, help, menu, slide, range, requireComponent, tooltip, type, serializable } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { warn } from '../core/platform'; @@ -248,7 +243,7 @@ export class VideoPlayer extends Component { */ @tooltip('i18n:videoplayer.fullScreenOnAwake') get fullScreenOnAwake () { - if (!EDITOR) { + if (!EDITOR || legacyCC.GAME_VIEW) { if (this._impl) { this._fullScreenOnAwake = this._impl.fullScreenOnAwake; return this._fullScreenOnAwake; @@ -269,8 +264,10 @@ export class VideoPlayer extends Component { * @en * Always below the game view (only useful on Web. * Note: The specific effects are not guaranteed to be consistent, depending on whether each browser supports or restricts). + * Note: This property depends on the translucency of Canvas, please enable ENABLE_TRANSPARENT_CANVAS in the project preferences * @zh * 永远在游戏视图最底层(这个属性只有在 Web 平台上有效果。注意:具体效果无法保证一致,跟各个浏览器是否支持与限制有关) + * 注意:该属性依赖 Canvas 的半透明特性,请在项目偏好设置里开启 ENABLE_TRANSPARENT_CANVAS */ @tooltip('i18n:videoplayer.stayOnBottom') get stayOnBottom () { @@ -372,7 +369,7 @@ export class VideoPlayer extends Component { } public __preload () { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { return; } this._impl = VideoPlayerImplManager.getImpl(this); diff --git a/cocos/web-view/category.json b/cocos/web-view/category.json new file mode 100644 index 0000000000..9f03b51c47 --- /dev/null +++ b/cocos/web-view/category.json @@ -0,0 +1,10 @@ +{ + "title": { + "zh": "WebView", + "en": "WebView" + }, + "description": { + "zh": "WebView 是一种显示网页的组件,该组件让你可以在游戏里面集成一个小的浏览器。由于不同平台对于 WebView 组件的授权、API、控制方式都不同,还没有形成统一的标准,所以目前只支持 Web、iOS 和 Android 平台。", + "en": "WebView is a component for displaying web pages, you could use this component to embed a mini web browser in your games. Because different platforms have different authorization, API and control methods for WebView component. And have not yet formed a unified standard, only Web, iOS, and Android platforms are currently supported." + } +} \ No newline at end of file diff --git a/cocos/web-view/web-view-enums.ts b/cocos/web-view/web-view-enums.ts index 27e554c61d..7996f3e80e 100644 --- a/cocos/web-view/web-view-enums.ts +++ b/cocos/web-view/web-view-enums.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component/web-view - */ - export enum EventType { /** * @en None diff --git a/cocos/web-view/web-view-impl-manager.ts b/cocos/web-view/web-view-impl-manager.ts index a781745d23..0b9ddf3b02 100644 --- a/cocos/web-view/web-view-impl-manager.ts +++ b/cocos/web-view/web-view-impl-manager.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component/web-view - */ - import { legacyCC } from '../core/global-exports'; import { WebViewImplWeb } from './web-view-impl-web'; diff --git a/cocos/web-view/web-view-impl-web.ts b/cocos/web-view/web-view-impl-web.ts index da15d356e0..06e48edf95 100644 --- a/cocos/web-view/web-view-impl-web.ts +++ b/cocos/web-view/web-view-impl-web.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component/web-view - */ - import { screenAdapter } from 'pal/screen-adapter'; import { EventType } from './web-view-enums'; import { error, warn } from '../core/platform'; diff --git a/cocos/web-view/web-view-impl.ts b/cocos/web-view/web-view-impl.ts index 6135c173f2..64ee646003 100644 --- a/cocos/web-view/web-view-impl.ts +++ b/cocos/web-view/web-view-impl.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component/web-view - */ - import { legacyCC } from '../core/global-exports'; import { WebView } from './web-view'; import { EventType } from './web-view-enums'; diff --git a/cocos/web-view/web-view.ts b/cocos/web-view/web-view.ts index 48b9616dbb..763d5145ad 100644 --- a/cocos/web-view/web-view.ts +++ b/cocos/web-view/web-view.ts @@ -23,11 +23,6 @@ THE SOFTWARE. */ -/** - * @packageDocumentation - * @module component/web-view - */ - import { ccclass, help, executeInEditMode, menu, tooltip, type, displayOrder, serializable, requireComponent } from 'cc.decorator'; import { EDITOR } from 'internal:constants'; import { UITransform } from '../2d/framework'; @@ -169,7 +164,7 @@ export class WebView extends Component { } public __preload () { - if (EDITOR) { + if (EDITOR && !legacyCC.GAME_VIEW) { return; } this._impl = WebViewImplManager.getImpl(this); diff --git a/native/docs/CODING_STYLE.md b/docs/CPP_CODING_STYLE.md similarity index 100% rename from native/docs/CODING_STYLE.md rename to docs/CPP_CODING_STYLE.md diff --git a/native/docs/LINTER_AUTOFIX_GUIDE.md b/docs/CPP_LINTER_AUTOFIX_GUIDE.md similarity index 98% rename from native/docs/LINTER_AUTOFIX_GUIDE.md rename to docs/CPP_LINTER_AUTOFIX_GUIDE.md index 5f6324668d..7b4b2be069 100644 --- a/native/docs/LINTER_AUTOFIX_GUIDE.md +++ b/docs/CPP_LINTER_AUTOFIX_GUIDE.md @@ -1,133 +1,133 @@ -# Linter Auto-fix Guide - -This is a guide to help you setting up the appropriate environment to enable auto-fixing most of the coding style check rules, including both `clang-format` and `clang-tidy`. - -For now, **Visual Studio Code** is our first recommended IDE for the job, while a brief discussion about the support in different IDEs can be found at the end of this document. - -## Environment Setup - -* Make sure both `clang-tidy` and `clang-format` are directly accessible in your terminal environment, i.e. install LLVM and add the bin folder into the environment path. LLVM 11+ is recommended. - - ![](imgs/LLVM.png) - -* Make sure you have `ANDROID_NDK_HOME` or `ANDROID_NDK_ROOT` or `NDK_ROOT` environment variable pointing to the Android NDK path. - - ![](imgs/NDK.png) - -* Open terminal (or git-bash/MSYS2 if you are on windows), navigate to `engine-native` folder and run: - - ```bash - utils/generate_compile_commands_android.sh # other platforms - utils/generate_compile_commands_android_windows.sh # if using git-bash on windows - ``` - - If it succeeds, you should see a `compile_commands.json` generated in the same folder, and ignored by git. - - ![](imgs/compile_commands.png) - -> Note: The `compile_commands.json` generated by the current approach is essentially the Android development environment. So other platform-specific code may likely not be included in the check. This behavior is consistent with the CI test environment. - -> Also note: After changes been made to CMake configurations, the `compile_commands.json` should be regenerated by running the same script in the last step. - -## VS Code With `clangd` and `Command Runner` Extension - -* Install both `clangd` and `Command Runner` extension from the market: - - ![](imgs/extensions.png) - -* If everything goes smoothly, after opening any source file, you should be able to see the `clang-tidy` extension's linting process and its output as warnings right inside the editor, without any errors. - - ![](imgs/editor-lint.png) - -* But in the case when you do see errors popping up like this: (note the red color in the scroll bar) - - ![](imgs/editor-lint-error.png) - - That means you have compile errors **for this single file**. Since it does compile on our target platforms as part of the engine project library, the most common cause for this issue is that it is not self-contained, i.e. the file does not include what it uses. You should always include all the headers your file depends on. - - In the case of this screenshot, the declaration of the base class `Object` is missing, so we are indeed missing headers. - -* After clearing the compile errors, you can fix most the issue by just clicking the light bulb on the side and choose an appropriate action. - - ![](imgs/manual-auto-fix.png) - -There are two important notes here: -* The issues reported here all come from `clangd` the language server, which only supports a subset of `clang-tidy` rules. -* It appears to be no 'fix-all' option in the editor. - -This is where the `Command Runner` extension comes in and saves the day: we can assign a suitable key binding to run any CLI commands, e.g. invoke the `clang-tidy` proper and fix all the issues in the current file! - -* Open the VSCode settings (JSON) and add the following property: - - ![](imgs/vscode-settings.png) - - ```js - "command-runner.commands": { - "tidy": "clang-tidy -fix '${file}'" - } - ``` - -* Open the keyboard shortcut preference (JSON) and add the following property: - - ![](imgs/keyboard-shortcut.png) - - ```js - { - "key": "shift+alt+c", // set this to any key binding that works best for you - "command": "command-runner.run", - "args": { "command": "tidy" } - } - ``` - - > Note: for more detailed instructions on setting keybindings, etc. refer to the `Command Runner` extension page. - -* If everything goes smoothly, you can finally auto-fix all the issues in the current opened file with a single key binding: - - ![](imgs/auto-fix.gif) - - Note that after auto-fix some issue could morph into new ones. (e.g. at line 774 in the screenshot above, the iterator type was auto-fixed into a simple `auto`, which in turn triggered another linter issue) Just remain calm and execute the fix again and most of them will be fixed correctly. - - Also note that by invoking `clang-tidy`, this is an unavoidably time-consuming process. - -* For `clang-format` issues, there are no in-place editor suggestions, but all issues are strictly auto-fixable, and if the environment set up above goes smoothly, it is as simple as executing the `Format Document` command. (By default `Shift + Alt + F` on Windows) - - ![](imgs/format.png) - - This functionality is provided by the `clangd` extension too. - - ![](imgs/auto-format.gif) - - On the contrary to `clang-tidy`, `clang-format` auto-formatting is an immediate operation and should be used frequently. - -## More Command Line Utilities - -On top of all the above infrastructures, we provide a bash script to apply auto-fix (both clang-tidy and clang-format issues) on all the changed files in arbitrary commit/range: - -First make sure the environment setup steps are done, i.e. `compile_commands.json` has been generated, then: - -```bash -utils/fix-tidy-format.sh # run auto-fix on files changed in the latest commit -utils/fix-tidy-format.sh 70181ed # run auto-fix on files changed in the specified commit -utils/fix-tidy-format.sh HEAD~3..HEAD # run auto-fix on files changed in the last 3 commit -``` - -All the issues will be reported in the standard output. This can be used as local self-test runs for CI checks. - -## Usage of `NOLINT` - -The general rule is: DO NOT USE IT. - -That being said, however, sometimes due to various reasons (clang-tidy false positives, fixing legacy codebase just requires too much work, etc.), when there is just no way around, you can use them with specific rule tags and reasons for why it has to be this way: -```cpp - // NOLINTNEXTLINE(google-explicit-constructor) false positive when involving __VA_ARGS__ - CC_VMATH_STRUCT(Model, transform, color, enabled) -``` -Never use `NOLINT` without any explanations or rule tags. - -## Other IDEs - -It is possible to use other IDEs as long as they [support clang-tidy](https://clang.llvm.org/extra/clang-tidy/Integrations.html). - -Notably there is `CLion`, or the `Resharper C++` MSVC extension that can do a fairly decent job on analyzing and fixing linter issues. But both are commercially licensed and [intentionally](https://resharper-support.jetbrains.com/hc/en-us/articles/207242695-Can-I-fix-all-issues-Quick-Fixes-naming-suggestions-etc-at-once-) lacks the functionality to apply fixes to all the issues. They can either apply auto-fix per issue instance or apply to the whole project by issue types. - -Considering the current circumstances this is usually not what we want in daily development, since the more files we touch, the heavier the burden is to pass the CI check, which detects problems on all the changed files in a single pull request. +# Linter Auto-fix Guide + +This is a guide to help you setting up the appropriate environment to enable auto-fixing most of the coding style check rules, including both `clang-format` and `clang-tidy`. + +For now, **Visual Studio Code** is our first recommended IDE for the job, while a brief discussion about the support in different IDEs can be found at the end of this document. + +## Environment Setup + +* Make sure both `clang-tidy` and `clang-format` are directly accessible in your terminal environment, i.e. install LLVM and add the bin folder into the environment path. LLVM 11+ is recommended. + + ![](imgs/LLVM.png) + +* Make sure you have `ANDROID_NDK_HOME` or `ANDROID_NDK_ROOT` or `NDK_ROOT` environment variable pointing to the Android NDK path. + + ![](imgs/NDK.png) + +* Open terminal (or git-bash/MSYS2 if you are on windows), navigate to `engine-native` folder and run: + + ```bash + utils/generate_compile_commands_android.sh # other platforms + utils/generate_compile_commands_android_windows.sh # if using git-bash on windows + ``` + + If it succeeds, you should see a `compile_commands.json` generated in the same folder, and ignored by git. + + ![](imgs/compile_commands.png) + +> Note: The `compile_commands.json` generated by the current approach is essentially the Android development environment. So other platform-specific code may likely not be included in the check. This behavior is consistent with the CI test environment. + +> Also note: After changes been made to CMake configurations, the `compile_commands.json` should be regenerated by running the same script in the last step. + +## VS Code With `clangd` and `Command Runner` Extension + +* Install both `clangd` and `Command Runner` extension from the market: + + ![](imgs/extensions.png) + +* If everything goes smoothly, after opening any source file, you should be able to see the `clang-tidy` extension's linting process and its output as warnings right inside the editor, without any errors. + + ![](imgs/editor-lint.png) + +* But in the case when you do see errors popping up like this: (note the red color in the scroll bar) + + ![](imgs/editor-lint-error.png) + + That means you have compile errors **for this single file**. Since it does compile on our target platforms as part of the engine project library, the most common cause for this issue is that it is not self-contained, i.e. the file does not include what it uses. You should always include all the headers your file depends on. + + In the case of this screenshot, the declaration of the base class `Object` is missing, so we are indeed missing headers. + +* After clearing the compile errors, you can fix most the issue by just clicking the light bulb on the side and choose an appropriate action. + + ![](imgs/manual-auto-fix.png) + +There are two important notes here: +* The issues reported here all come from `clangd` the language server, which only supports a subset of `clang-tidy` rules. +* It appears to be no 'fix-all' option in the editor. + +This is where the `Command Runner` extension comes in and saves the day: we can assign a suitable key binding to run any CLI commands, e.g. invoke the `clang-tidy` proper and fix all the issues in the current file! + +* Open the VSCode settings (JSON) and add the following property: + + ![](imgs/vscode-settings.png) + + ```js + "command-runner.commands": { + "tidy": "clang-tidy -fix '${file}'" + } + ``` + +* Open the keyboard shortcut preference (JSON) and add the following property: + + ![](imgs/keyboard-shortcut.png) + + ```js + { + "key": "shift+alt+c", // set this to any key binding that works best for you + "command": "command-runner.run", + "args": { "command": "tidy" } + } + ``` + + > Note: for more detailed instructions on setting keybindings, etc. refer to the `Command Runner` extension page. + +* If everything goes smoothly, you can finally auto-fix all the issues in the current opened file with a single key binding: + + ![](imgs/auto-fix.gif) + + Note that after auto-fix some issue could morph into new ones. (e.g. at line 774 in the screenshot above, the iterator type was auto-fixed into a simple `auto`, which in turn triggered another linter issue) Just remain calm and execute the fix again and most of them will be fixed correctly. + + Also note that by invoking `clang-tidy`, this is an unavoidably time-consuming process. + +* For `clang-format` issues, there are no in-place editor suggestions, but all issues are strictly auto-fixable, and if the environment set up above goes smoothly, it is as simple as executing the `Format Document` command. (By default `Shift + Alt + F` on Windows) + + ![](imgs/format.png) + + This functionality is provided by the `clangd` extension too. + + ![](imgs/auto-format.gif) + + On the contrary to `clang-tidy`, `clang-format` auto-formatting is an immediate operation and should be used frequently. + +## More Command Line Utilities + +On top of all the above infrastructures, we provide a bash script to apply auto-fix (both clang-tidy and clang-format issues) on all the changed files in arbitrary commit/range: + +First make sure the environment setup steps are done, i.e. `compile_commands.json` has been generated, then: + +```bash +utils/fix-tidy-format.sh # run auto-fix on files changed in the latest commit +utils/fix-tidy-format.sh 70181ed # run auto-fix on files changed in the specified commit +utils/fix-tidy-format.sh HEAD~3..HEAD # run auto-fix on files changed in the last 3 commit +``` + +All the issues will be reported in the standard output. This can be used as local self-test runs for CI checks. + +## Usage of `NOLINT` + +The general rule is: DO NOT USE IT. + +That being said, however, sometimes due to various reasons (clang-tidy false positives, fixing legacy codebase just requires too much work, etc.), when there is just no way around, you can use them with specific rule tags and reasons for why it has to be this way: +```cpp + // NOLINTNEXTLINE(google-explicit-constructor) false positive when involving __VA_ARGS__ + CC_VMATH_STRUCT(Model, transform, color, enabled) +``` +Never use `NOLINT` without any explanations or rule tags. + +## Other IDEs + +It is possible to use other IDEs as long as they [support clang-tidy](https://clang.llvm.org/extra/clang-tidy/Integrations.html). + +Notably there is `CLion`, or the `Resharper C++` MSVC extension that can do a fairly decent job on analyzing and fixing linter issues. But both are commercially licensed and [intentionally](https://resharper-support.jetbrains.com/hc/en-us/articles/207242695-Can-I-fix-all-issues-Quick-Fixes-naming-suggestions-etc-at-once-) lacks the functionality to apply fixes to all the issues. They can either apply auto-fix per issue instance or apply to the whole project by issue types. + +Considering the current circumstances this is usually not what we want in daily development, since the more files we touch, the heavier the burden is to pass the CI check, which detects problems on all the changed files in a single pull request. diff --git a/docs/contribution/deprecated-api.md b/docs/contribution/deprecated-api.md new file mode 100644 index 0000000000..54814a8381 --- /dev/null +++ b/docs/contribution/deprecated-api.md @@ -0,0 +1,151 @@ +# Deprecated API + +## Frame description + +In order to maintain the abandoned `API` while making it more friendly and convenient, it will be implemented through three functions: + +- `markAsWarning` embeds a warning in the property on the given object, and the property needs to exist on the given object. + +- `removeProperty` redefines the removed property on the given object, and embeds an error message. The property should not exist on the given object. + +- `replaceProperty` redefines the removed property on the given object, and embeds a warning and calls the new property. Incompatible parameters need to be adapted. The given object should not have the property. + +## Function signature + +```typescript +interface IRemoveItem { + /** The name of the obsolete property */ + name: string; + /** Number of warnings */ + logTimes?: number; + /** Additional suggestions */ + suggest?: string; +} + +interface IMarkItem { + /** The name of the obsolete property */ + name: string; + /** Number of warnings */ + logTimes?: number; + /** Additional suggestions */ + suggest?: string; +} + +interface IReplacement { + /** The name of the obsolete property */ + name: string; + /** Number of warnings */ + logTimes?: number; + /** Additional suggestions */ + suggest?: string; + /** The object of the discarded property */ + target?: object; + /** The name of the object of the discarded property */ + targetName?: string; + /** Custom replacement property (function) */ + customFunction?: Function; + /** Setter of custom replacement properties */ + customSetter?: (v: any) => void; + /** Getter for custom replacement propertys */ + customGetter?: () => any; +} + +export let removeProperty: (owner: object, ownerName: string, properties: IRemoveItem[]) => void; + +export let markAsWarning: (owner: object, ownerName: string, properties: IMarkItem[]) => void; + +export let replaceProperty: (owner: object, ownerName: string, properties: IReplacement[]) => void; + +/** This function is used to set the global default information output times */ +export function setDefaultLogTimes (times: number): void; +``` + +## Terms of Use + +According to the module division, each module maintains an obsolete file. In order to facilitate maintenance, the name is unified as deprecated.ts and placed in the directory of the corresponding module, and the file needs to be `import` in the `index.ts` file of the corresponding module, such as `import'./deprecated'`. + +> **Note**: the `deprecated.ts` file in the `cocos\utils` directory is a declaration and implementation file. + +## Usage example + +```typescript +// For APIs that are not compatible with replacement parameters, adapt them through appropriate custom functions +replaceProperty(AnimationComponent.prototype, 'AnimationComponent.prototype', [ + { + name: 'removeClip', + newName: 'removeState', + customFunction: function (...args: any) { + const arg0 = args[0] as AnimationClip; + return AnimationComponent.prototype.removeState.call(this, arg0.name); + } + } +]); + +replaceProperty(vmath, 'vmath', [ + { + name: 'vec2', + newName: 'Vec2', + target: math, + targetName: 'math', + 'logTimes': 1 + }, + { + name: 'EPSILON', + target: math, + targetName: 'math', + 'logTimes': 2 + } +]); + +removeProperty(vmath, 'vmath', [ + { + 'name': 'random', + 'suggest': 'use Math.random.' + } +]); + +markAsWarning(math, 'math', [ + { + 'name': 'toRadian' + } +]); +``` + +## Usage Notes + +- The operation targets are all objects. If you want to modify the member functions of the class, please pass in **target.prototype**. + +- `replaceProperty` does not pass in `newName` or `newTarget`, which means it is consistent with `name` or `target`. + +- If you want to control the number of times, it is best to call `setDefaultLogTimes` before use, because other modules may change the default times. + +## Deprecate Module Exported Name + +The engine supports deprecation of exported name since `3.6.0`, the above mentioned are object property deprecation operations. If you need to deprecate the object or type itself, you need to use the `deprecateModuleExportedName` interface. The usage example is as follows: + +```ts +deprecateModuleExportedName({ + ButtonComponent: { + newName: 'Button', + since: '1.2.0', + removed: false, + }, +}); + +deprecateModuleExportedName({ + replaceProperty: { + since: '3.6.0', + removed: false, + }, +}); +``` + +The project script will report a warning if the following import operations are performed: +```ts +import { ButtonComponent } from 'cc'; +``` +or +```ts +import * as cc from 'cc'; +console.log(cc.ButtonComponent); +``` \ No newline at end of file diff --git a/docs/contribution/deprecated-features.md b/docs/contribution/deprecated-features.md index 21f0c087a8..7de92fbe20 100644 --- a/docs/contribution/deprecated-features.md +++ b/docs/contribution/deprecated-features.md @@ -56,4 +56,6 @@ and the importing module: export * from './select-deprecated-1.2.0'; ``` +### More Reference +[How to deprecate an API](./deprecated-api.md) diff --git a/docs/contribution/modules.md b/docs/contribution/modules.md index 2e025de2d1..d94e75af98 100644 --- a/docs/contribution/modules.md +++ b/docs/contribution/modules.md @@ -4,10 +4,10 @@ ## Public modules Modules under `/exports` are considered as public modules. -**Only** public modules are visible to users. -Other modules transitively imported from public modules are private. +**Only** the bindings exported from public modules are visible to users. +Other modules even transitively imported from public modules are private. -The module `'cc'` is a module which export all from specific public modules: +The module `'cc'` is an artificial module which exports all from specific public modules: ```ts /* The source of module 'cc', for explanation purpose only */ @@ -50,8 +50,9 @@ If your API need to be in a brand new public module, you need to create the new ## Create public module -Creating a public module is simply add a module file under `/exports`. +Creating a public module is simply adding a module file under `/exports`. +Then, you need some extra steps to bring your public module to users: -Besides this, you need to config the category of the public module and whether the public module is defaulted, etc. +- Add an new element into `features` array in [cc.config.json](../../cc.config.json), **feature** means a feature set which might be selected by user. `modules` field indicates which public modules(see above) should be considered included while this feature is enabled. Each element of `modules` should be the extension-less file name of a public module. That JSON configuration file should have been associated with a schema file. For more fields or controls over that file, see the schema file. -Take a look at the `/cc.config.json`. The `features` field is the name(s) of public modules. +- Navigate to [render-config.json](../../editor/engine-features/render-config.json) to configure the feature's exterior in Editor. Also there's an associated schema file. diff --git a/native/docs/imgs/LLVM.png b/docs/imgs/LLVM.png similarity index 100% rename from native/docs/imgs/LLVM.png rename to docs/imgs/LLVM.png diff --git a/native/docs/imgs/NDK.png b/docs/imgs/NDK.png similarity index 100% rename from native/docs/imgs/NDK.png rename to docs/imgs/NDK.png diff --git a/native/docs/imgs/auto-fix.gif b/docs/imgs/auto-fix.gif similarity index 100% rename from native/docs/imgs/auto-fix.gif rename to docs/imgs/auto-fix.gif diff --git a/native/docs/imgs/auto-format.gif b/docs/imgs/auto-format.gif similarity index 100% rename from native/docs/imgs/auto-format.gif rename to docs/imgs/auto-format.gif diff --git a/native/docs/imgs/compile_commands.png b/docs/imgs/compile_commands.png similarity index 100% rename from native/docs/imgs/compile_commands.png rename to docs/imgs/compile_commands.png diff --git a/native/docs/imgs/editor-lint-error.png b/docs/imgs/editor-lint-error.png similarity index 100% rename from native/docs/imgs/editor-lint-error.png rename to docs/imgs/editor-lint-error.png diff --git a/native/docs/imgs/editor-lint.png b/docs/imgs/editor-lint.png similarity index 100% rename from native/docs/imgs/editor-lint.png rename to docs/imgs/editor-lint.png diff --git a/native/docs/imgs/extensions.png b/docs/imgs/extensions.png similarity index 100% rename from native/docs/imgs/extensions.png rename to docs/imgs/extensions.png diff --git a/native/docs/imgs/format.png b/docs/imgs/format.png similarity index 100% rename from native/docs/imgs/format.png rename to docs/imgs/format.png diff --git a/native/docs/imgs/keyboard-shortcut.png b/docs/imgs/keyboard-shortcut.png similarity index 100% rename from native/docs/imgs/keyboard-shortcut.png rename to docs/imgs/keyboard-shortcut.png diff --git a/native/docs/imgs/manual-auto-fix.png b/docs/imgs/manual-auto-fix.png similarity index 100% rename from native/docs/imgs/manual-auto-fix.png rename to docs/imgs/manual-auto-fix.png diff --git a/native/docs/imgs/vscode-settings.png b/docs/imgs/vscode-settings.png similarity index 100% rename from native/docs/imgs/vscode-settings.png rename to docs/imgs/vscode-settings.png diff --git a/editor/assets/Default-Particle.png.meta b/editor/assets/Default-Particle.png.meta index 6f63318789..12612b5f27 100644 --- a/editor/assets/Default-Particle.png.meta +++ b/editor/assets/Default-Particle.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "b5b27ab1-e740-4398-b407-848fc2b2c897", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,7 +26,8 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "b5b27ab1-e740-4398-b407-848fc2b2c897" + "imageUuidOrDatabaseUri": "b5b27ab1-e740-4398-b407-848fc2b2c897", + "visible": true }, "displayName": "Default-Particle", "id": "6c48a", @@ -36,6 +37,7 @@ "userData": { "type": "texture", "redirect": "b5b27ab1-e740-4398-b407-848fc2b2c897@6c48a", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/chunks/builtin.meta b/editor/assets/chunks/builtin.meta new file mode 100644 index 0000000000..e011724c9b --- /dev/null +++ b/editor/assets/chunks/builtin.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "85f366b2-d149-4b14-aa1d-4634e3c28f69", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/builtin/functionalities.meta b/editor/assets/chunks/builtin/functionalities.meta new file mode 100644 index 0000000000..fa8ad05d78 --- /dev/null +++ b/editor/assets/chunks/builtin/functionalities.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "784eb20c-c955-4a9b-a320-571a5c392f79", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/builtin/functionalities/fog.chunk b/editor/assets/chunks/builtin/functionalities/fog.chunk new file mode 100644 index 0000000000..36d7c71d7b --- /dev/null +++ b/editor/assets/chunks/builtin/functionalities/fog.chunk @@ -0,0 +1,31 @@ +#pragma define-meta CC_USE_FOG range([0, 4]) +#pragma define CC_FOG_LINEAR 0 +#pragma define CC_FOG_EXP 1 +#pragma define CC_FOG_EXP_SQUARED 2 +#pragma define CC_FOG_LAYERED 3 +#pragma define CC_FOG_NONE 4 + +#include +#if CC_USE_FOG != CC_FOG_NONE + #include +#endif + +// Fog helper functions +void CC_TRANSFER_FOG_BASE(vec4 pos, out float factor) +{ +#if CC_USE_FOG == CC_FOG_LINEAR + factor = LinearFog(pos, cc_cameraPos.xyz, cc_fogBase.x, cc_fogBase.y); +#elif CC_USE_FOG == CC_FOG_EXP + factor = ExpFog(pos, cc_cameraPos.xyz, cc_fogBase.x, cc_fogBase.z, cc_fogAdd.z); +#elif CC_USE_FOG == CC_FOG_EXP_SQUARED + factor = ExpSquaredFog(pos, cc_cameraPos.xyz, cc_fogBase.x, cc_fogBase.z, cc_fogAdd.z); +#elif CC_USE_FOG == CC_FOG_LAYERED + factor = LayeredFog(pos, cc_cameraPos.xyz, cc_fogAdd.x, cc_fogAdd.y, cc_fogAdd.z); +#else + factor = 1.0; +#endif +} + +void CC_APPLY_FOG_BASE(inout vec4 color, float factor) { + color = vec4(mix(cc_fogColor.rgb, color.rgb, factor), color.a); +} diff --git a/editor/assets/chunks/cc-fog-base.chunk.meta b/editor/assets/chunks/builtin/functionalities/fog.chunk.meta similarity index 60% rename from editor/assets/chunks/cc-fog-base.chunk.meta rename to editor/assets/chunks/builtin/functionalities/fog.chunk.meta index 88284d366a..58cb06b250 100644 --- a/editor/assets/chunks/cc-fog-base.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/fog.chunk.meta @@ -1,8 +1,8 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, - "uuid": "879b9f55-e5da-4d8f-bc84-3a12a20533ad", + "uuid": "02a04bf3-4c27-4596-81fd-dfc35224f1d1", "files": [], "subMetas": {}, "userData": {} diff --git a/editor/assets/chunks/morph.chunk b/editor/assets/chunks/builtin/functionalities/morph-animation.chunk similarity index 82% rename from editor/assets/chunks/morph.chunk rename to editor/assets/chunks/builtin/functionalities/morph-animation.chunk index 477188d8da..9d69842a1f 100644 --- a/editor/assets/chunks/morph.chunk +++ b/editor/assets/chunks/builtin/functionalities/morph-animation.chunk @@ -1,13 +1,5 @@ -// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. - -#include // decode32 -#pragma define-meta CC_MORPH_TARGET_COUNT range([2, 8]) - -#pragma builtin(local) -layout(set = 2, binding = 4) uniform CCMorph { - vec4 cc_displacementWeights[15]; - vec4 cc_displacementTextureInfo; -}; +#include // decode32 +#include /** * Fetch n-th pixel from texture, row by row. @@ -81,28 +73,23 @@ vec3 getVec3DisplacementFromTexture(sampler2D tex, int vertexIndex) { #endif } + #if CC_MORPH_TARGET_HAS_POSITION - #pragma builtin(local) - layout(set = 2, binding = 7) uniform sampler2D cc_PositionDisplacements; - vec3 getPositionDisplacement(int vertexId) { +vec3 getPositionDisplacement(int vertexId) { return getVec3DisplacementFromTexture(cc_PositionDisplacements, vertexId); - } +} #endif #if CC_MORPH_TARGET_HAS_NORMAL - #pragma builtin(local) - layout(set = 2, binding = 8) uniform sampler2D cc_NormalDisplacements; - vec3 getNormalDisplacement(int vertexId) { +vec3 getNormalDisplacement(int vertexId) { return getVec3DisplacementFromTexture(cc_NormalDisplacements, vertexId); - } +} #endif #if CC_MORPH_TARGET_HAS_TANGENT - #pragma builtin(local) - layout(set = 2, binding = 9) uniform sampler2D cc_TangentDisplacements; - vec3 getTangentDisplacement(int vertexId) { +vec3 getTangentDisplacement(int vertexId) { return getVec3DisplacementFromTexture(cc_TangentDisplacements, vertexId); - } +} #endif void applyMorph (inout vec4 position, inout vec3 normal, inout vec4 tangent) { diff --git a/editor/assets/chunks/cc-local-batch.chunk.meta b/editor/assets/chunks/builtin/functionalities/morph-animation.chunk.meta similarity index 60% rename from editor/assets/chunks/cc-local-batch.chunk.meta rename to editor/assets/chunks/builtin/functionalities/morph-animation.chunk.meta index 540a58a09c..354b4ae4f8 100644 --- a/editor/assets/chunks/cc-local-batch.chunk.meta +++ b/editor/assets/chunks/builtin/functionalities/morph-animation.chunk.meta @@ -1,8 +1,8 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, - "uuid": "21fbcb1c-648e-4700-b854-2a267fe50933", + "uuid": "3adaa06a-e674-487c-9d49-42bc398c255b", "files": [], "subMetas": {}, "userData": {} diff --git a/editor/assets/chunks/builtin/functionalities/shadow-map.chunk b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk new file mode 100644 index 0000000000..174a86c27e --- /dev/null +++ b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk @@ -0,0 +1,260 @@ +// used for replacing cc-shadow-map-base.chunk +#include +#include +#include + +#pragma define SHADOWMAP_FORMAT_RGBA8 1 +#pragma define SHADOWMAP_FORMAT_FLOAT 0 + +float CCGetLinearDepth(vec3 worldPos, float viewSpaceBias) { + vec4 viewPos = cc_matLightView * vec4(worldPos.xyz, 1.0); + viewPos.z += viewSpaceBias; + return GetLinearDepthFromViewSpace(viewPos.xyz, cc_shadowNFLSInfo.x, cc_shadowNFLSInfo.y); +} + +float CCGetLinearDepth(vec3 worldPos) { + return CCGetLinearDepth(worldPos, 0.0); +} + +#if CC_RECEIVE_SHADOW + #include + #include + + #include + #include + + + //////////////////////////////////////////////////////////Helper Functions + // When screenSpaceSingY and clipSpaceSignY have different signs, need to flip the uv + #pragma define CC_HANDLE_NDC_SAMPLE_FLIP(uv) uv = cc_cameraPos.w == 1.0 ? vec2(uv.x, 1.0 - uv.y) : uv + + bool GetShadowNDCPos(out vec3 shadowNDCPos, vec4 shadowPosWithDepthBias) + { + shadowNDCPos = shadowPosWithDepthBias.xyz / shadowPosWithDepthBias.w * 0.5 + 0.5; + if (shadowNDCPos.x < 0.0 || shadowNDCPos.x > 1.0 || + shadowNDCPos.y < 0.0 || shadowNDCPos.y > 1.0 || + shadowNDCPos.z < 0.0 || shadowNDCPos.z > 1.0) { + return false; + } + CC_HANDLE_NDC_SAMPLE_FLIP(shadowNDCPos.xy); + return true; + } + + vec4 ApplyShadowDepthBias_FaceNormal(vec4 shadowPos, vec3 worldNormal, float normalBias, mat4 matLightView, vec2 projScaleXY) + { + vec4 newShadowPos = shadowPos; + if (normalBias > EPSILON_LOWP) + { + vec4 viewNormal = matLightView * vec4(worldNormal, 0.0); + if (viewNormal.z < 0.1) + newShadowPos.xy += viewNormal.xy * projScaleXY * normalBias * clamp(viewNormal.z, 0.001, 0.1); + } + return newShadowPos; + } + + vec4 ApplyShadowDepthBias_Perspective(vec4 shadowPos, float viewspaceDepthBias) + { + // Recover the coord in view space: cc_matLightInvProj * shadowPos + vec3 viewSpacePos; + viewSpacePos.xy = shadowPos.xy * cc_shadowProjInfo.zw; + viewSpacePos.z = shadowPos.z * cc_shadowInvProjDepthInfo.x + shadowPos.w * cc_shadowInvProjDepthInfo.y; + + // Apply bias + viewSpacePos.xyz += cc_shadowProjDepthInfo.z * normalize(viewSpacePos.xyz) * viewspaceDepthBias; + + // Reconstuct clipspace: cc_matLightProj * viewSpacePos + vec4 clipSpacePos; + clipSpacePos.xy = viewSpacePos.xy * cc_shadowProjInfo.xy; + clipSpacePos.zw = viewSpacePos.z * cc_shadowProjDepthInfo.xz + vec2(cc_shadowProjDepthInfo.y, 0.0); + + // enabled linear depth? + #if CC_SHADOWMAP_USE_LINEAR_DEPTH + clipSpacePos.z = GetLinearDepthFromViewSpace(viewSpacePos.xyz, cc_shadowNFLSInfo.x, cc_shadowNFLSInfo.y); + clipSpacePos.z = (clipSpacePos.z * 2.0 - 1.0) * clipSpacePos.w; + #endif + + return clipSpacePos; + } + + // (projScaleZ, projBiasZ) = cc_shadowProjDepthInfo.xy + vec4 ApplyShadowDepthBias_Orthographic(vec4 shadowPos, float viewspaceDepthBias, float projScaleZ, float projBiasZ) + { + float coeffA = projScaleZ; + float coeffB = projBiasZ; + + // Recover the Z distance in view space: + float viewSpacePos_z = (shadowPos.z - coeffB) / coeffA; + + // Apply bias + viewSpacePos_z += viewspaceDepthBias; + + // Reconstuct clipspace + vec4 result = shadowPos; + result.z = viewSpacePos_z * coeffA + coeffB; + return result; + } + + vec4 ApplyShadowDepthBias_PerspectiveLinearDepth(vec4 shadowPos, float viewspaceDepthBias, vec3 worldPos) + { + // reverse operation for GetShadowNDCPos + shadowPos.z = CCGetLinearDepth(worldPos, viewspaceDepthBias) * 2.0 - 1.0; + shadowPos.z *= shadowPos.w; + return shadowPos; + } + + //////////////////////////////////////////////////////////Directional Light Shadow + float CCGetDirLightShadowFactorHard (vec4 shadowPosWithDepthBias) { + vec3 shadowNDCPos; + if (!GetShadowNDCPos(shadowNDCPos, shadowPosWithDepthBias)) { + return 1.0; + } + return NativePCFShadowFactorHard(shadowNDCPos, cc_shadowMap, cc_shadowWHPBInfo.xy); + } + + float CCGetDirLightShadowFactorSoft (vec4 shadowPosWithDepthBias) { + vec3 shadowNDCPos; + if (!GetShadowNDCPos(shadowNDCPos, shadowPosWithDepthBias)) { + return 1.0; + } + return NativePCFShadowFactorSoft(shadowNDCPos, cc_shadowMap, cc_shadowWHPBInfo.xy); + } + + float CCGetDirLightShadowFactorSoft3X (vec4 shadowPosWithDepthBias) { + vec3 shadowNDCPos; + if (!GetShadowNDCPos(shadowNDCPos, shadowPosWithDepthBias)) { + return 1.0; + } + return NativePCFShadowFactorSoft3X(shadowNDCPos, cc_shadowMap, cc_shadowWHPBInfo.xy); + } + + float CCGetDirLightShadowFactorSoft5X (vec4 shadowPosWithDepthBias) { + vec3 shadowNDCPos; + if (!GetShadowNDCPos(shadowNDCPos, shadowPosWithDepthBias)) { + return 1.0; + } + return NativePCFShadowFactorSoft5X(shadowNDCPos, cc_shadowMap, cc_shadowWHPBInfo.xy); + } + + + //////////////////////////////////////////////////////////Spot Light Shadow + float CCGetSpotLightShadowFactorHard (vec4 shadowPosWithDepthBias, vec3 worldPos) { + vec3 shadowNDCPos; + if (!GetShadowNDCPos(shadowNDCPos, shadowPosWithDepthBias)) { + return 1.0; + } + return NativePCFShadowFactorHard(shadowNDCPos, cc_spotShadowMap, cc_shadowWHPBInfo.xy); + } + + float CCGetSpotLightShadowFactorSoft (vec4 shadowPosWithDepthBias, vec3 worldPos) { + vec3 shadowNDCPos; + if (!GetShadowNDCPos(shadowNDCPos, shadowPosWithDepthBias)) { + return 1.0; + } + return NativePCFShadowFactorSoft(shadowNDCPos, cc_spotShadowMap, cc_shadowWHPBInfo.xy); + } + + float CCGetSpotLightShadowFactorSoft3X (vec4 shadowPosWithDepthBias, vec3 worldPos) { + vec3 shadowNDCPos; + if (!GetShadowNDCPos(shadowNDCPos, shadowPosWithDepthBias)) { + return 1.0; + } + return NativePCFShadowFactorSoft3X(shadowNDCPos, cc_spotShadowMap, cc_shadowWHPBInfo.xy); + } + + float CCGetSpotLightShadowFactorSoft5X (vec4 shadowPosWithDepthBias, vec3 worldPos) { + vec3 shadowNDCPos; + if (!GetShadowNDCPos(shadowNDCPos, shadowPosWithDepthBias)) { + return 1.0; + } + return NativePCFShadowFactorSoft5X(shadowNDCPos, cc_spotShadowMap, cc_shadowWHPBInfo.xy); + } + + + //////////////////////////////////////////////////////////Main Functions + float CCSpotShadowFactorBase(vec4 shadowPos, vec3 worldPos, vec2 shadowBias) + { + float pcf = cc_shadowWHPBInfo.z; + vec4 pos = vec4(1.0); + #if CC_SHADOWMAP_USE_LINEAR_DEPTH + pos = ApplyShadowDepthBias_PerspectiveLinearDepth(shadowPos, shadowBias.x, worldPos); + #else + pos = ApplyShadowDepthBias_Perspective(shadowPos, shadowBias.x); + #endif + + if (pcf > 2.9) { + return CCGetSpotLightShadowFactorSoft5X(pos, worldPos); + } else if (pcf > 1.9) { + return CCGetSpotLightShadowFactorSoft3X(pos, worldPos); + }else if (pcf > 0.9) { + return CCGetSpotLightShadowFactorSoft(pos, worldPos); + }else { + return CCGetSpotLightShadowFactorHard(pos, worldPos); + } + } + + float CCShadowFactorBase(vec4 shadowPos, vec3 N, vec2 shadowBias) + { + float realtimeShadow = 1.0; + vec4 pos = ApplyShadowDepthBias_FaceNormal(shadowPos, N, shadowBias.y, cc_matLightView, cc_shadowProjInfo.xy); + pos = ApplyShadowDepthBias_Orthographic(pos, shadowBias.x, cc_shadowProjDepthInfo.x, cc_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); + } + + + 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; + } + } + 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; + + 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); + } + return mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w); + } +#endif diff --git a/editor/assets/chunks/builtin/functionalities/shadow-map.chunk.meta b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk.meta new file mode 100644 index 0000000000..b10c803341 --- /dev/null +++ b/editor/assets/chunks/builtin/functionalities/shadow-map.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "d4c26490-0a2d-4b6a-9a52-55b5741f18a4", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/skinning-dqs.chunk b/editor/assets/chunks/builtin/functionalities/skinning-animation-dqs.chunk similarity index 57% rename from editor/assets/chunks/skinning-dqs.chunk rename to editor/assets/chunks/builtin/functionalities/skinning-animation-dqs.chunk index 517693404a..699ac3681b 100644 --- a/editor/assets/chunks/skinning-dqs.chunk +++ b/editor/assets/chunks/builtin/functionalities/skinning-animation-dqs.chunk @@ -1,5 +1,6 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. -#include + +#include #if CC_USE_BAKED_ANIMATION #if CC_DEVICE_SUPPORT_FLOAT_TEXTURE @@ -34,12 +35,48 @@ } #endif #else - void getJointDQ (float i, out vec4 Qr, out vec4 Qt, out vec3 S) { - int idx = int(i); - Qr = cc_joints[idx * 3]; - Qt = cc_joints[idx * 3 + 1]; - S = cc_joints[idx * 3 + 2].xyz; - } + #if CC_USE_REAL_TIME_JOINT_TEXTURE + #if CC_DEVICE_SUPPORT_FLOAT_TEXTURE + void getJointDQ (float i, out vec4 Qr, out vec4 Qt, out vec3 S) { + float x = i; + Qr = texture(cc_realtimeJoint, vec2( x / 256.0, 0.5 / 3.0)); + Qt = texture(cc_realtimeJoint, vec2( x / 256.0, 1.5 / 3.0)); + S = texture(cc_realtimeJoint, vec2( x / 256.0, 2.5 / 3.0)).xyz; + } + #else + void getJointDQ (float i, out vec4 Qr, out vec4 Qt, out vec3 S) { + float x = 4.0 * i; + vec4 v1 = vec4( + decode32(texture(cc_realtimeJoint, vec2((x + 0.5)/ 1024.0, 0.5 / 3.0))), + decode32(texture(cc_realtimeJoint, vec2((x + 1.5)/ 1024.0, 0.5 / 3.0))), + decode32(texture(cc_realtimeJoint, vec2((x + 2.5)/ 1024.0, 0.5 / 3.0))), + decode32(texture(cc_realtimeJoint, vec2((x + 3.5)/ 1024.0, 0.5 / 3.0))) + ); + vec4 v2 = vec4( + decode32(texture(cc_realtimeJoint, vec2((x + 0.5)/ 1024.0, 1.5 / 3.0))), + decode32(texture(cc_realtimeJoint, vec2((x + 1.5)/ 1024.0, 1.5 / 3.0))), + decode32(texture(cc_realtimeJoint, vec2((x + 2.5)/ 1024.0, 1.5 / 3.0))), + decode32(texture(cc_realtimeJoint, vec2((x + 3.5)/ 1024.0, 1.5 / 3.0))) + ); + vec4 v3 = vec4( + decode32(texture(cc_realtimeJoint, vec2((x + 0.5)/ 1024.0, 2.5 / 3.0))), + decode32(texture(cc_realtimeJoint, vec2((x + 1.5)/ 1024.0, 2.5 / 3.0))), + decode32(texture(cc_realtimeJoint, vec2((x + 2.5)/ 1024.0, 2.5 / 3.0))), + decode32(texture(cc_realtimeJoint, vec2((x + 3.5)/ 1024.0, 2.5 / 3.0))) + ); + Qr = v1; + Qt = v2; + S = v3.xyz; + } + #endif + #else + void getJointDQ (float i, out vec4 Qr, out vec4 Qt, out vec3 S) { + int idx = int(i); + Qr = cc_joints[idx * 3]; + Qt = cc_joints[idx * 3 + 1]; + S = cc_joints[idx * 3 + 2].xyz; + } + #endif #endif // [Kavan07] Skinning with Dual Quaternions diff --git a/editor/assets/chunks/builtin/functionalities/skinning-animation-dqs.chunk.meta b/editor/assets/chunks/builtin/functionalities/skinning-animation-dqs.chunk.meta new file mode 100644 index 0000000000..4daae2933a --- /dev/null +++ b/editor/assets/chunks/builtin/functionalities/skinning-animation-dqs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "80908463-4566-4fdf-9744-775605cd7ab7", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/skinning-lbs.chunk b/editor/assets/chunks/builtin/functionalities/skinning-animation-lbs.chunk similarity index 53% rename from editor/assets/chunks/skinning-lbs.chunk rename to editor/assets/chunks/builtin/functionalities/skinning-animation-lbs.chunk index 2d5792cab1..91799f39e0 100644 --- a/editor/assets/chunks/skinning-lbs.chunk +++ b/editor/assets/chunks/builtin/functionalities/skinning-animation-lbs.chunk @@ -1,5 +1,6 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. -#include + +#include #if CC_USE_BAKED_ANIMATION #if CC_DEVICE_SUPPORT_FLOAT_TEXTURE @@ -37,13 +38,48 @@ } #endif #else - mat4 getJointMatrix (float i) { - int idx = int(i); - vec4 v1 = cc_joints[idx * 3]; - vec4 v2 = cc_joints[idx * 3 + 1]; - vec4 v3 = cc_joints[idx * 3 + 2]; - return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0)); - } + #if CC_USE_REAL_TIME_JOINT_TEXTURE + #if CC_DEVICE_SUPPORT_FLOAT_TEXTURE + mat4 getJointMatrix (float i) { + float x = i; + vec4 v1 = texture(cc_realtimeJoint, vec2( x / 256.0, 0.5 / 3.0)); + vec4 v2 = texture(cc_realtimeJoint, vec2( x / 256.0, 1.5 / 3.0)); + vec4 v3 = texture(cc_realtimeJoint, vec2( x / 256.0, 2.5 / 3.0)); + return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0)); + } + #else + mat4 getJointMatrix (float i) { + float x = 4.0 * i; + vec4 v1 = vec4( + decode32(texture(cc_realtimeJoint, vec2((x + 0.5)/ 1024.0, 0.5 / 3.0))), + decode32(texture(cc_realtimeJoint, vec2((x + 1.5)/ 1024.0, 0.5 / 3.0))), + decode32(texture(cc_realtimeJoint, vec2((x + 2.5)/ 1024.0, 0.5 / 3.0))), + decode32(texture(cc_realtimeJoint, vec2((x + 3.5)/ 1024.0, 0.5 / 3.0))) + ); + vec4 v2 = vec4( + decode32(texture(cc_realtimeJoint, vec2((x + 0.5)/ 1024.0, 1.5 / 3.0))), + decode32(texture(cc_realtimeJoint, vec2((x + 1.5)/ 1024.0, 1.5 / 3.0))), + decode32(texture(cc_realtimeJoint, vec2((x + 2.5)/ 1024.0, 1.5 / 3.0))), + decode32(texture(cc_realtimeJoint, vec2((x + 3.5)/ 1024.0, 1.5 / 3.0))) + ); + vec4 v3 = vec4( + decode32(texture(cc_realtimeJoint, vec2((x + 0.5)/ 1024.0, 2.5 / 3.0))), + decode32(texture(cc_realtimeJoint, vec2((x + 1.5)/ 1024.0, 2.5 / 3.0))), + decode32(texture(cc_realtimeJoint, vec2((x + 2.5)/ 1024.0, 2.5 / 3.0))), + decode32(texture(cc_realtimeJoint, vec2((x + 3.5)/ 1024.0, 2.5 / 3.0))) + ); + return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0)); + } + #endif + #else + mat4 getJointMatrix (float i) { + int idx = int(i); + vec4 v1 = cc_joints[idx * 3]; + vec4 v2 = cc_joints[idx * 3 + 1]; + vec4 v3 = cc_joints[idx * 3 + 2]; + return mat4(vec4(v1.xyz, 0.0), vec4(v2.xyz, 0.0), vec4(v3.xyz, 0.0), vec4(v1.w, v2.w, v3.w, 1.0)); + } + #endif #endif mat4 skinMatrix () { diff --git a/editor/assets/chunks/builtin/functionalities/skinning-animation-lbs.chunk.meta b/editor/assets/chunks/builtin/functionalities/skinning-animation-lbs.chunk.meta new file mode 100644 index 0000000000..fb212ed6dd --- /dev/null +++ b/editor/assets/chunks/builtin/functionalities/skinning-animation-lbs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "258a17ce-6c50-4e8a-92aa-8ecec1a6af24", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/cc-local-batch.chunk b/editor/assets/chunks/builtin/functionalities/world-transform.chunk similarity index 66% rename from editor/assets/chunks/cc-local-batch.chunk rename to editor/assets/chunks/builtin/functionalities/world-transform.chunk index fe81194985..b4a1fd0844 100644 --- a/editor/assets/chunks/cc-local-batch.chunk +++ b/editor/assets/chunks/builtin/functionalities/world-transform.chunk @@ -1,19 +1,4 @@ -// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. - -#pragma define-meta USE_INSTANCING editor(elevated: true) -#pragma define-meta USE_BATCHING editor(elevated: true) - -#if !USE_INSTANCING - #if USE_BATCHING - #pragma define BATCHING_COUNT 10 - #pragma builtin(local) - layout(set = 2, binding = 0) uniform CCLocalBatched { - highp mat4 cc_matWorlds[BATCHING_COUNT]; - }; - #else - #include - #endif -#endif +#include void CCGetWorldMatrix(out mat4 matWorld) { diff --git a/editor/assets/chunks/builtin/functionalities/world-transform.chunk.meta b/editor/assets/chunks/builtin/functionalities/world-transform.chunk.meta new file mode 100644 index 0000000000..6d7ea1fe6b --- /dev/null +++ b/editor/assets/chunks/builtin/functionalities/world-transform.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "c2885f54-4ff2-4284-8bbc-b77bc71965b4", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/builtin/internal.meta b/editor/assets/chunks/builtin/internal.meta new file mode 100644 index 0000000000..818a0f3a1a --- /dev/null +++ b/editor/assets/chunks/builtin/internal.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "16ce72cc-31ca-4b20-86d3-28d643645218", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/alpha-test.chunk b/editor/assets/chunks/builtin/internal/alpha-test.chunk similarity index 100% rename from editor/assets/chunks/alpha-test.chunk rename to editor/assets/chunks/builtin/internal/alpha-test.chunk diff --git a/editor/assets/chunks/alpha-test.chunk.meta b/editor/assets/chunks/builtin/internal/alpha-test.chunk.meta similarity index 89% rename from editor/assets/chunks/alpha-test.chunk.meta rename to editor/assets/chunks/builtin/internal/alpha-test.chunk.meta index 407ebeb0ca..575c886b84 100644 --- a/editor/assets/chunks/alpha-test.chunk.meta +++ b/editor/assets/chunks/builtin/internal/alpha-test.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "2c3da5b6-0202-470a-a915-59f1e2968853", diff --git a/editor/assets/chunks/embedded-alpha.chunk b/editor/assets/chunks/builtin/internal/embedded-alpha.chunk similarity index 96% rename from editor/assets/chunks/embedded-alpha.chunk rename to editor/assets/chunks/builtin/internal/embedded-alpha.chunk index 9ce2cfe2ae..1a9aac6af2 100644 --- a/editor/assets/chunks/embedded-alpha.chunk +++ b/editor/assets/chunks/builtin/internal/embedded-alpha.chunk @@ -1,9 +1,9 @@ -// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. - -vec4 CCSampleWithAlphaSeparated(sampler2D tex, vec2 uv) { -#if CC_USE_EMBEDDED_ALPHA - return vec4(texture(tex, uv).rgb, texture(tex, uv + vec2(0.0, 0.5)).r); -#else - return texture(tex, uv); -#endif -} +// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. + +vec4 CCSampleWithAlphaSeparated(sampler2D tex, vec2 uv) { +#if CC_USE_EMBEDDED_ALPHA + return vec4(texture(tex, uv).rgb, texture(tex, uv + vec2(0.0, 0.5)).r); +#else + return texture(tex, uv); +#endif +} diff --git a/editor/assets/chunks/embedded-alpha.chunk.meta b/editor/assets/chunks/builtin/internal/embedded-alpha.chunk.meta similarity index 89% rename from editor/assets/chunks/embedded-alpha.chunk.meta rename to editor/assets/chunks/builtin/internal/embedded-alpha.chunk.meta index 807614d9ae..10ddc4f29f 100644 --- a/editor/assets/chunks/embedded-alpha.chunk.meta +++ b/editor/assets/chunks/builtin/internal/embedded-alpha.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "ef4fb7de-9b39-4eeb-9ae8-d292ff94a452", diff --git a/editor/assets/chunks/particle-common.chunk b/editor/assets/chunks/builtin/internal/particle-common.chunk similarity index 96% rename from editor/assets/chunks/particle-common.chunk rename to editor/assets/chunks/builtin/internal/particle-common.chunk index 1ff061abf9..4aba5d57da 100644 --- a/editor/assets/chunks/particle-common.chunk +++ b/editor/assets/chunks/builtin/internal/particle-common.chunk @@ -12,9 +12,9 @@ uniform Constants { vec4 nodeRotation; }; -#include -#include -#include +#include +#include +#include out mediump vec2 uv; out mediump vec4 color; diff --git a/editor/assets/chunks/particle-common.chunk.meta b/editor/assets/chunks/builtin/internal/particle-common.chunk.meta similarity index 89% rename from editor/assets/chunks/particle-common.chunk.meta rename to editor/assets/chunks/builtin/internal/particle-common.chunk.meta index 4c2252d3d0..d1117e8fa3 100644 --- a/editor/assets/chunks/particle-common.chunk.meta +++ b/editor/assets/chunks/builtin/internal/particle-common.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "7a49db3a-930e-4ffc-8659-a82141dabebb", diff --git a/editor/assets/chunks/particle-trail.chunk b/editor/assets/chunks/builtin/internal/particle-trail.chunk similarity index 94% rename from editor/assets/chunks/particle-trail.chunk rename to editor/assets/chunks/builtin/internal/particle-trail.chunk index 4e22480f79..c8935315da 100644 --- a/editor/assets/chunks/particle-trail.chunk +++ b/editor/assets/chunks/builtin/internal/particle-trail.chunk @@ -1,6 +1,6 @@ precision mediump float; -#include +#include in vec3 a_position; // center position in vec4 a_texCoord; // x:index y:size zw:texcoord in vec3 a_texCoord1; // xyz:velocity diff --git a/editor/assets/chunks/particle-trail.chunk.meta b/editor/assets/chunks/builtin/internal/particle-trail.chunk.meta similarity index 89% rename from editor/assets/chunks/particle-trail.chunk.meta rename to editor/assets/chunks/builtin/internal/particle-trail.chunk.meta index 910011983b..c299ebfbca 100644 --- a/editor/assets/chunks/particle-trail.chunk.meta +++ b/editor/assets/chunks/builtin/internal/particle-trail.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "df7d02d8-559a-4c02-9aac-3732cfc83d7a", diff --git a/editor/assets/chunks/particle-vs-gpu.chunk b/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk similarity index 88% rename from editor/assets/chunks/particle-vs-gpu.chunk rename to editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk index acc8e3ac51..bd886efdc5 100644 --- a/editor/assets/chunks/particle-vs-gpu.chunk +++ b/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk @@ -1,8 +1,8 @@ precision mediump float; -#include -#include -#include +#include +#include +#include #pragma define CURVE_MODE_FIX 1 #pragma define CURVE_MODE_BLEND 2 @@ -33,14 +33,22 @@ uniform TickConstants { }; in vec4 a_position_starttime; // center position,particle start time -in vec4 a_size_uv; // xyz:size, w:uv_0 -in vec4 a_rotation_uv; // xyz:rotation, w:uv_1 in vec4 a_color; in vec4 a_dir_life; // xyz:particle start velocity,w:particle lifetime in float a_rndSeed; +#if !CC_INSTANCE_PARTICLE + in vec4 a_size_uv; // xyz:size, w:uv_0 + in vec4 a_rotation_uv; // xyz:rotation, w:uv_1 +#endif +#if CC_INSTANCE_PARTICLE + in vec4 a_size_fid; // xyz:size, w:fid + in vec3 a_rotation; // xyz:rotation + in vec3 a_uv; +#endif + #if CC_RENDER_MODE == RENDER_MODE_MESH - in vec3 a_texCoord; // mesh uv + in vec3 a_texCoord; // mesh uv in vec3 a_texCoord3; // mesh vertices in vec3 a_normal; // mesh normal in vec4 a_color1; // mesh color @@ -87,7 +95,8 @@ float pseudoRandom(float x) { v *= 0.7071067812; // fix sheared 'distance' measurements - but this is 1D so unsure it's even a good thing to try v = y < 0.0 ? -v : v; return v; -#else +#endif +#if !USE_VK_SHADER float seed = mod(x, 233280.); float q = (seed * 9301. + 49297.) / 233280.; return fract(q); @@ -177,15 +186,26 @@ vec4 gpvs_main () { #if CC_RENDER_MODE == RENDER_MODE_MESH vec2 vertIdx = vec2(a_texCoord.x, a_texCoord.y); - #else - vec2 vertIdx = vec2(a_size_uv.w, a_rotation_uv.w); + #endif + #if CC_RENDER_MODE != RENDER_MODE_MESH + #if !CC_INSTANCE_PARTICLE + vec2 vertIdx = vec2(a_size_uv.w, a_rotation_uv.w); + #endif + #if CC_INSTANCE_PARTICLE + vec2 vertIdx = a_uv.xy; + #endif #endif vec4 velocity = vec4(a_dir_life.xyz, 0.); vec4 pos = vec4(a_position_starttime.xyz, 1.); // size - vec3 size = a_size_uv.xyz; + #if !CC_INSTANCE_PARTICLE + vec3 size = a_size_uv.xyz; + #endif + #if CC_INSTANCE_PARTICLE + vec3 size = a_size_fid.xyz; + #endif #if SIZE_OVER_TIME_MODULE_ENABLE if (u_size_mode == CURVE_MODE_FIX) { size *= unpackCurveData(size_over_time_tex0, timeCoord0); @@ -249,17 +269,24 @@ vec4 gpvs_main () { #endif // rotation - vec3 startRotation = a_rotation_uv.xyz; + #if !CC_INSTANCE_PARTICLE + vec3 startRotation = a_rotation_uv.xyz; + #endif + #if CC_INSTANCE_PARTICLE + vec3 startRotation = a_rotation; + #endif #if CC_RENDER_MODE != RENDER_MODE_MESH #if CC_RENDER_MODE == RENDER_MODE_BILLBOARD vec3 rotEuler = startRotation.xyz; #elif CC_RENDER_MODE == RENDER_MODE_STRETCHED_BILLBOARD vec3 rotEuler = vec3(0.); - #else + #endif + #if CC_RENDER_MODE != RENDER_MODE_BILLBOARD && CC_RENDER_MODE != RENDER_MODE_STRETCHED_BILLBOARD vec3 rotEuler = vec3(0., 0., startRotation.z); #endif vec4 rot = quaternionFromEuler(rotEuler); - #else + #endif + #if CC_RENDER_MODE == RENDER_MODE_MESH vec4 rot = quaternionFromEuler(startRotation); #endif @@ -295,7 +322,8 @@ vec4 gpvs_main () { float factor_c = pseudoRandom(a_rndSeed + COLOR_OVERTIME_RAND_OFFSET); color = a_color * mix(color_0, color_1, factor_c); } - #else + #endif + #if !COLOR_OVER_TIME_MODULE_ENABLE color = a_color; #endif @@ -315,10 +343,16 @@ vec4 gpvs_main () { , velocity , frameTile_velLenScale.z , frameTile_velLenScale.w - , a_size_uv.w + #if !CC_INSTANCE_PARTICLE + , a_size_uv.w + #endif + #if CC_INSTANCE_PARTICLE + , a_uv.x + #endif #endif ); - #else + #endif + #if CC_RENDER_MODE == RENDER_MODE_MESH mat3 rotMat = quatToMat3(rot); mat3 nodeMat = quatToMat3(nodeRotation); rotMat = nodeMat * rotMat; diff --git a/editor/assets/chunks/particle-vs-gpu.chunk.meta b/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk.meta similarity index 89% rename from editor/assets/chunks/particle-vs-gpu.chunk.meta rename to editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk.meta index c51d1602f3..814eb46b72 100644 --- a/editor/assets/chunks/particle-vs-gpu.chunk.meta +++ b/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "b4b00c01-eca8-4ae4-a04d-e00bbeb6d0e0", diff --git a/editor/assets/chunks/particle-vs-legacy.chunk b/editor/assets/chunks/builtin/internal/particle-vs-legacy.chunk similarity index 71% rename from editor/assets/chunks/particle-vs-legacy.chunk rename to editor/assets/chunks/builtin/internal/particle-vs-legacy.chunk index 15eb2fec7d..1747a56202 100644 --- a/editor/assets/chunks/particle-vs-legacy.chunk +++ b/editor/assets/chunks/builtin/internal/particle-vs-legacy.chunk @@ -1,15 +1,21 @@ precision highp float; -#include -#include -#include +#include +#include +#include -in vec3 a_position; // center position -in vec3 a_texCoord; // xy:vertex index,z:frame index -in vec3 a_texCoord1; // size -in vec3 a_texCoord2; // rotation +in vec3 a_texCoord1; // size +in vec3 a_texCoord2; // rotation in vec4 a_color; +in vec3 a_texCoord; // xy:vertex index,z:frame index +#if !CC_INSTANCE_PARTICLE + in vec3 a_position; // center position +#endif +#if CC_INSTANCE_PARTICLE + in vec4 a_texCoord4; // xyz:position,z:frame index +#endif + #if CC_RENDER_MODE == RENDER_MODE_STRETCHED_BILLBOARD in vec3 a_color1; // velocity.x, velocity.y, velocity.z, scale #endif @@ -22,7 +28,12 @@ in vec4 a_color; vec4 lpvs_main () { vec3 compScale = scale.xyz * a_texCoord1; - vec4 pos = vec4(a_position, 1); + #if !CC_INSTANCE_PARTICLE + vec4 pos = vec4(a_position.xyz, 1); + #endif + #if CC_INSTANCE_PARTICLE + vec4 pos = vec4(a_texCoord4.xyz, 1); + #endif #if CC_RENDER_MODE == RENDER_MODE_STRETCHED_BILLBOARD vec4 velocity = vec4(a_color1.xyz, 0); #endif @@ -46,17 +57,20 @@ vec4 lpvs_main () { } vec4 rot = vec4(rotTmp, 0.0); rot.w = mulFactor * sqrt(abs(1.0 - rot.x * rot.x - rot.y * rot.y - rot.z * rot.z)); - #else + #endif + #if !ROTATION_OVER_TIME_MODULE_ENABLE #if CC_RENDER_MODE != RENDER_MODE_MESH #if CC_RENDER_MODE == RENDER_MODE_BILLBOARD vec3 rotEuler = a_texCoord2; #elif CC_RENDER_MODE == RENDER_MODE_STRETCHED_BILLBOARD vec3 rotEuler = vec3(0.); - #else + #endif + #if CC_RENDER_MODE != RENDER_MODE_BILLBOARD && CC_RENDER_MODE != RENDER_MODE_STRETCHED_BILLBOARD vec3 rotEuler = vec3(0., 0., a_texCoord2.z); #endif vec4 rot = quaternionFromEuler(rotEuler); - #else + #endif + #if CC_RENDER_MODE == RENDER_MODE_MESH vec4 rot = quaternionFromEuler(a_texCoord2); #endif #endif @@ -73,7 +87,8 @@ vec4 lpvs_main () { #endif color = a_color; - #else + #endif + #if CC_RENDER_MODE == RENDER_MODE_MESH mat3 rotMat = quatToMat3(rot); mat3 nodeMat = quatToMat3(nodeRotation); rotMat = nodeMat * rotMat; @@ -85,7 +100,13 @@ vec4 lpvs_main () { vec4 normal = xformNoScale * vec4(a_normal, 0); color = a_color * a_color1; #endif - uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw; + + #if !CC_INSTANCE_PARTICLE + uv = computeUV(a_texCoord.z, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw; + #endif + #if CC_INSTANCE_PARTICLE + uv = computeUV(a_texCoord4.w, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw; + #endif pos = cc_matViewProj * pos; diff --git a/editor/assets/chunks/particle-vs-legacy.chunk.meta b/editor/assets/chunks/builtin/internal/particle-vs-legacy.chunk.meta similarity index 89% rename from editor/assets/chunks/particle-vs-legacy.chunk.meta rename to editor/assets/chunks/builtin/internal/particle-vs-legacy.chunk.meta index 0f14dcbc47..3654188849 100644 --- a/editor/assets/chunks/particle-vs-legacy.chunk.meta +++ b/editor/assets/chunks/builtin/internal/particle-vs-legacy.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "6e1b48cb-69c8-448c-8055-69ab9793fbab", diff --git a/editor/assets/chunks/cc-sprite-common.chunk b/editor/assets/chunks/builtin/internal/sprite-common.chunk similarity index 100% rename from editor/assets/chunks/cc-sprite-common.chunk rename to editor/assets/chunks/builtin/internal/sprite-common.chunk diff --git a/editor/assets/chunks/cc-sprite-common.chunk.meta b/editor/assets/chunks/builtin/internal/sprite-common.chunk.meta similarity index 89% rename from editor/assets/chunks/cc-sprite-common.chunk.meta rename to editor/assets/chunks/builtin/internal/sprite-common.chunk.meta index 980fe0321d..1b9639a9a5 100644 --- a/editor/assets/chunks/cc-sprite-common.chunk.meta +++ b/editor/assets/chunks/builtin/internal/sprite-common.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "35822e78-bb35-405f-87bd-d42af6ac9ede", diff --git a/editor/assets/chunks/cc-sprite-texture.chunk b/editor/assets/chunks/builtin/internal/sprite-texture.chunk similarity index 100% rename from editor/assets/chunks/cc-sprite-texture.chunk rename to editor/assets/chunks/builtin/internal/sprite-texture.chunk diff --git a/editor/assets/chunks/cc-sprite-texture.chunk.meta b/editor/assets/chunks/builtin/internal/sprite-texture.chunk.meta similarity index 89% rename from editor/assets/chunks/cc-sprite-texture.chunk.meta rename to editor/assets/chunks/builtin/internal/sprite-texture.chunk.meta index a844493118..b99baf3b52 100644 --- a/editor/assets/chunks/cc-sprite-texture.chunk.meta +++ b/editor/assets/chunks/builtin/internal/sprite-texture.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "4b48672e-e044-4035-9029-13afb50c1aee", diff --git a/editor/assets/chunks/builtin/uniforms.meta b/editor/assets/chunks/builtin/uniforms.meta new file mode 100644 index 0000000000..3966a7bbd4 --- /dev/null +++ b/editor/assets/chunks/builtin/uniforms.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "d81f2dfc-d5a9-49b9-a4ce-84a3cec1707a", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/cc-diffusemap.chunk b/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk similarity index 100% rename from editor/assets/chunks/cc-diffusemap.chunk rename to editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk diff --git a/editor/assets/chunks/cc-diffusemap.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk.meta similarity index 89% rename from editor/assets/chunks/cc-diffusemap.chunk.meta rename to editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk.meta index d2647ee43d..785b080d44 100644 --- a/editor/assets/chunks/cc-diffusemap.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-diffusemap.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "17e8e047-4c5e-412c-85c8-a76a98742f2a", diff --git a/editor/assets/chunks/cc-environment.chunk b/editor/assets/chunks/builtin/uniforms/cc-environment.chunk similarity index 100% rename from editor/assets/chunks/cc-environment.chunk rename to editor/assets/chunks/builtin/uniforms/cc-environment.chunk diff --git a/editor/assets/chunks/cc-environment.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-environment.chunk.meta similarity index 89% rename from editor/assets/chunks/cc-environment.chunk.meta rename to editor/assets/chunks/builtin/uniforms/cc-environment.chunk.meta index 418145bc0e..af73e27c3c 100644 --- a/editor/assets/chunks/cc-environment.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-environment.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "cd94308c-6959-4671-9dcb-6c58342273e2", diff --git a/editor/assets/chunks/cc-forward-light.chunk b/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk similarity index 100% rename from editor/assets/chunks/cc-forward-light.chunk rename to editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk diff --git a/editor/assets/chunks/cc-forward-light.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk.meta similarity index 89% rename from editor/assets/chunks/cc-forward-light.chunk.meta rename to editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk.meta index fd9a56f06b..c20ac85e4e 100644 --- a/editor/assets/chunks/cc-forward-light.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-forward-light.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "5e0f5e6e-5008-497f-b223-4e5f1801d8fd", diff --git a/editor/assets/chunks/cc-global.chunk b/editor/assets/chunks/builtin/uniforms/cc-global.chunk similarity index 81% rename from editor/assets/chunks/cc-global.chunk rename to editor/assets/chunks/builtin/uniforms/cc-global.chunk index 38cfc16971..0159581c56 100644 --- a/editor/assets/chunks/cc-global.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-global.chunk @@ -7,6 +7,11 @@ layout(set = 0, binding = 0) uniform CCGlobal { highp vec4 cc_time; // x: global time since started in seconds, y: delta time for current frame, z: total frames since started mediump vec4 cc_screenSize; // xy: screen size, zw: inverse screen size mediump vec4 cc_nativeSize; // xy: shading size, zw: inverse shading size + + mediump vec4 cc_debug_view_mode; // x: single mode, y: lighting with albedo, z: csm layer coloration w: unused + mediump vec4 cc_debug_view_composite_pack_1; // x: dir diffuse, y: dir specular, z: env diffuse, w: env specular + mediump vec4 cc_debug_view_composite_pack_2; // x: emissive, y: lightmap, z: shadow, w: ao + mediump vec4 cc_debug_view_composite_pack_3; // x: normalmap, y: fog, z: tonemapping, w: gamma correction }; #pragma builtin(global) diff --git a/editor/assets/chunks/cc-global.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-global.chunk.meta similarity index 89% rename from editor/assets/chunks/cc-global.chunk.meta rename to editor/assets/chunks/builtin/uniforms/cc-global.chunk.meta index 00fc115831..78b4e93f32 100644 --- a/editor/assets/chunks/cc-global.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-global.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "1ea907a3-a36e-432a-ae38-af712c77aaad", diff --git a/editor/assets/chunks/lightingmap-fs.chunk b/editor/assets/chunks/builtin/uniforms/cc-light-map.chunk similarity index 85% rename from editor/assets/chunks/lightingmap-fs.chunk rename to editor/assets/chunks/builtin/uniforms/cc-light-map.chunk index b40f4ea9b2..c4fc91ed3c 100644 --- a/editor/assets/chunks/lightingmap-fs.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-light-map.chunk @@ -1,3 +1,2 @@ -in vec3 v_luv; #pragma builtin(local) layout(set = 2, binding = 10) uniform sampler2D cc_lightingMap; diff --git a/editor/assets/chunks/builtin/uniforms/cc-light-map.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-light-map.chunk.meta new file mode 100644 index 0000000000..42d24030dc --- /dev/null +++ b/editor/assets/chunks/builtin/uniforms/cc-light-map.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "fa1c0cd1-03c6-45dd-8294-bf7a1e21aad4", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk b/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk new file mode 100644 index 0000000000..420504ad3c --- /dev/null +++ b/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk @@ -0,0 +1,13 @@ +// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. + +#if !USE_INSTANCING + #if USE_BATCHING + #pragma define BATCHING_COUNT 10 + #pragma builtin(local) + layout(set = 2, binding = 0) uniform CCLocalBatched { + highp mat4 cc_matWorlds[BATCHING_COUNT]; + }; + #else + #include + #endif +#endif diff --git a/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk.meta new file mode 100644 index 0000000000..50f2d38f86 --- /dev/null +++ b/editor/assets/chunks/builtin/uniforms/cc-local-batched.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "21b24bc9-a158-488e-b27c-b98a461fb438", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/cc-local.chunk b/editor/assets/chunks/builtin/uniforms/cc-local.chunk similarity index 100% rename from editor/assets/chunks/cc-local.chunk rename to editor/assets/chunks/builtin/uniforms/cc-local.chunk diff --git a/editor/assets/chunks/cc-local.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-local.chunk.meta similarity index 89% rename from editor/assets/chunks/cc-local.chunk.meta rename to editor/assets/chunks/builtin/uniforms/cc-local.chunk.meta index 327706e160..b30beab87f 100644 --- a/editor/assets/chunks/cc-local.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-local.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "e835c2d5-a377-4197-bdb8-382037573494", diff --git a/editor/assets/chunks/builtin/uniforms/cc-morph.chunk b/editor/assets/chunks/builtin/uniforms/cc-morph.chunk new file mode 100644 index 0000000000..6f0e769158 --- /dev/null +++ b/editor/assets/chunks/builtin/uniforms/cc-morph.chunk @@ -0,0 +1,24 @@ +// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. + +#pragma define-meta CC_MORPH_TARGET_COUNT range([2, 8]) + +#pragma builtin(local) +layout(set = 2, binding = 4) uniform CCMorph { + vec4 cc_displacementWeights[15]; + vec4 cc_displacementTextureInfo; +}; + +#if CC_MORPH_TARGET_HAS_POSITION + #pragma builtin(local) + layout(set = 2, binding = 7) uniform sampler2D cc_PositionDisplacements; +#endif + +#if CC_MORPH_TARGET_HAS_NORMAL + #pragma builtin(local) + layout(set = 2, binding = 8) uniform sampler2D cc_NormalDisplacements; +#endif + +#if CC_MORPH_TARGET_HAS_TANGENT + #pragma builtin(local) + layout(set = 2, binding = 9) uniform sampler2D cc_TangentDisplacements; +#endif diff --git a/editor/assets/chunks/builtin/uniforms/cc-morph.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-morph.chunk.meta new file mode 100644 index 0000000000..003376ce0a --- /dev/null +++ b/editor/assets/chunks/builtin/uniforms/cc-morph.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "94d19070-32c6-4900-a288-2258fda37f29", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk b/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk new file mode 100644 index 0000000000..dc82842bec --- /dev/null +++ b/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk @@ -0,0 +1,5 @@ +#pragma builtin(global) +layout(set = 0, binding = 3) uniform highp sampler2D cc_shadowMap; + +#pragma builtin(global) +layout(set = 0, binding = 5) 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 new file mode 100644 index 0000000000..b8d0fb62b5 --- /dev/null +++ b/editor/assets/chunks/builtin/uniforms/cc-shadow-map.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "e8411010-e411-43ab-8f2e-4f4865dca4cf", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk b/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk new file mode 100644 index 0000000000..8a5f24f3ff --- /dev/null +++ b/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk @@ -0,0 +1,24 @@ +// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. + +#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]); + highp vec4 cc_shadowProjDepthInfo; // x -> cc_matLightProj[10]([2][2]); y -> cc_matLightProj[14]([2][3]); z -> cc_matLightProj[11]([3][2]); w -> cc_matLightProj[15]([3][3]); + highp vec4 cc_shadowProjInfo; // x -> cc_matLightProj[0]; y -> cc_matLightProj[5]; z -> 1.0 / cc_matLightProj[0]; w -> 1.0 / cc_matLightProj[5]; + mediump vec4 cc_shadowNFLSInfo; // x -> near(N); y -> far(F); z -> reserved 0; w -> shadow saturation(S); + mediump vec4 cc_shadowWHPBInfo; // x -> width(W); y -> height(H); z -> pcf(P); w -> bias(B); + 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/cc-shadow.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk.meta similarity index 89% rename from editor/assets/chunks/cc-shadow.chunk.meta rename to editor/assets/chunks/builtin/uniforms/cc-shadow.chunk.meta index 96a083c2b0..a148f8d4bd 100644 --- a/editor/assets/chunks/cc-shadow.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-shadow.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "69f8ecd8-cdc9-4655-a6ec-d39dacdffc2f", diff --git a/editor/assets/chunks/cc-skinning.chunk b/editor/assets/chunks/builtin/uniforms/cc-skinning.chunk similarity index 80% rename from editor/assets/chunks/cc-skinning.chunk rename to editor/assets/chunks/builtin/uniforms/cc-skinning.chunk index 5034dd71ad..5a4d4806ee 100644 --- a/editor/assets/chunks/cc-skinning.chunk +++ b/editor/assets/chunks/builtin/uniforms/cc-skinning.chunk @@ -2,12 +2,7 @@ #pragma extension([GL_EXT_shader_explicit_arithmetic_types_int32, __VERSION__ > 310, require]) -#include - #if CC_USE_BAKED_ANIMATION - #if USE_INSTANCING - in highp vec4 a_jointAnimInfo; // frameID, totalJoints, offset - #endif #pragma builtin(local) layout(set = 2, binding = 3) uniform CCSkinningTexture { highp vec4 cc_jointTextureInfo; // length, totalJoints, offset, invLength @@ -36,12 +31,13 @@ y = (tempY + 0.5) * invSize; } #else - #pragma define JOINT_UNIFORM_CAPACITY 30 - #pragma builtin(local) - layout(set = 2, binding = 3) uniform CCSkinning { - highp vec4 cc_joints[JOINT_UNIFORM_CAPACITY * 3]; - }; + #if CC_USE_REAL_TIME_JOINT_TEXTURE + #pragma builtin(local) + layout(set = 2, binding = 6) uniform highp sampler2D cc_realtimeJoint; + #else + #pragma builtin(local) + layout(set = 2, binding = 3) uniform CCSkinning { + highp vec4 cc_joints[CC_JOINT_UNIFORM_CAPACITY * 3]; + }; + #endif #endif - -#include -// #include diff --git a/editor/assets/chunks/cc-skinning.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-skinning.chunk.meta similarity index 60% rename from editor/assets/chunks/cc-skinning.chunk.meta rename to editor/assets/chunks/builtin/uniforms/cc-skinning.chunk.meta index 66e1f29d6b..a23d9b8235 100644 --- a/editor/assets/chunks/cc-skinning.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-skinning.chunk.meta @@ -1,8 +1,8 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, - "uuid": "21191d65-d2ba-47a3-b9d2-c4afaaa713cd", + "uuid": "99488fd6-220b-4d13-9a41-8b9439cd3944", "files": [], "subMetas": {}, "userData": {} diff --git a/editor/assets/chunks/cc-world-bound.chunk b/editor/assets/chunks/builtin/uniforms/cc-world-bound.chunk similarity index 100% rename from editor/assets/chunks/cc-world-bound.chunk rename to editor/assets/chunks/builtin/uniforms/cc-world-bound.chunk diff --git a/editor/assets/chunks/cc-world-bound.chunk.meta b/editor/assets/chunks/builtin/uniforms/cc-world-bound.chunk.meta similarity index 89% rename from editor/assets/chunks/cc-world-bound.chunk.meta rename to editor/assets/chunks/builtin/uniforms/cc-world-bound.chunk.meta index 32a114f8ff..f60c1335b6 100644 --- a/editor/assets/chunks/cc-world-bound.chunk.meta +++ b/editor/assets/chunks/builtin/uniforms/cc-world-bound.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "669458fe-c428-40cd-8575-51607aa8edbc", diff --git a/editor/assets/chunks/cc-fog-base.chunk b/editor/assets/chunks/cc-fog-base.chunk deleted file mode 100644 index abf9a06ec6..0000000000 --- a/editor/assets/chunks/cc-fog-base.chunk +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. - -#include - -#pragma define-meta CC_USE_FOG range([0, 4]) -#pragma define CC_FOG_LINEAR 0 -#pragma define CC_FOG_EXP 1 -#pragma define CC_FOG_EXP_SQUARED 2 -#pragma define CC_FOG_LAYERED 3 - -float LinearFog(vec4 pos) { - vec4 wPos = pos; - float cam_dis = distance(cc_cameraPos, wPos); - float fogStart = cc_fogBase.x; - float fogEnd = cc_fogBase.y; - return clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.); -} - -float ExpFog(vec4 pos) { - vec4 wPos = pos; - float fogAtten = cc_fogAdd.z; - float fogStart = cc_fogBase.x; - float fogDensity = cc_fogBase.z; - float cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.; - float f = exp(-cam_dis * fogDensity); - return f; -} - -float ExpSquaredFog(vec4 pos) { - vec4 wPos = pos; - float fogAtten = cc_fogAdd.z; - float fogStart = cc_fogBase.x; - float fogDensity = cc_fogBase.z; - float cam_dis = max(distance(cc_cameraPos, wPos) - fogStart, 0.0) / fogAtten * 4.; - float f = exp(-cam_dis * cam_dis * fogDensity * fogDensity); - return f; -} - -float LayeredFog(vec4 pos) { - vec4 wPos = pos; - float fogAtten = cc_fogAdd.z; - float _FogTop = cc_fogAdd.x; - float _FogRange = cc_fogAdd.y; - vec3 camWorldProj = cc_cameraPos.xyz; - camWorldProj.y = 0.; - vec3 worldPosProj = wPos.xyz; - worldPosProj.y = 0.; - float fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0; - float fDeltaY, fDensityIntegral; - if (cc_cameraPos.y > _FogTop) { - if (wPos.y < _FogTop) { - fDeltaY = (_FogTop - wPos.y) / _FogRange * 2.0; - fDensityIntegral = fDeltaY * fDeltaY * 0.5; - } else { - fDeltaY = 0.; - fDensityIntegral = 0.; - } - } else { - if (wPos.y < _FogTop) { - float fDeltaA = (_FogTop - cc_cameraPos.y) / _FogRange * 2.; - float fDeltaB = (_FogTop - wPos.y) / _FogRange * 2.; - fDeltaY = abs(fDeltaA - fDeltaB); - fDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5)); - } else { - fDeltaY = abs(_FogTop - cc_cameraPos.y) / _FogRange * 2.; - fDensityIntegral = abs(fDeltaY * fDeltaY * 0.5); - } - } - float fDensity; - if (fDeltaY != 0.) { - fDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral; - } else { - fDensity = 0.; - } - float f = exp(-fDensity); - return f; -} - -void CC_TRANSFER_FOG_BASE(vec4 pos, out float factor) -{ - #if CC_USE_FOG == CC_FOG_LINEAR - factor = LinearFog(pos); - #elif CC_USE_FOG == CC_FOG_EXP - factor = ExpFog(pos); - #elif CC_USE_FOG == CC_FOG_EXP_SQUARED - factor = ExpSquaredFog(pos); - #elif CC_USE_FOG == CC_FOG_LAYERED - factor = LayeredFog(pos); - #else - factor = 1.0; - #endif -} - -void CC_APPLY_FOG_BASE(inout vec4 color, float factor) { - color = vec4(mix(cc_fogColor.rgb, color.rgb, factor), color.a); -} diff --git a/editor/assets/chunks/cc-shadow-map-base.chunk b/editor/assets/chunks/cc-shadow-map-base.chunk deleted file mode 100644 index 317de8b079..0000000000 --- a/editor/assets/chunks/cc-shadow-map-base.chunk +++ /dev/null @@ -1,360 +0,0 @@ -// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. - -#include -#include -#include -#include - -// When screenSpaceSingY and clipSpaceSignY have different signs, need to flip the uv -#pragma define CC_HANDLE_NDC_SAMPLE_FLIP(uv) uv = cc_cameraPos.w == 1.0 ? vec2(uv.x, 1.0 - uv.y) : uv - -float CCGetLinearDepthFromViewSpace(vec3 viewPos) { - float dist = length(viewPos); - return (dist - cc_shadowNFLSInfo.x) / (cc_shadowNFLSInfo.y - cc_shadowNFLSInfo.x); -} - -float CCGetLinearDepth(vec3 worldPos) { - vec4 viewStartPos = cc_matLightView * vec4(worldPos.xyz, 1.0); - return CCGetLinearDepthFromViewSpace(viewStartPos.xyz); -} - -float CCGetViewSpaceDepth(float depthHS) -{ - return cc_shadowProjDepthInfo.y / (depthHS - cc_shadowProjDepthInfo.x); -} - -#if CC_RECEIVE_SHADOW - #pragma builtin(global) - layout(set = 0, binding = 3) uniform highp sampler2D cc_shadowMap; - - #pragma builtin(global) - layout(set = 0, binding = 5) uniform highp sampler2D cc_spotLightingMap; - - vec4 ApplyShadowDepthBias_FaceNormal(vec4 shadowPos, vec3 worldNormal, float normalBias) - { - vec4 newShadowPos = shadowPos; - if(normalBias > 0.0001) - { - vec4 viewNormal = cc_matLightView * vec4(worldNormal, 0.0); - if(viewNormal.z < 0.1) - newShadowPos.xy += viewNormal.xy * cc_shadowProjInfo.xy * normalBias * clamp(viewNormal.z, 0.001, 0.1); - } - return newShadowPos; - } - - vec4 ApplyShadowDepthBias_Perspective(vec4 shadowPos, float viewspaceDepthBias) - { - // Recover the coord in view space: cc_matLightInvProj * shadowPos - vec3 viewSpacePos; - viewSpacePos.xy = shadowPos.xy * cc_shadowProjInfo.zw; - viewSpacePos.z = shadowPos.z * cc_shadowInvProjDepthInfo.x + shadowPos.w * cc_shadowInvProjDepthInfo.y; - - // Apply bias - viewSpacePos.xyz += cc_shadowProjDepthInfo.z * normalize(viewSpacePos.xyz) * viewspaceDepthBias; - - // Reconstuct clipspace: cc_matLightProj * viewSpacePos - vec4 clipSpacePos; - clipSpacePos.xy = viewSpacePos.xy * cc_shadowProjInfo.xy; - clipSpacePos.zw = viewSpacePos.z * cc_shadowProjDepthInfo.xz + vec2(cc_shadowProjDepthInfo.y, 0.0); - - // enabled linear depth? - if (cc_shadowNFLSInfo.z > 0.000001) { - clipSpacePos.z = CCGetLinearDepthFromViewSpace(viewSpacePos.xyz); - clipSpacePos.z = (clipSpacePos.z * 2.0 - 1.0) * clipSpacePos.w; - } - - return clipSpacePos; - } - - vec4 ApplyShadowDepthBias_Orthographic(vec4 shadowPos, float viewspaceDepthBias) - { - float coeffA = cc_shadowProjDepthInfo.x; - float coeffB = cc_shadowProjDepthInfo.y; - - // Recover the Z distance in view space: - float viewSpacePos_z = (shadowPos.z - coeffB) / coeffA; - - // Apply bias - viewSpacePos_z += viewspaceDepthBias; - - // Reconstuct clipspace - vec4 result = shadowPos; - result.z = viewSpacePos_z * coeffA + coeffB; - return result; - } - - float CCGetShadowFactorHard (vec4 shadowPos, float bias) { - vec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias); - vec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5; - if (clipPos.x < 0.0 || clipPos.x > 1.0 || - clipPos.y < 0.0 || clipPos.y > 1.0 || - clipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; } - CC_HANDLE_NDC_SAMPLE_FLIP(clipPos.xy); - - float shadow = 0.0; - float closestDepth = 0.0; - if (cc_shadowLPNNInfo.y > 0.000001) { - closestDepth = unpackRGBAToDepth(texture(cc_shadowMap, clipPos.xy)); - } else { - closestDepth = texture(cc_shadowMap, clipPos.xy).x; - } - shadow = step(clipPos.z, closestDepth); - - return shadow; - } - - float CCGetShadowFactorSoft (vec4 shadowPos, float bias) { - vec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias); - vec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5; - if (clipPos.x < 0.0 || clipPos.x > 1.0 || - clipPos.y < 0.0 || clipPos.y > 1.0 || - clipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; } - CC_HANDLE_NDC_SAMPLE_FLIP(clipPos.xy); - - float offsetDepth = clipPos.z; - vec2 mapSize = cc_shadowWHPBInfo.xy; - vec2 oneTap = 1.0 / mapSize; - vec2 clipPos_offset = clipPos.xy + oneTap; - - float block0, block1, block2, block3; - if (cc_shadowLPNNInfo.y > 0.000001) { - block0 = step(offsetDepth, unpackRGBAToDepth(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)))); - block1 = step(offsetDepth, unpackRGBAToDepth(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)))); - block2 = step(offsetDepth, unpackRGBAToDepth(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)))); - block3 = step(offsetDepth, unpackRGBAToDepth(texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)))); - } else { - block0 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x); - block1 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos.y)).x); - block2 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset.y)).x); - block3 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset.x, clipPos_offset.y)).x); - } - - float coefX = mod(clipPos.x, oneTap.x) * mapSize.x; - float resultX = mix(block0, block1, coefX); - float resultY = mix(block2, block3, coefX); - float coefY = mod(clipPos.y, oneTap.y) * mapSize.y; - - return mix(resultX, resultY, coefY); - } - - float CCGetShadowFactorSoft2X (vec4 shadowPos, float bias) { - vec4 clipPosNew = ApplyShadowDepthBias_Orthographic(shadowPos, bias); - vec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5; - if (clipPos.x < 0.0 || clipPos.x > 1.0 || - clipPos.y < 0.0 || clipPos.y > 1.0 || - clipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; } - CC_HANDLE_NDC_SAMPLE_FLIP(clipPos.xy); - - float offsetDepth = clipPos.z; - vec2 mapSize = cc_shadowWHPBInfo.xy; - vec2 oneTap = 1.0 / mapSize; - float clipPos_offset_L = clipPos.x - oneTap.x; - float clipPos_offset_R = clipPos.x + oneTap.x; - float clipPos_offset_U = clipPos.y - oneTap.y; - float clipPos_offset_D = clipPos.y + oneTap.y; - - float block0, block1, block2, block3, block4, block5, block6, block7, block8; - if (cc_shadowLPNNInfo.y > 0.000001) { - block0 = step(offsetDepth, unpackRGBAToDepth(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)))); - block1 = step(offsetDepth, unpackRGBAToDepth(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)))); - block2 = step(offsetDepth, unpackRGBAToDepth(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)))); - block3 = step(offsetDepth, unpackRGBAToDepth(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)))); - block4 = step(offsetDepth, unpackRGBAToDepth(texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)))); - block5 = step(offsetDepth, unpackRGBAToDepth(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)))); - block6 = step(offsetDepth, unpackRGBAToDepth(texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)))); - block7 = step(offsetDepth, unpackRGBAToDepth(texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)))); - block8 = step(offsetDepth, unpackRGBAToDepth(texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)))); - } else { - block0 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_U)).x); - block1 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_U)).x); - block2 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_U)).x); - block3 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos.y)).x); - block4 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos.y)).x); - block5 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos.y)).x); - block6 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_L, clipPos_offset_D)).x); - block7 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos.x, clipPos_offset_D)).x); - block8 = step(offsetDepth, texture(cc_shadowMap, vec2(clipPos_offset_R, clipPos_offset_D)).x); - } - - float coefX = mod(clipPos.x, oneTap.x) * mapSize.x; - float coefY = mod(clipPos.y, oneTap.y) * mapSize.y; - - float shadow = 0.0; - float resultX = mix(block0, block1, coefX); - float resultY = mix(block3, block4, coefX); - shadow += mix(resultX , resultY, coefY); - - resultX = mix(block1, block2, coefX); - resultY = mix(block4, block5, coefX); - shadow += mix(resultX , resultY, coefY); - - resultX = mix(block3, block4, coefX); - resultY = mix(block6, block7, coefX); - shadow += mix(resultX, resultY, coefY); - - resultX = mix(block4, block5, coefX); - resultY = mix(block7, block8, coefX); - shadow += mix(resultX, resultY, coefY); - - return shadow * 0.25; - } - - float CCGetSpotLightShadowFactorHard (vec4 shadowPos, vec3 worldPos, float bias) { - vec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias); - vec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5; - if (clipPos.x < 0.0 || clipPos.x > 1.0 || - clipPos.y < 0.0 || clipPos.y > 1.0 || - clipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; } - CC_HANDLE_NDC_SAMPLE_FLIP(clipPos.xy); - - float shadow = 0.0; - float closestDepth = 0.0; - float depth = clipPos.z; - - if (cc_shadowLPNNInfo.y > 0.000001) { - closestDepth = unpackRGBAToDepth(texture(cc_spotLightingMap, clipPos.xy)); - } else { - closestDepth = texture(cc_spotLightingMap, clipPos.xy).x; - } - shadow = step(depth, closestDepth); - - return shadow; - } - - float CCGetSpotLightShadowFactorSoft (vec4 shadowPos, vec3 worldPos, float bias) { - vec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias); - vec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5; - if (clipPos.x < 0.0 || clipPos.x > 1.0 || - clipPos.y < 0.0 || clipPos.y > 1.0 || - clipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; } - CC_HANDLE_NDC_SAMPLE_FLIP(clipPos.xy); - - float depth = 0.0; - if (cc_shadowNFLSInfo.z > 0.000001) { - depth = CCGetLinearDepth(worldPos); - } else { - depth = clipPos.z; - } - - vec2 oneTap = 1.0 / cc_shadowWHPBInfo.xy; - vec2 clipPos_offset = clipPos.xy + oneTap; - - float block0, block1, block2, block3; - if (cc_shadowLPNNInfo.y > 0.000001) { - block0 = step(depth, unpackRGBAToDepth(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)))); - block1 = step(depth, unpackRGBAToDepth(texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)))); - block2 = step(depth, unpackRGBAToDepth(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)))); - block3 = step(depth, unpackRGBAToDepth(texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)))); - } else { - block0 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x); - block1 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos.y)).x); - block2 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset.y)).x); - block3 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset.x, clipPos_offset.y)).x); - } - - float coefX = mod(clipPos.x, oneTap.x) * cc_shadowWHPBInfo.x; - float resultX = mix(block0, block1, coefX); - float resultY = mix(block2, block3, coefX); - float coefY = mod(clipPos.y, oneTap.y) * cc_shadowWHPBInfo.y; - - return mix(resultX, resultY, coefY); - } - - float CCGetSpotLightShadowFactorSoft2X (vec4 shadowPos, vec3 worldPos, float bias) { - vec4 clipPosNew = ApplyShadowDepthBias_Perspective(shadowPos, bias); - vec3 clipPos = clipPosNew.xyz / clipPosNew.w * 0.5 + 0.5; - if (clipPos.x < 0.0 || clipPos.x > 1.0 || - clipPos.y < 0.0 || clipPos.y > 1.0 || - clipPos.z < 0.0 || clipPos.z > 1.0) { return 1.0; } - CC_HANDLE_NDC_SAMPLE_FLIP(clipPos.xy); - - float depth = 0.0; - if (cc_shadowNFLSInfo.z > 0.000001) { - depth = CCGetLinearDepth(worldPos); - } else { - depth = clipPos.z; - } - - vec2 mapSize = cc_shadowWHPBInfo.xy; - vec2 oneTap = 1.0 / mapSize; - float clipPos_offset_L = clipPos.x - oneTap.x; - float clipPos_offset_R = clipPos.x + oneTap.x; - float clipPos_offset_U = clipPos.y - oneTap.y; - float clipPos_offset_D = clipPos.y + oneTap.y; - - float block0, block1, block2, block3, block4, block5, block6, block7, block8; - if (cc_shadowLPNNInfo.y > 0.000001) { - block0 = step(depth, unpackRGBAToDepth(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)))); - block1 = step(depth, unpackRGBAToDepth(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)))); - block2 = step(depth, unpackRGBAToDepth(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)))); - block3 = step(depth, unpackRGBAToDepth(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)))); - block4 = step(depth, unpackRGBAToDepth(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)))); - block5 = step(depth, unpackRGBAToDepth(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)))); - block6 = step(depth, unpackRGBAToDepth(texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)))); - block7 = step(depth, unpackRGBAToDepth(texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)))); - block8 = step(depth, unpackRGBAToDepth(texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)))); - } else { - block0 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_U)).x); - block1 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_U)).x); - block2 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_U)).x); - block3 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos.y)).x); - block4 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos.y)).x); - block5 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos.y)).x); - block6 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_L, clipPos_offset_D)).x); - block7 = step(depth, texture(cc_spotLightingMap, vec2(clipPos.x, clipPos_offset_D)).x); - block8 = step(depth, texture(cc_spotLightingMap, vec2(clipPos_offset_R, clipPos_offset_D)).x); - } - - float coefX = mod(clipPos.x, oneTap.x) * mapSize.x; - float coefY = mod(clipPos.y, oneTap.y) * mapSize.y; - - float shadow = 0.0; - float resultX = mix(block0, block1, coefX); - float resultY = mix(block3, block4, coefX); - shadow += mix(resultX , resultY, coefY); - - resultX = mix(block1, block2, coefX); - resultY = mix(block4, block5, coefX); - shadow += mix(resultX , resultY, coefY); - - resultX = mix(block3, block4, coefX); - resultY = mix(block6, block7, coefX); - shadow += mix(resultX, resultY, coefY); - - resultX = mix(block4, block5, coefX); - resultY = mix(block7, block8, coefX); - shadow += mix(resultX, resultY, coefY); - - return shadow * 0.25; - } - -float CCSpotShadowFactorBase(vec4 shadowPos, vec3 worldPos, vec2 shadowBias) -{ - float pcf = cc_shadowWHPBInfo.z; - if (pcf > 1.9) { - return CCGetSpotLightShadowFactorSoft2X(shadowPos, worldPos, shadowBias.x); - }else if (pcf > 0.9) { - return CCGetSpotLightShadowFactorSoft(shadowPos, worldPos, shadowBias.x); - }else { - return CCGetSpotLightShadowFactorHard(shadowPos, worldPos, shadowBias.x); - } -} - -float CCShadowFactorBase(vec4 shadowPos, vec3 N, vec2 shadowBias) -{ - float realtimeShadow = 1.0; - vec4 pos = ApplyShadowDepthBias_FaceNormal(shadowPos, N, shadowBias.y); - - float pcf = cc_shadowWHPBInfo.z; - if (pcf > 1.9) { - realtimeShadow = CCGetShadowFactorSoft2X(pos, shadowBias.x); - }else if (pcf > 0.9) { - realtimeShadow = CCGetShadowFactorSoft(pos, shadowBias.x); - }else { - realtimeShadow = CCGetShadowFactorHard(pos, shadowBias.x); - } - return mix(realtimeShadow, 1.0, cc_shadowNFLSInfo.w); -} -#endif - -#pragma define CC_TRANSFER_SHADOW_BASE(pos, shadowPos) shadowPos = cc_matLightViewProj * pos diff --git a/editor/assets/chunks/cc-shadow-map-base.chunk.meta b/editor/assets/chunks/cc-shadow-map-base.chunk.meta deleted file mode 100644 index ebcd528fb3..0000000000 --- a/editor/assets/chunks/cc-shadow-map-base.chunk.meta +++ /dev/null @@ -1,9 +0,0 @@ -{ - "ver": "1.0.2", - "importer": "effect-header", - "imported": true, - "uuid": "9b0e2f60-4c29-47e6-9b4c-ced160a61be6", - "files": [], - "subMetas": {}, - "userData": {} -} diff --git a/editor/assets/chunks/cc-shadow.chunk b/editor/assets/chunks/cc-shadow.chunk deleted file mode 100644 index 73429d1b4b..0000000000 --- a/editor/assets/chunks/cc-shadow.chunk +++ /dev/null @@ -1,16 +0,0 @@ -// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. - -#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]); - highp vec4 cc_shadowProjDepthInfo; // x -> cc_matLightProj[10]([2][2]); y -> cc_matLightProj[14]([2][3]); z -> cc_matLightProj[11]([3][2]); w -> cc_matLightProj[15]([3][3]); - highp vec4 cc_shadowProjInfo; // x -> cc_matLightProj[0]; y -> cc_matLightProj[5]; z -> 1.0 / cc_matLightProj[0]; w -> 1.0 / cc_matLightProj[5]; - mediump vec4 cc_shadowNFLSInfo; // x -> near(N); y -> far(F); z -> isLinear(L); w -> shadow saturation(S); - mediump vec4 cc_shadowWHPBInfo; // x -> width(W); y -> height(H); z -> pcf(P); w -> bias(B); - mediump vec4 cc_shadowLPNNInfo; // x -> lightType(L); y -> isPacking(P); z -> normalBias(N); w -> null(N); - lowp vec4 cc_shadowColor; - mediump vec4 cc_planarNDInfo; // xyz -> normalized plane (N); w -> plane (D); -}; diff --git a/editor/assets/chunks/common.meta b/editor/assets/chunks/common.meta new file mode 100644 index 0000000000..02948fb6ba --- /dev/null +++ b/editor/assets/chunks/common.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "5dce7e3d-7c28-4f47-974c-e6904aeada37", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/common/color.meta b/editor/assets/chunks/common/color.meta new file mode 100644 index 0000000000..3bf301246d --- /dev/null +++ b/editor/assets/chunks/common/color.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "280afbca-66a6-4948-9a32-a207b2415f6d", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/aces.chunk b/editor/assets/chunks/common/color/aces.chunk similarity index 100% rename from editor/assets/chunks/aces.chunk rename to editor/assets/chunks/common/color/aces.chunk diff --git a/editor/assets/chunks/aces.chunk.meta b/editor/assets/chunks/common/color/aces.chunk.meta similarity index 89% rename from editor/assets/chunks/aces.chunk.meta rename to editor/assets/chunks/common/color/aces.chunk.meta index eab88b41f8..ed401b322f 100644 --- a/editor/assets/chunks/aces.chunk.meta +++ b/editor/assets/chunks/common/color/aces.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "7efbe295-0202-4979-8cda-6cfe35e086cf", diff --git a/editor/assets/chunks/common/color/gamma.chunk b/editor/assets/chunks/common/color/gamma.chunk new file mode 100644 index 0000000000..2247c5c852 --- /dev/null +++ b/editor/assets/chunks/common/color/gamma.chunk @@ -0,0 +1,29 @@ +// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. + +#include + +// #pragma define SRGBToLinear(gamma) pow(gamma, vec3(2.2)) +vec3 SRGBToLinear (vec3 gamma) { +#ifdef CC_USE_SURFACE_SHADER + #if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_GAMMA_CORRECTION) { + return gamma; + } + #endif +#endif + + return gamma * gamma; +} + +// #pragma define LinearToSRGB(linear) pow(linear, vec3(0.454545)) +vec3 LinearToSRGB(vec3 linear) { +#ifdef CC_USE_SURFACE_SHADER + #if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_GAMMA_CORRECTION) { + return linear; + } + #endif +#endif + + return sqrt(linear); +} diff --git a/editor/assets/chunks/gamma.chunk.meta b/editor/assets/chunks/common/color/gamma.chunk.meta similarity index 89% rename from editor/assets/chunks/gamma.chunk.meta rename to editor/assets/chunks/common/color/gamma.chunk.meta index f3a006da12..00ea376a9e 100644 --- a/editor/assets/chunks/gamma.chunk.meta +++ b/editor/assets/chunks/common/color/gamma.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "bb213412-2e68-43b3-9de5-73ca332acace", diff --git a/editor/assets/chunks/common.chunk b/editor/assets/chunks/common/common-define.chunk similarity index 67% rename from editor/assets/chunks/common.chunk rename to editor/assets/chunks/common/common-define.chunk index ece16b958e..4f9a0195a4 100644 --- a/editor/assets/chunks/common.chunk +++ b/editor/assets/chunks/common/common-define.chunk @@ -3,17 +3,30 @@ // common module // constant value -#define PI 3.14159265359 -#define INV_PI 0.31830988618 -#define PI2 6.28318530718 -#define EPSILON 1e-6 -#define LOG2 1.442695 -#define FP_MAX 65504.0 -#define FP_SCALE 0.0009765625 -#define FP_SCALE_INV 1024.0 +#define QUATER_PI 0.78539816340 +#define HALF_PI 1.57079632679 +#define PI 3.14159265359 +#define PI2 6.28318530718 +#define PI4 12.5663706144 + +#define INV_QUATER_PI 1.27323954474 +#define INV_HALF_PI 0.63661977237 +#define INV_PI 0.31830988618 +#define INV_PI2 0.15915494309 +#define INV_PI4 0.07957747155 + +#define EPSILON 1e-6 +#define EPSILON_LOWP 1e-4 +#define LOG2 1.442695 +#define EXP_VALUE 2.71828183f +#define FP_MAX 65504.0 +#define FP_SCALE 0.0009765625 +#define FP_SCALE_INV 1024.0 +#define GRAY_VECTOR vec3(0.299, 0.587, 0.114) // common function #pragma define saturate(a) clamp(a, 0.0, 1.0) +#pragma define equalf(data1, data2) (abs(float(data1) - float(data2)) < EPSILON) // runtime constants #pragma define-meta CC_DEVICE_SUPPORT_FLOAT_TEXTURE default(1) diff --git a/editor/assets/chunks/common.chunk.meta b/editor/assets/chunks/common/common-define.chunk.meta similarity index 89% rename from editor/assets/chunks/common.chunk.meta rename to editor/assets/chunks/common/common-define.chunk.meta index e106796444..bcaeda1c0f 100644 --- a/editor/assets/chunks/common.chunk.meta +++ b/editor/assets/chunks/common/common-define.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "9d86a3e4-ec06-4e51-ba68-45f2b7739fbb", diff --git a/editor/assets/chunks/common/data.meta b/editor/assets/chunks/common/data.meta new file mode 100644 index 0000000000..65daa0e584 --- /dev/null +++ b/editor/assets/chunks/common/data.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "23b6d452-21a8-41c8-a910-fdb93eb21c61", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/packing.chunk b/editor/assets/chunks/common/data/packing.chunk similarity index 100% rename from editor/assets/chunks/packing.chunk rename to editor/assets/chunks/common/data/packing.chunk diff --git a/editor/assets/chunks/packing.chunk.meta b/editor/assets/chunks/common/data/packing.chunk.meta similarity index 89% rename from editor/assets/chunks/packing.chunk.meta rename to editor/assets/chunks/common/data/packing.chunk.meta index b1ab533fe1..5e7417f776 100644 --- a/editor/assets/chunks/packing.chunk.meta +++ b/editor/assets/chunks/common/data/packing.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "73866dd2-eaf5-40af-a061-1b9d38782204", diff --git a/editor/assets/chunks/unpack.chunk b/editor/assets/chunks/common/data/unpack.chunk similarity index 100% rename from editor/assets/chunks/unpack.chunk rename to editor/assets/chunks/common/data/unpack.chunk diff --git a/editor/assets/chunks/unpack.chunk.meta b/editor/assets/chunks/common/data/unpack.chunk.meta similarity index 89% rename from editor/assets/chunks/unpack.chunk.meta rename to editor/assets/chunks/common/data/unpack.chunk.meta index 9b4864e042..d22d3257f1 100644 --- a/editor/assets/chunks/unpack.chunk.meta +++ b/editor/assets/chunks/common/data/unpack.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "e3e5d086-acc9-4dd8-98e8-24ac02f547d5", diff --git a/editor/assets/chunks/common/debug.meta b/editor/assets/chunks/common/debug.meta new file mode 100644 index 0000000000..3bbe82131b --- /dev/null +++ b/editor/assets/chunks/common/debug.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "a1b68389-649a-4208-9453-85db77a65771", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/common/debug/debug-view-define.chunk b/editor/assets/chunks/common/debug/debug-view-define.chunk new file mode 100644 index 0000000000..701aa143ea --- /dev/null +++ b/editor/assets/chunks/common/debug/debug-view-define.chunk @@ -0,0 +1,61 @@ +// vertex & face data +#define CC_SURFACES_DEBUG_VIEW_VERTEX_COLOR 1 +#define CC_SURFACES_DEBUG_VIEW_VERTEX_NORMAL CC_SURFACES_DEBUG_VIEW_VERTEX_COLOR + 1 +#define CC_SURFACES_DEBUG_VIEW_VERTEX_TANGENT CC_SURFACES_DEBUG_VIEW_VERTEX_NORMAL + 1 +#define CC_SURFACES_DEBUG_VIEW_WORLD_POS CC_SURFACES_DEBUG_VIEW_VERTEX_TANGENT + 1 +#define CC_SURFACES_DEBUG_VIEW_VERTEX_MIRROR CC_SURFACES_DEBUG_VIEW_WORLD_POS + 1 +#define CC_SURFACES_DEBUG_VIEW_FACE_SIDE CC_SURFACES_DEBUG_VIEW_VERTEX_MIRROR + 1 +#define CC_SURFACES_DEBUG_VIEW_UV0 CC_SURFACES_DEBUG_VIEW_FACE_SIDE + 1 +#define CC_SURFACES_DEBUG_VIEW_UV1 CC_SURFACES_DEBUG_VIEW_UV0 + 1 +#define CC_SURFACES_DEBUG_VIEW_UVLIGHTMAP CC_SURFACES_DEBUG_VIEW_UV1 + 1 +#define CC_SURFACES_DEBUG_VIEW_PROJ_DEPTH CC_SURFACES_DEBUG_VIEW_UVLIGHTMAP + 1 +#define CC_SURFACES_DEBUG_VIEW_LINEAR_DEPTH CC_SURFACES_DEBUG_VIEW_PROJ_DEPTH + 1 + +// surface material data +#define CC_SURFACES_DEBUG_VIEW_FRAGMENT_NORMAL CC_SURFACES_DEBUG_VIEW_LINEAR_DEPTH + 1 +#define CC_SURFACES_DEBUG_VIEW_FRAGMENT_TANGENT CC_SURFACES_DEBUG_VIEW_FRAGMENT_NORMAL + 1 +#define CC_SURFACES_DEBUG_VIEW_FRAGMENT_BINORMAL CC_SURFACES_DEBUG_VIEW_FRAGMENT_TANGENT + 1 +#define CC_SURFACES_DEBUG_VIEW_BASE_COLOR CC_SURFACES_DEBUG_VIEW_FRAGMENT_BINORMAL + 1 +#define CC_SURFACES_DEBUG_VIEW_DIFFUSE_COLOR CC_SURFACES_DEBUG_VIEW_BASE_COLOR + 1 +#define CC_SURFACES_DEBUG_VIEW_SPECULAR_COLOR CC_SURFACES_DEBUG_VIEW_DIFFUSE_COLOR + 1 +#define CC_SURFACES_DEBUG_VIEW_TRANSPARENCY CC_SURFACES_DEBUG_VIEW_SPECULAR_COLOR + 1 +#define CC_SURFACES_DEBUG_VIEW_METALLIC CC_SURFACES_DEBUG_VIEW_TRANSPARENCY + 1 +#define CC_SURFACES_DEBUG_VIEW_ROUGHNESS CC_SURFACES_DEBUG_VIEW_METALLIC + 1 +#define CC_SURFACES_DEBUG_VIEW_SPECULAR_INTENSITY CC_SURFACES_DEBUG_VIEW_ROUGHNESS + 1 + +// lighting data +#define CC_SURFACES_DEBUG_VIEW_DIRECT_DIFFUSE CC_SURFACES_DEBUG_VIEW_SPECULAR_INTENSITY + 1 +#define CC_SURFACES_DEBUG_VIEW_DIRECT_SPECULAR CC_SURFACES_DEBUG_VIEW_DIRECT_DIFFUSE + 1 +#define CC_SURFACES_DEBUG_VIEW_DIRECT_ALL CC_SURFACES_DEBUG_VIEW_DIRECT_SPECULAR + 1 +#define CC_SURFACES_DEBUG_VIEW_ENV_DIFFUSE CC_SURFACES_DEBUG_VIEW_DIRECT_ALL + 1 +#define CC_SURFACES_DEBUG_VIEW_ENV_SPECULAR CC_SURFACES_DEBUG_VIEW_ENV_DIFFUSE + 1 +#define CC_SURFACES_DEBUG_VIEW_ENV_ALL CC_SURFACES_DEBUG_VIEW_ENV_SPECULAR + 1 +#define CC_SURFACES_DEBUG_VIEW_EMISSIVE CC_SURFACES_DEBUG_VIEW_ENV_ALL + 1 +#define CC_SURFACES_DEBUG_VIEW_LIGHT_MAP CC_SURFACES_DEBUG_VIEW_EMISSIVE + 1 +#define CC_SURFACES_DEBUG_VIEW_SHADOW CC_SURFACES_DEBUG_VIEW_LIGHT_MAP + 1 +#define CC_SURFACES_DEBUG_VIEW_AO CC_SURFACES_DEBUG_VIEW_SHADOW + 1 + +#define CC_SURFACES_DEBUG_VIEW_FOG CC_SURFACES_DEBUG_VIEW_AO + 1 + +// Debug view UI and macros +// #pragma define-meta CC_USE_DEBUG_VIEW range([0, 2]) + +// use uniforms for fast toggling +#define CC_SURFACES_DEBUG_VIEW_SINGLE 1 +#define CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC 2 + +#pragma define IS_DEBUG_VIEW_SINGLE_MODE(mode) equalf(cc_debug_view_mode.x, mode) +#define IS_DEBUG_VIEW_LIGHTING_ENABLE_WITH_ALBEDO (cc_debug_view_mode.y > 0.0) +#define IS_DEBUG_VIEW_MISC_ENABLE_CSM_LAYER_COLORATION (cc_debug_view_mode.z > 0.0) +#define IS_DEBUG_VIEW_COMPOSITE_ENABLE_DIRECT_DIFFUSE (cc_debug_view_composite_pack_1.x > 0.0) +#define IS_DEBUG_VIEW_COMPOSITE_ENABLE_DIRECT_SPECULAR (cc_debug_view_composite_pack_1.y > 0.0) +#define IS_DEBUG_VIEW_COMPOSITE_ENABLE_ENV_DIFFUSE (cc_debug_view_composite_pack_1.z > 0.0) +#define IS_DEBUG_VIEW_COMPOSITE_ENABLE_ENV_SPECULAR (cc_debug_view_composite_pack_1.w > 0.0) +#define IS_DEBUG_VIEW_COMPOSITE_ENABLE_EMISSIVE (cc_debug_view_composite_pack_2.x > 0.0) +#define IS_DEBUG_VIEW_COMPOSITE_ENABLE_LIGHT_MAP (cc_debug_view_composite_pack_2.y > 0.0) +#define IS_DEBUG_VIEW_COMPOSITE_ENABLE_SHADOW (cc_debug_view_composite_pack_2.z > 0.0) +#define IS_DEBUG_VIEW_COMPOSITE_ENABLE_AO (cc_debug_view_composite_pack_2.w > 0.0) +#define IS_DEBUG_VIEW_COMPOSITE_ENABLE_NORMAL_MAP (cc_debug_view_composite_pack_3.x > 0.0) +#define IS_DEBUG_VIEW_COMPOSITE_ENABLE_FOG (cc_debug_view_composite_pack_3.y > 0.0) +#define IS_DEBUG_VIEW_COMPOSITE_ENABLE_TONE_MAPPING (cc_debug_view_composite_pack_3.z > 0.0) +#define IS_DEBUG_VIEW_COMPOSITE_ENABLE_GAMMA_CORRECTION (cc_debug_view_composite_pack_3.w > 0.0) diff --git a/editor/assets/chunks/common/debug/debug-view-define.chunk.meta b/editor/assets/chunks/common/debug/debug-view-define.chunk.meta new file mode 100644 index 0000000000..81ea67f60a --- /dev/null +++ b/editor/assets/chunks/common/debug/debug-view-define.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "9c973ee8-952a-4ee3-a617-ba6397db6bac", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/common/effect.meta b/editor/assets/chunks/common/effect.meta new file mode 100644 index 0000000000..8d4205ead6 --- /dev/null +++ b/editor/assets/chunks/common/effect.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "98420980-4268-402a-a26d-f66e6ee50a03", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/common/effect/fog.chunk b/editor/assets/chunks/common/effect/fog.chunk new file mode 100644 index 0000000000..c871416b36 --- /dev/null +++ b/editor/assets/chunks/common/effect/fog.chunk @@ -0,0 +1,65 @@ +// fog related calculations + +//pos, cc_cameraPos.xyz, cc_fogBase.x, cc_fogBase.y +float LinearFog(vec4 pos, vec3 cameraPos, float fogStart, float fogEnd) { + vec4 wPos = pos; + float cam_dis = distance(cameraPos, wPos.xyz); + return clamp((fogEnd - cam_dis) / (fogEnd - fogStart), 0., 1.); +} + +//pos, cc_cameraPos.xyz, cc_fogBase.x, cc_fogBase.z, cc_fogAdd.z +float ExpFog(vec4 pos, vec3 cameraPos, float fogStart, float fogDensity, float fogAtten) { + vec4 wPos = pos; + float cam_dis = max(distance(cameraPos, wPos.xyz) - fogStart, 0.0) / fogAtten * 4.; + float f = exp(-cam_dis * fogDensity); + return f; +} + +float ExpSquaredFog(vec4 pos, vec3 cameraPos, float fogStart, float fogDensity, float fogAtten) { + vec4 wPos = pos; + float cam_dis = max(distance(cameraPos, wPos.xyz) - fogStart, 0.0) / fogAtten * 4.; + float f = exp(-cam_dis * cam_dis * fogDensity * fogDensity); + return f; +} + +//pos, cc_cameraPos.xyz, cc_fogAdd.x, cc_fogAdd.y, cc_fogAdd.z +float LayeredFog(vec4 pos, vec3 cameraPos, float fogTop, float fogRange, float fogAtten) { + vec4 wPos = pos; + vec3 camWorldProj = cameraPos.xyz; + camWorldProj.y = 0.; + vec3 worldPosProj = wPos.xyz; + worldPosProj.y = 0.; + float fDeltaD = distance(worldPosProj, camWorldProj) / fogAtten * 2.0; + float fDeltaY, fDensityIntegral; + if (cameraPos.y > fogTop) { + if (wPos.y < fogTop) { + fDeltaY = (fogTop - wPos.y) / fogRange * 2.0; + fDensityIntegral = fDeltaY * fDeltaY * 0.5; + } + else { + fDeltaY = 0.; + fDensityIntegral = 0.; + } + } + else { + if (wPos.y < fogTop) { + float fDeltaA = (fogTop - cameraPos.y) / fogRange * 2.; + float fDeltaB = (fogTop - wPos.y) / fogRange * 2.; + fDeltaY = abs(fDeltaA - fDeltaB); + fDensityIntegral = abs((fDeltaA * fDeltaA * 0.5) - (fDeltaB * fDeltaB * 0.5)); + } + else { + fDeltaY = abs(fogTop - cameraPos.y) / fogRange * 2.; + fDensityIntegral = abs(fDeltaY * fDeltaY * 0.5); + } + } + float fDensity; + if (fDeltaY != 0.) { + fDensity = (sqrt(1.0 + ((fDeltaD / fDeltaY) * (fDeltaD / fDeltaY)))) * fDensityIntegral; + } + else { + fDensity = 0.; + } + float f = exp(-fDensity); + return f; +} diff --git a/editor/assets/chunks/common/effect/fog.chunk.meta b/editor/assets/chunks/common/effect/fog.chunk.meta new file mode 100644 index 0000000000..9291399821 --- /dev/null +++ b/editor/assets/chunks/common/effect/fog.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "399f5890-dde1-40de-9751-a7aa91a56b93", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/common/internal-functions.meta b/editor/assets/chunks/common/internal-functions.meta new file mode 100644 index 0000000000..d2e456107a --- /dev/null +++ b/editor/assets/chunks/common/internal-functions.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "b67dfb5d-1a4d-469e-a35f-52e665ae1ea2", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/common/lighting.meta b/editor/assets/chunks/common/lighting.meta new file mode 100644 index 0000000000..8c7abb84c1 --- /dev/null +++ b/editor/assets/chunks/common/lighting.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "a2ba2f72-737d-4b4b-84be-3e014d996327", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/lighting.chunk b/editor/assets/chunks/common/lighting/attenuation.chunk similarity index 77% rename from editor/assets/chunks/lighting.chunk rename to editor/assets/chunks/common/lighting/attenuation.chunk index a0d12f36bf..f6ef44e5cd 100644 --- a/editor/assets/chunks/lighting.chunk +++ b/editor/assets/chunks/common/lighting/attenuation.chunk @@ -1,11 +1,3 @@ -// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. - -#pragma define CC_PIPELINE_TYPE_FORWARD 0 -#pragma define CC_PIPELINE_TYPE_DEFERRED 1 -#pragma define-meta CC_PIPELINE_TYPE range([0, 1]) -#pragma define-meta CC_FORCE_FORWARD_SHADING - -#include float SmoothDistAtt2 (float distSqr, float invSqrAttRadius) { float factor = distSqr * invSqrAttRadius; // ^2 diff --git a/editor/assets/chunks/common/lighting/attenuation.chunk.meta b/editor/assets/chunks/common/lighting/attenuation.chunk.meta new file mode 100644 index 0000000000..75f253af0f --- /dev/null +++ b/editor/assets/chunks/common/lighting/attenuation.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "077cca29-6f66-4aad-a3a7-4f0a7ecd523f", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/common/lighting/brdf.chunk b/editor/assets/chunks/common/lighting/brdf.chunk new file mode 100644 index 0000000000..63a70735c1 --- /dev/null +++ b/editor/assets/chunks/common/lighting/brdf.chunk @@ -0,0 +1,69 @@ +float D_GGX(float roughness, float NoH) +{ + float m = roughness * roughness; + float m2 = m * m; + float d = (NoH * m2 - NoH) * NoH + 1.0; + return m2 / max(EPSILON, d * d); +} + +float D_GGXMobile(float roughness, float NoH) { + float OneMinusNoHSqr = 1.0 - NoH * NoH; + float a = roughness * roughness; + float n = NoH * a; + float p = a / (OneMinusNoHSqr + n * n); + return p * p; +} + +void GetAnisotropicRoughness(float roughness, float anisotropyShape, out float roughnessX, out float roughnessY) +{ + float shapeSign = sign(anisotropyShape); + anisotropyShape *= anisotropyShape; + + float r1 = roughness, r2 = roughness; + float lerpedRoughness = mix(1.0, 10.0, anisotropyShape); + r2 *= shapeSign < 0.0 ? lerpedRoughness : 1.0; + r1 *= shapeSign > 0.0 ? lerpedRoughness : 1.0; + roughnessX = saturate(r1); + roughnessY = saturate(r2); +} + +float D_GGXAniso(float RoughnessX, float RoughnessY, float NoH, vec3 H, vec3 X, vec3 Y) +{ + float mx = max(EPSILON_LOWP, RoughnessX * RoughnessX); + float my = max(EPSILON_LOWP, RoughnessY * RoughnessY); + float XoH = dot(X, H); + float YoH = dot(Y, H); + float d = XoH * XoH / (mx * mx) + YoH * YoH / (my * my) + NoH * NoH; + return 1.0 / max(EPSILON_LOWP, mx * my * d * d); +} + +vec3 GetAnisotropicReflect(float roughness, float anisotropyShape, vec3 V, vec3 N, vec3 X, vec3 Y) +{ + float shapeSign = sign(anisotropyShape); + anisotropyShape *= anisotropyShape; + + //clamp to shape=0.6x for invert reflection artifact + anisotropyShape = min(anisotropyShape, 0.4); + + // roughness->0 means optical smooth surface (back to isotropic) + anisotropyShape *= smoothstep(0.0, 0.03, roughness); + + // use view co-planar vector instead of XoH->0 plane convolution, but not accuracy + vec3 reflectTarget = shapeSign < 0.0 ? mix(N, -Y, anisotropyShape) : + shapeSign > 0.0 ? mix(N, -X, anisotropyShape) : N; + return reflect(-V, reflectTarget); +} + +// EnvBRDFApprox +vec3 IntegratedGFApprox (vec3 specular, float roughness, float NoV) { + const vec4 c0 = vec4(-1.0, -0.0275, -0.572, 0.022); + const vec4 c1 = vec4(1.0, 0.0425, 1.04, -0.04); + vec4 r = roughness * c0 + c1; + float a004 = min(r.x * r.x, exp2(-9.28 * NoV)) * r.x + r.y; + vec2 AB = vec2(-1.04, 1.04) * a004 + r.zw; + AB.y *= clamp(50.0 * specular.g, 0.0, 1.0); + return specular * AB.x + AB.y; +} + +//Diffuse_Lambert +#define DiffuseCoefficient_EnergyConservation INV_PI diff --git a/editor/assets/chunks/common/lighting/brdf.chunk.meta b/editor/assets/chunks/common/lighting/brdf.chunk.meta new file mode 100644 index 0000000000..14002851f1 --- /dev/null +++ b/editor/assets/chunks/common/lighting/brdf.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "3a85eafd-0fd0-468f-8a2e-0c81493230c7", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/common/lighting/functions.chunk b/editor/assets/chunks/common/lighting/functions.chunk new file mode 100644 index 0000000000..7f48e073f9 --- /dev/null +++ b/editor/assets/chunks/common/lighting/functions.chunk @@ -0,0 +1,22 @@ +#include + +// helper functions for lighting model-functions + +float CalculateDistanceAttenuation(float distToLightSqr, float lightRadius, float lightRange) +{ + float litRadiusSqr = lightRadius * lightRadius; + float attRadiusSqrInv = 1.0 / max(lightRange, 0.01); + attRadiusSqrInv *= attRadiusSqrInv; + + // soft edge fading + float edgeAttenuation = litRadiusSqr / max(litRadiusSqr, distToLightSqr); + return GetDistAtt(distToLightSqr, attRadiusSqrInv) * edgeAttenuation; +} + +float CalculateAngleAttenuation(vec3 spotLightDir, vec3 L, float cosAngleOuter) +{ + float cosInner = max(dot(spotLightDir, L), 0.01); + float litAngleScale = 1.0 / max(0.001, cosInner - cosAngleOuter); + float litAngleOffset = -cosAngleOuter * litAngleScale; + return GetAngleAtt(L, spotLightDir, litAngleScale, litAngleOffset); +} diff --git a/editor/assets/chunks/common/lighting/functions.chunk.meta b/editor/assets/chunks/common/lighting/functions.chunk.meta new file mode 100644 index 0000000000..650ec89532 --- /dev/null +++ b/editor/assets/chunks/common/lighting/functions.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "d360c347-a546-4967-bdd3-30cae323f123", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/common/lighting/light-map.chunk b/editor/assets/chunks/common/lighting/light-map.chunk new file mode 100644 index 0000000000..e4f4b77ac0 --- /dev/null +++ b/editor/assets/chunks/common/lighting/light-map.chunk @@ -0,0 +1,14 @@ + +vec4 GetLightMapColor(sampler2D lightingMap, vec2 luv, float lum) +{ + vec4 lightmap = texture(lightingMap, luv); + lightmap.rgb *= lum; + +#if CC_USE_HDR + // convert from standard camera exposure parameters to current exposure value + // baked in LDR scene still regarded as exposured with standard camera parameters + lightmap.rgb *= cc_exposure.w * cc_exposure.x; +#endif + + return lightmap; +} diff --git a/editor/assets/chunks/common/lighting/light-map.chunk.meta b/editor/assets/chunks/common/lighting/light-map.chunk.meta new file mode 100644 index 0000000000..6ba97ff7df --- /dev/null +++ b/editor/assets/chunks/common/lighting/light-map.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "00e591cd-469d-4611-adb9-a5ca965a0552", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/rect-area-light.chunk b/editor/assets/chunks/common/lighting/rect-area-light.chunk similarity index 100% rename from editor/assets/chunks/rect-area-light.chunk rename to editor/assets/chunks/common/lighting/rect-area-light.chunk diff --git a/editor/assets/chunks/rect-area-light.chunk.meta b/editor/assets/chunks/common/lighting/rect-area-light.chunk.meta similarity index 89% rename from editor/assets/chunks/rect-area-light.chunk.meta rename to editor/assets/chunks/common/lighting/rect-area-light.chunk.meta index 1ab1daa523..2960457ec7 100644 --- a/editor/assets/chunks/rect-area-light.chunk.meta +++ b/editor/assets/chunks/common/lighting/rect-area-light.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "a24fb7a1-f7a5-430c-a8b2-e4c516131086", diff --git a/editor/assets/chunks/common/math.meta b/editor/assets/chunks/common/math.meta new file mode 100644 index 0000000000..c4e77402e7 --- /dev/null +++ b/editor/assets/chunks/common/math.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "328da6ff-910d-4cb5-904d-5c1a4ba35edd", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/common/math/coordinates.chunk b/editor/assets/chunks/common/math/coordinates.chunk new file mode 100644 index 0000000000..2d1a44062a --- /dev/null +++ b/editor/assets/chunks/common/math/coordinates.chunk @@ -0,0 +1,60 @@ +// depthHS = ndc depth(-1 ~ +1) +float GetCameraDepthRH(float depthHS, mat4 matProj) +{ + return -matProj[3][2] / (depthHS + matProj[2][2]); +} +float GetCameraDepthRH(float depthHS, float matProj32, float matProj22) +{ + return -matProj32 / (depthHS + matProj22); +} + +// posHS = ndc pos (xyz: -1 ~ +1) +vec4 GetViewPosFromNDCPosRH(vec3 posHS, mat4 matProj, mat4 matProjInv) +{ + float w = -GetCameraDepthRH(posHS.z, matProj); + return matProjInv * vec4(posHS * w, w); +} + +vec4 GetWorldPosFromNDCPosRH(vec3 posHS, mat4 matProj, mat4 matViewProjInv) +{ + float w = -GetCameraDepthRH(posHS.z, matProj); + return matViewProjInv * vec4(posHS * w, w); +} + +float GetLinearDepthFromViewSpace(vec3 viewPos, float near, float far) { + float dist = length(viewPos); + return (dist - near) / (far - near); +} + +// params must be normalized +vec3 CalculateBinormal(vec3 normal, vec3 tangent, float mirrorNormal) +{ + return cross(normal.xyz, tangent) * mirrorNormal; +} + + +// param1 is normal from normalmap +// return value is un-normalized +vec3 CalculateNormalFromTangentSpace(vec3 normalFromTangentSpace, float normalStrength, vec3 normal, vec3 tangent, float mirrorNormal) +{ + vec3 binormal = CalculateBinormal(normal, tangent, mirrorNormal); + return (normalFromTangentSpace.x * normalStrength) * normalize(tangent) + + (normalFromTangentSpace.y * normalStrength) * normalize(binormal) + + normalFromTangentSpace.z * normalize(normal); +} + + +// rotationAngle: 0-1 stand for 0-180 rotation +void RotateTangentAndBinormal(inout vec3 tangent, inout vec3 binormal, vec3 normal, float rotationAngle) +{ + rotationAngle = clamp(rotationAngle, 0.0, 1.0 - EPSILON_LOWP); // 1.0 is invalid value that equals to 90 rotation (coef=0, angle>0.5) + float coef = fract(rotationAngle * 2.0); + bool isNegative = rotationAngle <= 0.5; + + // spherical interpolating is more accuracy and linear transitions but expensive, use simple pow fix instead + coef = pow(coef, isNegative ? 0.75 : 1.25); + vec3 binormalNew = isNegative ? mix(binormal, -tangent, coef) : mix(-tangent, -binormal, coef); + vec3 tangentNew = isNegative ? mix(tangent, binormal, coef) : mix(binormal, -tangent, coef); + tangent = normalize(tangentNew); + binormal = normalize(binormalNew); +} diff --git a/editor/assets/chunks/common/math/coordinates.chunk.meta b/editor/assets/chunks/common/math/coordinates.chunk.meta new file mode 100644 index 0000000000..673d9ae7b7 --- /dev/null +++ b/editor/assets/chunks/common/math/coordinates.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "e9d8b3bb-03e4-46b2-be29-ea58fac18c18", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/common/math/number.chunk b/editor/assets/chunks/common/math/number.chunk new file mode 100644 index 0000000000..be14d95854 --- /dev/null +++ b/editor/assets/chunks/common/math/number.chunk @@ -0,0 +1,24 @@ +#if __VERSION__ <= 100 +bool isnan(float val) { + return (val < 0.0 || 0.0 < val || val == 0.0) ? false : true; +} +bool isinf(float x) { + return x == x * 2.0 && x != 0.0; +} +#endif + +bool isnans(vec3 val) { + return isnan(val.x) && isnan(val.y) && isnan(val.z); +} +bool isnans(vec4 val) { + return isnan(val.x) && isnan(val.y) && isnan(val.z) && isnan(val.w); +} +bool isinfs(vec4 val) { + return isinf(val.x) && isinf(val.y) && isinf(val.z) && isinf(val.w); +} +bool isinfs(vec3 val) { + return isinf(val.x) && isinf(val.y) && isinf(val.z); +} + + +// random number \ No newline at end of file diff --git a/editor/assets/chunks/common/math/number.chunk.meta b/editor/assets/chunks/common/math/number.chunk.meta new file mode 100644 index 0000000000..000a1f2345 --- /dev/null +++ b/editor/assets/chunks/common/math/number.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "9f84c121-c61b-499f-b400-81a5448d6078", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/octahedron-transform.chunk b/editor/assets/chunks/common/math/octahedron-transform.chunk similarity index 64% rename from editor/assets/chunks/octahedron-transform.chunk rename to editor/assets/chunks/common/math/octahedron-transform.chunk index 6c4869de2d..d86cf23bbf 100644 --- a/editor/assets/chunks/octahedron-transform.chunk +++ b/editor/assets/chunks/common/math/octahedron-transform.chunk @@ -16,17 +16,3 @@ vec3 oct_to_float32x3(vec2 e) { if (v.z < 0.0) v.xy = (1.0 - abs(v.yx)) * signNotZero(v.xy); return normalize(v); } - -vec4 screen2WS(vec3 coord) { - vec3 ndc = vec3( - 2.0 * (coord.x - cc_viewPort.x) / cc_viewPort.z - 1.0, - 2.0 * (coord.y - cc_viewPort.y) / cc_viewPort.w - 1.0, - #if __VERSION__ >= 450 - coord.z); - #else - 2.0 * coord.z - 1.0); - #endif - vec4 world = ((cc_matViewProjInv) * (vec4(ndc, 1.0))); - world = world / world.w; - return world; -} \ No newline at end of file diff --git a/editor/assets/chunks/octahedron-transform.chunk.meta b/editor/assets/chunks/common/math/octahedron-transform.chunk.meta similarity index 89% rename from editor/assets/chunks/octahedron-transform.chunk.meta rename to editor/assets/chunks/common/math/octahedron-transform.chunk.meta index 3bda3bf8cb..db4b5cf3dc 100644 --- a/editor/assets/chunks/octahedron-transform.chunk.meta +++ b/editor/assets/chunks/common/math/octahedron-transform.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "41f91fc1-5aec-45dd-91ca-39ab964f8054", diff --git a/editor/assets/chunks/transform.chunk b/editor/assets/chunks/common/math/transform.chunk similarity index 100% rename from editor/assets/chunks/transform.chunk rename to editor/assets/chunks/common/math/transform.chunk diff --git a/editor/assets/chunks/transform.chunk.meta b/editor/assets/chunks/common/math/transform.chunk.meta similarity index 89% rename from editor/assets/chunks/transform.chunk.meta rename to editor/assets/chunks/common/math/transform.chunk.meta index 3bd4f201fd..d3270470d9 100644 --- a/editor/assets/chunks/transform.chunk.meta +++ b/editor/assets/chunks/common/math/transform.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "0de81d5f-2a3e-467e-bcf5-84f7828edab6", diff --git a/editor/assets/chunks/common/mesh.meta b/editor/assets/chunks/common/mesh.meta new file mode 100644 index 0000000000..ab0c88b766 --- /dev/null +++ b/editor/assets/chunks/common/mesh.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "44c741c8-2cdd-41c1-b359-feb18b2f3c69", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/common/mesh/material.chunk b/editor/assets/chunks/common/mesh/material.chunk new file mode 100644 index 0000000000..0f70837976 --- /dev/null +++ b/editor/assets/chunks/common/mesh/material.chunk @@ -0,0 +1,47 @@ +bool GetMetallicAlbedoFromDiffuseSpecularMathematic(out float metallic, out vec3 albedo, vec3 diffuse, vec3 specular, float channelFaultTolerant /*= 0.2*/, float f0 /*= 0.04*/) +{ + // inaccuracy match first + //GetMetallicAlbedoFromDiffuseSpecular(metallic, albedo, diffuse, specular); + + // avoid illegal solver + diffuse += vec3(f0 + 0.01); + specular += vec3(f0 + 0.01); + + vec3 delta = (diffuse + specular) * (diffuse + specular) - 4.0 * f0 * diffuse; + vec3 deltaSqrt = sqrt(max(vec3(0.0), delta)); + // solver + vec3 m = (-diffuse - specular + 2.0 * f0 + deltaSqrt) / (2.0 * f0); + vec3 weight = diffuse + specular; + weight /= dot(weight, vec3(1.0)); + float solverMetallic = dot(m, weight); + vec3 solverAlbedo = diffuse + specular - f0 * (1.0 - solverMetallic); + + bool isValidSolver = delta.x >= 0.0 && delta.y >= 0.0 && delta.z >= 0.0 + && abs(m.x - m.y) < channelFaultTolerant && abs(m.x - m.z) < channelFaultTolerant + && m.x >= 0.0 && m.y >= 0.0 && m.z >= 0.0 + && m.x <= 1.0 && m.y <= 1.0 && m.z <= 1.0; + + metallic = isValidSolver ? solverMetallic : metallic; + albedo = isValidSolver ? solverAlbedo : albedo; + return isValidSolver; +} + +bool GetMetallicAlbedoFromDiffuseSpecularWithoutColor(out float metallic, out vec3 albedo, vec3 diffuse, vec3 specular, float f0 /*= 0.04*/) +{ + float d = max(max(diffuse.x, diffuse.y), diffuse.z); + vec3 normalizedColor = diffuse / (d + (d < EPSILON_LOWP ? EPSILON_LOWP : 0.0)); + normalizedColor = d < EPSILON_LOWP ? specular : normalizedColor; //change specular to gray with intensity of max channel of specular + + float s = max(max(specular.x, specular.y), specular.z); + + float delta = (d + s) * (d + s) - 4.0 * f0 * d; + float deltaSqrt = sqrt(max(0.0, delta)); + // solver + float solverMetallic = (-d - s + 2.0 * f0 + deltaSqrt) / (2.0 * f0); + vec3 solverAlbedo = (d + s) * normalizedColor - vec3(f0 * (1.0 - solverMetallic)); + + bool isValidSolver = delta >= 0.0; + metallic = isValidSolver ? clamp(solverMetallic, 0.0, 1.0) : 0.0; + albedo = isValidSolver ? vec3(max(0.0, solverAlbedo.x), max(0.0, solverAlbedo.y), max(0.0, solverAlbedo.z)) : diffuse; + return isValidSolver; +} diff --git a/editor/assets/chunks/common/mesh/material.chunk.meta b/editor/assets/chunks/common/mesh/material.chunk.meta new file mode 100644 index 0000000000..58551fa823 --- /dev/null +++ b/editor/assets/chunks/common/mesh/material.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "f992af76-5145-4f8e-beae-6d88be403e8e", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/common/shadow.meta b/editor/assets/chunks/common/shadow.meta new file mode 100644 index 0000000000..dab53678e4 --- /dev/null +++ b/editor/assets/chunks/common/shadow.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "be653157-db73-4064-b4e6-2f46a03ec65f", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/common/shadow/native-pcf.chunk b/editor/assets/chunks/common/shadow/native-pcf.chunk new file mode 100644 index 0000000000..78057bb9a5 --- /dev/null +++ b/editor/assets/chunks/common/shadow/native-pcf.chunk @@ -0,0 +1,201 @@ +// NDC shadowPos applied with normal bias and depth bias + +float NativePCFShadowFactorHard (vec3 shadowNDCPos, sampler2D shadowMap, vec2 shadowMapResolution) +{ + #if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8 + return step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, shadowNDCPos.xy))); + #else + return step(shadowNDCPos.z, texture(shadowMap, shadowNDCPos.xy).x); + #endif +} + +float NativePCFShadowFactorSoft (vec3 shadowNDCPos, sampler2D shadowMap, vec2 shadowMapResolution) +{ + vec2 oneTap = 1.0 / shadowMapResolution; + vec2 shadowNDCPos_offset = shadowNDCPos.xy + oneTap; + + float block0, block1, block2, block3; + #if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8 + block0 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos.y)))); + block1 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos_offset.x, shadowNDCPos.y)))); + block2 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos_offset.y)))); + block3 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos_offset.x, shadowNDCPos_offset.y)))); + #else + block0 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos.y)).x); + block1 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos_offset.x, shadowNDCPos.y)).x); + block2 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos_offset.y)).x); + block3 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos_offset.x, shadowNDCPos_offset.y)).x); + #endif + + float coefX = mod(shadowNDCPos.x, oneTap.x) * shadowMapResolution.x; + float resultX = mix(block0, block1, coefX); + float resultY = mix(block2, block3, coefX); + float coefY = mod(shadowNDCPos.y, oneTap.y) * shadowMapResolution.y; + + return mix(resultX, resultY, coefY); +} + +float NativePCFShadowFactorSoft3X (vec3 shadowNDCPos, sampler2D shadowMap, vec2 shadowMapResolution) +{ + vec2 oneTap = 1.0 / shadowMapResolution; + float shadowNDCPos_offset_L = shadowNDCPos.x - oneTap.x; + float shadowNDCPos_offset_R = shadowNDCPos.x + oneTap.x; + float shadowNDCPos_offset_U = shadowNDCPos.y - oneTap.y; + float shadowNDCPos_offset_D = shadowNDCPos.y + oneTap.y; + + float block0, block1, block2, block3, block4, block5, block6, block7, block8; + #if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8 + block0 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos_offset_L, shadowNDCPos_offset_U)))); + block1 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos_offset_U)))); + block2 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos_offset_R, shadowNDCPos_offset_U)))); + block3 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos_offset_L, shadowNDCPos.y)))); + block4 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos.y)))); + block5 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos_offset_R, shadowNDCPos.y)))); + block6 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos_offset_L, shadowNDCPos_offset_D)))); + block7 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos_offset_D)))); + block8 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, vec2(shadowNDCPos_offset_R, shadowNDCPos_offset_D)))); + #else + block0 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos_offset_L, shadowNDCPos_offset_U)).x); + block1 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos_offset_U)).x); + block2 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos_offset_R, shadowNDCPos_offset_U)).x); + block3 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos_offset_L, shadowNDCPos.y)).x); + block4 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos.y)).x); + block5 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos_offset_R, shadowNDCPos.y)).x); + block6 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos_offset_L, shadowNDCPos_offset_D)).x); + block7 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos.x, shadowNDCPos_offset_D)).x); + block8 = step(shadowNDCPos.z, texture(shadowMap, vec2(shadowNDCPos_offset_R, shadowNDCPos_offset_D)).x); + #endif + + float coefX = mod(shadowNDCPos.x, oneTap.x) * shadowMapResolution.x; + float coefY = mod(shadowNDCPos.y, oneTap.y) * shadowMapResolution.y; + + float shadow = 0.0; + float resultX = mix(block0, block1, coefX); + float resultY = mix(block3, block4, coefX); + shadow += mix(resultX , resultY, coefY); + + resultX = mix(block1, block2, coefX); + resultY = mix(block4, block5, coefX); + shadow += mix(resultX , resultY, coefY); + + resultX = mix(block3, block4, coefX); + resultY = mix(block6, block7, coefX); + shadow += mix(resultX, resultY, coefY); + + resultX = mix(block4, block5, coefX); + resultY = mix(block7, block8, coefX); + shadow += mix(resultX, resultY, coefY); + + return shadow * 0.25; +} + +float NativePCFShadowFactorSoft5X (vec3 shadowNDCPos, sampler2D shadowMap, vec2 shadowMapResolution) +{ + vec2 oneTap = 1.0 / shadowMapResolution; + vec2 twoTap = oneTap * 2.0; + + vec2 offset1 = shadowNDCPos.xy + vec2(-twoTap.x, -twoTap.y); + vec2 offset2 = shadowNDCPos.xy + vec2(-oneTap.x, -twoTap.y); + vec2 offset3 = shadowNDCPos.xy + vec2(0.0, -twoTap.y); + vec2 offset4 = shadowNDCPos.xy + vec2(oneTap.x, -twoTap.y); + vec2 offset5 = shadowNDCPos.xy + vec2(twoTap.x, -twoTap.y); + vec2 offset6 = shadowNDCPos.xy + vec2(-twoTap.x, -oneTap.y); + vec2 offset7 = shadowNDCPos.xy + vec2(-oneTap.x, -oneTap.y); + vec2 offset8 = shadowNDCPos.xy + vec2(0.0, -oneTap.y); + vec2 offset9 = shadowNDCPos.xy + vec2(oneTap.x, -oneTap.y); + vec2 offset10 = shadowNDCPos.xy + vec2(twoTap.x, -oneTap.y); + vec2 offset11 = shadowNDCPos.xy + vec2(-twoTap.x, 0.0); + vec2 offset12 = shadowNDCPos.xy + vec2(-oneTap.x, 0.0); + vec2 offset13 = shadowNDCPos.xy + vec2(0.0, 0.0); + vec2 offset14 = shadowNDCPos.xy + vec2(oneTap.x, 0.0); + vec2 offset15 = shadowNDCPos.xy + vec2(twoTap.x, 0.0); + vec2 offset16 = shadowNDCPos.xy + vec2(-twoTap.x, oneTap.y); + vec2 offset17 = shadowNDCPos.xy + vec2(-oneTap.x, oneTap.y); + vec2 offset18 = shadowNDCPos.xy + vec2(0.0, oneTap.y); + vec2 offset19 = shadowNDCPos.xy + vec2(oneTap.x, oneTap.y); + vec2 offset20 = shadowNDCPos.xy + vec2(twoTap.x, oneTap.y); + vec2 offset21 = shadowNDCPos.xy + vec2(-twoTap.x, twoTap.y); + vec2 offset22 = shadowNDCPos.xy + vec2(-oneTap.x, twoTap.y); + vec2 offset23 = shadowNDCPos.xy + vec2(0.0, twoTap.y); + vec2 offset24 = shadowNDCPos.xy + vec2(oneTap.x, twoTap.y); + vec2 offset25 = shadowNDCPos.xy + vec2(twoTap.x, twoTap.y); + + float block1, block2, block3, block4, block5, block6, block7, block8, block9, block10, block11, block12, block13, block14, block15, block16, block17, block18, block19, block20, block21, block22, block23, block24, block25; + #if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8 + block1 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset1))); + block2 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset2))); + block3 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset3))); + block4 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset4))); + block5 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset5))); + block6 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset6))); + block7 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset7))); + block8 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset8))); + block9 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset9))); + block10 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset10))); + block11 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset11))); + block12 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset12))); + block13 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset13))); + block14 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset14))); + block15 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset15))); + block16 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset16))); + block17 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset17))); + block18 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset18))); + block19 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset19))); + block20 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset20))); + block21 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset21))); + block22 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset22))); + block23 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset23))); + block24 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset24))); + block25 = step(shadowNDCPos.z, unpackRGBAToDepth(texture(shadowMap, offset25))); + #else + block1 = step(shadowNDCPos.z, texture(shadowMap, offset1).x); + block2 = step(shadowNDCPos.z, texture(shadowMap, offset2).x); + block3 = step(shadowNDCPos.z, texture(shadowMap, offset3).x); + block4 = step(shadowNDCPos.z, texture(shadowMap, offset4).x); + block5 = step(shadowNDCPos.z, texture(shadowMap, offset5).x); + block6 = step(shadowNDCPos.z, texture(shadowMap, offset6).x); + block7 = step(shadowNDCPos.z, texture(shadowMap, offset7).x); + block8 = step(shadowNDCPos.z, texture(shadowMap, offset8).x); + block9 = step(shadowNDCPos.z, texture(shadowMap, offset9).x); + block10 = step(shadowNDCPos.z, texture(shadowMap, offset10).x); + block11 = step(shadowNDCPos.z, texture(shadowMap, offset11).x); + block12 = step(shadowNDCPos.z, texture(shadowMap, offset12).x); + block13 = step(shadowNDCPos.z, texture(shadowMap, offset13).x); + block14 = step(shadowNDCPos.z, texture(shadowMap, offset14).x); + block15 = step(shadowNDCPos.z, texture(shadowMap, offset15).x); + block16 = step(shadowNDCPos.z, texture(shadowMap, offset16).x); + block17 = step(shadowNDCPos.z, texture(shadowMap, offset17).x); + block18 = step(shadowNDCPos.z, texture(shadowMap, offset18).x); + block19 = step(shadowNDCPos.z, texture(shadowMap, offset19).x); + block20 = step(shadowNDCPos.z, texture(shadowMap, offset20).x); + block21 = step(shadowNDCPos.z, texture(shadowMap, offset21).x); + block22 = step(shadowNDCPos.z, texture(shadowMap, offset22).x); + block23 = step(shadowNDCPos.z, texture(shadowMap, offset23).x); + block24 = step(shadowNDCPos.z, texture(shadowMap, offset24).x); + block25 = step(shadowNDCPos.z, texture(shadowMap, offset25).x); + #endif + + vec2 coef = fract(shadowNDCPos.xy * shadowMapResolution); + vec2 v1X1 = mix(vec2(block1, block6), vec2(block2, block7), coef.xx); + vec2 v1X2 = mix(vec2(block2, block7), vec2(block3, block8), coef.xx); + vec2 v1X3 = mix(vec2(block3, block8), vec2(block4, block9), coef.xx); + vec2 v1X4 = mix(vec2(block4, block9), vec2(block5, block10), coef.xx); + float v1 = mix(v1X1.x, v1X1.y, coef.y) + mix(v1X2.x, v1X2.y, coef.y) + mix(v1X3.x, v1X3.y, coef.y) + mix(v1X4.x, v1X4.y, coef.y); + vec2 v2X1 = mix(vec2(block6, block11), vec2(block7, block12), coef.xx); + vec2 v2X2 = mix(vec2(block7, block12), vec2(block8, block13), coef.xx); + vec2 v2X3 = mix(vec2(block8, block13), vec2(block9, block14), coef.xx); + vec2 v2X4 = mix(vec2(block9, block14), vec2(block10, block15), coef.xx); + float v2 = mix(v2X1.x, v2X1.y, coef.y) + mix(v2X2.x, v2X2.y, coef.y) + mix(v2X3.x, v2X3.y, coef.y) + mix(v2X4.x, v2X4.y, coef.y); + vec2 v3X1 = mix(vec2(block11, block16), vec2(block12, block17), coef.xx); + vec2 v3X2 = mix(vec2(block12, block17), vec2(block13, block18), coef.xx); + vec2 v3X3 = mix(vec2(block13, block18), vec2(block14, block19), coef.xx); + vec2 v3X4 = mix(vec2(block14, block19), vec2(block15, block20), coef.xx); + float v3 = mix(v3X1.x, v3X1.y, coef.y) + mix(v3X2.x, v3X2.y, coef.y) + mix(v3X3.x, v3X3.y, coef.y) + mix(v3X4.x, v3X4.y, coef.y); + vec2 v4X1 = mix(vec2(block16, block21), vec2(block17, block22), coef.xx); + vec2 v4X2 = mix(vec2(block17, block22), vec2(block18, block23), coef.xx); + vec2 v4X3 = mix(vec2(block18, block23), vec2(block19, block24), coef.xx); + vec2 v4X4 = mix(vec2(block19, block24), vec2(block20, block25), coef.xx); + float v4 = mix(v4X1.x, v4X1.y, coef.y) + mix(v4X2.x, v4X2.y, coef.y) + mix(v4X3.x, v4X3.y, coef.y) + mix(v4X4.x, v4X4.y, coef.y); + float fAvg = (v1 + v2 + v3 + v4) * 0.0625; + return fAvg; +} diff --git a/editor/assets/chunks/common/shadow/native-pcf.chunk.meta b/editor/assets/chunks/common/shadow/native-pcf.chunk.meta new file mode 100644 index 0000000000..95779e1cc1 --- /dev/null +++ b/editor/assets/chunks/common/shadow/native-pcf.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "cac4ba94-f412-4899-83b1-ce035b0c09e0", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/common/sss.meta b/editor/assets/chunks/common/sss.meta new file mode 100644 index 0000000000..9f17ffb862 --- /dev/null +++ b/editor/assets/chunks/common/sss.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "22d0392f-1cc0-4bb1-8b84-577e3f4551e0", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/common/texture.meta b/editor/assets/chunks/common/texture.meta new file mode 100644 index 0000000000..78b11e379d --- /dev/null +++ b/editor/assets/chunks/common/texture.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "fcd5dc66-1649-4a01-b94c-b528bb881cfb", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/common/texture/cubemap.chunk b/editor/assets/chunks/common/texture/cubemap.chunk new file mode 100644 index 0000000000..096cf8963f --- /dev/null +++ b/editor/assets/chunks/common/texture/cubemap.chunk @@ -0,0 +1,48 @@ +#pragma extension([GL_OES_standard_derivatives, __VERSION__ < 110]) + vec3 EnvReflectionWithMipFiltering(vec3 R, float roughness, float mipCount, float denoiseIntensity) { + #if CC_USE_IBL + // simulate GGX convolution + #if !CC_SURFACES_USE_LEGACY_COMPATIBLE_LIGHTING && !CC_IBL_CONVOLUTED + roughness = pow(roughness, 0.5); + #endif + + //#todo: add GL400 calcmip + float mip = roughness * mipCount; + float delta = (dot(dFdx(R), dFdy(R))) * 1000.0; + float mipBias = mix(0.0, 5.0, clamp(delta, 0.0, 1.0)); + + vec4 biased = fragTextureLod(cc_environment, R, mip + mipBias); + vec4 filtered = texture(cc_environment, R); + + #if CC_USE_IBL == IBL_RGBE + biased.rgb = unpackRGBE(biased); + filtered.rgb = unpackRGBE(filtered); + #else + biased.rgb = SRGBToLinear(biased.rgb); + filtered.rgb = SRGBToLinear(filtered.rgb); + #endif + + return mix(biased.rgb, filtered.rgb, denoiseIntensity); + #else + return vec3(0.0, 0.0, 0.0); + #endif + } + + vec3 EnvReflection(vec3 R, float roughness, float mipCount) { + #if CC_USE_IBL + // simulate GGX convolution + #if !CC_SURFACES_USE_LEGACY_COMPATIBLE_LIGHTING && !CC_IBL_CONVOLUTED + roughness = pow(roughness, 0.5); + #endif + + vec4 envmap = fragTextureLod(cc_environment, R, roughness * mipCount); + + #if CC_USE_IBL == IBL_RGBE + return unpackRGBE(envmap); + #else + return SRGBToLinear(envmap.rgb); + #endif + #else + return vec3(0.0, 0.0, 0.0); + #endif + } diff --git a/editor/assets/chunks/common/texture/cubemap.chunk.meta b/editor/assets/chunks/common/texture/cubemap.chunk.meta new file mode 100644 index 0000000000..824fdc2036 --- /dev/null +++ b/editor/assets/chunks/common/texture/cubemap.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "3931bd87-0a7b-4d2d-a5f1-9544227343a8", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/texture-lod.chunk b/editor/assets/chunks/common/texture/texture-lod.chunk similarity index 100% rename from editor/assets/chunks/texture-lod.chunk rename to editor/assets/chunks/common/texture/texture-lod.chunk diff --git a/editor/assets/chunks/texture-lod.chunk.meta b/editor/assets/chunks/common/texture/texture-lod.chunk.meta similarity index 89% rename from editor/assets/chunks/texture-lod.chunk.meta rename to editor/assets/chunks/common/texture/texture-lod.chunk.meta index ff25873856..6f3bad78d9 100644 --- a/editor/assets/chunks/texture-lod.chunk.meta +++ b/editor/assets/chunks/common/texture/texture-lod.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "d26f7be9-ac7f-4dfd-88ee-6657dfe3426e", diff --git a/editor/assets/chunks/common/ubo.meta b/editor/assets/chunks/common/ubo.meta new file mode 100644 index 0000000000..a8c355114b --- /dev/null +++ b/editor/assets/chunks/common/ubo.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "2476d369-6d06-4dab-ade6-0d8b22ae0948", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/deprecated.chunk.meta b/editor/assets/chunks/deprecated.chunk.meta index 43bfc3a5c6..4c57b9fe65 100644 --- a/editor/assets/chunks/deprecated.chunk.meta +++ b/editor/assets/chunks/deprecated.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "355259fc-3a13-4fed-b553-a5e2caeb2e75", diff --git a/editor/assets/chunks/embedded-alpha.meta b/editor/assets/chunks/embedded-alpha.meta deleted file mode 100644 index 284d478eab..0000000000 --- a/editor/assets/chunks/embedded-alpha.meta +++ /dev/null @@ -1,9 +0,0 @@ -{ - "ver": "1.0.0", - "importer": "effect-header", - "imported": true, - "uuid": "38c5e61f-5e12-4c1d-8e88-a9d832c48b16", - "files": [], - "subMetas": {}, - "userData": {} -} diff --git a/editor/assets/chunks/gamma.chunk b/editor/assets/chunks/gamma.chunk deleted file mode 100644 index eb58081d4a..0000000000 --- a/editor/assets/chunks/gamma.chunk +++ /dev/null @@ -1,9 +0,0 @@ -// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. - -// #pragma define SRGBToLinear(gamma) pow(gamma, vec3(2.2)) -vec3 SRGBToLinear (vec3 gamma) { - return gamma * gamma; -} - -// #pragma define LinearToSRGB(linear) pow(linear, vec3(0.454545)) -#pragma define LinearToSRGB(linear) sqrt(linear) diff --git a/editor/assets/chunks/legacy.meta b/editor/assets/chunks/legacy.meta new file mode 100644 index 0000000000..76fa2894fd --- /dev/null +++ b/editor/assets/chunks/legacy.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "ea1a269d-29b3-4ca1-bc48-e2be305a0a71", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/decode-base.chunk b/editor/assets/chunks/legacy/decode-base.chunk similarity index 81% rename from editor/assets/chunks/decode-base.chunk rename to editor/assets/chunks/legacy/decode-base.chunk index 9825b259a1..7c29282c0f 100644 --- a/editor/assets/chunks/decode-base.chunk +++ b/editor/assets/chunks/legacy/decode-base.chunk @@ -1,6 +1,9 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. -#include +#pragma define-meta USE_INSTANCING editor(elevated: true) +#pragma define-meta USE_BATCHING editor(elevated: true) + +#include struct StandardVertInput { highp vec4 position; @@ -13,11 +16,28 @@ layout(location = 1) in vec3 a_normal; layout(location = 2) in vec2 a_texCoord; layout(location = 3) in vec4 a_tangent; +#if CC_USE_SKINNING + #if __VERSION__ > 310 + // strictly speaking this should be u16vec4, but due to poor driver support + // somehow it seems we can get better results on many platforms using u32vec4 + layout(location = 4) in u32vec4 a_joints; + #else + #pragma format(RGBA16UI) + layout(location = 4) in vec4 a_joints; + #endif + + layout(location = 5) in vec4 a_weights; +#endif + + #if USE_INSTANCING + #if CC_USE_BAKED_ANIMATION + in highp vec4 a_jointAnimInfo; // frameID, totalJoints, offset + #endif in vec4 a_matWorld0; in vec4 a_matWorld1; in vec4 a_matWorld2; - #if USE_LIGHTMAP + #if CC_USE_LIGHTMAP in vec4 a_lightingMapUVParam; #endif #if CC_RECEIVE_SHADOW @@ -39,16 +59,3 @@ layout(location = 3) in vec4 a_tangent; } #endif #endif - -#if CC_USE_SKINNING - #if __VERSION__ > 310 - // strictly speaking this should be u16vec4, but due to poor driver support - // somehow it seems we can get better results on many platforms using u32vec4 - layout(location = 4) in u32vec4 a_joints; - #else - #pragma format(RGBA16UI) - layout(location = 4) in vec4 a_joints; - #endif - - layout(location = 5) in vec4 a_weights; -#endif diff --git a/editor/assets/chunks/decode-base.chunk.meta b/editor/assets/chunks/legacy/decode-base.chunk.meta similarity index 89% rename from editor/assets/chunks/decode-base.chunk.meta rename to editor/assets/chunks/legacy/decode-base.chunk.meta index f693d19c74..badd50fc3d 100644 --- a/editor/assets/chunks/decode-base.chunk.meta +++ b/editor/assets/chunks/legacy/decode-base.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "e05f440c-0ba5-4c83-a039-5644d248bb87", diff --git a/editor/assets/chunks/decode-standard.chunk b/editor/assets/chunks/legacy/decode-standard.chunk similarity index 88% rename from editor/assets/chunks/decode-standard.chunk rename to editor/assets/chunks/legacy/decode-standard.chunk index a36a3b22fa..7deecee12a 100644 --- a/editor/assets/chunks/decode-standard.chunk +++ b/editor/assets/chunks/legacy/decode-standard.chunk @@ -1,5 +1,5 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. -#include +#include #pragma define CCDecode(attr) \ attr.position = vec4(a_position, 1.0); \ diff --git a/editor/assets/chunks/decode-standard.chunk.meta b/editor/assets/chunks/legacy/decode-standard.chunk.meta similarity index 89% rename from editor/assets/chunks/decode-standard.chunk.meta rename to editor/assets/chunks/legacy/decode-standard.chunk.meta index 7fb1eb3973..5f72be4425 100644 --- a/editor/assets/chunks/decode-standard.chunk.meta +++ b/editor/assets/chunks/legacy/decode-standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "8daa33da-9438-4294-aace-2a58d1b183ab", diff --git a/editor/assets/chunks/decode.chunk b/editor/assets/chunks/legacy/decode.chunk similarity index 81% rename from editor/assets/chunks/decode.chunk rename to editor/assets/chunks/legacy/decode.chunk index 4f0163ae95..faf433592f 100644 --- a/editor/assets/chunks/decode.chunk +++ b/editor/assets/chunks/legacy/decode.chunk @@ -1,5 +1,5 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. -#include +#include #pragma define CCDecode(position) \ position = vec4(a_position, 1.0) diff --git a/editor/assets/chunks/decode.chunk.meta b/editor/assets/chunks/legacy/decode.chunk.meta similarity index 89% rename from editor/assets/chunks/decode.chunk.meta rename to editor/assets/chunks/legacy/decode.chunk.meta index 5a0fd7f9ab..c9784e1a4f 100644 --- a/editor/assets/chunks/decode.chunk.meta +++ b/editor/assets/chunks/legacy/decode.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "385a7ca1-9421-475c-aa02-38d52ef3ba7f", diff --git a/editor/assets/chunks/legacy/fog-base.chunk b/editor/assets/chunks/legacy/fog-base.chunk new file mode 100644 index 0000000000..f34d422934 --- /dev/null +++ b/editor/assets/chunks/legacy/fog-base.chunk @@ -0,0 +1 @@ +#include diff --git a/editor/assets/chunks/legacy/fog-base.chunk.meta b/editor/assets/chunks/legacy/fog-base.chunk.meta new file mode 100644 index 0000000000..6a0164cf37 --- /dev/null +++ b/editor/assets/chunks/legacy/fog-base.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "84b6c1d8-edf3-4d07-9151-8f7ec568fd69", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/cc-fog-fs.chunk b/editor/assets/chunks/legacy/fog-fs.chunk similarity index 95% rename from editor/assets/chunks/cc-fog-fs.chunk rename to editor/assets/chunks/legacy/fog-fs.chunk index b94bc76404..bf63dca0e8 100644 --- a/editor/assets/chunks/cc-fog-fs.chunk +++ b/editor/assets/chunks/legacy/fog-fs.chunk @@ -1,6 +1,6 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. -#include +#include #if !CC_USE_ACCURATE_FOG in float v_fog_factor; diff --git a/editor/assets/chunks/cc-fog-fs.chunk.meta b/editor/assets/chunks/legacy/fog-fs.chunk.meta similarity index 89% rename from editor/assets/chunks/cc-fog-fs.chunk.meta rename to editor/assets/chunks/legacy/fog-fs.chunk.meta index 7850128658..254c62b66d 100644 --- a/editor/assets/chunks/cc-fog-fs.chunk.meta +++ b/editor/assets/chunks/legacy/fog-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "5915ee07-9b06-4383-9b98-5b292bd116e9", diff --git a/editor/assets/chunks/cc-fog-vs.chunk b/editor/assets/chunks/legacy/fog-vs.chunk similarity index 91% rename from editor/assets/chunks/cc-fog-vs.chunk rename to editor/assets/chunks/legacy/fog-vs.chunk index 06aed9813f..a91408b9ce 100644 --- a/editor/assets/chunks/cc-fog-vs.chunk +++ b/editor/assets/chunks/legacy/fog-vs.chunk @@ -1,6 +1,6 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. -#include +#include #if !CC_USE_ACCURATE_FOG out float v_fog_factor; diff --git a/editor/assets/chunks/cc-fog-vs.chunk.meta b/editor/assets/chunks/legacy/fog-vs.chunk.meta similarity index 89% rename from editor/assets/chunks/cc-fog-vs.chunk.meta rename to editor/assets/chunks/legacy/fog-vs.chunk.meta index b7d58f30ef..927934a2bc 100644 --- a/editor/assets/chunks/cc-fog-vs.chunk.meta +++ b/editor/assets/chunks/legacy/fog-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "0bc1a9f5-9282-4192-a0d4-4818568f2b16", diff --git a/editor/assets/chunks/input-standard.chunk b/editor/assets/chunks/legacy/input-standard.chunk similarity index 78% rename from editor/assets/chunks/input-standard.chunk rename to editor/assets/chunks/legacy/input-standard.chunk index 8bffffecd8..23a5c6a256 100644 --- a/editor/assets/chunks/input-standard.chunk +++ b/editor/assets/chunks/legacy/input-standard.chunk @@ -1,10 +1,10 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. -#include +#include #if CC_USE_MORPH - #include + #include #endif #if CC_USE_SKINNING - #include + #include #endif void CCVertInput(inout StandardVertInput In) diff --git a/editor/assets/chunks/input-standard.chunk.meta b/editor/assets/chunks/legacy/input-standard.chunk.meta similarity index 89% rename from editor/assets/chunks/input-standard.chunk.meta rename to editor/assets/chunks/legacy/input-standard.chunk.meta index 6d57cac8a5..e207992247 100644 --- a/editor/assets/chunks/input-standard.chunk.meta +++ b/editor/assets/chunks/legacy/input-standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "f957d7e0-a3eb-480c-b3c6-43a1a5273b71", diff --git a/editor/assets/chunks/input.chunk b/editor/assets/chunks/legacy/input.chunk similarity index 76% rename from editor/assets/chunks/input.chunk rename to editor/assets/chunks/legacy/input.chunk index 3fe722afce..33a4ab69f1 100644 --- a/editor/assets/chunks/input.chunk +++ b/editor/assets/chunks/legacy/input.chunk @@ -1,10 +1,10 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. -#include +#include #if CC_USE_MORPH - #include + #include #endif #if CC_USE_SKINNING - #include + #include #endif void CCVertInput(inout vec4 In) diff --git a/editor/assets/chunks/input.chunk.meta b/editor/assets/chunks/legacy/input.chunk.meta similarity index 89% rename from editor/assets/chunks/input.chunk.meta rename to editor/assets/chunks/legacy/input.chunk.meta index feab5b5856..c42482bae0 100644 --- a/editor/assets/chunks/input.chunk.meta +++ b/editor/assets/chunks/legacy/input.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "3b9a2995-9fa1-4862-9bcf-9b6fa2c64bd4", diff --git a/editor/assets/chunks/legacy/lighting.chunk b/editor/assets/chunks/legacy/lighting.chunk new file mode 100644 index 0000000000..0eab4437f9 --- /dev/null +++ b/editor/assets/chunks/legacy/lighting.chunk @@ -0,0 +1,9 @@ +// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. + +#pragma define CC_PIPELINE_TYPE_FORWARD 0 +#pragma define CC_PIPELINE_TYPE_DEFERRED 1 +#pragma define-meta CC_PIPELINE_TYPE range([0, 1]) +#pragma define-meta CC_FORCE_FORWARD_SHADING + +#include +#include diff --git a/editor/assets/chunks/lighting.chunk.meta b/editor/assets/chunks/legacy/lighting.chunk.meta similarity index 60% rename from editor/assets/chunks/lighting.chunk.meta rename to editor/assets/chunks/legacy/lighting.chunk.meta index ccf012ca87..9441cbaf19 100644 --- a/editor/assets/chunks/lighting.chunk.meta +++ b/editor/assets/chunks/legacy/lighting.chunk.meta @@ -1,8 +1,8 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, - "uuid": "357618ca-4d71-41b6-af86-9534799c705e", + "uuid": "4b078b9b-ae79-4653-bc9d-d70e69b49f4b", "files": [], "subMetas": {}, "userData": {} diff --git a/editor/assets/chunks/legacy/lightingmap-fs.chunk b/editor/assets/chunks/legacy/lightingmap-fs.chunk new file mode 100644 index 0000000000..ce6dcc9419 --- /dev/null +++ b/editor/assets/chunks/legacy/lightingmap-fs.chunk @@ -0,0 +1,2 @@ +in vec3 v_luv; +#include \ No newline at end of file diff --git a/editor/assets/chunks/lightingmap-fs.chunk.meta b/editor/assets/chunks/legacy/lightingmap-fs.chunk.meta similarity index 60% rename from editor/assets/chunks/lightingmap-fs.chunk.meta rename to editor/assets/chunks/legacy/lightingmap-fs.chunk.meta index e5392020ba..1339518218 100644 --- a/editor/assets/chunks/lightingmap-fs.chunk.meta +++ b/editor/assets/chunks/legacy/lightingmap-fs.chunk.meta @@ -1,8 +1,8 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, - "uuid": "bf771826-ab41-49bd-8058-1cd0fa7a7273", + "uuid": "1cd3229a-63b6-438b-88e9-98afa7f1c69e", "files": [], "subMetas": {}, "userData": {} diff --git a/editor/assets/chunks/lightingmap-vs.chunk b/editor/assets/chunks/legacy/lightingmap-vs.chunk similarity index 100% rename from editor/assets/chunks/lightingmap-vs.chunk rename to editor/assets/chunks/legacy/lightingmap-vs.chunk diff --git a/editor/assets/chunks/lightingmap-vs.chunk.meta b/editor/assets/chunks/legacy/lightingmap-vs.chunk.meta similarity index 89% rename from editor/assets/chunks/lightingmap-vs.chunk.meta rename to editor/assets/chunks/legacy/lightingmap-vs.chunk.meta index 251df876ed..ac4b38351c 100644 --- a/editor/assets/chunks/lightingmap-vs.chunk.meta +++ b/editor/assets/chunks/legacy/lightingmap-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "d22a3ca1-78fe-442c-a604-0349f5c873f7", diff --git a/editor/assets/chunks/legacy/local-batch.chunk b/editor/assets/chunks/legacy/local-batch.chunk new file mode 100644 index 0000000000..00d8754841 --- /dev/null +++ b/editor/assets/chunks/legacy/local-batch.chunk @@ -0,0 +1,2 @@ +#include +#include \ No newline at end of file diff --git a/editor/assets/chunks/legacy/local-batch.chunk.meta b/editor/assets/chunks/legacy/local-batch.chunk.meta new file mode 100644 index 0000000000..cd7932b447 --- /dev/null +++ b/editor/assets/chunks/legacy/local-batch.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "bcff50e8-1d1f-4aea-bd0c-6868a4f2a45b", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/legacy/main-functions.meta b/editor/assets/chunks/legacy/main-functions.meta new file mode 100644 index 0000000000..47d9c389e1 --- /dev/null +++ b/editor/assets/chunks/legacy/main-functions.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "de715099-a76e-4d5d-85a3-108da7d8b29b", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/general-vs.chunk b/editor/assets/chunks/legacy/main-functions/general-vs.chunk similarity index 81% rename from editor/assets/chunks/general-vs.chunk rename to editor/assets/chunks/legacy/main-functions/general-vs.chunk index e827396bed..ceed7f5730 100644 --- a/editor/assets/chunks/general-vs.chunk +++ b/editor/assets/chunks/legacy/main-functions/general-vs.chunk @@ -1,11 +1,11 @@ precision highp float; -#include -#include -#include -#include -#include -#include +#include +#include +#include +#include +#include +#include in vec4 a_color; #if HAS_SECOND_UV diff --git a/editor/assets/chunks/general-vs.chunk.meta b/editor/assets/chunks/legacy/main-functions/general-vs.chunk.meta similarity index 89% rename from editor/assets/chunks/general-vs.chunk.meta rename to editor/assets/chunks/legacy/main-functions/general-vs.chunk.meta index 6ed03008b7..522b83410b 100644 --- a/editor/assets/chunks/general-vs.chunk.meta +++ b/editor/assets/chunks/legacy/main-functions/general-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "2cdcf2a6-42f3-4142-a340-eabfe530ccbf", diff --git a/editor/assets/chunks/outline-fs.chunk b/editor/assets/chunks/legacy/main-functions/outline-fs.chunk similarity index 86% rename from editor/assets/chunks/outline-fs.chunk rename to editor/assets/chunks/legacy/main-functions/outline-fs.chunk index f35273eb62..6675ffc01f 100644 --- a/editor/assets/chunks/outline-fs.chunk +++ b/editor/assets/chunks/legacy/main-functions/outline-fs.chunk @@ -1,7 +1,7 @@ precision highp float; -#include -#include +#include +#include in vec2 v_uv; diff --git a/editor/assets/chunks/outline-fs.chunk.meta b/editor/assets/chunks/legacy/main-functions/outline-fs.chunk.meta similarity index 89% rename from editor/assets/chunks/outline-fs.chunk.meta rename to editor/assets/chunks/legacy/main-functions/outline-fs.chunk.meta index 2d8169ce5a..31abf0e7b0 100644 --- a/editor/assets/chunks/outline-fs.chunk.meta +++ b/editor/assets/chunks/legacy/main-functions/outline-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "4864e2f6-3eb5-4f08-a87a-5c98141cdef4", diff --git a/editor/assets/chunks/outline-vs.chunk b/editor/assets/chunks/legacy/main-functions/outline-vs.chunk similarity index 87% rename from editor/assets/chunks/outline-vs.chunk rename to editor/assets/chunks/legacy/main-functions/outline-vs.chunk index c9a104392d..4bf1d02f6f 100644 --- a/editor/assets/chunks/outline-vs.chunk +++ b/editor/assets/chunks/legacy/main-functions/outline-vs.chunk @@ -1,8 +1,8 @@ precision highp float; -#include -#include -#include +#include +#include +#include out vec2 v_uv; diff --git a/editor/assets/chunks/outline-vs.chunk.meta b/editor/assets/chunks/legacy/main-functions/outline-vs.chunk.meta similarity index 89% rename from editor/assets/chunks/outline-vs.chunk.meta rename to editor/assets/chunks/legacy/main-functions/outline-vs.chunk.meta index 689b89766e..282d26c222 100644 --- a/editor/assets/chunks/outline-vs.chunk.meta +++ b/editor/assets/chunks/legacy/main-functions/outline-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "f71444cb-cecf-4692-a310-2a5fdb96b469", diff --git a/editor/assets/chunks/legacy/morph.chunk b/editor/assets/chunks/legacy/morph.chunk new file mode 100644 index 0000000000..f57a3e62ad --- /dev/null +++ b/editor/assets/chunks/legacy/morph.chunk @@ -0,0 +1 @@ +#include diff --git a/editor/assets/chunks/morph.chunk.meta b/editor/assets/chunks/legacy/morph.chunk.meta similarity index 60% rename from editor/assets/chunks/morph.chunk.meta rename to editor/assets/chunks/legacy/morph.chunk.meta index 780801a95d..0cf4637e72 100644 --- a/editor/assets/chunks/morph.chunk.meta +++ b/editor/assets/chunks/legacy/morph.chunk.meta @@ -1,8 +1,8 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, - "uuid": "5e669fb5-203c-4e59-90b1-10e6ef5d7e29", + "uuid": "48359533-f5f1-4346-b242-66597abd9838", "files": [], "subMetas": {}, "userData": {} diff --git a/editor/assets/chunks/output-standard.chunk b/editor/assets/chunks/legacy/output-standard.chunk similarity index 78% rename from editor/assets/chunks/output-standard.chunk rename to editor/assets/chunks/legacy/output-standard.chunk index 0cfce81242..7e15576c57 100644 --- a/editor/assets/chunks/output-standard.chunk +++ b/editor/assets/chunks/legacy/output-standard.chunk @@ -1,6 +1,6 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. -#include -#include +#include +#include vec4 CCFragOutput (vec4 color) { #if CC_USE_HDR diff --git a/editor/assets/chunks/output-standard.chunk.meta b/editor/assets/chunks/legacy/output-standard.chunk.meta similarity index 89% rename from editor/assets/chunks/output-standard.chunk.meta rename to editor/assets/chunks/legacy/output-standard.chunk.meta index c3fbe0d46a..963d8ad8c4 100644 --- a/editor/assets/chunks/output-standard.chunk.meta +++ b/editor/assets/chunks/legacy/output-standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "a3c0cc1c-64de-4e52-9698-5f73f8db488e", diff --git a/editor/assets/chunks/output.chunk b/editor/assets/chunks/legacy/output.chunk similarity index 61% rename from editor/assets/chunks/output.chunk rename to editor/assets/chunks/legacy/output.chunk index b65ca3b358..4e06fa9450 100644 --- a/editor/assets/chunks/output.chunk +++ b/editor/assets/chunks/legacy/output.chunk @@ -1,6 +1,6 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. -#include -#include +#include +#include vec4 CCFragOutput (vec4 color) { return color; diff --git a/editor/assets/chunks/output.chunk.meta b/editor/assets/chunks/legacy/output.chunk.meta similarity index 89% rename from editor/assets/chunks/output.chunk.meta rename to editor/assets/chunks/legacy/output.chunk.meta index a2203d5e61..b8bc4f3744 100644 --- a/editor/assets/chunks/output.chunk.meta +++ b/editor/assets/chunks/legacy/output.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "713f0582-5c82-484f-81f7-5006e5a4f48f", diff --git a/editor/assets/chunks/shading-cluster-additive.chunk b/editor/assets/chunks/legacy/shading-cluster-additive.chunk similarity index 100% rename from editor/assets/chunks/shading-cluster-additive.chunk rename to editor/assets/chunks/legacy/shading-cluster-additive.chunk diff --git a/editor/assets/chunks/shading-cluster-additive.chunk.meta b/editor/assets/chunks/legacy/shading-cluster-additive.chunk.meta similarity index 89% rename from editor/assets/chunks/shading-cluster-additive.chunk.meta rename to editor/assets/chunks/legacy/shading-cluster-additive.chunk.meta index 7112e9b999..456dad04bc 100644 --- a/editor/assets/chunks/shading-cluster-additive.chunk.meta +++ b/editor/assets/chunks/legacy/shading-cluster-additive.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "b2d386c6-615b-4375-accd-574405611e35", diff --git a/editor/assets/chunks/shading-standard-additive.chunk b/editor/assets/chunks/legacy/shading-standard-additive.chunk similarity index 98% rename from editor/assets/chunks/shading-standard-additive.chunk rename to editor/assets/chunks/legacy/shading-standard-additive.chunk index fffa68db83..af5a2963e3 100644 --- a/editor/assets/chunks/shading-standard-additive.chunk +++ b/editor/assets/chunks/legacy/shading-standard-additive.chunk @@ -1,6 +1,6 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. -#include +#include #if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 0 vec4 CCStandardShadingAdditive (StandardSurface s, vec4 shadowPos) { diff --git a/editor/assets/chunks/shading-standard-additive.chunk.meta b/editor/assets/chunks/legacy/shading-standard-additive.chunk.meta similarity index 89% rename from editor/assets/chunks/shading-standard-additive.chunk.meta rename to editor/assets/chunks/legacy/shading-standard-additive.chunk.meta index 91bdac4b31..adb70f1e55 100644 --- a/editor/assets/chunks/shading-standard-additive.chunk.meta +++ b/editor/assets/chunks/legacy/shading-standard-additive.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "a70c48b7-cf69-4c97-a857-21149cd71200", diff --git a/editor/assets/chunks/shading-standard-base.chunk b/editor/assets/chunks/legacy/shading-standard-base.chunk similarity index 86% rename from editor/assets/chunks/shading-standard-base.chunk rename to editor/assets/chunks/legacy/shading-standard-base.chunk index e321179e53..336727e4e2 100644 --- a/editor/assets/chunks/shading-standard-base.chunk +++ b/editor/assets/chunks/legacy/shading-standard-base.chunk @@ -1,18 +1,18 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. // reference: 'moving frostbite to pbr' & UE4 BRDF.usf -#include -#include -#include -#include +#include +#include +#include +#include #if CC_USE_IBL - #include - #include - #include + #include + #include + #include #if CC_USE_DIFFUSEMAP - #include + #include #endif #endif @@ -81,6 +81,7 @@ struct StandardSurface { float roughness; float metallic; float occlusion; + float specularIntensity; #if CC_RECEIVE_SHADOW vec2 shadowBias; @@ -91,7 +92,7 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) { // Calculate diffuse & specular vec3 diffuse = s.albedo.rgb * (1.0 - s.metallic); - vec3 specular = mix(vec3(0.04), s.albedo.rgb, s.metallic); + vec3 specular = mix(vec3(0.08 * s.specularIntensity), s.albedo.rgb, s.metallic); vec3 position; HIGHP_VALUE_FROM_STRUCT_DEFINED(position, s.position); @@ -116,15 +117,19 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) { float shadow = 1.0; #if CC_RECEIVE_SHADOW if (NL > 0.0 && cc_mainLitDir.w > 0.0) { - shadow = CCShadowFactorBase(shadowPos, N, s.shadowBias); + 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 USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD - if (s.lightmap_test > 0.0001) { + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + if (s.lightmap_test > EPSILON_LOWP) { finalColor = diffuse * s.lightmap.rgb * shadow; } #endif @@ -162,7 +167,6 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) { #endif finalColor += ambDiff.rgb * cc_ambientSky.w * diffuse * s.occlusion; - finalColor += s.emissive; diff --git a/editor/assets/chunks/shading-standard-base.chunk.meta b/editor/assets/chunks/legacy/shading-standard-base.chunk.meta similarity index 89% rename from editor/assets/chunks/shading-standard-base.chunk.meta rename to editor/assets/chunks/legacy/shading-standard-base.chunk.meta index 3585f00cd2..e2532ae168 100644 --- a/editor/assets/chunks/shading-standard-base.chunk.meta +++ b/editor/assets/chunks/legacy/shading-standard-base.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "9ae7cfaf-c5cc-4899-95a5-d6e1215c8964", diff --git a/editor/assets/chunks/shading-standard.chunk b/editor/assets/chunks/legacy/shading-standard.chunk similarity index 50% rename from editor/assets/chunks/shading-standard.chunk rename to editor/assets/chunks/legacy/shading-standard.chunk index 04bd0f01f4..eeb896c167 100644 --- a/editor/assets/chunks/shading-standard.chunk +++ b/editor/assets/chunks/legacy/shading-standard.chunk @@ -1,7 +1,7 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. -#include +#include #if CC_FORWARD_ADD -#include +#include #endif diff --git a/editor/assets/chunks/shading-standard.chunk.meta b/editor/assets/chunks/legacy/shading-standard.chunk.meta similarity index 89% rename from editor/assets/chunks/shading-standard.chunk.meta rename to editor/assets/chunks/legacy/shading-standard.chunk.meta index c068df4ee3..872b5824cc 100644 --- a/editor/assets/chunks/shading-standard.chunk.meta +++ b/editor/assets/chunks/legacy/shading-standard.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "f9ba1729-bacf-4e62-8c97-0103d940c464", diff --git a/editor/assets/chunks/shading-toon.chunk b/editor/assets/chunks/legacy/shading-toon.chunk similarity index 92% rename from editor/assets/chunks/shading-toon.chunk rename to editor/assets/chunks/legacy/shading-toon.chunk index 2fc4ea17e8..f13f95c37b 100644 --- a/editor/assets/chunks/shading-toon.chunk +++ b/editor/assets/chunks/legacy/shading-toon.chunk @@ -1,7 +1,7 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. -#include -#include -#include +#include +#include +#include struct ToonSurface { vec4 baseColor; @@ -26,11 +26,11 @@ struct ToonSurface { // Inspired by UTS2, (C)UTJ/UCL #if CC_FORWARD_ADD - #include + #include vec4 CCToonShading (ToonSurface s) { vec3 position; HIGHP_VALUE_FROM_STRUCT_DEFINED(position, s.position); - + vec3 V = normalize(cc_cameraPos.xyz - position); vec3 N = normalize(s.normal); float specularWeight = 1.0 - pow(s.specular.a, 5.0); @@ -72,7 +72,7 @@ struct ToonSurface { } #else #if CC_RECEIVE_SHADOW - #include + #include #endif vec4 CCToonShading (ToonSurface s) { @@ -102,7 +102,11 @@ struct ToonSurface { float shadow = 1.0; #if CC_RECEIVE_SHADOW if(s.shadowCover < NL && cc_mainLitDir.w > 0.0) { + if (cc_shadowLPNNInfo.w > 0.0) { + shadow = CCCSMFactorBase(position, N, s.shadowBias); + } else { shadow = CCShadowFactorBase(CC_SHADOW_POSITION, N, s.shadowBias); + } } #endif diff --git a/editor/assets/chunks/shading-toon.chunk.meta b/editor/assets/chunks/legacy/shading-toon.chunk.meta similarity index 89% rename from editor/assets/chunks/shading-toon.chunk.meta rename to editor/assets/chunks/legacy/shading-toon.chunk.meta index 49dc7e3349..ae89c4d64e 100644 --- a/editor/assets/chunks/shading-toon.chunk.meta +++ b/editor/assets/chunks/legacy/shading-toon.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "bbfd1dfb-8f99-4b68-9aa6-817d5b67096d", diff --git a/editor/assets/chunks/legacy/shadow-map-base.chunk b/editor/assets/chunks/legacy/shadow-map-base.chunk new file mode 100644 index 0000000000..f1f7562f85 --- /dev/null +++ b/editor/assets/chunks/legacy/shadow-map-base.chunk @@ -0,0 +1,3 @@ +#include + +#pragma define CC_TRANSFER_SHADOW_BASE(pos, shadowPos) shadowPos = cc_matLightViewProj * pos diff --git a/editor/assets/chunks/legacy/shadow-map-base.chunk.meta b/editor/assets/chunks/legacy/shadow-map-base.chunk.meta new file mode 100644 index 0000000000..a076463160 --- /dev/null +++ b/editor/assets/chunks/legacy/shadow-map-base.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "1d68b1b7-2f78-4c24-9f35-b215dc980207", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/cc-shadow-map-fs.chunk b/editor/assets/chunks/legacy/shadow-map-fs.chunk similarity index 74% rename from editor/assets/chunks/cc-shadow-map-fs.chunk rename to editor/assets/chunks/legacy/shadow-map-fs.chunk index e9347ae00c..cc9e947dc4 100644 --- a/editor/assets/chunks/cc-shadow-map-fs.chunk +++ b/editor/assets/chunks/legacy/shadow-map-fs.chunk @@ -2,7 +2,7 @@ in highp vec4 v_shadowPos; -#include +#include #pragma define CC_SHADOW_POSITION v_shadowPos @@ -15,4 +15,8 @@ void CC_SPOT_SHADOW_FACTOR(out float realtimeShadow, vec3 worldPos, vec3 lightPo void CC_SHADOW_FACTOR(out float realtimeShadow, vec3 N, float NL, vec2 shadowBias) { realtimeShadow = CCShadowFactorBase(CC_SHADOW_POSITION, N, shadowBias); } + +void CC_CSM_FACTOR(out float realtimeShadow, vec3 worldPos, vec3 N, float NL, vec2 shadowBias) { + realtimeShadow = CCCSMFactorBase(worldPos, N, shadowBias); +} #endif diff --git a/editor/assets/chunks/cc-shadow-map-fs.chunk.meta b/editor/assets/chunks/legacy/shadow-map-fs.chunk.meta similarity index 89% rename from editor/assets/chunks/cc-shadow-map-fs.chunk.meta rename to editor/assets/chunks/legacy/shadow-map-fs.chunk.meta index 73af35bdd5..dac386137d 100644 --- a/editor/assets/chunks/cc-shadow-map-fs.chunk.meta +++ b/editor/assets/chunks/legacy/shadow-map-fs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "5716d893-2ecc-4110-9291-88b7e939d37d", diff --git a/editor/assets/chunks/cc-shadow-map-vs.chunk b/editor/assets/chunks/legacy/shadow-map-vs.chunk similarity index 77% rename from editor/assets/chunks/cc-shadow-map-vs.chunk rename to editor/assets/chunks/legacy/shadow-map-vs.chunk index 40274cc7b0..e10bdb6b4b 100644 --- a/editor/assets/chunks/cc-shadow-map-vs.chunk +++ b/editor/assets/chunks/legacy/shadow-map-vs.chunk @@ -2,8 +2,8 @@ out highp vec4 v_shadowPos; -#include -#include +#include +#include #pragma define CC_SHADOW_POSITION v_shadowPos #pragma define CC_TRANSFER_SHADOW(worldPos) CC_TRANSFER_SHADOW_BASE(worldPos, v_shadowPos) @@ -13,8 +13,10 @@ vec2 CCGetShadowBias() { #if USE_INSTANCING return vec2(a_localShadowBias.x + cc_shadowWHPBInfo.w, a_localShadowBias.y + cc_shadowLPNNInfo.z); - #else + #elif !USE_BATCHING return vec2(cc_localShadowBias.x + cc_shadowWHPBInfo.w, cc_localShadowBias.y + cc_shadowLPNNInfo.z); + #else + return vec2(cc_shadowWHPBInfo.w, cc_shadowLPNNInfo.z); #endif } #endif diff --git a/editor/assets/chunks/cc-shadow-map-vs.chunk.meta b/editor/assets/chunks/legacy/shadow-map-vs.chunk.meta similarity index 89% rename from editor/assets/chunks/cc-shadow-map-vs.chunk.meta rename to editor/assets/chunks/legacy/shadow-map-vs.chunk.meta index 3c7b935b72..8ca760831c 100644 --- a/editor/assets/chunks/cc-shadow-map-vs.chunk.meta +++ b/editor/assets/chunks/legacy/shadow-map-vs.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "b2e7c003-9c9f-40ee-82c6-32d920a759e8", diff --git a/editor/assets/chunks/legacy/skinning.chunk b/editor/assets/chunks/legacy/skinning.chunk new file mode 100644 index 0000000000..9ecae15a4c --- /dev/null +++ b/editor/assets/chunks/legacy/skinning.chunk @@ -0,0 +1,4 @@ +#include +#include +#include +//#include \ No newline at end of file diff --git a/editor/assets/chunks/legacy/skinning.chunk.meta b/editor/assets/chunks/legacy/skinning.chunk.meta new file mode 100644 index 0000000000..b2122b52e9 --- /dev/null +++ b/editor/assets/chunks/legacy/skinning.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "f1e9de44-ca95-48c8-9233-d1b5406ab544", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/standard-surface-entry.chunk b/editor/assets/chunks/legacy/standard-surface-entry.chunk similarity index 89% rename from editor/assets/chunks/standard-surface-entry.chunk rename to editor/assets/chunks/legacy/standard-surface-entry.chunk index 4065e62a71..cd8c3dc9a4 100644 --- a/editor/assets/chunks/standard-surface-entry.chunk +++ b/editor/assets/chunks/legacy/standard-surface-entry.chunk @@ -1,16 +1,16 @@ // Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. -#include -#include -#include -#include +#include +#include +#include +#include #pragma define CC_STANDARD_SURFACE_ENTRY() \ #if CC_FORWARD_ADD \ - #include \ + #include \ #if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1 \ - #include \ + #include \ #endif \ \ layout(location = 0) out vec4 fragColorX; \ @@ -37,7 +37,7 @@ } \ \ #elif CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_DEFERRED \ - #include \ + #include \ \ layout(location = 0) out vec4 fragColor0; \ layout(location = 1) out vec4 fragColor1; \ diff --git a/editor/assets/chunks/standard-surface-entry.chunk.meta b/editor/assets/chunks/legacy/standard-surface-entry.chunk.meta similarity index 89% rename from editor/assets/chunks/standard-surface-entry.chunk.meta rename to editor/assets/chunks/legacy/standard-surface-entry.chunk.meta index 0725978f59..7aa2c5a7a1 100644 --- a/editor/assets/chunks/standard-surface-entry.chunk.meta +++ b/editor/assets/chunks/legacy/standard-surface-entry.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "31d0a199-05e2-422c-a019-8139a855841c", diff --git a/editor/assets/chunks/lighting-models.meta b/editor/assets/chunks/lighting-models.meta new file mode 100644 index 0000000000..2af6387735 --- /dev/null +++ b/editor/assets/chunks/lighting-models.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "fbccacc9-0f83-4d66-8bc5-afa9a6e54b36", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/lighting-models/data-structures.meta b/editor/assets/chunks/lighting-models/data-structures.meta new file mode 100644 index 0000000000..6948d608f4 --- /dev/null +++ b/editor/assets/chunks/lighting-models/data-structures.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "91df99f8-d0d2-451e-9c9e-f2d776851f91", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk b/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk new file mode 100644 index 0000000000..1da0b3f96d --- /dev/null +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk @@ -0,0 +1,76 @@ +struct LightingIntermediateData +{ + vec3 N, H, L, V; // normalized + float distToLight, distToLightSqr; // (pos->light)^2 + float distToCamera, distToCameraSqr; // pos->camera + + float NoL, NoV, NoH;//, VoH; + float NoLSat, NoVSat, NoHSat;//, VoHSat; // clamped to 0-1 + float NoVAbsSat; // abs and clamped to 1 + + // for advanced material + vec3 T, B; + + // material data + float specularParam; // roughness or specular power +#if CC_SURFACES_LIGHTING_ANISOTROPIC + float anisotropyShape; +#endif + + // #if CC_SURFACES_LIGHTING_SPECULAR_2ND + // float specularParam2nd, specularIntensity2nd, specularRotation2nd; // for hair + // vec3 specularColor2nd; + // #endif + // #if CC_SURFACES_LIGHTING_CLEAR_COAT + // float ior; + // float roughnessClearCoat; // for clear coat or multi-layer pbr + // #endif +}; + +// add overrided functions for difference shading-models in +void CCSurfacesLightingGetIntermediateData_PerPixel(inout LightingIntermediateData data, vec3 worldNormal, vec3 worldPos, vec3 worldTangent, vec3 worldBinormal +#if CC_SURFACES_LIGHTING_ANISOTROPIC + , float anisotropyShape +#endif +) +{ + // N V + data.N = worldNormal; + + data.V = cc_cameraPos.xyz - worldPos; + data.distToCameraSqr = dot(data.V, data.V); + data.distToCamera = sqrt(data.distToCameraSqr); + data.V /= data.distToCamera; + + data.NoV = dot(data.N, data.V); + data.NoVSat = max(data.NoV, 0.0); + data.NoVAbsSat = max(abs(data.NoV), 0.0); + + data.T = worldTangent; + data.B = worldBinormal; + +#if CC_SURFACES_LIGHTING_ANISOTROPIC + data.anisotropyShape = anisotropyShape; +#endif +} + +void CCSurfacesLightingGetIntermediateData_PerLight(inout LightingIntermediateData data, vec3 lightDirWithDist) +{ + // L H + data.L = lightDirWithDist; + data.distToLightSqr = dot(data.L, data.L); + data.distToLight = sqrt(data.distToLightSqr); + + data.L /= data.distToLight; + + data.H = normalize(data.L + data.V); + + // dot + data.NoL = dot(data.N, data.L); + data.NoH = dot(data.N, data.H); + // data.VoH = dot(data.V, data.H); + + data.NoLSat = max(data.NoL, 0.0); + data.NoHSat = max(data.NoH, 0.0); + // data.VoHSat = max(data.VoH, 0.0); +} 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 new file mode 100644 index 0000000000..a34b2330e0 --- /dev/null +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-intermediate-data.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "be2dc7d9-db45-4d0b-957b-aee1cb81bde0", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk b/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk new file mode 100644 index 0000000000..97fdda2eb7 --- /dev/null +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk @@ -0,0 +1,13 @@ +struct LightingResult +{ + // material-dependent lighting data + vec3 diffuseColorWithLighting, specularColorWithLighting; + + // pure lighting + vec3 directDiffuse, directSpecular; + vec3 environmentDiffuse, environmentSpecular; + float shadow, ao; + vec3 lightmapColor; + vec3 emissive; + //vec3 transmittance, scattered; +}; 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 new file mode 100644 index 0000000000..fdcb215751 --- /dev/null +++ b/editor/assets/chunks/lighting-models/data-structures/lighting-result.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "7646cc74-5fcc-47c4-970b-5958505c17e5", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/lighting-models/default-functions.meta b/editor/assets/chunks/lighting-models/default-functions.meta new file mode 100644 index 0000000000..5648ba8f91 --- /dev/null +++ b/editor/assets/chunks/lighting-models/default-functions.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "77dddf0f-b81c-4797-9222-905cbea8dcd5", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/lighting-models/default-functions/simple-skin.chunk b/editor/assets/chunks/lighting-models/default-functions/simple-skin.chunk new file mode 100644 index 0000000000..6691d26cdb --- /dev/null +++ b/editor/assets/chunks/lighting-models/default-functions/simple-skin.chunk @@ -0,0 +1,7 @@ +#ifndef CC_SURFACES_LIGHTING_MODIFY_SKIN_DIFFUSE_LIGHTING + vec3 SurfacesLightingModifySkinDiffuseLighting(in LightingIntermediateData lightingData, in float ssssCurvature) + { + // if user do not sample PreIntegratedSSS tex, fallback to default light model + return vec3(lightingData.NoL); + } +#endif 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 new file mode 100644 index 0000000000..2b899695c8 --- /dev/null +++ b/editor/assets/chunks/lighting-models/default-functions/simple-skin.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "9ada82f2-4c4e-433f-8090-e8bfad31fcf2", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/lighting-models/includes.meta b/editor/assets/chunks/lighting-models/includes.meta new file mode 100644 index 0000000000..859cc26b67 --- /dev/null +++ b/editor/assets/chunks/lighting-models/includes.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "30b9fedf-84ec-49a1-be3b-9555317e980e", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/lighting-models/includes/standard.chunk b/editor/assets/chunks/lighting-models/includes/standard.chunk new file mode 100644 index 0000000000..1da559d132 --- /dev/null +++ b/editor/assets/chunks/lighting-models/includes/standard.chunk @@ -0,0 +1,4 @@ +// Lighting-model includes +#include +#include +#include diff --git a/editor/assets/chunks/lighting-models/includes/standard.chunk.meta b/editor/assets/chunks/lighting-models/includes/standard.chunk.meta new file mode 100644 index 0000000000..ad70678752 --- /dev/null +++ b/editor/assets/chunks/lighting-models/includes/standard.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "cc12f5ac-3dcf-4455-aea9-b9be2dd9071e", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/lighting-models/includes/toon.chunk b/editor/assets/chunks/lighting-models/includes/toon.chunk new file mode 100644 index 0000000000..90a13e1dc8 --- /dev/null +++ b/editor/assets/chunks/lighting-models/includes/toon.chunk @@ -0,0 +1,4 @@ +// Lighting-model includes +#include +#include +#include diff --git a/editor/assets/chunks/lighting-models/includes/toon.chunk.meta b/editor/assets/chunks/lighting-models/includes/toon.chunk.meta new file mode 100644 index 0000000000..b8099d0120 --- /dev/null +++ b/editor/assets/chunks/lighting-models/includes/toon.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "2710ad01-b6c3-4048-b5d9-b3b69cec3e94", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/lighting-models/lighting-flow.meta b/editor/assets/chunks/lighting-models/lighting-flow.meta new file mode 100644 index 0000000000..b824a90ede --- /dev/null +++ b/editor/assets/chunks/lighting-models/lighting-flow.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "6fee360e-820e-45a0-81a2-3c4896c0838e", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk new file mode 100644 index 0000000000..a6bf1324e4 --- /dev/null +++ b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk @@ -0,0 +1,107 @@ +#if (CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_FORWARD || CC_FORCE_FORWARD_SHADING) + #if CC_FORWARD_ADD && !CC_ENABLE_CLUSTERED_LIGHT_CULLING + void CCSurfacesLighting(inout LightingResult lightingResult, in SurfacesMaterialData surfaceData, in vec2 shadowBias) + { + vec3 worldPos; + HIGHP_VALUE_FROM_STRUCT_DEFINED(worldPos, surfaceData.worldPos); + + LightingIntermediateData lightingData; + CCSurfacesInitializeLightingIntermediateData(lightingData, surfaceData); + + CCSurfacesLightingInitializeColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData); + + lightingResult.directDiffuse = lightingResult.directSpecular = vec3(0.0); + + int numLights = CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_FORWARD ? LIGHTS_PER_PASS : int(cc_lightDir[0].w); + for (int i = 0; i < LIGHTS_PER_PASS; i++) { + if (i >= numLights) break; + + CCSurfacesLightingCalculateIntermediateData_PerLight(lightingData, surfaceData, cc_lightPos[i].xyz - worldPos); + CCSurfacesLightingCalculateColorWithLighting(lightingResult.diffuseColorWithLighting, lightingResult.specularColorWithLighting, surfaceData, lightingData); + + vec3 diffuseLighting, specularLighting; + CCSurfacesLightingCalculateDirect(diffuseLighting, specularLighting, lightingData, cc_lightColor[i]); + + float shadow = 1.0; + #if CC_RECEIVE_SHADOW + if (cc_lightPos[i].w > 0.0 && cc_lightSizeRangeAngle[i].w > 0.0) { + if (CCSurfacesLightingEnableShadow(lightingData.NoL)) { + vec4 shadowPos = cc_matLightViewProj * vec4(surfaceData.worldPos, 1.0); + shadow = CCSpotShadowFactorBase(shadowPos, worldPos, shadowBias); + } + } + #endif + + #if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_SHADOW) { + shadow = 1.0; + } + #endif + + float distAtt = CCSurfacesLightingCalculateDistanceAttenuation(lightingData, cc_lightSizeRangeAngle[i]); + + float angleAtt = 1.0; + if (cc_lightPos[i].w > 0.0) { + angleAtt = CCSurfacesLightingCalculateAngleAttenuation(lightingData, cc_lightSizeRangeAngle[i], -cc_lightDir[i].xyz); + } + + float multiplier = distAtt * angleAtt * shadow; + + lightingResult.directDiffuse += diffuseLighting * multiplier; + lightingResult.directSpecular += specularLighting * multiplier; + } + } + #else + void CCSurfacesLighting(inout LightingResult lightingResult, in SurfacesMaterialData surfaceData, in vec2 shadowBias) + { + LightingIntermediateData lightingData; + CCSurfacesInitializeLightingIntermediateData(lightingData, surfaceData); + CCSurfacesInitializeLightingResult(lightingResult, surfaceData); + + 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); + } + } + } + #endif + + // apply SSR, local probe & global probe + CCSurfacesLightingCalculateEnvironment(lightingResult, lightingData); + + // 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; + + + + //#todo: cluster related lighting flow + #if CC_ENABLE_CLUSTERED_LIGHT_CULLING + //#include + #endif + } + #endif +#endif 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 new file mode 100644 index 0000000000..19fc3e1827 --- /dev/null +++ b/editor/assets/chunks/lighting-models/lighting-flow/common-flow.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "41c84281-f2e7-43e2-88bd-6ffcaf1daf5a", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/lighting-models/model-functions.meta b/editor/assets/chunks/lighting-models/model-functions.meta new file mode 100644 index 0000000000..d4064e1afa --- /dev/null +++ b/editor/assets/chunks/lighting-models/model-functions.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "78ea1b40-6c4b-4eb4-b91e-b5bbee21f992", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/lighting-models/model-functions/standard.chunk b/editor/assets/chunks/lighting-models/model-functions/standard.chunk new file mode 100644 index 0000000000..a05a4d09bc --- /dev/null +++ b/editor/assets/chunks/lighting-models/model-functions/standard.chunk @@ -0,0 +1,121 @@ +#include +#include + +bool CCSurfacesLightingEnableShadow(in float NoL) +{ + return NoL > 0.0; +} + +float CCSurfacesLightingCalculateDistanceAttenuation(in LightingIntermediateData lightingData, in vec4 lightSizeRangeAngle) +{ + return CalculateDistanceAttenuation(lightingData.distToLightSqr, lightSizeRangeAngle.x, lightSizeRangeAngle.y); +} + +float CCSurfacesLightingCalculateAngleAttenuation(in LightingIntermediateData lightingData, in vec4 lightSizeRangeAngle, in vec3 spotLightDir) +{ + return CalculateAngleAttenuation(spotLightDir, lightingData.L, lightSizeRangeAngle.z); +} + +void CCSurfacesLightingCalculateDirect(out vec3 lightingDiffuse, out vec3 lightingSpecular, in LightingIntermediateData lightingData, in vec4 lightSourceColorAndIntensity) +{ + vec3 irradiance = vec3(lightingData.NoLSat) * lightSourceColorAndIntensity.rgb * lightSourceColorAndIntensity.w; + + lightingDiffuse = irradiance * DiffuseCoefficient_EnergyConservation; + + float roughness = lightingData.specularParam; +#if CC_SURFACES_LIGHTING_ANISOTROPIC + float rT, rB; + GetAnisotropicRoughness(roughness, lightingData.anisotropyShape, rT, rB); + float calcSpec = D_GGXAniso(rT, rB, lightingData.NoHSat, lightingData.H, lightingData.T, lightingData.B); +#else + #if CC_SURFACES_USE_LEGACY_COMPATIBLE_LIGHTING + float calcSpec = (roughness * 0.25 + 0.25) * D_GGXMobile(roughness, lightingData.NoHSat); + #else + float calcSpec = D_GGX(roughness, lightingData.NoHSat); + #endif +#endif + lightingSpecular = irradiance * calcSpec; +} + + +#if CC_SURFACES_LIGHTING_ANISOTROPIC && CC_SURFACES_LIGHTING_ANISOTROPIC_ENVCONVOLUTION_COUNT + vec3 EnvAnisotropicReflection(vec3 R, float roughness, float mipCount, float anisotropyShape, vec3 V, vec3 N, vec3 T, vec3 B) { + R = normalize(R); + float integratedBRDF = 0.0; + vec3 envSpec = vec3(0.0); + // One direction sample count + const int SAMPLE_STEP_COUNT = CC_SURFACES_LIGHTING_ANISOTROPIC_ENVCONVOLUTION_COUNT; + float sampleAngleRange = PI * abs(anisotropyShape); + vec3 anisoDirection = anisotropyShape < 0.0 ? T : B; + vec3 ROnNormalPlane = normalize(R - anisoDirection * dot(R, anisoDirection)); + //ROnTangentPlane = R; //for example: cross-style + vec3 stepOffset = normalize(ROnNormalPlane - N) * (sampleAngleRange / float(SAMPLE_STEP_COUNT * 2)); + + for (int i = -SAMPLE_STEP_COUNT; i <= SAMPLE_STEP_COUNT; ++i) + { + float rT, rB; + GetAnisotropicRoughness(roughness, anisotropyShape, rT, rB); + #if CC_IBL_CONVOLUTED + float coef = abs(float(i)) / float(SAMPLE_STEP_COUNT) * float(SAMPLE_STEP_COUNT); + #else + float coef = pow(abs(float(i)) / float(SAMPLE_STEP_COUNT), 1.3) * float(SAMPLE_STEP_COUNT); + #endif + vec3 H = normalize(N + stepOffset * sign(float(i)) * coef); + vec3 L = reflect(-V, H); + float NoHSat = saturate(dot(N, H)); + float calcSpec = D_GGXAniso(rT, rB, NoHSat, H, T, B); + + envSpec += calcSpec * EnvReflection(L, roughness, mipCount); + integratedBRDF += calcSpec; + } + envSpec /= integratedBRDF; + return envSpec; + } +#endif + + +void CCSurfacesLightingCalculateEnvironment(inout LightingResult lightingResult, in LightingIntermediateData lightingData) +{ + float roughness = lightingData.specularParam; + float fAmb = 0.5 - lightingData.N.y * 0.5; + vec3 ambDiff = mix(cc_ambientSky.rgb, cc_ambientGround.rgb, fAmb); + vec3 envSpec = vec3(0.0); + + #if CC_USE_IBL + #if CC_USE_DIFFUSEMAP + // Diffuse irradiance + vec4 diffuseMap = texture(cc_diffuseMap, lightingData.N); + #if CC_USE_DIFFUSEMAP == IBL_RGBE + ambDiff = unpackRGBE(diffuseMap); + #else + ambDiff = SRGBToLinear(diffuseMap.rgb); + #endif + #endif + + #if CC_SURFACES_LIGHTING_ANISOTROPIC && !CC_SURFACES_LIGHTING_ANISOTROPIC_ENVCONVOLUTION_COUNT + vec3 R = GetAnisotropicReflect(roughness, lightingData.anisotropyShape, lightingData.V, lightingData.N, lightingData.T, lightingData.B); + #else + vec3 R = reflect(-lightingData.V, lightingData.N); + #endif + + #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 + envSpec = EnvReflectionWithMipFiltering(normalize(R), roughness, cc_ambientGround.w, 0.6); + #else + envSpec = EnvReflection(R, roughness, cc_ambientGround.w); + #endif + #endif + #endif + + lightingResult.environmentDiffuse = ambDiff.rgb * cc_ambientSky.w; + lightingResult.environmentSpecular = envSpec * cc_ambientSky.w; +} + +void CCSurfacesLightingCalculateTransmittence(inout LightingResult lightingResult, in LightingIntermediateData lightingData, vec3 shadowPos) +{ + vec3 irradiance = vec3(lightingData.NoLSat);// * lightSourceColorAndIntensity.rgb * lightSourceColorAndIntensity.w; + + vec3 transmittence = irradiance * DiffuseCoefficient_EnergyConservation; +} diff --git a/editor/assets/chunks/lighting-models/model-functions/standard.chunk.meta b/editor/assets/chunks/lighting-models/model-functions/standard.chunk.meta new file mode 100644 index 0000000000..cf93dfd88f --- /dev/null +++ b/editor/assets/chunks/lighting-models/model-functions/standard.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "4c24618b-1e1d-40e4-883a-cd3fd2304233", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/lighting-models/model-functions/toon.chunk b/editor/assets/chunks/lighting-models/model-functions/toon.chunk new file mode 100644 index 0000000000..4e6be6f9c4 --- /dev/null +++ b/editor/assets/chunks/lighting-models/model-functions/toon.chunk @@ -0,0 +1,42 @@ +#include +#include + +bool CCSurfacesLightingEnableShadow(in float NoL) +{ + return NoL > 0.0; +} + +float CCSurfacesLightingCalculateDistanceAttenuation(in LightingIntermediateData lightingData, in vec4 lightSizeRangeAngle) +{ + return CalculateDistanceAttenuation(lightingData.distToLightSqr, lightSizeRangeAngle.x, lightSizeRangeAngle.y); +} + +float CCSurfacesLightingCalculateAngleAttenuation(in LightingIntermediateData lightingData, in vec4 lightSizeRangeAngle, in vec3 spotLightDir) +{ + return CalculateAngleAttenuation(spotLightDir, lightingData.L, lightSizeRangeAngle.z); +} + +void CCSurfacesLightingCalculateDirect(out vec3 lightingDiffuse, out vec3 lightingSpecular, in LightingIntermediateData lightingData, in vec4 lightSourceColorAndIntensity) +{ + vec3 irradiance = lightSourceColorAndIntensity.rgb * lightSourceColorAndIntensity.w; + + lightingDiffuse = irradiance; // no energy conservation + + // punctual lighting is different from dir lighting +#if CC_FORWARD_ADD || CC_ENABLE_CLUSTERED_LIGHT_CULLING + float NL = 0.5 * lightingData.NoL + 0.5; + lightingDiffuse *= NL; +#endif + + float NH = 0.5 * lightingData.NoH + 0.5; + float specularWeight = 1.0 - pow(lightingData.specularParam, 5.0); + float specularMask = step(specularWeight, NH); + lightingSpecular = irradiance * specularMask; +} + +void CCSurfacesLightingCalculateEnvironment(inout LightingResult lightingResult, in LightingIntermediateData lightingData) +{ + lightingResult.environmentDiffuse = vec3(0.0); + lightingResult.environmentSpecular = vec3(0.0); +} + diff --git a/editor/assets/chunks/lighting-models/model-functions/toon.chunk.meta b/editor/assets/chunks/lighting-models/model-functions/toon.chunk.meta new file mode 100644 index 0000000000..afbfaec417 --- /dev/null +++ b/editor/assets/chunks/lighting-models/model-functions/toon.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "9276cd2c-6001-4f89-b024-f53f63628527", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/post-process.meta b/editor/assets/chunks/post-process.meta new file mode 100644 index 0000000000..536c98828e --- /dev/null +++ b/editor/assets/chunks/post-process.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "626374f8-3523-4561-841a-7a0e2396f310", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/anti-aliasing.chunk b/editor/assets/chunks/post-process/anti-aliasing.chunk similarity index 67% rename from editor/assets/chunks/anti-aliasing.chunk rename to editor/assets/chunks/post-process/anti-aliasing.chunk index 2c4e19e737..ae77813954 100644 --- a/editor/assets/chunks/anti-aliasing.chunk +++ b/editor/assets/chunks/post-process/anti-aliasing.chunk @@ -1,5 +1,5 @@ #pragma define-meta ANTIALIAS_TYPE #if ANTIALIAS_TYPE == 1 - #include + #include #endif diff --git a/editor/assets/chunks/anti-aliasing.chunk.meta b/editor/assets/chunks/post-process/anti-aliasing.chunk.meta similarity index 89% rename from editor/assets/chunks/anti-aliasing.chunk.meta rename to editor/assets/chunks/post-process/anti-aliasing.chunk.meta index 0451e74d58..e75d0351e9 100644 --- a/editor/assets/chunks/anti-aliasing.chunk.meta +++ b/editor/assets/chunks/post-process/anti-aliasing.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "60bb7684-4cd7-4d19-96c4-262e12e0b025", diff --git a/editor/assets/chunks/fxaa.chunk b/editor/assets/chunks/post-process/fxaa.chunk similarity index 100% rename from editor/assets/chunks/fxaa.chunk rename to editor/assets/chunks/post-process/fxaa.chunk diff --git a/editor/assets/chunks/fxaa.chunk.meta b/editor/assets/chunks/post-process/fxaa.chunk.meta similarity index 89% rename from editor/assets/chunks/fxaa.chunk.meta rename to editor/assets/chunks/post-process/fxaa.chunk.meta index 8c6675f4bc..c1801612d6 100644 --- a/editor/assets/chunks/fxaa.chunk.meta +++ b/editor/assets/chunks/post-process/fxaa.chunk.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.2", + "ver": "1.0.5", "importer": "effect-header", "imported": true, "uuid": "0afb4a28-945f-48ac-91e5-6f483345f8ab", diff --git a/editor/assets/chunks/shading-entries.meta b/editor/assets/chunks/shading-entries.meta new file mode 100644 index 0000000000..b7e1f7fbbb --- /dev/null +++ b/editor/assets/chunks/shading-entries.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "63ef0c7d-b48e-45d1-91ba-570e61a44c11", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/shading-entries/data-structures.meta b/editor/assets/chunks/shading-entries/data-structures.meta new file mode 100644 index 0000000000..ebc567d20a --- /dev/null +++ b/editor/assets/chunks/shading-entries/data-structures.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "f4c3a799-80ef-49a2-b0d8-b8f35ec3ddfb", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk b/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk new file mode 100644 index 0000000000..2c3ee3915b --- /dev/null +++ b/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk @@ -0,0 +1,58 @@ +#if __VERSION__ < 300 + #pragma define CC_SURFACES_VARING_MODIFIER varying +#else + #pragma define CC_SURFACES_VARING_MODIFIER in +#endif + +#include + +// FS Input +/*struct SurfacesStandardFragmentInput +{ +} +void CCSurfacesGetFragmentInput(out SurfacesStandardFragmentInput fsInput) +{ +} +*/ + +// Use macros instead of structure to avoid structure precision issues +#define FSInput_worldPos v_worldPos +#define FSInput_worldNormal v_normal.xyz +#define FSInput_faceSideSign v_normal.w +#define FSInput_texcoord v_uv + +#if CC_SURFACES_USE_VERTEX_COLOR + #define FSInput_vertexColor v_color +#else + #define FSInput_vertexColor vec4(1.0) // for compatible user-surface functions in other render usage +#endif + +#if CC_SURFACES_USE_TANGENT_SPACE + #define FSInput_worldTangent v_tangent.xyz + #define FSInput_mirrorNormal v_tangent.w +#else + #define FSInput_worldTangent vec3(0.0, 0.0, 0.0) + #define FSInput_mirrorNormal 1.0 +#endif + +#if CC_SURFACES_USE_SECOND_UV && !CC_USE_LIGHTMAP + #define FSInput_texcoord1 v_uv1 +#else + #define FSInput_texcoord1 vec2(0.0, 0.0) +#endif + +#if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #define FSInput_lightMapUV v_luv +#endif + +#if CC_RECEIVE_SHADOW + #define FSInput_shadowBias v_shadowBias +#endif + +#if CC_USE_FOG != CC_FOG_NONE && !CC_USE_ACCURATE_FOG + #define FSInput_fogFactor v_fogFactor +#endif + +#if CC_SURFACES_TRANSFER_LOCAL_POS + #define FSInput_localPos v_localPos +#endif 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 new file mode 100644 index 0000000000..42a257d04c --- /dev/null +++ b/editor/assets/chunks/shading-entries/data-structures/fs-input.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "ec870cfb-9c88-4f70-929a-ae540a33075b", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk b/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk new file mode 100644 index 0000000000..1b90213edf --- /dev/null +++ b/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk @@ -0,0 +1,32 @@ +//VS->PS +CC_SURFACES_VARING_MODIFIER highp vec3 v_worldPos; +CC_SURFACES_VARING_MODIFIER mediump vec4 v_normal; +CC_SURFACES_VARING_MODIFIER vec2 v_uv; + +#if CC_SURFACES_USE_VERTEX_COLOR + CC_SURFACES_VARING_MODIFIER lowp vec4 v_color; +#endif + +#if CC_SURFACES_USE_TANGENT_SPACE + CC_SURFACES_VARING_MODIFIER mediump vec4 v_tangent; +#endif + +#if CC_SURFACES_USE_SECOND_UV && !CC_USE_LIGHTMAP + CC_SURFACES_VARING_MODIFIER mediump vec2 v_uv1; +#endif + +#if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + CC_SURFACES_VARING_MODIFIER mediump vec3 v_luv; +#endif + +#if CC_RECEIVE_SHADOW + CC_SURFACES_VARING_MODIFIER mediump vec2 v_shadowBias; +#endif + +#if CC_USE_FOG != CC_FOG_NONE && !CC_USE_ACCURATE_FOG + CC_SURFACES_VARING_MODIFIER float v_fogFactor; +#endif + +#if CC_SURFACES_TRANSFER_LOCAL_POS + CC_SURFACES_VARING_MODIFIER highp vec4 v_localPos; +#endif 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 new file mode 100644 index 0000000000..0397a96d5e --- /dev/null +++ b/editor/assets/chunks/shading-entries/data-structures/vs-fs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "f3454fd7-28d9-48dd-a761-ebc8e26834ed", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk b/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk new file mode 100644 index 0000000000..65b1736054 --- /dev/null +++ b/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk @@ -0,0 +1,53 @@ +//IA Input +layout(location = 0) in vec3 a_position; +layout(location = 1) in vec3 a_normal; +layout(location = 2) in vec2 a_texCoord; +#if CC_SURFACES_USE_TANGENT_SPACE + layout(location = 3) in vec4 a_tangent; +#endif + +#if CC_SURFACES_USE_VERTEX_COLOR + in vec4 a_color; +#endif + +// Attribute define should depend on system macro, not surface macro +#if CC_SURFACES_USE_SECOND_UV || CC_USE_LIGHTMAP + in vec2 a_texCoord1; +#endif + +#if CC_USE_SKINNING + #if __VERSION__ > 310 + // strictly speaking this should be u16vec4, but due to poor driver support + // somehow it seems we can get better results on many platforms using u32vec4 + layout(location = 4) in u32vec4 a_joints; + #else + #pragma format(RGBA16UI) + layout(location = 4) in vec4 a_joints; + #endif + + layout(location = 5) in vec4 a_weights; +#endif + +#if USE_INSTANCING + #if CC_USE_BAKED_ANIMATION + in highp vec4 a_jointAnimInfo; // frameID, totalJoints, offset + #endif + in vec4 a_matWorld0; + in vec4 a_matWorld1; + in vec4 a_matWorld2; + #if CC_USE_LIGHTMAP + in vec4 a_lightingMapUVParam; + #endif + #if CC_RECEIVE_SHADOW + in vec2 a_localShadowBias; // x:shadow bias, y:shadow normal bias. + #endif +#elif USE_BATCHING + in float a_dyn_batch_id; +#endif + + +#if CC_USE_MORPH + #if __VERSION__ < 450 + in float a_vertexId; + #endif +#endif 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 new file mode 100644 index 0000000000..05258f96b8 --- /dev/null +++ b/editor/assets/chunks/shading-entries/data-structures/vs-input.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "65084d4a-ae7c-4ca9-8448-f4cd405144b7", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk b/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk new file mode 100644 index 0000000000..670b219b16 --- /dev/null +++ b/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk @@ -0,0 +1,53 @@ +struct SurfacesStandardVertexIntermediate +{ + //local space + highp vec4 position; + vec3 normal; +#if CC_SURFACES_USE_TANGENT_SPACE + vec4 tangent; +#endif + + //other data +#if CC_SURFACES_USE_VERTEX_COLOR + vec4 color; +#endif + + vec2 texCoord; +#if CC_SURFACES_USE_SECOND_UV && !CC_USE_LIGHTMAP + vec2 texCoord1; +#endif + + //transformed + highp vec4 clipPos; + highp vec3 worldPos; + vec4 worldNormal; // a: two side sign + #if CC_SURFACES_USE_TANGENT_SPACE + vec3 worldTangent, worldBinormal; + #endif + + //transfered +#if CC_RECEIVE_SHADOW + vec2 shadowBias; +#endif + +#if CC_USE_FOG != CC_FOG_NONE && !CC_USE_ACCURATE_FOG + float fogFactor; +#endif + +#if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + vec3 lightmapUV; +#endif +}; + + +#if CC_USE_MORPH + #if __VERSION__ < 450 + int getVertexId() { + return int(a_vertexId); + } + #else + int getVertexId() { + return gl_VertexIndex; // vulkan convension + } + #endif +#endif 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 new file mode 100644 index 0000000000..e8eca09b32 --- /dev/null +++ b/editor/assets/chunks/shading-entries/data-structures/vs-intermediate.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "45e6b403-a354-48de-a1e1-e59238bd30b1", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk b/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk new file mode 100644 index 0000000000..eb4bdc7ef0 --- /dev/null +++ b/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk @@ -0,0 +1,43 @@ +#if __VERSION__ < 300 + #pragma define CC_SURFACES_VARING_MODIFIER varying +#else + #pragma define CC_SURFACES_VARING_MODIFIER out +#endif + +#include + + +// Output item macros +#define VSOutput_worldPos v_worldPos +#define VSOutput_worldNormal v_normal.xyz +#define VSOutput_faceSideSign v_normal.w +#define VSOutput_texcoord v_uv + +#if CC_SURFACES_USE_VERTEX_COLOR + #define VSOutput_vertexColor v_color +#endif + +#if CC_SURFACES_USE_TANGENT_SPACE + #define VSOutput_worldTangent v_tangent.xyz + #define VSOutput_mirrorNormal v_tangent.w +#endif + +#if CC_SURFACES_USE_SECOND_UV && !CC_USE_LIGHTMAP + #define VSOutput_texcoord1 v_uv1 +#endif + +#if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #define VSOutput_lightMapUV v_luv +#endif + +#if CC_RECEIVE_SHADOW + #define VSOutput_shadowBias v_shadowBias +#endif + +#if CC_USE_FOG != CC_FOG_NONE && !CC_USE_ACCURATE_FOG + #define VSOutput_fogFactor v_fogFactor +#endif + +#if CC_SURFACES_TRANSFER_LOCAL_POS + #define VSOutput_localPos v_localPos +#endif 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 new file mode 100644 index 0000000000..bf692bfc58 --- /dev/null +++ b/editor/assets/chunks/shading-entries/data-structures/vs-output.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "513eb9a6-0193-4ab1-a7da-2ab087936caa", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/shading-entries/main-functions.meta b/editor/assets/chunks/shading-entries/main-functions.meta new file mode 100644 index 0000000000..8beeb23d3a --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "06ae07af-f0bd-4133-acd2-f1f8580f797b", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/shading-entries/main-functions/deferred.meta b/editor/assets/chunks/shading-entries/main-functions/deferred.meta new file mode 100644 index 0000000000..817d1ceccf --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/deferred.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "bf711db6-efd9-4505-b6cb-ab1583165328", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/shading-entries/main-functions/forward.meta b/editor/assets/chunks/shading-entries/main-functions/forward.meta new file mode 100644 index 0000000000..9e44948a56 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/forward.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "7698a66d-0cc2-4602-92b4-ced4196f5554", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/shading-entries/main-functions/misc.meta b/editor/assets/chunks/shading-entries/main-functions/misc.meta new file mode 100644 index 0000000000..004c94499c --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/misc.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "2cf1e156-25bd-4e1c-8cda-d9f14512debf", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-fs.chunk b/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-fs.chunk new file mode 100644 index 0000000000..1917b6c597 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-fs.chunk @@ -0,0 +1,22 @@ +layout(location = 0) out vec4 fragColorX; + +void main () { + // for alpha clip + vec4 color = SurfacesFragmentModifyBaseColorAndTransparency(); + + //#uniformStyle need sync here + + // Color output +#if CC_USE_HDR + #if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC + if (IS_DEBUG_VIEW_COMPOSITE_ENABLE_TONE_MAPPING) + #endif + color.rgb = ACESToneMap(color.rgb); +#endif +#if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC + if (IS_DEBUG_VIEW_COMPOSITE_ENABLE_GAMMA_CORRECTION) +#endif + color.rgb = LinearToSRGB(color.rgb); + + fragColorX = color; +} 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 new file mode 100644 index 0000000000..0af09667a2 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-fs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "1d7d5670-83c4-4dab-acf3-edb7ae758881", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-vs.chunk b/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-vs.chunk new file mode 100644 index 0000000000..afbe0606dd --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-vs.chunk @@ -0,0 +1,4 @@ +#include +#include + +#include 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 new file mode 100644 index 0000000000..1d6a31a520 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/misc/silhouette-edge-vs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "e25e8368-0f16-4322-981e-8b7eebc97afb", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk b/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk new file mode 100644 index 0000000000..ed9e54a4f8 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk @@ -0,0 +1,30 @@ +// default functions +#ifndef CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY +vec4 SurfacesFragmentModifyBaseColorAndTransparency() +{ + return vec4(cc_ambientSky.xyz * cc_ambientSky.w, 1.0); +} +#endif + +// no structure and module functions needed + + +layout(location = 0) out vec4 fragColorX; + +void main() { + vec4 color = SurfacesFragmentModifyBaseColorAndTransparency(); + color.a = 1.0; + + #if CC_USE_HDR + #if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC + if (IS_DEBUG_VIEW_COMPOSITE_ENABLE_TONE_MAPPING) + #endif + color.rgb = ACESToneMap(color.rgb); + #endif + #if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC + if (IS_DEBUG_VIEW_COMPOSITE_ENABLE_GAMMA_CORRECTION) + #endif + color.rgb = LinearToSRGB(color.rgb); + + fragColorX = color; +} 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 new file mode 100644 index 0000000000..ddc4b7b01d --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/misc/sky-fs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "6a27185f-415d-419c-95b0-85337e21eff9", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/shading-entries/main-functions/misc/sky-vs.chunk b/editor/assets/chunks/shading-entries/main-functions/misc/sky-vs.chunk new file mode 100644 index 0000000000..066a40a136 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/misc/sky-vs.chunk @@ -0,0 +1,55 @@ +#include +#include + +vec4 CalcSkyClipPos(vec3 viewDir) +{ + vec4 clipPos; + // Clip Space + mat4 matViewRotOnly = mat4(mat3(cc_matView)); + vec4 pos = matViewRotOnly * vec4(viewDir, 1.0); + + // orthographic projection adaptation + if (cc_matProj[3].w > 0.0) { + mat4 matProj = cc_matProj; + // default ortho height 10 approximate to default FOV 45 + // stretch x by 2 to remedy perspective effect + // w = sin(45/2), h = 2 * w, _11 = 2 / w, _22 = 2 / h + matProj[0].x = 5.2; + matProj[1].y = 2.6; + matProj[2].zw = vec2(-1.0); + matProj[3].zw = vec2(0.0); + // position is modified inside branches to work around a vk driver bug seen in + // low-end Qualcomm devices (Adreno 512, Oppo R11, cocos-creator/3d-tasks#9236) + clipPos = matProj * pos; + } + else { + clipPos = cc_matProj * pos; + } + + clipPos.z = 0.99999 * clipPos.w; + return clipPos; +} + +void main() +{ + SurfacesStandardVertexIntermediate In; + + // Local Space + CCSurfacesVertexInput(In); + + // cc_matWorld is undefined, so can not use mat4(mat3(cc_matWorld)) + In.worldPos = In.position.xyz; + In.worldPos = SurfacesVertexModifyWorldPos(In); + + In.clipPos = CalcSkyClipPos(In.position.xyz); + + In.worldNormal.w = 1.0; + In.worldNormal.xyz = normalize(In.position.xyz); + + // Other Data +#if CC_USE_FOG != CC_FOG_NONE && !CC_USE_ACCURATE_FOG + In.fogFactor = 0.0; +#endif + + CCSurfacesVertexOutput(In); +} 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 new file mode 100644 index 0000000000..ff1eeaeabb --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/misc/sky-vs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "070d960d-b2b5-437c-99da-0aeb502f7273", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-scene.meta new file mode 100644 index 0000000000..2fdbbcc211 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "3178c6da-bf26-4546-b3f2-a4d0dddd82aa", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk new file mode 100644 index 0000000000..74abf06c26 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk @@ -0,0 +1,5 @@ +#if (CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_FORWARD || CC_FORCE_FORWARD_SHADING) + #include +#elif CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_DEFERRED + #include +#endif 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 new file mode 100644 index 0000000000..416f4df722 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/fs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "52b875e1-87c0-4dc5-a3f7-ce32cb4d93c6", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline.meta new file mode 100644 index 0000000000..a4b519d6a2 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "adef72f1-d7cf-4519-b83c-6fd861d8c703", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/deferred-fs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/deferred-fs.chunk new file mode 100644 index 0000000000..75e7e1c512 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/deferred-fs.chunk @@ -0,0 +1,13 @@ + layout(location = 0) out vec4 fragColor0; + layout(location = 1) out vec4 fragColor1; + layout(location = 2) out vec4 fragColor2; + + void main () { + // Surface + SurfacesMaterialData surfaceData; + CCSurfacesFragmentGetMaterialData(surfaceData); + + fragColor0 = CCSurfacesDeferredOutput0(surfaceData); + fragColor1 = CCSurfacesDeferredOutput1(surfaceData); + fragColor2 = CCSurfacesDeferredOutput2(surfaceData); + } 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 new file mode 100644 index 0000000000..282eca1aa7 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/deferred-fs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "1101cf65-cc90-486b-b6a5-29ae060e01c7", + "files": [], + "subMetas": {}, + "userData": {} +} 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 new file mode 100644 index 0000000000..9776b74e4b --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk @@ -0,0 +1,135 @@ +layout(location = 0) out vec4 fragColorX; + +void main() { +#if CC_DISABLE_STRUCTURE_IN_FRAGMENT_SHADER + float NoL = dot(-cc_mainLitDir.xyz, FSInput_worldNormal.xyz); //trigger ubo binding + vec4 color = SurfacesFragmentModifyBaseColorAndTransparency(); +#else + // Surface + SurfacesMaterialData surfaceData; + CCSurfacesFragmentGetMaterialData(surfaceData); + + // Shadow parameters + vec2 shadowBias = vec2(0.0); + vec3 colDebugCSMLayer = vec3(1.0); + #if CC_RECEIVE_SHADOW + shadowBias = FSInput_shadowBias; + #if !CC_FORWARD_ADD + #if CC_USE_DEBUG_VIEW && CC_SURFACES_ENABLE_DEBUG_VIEW + if (IS_DEBUG_VIEW_MISC_ENABLE_CSM_LAYER_COLORATION) + { + vec4 csmPos; + vec4 shadowProjDepthInfo, shadowProjInfo; + mat4 matLightView; + int csmLayer = CCGetCSMLevel(csmPos, shadowProjDepthInfo, shadowProjInfo, matLightView[0], matLightView[1], matLightView[2], matLightView[3], surfaceData.worldPos); + bool OutOfRange = csmLayer < 0; + if (OutOfRange) + colDebugCSMLayer = vec3(1.0); + else if (csmLayer == 0) + colDebugCSMLayer = vec3(1.0, 0.0, 0.0); + else if (csmLayer == 1) + colDebugCSMLayer = vec3(0.0, 1.0, 0.0); + else if (csmLayer == 2) + colDebugCSMLayer = vec3(0.0, 0.0, 1.0); + else if (csmLayer == 3) + colDebugCSMLayer = vec3(0.0, 1.0, 1.0); + } + #endif + #endif + #endif + + + // Fog factor + #if !CC_FORWARD_ADD + float fogFactor = 1.0; + #if CC_USE_FOG != CC_FOG_NONE + #if !CC_USE_ACCURATE_FOG + fogFactor = FSInput_fogFactor; + #else + CC_TRANSFER_FOG_BASE(vec4(FSInput_worldPos, 1.0), fogFactor); + #endif + #endif + + #if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC && CC_SURFACES_ENABLE_DEBUG_VIEW + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_FOG) { + fogFactor = 1.0; + } + #endif + #endif + + + // Lighting + LightingResult lightingResult; + CCSurfacesLighting(lightingResult, surfaceData, shadowBias); + + + // Debug view + #if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_SINGLE && CC_SURFACES_ENABLE_DEBUG_VIEW + vec4 debugColor = vec4(0.0, 0.0, 0.0, 1.0); + #if !CC_FORWARD_ADD + CCSurfacesDebugViewMeshData(debugColor); + CCSurfacesDebugViewSurfaceData(debugColor, surfaceData); + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_FOG)) + { + fogFactor = 1.0 - fogFactor; + debugColor = vec4(fogFactor, fogFactor, fogFactor, 1.0); + } + #endif + + // only base pass or direct lighting is enabled in add pass + #if CC_FORWARD_ADD + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_DIFFUSE) || IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_SPECULAR) || IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_ALL)) + #endif + { + if (CCSurfacesDebugViewLightingResult(debugColor, lightingResult)) + { + // lighting needs color space conversion + #if CC_USE_HDR + if (IS_DEBUG_VIEW_COMPOSITE_ENABLE_TONE_MAPPING) + debugColor.rgb = ACESToneMap(debugColor.rgb); + #endif + if (IS_DEBUG_VIEW_COMPOSITE_ENABLE_GAMMA_CORRECTION) + debugColor.rgb = LinearToSRGB(debugColor.rgb); + } + } + + fragColorX = debugColor; + return; + + #elif CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC && CC_SURFACES_ENABLE_DEBUG_VIEW + CCSurfacesDebugViewCompositeLightingResult(lightingResult); + #endif + + + // Shading + vec4 color = CCSurfacesShading(surfaceData, lightingResult); + + #if !CC_FORWARD_ADD + CC_APPLY_FOG_BASE(color, fogFactor); + #endif + + // CSM Debug + #if CC_USE_DEBUG_VIEW && CC_SURFACES_ENABLE_DEBUG_VIEW + if (IS_DEBUG_VIEW_MISC_ENABLE_CSM_LAYER_COLORATION) { + color.rgb *= colDebugCSMLayer.rgb; + } + #endif +#endif + + // Color output + #if CC_USE_HDR + #if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC && CC_SURFACES_ENABLE_DEBUG_VIEW + if (IS_DEBUG_VIEW_COMPOSITE_ENABLE_TONE_MAPPING) + #endif + color.rgb = ACESToneMap(color.rgb); + #endif + #if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC + if (IS_DEBUG_VIEW_COMPOSITE_ENABLE_GAMMA_CORRECTION) + #endif + color.rgb = LinearToSRGB(color.rgb); + + + CCSurfacesDebugDisplayInvalidNumber(color); + + fragColorX = color; +} 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 new file mode 100644 index 0000000000..01e57b893a --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "349a2be0-c8d3-420c-9dd1-bf86e01a7055", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk new file mode 100644 index 0000000000..6d9239e75d --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk @@ -0,0 +1,32 @@ +void main() +{ + SurfacesStandardVertexIntermediate In; + + // Local Space + CCSurfacesVertexInput(In); + CCSurfacesVertexAnimation(In); + In.position.xyz = SurfacesVertexModifyLocalPos(In); + + // World Space + CCSurfacesVertexWorldTransform(In); + In.worldPos = SurfacesVertexModifyWorldPos(In); + + // Clip Space + In.clipPos = cc_matProj * cc_matView * vec4(In.worldPos, 1.0); + In.clipPos = SurfacesVertexModifyClipPos(In); + + // Other Surfaces Function + SurfacesVertexModifyUV(In); + + vec3 viewDirect = normalize(cc_cameraPos.xyz - In.worldPos); + In.worldNormal.w = dot(In.worldNormal.xyz, viewDirect) < 0.0 ? -1.0 : 1.0; + In.worldNormal.xyz = SurfacesVertexModifyWorldNormal(In); + + // Other Data + CCSurfacesVertexTransformUV(In); + CCSurfacesVertexTransferFog(In); + CCSurfacesVertexTransferShadow(In); + CCSurfacesVertexTransferLightMapUV(In); + + CCSurfacesVertexOutput(In); +} 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 new file mode 100644 index 0000000000..cfe1d49566 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/vs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "4306c0df-b6d6-4733-8a45-c85907f94d29", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap.meta b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap.meta new file mode 100644 index 0000000000..91f6878c7c --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "f9762a24-4414-4234-82fd-5c6b37f1cb51", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} 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 new file mode 100644 index 0000000000..33614ecd79 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk @@ -0,0 +1,23 @@ +in highp vec2 v_clip_depth; + +layout(location = 0) out vec4 fragColorX; + +void main () { + // for alpha clip + SurfacesFragmentModifyBaseColorAndTransparency(); + + highp float clipDepth = v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5; + // spot use linear + if(cc_shadowLPNNInfo.x > EPSILON && cc_shadowLPNNInfo.x < 1.999999) { + // enabled linear depth + #if CC_SHADOWMAP_USE_LINEAR_DEPTH + clipDepth = CCGetLinearDepth(FSInput_worldPos.xyz); + #endif + } + + #if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8 + fragColorX = packDepthToRGBA(clipDepth); + #else + fragColorX = vec4(clipDepth, 1.0, 1.0, 1.0); + #endif +} 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 new file mode 100644 index 0000000000..fa25ea61ea --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/fs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "a734c67a-3ce2-4978-bf57-080d1dfbbb43", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk new file mode 100644 index 0000000000..d5dcceaaf2 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk @@ -0,0 +1,33 @@ +#include +#include + +out highp vec2 v_clip_depth; + +void main() +{ + SurfacesStandardVertexIntermediate In; + + // Local Space + CCSurfacesVertexInput(In); + CCSurfacesVertexAnimation(In); + In.position.xyz = SurfacesVertexModifyLocalPos(In); + + // World Space + CCSurfacesVertexWorldTransform(In); + In.worldPos = SurfacesVertexModifyWorldPos(In); + + // Clip Space + In.clipPos = cc_matLightViewProj * vec4(In.worldPos, 1.0); + In.clipPos = SurfacesVertexModifyClipPos(In); + + // Other Surfaces Function + SurfacesVertexModifyUV(In); + + // Other Data + CCSurfacesVertexTransformUV(In); + + CCSurfacesVertexOutput(In); + + // Depth + v_clip_depth = In.clipPos.zw; +} 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 new file mode 100644 index 0000000000..942f03f737 --- /dev/null +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-shadowmap/vs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "7a668e36-d75e-488d-b47a-52591e07151d", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/skinning-dqs.chunk.meta b/editor/assets/chunks/skinning-dqs.chunk.meta deleted file mode 100644 index 344e7a5a86..0000000000 --- a/editor/assets/chunks/skinning-dqs.chunk.meta +++ /dev/null @@ -1,9 +0,0 @@ -{ - "ver": "1.0.2", - "importer": "effect-header", - "imported": true, - "uuid": "207a9764-f20a-4e41-997d-cadd0cdb65fd", - "files": [], - "subMetas": {}, - "userData": {} -} diff --git a/editor/assets/chunks/skinning-lbs.chunk.meta b/editor/assets/chunks/skinning-lbs.chunk.meta deleted file mode 100644 index 35dc6382e9..0000000000 --- a/editor/assets/chunks/skinning-lbs.chunk.meta +++ /dev/null @@ -1,9 +0,0 @@ -{ - "ver": "1.0.2", - "importer": "effect-header", - "imported": true, - "uuid": "d875d091-0140-4a00-9517-6810755d394d", - "files": [], - "subMetas": {}, - "userData": {} -} diff --git a/editor/assets/chunks/surfaces.meta b/editor/assets/chunks/surfaces.meta new file mode 100644 index 0000000000..c40fdf128b --- /dev/null +++ b/editor/assets/chunks/surfaces.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "a72601dc-aa97-42b1-b08b-89baead303e5", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/surfaces/data-structures.meta b/editor/assets/chunks/surfaces/data-structures.meta new file mode 100644 index 0000000000..afad70e182 --- /dev/null +++ b/editor/assets/chunks/surfaces/data-structures.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "d1b7b36d-4023-435d-9223-6ed39e86dbfb", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/surfaces/data-structures/standard.chunk b/editor/assets/chunks/surfaces/data-structures/standard.chunk new file mode 100644 index 0000000000..62711411f6 --- /dev/null +++ b/editor/assets/chunks/surfaces/data-structures/standard.chunk @@ -0,0 +1,21 @@ +struct SurfacesMaterialData +{ + HIGHP_VALUE_STRUCT_DEFINE(vec3, worldPos); + + vec4 baseColor; + vec3 worldNormal; + vec3 emissive; + + float specularIntensity; + float roughness; + float metallic; + float ao; + + // for advanced PBR + vec3 worldTangent, worldBinormal; +#if CC_SURFACES_LIGHTING_ANISOTROPIC + float anisotropyShape; +#endif + // float transmittanceFactor; + // float sssCurvature; +}; diff --git a/editor/assets/chunks/surfaces/data-structures/standard.chunk.meta b/editor/assets/chunks/surfaces/data-structures/standard.chunk.meta new file mode 100644 index 0000000000..4c83acc676 --- /dev/null +++ b/editor/assets/chunks/surfaces/data-structures/standard.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "29b8aed8-f4da-471e-a036-4fffc28868f3", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/data-structures/toon.chunk b/editor/assets/chunks/surfaces/data-structures/toon.chunk new file mode 100644 index 0000000000..0fe329c835 --- /dev/null +++ b/editor/assets/chunks/surfaces/data-structures/toon.chunk @@ -0,0 +1,17 @@ +struct SurfacesMaterialData +{ + HIGHP_VALUE_STRUCT_DEFINE(vec3, worldPos); + + vec4 baseColor; + vec4 specular; + vec3 worldNormal; + vec3 emissive; + + vec3 shade1; + vec3 shade2; + float baseStep; + float baseFeather; + float shadeStep; + float shadeFeather; + float shadowCover; +}; diff --git a/editor/assets/chunks/surfaces/data-structures/toon.chunk.meta b/editor/assets/chunks/surfaces/data-structures/toon.chunk.meta new file mode 100644 index 0000000000..4940e02b61 --- /dev/null +++ b/editor/assets/chunks/surfaces/data-structures/toon.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "7ac0dc35-81bc-4b7c-9701-a401747deccf", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/default-functions.meta b/editor/assets/chunks/surfaces/default-functions.meta new file mode 100644 index 0000000000..91a74700e7 --- /dev/null +++ b/editor/assets/chunks/surfaces/default-functions.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "eaa476cb-d357-463b-ae54-9807cb10e791", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/surfaces/default-functions/common-vs.chunk b/editor/assets/chunks/surfaces/default-functions/common-vs.chunk new file mode 100644 index 0000000000..b6252172ac --- /dev/null +++ b/editor/assets/chunks/surfaces/default-functions/common-vs.chunk @@ -0,0 +1,41 @@ +#ifndef CC_SURFACES_VERTEX_MODIFY_LOCAL_POS +vec3 SurfacesVertexModifyLocalPos(in SurfacesStandardVertexIntermediate In) +{ + return In.position.xyz; +} +#endif + +#ifndef CC_SURFACES_VERTEX_MODIFY_WORLD_POS +vec3 SurfacesVertexModifyWorldPos(in SurfacesStandardVertexIntermediate In) +{ + return In.worldPos; +} +#endif + +#ifndef CC_SURFACES_VERTEX_MODIFY_CLIP_POS +vec4 SurfacesVertexModifyClipPos(in SurfacesStandardVertexIntermediate In) +{ + return In.clipPos; +} +#endif + +#ifndef CC_SURFACES_VERTEX_MODIFY_UV +void SurfacesVertexModifyUV(inout SurfacesStandardVertexIntermediate In) +{ + In.texCoord = In.texCoord; +#if CC_SURFACES_USE_SECOND_UV && !CC_USE_LIGHTMAP + In.texCoord1 = In.texCoord1; +#endif +} +#endif + +#ifndef CC_SURFACES_VERTEX_MODIFY_WORLD_NORMAL +vec3 SurfacesVertexModifyWorldNormal(in SurfacesStandardVertexIntermediate In) +{ + vec3 worldNormal = In.worldNormal.xyz; + #if CC_SURFACES_USE_TWO_SIDED + worldNormal.xyz *= In.worldNormal.w; + #endif + return worldNormal; +} +#endif diff --git a/editor/assets/chunks/surfaces/default-functions/common-vs.chunk.meta b/editor/assets/chunks/surfaces/default-functions/common-vs.chunk.meta new file mode 100644 index 0000000000..68e84b64df --- /dev/null +++ b/editor/assets/chunks/surfaces/default-functions/common-vs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "b3d7cc71-db0a-4f76-a2e1-c145c679180f", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk new file mode 100644 index 0000000000..16ba4c5344 --- /dev/null +++ b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk @@ -0,0 +1,63 @@ +#ifndef CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY +vec4 SurfacesFragmentModifyBaseColorAndTransparency() +{ + return FSInput_vertexColor; +} +#endif + + +#ifndef CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL +vec3 SurfacesFragmentModifyWorldNormal() +{ + return normalize(FSInput_worldNormal); +} +#endif + +#ifndef CC_SURFACES_FRAGMENT_MODIFY_WORLD_TANGENT_AND_BINORMAL +void SurfacesFragmentModifyWorldTangentAndBinormal(inout vec3 worldTangent, inout vec3 worldBinormal, vec3 worldNormal) +{ + vec3 tangent = FSInput_worldTangent; + +#if CC_SURFACES_USE_TANGENT_SPACE + vec3 binormal = normalize(CalculateBinormal(worldNormal.xyz, tangent, FSInput_mirrorNormal)); + tangent = normalize(cross(binormal, worldNormal)); +#else + vec3 binormal = vec3(0.0, 0.0, 0.0); +#endif + + worldTangent = tangent; + worldBinormal = binormal; +} +#endif + +#ifndef CC_SURFACES_FRAGMENT_MODIFY_ANISOTROPY_PARAMS +// rotation, shape, xx, xx +vec4 SurfacesFragmentModifyAnisotropyParams() +{ + return vec4(0.0, 1.0, 0.0, 0.0); +} +#endif + +#ifndef CC_SURFACES_FRAGMENT_MODIFY_EMISSIVE +vec3 SurfacesFragmentModifyEmissive() +{ + return vec3(0.0, 0.0, 0.0); +} +#endif + +#ifndef CC_SURFACES_FRAGMENT_MODIFY_PBRPARAMS +vec4 SurfacesFragmentModifyPBRParams() +{ + // ao, roughness, metallic, specularIntensity + return vec4(1.0, 0.5, 0.0, 0.5); +} +#endif + +// some material datas use shared raw data, avoid sample / calculate same raw data multiply times, use this function for better performance +// this function invokes at last +// should use corresponding shading-model header: #include before function define +#ifndef CC_SURFACES_FRAGMENT_MODIFY_SHARED_DATA +void SurfacesFragmentModifySharedData(inout SurfacesMaterialData surfaceData) +{ +} +#endif diff --git a/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk.meta b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk.meta new file mode 100644 index 0000000000..e2a4ec4208 --- /dev/null +++ b/editor/assets/chunks/surfaces/default-functions/standard-fs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "57b9c877-9855-47c0-bb6f-da3a2c19414e", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/default-functions/toon-fs.chunk b/editor/assets/chunks/surfaces/default-functions/toon-fs.chunk new file mode 100644 index 0000000000..d37ff7a50d --- /dev/null +++ b/editor/assets/chunks/surfaces/default-functions/toon-fs.chunk @@ -0,0 +1,30 @@ +#include + +#ifndef CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TOONSHADE +void SurfacesFragmentModifyBaseColorAndToonShade(out vec4 baseColorAndTransparency, out vec3 shade1, out vec3 shade2, in vec3 baseColor) +{ + baseColorAndTransparency = FSInput_vertexColor; + shade1 = shade2 = vec3(0.0); +} +#endif + +#ifndef CC_SURFACES_FRAGMENT_MODIFY_TOON_STEP_AND_FEATHER +vec4 SurfacesFragmentModifyToonStepAndFeather() +{ + return vec3(0.8, 0.001, 0.5, 0.001); +} +#endif + +#ifndef CC_SURFACES_FRAGMENT_MODIFY_TOON_SHADOW_COVER +float SurfacesFragmentModifyToonShadowCover() +{ + return 0.5; +} +#endif + +#ifndef CC_SURFACES_FRAGMENT_MODIFY_TOON_SPECULAR +vec4 SurfacesFragmentModifyToonSpecular() +{ + return vec4(1.0, 1.0, 1.0, 0.3); +} +#endif diff --git a/editor/assets/chunks/surfaces/default-functions/toon-fs.chunk.meta b/editor/assets/chunks/surfaces/default-functions/toon-fs.chunk.meta new file mode 100644 index 0000000000..bf7c495dba --- /dev/null +++ b/editor/assets/chunks/surfaces/default-functions/toon-fs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "3804c73c-5c8d-42cf-8382-6b64ab2ea7bc", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/effect-macros.meta b/editor/assets/chunks/surfaces/effect-macros.meta new file mode 100644 index 0000000000..71beccfb44 --- /dev/null +++ b/editor/assets/chunks/surfaces/effect-macros.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "af5687e7-3bb4-438a-b00e-037a68d72478", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk new file mode 100644 index 0000000000..e75589ce87 --- /dev/null +++ b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk @@ -0,0 +1,58 @@ +// Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + +#pragma define-meta USE_INSTANCING editor(elevated: true) +#pragma define-meta USE_BATCHING editor(elevated: true) +// these two macros must be non-const +// use #pragma define to rename a macro with editor flag +//#pragma define CC_SURFACES_USE_INSTANCING USE_INSTANCING +//#pragma define CC_SURFACES_USE_BATCHING USE_BATCHING + + + +// all material->internal macros +// varying-dependent macros +#ifndef CC_SURFACES_USE_SECOND_UV + #define CC_SURFACES_USE_SECOND_UV 0 +#endif +#ifndef CC_SURFACES_USE_TANGENT_SPACE + #define CC_SURFACES_USE_TANGENT_SPACE 0 +#endif +#ifndef CC_SURFACES_USE_VERTEX_COLOR + #define CC_SURFACES_USE_VERTEX_COLOR 0 +#endif +#ifndef CC_SURFACES_TRANSFER_LOCAL_POS + #define CC_SURFACES_TRANSFER_LOCAL_POS 0 +#endif + +// Can force CC_SURFACES_USE_LIGHT_MAP to 0, can not force to 1 +#if CC_USE_LIGHTMAP + #ifndef CC_SURFACES_USE_LIGHT_MAP + #define CC_SURFACES_USE_LIGHT_MAP 1 + #endif +#else + #ifndef CC_SURFACES_USE_LIGHT_MAP + #define CC_SURFACES_USE_LIGHT_MAP 0 + #endif +#endif + +// varying-undependent macros +#ifndef CC_SURFACES_USE_TWO_SIDED + #define CC_SURFACES_USE_TWO_SIDED 0 +#endif +#ifndef CC_SURFACES_USE_REFLECTION_DENOISE + #define CC_SURFACES_USE_REFLECTION_DENOISE 0 +#endif +#ifndef CC_SURFACES_LIGHTING_ANISOTROPIC + #define CC_SURFACES_LIGHTING_ANISOTROPIC 0 +#endif +#ifndef CC_SURFACES_LIGHTING_ANISOTROPIC_ENVCONVOLUTION_COUNT + #define CC_SURFACES_LIGHTING_ANISOTROPIC_ENVCONVOLUTION_COUNT 0 +#endif +#ifndef CC_SURFACES_USE_LEGACY_COMPATIBLE_LIGHTING + #define CC_SURFACES_USE_LEGACY_COMPATIBLE_LIGHTING 0 +#endif + +// render-to-color-map can disable functionality to avoid error data map +#ifndef CC_SURFACES_ENABLE_DEBUG_VIEW + #define CC_SURFACES_ENABLE_DEBUG_VIEW 1 +#endif diff --git a/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk.meta new file mode 100644 index 0000000000..5fb3edc435 --- /dev/null +++ b/editor/assets/chunks/surfaces/effect-macros/common-macros.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "5fb14bc4-12ef-4b8f-b2d2-e0a7df233e31", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/effect-macros/render-to-shadowmap.chunk b/editor/assets/chunks/surfaces/effect-macros/render-to-shadowmap.chunk new file mode 100644 index 0000000000..ecf87e3a2d --- /dev/null +++ b/editor/assets/chunks/surfaces/effect-macros/render-to-shadowmap.chunk @@ -0,0 +1,11 @@ +// Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + +// Rename some user macros to surface internal macros + +#define CC_SURFACES_USE_TANGENT_SPACE 0 +#define CC_SURFACES_USE_VERTEX_COLOR 0 +#define CC_SURFACES_USE_SECOND_UV 0 +#define CC_SURFACES_USE_LIGHT_MAP 0 +#define CC_SURFACES_TRANSFER_LOCAL_POS 0 + +#include 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 new file mode 100644 index 0000000000..2f27574999 --- /dev/null +++ b/editor/assets/chunks/surfaces/effect-macros/render-to-shadowmap.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "f66020b7-1a8a-424a-abf4-a8cbe80e410f", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/effect-macros/silhouette-edge.chunk b/editor/assets/chunks/surfaces/effect-macros/silhouette-edge.chunk new file mode 100644 index 0000000000..ecf87e3a2d --- /dev/null +++ b/editor/assets/chunks/surfaces/effect-macros/silhouette-edge.chunk @@ -0,0 +1,11 @@ +// Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + +// Rename some user macros to surface internal macros + +#define CC_SURFACES_USE_TANGENT_SPACE 0 +#define CC_SURFACES_USE_VERTEX_COLOR 0 +#define CC_SURFACES_USE_SECOND_UV 0 +#define CC_SURFACES_USE_LIGHT_MAP 0 +#define CC_SURFACES_TRANSFER_LOCAL_POS 0 + +#include diff --git a/editor/assets/chunks/surfaces/effect-macros/silhouette-edge.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/silhouette-edge.chunk.meta new file mode 100644 index 0000000000..3886390638 --- /dev/null +++ b/editor/assets/chunks/surfaces/effect-macros/silhouette-edge.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "2f746ff4-a6d3-41ec-bcd7-52c8283f3a57", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/effect-macros/sky.chunk b/editor/assets/chunks/surfaces/effect-macros/sky.chunk new file mode 100644 index 0000000000..1f6d3ef76b --- /dev/null +++ b/editor/assets/chunks/surfaces/effect-macros/sky.chunk @@ -0,0 +1,11 @@ +// Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + +#pragma define USE_INSTANCING 0 +#pragma define USE_BATCHING 0 + +// Disable unused functionality and varying data +#define CC_SURFACES_USE_TANGENT_SPACE 0 +#define CC_SURFACES_USE_VERTEX_COLOR 0 +#define CC_SURFACES_USE_SECOND_UV 0 +#define CC_SURFACES_USE_LIGHT_MAP 0 +#define CC_SURFACES_TRANSFER_LOCAL_POS 0 diff --git a/editor/assets/chunks/surfaces/effect-macros/sky.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/sky.chunk.meta new file mode 100644 index 0000000000..48e61c6e3f --- /dev/null +++ b/editor/assets/chunks/surfaces/effect-macros/sky.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "dc6e17a4-b3b4-4316-8f1e-c925b6fab67c", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/effect-macros/terrain.chunk b/editor/assets/chunks/surfaces/effect-macros/terrain.chunk new file mode 100644 index 0000000000..f2f988a30c --- /dev/null +++ b/editor/assets/chunks/surfaces/effect-macros/terrain.chunk @@ -0,0 +1,23 @@ +// Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + +// Rename some user macros to surface internal macros + +#pragma define-meta USE_NORMAL_MAP +#define CC_SURFACES_USE_TANGENT_SPACE USE_NORMAL_MAP + +#define CC_SURFACES_USE_VERTEX_COLOR 0 +#define CC_SURFACES_USE_SECOND_UV 0 +#define CC_SURFACES_USE_TWO_SIDED 0 + +#define CC_SURFACES_USE_LIGHT_MAP CC_USE_LIGHTMAP + +// vs-fs varing addon data +#define CC_SURFACES_TRANSFER_LOCAL_POS 1 + +#if USE_REFLECTION_DENOISE + #define CC_SURFACES_USE_REFLECTION_DENOISE USE_REFLECTION_DENOISE +#else + #define CC_SURFACES_USE_REFLECTION_DENOISE 0 +#endif + +#include diff --git a/editor/assets/chunks/surfaces/effect-macros/terrain.chunk.meta b/editor/assets/chunks/surfaces/effect-macros/terrain.chunk.meta new file mode 100644 index 0000000000..1511825d54 --- /dev/null +++ b/editor/assets/chunks/surfaces/effect-macros/terrain.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "1de87047-07ab-491a-b418-588ff145eaec", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/includes.meta b/editor/assets/chunks/surfaces/includes.meta new file mode 100644 index 0000000000..a5ec2fdb8c --- /dev/null +++ b/editor/assets/chunks/surfaces/includes.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "7e22c0d7-a9df-4194-bdac-acddb43f365b", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/surfaces/includes/common-fs.chunk b/editor/assets/chunks/surfaces/includes/common-fs.chunk new file mode 100644 index 0000000000..59b8fe2a88 --- /dev/null +++ b/editor/assets/chunks/surfaces/includes/common-fs.chunk @@ -0,0 +1,54 @@ +// defines +//#todo: #10131 Redmi5A = 1 +#pragma define-meta CC_DISABLE_STRUCTURE_IN_FRAGMENT_SHADER range([0, 1]) + +#pragma define CC_PIPELINE_TYPE_FORWARD 0 +#pragma define CC_PIPELINE_TYPE_DEFERRED 1 +#pragma define-meta CC_PIPELINE_TYPE range([0, 1]) +#pragma define-meta CC_FORCE_FORWARD_SHADING + +#define CC_USE_SURFACE_SHADER 1 + +// Surface +#include + +// Uniforms--UBO +#include +#include +#if (CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_FORWARD || CC_FORCE_FORWARD_SHADING) + #if CC_FORWARD_ADD + #include + #endif +#endif + +// Uniforms--Tex +#include +#if CC_USE_IBL + #include + #if CC_USE_DIFFUSEMAP + #include + #endif +#endif + +// Base +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// Functional +#include +#include + +// Uniform should depend on system macro, not surface macro +#if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #include + #include +#endif diff --git a/editor/assets/chunks/surfaces/includes/common-fs.chunk.meta b/editor/assets/chunks/surfaces/includes/common-fs.chunk.meta new file mode 100644 index 0000000000..8f7f46821d --- /dev/null +++ b/editor/assets/chunks/surfaces/includes/common-fs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "a6451dbc-fc4c-4a10-84f5-072c6e982fa5", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/includes/common-vs.chunk b/editor/assets/chunks/surfaces/includes/common-vs.chunk new file mode 100644 index 0000000000..d08a6ef3b9 --- /dev/null +++ b/editor/assets/chunks/surfaces/includes/common-vs.chunk @@ -0,0 +1,27 @@ +#define CC_USE_SURFACE_SHADER 1 + +// Surface +#include +#include +#include + +// UBO +#include +#include + +#include + +// Functional +#include + +#if CC_USE_MORPH + #include +#endif + +#if CC_USE_SKINNING + #include +#endif + +#if CC_USE_FOG != CC_FOG_NONE && !CC_USE_ACCURATE_FOG + #include +#endif diff --git a/editor/assets/chunks/surfaces/includes/common-vs.chunk.meta b/editor/assets/chunks/surfaces/includes/common-vs.chunk.meta new file mode 100644 index 0000000000..8961da1726 --- /dev/null +++ b/editor/assets/chunks/surfaces/includes/common-vs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "c66380b2-694f-40bd-afd8-91a2e58d904d", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/includes/standard-fs.chunk b/editor/assets/chunks/surfaces/includes/standard-fs.chunk new file mode 100644 index 0000000000..625767bbb1 --- /dev/null +++ b/editor/assets/chunks/surfaces/includes/standard-fs.chunk @@ -0,0 +1,5 @@ +// Surface includes +#include +#include +#include +#include diff --git a/editor/assets/chunks/surfaces/includes/standard-fs.chunk.meta b/editor/assets/chunks/surfaces/includes/standard-fs.chunk.meta new file mode 100644 index 0000000000..db736e4f9a --- /dev/null +++ b/editor/assets/chunks/surfaces/includes/standard-fs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "0d0afa06-80d6-45b8-9fa6-6f6ad947c00b", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/includes/standard-vs.chunk b/editor/assets/chunks/surfaces/includes/standard-vs.chunk new file mode 100644 index 0000000000..56e839422a --- /dev/null +++ b/editor/assets/chunks/surfaces/includes/standard-vs.chunk @@ -0,0 +1,2 @@ +#include +#include diff --git a/editor/assets/chunks/surfaces/includes/standard-vs.chunk.meta b/editor/assets/chunks/surfaces/includes/standard-vs.chunk.meta new file mode 100644 index 0000000000..ae8aeba766 --- /dev/null +++ b/editor/assets/chunks/surfaces/includes/standard-vs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "698b9da6-3f0e-4113-8b1c-5ebc82e3ab3d", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/includes/toon-fs.chunk b/editor/assets/chunks/surfaces/includes/toon-fs.chunk new file mode 100644 index 0000000000..221f1ce377 --- /dev/null +++ b/editor/assets/chunks/surfaces/includes/toon-fs.chunk @@ -0,0 +1,5 @@ +// Surface includes +#include +#include +#include +#include diff --git a/editor/assets/chunks/surfaces/includes/toon-fs.chunk.meta b/editor/assets/chunks/surfaces/includes/toon-fs.chunk.meta new file mode 100644 index 0000000000..9e64e66c52 --- /dev/null +++ b/editor/assets/chunks/surfaces/includes/toon-fs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "5a2c165c-7d8d-4ed5-9142-52f895dee13c", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/includes/toon-vs.chunk b/editor/assets/chunks/surfaces/includes/toon-vs.chunk new file mode 100644 index 0000000000..56e839422a --- /dev/null +++ b/editor/assets/chunks/surfaces/includes/toon-vs.chunk @@ -0,0 +1,2 @@ +#include +#include diff --git a/editor/assets/chunks/surfaces/includes/toon-vs.chunk.meta b/editor/assets/chunks/surfaces/includes/toon-vs.chunk.meta new file mode 100644 index 0000000000..c8212a7459 --- /dev/null +++ b/editor/assets/chunks/surfaces/includes/toon-vs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "ef0e1f2a-454f-4613-959c-3d9da0cae4f8", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/module-functions.meta b/editor/assets/chunks/surfaces/module-functions.meta new file mode 100644 index 0000000000..666b1c9b85 --- /dev/null +++ b/editor/assets/chunks/surfaces/module-functions.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "e0dda21b-408d-4e5c-a519-71fad239c854", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/chunks/surfaces/module-functions/common-vs.chunk b/editor/assets/chunks/surfaces/module-functions/common-vs.chunk new file mode 100644 index 0000000000..ae45d43473 --- /dev/null +++ b/editor/assets/chunks/surfaces/module-functions/common-vs.chunk @@ -0,0 +1,137 @@ +// IA Input->Intermediate +void CCSurfacesVertexInput(out SurfacesStandardVertexIntermediate In) +{ + In.position = vec4(a_position, 1.0); + In.normal = a_normal; + +#if CC_SURFACES_USE_TANGENT_SPACE + In.tangent = a_tangent; +#endif + +#if CC_SURFACES_USE_VERTEX_COLOR + In.color = a_color; +#endif + + In.texCoord = a_texCoord; +#if CC_SURFACES_USE_SECOND_UV && !CC_USE_LIGHTMAP + In.texCoord1 = a_texCoord1; +#endif +} + +void CCSurfacesVertexOutput(in SurfacesStandardVertexIntermediate In) +{ + gl_Position = In.clipPos; + VSOutput_worldNormal = In.worldNormal.xyz; + VSOutput_faceSideSign = In.worldNormal.w; + VSOutput_worldPos = In.worldPos; + +#if CC_SURFACES_USE_TANGENT_SPACE + VSOutput_worldTangent = In.worldTangent.xyz; + // VSOutput_worldBitangent = In.worldBinormal; + VSOutput_mirrorNormal = In.tangent.w; +#endif + +#if CC_SURFACES_USE_VERTEX_COLOR + VSOutput_vertexColor = In.color; +#endif + + VSOutput_texcoord = In.texCoord; +#if CC_SURFACES_USE_SECOND_UV && !CC_USE_LIGHTMAP + VSOutput_texcoord1 = In.texCoord1; +#endif + +#if CC_USE_FOG != CC_FOG_NONE && !CC_USE_ACCURATE_FOG + VSOutput_fogFactor = In.fogFactor; +#endif + +#if CC_RECEIVE_SHADOW + VSOutput_shadowBias = In.shadowBias; +#endif + +#if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + VSOutput_lightMapUV = In.lightmapUV; +#endif + +#if CC_SURFACES_TRANSFER_LOCAL_POS + VSOutput_localPos = In.position; +#endif +} + +// Morph & Skinning +void CCSurfacesVertexAnimation(inout SurfacesStandardVertexIntermediate In) +{ +vec4 temp = vec4(0.0); +#if CC_USE_MORPH + #if CC_SURFACES_USE_TANGENT_SPACE + applyMorph(In.position, In.normal, In.tangent); + #else + applyMorph(In.position, In.normal, temp); + #endif +#endif + +#if CC_USE_SKINNING + #if CC_SURFACES_USE_TANGENT_SPACE + CCSkin(In.position, In.normal, In.tangent); + #else + CCSkin(In.position, In.normal, temp); + #endif +#endif +} + +// Space Transform +void CCSurfacesVertexWorldTransform(inout SurfacesStandardVertexIntermediate In) +{ + mat4 matWorld, matWorldIT; + CCGetWorldMatrixFull(matWorld, matWorldIT); + + In.worldPos = (matWorld * In.position).xyz; + In.worldNormal.xyz = normalize((matWorldIT * vec4(In.normal.xyz, 0.0)).xyz); + + #if CC_SURFACES_USE_TANGENT_SPACE + In.worldTangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz); + In.worldBinormal = cross(In.worldNormal.xyz, In.worldTangent) * In.tangent.w; // note the cross order + #endif +} + +void CCSurfacesVertexTransformUV(inout SurfacesStandardVertexIntermediate In) +{ + #if SAMPLE_FROM_RT + CC_HANDLE_RT_SAMPLE_FLIP(In.texCoord); + #if CC_SURFACES_USE_SECOND_UV && !CC_USE_LIGHTMAP + CC_HANDLE_RT_SAMPLE_FLIP(In.texCoord1); + #endif + #endif +} + +// Shading +void CCSurfacesVertexTransferFog(inout SurfacesStandardVertexIntermediate In) +{ +#if CC_USE_FOG != CC_FOG_NONE && !CC_USE_ACCURATE_FOG + CC_TRANSFER_FOG_BASE(vec4(In.worldPos, 1.0), In.fogFactor); +#endif +} + +void CCSurfacesVertexTransferShadow(inout SurfacesStandardVertexIntermediate In) +{ + #if CC_RECEIVE_SHADOW + In.shadowBias = vec2(cc_shadowWHPBInfo.w, cc_shadowLPNNInfo.z); + #if USE_INSTANCING + In.shadowBias += a_localShadowBias.xy; + #elif !USE_BATCHING + In.shadowBias += cc_localShadowBias.xy; + #endif + #endif +} + +void CCSurfacesVertexTransferLightMapUV(inout SurfacesStandardVertexIntermediate In) +{ +#if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if USE_INSTANCING + In.lightmapUV.xy = a_lightingMapUVParam.xy + a_texCoord1 * a_lightingMapUVParam.z; + In.lightmapUV.z = a_lightingMapUVParam.w; + #else + In.lightmapUV.xy = cc_lightingMapUVParam.xy + a_texCoord1 * cc_lightingMapUVParam.z; + In.lightmapUV.z = cc_lightingMapUVParam.w; + #endif +#endif +} diff --git a/editor/assets/chunks/surfaces/module-functions/common-vs.chunk.meta b/editor/assets/chunks/surfaces/module-functions/common-vs.chunk.meta new file mode 100644 index 0000000000..a949abc4ad --- /dev/null +++ b/editor/assets/chunks/surfaces/module-functions/common-vs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "e1feba3c-c7a2-4208-9c1f-732b7e46abd4", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/module-functions/debug-view.chunk b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk new file mode 100644 index 0000000000..6454bd2fbe --- /dev/null +++ b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk @@ -0,0 +1,189 @@ +// make divid-by-zero, non-rational pixel more obvious +void CCSurfacesDebugDisplayInvalidNumber(inout vec4 color) +{ + float index = mod(cc_time.x * 10.0, 2.0); + vec4 error = index < 1.0 ? vec4(1.0, 0.0, 0.2, 1.0) : vec4(0.0, 1.0, 0.2, 1.0); + + color = (isnans(color.rgb) || isinfs(color.rgb)) ? error : color; +} + + +#if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_SINGLE && !CC_FORWARD_ADD + void CCSurfacesDebugViewMeshData(out vec4 color) + { + vec4 white = vec4(1.0, 1.0, 1.0, 1.0); + vec4 black = vec4(0.0, 0.0, 0.0, 1.0); + + // vertex input + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_VERTEX_COLOR)) + { + #if CC_SURFACES_USE_VERTEX_COLOR + color = FSInput_vertexColor; + #else + color = white; + #endif + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_VERTEX_NORMAL)) + color = vec4(FSInput_worldNormal * 0.5 + vec3(0.5), 1.0); + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_VERTEX_TANGENT)) + { + #if CC_SURFACES_USE_TANGENT_SPACE + color = vec4(FSInput_worldTangent * 0.5 + vec3(0.5), 1.0); + #else + color = black; + #endif + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_VERTEX_MIRROR)) + { + #if CC_SURFACES_USE_TANGENT_SPACE + float sign = FSInput_mirrorNormal * 0.5 + 0.5; + color = vec4(sign, sign, sign, 1.0); + #else + color = black; + #endif + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_FACE_SIDE)) + { + float scalar = clamp(FSInput_faceSideSign, 0.0, 1.0); + color = vec4(scalar, scalar, scalar, 1.0); + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_UV0)) + color = vec4(FSInput_texcoord.xy, 0.0, 1.0); + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_UV1)) + color = vec4(FSInput_texcoord1.xy, 0.0, 1.0); + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_UVLIGHTMAP)) + { + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + color = vec4(FSInput_lightMapUV.xy, 0.0, 1.0); + #else + color = vec4(0.0, 0.0, 0.0, 1.0); + #endif + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_PROJ_DEPTH)) + { + vec4 clipPos = cc_matProj * cc_matView * vec4(FSInput_worldPos.xyz, 1.0); + float depth = clipPos.z / clipPos.w; + color = vec4(depth, depth, depth, 1.0); + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_LINEAR_DEPTH)) + { + vec4 viewPos = cc_matView * vec4(FSInput_worldPos.xyz, 1.0); + float depth = (-viewPos.z - cc_nearFar.x) / cc_nearFar.y; + color = vec4(depth, depth, depth, 1.0); + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_WORLD_POS)) + color = vec4(FSInput_worldPos.xyz, 1.0); + } +#endif + + + + // Lighting related +#if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_SINGLE + bool CCSurfacesDebugViewLightingResult(out vec4 color, in LightingResult lightingResult) + { + bool isDebugMatched = false; + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_DIFFUSE)) + { + color.rgb = lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting; + isDebugMatched = true; + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_SPECULAR)) + { + color.rgb = lightingResult.directSpecular * lightingResult.specularColorWithLighting; + isDebugMatched = true; + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIRECT_ALL)) + { + color.rgb = lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting + lightingResult.directSpecular * lightingResult.specularColorWithLighting; + isDebugMatched = true; + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_ENV_DIFFUSE)) + { + color.rgb = lightingResult.environmentDiffuse * lightingResult.diffuseColorWithLighting; + isDebugMatched = true; + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_ENV_SPECULAR)) + { + color.rgb = lightingResult.environmentSpecular * lightingResult.specularColorWithLighting; + isDebugMatched = true; + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_ENV_ALL)) + { + color.rgb = lightingResult.environmentDiffuse * lightingResult.diffuseColorWithLighting + lightingResult.environmentSpecular * lightingResult.specularColorWithLighting; + isDebugMatched = true; + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_LIGHT_MAP)) + { + color.rgb = lightingResult.lightmapColor; + isDebugMatched = true; + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_EMISSIVE)) + { + color.rgb = lightingResult.emissive; + isDebugMatched = true; + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_AO)) + { + color.rgb = vec3(lightingResult.ao); + isDebugMatched = true; + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_SHADOW)) + { + color.rgb = vec3(lightingResult.shadow); + isDebugMatched = true; + } + + return isDebugMatched; + } +#endif + + + +#if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC + void CCSurfacesDebugViewCompositeLightingResult(inout LightingResult lightingResult) + { + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_DIRECT_DIFFUSE) + lightingResult.directDiffuse = vec3(0.0); + + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_DIRECT_SPECULAR) + lightingResult.directSpecular = vec3(0.0); + + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_ENV_DIFFUSE) + lightingResult.environmentDiffuse = vec3(0.0); + + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_ENV_SPECULAR) + lightingResult.environmentSpecular = vec3(0.0); + + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_EMISSIVE) + lightingResult.emissive = vec3(0.0); + + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_LIGHT_MAP) + lightingResult.lightmapColor = vec3(0.0); + + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_SHADOW) + lightingResult.shadow = 1.0; + + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_AO) + lightingResult.ao = 1.0; + } +#endif diff --git a/editor/assets/chunks/surfaces/module-functions/debug-view.chunk.meta b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk.meta new file mode 100644 index 0000000000..49ff1d145f --- /dev/null +++ b/editor/assets/chunks/surfaces/module-functions/debug-view.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "30961f82-b8ef-4d3b-a9e5-944bb5e103f1", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk new file mode 100644 index 0000000000..b5917fb879 --- /dev/null +++ b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk @@ -0,0 +1,196 @@ +#include + +// Surface +void CCSurfacesFragmentGetMaterialData(inout SurfacesMaterialData surfaceData) +{ + HIGHP_VALUE_TO_STRUCT_DEFINED(FSInput_worldPos, surfaceData.worldPos); + + surfaceData.baseColor = SurfacesFragmentModifyBaseColorAndTransparency(); + + surfaceData.worldNormal = SurfacesFragmentModifyWorldNormal(); + SurfacesFragmentModifyWorldTangentAndBinormal(surfaceData.worldTangent, surfaceData.worldBinormal, surfaceData.worldNormal); +#if CC_SURFACES_LIGHTING_ANISOTROPIC + vec4 anisotropyParams = SurfacesFragmentModifyAnisotropyParams(); + surfaceData.anisotropyShape = anisotropyParams.y; + RotateTangentAndBinormal(surfaceData.worldTangent, surfaceData.worldBinormal, surfaceData.worldNormal, anisotropyParams.x); +#endif + + surfaceData.emissive = SurfacesFragmentModifyEmissive(); + + vec4 pbr = SurfacesFragmentModifyPBRParams(); + surfaceData.ao = pbr.x; + surfaceData.roughness = pbr.y; + surfaceData.metallic = pbr.z; + surfaceData.specularIntensity = pbr.w; + + SurfacesFragmentModifySharedData(surfaceData); + +#if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_NORMAL_MAP) { + surfaceData.worldNormal = FSInput_worldNormal; + surfaceData.worldTangent = FSInput_worldTangent; + } +#endif + +#if CC_USE_DEBUG_VIEW + if (!IS_DEBUG_VIEW_LIGHTING_ENABLE_WITH_ALBEDO) + surfaceData.baseColor.rgb = vec3(1.0); +#endif +} + +// Intrinsic function, make connection of material data and lighting data +vec3 CCSurfacesGetDiffuseColor(in SurfacesMaterialData surfaceData) +{ + return surfaceData.baseColor.rgb * (1.0 - surfaceData.metallic); +} +vec3 CCSurfacesGetSpecularColor(in SurfacesMaterialData surfaceData) +{ + float F0 = surfaceData.specularIntensity * 0.08; + return mix(vec3(F0), surfaceData.baseColor.rgb, surfaceData.metallic); +} + +// Diffuse/Specular Color with BRDF lighting preparation +void CCSurfacesLightingInitializeColorWithLighting(inout vec3 diffuseColorWithLighting, inout vec3 specularColorWithLighting, in SurfacesMaterialData surfaceData, in LightingIntermediateData lightingData) +{ + diffuseColorWithLighting = CCSurfacesGetDiffuseColor(surfaceData); + // (Intergrated) GF/4Pi use approximate value for both direct lighting and environment lighting + // accuracy value can be calculated in LightingCalculateDirect/Environment instead of IntegratedGFApprox + specularColorWithLighting = IntegratedGFApprox(CCSurfacesGetSpecularColor(surfaceData).xyz, surfaceData.roughness, lightingData.NoVAbsSat); +} +// Update two colors with BRDF which depend on lights (optional) +void CCSurfacesLightingCalculateColorWithLighting(inout vec3 diffuseColorWithLighting, inout vec3 specularColorWithLighting, in SurfacesMaterialData surfaceData, in LightingIntermediateData lightingData) +{ +} + +// Copy material data to lighting data +// such as tangent data for anisotropic materials +void CCSurfacesInitializeLightingIntermediateData(inout LightingIntermediateData lightingData, in SurfacesMaterialData surfaceData) +{ + vec3 worldPos; + HIGHP_VALUE_FROM_STRUCT_DEFINED(worldPos, surfaceData.worldPos); + CCSurfacesLightingGetIntermediateData_PerPixel(lightingData, surfaceData.worldNormal, worldPos, surfaceData.worldTangent, surfaceData.worldBinormal +#if CC_SURFACES_LIGHTING_ANISOTROPIC + , surfaceData.anisotropyShape +#endif + ); + lightingData.specularParam = surfaceData.roughness; +} +void CCSurfacesLightingCalculateIntermediateData_PerLight(inout LightingIntermediateData lightingData, in SurfacesMaterialData surfaceData, vec3 lightDirWithDist) +{ + CCSurfacesLightingGetIntermediateData_PerLight(lightingData, lightDirWithDist); +} + +// Copy material data to lighting results +void CCSurfacesInitializeLightingResult(inout LightingResult lightingResult, in SurfacesMaterialData surfaceData) +{ + lightingResult.ao = surfaceData.ao; + lightingResult.emissive = surfaceData.emissive; +} + + + +#if CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_DEFERRED + vec4 CCSurfacesDeferredOutput0(in SurfacesMaterialData surfaceData) + { + return surfaceData.baseColor; + } + vec4 CCSurfacesDeferredOutput1(in SurfacesMaterialData surfaceData) + { + return vec4(float32x3_to_oct(surfaceData.worldNormal), surfaceData.roughness, surfaceData.metallic); + } + vec4 CCSurfacesDeferredOutput2(in SurfacesMaterialData surfaceData) + { + return vec4(surfaceData.emissive, surfaceData.ao); + } +#endif + + +// Shading +vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult lightingResult) +{ + vec4 color = vec4(0.0, 0.0, 0.0, surfaceData.baseColor.a); +#if CC_FORWARD_ADD + 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 + + lightingResult.directSpecular * lightingResult.specularColorWithLighting) + * lightingResult.shadow; + + color.xyz += ( + lightingResult.environmentDiffuse * lightingResult.diffuseColorWithLighting + + lightingResult.environmentSpecular * lightingResult.specularColorWithLighting) + * lightingResult.ao; + + color.xyz += lightingResult.emissive; +#endif + + return color; +} + + +// Debug view +#if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_SINGLE +void CCSurfacesDebugViewSurfaceData(out vec4 color, in SurfacesMaterialData surfaceData) +{ + vec4 black = vec4(0.0, 0.0, 0.0, 1.0); + float scalar; + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_FRAGMENT_NORMAL)) + color = vec4(surfaceData.worldNormal * 0.5 + vec3(0.5), 1.0); + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_FRAGMENT_TANGENT)) + { + #if CC_SURFACES_USE_TANGENT_SPACE + color = vec4(surfaceData.worldTangent * 0.5 + vec3(0.5), 1.0); + #else + color = black; + #endif + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_FRAGMENT_BINORMAL)) + { + #if CC_SURFACES_USE_TANGENT_SPACE + color = vec4(surfaceData.worldBinormal * 0.5 + vec3(0.5), 1.0); + #else + color = black; + #endif + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_TRANSPARENCY)) { + scalar = surfaceData.baseColor.a; + color = vec4(scalar, scalar, scalar, 1.0); + } + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_BASE_COLOR)) + color = vec4(LinearToSRGB(surfaceData.baseColor.rgb), 1.0); + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIFFUSE_COLOR)) + color = vec4(LinearToSRGB(CCSurfacesGetDiffuseColor(surfaceData)), 1.0); + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_SPECULAR_COLOR)) + color = vec4(LinearToSRGB(CCSurfacesGetSpecularColor(surfaceData)), 1.0); + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_ROUGHNESS)) { + scalar = surfaceData.roughness; + color = vec4(scalar, scalar, scalar, 1.0); + } + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_METALLIC)) { + scalar = surfaceData.metallic; + color = vec4(scalar, scalar, scalar, 1.0); + } + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_SPECULAR_INTENSITY)) { + scalar = surfaceData.specularIntensity; + color = vec4(scalar, scalar, scalar, 1.0); + } +} +#endif + +// lighting flow module-function used by this material +#include diff --git a/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk.meta b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk.meta new file mode 100644 index 0000000000..dcd7687993 --- /dev/null +++ b/editor/assets/chunks/surfaces/module-functions/standard-fs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "6853f548-fd1c-4a96-94f3-ba6981fbefd4", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk b/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk new file mode 100644 index 0000000000..8787fb04b0 --- /dev/null +++ b/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk @@ -0,0 +1,167 @@ +// Surface +void CCSurfacesFragmentGetMaterialData(inout SurfacesMaterialData surfaceData) +{ + HIGHP_VALUE_TO_STRUCT_DEFINED(FSInput_worldPos, surfaceData.worldPos); + + // common + surfaceData.worldNormal = SurfacesFragmentModifyWorldNormal(); + + surfaceData.emissive = SurfacesFragmentModifyEmissive(); + + // toon + SurfacesFragmentModifyBaseColorAndToonShade(surfaceData.baseColor, surfaceData.shade1, surfaceData.shade2); + + surfaceData.specular = SurfacesFragmentModifyToonSpecular(); + surfaceData.shadowCover = SurfacesFragmentModifyToonShadowCover(); + + vec4 shaderParams = SurfacesFragmentModifyToonStepAndFeather(); + surfaceData.baseStep = shadeParams.x; + surfaceData.baseFeather = shadeParams.y; + surfaceData.shadeStep = shadeParams.z; + surfaceData.shadeFeather = shadeParams.w; + + SurfacesFragmentModifySharedData(surfaceData); + + +#if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_COMPOSITE_AND_MISC + if (!IS_DEBUG_VIEW_COMPOSITE_ENABLE_NORMAL_MAP) + surfaceData.worldNormal = FSInput_worldNormal; +#endif + +#if CC_USE_DEBUG_VIEW + if (!IS_DEBUG_VIEW_LIGHTING_ENABLE_WITH_ALBEDO) { + float brightBase = dot(GRAY_VECTOR, surfaceData.baseColor.rgb); + float brightShade1 = dot(GRAY_VECTOR, surfaceData.shade1.rgb); + float brightShade2 = dot(GRAY_VECTOR, surfaceData.shade2.rgb); + surfaceData.baseColor.rgb = vec3(1.0); + surfaceData.shade1.rgb = vec3(brightShade1 / brightBase); + surfaceData.shade2.rgb = vec3(brightShade2 / brightBase); + surfaceData.specular.rgb = vec3(1.0); + } +#endif +} + +// Intrinsic function +vec3 CCSurfacesGetDiffuseColor(in SurfacesMaterialData surfaceData) +{ + return surfaceData.shade1; +} +vec3 CCSurfacesGetSpecularColor(in SurfacesMaterialData surfaceData) +{ + return surfaceData.specular.xyz; +} +void CCSurfacesLightingInitializeColorWithLighting(inout vec3 diffuseColorWithLighting, inout vec3 specularColorWithLighting, in SurfacesMaterialData surfaceData, in LightingIntermediateData lightingData) +{ + specularColorWithLighting = surfaceData.specular.xyz * surfaceData.baseStep; +} +void CCSurfacesLightingCalculateColorWithLighting(inout vec3 diffuseColorWithLighting, inout vec3 specularColorWithLighting, in SurfacesMaterialData surfaceData, in LightingIntermediateData lightingData) +{ + float NL = 0.5 * lightingData.NoL + 0.5; + + vec3 diffuse = mix(surfaceData.shade1, surfaceData.shade2, + clamp(1.0 + (surfaceData.shadeStep - surfaceData.shadeFeather - NL) / surfaceData.shadeFeather, 0.0, 1.0)); + + diffuse = mix(surfaceData.baseColor.rgb, diffuse, + clamp(1.0 + (surfaceData.baseStep - surfaceData.baseFeather - NL) / surfaceData.baseFeather, 0.0, 1.0)); + + diffuseColorWithLighting = diffuse * surfaceData.baseStep; +} + + +// Copy material data to lighting data +// such as tangent data for anisotropic materials +void CCSurfacesInitializeLightingIntermediateData(inout LightingIntermediateData lightingData, in SurfacesMaterialData surfaceData) +{ + vec3 worldPos; + HIGHP_VALUE_FROM_STRUCT_DEFINED(worldPos, surfaceData.worldPos); + CCSurfacesLightingGetIntermediateData_PerPixel(lightingData, surfaceData.worldNormal, worldPos, vec3(0.0), vec3(0.0)); + lightingData.specularParam = surfaceData.specular.a; +} +void CCSurfacesLightingCalculateIntermediateData_PerLight(inout LightingIntermediateData lightingData, in SurfacesMaterialData surfaceData, vec3 lightDirWithDist) +{ + CCSurfacesLightingGetIntermediateData_PerLight(lightingData, lightDirWithDist); +} + +// Copy material data to lighting results +void CCSurfacesInitializeLightingResult(inout LightingResult lightingResult, in SurfacesMaterialData surfaceData) +{ + lightingResult.emissive = surfaceData.emissive; +} + +// Lighting +#if CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_DEFERRED + vec4 CCSurfacesDeferredOutput0(in SurfacesMaterialData surfaceData) + { + return surfaceData.baseColor; + } + vec4 CCSurfacesDeferredOutput1(in SurfacesMaterialData surfaceData) + { + return vec4(float32x3_to_oct(surfaceData.worldNormal), 0.5, 0.0); + } + vec4 CCSurfacesDeferredOutput2(in SurfacesMaterialData surfaceData) + { + return vec4(surfaceData.emissive, 1.0); + } +#endif + +// Shading +vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult lightingResult) +{ + vec4 color = vec4(0.0, 0.0, 0.0, surfaceData.baseColor.a); +#if CC_FORWARD_ADD + color.xyz += lightingResult.directDiffuse * lightingResult.diffuseColorWithLighting; + color.xyz += lightingResult.directSpecular * lightingResult.specularColorWithLighting; +#else + float lightmapCoef = 0.0; + + color.xyz += ( + mix(lightingResult.directDiffuse, lightingResult.lightmapColor, lightmapCoef) * lightingResult.diffuseColorWithLighting + + lightingResult.directSpecular * lightingResult.specularColorWithLighting) + * lightingResult.shadow; + + color.xyz += lightingResult.emissive; +#endif + + return color; +} + + +// Debug view +#if CC_USE_DEBUG_VIEW == CC_SURFACES_DEBUG_VIEW_SINGLE +void CCSurfacesDebugViewSurfaceData(out vec4 color, in SurfacesMaterialData surfaceData) +{ + float scalar; + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_FRAGMENT_NORMAL)) + color = vec4(surfaceData.worldNormal * 0.5 + vec3(0.5), 1.0); + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_FRAGMENT_TANGENT)) + color = vec4(0.0, 0.0, 0.0, 1.0); + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_FRAGMENT_BINORMAL)) + color = vec4(0.0, 0.0, 0.0, 1.0); + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_TRANSPARENCY)) + { + scalar = surfaceData.baseColor.a; + color = vec4(scalar, scalar, scalar, 1.0); + } + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_BASE_COLOR)) + color = vec4(LinearToSRGB(surfaceData.baseColor.rgb), 1.0); + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_DIFFUSE_COLOR)) + color = vec4(LinearToSRGB(CCSurfacesGetDiffuseColor(surfaceData)), 1.0); + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_SPECULAR_COLOR)) + color = vec4(LinearToSRGB(CCSurfacesGetSpecularColor(surfaceData)), 1.0); + + if (IS_DEBUG_VIEW_SINGLE_MODE(CC_SURFACES_DEBUG_VIEW_SPECULAR_INTENSITY)) + { + scalar = surfaceData.specular.a; + color = vec4(scalar, scalar, scalar, 1.0); + } +} +#endif + +// lighting flow module-function used by this material +#include diff --git a/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk.meta b/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk.meta new file mode 100644 index 0000000000..e73d37d4cd --- /dev/null +++ b/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk.meta @@ -0,0 +1,9 @@ +{ + "ver": "1.0.5", + "importer": "effect-header", + "imported": true, + "uuid": "218130cc-7167-4535-b6b8-99807138bb39", + "files": [], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/default-terrain/default-layer-texture.jpg.meta b/editor/assets/default-terrain/default-layer-texture.jpg.meta index c7857b1cb6..878ad55d3d 100644 --- a/editor/assets/default-terrain/default-layer-texture.jpg.meta +++ b/editor/assets/default-terrain/default-layer-texture.jpg.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "52ef29ed-bd92-4e94-ab2f-0ebc91bf3a60", @@ -26,7 +26,8 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "52ef29ed-bd92-4e94-ab2f-0ebc91bf3a60" + "imageUuidOrDatabaseUri": "52ef29ed-bd92-4e94-ab2f-0ebc91bf3a60", + "visible": true }, "displayName": "default-layer-texture", "id": "6c48a", @@ -36,6 +37,7 @@ "userData": { "type": "texture", "redirect": "52ef29ed-bd92-4e94-ab2f-0ebc91bf3a60@6c48a", - "hasAlpha": false + "hasAlpha": false, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default-video.mp4.meta b/editor/assets/default-video.mp4.meta index 80d5893f8f..293d8c712c 100644 --- a/editor/assets/default-video.mp4.meta +++ b/editor/assets/default-video.mp4.meta @@ -4,8 +4,8 @@ "imported": true, "uuid": "2be36297-9abb-4fee-8049-9ed5e271da8a", "files": [ - ".mp4", - ".json" + ".json", + ".mp4" ], "subMetas": {}, "userData": {} diff --git a/editor/assets/default_cubemap/back.jpg.meta b/editor/assets/default_cubemap/back.jpg.meta index 28a12a2ec1..a248822dd0 100644 --- a/editor/assets/default_cubemap/back.jpg.meta +++ b/editor/assets/default_cubemap/back.jpg.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "03721795-84b1-4dcd-8eb3-c8e6b88ee535", @@ -26,7 +26,8 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "03721795-84b1-4dcd-8eb3-c8e6b88ee535" + "imageUuidOrDatabaseUri": "03721795-84b1-4dcd-8eb3-c8e6b88ee535", + "visible": true }, "displayName": "back", "id": "6c48a", @@ -36,6 +37,7 @@ "userData": { "type": "texture", "redirect": "03721795-84b1-4dcd-8eb3-c8e6b88ee535@6c48a", - "hasAlpha": false + "hasAlpha": false, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_cubemap/bottom.jpg.meta b/editor/assets/default_cubemap/bottom.jpg.meta index ad3101a93f..9e82b36bd1 100644 --- a/editor/assets/default_cubemap/bottom.jpg.meta +++ b/editor/assets/default_cubemap/bottom.jpg.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "e049bea9-db6b-463b-8502-61bf426357a1", @@ -26,7 +26,8 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "e049bea9-db6b-463b-8502-61bf426357a1" + "imageUuidOrDatabaseUri": "e049bea9-db6b-463b-8502-61bf426357a1", + "visible": true }, "displayName": "bottom", "id": "6c48a", @@ -36,6 +37,7 @@ "userData": { "type": "texture", "redirect": "e049bea9-db6b-463b-8502-61bf426357a1@6c48a", - "hasAlpha": false + "hasAlpha": false, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_cubemap/front.jpg.meta b/editor/assets/default_cubemap/front.jpg.meta index 89daf6f3f1..345a535c9c 100644 --- a/editor/assets/default_cubemap/front.jpg.meta +++ b/editor/assets/default_cubemap/front.jpg.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "86eb75aa-3b2f-4c7b-b59e-bdc2e3984665", @@ -26,7 +26,8 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "86eb75aa-3b2f-4c7b-b59e-bdc2e3984665" + "imageUuidOrDatabaseUri": "86eb75aa-3b2f-4c7b-b59e-bdc2e3984665", + "visible": true }, "displayName": "front", "id": "6c48a", @@ -36,6 +37,7 @@ "userData": { "type": "texture", "redirect": "86eb75aa-3b2f-4c7b-b59e-bdc2e3984665@6c48a", - "hasAlpha": false + "hasAlpha": false, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_cubemap/left.jpg.meta b/editor/assets/default_cubemap/left.jpg.meta index 1e1464e5bd..5e3b661069 100644 --- a/editor/assets/default_cubemap/left.jpg.meta +++ b/editor/assets/default_cubemap/left.jpg.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "61ac0181-00bd-4c17-97f0-5fc7f4bafb3d", @@ -26,7 +26,8 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "61ac0181-00bd-4c17-97f0-5fc7f4bafb3d" + "imageUuidOrDatabaseUri": "61ac0181-00bd-4c17-97f0-5fc7f4bafb3d", + "visible": true }, "displayName": "left", "id": "6c48a", @@ -36,6 +37,7 @@ "userData": { "type": "texture", "redirect": "61ac0181-00bd-4c17-97f0-5fc7f4bafb3d@6c48a", - "hasAlpha": false + "hasAlpha": false, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_cubemap/right.jpg.meta b/editor/assets/default_cubemap/right.jpg.meta index 067139a624..c2323d97ee 100644 --- a/editor/assets/default_cubemap/right.jpg.meta +++ b/editor/assets/default_cubemap/right.jpg.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "80aabd92-9942-4765-b685-8577a1c88b4e", @@ -26,7 +26,8 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "80aabd92-9942-4765-b685-8577a1c88b4e" + "imageUuidOrDatabaseUri": "80aabd92-9942-4765-b685-8577a1c88b4e", + "visible": true }, "displayName": "right", "id": "6c48a", @@ -36,6 +37,7 @@ "userData": { "type": "texture", "redirect": "80aabd92-9942-4765-b685-8577a1c88b4e@6c48a", - "hasAlpha": false + "hasAlpha": false, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_cubemap/top.jpg.meta b/editor/assets/default_cubemap/top.jpg.meta index 653d9e5c34..0063acbe5d 100644 --- a/editor/assets/default_cubemap/top.jpg.meta +++ b/editor/assets/default_cubemap/top.jpg.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "6c895e98-967e-4a6d-8c08-bf6b035fa2c1", @@ -26,7 +26,8 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "6c895e98-967e-4a6d-8c08-bf6b035fa2c1" + "imageUuidOrDatabaseUri": "6c895e98-967e-4a6d-8c08-bf6b035fa2c1", + "visible": true }, "displayName": "top", "id": "6c48a", @@ -36,6 +37,7 @@ "userData": { "type": "texture", "redirect": "6c895e98-967e-4a6d-8c08-bf6b035fa2c1@6c48a", - "hasAlpha": false + "hasAlpha": false, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_file_content/chunk b/editor/assets/default_file_content/chunk index e8ae944eba..0325413d09 100644 --- a/editor/assets/default_file_content/chunk +++ b/editor/assets/default_file_content/chunk @@ -1,6 +1,6 @@ // you can write GLSL code directly in here -#include +#include #define iResolution cc_screenSize #define iTime cc_time.x diff --git a/editor/assets/default_file_content/effect b/editor/assets/default_file_content/effect index f52f773642..a8a3258246 100644 --- a/editor/assets/default_file_content/effect +++ b/editor/assets/default_file_content/effect @@ -4,7 +4,7 @@ CCEffect %{ techniques: - name: opaque passes: - - vert: general-vs:vert # builtin header + - vert: legacy/main-functions/general-vs:vert # builtin header frag: unlit-fs:frag properties: &props mainTexture: { value: white } @@ -25,8 +25,8 @@ CCEffect %{ CCProgram unlit-fs %{ precision highp float; - #include - #include + #include + #include in vec2 v_uv; in vec3 v_position; diff --git a/editor/assets/default_file_content/js b/editor/assets/default_file_content/js index 2d5c9f5ffd..1803536801 100644 --- a/editor/assets/default_file_content/js +++ b/editor/assets/default_file_content/js @@ -1,20 +1,22 @@ import { _decorator, Component, Node } from 'cc'; const { ccclass, property } = _decorator; -@ccclass('<%Name%>') -export class <%Name%> extends Component { - /* class member could be defined like this */ - // dummy = ''; +@ccclass('<%UnderscoreCaseClassName%>') +export class <%UnderscoreCaseClassName%> extends Component { + + // class member could be defined like this. + dummy = ''; - /* use `property` decorator if your want the member to be serializable */ - // @property - // serializableDummy = 0; + // Use 'property' decorator if your want the member to be serializable. + @property + serializableDummy = 0; - start () { + start() { // Your initialization goes here. } - // update (deltaTime) { - // // Your update function goes here. - // } + update(deltaTime) { + // Your update function goes here. + } + } diff --git a/editor/assets/default_file_content/scene b/editor/assets/default_file_content/scene index 26fcca53bf..56435e5f9e 100644 --- a/editor/assets/default_file_content/scene +++ b/editor/assets/default_file_content/scene @@ -273,19 +273,19 @@ }, "_firstSetCSM": false, "_fixedArea": false, - "_pcf": 0, + "_pcf": 1, "_bias": 0.00001, "_normalBias": 0, "_near": 0.1, "_far": 10, - "_shadowDistance": 100, + "_shadowDistance": 10, "_invisibleOcclusionRange": 200, "_orthoSize": 5, "_maxReceived": 4, "_size": { "__type__": "cc.Vec2", - "x": 512, - "y": 512 + "x": 1024, + "y": 1024 }, "_saturation": 0.75 }, diff --git a/editor/assets/default_file_content/scene-2d b/editor/assets/default_file_content/scene-2d index e1e92caac4..3b3ac017bb 100644 --- a/editor/assets/default_file_content/scene-2d +++ b/editor/assets/default_file_content/scene-2d @@ -10,7 +10,7 @@ }, { "__type__": "cc.Scene", - "_name": "", + "_name": "scene-2d", "_objFlags": 0, "_parent": null, "_children": [ @@ -23,37 +23,90 @@ "_prefab": null, "autoReleaseAssets": false, "_globals": { - "__id__": 4 + "__id__": 8 }, - "_id": "f46876e4-e81b-4931-b493-6d367be385e7" + "_id": "c77ecaa8-c936-46c4-a5b0-98692673ed87" }, { "__type__": "cc.Node", - "_name": "Main Camera", + "_name": "Canvas", "_objFlags": 0, "_parent": { "__id__": 1 }, - "_children": [], + "_children": [ + { + "__id__": 3 + } + ], "_active": true, "_components": [ { - "__id__": 3 + "__id__": 5 + }, + { + "__id__": 6 + }, + { + "__id__": 7 } ], "_prefab": null, "_lpos": { "__type__": "cc.Vec3", - "x": -10, - "y": 10, - "z": 10 + "x": 480, + "y": 320.00000000000006, + "z": 0 }, "_lrot": { "__type__": "cc.Quat", - "x": -0.27781593799591064, - "y": -0.36497166752815247, - "z": -0.11507512629032135, - "w": 0.8811195492744446 + "x": 0, + "y": 0, + "z": 0, + "w": 1 + }, + "_lscale": { + "__type__": "cc.Vec3", + "x": 1, + "y": 1, + "z": 1 + }, + "_layer": 33554432, + "_euler": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_id": "beI88Z2HpFELqR4T5EMHpg" + }, + { + "__type__": "cc.Node", + "_name": "Camera", + "_objFlags": 0, + "_parent": { + "__id__": 2 + }, + "_children": [], + "_active": true, + "_components": [ + { + "__id__": 4 + } + ], + "_prefab": null, + "_lpos": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_lrot": { + "__type__": "cc.Quat", + "x": 0, + "y": 0, + "z": 0, + "w": 1 }, "_lscale": { "__type__": "cc.Vec3", @@ -64,33 +117,33 @@ "_layer": 1073741824, "_euler": { "__type__": "cc.Vec3", - "x": -35, - "y": -45, + "x": 0, + "y": 0, "z": 0 }, - "_id": "c9DMICJLFO5IeO07EPon7U" + "_id": "ebFwiq8gBFaYpqYbdoDODe" }, { "__type__": "cc.Camera", "_name": "", "_objFlags": 0, "node": { - "__id__": 2 + "__id__": 3 }, "_enabled": true, "__prefab": null, - "_projection": 1, - "_priority": 0, + "_projection": 0, + "_priority": 1073741824, "_fov": 45, "_fovAxis": 0, - "_orthoHeight": 10, - "_near": 1, - "_far": 1000, + "_orthoHeight": 393.04773561811504, + "_near": 0, + "_far": 2000, "_color": { "__type__": "cc.Color", - "r": 51, - "g": 51, - "b": 51, + "r": 0, + "g": 0, + "b": 0, "a": 255 }, "_depth": 1, @@ -107,23 +160,91 @@ "_shutter": 7, "_iso": 0, "_screenScale": 1, - "_visibility": 1822425087, + "_visibility": 41943040, "_targetTexture": null, - "_id": "7dWQTpwS5LrIHnc1zAPUtf" + "_id": "63WIch3o5BEYRlXzTT0oWc" + }, + { + "__type__": "cc.UITransform", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 2 + }, + "_enabled": true, + "__prefab": null, + "_contentSize": { + "__type__": "cc.Size", + "width": 960, + "height": 640 + }, + "_anchorPoint": { + "__type__": "cc.Vec2", + "x": 0.5, + "y": 0.5 + }, + "_id": "d6rUX5yfhMlKoWX2bSbawx" + }, + { + "__type__": "cc.Canvas", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 2 + }, + "_enabled": true, + "__prefab": null, + "_cameraComponent": { + "__id__": 4 + }, + "_alignCanvasWithScreen": true, + "_id": "12O/ljcVlEqLmVm3U2gEOQ" + }, + { + "__type__": "cc.Widget", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 2 + }, + "_enabled": true, + "__prefab": null, + "_alignFlags": 45, + "_target": null, + "_left": 0, + "_right": 0, + "_top": 5.684341886080802e-14, + "_bottom": 5.684341886080802e-14, + "_horizontalCenter": 0, + "_verticalCenter": 0, + "_isAbsLeft": true, + "_isAbsRight": true, + "_isAbsTop": true, + "_isAbsBottom": true, + "_isAbsHorizontalCenter": true, + "_isAbsVerticalCenter": true, + "_originalWidth": 0, + "_originalHeight": 0, + "_alignMode": 2, + "_lockFlags": 0, + "_id": "c5V1EV8IpMtrIvY1OE9t2u" }, { "__type__": "cc.SceneGlobals", "ambient": { - "__id__": 5 + "__id__": 9 }, "shadows": { - "__id__": 6 + "__id__": 10 }, "_skybox": { - "__id__": 7 + "__id__": 11 }, "fog": { - "__id__": 8 + "__id__": 12 + }, + "octree": { + "__id__": 13 } }, { @@ -176,8 +297,8 @@ }, { "__type__": "cc.ShadowsInfo", - "_type": 0, "_enabled": false, + "_type": 0, "_normal": { "__type__": "cc.Vec3", "x": 0, @@ -192,34 +313,22 @@ "b": 76, "a": 255 }, - "_firstSetCSM": false, - "_fixedArea": false, - "_pcf": 0, - "_bias": 0.00001, - "_normalBias": 0, - "_near": 1, - "_far": 30, - "_shadowDistance": 100, - "_invisibleOcclusionRange": 200, - "_orthoSize": 5, "_maxReceived": 4, "_size": { "__type__": "cc.Vec2", "x": 512, "y": 512 - }, - "_saturation": 0.75 + } }, { "__type__": "cc.SkyboxInfo", - "_applyDiffuseMap": false, + "_envLightingType": 0, "_envmapHDR": null, "_envmap": null, "_envmapLDR": null, "_diffuseMapHDR": null, "_diffuseMapLDR": null, "_enabled": false, - "_useIBL": false, "_useHDR": true }, { @@ -238,6 +347,24 @@ "_fogEnd": 300, "_fogAtten": 5, "_fogTop": 1.5, - "_fogRange": 1.2 + "_fogRange": 1.2, + "_accurate": false + }, + { + "__type__": "cc.OctreeInfo", + "_enabled": false, + "_minPos": { + "__type__": "cc.Vec3", + "x": -1024, + "y": -1024, + "z": -1024 + }, + "_maxPos": { + "__type__": "cc.Vec3", + "x": 1024, + "y": 1024, + "z": 1024 + }, + "_depth": 8 } -] +] \ No newline at end of file diff --git a/editor/assets/default_file_content/ts b/editor/assets/default_file_content/ts index 1cf1108aa5..f51cb70b12 100644 --- a/editor/assets/default_file_content/ts +++ b/editor/assets/default_file_content/ts @@ -1,35 +1,40 @@ -import { _decorator, Component } from 'cc'; +import { _decorator, Component, Node } from 'cc'; const { ccclass, property } = _decorator; -@ccclass('<%Name%>') -export class <%Name%> extends Component { - start() {} +@ccclass('<%UnderscoreCaseClassName%>') +export class <%UnderscoreCaseClassName%> extends Component { + start() { - update(deltaTime: number) { } + } + + update(deltaTime: number) { + + } } /** - * GENERATE IGNORE - * Use the "GENERATE IGNORE" flag in comments to not generate these commented code in newly created script files. + * COMMENTS_GENERATE_IGNORE + * Use "COMMENTS_GENERATE_IGNORE" tag if you do not want later created scripts to contain these comments. * * Predefined Variables - * You can use predefined variables below, they can help you such as decide whether to use 'Camel Format Class Name'. + * You can use predefined variables below to setup your scripting preference. For example, whether to use camel case style. * - * <%Name%>, default format for class name in underscore format, like 'new_component' - * <%UnderscoreFormatClassName%>, class name in underscore format, like 'new_component' - * <%CamelFormatClassName%>, class name in camel format, like 'NewComponent' + * <%UnderscoreCaseClassName%>, class name in underscore format, like 'new_component' + * <%CamelCaseClassName%>, class name in camel format, like 'NewComponent' * <%Author%>, Who create this file * <%DateTime%>, when create this file - * <%FileBasename%>, this file name with extension - * <%FileBasenameNoExtension%>, this file name with no-extension + * <%FileBasename%>, creating file name with extension + * <%FileBasenameNoExtension%>, creating file name without extension * <%URL%>, url of this file in COCOS ASSET URL format - * <%ManualUrl%>, url of office help document, like 'https://docs.cocos.com/creator/manual/en' + * <%ManualUrl%>, url of office help document, like 'https://docs.cocos.com/creator/manual/en/' * * - * Annotated Template + * Example: * - export class <%Name%> extends Component { - // Class member could be defined like this. + @ccclass('<%UnderscoreCaseClassName%>') + export class <%UnderscoreCaseClassName%> extends Component { + + // class member could be defined like this. dummy = ''; // Use 'property' decorator if your want the member to be serializable. @@ -43,6 +48,7 @@ export class <%Name%> extends Component { update (deltaTime: number) { // Your update function goes here. } + } * * Learn more about scripting: <%ManualUrl%>scripting/ diff --git a/editor/assets/default_file_content/ts-animation-graph b/editor/assets/default_file_content/ts-animation-graph index 3ac956ef1c..6b467a3a69 100644 --- a/editor/assets/default_file_content/ts-animation-graph +++ b/editor/assets/default_file_content/ts-animation-graph @@ -1,10 +1,11 @@ -import { _decorator, animation } from "cc"; +import { _decorator, Component, Node, animation } from "cc"; const { ccclass, property } = _decorator; -@ccclass("<%Name%>") -export class <%Name%> extends animation.StateMachineComponent { +@ccclass("<%UnderscoreCaseClassName%>") +export class <%UnderscoreCaseClassName%> extends animation.StateMachineComponent { + /** - * Called when a motion state right after it entered. + * Called right after a motion state is entered. * @param controller The animation controller it within. * @param motionStateStatus The status of the motion. */ @@ -13,7 +14,7 @@ export class <%Name%> extends animation.StateMachineComponent { } /** - * Called when a motion state is going to be exited. + * Called when a motion state is about to exit. * @param controller The animation controller it within. * @param motionStateStatus The status of the motion. */ @@ -31,7 +32,7 @@ export class <%Name%> extends animation.StateMachineComponent { } /** - * Called when a state machine right after it entered. + * Called right after a state machine is entered. * @param controller The animation controller it within. */ public onStateMachineEnter (controller: animation.AnimationController) { @@ -39,10 +40,11 @@ export class <%Name%> extends animation.StateMachineComponent { } /** - * Called when a state machine right after it entered. + * Called right after a state machine is entered. * @param controller The animation controller it within. */ public onStateMachineExit (controller: animation.AnimationController) { // Can be overrode } + } diff --git a/editor/assets/default_file_content/ts-render-flow b/editor/assets/default_file_content/ts-render-flow index 43e15430b4..62482d43f1 100644 --- a/editor/assets/default_file_content/ts-render-flow +++ b/editor/assets/default_file_content/ts-render-flow @@ -1,18 +1,15 @@ import { _decorator, Component, Node, RenderFlow } from "cc"; const { ccclass, property } = _decorator; -@ccclass("<%Name%>") -export class <%Name%> extends RenderFlow { +@ccclass("<%UnderscoreCaseClassName%>") +export class <%UnderscoreCaseClassName%> extends RenderFlow { - /* use `property` decorator if your want the member to be serializable */ - // @property - // serializableDummy = 0; - - rebuild () { - - } - - destroy () { + rebuild() { } + + destroy() { + + } + } diff --git a/editor/assets/default_file_content/ts-render-pipeline b/editor/assets/default_file_content/ts-render-pipeline index 76d3de013a..d2991b5f07 100644 --- a/editor/assets/default_file_content/ts-render-pipeline +++ b/editor/assets/default_file_content/ts-render-pipeline @@ -1,13 +1,11 @@ import { _decorator, Component, Node, RenderPipeline } from "cc"; const { ccclass, property } = _decorator; -@ccclass("<%Name%>") -export class <%Name%> extends RenderPipeline { +@ccclass("<%UnderscoreCaseClassName%>") +export class <%UnderscoreCaseClassName%> extends RenderPipeline { - /* use `property` decorator if your want the member to be serializable */ - // @property - // serializableDummy = 0; - - destroy () { + destroy() { + } + } diff --git a/editor/assets/default_file_content/ts-render-stage b/editor/assets/default_file_content/ts-render-stage index ea054dc96c..550380a323 100644 --- a/editor/assets/default_file_content/ts-render-stage +++ b/editor/assets/default_file_content/ts-render-stage @@ -1,26 +1,23 @@ import { _decorator, Component, Node, RenderStage } from "cc"; const { ccclass, property } = _decorator; -@ccclass("<%Name%>") -export class <%Name%> extends RenderStage { +@ccclass("<%UnderscoreCaseClassName%>") +export class <%UnderscoreCaseClassName%> extends RenderStage { - /* use `property` decorator if your want the member to be serializable */ - // @property - // serializableDummy = 0; - - resize () { + resize() { } - render () { + render() { } - rebuild () { + rebuild() { } - destroy () { + destroy() { } + } diff --git a/editor/assets/default_fonts/builtin-bitmap/OpenSans-BoldItalic_0.png.meta b/editor/assets/default_fonts/builtin-bitmap/OpenSans-BoldItalic_0.png.meta index c26bee2684..0e61f377dd 100644 --- a/editor/assets/default_fonts/builtin-bitmap/OpenSans-BoldItalic_0.png.meta +++ b/editor/assets/default_fonts/builtin-bitmap/OpenSans-BoldItalic_0.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "35ac62e8-0b7a-4367-970d-dfdfbdd023c6", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -22,7 +22,8 @@ "magfilter": "linear", "mipfilter": "none", "anisotropy": 0, - "isUuid": true + "isUuid": true, + "visible": false }, "ver": "1.0.22", "imported": true, @@ -56,9 +57,63 @@ "packable": true, "isUuid": true, "imageUuidOrDatabaseUri": "35ac62e8-0b7a-4367-970d-dfdfbdd023c6@6c48a", - "atlasUuid": "" + "atlasUuid": "", + "vertices": { + "rawPosition": [ + -64, + -64, + 0, + 64, + -64, + 0, + -64, + 64, + 0, + 64, + 64, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 128, + 128, + 128, + 0, + 0, + 128, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -64, + -64, + 0 + ], + "maxPos": [ + 64, + 64, + 0 + ] + } }, - "ver": "1.0.10", + "ver": "1.0.11", "imported": true, "files": [ ".json" @@ -69,6 +124,7 @@ "userData": { "type": "sprite-frame", "hasAlpha": false, - "redirect": "35ac62e8-0b7a-4367-970d-dfdfbdd023c6@f9941" + "redirect": "35ac62e8-0b7a-4367-970d-dfdfbdd023c6@f9941", + "fixAlphaTransparencyArtifacts": true } } diff --git a/editor/assets/default_fonts/builtin-bitmap/OpenSans-Bold_0.png.meta b/editor/assets/default_fonts/builtin-bitmap/OpenSans-Bold_0.png.meta index d14c06f8d5..490914e3a3 100644 --- a/editor/assets/default_fonts/builtin-bitmap/OpenSans-Bold_0.png.meta +++ b/editor/assets/default_fonts/builtin-bitmap/OpenSans-Bold_0.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "c903a495-69a9-4bb1-8266-c5d8a692ee6f", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -22,7 +22,8 @@ "magfilter": "linear", "mipfilter": "none", "anisotropy": 0, - "isUuid": true + "isUuid": true, + "visible": false }, "ver": "1.0.22", "imported": true, @@ -56,9 +57,63 @@ "packable": true, "isUuid": true, "imageUuidOrDatabaseUri": "c903a495-69a9-4bb1-8266-c5d8a692ee6f@6c48a", - "atlasUuid": "" + "atlasUuid": "", + "vertices": { + "rawPosition": [ + -64, + -64, + 0, + 64, + -64, + 0, + -64, + 64, + 0, + 64, + 64, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 128, + 128, + 128, + 0, + 0, + 128, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -64, + -64, + 0 + ], + "maxPos": [ + 64, + 64, + 0 + ] + } }, - "ver": "1.0.10", + "ver": "1.0.11", "imported": true, "files": [ ".json" @@ -69,6 +124,7 @@ "userData": { "type": "sprite-frame", "hasAlpha": false, - "redirect": "c903a495-69a9-4bb1-8266-c5d8a692ee6f@f9941" + "redirect": "c903a495-69a9-4bb1-8266-c5d8a692ee6f@f9941", + "fixAlphaTransparencyArtifacts": true } } diff --git a/editor/assets/default_fonts/builtin-bitmap/OpenSans-Italic_0.png.meta b/editor/assets/default_fonts/builtin-bitmap/OpenSans-Italic_0.png.meta index d436a13733..25d6e50dcf 100644 --- a/editor/assets/default_fonts/builtin-bitmap/OpenSans-Italic_0.png.meta +++ b/editor/assets/default_fonts/builtin-bitmap/OpenSans-Italic_0.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "1a8fc1a3-80e2-4d20-9087-426d2162ba44", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -22,7 +22,8 @@ "magfilter": "linear", "mipfilter": "none", "anisotropy": 0, - "isUuid": true + "isUuid": true, + "visible": false }, "ver": "1.0.22", "imported": true, @@ -56,9 +57,63 @@ "packable": true, "isUuid": true, "imageUuidOrDatabaseUri": "1a8fc1a3-80e2-4d20-9087-426d2162ba44@6c48a", - "atlasUuid": "" + "atlasUuid": "", + "vertices": { + "rawPosition": [ + -64, + -64, + 0, + 64, + -64, + 0, + -64, + 64, + 0, + 64, + 64, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 128, + 128, + 128, + 0, + 0, + 128, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -64, + -64, + 0 + ], + "maxPos": [ + 64, + 64, + 0 + ] + } }, - "ver": "1.0.10", + "ver": "1.0.11", "imported": true, "files": [ ".json" @@ -69,6 +124,7 @@ "userData": { "type": "sprite-frame", "hasAlpha": false, - "redirect": "1a8fc1a3-80e2-4d20-9087-426d2162ba44@f9941" + "redirect": "1a8fc1a3-80e2-4d20-9087-426d2162ba44@f9941", + "fixAlphaTransparencyArtifacts": true } } diff --git a/editor/assets/default_fonts/builtin-bitmap/OpenSans-Regular_0.png.meta b/editor/assets/default_fonts/builtin-bitmap/OpenSans-Regular_0.png.meta index b85c6a67c5..618ffc86aa 100644 --- a/editor/assets/default_fonts/builtin-bitmap/OpenSans-Regular_0.png.meta +++ b/editor/assets/default_fonts/builtin-bitmap/OpenSans-Regular_0.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "744d520a-8483-4fbc-a47b-ab57d28d6203", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -22,7 +22,8 @@ "magfilter": "linear", "mipfilter": "none", "anisotropy": 0, - "isUuid": true + "isUuid": true, + "visible": false }, "ver": "1.0.22", "imported": true, @@ -56,9 +57,63 @@ "packable": true, "isUuid": true, "imageUuidOrDatabaseUri": "744d520a-8483-4fbc-a47b-ab57d28d6203@6c48a", - "atlasUuid": "" + "atlasUuid": "", + "vertices": { + "rawPosition": [ + -64, + -64, + 0, + 64, + -64, + 0, + -64, + 64, + 0, + 64, + 64, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 128, + 128, + 128, + 0, + 0, + 128, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -64, + -64, + 0 + ], + "maxPos": [ + 64, + 64, + 0 + ] + } }, - "ver": "1.0.10", + "ver": "1.0.11", "imported": true, "files": [ ".json" @@ -69,6 +124,7 @@ "userData": { "type": "sprite-frame", "hasAlpha": false, - "redirect": "744d520a-8483-4fbc-a47b-ab57d28d6203@f9941" + "redirect": "744d520a-8483-4fbc-a47b-ab57d28d6203@f9941", + "fixAlphaTransparencyArtifacts": true } } diff --git a/editor/assets/default_fonts/builtin-freetype/OpenSans-Bold.ttf.meta b/editor/assets/default_fonts/builtin-freetype/OpenSans-Bold.ttf.meta index 0d8b7baf26..e460e52d18 100644 --- a/editor/assets/default_fonts/builtin-freetype/OpenSans-Bold.ttf.meta +++ b/editor/assets/default_fonts/builtin-freetype/OpenSans-Bold.ttf.meta @@ -4,8 +4,8 @@ "imported": true, "uuid": "b5475517-23b9-4873-bc1a-968d96616081", "files": [ - "OpenSans-Bold.ttf", - ".json" + ".json", + "OpenSans-Bold.ttf" ], "subMetas": {}, "userData": {} diff --git a/editor/assets/default_fonts/builtin-freetype/OpenSans-BoldItalic.ttf.meta b/editor/assets/default_fonts/builtin-freetype/OpenSans-BoldItalic.ttf.meta index 83cc6c2e7f..de425a8c96 100644 --- a/editor/assets/default_fonts/builtin-freetype/OpenSans-BoldItalic.ttf.meta +++ b/editor/assets/default_fonts/builtin-freetype/OpenSans-BoldItalic.ttf.meta @@ -4,8 +4,8 @@ "imported": true, "uuid": "b23391b6-52eb-46a6-8da1-6244d9d315fb", "files": [ - "OpenSans-BoldItalic.ttf", - ".json" + ".json", + "OpenSans-BoldItalic.ttf" ], "subMetas": {}, "userData": {} diff --git a/editor/assets/default_fonts/builtin-freetype/OpenSans-Italic.ttf.meta b/editor/assets/default_fonts/builtin-freetype/OpenSans-Italic.ttf.meta index ab7ee8aef3..e1dbefdaab 100644 --- a/editor/assets/default_fonts/builtin-freetype/OpenSans-Italic.ttf.meta +++ b/editor/assets/default_fonts/builtin-freetype/OpenSans-Italic.ttf.meta @@ -4,8 +4,8 @@ "imported": true, "uuid": "0ed97c56-390e-4dd1-96b7-e7f2d93a98ed", "files": [ - "OpenSans-Italic.ttf", - ".json" + ".json", + "OpenSans-Italic.ttf" ], "subMetas": {}, "userData": {} diff --git a/editor/assets/default_fonts/builtin-freetype/OpenSans-Regular.ttf.meta b/editor/assets/default_fonts/builtin-freetype/OpenSans-Regular.ttf.meta index 4d02a490df..d26037943b 100644 --- a/editor/assets/default_fonts/builtin-freetype/OpenSans-Regular.ttf.meta +++ b/editor/assets/default_fonts/builtin-freetype/OpenSans-Regular.ttf.meta @@ -4,8 +4,8 @@ "imported": true, "uuid": "0835f102-5471-47a3-9a76-01c07ac9cdb2", "files": [ - "OpenSans-Regular.ttf", - ".json" + ".json", + "OpenSans-Regular.ttf" ], "subMetas": {}, "userData": {} diff --git a/editor/assets/default_materials/default-billboard-material.mtl b/editor/assets/default_materials/default-billboard-material.mtl new file mode 100644 index 0000000000..5879a7d766 --- /dev/null +++ b/editor/assets/default_materials/default-billboard-material.mtl @@ -0,0 +1,28 @@ +{ + "__type__": "cc.Material", + "_name": "", + "_objFlags": 0, + "_native": "", + "_effectAsset": { + "__uuid__": "711ebe11-f673-4cd9-9a83-63c60ba54c5b", + "__expectedType__": "cc.EffectAsset" + }, + "_techIdx": 0, + "_defines": [ + {} + ], + "_states": [ + { + "rasterizerState": {}, + "depthStencilState": {}, + "blendState": { + "targets": [ + {} + ] + } + } + ], + "_props": [ + {} + ] +} \ No newline at end of file diff --git a/editor/assets/default_materials/default-billboard-material.mtl.meta b/editor/assets/default_materials/default-billboard-material.mtl.meta new file mode 100644 index 0000000000..b0d7b4b01f --- /dev/null +++ b/editor/assets/default_materials/default-billboard-material.mtl.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.0.13", + "importer": "material", + "imported": true, + "uuid": "78e0584a-4343-4727-8f37-e14e65c2a2db", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/default_materials/default-clear-stencil.mtl b/editor/assets/default_materials/default-clear-stencil.mtl new file mode 100644 index 0000000000..2f4d7d94f2 --- /dev/null +++ b/editor/assets/default_materials/default-clear-stencil.mtl @@ -0,0 +1,30 @@ +{ + "__type__": "cc.Material", + "_name": "", + "_objFlags": 0, + "_native": "", + "_effectAsset": { + "__uuid__": "810e96e4-e456-4468-9b59-f4e8f39732c0", + "__expectedType__": "cc.EffectAsset" + }, + "_techIdx": 0, + "_defines": [ + { + "USE_TEXTURE": false + } + ], + "_states": [ + { + "rasterizerState": {}, + "depthStencilState": {}, + "blendState": { + "targets": [ + {} + ] + } + } + ], + "_props": [ + {} + ] +} \ No newline at end of file diff --git a/editor/assets/default_materials/default-clear-stencil.mtl.meta b/editor/assets/default_materials/default-clear-stencil.mtl.meta new file mode 100644 index 0000000000..c9a1dbaeaf --- /dev/null +++ b/editor/assets/default_materials/default-clear-stencil.mtl.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.0.13", + "importer": "material", + "imported": true, + "uuid": "8bbdbcdd-5cd4-4100-b6d5-b7c9625b6107", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/default_materials/default-material-transparent.mtl.meta b/editor/assets/default_materials/default-material-transparent.mtl.meta index b9a26f899e..682a8e2d05 100644 --- a/editor/assets/default_materials/default-material-transparent.mtl.meta +++ b/editor/assets/default_materials/default-material-transparent.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.12", + "ver": "1.0.13", "importer": "material", "imported": true, "uuid": "c31a901b-671b-4c3d-9246-f9a6e5f14b90", diff --git a/editor/assets/default_materials/default-material.mtl.meta b/editor/assets/default_materials/default-material.mtl.meta index d620828122..5ee0f527bd 100644 --- a/editor/assets/default_materials/default-material.mtl.meta +++ b/editor/assets/default_materials/default-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.12", + "ver": "1.0.13", "importer": "material", "imported": true, "uuid": "d3c7820c-2a98-4429-8bc7-b8453bc9ac41", diff --git a/editor/assets/default_materials/default-particle-gpu-material.mtl b/editor/assets/default_materials/default-particle-gpu-material.mtl new file mode 100644 index 0000000000..c73cf2245e --- /dev/null +++ b/editor/assets/default_materials/default-particle-gpu-material.mtl @@ -0,0 +1,28 @@ +{ + "__type__": "cc.Material", + "_name": "", + "_objFlags": 0, + "_native": "", + "_effectAsset": { + "__uuid__": "971bdb23-3ff6-43eb-b422-1c30165a3663", + "__expectedType__": "cc.EffectAsset" + }, + "_techIdx": 0, + "_defines": [ + {} + ], + "_states": [ + { + "rasterizerState": {}, + "depthStencilState": {}, + "blendState": { + "targets": [ + {} + ] + } + } + ], + "_props": [ + {} + ] +} \ No newline at end of file diff --git a/editor/assets/default_materials/default-particle-gpu-material.mtl.meta b/editor/assets/default_materials/default-particle-gpu-material.mtl.meta new file mode 100644 index 0000000000..cf9f5a4ffc --- /dev/null +++ b/editor/assets/default_materials/default-particle-gpu-material.mtl.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.0.13", + "importer": "material", + "imported": true, + "uuid": "14da1725-c4c2-42b4-ab08-ee0aeb6898b3", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/default_materials/default-particle-material.mtl b/editor/assets/default_materials/default-particle-material.mtl new file mode 100644 index 0000000000..42d98fca73 --- /dev/null +++ b/editor/assets/default_materials/default-particle-material.mtl @@ -0,0 +1,28 @@ +{ + "__type__": "cc.Material", + "_name": "", + "_objFlags": 0, + "_native": "", + "_effectAsset": { + "__uuid__": "d1346436-ac96-4271-b863-1f4fdead95b0", + "__expectedType__": "cc.EffectAsset" + }, + "_techIdx": 0, + "_defines": [ + {} + ], + "_states": [ + { + "rasterizerState": {}, + "depthStencilState": {}, + "blendState": { + "targets": [ + {} + ] + } + } + ], + "_props": [ + {} + ] +} \ No newline at end of file diff --git a/editor/assets/default_materials/default-particle-material.mtl.meta b/editor/assets/default_materials/default-particle-material.mtl.meta new file mode 100644 index 0000000000..9e37a9492d --- /dev/null +++ b/editor/assets/default_materials/default-particle-material.mtl.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.0.13", + "importer": "material", + "imported": true, + "uuid": "c0143906-9aed-447e-9436-2ae8512d1b6e", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/default_materials/default-spine-material.mtl b/editor/assets/default_materials/default-spine-material.mtl new file mode 100644 index 0000000000..720005c71e --- /dev/null +++ b/editor/assets/default_materials/default-spine-material.mtl @@ -0,0 +1,32 @@ +{ + "__type__": "cc.Material", + "_name": "", + "_objFlags": 0, + "_native": "", + "_effectAsset": { + "__uuid__": "c27215d8-6835-4b68-bfbb-bdeac6100c04", + "__expectedType__": "cc.EffectAsset" + }, + "_techIdx": 0, + "_defines": [ + { + "USE_TEXTURE": true, + "CC_USE_EMBEDDED_ALPHA": false, + "IS_GRAY": false + } + ], + "_states": [ + { + "rasterizerState": {}, + "depthStencilState": {}, + "blendState": { + "targets": [ + {} + ] + } + } + ], + "_props": [ + {} + ] +} \ No newline at end of file diff --git a/editor/assets/default_materials/default-spine-material.mtl.meta b/editor/assets/default_materials/default-spine-material.mtl.meta new file mode 100644 index 0000000000..8ce075055b --- /dev/null +++ b/editor/assets/default_materials/default-spine-material.mtl.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.0.13", + "importer": "material", + "imported": true, + "uuid": "b5d6115f-0370-4d7c-aad3-c194cc71cf98", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/default_materials/default-sprite-renderer-material.mtl b/editor/assets/default_materials/default-sprite-renderer-material.mtl new file mode 100644 index 0000000000..6568cebe50 --- /dev/null +++ b/editor/assets/default_materials/default-sprite-renderer-material.mtl @@ -0,0 +1,28 @@ +{ + "__type__": "cc.Material", + "_name": "", + "_objFlags": 0, + "_native": "", + "_effectAsset": { + "__uuid__": "6ef1defe-7997-477a-9b35-c18859ff8066", + "__expectedType__": "cc.EffectAsset" + }, + "_techIdx": 0, + "_defines": [ + {} + ], + "_states": [ + { + "rasterizerState": {}, + "depthStencilState": {}, + "blendState": { + "targets": [ + {} + ] + } + } + ], + "_props": [ + {} + ] +} \ No newline at end of file diff --git a/editor/assets/default_materials/default-sprite-renderer-material.mtl.meta b/editor/assets/default_materials/default-sprite-renderer-material.mtl.meta new file mode 100644 index 0000000000..f15f7185b0 --- /dev/null +++ b/editor/assets/default_materials/default-sprite-renderer-material.mtl.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.0.13", + "importer": "material", + "imported": true, + "uuid": "ade8a15a-dcca-4b3c-84c6-f6476ac875bb", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/default_materials/default-trail-material.mtl b/editor/assets/default_materials/default-trail-material.mtl new file mode 100644 index 0000000000..456251692b --- /dev/null +++ b/editor/assets/default_materials/default-trail-material.mtl @@ -0,0 +1,28 @@ +{ + "__type__": "cc.Material", + "_name": "", + "_objFlags": 0, + "_native": "", + "_effectAsset": { + "__uuid__": "17debcc3-0a6b-4b8a-b00b-dc58b885581e", + "__expectedType__": "cc.EffectAsset" + }, + "_techIdx": 0, + "_defines": [ + {} + ], + "_states": [ + { + "rasterizerState": {}, + "depthStencilState": {}, + "blendState": { + "targets": [ + {} + ] + } + } + ], + "_props": [ + {} + ] +} \ No newline at end of file diff --git a/editor/assets/default_materials/default-trail-material.mtl.meta b/editor/assets/default_materials/default-trail-material.mtl.meta new file mode 100644 index 0000000000..ad605285f6 --- /dev/null +++ b/editor/assets/default_materials/default-trail-material.mtl.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.0.13", + "importer": "material", + "imported": true, + "uuid": "081cab31-dccd-428e-8652-f2404cc81c47", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/default_materials/missing-effect-material.mtl b/editor/assets/default_materials/missing-effect-material.mtl new file mode 100644 index 0000000000..55d630d8f8 --- /dev/null +++ b/editor/assets/default_materials/missing-effect-material.mtl @@ -0,0 +1,38 @@ +{ + "__type__": "cc.Material", + "_name": "", + "_objFlags": 0, + "_native": "", + "_effectAsset": { + "__uuid__": "a3cd009f-0ab0-420d-9278-b9fdab939bbc", + "__expectedType__": "cc.EffectAsset" + }, + "_techIdx": 0, + "_defines": [ + { + "USE_COLOR": true + } + ], + "_states": [ + { + "rasterizerState": {}, + "depthStencilState": {}, + "blendState": { + "targets": [ + {} + ] + } + } + ], + "_props": [ + { + "mainColor": { + "__type__": "cc.Color", + "r": 255, + "g": 255, + "b": 0, + "a": 255 + } + } + ] +} \ No newline at end of file diff --git a/editor/assets/default_materials/missing-effect-material.mtl.meta b/editor/assets/default_materials/missing-effect-material.mtl.meta new file mode 100644 index 0000000000..5df39e4c85 --- /dev/null +++ b/editor/assets/default_materials/missing-effect-material.mtl.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.0.13", + "importer": "material", + "imported": true, + "uuid": "bcd64cc6-2dd9-43f6-abbe-66318d332032", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/default_materials/missing-material.mtl b/editor/assets/default_materials/missing-material.mtl new file mode 100644 index 0000000000..65701c705a --- /dev/null +++ b/editor/assets/default_materials/missing-material.mtl @@ -0,0 +1,38 @@ +{ + "__type__": "cc.Material", + "_name": "", + "_objFlags": 0, + "_native": "", + "_effectAsset": { + "__uuid__": "a3cd009f-0ab0-420d-9278-b9fdab939bbc", + "__expectedType__": "cc.EffectAsset" + }, + "_techIdx": 0, + "_defines": [ + { + "USE_COLOR": true + } + ], + "_states": [ + { + "rasterizerState": {}, + "depthStencilState": {}, + "blendState": { + "targets": [ + {} + ] + } + } + ], + "_props": [ + { + "mainColor": { + "__type__": "cc.Color", + "r": 255, + "g": 0, + "b": 255, + "a": 255 + } + } + ] +} \ No newline at end of file diff --git a/editor/assets/default_materials/missing-material.mtl.meta b/editor/assets/default_materials/missing-material.mtl.meta new file mode 100644 index 0000000000..32c04d6666 --- /dev/null +++ b/editor/assets/default_materials/missing-material.mtl.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.0.13", + "importer": "material", + "imported": true, + "uuid": "d930590d-bb92-4cc8-8bd1-23cd027f9edf", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/default_materials/particle-add.mtl.meta b/editor/assets/default_materials/particle-add.mtl.meta index f4d33c483f..0310076572 100644 --- a/editor/assets/default_materials/particle-add.mtl.meta +++ b/editor/assets/default_materials/particle-add.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.12", + "ver": "1.0.13", "importer": "material", "imported": true, "uuid": "ea7478b0-408d-4052-b703-f0d2355e095f", diff --git a/editor/assets/default_materials/standard-material.mtl b/editor/assets/default_materials/standard-material.mtl new file mode 100644 index 0000000000..75533e95d7 --- /dev/null +++ b/editor/assets/default_materials/standard-material.mtl @@ -0,0 +1,14 @@ +{ + "__type__": "cc.Material", + "_name": "", + "_objFlags": 0, + "_native": "", + "_effectAsset": { + "__uuid__": "1baf0fc9-befa-459c-8bdd-af1a450a0319" + }, + "_techIdx": 0, + "_defines": [], + "_props": [ + {} + ] +} \ No newline at end of file diff --git a/editor/assets/default_materials/standard-material.mtl.meta b/editor/assets/default_materials/standard-material.mtl.meta new file mode 100644 index 0000000000..20f739f7cc --- /dev/null +++ b/editor/assets/default_materials/standard-material.mtl.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.0.13", + "importer": "material", + "imported": true, + "uuid": "620b6bf3-0369-4560-837f-2a2c00b73c26", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/default_materials/ui-alpha-test-material.mtl b/editor/assets/default_materials/ui-alpha-test-material.mtl new file mode 100644 index 0000000000..a6dd3ce9ef --- /dev/null +++ b/editor/assets/default_materials/ui-alpha-test-material.mtl @@ -0,0 +1,33 @@ +{ + "__type__": "cc.Material", + "_name": "", + "_objFlags": 0, + "_native": "", + "_effectAsset": { + "__uuid__": "60f7195c-ec2a-45eb-ba94-8955f60e81d0", + "__expectedType__": "cc.EffectAsset" + }, + "_techIdx": 0, + "_defines": [ + { + "USE_ALPHA_TEST": true, + "USE_TEXTURE": true, + "IS_GRAY": false, + "CC_USE_EMBEDDED_ALPHA": false + } + ], + "_states": [ + { + "rasterizerState": {}, + "depthStencilState": {}, + "blendState": { + "targets": [ + {} + ] + } + } + ], + "_props": [ + {} + ] +} \ No newline at end of file diff --git a/editor/assets/default_materials/ui-alpha-test-material.mtl.meta b/editor/assets/default_materials/ui-alpha-test-material.mtl.meta new file mode 100644 index 0000000000..24e98c4ae6 --- /dev/null +++ b/editor/assets/default_materials/ui-alpha-test-material.mtl.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.0.13", + "importer": "material", + "imported": true, + "uuid": "50f4348b-c883-4e2f-8f11-ce233b859fa1", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/default_materials/ui-base-material.mtl b/editor/assets/default_materials/ui-base-material.mtl new file mode 100644 index 0000000000..6a325a6089 --- /dev/null +++ b/editor/assets/default_materials/ui-base-material.mtl @@ -0,0 +1,30 @@ +{ + "__type__": "cc.Material", + "_name": "", + "_objFlags": 0, + "_native": "", + "_effectAsset": { + "__uuid__": "60f7195c-ec2a-45eb-ba94-8955f60e81d0", + "__expectedType__": "cc.EffectAsset" + }, + "_techIdx": 0, + "_defines": [ + { + "USE_TEXTURE": false + } + ], + "_states": [ + { + "rasterizerState": {}, + "depthStencilState": {}, + "blendState": { + "targets": [ + {} + ] + } + } + ], + "_props": [ + {} + ] +} \ No newline at end of file diff --git a/editor/assets/default_materials/ui-base-material.mtl.meta b/editor/assets/default_materials/ui-base-material.mtl.meta new file mode 100644 index 0000000000..9161cd8ed0 --- /dev/null +++ b/editor/assets/default_materials/ui-base-material.mtl.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.0.13", + "importer": "material", + "imported": true, + "uuid": "e9aa9a3e-5b2b-4ac7-a2c7-073de2b2b24f", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/default_materials/ui-graphics-material.mtl b/editor/assets/default_materials/ui-graphics-material.mtl new file mode 100644 index 0000000000..8f9dea8288 --- /dev/null +++ b/editor/assets/default_materials/ui-graphics-material.mtl @@ -0,0 +1,28 @@ +{ + "__type__": "cc.Material", + "_name": "", + "_objFlags": 0, + "_native": "", + "_effectAsset": { + "__uuid__": "1c02ae6f-4492-4915-b8f8-7492a3b1e4cd", + "__expectedType__": "cc.EffectAsset" + }, + "_techIdx": 0, + "_defines": [ + {} + ], + "_states": [ + { + "rasterizerState": {}, + "depthStencilState": {}, + "blendState": { + "targets": [ + {} + ] + } + } + ], + "_props": [ + {} + ] +} \ No newline at end of file diff --git a/editor/assets/default_materials/ui-graphics-material.mtl.meta b/editor/assets/default_materials/ui-graphics-material.mtl.meta new file mode 100644 index 0000000000..69289119a2 --- /dev/null +++ b/editor/assets/default_materials/ui-graphics-material.mtl.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.0.13", + "importer": "material", + "imported": true, + "uuid": "f0416e68-0200-4b77-a926-4f9d16e494da", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/default_materials/ui-sprite-alpha-sep-material.mtl b/editor/assets/default_materials/ui-sprite-alpha-sep-material.mtl new file mode 100644 index 0000000000..62b16f7d1b --- /dev/null +++ b/editor/assets/default_materials/ui-sprite-alpha-sep-material.mtl @@ -0,0 +1,32 @@ +{ + "__type__": "cc.Material", + "_name": "", + "_objFlags": 0, + "_native": "", + "_effectAsset": { + "__uuid__": "60f7195c-ec2a-45eb-ba94-8955f60e81d0", + "__expectedType__": "cc.EffectAsset" + }, + "_techIdx": 0, + "_defines": [ + { + "USE_TEXTURE": true, + "CC_USE_EMBEDDED_ALPHA": true, + "IS_GRAY": false + } + ], + "_states": [ + { + "rasterizerState": {}, + "depthStencilState": {}, + "blendState": { + "targets": [ + {} + ] + } + } + ], + "_props": [ + {} + ] +} \ No newline at end of file diff --git a/editor/assets/default_materials/ui-sprite-alpha-sep-material.mtl.meta b/editor/assets/default_materials/ui-sprite-alpha-sep-material.mtl.meta new file mode 100644 index 0000000000..5943fb0914 --- /dev/null +++ b/editor/assets/default_materials/ui-sprite-alpha-sep-material.mtl.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.0.13", + "importer": "material", + "imported": true, + "uuid": "f92806d7-1768-443f-afe8-12bcde84d0f0", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/default_materials/ui-sprite-gray-alpha-sep-material.mtl b/editor/assets/default_materials/ui-sprite-gray-alpha-sep-material.mtl new file mode 100644 index 0000000000..35cdecd8fa --- /dev/null +++ b/editor/assets/default_materials/ui-sprite-gray-alpha-sep-material.mtl @@ -0,0 +1,32 @@ +{ + "__type__": "cc.Material", + "_name": "", + "_objFlags": 0, + "_native": "", + "_effectAsset": { + "__uuid__": "60f7195c-ec2a-45eb-ba94-8955f60e81d0", + "__expectedType__": "cc.EffectAsset" + }, + "_techIdx": 0, + "_defines": [ + { + "USE_TEXTURE": true, + "CC_USE_EMBEDDED_ALPHA": true, + "IS_GRAY": true + } + ], + "_states": [ + { + "rasterizerState": {}, + "depthStencilState": {}, + "blendState": { + "targets": [ + {} + ] + } + } + ], + "_props": [ + {} + ] +} \ No newline at end of file diff --git a/editor/assets/default_materials/ui-sprite-gray-alpha-sep-material.mtl.meta b/editor/assets/default_materials/ui-sprite-gray-alpha-sep-material.mtl.meta new file mode 100644 index 0000000000..76bd56caa4 --- /dev/null +++ b/editor/assets/default_materials/ui-sprite-gray-alpha-sep-material.mtl.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.0.13", + "importer": "material", + "imported": true, + "uuid": "dd3a144d-ab7f-41f0-82b8-2e43a090d496", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/default_materials/ui-sprite-gray-material.mtl b/editor/assets/default_materials/ui-sprite-gray-material.mtl new file mode 100644 index 0000000000..16a55a8c93 --- /dev/null +++ b/editor/assets/default_materials/ui-sprite-gray-material.mtl @@ -0,0 +1,32 @@ +{ + "__type__": "cc.Material", + "_name": "", + "_objFlags": 0, + "_native": "", + "_effectAsset": { + "__uuid__": "60f7195c-ec2a-45eb-ba94-8955f60e81d0", + "__expectedType__": "cc.EffectAsset" + }, + "_techIdx": 0, + "_defines": [ + { + "USE_TEXTURE": true, + "CC_USE_EMBEDDED_ALPHA": false, + "IS_GRAY": true + } + ], + "_states": [ + { + "rasterizerState": {}, + "depthStencilState": {}, + "blendState": { + "targets": [ + {} + ] + } + } + ], + "_props": [ + {} + ] +} \ No newline at end of file diff --git a/editor/assets/default_materials/ui-sprite-gray-material.mtl.meta b/editor/assets/default_materials/ui-sprite-gray-material.mtl.meta new file mode 100644 index 0000000000..8095ee5128 --- /dev/null +++ b/editor/assets/default_materials/ui-sprite-gray-material.mtl.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.0.13", + "importer": "material", + "imported": true, + "uuid": "efe8e2a3-eace-427b-b4f1-cb8a937ec77d", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/default_materials/ui-sprite-material.mtl b/editor/assets/default_materials/ui-sprite-material.mtl index 157abdae56..a7d8e6a2ab 100644 --- a/editor/assets/default_materials/ui-sprite-material.mtl +++ b/editor/assets/default_materials/ui-sprite-material.mtl @@ -4,15 +4,28 @@ "_objFlags": 0, "_native": "", "_effectAsset": { - "__uuid__": "60f7195c-ec2a-45eb-ba94-8955f60e81d0" + "__uuid__": "60f7195c-ec2a-45eb-ba94-8955f60e81d0", + "__expectedType__": "cc.EffectAsset" }, "_techIdx": 0, "_defines": [ { - "USE_TEXTURE": true + "USE_TEXTURE": true, + "IS_GRAY": false, + "CC_USE_EMBEDDED_ALPHA": false + } + ], + "_states": [ + { + "rasterizerState": {}, + "depthStencilState": {}, + "blendState": { + "targets": [ + {} + ] + } } ], - "_states": [], "_props": [ {} ] diff --git a/editor/assets/default_materials/ui-sprite-material.mtl.meta b/editor/assets/default_materials/ui-sprite-material.mtl.meta index 274c988176..524140c710 100644 --- a/editor/assets/default_materials/ui-sprite-material.mtl.meta +++ b/editor/assets/default_materials/ui-sprite-material.mtl.meta @@ -1,5 +1,5 @@ { - "ver": "1.0.12", + "ver": "1.0.13", "importer": "material", "imported": true, "uuid": "fda095cb-831d-4601-ad94-846013963de8", diff --git a/editor/assets/default_prefab/2d.meta b/editor/assets/default_prefab/2d.meta new file mode 100644 index 0000000000..9f56cca70a --- /dev/null +++ b/editor/assets/default_prefab/2d.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "2201b77a-5090-48dd-8dc0-48503a9be474", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/default_prefab/2d/Camera.prefab b/editor/assets/default_prefab/2d/Camera.prefab new file mode 100644 index 0000000000..19bdc3a8a1 --- /dev/null +++ b/editor/assets/default_prefab/2d/Camera.prefab @@ -0,0 +1,115 @@ +[ + { + "__type__": "cc.Prefab", + "_name": "Camera", + "_objFlags": 0, + "_native": "", + "data": { + "__id__": 1 + }, + "optimizationPolicy": 0, + "persistent": false, + "asyncLoadAssets": false + }, + { + "__type__": "cc.Node", + "_name": "Camera", + "_objFlags": 0, + "__editorExtras__": {}, + "_parent": null, + "_children": [], + "_active": true, + "_components": [ + { + "__id__": 2 + } + ], + "_prefab": { + "__id__": 4 + }, + "_lpos": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_lrot": { + "__type__": "cc.Quat", + "x": 0, + "y": 0, + "z": 0, + "w": 1 + }, + "_lscale": { + "__type__": "cc.Vec3", + "x": 1, + "y": 1, + "z": 1 + }, + "_layer": 1073741824, + "_euler": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_id": "" + }, + { + "__type__": "cc.Camera", + "_name": "Camera", + "_objFlags": 0, + "node": { + "__id__": 1 + }, + "_enabled": true, + "__prefab": { + "__id__": 3 + }, + "_projection": 0, + "_priority": 0, + "_fov": 45, + "_fovAxis": 0, + "_orthoHeight": 10, + "_near": 0, + "_far": 1000, + "_color": { + "__type__": "cc.Color", + "r": 51, + "g": 76, + "b": 120, + "a": 255 + }, + "_depth": 1, + "_stencil": 0, + "_clearFlags": 7, + "_rect": { + "__type__": "cc.Rect", + "x": 0, + "y": 0, + "width": 1, + "height": 1 + }, + "_aperture": 19, + "_shutter": 7, + "_iso": 0, + "_screenScale": 1, + "_visibility": 1108344832, + "_targetTexture": null, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "da2BI3+SxOmYFitcPWPxAg" + }, + { + "__type__": "cc.PrefabInfo", + "root": { + "__id__": 1 + }, + "asset": { + "__id__": 0 + }, + "fileId": "04zH6qlZ9EeJlFO7H23rXj" + } +] \ No newline at end of file diff --git a/editor/assets/default_prefab/2d/Camera.prefab.meta b/editor/assets/default_prefab/2d/Camera.prefab.meta new file mode 100644 index 0000000000..e5d2aa0158 --- /dev/null +++ b/editor/assets/default_prefab/2d/Camera.prefab.meta @@ -0,0 +1,13 @@ +{ + "ver": "1.1.39", + "importer": "prefab", + "imported": true, + "uuid": "3487d118-0158-4983-93fe-c3822790e7c5", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": { + "syncNodeName": "Camera" + } +} diff --git a/editor/assets/default_prefab/3d/Capsule.prefab.meta b/editor/assets/default_prefab/3d/Capsule.prefab.meta index 6c0f7d3195..eb117b6061 100644 --- a/editor/assets/default_prefab/3d/Capsule.prefab.meta +++ b/editor/assets/default_prefab/3d/Capsule.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "73ce1f7f-d1f4-4942-ad93-66ca3b3041ab", diff --git a/editor/assets/default_prefab/3d/Cone.prefab.meta b/editor/assets/default_prefab/3d/Cone.prefab.meta index a7cabfec16..0cb28ca198 100644 --- a/editor/assets/default_prefab/3d/Cone.prefab.meta +++ b/editor/assets/default_prefab/3d/Cone.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "6350d660-e888-4acf-a552-f3b719ae9110", diff --git a/editor/assets/default_prefab/3d/Cube.prefab.meta b/editor/assets/default_prefab/3d/Cube.prefab.meta index 4fbd40006c..966e0ddf6a 100644 --- a/editor/assets/default_prefab/3d/Cube.prefab.meta +++ b/editor/assets/default_prefab/3d/Cube.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "30da77a1-f02d-4ede-aa56-403452ee7fde", diff --git a/editor/assets/default_prefab/3d/Cylinder.prefab.meta b/editor/assets/default_prefab/3d/Cylinder.prefab.meta index 947e5683cd..4d8a36732f 100644 --- a/editor/assets/default_prefab/3d/Cylinder.prefab.meta +++ b/editor/assets/default_prefab/3d/Cylinder.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "ab3e16f9-671e-48a7-90b7-d0884d9cbb85", diff --git a/editor/assets/default_prefab/3d/Plane.prefab.meta b/editor/assets/default_prefab/3d/Plane.prefab.meta index ecd98b8b73..9ae4b4b379 100644 --- a/editor/assets/default_prefab/3d/Plane.prefab.meta +++ b/editor/assets/default_prefab/3d/Plane.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "40563723-f8fc-4216-99ea-a81636435c10", diff --git a/editor/assets/default_prefab/3d/Quad.prefab.meta b/editor/assets/default_prefab/3d/Quad.prefab.meta index 9e33406e5b..71a6bc9b2d 100644 --- a/editor/assets/default_prefab/3d/Quad.prefab.meta +++ b/editor/assets/default_prefab/3d/Quad.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "34a07346-9f62-4a84-90ae-cb83f7a426c1", diff --git a/editor/assets/default_prefab/3d/Sphere.prefab.meta b/editor/assets/default_prefab/3d/Sphere.prefab.meta index 7e6461e774..5a68a78e77 100644 --- a/editor/assets/default_prefab/3d/Sphere.prefab.meta +++ b/editor/assets/default_prefab/3d/Sphere.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "655c9519-1a37-472b-bae6-29fefac0b550", diff --git a/editor/assets/default_prefab/3d/Torus.prefab.meta b/editor/assets/default_prefab/3d/Torus.prefab.meta index f6334d9068..7cdeb4a8bc 100644 --- a/editor/assets/default_prefab/3d/Torus.prefab.meta +++ b/editor/assets/default_prefab/3d/Torus.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "d47f5d5e-c931-4ff4-987b-cc818a728b82", diff --git a/editor/assets/default_prefab/Camera.prefab.meta b/editor/assets/default_prefab/Camera.prefab.meta index 6b543dbcbe..dd25cfe779 100644 --- a/editor/assets/default_prefab/Camera.prefab.meta +++ b/editor/assets/default_prefab/Camera.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "bb0a6472-cd67-4afb-a031-94fca8f4cc92", diff --git a/editor/assets/default_prefab/Terrain.prefab.meta b/editor/assets/default_prefab/Terrain.prefab.meta index eb64f2e80b..f76e9e78f9 100644 --- a/editor/assets/default_prefab/Terrain.prefab.meta +++ b/editor/assets/default_prefab/Terrain.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "90e8b0d4-12dc-412d-9156-ea1fdb18c15b", diff --git a/editor/assets/default_prefab/effects/Particle System.prefab.meta b/editor/assets/default_prefab/effects/Particle System.prefab.meta index 297c8371f1..db31b7361f 100644 --- a/editor/assets/default_prefab/effects/Particle System.prefab.meta +++ b/editor/assets/default_prefab/effects/Particle System.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "f09a0597-10e6-49e5-8759-a148b5e85395", diff --git a/editor/assets/default_prefab/light/Directional Light.prefab b/editor/assets/default_prefab/light/Directional Light.prefab index 2c6adde42c..49a581849c 100644 --- a/editor/assets/default_prefab/light/Directional Light.prefab +++ b/editor/assets/default_prefab/light/Directional Light.prefab @@ -76,7 +76,11 @@ "_id": "", "__prefab": { "__id__": 3 - } + }, + "_shadowFixedArea": false, + "_csmLevel": 4, + "_csmLayerLambda": 0.75, + "_csmOptimizationMode": 2 }, { "__type__": "cc.CompPrefabInfo", diff --git a/editor/assets/default_prefab/light/Directional Light.prefab.meta b/editor/assets/default_prefab/light/Directional Light.prefab.meta index c628544750..7034718420 100644 --- a/editor/assets/default_prefab/light/Directional Light.prefab.meta +++ b/editor/assets/default_prefab/light/Directional Light.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "a0e9756d-9128-4f49-8097-e041c8b733b8", diff --git a/editor/assets/default_prefab/light/Sphere Light.prefab.meta b/editor/assets/default_prefab/light/Sphere Light.prefab.meta index a838a97da8..5ce2bcdf49 100644 --- a/editor/assets/default_prefab/light/Sphere Light.prefab.meta +++ b/editor/assets/default_prefab/light/Sphere Light.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "4182ee46-ffa0-4de2-b66b-c93cc6c7e9b8", diff --git a/editor/assets/default_prefab/light/Spot Light.prefab.meta b/editor/assets/default_prefab/light/Spot Light.prefab.meta index 9de5a6b17d..5801e2545b 100644 --- a/editor/assets/default_prefab/light/Spot Light.prefab.meta +++ b/editor/assets/default_prefab/light/Spot Light.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "7a49aa24-bd7a-40a8-b31a-b2a9da85abcd", diff --git a/editor/assets/default_prefab/ui/Button.prefab.meta b/editor/assets/default_prefab/ui/Button.prefab.meta index b02cb3e78a..398c69f09b 100644 --- a/editor/assets/default_prefab/ui/Button.prefab.meta +++ b/editor/assets/default_prefab/ui/Button.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "90bdd2a9-2838-4888-b66c-e94c8b7a5169", diff --git a/editor/assets/default_prefab/ui/Canvas.prefab.meta b/editor/assets/default_prefab/ui/Canvas.prefab.meta index ddf7773a47..c64cc38c52 100644 --- a/editor/assets/default_prefab/ui/Canvas.prefab.meta +++ b/editor/assets/default_prefab/ui/Canvas.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "f773db21-62b8-4540-956a-29bacf5ddbf5", diff --git a/editor/assets/default_prefab/ui/EditBox.prefab.meta b/editor/assets/default_prefab/ui/EditBox.prefab.meta index 11d1d01ca6..30f845c7ec 100644 --- a/editor/assets/default_prefab/ui/EditBox.prefab.meta +++ b/editor/assets/default_prefab/ui/EditBox.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "05e79121-8675-4551-9ad7-1b901a4025db", diff --git a/editor/assets/default_prefab/ui/Graphics.prefab.meta b/editor/assets/default_prefab/ui/Graphics.prefab.meta index 0455bd1370..271902574e 100644 --- a/editor/assets/default_prefab/ui/Graphics.prefab.meta +++ b/editor/assets/default_prefab/ui/Graphics.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "c96e159e-43ea-4a16-8279-05bc39119d1a", diff --git a/editor/assets/default_prefab/ui/Label.prefab.meta b/editor/assets/default_prefab/ui/Label.prefab.meta index 5bd9b351e2..912236bd2e 100644 --- a/editor/assets/default_prefab/ui/Label.prefab.meta +++ b/editor/assets/default_prefab/ui/Label.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "36008810-7ad3-47c0-8112-e30aee089e45", diff --git a/editor/assets/default_prefab/ui/Layout.prefab.meta b/editor/assets/default_prefab/ui/Layout.prefab.meta index 5826bbdcf4..7c277649e1 100644 --- a/editor/assets/default_prefab/ui/Layout.prefab.meta +++ b/editor/assets/default_prefab/ui/Layout.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "a9ef7dfc-ea8b-4cf8-918e-36da948c4de0", diff --git a/editor/assets/default_prefab/ui/Mask.prefab.meta b/editor/assets/default_prefab/ui/Mask.prefab.meta index 67f06e860c..d6305572da 100644 --- a/editor/assets/default_prefab/ui/Mask.prefab.meta +++ b/editor/assets/default_prefab/ui/Mask.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "7fa63aed-f3e2-46a5-8a7c-c1a1adf6cea6", diff --git a/editor/assets/default_prefab/ui/ParticleSystem2D.prefab.meta b/editor/assets/default_prefab/ui/ParticleSystem2D.prefab.meta index 4c86660318..879d045f63 100644 --- a/editor/assets/default_prefab/ui/ParticleSystem2D.prefab.meta +++ b/editor/assets/default_prefab/ui/ParticleSystem2D.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "f396261e-3e06-41ec-bdd6-9a8b6d99026f", diff --git a/editor/assets/default_prefab/ui/ProgressBar.prefab.meta b/editor/assets/default_prefab/ui/ProgressBar.prefab.meta index 5fd7e80268..b43f5afb59 100644 --- a/editor/assets/default_prefab/ui/ProgressBar.prefab.meta +++ b/editor/assets/default_prefab/ui/ProgressBar.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "0d9353c4-6fb9-49bb-bc62-77f1750078c2", diff --git a/editor/assets/default_prefab/ui/RichText.prefab.meta b/editor/assets/default_prefab/ui/RichText.prefab.meta index 7b45e380fe..ecf7bc4323 100644 --- a/editor/assets/default_prefab/ui/RichText.prefab.meta +++ b/editor/assets/default_prefab/ui/RichText.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "fc6bfcfa-8086-4326-809b-0ba1226bac7d", diff --git a/editor/assets/default_prefab/ui/ScrollView.prefab.meta b/editor/assets/default_prefab/ui/ScrollView.prefab.meta index e347c512e1..bb27e18a4e 100644 --- a/editor/assets/default_prefab/ui/ScrollView.prefab.meta +++ b/editor/assets/default_prefab/ui/ScrollView.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "c1baa707-78d6-4b89-8d5d-0b7fdf0c39bc", diff --git a/editor/assets/default_prefab/ui/Slider.prefab.meta b/editor/assets/default_prefab/ui/Slider.prefab.meta index 411b9f770d..8b96c45e34 100644 --- a/editor/assets/default_prefab/ui/Slider.prefab.meta +++ b/editor/assets/default_prefab/ui/Slider.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "2bd7e5b6-cd8c-41a1-8136-ddb8efbf6326", diff --git a/editor/assets/default_prefab/ui/Sprite.prefab.meta b/editor/assets/default_prefab/ui/Sprite.prefab.meta index 218d70c106..68fb21cc8c 100644 --- a/editor/assets/default_prefab/ui/Sprite.prefab.meta +++ b/editor/assets/default_prefab/ui/Sprite.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "9db8cd0b-cbe4-42e7-96a9-a239620c0a9d", diff --git a/editor/assets/default_prefab/ui/SpriteRenderer.prefab b/editor/assets/default_prefab/ui/SpriteRenderer.prefab new file mode 100644 index 0000000000..33c6e24118 --- /dev/null +++ b/editor/assets/default_prefab/ui/SpriteRenderer.prefab @@ -0,0 +1,113 @@ +[ + { + "__type__": "cc.Prefab", + "_name": "SpriteRenderer", + "_objFlags": 0, + "_native": "", + "data": { + "__id__": 1 + }, + "optimizationPolicy": 0, + "persistent": false, + "asyncLoadAssets": false + }, + { + "__type__": "cc.Node", + "_name": "SpriteRenderer", + "_objFlags": 0, + "__editorExtras__": {}, + "_parent": null, + "_children": [], + "_active": true, + "_components": [ + { + "__id__": 2 + } + ], + "_prefab": { + "__id__": 4 + }, + "_lpos": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_lrot": { + "__type__": "cc.Quat", + "x": 0, + "y": 0, + "z": 0, + "w": 1 + }, + "_lscale": { + "__type__": "cc.Vec3", + "x": 1, + "y": 1, + "z": 1 + }, + "_layer": 1073741824, + "_euler": { + "__type__": "cc.Vec3", + "x": 0, + "y": 0, + "z": 0 + }, + "_id": "" + }, + { + "__type__": "cc.SpriteRenderer", + "_name": "", + "_objFlags": 0, + "node": { + "__id__": 1 + }, + "_enabled": true, + "__prefab": { + "__id__": 3 + }, + "_visFlags": 0, + "_materials": [ + { + "__uuid__": "ade8a15a-dcca-4b3c-84c6-f6476ac875bb", + "__expectedType__": "cc.Material" + } + ], + "_spriteFrame": { + "__uuid__": "57520716-48c8-4a19-8acf-41c9f8777fb0@f9941", + "__expectedType__": "cc.SpriteFrame" + }, + "_mode": 0, + "_color": { + "__type__": "cc.Color", + "r": 255, + "g": 255, + "b": 255, + "a": 255 + }, + "_flipX": false, + "_flipY": false, + "_size": { + "__type__": "cc.Vec2", + "x": 0, + "y": 0 + }, + "_sortLayer": 0, + "_sortOrder": 0, + "_id": "" + }, + { + "__type__": "cc.CompPrefabInfo", + "fileId": "d30sWvU11C1ZKZpLis93n8" + }, + { + "__type__": "cc.PrefabInfo", + "root": { + "__id__": 1 + }, + "asset": { + "__id__": 0 + }, + "fileId": "c9tzX97oVFgq0eglcSnA9i" + } +] \ No newline at end of file diff --git a/editor/assets/default_prefab/ui/SpriteRenderer.prefab.meta b/editor/assets/default_prefab/ui/SpriteRenderer.prefab.meta new file mode 100644 index 0000000000..5a7ae62cdd --- /dev/null +++ b/editor/assets/default_prefab/ui/SpriteRenderer.prefab.meta @@ -0,0 +1,13 @@ +{ + "ver": "1.1.39", + "importer": "prefab", + "imported": true, + "uuid": "279ed042-5a65-4efe-9afb-2fc23c61e15a", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": { + "syncNodeName": "SpriteRenderer" + } +} diff --git a/editor/assets/default_prefab/ui/SpriteSplash.prefab.meta b/editor/assets/default_prefab/ui/SpriteSplash.prefab.meta index 4987083297..1af8f23741 100644 --- a/editor/assets/default_prefab/ui/SpriteSplash.prefab.meta +++ b/editor/assets/default_prefab/ui/SpriteSplash.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "e5f21aad-3a69-4011-ac62-b74352ac025e", diff --git a/editor/assets/default_prefab/ui/TiledMap.prefab.meta b/editor/assets/default_prefab/ui/TiledMap.prefab.meta index 32e9b850d7..5ffcd258f7 100644 --- a/editor/assets/default_prefab/ui/TiledMap.prefab.meta +++ b/editor/assets/default_prefab/ui/TiledMap.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "3139fa4f-8c42-4ce6-98be-15e848d9734c", diff --git a/editor/assets/default_prefab/ui/Toggle.prefab.meta b/editor/assets/default_prefab/ui/Toggle.prefab.meta index 986f7207f7..167366e29b 100644 --- a/editor/assets/default_prefab/ui/Toggle.prefab.meta +++ b/editor/assets/default_prefab/ui/Toggle.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "0e89afe7-56de-4f99-96a1-cba8a75bedd2", diff --git a/editor/assets/default_prefab/ui/ToggleContainer.prefab.meta b/editor/assets/default_prefab/ui/ToggleContainer.prefab.meta index e250f78aae..b45baf3d8f 100644 --- a/editor/assets/default_prefab/ui/ToggleContainer.prefab.meta +++ b/editor/assets/default_prefab/ui/ToggleContainer.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "2af73429-41d1-4346-9062-7798e42945dd", diff --git a/editor/assets/default_prefab/ui/VideoPlayer.prefab.meta b/editor/assets/default_prefab/ui/VideoPlayer.prefab.meta index 830e398189..2c0732b677 100644 --- a/editor/assets/default_prefab/ui/VideoPlayer.prefab.meta +++ b/editor/assets/default_prefab/ui/VideoPlayer.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "7e089eaf-fa97-40d7-8a20-741a152585df", diff --git a/editor/assets/default_prefab/ui/WebView.prefab.meta b/editor/assets/default_prefab/ui/WebView.prefab.meta index 1af05b9eae..8083a278d9 100644 --- a/editor/assets/default_prefab/ui/WebView.prefab.meta +++ b/editor/assets/default_prefab/ui/WebView.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "9c541fa2-1dc8-4d8b-813a-aec89133f5b1", diff --git a/editor/assets/default_prefab/ui/Widget.prefab.meta b/editor/assets/default_prefab/ui/Widget.prefab.meta index 5783e4c2c0..0459e2ef5e 100644 --- a/editor/assets/default_prefab/ui/Widget.prefab.meta +++ b/editor/assets/default_prefab/ui/Widget.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "36ed4422-3542-4cc4-bf02-dc4bfc590836", diff --git a/editor/assets/default_prefab/ui/pageView.prefab.meta b/editor/assets/default_prefab/ui/pageView.prefab.meta index 8bcc6d1088..b029ba3d69 100644 --- a/editor/assets/default_prefab/ui/pageView.prefab.meta +++ b/editor/assets/default_prefab/ui/pageView.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.38", + "ver": "1.1.39", "importer": "prefab", "imported": true, "uuid": "20a5d8cb-ccad-4543-a937-fccd98c9f3de", diff --git a/editor/assets/default_skybox/default_skybox.hdr.meta b/editor/assets/default_skybox/default_skybox.hdr.meta index a445325933..faf7b6e215 100644 --- a/editor/assets/default_skybox/default_skybox.hdr.meta +++ b/editor/assets/default_skybox/default_skybox.hdr.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "d032ac98-05e1-4090-88bb-eb640dcb5fc1", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "b47c0": { @@ -40,8 +40,8 @@ "ver": "1.0.0", "imported": true, "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": {} }, @@ -55,8 +55,8 @@ "ver": "1.0.0", "imported": true, "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": {} }, @@ -70,8 +70,8 @@ "ver": "1.0.0", "imported": true, "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": {} }, @@ -85,8 +85,8 @@ "ver": "1.0.0", "imported": true, "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": {} }, @@ -100,8 +100,8 @@ "ver": "1.0.0", "imported": true, "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": {} }, @@ -115,8 +115,8 @@ "ver": "1.0.0", "imported": true, "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": {} } @@ -127,6 +127,7 @@ "type": "texture cube", "isRGBE": true, "hasAlpha": true, - "redirect": "d032ac98-05e1-4090-88bb-eb640dcb5fc1@b47c0" + "redirect": "d032ac98-05e1-4090-88bb-eb640dcb5fc1@b47c0", + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_skybox/default_skybox.png.meta b/editor/assets/default_skybox/default_skybox.png.meta index 638c642d40..a2ff05be73 100644 --- a/editor/assets/default_skybox/default_skybox.png.meta +++ b/editor/assets/default_skybox/default_skybox.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "6f01cf7f-81bf-4a7e-bd5d-0afc19696480", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "b47c0": { @@ -40,8 +40,8 @@ "ver": "1.0.0", "imported": true, "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": {} }, @@ -55,8 +55,8 @@ "ver": "1.0.0", "imported": true, "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": {} }, @@ -70,8 +70,8 @@ "ver": "1.0.0", "imported": true, "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": {} }, @@ -85,8 +85,8 @@ "ver": "1.0.0", "imported": true, "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": {} }, @@ -100,8 +100,8 @@ "ver": "1.0.0", "imported": true, "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": {} }, @@ -115,8 +115,8 @@ "ver": "1.0.0", "imported": true, "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": {} } @@ -126,6 +126,7 @@ "userData": { "hasAlpha": false, "type": "texture cube", - "redirect": "6f01cf7f-81bf-4a7e-bd5d-0afc19696480@b47c0" + "redirect": "6f01cf7f-81bf-4a7e-bd5d-0afc19696480@b47c0", + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/atom.plist.meta b/editor/assets/default_ui/atom.plist.meta index a680e02621..75929aa582 100644 --- a/editor/assets/default_ui/atom.plist.meta +++ b/editor/assets/default_ui/atom.plist.meta @@ -4,8 +4,8 @@ "imported": true, "uuid": "86f25d5c-9de5-454f-a5f9-ee16603e6701", "files": [ - ".plist", - ".json" + ".json", + ".plist" ], "subMetas": {}, "userData": { diff --git a/editor/assets/default_ui/atom.png.meta b/editor/assets/default_ui/atom.png.meta index 904a183ede..00f5422c2a 100644 --- a/editor/assets/default_ui/atom.png.meta +++ b/editor/assets/default_ui/atom.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "24c419ea-63a8-4ea1-a9d0-7fc469489bbc", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -22,7 +22,8 @@ "mipfilter": "none", "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "24c419ea-63a8-4ea1-a9d0-7fc469489bbc" + "imageUuidOrDatabaseUri": "24c419ea-63a8-4ea1-a9d0-7fc469489bbc", + "visible": false }, "ver": "1.0.22", "imported": true, @@ -56,9 +57,63 @@ "isUuid": true, "imageUuidOrDatabaseUri": "24c419ea-63a8-4ea1-a9d0-7fc469489bbc@6c48a", "atlasUuid": "", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -15.5, + -15.5, + 0, + 15.5, + -15.5, + 0, + -15.5, + 15.5, + 0, + 15.5, + 15.5, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 31, + 31, + 31, + 0, + 0, + 31, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -15.5, + -15.5, + 0 + ], + "maxPos": [ + 15.5, + 15.5, + 0 + ] + } }, - "ver": "1.0.10", + "ver": "1.0.11", "imported": true, "files": [ ".json" @@ -69,6 +124,7 @@ "userData": { "hasAlpha": true, "type": "sprite-frame", - "redirect": "24c419ea-63a8-4ea1-a9d0-7fc469489bbc@f9941" + "redirect": "24c419ea-63a8-4ea1-a9d0-7fc469489bbc@f9941", + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_btn_disabled.png.meta b/editor/assets/default_ui/default_btn_disabled.png.meta index d1913c08c5..129deb57d8 100644 --- a/editor/assets/default_ui/default_btn_disabled.png.meta +++ b/editor/assets/default_ui/default_btn_disabled.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "951249e0-9f16-456d-8b85-a6ca954da16b", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,14 +26,15 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "951249e0-9f16-456d-8b85-a6ca954da16b" + "imageUuidOrDatabaseUri": "951249e0-9f16-456d-8b85-a6ca954da16b", + "visible": false }, "displayName": "default_btn_disabled", "id": "6c48a", "name": "texture" }, "f9941": { - "ver": "1.0.10", + "ver": "1.0.11", "importer": "sprite-frame", "uuid": "951249e0-9f16-456d-8b85-a6ca954da16b@f9941", "imported": true, @@ -68,7 +69,61 @@ "imageUuidOrDatabaseUri": "951249e0-9f16-456d-8b85-a6ca954da16b@6c48a", "atlasUuid": "", "mipfilter": "none", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -20, + -20, + 0, + 20, + -20, + 0, + -20, + 20, + 0, + 20, + 20, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 40, + 40, + 40, + 0, + 0, + 40, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -20, + -20, + 0 + ], + "maxPos": [ + 20, + 20, + 0 + ] + } }, "displayName": "default_btn_disabled", "id": "f9941", @@ -78,6 +133,7 @@ "userData": { "type": "sprite-frame", "redirect": "951249e0-9f16-456d-8b85-a6ca954da16b@f9941", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_btn_normal.png.meta b/editor/assets/default_ui/default_btn_normal.png.meta index cd89bbdefd..83e0f37685 100644 --- a/editor/assets/default_ui/default_btn_normal.png.meta +++ b/editor/assets/default_ui/default_btn_normal.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "20835ba4-6145-4fbc-a58a-051ce700aa3e", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,14 +26,15 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "20835ba4-6145-4fbc-a58a-051ce700aa3e" + "imageUuidOrDatabaseUri": "20835ba4-6145-4fbc-a58a-051ce700aa3e", + "visible": false }, "displayName": "default_btn_normal", "id": "6c48a", "name": "texture" }, "f9941": { - "ver": "1.0.10", + "ver": "1.0.11", "importer": "sprite-frame", "uuid": "20835ba4-6145-4fbc-a58a-051ce700aa3e@f9941", "imported": true, @@ -68,7 +69,61 @@ "imageUuidOrDatabaseUri": "20835ba4-6145-4fbc-a58a-051ce700aa3e@6c48a", "atlasUuid": "", "mipfilter": "none", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -20, + -20, + 0, + 20, + -20, + 0, + -20, + 20, + 0, + 20, + 20, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 40, + 40, + 40, + 0, + 0, + 40, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -20, + -20, + 0 + ], + "maxPos": [ + 20, + 20, + 0 + ] + } }, "displayName": "default_btn_normal", "id": "f9941", @@ -78,6 +133,7 @@ "userData": { "type": "sprite-frame", "redirect": "20835ba4-6145-4fbc-a58a-051ce700aa3e@f9941", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_btn_pressed.png.meta b/editor/assets/default_ui/default_btn_pressed.png.meta index 978874fb73..8e74d199ca 100644 --- a/editor/assets/default_ui/default_btn_pressed.png.meta +++ b/editor/assets/default_ui/default_btn_pressed.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "544e49d6-3f05-4fa8-9a9e-091f98fc2ce8", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,14 +26,15 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "544e49d6-3f05-4fa8-9a9e-091f98fc2ce8" + "imageUuidOrDatabaseUri": "544e49d6-3f05-4fa8-9a9e-091f98fc2ce8", + "visible": false }, "displayName": "default_btn_pressed", "id": "6c48a", "name": "texture" }, "f9941": { - "ver": "1.0.10", + "ver": "1.0.11", "importer": "sprite-frame", "uuid": "544e49d6-3f05-4fa8-9a9e-091f98fc2ce8@f9941", "imported": true, @@ -68,7 +69,61 @@ "imageUuidOrDatabaseUri": "544e49d6-3f05-4fa8-9a9e-091f98fc2ce8@6c48a", "atlasUuid": "", "mipfilter": "none", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -20, + -20, + 0, + 20, + -20, + 0, + -20, + 20, + 0, + 20, + 20, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 40, + 40, + 40, + 0, + 0, + 40, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -20, + -20, + 0 + ], + "maxPos": [ + 20, + 20, + 0 + ] + } }, "displayName": "default_btn_pressed", "id": "f9941", @@ -78,6 +133,7 @@ "userData": { "type": "sprite-frame", "redirect": "544e49d6-3f05-4fa8-9a9e-091f98fc2ce8@f9941", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_editbox_bg.png.meta b/editor/assets/default_ui/default_editbox_bg.png.meta index 5f06b039a8..934855ed58 100644 --- a/editor/assets/default_ui/default_editbox_bg.png.meta +++ b/editor/assets/default_ui/default_editbox_bg.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "bd1bcaba-bd7d-4a71-b143-997c882383e4", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,14 +26,15 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "bd1bcaba-bd7d-4a71-b143-997c882383e4" + "imageUuidOrDatabaseUri": "bd1bcaba-bd7d-4a71-b143-997c882383e4", + "visible": false }, "displayName": "default_editbox_bg", "id": "6c48a", "name": "texture" }, "f9941": { - "ver": "1.0.10", + "ver": "1.0.11", "importer": "sprite-frame", "uuid": "bd1bcaba-bd7d-4a71-b143-997c882383e4@f9941", "imported": true, @@ -68,7 +69,61 @@ "imageUuidOrDatabaseUri": "bd1bcaba-bd7d-4a71-b143-997c882383e4@6c48a", "atlasUuid": "", "mipfilter": "none", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -20, + -20, + 0, + 20, + -20, + 0, + -20, + 20, + 0, + 20, + 20, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 40, + 40, + 40, + 0, + 0, + 40, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -20, + -20, + 0 + ], + "maxPos": [ + 20, + 20, + 0 + ] + } }, "displayName": "default_editbox_bg", "id": "f9941", @@ -78,6 +133,7 @@ "userData": { "type": "sprite-frame", "redirect": "bd1bcaba-bd7d-4a71-b143-997c882383e4@f9941", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_panel.png.meta b/editor/assets/default_ui/default_panel.png.meta index ef299c4647..0ee011206a 100644 --- a/editor/assets/default_ui/default_panel.png.meta +++ b/editor/assets/default_ui/default_panel.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "b730527c-3233-41c2-aaf7-7cdab58f9749", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,14 +26,15 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "b730527c-3233-41c2-aaf7-7cdab58f9749" + "imageUuidOrDatabaseUri": "b730527c-3233-41c2-aaf7-7cdab58f9749", + "visible": false }, "displayName": "default_panel", "id": "6c48a", "name": "texture" }, "f9941": { - "ver": "1.0.10", + "ver": "1.0.11", "importer": "sprite-frame", "uuid": "b730527c-3233-41c2-aaf7-7cdab58f9749@f9941", "imported": true, @@ -68,7 +69,61 @@ "imageUuidOrDatabaseUri": "b730527c-3233-41c2-aaf7-7cdab58f9749@6c48a", "atlasUuid": "", "mipfilter": "none", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -10, + -10, + 0, + 10, + -10, + 0, + -10, + 10, + 0, + 10, + 10, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 20, + 20, + 20, + 0, + 0, + 20, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -10, + -10, + 0 + ], + "maxPos": [ + 10, + 10, + 0 + ] + } }, "displayName": "default_panel", "id": "f9941", @@ -78,6 +133,7 @@ "userData": { "type": "sprite-frame", "redirect": "b730527c-3233-41c2-aaf7-7cdab58f9749@f9941", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_progressbar.png.meta b/editor/assets/default_ui/default_progressbar.png.meta index d2ddbd964f..908a212144 100644 --- a/editor/assets/default_ui/default_progressbar.png.meta +++ b/editor/assets/default_ui/default_progressbar.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "24a704da-2867-446d-8d1a-5e920c75e09d", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,14 +26,15 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "24a704da-2867-446d-8d1a-5e920c75e09d" + "imageUuidOrDatabaseUri": "24a704da-2867-446d-8d1a-5e920c75e09d", + "visible": false }, "displayName": "default_progressbar", "id": "6c48a", "name": "texture" }, "f9941": { - "ver": "1.0.10", + "ver": "1.0.11", "importer": "sprite-frame", "uuid": "24a704da-2867-446d-8d1a-5e920c75e09d@f9941", "imported": true, @@ -68,7 +69,61 @@ "imageUuidOrDatabaseUri": "24a704da-2867-446d-8d1a-5e920c75e09d@6c48a", "atlasUuid": "", "mipfilter": "none", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -15, + -7.5, + 0, + 15, + -7.5, + 0, + -15, + 7.5, + 0, + 15, + 7.5, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 15, + 30, + 15, + 0, + 0, + 30, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -15, + -7.5, + 0 + ], + "maxPos": [ + 15, + 7.5, + 0 + ] + } }, "displayName": "default_progressbar", "id": "f9941", @@ -78,6 +133,7 @@ "userData": { "type": "sprite-frame", "redirect": "24a704da-2867-446d-8d1a-5e920c75e09d@f9941", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_progressbar_bg.png.meta b/editor/assets/default_ui/default_progressbar_bg.png.meta index bffa297c9d..a48c4ed82e 100644 --- a/editor/assets/default_ui/default_progressbar_bg.png.meta +++ b/editor/assets/default_ui/default_progressbar_bg.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "9fd900dd-221b-4f89-8f2c-fba34243c835", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,14 +26,15 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "9fd900dd-221b-4f89-8f2c-fba34243c835" + "imageUuidOrDatabaseUri": "9fd900dd-221b-4f89-8f2c-fba34243c835", + "visible": false }, "displayName": "default_progressbar_bg", "id": "6c48a", "name": "texture" }, "f9941": { - "ver": "1.0.10", + "ver": "1.0.11", "importer": "sprite-frame", "uuid": "9fd900dd-221b-4f89-8f2c-fba34243c835@f9941", "imported": true, @@ -68,7 +69,61 @@ "imageUuidOrDatabaseUri": "9fd900dd-221b-4f89-8f2c-fba34243c835@6c48a", "atlasUuid": "", "mipfilter": "none", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -30, + -7.5, + 0, + 30, + -7.5, + 0, + -30, + 7.5, + 0, + 30, + 7.5, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 15, + 60, + 15, + 0, + 0, + 60, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -30, + -7.5, + 0 + ], + "maxPos": [ + 30, + 7.5, + 0 + ] + } }, "displayName": "default_progressbar_bg", "id": "f9941", @@ -78,6 +133,7 @@ "userData": { "type": "sprite-frame", "redirect": "9fd900dd-221b-4f89-8f2c-fba34243c835@f9941", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_radio_button_off.png.meta b/editor/assets/default_ui/default_radio_button_off.png.meta index 54445ccf36..895d35ea00 100644 --- a/editor/assets/default_ui/default_radio_button_off.png.meta +++ b/editor/assets/default_ui/default_radio_button_off.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "f12a23c4-b924-4322-a260-3d982428f1e8", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,14 +26,15 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "f12a23c4-b924-4322-a260-3d982428f1e8" + "imageUuidOrDatabaseUri": "f12a23c4-b924-4322-a260-3d982428f1e8", + "visible": false }, "displayName": "default_radio_button_off", "id": "6c48a", "name": "texture" }, "f9941": { - "ver": "1.0.10", + "ver": "1.0.11", "importer": "sprite-frame", "uuid": "f12a23c4-b924-4322-a260-3d982428f1e8@f9941", "imported": true, @@ -68,7 +69,61 @@ "imageUuidOrDatabaseUri": "f12a23c4-b924-4322-a260-3d982428f1e8@6c48a", "atlasUuid": "", "mipfilter": "none", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -13, + -13, + 0, + 13, + -13, + 0, + -13, + 13, + 0, + 13, + 13, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 3, + 29, + 29, + 29, + 3, + 3, + 29, + 3 + ], + "nuv": [ + 0.09375, + 0.09375, + 0.90625, + 0.09375, + 0.09375, + 0.90625, + 0.90625, + 0.90625 + ], + "minPos": [ + -13, + -13, + 0 + ], + "maxPos": [ + 13, + 13, + 0 + ] + } }, "displayName": "default_radio_button_off", "id": "f9941", @@ -78,6 +133,7 @@ "userData": { "type": "sprite-frame", "redirect": "f12a23c4-b924-4322-a260-3d982428f1e8@f9941", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_radio_button_on.png.meta b/editor/assets/default_ui/default_radio_button_on.png.meta index be518e209b..d5d81a6619 100644 --- a/editor/assets/default_ui/default_radio_button_on.png.meta +++ b/editor/assets/default_ui/default_radio_button_on.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "45828f25-b50d-4c52-a591-e19491a62b8c", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,14 +26,15 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "45828f25-b50d-4c52-a591-e19491a62b8c" + "imageUuidOrDatabaseUri": "45828f25-b50d-4c52-a591-e19491a62b8c", + "visible": false }, "displayName": "default_radio_button_on", "id": "6c48a", "name": "texture" }, "f9941": { - "ver": "1.0.10", + "ver": "1.0.11", "importer": "sprite-frame", "uuid": "45828f25-b50d-4c52-a591-e19491a62b8c@f9941", "imported": true, @@ -68,7 +69,61 @@ "imageUuidOrDatabaseUri": "45828f25-b50d-4c52-a591-e19491a62b8c@6c48a", "atlasUuid": "", "mipfilter": "none", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -15, + -15, + 0, + 15, + -15, + 0, + -15, + 15, + 0, + 15, + 15, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 1, + 31, + 31, + 31, + 1, + 1, + 31, + 1 + ], + "nuv": [ + 0.03125, + 0.03125, + 0.96875, + 0.03125, + 0.03125, + 0.96875, + 0.96875, + 0.96875 + ], + "minPos": [ + -15, + -15, + 0 + ], + "maxPos": [ + 15, + 15, + 0 + ] + } }, "displayName": "default_radio_button_on", "id": "f9941", @@ -78,6 +133,7 @@ "userData": { "type": "sprite-frame", "redirect": "45828f25-b50d-4c52-a591-e19491a62b8c@f9941", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_scrollbar.png.meta b/editor/assets/default_ui/default_scrollbar.png.meta index 240bd1fd2b..8a4913269d 100644 --- a/editor/assets/default_ui/default_scrollbar.png.meta +++ b/editor/assets/default_ui/default_scrollbar.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "0da256a2-21f6-481b-90b6-d3643a09179b", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,14 +26,15 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "0da256a2-21f6-481b-90b6-d3643a09179b" + "imageUuidOrDatabaseUri": "0da256a2-21f6-481b-90b6-d3643a09179b", + "visible": false }, "displayName": "default_scrollbar", "id": "6c48a", "name": "texture" }, "f9941": { - "ver": "1.0.10", + "ver": "1.0.11", "importer": "sprite-frame", "uuid": "0da256a2-21f6-481b-90b6-d3643a09179b@f9941", "imported": true, @@ -68,7 +69,61 @@ "imageUuidOrDatabaseUri": "0da256a2-21f6-481b-90b6-d3643a09179b@6c48a", "atlasUuid": "", "mipfilter": "none", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -15, + -7.5, + 0, + 15, + -7.5, + 0, + -15, + 7.5, + 0, + 15, + 7.5, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 15, + 30, + 15, + 0, + 0, + 30, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -15, + -7.5, + 0 + ], + "maxPos": [ + 15, + 7.5, + 0 + ] + } }, "displayName": "default_scrollbar", "id": "f9941", @@ -78,6 +133,7 @@ "userData": { "type": "sprite-frame", "redirect": "0da256a2-21f6-481b-90b6-d3643a09179b@f9941", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_scrollbar_bg.png.meta b/editor/assets/default_ui/default_scrollbar_bg.png.meta index 05f2200321..b76517c577 100644 --- a/editor/assets/default_ui/default_scrollbar_bg.png.meta +++ b/editor/assets/default_ui/default_scrollbar_bg.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "28765e2f-040a-4c65-8e8c-f9d0bb79d863", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,14 +26,15 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "28765e2f-040a-4c65-8e8c-f9d0bb79d863" + "imageUuidOrDatabaseUri": "28765e2f-040a-4c65-8e8c-f9d0bb79d863", + "visible": false }, "displayName": "default_scrollbar_bg", "id": "6c48a", "name": "texture" }, "f9941": { - "ver": "1.0.10", + "ver": "1.0.11", "importer": "sprite-frame", "uuid": "28765e2f-040a-4c65-8e8c-f9d0bb79d863@f9941", "imported": true, @@ -68,7 +69,61 @@ "imageUuidOrDatabaseUri": "28765e2f-040a-4c65-8e8c-f9d0bb79d863@6c48a", "atlasUuid": "", "mipfilter": "none", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -15, + -7.5, + 0, + 15, + -7.5, + 0, + -15, + 7.5, + 0, + 15, + 7.5, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 15, + 30, + 15, + 0, + 0, + 30, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -15, + -7.5, + 0 + ], + "maxPos": [ + 15, + 7.5, + 0 + ] + } }, "displayName": "default_scrollbar_bg", "id": "f9941", @@ -78,6 +133,7 @@ "userData": { "type": "sprite-frame", "redirect": "28765e2f-040a-4c65-8e8c-f9d0bb79d863@f9941", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_scrollbar_vertical.png.meta b/editor/assets/default_ui/default_scrollbar_vertical.png.meta index d82049ce9a..8581ec0295 100644 --- a/editor/assets/default_ui/default_scrollbar_vertical.png.meta +++ b/editor/assets/default_ui/default_scrollbar_vertical.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "afc47931-f066-46b0-90be-9fe61f213428", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,14 +26,15 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "afc47931-f066-46b0-90be-9fe61f213428" + "imageUuidOrDatabaseUri": "afc47931-f066-46b0-90be-9fe61f213428", + "visible": false }, "displayName": "default_scrollbar_vertical", "id": "6c48a", "name": "texture" }, "f9941": { - "ver": "1.0.10", + "ver": "1.0.11", "importer": "sprite-frame", "uuid": "afc47931-f066-46b0-90be-9fe61f213428@f9941", "imported": true, @@ -68,7 +69,61 @@ "imageUuidOrDatabaseUri": "afc47931-f066-46b0-90be-9fe61f213428@6c48a", "atlasUuid": "", "mipfilter": "none", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -7.5, + -15, + 0, + 7.5, + -15, + 0, + -7.5, + 15, + 0, + 7.5, + 15, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 30, + 15, + 30, + 0, + 0, + 15, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -7.5, + -15, + 0 + ], + "maxPos": [ + 7.5, + 15, + 0 + ] + } }, "displayName": "default_scrollbar_vertical", "id": "f9941", @@ -78,6 +133,7 @@ "userData": { "type": "sprite-frame", "redirect": "afc47931-f066-46b0-90be-9fe61f213428@f9941", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_scrollbar_vertical_bg.png.meta b/editor/assets/default_ui/default_scrollbar_vertical_bg.png.meta index 02b91b9288..d0ea273735 100644 --- a/editor/assets/default_ui/default_scrollbar_vertical_bg.png.meta +++ b/editor/assets/default_ui/default_scrollbar_vertical_bg.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "ffb88a8f-af62-48f4-8f1d-3cb606443a43", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,14 +26,15 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "ffb88a8f-af62-48f4-8f1d-3cb606443a43" + "imageUuidOrDatabaseUri": "ffb88a8f-af62-48f4-8f1d-3cb606443a43", + "visible": false }, "displayName": "default_scrollbar_vertical_bg", "id": "6c48a", "name": "texture" }, "f9941": { - "ver": "1.0.10", + "ver": "1.0.11", "importer": "sprite-frame", "uuid": "ffb88a8f-af62-48f4-8f1d-3cb606443a43@f9941", "imported": true, @@ -68,7 +69,61 @@ "imageUuidOrDatabaseUri": "ffb88a8f-af62-48f4-8f1d-3cb606443a43@6c48a", "atlasUuid": "", "mipfilter": "none", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -7.5, + -15, + 0, + 7.5, + -15, + 0, + -7.5, + 15, + 0, + 7.5, + 15, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 30, + 15, + 30, + 0, + 0, + 15, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -7.5, + -15, + 0 + ], + "maxPos": [ + 7.5, + 15, + 0 + ] + } }, "displayName": "default_scrollbar_vertical_bg", "id": "f9941", @@ -78,6 +133,7 @@ "userData": { "type": "sprite-frame", "redirect": "ffb88a8f-af62-48f4-8f1d-3cb606443a43@f9941", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_sprite.png.meta b/editor/assets/default_ui/default_sprite.png.meta index ea3e6eb5b8..46846d159f 100644 --- a/editor/assets/default_ui/default_sprite.png.meta +++ b/editor/assets/default_ui/default_sprite.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "57520716-48c8-4a19-8acf-41c9f8777fb0", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,14 +26,15 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "57520716-48c8-4a19-8acf-41c9f8777fb0" + "imageUuidOrDatabaseUri": "57520716-48c8-4a19-8acf-41c9f8777fb0", + "visible": false }, "displayName": "default_sprite", "id": "6c48a", "name": "texture" }, "f9941": { - "ver": "1.0.10", + "ver": "1.0.11", "importer": "sprite-frame", "uuid": "57520716-48c8-4a19-8acf-41c9f8777fb0@f9941", "imported": true, @@ -68,7 +69,61 @@ "imageUuidOrDatabaseUri": "57520716-48c8-4a19-8acf-41c9f8777fb0@6c48a", "atlasUuid": "", "mipfilter": "none", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -20, + -18, + 0, + 20, + -18, + 0, + -20, + 18, + 0, + 20, + 18, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 38, + 40, + 38, + 0, + 2, + 40, + 2 + ], + "nuv": [ + 0, + 0.05, + 1, + 0.05, + 0, + 0.95, + 1, + 0.95 + ], + "minPos": [ + -20, + -18, + 0 + ], + "maxPos": [ + 20, + 18, + 0 + ] + } }, "displayName": "default_sprite", "id": "f9941", @@ -78,6 +133,7 @@ "userData": { "type": "sprite-frame", "redirect": "57520716-48c8-4a19-8acf-41c9f8777fb0@f9941", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_sprite_splash.png.meta b/editor/assets/default_ui/default_sprite_splash.png.meta index b3cdc21255..6ce37c02fe 100644 --- a/editor/assets/default_ui/default_sprite_splash.png.meta +++ b/editor/assets/default_ui/default_sprite_splash.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "7d8f9b89-4fd1-4c9f-a3ab-38ec7cded7ca", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,14 +26,15 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "7d8f9b89-4fd1-4c9f-a3ab-38ec7cded7ca" + "imageUuidOrDatabaseUri": "7d8f9b89-4fd1-4c9f-a3ab-38ec7cded7ca", + "visible": false }, "displayName": "default_sprite_splash", "id": "6c48a", "name": "texture" }, "f9941": { - "ver": "1.0.10", + "ver": "1.0.11", "importer": "sprite-frame", "uuid": "7d8f9b89-4fd1-4c9f-a3ab-38ec7cded7ca@f9941", "imported": true, @@ -68,7 +69,61 @@ "imageUuidOrDatabaseUri": "7d8f9b89-4fd1-4c9f-a3ab-38ec7cded7ca@6c48a", "atlasUuid": "", "mipfilter": "none", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -1, + -1, + 0, + 1, + -1, + 0, + -1, + 1, + 0, + 1, + 1, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 2, + 2, + 2, + 0, + 0, + 2, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -1, + -1, + 0 + ], + "maxPos": [ + 1, + 1, + 0 + ] + } }, "displayName": "default_sprite_splash", "id": "f9941", @@ -78,6 +133,7 @@ "userData": { "type": "sprite-frame", "redirect": "7d8f9b89-4fd1-4c9f-a3ab-38ec7cded7ca@f9941", - "hasAlpha": false + "hasAlpha": false, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_toggle_checkmark.png.meta b/editor/assets/default_ui/default_toggle_checkmark.png.meta index a70fd49a5b..4882c07993 100644 --- a/editor/assets/default_ui/default_toggle_checkmark.png.meta +++ b/editor/assets/default_ui/default_toggle_checkmark.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "158e7e52-3220-4cd7-9694-713e0e6e8278", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,14 +26,15 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "158e7e52-3220-4cd7-9694-713e0e6e8278" + "imageUuidOrDatabaseUri": "158e7e52-3220-4cd7-9694-713e0e6e8278", + "visible": false }, "displayName": "default_toggle_checkmark", "id": "6c48a", "name": "texture" }, "f9941": { - "ver": "1.0.10", + "ver": "1.0.11", "importer": "sprite-frame", "uuid": "158e7e52-3220-4cd7-9694-713e0e6e8278@f9941", "imported": true, @@ -68,7 +69,61 @@ "imageUuidOrDatabaseUri": "158e7e52-3220-4cd7-9694-713e0e6e8278@6c48a", "atlasUuid": "", "mipfilter": "none", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -10, + -9, + 0, + 10, + -9, + 0, + -10, + 9, + 0, + 10, + 9, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 4, + 23, + 24, + 23, + 4, + 5, + 24, + 5 + ], + "nuv": [ + 0.14285714285714285, + 0.17857142857142858, + 0.8571428571428571, + 0.17857142857142858, + 0.14285714285714285, + 0.8214285714285714, + 0.8571428571428571, + 0.8214285714285714 + ], + "minPos": [ + -10, + -9, + 0 + ], + "maxPos": [ + 10, + 9, + 0 + ] + } }, "displayName": "default_toggle_checkmark", "id": "f9941", @@ -78,6 +133,7 @@ "userData": { "type": "sprite-frame", "redirect": "158e7e52-3220-4cd7-9694-713e0e6e8278@f9941", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_toggle_disabled.png.meta b/editor/assets/default_ui/default_toggle_disabled.png.meta index 44e176c965..4992203dd7 100644 --- a/editor/assets/default_ui/default_toggle_disabled.png.meta +++ b/editor/assets/default_ui/default_toggle_disabled.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "ca7e121b-293c-4763-829a-b7a5fa81f0d2", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,7 +26,8 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "ca7e121b-293c-4763-829a-b7a5fa81f0d2" + "imageUuidOrDatabaseUri": "ca7e121b-293c-4763-829a-b7a5fa81f0d2", + "visible": true }, "displayName": "default_toggle_disabled", "id": "6c48a", @@ -36,6 +37,7 @@ "userData": { "type": "texture", "redirect": "ca7e121b-293c-4763-829a-b7a5fa81f0d2@6c48a", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_toggle_normal.png.meta b/editor/assets/default_ui/default_toggle_normal.png.meta index 891c01ccf5..65b426ad8a 100644 --- a/editor/assets/default_ui/default_toggle_normal.png.meta +++ b/editor/assets/default_ui/default_toggle_normal.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "11bdc4b0-64a8-4eb7-a2a7-9fb9e233e977", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,14 +26,15 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "11bdc4b0-64a8-4eb7-a2a7-9fb9e233e977" + "imageUuidOrDatabaseUri": "11bdc4b0-64a8-4eb7-a2a7-9fb9e233e977", + "visible": false }, "displayName": "default_toggle_normal", "id": "6c48a", "name": "texture" }, "f9941": { - "ver": "1.0.10", + "ver": "1.0.11", "importer": "sprite-frame", "uuid": "11bdc4b0-64a8-4eb7-a2a7-9fb9e233e977@f9941", "imported": true, @@ -68,7 +69,61 @@ "imageUuidOrDatabaseUri": "11bdc4b0-64a8-4eb7-a2a7-9fb9e233e977@6c48a", "atlasUuid": "", "mipfilter": "none", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -14, + -14, + 0, + 14, + -14, + 0, + -14, + 14, + 0, + 14, + 14, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 28, + 28, + 28, + 0, + 0, + 28, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -14, + -14, + 0 + ], + "maxPos": [ + 14, + 14, + 0 + ] + } }, "displayName": "default_toggle_normal", "id": "f9941", @@ -78,6 +133,7 @@ "userData": { "type": "sprite-frame", "redirect": "11bdc4b0-64a8-4eb7-a2a7-9fb9e233e977@f9941", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/default_ui/default_toggle_pressed.png.meta b/editor/assets/default_ui/default_toggle_pressed.png.meta index a0368421d7..a32f1d1d8a 100644 --- a/editor/assets/default_ui/default_toggle_pressed.png.meta +++ b/editor/assets/default_ui/default_toggle_pressed.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "a04e994f-ee49-47b6-9d08-2f59e3773fcc", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,14 +26,15 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "a04e994f-ee49-47b6-9d08-2f59e3773fcc" + "imageUuidOrDatabaseUri": "a04e994f-ee49-47b6-9d08-2f59e3773fcc", + "visible": false }, "displayName": "default_toggle_pressed", "id": "6c48a", "name": "texture" }, "f9941": { - "ver": "1.0.10", + "ver": "1.0.11", "importer": "sprite-frame", "uuid": "a04e994f-ee49-47b6-9d08-2f59e3773fcc@f9941", "imported": true, @@ -68,7 +69,61 @@ "imageUuidOrDatabaseUri": "a04e994f-ee49-47b6-9d08-2f59e3773fcc@6c48a", "atlasUuid": "", "mipfilter": "none", - "packable": true + "packable": true, + "vertices": { + "rawPosition": [ + -14, + -14, + 0, + 14, + -14, + 0, + -14, + 14, + 0, + 14, + 14, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 0, + 28, + 28, + 28, + 0, + 0, + 28, + 0 + ], + "nuv": [ + 0, + 0, + 1, + 0, + 0, + 1, + 1, + 1 + ], + "minPos": [ + -14, + -14, + 0 + ], + "maxPos": [ + 14, + 14, + 0 + ] + } }, "displayName": "default_toggle_pressed", "id": "f9941", @@ -78,6 +133,7 @@ "userData": { "type": "sprite-frame", "redirect": "a04e994f-ee49-47b6-9d08-2f59e3773fcc@f9941", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/effects/builtin-billboard.effect b/editor/assets/effects/builtin-billboard.effect index eaae4daa76..ac98142cd9 100644 --- a/editor/assets/effects/builtin-billboard.effect +++ b/editor/assets/effects/builtin-billboard.effect @@ -70,7 +70,7 @@ CCEffect %{ CCProgram vert %{ precision mediump float; - #include + #include #pragma define CC_RENDER_MODE RENDER_MODE_BILLBOARD in vec3 a_position; // center position in vec2 a_texCoord; // texcoord @@ -96,7 +96,7 @@ CCProgram vert %{ CCProgram tinted-fs %{ precision mediump float; - #include + #include in vec2 uv; in vec4 color; @@ -122,7 +122,7 @@ CCProgram tinted-fs %{ CCProgram no-tint-fs %{ precision mediump float; - #include + #include in vec2 uv; in vec4 color; diff --git a/editor/assets/effects/builtin-billboard.effect.meta b/editor/assets/effects/builtin-billboard.effect.meta index 2ad0f26f28..0330371d48 100644 --- a/editor/assets/effects/builtin-billboard.effect.meta +++ b/editor/assets/effects/builtin-billboard.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "711ebe11-f673-4cd9-9a83-63c60ba54c5b", diff --git a/editor/assets/effects/builtin-camera-texture.effect b/editor/assets/effects/builtin-camera-texture.effect index d75d449d08..9c320a38d4 100644 --- a/editor/assets/effects/builtin-camera-texture.effect +++ b/editor/assets/effects/builtin-camera-texture.effect @@ -64,10 +64,11 @@ CCEffect %{ CCProgram camera-texture-vs %{ precision highp float; - #include - #include - #include - #include + #include + #include + #include + #include + #include #if USE_VERTEX_COLOR in lowp vec4 a_color; @@ -105,7 +106,7 @@ CCProgram camera-texture-vs %{ CCProgram camera-texture-fs %{ precision highp float; - #include + #include #if USE_ALPHA_TEST #pragma define-meta ALPHA_TEST_CHANNEL options([a, r, g, b]) diff --git a/editor/assets/effects/builtin-camera-texture.effect.meta b/editor/assets/effects/builtin-camera-texture.effect.meta index 3122e90ef8..c1306a4724 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.2", + "ver": "1.5.7", "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 30a9ec815b..3bad34afcb 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.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "810e96e4-e456-4468-9b59-f4e8f39732c0", diff --git a/editor/assets/effects/builtin-debug-renderer.effect b/editor/assets/effects/builtin-debug-renderer.effect index d619e65d98..d58588debb 100644 --- a/editor/assets/effects/builtin-debug-renderer.effect +++ b/editor/assets/effects/builtin-debug-renderer.effect @@ -20,8 +20,8 @@ CCEffect %{ CCProgram debug-renderer-vs %{ precision mediump float; - #include - #include + #include + #include in vec2 a_position; in vec2 a_texCoord; @@ -60,7 +60,7 @@ CCProgram debug-renderer-vs %{ CCProgram debug-renderer-fs %{ precision mediump float; - #include + #include in vec2 v_texCoord; in vec4 v_color; diff --git a/editor/assets/effects/builtin-debug-renderer.effect.meta b/editor/assets/effects/builtin-debug-renderer.effect.meta index 419da0e7d5..100aa99380 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.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "ff9be190-20a4-4e48-b68c-76e3c7cff085", diff --git a/editor/assets/effects/builtin-geometry-renderer.effect b/editor/assets/effects/builtin-geometry-renderer.effect index e53f3dd072..9fac791a46 100644 --- a/editor/assets/effects/builtin-geometry-renderer.effect +++ b/editor/assets/effects/builtin-geometry-renderer.effect @@ -101,7 +101,7 @@ CCEffect %{ CCProgram line-vs %{ precision mediump float; - #include + #include in highp vec3 a_position; in vec4 a_color; @@ -120,7 +120,7 @@ CCProgram line-vs %{ CCProgram line-fs %{ precision mediump float; - #include + #include in vec4 v_color; @@ -143,7 +143,7 @@ CCProgram line-fs %{ CCProgram dashed-line-vs %{ precision mediump float; - #include + #include in highp vec3 a_position; in vec4 a_color; @@ -164,7 +164,7 @@ CCProgram dashed-line-vs %{ CCProgram dashed-line-fs %{ precision mediump float; - #include + #include in vec4 v_color; in float v_distance; @@ -196,7 +196,7 @@ CCProgram dashed-line-fs %{ CCProgram triangle-vs %{ precision mediump float; - #include + #include in highp vec3 a_position; in vec4 a_normal; @@ -219,7 +219,7 @@ CCProgram triangle-vs %{ CCProgram triangle-fs %{ precision mediump float; - #include + #include in vec4 v_color; diff --git a/editor/assets/effects/builtin-geometry-renderer.effect.meta b/editor/assets/effects/builtin-geometry-renderer.effect.meta index d1abcc561a..229c4ccaec 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.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "4bb480dd-8384-4bc9-987f-de67cc53052a", diff --git a/editor/assets/effects/builtin-graphics.effect b/editor/assets/effects/builtin-graphics.effect index 9f733f0774..4eb6f75d33 100644 --- a/editor/assets/effects/builtin-graphics.effect +++ b/editor/assets/effects/builtin-graphics.effect @@ -22,8 +22,8 @@ CCEffect %{ CCProgram vs %{ precision highp float; - #include - #include + #include + #include in vec3 a_position; diff --git a/editor/assets/effects/builtin-graphics.effect.meta b/editor/assets/effects/builtin-graphics.effect.meta index 1eaef1034f..7a96ca66ad 100644 --- a/editor/assets/effects/builtin-graphics.effect.meta +++ b/editor/assets/effects/builtin-graphics.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "1c02ae6f-4492-4915-b8f8-7492a3b1e4cd", diff --git a/editor/assets/effects/builtin-occlusion-query.effect b/editor/assets/effects/builtin-occlusion-query.effect index 11679830ed..71d50e9502 100644 --- a/editor/assets/effects/builtin-occlusion-query.effect +++ b/editor/assets/effects/builtin-occlusion-query.effect @@ -17,8 +17,8 @@ CCEffect %{ CCProgram occlusion-query-vs %{ precision highp float; - #include - #include + #include + #include layout(location = 0) in vec3 a_position; diff --git a/editor/assets/effects/builtin-occlusion-query.effect.meta b/editor/assets/effects/builtin-occlusion-query.effect.meta index 1bbf9360e0..ab0239f48d 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.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "d9937e59-61fe-4ec6-92ab-7ac5a19c89b0", diff --git a/editor/assets/effects/builtin-particle-gpu.effect b/editor/assets/effects/builtin-particle-gpu.effect index 6fc42846b7..7aaa5a3b8c 100644 --- a/editor/assets/effects/builtin-particle-gpu.effect +++ b/editor/assets/effects/builtin-particle-gpu.effect @@ -34,7 +34,7 @@ CCEffect %{ techniques: - name: add passes: - - vert: particle-vs-gpu:gpvs_main + - vert: builtin/internal/particle-vs-gpu:gpvs_main frag: tinted-fs:add rasterizerState: *r1 depthStencilState: *d1 @@ -42,7 +42,7 @@ CCEffect %{ properties: *p2 - name: alpha-blend passes: - - vert: particle-vs-gpu:gpvs_main + - vert: builtin/internal/particle-vs-gpu:gpvs_main frag: tinted-fs:add rasterizerState: *r1 depthStencilState: *d1 @@ -50,7 +50,7 @@ CCEffect %{ properties: *p2 - name: add-multiply passes: - - vert: particle-vs-gpu:gpvs_main + - vert: builtin/internal/particle-vs-gpu:gpvs_main frag: tinted-fs:multiply rasterizerState: *r1 depthStencilState: *d1 @@ -58,7 +58,7 @@ CCEffect %{ properties: *p2 - name: add-smooth passes: - - vert: particle-vs-gpu:gpvs_main + - vert: builtin/internal/particle-vs-gpu:gpvs_main frag: no-tint-fs:addSmooth rasterizerState: *r1 depthStencilState: *d1 @@ -66,7 +66,7 @@ CCEffect %{ properties: *p1 - name: premultiply-blend passes: - - vert: particle-vs-gpu:gpvs_main + - vert: builtin/internal/particle-vs-gpu:gpvs_main frag: no-tint-fs:premultiplied rasterizerState: *r1 depthStencilState: *d1 @@ -78,7 +78,7 @@ CCEffect %{ CCProgram tinted-fs %{ precision mediump float; - #include + #include in vec2 uv; in vec4 color; @@ -104,7 +104,7 @@ CCProgram tinted-fs %{ CCProgram no-tint-fs %{ precision mediump float; - #include + #include in vec2 uv; in vec4 color; diff --git a/editor/assets/effects/builtin-particle-gpu.effect.meta b/editor/assets/effects/builtin-particle-gpu.effect.meta index bbc5bf3372..2c6c603fed 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.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "971bdb23-3ff6-43eb-b422-1c30165a3663", diff --git a/editor/assets/effects/builtin-particle-trail.effect b/editor/assets/effects/builtin-particle-trail.effect index 169958a190..37afc3ce1a 100644 --- a/editor/assets/effects/builtin-particle-trail.effect +++ b/editor/assets/effects/builtin-particle-trail.effect @@ -27,7 +27,7 @@ CCEffect %{ techniques: - name: add passes: - - vert: particle-trail:vs_main + - vert: builtin/internal/particle-trail:vs_main frag: tinted-fs:add rasterizerState: *r1 depthStencilState: *d1 @@ -35,7 +35,7 @@ CCEffect %{ properties: *p2 - name: alpha-blend passes: - - vert: particle-trail:vs_main + - vert: builtin/internal/particle-trail:vs_main frag: tinted-fs:add rasterizerState: *r1 depthStencilState: *d1 @@ -43,7 +43,7 @@ CCEffect %{ properties: *p2 - name: add-multiply passes: - - vert: particle-trail:vs_main + - vert: builtin/internal/particle-trail:vs_main frag: tinted-fs:multiply rasterizerState: *r1 depthStencilState: *d1 @@ -51,7 +51,7 @@ CCEffect %{ properties: *p2 - name: add-smooth passes: - - vert: particle-trail:vs_main + - vert: builtin/internal/particle-trail:vs_main frag: no-tint-fs:addSmooth rasterizerState: *r1 depthStencilState: *d1 @@ -59,7 +59,7 @@ CCEffect %{ properties: *p1 - name: premultiply-blend passes: - - vert: particle-trail:vs_main + - vert: builtin/internal/particle-trail:vs_main frag: no-tint-fs:premultiplied rasterizerState: *r1 depthStencilState: *d1 @@ -71,7 +71,7 @@ CCEffect %{ CCProgram tinted-fs %{ precision mediump float; - #include + #include in vec2 uv; in vec4 color; @@ -110,7 +110,7 @@ CCProgram tinted-fs %{ CCProgram no-tint-fs %{ precision mediump float; - #include + #include in vec2 uv; in vec4 color; diff --git a/editor/assets/effects/builtin-particle-trail.effect.meta b/editor/assets/effects/builtin-particle-trail.effect.meta index cf40726987..a924478f5c 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.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "17debcc3-0a6b-4b8a-b00b-dc58b885581e", diff --git a/editor/assets/effects/builtin-particle.effect b/editor/assets/effects/builtin-particle.effect index 791b98ed0a..d7838b29e5 100644 --- a/editor/assets/effects/builtin-particle.effect +++ b/editor/assets/effects/builtin-particle.effect @@ -34,7 +34,7 @@ CCEffect %{ techniques: - name: add passes: - - vert: particle-vs-legacy:lpvs_main + - vert: builtin/internal/particle-vs-legacy:lpvs_main frag: tinted-fs:add rasterizerState: *r1 depthStencilState: *d1 @@ -42,7 +42,7 @@ CCEffect %{ properties: *p2 - name: alpha-blend passes: - - vert: particle-vs-legacy:lpvs_main + - vert: builtin/internal/particle-vs-legacy:lpvs_main frag: tinted-fs:add rasterizerState: *r1 depthStencilState: *d1 @@ -50,7 +50,7 @@ CCEffect %{ properties: *p2 - name: add-multiply passes: - - vert: particle-vs-legacy:lpvs_main + - vert: builtin/internal/particle-vs-legacy:lpvs_main frag: tinted-fs:multiply rasterizerState: *r1 depthStencilState: *d1 @@ -58,7 +58,7 @@ CCEffect %{ properties: *p2 - name: add-smooth passes: - - vert: particle-vs-legacy:lpvs_main + - vert: builtin/internal/particle-vs-legacy:lpvs_main frag: no-tint-fs:addSmooth rasterizerState: *r1 depthStencilState: *d1 @@ -66,7 +66,7 @@ CCEffect %{ properties: *p1 - name: premultiply-blend passes: - - vert: particle-vs-legacy:lpvs_main + - vert: builtin/internal/particle-vs-legacy:lpvs_main frag: no-tint-fs:premultiplied rasterizerState: *r1 depthStencilState: *d1 @@ -78,7 +78,7 @@ CCEffect %{ CCProgram tinted-fs %{ precision mediump float; - #include + #include in vec2 uv; in vec4 color; @@ -103,7 +103,7 @@ CCProgram tinted-fs %{ CCProgram no-tint-fs %{ precision mediump float; - #include + #include in vec2 uv; in vec4 color; diff --git a/editor/assets/effects/builtin-particle.effect.meta b/editor/assets/effects/builtin-particle.effect.meta index 1b592f24df..9f33a7edef 100644 --- a/editor/assets/effects/builtin-particle.effect.meta +++ b/editor/assets/effects/builtin-particle.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "d1346436-ac96-4271-b863-1f4fdead95b0", diff --git a/editor/assets/effects/builtin-reflection-deferred.effect b/editor/assets/effects/builtin-reflection-deferred.effect index 42e5708fbc..97d8c3a8d1 100644 --- a/editor/assets/effects/builtin-reflection-deferred.effect +++ b/editor/assets/effects/builtin-reflection-deferred.effect @@ -47,12 +47,13 @@ CCProgram shared-ubos %{ CCProgram standard-vs %{ precision highp float; - #include - #include - #include + #include + #include + #include + #include #include - #include - #include + #include + #include #if USE_VERTEX_COLOR in vec4 a_color; @@ -69,12 +70,12 @@ CCProgram standard-vs %{ out vec3 v_bitangent; #endif - #if HAS_SECOND_UV || USE_LIGHTMAP + #if HAS_SECOND_UV || CC_USE_LIGHTMAP in vec2 a_texCoord1; #endif - #if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD - #include + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #include #endif void main () { @@ -105,7 +106,7 @@ CCProgram standard-vs %{ CC_TRANSFER_FOG(pos); CC_TRANSFER_SHADOW(pos); - #if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD CCLightingMapCaclUV(); #endif @@ -116,12 +117,12 @@ CCProgram standard-vs %{ CCProgram standard-fs %{ precision highp float; - #include + #include #include - #include - #include - #if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD - #include + #include + #include + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #include #endif in vec3 v_position; @@ -183,7 +184,7 @@ CCProgram standard-fs %{ if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard; #endif - #if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD s.lightmap = texture(cc_lightingMap, v_luv); #endif @@ -215,6 +216,7 @@ CCProgram standard-fs %{ #endif s.occlusion = pbr.x; s.roughness = pbr.y; + s.specularIntensity = 0.5; s.metallic = pbr.z; s.emissive = emissive.rgb * emissiveScaleParam.xyz; diff --git a/editor/assets/effects/builtin-reflection-deferred.effect.meta b/editor/assets/effects/builtin-reflection-deferred.effect.meta index 878f49d3fd..372ca1464d 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.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "99498f84-efe6-43a6-a9a7-e6e93eb845c1", diff --git a/editor/assets/effects/builtin-spine.effect b/editor/assets/effects/builtin-spine.effect index 8c2fdd5a0a..c355817e2c 100644 --- a/editor/assets/effects/builtin-spine.effect +++ b/editor/assets/effects/builtin-spine.effect @@ -21,9 +21,9 @@ CCEffect %{ CCProgram sprite-vs %{ precision highp float; - #include + #include #if USE_LOCAL - #include + #include #endif in vec3 a_position; @@ -60,7 +60,7 @@ CCProgram sprite-vs %{ CCProgram sprite-fs %{ precision highp float; - #include + #include in vec4 v_light; #if TWO_COLORED diff --git a/editor/assets/effects/builtin-spine.effect.meta b/editor/assets/effects/builtin-spine.effect.meta index f5fc2525e3..9af7395abb 100644 --- a/editor/assets/effects/builtin-spine.effect.meta +++ b/editor/assets/effects/builtin-spine.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "c27215d8-6835-4b68-bfbb-bdeac6100c04", diff --git a/editor/assets/effects/builtin-sprite-renderer.effect b/editor/assets/effects/builtin-sprite-renderer.effect new file mode 100644 index 0000000000..376c6b5c92 --- /dev/null +++ b/editor/assets/effects/builtin-sprite-renderer.effect @@ -0,0 +1,56 @@ +// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. +CCEffect %{ + techniques: + - name: default + passes: + - vert: spriteRender-vs:vert + frag: spriteRender-fs:frag + depthStencilState: + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: src_alpha + blendDst: one_minus_src_alpha + blendDstAlpha: one_minus_src_alpha + rasterizerState: + cullMode: none +}% + +CCProgram spriteRender-vs %{ + precision highp float; + #include + #include + + in vec3 a_position; + in vec2 a_texCoord; + + out vec2 uv0; + + vec4 vert () { + vec4 pos = vec4(a_position, 1); + + pos = cc_matViewProj * cc_matWorld * pos; + + uv0 = vec2(a_texCoord.x, 1.0 - a_texCoord.y); + + return pos; + } +}% + +CCProgram spriteRender-fs %{ + precision highp float; + + in vec2 uv0; + #pragma builtin(local) + layout(set = 2, binding = 11) uniform sampler2D cc_spriteTexture; + + vec4 frag () { + vec4 o = vec4(1, 1, 1, 1); + + o *= texture(cc_spriteTexture, uv0); + + return o; + } +}% diff --git a/editor/assets/effects/builtin-sprite-renderer.effect.meta b/editor/assets/effects/builtin-sprite-renderer.effect.meta new file mode 100644 index 0000000000..b0163d210a --- /dev/null +++ b/editor/assets/effects/builtin-sprite-renderer.effect.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.5.7", + "importer": "effect", + "imported": true, + "uuid": "6ef1defe-7997-477a-9b35-c18859ff8066", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/effects/builtin-sprite.effect b/editor/assets/effects/builtin-sprite.effect index 4f30013670..86e1d95d05 100644 --- a/editor/assets/effects/builtin-sprite.effect +++ b/editor/assets/effects/builtin-sprite.effect @@ -21,12 +21,12 @@ CCEffect %{ CCProgram sprite-vs %{ precision highp float; - #include + #include #if USE_LOCAL - #include + #include #endif #if SAMPLE_FROM_RT - #include + #include #endif in vec3 a_position; in vec2 a_texCoord; @@ -62,8 +62,8 @@ CCProgram sprite-vs %{ CCProgram sprite-fs %{ precision highp float; - #include - #include + #include + #include in vec4 color; diff --git a/editor/assets/effects/builtin-sprite.effect.meta b/editor/assets/effects/builtin-sprite.effect.meta index b47a670aed..29f28e1cc8 100644 --- a/editor/assets/effects/builtin-sprite.effect.meta +++ b/editor/assets/effects/builtin-sprite.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.2", + "ver": "1.5.7", "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 8e2dcac276..69fa82c50b 100644 --- a/editor/assets/effects/builtin-standard.effect +++ b/editor/assets/effects/builtin-standard.effect @@ -14,10 +14,10 @@ CCEffect %{ occlusion: { value: 1.0, target: pbrParams.x, editor: { slide: true, range: [0, 1.0], step: 0.001 } } roughness: { value: 0.8, target: pbrParams.y, editor: { slide: true, range: [0, 1.0], step: 0.001 } } metallic: { value: 0.6, target: pbrParams.z, editor: { slide: true, range: [0, 1.0], step: 0.001 } } - SpecularIntensity: { value: 0.5, target: pbrParams.w, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } + specularIntensity: { value: 0.5, target: pbrParams.w, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } emissive: { value: [0.0, 0.0, 0.0, 1.0], linear: true, editor: { type: color } } emissiveScale: { value: [1.0, 1.0, 1.0], target: emissiveScaleParam.xyz } - normalStrenth: { value: 1.0, target: emissiveScaleParam.w, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 1.0], step: 0.001 } } + normalStrength: { value: 1.0, target: emissiveScaleParam.w, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 5.0], step: 0.001 } } mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } normalMap: { value: normal } pbrMap: { value: grey } @@ -86,38 +86,40 @@ CCProgram shared-ubos %{ CCProgram standard-vs %{ precision highp float; - #include - #include - #include + #include + #include + #include + #include #include - #include - #include + #include + #include #if USE_VERTEX_COLOR in vec4 a_color; - out vec4 v_color; + out lowp vec4 v_color; #endif out vec3 v_position; - out vec3 v_normal; + out mediump vec3 v_normal; out vec2 v_uv; - out vec2 v_uv1; + #if HAS_SECOND_UV + out mediump vec2 v_uv1; + #endif #if CC_RECEIVE_SHADOW - out vec2 v_shadowBias; + out mediump vec2 v_shadowBias; #endif #if USE_NORMAL_MAP - out vec3 v_tangent; - out vec3 v_bitangent; + out mediump vec4 v_tangent; #endif - #if HAS_SECOND_UV || USE_LIGHTMAP + #if HAS_SECOND_UV || CC_USE_LIGHTMAP in vec2 a_texCoord1; #endif - #if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD - #include + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #include #endif void main () { @@ -142,8 +144,8 @@ CCProgram standard-vs %{ #endif #if USE_NORMAL_MAP - v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz); - v_bitangent = cross(v_normal, v_tangent) * In.tangent.w; // note the cross order + v_tangent.xyz = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz); + v_tangent.w = In.tangent.w; #endif v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw; @@ -164,7 +166,7 @@ CCProgram standard-vs %{ CC_TRANSFER_FOG(pos); CC_TRANSFER_SHADOW(pos); - #if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD CCLightingMapCaclUV(); #endif @@ -174,25 +176,27 @@ CCProgram standard-vs %{ CCProgram standard-fs %{ precision highp float; - #include + #include #include - #include - #include - #if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD - #include + #include + #include + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #include #endif in vec3 v_position; in vec2 v_uv; - in vec2 v_uv1; - in vec3 v_normal; + #if HAS_SECOND_UV + in mediump vec2 v_uv1; + #endif + in mediump vec3 v_normal; #if CC_RECEIVE_SHADOW - in vec2 v_shadowBias; + in mediump vec2 v_shadowBias; #endif #if USE_VERTEX_COLOR - in vec4 v_color; + in lowp vec4 v_color; #endif #if USE_ALBEDO_MAP @@ -200,8 +204,7 @@ CCProgram standard-fs %{ #pragma define-meta ALBEDO_UV options([v_uv, v_uv1]) #endif #if USE_NORMAL_MAP - in vec3 v_tangent; - in vec3 v_bitangent; + in mediump vec4 v_tangent; uniform sampler2D normalMap; #pragma define-meta NORMAL_UV options([v_uv, v_uv1]) #endif @@ -247,7 +250,7 @@ CCProgram standard-fs %{ if (s.albedo.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard; #endif - #if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD vec4 lightColor = texture(cc_lightingMap, v_luv.xy); s.lightmap = lightColor.xyz * v_luv.z; s.lightmap_test = v_luv.z; /*lum*/ @@ -261,9 +264,10 @@ CCProgram standard-fs %{ #if USE_NORMAL_MAP vec3 nmmp = texture(normalMap, NORMAL_UV).xyz - vec3(0.5); + vec3 bitangent = cross(v_normal, v_tangent.xyz) * v_tangent.w; // note the cross order s.normal = - (nmmp.x * emissiveScaleParam.w) * normalize(v_tangent) + - (nmmp.y * emissiveScaleParam.w) * normalize(v_bitangent) + + (nmmp.x * emissiveScaleParam.w) * normalize(v_tangent.xyz) + + (nmmp.y * emissiveScaleParam.w) * normalize(bitangent) + nmmp.z * normalize(s.normal); #endif @@ -287,6 +291,7 @@ CCProgram standard-fs %{ #endif s.occlusion = pbr.x; s.roughness = pbr.y; + s.specularIntensity = 0.5; s.metallic = pbr.z; s.emissive = emissive.rgb * emissiveScaleParam.xyz; @@ -300,20 +305,22 @@ CCProgram standard-fs %{ CCProgram shadow-caster-vs %{ precision highp float; - #include - #include + #include + #include + #include #include - #include + #include - #if HAS_SECOND_UV || USE_LIGHTMAP + #if HAS_SECOND_UV || CC_USE_LIGHTMAP in vec2 a_texCoord1; #endif out vec2 v_uv; - out vec2 v_uv1; + #if HAS_SECOND_UV + out vec2 v_uv1; + #endif out vec4 v_worldPos; - - out float v_clip_depth; + out highp vec2 v_clip_depth; vec4 vert () { StandardVertInput In; @@ -330,7 +337,7 @@ CCProgram shadow-caster-vs %{ v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw; #endif - v_clip_depth = clipPos.z / clipPos.w * 0.5 + 0.5; + v_clip_depth = clipPos.zw; return clipPos; } @@ -339,13 +346,15 @@ CCProgram shadow-caster-vs %{ CCProgram shadow-caster-fs %{ precision highp float; #include - #include - #include + #include + #include in vec2 v_uv; - in vec2 v_uv1; + #if HAS_SECOND_UV + in vec2 v_uv1; + #endif in vec4 v_worldPos; - in float v_clip_depth; + in highp vec2 v_clip_depth; #if USE_ALBEDO_MAP uniform sampler2D albedoMap; @@ -367,18 +376,19 @@ CCProgram shadow-caster-fs %{ if (baseColor.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard; #endif + highp float clipDepth = v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5; // spot use linear if(cc_shadowLPNNInfo.x > 0.000001 && cc_shadowLPNNInfo.x < 1.999999) { // enabled linear depth - if (cc_shadowNFLSInfo.z > 0.000001) { - return vec4(CCGetLinearDepth(v_worldPos.xyz), 1.0, 1.0, 1.0); - } + #if CC_SHADOWMAP_USE_LINEAR_DEPTH + clipDepth = CCGetLinearDepth(v_worldPos.xyz); + #endif } - if (cc_shadowLPNNInfo.y > 0.000001) { - return packDepthToRGBA(v_clip_depth); - } - - return vec4(v_clip_depth, 1.0, 1.0, 1.0); + #if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8 + return packDepthToRGBA(clipDepth); + #else + return vec4(clipDepth, 1.0, 1.0, 1.0); + #endif } }% diff --git a/editor/assets/effects/builtin-standard.effect.meta b/editor/assets/effects/builtin-standard.effect.meta index 11d688c7df..14658ad55d 100644 --- a/editor/assets/effects/builtin-standard.effect.meta +++ b/editor/assets/effects/builtin-standard.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "1baf0fc9-befa-459c-8bdd-af1a450a0319", diff --git a/editor/assets/effects/builtin-terrain.effect b/editor/assets/effects/builtin-terrain.effect index 0b441cb698..540468c105 100644 --- a/editor/assets/effects/builtin-terrain.effect +++ b/editor/assets/effects/builtin-terrain.effect @@ -47,10 +47,10 @@ CCEffect %{ CCProgram terrain-vs %{ precision mediump float; - #include - #include - #include - #include + #include + #include + #include + #include in vec3 a_position; in vec3 a_normal; @@ -62,10 +62,6 @@ CCProgram terrain-vs %{ out highp vec3 v_position; out mediump vec3 v_normal; - #if USE_NORMALMAP - out mediump vec3 v_tangent; - out mediump vec3 v_binormal; - #endif out mediump vec2 uvw; out mediump vec2 uv0; out mediump vec2 uv1; @@ -93,7 +89,7 @@ CCProgram terrain-vs %{ uv1 = a_position.xz * UVScale.y; uv2 = a_position.xz * UVScale.z; uv3 = a_position.xz * UVScale.w; - #if USE_LIGHTMAP + #if CC_USE_LIGHTMAP luv.xy = lightMapUVParam.xy + a_texCoord * lightMapUVParam.z; luv.z = lightMapUVParam.w; #endif @@ -106,14 +102,6 @@ CCProgram terrain-vs %{ v_shadowBias = vec2(0.0, 0.0); #endif - #if USE_NORMALMAP - v_tangent = vec3(1.0, 0.0, 0.0); - v_binormal = vec3(0.0, 0.0, 1.0); - - v_binormal = cross(v_tangent, a_normal); - v_tangent = cross(a_normal, v_binormal); - #endif - CC_TRANSFER_SHADOW(vec4(worldPos, 1.0)); gl_Position = pos; @@ -122,11 +110,11 @@ CCProgram terrain-vs %{ CCProgram terrain-fs %{ precision highp float; - #include - #include - #include - #if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD - #include + #include + #include + #include + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #include #endif #pragma define-meta LAYERS range([0, 4]) @@ -137,11 +125,6 @@ CCProgram terrain-fs %{ in vec2 v_shadowBias; #endif - #if USE_NORMALMAP - in mediump vec3 v_tangent; - in mediump vec3 v_binormal; - #endif - in mediump vec2 uvw; in mediump vec2 uv0; in mediump vec2 uv1; @@ -211,10 +194,16 @@ CCProgram terrain-fs %{ baseNormal = texture(normalMap0, uv0); #endif + vec3 tangent = vec3(1.0, 0.0, 0.0); + vec3 binormal = vec3(0.0, 0.0, 1.0); + + binormal = cross(tangent, v_normal); + tangent = cross(v_normal, binormal); + vec3 nmmp = baseNormal.xyz - vec3(0.5); s.normal = - nmmp.x * normalize(v_tangent) + - nmmp.y * normalize(v_binormal) + + nmmp.x * normalize(tangent) + + nmmp.y * normalize(binormal) + nmmp.z * normalize(v_normal); #else s.normal = v_normal; @@ -246,8 +235,11 @@ CCProgram terrain-fs %{ s.roughness = 1.0; #endif + s.specularIntensity = 0.5; + s.metallic = 0.0; #if LAYERS == 1 + s.specularIntensity = 0.5; s.metallic = metallic.x; #elif LAYERS == 2 s.metallic += metallic.x * w.r; @@ -262,15 +254,17 @@ CCProgram terrain-fs %{ s.metallic += metallic.z * w.b; s.metallic += metallic.w * w.a; #else + s.specularIntensity = 0.5; s.metallic = 0.0; #endif #else s.roughness = 1.0; + s.specularIntensity = 0.5; s.metallic = 0.0; #endif s.emissive = vec3(0.0, 0.0, 0.0); - #if USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD vec4 lightColor = texture(lightMap, luv.xy); s.lightmap = lightColor.xyz * luv.z; s.lightmap_test = luv.z; /*lum*/ @@ -282,15 +276,15 @@ CCProgram terrain-fs %{ CCProgram shadow-caster-vs %{ precision highp float; - #include - #include - #include + #include + #include + #include in vec3 a_position; in vec3 a_normal; in vec2 a_texCoord; - out vec2 v_clip_depth; + out highp vec2 v_clip_depth; vec4 vert () { vec4 worldPos; @@ -309,11 +303,22 @@ CCProgram shadow-caster-vs %{ CCProgram shadow-caster-fs %{ precision highp float; - #include + #include - in vec2 v_clip_depth; + #pragma define SHADOWMAP_FORMAT_RGBA8 1 + #pragma define SHADOWMAP_FORMAT_FLOAT 0 + + in highp vec2 v_clip_depth; vec4 frag () { - return packDepthToRGBA(v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5); + highp float clipDepth = v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5; + + //todo: do not support linear mode spot shadow + + #if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8 + return packDepthToRGBA(clipDepth); + #else + return vec4(clipDepth, 1.0, 1.0, 1.0); + #endif } }% diff --git a/editor/assets/effects/builtin-terrain.effect.meta b/editor/assets/effects/builtin-terrain.effect.meta index 41d323afb4..28b87b72b6 100644 --- a/editor/assets/effects/builtin-terrain.effect.meta +++ b/editor/assets/effects/builtin-terrain.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.2", + "ver": "1.5.7", "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 c94bd332ec..7c9a6badec 100644 --- a/editor/assets/effects/builtin-toon.effect +++ b/editor/assets/effects/builtin-toon.effect @@ -4,8 +4,8 @@ CCEffect %{ techniques: - passes: - switch: USE_OUTLINE_PASS - vert: outline-vs:vert - frag: outline-fs:frag + vert: legacy/main-functions/outline-vs:vert + frag: legacy/main-functions/outline-fs:frag rasterizerState: cullMode: front depthStencilState: @@ -34,7 +34,7 @@ CCEffect %{ shadowCover: { value: 0.5, target: miscParams.x, editor: { slide: true, range: [0, 1.0], step: 0.001 } } emissive: { value: [0.0, 0.0, 0.0, 1.0], linear: true, editor: { type: color } } emissiveScale: { value: [1.0, 1.0, 1.0], target: emissiveScaleAndStrenth.xyz } - normalStrenth: { value: 1.0, target: emissiveScaleAndStrenth.w, editor: { parent: USE_NORMAL_MAP } } + normalStrength: { value: 1.0, target: emissiveScaleAndStrenth.w, editor: { parent: USE_NORMAL_MAP }, slide: true, range: [0, 5.0], step: 0.001 } normalMap: { value: normal } mainTexture: { value: white, target: baseColorMap, editor: { displayName: BaseColorMap } } shadeMap1: { value: white } @@ -99,23 +99,23 @@ CCProgram shared-ubos %{ CCProgram toon-vs %{ precision highp float; - #include - #include - #include + #include + #include + #include + #include #include - #include + #include out vec3 v_position; out vec2 v_uv; - out vec3 v_normal; + out mediump vec3 v_normal; #if CC_RECEIVE_SHADOW - out vec2 v_shadowBias; + out mediump vec2 v_shadowBias; #endif #if USE_NORMAL_MAP - out vec3 v_tangent; - out vec3 v_bitangent; + out mediump vec4 v_tangent; #endif vec4 vert () { @@ -135,8 +135,8 @@ CCProgram toon-vs %{ v_normal = (matWorldIT * vec4(In.normal, 0.0)).xyz; #if USE_NORMAL_MAP - v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz); - v_bitangent = cross(v_normal, v_tangent) * In.tangent.w; // note the cross order + v_tangent.xyz = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz); + v_tangent.w = In.tangent.w; #endif CC_TRANSFER_SHADOW(pos); @@ -147,27 +147,26 @@ CCProgram toon-vs %{ CCProgram toon-fs %{ precision highp float; - #include - #include + #include + #include #include - #include - #include + #include + #include in vec3 v_position; in vec2 v_uv; #if CC_RECEIVE_SHADOW - in vec2 v_shadowBias; + in mediump vec2 v_shadowBias; #endif #if USE_BASE_COLOR_MAP uniform sampler2D baseColorMap; #endif - in vec3 v_normal; + in mediump vec3 v_normal; #if USE_NORMAL_MAP - in vec3 v_tangent; - in vec3 v_bitangent; + in mediump vec4 v_tangent; uniform sampler2D normalMap; #endif @@ -228,9 +227,10 @@ CCProgram toon-fs %{ #if USE_NORMAL_MAP vec3 nmmp = texture(normalMap, v_uv).xyz - vec3(0.5); + vec3 bitangent = cross(v_normal, v_tangent.xyz) * v_tangent.w; // note the cross order s.normal = - (nmmp.x * emissiveScaleAndStrenth.w) * normalize(v_tangent) + - (nmmp.y * emissiveScaleAndStrenth.w) * normalize(v_bitangent) + + (nmmp.x * emissiveScaleAndStrenth.w) * normalize(v_tangent.xyz) + + (nmmp.y * emissiveScaleAndStrenth.w) * normalize(bitangent) + nmmp.z * normalize(s.normal); #endif @@ -262,14 +262,15 @@ CCProgram toon-fs %{ CCProgram shadow-caster-vs %{ precision highp float; - #include - #include + #include + #include + #include #include - #include + #include out vec2 v_uv; out vec4 v_worldPos; - out float v_clip_depth; + out highp vec2 v_clip_depth; vec4 vert () { StandardVertInput In; @@ -280,7 +281,7 @@ CCProgram shadow-caster-vs %{ v_worldPos = matWorld * In.position; vec4 clipPos = cc_matLightViewProj * v_worldPos; - v_clip_depth = clipPos.z / clipPos.w * 0.5 + 0.5; + v_clip_depth = clipPos.zw; v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw; @@ -291,12 +292,12 @@ CCProgram shadow-caster-vs %{ CCProgram shadow-caster-fs %{ precision highp float; #include - #include - #include + #include + #include in vec2 v_uv; in vec4 v_worldPos; - in float v_clip_depth; + in highp vec2 v_clip_depth; #if USE_BASE_COLOR_MAP uniform sampler2D baseColorMap; @@ -316,18 +317,19 @@ CCProgram shadow-caster-fs %{ if (baseColor.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard; #endif + highp float clipDepth = v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5; // spot use linear if(cc_shadowLPNNInfo.x > 0.000001 && cc_shadowLPNNInfo.x < 1.999999) { // enabled linear depth - if (cc_shadowNFLSInfo.z > 0.000001) { - return vec4(CCGetLinearDepth(v_worldPos.xyz), 1.0, 1.0, 1.0); - } + #if CC_SHADOWMAP_USE_LINEAR_DEPTH + clipDepth = CCGetLinearDepth(v_worldPos.xyz); + #endif } - if (cc_shadowLPNNInfo.y > 0.000001) { - return packDepthToRGBA(v_clip_depth); - } - - return vec4(v_clip_depth, 1.0, 1.0, 1.0); + #if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8 + return packDepthToRGBA(clipDepth); + #else + return vec4(clipDepth, 1.0, 1.0, 1.0); + #endif } }% diff --git a/editor/assets/effects/builtin-toon.effect.meta b/editor/assets/effects/builtin-toon.effect.meta index 1546c7db28..afd69e1d7f 100644 --- a/editor/assets/effects/builtin-toon.effect.meta +++ b/editor/assets/effects/builtin-toon.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "a7612b54-35e3-4238-a1a9-4a7b54635839", diff --git a/editor/assets/effects/builtin-unlit.effect b/editor/assets/effects/builtin-unlit.effect index cfac3ce469..89eff207d6 100644 --- a/editor/assets/effects/builtin-unlit.effect +++ b/editor/assets/effects/builtin-unlit.effect @@ -64,11 +64,12 @@ CCEffect %{ CCProgram unlit-vs %{ precision highp float; - #include - #include - #include - #include - #include + #include + #include + #include + #include + #include + #include #if USE_VERTEX_COLOR in lowp vec4 a_color; @@ -107,8 +108,8 @@ CCProgram unlit-vs %{ CCProgram unlit-fs %{ precision highp float; - #include - #include + #include + #include #if USE_ALPHA_TEST #pragma define-meta ALPHA_TEST_CHANNEL options([a, r, g, b]) diff --git a/editor/assets/effects/builtin-unlit.effect.meta b/editor/assets/effects/builtin-unlit.effect.meta index 91c9f9b80d..460184af4a 100644 --- a/editor/assets/effects/builtin-unlit.effect.meta +++ b/editor/assets/effects/builtin-unlit.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "a3cd009f-0ab0-420d-9278-b9fdab939bbc", diff --git a/editor/assets/effects/builtin-wireframe.effect b/editor/assets/effects/builtin-wireframe.effect index 0c29b3c61f..e7a03d9f75 100644 --- a/editor/assets/effects/builtin-wireframe.effect +++ b/editor/assets/effects/builtin-wireframe.effect @@ -11,10 +11,10 @@ CCEffect %{ CCProgram wireframe-vs %{ precision mediump float; - #include - #include - #include - #include + #include + #include + #include + #include uniform TexCoords { vec4 lineColor; @@ -39,7 +39,7 @@ CCProgram wireframe-vs %{ CCProgram wireframe-fs %{ precision mediump float; - #include + #include in vec2 bary; diff --git a/editor/assets/effects/builtin-wireframe.effect.meta b/editor/assets/effects/builtin-wireframe.effect.meta index 3bfd107f7f..4dc7a7aa5a 100644 --- a/editor/assets/effects/builtin-wireframe.effect.meta +++ b/editor/assets/effects/builtin-wireframe.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "81127eb0-7556-453c-b147-670782dd5e53", diff --git a/editor/assets/effects/dcc.meta b/editor/assets/effects/dcc.meta new file mode 100644 index 0000000000..c76976d314 --- /dev/null +++ b/editor/assets/effects/dcc.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "7318038e-8127-4c1b-9b93-e809f973ce6c", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/effects/dcc/imported-metallic-roughness.effect b/editor/assets/effects/dcc/imported-metallic-roughness.effect new file mode 100644 index 0000000000..cc26af5ded --- /dev/null +++ b/editor/assets/effects/dcc/imported-metallic-roughness.effect @@ -0,0 +1,468 @@ +// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. + +CCEffect %{ + techniques: + - name: opaque + passes: + - vert: standard-vs + frag: standard-fs + properties: &props + tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, linear: true, editor: { displayName: BaseColor, type: color } } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: BaseColorMap } } + baseWeightMap: { value: grey } + albedoScale: { value: 1.0, editor: { displayName: BaseWeight } } + roughness: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + roughnessMap: { value: grey } + metallic: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + metallicMap: { value: grey } + occlusion: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + occlusionMap: { value: white } + emissiveScale: { value: 1.0, editor: { displayName: Emissive } } + emissiveScaleMap: { value: grey, editor: { displayName: EmissiveMap } } + emissive: { value: [0.0, 0.0, 0.0, 1.0], linear: true, editor: { displayName: EmissiveColor, type: color} } + emissiveMap: { value: grey, editor: { displayName: EmissiveColorMap } } + alphaSource: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + alphaSourceMap: { value: grey, editor: { parent: USE_OPACITY_MAP } } + alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } + normalStrength: { value: 1.0, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 1.0], step: 0.001 } } + normalMap: { value: normal } + - &forward-add + vert: standard-vs + frag: standard-fs + phase: forward-add + propertyIndex: 0 + embeddedMacros: { CC_FORWARD_ADD: true } + depthStencilState: + depthFunc: equal + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: one + blendDst: one + blendSrcAlpha: zero + blendDstAlpha: one + - &shadow-caster + vert: shadow-caster-vs:vert + frag: shadow-caster-fs:frag + phase: shadow-caster + propertyIndex: 0 + 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 } } + - name: transparent + passes: + - vert: standard-vs + frag: standard-fs + embeddedMacros: { CC_FORCE_FORWARD_SHADING: true } + depthStencilState: + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: src_alpha + blendDst: one_minus_src_alpha + blendDstAlpha: one_minus_src_alpha + properties: *props + - *forward-add + - *shadow-caster +}% + +CCProgram shared-ubos %{ + uniform Constants { + vec4 tilingOffset; + vec4 albedo; + vec4 albedoScaleAndCutoff; + vec4 emissive; + float emissiveScale; + float occlusion; + float roughness; + float metallic; + float normalStrength; + float alphaSource; + float albedoScale; + }; +}% + +CCProgram standard-vs %{ + precision highp float; + #include + #include + #include + #include + #include + #include + #include + + #if USE_VERTEX_COLOR + in vec4 a_color; + out vec4 v_color; + #endif + + out vec3 v_position; + out vec3 v_normal; + out vec2 v_uv; + out vec2 v_uv1; + + #if CC_RECEIVE_SHADOW + out vec2 v_shadowBias; + #endif + + #if USE_NORMAL_MAP + out vec3 v_tangent; + out vec3 v_bitangent; + #endif + + #if HAS_SECOND_UV || CC_USE_LIGHTMAP + in vec2 a_texCoord1; + #endif + + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #include + #endif + + void main () { + StandardVertInput In; + CCVertInput(In); + + mat4 matWorld, matWorldIT; + CCGetWorldMatrixFull(matWorld, matWorldIT); + + vec4 pos = matWorld * In.position; + + v_position = pos.xyz; + v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz); + + #if CC_RECEIVE_SHADOW + v_shadowBias = CCGetShadowBias(); + #endif + + #if USE_TWOSIDE + vec3 viewDirect = normalize(cc_cameraPos.xyz - v_position); + v_normal *= dot(v_normal, viewDirect) < 0.0 ? -1.0 : 1.0; + #endif + + #if USE_NORMAL_MAP + v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz); + v_bitangent = cross(v_normal, v_tangent) * In.tangent.w; // note the cross order + #endif + + v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw; + #if SAMPLE_FROM_RT + CC_HANDLE_RT_SAMPLE_FLIP(v_uv); + #endif + #if HAS_SECOND_UV + v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw; + #if SAMPLE_FROM_RT + CC_HANDLE_RT_SAMPLE_FLIP(v_uv1); + #endif + #endif + + #if USE_VERTEX_COLOR + v_color = a_color; + #endif + + CC_TRANSFER_FOG(pos); + CC_TRANSFER_SHADOW(pos); + + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + CCLightingMapCaclUV(); + #endif + + gl_Position = cc_matProj * (cc_matView * matWorld) * In.position; + } +}% + +CCProgram standard-fs %{ + precision highp float; + #include + #include + #include + #include + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #include + #endif + + in vec3 v_position; + in vec2 v_uv; + in vec2 v_uv1; + in vec3 v_normal; + + #if CC_RECEIVE_SHADOW + in vec2 v_shadowBias; + #endif + + #if USE_VERTEX_COLOR + in vec4 v_color; + #endif + + #pragma define-meta TEXTURE_UV options([v_uv, v_uv1]) + + #if USE_ALBEDO_MAP + uniform sampler2D albedoMap; + #endif + + #if USE_WEIGHT_MAP + uniform sampler2D baseWeightMap; + #endif + + #if USE_NORMAL_MAP + in vec3 v_tangent; + in vec3 v_bitangent; + uniform sampler2D normalMap; + #pragma define-meta NORMAL_UV options([v_uv, v_uv1]) + #endif + + #if USE_METALLIC_MAP + #pragma define-meta METALLIC_CHANNEL options([r, g, b, a]) + uniform sampler2D metallicMap; + #endif + + #if USE_ROUGHNESS_MAP + #pragma define-meta ROUGHNESS_CHANNEL options([r, g, b, a]) + uniform sampler2D roughnessMap; + #endif + + #if USE_OCCLUSION_MAP + #pragma define-meta OCCLUSION_CHANNEL options([r, g, b, a]) + uniform sampler2D occlusionMap; + #endif + + #if USE_TRANSPARENCY_MAP + uniform sampler2D transparencyMap; + #endif + + #if USE_TRANSPARENCYCOLOR_MAP + uniform sampler2D transparencyColorMap; + #endif + + #if USE_EMISSIVE_MAP + uniform sampler2D emissiveMap; + #endif + #if USE_EMISSIVESCALE_MAP + uniform sampler2D emissiveScaleMap; + #endif + + #if USE_OPACITY_MAP + #pragma define-meta ALPHA_SOURCE_CHANNEL options([r, g, b, a]) + uniform sampler2D alphaSourceMap; + #endif + + float discolor(vec3 srcColor) { + return dot(GRAY_VECTOR, srcColor); + } + + void surf (out StandardSurface s) { + vec4 baseColor = albedo; + #if USE_VERTEX_COLOR + baseColor.rgb *= SRGBToLinear(v_color.rgb); // use linear + baseColor.a *= v_color.a; + #endif + + #if USE_ALBEDO_MAP + vec4 texColor = texture(albedoMap, TEXTURE_UV); + texColor.rgb = SRGBToLinear(texColor.rgb); + baseColor = texColor; + #endif + + #if USE_WEIGHT_MAP + vec4 weightColor = texture(baseWeightMap, TEXTURE_UV); + weightColor.rgb = SRGBToLinear(weightColor.rgb); + baseColor.rgb *= weightColor.rgb; + #else + baseColor.rgb *= albedoScale; + #endif + //////////////////////// + float metallicValue = metallic; + #if USE_METALLIC_MAP + vec4 metallicColor = texture(metallicMap, TEXTURE_UV); + metallicValue = discolor(metallicColor.rgb); + #if USE_METALLIC_CHANNEL + metallicColor.rgb = SRGBToLinear(metallicColor.rgb); + metallicValue = metallicColor.METALLIC_CHANNEL; + #endif + #endif + s.metallic = metallicValue; + + float roughnessValue = roughness; + #if USE_ROUGHNESS_MAP + vec4 roughnessColor = texture(roughnessMap, TEXTURE_UV); + roughnessValue = discolor(roughnessColor.rgb); + #if USE_ROUGHNESS_CHANNEL + roughnessColor.rgb = SRGBToLinear(roughnessColor.rgb); + roughnessValue = roughnessColor.ROUGHNESS_CHANNEL; + #endif + #endif + //fit specular ior=1.5 + s.roughness = max(0.02, roughnessValue); + + + float occlusionValue = occlusion; + #if USE_OCCLUSION_MAP + vec4 occlusionColor = texture(occlusionMap, TEXTURE_UV); + occlusionValue = discolor(occlusionColor.rgb); + #if USE_OCCLUSION_CHANNEL + occlusionColor.rgb = SRGBToLinear(occlusionColor.rgb); + occlusionValue = occlusionColor.OCCLUSION_CHANNEL; + #endif + #endif + s.occlusion = occlusionValue; + + #if ALPHA_SOURCE_IS_OPACITY + #if USE_OPACITY_MAP + baseColor.a = 1.0 - texture(alphaSourceMap, TEXTURE_UV).ALPHA_SOURCE_CHANNEL; + #else + baseColor.a = 1.0 - alphaSource; + #endif + #else + #if USE_OPACITY_MAP + baseColor.a = texture(alphaSourceMap, TEXTURE_UV).ALPHA_SOURCE_CHANNEL; + #else + baseColor.a = alphaSource; + #endif + #endif + #if USE_ALPHA_TEST + if (baseColor.a < albedoScaleAndCutoff.w) discard; + #endif + ///////////////////////////// + s.albedo = baseColor; + + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + vec4 lightColor = texture(cc_lightingMap, v_luv.xy); + s.lightmap = lightColor.xyz * v_luv.z; + s.lightmap_test = v_luv.z; /*lum*/ + #endif + + s.normal = v_normal; + + #if CC_RECEIVE_SHADOW + s.shadowBias = v_shadowBias; + #endif + + #if USE_NORMAL_MAP + vec3 nmmp = texture(normalMap, NORMAL_UV).xyz - vec3(0.5); + s.normal = + (nmmp.x * normalStrength) * normalize(v_tangent) + + (nmmp.y * normalStrength) * normalize(v_bitangent) + + nmmp.z * normalize(s.normal); + #endif + + HIGHP_VALUE_TO_STRUCT_DEFINED(v_position, s.position); + + s.specularIntensity = 0.5; + + //emissive color + vec3 emissiveColor = emissive.rgb; + #if USE_EMISSIVE_MAP + emissiveColor.rgb = SRGBToLinear(texture(emissiveMap, TEXTURE_UV).rgb); + #endif + //emissive color scale + #if USE_EMISSIVESCALE_MAP + vec4 emissiveScaleColor = texture(emissiveScaleMap, TEXTURE_UV); + emissiveScaleColor.rgb = SRGBToLinear(emissiveScaleColor.rgb); + emissiveColor.rgb *= emissiveScaleColor.rgb; + #else + emissiveColor.rgb *= emissiveScale; + #endif + + s.emissive = emissiveColor.rgb; + } + + CC_STANDARD_SURFACE_ENTRY() +}% + +CCProgram shadow-caster-vs %{ + precision highp float; + #include + #include + #include + #include + #include + #include + + #if HAS_SECOND_UV || CC_USE_LIGHTMAP + in vec2 a_texCoord1; + #endif + + out vec2 v_uv; + out vec2 v_uv1; + out vec4 v_worldPos; + + out highp vec2 v_clip_depth; + + vec4 vert () { + StandardVertInput In; + CCVertInput(In); + + mat4 matWorld, matWorldIT; + CCGetWorldMatrixFull(matWorld, matWorldIT); + + v_worldPos = matWorld * In.position; + vec4 clipPos = cc_matLightViewProj * v_worldPos; + + v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw; + #if HAS_SECOND_UV + v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw; + #endif + + v_clip_depth = clipPos.zw; + + return clipPos; + } +}% + +CCProgram shadow-caster-fs %{ + precision highp float; + #include + #include + #include + + in vec2 v_uv; + in vec2 v_uv1; + in vec4 v_worldPos; + in highp vec2 v_clip_depth; + + #if USE_ALBEDO_MAP + uniform sampler2D albedoMap; + #pragma define-meta ALBEDO_UV options([v_uv, v_uv1]) + #endif + + #if USE_ALPHA_TEST + #pragma define-meta ALPHA_TEST_CHANNEL options([a, r]) + #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; + #endif + + highp float clipDepth = v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5; + // spot use linear + if(cc_shadowLPNNInfo.x > 0.000001 && cc_shadowLPNNInfo.x < 1.999999) { + // enabled linear depth + #if CC_SHADOWMAP_USE_LINEAR_DEPTH + clipDepth = CCGetLinearDepth(v_worldPos.xyz); + #endif + } + + #if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8 + return packDepthToRGBA(clipDepth); + #else + return vec4(clipDepth, 1.0, 1.0, 1.0); + #endif + } +}% diff --git a/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta b/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta new file mode 100644 index 0000000000..b0d0358205 --- /dev/null +++ b/editor/assets/effects/dcc/imported-metallic-roughness.effect.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.5.7", + "importer": "effect", + "imported": true, + "uuid": "2ec11458-f855-4978-b14d-f3ed5cf697fa", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/effects/dcc/imported-specular-glossiness.effect b/editor/assets/effects/dcc/imported-specular-glossiness.effect new file mode 100644 index 0000000000..e7bbd5f9ed --- /dev/null +++ b/editor/assets/effects/dcc/imported-specular-glossiness.effect @@ -0,0 +1,478 @@ +// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. + +CCEffect %{ + techniques: + - name: opaque + passes: + - vert: standard-vs + frag: standard-fs + properties: &props + 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 } } + 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' } } + shininessExponent: { value: 100.0, editor: { parent: '!HAS_EXPORTED_GLOSSINESS' } } + specularGlossinessMap: { value: grey, editor: { parent: '!HAS_EXPORTED_GLOSSINESS' } } + specularColor: { value: [0.0, 0.0, 0.0, 0.0], linear: true, editor: { displayName: SpecularColor, type: color } } + 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: 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 } + glossiness: { value: 0.0, editor: { parent: HAS_EXPORTED_GLOSSINESS, slide: true, range: [0, 1.0], step: 0.001 } } + metallic: { value: 0.0, editor: { parent: HAS_EXPORTED_METALLIC, slide: true, range: [0, 1.0], step: 0.001 } } + metallicMap: { value: grey, editor: { parent: HAS_EXPORTED_METALLIC } } + - &forward-add + vert: standard-vs + frag: standard-fs + phase: forward-add + propertyIndex: 0 + embeddedMacros: { CC_FORWARD_ADD: true } + depthStencilState: + depthFunc: equal + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: one + blendDst: one + blendSrcAlpha: zero + blendDstAlpha: one + - &shadow-caster + vert: shadow-caster-vs:vert + frag: shadow-caster-fs:frag + phase: shadow-caster + propertyIndex: 0 + 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 } } + - name: transparent + passes: + - vert: standard-vs + frag: standard-fs + embeddedMacros: { CC_FORCE_FORWARD_SHADING: true } + depthStencilState: + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: src_alpha + blendDst: one_minus_src_alpha + blendDstAlpha: one_minus_src_alpha + properties: *props + - *forward-add + - *shadow-caster +}% + +CCProgram shared-ubos %{ + uniform Constants { + vec4 tilingOffset; + vec4 albedo; + vec4 albedoScaleAndCutoff; + + vec4 diffuseColor; + vec4 specularColor; + vec4 emissive; + float alphaThreshold; + float shininessExponent; + float glossiness; + float metallic; + float normalScale; + float transparencyFactor; + float diffuseFactor; + float specularFactor; + }; +}% + +CCProgram standard-vs %{ + precision highp float; + #include + #include + #include + #include + #include + #include + + #if USE_VERTEX_COLOR + in vec4 a_color; + out vec4 v_color; + #endif + + out vec3 v_position; + out vec3 v_normal; + out vec2 v_uv; + out vec2 v_uv1; + + #if USE_NORMAL_MAP + out vec3 v_tangent; + out vec3 v_bitangent; + #endif + + #if CC_RECEIVE_SHADOW + out mediump vec2 v_shadowBias; + #endif + + #if HAS_SECOND_UV || CC_USE_LIGHTMAP + in vec2 a_texCoord1; + #endif + + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #include + #endif + + void main () { + StandardVertInput In; + CCVertInput(In); + + mat4 matWorld, matWorldIT; + CCGetWorldMatrixFull(matWorld, matWorldIT); + + vec4 pos = matWorld * In.position; + + v_position = pos.xyz; + v_normal = normalize((matWorldIT * vec4(In.normal, 0.0)).xyz); + + #if USE_TWOSIDE + vec3 viewDirect = normalize(cc_cameraPos.xyz - v_position); + v_normal *= dot(v_normal, viewDirect) < 0.0 ? -1.0 : 1.0; + #endif + + #if USE_NORMAL_MAP + v_tangent = normalize((matWorld * vec4(In.tangent.xyz, 0.0)).xyz); + v_bitangent = cross(v_normal, v_tangent) * In.tangent.w; // note the cross order + #endif + + v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw; + + #if HAS_SECOND_UV + v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw; + #endif + + #if USE_VERTEX_COLOR + v_color = a_color; + #endif + + CC_TRANSFER_FOG(pos); + CC_TRANSFER_SHADOW(pos); + + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + CCLightingMapCaclUV(); + #endif + + #if CC_RECEIVE_SHADOW + v_shadowBias = CCGetShadowBias(); + #endif + + gl_Position = cc_matProj * (cc_matView * matWorld) * In.position; + } +}% + +CCProgram standard-fs %{ + precision highp float; + #include + #include + #include + #include + #include + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + #include + #endif + + in vec3 v_position; + in vec2 v_uv; + in vec2 v_uv1; + in vec3 v_normal; + + #if CC_RECEIVE_SHADOW + in mediump vec2 v_shadowBias; + #endif + + + #pragma define-meta TEXTURE_UV options([v_uv, v_uv1]) + #pragma define-meta DCC_APP_NAME range([0, 4]) + #define DCC_APP_OTHERS 0 + #define DCC_APP_AUTODESK 1 + #define DCC_APP_BLENDER 2 + #define DCC_APP_CINEMA4D 3 + #define DCC_APP_GLTF 4 + + #if USE_SHININESS_MAP + uniform sampler2D shininessExponentMap; + #pragma define-meta SHININESS_MAP_CHANNEL options([a,r,g,b]) + #endif + #if USE_SPECULAR_GLOSSINESS_MAP + uniform sampler2D specularGlossinessMap; + #endif + #if USE_SPECULAR_MAP + uniform sampler2D specularMap; + #endif + #if USE_METALLIC_MAP + uniform sampler2D metallicMap; + #endif + + #if USE_VERTEX_COLOR + in vec4 v_color; + #endif + + #if USE_ALBEDO_MAP + uniform sampler2D albedoMap; + #endif + #if USE_TRANSPARENCY_MAP + uniform sampler2D transparencyMap; + #endif + + #if USE_NORMAL_MAP + in vec3 v_tangent; + in vec3 v_bitangent; + uniform sampler2D normalMap; + #endif + + #if USE_EMISSIVE_MAP + uniform sampler2D emissiveMap; + #endif + + float discolor(vec3 srcColor) { + return dot(GRAY_VECTOR, srcColor); + } + float convertShininessExponent(float shininessExp) + { + #if DCC_APP_NAME == DCC_APP_BLENDER + // 2-100 + float glossiness = clamp(sqrt(shininessExp) * 0.1/*/10.0*/, 0.0, 0.95); // glossiness=1 may leads to specular disappear + #elif DCC_APP_NAME == DCC_APP_AUTODESK + // 2-1024 + float l2 = clamp(log(shininessExp + EPSILON) * 0.1442695 /*/log(2.0)/10.0*/, 0.0, 1.0); + float glossiness = pow(l2, 0.5); + #else // DCC_APP_NAME == DCC_APP_CINEMA4D / DCC_APP_GLTF / DCC_APP_OTHERS + // 2-1024 + float glossiness = clamp(log(shininessExp + EPSILON) * 0.1442695 /*/log(2.0)/10.0*/, 0.0, 1.0); + #endif + return glossiness; + } + float getSpecularIntensityFromRoughness(float roughness) + { + #if DCC_APP_NAME == DCC_APP_BLENDER + float specularIntensityMultiplier = mix(1.0, 5.0, roughness); + #elif DCC_APP_NAME == DCC_APP_CINEMA4D + float specularIntensityMultiplier = mix(1.0, 50.0, roughness); + #elif DCC_APP_NAME == DCC_APP_AUTODESK + float specularIntensityMultiplier = mix(1.0, 20.0, roughness); + #else // DCC_APP_NAME == DCC_APP_GLTF / DCC_APP_OTHERS + float specularIntensityMultiplier = 1.0; + #endif + return specularIntensityMultiplier; + } + + vec4 getSpecularColorAndFactor() + { + vec3 inSpecular = specularColor.rgb; + #if USE_SPECULAR_GLOSSINESS_MAP + inSpecular = SRGBToLinear(texture(specularGlossinessMap, TEXTURE_UV).rgb); + #endif + #if USE_SPECULAR_MAP + vec4 specularTex = texture(specularMap, TEXTURE_UV); + specularTex.rgb = SRGBToLinear(specularTex.rgb); + inSpecular = specularTex.rgb; + #endif + return vec4(inSpecular, specularFactor); + } + void surf (out StandardSurface s) { + //diffuse + vec4 baseColor = vec4(1.0); + #if USE_VERTEX_COLOR + baseColor.rgb *= SRGBToLinear(v_color.rgb); + baseColor.a *= v_color.a; + #endif + #if USE_ALBEDO_MAP + vec4 texColor = texture(albedoMap, TEXTURE_UV); + texColor.rgb = SRGBToLinear(texColor.rgb); + baseColor *= texColor; + #else + baseColor *= diffuseColor; + #endif + baseColor.rgb *= diffuseFactor; + + #if USE_TRANSPARENCY_MAP + baseColor.a = texture(transparencyMap, TEXTURE_UV).a * transparencyFactor; + #endif + + #if USE_ALPHA_TEST + if (baseColor.a < albedoScaleAndCutoff.w) discard; + #endif + + #if CC_RECEIVE_SHADOW + s.shadowBias = v_shadowBias; + #endif + + vec4 specularColorAndFactor = getSpecularColorAndFactor(); + + //glossiness + float inGlossiness = 0.0, inSpecularIntensity = specularColorAndFactor.w; + #if HAS_EXPORTED_GLOSSINESS + #if USE_SPECULAR_GLOSSINESS_MAP + inGlossiness = 1.0 - texture(specularGlossinessMap, TEXTURE_UV).a; + #else + inGlossiness = glossiness; + #endif + #else + #if USE_SHININESS_MAP + #if USE_SHININESS_MAP_CHANNEL + inGlossiness = 1.0 - texture(shininessExponentMap, TEXTURE_UV).SHININESS_MAP_CHANNEL; + #else + inGlossiness = 1.0 - discolor(texture(shininessExponentMap, TEXTURE_UV).rgb); + #endif + #else + inGlossiness = convertShininessExponent(shininessExponent); + #endif + + inSpecularIntensity *= getSpecularIntensityFromRoughness(1.0 - inGlossiness); + #endif + + //metallic + float inMetallic = 0.0; + vec4 albedo = baseColor; + #if HAS_EXPORTED_METALLIC + inMetallic = metallic; + float spec = specularFactor; + #if USE_SPECULAR_MAP + spec = dot(GRAY_VECTOR, texture(specularMap, TEXTURE_UV).rgb); + #endif + inSpecularIntensity *= spec * 0.5; + #else + GetMetallicAlbedoFromDiffuseSpecularWithoutColor(inMetallic, albedo.rgb, baseColor.rgb, specularColorAndFactor.rgb, 0.04); + inSpecularIntensity *= inMetallic; //simulate specular color is black + #endif + + s.normal = v_normal; + #if USE_NORMAL_MAP + vec3 nmmp = texture(normalMap, TEXTURE_UV).xyz - vec3(0.5); + s.normal = + (nmmp.x * normalScale) * normalize(v_tangent) + + (nmmp.y * normalScale) * normalize(v_bitangent) + + nmmp.z * normalize(s.normal); + #endif + + HIGHP_VALUE_TO_STRUCT_DEFINED(v_position, s.position); + + s.albedo = albedo; + s.occlusion = 1.0; + s.roughness = 1.0 - inGlossiness; + s.metallic = inMetallic; + s.specularIntensity = inSpecularIntensity * 0.5; + s.emissive = vec3(0.0); + #if USE_EMISSIVE_MAP + s.emissive = texture(emissiveMap, TEXTURE_UV).xyz; + #endif + + #if CC_USE_LIGHTMAP && !USE_BATCHING && !CC_FORWARD_ADD + vec4 lightColor = texture(cc_lightingMap, v_luv.xy); + s.lightmap = lightColor.xyz * v_luv.z; + s.lightmap_test = v_luv.z; /*lum*/ + #endif + } + + CC_STANDARD_SURFACE_ENTRY() +}% + +CCProgram shadow-caster-vs %{ + precision highp float; + #include + #include + #include + #include + + #if HAS_SECOND_UV || CC_USE_LIGHTMAP + in vec2 a_texCoord1; + #endif + + out vec2 v_uv; + out vec2 v_uv1; + out vec4 v_worldPos; + + out highp vec2 v_clip_depth; + + vec4 vert () { + StandardVertInput In; + CCVertInput(In); + + mat4 matWorld, matWorldIT; + CCGetWorldMatrixFull(matWorld, matWorldIT); + + v_worldPos = matWorld * In.position; + vec4 clipPos = cc_matLightViewProj * v_worldPos; + + v_uv = a_texCoord * tilingOffset.xy + tilingOffset.zw; + #if HAS_SECOND_UV + v_uv1 = a_texCoord1 * tilingOffset.xy + tilingOffset.zw; + #endif + + v_clip_depth = clipPos.zw; + + return clipPos; + } +}% + +CCProgram shadow-caster-fs %{ + precision highp float; + #include + #include + #include + + in vec2 v_uv; + in vec2 v_uv1; + in vec4 v_worldPos; + in highp vec2 v_clip_depth; + + #pragma define-meta TEXTURE_UV options([v_uv, v_uv1]) + + #if USE_ALBEDO_MAP + uniform sampler2D albedoMap; + #endif + + #if USE_TRANSPARENCY_MAP + 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_ALPHA_TEST + if (baseColor.a < albedoScaleAndCutoff.w) discard; + #endif + + highp float clipDepth = v_clip_depth.x / v_clip_depth.y * 0.5 + 0.5; + // spot use linear + if(cc_shadowLPNNInfo.x > 0.000001 && cc_shadowLPNNInfo.x < 1.999999) { + // enabled linear depth + #if CC_SHADOWMAP_USE_LINEAR_DEPTH + clipDepth = CCGetLinearDepth(v_worldPos.xyz); + #endif + } + + #if CC_SHADOWMAP_FORMAT == SHADOWMAP_FORMAT_RGBA8 + return packDepthToRGBA(clipDepth); + #else + return vec4(clipDepth, 1.0, 1.0, 1.0); + #endif + } +}% diff --git a/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta b/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta new file mode 100644 index 0000000000..a410f41320 --- /dev/null +++ b/editor/assets/effects/dcc/imported-specular-glossiness.effect.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.5.7", + "importer": "effect", + "imported": true, + "uuid": "f648964e-8d32-41fc-9ac9-7a1e714dd17b", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect b/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect new file mode 100644 index 0000000000..a7e51a0614 --- /dev/null +++ b/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect @@ -0,0 +1,377 @@ +// Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + +CCEffect %{ + techniques: + - name: opaque + passes: + - vert: standard-vs + frag: standard-fs + properties: &props + tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, linear: true, editor: { displayName: BaseColor, type: color } } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: BaseColorMap } } + baseWeightMap: { value: grey } + albedoScale: { value: 1.0, editor: { displayName: BaseWeight } } + roughness: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + roughnessMap: { value: grey } + metallic: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + metallicMap: { value: grey } + occlusion: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + occlusionMap: { value: white } + emissiveScale: { value: 1.0, editor: { displayName: Emissive } } + emissiveScaleMap: { value: grey, editor: { displayName: EmissiveMap } } + emissive: { value: [0.0, 0.0, 0.0, 1.0], linear: true, editor: { displayName: EmissiveColor, type: color} } + emissiveMap: { value: grey, editor: { displayName: EmissiveColorMap } } + alphaSource: { value: 1.0, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + alphaSourceMap: { value: grey, editor: { parent: USE_OPACITY_MAP } } + alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } + normalStrength: { value: 1.0, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 1.0], step: 0.001 } } + normalMap: { value: normal } + - &forward-add + vert: standard-vs + frag: standard-fs + phase: forward-add + propertyIndex: 0 + embeddedMacros: { CC_FORWARD_ADD: true } + depthStencilState: + depthFunc: equal + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: one + blendDst: one + blendSrcAlpha: zero + blendDstAlpha: one + - &shadow-caster + vert: shadow-caster-vs + frag: shadow-caster-fs + phase: shadow-caster + propertyIndex: 0 + 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 } } + - name: transparent + passes: + - vert: standard-vs + frag: standard-fs + embeddedMacros: { CC_FORCE_FORWARD_SHADING: true } + depthStencilState: + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: src_alpha + blendDst: one_minus_src_alpha + blendDstAlpha: one_minus_src_alpha + properties: *props + - *forward-add + - *shadow-caster +}% + +CCProgram shared-ubos %{ + uniform Constants { + vec4 tilingOffset; + vec4 albedo; + vec4 albedoScaleAndCutoff; + vec4 emissive; + float emissiveScale; + float occlusion; + float roughness; + float metallic; + float normalStrength; + float alphaSource; + float albedoScale; + }; +}% + +CCProgram macro-remapping %{ + // ui displayed macros + #pragma define-meta HAS_SECOND_UV + #pragma define-meta USE_TWOSIDE + #pragma define-meta USE_REFLECTION_DENOISE + #pragma define-meta IS_ANISOTROPY + #pragma define-meta USE_VERTEX_COLOR + + #define CC_SURFACES_USE_SECOND_UV HAS_SECOND_UV + #define CC_SURFACES_USE_TWO_SIDED USE_TWOSIDE + #define CC_SURFACES_USE_REFLECTION_DENOISE USE_REFLECTION_DENOISE + #define CC_SURFACES_LIGHTING_ANISOTROPIC IS_ANISOTROPY + #define CC_SURFACES_USE_VERTEX_COLOR USE_VERTEX_COLOR + + // if disabled, simulate convoluted IBL without convolution + #pragma define-meta USE_COMPATIBLE_LIGHTING + #define CC_SURFACES_USE_LEGACY_COMPATIBLE_LIGHTING USE_COMPATIBLE_LIGHTING + + // depend on UI macros +#if IS_ANISOTROPY || USE_NORMAL_MAP + #define CC_SURFACES_USE_TANGENT_SPACE 1 +#endif + + // functionality for each effect + #define CC_SURFACES_LIGHTING_ANISOTROPIC_ENVCONVOLUTION_COUNT 31 +}% + +CCProgram surface-vertex %{ + #define CC_SURFACES_VERTEX_MODIFY_UV + void SurfacesVertexModifyUV(inout SurfacesStandardVertexIntermediate In) + { + In.texCoord = In.texCoord * tilingOffset.xy + tilingOffset.zw; + #if USE_SECOND_UV && !CC_USE_LIGHTMAP + In.texCoord1 = In.texCoord1 * tilingOffset.xy + tilingOffset.zw; + #endif + } +}% + +CCProgram surface-fragment %{ + #pragma define-meta TEXTURE_UV options([v_uv, v_uv1]) + #if USE_ALBEDO_MAP + uniform sampler2D albedoMap; + #endif + + #if USE_WEIGHT_MAP + uniform sampler2D baseWeightMap; + #endif + + #if USE_METALLIC_MAP + #pragma define-meta METALLIC_CHANNEL options([r, g, b, a]) + uniform sampler2D metallicMap; + #endif + + #if USE_ROUGHNESS_MAP + #pragma define-meta ROUGHNESS_CHANNEL options([r, g, b, a]) + uniform sampler2D roughnessMap; + #endif + + #if USE_OCCLUSION_MAP + #pragma define-meta OCCLUSION_CHANNEL options([r, g, b, a]) + uniform sampler2D occlusionMap; + #endif + + #if USE_TRANSPARENCY_MAP + uniform sampler2D transparencyMap; + #endif + + #if USE_TRANSPARENCYCOLOR_MAP + uniform sampler2D transparencyColorMap; + #endif + + #if USE_EMISSIVE_MAP + uniform sampler2D emissiveMap; + #endif + #if USE_EMISSIVESCALE_MAP + uniform sampler2D emissiveScaleMap; + #endif + + #if USE_OPACITY_MAP + #pragma define-meta ALPHA_SOURCE_CHANNEL options([r, g, b, a]) + uniform sampler2D alphaSourceMap; + #endif + + #if USE_NORMAL_MAP + uniform sampler2D normalMap; + #pragma define-meta NORMAL_UV options([v_uv, v_uv1]) + #endif + + float discolor(vec3 srcColor) { + return dot(GRAY_VECTOR, srcColor); + } + + #define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY + vec4 SurfacesFragmentModifyBaseColorAndTransparency() + { + vec4 baseColor = albedo; + #if USE_VERTEX_COLOR + baseColor.rgb *= SRGBToLinear(FSInput_vertexColor.rgb); // use linear + baseColor.a *= FSInput_vertexColor.a; + #endif + + #if USE_ALBEDO_MAP + vec4 texColor = texture(albedoMap, TEXTURE_UV); + texColor.rgb = SRGBToLinear(texColor.rgb); + baseColor = texColor; + #endif + + #if USE_WEIGHT_MAP + vec4 weightColor = texture(baseWeightMap, TEXTURE_UV); + weightColor.rgb = SRGBToLinear(weightColor.rgb); + baseColor.rgb *= weightColor.rgb; + #else + baseColor.rgb *= albedoScale; + #endif + #if ALPHA_SOURCE_IS_OPACITY + #if USE_OPACITY_MAP + baseColor.a = 1.0 - texture(alphaSourceMap, TEXTURE_UV).ALPHA_SOURCE_CHANNEL; + #else + baseColor.a = 1.0 - alphaSource; + #endif + #else + #if USE_OPACITY_MAP + baseColor.a = texture(alphaSourceMap, TEXTURE_UV).ALPHA_SOURCE_CHANNEL; + #else + baseColor.a = alphaSource; + #endif + #endif + #if USE_ALPHA_TEST + if (baseColor.a < albedoScaleAndCutoff.w) discard; + #endif + return baseColor; + } + + #define CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL + vec3 SurfacesFragmentModifyWorldNormal() + { + vec3 normal = FSInput_worldNormal; + #if USE_NORMAL_MAP + vec3 nmmp = texture(normalMap, NORMAL_UV).xyz - vec3(0.5); + normal = CalculateNormalFromTangentSpace(nmmp, normalStrength, normal.xyz, FSInput_worldTangent, FSInput_mirrorNormal); + #endif + + return normalize(normal); + } + + #define CC_SURFACES_FRAGMENT_MODIFY_EMISSIVE + vec3 SurfacesFragmentModifyEmissive() + { + //emissive color + vec3 emissiveColor = emissive.rgb; + #if USE_EMISSIVE_MAP + emissiveColor.rgb = SRGBToLinear(texture(emissiveMap, TEXTURE_UV).rgb); + #endif + //emissive color scale + #if USE_EMISSIVESCALE_MAP + vec4 emissiveScaleColor = texture(emissiveScaleMap, TEXTURE_UV); + emissiveScaleColor.rgb = SRGBToLinear(emissiveScaleColor.rgb); + emissiveColor.rgb *= emissiveScaleColor.rgb; + #else + emissiveColor.rgb *= emissiveScale; + #endif + + return emissiveColor.rgb; + } + + #define CC_SURFACES_FRAGMENT_MODIFY_PBRPARAMS + vec4 SurfacesFragmentModifyPBRParams() + { + vec4 pbr = vec4(1.0,1.0,1.0,1.0); + //ao + float occlusionValue = occlusion; + #if USE_OCCLUSION_MAP + vec4 occlusionColor = texture(occlusionMap, TEXTURE_UV); + occlusionValue = discolor(occlusionColor.rgb); + #if USE_OCCLUSION_CHANNEL + occlusionColor.rgb = SRGBToLinear(occlusionColor.rgb); + occlusionValue = occlusionColor.OCCLUSION_CHANNEL; + #endif + #endif + pbr.x = occlusionValue; + + //roughness + float roughnessValue = roughness; + #if USE_ROUGHNESS_MAP + vec4 roughnessColor = texture(roughnessMap, TEXTURE_UV); + roughnessValue = discolor(roughnessColor.rgb); + #if USE_ROUGHNESS_CHANNEL + roughnessColor.rgb = SRGBToLinear(roughnessColor.rgb); + roughnessValue = roughnessColor.ROUGHNESS_CHANNEL; + #endif + #endif + //fit specular ior=1.5 + pbr.y = max(0.02, roughnessValue); + + //metallic + float metallicValue = metallic; + #if USE_METALLIC_MAP + vec4 metallicColor = texture(metallicMap, TEXTURE_UV); + metallicValue = discolor(metallicColor.rgb); + #if USE_METALLIC_CHANNEL + metallicColor.rgb = SRGBToLinear(metallicColor.rgb); + metallicValue = metallicColor.METALLIC_CHANNEL; + #endif + #endif + pbr.z = metallicValue; + + //specularIntensity + pbr.w = 0.5; + return pbr; + } +}% + +CCProgram standard-vs %{ + precision highp float; + + // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros + #include + #include + + // 2. common include with corresponding shader stage, include before surface functions + #include + + // 3. user surface functions that can use user (effect) parameters (ubo Constants) + // see surfaces/default-functions/xxx.chunk + #include + #include + + // 4. surface include with corresponding shader stage and shading-model (optional) + #include + + // 5. shader entry with corresponding shader stage and technique usage/type + #include +}% + + +CCProgram shadow-caster-vs %{ + precision highp float; + #include + #include + #include + #include + #include +}% + + + +CCProgram standard-fs %{ + // shading-model : standard + // lighting-model : standard (isotropy / anisotropy pbr) + // shader stage : fs + // technique usage/type : render-to-scene + + precision highp float; + // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros + #include + #include + + // 2. common include with corresponding shader stage, include before surface functions + #include + + // 3. user surface functions that can use user (effect) parameters (ubo Constants) + // see surfaces/default-functions/xxx.chunk + #include + #include + + // 4. lighting-model (optional) + #include + + // 5. surface include with corresponding shader stage and shading-model (optional) + #include + + // 6. shader entry with corresponding shader stage and technique usage/type + #include +}% + +CCProgram shadow-caster-fs %{ + precision highp float; + #include + #include + #include + #include + #include +}% diff --git a/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta b/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta new file mode 100644 index 0000000000..78dc909476 --- /dev/null +++ b/editor/assets/effects/dcc/surfaces-imported-metallic-roughness.effect.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.5.7", + "importer": "effect", + "imported": true, + "uuid": "994bae8e-8bfc-4bc4-a32d-ad924f9917d0", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect new file mode 100644 index 0000000000..fff8749109 --- /dev/null +++ b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect @@ -0,0 +1,395 @@ +// Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. + +CCEffect %{ + techniques: + - name: opaque + passes: + - vert: standard-vs + frag: standard-fs + properties: &props + 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 } } + 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' } } + shininessExponent: { value: 100.0, editor: { parent: '!HAS_EXPORTED_GLOSSINESS' } } + specularColor: { value: [0.0, 0.0, 0.0, 0.0], linear: true, editor: { displayName: SpecularColor, type: color } } + 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 } } + 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 } + glossiness: { value: 0.0, editor: { parent: HAS_EXPORTED_GLOSSINESS, slide: true, range: [0, 1.0], step: 0.001 } } + metallic: { value: 0.0, editor: { parent: HAS_EXPORTED_METALLIC, slide: true, range: [0, 1.0], step: 0.001 } } + metallicMap: { value: grey, editor: { parent: HAS_EXPORTED_METALLIC } } + occlusionMap: { value: white } + - &forward-add + vert: standard-vs + frag: standard-fs + phase: forward-add + propertyIndex: 0 + embeddedMacros: { CC_FORWARD_ADD: true } + depthStencilState: + depthFunc: equal + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: one + blendDst: one + blendSrcAlpha: zero + blendDstAlpha: one + - &shadow-caster + vert: shadow-caster-vs + frag: shadow-caster-fs + phase: shadow-caster + propertyIndex: 0 + 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 } } + - name: transparent + passes: + - vert: standard-vs + frag: standard-fs + embeddedMacros: { CC_FORCE_FORWARD_SHADING: true } + depthStencilState: + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: src_alpha + blendDst: one_minus_src_alpha + blendDstAlpha: one_minus_src_alpha + properties: *props + - *forward-add + - *shadow-caster +}% + +CCProgram shared-ubos %{ + uniform Constants { + vec4 tilingOffset; + vec4 albedo; + vec4 albedoScaleAndCutoff; + + vec4 diffuseColor; + vec4 specularColor; + vec4 emissive; + float alphaThreshold; + float shininessExponent; + float glossiness; + float metallic; + float normalScale; + float transparencyFactor; + float diffuseFactor; + float specularFactor; + }; +}% + +CCProgram macro-remapping %{ + // ui displayed macros + #pragma define-meta HAS_SECOND_UV + #pragma define-meta USE_TWOSIDE + #pragma define-meta USE_REFLECTION_DENOISE + #pragma define-meta IS_ANISOTROPY + #pragma define-meta USE_VERTEX_COLOR + + #define CC_SURFACES_USE_SECOND_UV HAS_SECOND_UV + #define CC_SURFACES_USE_TWO_SIDED USE_TWOSIDE + #define CC_SURFACES_USE_REFLECTION_DENOISE USE_REFLECTION_DENOISE + #define CC_SURFACES_LIGHTING_ANISOTROPIC IS_ANISOTROPY + #define CC_SURFACES_USE_VERTEX_COLOR USE_VERTEX_COLOR + + // if disabled, simulate convoluted IBL without convolution + #pragma define-meta USE_COMPATIBLE_LIGHTING + #define CC_SURFACES_USE_LEGACY_COMPATIBLE_LIGHTING USE_COMPATIBLE_LIGHTING + + // depend on UI macros +#if IS_ANISOTROPY || USE_NORMAL_MAP + #define CC_SURFACES_USE_TANGENT_SPACE 1 +#endif + + // functionality for each effect + #define CC_SURFACES_LIGHTING_ANISOTROPIC_ENVCONVOLUTION_COUNT 31 +}% + +CCProgram surface-vertex %{ + #define CC_SURFACES_VERTEX_MODIFY_UV + void SurfacesVertexModifyUV(inout SurfacesStandardVertexIntermediate In) + { + In.texCoord = In.texCoord * tilingOffset.xy + tilingOffset.zw; + #if USE_SECOND_UV && !CC_USE_LIGHTMAP + In.texCoord1 = In.texCoord1 * tilingOffset.xy + tilingOffset.zw; + #endif + } +}% + + +CCProgram surface-fragment %{ + #pragma define-meta TEXTURE_UV options([v_uv, v_uv1]) + #pragma define-meta DCC_APP_NAME range([0, 4]) + #define DCC_APP_OTHERS 0 + #define DCC_APP_AUTODESK 1 + #define DCC_APP_BLENDER 2 + #define DCC_APP_CINEMA4D 3 + #define DCC_APP_GLTF 4 + + #if USE_SHININESS_MAP + uniform sampler2D shininessExponentMap; + #pragma define-meta GLOSSINESS_MAP_CHANNEL options([r,g,b,a]) + #endif + #if USE_SPECULAR_MAP + uniform sampler2D specularMap; + #endif + #if USE_METALLIC_MAP + uniform sampler2D metallicMap; + #endif + + #if USE_ALBEDO_MAP + uniform sampler2D albedoMap; + #endif + #if USE_TRANSPARENCY_MAP + uniform sampler2D transparencyMap; + #endif + + #if USE_EMISSIVE_MAP + uniform sampler2D emissiveMap; + #endif + + #if USE_NORMAL_MAP + uniform sampler2D normalMap; + #pragma define-meta NORMAL_UV options([v_uv, v_uv1]) + #endif + + #if USE_OCCLUSION_MAP + uniform sampler2D occlusionMap; + #pragma define-meta OCCLUSION_UV options([v_uv, v_uv1]) + #pragma define-meta OCCLUSION_CHANNEL options([r,g,b,a]) + #endif + + float discolor(vec3 srcColor) + { + return dot(GRAY_VECTOR, srcColor); + } + float convertShininessExponent(float shininessExp) + { + #if DCC_APP_NAME == DCC_APP_BLENDER + // 2-100 + float glossiness = clamp(sqrt(shininessExp) * 0.1/*/10.0*/, 0.0, 0.95); // glossiness=1 may leads to specular disappear + #elif DCC_APP_NAME == DCC_APP_AUTODESK + // 2-1024 + float l2 = clamp(log(shininessExp + EPSILON) * 0.1442695 /*/log(2.0)/10.0*/, 0.0, 1.0); + float glossiness = pow(l2, 0.5); + #else // DCC_APP_NAME == DCC_APP_CINEMA4D、DCC_APP_GLTF、DCC_APP_OTHERS + // 2-1024 + float glossiness = clamp(log(shininessExp + EPSILON) * 0.1442695 /*/log(2.0)/10.0*/, 0.0, 1.0); + #endif + return glossiness; + } + float getSpecularIntensityFromRoughness(float roughness) + { + #if DCC_APP_NAME == DCC_APP_BLENDER + float specularIntensityMultiplier = mix(1.0, 5.0, roughness); + #elif DCC_APP_NAME == DCC_APP_CINEMA4D + float specularIntensityMultiplier = mix(1.0, 50.0, roughness); + #elif DCC_APP_NAME == DCC_APP_AUTODESK + float specularIntensityMultiplier = mix(1.0, 20.0, roughness); + #else // DCC_APP_NAME == DCC_APP_GLTF、DCC_APP_OTHERS + float specularIntensityMultiplier = 1.0; + #endif + return specularIntensityMultiplier; + } + + vec4 getSpecularColorAndFactor() + { + vec3 inSpecular = specularColor.rgb; + #if USE_SPECULAR_MAP + vec4 specularTex = texture(specularMap, TEXTURE_UV); + specularTex.rgb = SRGBToLinear(specularTex.rgb); + inSpecular = specularTex.rgb; + #endif + return vec4(inSpecular, specularFactor); + } + + #define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY + vec4 SurfacesFragmentModifyBaseColorAndTransparency() + { + //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; + } + + #define CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL + vec3 SurfacesFragmentModifyWorldNormal() + { + vec3 normal = FSInput_worldNormal; + #if USE_NORMAL_MAP + vec3 nmmp = texture(normalMap, NORMAL_UV).xyz - vec3(0.5); + normal = CalculateNormalFromTangentSpace(nmmp, normalScale, normal.xyz, FSInput_worldTangent, FSInput_mirrorNormal); + #endif + + return normalize(normal); + } + + #define CC_SURFACES_FRAGMENT_MODIFY_EMISSIVE + vec3 SurfacesFragmentModifyEmissive() + { + vec3 emissiveColor = emissive.rgb; + #if USE_EMISSIVE_MAP + emissiveColor = texture(emissiveMap, TEXTURE_UV).xyz; + #endif + return emissiveColor; + } + + #define CC_SURFACES_FRAGMENT_MODIFY_SHARED_DATA + #include + void SurfacesFragmentModifySharedData(inout SurfacesMaterialData surfaceData) + { + vec4 baseColor = diffuseColor; + #if USE_VERTEX_COLOR + baseColor.rgb *= SRGBToLinear(FSInput_vertexColor.rgb); // use linear + baseColor.a *= FSInput_vertexColor.a; + #endif + #if USE_ALBEDO_MAP + vec4 texColor = texture(albedoMap, TEXTURE_UV); + texColor.rgb = SRGBToLinear(texColor.rgb); + baseColor = texColor; + #else + baseColor.rgb *= diffuseFactor; + #endif + + vec4 specularColorAndFactor = getSpecularColorAndFactor(); + //glossiness + float inGlossiness = 0.0, inSpecularIntensity = specularColorAndFactor.w; + #if HAS_EXPORTED_GLOSSINESS + inGlossiness = glossiness; + #else + #if USE_SHININESS_MAP + #if GLOSSINESS_MAP_USE_SINGLE_CHANNEL + inGlossiness = 1.0 - texture(shininessExponentMap, TEXTURE_UV).GLOSSINESS_MAP_CHANNEL; + #else + inGlossiness = 1.0 - discolor(texture(shininessExponentMap, TEXTURE_UV).rgb); + #endif + #else + inGlossiness = convertShininessExponent(shininessExponent); + #endif + inSpecularIntensity *= getSpecularIntensityFromRoughness(1.0 - inGlossiness); + #endif + + //metallic + float inMetallic = 0.0; + vec3 albedo = baseColor.rgb; + #if HAS_EXPORTED_METALLIC + inMetallic = metallic; + float spec = specularFactor; + #if USE_SPECULAR_MAP + spec = dot(GRAY_VECTOR, texture(specularMap, TEXTURE_UV).rgb); + #endif + inSpecularIntensity *= spec * 0.5; //0.5 is suitable for blender + #else + GetMetallicAlbedoFromDiffuseSpecularWithoutColor(inMetallic, albedo.rgb, baseColor.rgb, specularColorAndFactor.rgb, 0.04); + inSpecularIntensity *= inMetallic; //simulate specular color is black + #endif + baseColor.rgb = albedo; + + surfaceData.baseColor.rgb = baseColor.rgb; + surfaceData.specularIntensity = inSpecularIntensity * 0.5; + surfaceData.roughness = 1.0 - inGlossiness; + surfaceData.metallic = inMetallic; + surfaceData.ao = 1.0; + #if USE_OCCLUSION_MAP + surfaceData.ao = texture(occlusionMap, OCCLUSION_UV).OCCLUSION_CHANNEL; + #endif + } +}% + +CCProgram standard-vs %{ + precision highp float; + + // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros + #include + #include + + // 2. common include with corresponding shader stage, include before surface functions + #include + + // 3. user surface functions that can use user (effect) parameters (ubo Constants) + // see surfaces/default-functions/xxx.chunk + #include + #include + + // 4. surface include with corresponding shader stage and shading-model (optional) + #include + + // 5. shader entry with corresponding shader stage and technique usage/type + #include +}% + + +CCProgram shadow-caster-vs %{ + precision highp float; + #include + #include + #include + #include + #include +}% + + + +CCProgram standard-fs %{ + // shading-model : standard + // lighting-model : standard (isotropy / anisotropy pbr) + // shader stage : fs + // technique usage/type : render-to-scene + + precision highp float; + // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros + #include + #include + + // 2. common include with corresponding shader stage, include before surface functions + #include + + // 3. user surface functions that can use user (effect) parameters (ubo Constants) + // see surfaces/default-functions/xxx.chunk + #include + #include + + // 4. lighting-model (optional) + #include + + // 5. surface include with corresponding shader stage and shading-model (optional) + #include + + // 6. shader entry with corresponding shader stage and technique usage/type + #include +}% + +CCProgram shadow-caster-fs %{ + precision highp float; + #include + #include + #include + #include + #include +}% diff --git a/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta new file mode 100644 index 0000000000..29279dae5d --- /dev/null +++ b/editor/assets/effects/dcc/surfaces-imported-specular-glossiness.effect.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.5.7", + "importer": "effect", + "imported": true, + "uuid": "5b7d6814-90a6-4d9f-b7fd-410dca9de957", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/effects/editor/gizmo.effect b/editor/assets/effects/editor/gizmo.effect index cd40bfd90f..a55cfccb3f 100644 --- a/editor/assets/effects/editor/gizmo.effect +++ b/editor/assets/effects/editor/gizmo.effect @@ -56,8 +56,8 @@ CCEffect %{ CCProgram gizmo-vs %{ precision mediump float; - #include - #include + #include + #include in vec3 a_position; in vec3 a_normal; @@ -85,10 +85,10 @@ CCProgram gizmo-vs %{ CCProgram gizmo-fs %{ precision mediump float; - #include - #include - #include - #include + #include + #include + #include + #include in vec3 normal_w; in vec3 pos_w; @@ -125,8 +125,8 @@ CCProgram gizmo-fs %{ CCProgram line-vs %{ precision mediump float; - #include - #include + #include + #include in highp vec3 a_position; @@ -147,7 +147,7 @@ CCProgram line-vs %{ CCProgram line-fs %{ precision mediump float; - #include + #include uniform Constant { vec4 mainColor; @@ -178,8 +178,8 @@ CCProgram line-fs %{ CCProgram sprite-vs %{ precision mediump float; - #include - #include + #include + #include in vec3 a_position; in vec2 a_texCoord; @@ -198,7 +198,7 @@ CCProgram sprite-vs %{ CCProgram sprite-fs %{ precision mediump float; - #include + #include in vec2 uv0; uniform Constant { diff --git a/editor/assets/effects/editor/gizmo.effect.meta b/editor/assets/effects/editor/gizmo.effect.meta index 938823684a..d04dd02b1f 100644 --- a/editor/assets/effects/editor/gizmo.effect.meta +++ b/editor/assets/effects/editor/gizmo.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "9d6c6bde-2fe2-44ee-883b-909608948b04", diff --git a/editor/assets/effects/editor/grid-2d.effect b/editor/assets/effects/editor/grid-2d.effect index f151e6f563..f1595bda7c 100644 --- a/editor/assets/effects/editor/grid-2d.effect +++ b/editor/assets/effects/editor/grid-2d.effect @@ -20,8 +20,8 @@ CCEffect %{ CCProgram grid-vs %{ precision mediump float; - #include - #include + #include + #include in vec2 a_position; in vec4 a_color; @@ -40,7 +40,7 @@ CCProgram grid-vs %{ CCProgram grid-fs %{ precision mediump float; in vec4 color; - #include + #include vec4 frag () { vec4 o = vec4(1, 1, 1, 1); diff --git a/editor/assets/effects/editor/grid-2d.effect.meta b/editor/assets/effects/editor/grid-2d.effect.meta index 50aba76f1f..0de78e4d9a 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.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "cb2c332a-fa5e-4235-a129-f011634bb7ad", diff --git a/editor/assets/effects/editor/grid-stroke.effect b/editor/assets/effects/editor/grid-stroke.effect index 3e0d5b1320..0a3848de62 100644 --- a/editor/assets/effects/editor/grid-stroke.effect +++ b/editor/assets/effects/editor/grid-stroke.effect @@ -32,7 +32,7 @@ CCEffect %{ */ CCProgram grid-vs %{ precision mediump float; - #include + #include in vec2 a_texCoord; in vec3 a_position; @@ -57,8 +57,8 @@ CCProgram grid-vs %{ CCProgram grid-fs %{ precision mediump float; - #include - #include + #include + #include in vec2 uv; in vec3 pos_w; diff --git a/editor/assets/effects/editor/grid-stroke.effect.meta b/editor/assets/effects/editor/grid-stroke.effect.meta index 9c25c605eb..29685ea2bb 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.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "4736e978-c8fa-449f-9cf6-fe0158ded9d7", diff --git a/editor/assets/effects/editor/grid.effect b/editor/assets/effects/editor/grid.effect index 6993397a57..c4a10d9666 100644 --- a/editor/assets/effects/editor/grid.effect +++ b/editor/assets/effects/editor/grid.effect @@ -20,8 +20,8 @@ CCEffect %{ CCProgram grid-vs %{ precision mediump float; - #include - #include + #include + #include in vec2 a_position; in vec4 a_color; @@ -41,8 +41,8 @@ CCProgram grid-vs %{ CCProgram grid-fs %{ precision mediump float; - #include - #include + #include + #include in vec4 color; in vec3 pos_w; diff --git a/editor/assets/effects/editor/grid.effect.meta b/editor/assets/effects/editor/grid.effect.meta index 5ca08b286d..78d9c604ea 100644 --- a/editor/assets/effects/editor/grid.effect.meta +++ b/editor/assets/effects/editor/grid.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "ba35f02e-a81c-464c-bfc5-c788328da667", diff --git a/editor/assets/effects/editor/light.effect b/editor/assets/effects/editor/light.effect index 0ad95f064f..8176ed6cd4 100644 --- a/editor/assets/effects/editor/light.effect +++ b/editor/assets/effects/editor/light.effect @@ -20,9 +20,9 @@ CCEffect %{ CCProgram light-vs %{ precision mediump float; - #include - #include - #include + #include + #include + #include in vec3 a_position; in vec2 a_texCoord; @@ -36,7 +36,7 @@ CCProgram light-vs %{ CCProgram light-fs %{ precision mediump float; - #include + #include uniform Constant { vec4 mainColor; diff --git a/editor/assets/effects/editor/light.effect.meta b/editor/assets/effects/editor/light.effect.meta index 9007cd93d0..6d7e64d869 100644 --- a/editor/assets/effects/editor/light.effect.meta +++ b/editor/assets/effects/editor/light.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "e4e4cb19-8dd2-450d-ad20-1a818263b8d3", diff --git a/editor/assets/effects/editor/terrain-circle-brush.effect b/editor/assets/effects/editor/terrain-circle-brush.effect index 807fcb0a0f..f06f6b0baf 100644 --- a/editor/assets/effects/editor/terrain-circle-brush.effect +++ b/editor/assets/effects/editor/terrain-circle-brush.effect @@ -23,8 +23,8 @@ CCEffect %{ CCProgram terrain-brush-vs %{ precision mediump float; - #include - #include + #include + #include in vec3 a_position; @@ -48,7 +48,7 @@ CCProgram terrain-brush-vs %{ CCProgram terrain-brush-fs %{ precision mediump float; - #include + #include in vec4 wposition; diff --git a/editor/assets/effects/editor/terrain-circle-brush.effect.meta b/editor/assets/effects/editor/terrain-circle-brush.effect.meta index 81248cf2aa..02be42bc8f 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.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "a3e72674-c38f-4336-a285-1826b1799cd7", diff --git a/editor/assets/effects/editor/terrain-image-brush.effect b/editor/assets/effects/editor/terrain-image-brush.effect index 784996aa34..fe3d9f227f 100644 --- a/editor/assets/effects/editor/terrain-image-brush.effect +++ b/editor/assets/effects/editor/terrain-image-brush.effect @@ -24,8 +24,8 @@ CCEffect %{ CCProgram terrain-brush-vs %{ precision mediump float; - #include - #include + #include + #include in vec3 a_position; @@ -49,7 +49,7 @@ CCProgram terrain-brush-vs %{ CCProgram terrain-brush-fs %{ precision mediump float; - #include + #include in vec4 wposition; @@ -63,9 +63,21 @@ CCProgram terrain-brush-fs %{ vec4 frag () { float Radius = BrushParams.x; float Falloff = BrushParams.y; + float Rotation = BrushParams.z; float DeltaU = BrushPos.x - wposition.x; float DeltaV = BrushPos.z - wposition.z; + if (Rotation != 0.0) { + float sine = sin(Rotation); + float cosine = cos(Rotation); + float _11 = cosine, _21 = sine; + float _12 = -sine, _22 = cosine; + float tmpx = DeltaU * _11 + DeltaV * _21; + float tmpz = DeltaU * _12 + DeltaV * _22; + DeltaU = tmpx; + DeltaV = tmpz; + } + float k = 0.0; if (abs(DeltaU) < Radius && abs(DeltaV) < Radius) { float u = DeltaU / Radius * 0.5 + 0.5; diff --git a/editor/assets/effects/editor/terrain-image-brush.effect.meta b/editor/assets/effects/editor/terrain-image-brush.effect.meta index 37fb8d1cba..bdf635471b 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.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "7a115de7-2d94-4620-8b89-766d7f8cbff9", diff --git a/editor/assets/effects/editor/terrain-select-brush.effect b/editor/assets/effects/editor/terrain-select-brush.effect index b7324d1737..cdee16ca51 100644 --- a/editor/assets/effects/editor/terrain-select-brush.effect +++ b/editor/assets/effects/editor/terrain-select-brush.effect @@ -19,8 +19,8 @@ CCEffect %{ CCProgram terrain-brush-vs %{ precision mediump float; - #include - #include + #include + #include in vec3 a_position; @@ -40,7 +40,7 @@ CCProgram terrain-brush-vs %{ CCProgram terrain-brush-fs %{ precision mediump float; - #include + #include vec4 frag () { vec4 color = vec4(0.0, 0.0, 0.0, 0.0); diff --git a/editor/assets/effects/editor/terrain-select-brush.effect.meta b/editor/assets/effects/editor/terrain-select-brush.effect.meta index bd2d8d8fac..63be517a0b 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.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "9b4d3fa5-89bf-4715-b69a-dbbd1efaf6a5", diff --git a/editor/assets/effects/pipeline/bloom.effect b/editor/assets/effects/pipeline/bloom.effect index f765310b59..c1593f05c7 100644 --- a/editor/assets/effects/pipeline/bloom.effect +++ b/editor/assets/effects/pipeline/bloom.effect @@ -44,9 +44,9 @@ CCEffect %{ CCProgram bloom-vs %{ precision highp float; - #include - #include - #include + #include + #include + #include out vec2 v_uv; @@ -62,8 +62,8 @@ CCProgram bloom-vs %{ CCProgram prefilter-fs %{ precision highp float; - #include - #include + #include + #include in vec2 v_uv; @@ -91,7 +91,7 @@ CCProgram prefilter-fs %{ CCProgram downsample-fs %{ precision highp float; - #include + #include in vec2 v_uv; @@ -133,7 +133,7 @@ CCProgram downsample-fs %{ CCProgram upsample-fs %{ precision highp float; - #include + #include in vec2 v_uv; @@ -175,7 +175,7 @@ CCProgram upsample-fs %{ CCProgram combine-fs %{ precision highp float; - #include + #include in vec2 v_uv; diff --git a/editor/assets/effects/pipeline/bloom.effect.meta b/editor/assets/effects/pipeline/bloom.effect.meta index 387c60543f..4c2ea4ad1f 100644 --- a/editor/assets/effects/pipeline/bloom.effect.meta +++ b/editor/assets/effects/pipeline/bloom.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "28d6d6b8-3f66-4a73-9795-17a0852ba2d4", diff --git a/editor/assets/effects/pipeline/deferred-lighting.effect b/editor/assets/effects/pipeline/deferred-lighting.effect index 88c793fdc3..e1f3526970 100644 --- a/editor/assets/effects/pipeline/deferred-lighting.effect +++ b/editor/assets/effects/pipeline/deferred-lighting.effect @@ -14,9 +14,9 @@ CCEffect %{ CCProgram lighting-vs %{ precision highp float; - #include - #include - #include + #include + #include + #include out vec2 v_uv; @@ -31,15 +31,16 @@ CCProgram lighting-vs %{ CCProgram lighting-fs %{ precision highp float; - #include - #include - #include + #include + #include + #include #if CC_ENABLE_CLUSTERED_LIGHT_CULLING == 1 - #include + #include #endif - #include - #include - #include + #include + #include + #include + #include in vec2 v_uv; @@ -49,22 +50,40 @@ CCProgram lighting-fs %{ layout(binding = 0, input_attachment_index = 0) uniform subpassInput gbuffer_albedoMap; layout(binding = 1, input_attachment_index = 1) uniform subpassInput gbuffer_normalMap; layout(binding = 2, input_attachment_index = 2) uniform subpassInput gbuffer_emissiveMap; + layout(binding = 3, input_attachment_index = 3) uniform subpassInput depth_stencil; #elif __VERSION__ >= 300 layout(location = 0) inout vec4 gbuffer_albedoMap; layout(location = 1) inout vec4 gbuffer_normalMap; layout(location = 2) inout vec4 gbuffer_emissiveMap; + layout(binding = 3) uniform sampler2D depth_stencil; + #else + layout(binding = 3) uniform sampler2D depth_stencil; #endif #else layout(binding = 0) uniform sampler2D gbuffer_albedoMap; layout(binding = 1) uniform sampler2D gbuffer_normalMap; layout(binding = 2) uniform sampler2D gbuffer_emissiveMap; + layout(binding = 3) uniform sampler2D depth_stencil; #endif - layout(binding = 3) uniform sampler2D depth_stencil; #if !CC_DEVICE_CAN_BENEFIT_FROM_INPUT_ATTACHMENT || __VERSION__ >= 450 layout(location = 0) out vec4 fragColor; #endif + + vec4 screen2WS(vec3 coord) { + vec3 ndc = vec3( + 2.0 * (coord.x - cc_viewPort.x) / cc_viewPort.z - 1.0, + 2.0 * (coord.y - cc_viewPort.y) / cc_viewPort.w - 1.0, + #if __VERSION__ >= 450 + coord.z); + #else + 2.0 * coord.z - 1.0); + #endif + + return GetWorldPosFromNDCPosRH(ndc, cc_matProj, cc_matViewProjInv); + } + void main () { StandardSurface s; @@ -73,27 +92,31 @@ CCProgram lighting-fs %{ vec4 albedoMap = subpassLoad(gbuffer_albedoMap); vec4 normalMap = subpassLoad(gbuffer_normalMap); vec4 emissiveMap = subpassLoad(gbuffer_emissiveMap); + float depth = subpassLoad(depth_stencil).x; #elif __VERSION__ >= 300 vec4 albedoMap = gbuffer_albedoMap; vec4 normalMap = gbuffer_normalMap; vec4 emissiveMap = gbuffer_emissiveMap; + float depth = texture(depth_stencil, v_uv).x; #else vec4 albedoMap = gl_LastFragData[0]; vec4 normalMap = gl_LastFragData[1]; - vec4 emissiveMap = gl_LastFragDat[2]; + vec4 emissiveMap = gl_LastFragData[2]; + float depth = texture(depth_stencil, v_uv).x; #endif #else vec4 albedoMap = texture(gbuffer_albedoMap,v_uv); vec4 normalMap = texture(gbuffer_normalMap,v_uv); vec4 emissiveMap = texture(gbuffer_emissiveMap,v_uv); + float depth = texture(depth_stencil, v_uv).x; #endif - float depth = texture(depth_stencil, v_uv).x; s.albedo = albedoMap; vec3 position = screen2WS(vec3(gl_FragCoord.xy, depth)).xyz; s.position = position; s.roughness = normalMap.z; s.normal = oct_to_float32x3(normalMap.xy); + s.specularIntensity = 0.5; s.metallic = normalMap.w; s.emissive = emissiveMap.xyz; s.occlusion = emissiveMap.w; diff --git a/editor/assets/effects/pipeline/deferred-lighting.effect.meta b/editor/assets/effects/pipeline/deferred-lighting.effect.meta index 5fe58c75b8..9b7398987d 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.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "5d45aa00-e064-4938-b314-4265f0c2258c", diff --git a/editor/assets/effects/pipeline/planar-shadow.effect b/editor/assets/effects/pipeline/planar-shadow.effect index bf772be1dc..9ce981af16 100644 --- a/editor/assets/effects/pipeline/planar-shadow.effect +++ b/editor/assets/effects/pipeline/planar-shadow.effect @@ -25,10 +25,11 @@ CCEffect %{ CCProgram planar-shadow-vs %{ precision highp float; - #include - #include - #include - #include + #include + #include + #include + #include + #include out float v_dist; @@ -58,9 +59,9 @@ CCProgram planar-shadow-vs %{ }% CCProgram planar-shadow-fs %{ - precision mediump float; - #include - #include + precision highp float; + #include + #include in float v_dist; diff --git a/editor/assets/effects/pipeline/planar-shadow.effect.meta b/editor/assets/effects/pipeline/planar-shadow.effect.meta index ebc50a9fd3..602f81fcae 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.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "9361fd90-ba52-4f84-aa93-6e878fd576ca", diff --git a/editor/assets/effects/pipeline/post-process.effect b/editor/assets/effects/pipeline/post-process.effect index 62c329b31c..3125904c5e 100644 --- a/editor/assets/effects/pipeline/post-process.effect +++ b/editor/assets/effects/pipeline/post-process.effect @@ -20,9 +20,9 @@ CCEffect %{ CCProgram post-process-vs %{ precision highp float; - #include - #include - #include + #include + #include + #include out vec2 v_uv; @@ -38,8 +38,8 @@ CCProgram post-process-vs %{ CCProgram post-process-fs %{ precision highp float; - #include - #include + #include + #include in vec2 v_uv; layout(binding = 0) uniform sampler2D outputResultMap; diff --git a/editor/assets/effects/pipeline/post-process.effect.meta b/editor/assets/effects/pipeline/post-process.effect.meta index 06ad4cb66e..22332aa354 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.2", + "ver": "1.5.7", "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 c762d138f3..0d74301934 100644 --- a/editor/assets/effects/pipeline/skybox.effect +++ b/editor/assets/effects/pipeline/skybox.effect @@ -13,8 +13,8 @@ CCEffect %{ CCProgram sky-vs %{ precision highp float; - #include - #include + #include + #include out mediump vec4 viewDir; @@ -48,19 +48,20 @@ CCProgram sky-vs %{ CCProgram sky-fs %{ precision mediump float; - #include - #include - #include - #include - #include + #include + #include + #include + #include + #include + #include in mediump vec4 viewDir; vec4 frag () { #if USE_RGBE_CUBEMAP - vec3 c = unpackRGBE(texture(cc_environment, viewDir.xyz)); + vec3 c = unpackRGBE(fragTextureLod(cc_environment, viewDir.xyz, 0.0)); #else - vec3 c = SRGBToLinear(texture(cc_environment, viewDir.xyz).rgb); + vec3 c = SRGBToLinear(fragTextureLod(cc_environment, viewDir.xyz, 0.0).rgb); #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 5f4e2c1449..8772f85d25 100644 --- a/editor/assets/effects/pipeline/skybox.effect.meta +++ b/editor/assets/effects/pipeline/skybox.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "511d2633-09a7-4bdd-ac42-f778032124b3", diff --git a/editor/assets/effects/pipeline/smaa.effect b/editor/assets/effects/pipeline/smaa.effect index f338f8a6c4..37fb04cc15 100644 --- a/editor/assets/effects/pipeline/smaa.effect +++ b/editor/assets/effects/pipeline/smaa.effect @@ -36,7 +36,7 @@ CCEffect %{ CCProgram smaa-edge-vs %{ precision highp float; - #include + #include in vec2 a_position; in vec2 a_texCoord; @@ -56,10 +56,10 @@ CCProgram smaa-edge-vs %{ CCProgram smaa-edge-fs %{ precision highp float; - #include - #include - #include - #include + #include + #include + #include + #include #pragma define SMAA_THRESHOLD 0.1 @@ -115,7 +115,7 @@ CCProgram smaa-edge-fs %{ CCProgram smaa-blend-vs %{ precision highp float; - #include + #include #pragma define SMAA_MAX_SEARCH_STEPS 8 @@ -139,7 +139,7 @@ CCProgram smaa-blend-vs %{ CCProgram smaa-blend-fs %{ precision highp float; - #include + #include #pragma define SMAA_MAX_SEARCH_STEPS 8 #pragma define SMAA_AREATEX_MAX_DISTANCE 16 diff --git a/editor/assets/effects/pipeline/smaa.effect.meta b/editor/assets/effects/pipeline/smaa.effect.meta index cd3bd4eab7..77044b5679 100644 --- a/editor/assets/effects/pipeline/smaa.effect.meta +++ b/editor/assets/effects/pipeline/smaa.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "6624c63c-0e3d-4d5f-bd15-a7805b71c521", diff --git a/editor/assets/effects/pipeline/tonemap.effect b/editor/assets/effects/pipeline/tonemap.effect index af27f5e726..f30c67c397 100644 --- a/editor/assets/effects/pipeline/tonemap.effect +++ b/editor/assets/effects/pipeline/tonemap.effect @@ -22,8 +22,8 @@ CCEffect %{ CCProgram tonemap-vs %{ precision highp float; - #include - #include + #include + #include in vec2 a_position; in vec2 a_texCoord; @@ -41,10 +41,10 @@ CCProgram tonemap-vs %{ CCProgram tonemap-fs %{ precision highp float; - #include - #include - #include - #include + #include + #include + #include + #include in vec2 v_uv; in vec4 v_offset; diff --git a/editor/assets/effects/pipeline/tonemap.effect.meta b/editor/assets/effects/pipeline/tonemap.effect.meta index db882bfd65..20ffa1b2d1 100644 --- a/editor/assets/effects/pipeline/tonemap.effect.meta +++ b/editor/assets/effects/pipeline/tonemap.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "31b152ff-f689-4082-a292-3eb5a0b33014", diff --git a/editor/assets/effects/surfaces.meta b/editor/assets/effects/surfaces.meta new file mode 100644 index 0000000000..3c19b6aeec --- /dev/null +++ b/editor/assets/effects/surfaces.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.1.0", + "importer": "directory", + "imported": true, + "uuid": "943258e0-bb7e-46a9-8995-31c983e3b692", + "files": [], + "subMetas": {}, + "userData": { + "compressionType": {}, + "isRemoteBundle": {} + } +} diff --git a/editor/assets/effects/surfaces/sky.effect b/editor/assets/effects/surfaces/sky.effect new file mode 100644 index 0000000000..49e05e217d --- /dev/null +++ b/editor/assets/effects/surfaces/sky.effect @@ -0,0 +1,61 @@ +// Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + +CCEffect %{ + techniques: + - name: opaque + passes: + - vert: sky-vs + frag: sky-fs + priority : max - 10 + rasterizerState : + cullMode : none + depthStencilState : + depthTest: true + depthWrite : false +}% + + +CCProgram surface-vertex %{ + #define CC_SURFACES_VERTEX_MODIFY_WORLD_POS + vec3 SurfacesVertexModifyWorldPos(in SurfacesStandardVertexIntermediate In) + { + // Apply uniform scaling for atmosphere effects + return In.worldPos; + } +}% + +CCProgram surface-fragment %{ + #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); + #endif + #endif + return vec4(c * cc_ambientSky.w, 1.0); + } +}% + +CCProgram sky-vs %{ + precision highp float; + + #include + #include + #include + #include +}% + + +CCProgram sky-fs %{ + precision highp float; + + #include + #include + #include + #include +}% diff --git a/editor/assets/effects/surfaces/sky.effect.meta b/editor/assets/effects/surfaces/sky.effect.meta new file mode 100644 index 0000000000..e2aa6109bf --- /dev/null +++ b/editor/assets/effects/surfaces/sky.effect.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.5.7", + "importer": "effect", + "imported": true, + "uuid": "6308c013-7d49-4160-9516-562dd205b480", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/effects/surfaces/standard.effect b/editor/assets/effects/surfaces/standard.effect new file mode 100644 index 0000000000..54a73ad84b --- /dev/null +++ b/editor/assets/effects/surfaces/standard.effect @@ -0,0 +1,338 @@ +// Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + +CCEffect %{ + techniques: + - name: opaque + passes: + - vert: standard-vs + frag: standard-fs + properties: &props + tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, linear: true, 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, slide: true, range: [0, 1.0], step: 0.001 } } + occlusion: { value: 1.0, target: pbrParams.x, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + roughness: { value: 0.8, target: pbrParams.y, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + metallic: { value: 0.6, target: pbrParams.z, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + specularIntensity: { value: 0.5, target: pbrParams.w, editor: { slide: true, range: [0.0, 1.0], step: 0.001 } } + emissive: { value: [0.0, 0.0, 0.0, 1.0], linear: true, editor: { type: color } } + emissiveScale: { value: [1.0, 1.0, 1.0], target: emissiveScaleParam.xyz } + normalStrength: { value: 1.0, target: emissiveScaleParam.w, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 5.0], step: 0.001 } } + anisotropyShape: { value: 1.0, target: anisotropyParam.x, editor: { parent: IS_ANISOTROPY, slide : true, range : [0.0, 1.0] , step : 0.0001 } } + anisotropyRotation: { value: 0.0, target: anisotropyParam.y, editor: { parent: IS_ANISOTROPY, slide : true, range : [0, 1.0] , step : 0.0001 } } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + normalMap: { value: normal } + pbrMap: { value: grey } + metallicRoughnessMap: { value: grey } + occlusionMap: { value: white } + emissiveMap: { value: grey } + anisotropyRotationMap: { value: black, editor : { parent: IS_ANISOTROPY } } + - &forward-add + vert: standard-vs + frag: standard-fs + phase: forward-add + propertyIndex: 0 + embeddedMacros: { CC_FORWARD_ADD: true } + depthStencilState: + depthFunc: equal + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: one + blendDst: one + blendSrcAlpha: zero + blendDstAlpha: one + - &shadow-caster + vert: shadow-caster-vs + frag: shadow-caster-fs + phase: shadow-caster + propertyIndex: 0 + 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 } } + - name: transparent + passes: + - vert: standard-vs + frag: standard-fs + embeddedMacros: { CC_FORCE_FORWARD_SHADING: true } + depthStencilState: + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: src_alpha + blendDst: one_minus_src_alpha + blendDstAlpha: one_minus_src_alpha + properties: *props + - *forward-add + - *shadow-caster +}% + +CCProgram shared-ubos %{ + uniform Constants { + vec4 tilingOffset; + vec4 albedo; + vec4 albedoScaleAndCutoff; + vec4 pbrParams; + vec4 emissive; + vec4 emissiveScaleParam; + vec2 anisotropyParam; + }; +}% + +CCProgram macro-remapping %{ + // ui displayed macros + #pragma define-meta HAS_SECOND_UV + #pragma define-meta USE_TWOSIDE + #pragma define-meta USE_REFLECTION_DENOISE + #pragma define-meta IS_ANISOTROPY + #pragma define-meta USE_VERTEX_COLOR + + #define CC_SURFACES_USE_SECOND_UV HAS_SECOND_UV + #define CC_SURFACES_USE_TWO_SIDED USE_TWOSIDE + #define CC_SURFACES_USE_REFLECTION_DENOISE USE_REFLECTION_DENOISE + #define CC_SURFACES_LIGHTING_ANISOTROPIC IS_ANISOTROPY + #define CC_SURFACES_USE_VERTEX_COLOR USE_VERTEX_COLOR + + // if disabled, simulate convoluted IBL without convolution + #pragma define-meta USE_COMPATIBLE_LIGHTING + #define CC_SURFACES_USE_LEGACY_COMPATIBLE_LIGHTING USE_COMPATIBLE_LIGHTING + + // depend on UI macros +#if IS_ANISOTROPY || USE_NORMAL_MAP + #define CC_SURFACES_USE_TANGENT_SPACE 1 +#endif + + // functionality for each effect + #define CC_SURFACES_LIGHTING_ANISOTROPIC_ENVCONVOLUTION_COUNT 31 +}% + +CCProgram surface-vertex %{ + /*#define CC_SURFACES_VERTEX_MODIFY_WORLD_POS + vec3 SurfacesVertexModifyWorldPos(in SurfacesStandardVertexIntermediate In) + { + vec3 worldPos = In.worldPos; + worldPos.x += sin(cc_time.x * worldPos.z); + worldPos.y += cos(cc_time.x * worldPos.z); + return worldPos; + } + + #define CC_SURFACES_VERTEX_MODIFY_WORLD_NORMAL + vec3 SurfacesVertexModifyWorldNormal(in SurfacesStandardVertexIntermediate In) + { + vec3 worldNormal = In.worldNormal.xyz; + worldNormal.x += sin(cc_time.x * 3.0); + worldNormal.y += cos(cc_time.x * 3.0); + #if CC_SURFACES_USE_TWO_SIDED + worldNormal.xyz *= In.worldNormal.w; + #endif + return normalize(worldNormal); + }*/ + + #define CC_SURFACES_VERTEX_MODIFY_UV + void SurfacesVertexModifyUV(inout SurfacesStandardVertexIntermediate In) + { + In.texCoord = In.texCoord * tilingOffset.xy + tilingOffset.zw; + #if CC_SURFACES_USE_SECOND_UV && !CC_USE_LIGHTMAP + In.texCoord1 = In.texCoord1 * tilingOffset.xy + tilingOffset.zw; + #endif + } +}% + +CCProgram surface-fragment %{ + #if USE_ALBEDO_MAP + uniform sampler2D albedoMap; + #pragma define-meta ALBEDO_UV options([v_uv, v_uv1]) + #endif + #if USE_NORMAL_MAP + uniform sampler2D normalMap; + #pragma define-meta NORMAL_UV options([v_uv, v_uv1]) + #endif + #pragma define-meta DEFAULT_UV options([v_uv, v_uv1]) + #if USE_PBR_MAP + uniform sampler2D pbrMap; + #endif + #if USE_METALLIC_ROUGHNESS_MAP + uniform sampler2D metallicRoughnessMap; + #endif + #if USE_OCCLUSION_MAP + uniform sampler2D occlusionMap; + #endif + #if USE_EMISSIVE_MAP + uniform sampler2D emissiveMap; + #pragma define-meta EMISSIVE_UV options([v_uv, v_uv1]) + #endif + #if IS_ANISOTROPY && USE_ANISOTROPY_ROTATION_MAP + uniform sampler2D anisotropyRotationMap; + #endif + + #pragma define OCCLUSION_CHANNEL r + #pragma define ROUGHNESS_CHANNEL g + #pragma define METALLIC_CHANNEL b + #pragma define SPECULAR_INTENSITY_CHANNEL a + + #if USE_ALPHA_TEST + #pragma define-meta ALPHA_TEST_CHANNEL options([a, r]) + #endif + + + #define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY + vec4 SurfacesFragmentModifyBaseColorAndTransparency() + { + vec4 baseColor = albedo; + + #if USE_VERTEX_COLOR + 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); + baseColor *= texColor; + #endif + + #if USE_ALPHA_TEST + if (baseColor.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard; + #endif + + baseColor.rgb *= albedoScaleAndCutoff.xyz; + return baseColor; + } + + #define CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL + vec3 SurfacesFragmentModifyWorldNormal() + { + 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); + #endif + + return normalize(normal); + } + + #define CC_SURFACES_FRAGMENT_MODIFY_ANISOTROPY_PARAMS + vec4 SurfacesFragmentModifyAnisotropyParams() + { + float anisotropyRotation = anisotropyParam.y; + float anisotropyShape = anisotropyParam.x; + #if IS_ANISOTROPY && USE_ANISOTROPY_ROTATION_MAP + anisotropyRotation = fract(anisotropyRotation + texture(anisotropyRotationMap, DEFAULT_UV).x); + #endif + return vec4(anisotropyRotation, anisotropyShape, 0.0, 0.0); + } + + #define CC_SURFACES_FRAGMENT_MODIFY_EMISSIVE + vec3 SurfacesFragmentModifyEmissive() + { + vec3 emissive = emissive.rgb * emissiveScaleParam.xyz; + #if USE_EMISSIVE_MAP + emissive *= SRGBToLinear(texture(emissiveMap, EMISSIVE_UV).rgb); + #endif + return emissive; + } + + #define CC_SURFACES_FRAGMENT_MODIFY_PBRPARAMS + vec4 SurfacesFragmentModifyPBRParams() + { + vec4 pbr = pbrParams; + #if USE_PBR_MAP + vec4 res = texture(pbrMap, DEFAULT_UV); + pbr.x *= res.OCCLUSION_CHANNEL; + pbr.y *= res.ROUGHNESS_CHANNEL; + pbr.z *= res.METALLIC_CHANNEL; + pbr.w *= res.SPECULAR_INTENSITY_CHANNEL; + #endif + #if USE_METALLIC_ROUGHNESS_MAP + vec4 metallicRoughness = texture(metallicRoughnessMap, DEFAULT_UV); + pbr.z *= metallicRoughness.METALLIC_CHANNEL; + pbr.y *= metallicRoughness.ROUGHNESS_CHANNEL; + #endif + #if USE_OCCLUSION_MAP + pbr.x *= texture(occlusionMap, DEFAULT_UV).OCCLUSION_CHANNEL; + #endif + + return pbr; + } +}% + +CCProgram standard-vs %{ + precision highp float; + + // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros + #include + #include + + // 2. common include with corresponding shader stage, include before surface functions + #include + + // 3. user surface functions that can use user (effect) parameters (ubo Constants) + // see surfaces/default-functions/xxx.chunk + #include + #include + + // 4. surface include with corresponding shader stage and shading-model (optional) + #include + + // 5. shader entry with corresponding shader stage and technique usage/type + #include +}% + + +CCProgram shadow-caster-vs %{ + precision highp float; + #include + #include + #include + #include + #include +}% + + + +CCProgram standard-fs %{ + // shading-model : standard + // lighting-model : standard (isotropy / anisotropy pbr) + // shader stage : fs + // technique usage/type : render-to-scene + + precision highp float; + // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros + #include + #include + + // 2. common include with corresponding shader stage, include before surface functions + #include + + // 3. user surface functions that can use user (effect) parameters (ubo Constants) + // see surfaces/default-functions/xxx.chunk + #include + #include + + // 4. lighting-model (optional) + #include + + // 5. surface include with corresponding shader stage and shading-model (optional) + #include + + // 6. shader entry with corresponding shader stage and technique usage/type + #include +}% + +CCProgram shadow-caster-fs %{ + precision highp float; + #include + #include + #include + #include + #include +}% diff --git a/editor/assets/effects/surfaces/standard.effect.meta b/editor/assets/effects/surfaces/standard.effect.meta new file mode 100644 index 0000000000..466869b12f --- /dev/null +++ b/editor/assets/effects/surfaces/standard.effect.meta @@ -0,0 +1,16 @@ +{ + "ver": "1.5.7", + "importer": "effect", + "imported": true, + "uuid": "c8f66d17-351a-48da-a12c-0212d28575c4", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": { + "combinations": [ + {}, + {} + ] + } +} diff --git a/editor/assets/effects/surfaces/toon.effect b/editor/assets/effects/surfaces/toon.effect new file mode 100644 index 0000000000..380a66dbe8 --- /dev/null +++ b/editor/assets/effects/surfaces/toon.effect @@ -0,0 +1,392 @@ +// Copyright (c) 2017-2022 Xiamen Yaji Software Co., Ltd. + +CCEffect %{ + techniques: + - passes: + - switch: USE_OUTLINE_PASS + vert: silhouette-edge-vs + frag: silhouette-edge-fs + rasterizerState: + cullMode: front + depthStencilState: + depthFunc: less_equal + depthTest: true + depthWrite: true + properties: + lineWidth: { value: 10, target: outlineParams.x } + depthBias: { value: 0, target: outlineParams.y } + baseColor: { editor: { type: color } } + baseColorMap: { value: grey } + - vert: toon-vs + frag: toon-fs + properties: &props + tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } + mainColor: { value: [0.6, 0.6, 0.6, 1.0], target: baseColor, linear: true, editor: { displayName: BaseColor, type: color } } + colorScale: { value: [1.0, 1.0, 1.0], target: colorScaleAndCutoff.xyz } + alphaThreshold: { value: 0.5, target: colorScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } } + shadeColor1: { value: [0.4, 0.4, 0.4, 1.0], linear: true, editor: { type: color } } + shadeColor2: { value: [0.2, 0.2, 0.2, 1.0], linear: true, editor: { type: color } } + specular: { value: [1.0, 1.0, 1.0, 0.3], linear: true, editor: { type: color } } + baseStep: { value: 0.8, target: shadeParams.x } + baseFeather: { value: 0.001, target: shadeParams.y } + shadeStep: { value: 0.5, target: shadeParams.z } + shadeFeather: { value: 0.001, target: shadeParams.w } + shadowCover: { value: 0.5, target: miscParams.x, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + emissive: { value: [0.0, 0.0, 0.0, 1.0], linear: true, editor: { type: color } } + emissiveScale: { value: [1.0, 1.0, 1.0], target: emissiveScaleAndStrenth.xyz } + normalStrength: { value: 1.0, target: emissiveScaleAndStrenth.w, editor: { parent: USE_NORMAL_MAP }, slide: true, range: [0, 5.0], step: 0.001 } + normalMap: { value: normal } + mainTexture: { value: white, target: baseColorMap, editor: { displayName: BaseColorMap } } + shadeMap1: { value: white } + shadeMap2: { value: white } + specularMap: { value: white } + emissiveMap: { value: grey } + - vert: toon-vs + frag: toon-fs + phase: forward-add + propertyIndex: 1 + embeddedMacros: { CC_FORWARD_ADD: true } + depthStencilState: + depthFunc: equal + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: one + blendDst: one + blendSrcAlpha: zero + blendDstAlpha: one + properties: *props + - vert: shadow-caster-vs + frag: shadow-caster-fs + phase: shadow-caster + propertyIndex: 1 + rasterizerState: + cullMode: front + properties: + tilingOffset: { value: [1.0, 1.0, 0.0, 0.0] } + mainColor: { value: [0.6, 0.6, 0.6, 1.0], target: baseColor, editor: { displayName: BaseColor, type: color } } + colorScale: { value: [1.0, 1.0, 1.0], target: colorScaleAndCutoff.xyz } + alphaThreshold: { value: 0.5, target: colorScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } } + shadeColor1: { value: [0.4, 0.4, 0.4, 1.0], editor: { type: color } } + shadeColor2: { value: [0.2, 0.2, 0.2, 1.0], editor: { type: color } } + specular: { value: [1.0, 1.0, 1.0, 0.3], editor: { type: color } } + baseStep: { value: 0.8, target: shadeParams.x } + baseFeather: { value: 0.001, target: shadeParams.y } + shadeStep: { value: 0.5, target: shadeParams.z } + shadeFeather: { value: 0.001, target: shadeParams.w } + emissive: { value: [0.0, 0.0, 0.0, 1.0], editor: { type: color } } + emissiveScale: { value: [1.0, 1.0, 1.0], target: emissiveScaleAndStrenth.xyz } + normalStrenth: { value: 1.0, target: emissiveScaleAndStrenth.w, editor: { parent: USE_NORMAL_MAP } } + mainTexture: { value: white, target: baseColorMap, editor: { displayName: BaseColorMap } } +}% + +CCProgram shared-ubos %{ + uniform Constants { + vec4 tilingOffset; + vec4 baseColor; + vec4 colorScaleAndCutoff; + vec4 shadeColor1; + vec4 shadeColor2; + vec4 specular; // xyz: specular color, w: power + vec4 shadeParams; + vec4 miscParams; + vec4 emissive; + vec4 emissiveScaleAndStrenth; + };}% + +CCProgram macro-remapping %{ + #pragma define-meta USE_NORMAL_MAP + #define CC_SURFACES_USE_TANGENT_SPACE USE_NORMAL_MAP +}% + +CCProgram surface-vertex %{ + #define CC_SURFACES_VERTEX_MODIFY_UV + void SurfacesVertexModifyUV(inout SurfacesStandardVertexIntermediate In) + { + In.texCoord = In.texCoord * tilingOffset.xy + tilingOffset.zw; + } +}% + +CCProgram surface-fragment %{ + #if USE_BASE_COLOR_MAP + uniform sampler2D baseColorMap; + #endif + + #if USE_NORMAL_MAP + uniform sampler2D normalMap; + #endif + + #if USE_1ST_SHADE_MAP + uniform sampler2D shadeMap1; + #endif + #if USE_2ND_SHADE_MAP + uniform sampler2D shadeMap2; + #endif + #if USE_SPECULAR_MAP + uniform sampler2D specularMap; + #endif + #if USE_EMISSIVE_MAP + uniform sampler2D emissiveMap; + #endif + + #if USE_ALPHA_TEST + #pragma define-meta ALPHA_TEST_CHANNEL options([a, r, g, b]) + #endif + + + #define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TOONSHADE + void SurfacesFragmentModifyBaseColorAndToonShade(out vec4 baseColorAndTransparency, out vec3 shade1, out vec3 shade2) + { + shade2 = shadeColor2.rgb * colorScaleAndCutoff.rgb; + #if USE_2ND_SHADE_MAP + shade2 *= SRGBToLinear(texture(shadeMap2, FSInput_texcoord).rgb); + #endif + shade1 = shadeColor1.rgb * colorScaleAndCutoff.rgb; + #if USE_1ST_SHADE_MAP + shade1 *= SRGBToLinear(texture(shadeMap1, FSInput_texcoord).rgb); + #if SHADE_MAP_1_AS_SHADE_MAP_2 + shade2 *= shade1.rgb; + #endif + #endif + + vec4 color = baseColor; + #if USE_BASE_COLOR_MAP + vec4 texColor = texture(baseColorMap, FSInput_texcoord); + texColor.rgb = SRGBToLinear(texColor.rgb); + color *= texColor; + #if BASE_COLOR_MAP_AS_SHADE_MAP_1 + shade1 *= texColor.rgb; + #endif + #if BASE_COLOR_MAP_AS_SHADE_MAP_2 + shade2 *= texColor.rgb; + #endif + #endif + baseColorAndTransparency = color; + baseColorAndTransparency.rgb *= colorScaleAndCutoff.xyz; + + #if USE_ALPHA_TEST + if (baseColorAndTransparency.ALPHA_TEST_CHANNEL < colorScaleAndCutoff.w) discard; + #endif + } + + // only for render-to-shadow-map or misc usage + #define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY + vec4 SurfacesFragmentModifyBaseColorAndTransparency() + { + 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; + #endif + + return color; + } + + #define CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL + vec3 SurfacesFragmentModifyWorldNormal() + { + 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); + #endif + + return normalize(normal); + } + + #define CC_SURFACES_FRAGMENT_MODIFY_EMISSIVE + vec3 SurfacesFragmentModifyEmissive() + { + vec3 emissive = emissive.rgb * emissiveScaleAndStrenth.xyz; + #if USE_EMISSIVE_MAP + emissive *= SRGBToLinear(texture(emissiveMap, FSInput_texcoord).rgb); + #endif + return emissive; + } + + #define CC_SURFACES_FRAGMENT_MODIFY_TOON_STEP_AND_FEATHER + vec4 SurfacesFragmentModifyToonStepAndFeather() + { + return shadeParams; + } + + #define CC_SURFACES_FRAGMENT_MODIFY_TOON_SHADOW_COVER + float SurfacesFragmentModifyToonShadowCover() + { + return miscParams.x; + } + + #define CC_SURFACES_FRAGMENT_MODIFY_TOON_SPECULAR + vec4 SurfacesFragmentModifyToonSpecular() + { + vec4 specularParam = specular; + #if USE_SPECULAR_MAP + specularParam.rgb *= SRGBToLinear(texture(specularMap, FSInput_texcoord).rgb); + #endif + return specularParam; + } +}% + +CCProgram toon-vs %{ + precision highp float; + + // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros + #include + #include + + // 2. common include with corresponding shader stage + #include + + // 3. user surface functions that can use user (effect) parameters (ubo Constants) + // see surfaces/default-functions/xxx.chunk + #include + #include + + // 4. surface include with corresponding shader stage and shading-model (optional) + #include + + // 5. shader entry with corresponding shader stage and technique usage/type + #include +}% + + +CCProgram shadow-caster-vs %{ + precision highp float; + #include + #include + #include + #include + #include +}% + +CCProgram toon-fs %{ + // shading-model : toon + // lighting-model : toon + // shader stage : fs + // technique usage/type : render-to-scene + + precision highp float; + // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros + #include + #include + + // 2. common include with corresponding shader stage + #include + + // 3. user surface functions that can use user (effect) parameters (ubo Constants) + // see surfaces/default-functions/xxx.chunk + #include + #include + + // 4. lighting-model (optional) + #include + + // 5. surface include with corresponding shader stage and shading-model (optional) + #include + + // 6. shader entry with corresponding shader stage and technique usage/type + #include +}% + +CCProgram shadow-caster-fs %{ + precision highp float; + #include + #include + #include + #include + #include +}% + + + + + + + + + + + + + + + +////////////////////////////////////////////////silhouette-edge sample +// how to write a simple surface material +// change technique outline-vs/fs:vert/frag to silhouette-edge-vs/fs +CCProgram surface-vertex-silhouette-edge %{ + uniform OutlineVert { + vec4 outlineParams; // x: line width, y: depth hack +}; + + #define CC_SURFACES_VERTEX_MODIFY_LOCAL_POS + vec3 SurfacesVertexModifyLocalPos(in SurfacesStandardVertexIntermediate In) + { + float width = outlineParams.x * 0.001; + vec3 localPos = In.position.xyz; + + #if USE_POSITION_SCALING + vec3 dir = normalize(localPos); + float flip = dot(dir, normalize(In.normal)) < 0.0 ? -1.0 : 1.0; + localPos += flip * dir * width * 2.0; + #else + localPos += normalize(In.normal) * width; + #endif + return localPos; + } + + #define CC_SURFACES_VERTEX_MODIFY_CLIP_POS + vec4 SurfacesVertexModifyClipPos(in SurfacesStandardVertexIntermediate In) + { + vec4 clipPos = In.clipPos; + clipPos.z -= outlineParams.y * 0.002; + return clipPos; + } +}% + +CCProgram surface-fragment-silhouette-edge %{ + uniform OutlineFrag { + vec4 baseColor; + }; + #if USE_BASE_COLOR_MAP + uniform sampler2D baseColorMap; + #endif + + // only for render-to-shadow-map or misc usage + #define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY + vec4 SurfacesFragmentModifyBaseColorAndTransparency() + { + vec4 color = vec4(cc_mainLitColor.rgb, 1.0); + color.rgb = SRGBToLinear(baseColor.rgb); + #if USE_BASE_COLOR_MAP + vec4 texColor = texture(baseColorMap, FSInput_texcoord); + texColor.rgb = SRGBToLinear(texColor.rgb); + color *= texColor; + #endif + + return color; + } +}% + +CCProgram silhouette-edge-vs %{ + precision highp float; + #include + #include + #include + #include +}% + +CCProgram silhouette-edge-fs %{ + precision highp float; + #include + #include + #include + #include +}% diff --git a/editor/assets/effects/surfaces/toon.effect.meta b/editor/assets/effects/surfaces/toon.effect.meta new file mode 100644 index 0000000000..1bdd20b5af --- /dev/null +++ b/editor/assets/effects/surfaces/toon.effect.meta @@ -0,0 +1,11 @@ +{ + "ver": "1.5.7", + "importer": "effect", + "imported": true, + "uuid": "9b20a514-6cc3-49de-b216-b6b863046249", + "files": [ + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/effects/util/batched-unlit.effect b/editor/assets/effects/util/batched-unlit.effect index 353fcf85bc..9ac83738d1 100644 --- a/editor/assets/effects/util/batched-unlit.effect +++ b/editor/assets/effects/util/batched-unlit.effect @@ -31,9 +31,10 @@ CCEffect %{ CCProgram unlit-vs %{ precision highp float; - #include - #include - #include + #include + #include + #include + #include // array lengths need to be determined at resource-import-time // so we can't define this as a runtime macro @@ -93,7 +94,7 @@ CCProgram unlit-vs %{ CCProgram unlit-fs %{ precision highp float; - #include + #include #pragma define BATCHED_UNITS 6 #if USE_TEXTURE diff --git a/editor/assets/effects/util/batched-unlit.effect.meta b/editor/assets/effects/util/batched-unlit.effect.meta index fca27fb294..f6dbbb069e 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.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "f1556893-88b6-4c65-8c16-a5256ef3ad25", diff --git a/editor/assets/effects/util/profiler.effect b/editor/assets/effects/util/profiler.effect index 6ac18ade69..5e2ad84050 100644 --- a/editor/assets/effects/util/profiler.effect +++ b/editor/assets/effects/util/profiler.effect @@ -20,7 +20,7 @@ CCEffect %{ CCProgram profiler-vs %{ precision mediump float; - #include + #include #pragma define ROWS 8 // multiple of 4 #pragma define COLS 10 @@ -63,7 +63,7 @@ CCProgram profiler-vs %{ CCProgram profiler-fs %{ precision mediump float; - #include + #include in vec2 v_uv; uniform sampler2D mainTexture; diff --git a/editor/assets/effects/util/profiler.effect.meta b/editor/assets/effects/util/profiler.effect.meta index 35889de0aa..3673052970 100644 --- a/editor/assets/effects/util/profiler.effect.meta +++ b/editor/assets/effects/util/profiler.effect.meta @@ -1,5 +1,5 @@ { - "ver": "1.5.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "871c3b6c-7379-419d-bda3-794b239ab90d", diff --git a/editor/assets/effects/util/sequence-anim.effect b/editor/assets/effects/util/sequence-anim.effect index b30d4fbb56..e93dccdd78 100644 --- a/editor/assets/effects/util/sequence-anim.effect +++ b/editor/assets/effects/util/sequence-anim.effect @@ -70,9 +70,10 @@ CCEffect %{ CCProgram unlit-vs %{ precision highp float; - #include - #include - #include + #include + #include + #include + #include #if USE_VERTEX_COLOR in lowp vec4 a_color; @@ -125,7 +126,7 @@ CCProgram unlit-vs %{ CCProgram unlit-fs %{ precision highp float; - #include + #include #if USE_ALPHA_TEST #pragma define-meta ALPHA_TEST_CHANNEL options([a, r, g, b]) diff --git a/editor/assets/effects/util/sequence-anim.effect.meta b/editor/assets/effects/util/sequence-anim.effect.meta index e6d70e8a79..6c878d5975 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.2", + "ver": "1.5.7", "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 6945a51704..2b1b7c4e7d 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.2", + "ver": "1.5.7", "importer": "effect", "imported": true, "uuid": "970b0598-bcb0-4714-91fb-2e81440dccd8", diff --git a/editor/assets/gizmo/camera.png.meta b/editor/assets/gizmo/camera.png.meta index b34a5d65be..2ecace6893 100644 --- a/editor/assets/gizmo/camera.png.meta +++ b/editor/assets/gizmo/camera.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "bd373594-df84-486d-a34a-19d09ddaa973", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,7 +26,8 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "bd373594-df84-486d-a34a-19d09ddaa973" + "imageUuidOrDatabaseUri": "bd373594-df84-486d-a34a-19d09ddaa973", + "visible": true }, "displayName": "camera", "id": "6c48a", @@ -37,6 +38,7 @@ "type": "texture", "redirect": "bd373594-df84-486d-a34a-19d09ddaa973@6c48a", "flipVertical": true, - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/gizmo/directional-light.png.meta b/editor/assets/gizmo/directional-light.png.meta index 544e8ff8a4..5729c79fb6 100644 --- a/editor/assets/gizmo/directional-light.png.meta +++ b/editor/assets/gizmo/directional-light.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "9cb543ba-d152-4809-8a44-8e7bd5712123", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,7 +26,8 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "9cb543ba-d152-4809-8a44-8e7bd5712123" + "imageUuidOrDatabaseUri": "9cb543ba-d152-4809-8a44-8e7bd5712123", + "visible": true }, "displayName": "directional-light", "id": "6c48a", @@ -36,6 +37,7 @@ "userData": { "type": "texture", "redirect": "9cb543ba-d152-4809-8a44-8e7bd5712123@6c48a", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/gizmo/particle-system.png.meta b/editor/assets/gizmo/particle-system.png.meta index 68b1d7b481..75d075c168 100644 --- a/editor/assets/gizmo/particle-system.png.meta +++ b/editor/assets/gizmo/particle-system.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "55052bc6-9909-43c1-b2fc-8818060fb069", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,7 +26,8 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "55052bc6-9909-43c1-b2fc-8818060fb069" + "imageUuidOrDatabaseUri": "55052bc6-9909-43c1-b2fc-8818060fb069", + "visible": true }, "displayName": "particle-system", "id": "6c48a", @@ -37,6 +38,7 @@ "type": "texture", "redirect": "55052bc6-9909-43c1-b2fc-8818060fb069@6c48a", "flipVertical": true, - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/gizmo/sphere-light.png.meta b/editor/assets/gizmo/sphere-light.png.meta index a35b655129..eb08ffa1c0 100644 --- a/editor/assets/gizmo/sphere-light.png.meta +++ b/editor/assets/gizmo/sphere-light.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "c78f78a5-3553-4d1f-ad3b-177fe55af68b", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,7 +26,8 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "c78f78a5-3553-4d1f-ad3b-177fe55af68b" + "imageUuidOrDatabaseUri": "c78f78a5-3553-4d1f-ad3b-177fe55af68b", + "visible": true }, "displayName": "sphere-light", "id": "6c48a", @@ -36,6 +37,7 @@ "userData": { "type": "texture", "redirect": "c78f78a5-3553-4d1f-ad3b-177fe55af68b@6c48a", - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/gizmo/spot-light.png.meta b/editor/assets/gizmo/spot-light.png.meta index 8fc7c072d5..2b98ec6ab7 100644 --- a/editor/assets/gizmo/spot-light.png.meta +++ b/editor/assets/gizmo/spot-light.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "191b676f-175b-41fa-8283-ac539875bfd8", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -26,7 +26,8 @@ "premultiplyAlpha": false, "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "191b676f-175b-41fa-8283-ac539875bfd8" + "imageUuidOrDatabaseUri": "191b676f-175b-41fa-8283-ac539875bfd8", + "visible": true }, "displayName": "spot-light", "id": "6c48a", @@ -37,6 +38,7 @@ "type": "texture", "redirect": "191b676f-175b-41fa-8283-ac539875bfd8@6c48a", "flipVertical": true, - "hasAlpha": true + "hasAlpha": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/gizmo/webview.png.meta b/editor/assets/gizmo/webview.png.meta index 0d08eb5508..459c27f9b1 100644 --- a/editor/assets/gizmo/webview.png.meta +++ b/editor/assets/gizmo/webview.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "b9f47df4-b2f0-4270-bd8a-07bb344a8253", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -22,7 +22,8 @@ "mipfilter": "none", "anisotropy": 0, "isUuid": true, - "imageUuidOrDatabaseUri": "b9f47df4-b2f0-4270-bd8a-07bb344a8253" + "imageUuidOrDatabaseUri": "b9f47df4-b2f0-4270-bd8a-07bb344a8253", + "visible": true }, "ver": "1.0.22", "imported": true, @@ -35,6 +36,7 @@ "userData": { "hasAlpha": true, "type": "texture", - "redirect": "b9f47df4-b2f0-4270-bd8a-07bb344a8253@6c48a" + "redirect": "b9f47df4-b2f0-4270-bd8a-07bb344a8253@6c48a", + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/gizmo/x.png.meta b/editor/assets/gizmo/x.png.meta index 851e53a5b8..931b8339d1 100644 --- a/editor/assets/gizmo/x.png.meta +++ b/editor/assets/gizmo/x.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "ac74fa2b-1f5b-4ff5-a3f0-f127f4483e91", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -22,7 +22,8 @@ "magfilter": "linear", "mipfilter": "none", "anisotropy": 0, - "isUuid": true + "isUuid": true, + "visible": false }, "ver": "1.0.22", "imported": true, @@ -56,9 +57,63 @@ "packable": true, "isUuid": true, "imageUuidOrDatabaseUri": "ac74fa2b-1f5b-4ff5-a3f0-f127f4483e91@6c48a", - "atlasUuid": "" + "atlasUuid": "", + "vertices": { + "rawPosition": [ + -22, + -24.5, + 0, + 22, + -24.5, + 0, + -22, + 24.5, + 0, + 22, + 24.5, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 10, + 57, + 54, + 57, + 10, + 8, + 54, + 8 + ], + "nuv": [ + 0.15625, + 0.125, + 0.84375, + 0.125, + 0.15625, + 0.890625, + 0.84375, + 0.890625 + ], + "minPos": [ + -22, + -24.5, + 0 + ], + "maxPos": [ + 22, + 24.5, + 0 + ] + } }, - "ver": "1.0.10", + "ver": "1.0.11", "imported": true, "files": [ ".json" @@ -70,6 +125,7 @@ "type": "sprite-frame", "hasAlpha": true, "redirect": "ac74fa2b-1f5b-4ff5-a3f0-f127f4483e91@f9941", - "flipVertical": true + "flipVertical": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/gizmo/y.png.meta b/editor/assets/gizmo/y.png.meta index 85ab40923d..8f359328aa 100644 --- a/editor/assets/gizmo/y.png.meta +++ b/editor/assets/gizmo/y.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "7b5313d0-f1aa-4b1b-a3c8-59d523c35301", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -22,7 +22,8 @@ "magfilter": "linear", "mipfilter": "none", "anisotropy": 0, - "isUuid": true + "isUuid": true, + "visible": false }, "ver": "1.0.22", "imported": true, @@ -56,9 +57,63 @@ "packable": true, "isUuid": true, "imageUuidOrDatabaseUri": "7b5313d0-f1aa-4b1b-a3c8-59d523c35301@6c48a", - "atlasUuid": "" + "atlasUuid": "", + "vertices": { + "rawPosition": [ + -21.5, + -24.5, + 0, + 21.5, + -24.5, + 0, + -21.5, + 24.5, + 0, + 21.5, + 24.5, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 11, + 57, + 54, + 57, + 11, + 8, + 54, + 8 + ], + "nuv": [ + 0.171875, + 0.125, + 0.84375, + 0.125, + 0.171875, + 0.890625, + 0.84375, + 0.890625 + ], + "minPos": [ + -21.5, + -24.5, + 0 + ], + "maxPos": [ + 21.5, + 24.5, + 0 + ] + } }, - "ver": "1.0.10", + "ver": "1.0.11", "imported": true, "files": [ ".json" @@ -70,6 +125,7 @@ "type": "sprite-frame", "hasAlpha": true, "redirect": "7b5313d0-f1aa-4b1b-a3c8-59d523c35301@f9941", - "flipVertical": true + "flipVertical": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/gizmo/z.png.meta b/editor/assets/gizmo/z.png.meta index 85880fa7cf..47cc5a3c70 100644 --- a/editor/assets/gizmo/z.png.meta +++ b/editor/assets/gizmo/z.png.meta @@ -1,11 +1,11 @@ { - "ver": "1.0.23", + "ver": "1.0.24", "importer": "image", "imported": true, "uuid": "389d5fee-e29c-4221-b397-a4934a0a5694", "files": [ - ".png", - ".json" + ".json", + ".png" ], "subMetas": { "6c48a": { @@ -22,7 +22,8 @@ "magfilter": "linear", "mipfilter": "none", "anisotropy": 0, - "isUuid": true + "isUuid": true, + "visible": false }, "ver": "1.0.22", "imported": true, @@ -56,9 +57,63 @@ "packable": true, "isUuid": true, "imageUuidOrDatabaseUri": "389d5fee-e29c-4221-b397-a4934a0a5694@6c48a", - "atlasUuid": "" + "atlasUuid": "", + "vertices": { + "rawPosition": [ + -19, + -24.5, + 0, + 19, + -24.5, + 0, + -19, + 24.5, + 0, + 19, + 24.5, + 0 + ], + "indexes": [ + 0, + 1, + 2, + 2, + 1, + 3 + ], + "uv": [ + 13, + 57, + 51, + 57, + 13, + 8, + 51, + 8 + ], + "nuv": [ + 0.203125, + 0.125, + 0.796875, + 0.125, + 0.203125, + 0.890625, + 0.796875, + 0.890625 + ], + "minPos": [ + -19, + -24.5, + 0 + ], + "maxPos": [ + 19, + 24.5, + 0 + ] + } }, - "ver": "1.0.10", + "ver": "1.0.11", "imported": true, "files": [ ".json" @@ -70,6 +125,7 @@ "type": "sprite-frame", "hasAlpha": true, "redirect": "389d5fee-e29c-4221-b397-a4934a0a5694@f9941", - "flipVertical": true + "flipVertical": true, + "fixAlphaTransparencyArtifacts": false } } diff --git a/editor/assets/primitives.fbx.meta b/editor/assets/primitives.fbx.meta index a263817ffc..f979262dd8 100644 --- a/editor/assets/primitives.fbx.meta +++ b/editor/assets/primitives.fbx.meta @@ -1,5 +1,5 @@ { - "ver": "2.1.11", + "ver": "2.2.0", "importer": "fbx", "imported": true, "uuid": "1263d74c-8167-4928-91a6-4e2672411f47", @@ -216,7 +216,8 @@ "imageMetas": [], "legacyFbxImporter": false, "fbx": { - "preferLocalTimeSpan": false + "preferLocalTimeSpan": false, + "smartMaterialEnabled": false } } } diff --git a/editor/engine-features/render-config.json b/editor/engine-features/render-config.json index a52630021d..3f1b52bc1c 100644 --- a/editor/engine-features/render-config.json +++ b/editor/engine-features/render-config.json @@ -128,6 +128,30 @@ "description": "i18n:ENGINE.features.profiler.description", "wechatPlugin": true }, + "occlusion-query": { + "default": ["occlusion-query"], + "label": "i18n:ENGINE.features.occlusion_query.label", + "description": "i18n:ENGINE.features.occlusion_query.description", + "native": "USE_OCCLUSION_QUERY", + "wechatPlugin": true, + "category": "3d" + }, + "geometry-renderer": { + "default": ["geometry-renderer"], + "label": "i18n:ENGINE.features.geometry_renderer.label", + "description": "i18n:ENGINE.features.geometry_renderer.description", + "native": "USE_GEOMETRY_RENDERER", + "wechatPlugin": true, + "category": "3d" + }, + "debug-renderer": { + "default": ["debug-renderer"], + "label": "i18n:ENGINE.features.debug_renderer.label", + "description": "i18n:ENGINE.features.debug_renderer.description", + "native": "USE_DEBUG_RENDERER", + "wechatPlugin": true, + "category": "3d" + }, "particle-2d": { "default": ["particle-2d"], "label": "i18n:ENGINE.features.particle_2d.label", diff --git a/editor/exports/embedded-player.ts b/editor/exports/embedded-player.ts new file mode 100644 index 0000000000..43a809e509 --- /dev/null +++ b/editor/exports/embedded-player.ts @@ -0,0 +1,15 @@ +export { + embeddedPlayerCountTag, + getEmbeddedPlayersTag, + addEmbeddedPlayerTag, + removeEmbeddedPlayerTag, + clearEmbeddedPlayersTag, +} from '../../cocos/core/animation/animation-clip'; + +export { EmbeddedPlayer } from '../../cocos/core/animation/embedded-player/embedded-player'; + +export type { EmbeddedPlayable } from '../../cocos/core/animation/embedded-player/embedded-player'; + +export { EmbeddedParticleSystemPlayable } from '../../cocos/core/animation/embedded-player/embedded-particle-system-player'; + +export { EmbeddedAnimationClipPlayable } from '../../cocos/core/animation/embedded-player/embedded-animation-clip-player'; diff --git a/editor/exports/exotic-animation.ts b/editor/exports/exotic-animation.ts index e14efecc50..f68d221ac1 100644 --- a/editor/exports/exotic-animation.ts +++ b/editor/exports/exotic-animation.ts @@ -6,3 +6,7 @@ export { export { ExoticAnimation, } from '../../cocos/core/animation/exotic-animation/exotic-animation'; + +export { + RealArrayTrack, +} from '../../cocos/core/animation/tracks/array-track'; diff --git a/editor/exports/new-gen-anim.ts b/editor/exports/new-gen-anim.ts index 64eb34c054..a4d402790d 100644 --- a/editor/exports/new-gen-anim.ts +++ b/editor/exports/new-gen-anim.ts @@ -14,3 +14,17 @@ export type { } from '../../cocos/core/animation/marionette/blend-2d'; export * from '../../cocos/core/animation/marionette/asset-creation'; + +export { viewVariableBindings } from '../src/marionette/variable-binding'; + +export type { VariableBindingView } from '../src/marionette/variable-binding'; + +export { + MotionPreviewer, + TransitionPreviewer, +} from '../src/marionette/preview'; + +export type { + MotionPreviewerTimelineStats, + TransitionPreviewerTimelineStats, +} from '../src/marionette/preview'; diff --git a/editor/i18n/en/assets.js b/editor/i18n/en/assets.js index f5be822d67..ef48dcb1fe 100644 --- a/editor/i18n/en/assets.js +++ b/editor/i18n/en/assets.js @@ -4,10 +4,12 @@ module.exports = { cancel: 'Cancel', warn: 'Warn', }, + inspector: { cloneToEdit: 'Clone it. Use and go into edit.', cloneToDirectoryIllegal: 'Please limit the saved path to the current project assets path', }, + assets: { reset: 'Reset', save: 'Save', @@ -41,6 +43,7 @@ module.exports = { mipFilterTip: 'Mip Filter', wrapModeSTip: 'Wrap Mode S', wrapModeTTip: 'Wrap Mode T', + bakeReflectionConvolution: 'Bake Reflection Convolution', faceSize: { name: 'Face Size', title: 'Size of each cube face. If not specified, or specified as 0, the default size, which is the nearest power of two to (image.width)/4, is used.', @@ -84,8 +87,8 @@ module.exports = { image: { type: 'Type', typeTip: 'Type', - bakeOfflineMipmaps: 'Bake Offline Mipmaps', - bakeOfflineMipmapsTip: 'Bake Offline Mipmaps', + // bakeOfflineMipmaps: 'Bake Offline Mipmaps', + // bakeOfflineMipmapsTip: 'Bake Offline Mipmaps', flipVertical: 'Flip Vertical', flipVerticalTip: 'Flip Vertical', fixAlphaTransparencyArtifacts: 'Fix Alpha Transparency Artifacts', @@ -95,7 +98,7 @@ module.exports = { }, spriteFrame: { packable: 'Packable', - packableTip: 'Whether to participate in dynamic atlas', + packableTip: 'Whether to participate in dynamic atlas or automatic atlas in build processes.', rotated: 'Rotated', rotatedTip: 'Whether the sprite frame in TexturePacker is rotated', offsetX: 'Offset X', @@ -124,6 +127,14 @@ module.exports = { borderRightTip: 'The right margin of 9-slicing', edit: 'Edit', editTip: 'Edit', + meshType: 'Mesh Type', + meshTypeTip: 'Type of the mesh generated for the sprite frame', + pixelsToUnit: 'Pixels To Unit', + pixelsToUnitTip: 'How many pixels in the sprite frame correspond to one unit in the world space', + pivotX: 'Pivot X', + pivotXTip: 'The origin`s X-axis position of sprite frame in the local coordinate system', + pivotY: 'Pivot Y', + pivotYTip: 'The origin`s Y-axis position of sprite frame in the local coordinate system', }, texture: { anisotropy: 'Anisotropy', @@ -241,7 +252,7 @@ module.exports = { original: 'Original', }, limitMaterialDumpDir: 'The extracted path needs to be scoped to the project path.', - legacyOptions:'Legacy Options', + legacyOptions: 'Legacy Options', legacyFbxImporter: { name: 'Compatible with v1.*', title: 'Whether this importer should be compatible with its behaviour prior to Cocos Creator version 1.* .', @@ -259,6 +270,12 @@ module.exports = { 'toggling this would update the corresponding prefab, so all the references in the scene should be
' + 'updated as well to accompany that. To be removed in further refactors.', }, + allowMeshDataAccess: { + name: 'Allow Data Access', + title: + 'Indicate whether the mesh data in this model could be read or write.
' + + 'If it is unchecked, the mesh data will be released after it is uploaded to GPU', + }, meshOptimizer: { name: 'Mesh Optimizer', title: 'Mesh Optimizer', @@ -307,19 +324,24 @@ module.exports = { auto: 'Auto', }, promoteSingleRootNode: { - name: 'Promote single root node', + name: 'Promote Single Root Node', title: - 'If enabled and there is only one single root node in a FBX scene,
' + - 'the single root node is used as the root of prefab when converting the FBX scene to Cocos Creator prefab.
' + - "Otherwise, the FBX scene become prefab's root.", + 'If enabled and there is only one root node in model scene,
' + + 'the single node becomes prefab\'s root after importing.
' + + "Otherwise, each root node of the scene becomes prefab's child node.", }, preferLocalTimeSpan: { name: 'Prefer Local Time Span', title: - 'When exporting FBX animations, whether prefer to use the time range recorded in FBX file. ' + - 'If one is not preferred, or one is invalid for use, the time range is robustly calculated. ' + + 'When exporting FBX animations, whether prefer to use the time range recorded in FBX file.
' + + 'If one is not preferred, or one is invalid for use, the time range is robustly calculated.
' + 'Some FBX generators may not export this information.', }, + smartMaterialEnabled: { + name: 'Smart Material Conversion', + title: 'Convert DCC materials to engine builtin materials which match the internal lighting model.', + warn: 'The model feature "Smart Material Conversion" in the project settings is turned off, please enable this feature to modify model level settings.', + }, }, textureCube: { anisotropy: 'Anisotropy', @@ -349,7 +371,7 @@ module.exports = { clearAllNodes: 'Clear', clearAllNodesWarn: 'Are you sure to clear all data of this Animation Mask?', illegalFbx: 'Import Skeleton Failed: this fbx asset has not contained sub prefab asset.', - nodeEnableTip: 'Whether enable this joint;
Alt + Click can toggle the children state.', + nodeEnableTip: 'Whether to enable this joint and its descendants.;
Alt + Click only toggle the state of itself.', }, multipleWarning: 'Multi-select editing of this type of asset is not supported', check_is_saved: { diff --git a/editor/i18n/en/components.js b/editor/i18n/en/components.js index 6dd7ecd94d..b4d0bcb53b 100644 --- a/editor/i18n/en/components.js +++ b/editor/i18n/en/components.js @@ -29,5 +29,7 @@ module.exports = { change_children: 'Yes, change children', change_self: 'No, this object only', }, + + missScriptTip: 'Script compilation fails, please check the error message and correct it, the component will be automatically restored after correction.', }, }; diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index bf6a46739d..1125566083 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -12,22 +12,22 @@ module.exports = { MeshRenderer: `${url}/${version}/manual/en/engine/renderable/model-component.html`, UITransform: `${url}/${version}/manual/en/ui-system/components/editor/ui-transform.html`, Sprite: `${url}/${version}/manual/en/ui-system/components/editor/sprite.html`, - SubContextView: `${url}/${version}/manual/zh/editor/publish/build-open-data-context.html`, + SubContextView: `${url}/${version}/manual/en/editor/publish/build-open-data-context.html`, BlockInputEvents: `${url}/${version}/manual/en/ui-system/components/editor/block-input-events.html`, Camera: `${url}/${version}/manual/en/editor/components/camera-component.html`, Canvas: `${url}/${version}/manual/en/ui-system/components/editor/canvas.html`, - SkinnedMeshRenderer: `${url}/${version}/manual/en/engine/animation/skeletal-animation.html`, - SkinnedMeshBatchRenderer: `${url}/${version}/manual/en/engine/animation/skeletal-animation.html`, - Ambient: `${url}/${version}/manual/zh/concepts/scene/light/lighttype/ambient.html`, - Skybox: `${url}/${version}/manual/zh/concepts/scene/skybox.html`, - Fog: `${url}/${version}/manual/zh/concepts/scene/fog.html`, - Shadow: `${url}/${version}/manual/zh/concepts/scene/light/shadow.html`, - DirectionalLight: `${url}/${version}/manual/en/concepts/scene/light/dir-light.html`, - SphereLight: `${url}/${version}/manual/en/concepts/scene/light/sphere-light.html`, - SpotLight: `${url}/${version}/manual/en/concepts/scene/light/spot-light.html`, + SkinnedMeshRenderer: `${url}/${version}/manual/en/animation/skeletal-animation.html`, + SkinnedMeshBatchRenderer: `${url}/${version}/manual/en/animation/skeletal-animation.html`, + Ambient: `${url}/${version}/manual/en/concepts/scene/light/lightType/ambient.html`, + Skybox: `${url}/${version}/manual/en/concepts/scene/skybox.html`, + Fog: `${url}/${version}/manual/en/concepts/scene/fog.html`, + Shadow: `${url}/${version}/manual/en/concepts/scene/light/shadow.html`, + DirectionalLight: `${url}/${version}/manual/en/concepts/scene/light/lightType/dir-light.html`, + SphereLight: `${url}/${version}/manual/en/concepts/scene/light/lightType/sphere-light.html`, + SpotLight: `${url}/${version}/manual/en/concepts/scene/light/lightType/spot-light.html`, UICoordinateTracker: `${url}/${version}/manual/en/ui-system/components/editor/ui-coordinate-tracker.html`, - Animation: `${url}/${version}/manual/en/engine/animation/animation-component.html`, - SkeletalAnimation: `${url}/${version}/manual/en/engine/animation/skeletal-animation.html`, + Animation: `${url}/${version}/manual/en/animation/animation-component.html`, + SkeletalAnimation: `${url}/${version}/manual/en/animation/skeletal-animation.html`, AudioSource: `${url}/${version}/manual/en/audio-system/overview.html`, Billboard: `${url}/${version}/manual/en/particle-system/billboard-component.html`, Line: `${url}/${version}/manual/en/particle-system/line-component.html`, @@ -243,7 +243,13 @@ module.exports = { label: { string: 'Text of the Label', horizontal_align: 'Horizontal alignment', + horizontal_align_left: 'Align Left', + horizontal_align_center: 'Align Horizontal Center', + horizontal_align_right: 'Align Right', vertical_align: 'Vertical alignment', + vertical_align_top: 'Align Top', + vertical_align_center: 'Align Vertical Center', + vertical_align_bottom: 'Align Bottom', font_size: 'Font size, in points', font_family: 'Font family name', line_height: 'Line height, in points', @@ -611,7 +617,6 @@ module.exports = { dstBlendFactor: 'Specify the destination Blend Factor', playOnLoad: 'If set to true, the particle system will automatically start playing on load', autoRemoveOnFinish: 'Indicate whether the owner node will be auto-removed when it has no particles left', - duration: 'How many seconds the emitter wil run. -1 means forever', emissionRate: 'Emission rate of the particles', life: 'Life and variation of each particle setter', totalParticles: 'Maximum particles of the system', @@ -874,6 +879,18 @@ module.exports = { label: "Running Stats", description: "Include various components and tools used to audit and display rendering stats.", }, + occlusion_query: { + label: "Occlusion Query", + description: "Hardware based occlusion query.", + }, + geometry_renderer: { + label: "Geometry Renderer", + description: "Used to render various geometries for debugging or use in editor.", + }, + debug_renderer: { + label: "Debug Renderer", + description: "Used to render screen text for debugging.", + }, tiled_map: { label: "Tiled Map", description: "Tiled map support.", diff --git a/editor/i18n/zh/assets.js b/editor/i18n/zh/assets.js index 6deaf405aa..83878c106b 100644 --- a/editor/i18n/zh/assets.js +++ b/editor/i18n/zh/assets.js @@ -4,10 +4,12 @@ module.exports = { cancel: '取消', warn: '警告', }, + inspector: { cloneToEdit: '克隆出新资源,使用并编辑', cloneToDirectoryIllegal: '保存路径请限制在当前项目 /assets 路径内', }, + assets: { reset: '重置', save: '保存', @@ -24,9 +26,9 @@ module.exports = { StartChar: 'Start Char', FontSize: 'Font Size', }, - particle:{ - spriteFrame:'Sprite Frame', - spriteFrameTip:'Sprite Frame', + particle: { + spriteFrame: 'Sprite Frame', + spriteFrameTip: 'Sprite Frame', }, erpTextureCube: { anisotropy: 'Anisotropy', @@ -41,6 +43,7 @@ module.exports = { mipFilterTip: 'Mip Filter', wrapModeSTip: 'Wrap Mode S', wrapModeTTip: 'Wrap Mode T', + bakeReflectionConvolution: 'Bake Reflection Convolution', faceSize: { name: 'Face Size', title: @@ -85,8 +88,8 @@ module.exports = { image: { type: 'Type', typeTip: 'Type', - bakeOfflineMipmaps: 'Bake Offline Mipmaps', - bakeOfflineMipmapsTip: 'Bake Offline Mipmaps', + // bakeOfflineMipmaps: 'Bake Offline Mipmaps', + // bakeOfflineMipmapsTip: 'Bake Offline Mipmaps', flipVertical: 'Flip Vertical', flipVerticalTip: 'Flip Vertical', fixAlphaTransparencyArtifacts: 'Fix Alpha Transparency Artifacts', @@ -96,7 +99,7 @@ module.exports = { }, spriteFrame: { packable: 'Packable', - packableTip: '是否参与动态合图', + packableTip: '是否参与动态合图或者自动图集的构建处理', rotated: 'Rotated', rotatedTip: 'TexturePacker 中的子资源是否被旋转', offsetX: 'Offset X', @@ -125,6 +128,14 @@ module.exports = { borderRightTip: '九宫格右边距', edit: 'Edit', editTip: '编辑', + meshType: 'Mesh Type', + meshTypeTip: 'SpriteFrame 生成的网格类型', + pixelsToUnit: 'Pixels To Unit', + pixelsToUnitTip: 'SpriteFrame 像素对应世界空间内单位长度的比例尺', + pivotX: 'Pivot X', + pivotXTip: 'SpriteFrame 本地坐标系原点的 X 轴位置', + pivotY: 'Pivot Y', + pivotYTip: 'SpriteFrame 本地坐标系原点的 Y 轴位置', }, texture: { anisotropy: 'Anisotropy', @@ -149,8 +160,8 @@ module.exports = { modelPreview: '模型预览', material: '材质', fbx: 'FBX', - no_model_tips:'没有模型可供预览', - drag_model_tips:'可将模型拖到这里进行预览', + no_model_tips: '没有模型可供预览', + drag_model_tips: '可将模型拖到这里进行预览', GlTFUserData: { normals: { name: '法线', @@ -242,7 +253,7 @@ module.exports = { original: '原始', }, limitMaterialDumpDir: '提取的路径需要限定在项目路径范围内', - legacyOptions:'旧版本遗留', + legacyOptions: '旧版本遗留', legacyFbxImporter: { name: '与 1.* 版本兼容', title: '此导入器是否应该与其在 Cocos Creator 1.* 之前版本的导入方式兼容。', @@ -258,6 +269,12 @@ module.exports = { '但注意改变此选项会影响生成的 prefab 内容,需要对应更新场景中的引用。
' + '后续重构会移除此流程。', }, + allowMeshDataAccess: { + name: '允许数据访问', + title: + '标识此模型中的所有网格的数据是否可被读写,此接口只对静态网格资源生效,
' + + '若不勾选,网格数据被提交到 GPU 后会被自动释放。
', + }, meshOptimizer: { name: 'Mesh Optimizer', title: 'Mesh Optimizer', @@ -305,12 +322,17 @@ module.exports = { auto: '自动', }, promoteSingleRootNode: { - name: '提升单一根结点', - title: '若开启并且 FBX 场景仅有一个根节点,那么当转换该 FBX 场景为 Cocos Creator 预制体时,
以该根节点作为预制体的根节点,否则以该 FBX 场景的根节点作为预制体的根节点。', + name: '提升单一根节点', + title: '若开启并且模型场景顶部仅有一个根节点,那么该节点就作为预制体的根节点。
否则,场景的所有根节点作为预制体的子节点。', }, preferLocalTimeSpan: { name: '优先使用文件时间范围', - title: '在导出 FBX 动画时,是否优先使用 FBX 文件中记录的动画时间范围。若不使用该时间范围或此范围不可能用,则会粗略地计算动画时间范围。有些 FBX 生产工具中可能并未导出该信息。', + title: '在导出 FBX 动画时,是否优先使用 FBX 文件中记录的动画时间范围。
若不使用该时间范围或此范围不可能用,则会粗略地计算动画时间范围。有些 FBX 生产工具中可能并未导出该信息。', + }, + smartMaterialEnabled: { + name: '材质智能转换', + title: '将 DCC 材质转化为引擎材质, 并匹对 DCC 材质的光照模型', + warn: '项目设置里的模型配置 "材质智能转换" 已关闭,请启用此项功能来修改模型级别设置。', }, }, textureCube: { @@ -327,7 +349,7 @@ 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 模式,这会使材质的 tilingOffset 等属性完全失效。', }, material: { 'fail-to-load-custom-inspector': 'material: 自定义 effect {effect} 的 inspector 加载失败', @@ -341,7 +363,7 @@ module.exports = { clearAllNodes: '清空', clearAllNodesWarn: '确定清空所有遮罩数据吗?', illegalFbx: '导入骨骼失败:此 fbx 文件不含有 prefab 子资源。', - nodeEnableTip: '是否启用这个节点
按住 Alt + 点击,可以切换自身和子孙节点的状态', + nodeEnableTip: '是否启用该节点及其子孙节点
按住 Alt + 点击,只切换自身的状态。', }, multipleWarning: '不支持此类型资源的多选编辑', check_is_saved: { diff --git a/editor/i18n/zh/components.js b/editor/i18n/zh/components.js index dd3ab89257..85671c2098 100644 --- a/editor/i18n/zh/components.js +++ b/editor/i18n/zh/components.js @@ -24,5 +24,7 @@ module.exports = { change_children: '连同修改子节点', change_self: '只修改节点自身', }, + + missScriptTip: "脚本编译失败,请检查报错信息并进行修正,该组件将在修正后自动还原。", }, }; diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index b67fbfa9b6..f75c669399 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -16,18 +16,18 @@ module.exports = { BlockInputEvents: `${url}/${version}/manual/zh/ui-system/components/editor/block-input-events.html`, Camera: `${url}/${version}/manual/zh/editor/components/camera-component.html`, Canvas: `${url}/${version}/manual/zh/ui-system/components/editor/canvas.html`, - SkinnedMeshRenderer: `${url}/${version}/manual/zh/engine/animation/skeletal-animation.html`, - SkinnedMeshBatchRenderer: `${url}/${version}/manual/zh/engine/animation/skeletal-animation.html`, - Ambient: `${url}/${version}/manual/zh/concepts/scene/light/lighttype/ambient.html`, + SkinnedMeshRenderer: `${url}/${version}/manual/zh/animation/skeletal-animation.html`, + SkinnedMeshBatchRenderer: `${url}/${version}/manual/zh/animation/skeletal-animation.html`, + Ambient: `${url}/${version}/manual/zh/concepts/scene/light/lightType/ambient.html`, Skybox: `${url}/${version}/manual/zh/concepts/scene/skybox.html`, Fog: `${url}/${version}/manual/zh/concepts/scene/fog.html`, Shadow: `${url}/${version}/manual/zh/concepts/scene/light/shadow.html`, - DirectionalLight: `${url}/${version}/manual/zh/concepts/scene/light/dir-light.html`, - SphereLight: `${url}/${version}/manual/zh/concepts/scene/light/sphere-light.html`, - SpotLight: `${url}/${version}/manual/zh/concepts/scene/light/spot-light.html`, + DirectionalLight: `${url}/${version}/manual/zh/concepts/scene/light/lightType/dir-light.html`, + SphereLight: `${url}/${version}/manual/zh/concepts/scene/light/lightType/sphere-light.html`, + SpotLight: `${url}/${version}/manual/zh/concepts/scene/light/lightType/spot-light.html`, UICoordinateTracker: `${url}/${version}/manual/zh/ui-system/components/editor/ui-coordinate-tracker.html`, - Animation: `${url}/${version}/manual/zh/engine/animation/animation-component.html`, - SkeletalAnimation: `${url}/${version}/manual/zh/engine/animation/skeletal-animation.html`, + Animation: `${url}/${version}/manual/zh/animation/animation-component.html`, + SkeletalAnimation: `${url}/${version}/manual/zh/animation/skeletal-animation.html`, AudioSource: `${url}/${version}/manual/zh/audio-system/overview.html`, Billboard: `${url}/${version}/manual/zh/particle-system/billboard-component.html`, Line: `${url}/${version}/manual/zh/particle-system/line-component.html`, @@ -154,7 +154,7 @@ module.exports = { use_color_temperature: '是否启用光源色温', color_temperature: '光源色温', illuminance: '光源强度', - luminous_power: '光通量', + luminous_flux: '光通量', luminance: '光亮度', term: '当前使用的光度学计量单位', size: '光源大小', @@ -239,7 +239,13 @@ module.exports = { label: { string: 'Label 显示的文本内容字符串', horizontal_align: '文字水平对齐模式', + horizontal_align_left: '左对齐', + horizontal_align_center: '水平居中对齐', + horizontal_align_right: '右对齐', vertical_align: '文字垂直对齐模式', + vertical_align_top: '顶对齐', + vertical_align_center: '垂直居中对齐', + vertical_align_bottom: '底对齐', font_size: '文字尺寸,以 point 为单位', font_family: '文字字体名字', line_height: '文字行高,以 point 为单位', @@ -595,7 +601,6 @@ module.exports = { dstBlendFactor: '指定目标的混合模式', playOnLoad: '如果设置为 true 运行时会自动发射粒子', autoRemoveOnFinish: '粒子播放完毕后自动销毁所在的节点', - duration: '发射器生存时间,单位秒,-1表示持续发射', emissionRate: '每秒发射的粒子数目', life: '粒子的运行时间及变化范围', totalParticles: '粒子最大数量', @@ -855,6 +860,18 @@ module.exports = { label: "运行状态统计", description: "包含用于统计、显示渲染数据的组件与工具。", }, + occlusion_query: { + label: "遮挡查询", + description: "基于硬件的遮挡查询。", + }, + geometry_renderer: { + label: "几何体渲染器", + description: "渲染各种几何体,用于调试目的或者编辑器。", + }, + debug_renderer: { + label: "调试文字渲染器", + description: "渲染屏幕文字,用于调试目的。", + }, tiled_map: { label: "Tiled 地图", description: "Tiled 地图支持。", diff --git a/editor/inspector/assets.js b/editor/inspector/assets.js index 801af0b256..c44d89d898 100644 --- a/editor/inspector/assets.js +++ b/editor/inspector/assets.js @@ -29,6 +29,5 @@ module.exports = { texture: join(__dirname, './assets/texture/index.js'), typescript: join(__dirname, './assets/typescript.js'), unknown: join(__dirname, './assets/unknown.js'), - markdown: join(__dirname, './assets/markdown.js'), prefab: join(__dirname, './assets/prefab.js'), }; diff --git a/editor/inspector/assets/animation-mask.js b/editor/inspector/assets/animation-mask.js index fa536f0a1d..b9169ac438 100644 --- a/editor/inspector/assets/animation-mask.js +++ b/editor/inspector/assets/animation-mask.js @@ -17,43 +17,57 @@ exports.template = ` `; exports.methods = { - updateReadonly(element) { - if (this.asset.readonly) { - element.setAttribute('disabled', true); - } else { - element.removeAttribute('disabled'); - } + record() { + return JSON.stringify(this.queryData); }, + + async restore(record) { + record = JSON.parse(record); + if (!record || typeof record !== 'object') { + return false; + } + + this.queryData = await Editor.Message.request('scene', 'change-animation-mask', { + method: 'change-dump', + dump: record, + }); + await this.changed({ snapshot: false }); + return true; + }, + async query(uuid) { - this.queryData = await Editor.Message.request('scene', 'query-animation-mask', uuid); - this.updateTree(); + return await Editor.Message.request('scene', 'query-animation-mask', uuid); }, async apply() { this.reset(); await Editor.Message.request('scene', 'apply-animation-mask', this.asset.uuid); }, reset() { - this.dirtyData.origin = this.dirtyData.realtime; this.dirtyData.uuid = ''; }, - async dataChange() { - await Editor.Message.request('scene', 'change-animation-mask', { - method: 'change-dump', - dump: this.queryData, - }); - + async changed(state) { + this.updateInterface(); this.setDirtyData(); - this.dispatch('change'); + + this.dispatch('change', state); }, - jointEnableChange(key, checked, loop) { - const { children, origin } = this.flatData[key]; - origin.value.enabled.value = checked; + updateInterface() { + const convertData = this.convertData(this.queryData.joints.value); + this.flatData = convertData.flatData; + this.$.tree.tree = convertData.treeData; - if (loop) { - children.forEach((childKey) => { - this.jointEnableChange(childKey, checked, loop); - }); + + this.updateReadonly(this.$.import); + this.updateReadonly(this.$.clear); + this.updateReadonly(this.$.tree); + }, + + updateReadonly(element) { + if (this.asset.readonly) { + element.setAttribute('disabled', true); + } else { + element.removeAttribute('disabled'); } }, @@ -65,6 +79,8 @@ exports.methods = { if (!this.dirtyData.origin) { this.dirtyData.origin = this.dirtyData.realtime; + + this.dispatch('snapshot'); } }, @@ -159,10 +175,15 @@ exports.methods = { return { flatData, treeData }; }, - updateTree() { - const convertData = this.convertData(this.queryData._jointMasks.value); - this.flatData = convertData.flatData; - this.$.tree.tree = convertData.treeData; + jointEnableChange(key, checked, loop) { + const { children, origin } = this.flatData[key]; + origin.value.enabled.value = checked; + + if (loop) { + children.forEach((childKey) => { + this.jointEnableChange(childKey, checked, loop); + }); + } }, }; @@ -215,7 +236,7 @@ exports.ready = function() { timestamp: rawTimestamp, type: 'asset', assetFilter: { - importer: 'fbx', + importer: ['fbx', 'gltf'], }, events: { async confirm(uuid) { @@ -229,9 +250,7 @@ exports.ready = function() { uuid: info.redirect.uuid, }); - panel.updateTree(); - panel.setDirtyData(); - panel.dispatch('change'); + panel.changed(); }, }, }); @@ -251,9 +270,7 @@ exports.ready = function() { uuid: this.asset.uuid, }); - panel.updateTree(); - panel.setDirtyData(); - panel.dispatch('change'); + this.changed(); } }); @@ -267,12 +284,17 @@ exports.ready = function() { panel.$.tree.setTemplate('left', ''); panel.$.tree.setTemplateInit('left', ($left) => { $left.$checkbox = $left.querySelector('ui-checkbox'); - $left.$checkbox.addEventListener('click', (event) => { + $left.$checkbox.addEventListener('click', async (event) => { const key = $left.data.detail.key; const origin = panel.flatData[key].origin; - panel.jointEnableChange(key, !origin.value.enabled.value, event.altKey); - panel.dataChange(); - panel.$.tree.render(); + panel.jointEnableChange(key, !origin.value.enabled.value, !event.altKey); + + panel.queryData = await Editor.Message.request('scene', 'change-animation-mask', { + method: 'change-dump', + dump: panel.queryData, + }); + + panel.changed(); }); }); panel.$.tree.setRender('left', ($left) => { @@ -307,7 +329,7 @@ exports.update = async function(assetList, metaList) { this.meta = metaList[0]; if (assetList.length !== 1) { - this.$.container.innerText = ''; + this.$.container.innerText = Editor.I18n.t('ENGINE.assets.multipleWarning'); return; } @@ -316,8 +338,9 @@ exports.update = async function(assetList, metaList) { this.dirtyData.origin = ''; } - await this.query(this.asset.uuid); + this.queryData = await this.query(this.asset.uuid); + this.updateInterface(); this.setDirtyData(); }; diff --git a/editor/inspector/assets/audio-clip.js b/editor/inspector/assets/audio-clip.js index ee69af99c1..beca784a2f 100644 --- a/editor/inspector/assets/audio-clip.js +++ b/editor/inspector/assets/audio-clip.js @@ -27,7 +27,7 @@ exports.update = function(assetList, metaList) { html += `
${asset.name}
`; } - html += ``; + html += ``; }); this.$.constainer.innerHTML = html; diff --git a/editor/inspector/assets/erp-texture-cube.js b/editor/inspector/assets/erp-texture-cube.js index b3a134f376..97bcae6a8c 100644 --- a/editor/inspector/assets/erp-texture-cube.js +++ b/editor/inspector/assets/erp-texture-cube.js @@ -1,4 +1,4 @@ -exports.template = ` +exports.template = /* html */`
@@ -8,7 +8,7 @@ exports.template = ` value="i18n:ENGINE.assets.erpTextureCube.anisotropy" > - @@ -19,7 +19,7 @@ exports.template = ` value="i18n:ENGINE.assets.erpTextureCube.faceSize.name" > - @@ -96,6 +96,15 @@ exports.template = ` + + + + + +
`; @@ -114,6 +123,8 @@ exports.$ = { mipfilter: '#mipfilter', wrapModeS: '#wrapModeS', wrapModeT: '#wrapModeT', + bakeReflectionConvo: '.bake-reflection-convo', + mipBakeMode: '#mipBakeMode', }; exports.ready = function() { @@ -209,6 +220,17 @@ const Elements = { this.updateReadonly(this.$.wrapModeT); }, }, + mipBakeMode: { + ready() { + this.$.mipBakeMode.addEventListener('change', this.dataChange.bind(this, 'mipBakeMode')); + }, + update() { + 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'); + }, + }, }; @@ -226,9 +248,20 @@ 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] = event.target.value || undefined; + meta.userData[key] = value || undefined; }); this.dispatch('change'); diff --git a/editor/inspector/assets/fbx/animation.js b/editor/inspector/assets/fbx/animation.js index 8144d03e3f..b7493b8015 100644 --- a/editor/inspector/assets/fbx/animation.js +++ b/editor/inspector/assets/fbx/animation.js @@ -563,15 +563,17 @@ const Elements = { panel.$.rulerMaking.innerText = ''; const maxNum = panel.gridConfig.mod + 1; for (let minNum = 1; minNum <= maxNum; minNum++) { - const label = document.createElement('div'); - label.setAttribute('class', 'label-item'); - label.style.left = `${panel.gridConfig.spacing * 5 * (minNum - 1) - 6}px`; - panel.$.rulerMaking.appendChild(label); - - const span = document.createElement('span'); - span.setAttribute('class', 'mid-label'); - span.innerText = (panel.gridConfig.labelStep * (minNum - 1)).toFixed(2); - label.appendChild(span); + // If the remaining cells are less than 1.5, hide the label + if (((panel.gridConfig.width / panel.gridConfig.spacing) % 5) >= 1.5 || minNum !== maxNum) { + const label = document.createElement('div'); + label.setAttribute('class', 'label-item'); + label.style.left = `${panel.gridConfig.spacing * 5 * (minNum - 1) - 6}px`; + panel.$.rulerMaking.appendChild(label); + const span = document.createElement('span'); + span.setAttribute('class', 'mid-label'); + span.innerText = (panel.gridConfig.labelStep * (minNum - 1)).toFixed(2); + label.appendChild(span); + } } const lastMakingLabel = document.createElement('div'); lastMakingLabel.setAttribute('class', 'label-item'); diff --git a/editor/inspector/assets/fbx/fbx.js b/editor/inspector/assets/fbx/fbx.js index aa1a89c014..dacbb0a613 100644 --- a/editor/inspector/assets/fbx/fbx.js +++ b/editor/inspector/assets/fbx/fbx.js @@ -12,14 +12,17 @@ exports.template = ` - - - - + + + +
+ +
+
@@ -47,6 +50,19 @@ ui-section { display: none; margin-top: 10px; } +.smart-material-prop .warn-words { + display: none; +} + +.smart-material-prop[readonly] .warn-words { + display: block; + margin-top: 5px; + line-height: 20px; +} +.smart-material-prop[readonly] .smartMaterialEnabled-checkbox { + pointer-events: none; + opacity: 0.3; +} `; exports.$ = { @@ -55,8 +71,9 @@ exports.$ = { legacyImporter: '.legacy-importer', legacyFbxImporterCheckbox: '.legacyFbxImporter-checkbox', animationBakeRateSelect: '.animationBakeRate-select', - promoteSingleRootNodeCheckbox: '.promoteSingleRootNode-checkbox', preferLocalTimeSpanCheckbox: '.preferLocalTimeSpan-checkbox', + smartMaterialEnabledCheckbox: '.smartMaterialEnabled-checkbox', + smartMaterialEnabledProp: '.smart-material-prop', }; /** @@ -114,26 +131,6 @@ const Elements = { panel.updateReadonly(panel.$.animationBakeRateSelect); }, }, - promoteSingleRootNode: { - ready() { - const panel = this; - - panel.$.promoteSingleRootNodeCheckbox.addEventListener('change', panel.setProp.bind(panel, 'fbx.promoteSingleRootNode', 'boolean')); - }, - update() { - const panel = this; - - let defaultValue = false; - if (panel.meta.userData.fbx) { - defaultValue = panel.getDefault(panel.meta.userData.fbx.promoteSingleRootNode, defaultValue); - } - - panel.$.promoteSingleRootNodeCheckbox.value = defaultValue; - - panel.updateInvalid(panel.$.promoteSingleRootNodeCheckbox, 'fbx.promoteSingleRootNode'); - panel.updateReadonly(panel.$.promoteSingleRootNodeCheckbox); - }, - }, preferLocalTimeSpan: { ready() { const panel = this; @@ -154,9 +151,36 @@ const Elements = { panel.updateReadonly(panel.$.preferLocalTimeSpanCheckbox); }, }, + smartMaterialEnabled: { + ready() { + const panel = this; + + panel.$.smartMaterialEnabledCheckbox.addEventListener('change', panel.setProp.bind(panel, 'fbx.smartMaterialEnabled', 'boolean')); + }, + async update() { + const panel = this; + + const laboratoryExpectedValue = await Editor.Profile.getProject('project', 'fbx.material.smart'); + if (!laboratoryExpectedValue) { + panel.$.smartMaterialEnabledProp.setAttribute('readonly', ''); + } else { + panel.$.smartMaterialEnabledProp.removeAttribute('readonly'); + } + + let defaultValue = false; + if (panel.meta.userData.fbx) { + defaultValue = panel.getDefault(panel.meta.userData.fbx.smartMaterialEnabled, defaultValue); + } + + panel.$.smartMaterialEnabledCheckbox.value = defaultValue; + + panel.updateInvalid(panel.$.smartMaterialEnabledCheckbox, 'fbx.smartMaterialEnabled'); + panel.updateReadonly(panel.$.smartMaterialEnabledCheckbox); + }, + }, }; -exports.update = function(assetList, metaList) { +exports.update = async function(assetList, metaList) { this.assetList = assetList; this.metaList = metaList; this.asset = assetList[0]; @@ -165,7 +189,7 @@ exports.update = function(assetList, metaList) { for (const prop in Elements) { const element = Elements[prop]; if (element.update) { - element.update.call(this); + await element.update.call(this); } } }; diff --git a/editor/inspector/assets/fbx/model.js b/editor/inspector/assets/fbx/model.js index c6c359fbfd..bb82838971 100644 --- a/editor/inspector/assets/fbx/model.js +++ b/editor/inspector/assets/fbx/model.js @@ -22,7 +22,15 @@ exports.template = ` - + + + + + + + + +
@@ -95,6 +103,8 @@ exports.$ = { morphNormalsSelect: '.morphNormals-select', skipValidationCheckbox: '.skipValidation-checkbox', disableMeshSplitCheckbox: '.disableMeshSplit-checkbox', + allowMeshDataAccessCheckbox: '.allowMeshDataAccess-checkbox', + promoteSingleRootNodeCheckbox: '.promoteSingleRootNode-checkbox', meshOptimizerCheckbox: '.meshOptimizer-checkbox', meshOptimizerSISlider: '.meshOptimizer-si-slider', meshOptimizerSACheckbox: '.meshOptimizer-sa-checkbox', @@ -210,6 +220,42 @@ const Elements = { panel.updateReadonly(panel.$.disableMeshSplitCheckbox); }, }, + allowMeshDataAccess: { + ready() { + const panel = this; + + panel.$.allowMeshDataAccessCheckbox.addEventListener('change', panel.setProp.bind(panel, 'allowMeshDataAccess')); + }, + update() { + const panel = this; + + panel.$.allowMeshDataAccessCheckbox.value = panel.getDefault(panel.meta.userData.allowMeshDataAccess, true); + + panel.updateInvalid(panel.$.allowMeshDataAccessCheckbox, 'allowMeshDataAccess'); + panel.updateReadonly(panel.$.allowMeshDataAccessCheckbox); + }, + }, + // move this from ./fbx.js in v3.6.0 + promoteSingleRootNode: { + ready() { + const panel = this; + + panel.$.promoteSingleRootNodeCheckbox.addEventListener('change', panel.setProp.bind(panel, 'promoteSingleRootNode')); + }, + update() { + const panel = this; + + let defaultValue = false; + if (panel.meta.userData) { + defaultValue = panel.getDefault(panel.meta.userData.promoteSingleRootNode, defaultValue); + } + + panel.$.promoteSingleRootNodeCheckbox.value = defaultValue; + + panel.updateInvalid(panel.$.promoteSingleRootNodeCheckbox, 'promoteSingleRootNode'); + panel.updateReadonly(panel.$.promoteSingleRootNodeCheckbox); + }, + }, meshOptimizer: { ready() { const panel = this; @@ -357,6 +403,9 @@ exports.methods = { case 'normals': case 'tangents': case 'morphNormals': value = Number(value); break; + case 'promoteSingleRootNode': + value = Boolean(value); + break; } meta.userData[prop] = value; diff --git a/editor/inspector/assets/image.js b/editor/inspector/assets/image.js index 2dd755856e..30d25adec8 100644 --- a/editor/inspector/assets/image.js +++ b/editor/inspector/assets/image.js @@ -12,10 +12,10 @@ exports.template = ` - + @@ -26,8 +26,13 @@ exports.template = ` - - + + + + +
`; @@ -45,9 +50,8 @@ exports.style = ` `; exports.$ = { - panel: '.sub-panel', panelSection: '.sub-panel-section', - panelName: '.sub-panel-name', + texturePanelSection: '.sub-texture-panel-section', container: '.asset-image', typeSelect: '.type-select', @@ -57,7 +61,7 @@ exports.$ = { isRGBEProp: '.isRGBE-prop', isRGBECheckbox: '.isRGBE-checkbox', - bakeOfflineMipmapsCheckbox: '.bakeOfflineMipmaps-checkbox', + // bakeOfflineMipmapsCheckbox: '.bakeOfflineMipmaps-checkbox', }; /** @@ -77,6 +81,7 @@ 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(); }); }, update() { @@ -115,26 +120,26 @@ const Elements = { panel.updateReadonly(panel.$.flipVerticalCheckbox); }, }, - bakeOfflineMipmaps: { - ready() { - const panel = this; + // bakeOfflineMipmaps: { + // ready() { + // const panel = this; - panel.$.bakeOfflineMipmapsCheckbox.addEventListener('change', (event) => { - panel.metaList.forEach((meta) => { - meta.userData.bakeOfflineMipmaps = event.target.value; - }); - panel.dispatch('change'); - }); - }, - update() { - const panel = this; + // panel.$.bakeOfflineMipmapsCheckbox.addEventListener('change', (event) => { + // panel.metaList.forEach((meta) => { + // meta.userData.bakeOfflineMipmaps = event.target.value; + // }); + // panel.dispatch('change'); + // }); + // }, + // update() { + // const panel = this; - panel.$.bakeOfflineMipmapsCheckbox.value = panel.meta.userData.bakeOfflineMipmaps; + // panel.$.bakeOfflineMipmapsCheckbox.value = panel.meta.userData.bakeOfflineMipmaps; - panel.updateInvalid(panel.$.bakeOfflineMipmapsCheckbox, 'bakeOfflineMipmaps'); - panel.updateReadonly(panel.$.bakeOfflineMipmapsCheckbox); - }, - }, + // panel.updateInvalid(panel.$.bakeOfflineMipmapsCheckbox, 'bakeOfflineMipmaps'); + // panel.updateReadonly(panel.$.bakeOfflineMipmapsCheckbox); + // }, + // }, fixAlphaTransparencyArtifacts: { ready() { @@ -226,7 +231,10 @@ exports.ready = function() { element.ready.call(this); } } - this.$.panel.addEventListener('change', () => { + this.$.panelSection.addEventListener('change', () => { + this.dispatch('change'); + }); + this.$.texturePanelSection.addEventListener('change', () => { this.dispatch('change'); }); }; @@ -252,7 +260,7 @@ exports.methods = { } }, - async updatePanel() { + async _updatePanel($section, type) { const assetList = []; const metaList = []; @@ -264,7 +272,7 @@ exports.methods = { 'texture cube': 'erp-texture-cube', }; - const imageImporter = imageTypeToImporter[this.meta.userData.type]; + const imageImporter = imageTypeToImporter[type]; this.assetList.forEach((asset) => { if (!asset) { @@ -305,15 +313,26 @@ exports.methods = { }); if (!assetList.length || !metaList.length) { - this.$.panelSection.style.display = 'none'; + $section.style.display = 'none'; return; } else { - this.$.panelSection.style.display = 'block'; + $section.style.display = 'block'; } const asset = assetList[0]; - this.$.panelName.setAttribute('value', this.meta.userData.type); - this.$.panel.setAttribute('src', path.join(__dirname, `./${asset.importer}.js`)); - this.$.panel.update(assetList, metaList); + const $label = $section.querySelector('ui-label'); + $label.setAttribute('value', type); + const $panel = $section.querySelector('ui-panel'); + $panel.setAttribute('src', path.join(__dirname, `./${asset.importer}.js`)); + $panel.update(assetList, metaList); + }, + + async updatePanel() { + this._updatePanel(this.$.panelSection, this.meta.userData.type); + if (this.meta.userData.type === 'sprite-frame') { + this._updatePanel(this.$.texturePanelSection, 'texture'); + } else { + this.$.texturePanelSection.style.display = 'none'; + } }, }; diff --git a/editor/inspector/assets/markdown.js b/editor/inspector/assets/markdown.js deleted file mode 100644 index d757b2053c..0000000000 --- a/editor/inspector/assets/markdown.js +++ /dev/null @@ -1,87 +0,0 @@ -const { createReadStream } = require('fs'); -const ReadLine = require('readline'); - -const MAX_LINES = 400; -const MAX_LENGTH = 20000; - -exports.template = ` -
- -
`; - -exports.$ = { - container: '.asset-markdown', - code: 'ui-markdown', -}; - -exports.style = ` -.asset-markdown { - flex: 1; - display: flex; - flex-direction: column; - height: 0px; // it is necessary -} -.asset-typescript > ui-markdown { - flex: 1; -} -`; - -exports.update = function update(assetList, metaList) { - this.assetList = assetList; - this.metaList = metaList; - this.meta = metaList[0]; - this.asset = assetList[0]; - - let display = 'none'; - if (assetList.length === 1) { - display = 'flex'; - } - this.$.container.style.display = display; - - if (display === 'none') { - return; - } - - // Displays 400 lines or 20,000 characters - const readStream = createReadStream(this.asset.file, { - encoding: 'utf-8', - }); - - let remainLines = MAX_LINES; - let remainLength = MAX_LENGTH; - let text = ''; - - const readLineStream = ReadLine.createInterface({ - input: readStream, - setEncoding: 'utf-8', - }); - - readLineStream.on('line', (line) => { - const lineLength = line.length; - if (lineLength > remainLength) { - line = line.substr(0, remainLength); - remainLength = 0; - } else { - remainLength -= lineLength; - } - - remainLines--; - text += `${line}\n`; - - if (remainLines <= 0 || remainLength <= 0) { - text += '...\n'; - readLineStream.close(); - readStream.close(); - } - }); - - readLineStream.on('close', (err) => { - if (err) { - throw err; - } - - if (this.$.code) { - this.$.code.textContent = text; - } - }); -}; diff --git a/editor/inspector/assets/material-header.js b/editor/inspector/assets/material-header.js index e237bf1ce5..0cedc584b9 100644 --- a/editor/inspector/assets/material-header.js +++ b/editor/inspector/assets/material-header.js @@ -184,4 +184,7 @@ exports.close = function() { callMaterialPreviewFunction('hide'); panel.resizeObserver.unobserve(panel.$.container); Editor.Message.removeBroadcastListener('material-inspector:change-dump', this.updatePreviewDataDirtyBind); + // clear the canvas on close hook + const context = panel.$.canvas.getContext('2d'); + context.clearRect(0, 0, panel.$.canvas.width, panel.$.canvas.height); }; diff --git a/editor/inspector/assets/material.js b/editor/inspector/assets/material.js index c5cb0b0f23..d371abe55c 100644 --- a/editor/inspector/assets/material.js +++ b/editor/inspector/assets/material.js @@ -3,13 +3,21 @@ const { materialTechniquePolyfill } = require('../utils/material'); const { setDisabled, setReadonly, setHidden, loopSetAssetDumpDataReadonly } = require('../utils/prop'); const { join, sep, normalize } = require('path'); -const cacheDot = '._'; exports.style = ` -ui-button.location { flex: none; margin-left: 6px; } +.invalid { display: none; } +.invalid[active] { display: block; } +.invalid[active] ~ * { display: none; } + +.custom[src] + .default { display: none; } + +ui-button.location { flex: none; margin-left: 4px; } `; exports.template = /* html */ ` +
+ +
Effect @@ -23,126 +31,163 @@ exports.template = /* html */ `
-
- -
-
- - -
-
+ +
+
+ + +
+
+
`; exports.$ = { - pass: '.pass', + invalid: '.invalid', + header: '.header', - section: '.section', effect: '.effect', location: '.location', technique: '.technique', - materialDump: '.material-dump', useInstancing: '.useInstancing', useBatching: '.useBatching', - customSection: '.customSection', - customPanel: '.customPanel', + materialDump: '.material-dump', + + custom: '.custom', }; exports.methods = { - async getCustomInspector() { - const currentEffectInfo = this._effects.find((effect) => { - return effect.name === this.material.effect; + record() { + return JSON.stringify({ + material: this.material, + cacheData: this.cacheData, }); - if (currentEffectInfo && currentEffectInfo.uuid) { - const meta = await Editor.Message.request('asset-db', 'query-asset-meta', currentEffectInfo.uuid); - return meta && meta.userData && meta.userData.editor && meta.userData.editor.inspector; - } - return ''; }, - /** - * Custom Save - */ + async restore(record) { + record = JSON.parse(record); + if (!record || typeof record !== 'object' || !record.material) { + return false; + } + + this.material = record.material; + this.cacheData = record.cacheData; + + await this.updateEffect(); + + await this.updateInterface(); + + await this.change({ snapshot: false }); + + return true; + }, + async apply() { this.reset(); await Editor.Message.request('scene', 'apply-material', this.asset.uuid, this.material); }, reset() { - this.dirtyData.origin = this.dirtyData.realtime; this.dirtyData.uuid = ''; this.cacheData = {}; }, - /** - * - * @param {string} inspector - */ - async updateCustomInspector(inspector) { - this.$.customPanel.hidden = false; - this.$.section.hidden = true; - this.$.materialDump.hidden = true; - try { - if (inspector.startsWith('packages://')) { - const relatePath = normalize(inspector.replace('packages://', '')); - const name = relatePath.split(sep)[0]; - const packagePath = Editor.Package.getPackages({ name, enable: true })[0].path; - const path = join(packagePath, relatePath.split(name)[1]); - if (this.$.customPanel.getAttribute('src') !== path) { - this.$.customPanel.setAttribute('src', path); - } - this.$.customPanel.update(this.material, this.assetList, this.metaList); - } else { - throw Editor.I18n.t('ENGINE.assets.material.illegal-inspector-url'); + + async change(state) { + this.canUpdatePreview = true; + await this.setDirtyData(); + this.dispatch('change', state); + }, + + async updateEffect() { + const effectMap = await Editor.Message.request('scene', 'query-all-effects'); + this.effects = Object.keys(effectMap).sort().filter((name) => { + const effect = effectMap[name]; + return !effect.hideInEditor; + }).map((name) => { + const effect = effectMap[name]; + return { + name, + uuid: effect.uuid, + }; + }); + + let effectOption = ''; + for (let effect of this.effects) { + effectOption += ``; + } + this.$.effect.innerHTML = effectOption; + + this.$.effect.value = this.material.effect; + setDisabled(this.asset.readonly, this.$.effect); + }, + + async updateInterface() { + this.updateTechnique(); + + const currentEffectInfo = this.effects.find((effect) => { + return effect.name === this.material.effect; + }); + + this.customInterface = ''; + if (currentEffectInfo && currentEffectInfo.uuid) { + const meta = await Editor.Message.request('asset-db', 'query-asset-meta', currentEffectInfo.uuid); + if (meta && meta.userData && meta.userData.editor) { + this.customInterface = meta.userData.editor.inspector; } - } catch (error) { - console.error(error); - console.error(Editor.I18n.t('ENGINE.assets.material.fail-to-load-custom-inspector', { effect: this.material.effect })); + } + + if (this.customInterface && this.customInterface.startsWith('packages://')) { + try { + const relatePath = normalize(this.customInterface.replace('packages://', '')); + const name = relatePath.split(sep)[0]; + + const packagePath = Editor.Package.getPackages({ name, enable: true })[0].path; + + const filePath = join(packagePath, relatePath.split(name)[1]); + if (this.$.custom.getAttribute('src') !== filePath) { + this.$.custom.setAttribute('src', filePath); + } + + this.$.custom.update(this.material, this.assetList, this.metaList); + + } catch (err) { + console.error(err); + console.error(Editor.I18n.t('ENGINE.assets.material.illegal-inspector-url')); + } + } else { + this.$.custom.removeAttribute('src'); this.updatePasses(); } }, - /** - * Detection of data changes only determines the currently selected technique - */ - setDirtyData() { - this.dirtyData.realtime = JSON.stringify({ - effect: this.material.effect, - technique: this.material.technique, - techniqueData: this.material.data[this.material.technique], + + updateTechnique() { + let techniqueOption = ''; + this.material.data.forEach((technique, index) => { + const name = technique.name ? `${index} - ${technique.name}` : index; + techniqueOption += ``; }); + this.$.technique.innerHTML = techniqueOption; + this.$.technique.value = this.material.technique; - if (!this.dirtyData.origin) { - this.dirtyData.origin = this.dirtyData.realtime; - } - - this.canUpdatePreview = true; + setDisabled(this.asset.readonly, this.$.technique); }, - isDirty() { - const isDirty = this.dirtyData.origin !== this.dirtyData.realtime; - return isDirty; - }, - - /** - * Update the pass data that is finally displayed in the panel - */ - updatePasses() { - if (this.$.customPanel.hasAttribute('src')) { - this.$.customPanel.removeAttribute('src'); - } - this.$.customPanel.hidden = true; - this.$.section.hidden = false; - this.$.materialDump.hidden = false; - // Automatic rendering of content - // The data in passes is not all the values that need to be rendered - // So it's sorted here, but that doesn't make sense - // The logical way to do it would be to return a normal dump when querying for material - + async updatePasses() { const technique = materialTechniquePolyfill(this.material.data[this.material.technique]); - this.technique = technique; + this.technique = technique; if (!technique || !technique.passes) { return; } - this.useCache(); + if (this.requestInitCache) { + this.initCache(); + + if (!this.canUpdatePreview) { + await this.updatePreview(false); + } + } else { + this.useCache(); + await this.updatePreview(true); + } if (technique.passes) { // The interface is not a regular data loop, which needs to be completely cleared and placed, but the UI-prop element is still reusable @@ -155,10 +200,6 @@ exports.methods = { for (let i = 0; i < technique.passes.length; i++) { const pass = technique.passes[i]; - // If the propertyIndex is not equal to the current pass index, then do not render - if (pass.propertyIndex !== undefined && pass.propertyIndex.value !== i) { - continue; - } // if asset is readonly if (this.asset.readonly) { @@ -169,7 +210,6 @@ exports.methods = { $container.$children[i] = document.createElement('ui-prop'); $container.$children[i].setAttribute('type', 'dump'); - $container.$children[i].setAttribute('fold', 'false'); $container.appendChild($container.$children[i]); $container.$children[i].render(pass); @@ -219,6 +259,14 @@ exports.methods = { if (Array.from($prop.$children.children).length) { $prop.after($prop.$children); } + + $prop.addEventListener('change-dump', (e) => { + if (e.target.dump.value) { + $prop.$children.removeAttribute('hidden'); + } else { + $prop.$children.setAttribute('hidden', ''); + } + }); } if (dump.value) { @@ -230,6 +278,8 @@ exports.methods = { }); } } + + this.updateInstancing(); }, updateInstancing() { @@ -260,6 +310,12 @@ exports.methods = { } }, + async updatePreview(emit) { + await Editor.Message.request('scene', 'preview-material', this.asset.uuid, this.material, { emit }); + + Editor.Message.broadcast('material-inspector:change-dump'); + }, + changeInstancing(checked) { this.technique.passes.forEach((pass) => { if (pass.childMap.USE_INSTANCING) { @@ -274,6 +330,7 @@ exports.methods = { this.$.useBatching.render(this.technique.useBatching); } }, + changeBatching(checked) { this.technique.passes.forEach((pass) => { if (pass.childMap.USE_BATCHING) { @@ -281,26 +338,55 @@ exports.methods = { } }); }, - /** - * Update the options data in technique - */ - updateTechniqueOptions() { - let techniqueOption = ''; - this.material.data.forEach((technique, index) => { - const name = technique.name ? `${index} - ${technique.name}` : index; - techniqueOption += ``; - }); - this.$.technique.innerHTML = techniqueOption; - }, - hideAllContent(hide) { - this.$.header.style = hide ? 'display:none' : ''; - this.$.section.style = hide ? 'display:none' : ''; - this.$.materialDump.style = hide ? 'display:none' : ''; - }, - async updatePreview() { - await Editor.Message.request('scene', 'preview-material', this.asset.uuid, this.material); - Editor.Message.broadcast('material-inspector:change-dump'); + initCache() { + const excludeNames = [ + 'children', + 'defines', + 'extends', + 'pipelineStates', + ]; + + const cacheData = this.cacheData; + this.technique.passes.forEach((pass, i) => { + if (pass.propertyIndex !== undefined && pass.propertyIndex.value !== i) { + return; + } + + cacheProperty(pass.value); + }); + + function cacheProperty(prop) { + for (const name in prop) { + // 这些字段是基础类型或配置性的数据,不需要变动 + if (excludeNames.includes(name)) { + continue; + } + + if (prop[name] && typeof prop[name] === 'object') { + if (!(name in cacheData)) { + const { type, value } = prop[name]; + if (type) { + if (value !== undefined) { + cacheData[name] = { type }; + if (value && typeof value === 'object') { + cacheData[name].value = JSON.parse(JSON.stringify(value)); + } else { + cacheData[name].value = value; + } + } + } + } + + if (prop[name].childMap && typeof prop[name].childMap === 'object') { + cacheProperty(prop[name].childMap); + } + } + } + } + + this.requestInitCache = false; + this.updateInstancing(); }, storeCache(dump) { @@ -343,10 +429,29 @@ exports.methods = { } } } + }, - // Update the extracted useInstancing and useBatching - this.updateInstancing(); - this.updatePreview(); + async setDirtyData() { + if (this.canUpdatePreview) { + await this.updatePreview(true); + } + + this.dirtyData.realtime = JSON.stringify({ + effect: this.material.effect, + technique: this.material.technique, + techniqueData: this.material.data[this.material.technique], + }); + + if (!this.dirtyData.origin) { + this.dirtyData.origin = this.dirtyData.realtime; + + this.dispatch('snapshot'); + } + }, + + isDirty() { + const isDirty = this.dirtyData.origin !== this.dirtyData.realtime; + return isDirty; }, }; @@ -360,43 +465,28 @@ exports.update = async function(assetList, metaList) { this.metaList = metaList; this.asset = assetList[0]; this.meta = metaList[0]; - const notOnlyOne = assetList.length !== 1; - this.hideAllContent(notOnlyOne); - if (notOnlyOne) { - return; - } - if (!this.dirtyData) { + + if (assetList.length !== 1) { + this.$.invalid.setAttribute('active', ''); return; + } else { + this.$.invalid.removeAttribute('active'); } + if (this.dirtyData.uuid !== this.asset.uuid) { this.dirtyData.uuid = this.asset.uuid; this.dirtyData.origin = ''; + this.dirtyData.realtime = ''; this.cacheData = {}; + this.requestInitCache = true; } - // set this.material.technique + this.material = await Editor.Message.request('scene', 'query-material', this.asset.uuid); - if (this.canUpdatePreview) { - await this.updatePreview(); - } - // effect tag - this.$.technique.value = this.material.technique; - setDisabled(this.asset.readonly, this.$.technique); + await this.updateEffect(); - this.updateTechniqueOptions(); - this.setDirtyData(); - const inspector = await this.getCustomInspector(); - if (inspector) { - this.updateCustomInspector(inspector); - } else { - // optimize calculate speed when edit multiple materials in node mode - requestIdleCallback(() => { - this.updatePasses(); - }); - } + await this.updateInterface(); + await this.setDirtyData(); }; /** @@ -414,49 +504,20 @@ exports.ready = async function() { // Retain the previously modified data when switching pass this.cacheData = {}; - // The event triggered when the content of material is modified - this.$.materialDump.addEventListener('change-dump', async (event) => { - const dump = event.target.dump; - - // show its children - if (dump && dump.childMap && dump.children.length && event.target.$children) { - if (dump.value) { - event.target.$children.removeAttribute('hidden'); - } else { - event.target.$children.setAttribute('hidden', ''); - } - } - - this.setDirtyData(); - this.storeCache(dump); - this.dispatch('change'); - - await this.updatePreview(); - }); - // The event that is triggered when the effect used is modified this.$.effect.addEventListener('change', async (event) => { this.material.effect = event.target.value; this.material.data = await Editor.Message.request('scene', 'query-effect', this.material.effect); - this.updateTechniqueOptions(); - if (!this.material.data[this.material.technique]) { - this.$.technique.value = this.material.technique = 0; - } else { - this.$.technique.value = this.material.technique; - } - const inspector = await this.getCustomInspector(); - if (inspector) { - this.updateCustomInspector(inspector); - } else { - this.updatePasses(); - } - this.setDirtyData(); - this.dispatch('change'); + this.$.technique.value = this.material.technique = 0; + + await this.updateInterface(); + + this.change(); }); this.$.location.addEventListener('change', () => { - const effect = this._effects.find((_effect) => _effect.name === this.material.effect); + const effect = this.effects.find((_effect) => _effect.name === this.material.effect); if (effect) { Editor.Message.send('assets', 'twinkle', effect.uuid); } @@ -465,60 +526,43 @@ exports.ready = async function() { // Event triggered when the technique being used is changed this.$.technique.addEventListener('change', async (event) => { this.material.technique = event.target.value; - - const inspector = await this.getCustomInspector(); - if (inspector) { - this.updateCustomInspector(inspector); - } else { - this.updatePasses(); - } - this.setDirtyData(); - this.dispatch('change'); - this.updatePreview(); + await this.updateInterface(); + this.change(); }); // The event is triggered when the useInstancing is modified this.$.useInstancing.addEventListener('change-dump', (event) => { this.changeInstancing(event.target.dump.value); this.storeCache(event.target.dump); - this.setDirtyData(); - this.dispatch('change'); - this.updatePreview(); + this.change(); }); // The event is triggered when the useBatching is modified this.$.useBatching.addEventListener('change-dump', (event) => { this.changeBatching(event.target.dump.value); this.storeCache(event.target.dump); - this.setDirtyData(); - this.dispatch('change'); - this.updatePreview(); + this.change(); }); - // When the page is initialized, all effect lists are queried and then not updated again - const effectMap = await Editor.Message.request('scene', 'query-all-effects'); - this._effects = Object.keys(effectMap) - .sort() - .filter((name) => { - const effect = effectMap[name]; - return !effect.hideInEditor; - }) - .map((name) => { - const effect = effectMap[name]; - return { - name, - uuid: effect.uuid, - }; - }); - let effectOption = ''; - for (let effect of this._effects) { - effectOption += ``; - } - this.$.effect.innerHTML = effectOption; - this.$.customPanel.addEventListener('change', () => { - this.setDirtyData(); - this.dispatch('change'); - this.updatePreview(); + // The event triggered when the content of material is modified + this.$.materialDump.addEventListener('change-dump', async (event) => { + const dump = event.target.dump; + + // // show its children + // if (dump && dump.childMap && dump.children.length && event.target.$children) { + // if (dump.value) { + // event.target.$children.removeAttribute('hidden'); + // } else { + // event.target.$children.setAttribute('hidden', ''); + // } + // } + + this.storeCache(dump); + this.change(); + }); + + this.$.custom.addEventListener('change', () => { + this.change(); }); }; diff --git a/editor/inspector/assets/physics-material.js b/editor/inspector/assets/physics-material.js index a8703ff2d9..5614b8ca7d 100644 --- a/editor/inspector/assets/physics-material.js +++ b/editor/inspector/assets/physics-material.js @@ -4,28 +4,68 @@ exports.template = ` `; exports.methods = { - updateReadonly(element) { - if (this.asset.readonly) { - element.setAttribute('disabled', true); - } else { - element.removeAttribute('disabled'); - } + record() { + return JSON.stringify(this.physicsMaterial); }, + + async restore(record) { + record = JSON.parse(record); + if (!record || typeof record !== 'object') { + return false; + } + + this.physicsMaterial = record; + await this.change({ snapshot: false }); + return true; + }, + async query(uuid) { return await Editor.Message.request('scene', 'query-physics-material', uuid); }, + async apply() { this.reset(); await Editor.Message.request('scene', 'apply-physics-material', this.asset.uuid, this.physicsMaterial); }, + reset() { - this.dirtyData.origin = this.dirtyData.realtime; + /** + * reset 环节只需把 uuid 清空 + * 会重新进入 panel.update 周期,根据 uuid 为空的条件,把 this.dirtyData.origin 重新填充 + */ this.dirtyData.uuid = ''; }, - async dataChange() { - await Editor.Message.request('scene', 'change-physics-material', this.physicsMaterial); + + async change(state) { + this.physicsMaterial = await Editor.Message.request('scene', 'change-physics-material', this.physicsMaterial); + + this.updateInterface(); this.setDirtyData(); - this.dispatch('change'); + this.dispatch('change', state); + }, + + updateInterface() { + for (const key in this.physicsMaterial) { + const dump = this.physicsMaterial[key]; + + if (!dump.visible) { + continue; + } + + // reuse + if (!this.$[key]) { + this.$[key] = document.createElement('ui-prop'); + this.$[key].setAttribute('type', 'dump'); + this.$[key].addEventListener('change-dump', this.change.bind(this)); + this.$.container.appendChild(this.$[key]); + } + + if (this.asset.readonly) { + dump.readonly = true; + } + + this.$[key].render(dump); + } }, /** @@ -36,6 +76,8 @@ exports.methods = { if (!this.dirtyData.origin) { this.dirtyData.origin = this.dirtyData.realtime; + + this.dispatch('snapshot'); } }, @@ -64,7 +106,7 @@ exports.update = async function(assetList, metaList) { this.meta = metaList[0]; if (assetList.length !== 1) { - this.$.container.innerText = ''; + this.$.container.innerText = Editor.I18n.t('ENGINE.assets.multipleWarning'); return; } @@ -75,25 +117,7 @@ exports.update = async function(assetList, metaList) { this.physicsMaterial = await this.query(this.asset.uuid); - for (const key in this.physicsMaterial) { - const dump = this.physicsMaterial[key]; - - if (!dump.visible) { - continue; - } - - // reuse - if (!this.$[key]) { - this.$[key] = document.createElement('ui-prop'); - this.$[key].setAttribute('type', 'dump'); - this.$[key].addEventListener('change-dump', this.dataChange.bind(this)); - } - - this.$.container.appendChild(this.$[key]); - this.updateReadonly(this.$[key]); - this.$[key].render(dump); - } - + this.updateInterface(); this.setDirtyData(); }; diff --git a/editor/inspector/assets/render-pipeline.js b/editor/inspector/assets/render-pipeline.js index 543541efcf..566e939e87 100644 --- a/editor/inspector/assets/render-pipeline.js +++ b/editor/inspector/assets/render-pipeline.js @@ -1,184 +1,23 @@ -const { setDisabled, loopSetAssetDumpDataReadonly } = require('../utils/prop'); - exports.template = ` -
-
- - Pipelines - - -
-
-
-
+ + `; -exports.$ = { - container: '.asset-render-pipeline', - header: '.header', - content: '.content', - pipelinesSelect: '.pipelines-select', -}; - -exports.style = ` - .asset-render-pipeline > .header { - padding-bottom: 8px; - margin-bottom: 4px; - border-bottom: 1px var(--color-normal-border) dashed; - } -`; - -const Elements = { - pipelines: { - ready() { - const panel = this; - - panel.$.pipelinesSelect.addEventListener('change', async (event) => { - panel.$.content.removeAttribute('hidden'); - - panel.pipelineIndex = event.target.value; - - panel.pipeline = await Editor.Message.request('scene', 'select-render-pipeline', panel.pipelines[panel.pipelineIndex].name); - Elements.pipeline.update.call(panel); - - panel.setDirtyData(); - panel.dispatch('change'); - }); - }, - async update() { - const panel = this; - - let optionsHtml = ''; - panel.pipelines.forEach((pipeline, index) => { - optionsHtml += ``; - }); - panel.$.pipelinesSelect.innerHTML = optionsHtml; - - panel.$.pipelinesSelect.value = panel.pipelines.findIndex((one) => one.name === panel.pipeline.name); - - setDisabled(panel.asset.readonly, panel.$.pipelinesSelect); - }, - }, - pipeline: { - async update() { - const panel = this; - - const $content = panel.$.content; - const oldPropList = Object.keys(panel.$propList); - const newPropList = []; - - if (panel.$.pipelinesSelect.value === '-1') { - $content.setAttribute('hidden', ''); - return; - } else { - $content.removeAttribute('hidden'); - } - - for (const key in panel.pipeline.value) { - const dump = panel.pipeline.value[key]; - if (panel.asset.readonly) { - loopSetAssetDumpDataReadonly(dump); - } - - if (!dump.visible) { - continue; - } - - const id = `${dump.type}:${dump.name}`; - newPropList.push(id); - - let $prop = this.$propList[id]; - if (!$prop) { - $prop = document.createElement('ui-prop'); - $prop.setAttribute('type', 'dump'); - $prop.addEventListener('change-dump', this.dataChange.bind(this)); - - $content.appendChild($prop); - panel.$propList[id] = $prop; - } - - $prop.render(dump); - } - - for (const id of oldPropList) { - if (!newPropList.includes(id)) { - const $prop = panel.$propList[id]; - if ($prop && $prop.parentElement) { - $prop.parentElement.removeChild($prop); - } - } - } - }, - }, -}; - -exports.update = async function(assetList, metaList) { - this.assetList = assetList; - this.metaList = metaList; - this.meta = this.metaList[0]; - this.asset = this.assetList[0]; - - if (assetList.length !== 1) { - this.$.container.setAttribute('hidden', ''); - return; - } else { - this.$.container.removeAttribute('hidden'); - } - - if (this.dirtyData.uuid !== this.asset.uuid) { - this.dirtyData.uuid = this.asset.uuid; - this.dirtyData.origin = ''; - } - - this.pipeline = await this.query(this.asset.uuid); - this.pipelines = await Editor.Message.request('scene', 'query-all-render-pipelines'); - - for (const prop in Elements) { - const element = Elements[prop]; - if (element.update) { - await element.update.call(this); - } - } - - this.setDirtyData(); - await this.preview(); -}; - -exports.ready = function() { - // Used to determine whether the material has been modified in isDirty() - this.dirtyData = { - uuid: '', - origin: '', - realtime: '', - }; - - this.$propList = {}; - - for (const prop in Elements) { - const element = Elements[prop]; - if (element.ready) { - element.ready.call(this); - } - } -}; - -exports.close = function() { - // Used to determine whether the material has been modified in isDirty() - this.dirtyData = { - uuid: '', - origin: '', - realtime: '', - }; - - this.$propList = {}; -}; - exports.methods = { - async preview() { - if (!this.pipeline) { - return; + record() { + return JSON.stringify(this.pipeline); + }, + + async restore(record) { + record = JSON.parse(record); + if (!record || typeof record !== 'object') { + return false; } - await Editor.Message.request('scene', 'preview-render-pipeline', this.asset.uuid, this.pipeline); + + this.pipeline = record; + await this.change({ snapshot: false }); + + return true; }, async query(uuid) { @@ -188,22 +27,41 @@ exports.methods = { async apply() { this.reset(); await Editor.Message.request('scene', 'apply-render-pipeline', this.asset.uuid, this.pipeline); - await this.preview(); }, + reset() { - this.dirtyData.origin = this.dirtyData.realtime; + /** + * reset 环节只需把 uuid 清空 + * 会重新进入 panel.update 周期,根据 uuid 为空的条件,把 this.dirtyData.origin 重新填充 + */ this.dirtyData.uuid = ''; }, - async dataChange() { + async change(state) { this.pipeline = await Editor.Message.request('scene', 'change-render-pipeline', this.pipeline); - Elements.pipeline.update.call(this); - + this.updateInterface(); this.setDirtyData(); - this.dispatch('change'); + this.dispatch('change', state); + }, - await this.preview(); + updateInterface() { + this.updateReadonly(this.pipeline); + this.$.container.render(this.pipeline); + }, + + updateReadonly(obj) { + if (this.asset.readonly) { + if (obj && 'readonly' in obj && 'value' in obj) { + obj.readonly = true; + + if (typeof obj.value === 'object') { + for (const key in obj.value) { + this.updateReadonly(obj.value[key]); + } + } + } + } }, /** @@ -214,6 +72,8 @@ exports.methods = { if (!this.dirtyData.origin) { this.dirtyData.origin = this.dirtyData.realtime; + + this.dispatch('snapshot'); } }, @@ -222,3 +82,50 @@ exports.methods = { return isDirty; }, }; + +exports.$ = { + container: '.asset-render-pipeline', +}; + +exports.ready = function() { + this.$.container.addEventListener('change-dump', this.change.bind(this)); + + // Used to determine whether the material has been modified in isDirty() + this.dirtyData = { + uuid: '', + origin: '', + realtime: '', + }; +}; + +exports.update = async function(assetList, metaList) { + this.assetList = assetList; + this.metaList = metaList; + this.meta = this.metaList[0]; + this.asset = this.assetList[0]; + + if (assetList.length !== 1) { + this.$.container.innerText = Editor.I18n.t('ENGINE.assets.multipleWarning'); + return; + } + + if (this.dirtyData.uuid !== this.asset.uuid) { + this.dirtyData.uuid = this.asset.uuid; + this.dirtyData.origin = ''; + } + + this.pipeline = await this.query(this.asset.uuid); + + this.updateInterface(); + this.setDirtyData(); +}; + +exports.close = function() { + // Used to determine whether the material has been modified in isDirty() + this.dirtyData = { + uuid: '', + origin: '', + realtime: '', + }; +}; + diff --git a/editor/inspector/assets/sprite-frame.js b/editor/inspector/assets/sprite-frame.js index 9520275035..81b7bbec81 100644 --- a/editor/inspector/assets/sprite-frame.js +++ b/editor/inspector/assets/sprite-frame.js @@ -43,6 +43,27 @@ exports.template = ` + + +
+ + + + + + + + + + + + + + + + +
+
@@ -69,12 +90,12 @@ exports.template = ` `; exports.style = ` - .asset-sprite-frame { + .asset-sprite-frame { display: flex; flex: 1; flex-direction: column; } - .asset-sprite-frame > .content { + .asset-sprite-frame > .content { padding-bottom: 15px; flex: 1; } @@ -85,6 +106,13 @@ exports.style = ` text-align: center; margin-top: 10px; } + .asset-sprite-frame .mesh { + padding-top: 4px; + padding-left: 10px; + } + .asset-sprite-frame .mesh > ui-prop { + margin: 4px 0; + } `; exports.$ = { @@ -104,6 +132,10 @@ exports.$ = { borderLeftInput: '.borderLeft-input', borderRightInput: '.borderRight-input', editButton: '.edit-button', + pixelsToUnitInput: '.pixelsToUnit-input', + pivotXInput: '.pivotX-input', + pivotYInput: '.pivotY-input', + meshTypeSelect: '.meshType-select', }; /** @@ -452,6 +484,95 @@ const Elements = { Editor.Message.removeBroadcastListener('sprite-editor:changed', panel.updateFromBroadcastBind); }, }, + pixelsToUnit: { + ready() { + const panel = this; + + panel.$.pixelsToUnitInput.addEventListener('change', (event) => { + panel.metaList.forEach((meta) => { + meta.userData.pixelsToUnit = event.target.value; + }); + panel.dispatch('change'); + Editor.Message.send('inspector', 'sprite-keys', panel.meta); + }); + }, + update() { + const panel = this; + + panel.$.pixelsToUnitInput.value = panel.meta.userData.pixelsToUnit; + + panel.updateInvalid(panel.$.pixelsToUnitInput, 'pixelsToUnit'); + panel.updateReadonly(panel.$.pixelsToUnitInput); + }, + }, + pivotX: { + ready() { + const panel = this; + + panel.$.pivotXInput.addEventListener('change', (event) => { + panel.metaList.forEach((meta) => { + meta.userData.pivotX = event.target.value; + }); + panel.dispatch('change'); + }); + }, + update() { + const panel = this; + + panel.$.pivotXInput.value = panel.meta.userData.pivotX; + + panel.updateInvalid(panel.$.pivotXInput, 'pivotX'); + panel.updateReadonly(panel.$.pivotXInput); + }, + }, + pivotY: { + ready() { + const panel = this; + + panel.$.pivotYInput.addEventListener('change', (event) => { + panel.metaList.forEach((meta) => { + meta.userData.pivotY = event.target.value; + }); + panel.dispatch('change'); + }); + }, + update() { + const panel = this; + + panel.$.pivotYInput.value = panel.meta.userData.pivotY; + + panel.updateInvalid(panel.$.pivotYInput, 'pivotY'); + panel.updateReadonly(panel.$.pivotYInput); + }, + }, + meshType: { + ready() { + const panel = this; + + panel.$.meshTypeSelect.addEventListener('change', (event) => { + panel.metaList.forEach((meta) => { + meta.userData.meshType = Number(event.target.value); + }); + panel.dispatch('change'); + }); + }, + update() { + const panel = this; + + let optionsHtml = ''; + // const types = ['rect', 'polygon']; // polygon is not ready + const types = ['rect']; + types.forEach((name, index) => { + optionsHtml += ``; + }); + panel.$.meshTypeSelect.innerHTML = optionsHtml; + + panel.$.meshTypeSelect.value = panel.meta.userData.meshType; + + panel.updateInvalid(panel.$.meshTypeSelect, 'meshType'); + panel.updateReadonly(panel.$.meshTypeSelect); + }, + }, }; /** diff --git a/editor/inspector/assets/text.js b/editor/inspector/assets/text.js index f97117f7f3..9250b4be93 100644 --- a/editor/inspector/assets/text.js +++ b/editor/inspector/assets/text.js @@ -1,5 +1,6 @@ const { createReadStream } = require('fs'); const ReadLine = require('readline'); +const { extname } = require('path'); const MAX_LINES = 400; const MAX_LENGTH = 20000; @@ -7,11 +8,13 @@ const MAX_LENGTH = 20000; exports.template = `
+
`; exports.$ = { container: '.asset-text', code: 'ui-code', + markdown: 'ui-markdown', }; exports.style = ` @@ -26,6 +29,29 @@ exports.style = ` } `; +exports.methods = { + renderContent(content, type = '.txt') { + const panel = this; + const domMap = { + '.txt': panel.$.code, + '.md': panel.$.markdown, + '.markdown': panel.$.markdown, + }; + + Object.values(domMap).forEach(dom => { + if (dom) { + dom.style.display = 'none'; + dom.textContent = ''; + } + }); + + if (domMap[type]) { + domMap[type].textContent = content; + domMap[type].style.display = 'block'; + } + }, +}; + exports.update = function(assetList, metaList) { this.assetList = assetList; this.metaList = metaList; @@ -80,8 +106,6 @@ exports.update = function(assetList, metaList) { throw err; } - if (this.$.code) { - this.$.code.textContent = text; - } + this.renderContent(text, extname(this.asset.name)); }); }; diff --git a/editor/inspector/assets/video-clip.js b/editor/inspector/assets/video-clip.js index 075faae8c5..e4f4f5654e 100644 --- a/editor/inspector/assets/video-clip.js +++ b/editor/inspector/assets/video-clip.js @@ -30,7 +30,7 @@ exports.update = function(assetList, metaList) { html += `
${asset.name}
`; } - html += ``; + html += ``; }); this.$.constainer.innerHTML = html; diff --git a/editor/inspector/components/class.js b/editor/inspector/components/class.js index d1d1694c81..129dc31ba2 100644 --- a/editor/inspector/components/class.js +++ b/editor/inspector/components/class.js @@ -68,11 +68,7 @@ exports.methods = { }, appendChildByDisplayOrder(parent, newChild, displayOrder = 0) { const children = Array.from(parent.children); - const child = children.find((child) => { - if (child.dump && child.dump.displayOrder > displayOrder) { - return child; - } - }); + const child = children.find(child => child.dump && child.displayOrder > displayOrder); if (child) { child.before(newChild); } else { @@ -98,11 +94,13 @@ async function update(dump) { const $section = $panel.$.section; const oldPropList = Object.keys($panel.$propList); const newPropList = []; - for (const key in dump.value) { + + Object.keys(dump.value).forEach((key, index) => { const info = dump.value[key]; if (!info.visible) { - continue; + return; } + if (dump.values) { info.values = dump.values.map((value) => { return value[key].value; @@ -115,31 +113,40 @@ async function update(dump) { $prop = document.createElement('ui-prop'); $prop.setAttribute('type', 'dump'); $panel.$propList[id] = $prop; + + const _displayOrder = info.group?.displayOrder || info.displayOrder; + $prop.displayOrder = _displayOrder === undefined ? index : Number(_displayOrder); + if (info.group && dump.groups) { - const key = info.group.id || 'default'; - const name = info.group.name; - if (!$panel.$groups[key] && dump.groups[key]) { - if (dump.groups[key].style === 'tab') { - $panel.$groups[key] = $panel.createTabGroup(dump.groups[key]); + const { id = 'default', name } = info.group; + if (!$panel.$groups[id] && dump.groups[id]) { + if (dump.groups[id].style === 'tab') { + $panel.$groups[id] = $panel.createTabGroup(dump.groups[id]); } } - if ($panel.$groups[key]) { - if (!$panel.$groups[key].isConnected) { - $panel.appendChildByDisplayOrder($section, $panel.$groups[key], dump.groups[key].displayOrder); + if ($panel.$groups[id]) { + if (!$panel.$groups[id].isConnected) { + $panel.appendChildByDisplayOrder($section, $panel.$groups[id], dump.groups[id].displayOrder); } - if (dump.groups[key].style === 'tab') { - $panel.appendToTabGroup($panel.$groups[key], name); + if (dump.groups[id].style === 'tab') { + $panel.appendToTabGroup($panel.$groups[id], name); } } - $panel.appendChildByDisplayOrder($panel.$groups[key].tabs[name], $prop, info.displayOrder); + $panel.appendChildByDisplayOrder($panel.$groups[id].tabs[name], $prop, $prop.displayOrder); } else { - $panel.appendChildByDisplayOrder($section, $prop, info.displayOrder); + $panel.appendChildByDisplayOrder($section, $prop, $prop.displayOrder); } } else if (!$prop.isConnected || !$prop.parentElement) { - $panel.appendChildByDisplayOrder($section, $prop, info.displayOrder); + if (info.group && dump.groups) { + const { id = 'default', name } = info.group; + $panel.appendChildByDisplayOrder($panel.$groups[id].tabs[name], $prop, $prop.displayOrder); + } else { + $panel.appendChildByDisplayOrder($section, $prop, $prop.displayOrder); + } } $prop.render(info); - } + }); + for (const id of oldPropList) { if (!newPropList.includes(id)) { const $prop = $panel.$propList[id]; diff --git a/editor/inspector/components/label.js b/editor/inspector/components/label.js index 36b99db4b1..a5f04ced3e 100644 --- a/editor/inspector/components/label.js +++ b/editor/inspector/components/label.js @@ -72,19 +72,15 @@ exports.ready = function() { for (let index = 0; index < dump.enumList.length; index++) { const element = dump.enumList[index]; - const image = document.createElement('ui-image'); + const image = document.createElement('ui-icon'); const button = document.createElement('ui-button'); const iconName = element.name.toLocaleLowerCase(); if (iconName === 'center') { - image.setAttribute('value', `packages://scene/static/icons/align-h-${iconName}.png`); + image.setAttribute('value', `align-h-${iconName}`); } else { - image.setAttribute('value', `packages://scene/static/icons/align-${iconName}.png`); + image.setAttribute('value', `align-${iconName}`); } - image.style.height = '20px'; - image.style.width = '22px'; - image.style.verticalAlign = 'middle'; - image.setAttribute('fill', true); - setTooltip(image, dump); + setTooltip(image, { tooltip: `${dump.tooltip}_${iconName}` }); image.setAttribute('readonly', true); button.appendChild(image); content.appendChild(button); @@ -123,20 +119,15 @@ exports.ready = function() { for (let index = 0; index < dump.enumList.length; index++) { const element = dump.enumList[index]; - const image = document.createElement('ui-image'); + const image = document.createElement('ui-icon'); const button = document.createElement('ui-button'); const iconName = element.name.toLocaleLowerCase(); if (iconName === 'center') { - image.setAttribute('value', `packages://scene/static/icons/align-v-${iconName}.png`); + image.setAttribute('value', `align-v-${iconName}`); } else { - image.setAttribute('value', `packages://scene/static/icons/align-${iconName}.png`); + image.setAttribute('value', `align-${iconName}`); } - image.style.height = '20px'; - image.style.width = '22px'; - image.style.verticalAlign = 'middle'; - image.setAttribute('fill', true); - image.setAttribute('tooltip', dump.tooltip); - image.setAttribute('readonly', true); + setTooltip(image, { tooltip: `${dump.tooltip}_${iconName}` }); button.appendChild(image); content.appendChild(button); } diff --git a/editor/inspector/components/particle-system-2d.js b/editor/inspector/components/particle-system-2d.js index 3912c46630..2255796283 100644 --- a/editor/inspector/components/particle-system-2d.js +++ b/editor/inspector/components/particle-system-2d.js @@ -1,4 +1,6 @@ const { template, $, update } = require('./base'); +// 排列时,相邻元素的间隔间距 +const MARGIN = '4PX'; exports.template = template; exports.$ = $; @@ -36,6 +38,7 @@ exports.ready = function() { const $checkbox = element.querySelector('ui-checkbox[slot="content"]'); const $sync = document.createElement('ui-button'); + $sync.setAttribute('style', `margin-right: ${MARGIN}`); $sync.setAttribute('slot', 'content'); $sync.setAttribute('class', 'blue'); $sync.setAttribute('tooltip', 'i18n:ENGINE.components.particle_system_2d.sync_tips'); @@ -161,7 +164,7 @@ exports.ready = function() { $right.setAttribute('no-label', ''); $right.setAttribute('slot', 'content'); - $right.setAttribute('style', 'margin: 0'); + $right.setAttribute('style', `margin-left: ${MARGIN}`); $left.appendChild($right); }); diff --git a/editor/inspector/components/particle-system.js b/editor/inspector/components/particle-system.js index ac84812a22..5c64a73fd9 100644 --- a/editor/inspector/components/particle-system.js +++ b/editor/inspector/components/particle-system.js @@ -20,23 +20,22 @@ exports.template = /* html*/` - - + + - - + + - - - + + -
-
+
+ @@ -47,11 +46,37 @@ exports.template = /* html*/` - Show Bounds + - + Regenerate bounding box + + + + + + + +
+ +
+
+ + + + + + + + + + + + + + +
@@ -59,110 +84,75 @@ exports.template = /* html*/` - + - - - - - - - - - - - - - - - - - - - + + + + + + + + + - - - - - - - - - + - - - - - - - - + + + + - - + - - - - + + + - - - - - + + + + - - - - + + + + - + @@ -178,11 +168,11 @@ exports.template = /* html*/` -
+ `; const excludeList = [ 'duration', 'capacity', 'loop', 'playOnAwake', 'prewarm', @@ -195,7 +185,7 @@ const excludeList = [ 'velocityOvertimeModule', 'forceOvertimeModule', 'sizeOvertimeModule', 'rotationOvertimeModule', 'colorOverLifetimeModule', 'textureAnimationModule', 'trailModule', 'renderer', 'renderCulling', 'limitVelocityOvertimeModule', 'cullingMode', - 'aabbHalfX', 'aabbHalfY', 'aabbHalfZ', + 'aabbHalfX', 'aabbHalfY', 'aabbHalfZ', 'noiseModule', ]; exports.methods = { @@ -291,15 +281,6 @@ exports.methods = { return emitEnum; }, - checkEnumInSubset(enumValue, ...subset) { - const optName = this.getEnumName(enumValue, enumValue.value); - for (const name of subset) { - if (name === optName) { - return true; - } - } - return false; - }, }; const uiElements = { @@ -331,7 +312,13 @@ const uiElements = { }, update() { const isInvalid = propUtils.isMultipleInvalid(this.dump.value.renderCulling); - this.$.resetBounds.setAttribute('disabled', isInvalid || !this.dump.value.renderCulling.value); + if (isInvalid || !this.dump.value.renderCulling.value) { + this.$.resetBounds.setAttribute('disabled', true); + } else { + if (this.$.resetBounds.hasAttribute('disabled')) { + this.$.resetBounds.removeAttribute('disabled'); + } + } }, }, uiSections: { @@ -444,7 +431,11 @@ const uiElements = { }); }, async update() { - this.$.showBounds.disabled = !this.dump.value.renderCulling.value; + if (!this.dump.value.renderCulling.value) { + this.$.showBounds.setAttribute('disabled', true); + } else if (this.$.showBounds.hasAttribute('disabled')) { + this.$.showBounds.removeAttribute('disabled'); + } const componentUUIDs = this.dump.value.uuid.values || [this.dump.value.uuid.value]; const values = await Promise.all( componentUUIDs.map( @@ -514,8 +505,8 @@ const uiElements = { }); }, /** - * - * @param {string} [eventInstigatorKey] + * + * @param {string} [eventInstigatorKey] */ update(eventInstigatorKey) { this.$.baseProps.forEach((element) => { @@ -528,35 +519,28 @@ const uiElements = { const showflag = element.getAttribute('showflag'); const disableflag = element.getAttribute('disableflag'); if (typeof showflag === 'string') { - if (showflag.startsWith('checkEnumInSubset')) { - const params = showflag.split(','); - const enumValue = this.getObjectByKey(this.dump.value, params[1]); - const subset = params.slice(2); - isShow = isShow && this.checkEnumInSubset(enumValue, ...subset); - } else { - // only update the elements relate to eventInstigator - if (eventInstigatorKey) { - if (showflag.startsWith(`!${eventInstigatorKey}`)) { - const dump = this.getObjectByKey(this.dump.value, showflag.slice(1)); - const isInvalid = propUtils.isMultipleInvalid(dump); - isShow = isShow && !isInvalid && !dump.value; - } else if (showflag.startsWith(eventInstigatorKey)) { - const dump = this.getObjectByKey(this.dump.value, showflag); - const isInvalid = propUtils.isMultipleInvalid(dump); - isShow = isShow && !isInvalid && dump.value; - } else { - return; - } + // only update the elements relate to eventInstigator + if (eventInstigatorKey) { + if (showflag.startsWith(`!${eventInstigatorKey}`)) { + const dump = this.getObjectByKey(this.dump.value, showflag.slice(1)); + const isInvalid = propUtils.isMultipleInvalid(dump); + isShow = isShow && !isInvalid && !dump.value; + } else if (showflag.startsWith(eventInstigatorKey)) { + const dump = this.getObjectByKey(this.dump.value, showflag); + const isInvalid = propUtils.isMultipleInvalid(dump); + isShow = isShow && !isInvalid && dump.value; } else { - if (showflag.startsWith('!')) { - const dump = this.getObjectByKey(this.dump.value, showflag.slice(1)); - const isInvalid = propUtils.isMultipleInvalid(dump); - isShow = isShow && !isInvalid && !dump.value; - } else { - const dump = this.getObjectByKey(this.dump.value, showflag); - const isInvalid = propUtils.isMultipleInvalid(dump); - isShow = isShow && !isInvalid && dump.value; - } + return; + } + } else { + if (showflag.startsWith('!')) { + const dump = this.getObjectByKey(this.dump.value, showflag.slice(1)); + const isInvalid = propUtils.isMultipleInvalid(dump); + isShow = isShow && !isInvalid && !dump.value; + } else { + const dump = this.getObjectByKey(this.dump.value, showflag); + const isInvalid = propUtils.isMultipleInvalid(dump); + isShow = isShow && !isInvalid && dump.value; } } } else if (typeof disableflag === 'string') { @@ -568,12 +552,20 @@ const uiElements = { } if (disableflag.startsWith(`!${eventInstigatorKey}`)) { const dump = this.getObjectByKey(this.dump.value, disableflag.slice(1)); - const isInvalid = propUtils.isMultipleInvalid(dump); - contentSlot.disabled = isInvalid || !dump.value; + const isInvalid = propUtils.isMultipleInvalid(dump) || !dump.value; + if (isInvalid) { + contentSlot.setAttribute('disabled', true); + } else if (contentSlot.hasAttribute('disabled')) { + contentSlot.removeAttribute('disabled'); + } } else if (disableflag.startsWith(eventInstigatorKey)) { const dump = this.getObjectByKey(this.dump.value, disableflag); - const isInvalid = propUtils.isMultipleInvalid(dump); - contentSlot.disabled = isInvalid || !!dump.value; + const isInvalid = propUtils.isMultipleInvalid(dump) || !!dump.value; + if (isInvalid) { + contentSlot.setAttribute('disabled', true); + } else if (contentSlot.hasAttribute('disabled')) { + contentSlot.removeAttribute('disabled'); + } } else { return; } @@ -602,7 +594,11 @@ const uiElements = { if (typeof disableflag === 'string') { const contentSlot = element.querySelector('[slot=content]'); if (contentSlot) { - contentSlot.disabled = isDisable; + if (isDisable) { + contentSlot.setAttribute('disabled', true); + } else if (contentSlot.hasAttribute('disabled')) { + contentSlot.removeAttribute('disabled'); + } } } } else { @@ -640,14 +636,40 @@ const uiElements = { }); }, }, + noisePreview: { + async update() { + if (!this.dump?.value?.uuid?.values && !this.dump?.value?.uuid?.value) { return; } + let uuid = this.dump.value.uuid.values ? this.dump.value.uuid.values[0] : this.dump.value.uuid.value; + if (!uuid) { return; } + let data = await Editor.Message.request('scene', 'execute-component-method', { + uuid, + name: 'getNoisePreview', + args: [100, 100], + }); + if (data.length === 0) { return; } + + data = data.reduce((result, item) => { + const value = item * 255; + const rgba = [value, value, value, 255]; + result.push(...rgba); + return result; + }, []); + + const imageData = new ImageData(new Uint8ClampedArray(data), 100, 100); + const context = this.$.noisePreview.getContext('2d'); + context.putImageData(imageData, 0, 0); + }, + }, }; exports.$ = { customProps: '#customProps', emitFromSelect: '#emitFromSelect', showBounds: '#showBounds', resetBounds: '#resetBounds', + noisePreview: '#noisePreview', + }; -exports.ready = function() { +exports.ready = function () { for (const key in uiElements) { const element = uiElements[key]; if (typeof element.ready === 'function') { @@ -655,7 +677,7 @@ exports.ready = function() { } } }; -exports.update = function(dump) { +exports.update = function (dump) { this.dump = dump; for (const key in uiElements) { const element = uiElements[key]; diff --git a/editor/inspector/components/widget.js b/editor/inspector/components/widget.js index ed66f8e46d..f8cf67e97f 100644 --- a/editor/inspector/components/widget.js +++ b/editor/inspector/components/widget.js @@ -124,7 +124,7 @@ exports.template = ` z-index: 10; background-color: var(--color-normal-fill); border: 1px solid var(--color-normal-fill-important); - border-radius: 4px; + border-radius: 2px; box-sizing: border-box; } @@ -286,8 +286,8 @@ exports.template = ` } .widget-component .button-group { - border: 1px solid var(--color-normal-border); - border-radius: 3px; + border: 1px solid var(--color-default-border-important); + border-radius: 2px; overflow: hidden; display: flex; flex: 1; @@ -299,7 +299,7 @@ exports.template = ` padding: 0 5px; text-align: center; font-size: 11px; - border-right: 1px solid var(--color-normal-border); + border-right: 1px solid var(--color-default-border-important); cursor: pointer; } @@ -341,14 +341,14 @@ exports.template = ` position: absolute; width: 12px; height: 4px; - background-color: var(--color-normal-border-weakest); + background-color: var(--color-normal-contrast-weakest); } .widget-component .button-group .button .icon .short { position: absolute; width: 7px; height: 4px; - background-color: var(--color-normal-border-weakest); + background-color: var(--color-normal-contrast-weakest); } .widget-component .button-group .button .left.bottom { diff --git a/editor/inspector/contributions/asset-history/history-manager-base.js b/editor/inspector/contributions/asset-history/history-manager-base.js new file mode 100644 index 0000000000..fc3da1dbfa --- /dev/null +++ b/editor/inspector/contributions/asset-history/history-manager-base.js @@ -0,0 +1,41 @@ +class HistoryManagerBase { + // 步骤控制 + undoArray = []; + redoArray = []; + + constructor() {} + + push(command) { + this.undoArray.unshift(command); + this.redoArray.length = 0; + + // 步骤数最大 100 + if (this.undoArray.length > 100) { + this.undoArray.length = 100; + } + } + async undo() { + const command = this.undoArray.shift(); + + if (command) { + await command.undo(); + this.redoArray.unshift(command); + } + } + async redo() { + const command = this.redoArray.shift(); + + if (command) { + await command.redo(); + this.undoArray.unshift(command); + } + } + rebase() { + this.undoArray.length = 0; + this.redoArray.length = 0; + } + reset() {} + snapshot() {} +} + +module.exports = HistoryManagerBase; diff --git a/editor/inspector/contributions/asset-history/index.js b/editor/inspector/contributions/asset-history/index.js new file mode 100644 index 0000000000..d34a6b2541 --- /dev/null +++ b/editor/inspector/contributions/asset-history/index.js @@ -0,0 +1,77 @@ +'use strict'; + +const HistoryManagerBase = require('./history-manager-base'); +const SnapshotCommand = require('./snapshot-command'); + +class AssetHistoryManager extends HistoryManagerBase { + lastRecord = { + uuidListStr: '', + metaListStr:'', + renderDataStr: '', + }; + + constructor() { + super(); + } + + async snapshot(panel) { + // 避免连续 change 产生大量的快照 + clearTimeout(this.timeId); + this.timeId = setTimeout(() => { + this.record(panel); + }, 200); + } + + async record(panel) { + const record = await panel.record(); + + if (this.lastRecord.uuidListStr === record.uuidListStr) { + // 数据没变化 + const metaChanged = this.lastRecord.metaListStr !== record.metaListStr; + const renderChanged = this.lastRecord.renderDataStr !== record.renderDataStr; + if (!metaChanged && !renderChanged) { + return; + } + + const undoData = Object.assign({}, this.lastRecord); + + Object.assign(this.lastRecord, record); + + const redoData = Object.assign({}, this.lastRecord); + + const command = new AssetHistoryCommand(undoData, redoData); + command.panel = panel; + command.manager = this; + this.push(command); + } else { + this.lastRecord = Object.assign({ + uuidListStr: '', + metaListStr:'', + renderDataStr: '', + }, record); + + this.rebase(); + } + } + + async undo() { + await super.undo(); + } + + async redo() { + await super.redo(); + } +} +class AssetHistoryCommand extends SnapshotCommand { + async execute(record) { + if (this.panel) { + const success = await this.panel.restore(record); + + if (success) { + this.manager.lastRecord = record; + } + } + } +} + +module.exports = AssetHistoryManager; diff --git a/editor/inspector/contributions/asset-history/snapshot-command.js b/editor/inspector/contributions/asset-history/snapshot-command.js new file mode 100644 index 0000000000..968da62a54 --- /dev/null +++ b/editor/inspector/contributions/asset-history/snapshot-command.js @@ -0,0 +1,23 @@ +class SnapshotCommand { + undoData; + redoData; + + panel; + manager; + + constructor(undoData, redoData) { + this.undoData = undoData; + this.redoData = redoData; + } + + async undo() { + await this.execute(this.undoData); + } + async redo() { + await this.execute(this.redoData); + } + + async execute() {} +} + +module.exports = SnapshotCommand; diff --git a/editor/inspector/contributions/asset.js b/editor/inspector/contributions/asset.js index 159009eca8..f9feae2fac 100644 --- a/editor/inspector/contributions/asset.js +++ b/editor/inspector/contributions/asset.js @@ -1,9 +1,9 @@ 'use strict'; const fs = require('fs'); const path = require('path'); +const History = require('./asset-history/index'); -const showImage = ['cc.ImageAsset', 'cc.SpriteFrame', 'cc.Texture2D']; - +const showImage = ['image', 'texture', 'sprite-frame', 'gltf-mesh']; exports.listeners = {}; exports.style = fs.readFileSync(path.join(__dirname, './asset.css'), 'utf8'); @@ -32,6 +32,7 @@ exports.template = `
`; + exports.$ = { container: '.container', header: '.header', @@ -48,6 +49,7 @@ exports.$ = { contentSection: '.content-section', contentFooter: '.content-footer', }; + const Elements = { panel: { ready() { @@ -64,6 +66,8 @@ const Elements = { }; Editor.Message.addBroadcastListener('asset-db:asset-change', panel.__assetChanged__); + + panel.history = new History(); }, async update() { const panel = this; @@ -145,6 +149,8 @@ const Elements = { const panel = this; Editor.Message.removeBroadcastListener('asset-db:asset-change', panel.__assetChanged__); + + delete panel.history; }, }, header: { @@ -221,14 +227,19 @@ const Elements = { if (panel.asset.readonly) { panel.$.name.setAttribute('tooltip', 'i18n:inspector.asset.prohibitEditInternalAsset'); panel.$.name.setAttribute('readonly', ''); - panel.$.copy.style.display = 'inline-block'; + + if (panel.asset.source) { + panel.$.copy.style.display = 'inline-block'; + } else { + panel.$.copy.style.display = 'none'; + } } else { panel.$.name.removeAttribute('tooltip'); panel.$.name.removeAttribute('readonly'); panel.$.copy.style.display = 'none'; } - const isImage = showImage.includes(panel.asset.type); + const isImage = showImage.includes(panel.asset.importer); if (isImage) { panel.$.image.value = panel.asset.uuid; @@ -292,8 +303,15 @@ const Elements = { const file = list[i]; if (!contentRender.__panels__[i]) { contentRender.__panels__[i] = document.createElement('ui-panel'); - contentRender.__panels__[i].addEventListener('change', () => { + contentRender.__panels__[i].addEventListener('change', (event) => { Elements.header.isDirty.call(panel); + + if (!event || !event.args || !event.args[0] || event.args[0].snapshot !== false) { + panel.history && panel.history.snapshot(panel); + } + }); + contentRender.__panels__[i].addEventListener('snapshot', () => { + panel.history && panel.history.snapshot(panel); }); contentRender.appendChild(contentRender.__panels__[i]); } @@ -314,7 +332,104 @@ const Elements = { }, }, }; + exports.methods = { + undo() { + const panel = this; + panel.history && panel.history.undo(); + }, + redo() { + const panel = this; + panel.history && panel.history.redo(); + }, + async record() { + const panel = this; + + const renderData = {}; + for (const renderName in panel.contentRenders) { + const { contentRender } = panel.contentRenders[renderName]; + + if (!Array.isArray(contentRender.__panels__)) { + continue; + } + + renderData[renderName] = []; + + for (let i = 0; i < contentRender.__panels__.length; i++) { + if (contentRender.__panels__[i].panelObject.record) { + const data = await contentRender.__panels__[i].callMethod('record'); + renderData[renderName].push(data); + } else { + renderData[renderName].push(null); + } + } + } + + return { + uuidListStr:JSON.stringify(panel.uuidList), + metaListStr:JSON.stringify(panel.metaList), + renderDataStr:JSON.stringify(renderData), + }; + }, + restore(record) { + const panel = this; + + try { + const { uuidListStr, metaListStr, renderDataStr } = record; + + // uuid 数据不匹配表明不是同一个编辑对象了 + if (JSON.stringify(panel.uuidList) !== uuidListStr) { + return false; + } + + // metaList 数据不一样的对 metaList 进行更新 + if (JSON.stringify(panel.metaList) !== metaListStr) { + panel.metaList = JSON.parse(metaListStr); + + for (const renderName in panel.contentRenders) { + const { contentRender } = panel.contentRenders[renderName]; + + if (!Array.isArray(contentRender.__panels__)) { + continue; + } + + for (let i = 0; i < contentRender.__panels__.length; i++) { + contentRender.__panels__[i].update(panel.assetList, panel.metaList); + } + } + } + + const renderData = JSON.parse(renderDataStr); + for (const renderName in panel.contentRenders) { + const { contentRender } = panel.contentRenders[renderName]; + + if (!Array.isArray(contentRender.__panels__)) { + continue; + } + + if (!Array.isArray(renderData[renderName])) { + continue; + } + + if (!renderData[renderName].length) { + continue; + } + + for (let i = 0; i < contentRender.__panels__.length; i++) { + if (renderData[renderName][i] && contentRender.__panels__[i].panelObject.restore) { + contentRender.__panels__[i].callMethod('restore', renderData[renderName][i]); + } + } + } + + Elements.header.isDirty.call(panel); + return true; + } catch (error) { + console.error(error); + return false; + } + }, + async isDirty() { const panel = this; @@ -437,9 +552,19 @@ exports.methods = { } }, }; + exports.update = async function update(uuidList, renderMap, dropConfig) { const panel = this; + const enginePath = path.join('editor', 'inspector', 'assets'); + Object.values(renderMap).forEach(config => { + Object.values(config).forEach(renders => { + renders.sort((a, b) => { + return b.indexOf(enginePath) - a.indexOf(enginePath); + }); + }); + }); + panel.uuidList = uuidList || []; panel.renderMap = renderMap; panel.dropConfig = dropConfig; @@ -450,7 +575,10 @@ exports.update = async function update(uuidList, renderMap, dropConfig) { await element.update.call(panel); } } + + panel.history && panel.history.snapshot(panel); }; + exports.ready = function ready() { const panel = this; diff --git a/editor/inspector/contributions/node.css b/editor/inspector/contributions/node.css index 021a1e1db5..9846d8146a 100644 --- a/editor/inspector/contributions/node.css +++ b/editor/inspector/contributions/node.css @@ -44,9 +44,11 @@ .header { display: none; margin-top: 7px; + padding-left: 4px; } -.header > .name { +.header > .name, +.component-header .name { flex: 1; } @@ -58,7 +60,7 @@ margin: 10px 0; } -:host([sub-type='scene']) > .container > .scene { +:host([type="node"][sub-type='scene']) > .container > .scene { display: block; } @@ -88,6 +90,11 @@ .section-missing .name { flex: 1; + color: var(--color-normal-contrast-emphasis); +} + +.section-missing .name span { + text-decoration: line-through; } .section-missing > section > ui-icon { @@ -117,7 +124,7 @@ } .node .layer-content > .layer-edit { - margin-left: 6px; + margin-left: 4px; } .node .node-section { @@ -134,12 +141,16 @@ .component .component-header { flex: 1; + display: flex; +} + +.component .component-header ui-drag-item { + flex: 1; } .component .component-header > .menu, .component .component-header > .link { padding: 0 5px; - float: right; transition: color 0.15s; } @@ -173,3 +184,12 @@ .section-asset:empty { display: none; } + +.section-asset > ui-panel[type="asset"] { + margin-bottom: 8px; + border-radius: 8px; +} + +.section-asset > ui-panel[type="asset"][focused] { + box-shadow: var(--color-normal-fill-emphasis) 0 0 4px; +} diff --git a/editor/inspector/contributions/node.js b/editor/inspector/contributions/node.js index 1f1b02fb57..31b0adf90e 100644 --- a/editor/inspector/contributions/node.js +++ b/editor/inspector/contributions/node.js @@ -98,6 +98,34 @@ exports.listeners = { panel.snapshotLock = false; }, + 'create-dump'(event) { + const panel = this; + + const target = event.target; + if (!target) { + return; + } + + Editor.Message.send('scene', 'snapshot'); + + const dump = event.target.dump; + + try { + for (let i = 0; i < panel.uuidList.length; i++) { + const uuid = panel.uuidList[i]; + if (i > 0) { + dump.values[i] = dump.value; + } + + Editor.Message.send('scene', 'update-property-from-null', { + uuid, + path: dump.path, + }); + } + } catch (error) { + console.error(error); + } + }, 'reset-dump'(event) { const panel = this; @@ -126,8 +154,71 @@ exports.listeners = { console.error(error); } }, + 'preview-dump'(event) { + const panel = this; + + const target = event.target; + if (!target) { + return; + } + + const dump = event.target.dump; + if (!dump || panel.isDialoging) { + return; + } + + const { method, value: assetUuid } = event.detail; + if (method === 'confirm') { + clearTimeout(panel.previewTimeId); + + try { + panel.previewTimeId = setTimeout(() => { + for (let i = 0; i < panel.uuidList.length; i++) { + const uuid = panel.uuidList[i]; + const { path, type } = dump; + let value = dump.value; + + if (dump.values) { + value = dump.values[i]; + } + + // 预览新的值 + value.uuid = assetUuid; + + Editor.Message.send('scene', 'preview-set-property', { + uuid, + path, + dump: { + type, + value, + }, + }); + } + }, 500); + } catch (error) { + console.error(error); + } + } else if (method === 'cancel') { + clearTimeout(panel.previewTimeId); + + try { + for (let i = 0; i < panel.uuidList.length; i++) { + const uuid = panel.uuidList[i]; + const { path } = dump; + + Editor.Message.send('scene', 'cancel-preview-set-property', { + uuid, + path, + }); + } + } catch (error) { + console.error(error); + } + } + }, }; -exports.template = ` + +exports.template = /* html*/`