Merge branch 'v3.6.0' into develop_merge_v3.6

This commit is contained in:
minggo
2022-07-18 10:38:14 +08:00
3327 changed files with 149922 additions and 93327 deletions
+1 -1
View File
@@ -2,7 +2,7 @@
{
"problemMatcher": [
{
"owner": "circular-reference-check",
"owner": "<Web> build",
"pattern": [
{
"regexp": "^Circular dependency: (.*)$",
@@ -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);
-17
View File
@@ -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 }}
+12 -3
View File
@@ -3,6 +3,9 @@ name: <Native> 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 <cocos-robot@cocos.com>
author: cocos-robot <cocos-robot@cocos.com>
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: |
+3 -1
View File
@@ -4,6 +4,9 @@ name: <Native> 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
+24 -6
View File
@@ -1,19 +1,37 @@
name: <Native> 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 .
+95 -34
View File
@@ -1,25 +1,42 @@
name: <Native> 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!"
+23 -3
View File
@@ -1,6 +1,15 @@
name: <Native> 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
+59 -41
View File
@@ -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
@@ -0,0 +1,45 @@
name: <Native> 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
+122 -12
View File
@@ -1,10 +1,66 @@
name: <Native> 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
-107
View File
@@ -1,107 +0,0 @@
name: <Native> 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!"
+1 -17
View File
@@ -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:
+8 -2
View File
@@ -5,11 +5,17 @@ name: <Web> 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]
+13 -16
View File
@@ -3,10 +3,16 @@ name: <Web> 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}
@@ -3,8 +3,15 @@ name: <Web> 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
+7 -1
View File
@@ -2,10 +2,16 @@ name: <Web> 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
+10 -1
View File
@@ -1,9 +1,18 @@
name: <Web> 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
+5
View File
@@ -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
+1
View File
@@ -0,0 +1 @@
14
+1
View File
@@ -21,6 +21,7 @@
"eventified",
"eventify",
"forin",
"interruptible",
"glsl",
"grayscale",
"IGFX",
+2 -1
View File
@@ -56,7 +56,8 @@
"program": "${workspaceFolder}/node_modules/jest/bin/jest.js"
},
"args": [
"${fileBasenameNoExtension}"
"--runTestsByPath",
"${relativeFileDirname}/${fileBasename}"
],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
+3
View File
@@ -18,4 +18,7 @@
"editor.codeActionsOnSave": {
"source.fixAll": true,
},
"files.associations": {
"iterator": "cpp"
},
}
-124
View File
@@ -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;
}
+2
View File
@@ -84,6 +84,8 @@ declare interface IWritableArrayLike<T> {
declare type Constructor<T = unknown> = new (...args: any[]) => T;
declare type AbstractedConstructor<T = unknown> = abstract new (...args: any[]) => T;
/**
* Alias of `Function` but suppress eslint warning.
* Please avoid using it and explicitly specify function signatures as possible.
+32 -481
View File
@@ -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
* <?xml version="1.0" encoding="UTF-8"?>
* <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
* <plist version="1.0">
* <dict>
* <key>filenames</key>
* <dict>
* <key>sounds/click.wav</key>
* <string>sounds/click.caf</string>
* <key>sounds/endgame.wav</key>
* <string>sounds/endgame.caf</string>
* <key>sounds/gem-0.wav</key>
* <string>sounds/gem-0.caf</string>
* </dict>
* <key>metadata</key>
* <dict>
* <key>version</key>
* <integer>1</integer>
* </dict>
* </dict>
* </plist>
* @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<any>;
/**
* 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<string>;
/**
*
* @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<string>;
/**
* 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<string>;
/**
* 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<string>):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<string>):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<any>, 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<std::string>&), fullPathForFilename(const char*).
* @since v2.1
* @lua NA
*/
export function getSearchResolutionsOrder ():Array<string>;
/**
* 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<string>):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;
}
}
+11
View File
@@ -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.
+4
View File
@@ -0,0 +1,4 @@
declare module 'pal/env' {
export function findCanvas (): { frame: HTMLDivElement, container: HTMLDivElement, canvas: HTMLCanvasElement };
export function loadJsFile (path: string): Promise<void>;
}
+8
View File
@@ -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);
}
/**
+21
View File
@@ -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;
}
+10
View File
@@ -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;
}
}
+54 -1
View File
@@ -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
<!-- DEPRECATED -->
@@ -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.
<!-- Rendering algorithm reserved: 15000 - 16000 -->
### 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.
+2
View File
@@ -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.
+276 -15
View File
@@ -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
}
}
}
+157
View File
@@ -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"
}
}
}
@@ -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) {
+16
View File
@@ -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;
}
+2 -2
View File
@@ -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;
},
};
-5
View File
@@ -23,11 +23,6 @@
THE SOFTWARE.
*/
/**
* @packageDocumentation
* @module ui
*/
import './utils';
export * from './graphics';
-9
View File
@@ -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);
+50 -3
View File
@@ -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) {
},
-5
View File
@@ -23,11 +23,6 @@
THE SOFTWARE.
*/
/**
* @packageDocumentation
* @module ui-assembler
*/
import { BitmapFont } from '../../assets';
import { Label } from '../../components';
import { IAssemblerManager } from '../../renderer/base';
-9
View File
@@ -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,
};
+32 -38
View File
@@ -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) {
+11 -4
View File
@@ -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());
}
}
}
}
-2
View File
@@ -23,8 +23,6 @@
THE SOFTWARE.
*/
import { maskAssembler as mask, maskEndAssembler as maskEnd } from './mask-assembler';
export {
+15 -19
View File
@@ -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;
+10 -8
View File
@@ -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;
+2 -4
View File
@@ -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;
+41 -8
View File
@@ -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;
+57 -73
View File
@@ -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;
},
+58 -17
View File
@@ -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];
+317 -200
View File
@@ -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;
-2
View File
@@ -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';
-5
View File
@@ -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';
-5
View File
@@ -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';
+1 -4
View File
@@ -1,7 +1,4 @@
/**
* @packageDocumentation
* @module asset
*/
export * from './sprite-frame';
export { SpriteAtlas } from './sprite-atlas';
-5
View File
@@ -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';
+3 -8
View File
@@ -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));
}
}
}
+287 -52
View File
@@ -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;
+3 -8
View File
@@ -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 () {
+10
View File
@@ -0,0 +1,10 @@
{
"title": {
"zh": "2D 渲染",
"en": "2D Rendering"
},
"description": {
"zh": "2D 渲染相关的组件与资源",
"en": "2D rendering related components and assets"
}
}
+10 -4
View File
@@ -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',
},
]);
+139 -54
View File
@@ -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;
-5
View File
@@ -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';
-5
View File
@@ -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';
+26 -36
View File
@@ -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();
}
}
}
+186 -93
View File
@@ -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<Material>('ui-alpha-test-material');
target.setMaterial(mat, 0);
mat = target.getMaterialInstance(0);
mat.setProperty('alphaThreshold', this._alphaThreshold);
} else {
mat = builtinResMgr.get<Material>('ui-graphics-material');
target.setMaterial(mat, 0);
target.getMaterialInstance(0);
}
const mat = builtinResMgr.get<Material>('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<Material>('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;
+5 -11
View File
@@ -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();
+23 -20
View File
@@ -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();
+104 -15
View File
@@ -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;
+16 -5
View File
@@ -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);
}
}
+3 -41
View File
@@ -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<Color> {
@@ -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();
+1 -7
View File
@@ -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;
+13 -10
View File
@@ -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');
+2 -3
View File
@@ -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';
-5
View File
@@ -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';
+247
View File
@@ -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);
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<Material>('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);
}
}
}
+2 -18
View File
@@ -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.
+55
View File
@@ -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();
@@ -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;
+24 -21
View File
@@ -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),因此它开始于节点的中心位置。<br>
* 注意: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; }
}
}
+2 -2
View File
@@ -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;
}
+124 -65
View File
@@ -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!);
-5
View File
@@ -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';
+10 -41
View File
@@ -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;
}
}
}
}
}
+5 -5
View File
@@ -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);
@@ -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';
+134 -16
View File
@@ -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;
+7
View File
@@ -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;
+9
View File
@@ -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;
+147
View File
@@ -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;
}
+342 -40
View File
@@ -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<RenderData> = null!;
const _pool: RecyclePool<RenderData> = 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<MeshRenderData> = new RecyclePool(() => new MeshRenderData(), 32);
+291
View File
@@ -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());
}
}
}
+242
View File
@@ -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);
}
}
}
+37 -6
View File
@@ -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<IFreeEntry>(() => ({
* @internal
*/
export class StaticVBChunk {
// JSB
public get ib (): Readonly<Uint16Array> {
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<number>) {
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++;
}
}
+23 -3
View File
@@ -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;
}
+46
View File
@@ -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++) {
+14 -7
View File
@@ -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;
-4
View File
@@ -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';

Some files were not shown because too many files have changed in this diff Show More