diff --git a/.github/workflows/native-compile-platforms.yml b/.github/workflows/native-compile-platforms.yml index 874e147b6d..b0760b0f8e 100644 --- a/.github/workflows/native-compile-platforms.yml +++ b/.github/workflows/native-compile-platforms.yml @@ -352,7 +352,7 @@ jobs: compile_wgpu_mac: name: "Emscripten" runs-on: macos-latest - if: contains( github.event.head_commit.message, 'WGPU_CI_ON' ) + if: contains( github.event.pull_request.title, 'WGPU_CI_ON' ) steps: - uses: actions/checkout@v2 - name: Download external libraries @@ -362,10 +362,11 @@ jobs: git clone --branch $EXT_VERSION --depth 1 https://github.com/cocos/cocos-engine-external native/external - name: Setup Emscripten run: | - git clone https://github.com/emscripten-core/emsdk.git ../emsdk - cd ../emsdk - ./emsdk install latest - ./emsdk activate latest + NATIVE_ROOT=$GITHUB_WORKSPACE/native + git clone https://github.com/emscripten-core/emsdk.git NATIVE_ROOT/../../emsdk + cd NATIVE_ROOT/../../emsdk + ./emsdk install 3.1.17 + ./emsdk activate 3.1.17 source ./emsdk_env.sh emcc -v - name: Compile @@ -374,6 +375,6 @@ jobs: run: | 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 + $NATIVE_ROOT/../../emsdk/upstream/emscripten/emcmake cmake . + $NATIVE_ROOT/../../emsdk/upstream/emscripten/emmake make echo "Compile WGPU by ems on MacOS Done!" diff --git a/.github/workflows/native-linter-android.yml b/.github/workflows/native-linter-android.yml index 2e92a0ea6c..58403783ca 100644 --- a/.github/workflows/native-linter-android.yml +++ b/.github/workflows/native-linter-android.yml @@ -63,6 +63,9 @@ jobs: - exclude: 'native/cocos/bindings/manual/jsb_conversions.*' - exclude: 'native/cocos/bindings/jswrapper/v8/debugger/**' - exclude: 'native/cocos/audio/android/audio_utils/**' + - exclude: 'native/cocos/audio/android/AudioMixer.cpp' + - exclude: 'native/cocos/audio/android/AudioResampler.cpp' + - exclude: 'native/cocos/audio/common/utils/**' allChanges: - added|modified|deleted: '**' skipedDebug: diff --git a/.github/workflows/native-unit-test.yml b/.github/workflows/native-unit-test.yml index 19baefe516..1adec78f39 100644 --- a/.github/workflows/native-unit-test.yml +++ b/.github/workflows/native-unit-test.yml @@ -1,4 +1,4 @@ -name: Run Tests +name: Run Unit Tests on: pull_request: diff --git a/@types/editor-extends.d.ts b/@types/editor-extends.d.ts index e38f7cfee7..174adb210f 100644 --- a/@types/editor-extends.d.ts +++ b/@types/editor-extends.d.ts @@ -33,6 +33,10 @@ interface EditorExtendsNode { getNodes(): {[uuid: string]: any}; } +interface EditorExtendsPrefabUtils { + addPrefabInstance(node: Node); +} + interface EditorExtendsComponent { addMenu(component: Function, path: string, priority?: number); removeMenu(component: Function); @@ -65,12 +69,12 @@ declare namespace EditorExtends { const Component: EditorExtendsComponent; const Asset: EditorExtendsAsset; const UuidUtils: EditorExtendsUuid; - + const PrefabUtils:EditorExtendsPrefabUtils; const MissingReporter: { classInstance: any; class: any; object: any; - } + }; const serialize: any; diff --git a/EngineErrorMap.md b/EngineErrorMap.md index c9f1ff2518..36395a2801 100644 --- a/EngineErrorMap.md +++ b/EngineErrorMap.md @@ -2471,6 +2471,10 @@ cc.ParticleSystem: shouldn't be initialized repetitively, otherwise there will b cc.ParticleSystem: change material failed, please use proper particle material +### 6036 + +cc.ParticleSystem: life time should bigger than 1 or buffer will be insufficient + ### 6100 @@ -3294,4 +3298,8 @@ The native folder may be generated from older versions, please refer https://doc ### 16101 -The effect('%s') you are looking for does not exist, please confirm the effect name in the editor. NOTE: Since 3.6, the name of the built-in effect has been changed to its name in the editor, please check it out. More information please refer to https://docs.cocos.com/creator/manual/en/shader/effect-inspector.html \ No newline at end of file +The effect('%s') you are looking for does not exist, please confirm the effect name in the editor. NOTE: Since 3.6, the name of the built-in effect has been changed to its name in the editor, please check it out. More information please refer to https://docs.cocos.com/creator/manual/en/shader/effect-inspector.html + +### 16201 + +The asset replacing failed, can not found override asset('%s') for '%s' \ No newline at end of file diff --git a/README.md b/README.md index 16bd096d94..694ce7f32e 100644 --- a/README.md +++ b/README.md @@ -29,28 +29,43 @@ # Engine for Cocos Creator -![image](https://user-images.githubusercontent.com/1503156/111035862-53548000-8457-11eb-8e8b-52d854caf627.png) +**Cocos Creator is the new generation of game development tool in Cocos family, it brings a complete set of 3D and 2D features while providing an intuitive, low cost and collaboration friendly workflow to game developers.** Cocos Engine is the runtime framework for Cocos Creator editor. -Cocos Engine is the framework for Cocos Creator editor. Cocos Creator is the new generation of game development tool in Cocos family, it brings a complete set of 3D features and provides an intuitive, low cost and collaboration friendly workflow to game developers. +![image](https://www.cocos.com/wp-content/uploads/2022/08/13f41f1c975e8255fdc06f59597b9546-7.png) -Cocos Creator inherited many good qualities and cool features from its previous versions, such as cross-platform support including instant gaming platforms like WeChat mini game, asset management, powerful animation editing, etc. Furthermore, Cocos Creator has pushed our technology to a whole new level. Our GFX implementation is designed to adapt to the latest graphic backend APIs, it already supports WebGL 2 and can be seamlessly fall back to WebGL 1, it will support Vulkan and Metal in the native build. The material system is built on our own effect format which uses GLSL 300 and can be easily adapted to lower version on low end devices. Developers can produce high performance, extremely expressive shaders with good compatibility. Along with physical based camera and lighting, high level game graphic can be easily achieved. Our pure GPU driven skeleton animation also make sure your game runs as smooth as possible. Besides all these exciting features, Cocos Creator have builtin physics support, terrain editing support, visual effect editing, ui system, TypeScript support, instant preview etc. +Cocos Creator inherited many good qualities and cool features from its previous versions, such as high performance low level C++ implementation, intuitive editor, cross-platform support. It supports native platforms, web platforms and rapidly expanding instant gaming platforms, including Windows, Mac, iOS, Android, HarmonyOS, Web, Facebook Instant Games, WeChat Mini Game and TikTok Mini Games. + +Furthermore, Cocos Creator has pushed the engine technology to a whole new level for high performance with scalability on various platforms, full extensibility and easy development. + +1. **Modern Graphics**: The GFX implementation is designed to adapt to the modern graphics APIs, it uses Vulkan on Windows and Android, Metal on Mac OS and iOS, WebGL on Web platform. +2. **High Performance**: The runtime engine is built with half C++ and half TypeScript, low level infrastructure, native platform adaptation, renderer and scene management are all written in C++ to ensure high runtime performance. We continue to move heavy lifting work to native as much as possible. +3. **Customizable Render Pipeline**: The render pipeline is designed to be fully customizable, it has supported the builtin forward and deferred render pipeline across all platforms. Developers can customize their own render pipeline following the same approach. +4. **Extensible Surface Shader**: The material system is built on Cocos effect format which uses GLSL 300, the shader programs will be converted to suitable runtime format automatically. The surface shader permit to fully customize the surface material while ensuring universal lighting model. +5. **Physically Based Rendering (PBR)**: The standard effect adopts physically based rendering, along with the physically based camera and the lighting based on physical metrics, developers can easily achieve realistic and seamless rendering results across different environment. +6. **Easy TypeScript API**: The user level API set is provided in TypeScript, along with the powerful VSCode editor, development with Cocos Creator is incredibly efficient. + +Besides all these highlights, Cocos Creator also provides builtin animation system, physics system, particle system, terrain editing support, complex UI system, instant preview etc. ![image](https://user-images.githubusercontent.com/1503156/111037166-f27c7600-845d-11eb-988f-4c2c8b5c7321.png) -This repo is the engine part of Cocos Creator, it's mainly written in TypeScript and support users to use TypeScript or ES6 to write game logics. In addition, the `native` directory provides the underlying implementation of the engine on native platforms. The engine itself is mostly self-contained, with full-fledged runtime modules including lighting, material, particle, animation, physical, UI, terrain, sound, resource and scene-graph management, etc. It supports both native and web platforms, including Windows, Mac, iOS, Android, HarmonyOS, Web. What's more exciting is that it supports rapidly expanding instant gaming platforms like WeChat Mini Game and Facebook Instant Games. +This open source repository is the runtime engine of Cocos Creator, the engine is naturally integrated within Cocos Creator, designed to only be the essential runtime library and not to be used independently. -The engine is naturally integrated within Cocos Creator, designed to only be the essential runtime library and not to be used independently. +## Development and Contribution Notice -## Developer +Cocos Creator engine is open source and welcomes community participation, for open source engine development with Cocos Creator editor, you should fork this repository and setup [custom engine](https://docs.cocos.com/creator/manual/en/advanced-topics/engine-customization.html) in the editor. ### Prerequisite - Install [node.js v9.11.2 +](https://nodejs.org/) - Install [gulp-cli v2.3.0 +](https://github.com/gulpjs/gulp/tree/master/docs/getting-started) +### Clone + +Clone this repository into your local environment. + ### Install -In the cloned repo, run the following command to setup dev environment: +In the cloned engine folder, run the following command to setup development environment: ```bash # download & build engine dependencies @@ -64,24 +79,46 @@ This is all you have to do to setup engine development environment. - If running inside Cocos Creator, the engine will automatically compile and build after the editor window is opened. For more instructions on modifying the engine in Cocos Creator, please refer to [Engine Customization Workflow](https://docs.cocos.com/creator/manual/en/advanced-topics/engine-customization.html). - Outside the editor, you need to run the following command to build: - ```bash - npm run build - ``` +```bash +npm run build +``` -Please refer to [native readme](native/README.md) if want to develop native applications. +Please refer to [native readme](native/README.md) if you want to develop native applications. + +### Contribution + +You can contribute to the Cocos Creator open source engine in many ways, they are very much appreciated: + +1. Report bug or feature requests by [creating an issue](https://github.com/cocos/cocos-engine/issues/new/choose). +2. Participate discussions in the [issues](https://github.com/cocos/cocos-engine/issues/). +3. Create a pull request if you have fixed or improved anything, implemented any features. +4. Improve the documentations with pull request to the [usage documentation repository](https://github.com/cocos/cocos-docs). +5. Help other developers in our [Forum](https://discuss.cocos2d-x.org/c/creator). + +### Contribution notice + +If you are trying to make a pull request, there are some requirements that must be met so that your pull request can be accepted: + +1. Follow our [Cpp Coding Style Guide](./docs/CPP_CODING_STYLE.md) and [TypeScript Coding Style Reference](./docs/TS_CODING_STYLE.md). +2. Try to integrate ESLint and [CPP auto fix tools](./docs/CPP_LINTER_AUTOFIX_GUIDE.md) in your coding environment. +3. Link related issues or discussions in your pull request and clearly state the purpose of your pull request. +4. Pass all automatic continuous integration tests. +5. Request file owner or engine developers to review your pull request. +6. Get one valid approval from the engine architects. ## Example Project -- [Example Cases](https://github.com/cocos/cocos-example-projects): Simple yet expressive demo scenes for baseline testing and topic-specific case study. - [Mind Your Step 3D](https://github.com/cocos/cocos-tutorial-mind-your-step): Beginner's step-by-step tutorial project repo. -- [UI Demo](https://github.com/cocos/cocos-example-ui): Use cases for various kinds of UI components. - [Test Cases](https://github.com/cocos/cocos-test-projects): Unit test scenes for every engine module. +- [Example Cases](https://github.com/cocos/cocos-example-projects): Simple yet expressive demo scenes for baseline testing and topic-specific case study. +- [Awesome Cocos](https://github.com/cocos/awesome-cocos): You can find out other useful tools and show cases here. ## Links -- [Official site](https://www.cocos.com/products#CocosCreator) -- [Download](https://www.cocos.com/creator) +- [Official site](https://www.cocos.com/) +- [Download](https://www.cocos.com/en/creator/download) - [Documentation](https://docs.cocos.com/creator/manual/en/) - [API References](https://docs.cocos.com/creator/api/en/) +- [Projects and road map](https://github.com/orgs/cocos/projects?query=is%3Aopen&type=new) - [Forum](https://discuss.cocos2d-x.org/c/creator) -- [Road Map](https://trello.com/b/JWVRRxMG/cocos-creator-roadmap) +- Discord community: Search for Cocos in the Discover panel of Discord. diff --git a/cc.config.json b/cc.config.json index 69d3361148..9285e341dc 100644 --- a/cc.config.json +++ b/cc.config.json @@ -53,9 +53,12 @@ "14da1725-c4c2-42b4-ab08-ee0aeb6898b3", "081cab31-dccd-428e-8652-f2404cc81c47", "78e0584a-4343-4727-8f37-e14e65c2a2db" - ] + ] + }, + "particle-2d": { + "modules": [ "particle-2d" ], + "dependentModules": [ "2d" ] }, - "particle-2d": { "modules": [ "particle-2d" ] }, "physics-framework": { "modules": [ "physics-framework" ] }, "physics-cannon": { "modules": [ "physics-cannon", "physics-framework" ] , "dependentAssets": [ "ba21476f-2866-4f81-9c4d-6e359316e448" ]}, @@ -100,15 +103,22 @@ }, "webview": { "modules": [ "webview" ] }, "tween": { "modules": [ "tween" ] }, - "tiled-map": { "modules": [ "tiled-map" ] }, + "tiled-map": { + "modules": [ "tiled-map" ], + "dependentModules": [ "2d" ] + }, "spine": { "modules": [ "spine" ], "dependentAssets":[ "c27215d8-6835-4b68-bfbb-bdeac6100c04", "b5d6115f-0370-4d7c-aad3-c194cc71cf98" - ] + ], + "dependentModules": [ "2d" ] + }, + "dragon-bones": { + "modules": [ "dragon-bones" ], + "dependentModules": [ "2d" ] }, - "dragon-bones": { "modules": [ "dragon-bones" ] }, "marionette": { "modules": [], "intrinsicFlags": { diff --git a/cocos/2d/assembler/index.ts b/cocos/2d/assembler/index.ts index 54f5a8c8e4..13d45196c7 100644 --- a/cocos/2d/assembler/index.ts +++ b/cocos/2d/assembler/index.ts @@ -27,5 +27,4 @@ import './utils'; export * from './graphics'; export * from './label'; -export * from './mask'; export * from './sprite'; diff --git a/cocos/2d/assembler/mask/mask-assembler.ts b/cocos/2d/assembler/mask/mask-assembler.ts deleted file mode 100644 index a564f0bd99..0000000000 --- a/cocos/2d/assembler/mask/mask-assembler.ts +++ /dev/null @@ -1,99 +0,0 @@ -/* - Copyright (c) 2017-2020 Xiamen Yaji Software Co., Ltd. - - https://www.cocos.com/ - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*/ - -import { IBatcher } from '../../renderer/i-batcher'; -import { Mask, MaskType } from '../../components/mask'; -import { IAssembler, IAssemblerManager } from '../../renderer/base'; -import { StencilManager } from '../../renderer/stencil-manager'; -import { RenderDrawInfoType } from '../../renderer/render-draw-info'; - -const _stencilManager = StencilManager.sharedManager!; - -function applyClearMask (mask: Mask, renderer: IBatcher) { - _stencilManager.clear(mask); - renderer.commitModel(mask, mask._clearModel, mask._clearStencilMtl); -} - -function applyAreaMask (mask: Mask, renderer: IBatcher) { - _stencilManager.enterLevel(mask); - if (mask.type === MaskType.IMAGE_STENCIL) { - // Apply stencil stage - _stencilManager.stage = mask.subComp!.stencilStage; - } -} - -export const maskAssembler: IAssembler = { - createData (mask: Mask) { - const renderData = mask.requestRenderData(RenderDrawInfoType.MODEL); - return renderData; - }, - - updateRenderData (mask: Mask) { - }, - - fillBuffers (mask: Mask, renderer: IBatcher) { - if (mask.type !== MaskType.IMAGE_STENCIL || mask.spriteFrame) { - _stencilManager.pushMask(mask); - - renderer.finishMergeBatches(); - applyClearMask(mask, renderer); - applyAreaMask(mask, renderer); - } - }, -}; - -export const maskEndAssembler: IAssembler = { - fillBuffers (mask: Mask, ui: IBatcher) { - _stencilManager.exitMask(); - }, -}; - -const StartAssembler: IAssemblerManager = { - getAssembler () { - return maskAssembler; - }, -}; - -const PostAssembler: IAssemblerManager = { - getAssembler () { - return maskEndAssembler; - }, -}; - -const childPostAssembler: IAssemblerManager = { - getAssembler () { - return childEndAssembler; - }, -}; - -export const childEndAssembler: IAssembler = { - fillBuffers (subComp: any, ui: IBatcher) { - _stencilManager.enableMask(); - }, -}; - -Mask.Assembler = StartAssembler; -Mask.PostAssembler = PostAssembler; -Mask.ChildPostAssembler = childPostAssembler; diff --git a/cocos/2d/assembler/sprite/bar-filled.ts b/cocos/2d/assembler/sprite/bar-filled.ts index f13ca49a76..88b566464f 100644 --- a/cocos/2d/assembler/sprite/bar-filled.ts +++ b/cocos/2d/assembler/sprite/bar-filled.ts @@ -70,7 +70,6 @@ export const barFilled: IAssembler = { let fillEnd = fillStart + fillRange; fillEnd = fillEnd > 1 ? 1 : fillEnd; - this.updateColor(sprite); // need Dirty this.updateUVs(sprite, fillStart, fillEnd); // need Dirty this.updateVertexData(sprite, fillStart, fillEnd); renderData.updateRenderData(sprite, frame); diff --git a/cocos/2d/assembler/sprite/radial-filled.ts b/cocos/2d/assembler/sprite/radial-filled.ts index 709ff79a92..340227efbe 100644 --- a/cocos/2d/assembler/sprite/radial-filled.ts +++ b/cocos/2d/assembler/sprite/radial-filled.ts @@ -28,7 +28,7 @@ import { SpriteFrame } from '../../assets'; import { Mat4, Vec2 } from '../../../core/math'; import { IRenderData, RenderData } from '../../renderer/render-data'; import { IBatcher } from '../../renderer/i-batcher'; -import { Sprite } from '../../components'; +import { Sprite, UIOpacity } from '../../components'; import { IAssembler } from '../../renderer/base'; import { dynamicAtlasManager } from '../../utils/dynamic-atlas/atlas-manager'; import { StaticVBChunk } from '../../renderer/static-vb-accessor'; @@ -353,7 +353,8 @@ export const radialFilled: IAssembler = { // may can update color & uv here // need dirty this.updateWorldUVData(sprite); - this.updateColorLate(sprite); + //this.updateColorLate(sprite); + sprite.renderEntity.colorDirty = true; } renderData.updateRenderData(sprite, frame); } diff --git a/cocos/2d/assembler/sprite/tiled.ts b/cocos/2d/assembler/sprite/tiled.ts index a7951e46f1..ddc847da74 100644 --- a/cocos/2d/assembler/sprite/tiled.ts +++ b/cocos/2d/assembler/sprite/tiled.ts @@ -102,7 +102,7 @@ export const tiled: IAssembler = { this.updateVerts(sprite, sizableWidth, sizableHeight, row, col); if (renderData.vertexCount !== row * col * 4) { - if (sprite.renderEntity) { sprite.renderEntity.colorDirty = true; } + sprite.renderEntity.colorDirty = true; } // update data property renderData.resize(row * col * 4, row * col * 6); diff --git a/cocos/2d/components/deprecated.ts b/cocos/2d/components/deprecated.ts index 49ed13365f..037a4e834c 100644 --- a/cocos/2d/components/deprecated.ts +++ b/cocos/2d/components/deprecated.ts @@ -23,7 +23,7 @@ THE SOFTWARE. */ -import { Mask } from './mask'; +import { Mask, MaskType } from './mask'; import { Label } from './label'; import { LabelOutline } from './label-outline'; import { RichText } from './rich-text'; @@ -107,3 +107,24 @@ replaceProperty(Mask.prototype, 'Mask', [ targetName: 'Mask', }, ]); + +replaceProperty(MaskType, 'MaskType', [ + { + name: 'RECT', + newName: 'GRAPHICS_RECT', + target: MaskType, + targetName: 'MaskType', + }, + { + name: 'ELLIPSE', + newName: 'GRAPHICS_ELLIPSE', + target: MaskType, + targetName: 'MaskType', + }, + { + name: 'IMAGE_STENCIL', + newName: 'SPRITE_STENCIL', + target: MaskType, + targetName: 'MaskType', + }, +]); diff --git a/cocos/2d/components/graphics.ts b/cocos/2d/components/graphics.ts index 5aae82d7fd..4c204836e7 100644 --- a/cocos/2d/components/graphics.ts +++ b/cocos/2d/components/graphics.ts @@ -275,15 +275,6 @@ export class Graphics extends UIRenderer { this._flushAssembler(); } - // hack for mask - protected _postRender (render: IBatcher) { - if (!this._postAssembler) { - return; - } - - render.commitComp(this, null, null, this._postAssembler, null); - } - public onEnable () { super.onEnable(); this._updateMtlForGraphics(); diff --git a/cocos/2d/components/mask.ts b/cocos/2d/components/mask.ts index a50b212366..c7d3c51717 100644 --- a/cocos/2d/components/mask.ts +++ b/cocos/2d/components/mask.ts @@ -24,27 +24,17 @@ THE SOFTWARE. */ -import { ccclass, help, executionOrder, menu, tooltip, displayOrder, type, visible, override, serializable, range, slide } from 'cc.decorator'; +import { ccclass, help, executionOrder, menu, tooltip, displayOrder, type, visible, serializable, range, slide, executeInEditMode } from 'cc.decorator'; import { JSB } from 'internal:constants'; -import { InstanceMaterialType, UIRenderer } from '../framework/ui-renderer'; import { clamp, Color, Mat4, Vec2, Vec3 } from '../../core/math'; -import { IBatcher } from '../renderer/i-batcher'; 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 { Material, builtinResMgr, director, CCObject, Node, NodeEventType } from '../../core'; -import { Device, BufferInfo, BufferUsageBit, MemoryUsageBit, PrimitiveMode, deviceManager } from '../../gfx'; +import { NodeEventType, Component } from '../../core'; import { legacyCC } from '../../core/global-exports'; -import { MaterialInstance, scene } from '../../core/renderer'; -import { Model } from '../../core/renderer/scene'; -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 { MaskMode, RenderEntity, RenderEntityType } from '../renderer/render-entity'; -import { RenderDrawInfoType } from '../renderer/render-draw-info'; +import { MaskMode } from '../renderer/render-entity'; import { Sprite } from './sprite'; const _worldMatrix = new Mat4(); @@ -74,7 +64,7 @@ export enum MaskType { * @zh * 使用矩形作为遮罩。 */ - RECT = 0, + GRAPHICS_RECT = 0, /** * @en Ellipse Mask. @@ -82,7 +72,7 @@ export enum MaskType { * @zh * 使用椭圆作为遮罩。 */ - ELLIPSE = 1, + GRAPHICS_ELLIPSE = 1, /** * @en Graphics Mask. @@ -98,7 +88,7 @@ export enum MaskType { * @zh * 使用图片模版作为遮罩。 */ - IMAGE_STENCIL = 3, + SPRITE_STENCIL = 3, } ccenum(MaskType); @@ -117,9 +107,15 @@ const SEGMENTS_MAX = 10000; @help('i18n:cc.Mask') @executionOrder(110) @menu('2D/Mask') -export class Mask extends UIRenderer { - // only for the mask use to reset stage - public static ChildPostAssembler: IAssemblerManager | null = null; +@executeInEditMode +export class Mask extends Component { + /** + * @en The type for mask. + * + * @zh 遮罩组件类型。 + */ + public static Type = MaskType; + /** * @en * The mask type. @@ -139,39 +135,37 @@ export class Mask extends UIRenderer { } this._type = value; - this.markForUpdateRenderData(false); - this._updateMaterial(); - if (this._type !== MaskType.IMAGE_STENCIL) { + if (this._type !== MaskType.SPRITE_STENCIL) { if (this._sprite) { + this.node.removeComponent(Sprite); + this._sprite._destroyImmediate(); this._sprite = null; } - this._spriteFrame = null; - this._maskNode!.parent = null; this._changeRenderType(); this._updateGraphics(); if (JSB) { - this.subComp!.renderEntity.setMaskMode(this._inverted ? MaskMode.MASK_NODE_INVERTED : MaskMode.MASK_NODE); + this.subComp!.renderEntity.setMaskMode(this._inverted ? MaskMode.MASK_INVERTED : MaskMode.MASK); } } else { if (this._graphics) { this._graphics.clear(); + this.node.removeComponent(Graphics); + this._graphics._destroyImmediate(); this._graphics = null; } - this._maskNode!.parent = null; this._changeRenderType(); if (JSB) { - this.subComp!.renderEntity.setMaskMode(this._inverted ? MaskMode.MASK_NODE_INVERTED : MaskMode.MASK_NODE); + this.subComp!.renderEntity.setMaskMode(this._inverted ? MaskMode.MASK_INVERTED : MaskMode.MASK); } } } /** * @en - * Reverse mask (Not supported Canvas Mode) - * . + * Reverse mask * @zh - * 反向遮罩(不支持 Canvas 模式)。 + * 反向遮罩 */ @displayOrder(14) @tooltip('i18n:mask.inverted') @@ -181,16 +175,10 @@ export class Mask extends UIRenderer { set inverted (value) { this._inverted = value; - this.stencilStage = Stage.DISABLED; - if (this._graphics) { - this._graphics.stencilStage = Stage.DISABLED; - } else if (this._sprite) { - this._sprite.stencilStage = Stage.DISABLED; - } + this.subComp!.stencilStage = this.inverted ? Stage.ENTER_LEVEL_INVERTED : Stage.ENTER_LEVEL; if (JSB) { - this._renderEntity.setMaskMode(this._inverted ? MaskMode.MASK_INVERTED : MaskMode.MASK); - this.subComp!.renderEntity.setMaskMode(this._inverted ? MaskMode.MASK_NODE_INVERTED : MaskMode.MASK_NODE); + this.subComp!.renderEntity.setMaskMode(this._inverted ? MaskMode.MASK_INVERTED : MaskMode.MASK); } } @@ -203,7 +191,7 @@ export class Mask extends UIRenderer { * 椭圆遮罩的曲线细分数。 */ @visible(function (this: Mask) { - return this.type === MaskType.ELLIPSE; + return this.type === MaskType.GRAPHICS_ELLIPSE; }) get segments () { return this._segments; @@ -224,26 +212,21 @@ export class Mask extends UIRenderer { * * @zh * 遮罩所需要的贴图。 + * @deprecated since v3.6.1 */ - @type(SpriteFrame) - @visible(function (this: Mask) { - return this.type === MaskType.IMAGE_STENCIL; - }) get spriteFrame () { - return this._spriteFrame; + if (this._sprite) { + return this._sprite.spriteFrame; + } + return null; } set spriteFrame (value) { - if (this._spriteFrame === value) { - return; - } - - this._spriteFrame = value; - if (this._sprite) { this._sprite.spriteFrame = value; + } else { + console.error('please change type to sprite_stencil first'); } - this._updateMaterial(); } /** @@ -260,7 +243,7 @@ export class Mask extends UIRenderer { * 当被设置为 1 时,会丢弃所有蒙版像素,所以不会显示任何内容 */ @visible(function (this: Mask) { - return this.type === MaskType.IMAGE_STENCIL; + return this.type === MaskType.SPRITE_STENCIL; }) @range([0, 1, 0.1]) @slide @@ -274,7 +257,7 @@ export class Mask extends UIRenderer { } this._alphaThreshold = value; - if (this.type === MaskType.IMAGE_STENCIL && this._sprite) { + if (this.type === MaskType.SPRITE_STENCIL && this._sprite) { const mat = this._sprite.getMaterialInstance(0)!; mat.setProperty('alphaThreshold', this._alphaThreshold); } @@ -284,40 +267,8 @@ export class Mask extends UIRenderer { return this._graphics || this._sprite; } - @override - @visible(false) - // @constget - get color (): Readonly { - return this._color; - } - - set color (value) { - super.color = value; - } - - @override - @visible(false) - get customMaterial () { - return this._customMaterial; - } - - set customMaterial (val) { - // mask don`t support customMaterial - } - - public static Type = MaskType; - - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _clearStencilMtl: Material | null = null; - /** - * @deprecated since v3.5.0, this is an engine private interface that will be removed in the future. - */ - public _clearModel: Model | null = null; - @serializable - protected _type = MaskType.RECT; + protected _type = MaskType.GRAPHICS_RECT; @serializable protected _inverted = false; @@ -325,53 +276,30 @@ export class Mask extends UIRenderer { @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 - // always use - private _clearModelMesh: RenderingSubMesh | null = null; - - constructor () { - super(); - this._instanceMaterialType = InstanceMaterialType.ADD_COLOR; - } + protected _stencilStage: Stage = Stage.DISABLED; public onLoad () { - super.onLoad(); - this._createClearModel(); this._changeRenderType(); if (JSB) { - if (this.renderData && this.subComp) { - this._renderEntity.setMaskMode(this._inverted ? MaskMode.MASK_INVERTED : MaskMode.MASK); - this.subComp.renderEntity.setMaskMode(this._inverted ? MaskMode.MASK_NODE_INVERTED : MaskMode.MASK_NODE); - // hack for isMeshBuffer flag - this.renderData.renderDrawInfo.setIsMeshBuffer(true); - this.renderData.drawInfoType = RenderDrawInfoType.MODEL; + if (this.subComp) { + this.subComp.renderEntity.setMaskMode(this._inverted ? MaskMode.MASK_INVERTED : MaskMode.MASK); } } } public onEnable () { - super.onEnable(); + this._changeRenderType();// Maybe useless,a protect,may effect custom setting this._updateGraphics(); - this._enableGraphics(); - this._changeRenderType(); - this.node.on(NodeEventType.SIZE_CHANGED, this._sizeChange, this); - this.node.on(NodeEventType.ANCHOR_CHANGED, this._anchorChange, 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(); + this._enableRender(); + this.node.on(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this); + this.node.on(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this); } /** @@ -380,32 +308,17 @@ export class Mask extends UIRenderer { */ public onRestore () { this._changeRenderType(); - super.updateMaterial(); this._updateGraphics(); - this.markForUpdateRenderData(); } public onDisable () { - super.onDisable(); - this._disableGraphics(); - this.node.off(NodeEventType.SIZE_CHANGED, this._sizeChange, this); - this.node.off(NodeEventType.ANCHOR_CHANGED, this._anchorChange, this); - this.node.off(NodeEventType.SIBLING_ORDER_CHANGED, this._siblingChange, this); - this.node.off(NodeEventType.LAYER_CHANGED, this._layerChange, this); + this._disableRender(); + this.node.off(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this); + this.node.off(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this); } public onDestroy () { - if (this._clearModel && this._clearModelMesh) { - director.root!.destroyModel(this._clearModel); - this._clearModelMesh.destroy(); - } - - if (this._clearStencilMtl) { - this._clearStencilMtl.destroy(); - } - this._removeMaskNode(); - super.onDestroy(); } /** @@ -428,9 +341,9 @@ export class Mask extends UIRenderer { testPt.y += ap.y * h; let result = false; - if (this.type === MaskType.RECT || this.type === MaskType.GRAPHICS_STENCIL || this.type === MaskType.IMAGE_STENCIL) { + if (this.type === MaskType.GRAPHICS_RECT || this.type === MaskType.GRAPHICS_STENCIL || this.type === MaskType.SPRITE_STENCIL) { result = testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h; - } else if (this.type === MaskType.ELLIPSE) { + } else if (this.type === MaskType.GRAPHICS_ELLIPSE) { const rx = w / 2; const ry = h / 2; const px = testPt.x - 0.5 * w; @@ -445,54 +358,12 @@ export class Mask extends UIRenderer { return result; } - protected _render (render: IBatcher) { - render.commitComp(this, this.renderData, null, this._assembler!, null); - } - - protected _postRender (render: IBatcher) { - if (!this._postAssembler) { - return; - } - - render.commitComp(this, null, null, this._postAssembler, null); - } - protected _nodeStateChange (type: TransformBit) { - super._nodeStateChange(type); - this._updateGraphics(); } - protected _canRender () { - if (!super._canRender()) { - return false; - } - - if (this._type !== MaskType.IMAGE_STENCIL) { - return this._graphics !== null; - } else { - return this._sprite !== null && this._spriteFrame !== null; // Or use sprite canRender - } - } - - protected _flushAssembler () { - const assembler = Mask.Assembler.getAssembler(this); - const posAssembler = Mask.PostAssembler!.getAssembler(this); - - if (this._assembler !== assembler) { - this.destroyRenderData(); - this._assembler = assembler; - } - - if (this._postAssembler !== posAssembler) { - this._postAssembler = posAssembler; - } - - this._useRenderData(); - } - private _changeRenderType () { - const isGraphics = (this._type !== MaskType.IMAGE_STENCIL); + const isGraphics = (this._type !== MaskType.SPRITE_STENCIL); if (isGraphics) { this._createGraphics(); } else { @@ -500,84 +371,38 @@ export class Mask extends UIRenderer { } } - 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 _anchorChange () { - if (this._sprite) { - this._maskNode!._uiProps.uiTransformComp!.setAnchorPoint(this.node._uiProps.uiTransformComp!.anchorPoint); - } - } - - 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)!; + let sprite = this._sprite = this.node.getComponent(Sprite); + if (!sprite) { + const node = this.node; + sprite = this._sprite = node.addComponent(Sprite); + } sprite.color = Color.WHITE.clone(); - // @ts-expect-error Mask hack - sprite._postAssembler = Mask.ChildPostAssembler!.getAssembler(this); sprite.sizeMode = 0; - this._sizeChange(); - this._anchorChange(); } - 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); + this._sprite!.stencilStage = this.inverted ? Stage.ENTER_LEVEL_INVERTED : Stage.ENTER_LEVEL; + // @ts-expect-error Mask hack + this._sprite!.updateMaterial(); } protected _createGraphics () { if (!this._graphics) { - this._initGraphicsNode(); - const graphics = this._graphics = this._maskNode!.getComponent(Graphics)!; - graphics._objFlags |= CCObject.Flags.IsOnLoadCalled;// hack for destroy - graphics.node.getWorldMatrix(); - graphics.lineWidth = 0; + let graphics = this._graphics = this.node.getComponent(Graphics); + if (!graphics) { + const node = this.node; + graphics = this._graphics = node.addComponent(Graphics); + } + graphics.lineWidth = 1; 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.node.insertChild(this._maskNode!, 0); - this._updateMaterial(); + this._graphics!.stencilStage = this.inverted ? Stage.ENTER_LEVEL_INVERTED : Stage.ENTER_LEVEL; } protected _updateGraphics () { - if (!this._graphics || (this._type !== MaskType.RECT && this._type !== MaskType.ELLIPSE)) { + if (!this._graphics || (this._type !== MaskType.GRAPHICS_RECT && this._type !== MaskType.GRAPHICS_ELLIPSE)) { return; } @@ -591,9 +416,9 @@ export class Mask extends UIRenderer { const ap = uiTrans.anchorPoint; const x = -width * ap.x; const y = -height * ap.y; - if (this._type === MaskType.RECT) { + if (this._type === MaskType.GRAPHICS_RECT) { graphics.rect(x, y, width, height); - } else if (this._type === MaskType.ELLIPSE) { + } else if (this._type === MaskType.GRAPHICS_ELLIPSE) { const center = new Vec3(x + width / 2, y + height / 2, 0); const radius = new Vec3(width / 2, height / 2, 0); const points = _calculateCircle(center, radius, this._segments); @@ -611,110 +436,31 @@ export class Mask extends UIRenderer { graphics.fill(); } - protected _createClearModel () { - if (!this._clearModel) { - const mtl = builtinResMgr.get('default-clear-stencil'); - this._clearStencilMtl = new MaterialInstance({ - parent: mtl, - owner: this, - subModelIdx: 0, - }); - - this._clearModel = director.root!.createModel(scene.Model); - this._clearModel.node = this._clearModel.transform = this.node; - const stride = getAttributeStride(vfmt); - const gfxDevice: Device = deviceManager.gfxDevice; - const vertexBuffer = gfxDevice.createBuffer(new BufferInfo( - BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, - MemoryUsageBit.DEVICE, - 4 * stride, - stride, - )); - - const vb = new Float32Array([-1, -1, 0, 1, -1, 0, -1, 1, 0, 1, 1, 0]); - vertexBuffer.update(vb); - const indexBuffer = gfxDevice.createBuffer(new BufferInfo( - BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, - MemoryUsageBit.DEVICE, - 6 * Uint16Array.BYTES_PER_ELEMENT, - Uint16Array.BYTES_PER_ELEMENT, - )); - - const ib = new Uint16Array([0, 1, 2, 2, 1, 3]); - indexBuffer.update(ib); - this._clearModelMesh = new RenderingSubMesh([vertexBuffer], vfmt, PrimitiveMode.TRIANGLE_LIST, indexBuffer); - 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 builtinResMgr.get('default-clear-stencil'); - } - - protected _updateMaterial () { - if (this._graphics) { - const target = this._graphics; - target.stencilStage = Stage.DISABLED; - const mat = builtinResMgr.get('ui-graphics-material'); - target.setMaterial(mat, 0); - target.getMaterialInstance(0); - } else if (this._sprite) { - const target = this._sprite; - target.stencilStage = Stage.DISABLED; - let mat = builtinResMgr.get('ui-alpha-test-material'); - target.setMaterial(mat, 0); - mat = target.getMaterialInstance(0)!; - mat.setProperty('alphaThreshold', this._alphaThreshold); - } - } - - protected _enableGraphics () { + protected _enableRender () { if (this.subComp) { this.subComp.enabled = true; } } - protected _disableGraphics () { + protected _disableRender () { if (this.subComp) { + this.subComp.stencilStage = Stage.DISABLED; + // @ts-expect-error Mask hack + this.subComp.updateMaterial(); this.subComp.enabled = false; } } 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 + if (this._sprite) { + this._sprite.destroy(); this._sprite = null; + } + if (this._graphics) { + this._graphics.destroy(); this._graphics = null; } } - - protected _useRenderData () { - //if (this._type === MaskType.IMAGE_STENCIL && !this.renderData) { - if (!this.renderData) { - if (this._assembler && this._assembler.createData) { - this._renderData = this._assembler.createData(this); - this.markForUpdateRenderData(); - } - } - } - - // RenderEntity - // it should be overwritten by inherited classes - protected createRenderEntity () { - return new RenderEntity(RenderEntityType.DYNAMIC); - } } NodeEventProcessor._maskComp = Mask; diff --git a/cocos/2d/components/rich-text.ts b/cocos/2d/components/rich-text.ts index 8d59472278..20345b2802 100644 --- a/cocos/2d/components/rich-text.ts +++ b/cocos/2d/components/rich-text.ts @@ -25,7 +25,7 @@ */ import { ccclass, executeInEditMode, executionOrder, help, menu, tooltip, multiline, type, displayOrder, serializable } from 'cc.decorator'; -import { DEV, EDITOR } from 'internal:constants'; +import { DEBUG, DEV, EDITOR } from 'internal:constants'; import { Font, SpriteAtlas, TTFFont, SpriteFrame } from '../assets'; import { EventTouch } from '../../input/types'; import { assert, warnID } from '../../core/platform'; @@ -758,13 +758,10 @@ export class RichText extends Component { for (let i = children.length - 1; i >= 0; i--) { const child = children[i]; if (child.name === RichTextChildName || child.name === RichTextChildImageName) { - if (child.parent === this.node) { - child.parent = null; - } else { - // In case child.parent !== this.node, child cannot be removed from children - - children.splice(i, 1); + if (DEBUG) { + assert(child.parent === this.node); } + child.parent = null; const segment = createSegment(child.name); segment.node = child; diff --git a/cocos/2d/components/sprite.ts b/cocos/2d/components/sprite.ts index bf884dea04..cd0627e696 100644 --- a/cocos/2d/components/sprite.ts +++ b/cocos/2d/components/sprite.ts @@ -605,15 +605,6 @@ export class Sprite extends UIRenderer { } } - // 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 (BUILD || !this._spriteFrame.isDefault) { diff --git a/cocos/2d/components/ui-opacity.ts b/cocos/2d/components/ui-opacity.ts index 513ffdfe44..76960b07fa 100644 --- a/cocos/2d/components/ui-opacity.ts +++ b/cocos/2d/components/ui-opacity.ts @@ -84,6 +84,12 @@ export class UIOpacity extends Component { // for UIOpacity public static setEntityLocalOpacityDirtyRecursively (node: Node, dirty: boolean, interruptParentOpacity: number) { + if (!node.isValid) { + // Since children might be destroyed before the parent, + // we should add protecting condition when executing recursion downwards. + return; + } + const render = node._uiProps.uiComp as UIRenderer; const uiOp = node.getComponent(UIOpacity); let interruptOpacity = interruptParentOpacity;// if there is no UIOpacity component, it should always equal to 1. @@ -99,7 +105,8 @@ export class UIOpacity extends Component { interruptOpacity = 1; } else if (uiOp) { // there is a just UIOpacity but no UIRenderer on the node. - interruptOpacity = uiOp.opacity / 255; + // we should transport the interrupt opacity downward + interruptOpacity = interruptOpacity * uiOp.opacity / 255; } for (let i = 0; i < node.children.length; i++) { diff --git a/cocos/2d/framework/deprecated-1.2.0.ts b/cocos/2d/framework/deprecated-1.2.0.ts new file mode 100644 index 0000000000..fa046b7893 --- /dev/null +++ b/cocos/2d/framework/deprecated-1.2.0.ts @@ -0,0 +1,44 @@ +/* + Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + +import { deprecateModuleExportedName } from '../../core/utils/x-deprecated'; + +deprecateModuleExportedName({ + RenderComponent: { + newName: 'UIRenderer', + since: '1.2.0', + removed: true, + }, + UITransformComponent: { + newName: 'UITransform', + since: '1.2.0', + removed: false, + }, + CanvasComponent: { + newName: 'Canvas', + since: '1.2.0', + removed: false, + }, +}); diff --git a/cocos/2d/assembler/mask/index.ts b/cocos/2d/framework/deprecated-3.0.0.ts similarity index 85% rename from cocos/2d/assembler/mask/index.ts rename to cocos/2d/framework/deprecated-3.0.0.ts index ae2cf72dc9..33415e7524 100644 --- a/cocos/2d/assembler/mask/index.ts +++ b/cocos/2d/framework/deprecated-3.0.0.ts @@ -23,9 +23,12 @@ THE SOFTWARE. */ -import { maskAssembler as mask, maskEndAssembler as maskEnd } from './mask-assembler'; +import { deprecateModuleExportedName } from '../../core/utils/x-deprecated'; -export { - mask, - maskEnd, -}; +deprecateModuleExportedName({ + UIRenderable: { + newName: 'UIRenderer', + since: '3.0.0', + removed: true, + }, +}); diff --git a/cocos/2d/framework/deprecated-3.6.0.ts b/cocos/2d/framework/deprecated-3.6.0.ts new file mode 100644 index 0000000000..16a6220d62 --- /dev/null +++ b/cocos/2d/framework/deprecated-3.6.0.ts @@ -0,0 +1,34 @@ +/* + Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + +import { deprecateModuleExportedName } from '../../core/utils/x-deprecated'; + +deprecateModuleExportedName({ + Renderable2D: { + newName: 'UIRenderer', + since: '3.6.0', + removed: true, + }, +}); diff --git a/cocos/2d/framework/index.ts b/cocos/2d/framework/index.ts index 4a804dbcbe..acc838ba80 100644 --- a/cocos/2d/framework/index.ts +++ b/cocos/2d/framework/index.ts @@ -23,6 +23,10 @@ THE SOFTWARE. */ +import './deprecated-1.2.0'; +import './deprecated-3.0.0'; +import './deprecated-3.6.0'; + export * from './canvas'; export * from './ui-component'; export * from './ui-renderer'; diff --git a/cocos/2d/framework/ui-renderer.ts b/cocos/2d/framework/ui-renderer.ts index cb6e804382..a3b1aa25a8 100644 --- a/cocos/2d/framework/ui-renderer.ts +++ b/cocos/2d/framework/ui-renderer.ts @@ -214,6 +214,7 @@ export class UIRenderer extends Renderer { } /** + * @internal * @en The component stencil stage (please do not any modification directly on this object) * @zh 组件模板缓冲状态 (注意:请不要直接修改它的值) */ @@ -423,6 +424,9 @@ export class UIRenderer extends Renderer { } const mat = this._updateBuiltinMaterial(); this.setMaterial(mat, 0); + if (this.stencilStage === Stage.ENTER_LEVEL || this.stencilStage === Stage.ENTER_LEVEL_INVERTED) { + this.getMaterialInstance(0)!.recompileShaders({ USE_ALPHA_TEST: true }); + } this._updateBlendFunc(); } diff --git a/cocos/2d/renderer/batcher-2d.ts b/cocos/2d/renderer/batcher-2d.ts index a50030e7e0..6879ad1b43 100644 --- a/cocos/2d/renderer/batcher-2d.ts +++ b/cocos/2d/renderer/batcher-2d.ts @@ -24,12 +24,12 @@ */ import { JSB } from 'internal:constants'; -import { Camera, Model } from 'cocos/core/renderer/scene'; +import { Camera, Model } from '../../core/renderer/scene'; import type { UIStaticBatch } from '../components/ui-static-batch'; import { Material } from '../../core/assets/material'; import { RenderRoot2D, UIRenderer } from '../framework'; import { Texture, Device, Attribute, Sampler, DescriptorSetInfo, Buffer, - BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet, InputAssembler, deviceManager } from '../../gfx'; + BufferInfo, BufferUsageBit, MemoryUsageBit, DescriptorSet, InputAssembler, deviceManager, PrimitiveMode } from '../../gfx'; import { Pool } from '../../core/memop'; import { CachedArray } from '../../core/memop/cached-array'; import { Root } from '../../core/root'; @@ -44,12 +44,14 @@ import { Mat4 } from '../../core/math'; import { IBatcher } from './i-batcher'; import { StaticVBAccessor } from './static-vb-accessor'; import { assertIsTrue } from '../../core/data/utils/asserts'; -import { getAttributeStride, vfmtPosUvColor } from './vertex-format'; +import { getAttributeStride, vfmt, vfmtPosUvColor } from './vertex-format'; import { updateOpacity } from '../assembler/utils'; import { BaseRenderData, MeshRenderData } from './render-data'; import { UIMeshRenderer } from '../components/ui-mesh-renderer'; import { NativeBatcher2d, NativeUIMeshBuffer } from './native-2d'; import { MeshBuffer } from './mesh-buffer'; +import { scene } from '../../core/renderer'; +import { builtinResMgr, RenderingSubMesh } from '../../core'; const _dsInfo = new DescriptorSetInfo(null!); const m4_1 = new Mat4(); @@ -116,6 +118,11 @@ export class Batcher2D implements IBatcher { private _meshDataArray :MeshRenderData[] = []; + // mask use + private _maskClearModel :Model | null = null; + private _maskClearMtl :Material | null = null; + private _maskModelMesh :RenderingSubMesh | null = null; + constructor (private _root: Root) { this.device = _root.device; this._batches = new CachedArray(64); @@ -146,6 +153,14 @@ export class Batcher2D implements IBatcher { this._descriptorSetCache.destroy(); StencilManager.sharedManager!.destroy(); + + if (this._maskClearModel && this._maskModelMesh) { + legacyCC.director.root.destroyModel(this._maskClearModel); + this._maskModelMesh.destroy(); + } + if (this._maskClearMtl) { + this._maskClearMtl.destroy(); + } } private syncRootNodesToNative () { @@ -369,7 +384,12 @@ export class Batcher2D implements IBatcher { mat = renderData.material; bufferID = renderData.chunk.bufferId; } - comp.stencilStage = StencilManager.sharedManager!.stage; + // Notice: A little hack, if it is for mask, not need update here, while control by stencilManger + if (comp.stencilStage === Stage.ENTER_LEVEL || comp.stencilStage === Stage.ENTER_LEVEL_INVERTED) { + this._insertMaskBatch(comp); + } else { + comp.stencilStage = StencilManager.sharedManager!.stage; + } const depthStencilStateStage = comp.stencilStage; if (this._currHash !== dataHash || dataHash === 0 || this._currMaterial !== mat @@ -470,8 +490,10 @@ export class Batcher2D implements IBatcher { let depthStencil; let dssHash = 0; if (mat) { - // Notice: A little hack, if not this two stage, not need update here, while control by stencilManger - if (comp.stencilStage === Stage.ENABLED || comp.stencilStage === Stage.DISABLED) { + // Notice: A little hack, if it is for mask, not need update here, while control by stencilManger + if (comp.stencilStage === Stage.ENTER_LEVEL || comp.stencilStage === Stage.ENTER_LEVEL_INVERTED) { + this._insertMaskBatch(comp); + } else { comp.stencilStage = StencilManager.sharedManager!.stage; } depthStencil = StencilManager.sharedManager!.getStencilStage(comp.stencilStage, mat); @@ -719,6 +741,12 @@ export class Batcher2D implements IBatcher { // ATTENTION: Will also reset colorDirty inside postUpdateAssembler if (render && render.enabledInHierarchy) { render.postUpdateAssembler(this); + if ((render.stencilStage === Stage.ENTER_LEVEL || render.stencilStage === Stage.ENTER_LEVEL_INVERTED) + && (StencilManager.sharedManager!.getMaskStackSize() > 0)) { + this.autoMergeBatches(this._currComponent!); + this.resetRenderStates(); + StencilManager.sharedManager!.exitMask(); + } } level += 1; @@ -737,6 +765,81 @@ export class Batcher2D implements IBatcher { } } + // Mask use + private _createClearModel () { + if (!this._maskClearModel) { + this._maskClearMtl = builtinResMgr.get('default-clear-stencil'); + + this._maskClearModel = legacyCC.director.root.createModel(scene.Model); + const stride = getAttributeStride(vfmt); + const gfxDevice: Device = deviceManager.gfxDevice; + const vertexBuffer = gfxDevice.createBuffer(new BufferInfo( + BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.DEVICE, + 4 * stride, + stride, + )); + + const vb = new Float32Array([-1, -1, 0, 1, -1, 0, -1, 1, 0, 1, 1, 0]); + vertexBuffer.update(vb); + const indexBuffer = gfxDevice.createBuffer(new BufferInfo( + BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST, + MemoryUsageBit.DEVICE, + 6 * Uint16Array.BYTES_PER_ELEMENT, + Uint16Array.BYTES_PER_ELEMENT, + )); + + const ib = new Uint16Array([0, 1, 2, 2, 1, 3]); + indexBuffer.update(ib); + this._maskModelMesh = new RenderingSubMesh([vertexBuffer], vfmt, PrimitiveMode.TRIANGLE_LIST, indexBuffer); + this._maskModelMesh.subMeshIdx = 0; + + this._maskClearModel!.initSubModel(0, this._maskModelMesh, this._maskClearMtl); + } + } + + private _insertMaskBatch (comp: UIRenderer | UIMeshRenderer) { + this.autoMergeBatches(this._currComponent!); + this.resetRenderStates(); + this._createClearModel(); + this._maskClearModel!.node = this._maskClearModel!.transform = comp.node; + const _stencilManager = StencilManager.sharedManager!; + _stencilManager.pushMask(1);//not need object,only use length + const stage = _stencilManager.clear(comp); //invert + + let depthStencil; + let dssHash = 0; + const mat = this._maskClearMtl; + if (mat) { + depthStencil = _stencilManager.getStencilStage(stage, mat); + dssHash = _stencilManager.getStencilHash(stage); + } + + const model = this._maskClearModel!; + const stamp = legacyCC.director.getTotalFrames(); + if (model) { + model.updateTransform(stamp); + model.updateUBOs(stamp); + } + + for (let i = 0; i < model.subModels.length; i++) { + const curDrawBatch = this._drawBatchPool.alloc(); + const subModel = model.subModels[i]; + curDrawBatch.visFlags = comp.node.layer; + curDrawBatch.model = model; + curDrawBatch.texture = null; + curDrawBatch.sampler = null; + curDrawBatch.useLocalData = null; + if (!depthStencil) { depthStencil = null; } + curDrawBatch.fillPasses(mat, depthStencil, dssHash, subModel.patches); + curDrawBatch.inputAssembler = subModel.inputAssembler; + curDrawBatch.model.visFlags = curDrawBatch.visFlags; + curDrawBatch.descriptorSet = subModel.descriptorSet; + this._batches.push(curDrawBatch); + } + _stencilManager.enableMask(); + } + //sync mesh buffer to naive public syncMeshBuffersToNative (accId: number, buffers: MeshBuffer[]) { if (JSB) { diff --git a/cocos/2d/renderer/buffer-accessor.ts b/cocos/2d/renderer/buffer-accessor.ts index 14e718f38f..a8044d6d54 100644 --- a/cocos/2d/renderer/buffer-accessor.ts +++ b/cocos/2d/renderer/buffer-accessor.ts @@ -25,7 +25,7 @@ import { Attribute, Device } from '../../gfx'; import type { MeshBuffer } from './mesh-buffer'; -import { getComponentPerVertex } from './vertex-format'; +import { getAttributeStride, getComponentPerVertex } from './vertex-format'; export class BufferAccessor { public get attributes (): Readonly { return this._attributes; } @@ -41,7 +41,8 @@ export class BufferAccessor { constructor (device: Device, attributes: Attribute[]) { this._device = device; this._attributes = attributes; - this._floatsPerVertex = getComponentPerVertex(attributes); + + this._floatsPerVertex = getAttributeStride(attributes) >> 2; this._vertexFormatBytes = this._floatsPerVertex * Float32Array.BYTES_PER_ELEMENT; } diff --git a/cocos/2d/renderer/mesh-buffer.ts b/cocos/2d/renderer/mesh-buffer.ts index a21a0640a2..2b7b014a05 100644 --- a/cocos/2d/renderer/mesh-buffer.ts +++ b/cocos/2d/renderer/mesh-buffer.ts @@ -25,7 +25,7 @@ import { JSB } from 'internal:constants'; import { Device, BufferUsageBit, MemoryUsageBit, Attribute, Buffer, BufferInfo, InputAssembler, InputAssemblerInfo } from '../../gfx'; -import { getComponentPerVertex } from './vertex-format'; +import { getAttributeStride } from './vertex-format'; import { getError, warnID } from '../../core/platform/debug'; import { sys } from '../../core'; import { assertIsTrue } from '../../core/data/utils/asserts'; @@ -187,7 +187,7 @@ export class MeshBuffer { this._attributes = attrs; //sync to native - this.floatsPerVertex = getComponentPerVertex(attrs); + this.floatsPerVertex = getAttributeStride(attrs) >> 2; assertIsTrue(this._initVDataCount / this._floatsPerVertex < 65536, getError(9005)); diff --git a/cocos/2d/renderer/native-2d.ts b/cocos/2d/renderer/native-2d.ts index ac443237d1..6ad3094f79 100644 --- a/cocos/2d/renderer/native-2d.ts +++ b/cocos/2d/renderer/native-2d.ts @@ -51,6 +51,9 @@ export declare class NativeRenderEntity { get node(): Node | null; set node(node: Node | null); + get renderTransform(): Node | null; + set renderTransform(node: Node | null); + get stencilStage(): number; set stencilStage(stage: number); diff --git a/cocos/2d/renderer/render-data.ts b/cocos/2d/renderer/render-data.ts index cd756a66e2..e4374ebcc6 100644 --- a/cocos/2d/renderer/render-data.ts +++ b/cocos/2d/renderer/render-data.ts @@ -226,9 +226,7 @@ export class BaseRenderData { */ export class RenderData extends BaseRenderData { public static add (vertexFormat = vfmtPosUvColor, accessor?: StaticVBAccessor) { - const rd = new RenderData(vertexFormat); - rd._floatStride = vertexFormat === vfmtPosUvColor ? DEFAULT_STRIDE : (getAttributeStride(vertexFormat) >> 2); - rd._vertexFormat = vertexFormat; + const rd = new RenderData(vertexFormat, accessor); if (!accessor) { const batcher = director.root!.batcher2D; accessor = batcher.switchBufferAccessor(rd._vertexFormat); diff --git a/cocos/2d/renderer/render-entity.ts b/cocos/2d/renderer/render-entity.ts index d9dde93670..75a45713e0 100644 --- a/cocos/2d/renderer/render-entity.ts +++ b/cocos/2d/renderer/render-entity.ts @@ -27,7 +27,7 @@ export enum RenderEntityUInt8SharedBufferView { count, } -export enum RenderEntityBoolSharedBufferView{ +export enum RenderEntityBoolSharedBufferView { colorDirty, enabled, useLocal, @@ -48,13 +48,14 @@ export class RenderEntity { private _dynamicDrawInfoArr: RenderDrawInfo[] = []; protected _node: Node | null = null; + protected _renderTransform: Node | null = null; protected _stencilStage: Stage = Stage.DISABLED; protected _useLocal = false; protected _maskMode = MaskMode.NONE; protected declare _floatSharedBuffer: Float32Array; protected declare _uint8SharedBuffer: Uint8Array; - protected declare _boolSharedBuffer:Uint8Array; + protected declare _boolSharedBuffer: Uint8Array; private declare _nativeObj: NativeRenderEntity; get nativeObj () { @@ -197,6 +198,15 @@ export class RenderEntity { this._node = node; } + setRenderTransform (renderTransform: Node | null) { + if (JSB) { + if (this._renderTransform !== renderTransform) { + this._nativeObj.renderTransform = renderTransform; + } + } + this._renderTransform = renderTransform; + } + setStencilStage (stage: Stage) { if (JSB) { if (this._stencilStage !== stage) { diff --git a/cocos/2d/renderer/stencil-manager.ts b/cocos/2d/renderer/stencil-manager.ts index e303be14f0..aac315b458 100644 --- a/cocos/2d/renderer/stencil-manager.ts +++ b/cocos/2d/renderer/stencil-manager.ts @@ -24,8 +24,9 @@ */ import { ComparisonFunc, StencilOp, DepthStencilState } from '../../gfx'; -import { Mask } from '../components/mask'; import { Material } from '../../core'; +import { UIRenderer } from '../framework/ui-renderer'; +import { UIMeshRenderer } from '../components/ui-mesh-renderer'; // Stage types export enum Stage { @@ -87,14 +88,9 @@ export class StencilManager { this._maskStack.push(mask); } - public clear (comp: Mask) { - comp.stencilStage = comp.inverted ? Stage.CLEAR_INVERTED : Stage.CLEAR; - // this.stage = Stage.CLEAR; - } - - public enterLevel (comp: Mask) { - comp.subComp!.stencilStage = comp.inverted ? Stage.ENTER_LEVEL_INVERTED : Stage.ENTER_LEVEL; - // this.stage = Stage.ENTER_LEVEL; + public clear (comp: UIRenderer | UIMeshRenderer) { + const isInverted = (comp.stencilStage !== Stage.ENTER_LEVEL); + return isInverted ? Stage.CLEAR_INVERTED : Stage.CLEAR; } public enableMask () { @@ -130,6 +126,10 @@ export class StencilManager { return result; } + public getMaskStackSize () { + return this._maskStack.length; + } + public reset () { // reset stack and stage this._maskStack.length = 0; diff --git a/cocos/2d/renderer/vertex-format.ts b/cocos/2d/renderer/vertex-format.ts index 9aeadacfd8..de3db5628a 100644 --- a/cocos/2d/renderer/vertex-format.ts +++ b/cocos/2d/renderer/vertex-format.ts @@ -63,6 +63,12 @@ export const vfmtPosUvColor = [ new Attribute(AttributeName.ATTR_COLOR, Format.RGBA32F), ]; +export const vfmtPosUvColor4B = [ + new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), + new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), + new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true), +]; + /** * @en Vertex format with the following layout * 1. Vector 3 position attribute (Float32) @@ -82,6 +88,13 @@ export const vfmtPosUvTwoColor = [ new Attribute(AttributeName.ATTR_COLOR2, Format.RGBA32F), ]; +export const vfmtPosUvTwoColor4B = [ + new Attribute(AttributeName.ATTR_POSITION, Format.RGB32F), + new Attribute(AttributeName.ATTR_TEX_COORD, Format.RG32F), + new Attribute(AttributeName.ATTR_COLOR, Format.RGBA8, true), + new Attribute(AttributeName.ATTR_COLOR2, Format.RGBA8, true), +]; + /** * @en Get total components count for all attributes per vertex. * @zh 获取每个顶点上所有属性的分量数总和 @@ -118,3 +131,5 @@ export function getAttributeStride (attrs: Attribute[]) { legacyCC.internal.vfmtPosUvColor = vfmtPosUvColor; legacyCC.internal.vfmtPosUvTwoColor = vfmtPosUvTwoColor; +legacyCC.internal.vfmtPosUvColor4B = vfmtPosUvColor4B; +legacyCC.internal.vfmtPosUvTwoColor4B = vfmtPosUvTwoColor4B; diff --git a/cocos/3d/assets/mesh.jsb.ts b/cocos/3d/assets/mesh.jsb.ts index a286755e50..6a4e8d79f7 100644 --- a/cocos/3d/assets/mesh.jsb.ts +++ b/cocos/3d/assets/mesh.jsb.ts @@ -24,8 +24,11 @@ */ import { ccclass, serializable } from 'cc.decorator'; import { legacyCC } from '../../core/global-exports'; +import { Vec3 } from '../../core/math'; import '../../core/assets/asset'; +declare const jsb: any; + export declare namespace Mesh { export interface IBufferView { offset: number; @@ -43,6 +46,50 @@ export declare namespace Mesh { export type Mesh = jsb.Mesh; export const Mesh = jsb.Mesh; +const IStructProto: any = jsb.Mesh.IStruct.prototype; + +Object.defineProperty(IStructProto, 'minPosition', { + configurable: true, + enumerable: true, + get () { + const r = this.getMinPosition(); + if (r) { + if (!this._minPositionCache) { + this._minPositionCache = new Vec3(r.x, r.y, r.z); + } else { + this._minPositionCache.set(r.x, r.y, r.z); + } + } else { + this._minPositionCache = undefined; + } + return this._minPositionCache; + }, + set (v) { + this.setMinPosition(v); + } +}); + +Object.defineProperty(IStructProto, 'maxPosition', { + configurable: true, + enumerable: true, + get () { + const r = this.getMaxPosition(); + if (r) { + if (!this._maxPositionCache) { + this._maxPositionCache = new Vec3(r.x, r.y, r.z); + } else { + this._maxPositionCache.set(r.x, r.y, r.z); + } + } else { + this._maxPositionCache = undefined; + } + return this._maxPositionCache; + }, + set (v) { + this.setMaxPosition(v); + } +}); + const meshAssetProto: any = jsb.Mesh.prototype; meshAssetProto.createNode = null!; @@ -54,6 +101,8 @@ meshAssetProto._ctor = function () { vertexBundles: [], primitives: [], }; + this._minPosition = undefined; + this._maxPosition = undefined; }; Object.defineProperty(meshAssetProto, 'struct', { @@ -64,6 +113,42 @@ Object.defineProperty(meshAssetProto, 'struct', { } }); +Object.defineProperty(meshAssetProto, 'minPosition', { + configurable: true, + enumerable: true, + get () { + const r = this.getMinPosition(); + if (r) { + if (!this._minPosition) { + this._minPosition = new Vec3(r.x, r.y, r.z); + } else { + this._minPosition.set(r.x, r.y, r.z); + } + } else { + this._minPosition = undefined; + } + return this._minPosition; + } +}); + +Object.defineProperty(meshAssetProto, 'maxPosition', { + configurable: true, + enumerable: true, + get () { + const r = this.getMaxPosition(); + if (r) { + if (!this._maxPosition) { + this._maxPosition = new Vec3(r.x, r.y, r.z); + } else { + this._maxPosition.set(r.x, r.y, r.z); + } + } else { + this._maxPosition = undefined; + } + return this._maxPosition; + } +}); + meshAssetProto.onLoaded = function () { // might be undefined if (this._struct != undefined) { diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 57f47bc779..4202b2316f 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -261,7 +261,7 @@ export class Mesh extends Asset { * @zh (各分量都)小于等于此网格任何顶点位置的最大位置。 * @deprecated Please use [[struct.minPosition]] instead */ - get minPosition () { + get minPosition (): Readonly | undefined { return this.struct.minPosition; } @@ -270,7 +270,7 @@ export class Mesh extends Asset { * @zh (各分量都)大于等于此网格任何顶点位置的最大位置。 * @deprecated Please use [[struct.maxPosition]] instead */ - get maxPosition () { + get maxPosition (): Readonly | undefined { return this.struct.maxPosition; } diff --git a/cocos/3d/framework/mesh-renderer.ts b/cocos/3d/framework/mesh-renderer.ts index 939f7440e0..b5e18333a7 100644 --- a/cocos/3d/framework/mesh-renderer.ts +++ b/cocos/3d/framework/mesh-renderer.ts @@ -398,7 +398,8 @@ export class MeshRenderer extends ModelRenderer { public onGeometryChanged () { if (this._model && this._mesh) { - this._model.createBoundingShape(this._mesh.struct.minPosition, this._mesh.struct.maxPosition); + const meshStruct = this._mesh.struct; + this._model.createBoundingShape(meshStruct.minPosition, meshStruct.maxPosition); this._model.updateWorldBound(); this._model.onGeometryChanged(); } @@ -514,7 +515,8 @@ export class MeshRenderer extends ModelRenderer { if (this._model) { if (this._mesh) { - this._model.createBoundingShape(this._mesh.struct.minPosition, this._mesh.struct.maxPosition); + const meshStruct = this._mesh.struct; + this._model.createBoundingShape(meshStruct.minPosition, meshStruct.maxPosition); } // Initialize lighting map before model initializing // because the lighting map will influence the model's shader diff --git a/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts b/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts index 3ee9d4b6bf..e77631a89c 100644 --- a/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts +++ b/cocos/3d/skinned-mesh-renderer/skinned-mesh-renderer.ts @@ -26,6 +26,7 @@ import { ccclass, executeInEditMode, executionOrder, help, menu, tooltip, type, } from 'cc.decorator'; +import { EDITOR } from 'internal:constants'; import type { AnimationClip } from '../../core/animation/animation-clip'; import { Material } from '../../core/assets'; import { Skeleton } from '../assets/skeleton'; @@ -104,6 +105,9 @@ export class SkinnedMeshRenderer extends MeshRenderer { public onLoad () { super.onLoad(); + if (EDITOR) { + this._objFlags |= legacyCC.Object.Flags.IsPositionLocked | legacyCC.Object.Flags.IsRotationLocked | legacyCC.Object.Flags.IsScaleLocked; + } this._tryBindAnimation(); } diff --git a/cocos/audio/audio-source.ts b/cocos/audio/audio-source.ts index 68b58b4dd4..6c21013fa4 100644 --- a/cocos/audio/audio-source.ts +++ b/cocos/audio/audio-source.ts @@ -329,8 +329,9 @@ export class AudioSource extends Component { if (this.state === AudioState.PLAYING) { this._player?.stop().catch((e) => {}); } + const player = this._player; this._player?.play().then(() => { - audioManager.addPlaying(this._player!); + audioManager.addPlaying(player!); this.node?.emit(AudioSourceEventType.STARTED, this); }).catch((e) => {}); } @@ -346,8 +347,9 @@ export class AudioSource extends Component { this._operationsBeforeLoading.push('pause'); return; } + const player = this._player; this._player?.pause().then(() => { - audioManager.removePlaying(this._player!); + audioManager.removePlaying(player!); }).catch((e) => {}); } @@ -362,8 +364,9 @@ export class AudioSource extends Component { this._operationsBeforeLoading.push('stop'); return; } + const player = this._player; this._player?.stop().then(() => { - audioManager.removePlaying(this._player!); + audioManager.removePlaying(player!); }).catch((e) => {}); } diff --git a/cocos/core/asset-manager/asset-manager.ts b/cocos/core/asset-manager/asset-manager.ts index 6509f34013..c1e29b8f64 100644 --- a/cocos/core/asset-manager/asset-manager.ts +++ b/cocos/core/asset-manager/asset-manager.ts @@ -55,10 +55,10 @@ import { Request, references, IJsonAssetOptions, - assets, BuiltinBundleName, bundles, fetchPipeline, files, parsed, pipeline, transformPipeline } from './shared'; + assets, BuiltinBundleName, bundles, fetchPipeline, files, parsed, pipeline, transformPipeline, assetsOverrideMap } from './shared'; import Task from './task'; -import { combine, parse } from './url-transformer'; +import { combine, parse, replaceOverrideAsset } from './url-transformer'; import { asyncify, parseParameters } from './utilities'; /** @@ -149,7 +149,7 @@ export class AssetManager { * Url 转换器 * */ - public transformPipeline: Pipeline = transformPipeline.append(parse).append(combine); + public transformPipeline: Pipeline = transformPipeline.append(parse).append(replaceOverrideAsset).append(combine); /** * @en @@ -170,6 +170,11 @@ export class AssetManager { */ public assets: ICache = assets; + /** + * @internal only using in L10N for now + */ + public readonly assetsOverrideMap = assetsOverrideMap; + public generalImportBase = ''; public generalNativeBase = ''; @@ -347,6 +352,10 @@ export class AssetManager { this.generalImportBase = importBase; this.generalNativeBase = nativeBase; this._projectBundles = settings.querySettings(Settings.Category.ASSETS, 'projectBundles') || []; + const assetsOverride = settings.querySettings(Settings.Category.ASSETS, 'assetsOverrides') || {}; + for (const key in assetsOverride) { + this.assetsOverrideMap.set(key, assetsOverride[key]); + } } /** diff --git a/cocos/core/asset-manager/editor-path-replace.ts b/cocos/core/asset-manager/editor-path-replace.ts index c1049544ba..b931f30482 100644 --- a/cocos/core/asset-manager/editor-path-replace.ts +++ b/cocos/core/asset-manager/editor-path-replace.ts @@ -39,7 +39,7 @@ if ((EDITOR || PREVIEW) && !TEST) { const item = task.input[i]; if (!item.uuid || item.isNative) { continue; } try { - const extension = await queryExtension(item.uuid); + const extension = await queryExtension(item.overrideUuid || item.uuid); if (extension) { item.ext = extension; item.url = item.url.replace('.json', extension); diff --git a/cocos/core/asset-manager/request-item.ts b/cocos/core/asset-manager/request-item.ts index b6f4577531..51fe901f80 100644 --- a/cocos/core/asset-manager/request-item.ts +++ b/cocos/core/asset-manager/request-item.ts @@ -43,7 +43,7 @@ export default class RequestItem { */ get id (): string { if (!this._id) { - this._id = `${this.uuid}@${this.isNative ? 'native' : 'import'}`; + this._id = `${this.overrideUuid || this.uuid}@${this.isNative ? 'native' : 'import'}`; } return this._id; } @@ -83,6 +83,8 @@ export default class RequestItem { */ public uuid = ''; + public overrideUuid = ''; + /** * @en * The final url of request @@ -169,6 +171,7 @@ export default class RequestItem { if (RequestItem._deadPool.length === RequestItem.MAX_DEAD_NUM) { return; } this._id = ''; this.uuid = ''; + this.overrideUuid = ''; this.url = ''; this.ext = '.json'; this.content = null; diff --git a/cocos/core/asset-manager/shared.ts b/cocos/core/asset-manager/shared.ts index 5d01627410..f3a8cd5682 100644 --- a/cocos/core/asset-manager/shared.ts +++ b/cocos/core/asset-manager/shared.ts @@ -100,6 +100,7 @@ export const pipeline = new Pipeline('normal load', []); export const fetchPipeline = new Pipeline('fetch', []); export const transformPipeline = new Pipeline('transform url', []); export const references = EDITOR ? new Cache() : null; +export const assetsOverrideMap = new Map(); export enum RequestType { diff --git a/cocos/core/asset-manager/url-transformer.ts b/cocos/core/asset-manager/url-transformer.ts index 87cc0818d8..be1d2fdf71 100644 --- a/cocos/core/asset-manager/url-transformer.ts +++ b/cocos/core/asset-manager/url-transformer.ts @@ -23,13 +23,15 @@ THE SOFTWARE. */ +import { EDITOR } from 'internal:constants'; import { legacyCC } from '../global-exports'; +import { warnID } from '../platform/debug'; import { js } from '../utils/js'; import * as path from '../utils/path'; import Config, { IAddressableInfo, IAssetInfo } from './config'; import { decodeUuid } from './helper'; import RequestItem from './request-item'; -import { bundles, presets, RequestType } from './shared'; +import { assetsOverrideMap, bundles, presets, RequestType } from './shared'; import Task from './task'; const infos: IAddressableInfo[] = []; @@ -157,6 +159,38 @@ export function parse (task: Task) { return null; } +export function replaceOverrideAsset (task: Task) { + const input = task.output = task.input; + for (let i = 0; i < input.length; i++) { + const item = input[i] as RequestItem; + if (assetsOverrideMap.has(item.uuid)) { + const uuid = assetsOverrideMap.get(item.uuid)!; + if (EDITOR) { + // In EDITOR, there is no bundle, so just change uuid. + item.overrideUuid = uuid; + item.ext = item.isNative ? item.ext : '.json'; + continue; + } + const bundle = bundles.find((bundle) => !!bundle.getAssetInfo(uuid)); + if (bundle) { + item.overrideUuid = uuid; + let config = bundle.config; + let info = config.getAssetInfo(uuid); + if (info && info.redirect) { + if (!bundles.has(info.redirect)) { throw new Error(`Please load bundle ${info.redirect} first`); } + config = bundles.get(info.redirect)!.config; + info = config.getAssetInfo(uuid); + } + item.config = config; + item.info = info; + item.ext = item.isNative ? item.ext : (info?.extension || '.json'); + } else { + warnID(16201, uuid, item.uuid); + } + } + } +} + export function combine (task: Task) { const input = task.output = task.input; for (let i = 0; i < input.length; i++) { @@ -172,7 +206,7 @@ export function combine (task: Task) { base = (config && config.importBase) ? (config.base + config.importBase) : legacyCC.assetManager.generalImportBase; } - const uuid = item.uuid; + const uuid = item.overrideUuid || item.uuid; let ver = ''; if (item.info) { diff --git a/cocos/core/root.jsb.ts b/cocos/core/root.jsb.ts index 289db2f71f..c280f3f60a 100644 --- a/cocos/core/root.jsb.ts +++ b/cocos/core/root.jsb.ts @@ -5,6 +5,7 @@ import { DataPoolManager } from '../3d/skeletal-animation/data-pool-manager'; import { Device, deviceManager } from '../gfx'; import { DebugView } from './pipeline/debug-view'; import { buildDeferredLayout, buildForwardLayout } from './pipeline/custom/effect'; +import { settings, Settings } from './settings'; declare const nr: any; declare const jsb: any; @@ -97,6 +98,8 @@ rootProto._ctor = function (device: Device) { rootProto.initialize = function (info: IRootInfo) { // TODO: this._initialize(deviceManager.swapchain); + const customJointTextureLayouts = settings.querySettings(Settings.Category.ANIMATION, 'customJointTextureLayouts') || []; + this._dataPoolMgr?.jointTexturePool.registerCustomTextureLayouts(customJointTextureLayouts); }; rootProto.createModel = function (ModelCtor) { @@ -220,4 +223,4 @@ rootProto.removeBatch = function (batch) { rootProto.removeBatches = function () { console.error('The Draw Batch class is implemented differently in the native platform and does not support this interface.'); -} \ No newline at end of file +} diff --git a/cocos/core/utils/deprecated-3.6.0.ts b/cocos/core/utils/deprecated-3.6.0.ts index 9f44ff1908..34da21b757 100644 --- a/cocos/core/utils/deprecated-3.6.0.ts +++ b/cocos/core/utils/deprecated-3.6.0.ts @@ -1,3 +1,28 @@ +/* + Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + import { deprecateModuleExportedName } from './x-deprecated'; deprecateModuleExportedName({ diff --git a/cocos/input/deprecated-3.3.0.ts b/cocos/input/deprecated-3.3.0.ts index 076adb430f..7173e4f69d 100644 --- a/cocos/input/deprecated-3.3.0.ts +++ b/cocos/input/deprecated-3.3.0.ts @@ -1,3 +1,28 @@ +/* + Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + import { deprecateModuleExportedName } from '../core/utils/x-deprecated'; deprecateModuleExportedName({ diff --git a/cocos/input/deprecated-3.4.0.ts b/cocos/input/deprecated-3.4.0.ts index ddd9001a10..8bd09af4e5 100644 --- a/cocos/input/deprecated-3.4.0.ts +++ b/cocos/input/deprecated-3.4.0.ts @@ -1,3 +1,28 @@ +/* + Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + import { deprecateModuleExportedName } from '../core/utils/x-deprecated'; deprecateModuleExportedName({ diff --git a/cocos/native-binding/impl.ts b/cocos/native-binding/impl.ts index 1b95baf61d..290976ec13 100644 --- a/cocos/native-binding/impl.ts +++ b/cocos/native-binding/impl.ts @@ -124,6 +124,18 @@ if( NATIVE ){ globalJsb.__JsbBridgeWrapper = value; }, }); + const originSaveImageData = globalJsb.saveImageData; + globalJsb.saveImageData = (data: Uint8Array, width: number, height: number, filePath: string) => { + return new Promise((resolve, reject) => { + originSaveImageData(data, width, height, filePath, (isSuccess) => { + if (isSuccess) { + resolve(); + } else { + reject(); + } + }) + }); + } } export const native = { @@ -140,4 +152,5 @@ export const native = { AssetsManager: globalJsb.AssetsManager, EventAssetsManager: globalJsb.EventAssetsManager, Manifest: globalJsb.Manifest, + saveImageData: globalJsb.saveImageData, }; diff --git a/cocos/native-binding/index.ts b/cocos/native-binding/index.ts index 8b627c6207..6e4ccedc67 100644 --- a/cocos/native-binding/index.ts +++ b/cocos/native-binding/index.ts @@ -1332,4 +1332,37 @@ export declare namespace native { */ export function removeAllListeners(); } + /** + * @en Save the image to the path indicated. + * @zh 保存图片到指定路径。 + * @param data : @en the image data, should be raw data array with uint8 @zh 图片数据, 应为原始数据数组,uint8 格式。 + * @param path : @en the path to save @zh 保存路径 + * @param width : @en the width of the image @zh 图片宽度 + * @param height : @en the height of the image @zh 图片高度 + * @param filePath : @en the file path of the image @zh 图片文件路径 + * @param callback : @en the callback function @zh 回调函数 + * @example + * ```ts + let renderTexture = new RenderTexture(); + let renderWindowInfo = { + width: this._width, + height: this._height + }; + renderTexture.reset(renderWindowInfo); + cameras.forEach((camera: any) => { + camera.targetTexture = renderTexture; + }); + await this.waitForNextFrame(); + cameras.forEach((camera: any) => { + camera.targetTexture = null; + }); + let pixelData = renderTexture.readPixels(); + jsb.saveImageData(pixelData, path, width, height, filePath, (isSuccess) => { + if (isSuccess) { + console.log('save image success'); + } else { + console.log('save image failed'); + })); + */ + export function saveImageData(data: Uint8Array, width: number, height: number, filePath: string): Promise; } diff --git a/cocos/particle-2d/particle-system-2d.ts b/cocos/particle-2d/particle-system-2d.ts index f068053337..e4ca20fec4 100644 --- a/cocos/particle-2d/particle-system-2d.ts +++ b/cocos/particle-2d/particle-system-2d.ts @@ -502,6 +502,7 @@ export class ParticleSystem2D extends UIRenderer { public set positionType (val) { this._positionType = val; this._updateMaterial(); + this._updatePositionType(); } /** @@ -750,6 +751,7 @@ export class ParticleSystem2D extends UIRenderer { public onEnable () { super.onEnable(); this._updateMaterial(); + this._updatePositionType(); } public onDestroy () { @@ -1166,6 +1168,9 @@ export class ParticleSystem2D extends UIRenderer { public _updateMaterial () { const mat = this.getMaterialInstance(0); if (mat) mat.recompileShaders({ USE_LOCAL: this._positionType !== PositionType.FREE }); + if (mat && mat.passes.length > 0) { + this._updateBlendFunc(); + } } /** @@ -1187,7 +1192,7 @@ export class ParticleSystem2D extends UIRenderer { } protected _canRender () { - return super._canRender() && !this._stopped && this._renderSpriteFrame !== null; + return super._canRender() && !this._stopped && this._renderSpriteFrame !== null && this._renderSpriteFrame !== undefined; } protected _render (render: IBatcher) { @@ -1199,4 +1204,17 @@ export class ParticleSystem2D extends UIRenderer { render.commitComp(this, this._simulator.renderData, this._renderSpriteFrame, this._assembler, null); } } + + protected _updatePositionType () { + if (this._positionType === PositionType.RELATIVE) { + this._renderEntity.setRenderTransform(this.node.parent); + this._renderEntity.setUseLocal(true); + } else if (this.positionType === PositionType.GROUPED) { + this._renderEntity.setRenderTransform(this.node); + this._renderEntity.setUseLocal(true); + } else { + this._renderEntity.setRenderTransform(null); + this._renderEntity.setUseLocal(false); + } + } } diff --git a/cocos/particle/animator/curve-range.ts b/cocos/particle/animator/curve-range.ts index 1aad3808d7..b9567e9449 100644 --- a/cocos/particle/animator/curve-range.ts +++ b/cocos/particle/animator/curve-range.ts @@ -247,9 +247,24 @@ function packTexture (data, width, height) { return texture; } -export function packCurveRangeZ (samples:number, cr: CurveRange, discrete?: boolean) { +function updateTexture (tex: Texture2D | null, data, width, height): Texture2D { + if (tex === null || width !== tex.width || height !== tex.height) { + if (tex) { + tex.destroy(); + } + tex = packTexture(data, width, height); + } else { + tex.uploadData(data); + } + return tex; +} + +export function packCurveRangeZ (tex: Texture2D | null, data: Float32Array | null, samples:number, cr: CurveRange, discrete?: boolean) { const height = evaluateHeight(cr); - const data = new Float32Array(samples * height * 4); + const len = samples * height * 4; + if (data === null || data.length !== len) { + data = new Float32Array(samples * height * 4); + } const interval = 1.0 / (samples - 1); let sum = 0; let average = 0; @@ -269,11 +284,14 @@ export function packCurveRangeZ (samples:number, cr: CurveRange, discrete?: bool offset += 4; } } - return packTexture(data, samples, height); + return { texture: updateTexture(tex, data, samples, height), texdata: data }; } -export function packCurveRangeN (samples:number, cr: CurveRange, discrete?: boolean) { +export function packCurveRangeN (tex: Texture2D | null, data: Float32Array | null, samples:number, cr: CurveRange, discrete?: boolean) { const height = evaluateHeight(cr); - const data = new Float32Array(samples * height * 4); + const len = samples * height * 4; + if (data === null || data.length !== len) { + data = new Float32Array(samples * height * 4); + } const interval = 1.0 / (samples - 1); let sum = 0; let average = 0; @@ -294,12 +312,16 @@ export function packCurveRangeN (samples:number, cr: CurveRange, discrete?: bool offset += 4; } } - return packTexture(data, samples, height); + return { texture: updateTexture(tex, data, samples, height), texdata: data }; } -export function packCurveRangeXY (samples: number, x: CurveRange, y: CurveRange, discrete?: boolean) { +// eslint-disable-next-line max-len +export function packCurveRangeXY (tex: Texture2D | null, data: Float32Array | null, samples: number, x: CurveRange, y: CurveRange, discrete?: boolean) { const height = Math.max(evaluateHeight(x), evaluateHeight(y)); - const data = new Float32Array(samples * height * 4); + const len = samples * height * 4; + if (data === null || data.length !== len) { + data = new Float32Array(samples * height * 4); + } const curves: CurveRange[] = [x, y]; const interval = 1.0 / (samples - 1); @@ -320,12 +342,16 @@ export function packCurveRangeXY (samples: number, x: CurveRange, y: CurveRange, } } } - return packTexture(data, samples, height); + return { texture: updateTexture(tex, data, samples, height), texdata: data }; } -export function packCurveRangeXYZ (samples: number, x: CurveRange, y: CurveRange, z: CurveRange, discrete?: boolean) { +// eslint-disable-next-line max-len +export function packCurveRangeXYZ (tex: Texture2D | null, data: Float32Array | null, samples: number, x: CurveRange, y: CurveRange, z: CurveRange, discrete?: boolean) { const height = Math.max(evaluateHeight(x), evaluateHeight(y), evaluateHeight(z)); - const data = new Float32Array(samples * height * 4); + const len = samples * height * 4; + if (data === null || data.length !== len) { + data = new Float32Array(samples * height * 4); + } const curves: CurveRange[] = [x, y, z]; const interval = 1.0 / (samples - 1); @@ -346,12 +372,16 @@ export function packCurveRangeXYZ (samples: number, x: CurveRange, y: CurveRange } } } - return packTexture(data, samples, height); + return { texture: updateTexture(tex, data, samples, height), texdata: data }; } -export function packCurveRangeXYZW (samples: number, x: CurveRange, y: CurveRange, z: CurveRange, w: CurveRange, discrete?: boolean) { +// eslint-disable-next-line max-len +export function packCurveRangeXYZW (tex: Texture2D | null, data: Float32Array | null, samples: number, x: CurveRange, y: CurveRange, z: CurveRange, w: CurveRange, discrete?: boolean) { const height = Math.max(evaluateHeight(x), evaluateHeight(y), evaluateHeight(z), evaluateHeight(w)); - const data = new Float32Array(samples * height * 4); + const len = samples * height * 4; + if (data === null || data.length !== len) { + data = new Float32Array(samples * height * 4); + } const curves: CurveRange[] = [x, y, z, w]; const interval = 1.0 / (samples - 1); @@ -372,5 +402,5 @@ export function packCurveRangeXYZW (samples: number, x: CurveRange, y: CurveRang } } } - return packTexture(data, samples, height); + return { texture: updateTexture(tex, data, samples, height), texdata: data }; } diff --git a/cocos/particle/animator/gradient-range.ts b/cocos/particle/animator/gradient-range.ts index a19c8dbe05..cba4449a9e 100644 --- a/cocos/particle/animator/gradient-range.ts +++ b/cocos/particle/animator/gradient-range.ts @@ -171,9 +171,12 @@ function evaluateHeight (gr: GradientRange) { return 1; } } -export function packGradientRange (samples: number, gr: GradientRange) { +export function packGradientRange (tex: Texture2D | null, data: Uint8Array | null, samples: number, gr: GradientRange) { const height = evaluateHeight(gr); - const data = new Uint8Array(samples * height * 4); + const len = samples * height * 4; + if (data === null || data.length !== len) { + data = new Uint8Array(samples * height * 4); + } const interval = 1.0 / (samples); let offset = 0; @@ -188,11 +191,16 @@ export function packGradientRange (samples: number, gr: GradientRange) { } } - const texture = new Texture2D(); - texture.create(samples, height, PixelFormat.RGBA8888); - texture.setFilters(Filter.LINEAR, Filter.LINEAR); - texture.setWrapMode(WrapMode.CLAMP_TO_EDGE, WrapMode.CLAMP_TO_EDGE); - texture.uploadData(data); + if (tex === null || samples !== tex.width || height !== tex.height) { + if (tex) { + tex.destroy(); + } + tex = new Texture2D(); + tex.create(samples, height, PixelFormat.RGBA8888); + tex.setFilters(Filter.LINEAR, Filter.LINEAR); + tex.setWrapMode(WrapMode.CLAMP_TO_EDGE, WrapMode.CLAMP_TO_EDGE); + } + tex.uploadData(data); - return texture; + return { texture: tex, texdata: data }; } diff --git a/cocos/particle/animator/noise-module.ts b/cocos/particle/animator/noise-module.ts index 1e8251d68a..9132a9573b 100644 --- a/cocos/particle/animator/noise-module.ts +++ b/cocos/particle/animator/noise-module.ts @@ -234,6 +234,8 @@ export class NoiseModule extends ParticleModuleBase { private noise: ParticleNoise = new ParticleNoise(); + private samplePosition: Vec3 = new Vec3(); + public animate (particle: Particle, dt: number) { this.noise.setTime(particle.particleSystem.time); this.noise.setSpeed(this.noiseSpeedX, this.noiseSpeedY, this.noiseSpeedZ); @@ -241,7 +243,10 @@ export class NoiseModule extends ParticleModuleBase { this.noise.setAbs(this.remapX, this.remapY, this.remapZ); this.noise.setAmplititude(this.strengthX, this.strengthY, this.strengthZ); this.noise.setOctaves(this.octaves, this.octaveMultiplier, this.octaveScale); - this.noise.setSamplePoint(particle.position); + + this.samplePosition.set(particle.position); + this.samplePosition.add3f(Math.random() * 1.0, Math.random() * 1.0, Math.random() * 1.0); + this.noise.setSamplePoint(this.samplePosition); this.noise.getNoiseParticle(); const noisePosition: Vec3 = this.noise.getResult(); diff --git a/cocos/particle/models/particle-batch-model.ts b/cocos/particle/models/particle-batch-model.ts index 84a5b97e11..125fc9ecf7 100644 --- a/cocos/particle/models/particle-batch-model.ts +++ b/cocos/particle/models/particle-batch-model.ts @@ -490,6 +490,7 @@ export default class ParticleBatchModel extends scene.Model { this._vdataF32![idx++] = p.rotation.x; this._vdataF32![idx++] = p.rotation.y; this._vdataF32![idx++] = p.rotation.z; + this._vdataF32![idx++] = p.randomSeed; this._vdataF32![idx++] = p.startColor.r / 255.0; this._vdataF32![idx++] = p.startColor.g / 255.0; @@ -501,8 +502,6 @@ export default class ParticleBatchModel extends scene.Model { this._vdataF32![idx++] = p.velocity.z; this._vdataF32![idx++] = p.startLifetime; - this._vdataF32![idx++] = p.randomSeed; - offset += this._vertAttrsFloatCount; } diff --git a/cocos/particle/particle-system.ts b/cocos/particle/particle-system.ts index 76cc6f685b..bc74efac1c 100644 --- a/cocos/particle/particle-system.ts +++ b/cocos/particle/particle-system.ts @@ -795,7 +795,9 @@ export class ParticleSystem extends ModelRenderer { // HACK, TODO this.renderer.onInit(this); if (this._shapeModule) this._shapeModule.onInit(this); - if (this._trailModule) this._trailModule.onInit(this); + if (this._trailModule && !this.renderer.useGPU) { + this._trailModule.onInit(this); + } this.bindModule(); this._resetPosition(); @@ -996,7 +998,6 @@ export class ParticleSystem extends ModelRenderer { this._trailModule._detachFromScene(); } } - legacyCC.director.off(legacyCC.Director.EVENT_BEFORE_COMMIT, this.beforeRender, this); // this._system.remove(this); this.processor.onDestroy(); diff --git a/cocos/particle/renderer/particle-system-renderer-base.ts b/cocos/particle/renderer/particle-system-renderer-base.ts index 0191c90b92..f6cc884ba7 100644 --- a/cocos/particle/renderer/particle-system-renderer-base.ts +++ b/cocos/particle/renderer/particle-system-renderer-base.ts @@ -44,6 +44,7 @@ export interface IParticleSystemRenderer { attachToScene (): void; detachFromScene (): void; updateMaterialParams (): void; + updateVertexAttrib (): void; setVertexAttributes (): void; updateRenderMode (): void; onMaterialModified (index: number, material: Material): void; @@ -132,6 +133,7 @@ export abstract class ParticleSystemRendererBase implements IParticleSystemRende public setVertexAttributes () { if (this._model) { + this.updateVertexAttrib(); this._model.setVertexAttributes(this._renderInfo!.renderMode === RenderMode.Mesh ? this._renderInfo!.mesh : null, this._vertAttrs); } } @@ -158,6 +160,7 @@ export abstract class ParticleSystemRendererBase implements IParticleSystemRende public abstract getFreeParticle (): Particle | null; public abstract onMaterialModified (index: number, material: Material) : void; public abstract onRebuildPSO (index: number, material: Material) : void; + public abstract updateVertexAttrib (): void; public abstract updateRenderMode () : void; public abstract updateMaterialParams () : void; public abstract setNewParticle (p: Particle): void; diff --git a/cocos/particle/renderer/particle-system-renderer-cpu.ts b/cocos/particle/renderer/particle-system-renderer-cpu.ts index 54bd504334..c6fe8d2602 100644 --- a/cocos/particle/renderer/particle-system-renderer-cpu.ts +++ b/cocos/particle/renderer/particle-system-renderer-cpu.ts @@ -26,7 +26,7 @@ import { EDITOR } from 'internal:constants'; import { builtinResMgr } from '../../core/builtin'; import { Material } from '../../core/assets'; -import { AttributeName, Format, Attribute } from '../../gfx'; +import { AttributeName, Format, Attribute, FormatInfos } from '../../gfx'; import { Mat4, Vec2, Vec3, Vec4, pseudoRandom, Quat } from '../../core/math'; import { RecyclePool } from '../../core/memop'; import { MaterialInstance, IMaterialInstanceInfo } from '../../core/renderer/core/material-instance'; @@ -568,6 +568,28 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas this._model!.addParticleVertexData(i, this._attrs); } + public updateVertexAttrib () { + if (this._renderInfo!.renderMode !== RenderMode.Mesh) { + return; + } + if (this._renderInfo!.mesh) { + const format = this._renderInfo!.mesh.readAttributeFormat(0, AttributeName.ATTR_COLOR); + if (format) { + let type = Format.RGBA8; + for (let i = 0; i < FormatInfos.length; ++i) { + if (FormatInfos[i].name === format.name) { + type = i; + break; + } + } + this._vertAttrs[7] = new Attribute(AttributeName.ATTR_COLOR1, type, true, !this._useInstance ? 0 : 1); + } else { // mesh without vertex color + const type = Format.RGBA8; + this._vertAttrs[7] = new Attribute(AttributeName.ATTR_COLOR1, type, true, !this._useInstance ? 0 : 1); + } + } + } + private _setVertexAttrib () { if (!this._useInstance) { switch (this._renderInfo!.renderMode) { @@ -608,10 +630,6 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas if (shareMaterial != null) { const effectName = shareMaterial._effectAsset._name; this._renderInfo!.mainTexture = shareMaterial.getProperty('mainTexture', 0); - // reset material - if (effectName.indexOf('builtin-particle') === -1 || effectName.indexOf('builtin-particle-gpu') !== -1) { - ps.setMaterial(null, 0); - } } if (ps.sharedMaterial == null && this._defaultMat == null) { diff --git a/cocos/particle/renderer/particle-system-renderer-gpu.ts b/cocos/particle/renderer/particle-system-renderer-gpu.ts index 81f0cc88aa..6ea1772c10 100644 --- a/cocos/particle/renderer/particle-system-renderer-gpu.ts +++ b/cocos/particle/renderer/particle-system-renderer-gpu.ts @@ -28,7 +28,7 @@ import { builtinResMgr } from '../../core/builtin'; import { Material } from '../../core/assets'; import { Texture2D } from '../../core'; import { Component } from '../../core/components'; -import { AttributeName, Format, Attribute, API, deviceManager } from '../../gfx'; +import { AttributeName, Format, Attribute, API, deviceManager, FormatInfos } from '../../gfx'; import { Mat4, Vec2, Vec4, Quat, Vec3 } from '../../core/math'; import { MaterialInstance, IMaterialInstanceInfo } from '../../core/renderer/core/material-instance'; import { MacroRecord } from '../../core/renderer/core/pass-utils'; @@ -76,7 +76,7 @@ const _vert_attr_name = { DIR_LIFE: 'a_dir_life', RANDOM_SEED: 'a_rndSeed', VERT_SIZE_FID: 'a_size_fid', - VERT_ROTATION: 'a_rotation', + VERT_ROTATION_RND: 'a_rotation_rnd', VERT_UV: 'a_uv', }; @@ -105,20 +105,18 @@ const _gpu_vert_attr_mesh = [ const _gpu_vert_attr_ins = [ new Attribute(_vert_attr_name.POSITION_STARTTIME, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.VERT_SIZE_FID, Format.RGBA32F, false, 0, true), - new Attribute(_vert_attr_name.VERT_ROTATION, Format.RGB32F, false, 0, true), + new Attribute(_vert_attr_name.VERT_ROTATION_RND, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.COLOR, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.DIR_LIFE, Format.RGBA32F, false, 0, true), - new Attribute(_vert_attr_name.RANDOM_SEED, Format.R32F, false, 0, true), new Attribute(_vert_attr_name.VERT_UV, Format.RGB32F, false, 1), ]; const _gpu_vert_attr_mesh_ins = [ new Attribute(_vert_attr_name.POSITION_STARTTIME, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.VERT_SIZE_FID, Format.RGBA32F, false, 0, true), - new Attribute(_vert_attr_name.VERT_ROTATION, Format.RGB32F, false, 0, true), + new Attribute(_vert_attr_name.VERT_ROTATION_RND, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.COLOR, Format.RGBA32F, false, 0, true), new Attribute(_vert_attr_name.DIR_LIFE, Format.RGBA32F, false, 0, true), - new Attribute(_vert_attr_name.RANDOM_SEED, Format.R32F, false, 0, true), new Attribute(AttributeName.ATTR_TEX_COORD, Format.RGB32F, false, 1), // mesh uv new Attribute(AttributeName.ATTR_TEX_COORD3, Format.RGB32F, false, 1), // mesh position new Attribute(AttributeName.ATTR_NORMAL, Format.RGB32F, false, 1), // mesh normal @@ -147,6 +145,12 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas private _rotationTexture: Texture2D | null = null; private _sizeTexture: Texture2D | null = null; private _animTexture: Texture2D | null = null; + private _colorData: Uint8Array | null = null; + private _forceData: Float32Array | null = null; + private _velocityData: Float32Array | null = null; + private _rotationData: Float32Array | null = null; + private _sizeData: Float32Array | null = null; + private _animData: Float32Array | null = null; private _uTimeHandle = 0; private _uRotHandle = 0; private _uNodeRotHandle = 0; @@ -207,6 +211,12 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas if (this._sizeTexture) this._sizeTexture.destroy(); if (this._rotationTexture) this._rotationTexture.destroy(); if (this._animTexture) this._animTexture.destroy(); + this._forceData = null; + this._velocityData = null; + this._colorData = null; + this._sizeData = null; + this._rotationData = null; + this._animData = null; } public enableModule (name: string, val: boolean, pm: IParticleModule) { @@ -368,8 +378,9 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas enable = forceModule && forceModule.enable; this._defines[FORCE_OVER_TIME_MODULE_ENABLE] = enable; if (enable) { - if (this._forceTexture) this._forceTexture.destroy(); - this._forceTexture = packCurveRangeXYZ(_sample_num, forceModule.x, forceModule.y, forceModule.z); + const packed = packCurveRangeXYZ(this._forceTexture, this._forceData, _sample_num, forceModule.x, forceModule.y, forceModule.z); + this._forceTexture = packed.texture; + this._forceData = packed.texdata; const handle = pass.getHandle('force_over_time_tex0'); const binding = Pass.getBindingFromHandle(handle); pass.bindSampler(binding, this._forceTexture.getGFXSampler()!); @@ -385,9 +396,10 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas enable = velocityModule && velocityModule.enable; this._defines[VELOCITY_OVER_TIME_MODULE_ENABLE] = enable; if (enable) { - if (this._velocityTexture) this._velocityTexture.destroy(); - this._velocityTexture = packCurveRangeXYZW(_sample_num, velocityModule.x, velocityModule.y, + const packed = packCurveRangeXYZW(this._velocityTexture, this._velocityData, _sample_num, velocityModule.x, velocityModule.y, velocityModule.z, velocityModule.speedModifier); + this._velocityTexture = packed.texture; + this._velocityData = packed.texdata; const handle = pass.getHandle('velocity_over_time_tex0'); const binding = Pass.getBindingFromHandle(handle); pass.bindSampler(binding, this._velocityTexture.getGFXSampler()!); @@ -403,8 +415,9 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas enable = colorModule && colorModule.enable; this._defines[COLOR_OVER_TIME_MODULE_ENABLE] = enable; if (enable) { - if (this._colorTexture) this._colorTexture.destroy(); - this._colorTexture = packGradientRange(_sample_num, colorModule.color); + const packed = packGradientRange(this._colorTexture, this._colorData, _sample_num, colorModule.color); + this._colorTexture = packed.texture; + this._colorData = packed.texdata; const handle = pass.getHandle('color_over_time_tex0'); const binding = Pass.getBindingFromHandle(handle); pass.bindSampler(binding, this._colorTexture.getGFXSampler()!); @@ -418,18 +431,23 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas enable = roationModule && roationModule.enable; this._defines[ROTATION_OVER_TIME_MODULE_ENABLE] = enable; if (enable) { - if (this._rotationTexture) this._rotationTexture.destroy(); + let packed; if (roationModule.separateAxes) { - this._rotationTexture = packCurveRangeXYZ(_sample_num, roationModule.x, roationModule.y, roationModule.z); + // eslint-disable-next-line max-len + packed = packCurveRangeXYZ(this._rotationTexture, this._rotationData, _sample_num, roationModule.x, roationModule.y, roationModule.z); } else { - this._rotationTexture = packCurveRangeZ(_sample_num, roationModule.z); + packed = packCurveRangeZ(this._rotationTexture, this._rotationData, _sample_num, roationModule.z); + } + this._rotationTexture = packed.texture; + this._rotationData = packed.texdata; + if (this._rotationTexture) { + const handle = pass.getHandle('rotation_over_time_tex0'); + const binding = Pass.getBindingFromHandle(handle); + pass.bindSampler(binding, this._rotationTexture.getGFXSampler()!); + pass.bindTexture(binding, this._rotationTexture.getGFXTexture()!); + const modeHandle = pass.getHandle('u_rotation_mode'); + pass.setUniform(modeHandle, this._rotationTexture.height); } - const handle = pass.getHandle('rotation_over_time_tex0'); - const binding = Pass.getBindingFromHandle(handle); - pass.bindSampler(binding, this._rotationTexture.getGFXSampler()!); - pass.bindTexture(binding, this._rotationTexture.getGFXTexture()!); - const modeHandle = pass.getHandle('u_rotation_mode'); - pass.setUniform(modeHandle, this._rotationTexture.height); } // size module @@ -437,18 +455,22 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas enable = sizeModule && sizeModule.enable; this._defines[SIZE_OVER_TIME_MODULE_ENABLE] = enable; if (enable) { - if (this._sizeTexture) this._sizeTexture.destroy(); + let packed; if (sizeModule.separateAxes) { - this._sizeTexture = packCurveRangeXYZ(_sample_num, sizeModule.x, sizeModule.y, sizeModule.z, true); + packed = packCurveRangeXYZ(this._sizeTexture, this._sizeData, _sample_num, sizeModule.x, sizeModule.y, sizeModule.z, true); } else { - this._sizeTexture = packCurveRangeN(_sample_num, sizeModule.size, true); + packed = packCurveRangeN(this._sizeTexture, this._sizeData, _sample_num, sizeModule.size, true); + } + this._sizeTexture = packed.texture; + this._sizeData = packed.texdata; + if (this._sizeTexture) { + const handle = pass.getHandle('size_over_time_tex0'); + const binding = Pass.getBindingFromHandle(handle); + pass.bindSampler(binding, this._sizeTexture.getGFXSampler()!); + pass.bindTexture(binding, this._sizeTexture.getGFXTexture()!); + const modeHandle = pass.getHandle('u_size_mode'); + pass.setUniform(modeHandle, this._sizeTexture.height); } - const handle = pass.getHandle('size_over_time_tex0'); - const binding = Pass.getBindingFromHandle(handle); - pass.bindSampler(binding, this._sizeTexture.getGFXSampler()!); - pass.bindTexture(binding, this._sizeTexture.getGFXTexture()!); - const modeHandle = pass.getHandle('u_size_mode'); - pass.setUniform(modeHandle, this._sizeTexture.height); } // texture module @@ -456,8 +478,10 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas enable = textureModule && textureModule.enable; this._defines[TEXTURE_ANIMATION_MODULE_ENABLE] = enable; if (enable) { - if (this._animTexture) this._animTexture.destroy(); - this._animTexture = packCurveRangeXY(_sample_num, textureModule.startFrame, textureModule.frameOverTime, true); + // eslint-disable-next-line max-len + const packed = packCurveRangeXY(this._animTexture, this._animData, _sample_num, textureModule.startFrame, textureModule.frameOverTime, true); + this._animTexture = packed.texture; + this._animData = packed.texdata; const handle = pass.getHandle('texture_animation_tex0'); const binding = Pass.getBindingFromHandle(handle); pass.bindSampler(binding, this._animTexture.getGFXSampler()!); @@ -490,6 +514,28 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas } } + public updateVertexAttrib () { + if (this._renderInfo!.renderMode !== RenderMode.Mesh) { + return; + } + if (this._renderInfo!.mesh) { + const format = this._renderInfo!.mesh.readAttributeFormat(0, AttributeName.ATTR_COLOR); + if (format) { + let type = Format.RGBA8; + for (let i = 0; i < FormatInfos.length; ++i) { + if (FormatInfos[i].name === format.name) { + type = i; + break; + } + } + this._vertAttrs[9] = new Attribute(AttributeName.ATTR_COLOR1, type, true, !this._useInstance ? 0 : 1); + } else { // mesh without vertex color + const type = Format.RGBA8; + this._vertAttrs[9] = new Attribute(AttributeName.ATTR_COLOR1, type, true, !this._useInstance ? 0 : 1); + } + } + } + private _setVertexAttrib () { if (!this._useInstance) { switch (this._renderInfo!.renderMode) { @@ -529,11 +575,6 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas if (shareMaterial !== null) { const effectName = shareMaterial._effectAsset._name; this._renderInfo!.mainTexture = shareMaterial.getProperty('mainTexture', 0); - if (effectName.indexOf('builtin-particle-gpu') === -1) { - this._renderInfo!.mainTexture = shareMaterial.getProperty('mainTexture', 0); - // reset material - this._particleSystem.setMaterial(null, 0); - } } if (ps.sharedMaterial == null && this._defaultMat == null) { diff --git a/cocos/particle/renderer/trail.ts b/cocos/particle/renderer/trail.ts index f757cfe699..fff0f94b4f 100644 --- a/cocos/particle/renderer/trail.ts +++ b/cocos/particle/renderer/trail.ts @@ -38,6 +38,7 @@ import { Space, TextureMode, TrailMode } from '../enum'; import { Particle } from '../particle'; import { legacyCC } from '../../core/global-exports'; import { TransformBit } from '../../core/scene-graph/node-enum'; +import { warnID } from '../../core'; const PRE_TRIANGLE_INDEX = 1; const NEXT_TRIANGLE_INDEX = 1 << 2; @@ -368,7 +369,10 @@ export default class TrailModule { const b = ps.bursts[i]; burstCount += b.getMaxCount(ps) * Math.ceil(psTime / duration); } - this._trailNum = Math.ceil(psTime * this.lifeTime.getMax() * 60 * (psRate * duration + burstCount)); + if (this.lifeTime.getMax() < 1.0) { + warnID(6036); + } + this._trailNum = Math.ceil(psTime * Math.ceil(this.lifeTime.getMax()) * 60 * (psRate * duration + burstCount)); this._trailSegments = new Pool(() => new TrailSegment(10), Math.ceil(psRate * duration), (obj: TrailSegment) => obj.trailElements.length = 0); if (this._enable) { this.enable = this._enable; @@ -613,7 +617,9 @@ export default class TrailModule { this._fillVertexBuffer(_temp_trailEle, this.colorOverTrail.evaluate(0, 1), indexOffset, 0, trailNum, PRE_TRIANGLE_INDEX); } } - this._trailModel!.enabled = this.ibOffset > 0; + if (this._trailModel) { + this._trailModel.enabled = this.ibOffset > 0; + } } public updateIA (count: number) { @@ -675,10 +681,10 @@ export default class TrailModule { this._subMeshData = new RenderingSubMesh([vertexBuffer], this._vertAttrs, PrimitiveMode.TRIANGLE_LIST, indexBuffer, this._iaInfoBuffer); const trailModel = this._trailModel; - if (trailModel) { + if (trailModel && this._material) { trailModel.node = trailModel.transform = this._particleSystem.node; trailModel.visFlags = this._particleSystem.visibility; - trailModel.initSubModel(0, this._subMeshData, this._material!); + trailModel.initSubModel(0, this._subMeshData, this._material); trailModel.enabled = true; } } diff --git a/cocos/physics/framework/physics-selector.ts b/cocos/physics/framework/physics-selector.ts index 763c7145dc..27bffe3931 100644 --- a/cocos/physics/framework/physics-selector.ts +++ b/cocos/physics/framework/physics-selector.ts @@ -117,7 +117,7 @@ interface IPhysicsSelector { function updateLegacyMacro (id: string) { legacyCC._global.CC_PHYSICS_BUILTIN = id === 'builtin'; legacyCC._global.CC_PHYSICS_CANNON = id === 'cannon.js'; - legacyCC._global.CC_PHYSICS_AMMO = id === 'ammo.js'; + legacyCC._global.CC_PHYSICS_AMMO = id === 'bullet'; } function register (id: IPhysicsEngineId, wrapper: IPhysicsWrapperObject): void { diff --git a/cocos/spine/assembler/simple.ts b/cocos/spine/assembler/simple.ts index 5fe695b2c0..3737e7751b 100644 --- a/cocos/spine/assembler/simple.ts +++ b/cocos/spine/assembler/simple.ts @@ -1,3 +1,4 @@ +/* eslint-disable max-len */ /* Copyright (c) 2020-2022 Xiamen Yaji Software Co., Ltd. @@ -29,7 +30,7 @@ import { Batcher2D } from '../../2d/renderer/batcher-2d'; import { FrameColor } from '../skeleton-cache'; import { MaterialInstance } from '../../core/renderer'; import { SkeletonTexture } from '../skeleton-texture'; -import { vfmtPosUvColor, vfmtPosUvTwoColor } from '../../2d/renderer/vertex-format'; +import { getAttributeStride, vfmtPosUvColor4B, vfmtPosUvTwoColor4B } from '../../2d/renderer/vertex-format'; import { Skeleton, SpineMaterialType } from '../skeleton'; import { Color, director, Node, Texture2D } from '../../core'; import { BlendFactor } from '../../gfx'; @@ -37,8 +38,6 @@ import { legacyCC } from '../../core/global-exports'; import { StaticVBAccessor } from '../../2d/renderer/static-vb-accessor'; import { RenderData } from '../../2d/renderer/render-data'; -const FLAG_TWO_COLOR = 0x01; - const _quadTriangles = [0, 1, 2, 2, 3, 0]; const _slotColor = new Color(0, 0, 255, 255); const _boneColor = new Color(255, 0, 0, 255); @@ -62,8 +61,8 @@ let _nodeR: number; let _nodeG: number; let _nodeB: number; let _nodeA: number; -const _finalColor32: Float32Array = new Float32Array(4); -const _darkColor32: Float32Array = new Float32Array(4); +let _finalColor32: number; +let _darkColor32: number; let _perVertexSize: number; let _perClipVertexSize: number; @@ -80,14 +79,6 @@ let _tempg: number; let _tempb: number; let _inRange: boolean; let _mustFlush: boolean; -let _x: number; -let _y: number; -let _m00: number; -let _m04: number; -let _m12: number; -let _m01: number; -let _m05: number; -let _m13: number; let _r: number; let _g: number; let _b: number; @@ -100,10 +91,10 @@ let _dg: number; let _db: number; let _da: number; let _comp: Skeleton | undefined; -let _node: Node | undefined; let _renderData: RenderData | null; let _ibuf: Uint16Array; let _vbuf: Float32Array; +let _vUintBuf: Uint32Array; let _needColor: boolean; let _vertexEffect: spine.VertexEffect | null = null; let _currentMaterial: MaterialInstance | null = null; @@ -138,7 +129,7 @@ function _getSlotMaterial (blendMode: spine.BlendMode) { function _handleColor (color: FrameColor) { // temp rgb has multiply 255, so need divide 255; _fa = color.fa * _nodeA; - _multiplier = _premultipliedAlpha ? _fa * _inv255 : 1; + _multiplier = _premultipliedAlpha ? _fa / 255 : 1; _r = _nodeR * _multiplier; _g = _nodeG * _multiplier; _b = _nodeB * _multiplier; @@ -146,32 +137,22 @@ function _handleColor (color: FrameColor) { _fr = color.fr * _r; _fg = color.fg * _g; _fb = color.fb * _b; - _finalColor32[0] = _fr * _inv255; - _finalColor32[1] = _fg * _inv255; - _finalColor32[2] = _fb * _inv255; - _finalColor32[3] = _fa * _inv255; + _finalColor32 = ((_fa << 24) >>> 0) + (_fb << 16) + (_fg << 8) + _fr; _dr = color.dr * _r; _dg = color.dg * _g; _db = color.db * _b; - _da = _premultipliedAlpha ? 255 : 0; - _darkColor32[0] = _dr * _inv255; - _darkColor32[1] = _dg * _inv255; - _darkColor32[2] = _db * _inv255; - _darkColor32[3] = _da * _inv255; + _da = _premultipliedAlpha ? 255 : 0; + _darkColor32 = ((_da << 24) >>> 0) + (_db << 16) + (_dg << 8) + _dr; } -const _tmpColor4 = new Float32Array(4); -function _spineColorToFloat32Array4 (spineColor: spine.Color) { - _tmpColor4[0] = spineColor.r * _inv255; - _tmpColor4[1] = spineColor.g * _inv255; - _tmpColor4[2] = spineColor.b * _inv255; - _tmpColor4[3] = spineColor.a * _inv255; - return _tmpColor4; +function _spineColorToUint32 (spineColor: spine.Color) { + return ((spineColor.a << 24) >>> 0) + (spineColor.b << 16) + (spineColor.g << 8) + spineColor.r; } function _vfmtFloatSize (useTint: boolean) { - return useTint ? 3 + 2 + 4 + 4 : 3 + 2 + 4; + const attributes = useTint ? vfmtPosUvTwoColor4B : vfmtPosUvColor4B; + return getAttributeStride(attributes) >> 2; } let _accessor: StaticVBAccessor = null!; @@ -188,7 +169,7 @@ export const simple: IAssembler = { if (!accessor) { const device = director.root!.device; const batcher = director.root!.batcher2D; - const attributes = useTint ? vfmtPosUvTwoColor : vfmtPosUvColor; + const attributes = useTint ? vfmtPosUvTwoColor4B : vfmtPosUvColor4B; if (useTint) { accessor = _tintAccessor = new StaticVBAccessor(device, attributes, this.vCount); // Register to batcher so that batcher can upload buffers after batching process @@ -226,7 +207,7 @@ export const simple: IAssembler = { } } } - rd = RenderData.add(useTint ? vfmtPosUvTwoColor : vfmtPosUvColor, accessor); + rd = RenderData.add(useTint ? vfmtPosUvTwoColor4B : vfmtPosUvColor4B, accessor); rd.resize(vCount, iCount); if (!rd.indices || iCount !== rd.indices.length) { rd.indices = new Uint16Array(iCount); @@ -263,9 +244,9 @@ function updateComponentRenderData (comp: Skeleton, batcher: Batcher2D) { if (!comp._skeleton) return; const nodeColor = comp.color; - _nodeR = nodeColor.r * _inv255; - _nodeG = nodeColor.g * _inv255; - _nodeB = nodeColor.b * _inv255; + _nodeR = nodeColor.r / 255; + _nodeG = nodeColor.g / 255; + _nodeB = nodeColor.b / 255; _nodeA = comp.node._uiProps.opacity; _useTint = comp.useTint || comp.isAnimationCached(); @@ -275,7 +256,6 @@ function updateComponentRenderData (comp: Skeleton, batcher: Batcher2D) { // Reuse draw list comp.drawList.reset(); _comp = comp; - _node = comp.node; _renderData = comp.renderData!; _currentMaterial = null; @@ -306,7 +286,6 @@ function updateComponentRenderData (comp: Skeleton, batcher: Batcher2D) { comp.attachUtil._syncAttachedNode(); // Clear temp var. - _node = undefined; _comp = undefined; _vertexEffect = null; } @@ -328,6 +307,7 @@ function updateChunkForClip (clippedVertices: number[], clippedTriangles: number if (_actualVCount > rd.vertexCount) { rd.resizeAndCopy(_actualVCount, _actualICount > rd.indexCount ? _actualICount : rd.indexCount); _vbuf = rd.chunk.vb; + _vUintBuf = new Uint32Array(_vbuf.buffer); updateIBuf = true; } if (_actualICount > _ibuf.length) { @@ -382,16 +362,16 @@ function fillVertices (skeletonColor: spine.Color, _vbuf[v + 3] = _tempUv.x; // u _vbuf[v + 4] = _tempUv.y; // v - _vbuf.set(_spineColorToFloat32Array4(_finalColor), v + 5); - _vbuf.set(_spineColorToFloat32Array4(_darkColor), v + 9); // dark color + _vUintBuf[v + 5] = _spineColorToUint32(_finalColor); + _vUintBuf[v + 6] = _spineColorToUint32(_darkColor); } } else { - _finalColor32.set(_spineColorToFloat32Array4(_finalColor)); - _darkColor32.set(_spineColorToFloat32Array4(_darkColor)); + _finalColor32 = _spineColorToUint32(_finalColor); + _darkColor32 = _spineColorToUint32(_darkColor); for (let v = _vertexFloatOffset, n = _vertexFloatOffset + _vertexFloatCount; v < n; v += _perVertexSize) { - _vbuf.set(_finalColor32, v + 5); // light color - _vbuf.set(_darkColor32, v + 9); // dark color + _vUintBuf[v + 5] = _finalColor32; // light color + _vUintBuf[v + 6] = _darkColor32; // dark color } } } else { @@ -428,8 +408,8 @@ function fillVertices (skeletonColor: spine.Color, _vbuf[offset + 1] = _tempPos.y; // y _vbuf[offset + 3] = _tempUv.x; // u _vbuf[offset + 4] = _tempUv.y; // v - _vbuf.set(_spineColorToFloat32Array4(_finalColor), offset + 5); - _vbuf.set(_spineColorToFloat32Array4(_darkColor), offset + 9); + _vUintBuf[offset + 5] = _spineColorToUint32(_finalColor); + _vUintBuf[offset + 6] = _spineColorToUint32(_darkColor); } } else { // x y r g b a u v (rr gg bb aa) @@ -439,15 +419,11 @@ function fillVertices (skeletonColor: spine.Color, _vbuf[offset + 3] = clippedVertices[v + 6]; // u _vbuf[offset + 4] = clippedVertices[v + 7]; // v - _vbuf[offset + 5] = clippedVertices[v + 2] * _inv255; - _vbuf[offset + 6] = clippedVertices[v + 3] * _inv255; - _vbuf[offset + 7] = clippedVertices[v + 4] * _inv255; - _vbuf[offset + 8] = clippedVertices[v + 5] * _inv255; + _finalColor32 = ((clippedVertices[v + 5] << 24) >>> 0) + (clippedVertices[v + 4] << 16) + (clippedVertices[v + 3] << 8) + clippedVertices[v + 2]; + _vUintBuf[offset + 5] = _finalColor32; - _vbuf[offset + 9] = clippedVertices[v + 8] * _inv255; - _vbuf[offset + 10] = clippedVertices[v + 9] * _inv255; - _vbuf[offset + 11] = clippedVertices[v + 10] * _inv255; - _vbuf[offset + 12] = clippedVertices[v + 11] * _inv255; + _darkColor32 = ((clippedVertices[v + 11] << 24) >>> 0) + (clippedVertices[v + 10] << 16) + (clippedVertices[v + 9] << 8) + clippedVertices[v + 8]; + _vUintBuf[offset + 6] = _finalColor32; } } } @@ -464,15 +440,14 @@ function fillVertices (skeletonColor: spine.Color, _vbuf[v + 1] = _tempPos.y; // y _vbuf[v + 3] = _tempUv.x; // u _vbuf[v + 4] = _tempUv.y; // v - - _vbuf.set(_spineColorToFloat32Array4(_finalColor), v + 5); + _vUintBuf[v + 5] = _spineColorToUint32(_finalColor); } } else { - _finalColor32.set(_spineColorToFloat32Array4(_finalColor)); - _darkColor32.set(_spineColorToFloat32Array4(_darkColor)); + _finalColor32 = _spineColorToUint32(_finalColor); + _darkColor32 = _spineColorToUint32(_darkColor); for (let v = _vertexFloatOffset, n = _vertexFloatOffset + _vertexFloatCount; v < n; v += _perVertexSize) { - _vbuf.set(_finalColor32, v + 5); // light color + _vUintBuf[v + 5] = _finalColor32; } } } else { @@ -509,7 +484,7 @@ function fillVertices (skeletonColor: spine.Color, _vbuf[offset + 1] = _tempPos.y; // y _vbuf[offset + 3] = _tempUv.x; // u _vbuf[offset + 4] = _tempUv.y; // v - _vbuf.set(_spineColorToFloat32Array4(_finalColor), offset + 5); + _vUintBuf[offset + 5] = _spineColorToUint32(_finalColor); } } else { // x y r g b a u v (rr gg bb aa) @@ -519,10 +494,7 @@ function fillVertices (skeletonColor: spine.Color, _vbuf[offset + 3] = clippedVertices[v + 6]; // u _vbuf[offset + 4] = clippedVertices[v + 7]; // v - _vbuf[offset + 5] = clippedVertices[v + 2] * _inv255; - _vbuf[offset + 6] = clippedVertices[v + 3] * _inv255; - _vbuf[offset + 7] = clippedVertices[v + 4] * _inv255; - _vbuf[offset + 8] = clippedVertices[v + 5] * _inv255; + _vUintBuf[offset + 5] = ((clippedVertices[v + 5] << 24) >>> 0) + (clippedVertices[v + 4] << 16) + (clippedVertices[v + 3] << 8) + clippedVertices[v + 2]; } } } @@ -531,6 +503,7 @@ function fillVertices (skeletonColor: spine.Color, function realTimeTraverse (batcher: Batcher2D) { const rd = _renderData!; _vbuf = rd.chunk.vb; + _vUintBuf = new Uint32Array(_vbuf.buffer); _ibuf = rd.indices!; _actualVCount = _comp!.maxVertexCount; _actualICount = _comp!.maxIndexCount; @@ -820,15 +793,15 @@ function cacheTraverse () { if (_needColor) { // handle color // tip: step of frameColorOffset should fix with vertex attributes, (xyzuvrgbargba--xyuvcc) - let frameColorOffset = frameVFOffset / 13 * 6; + let frameColorOffset = frameVFOffset / 7 * 6; for (let ii = frameVFOffset, iEnd = frameVFOffset + segVFCount; ii < iEnd; ii += _perVertexSize, frameColorOffset += 6) { if (frameColorOffset >= maxVFOffset) { nowColor = colors[colorOffset++]; _handleColor(nowColor); maxVFOffset = nowColor.vfOffset; } - vbuf.set(_finalColor32, ii + 5); - vbuf.set(_darkColor32, ii + 9); + _vUintBuf[ii + 5] = _finalColor32; + _vUintBuf[ii + 6] = _darkColor32; } } diff --git a/cocos/spine/skeleton-cache.ts b/cocos/spine/skeleton-cache.ts index 525c332dc5..cf05b1e6bd 100644 --- a/cocos/spine/skeleton-cache.ts +++ b/cocos/spine/skeleton-cache.ts @@ -51,7 +51,7 @@ const PerVertexSize = 6; // x y u v r1 g1 b1 a1 r2 g2 b2 a2 const PerClipVertexSize = 12; // x y z / u v / r g b a/ r g b a -const ExportVertexSize = 13; +const ExportVertexSize = 7; let _vfCount = 0; let _indexCount = 0; @@ -407,13 +407,14 @@ export class AnimationCache { if (!vertices || vertices.length < copyOutVerticeSize) { vertices = frame.vertices = new Float32Array(copyOutVerticeSize); } + const intVbuf = new Uint32Array(vertices.buffer); for (let i = 0, j = 0; i < copyOutVerticeSize;) { vertices[i] = _vertices[j++]; // x vertices[i + 1] = _vertices[j++]; // y vertices[i + 3] = _vertices[j++]; // u vertices[i + 4] = _vertices[j++]; // v - this._setVerticeColor(_vertices[j++], vertices, i + 5); - this._setVerticeColor(_vertices[j++], vertices, i + 9); + intVbuf[i + 5] = _vertices[j++]; + intVbuf[i + 6] = _vertices[j++]; i += ExportVertexSize; } @@ -599,12 +600,12 @@ export class AnimationCache { clipper.clipEnd(); } - private _setVerticeColor (colorI32: number, buffer: Float32Array, offset: number) { - buffer[offset] = (colorI32 & 0xff) / 255.0; - buffer[offset + 1] = ((colorI32 >> 8) & 0xff) / 255.0; - buffer[offset + 2] = ((colorI32 >> 16) & 0xff) / 255.0; - buffer[offset + 3] = ((colorI32 >> 24) & 0xff) / 255.0; - } + // private _setVerticeColor (colorI32: number, buffer: Float32Array, offset: number) { + // buffer[offset] = (colorI32 & 0xff) / 255.0; + // buffer[offset + 1] = ((colorI32 >> 8) & 0xff) / 255.0; + // buffer[offset + 2] = ((colorI32 >> 16) & 0xff) / 255.0; + // buffer[offset + 3] = ((colorI32 >> 24) & 0xff) / 255.0; + // } } class SkeletonCache { diff --git a/cocos/terrain/terrain.ts b/cocos/terrain/terrain.ts index 03195f1a3a..36a004da19 100644 --- a/cocos/terrain/terrain.ts +++ b/cocos/terrain/terrain.ts @@ -1559,6 +1559,13 @@ export class Terrain extends Component { asset.layerBuffer[i * 4 + 3] = this._blocks[i].layers[3]; } + this.exportLayerListToAsset(asset); + + return asset; + } + + public exportLayerListToAsset (asset: TerrainAsset) { + asset.layerInfos.length = 0; for (let i = 0; i < this._layerList.length; ++i) { const temp = this._layerList[i]; if (temp && temp.detailMap && isValid(temp.detailMap)) { @@ -1569,12 +1576,9 @@ export class Terrain extends Component { layer.normalMap = temp.normalMap; layer.metallic = temp.metallic; layer.roughness = temp.roughness; - asset.layerInfos.push(layer); } } - - return asset; } public getEffectAsset () { @@ -1656,6 +1660,9 @@ export class Terrain extends Component { for (let i = 0; i < this._layerList.length; ++i) { if (this._layerList[i] === null || (this._layerList[i] && this._layerList[i]?.detailMap === null)) { this._layerList[i] = layer; + if (this._asset) { + this.exportLayerListToAsset(this._asset); + } return i; } } @@ -1669,6 +1676,9 @@ export class Terrain extends Component { */ public setLayer (i: number, layer: TerrainLayer) { this._layerList[i] = layer; + if (this._asset) { + this.exportLayerListToAsset(this._asset); + } } /** @@ -1677,6 +1687,9 @@ export class Terrain extends Component { */ public removeLayer (id: number) { this._layerList[id] = null; + if (this._asset) { + this.exportLayerListToAsset(this._asset); + } } /** diff --git a/cocos/tween/actions/action-instant.ts b/cocos/tween/actions/action-instant.ts index 0c6244808c..3e38f6283a 100644 --- a/cocos/tween/actions/action-instant.ts +++ b/cocos/tween/actions/action-instant.ts @@ -24,9 +24,10 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ +/* eslint-disable @typescript-eslint/ban-types */ import { FiniteTimeAction, Action } from './action'; -import { ModelRenderer } from '../../core/components/model-renderer'; +import { Renderer } from '../../core/components/renderer'; /** * @en Instant actions are immediate actions. They don't have a duration like the ActionInterval actions. @@ -70,7 +71,7 @@ export class ActionInstant extends FiniteTimeAction { */ export class Show extends ActionInstant { update (dt: any) { - const _renderComps = this.target!.getComponentsInChildren(ModelRenderer); + const _renderComps = this.target!.getComponentsInChildren(Renderer); for (let i = 0; i < _renderComps.length; ++i) { const render = _renderComps[i]; render.enabled = true; @@ -106,7 +107,7 @@ export function show (): ActionInstant { */ export class Hide extends ActionInstant { update (dt: any) { - const _renderComps = this.target!.getComponentsInChildren(ModelRenderer); + const _renderComps = this.target!.getComponentsInChildren(Renderer); for (let i = 0; i < _renderComps.length; ++i) { const render = _renderComps[i]; render.enabled = false; @@ -142,7 +143,7 @@ export function hide (): ActionInstant { */ export class ToggleVisibility extends ActionInstant { update (dt: any) { - const _renderComps = this.target!.getComponentsInChildren(ModelRenderer); + const _renderComps = this.target!.getComponentsInChildren(Renderer); for (let i = 0; i < _renderComps.length; ++i) { const render = _renderComps[i]; render.enabled = !render.enabled; @@ -247,11 +248,11 @@ export class CallFunc extends ActionInstant { /* * Constructor function, override it to extend the construction behavior, remember to call "this._super()" in the extended "ctor" function.
- * Creates a CallFunc action with the callback. - * @param {function} selector - * @param {object} [selectorTarget=null] - * @param {*} [data=null] data for function, it accepts all data types. - */ + * Creates a CallFunc action with the callback. + * @param {function} selector + * @param {object} [selectorTarget=null] + * @param {*} [data=null] data for function, it accepts all data types. + */ constructor (selector?: Function, selectorTarget?: any, data?: any) { super(); this.initWithFunction(selector, selectorTarget, data); diff --git a/cocos/ui/deprecated-1.2.0.ts b/cocos/ui/deprecated-1.2.0.ts index 5e2d805b46..a99c7de028 100644 --- a/cocos/ui/deprecated-1.2.0.ts +++ b/cocos/ui/deprecated-1.2.0.ts @@ -1,3 +1,28 @@ +/* + Copyright (c) 2020 Xiamen Yaji Software Co., Ltd. + + https://www.cocos.com/ + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated engine source code (the "Software"), a limited, + worldwide, royalty-free, non-assignable, revocable and non-exclusive license + to use Cocos Creator solely to develop games on your target platforms. You shall + not use Cocos Creator software for developing other software or tools that's + used for developing games. You are not granted to publish, distribute, + sublicense, and/or sell copies of Cocos Creator. + + The software or tools in this License Agreement are licensed, not sold. + Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. + */ + import { deprecateModuleExportedName } from '../core/utils/x-deprecated'; deprecateModuleExportedName({ diff --git a/docs/TS_CODING_STYLE.md b/docs/TS_CODING_STYLE.md new file mode 100644 index 0000000000..2ca2c94c82 --- /dev/null +++ b/docs/TS_CODING_STYLE.md @@ -0,0 +1,612 @@ +# TypeScript and JavaScript Coding Style Reference + +The following are some coding style rules for TypeScript and JavaScript we concluded during the development of Cocos Creator. It's important to mention that it's based on some basic conventions and our practices. Due to the fact that TypeScript compiler and JavaScript engine is keep evolving rapidly, we try to make the references quite simple. + +There are also some project related background need to be clarified: + +1. TypeScript is used for script level code in the engine. +2. [Babel](https://babeljs.io/) and [Rollup](https://rollupjs.org/) are used to compile TypeScript to JavaScript. +3. [ESLint](https://eslint.org/) is strongly recommended for all engine developers. +4. [VSCode](https://code.visualstudio.com/) is suggested for TypeScript coding. +5. In web runtime environments, the engine is fully running compiled TypeScript codes with some WebAssembly modules like physics engine. +6. In native runtime environments, the TypeScript codes are running based on the C++ codes and the JavaScript binding. + +## Naming Rules + +- Use camelCase naming convention for object and instance variables, properties, functions and namespaces. + + ```typescript + // bad + let FOOBar = {}; + let foo_bar = {}; + function FOOBar () {} + + // good + let fooBar = {}; + function fooBar () {} + ``` + +- When using acronym for variables, properties or functions, keep all characters of the acronym case aligned. If the name starts with acronym then use lower case for all characters, otherwise capitalize all characters. + + ```typescript + // bad + let Id = 0; + let iD = 0; + function requireId () {} + + // good + let id = 0; + let uuid = ''; + function requireID () {} + class AssetUUID {} + ``` + +- Use PascalCase naming convention for classes or modules + + ```javascript + // bad + let foobar = cc.Class({ + foo: 'foo', + bar: 'bar', + }); + let foobar = require('foo-bar'); + + // good + let FooBar = cc.Class({ + foo: 'foo', + bar: 'bar', + }); + let FooBar = require('foo-bar'); + ``` + +- Accessor API conventions + - Declare `public` property when the property is a direct value. + + ```typescript + // bad + class A { + get a ():number { + return this._a; + } + set a (val:number) { + this._a = val; + } + private _a: number; + } + // good + class A { + public a: number; + } + ``` + + - Suggest to make the property private and provide `getXXX/setXXX` methods when data accessing requires heavy logic. + - Suggest to make the property private and provide `getXXX/setXXX` methods when data accessing implicitly affect other data. + + ```typescript + // not recommended + class A { + get property ():number { + // computeResult have some heavy logic + return this.computeResult(); + } + } + // recommended + class A { + getProperty ():number { + // computeResult have some heavy logic + return this.computeResult(); + } + } + + // --- + + // not recommended + class A { + get property ():number { + return this._prop; + } + set property (val: number) { + this._prop = val; + this._a = this.computeA(); + } + + private _prop: number; + private _a: number; + } + // recommended + class A { + getProperty ():number { + return this._prop; + } + setProperty (val: number) { + this._prop = val; + this._a = this.computeA(); + } + + private _prop: number; + private _a: number; + } + ``` + + - Suggest to make the property private and provide public accessors if data accessing is light weight. + - In other conditions, please follow the existing API design in the file context. + +- Use all capitalized characters with underscores as word separator for CONSTANTS. + + ```typescript + // bad + const PRIVATE_letIABLE = 'should not be unnecessarily uppercased within a file'; + + // bad + let THING_TO_BE_CHANGED = 'should obviously not be uppercased'; + + // bad + let REASSIGNABLE_letIABLE = 'do not use let with uppercase letiables'; + + // --- + + // allowed but does not supply semantic value + export const apiKey = 'SOMEKEY'; + + // better in most cases + export const API_KEY = 'SOMEKEY'; + + // --- + + // bad - unnecessarily uppercases key while adding no semantic value + export const MAPPING = { + KEY: 'value' + }; + + // good + export const Type = { + SIMPLE: 'value' + }; + ``` + +- Use underscore `_` as prefix for private properties. + + ```typescript + // bad + class A { + private __firstName__: string; + private firstName_: string; + } + + // good + class A { + private _firstName: string; + } + ``` + +- Use lowercase characters with dash `-` as word separator for TypeScript file names. + + ```bash + // bad + fooBar.ts + FooBar.ts + + // good + foo-bar.ts + ``` + +## Syntax references + +- If a class property doesn't contain any initialization value, should consider using declare to avoid potential [issue](https://github.com/microsoft/TypeScript/issues/37640) + + ```typescript + // bad + class A { + public a:number; + constructor (a:number) { + // After compilation, the following line would be added to the constructor. + // this.a = void 0; + // As the type of `a` is changing, this could cause performance issue + this.a = a; + } + } + + // good + class A { + public a:number = 0; // Ok. + constructor (a:number) { + // After compilation, the following line would be added to the constructor. + // this.a = 0; + // The type of `a` is constant + this.a = a; + } + } + + // best + class A { + public declare a:number; + public b:undefined | object; // OK: b won't be reassigned in constructor + public declare c:object|null; + + constructor (a:number, c:object) { + this.a = a; + this.c = c; + } + } + ``` + +- Suggest to use `Object.create(null)` to create dictionaries, whose contents will be added or deleted frequently. + + ```javascript + // bad + let map = new Object(); + + // bad + let map = {}; + + // good + let map = Object.create(null); + ``` + +- Use strict comparison `===` and `!==` instead of `==` and `!=` + +## Other coding conventions + +- Use 4 spaces indent. + + ```typescript + // bad + function () { + ∙let name; + } + + // bad + function () { + ∙∙let name; + } + + // very bad + function () { + ∙∙let name; + } + + // good + function () { + ∙∙∙∙let name; + } + ``` + +- Don't leave tailed spaces, and leave an empty line at the end of the file. + + ```typescript + // bad + function () {∙ + ∙∙∙∙let name;∙ + } + /* EOF */ + + // good + function () { + ∙∙∙∙let name; + } + + /* EOF */ + ``` + +- Always add `;` at the end of a code line. + + ```typescript + // bad + proto.foo = function () { + } + + // good + proto.foo = function () { + }; + + // bad + function foo () { + return 'test' + } + + // very bad + // returns `undefined` instead of the value on the next line, + // always happens when `return` is on a line by itself because of Automatic Semicolon Insertion! + function foo () { + return + 'test' + } + + // good + function foo () { + return 'test'; + } + + // bad + function foo () { + }; + + // good: this is not a code line + function foo () { + } + ``` + +- Suggest to keep `{` with the previous line. + + ```typescript + // bad + if ( isFoobar ) + { + } + + // good + if ( isFoobar ) { + } + + // bad + function foobar () + { + } + + // good + function foobar () { + } + + // bad + let obj = + { + foo: 'foo', + bar: 'bar', + } + + // good + let obj = { + foo: 'foo', + bar: 'bar', + } + ``` + +- Leave one space before `{` + + ```typescript + // bad + if (isJedi){ + fight(); + } + else{ + escape(); + } + + // good + if (isJedi) { + fight(); + } + else { + escape(); + } + + // bad + dog.set('attr',{ + age: '1 year', + breed: 'Bernese Mountain Dog', + }); + + // good + dog.set('attr', { + age: '1 year', + breed: 'Bernese Mountain Dog', + }); + ``` + +- Leave one space after `if`, `else`, `while` and `switch` + + ```typescript + // bad + if(isJedi) { + fight (); + } + else{ + escape(); + } + + // good + if (isJedi) { + fight(); + } + else { + escape(); + } + ``` + +- Leave one space before and after binary and ternary operators. + + ```typescript + // bad + let x=y+5; + let left = rotated? y: x; + + // good + let x = y + 5; + let left = rotated ? y : x; + + // bad + for (let i=0; i< 10; i++) { + } + + // good + for (let i = 0; i < 10; i++) { + } + ``` + +- Some function declaration references + + ```typescript + // bad + let test = function () { + console.log('test'); + }; + + // good + function test () { + console.log('test'); + } + + // bad + function test () { console.log('test'); }; + + // good + function test () { + console.log('test'); + } + + // bad + function divisibleFunction () { + return DEBUG ? 'foo' : 'bar'; + } + + // best + let divisibleFunction = DEBUG ? + function () { + return 'foo'; + } : + function () { + return 'bar'; + }; + + // bad + function test(){ + } + + // good + function test () { + } + + // bad + let obj = { + foo: function () { + } + }; + + // good + let obj = { + foo () { + } + }; + + // bad + array.map(x=>x + 1); + array.map(x => { + return x + 1; + }); + + // good + array.map(x => x + 1); + ``` + +- Suggest to leave empty line between code blocks. + + ```typescript + // bad + if (foo) { + return bar; + } + return baz; + + // good + if (foo) { + return bar; + } + + return baz; + + // bad + const obj = { + x: 0, + y: 0, + foo () { + }, + bar () { + }, + }; + return obj; + + // good + const obj = { + x: 0, + y: 0, + + foo () { + }, + + bar () { + }, + }; + + return obj; + ``` + +- Semicolon alignment. + + ```typescript + // bad + let story = [ + once + , upon + , aTime + ]; + + // good + let story = [ + once, + upon, + aTime, + ]; + + // bad + let hero = { + firstName: 'Ada' + , lastName: 'Lovelace' + , birthYear: 1815 + , superPower: 'computers' + }; + + // good + let hero = { + firstName: 'Ada', + lastName: 'Lovelace', + birthYear: 1815, + superPower: 'computers', + }; + ``` + +- Single line comments + + ```typescript + //bad + // good + ``` + +- Multiple line comments + + ```typescript + /* + * good + */ + ``` + +- API documentation comments + + ```typescript + /** + * good + */ + ``` + +- Except for API documentation, all comments must be written in English + + ```js + // bad + // 中文注释不利于非中文开发者阅读代码 + // good + // Please write all in file comments in English + ``` + +## Other references + +- [Google JavaScript Style Guide](https://google.github.io/styleguide/jsguide.html) +- [Airbnb JavaScript Style Guide](https://github.com/airbnb/javascript#table-of-contents) diff --git a/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk b/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk index bd886efdc5..d5712eae78 100644 --- a/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk +++ b/editor/assets/chunks/builtin/internal/particle-vs-gpu.chunk @@ -35,15 +35,15 @@ uniform TickConstants { in vec4 a_position_starttime; // center position,particle start time in vec4 a_color; in vec4 a_dir_life; // xyz:particle start velocity,w:particle lifetime -in float a_rndSeed; #if !CC_INSTANCE_PARTICLE in vec4 a_size_uv; // xyz:size, w:uv_0 in vec4 a_rotation_uv; // xyz:rotation, w:uv_1 + in float a_rndSeed; #endif #if CC_INSTANCE_PARTICLE - in vec4 a_size_fid; // xyz:size, w:fid - in vec3 a_rotation; // xyz:rotation + in vec4 a_size_fid; // xyz:size, w:fid + in vec4 a_rotation_rnd; // xyz:rotation, w:random in vec3 a_uv; #endif @@ -178,6 +178,12 @@ vec4 toQuat(vec3 rotation) { } vec4 gpvs_main () { + #if CC_INSTANCE_PARTICLE + float randSeed = a_rotation_rnd.w; + #else + float randSeed = a_rndSeed; + #endif + float activeTime = u_timeDelta.x - a_position_starttime.w; float normalizedTime = clamp(activeTime / a_dir_life.w, 0.0, 1.0); @@ -212,7 +218,7 @@ vec4 gpvs_main () { } else { vec3 size_0 = unpackCurveData(size_over_time_tex0, timeCoord0); vec3 size_1 = unpackCurveData(size_over_time_tex0, timeCoord1); - float factor_s = pseudoRandom(a_rndSeed + SIZE_OVERTIME_RAND_OFFSET); + float factor_s = pseudoRandom(randSeed + SIZE_OVERTIME_RAND_OFFSET); size *= mix(size_0, size_1, factor_s); } #endif @@ -227,7 +233,7 @@ vec4 gpvs_main () { } else { vec3 force_0 = unpackCurveData(force_over_time_tex0, timeCoord0); vec3 force_1 = unpackCurveData(force_over_time_tex0, timeCoord1); - float factor_f = pseudoRandom(a_rndSeed + FORCE_OVERTIME_RAND_OFFSET); + float factor_f = pseudoRandom(randSeed + FORCE_OVERTIME_RAND_OFFSET); forceAnim = mix(force_0, force_1, factor_f); } vec4 forceTrack = vec4(forceAnim, 0.); @@ -247,7 +253,7 @@ vec4 gpvs_main () { } else { vec3 vectory_0 = unpackCurveData(velocity_over_time_tex0, timeCoord0, speedModifier0); vec3 vectory_1 = unpackCurveData(velocity_over_time_tex0, timeCoord1, speedModifier1); - float factor_v = pseudoRandom(a_rndSeed + VELOCITY_OVERTIME_RAND_OFFSET); + float factor_v = pseudoRandom(randSeed + VELOCITY_OVERTIME_RAND_OFFSET); velocityAnim = mix(vectory_0, vectory_1, factor_v); speedModifier0 = mix(speedModifier0, speedModifier1, factor_v); } @@ -273,7 +279,7 @@ vec4 gpvs_main () { vec3 startRotation = a_rotation_uv.xyz; #endif #if CC_INSTANCE_PARTICLE - vec3 startRotation = a_rotation; + vec3 startRotation = a_rotation_rnd.xyz; #endif #if CC_RENDER_MODE != RENDER_MODE_MESH #if CC_RENDER_MODE == RENDER_MODE_BILLBOARD @@ -300,7 +306,7 @@ vec4 gpvs_main () { } else { vec3 rotation_0 = unpackCurveData(rotation_over_time_tex0, timeCoord0); vec3 rotation_1 = unpackCurveData(rotation_over_time_tex0, timeCoord1); - float factor_r = pseudoRandom(a_rndSeed + ROTATION_OVERTIME_RAND_OFFSET); + float factor_r = pseudoRandom(randSeed + ROTATION_OVERTIME_RAND_OFFSET); vec3 euler = mix(rotation_0, rotation_1, factor_r) * normalizedTime * a_dir_life.w; #if CC_RENDER_MODE == RENDER_MODE_VERTICAL_BILLBOARD || CC_RENDER_MODE == RENDER_MODE_HORIZONTAL_BILLBOARD euler = vec3(0.0, 0.0, euler.z); @@ -319,7 +325,7 @@ vec4 gpvs_main () { } else { vec4 color_0 = texture(color_over_time_tex0, timeCoord0); vec4 color_1 = texture(color_over_time_tex0, timeCoord1); - float factor_c = pseudoRandom(a_rndSeed + COLOR_OVERTIME_RAND_OFFSET); + float factor_c = pseudoRandom(randSeed + COLOR_OVERTIME_RAND_OFFSET); color = a_color * mix(color_0, color_1, factor_c); } #endif @@ -376,7 +382,7 @@ vec4 gpvs_main () { } else { vec3 frameInfo0 = unpackCurveData(texture_animation_tex0, timeCoord0); vec3 frameInfo1 = unpackCurveData(texture_animation_tex0, timeCoord1); - float factor_t = pseudoRandom(a_rndSeed + TEXTURE_ANIMATION_RAND_OFFSET); + float factor_t = pseudoRandom(randSeed + TEXTURE_ANIMATION_RAND_OFFSET); frameInfo = mix(frameInfo0, frameInfo1, factor_t); } startFrame = frameInfo.x / u_anim_info.y; diff --git a/editor/assets/chunks/common/math/coordinates.chunk b/editor/assets/chunks/common/math/coordinates.chunk index cfa7ff33e4..07a32909e8 100644 --- a/editor/assets/chunks/common/math/coordinates.chunk +++ b/editor/assets/chunks/common/math/coordinates.chunk @@ -60,14 +60,10 @@ void RotateTangentAndBinormal(inout vec3 tangent, inout vec3 binormal, vec3 norm vec3 T = RotationVecFromAxisY(vec3(0.0, 0.0, 1.0), cosTheta, sinTheta); vec3 tangentNew, binormalNew; - binormalNew.x = dot(B, binormal); - binormalNew.y = dot(B, normal); - binormalNew.z = dot(B, tangent); + binormalNew = B.x * binormal + B.y * normal + B.z * tangent; binormal = normalize(binormalNew); - tangentNew.x = dot(T, binormal); - tangentNew.y = dot(T, normal); - tangentNew.z = dot(T, tangent); + tangentNew = T.x * binormal + T.y * normal + T.z * tangent; tangent = normalize(tangentNew); // tangent = cross(binormal, normal); } diff --git a/editor/assets/chunks/legacy/standard-surface-entry.chunk b/editor/assets/chunks/legacy/standard-surface-entry.chunk index 5abc13073b..78f968872d 100644 --- a/editor/assets/chunks/legacy/standard-surface-entry.chunk +++ b/editor/assets/chunks/legacy/standard-surface-entry.chunk @@ -31,11 +31,11 @@ \ void main () { \ StandardSurface s; surf(s); \ - vec4 color = CCStandardShadingBase(s, CC_SHADOW_POSITION); \ + vec4 color = CCFragOutput(CCStandardShadingBase(s, CC_SHADOW_POSITION)); \ #if CC_USE_FOG != CC_FOG_NONE \ CC_APPLY_FOG(color, s.position.xyz); \ #endif \ - fragColorX = CCFragOutput(color); \ + fragColorX = color; \ } \ \ #elif CC_PIPELINE_TYPE == CC_PIPELINE_TYPE_DEFERRED \ diff --git a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk index 3b173b5636..60ad5b178c 100644 --- a/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk +++ b/editor/assets/chunks/shading-entries/main-functions/render-to-scene/pipeline/forward-fs.chunk @@ -104,10 +104,6 @@ void main() { // Shading vec4 color = CCSurfacesShading(surfaceData, lightingResult); - #if !CC_FORWARD_ADD && CC_USE_FOG != CC_FOG_NONE - CC_APPLY_FOG_BASE(color, fogFactor); - #endif - #if CC_USE_DEBUG_VIEW && CC_SURFACES_ENABLE_DEBUG_VIEW // CSM Debug if (IS_DEBUG_VIEW_MISC_ENABLE_CSM_LAYER_COLORATION) { @@ -132,6 +128,9 @@ void main() { #endif color.rgb = LinearToSRGB(color.rgb); + #if !CC_FORWARD_ADD && CC_USE_FOG != CC_FOG_NONE + CC_APPLY_FOG_BASE(color, fogFactor); + #endif fragColorX = CCSurfacesDebugDisplayInvalidNumber(color); } diff --git a/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk b/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk index 10d946ec83..2cf4b60508 100644 --- a/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk +++ b/editor/assets/chunks/surfaces/module-functions/toon-fs.chunk @@ -114,10 +114,24 @@ vec4 CCSurfacesShading(in SurfacesMaterialData surfaceData, in LightingResult li #else float lightmapCoef = 0.0; +#if CC_SURFACES_USE_LEGACY_COMPATIBLE_LIGHTING color.xyz += ( mix(lightingResult.directDiffuse, lightingResult.lightmapColor, lightmapCoef) * lightingResult.diffuseColorWithLighting + lightingResult.directSpecular * lightingResult.specularColorWithLighting) - * lightingResult.shadow; + * lightingResult.shadow + ; +#else + // shadowed area equals to back lighting area + LightingIntermediateData lightingData; + lightingData.NoL = -1.0; + vec3 backLightingDiffuse, backLightingSpecular; + CCSurfacesLightingCalculateColorWithLighting(backLightingDiffuse, backLightingSpecular, surfaceData, lightingData); + + color.xyz += + mix(lightingResult.directDiffuse, lightingResult.lightmapColor, lightmapCoef) * mix(backLightingDiffuse, lightingResult.diffuseColorWithLighting, lightingResult.shadow) + + lightingResult.directSpecular * lightingResult.specularColorWithLighting * lightingResult.shadow + ; +#endif color.xyz += lightingResult.emissive; #endif diff --git a/editor/assets/default_file_content/effect-surface b/editor/assets/default_file_content/effect-surface new file mode 100644 index 0000000000..671e1d0d53 --- /dev/null +++ b/editor/assets/default_file_content/effect-surface @@ -0,0 +1,239 @@ +// Effect Syntax Guide: https://docs.cocos.com/creator/manual/zh/shader/index.html + +CCEffect %{ + techniques: + - name: opaque + passes: + - vert: standard-vs + frag: standard-fs + properties: &props + mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, linear: true, editor: { displayName: Albedo, type: color } } + albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } + alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST, slide: true, range: [0, 1.0], step: 0.001 } } + roughness: { value: 0.8, target: pbrParams.y, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + metallic: { value: 0.6, target: pbrParams.z, editor: { slide: true, range: [0, 1.0], step: 0.001 } } + - &forward-add + vert: standard-vs + frag: standard-fs + phase: forward-add + propertyIndex: 0 + embeddedMacros: { CC_FORWARD_ADD: true } + depthStencilState: + depthFunc: equal + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: one + blendDst: one + blendSrcAlpha: zero + blendDstAlpha: one + - &shadow-caster + vert: shadow-caster-vs + frag: shadow-caster-fs + phase: shadow-caster + propertyIndex: 0 + rasterizerState: + cullMode: front + properties: + mainColor: { value: [1.0, 1.0, 1.0, 1.0], target: albedo, editor: { displayName: Albedo, type: color } } + albedoScale: { value: [1.0, 1.0, 1.0], target: albedoScaleAndCutoff.xyz } + alphaThreshold: { value: 0.5, target: albedoScaleAndCutoff.w, editor: { parent: USE_ALPHA_TEST } } + mainTexture: { value: grey, target: albedoMap, editor: { displayName: AlbedoMap } } + - name: transparent + passes: + - vert: standard-vs + frag: standard-fs + embeddedMacros: { CC_FORCE_FORWARD_SHADING: true } + depthStencilState: + depthTest: true + depthWrite: false + blendState: + targets: + - blend: true + blendSrc: src_alpha + blendDst: one_minus_src_alpha + blendDstAlpha: one_minus_src_alpha + properties: *props + - *forward-add + - *shadow-caster +}% + + +CCProgram shared-ubos %{ + uniform Constants { + vec4 albedo; + vec4 albedoScaleAndCutoff; + vec4 pbrParams; + }; +}% + +CCProgram macro-remapping %{ + // ui displayed macros + #pragma define-meta USE_TWOSIDE + #pragma define-meta USE_VERTEX_COLOR + + #define CC_SURFACES_USE_TWO_SIDED USE_TWOSIDE + #define CC_SURFACES_USE_VERTEX_COLOR USE_VERTEX_COLOR +}% +CCProgram surface-vertex %{ + #define CC_SURFACES_VERTEX_MODIFY_WORLD_POS + vec3 SurfacesVertexModifyWorldPos(in SurfacesStandardVertexIntermediate In) + { + return In.worldPos; + } + + #define CC_SURFACES_VERTEX_MODIFY_WORLD_NORMAL + vec3 SurfacesVertexModifyWorldNormal(in SurfacesStandardVertexIntermediate In) + { + return In.worldNormal.xyz; + } + + #define CC_SURFACES_VERTEX_MODIFY_UV + void SurfacesVertexModifyUV(inout SurfacesStandardVertexIntermediate In) + { + } +}% + + +CCProgram surface-fragment %{ + #if USE_ALBEDO_MAP + uniform sampler2D albedoMap; + #pragma define-meta ALBEDO_UV options([v_uv, v_uv1]) + #endif + + #if USE_ALPHA_TEST + #pragma define-meta ALPHA_TEST_CHANNEL options([a, r]) + #endif + + #define CC_SURFACES_FRAGMENT_MODIFY_BASECOLOR_AND_TRANSPARENCY + vec4 SurfacesFragmentModifyBaseColorAndTransparency() + { + vec4 baseColor = albedo; + + #if USE_ALBEDO_MAP + vec4 texColor = texture(albedoMap, ALBEDO_UV); + texColor.rgb = SRGBToLinear(texColor.rgb); + baseColor *= texColor; + #endif + + #if USE_ALPHA_TEST + if (baseColor.ALPHA_TEST_CHANNEL < albedoScaleAndCutoff.w) discard; + #endif + + baseColor.rgb *= albedoScaleAndCutoff.xyz; + return baseColor; + } + + #define CC_SURFACES_FRAGMENT_ALPHA_CLIP_ONLY + void SurfacesFragmentAlphaClipOnly() + { + #if USE_ALPHA_TEST + float alpha = albedo.ALPHA_TEST_CHANNEL; + #if USE_VERTEX_COLOR + alpha *= FSInput_vertexColor.a; + #endif + #if USE_ALBEDO_MAP + alpha = texture(albedoMap, ALBEDO_UV).ALPHA_TEST_CHANNEL; + #endif + + if (alpha < albedoScaleAndCutoff.w) discard; + #endif + } + + #define CC_SURFACES_FRAGMENT_MODIFY_WORLD_NORMAL + vec3 SurfacesFragmentModifyWorldNormal() + { + return normalize(FSInput_worldNormal); + } + + #define CC_SURFACES_FRAGMENT_MODIFY_EMISSIVE + vec3 SurfacesFragmentModifyEmissive() + { + return vec3(0.0, 0.0, 0.0); + } + + #define CC_SURFACES_FRAGMENT_MODIFY_PBRPARAMS + vec4 SurfacesFragmentModifyPBRParams() + { + // ao, roughness, metallic, specularIntensity + return vec4(1.0, pbrParams.y, pbrParams.z, 0.5); + } +}% + + + + +CCProgram standard-vs %{ + precision highp float; + + // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros + #include + #include + + // 2. common include with corresponding shader stage, include before surface functions + #include + + // 3. user surface functions that can use user (effect) parameters (ubo Constants) + // see surfaces/default-functions/xxx.chunk + #include + #include + + // 4. surface include with corresponding shader stage and shading-model (optional) + #include + + // 5. shader entry with corresponding shader stage and technique usage/type + #include +}% + + +CCProgram shadow-caster-vs %{ + precision highp float; + #include + #include + #include + #include + #include +}% + + + +CCProgram standard-fs %{ + // shading-model : standard + // lighting-model : standard (isotropy / anisotropy pbr) + // shader stage : fs + // technique usage/type : render-to-scene + + precision highp float; + // 1. surface internal macros, for technique usage or remapping some user (material) macros to surface internal macros + #include + #include + + // 2. common include with corresponding shader stage, include before surface functions + #include + + // 3. user surface functions that can use user (effect) parameters (ubo Constants) + // see surfaces/default-functions/xxx.chunk + #include + #include + + // 4. lighting-model (optional) + #include + + // 5. surface include with corresponding shader stage and shading-model (optional) + #include + + // 6. shader entry with corresponding shader stage and technique usage/type + #include +}% + +CCProgram shadow-caster-fs %{ + precision highp float; + #include + #include + #include + #include + #include +}% diff --git a/editor/assets/default_file_content/effect-surface.meta b/editor/assets/default_file_content/effect-surface.meta new file mode 100644 index 0000000000..caa639a2df --- /dev/null +++ b/editor/assets/default_file_content/effect-surface.meta @@ -0,0 +1,12 @@ +{ + "ver": "1.0.0", + "importer": "*", + "imported": true, + "uuid": "6c68ba5e-4590-4a25-bd25-430a0ebc1544", + "files": [ + "", + ".json" + ], + "subMetas": {}, + "userData": {} +} diff --git a/editor/assets/default_file_content/rt b/editor/assets/default_file_content/rt index a217d25851..a9eb94b9d9 100644 --- a/editor/assets/default_file_content/rt +++ b/editor/assets/default_file_content/rt @@ -4,8 +4,8 @@ "_native": "", "content": { "base": "2,2,0,0,0,0", - "w": 1, - "h": 1, + "w": 256, + "h": 256, "n": "" } } \ No newline at end of file diff --git a/editor/assets/default_prefab/2d/Camera.prefab.meta b/editor/assets/default_prefab/2d/Camera.prefab.meta index e5d2aa0158..0f464abf21 100644 --- a/editor/assets/default_prefab/2d/Camera.prefab.meta +++ b/editor/assets/default_prefab/2d/Camera.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "3487d118-0158-4983-93fe-c3822790e7c5", diff --git a/editor/assets/default_prefab/3d/Capsule.prefab.meta b/editor/assets/default_prefab/3d/Capsule.prefab.meta index eb117b6061..9bef03cba5 100644 --- a/editor/assets/default_prefab/3d/Capsule.prefab.meta +++ b/editor/assets/default_prefab/3d/Capsule.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "73ce1f7f-d1f4-4942-ad93-66ca3b3041ab", diff --git a/editor/assets/default_prefab/3d/Cone.prefab.meta b/editor/assets/default_prefab/3d/Cone.prefab.meta index 0cb28ca198..11140900cf 100644 --- a/editor/assets/default_prefab/3d/Cone.prefab.meta +++ b/editor/assets/default_prefab/3d/Cone.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "6350d660-e888-4acf-a552-f3b719ae9110", diff --git a/editor/assets/default_prefab/3d/Cube.prefab.meta b/editor/assets/default_prefab/3d/Cube.prefab.meta index 966e0ddf6a..2d427d2b95 100644 --- a/editor/assets/default_prefab/3d/Cube.prefab.meta +++ b/editor/assets/default_prefab/3d/Cube.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "30da77a1-f02d-4ede-aa56-403452ee7fde", diff --git a/editor/assets/default_prefab/3d/Cylinder.prefab.meta b/editor/assets/default_prefab/3d/Cylinder.prefab.meta index 4d8a36732f..2d67ac6075 100644 --- a/editor/assets/default_prefab/3d/Cylinder.prefab.meta +++ b/editor/assets/default_prefab/3d/Cylinder.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "ab3e16f9-671e-48a7-90b7-d0884d9cbb85", diff --git a/editor/assets/default_prefab/3d/Plane.prefab.meta b/editor/assets/default_prefab/3d/Plane.prefab.meta index 9ae4b4b379..7d4d2e262d 100644 --- a/editor/assets/default_prefab/3d/Plane.prefab.meta +++ b/editor/assets/default_prefab/3d/Plane.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "40563723-f8fc-4216-99ea-a81636435c10", diff --git a/editor/assets/default_prefab/3d/Quad.prefab.meta b/editor/assets/default_prefab/3d/Quad.prefab.meta index 71a6bc9b2d..85ec1471d9 100644 --- a/editor/assets/default_prefab/3d/Quad.prefab.meta +++ b/editor/assets/default_prefab/3d/Quad.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "34a07346-9f62-4a84-90ae-cb83f7a426c1", diff --git a/editor/assets/default_prefab/3d/Sphere.prefab.meta b/editor/assets/default_prefab/3d/Sphere.prefab.meta index 5a68a78e77..7c4a1d4e9a 100644 --- a/editor/assets/default_prefab/3d/Sphere.prefab.meta +++ b/editor/assets/default_prefab/3d/Sphere.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "655c9519-1a37-472b-bae6-29fefac0b550", diff --git a/editor/assets/default_prefab/3d/Torus.prefab.meta b/editor/assets/default_prefab/3d/Torus.prefab.meta index 7cdeb4a8bc..7481a2b0a5 100644 --- a/editor/assets/default_prefab/3d/Torus.prefab.meta +++ b/editor/assets/default_prefab/3d/Torus.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "d47f5d5e-c931-4ff4-987b-cc818a728b82", diff --git a/editor/assets/default_prefab/Camera.prefab.meta b/editor/assets/default_prefab/Camera.prefab.meta index dd25cfe779..7cf2aca3be 100644 --- a/editor/assets/default_prefab/Camera.prefab.meta +++ b/editor/assets/default_prefab/Camera.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "bb0a6472-cd67-4afb-a031-94fca8f4cc92", diff --git a/editor/assets/default_prefab/Terrain.prefab.meta b/editor/assets/default_prefab/Terrain.prefab.meta index f76e9e78f9..bb7b0c1f7c 100644 --- a/editor/assets/default_prefab/Terrain.prefab.meta +++ b/editor/assets/default_prefab/Terrain.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "90e8b0d4-12dc-412d-9156-ea1fdb18c15b", diff --git a/editor/assets/default_prefab/effects/Particle System.prefab.meta b/editor/assets/default_prefab/effects/Particle System.prefab.meta index db31b7361f..3293783829 100644 --- a/editor/assets/default_prefab/effects/Particle System.prefab.meta +++ b/editor/assets/default_prefab/effects/Particle System.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "f09a0597-10e6-49e5-8759-a148b5e85395", diff --git a/editor/assets/default_prefab/light/Directional Light.prefab.meta b/editor/assets/default_prefab/light/Directional Light.prefab.meta index 7034718420..6b9b01a1c7 100644 --- a/editor/assets/default_prefab/light/Directional Light.prefab.meta +++ b/editor/assets/default_prefab/light/Directional Light.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "a0e9756d-9128-4f49-8097-e041c8b733b8", diff --git a/editor/assets/default_prefab/light/Sphere Light.prefab.meta b/editor/assets/default_prefab/light/Sphere Light.prefab.meta index 5ce2bcdf49..611742c5d2 100644 --- a/editor/assets/default_prefab/light/Sphere Light.prefab.meta +++ b/editor/assets/default_prefab/light/Sphere Light.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "4182ee46-ffa0-4de2-b66b-c93cc6c7e9b8", diff --git a/editor/assets/default_prefab/light/Spot Light.prefab.meta b/editor/assets/default_prefab/light/Spot Light.prefab.meta index 5801e2545b..8b3c069382 100644 --- a/editor/assets/default_prefab/light/Spot Light.prefab.meta +++ b/editor/assets/default_prefab/light/Spot Light.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "7a49aa24-bd7a-40a8-b31a-b2a9da85abcd", diff --git a/editor/assets/default_prefab/ui/Button.prefab.meta b/editor/assets/default_prefab/ui/Button.prefab.meta index 398c69f09b..2c32c912f5 100644 --- a/editor/assets/default_prefab/ui/Button.prefab.meta +++ b/editor/assets/default_prefab/ui/Button.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "90bdd2a9-2838-4888-b66c-e94c8b7a5169", diff --git a/editor/assets/default_prefab/ui/Canvas.prefab.meta b/editor/assets/default_prefab/ui/Canvas.prefab.meta index c64cc38c52..b54eb40b6a 100644 --- a/editor/assets/default_prefab/ui/Canvas.prefab.meta +++ b/editor/assets/default_prefab/ui/Canvas.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "f773db21-62b8-4540-956a-29bacf5ddbf5", diff --git a/editor/assets/default_prefab/ui/EditBox.prefab.meta b/editor/assets/default_prefab/ui/EditBox.prefab.meta index 30f845c7ec..6f1ea23f0f 100644 --- a/editor/assets/default_prefab/ui/EditBox.prefab.meta +++ b/editor/assets/default_prefab/ui/EditBox.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "05e79121-8675-4551-9ad7-1b901a4025db", diff --git a/editor/assets/default_prefab/ui/Graphics.prefab.meta b/editor/assets/default_prefab/ui/Graphics.prefab.meta index 271902574e..f47e3f5584 100644 --- a/editor/assets/default_prefab/ui/Graphics.prefab.meta +++ b/editor/assets/default_prefab/ui/Graphics.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "c96e159e-43ea-4a16-8279-05bc39119d1a", diff --git a/editor/assets/default_prefab/ui/Label.prefab.meta b/editor/assets/default_prefab/ui/Label.prefab.meta index 912236bd2e..c2e581395a 100644 --- a/editor/assets/default_prefab/ui/Label.prefab.meta +++ b/editor/assets/default_prefab/ui/Label.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "36008810-7ad3-47c0-8112-e30aee089e45", diff --git a/editor/assets/default_prefab/ui/Layout.prefab.meta b/editor/assets/default_prefab/ui/Layout.prefab.meta index 7c277649e1..bf9fec85ea 100644 --- a/editor/assets/default_prefab/ui/Layout.prefab.meta +++ b/editor/assets/default_prefab/ui/Layout.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "a9ef7dfc-ea8b-4cf8-918e-36da948c4de0", diff --git a/editor/assets/default_prefab/ui/Mask.prefab.meta b/editor/assets/default_prefab/ui/Mask.prefab.meta index d6305572da..ff5366e4c1 100644 --- a/editor/assets/default_prefab/ui/Mask.prefab.meta +++ b/editor/assets/default_prefab/ui/Mask.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "7fa63aed-f3e2-46a5-8a7c-c1a1adf6cea6", diff --git a/editor/assets/default_prefab/ui/ParticleSystem2D.prefab.meta b/editor/assets/default_prefab/ui/ParticleSystem2D.prefab.meta index 879d045f63..9e459bc5ed 100644 --- a/editor/assets/default_prefab/ui/ParticleSystem2D.prefab.meta +++ b/editor/assets/default_prefab/ui/ParticleSystem2D.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "f396261e-3e06-41ec-bdd6-9a8b6d99026f", diff --git a/editor/assets/default_prefab/ui/ProgressBar.prefab.meta b/editor/assets/default_prefab/ui/ProgressBar.prefab.meta index b43f5afb59..b9720cb6da 100644 --- a/editor/assets/default_prefab/ui/ProgressBar.prefab.meta +++ b/editor/assets/default_prefab/ui/ProgressBar.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "0d9353c4-6fb9-49bb-bc62-77f1750078c2", diff --git a/editor/assets/default_prefab/ui/RichText.prefab.meta b/editor/assets/default_prefab/ui/RichText.prefab.meta index ecf7bc4323..46eef95adb 100644 --- a/editor/assets/default_prefab/ui/RichText.prefab.meta +++ b/editor/assets/default_prefab/ui/RichText.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "fc6bfcfa-8086-4326-809b-0ba1226bac7d", diff --git a/editor/assets/default_prefab/ui/ScrollView.prefab.meta b/editor/assets/default_prefab/ui/ScrollView.prefab.meta index bb27e18a4e..34fe466c90 100644 --- a/editor/assets/default_prefab/ui/ScrollView.prefab.meta +++ b/editor/assets/default_prefab/ui/ScrollView.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "c1baa707-78d6-4b89-8d5d-0b7fdf0c39bc", diff --git a/editor/assets/default_prefab/ui/Slider.prefab.meta b/editor/assets/default_prefab/ui/Slider.prefab.meta index 8b96c45e34..15b96e18ab 100644 --- a/editor/assets/default_prefab/ui/Slider.prefab.meta +++ b/editor/assets/default_prefab/ui/Slider.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "2bd7e5b6-cd8c-41a1-8136-ddb8efbf6326", diff --git a/editor/assets/default_prefab/ui/Sprite.prefab.meta b/editor/assets/default_prefab/ui/Sprite.prefab.meta index 68fb21cc8c..6cdad31d56 100644 --- a/editor/assets/default_prefab/ui/Sprite.prefab.meta +++ b/editor/assets/default_prefab/ui/Sprite.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "9db8cd0b-cbe4-42e7-96a9-a239620c0a9d", diff --git a/editor/assets/default_prefab/ui/SpriteRenderer.prefab.meta b/editor/assets/default_prefab/ui/SpriteRenderer.prefab.meta index 5a7ae62cdd..27ae8ce476 100644 --- a/editor/assets/default_prefab/ui/SpriteRenderer.prefab.meta +++ b/editor/assets/default_prefab/ui/SpriteRenderer.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "279ed042-5a65-4efe-9afb-2fc23c61e15a", diff --git a/editor/assets/default_prefab/ui/SpriteSplash.prefab.meta b/editor/assets/default_prefab/ui/SpriteSplash.prefab.meta index 1af8f23741..0578f6665e 100644 --- a/editor/assets/default_prefab/ui/SpriteSplash.prefab.meta +++ b/editor/assets/default_prefab/ui/SpriteSplash.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "e5f21aad-3a69-4011-ac62-b74352ac025e", diff --git a/editor/assets/default_prefab/ui/TiledMap.prefab.meta b/editor/assets/default_prefab/ui/TiledMap.prefab.meta index 5ffcd258f7..f50f5502ae 100644 --- a/editor/assets/default_prefab/ui/TiledMap.prefab.meta +++ b/editor/assets/default_prefab/ui/TiledMap.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "3139fa4f-8c42-4ce6-98be-15e848d9734c", diff --git a/editor/assets/default_prefab/ui/Toggle.prefab.meta b/editor/assets/default_prefab/ui/Toggle.prefab.meta index 167366e29b..be08fd508f 100644 --- a/editor/assets/default_prefab/ui/Toggle.prefab.meta +++ b/editor/assets/default_prefab/ui/Toggle.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "0e89afe7-56de-4f99-96a1-cba8a75bedd2", diff --git a/editor/assets/default_prefab/ui/ToggleContainer.prefab.meta b/editor/assets/default_prefab/ui/ToggleContainer.prefab.meta index b45baf3d8f..305e345673 100644 --- a/editor/assets/default_prefab/ui/ToggleContainer.prefab.meta +++ b/editor/assets/default_prefab/ui/ToggleContainer.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "2af73429-41d1-4346-9062-7798e42945dd", diff --git a/editor/assets/default_prefab/ui/VideoPlayer.prefab.meta b/editor/assets/default_prefab/ui/VideoPlayer.prefab.meta index 2c0732b677..e1fcf13dde 100644 --- a/editor/assets/default_prefab/ui/VideoPlayer.prefab.meta +++ b/editor/assets/default_prefab/ui/VideoPlayer.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "7e089eaf-fa97-40d7-8a20-741a152585df", diff --git a/editor/assets/default_prefab/ui/WebView.prefab.meta b/editor/assets/default_prefab/ui/WebView.prefab.meta index 8083a278d9..fb0944f27c 100644 --- a/editor/assets/default_prefab/ui/WebView.prefab.meta +++ b/editor/assets/default_prefab/ui/WebView.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "9c541fa2-1dc8-4d8b-813a-aec89133f5b1", diff --git a/editor/assets/default_prefab/ui/Widget.prefab.meta b/editor/assets/default_prefab/ui/Widget.prefab.meta index 0459e2ef5e..88c5b2828a 100644 --- a/editor/assets/default_prefab/ui/Widget.prefab.meta +++ b/editor/assets/default_prefab/ui/Widget.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "36ed4422-3542-4cc4-bf02-dc4bfc590836", diff --git a/editor/assets/default_prefab/ui/pageView.prefab b/editor/assets/default_prefab/ui/pageView.prefab index fc89644301..453cb591b5 100644 --- a/editor/assets/default_prefab/ui/pageView.prefab +++ b/editor/assets/default_prefab/ui/pageView.prefab @@ -695,7 +695,6 @@ "_type": 0, "_inverted": false, "_segments": 64, - "_spriteFrame": null, "_alphaThreshold": 0.1, "_id": "" }, diff --git a/editor/assets/default_prefab/ui/pageView.prefab.meta b/editor/assets/default_prefab/ui/pageView.prefab.meta index b029ba3d69..cec5d685d7 100644 --- a/editor/assets/default_prefab/ui/pageView.prefab.meta +++ b/editor/assets/default_prefab/ui/pageView.prefab.meta @@ -1,5 +1,5 @@ { - "ver": "1.1.39", + "ver": "1.1.40", "importer": "prefab", "imported": true, "uuid": "20a5d8cb-ccad-4543-a937-fccd98c9f3de", diff --git a/editor/assets/effects/surfaces/toon.effect b/editor/assets/effects/surfaces/toon.effect index 5460bca9dd..d88e7e1c8e 100644 --- a/editor/assets/effects/surfaces/toon.effect +++ b/editor/assets/effects/surfaces/toon.effect @@ -97,6 +97,10 @@ CCProgram shared-ubos %{ };}% CCProgram macro-remapping %{ + // if enabled, shadowed area is very dark + #pragma define-meta USE_COMPATIBLE_LIGHTING + #define CC_SURFACES_USE_LEGACY_COMPATIBLE_LIGHTING USE_COMPATIBLE_LIGHTING + #pragma define-meta USE_NORMAL_MAP #define CC_SURFACES_USE_TANGENT_SPACE USE_NORMAL_MAP }% diff --git a/editor/assets/primitives.fbx.meta b/editor/assets/primitives.fbx.meta index d4bb5bcfb7..28f22c7465 100644 --- a/editor/assets/primitives.fbx.meta +++ b/editor/assets/primitives.fbx.meta @@ -1,5 +1,5 @@ { - "ver": "2.3.0", + "ver": "2.3.1", "importer": "fbx", "imported": true, "uuid": "1263d74c-8167-4928-91a6-4e2672411f47", diff --git a/editor/inspector/assets/fbx/fbx.js b/editor/inspector/assets/fbx/fbx.js index dacbb0a613..ed26af1b91 100644 --- a/editor/inspector/assets/fbx/fbx.js +++ b/editor/inspector/assets/fbx/fbx.js @@ -242,6 +242,7 @@ exports.methods = { }); this.dispatch('change'); + this.dispatch('track', { tab: 'fbx', prop, value: event.target.value }); }, /** * Update whether a data is editable in multi-select state diff --git a/editor/inspector/assets/fbx/index.js b/editor/inspector/assets/fbx/index.js index 029e6544c6..b69a6e6f13 100644 --- a/editor/inspector/assets/fbx/index.js +++ b/editor/inspector/assets/fbx/index.js @@ -149,3 +149,28 @@ exports.methods = { } }, }; + + +exports.listeners = { + 'track'(event) { + + if (event.args?.length) { + const { prop, value } = event.args[0]; + if (!value) { return; } // 只有被勾选的时候上报埋点 + + const trackMap = { + meshOptimizer: 'A100000', + 'fbx.smartMaterialEnabled': 'A100001', + disableMeshSplit: 'A100002', + }; + const trackId = trackMap[prop]; + if (trackId) { + Editor.Metrics._trackEventWithTimer({ + category: 'importSystem', + id: trackId, + value: 1, + }); + } + } + }, +}; diff --git a/editor/inspector/assets/fbx/material.js b/editor/inspector/assets/fbx/material.js index c10e4e0cf8..a342204bac 100644 --- a/editor/inspector/assets/fbx/material.js +++ b/editor/inspector/assets/fbx/material.js @@ -355,6 +355,7 @@ exports.methods = { }); this.dispatch('change'); + this.dispatch('track', { tab: 'material', prop, value: event.target.value }); }, /** * Update whether a data is editable in multi-select state diff --git a/editor/inspector/assets/fbx/model.js b/editor/inspector/assets/fbx/model.js index 44def8d59d..d9ed449ddd 100644 --- a/editor/inspector/assets/fbx/model.js +++ b/editor/inspector/assets/fbx/model.js @@ -363,7 +363,7 @@ const Elements = { }, }; -exports.update = function (assetList, metaList) { +exports.update = function(assetList, metaList) { this.assetList = assetList; this.metaList = metaList; this.asset = assetList[0]; @@ -377,7 +377,7 @@ exports.update = function (assetList, metaList) { } }; -exports.ready = function () { +exports.ready = function() { for (const prop in Elements) { const element = Elements[prop]; if (element.ready) { @@ -386,7 +386,7 @@ exports.ready = function () { } }; -exports.close = function () { +exports.close = function() { for (const prop in Elements) { const element = Elements[prop]; if (element.close) { @@ -410,8 +410,8 @@ exports.methods = { meta.userData[prop] = value; }); - this.dispatch('change'); + this.dispatch('track', { tab: 'model', prop, value: event.target.value }); }, setMeshOptimizerOptions(prop, event) { this.metaList.forEach((meta) => { diff --git a/editor/inspector/assets/image.js b/editor/inspector/assets/image.js index 2acf90eccc..103a06a47f 100644 --- a/editor/inspector/assets/image.js +++ b/editor/inspector/assets/image.js @@ -73,7 +73,7 @@ const Elements = { const panel = this; panel.$.typeSelect.addEventListener('change', (event) => { - // metaList 时以以选中的第一个 asset 的类型进行处理 + // metaList take the type of the first asset selected to solve let spriteFrameChange; if (panel.meta.userData.type === 'sprite-frame') { spriteFrameChange = 'spriteFrameToOthers'; @@ -84,13 +84,14 @@ const Elements = { panel.metaList.forEach((meta) => { meta.userData.type = event.target.value; }); - panel.dispatch('change'); // There are other properties whose updates depend on its changes attribute corresponds to the edit element Elements.isRGBE.update.call(panel); Elements.fixAlphaTransparencyArtifacts.update.call(panel); - // imageAssets 类型有 spriteFrame 变化的话需要处理 mipmaps + // imageAssets type change to spriteFrame, update mipmaps panel.updatePanel(spriteFrameChange); + // need to be dispatched after updatePanel + panel.dispatch('change'); }); }, update() { diff --git a/editor/inspector/components/batched-skinning-model.js b/editor/inspector/components/batched-skinning-model.js index 797d673737..d30ef5ee07 100644 --- a/editor/inspector/components/batched-skinning-model.js +++ b/editor/inspector/components/batched-skinning-model.js @@ -19,25 +19,27 @@ exports.ready = function() { $button.innerText = 'Cook'; $prop.appendChild($button); - $button.addEventListener('confirm', () => { + $button.addEventListener('confirm', async () => { Editor.Message.send('scene', 'snapshot'); const uuids = this.dump.value.uuid.values || [this.dump.value.uuid.value]; - uuids.forEach((uuid) => { - Editor.Message.send('scene', 'execute-component-method', { + for (const uuid of uuids) { + await Editor.Message.request('scene', 'execute-component-method', { uuid: uuid, name: 'cook', args: [], }); - }); + } - uuids.forEach((uuid) => { - Editor.Message.send('scene', 'execute-component-method', { + for (const uuid of uuids) { + await Editor.Message.request('scene', 'execute-component-method', { uuid: uuid, name: 'combine', args: [], }); - }); + } + + Editor.Message.send('scene', 'snapshot'); }); }; diff --git a/editor/inspector/components/particle-system-2d.js b/editor/inspector/components/particle-system-2d.js index 2255796283..401cb73686 100644 --- a/editor/inspector/components/particle-system-2d.js +++ b/editor/inspector/components/particle-system-2d.js @@ -91,6 +91,8 @@ exports.ready = function() { this.$this.dispatch('change-dump'); } + + Editor.Message.send('scene', 'snapshot'); }); const $export = document.createElement('ui-button'); @@ -128,6 +130,8 @@ exports.ready = function() { this.$this.dispatch('change-dump'); } + + Editor.Message.send('scene', 'snapshot'); }); this.$.syncButton = $sync; diff --git a/editor/inspector/components/particle-system.js b/editor/inspector/components/particle-system.js index 4aed84e75a..dd26951863 100644 --- a/editor/inspector/components/particle-system.js +++ b/editor/inspector/components/particle-system.js @@ -699,3 +699,54 @@ exports.style = /* css */` margin-left: 10px; } `; + +exports.listeners = { + async 'change-dump'(event) { + + const target = event.target; + if (!target) { + return; + } + + const dump = event.target.dump; + if (!dump) { + return; + } + + // renderMode选择mesh次数 + if (dump.path.endsWith('renderer.renderMode') && dump.value === 4) { + Editor.Metrics._trackEventWithTimer({ + category: 'particleSystem', + id: 'A100011', + value: 1, + }); + } + + // 粒子系统其他模块埋点 + const trackMap = { + 'noiseModule.enable': 'A100000', + 'shapeModule.enable': 'A100001', + velocityOvertimeModule: 'A100002', + forceOvertimeModule: 'A100003', + 'sizeOvertimeModule.enable': 'A100004', + 'rotationOvertimeModule.enable': 'A100005', + colorOverLifetimeModule: 'A100006', + textureAnimationModule: 'A100007', + 'limitVelocityOvertimeModule.enable':'A100008', + 'trailModule.enable': 'A100009', + 'renderer.useGPU': 'A100010', + }; + + const dumpKey = Object.keys(trackMap).find(key => dump.path.endsWith(key)); + if (!dumpKey) { return; } + + const value = dump.type === 'Boolean' ? dump.value : dump.value.enable.value; + if (!value) { return; } + + Editor.Metrics._trackEventWithTimer({ + category: 'particleSystem', + id: trackMap[dumpKey], + value: 1, + }); + }, +}; diff --git a/editor/inspector/components/polygon-collider.js b/editor/inspector/components/polygon-collider.js index b1a62efc86..b217d462f5 100644 --- a/editor/inspector/components/polygon-collider.js +++ b/editor/inspector/components/polygon-collider.js @@ -23,14 +23,15 @@ exports.ready = function() { Editor.Message.send('scene', 'snapshot'); }); - $button.addEventListener('confirm', (event) => { + $button.addEventListener('confirm', async (event) => { event.stopPropagation(); const uuids = this.dump.value.uuid.values || [this.dump.value.uuid.value]; + for (const uuid of uuids) { + await Editor.Message.request('scene', 'regenerate-polygon-2d-points', uuid); + } - uuids.forEach((uuid) => { - Editor.Message.request('scene', 'regenerate-polygon-2d-points', uuid); - }); + Editor.Message.send('scene', 'snapshot'); }); }, }, diff --git a/editor/inspector/contributions/asset.css b/editor/inspector/contributions/asset.css index 51f52e0cfa..1dcd18a4b5 100644 --- a/editor/inspector/contributions/asset.css +++ b/editor/inspector/contributions/asset.css @@ -21,14 +21,15 @@ } :host > .container > .header > .icon { - width: 20px; - font-size: 14px; + width: 16px; + font-size: 12px; cursor: pointer; } :host > .container > .header > .image { width: 20px; - height: 24px; + height: 20px; + margin-top: 2px; cursor: pointer; } @@ -39,14 +40,14 @@ :host > .container > .header > .name { flex: 1; - padding-left: 5px; + padding-left: 4px; text-overflow: ellipsis; overflow: hidden; white-space: nowrap; } :host > .container > .header > .name[readonly] { - opacity: 0.5; + opacity: 0.55; } :host > .container > .header > .help { @@ -69,6 +70,7 @@ height: 20px; line-height: 20px; margin-left: 8px; + margin-top: 2px; } :host > .container > .header[dirty] > .tiny { diff --git a/editor/inspector/contributions/node.css b/editor/inspector/contributions/node.css index a308940dcd..f5b7c383fe 100644 --- a/editor/inspector/contributions/node.css +++ b/editor/inspector/contributions/node.css @@ -61,6 +61,10 @@ margin: 10px 0; } +.scene ui-section div[slot="header"] ui-link { + margin-right: 4px; +} + :host([type="node"][sub-type='scene']) > .container > .scene { display: block; } @@ -188,10 +192,10 @@ } .section-asset > ui-panel[type="asset"] { - margin-bottom: 8px; - border-radius: 8px; + margin-bottom: 4px; + border-radius: 2px; } .section-asset > ui-panel[type="asset"][focused] { - box-shadow: var(--color-normal-fill-emphasis) 0 0 4px; + box-shadow: var(--color-primary-contrast-weakest) 0 0 4px; } diff --git a/editor/inspector/contributions/node.js b/editor/inspector/contributions/node.js index 10d7eccd8d..3d0e7fe1ec 100644 --- a/editor/inspector/contributions/node.js +++ b/editor/inspector/contributions/node.js @@ -69,7 +69,7 @@ exports.listeners = { } if (setChildrenLayer) { - Editor.Message.send('scene', 'set-node-and-children-layer', { + await Editor.Message.request('scene', 'set-node-and-children-layer', { uuid, dump: { value, @@ -79,7 +79,7 @@ exports.listeners = { continue; } - Editor.Message.send('scene', 'set-property', { + await Editor.Message.request('scene', 'set-property', { uuid, path, dump: { @@ -89,6 +89,8 @@ exports.listeners = { }, }); } + + Editor.Message.send('scene', 'snapshot'); } catch (error) { console.error(error); } @@ -98,7 +100,7 @@ exports.listeners = { panel.snapshotLock = false; }, - 'create-dump'(event) { + async 'create-dump'(event) { const panel = this; const target = event.target; @@ -117,16 +119,18 @@ exports.listeners = { dump.values[i] = dump.value; } - Editor.Message.send('scene', 'update-property-from-null', { + await Editor.Message.request('scene', 'update-property-from-null', { uuid, path: dump.path, }); } + + Editor.Message.send('scene', 'snapshot'); } catch (error) { console.error(error); } }, - 'reset-dump'(event) { + async 'reset-dump'(event) { const panel = this; const target = event.target; @@ -145,11 +149,13 @@ exports.listeners = { dump.values[i] = dump.value; } - Editor.Message.send('scene', 'reset-property', { + await Editor.Message.request('scene', 'reset-property', { uuid, path: dump.path, }); } + + Editor.Message.send('scene', 'snapshot'); } catch (error) { console.error(error); } @@ -308,9 +314,7 @@ exports.template = /* html*/`
-
-