Compare commits

..

147 Commits

Author SHA1 Message Date
llsansun ff0f46ff81 engine upgrade (#368) 2026-10-12 17:42:54 +08:00
yangchao 0616a948ef fix(audio): iterator invalidation、exit crash issue。 (#360)
* fix(audio): iterator invalidation when call stopall in finish callback

* fix(audio): prevent callback crashes and cache teardown hangs on Apple platforms

---------

Co-authored-by: yangchao <1162486779@qq.com>
2026-09-24 11:25:09 +08:00
yangchao ee89a99a9b fix(v8): fix iterator invalidation when removing handled promises (#357)
* fix(v8): fix iterator invalidation when removing handled promises

* fix(native): prevent iterator invalidation in callbacks and scheduler
2026-09-23 16:28:56 +08:00
llsansun f620989ce7 The final set skeleton call destroys and rebuilds the GPU bone reso… (#359)
* The final `set skeleton` call destroys and rebuilds the GPU bone resources that were bound in the previous two steps. However, the descriptor set is not rebound. As a result, the draw call for this subModel cannot access the bone matrices, so the entire character fails to render (this is not vertex deformation; the character does not appear at all). The fix should replace the reference in `descriptor.buffer` with the new buffer, mark it dirty, and lazily rebuild the descriptor before the next draw.

* opt
2026-09-23 16:18:03 +08:00
jk20012001 661de759ef fix(shader): HDR output for all floating point render targets (#351) 2026-09-22 11:50:47 +08:00
Tianze-Chen 0ab8246486 feat(ui): add component-level event API for Button (#356)
Add `on`/`off`/`targetOff` shorthands on Button that forward to the
owner node's event registry, so `button.on(Button.EventType.CLICK, ...)`
is now the documented way to listen for clicks in code (closes #104).

The CLICK event also carries the original EventTouch as the second
callback argument (non-breaking; XR-triggered clicks pass undefined).
Fix the outdated class doc example which referenced the non-existent
`Node.EventType.CLICK`, and correct the swapped `@param` docs on
ButtonEventType.

Co-authored-by: Engineer <engineer@cocos.com>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-09-22 10:21:20 +08:00
zxx43 67642997f7 modify emit rate (#352)
* modify emit rate

* fix eslint

* fix eslint

* fix eslint

* fix
2026-09-21 17:07:35 +08:00
MagicX 3be9ebc5b7 fix: prevent accessor recursion in SkinnedMeshBatchRenderer. (#354)
* Changed the GeometryRenderer and DebugRenderer from using intrusive calls to registering callbacks (custom pipeline).

* Changed the GeometryRenderer and DebugRenderer from using intrusive calls to registering callbacks. (old pipeline)

* CI error: Function parameter names cannot be omitted.

* Move the devil string to macro

* fix(mesh): hoose index format by max index value in createMesh

* perf(pipeline): reduce render queue sort to two packed key compares (native platform).

* fix CI error caused by native/cocos/base/Utils.h

* fix(scene): LOD screen usage distance truncated to int (native platform)

* fix: prevent accessor recursion in SkinnedMeshBatchRenderer.
2026-09-21 10:27:35 +08:00
hyde zhou 47ebc462e5 bump version to 4.0.0-alpha.35 (#353) 2026-09-20 17:33:35 +08:00
Tianze-Chen b4bea55859 fix(label): abnormal font display when label text is too long (#348)
A very long label string (e.g. 8000+ characters) makes the text layout
canvas exceed MAX_SIZE, so the font is meant to be scaled down by the
shrink ratio. Clamping _fontScale to a minimum of 1 defeated that
downscale and the text displayed abnormally; lower the floor to 0.1 so
the font can shrink with the canvas.

Fixes #344

Co-authored-by: ctz <ctz@ctzdeMacBook-Air.local>
Co-authored-by: Claude Code <noreply@anthropic.com>
2026-09-20 17:27:24 +08:00
Cocos Robot 82f13c86e9 [ci skip][AUTO]: Automated clang-format update: d67d6ac324 (#341) (#342)
Co-authored-by: cocos-robot <cocos-robot@cocos.com>
2026-09-20 17:22:37 +08:00
zxx43 0fd910220e reset bone.active after updateCache (#340)
* reset bone.active after updateCache

* upload version
2026-09-20 10:13:12 +08:00
MagicX 557b06f7e6 fix(scene): LOD screen usage distance truncated to int (native platform) (#343)
* Changed the GeometryRenderer and DebugRenderer from using intrusive calls to registering callbacks (custom pipeline).

* Changed the GeometryRenderer and DebugRenderer from using intrusive calls to registering callbacks. (old pipeline)

* CI error: Function parameter names cannot be omitted.

* Move the devil string to macro

* fix(mesh): hoose index format by max index value in createMesh

* perf(pipeline): reduce render queue sort to two packed key compares (native platform).

* fix CI error caused by native/cocos/base/Utils.h

* fix(scene): LOD screen usage distance truncated to int (native platform)
2026-09-17 18:59:26 +08:00
MagicX b46553e615 perf(pipeline): reduce render queue sort to two packed key compares (native platform). (#341)
* Changed the GeometryRenderer and DebugRenderer from using intrusive calls to registering callbacks (custom pipeline).

* Changed the GeometryRenderer and DebugRenderer from using intrusive calls to registering callbacks. (old pipeline)

* CI error: Function parameter names cannot be omitted.

* Move the devil string to macro

* fix(mesh): hoose index format by max index value in createMesh

* perf(pipeline): reduce render queue sort to two packed key compares (native platform).

* fix CI error caused by native/cocos/base/Utils.h
2026-09-17 09:35:05 +08:00
hyde zhou fffd9a514a bump version to 4.0.0-alpha.34 (#339) 2026-09-14 17:55:42 +08:00
Cocos Robot 5678d0d17c [ci skip][AUTO]: Automated clang-format update: f264405b7e (#330) (#331)
Co-authored-by: cocos-robot <cocos-robot@cocos.com>
2026-09-14 17:03:08 +08:00
Cocos Robot 2ce7b89be5 [ci skip][AUTO]: Automated clang-format update: ffc817b76f (#336) (#337)
Co-authored-by: cocos-robot <cocos-robot@cocos.com>
2026-09-14 17:02:34 +08:00
zxx43 6b455561f4 optimize noise function (#338)
* optimize noise function

* format
2026-09-14 16:06:30 +08:00
MagicX 60f9352c56 fix(mesh): hoose index format by max index value in createMesh (#336)
* Changed the GeometryRenderer and DebugRenderer from using intrusive calls to registering callbacks (custom pipeline).

* Changed the GeometryRenderer and DebugRenderer from using intrusive calls to registering callbacks. (old pipeline)

* CI error: Function parameter names cannot be omitted.

* Move the devil string to macro

* fix(mesh): hoose index format by max index value in createMesh
2026-09-14 14:10:33 +08:00
李吉林 f66365f959 add @visible(false) for TerrainInfo (#334) 2026-09-11 15:09:24 +08:00
MagicXHouse a3c3fcbea5 Changed the GeometryRenderer and DebugRenderer from using intrusive calls to registering callbacks. (#330)
* Changed the GeometryRenderer and DebugRenderer from using intrusive calls to registering callbacks (custom pipeline).

* Changed the GeometryRenderer and DebugRenderer from using intrusive calls to registering callbacks. (old pipeline)

* CI error: Function parameter names cannot be omitted.

* Move the devil string to macro
2026-09-08 19:35:05 +08:00
Ming 2a75cfb9da fix(webgpu): fix error pipelinelayout order (#329)
Co-authored-by: vanitynie <vanitynie@qq.com>
2026-09-08 11:27:06 +08:00
yangchao 0c3f4534b8 fix: normalize asset root path for source_group on windows (#324) 2026-09-07 21:41:36 +08:00
hyde zhou 7f806abad6 bump version to 4.0.0-alpha.33 (#328) 2026-09-07 20:00:19 +08:00
Ming df98a99bb6 fix(wgpu): correct swapped maxComputeWorkGroupSize/Count capabilities (#327)
Co-authored-by: vanitynie <vanitynie@qq.com>
2026-09-07 19:00:55 +08:00
Ming a5090e5ae4 add compute shader on webgpu (#323)
* feat(webgpu): support compute shader on webgpu

* fix(webgpu): fix webComputePassBuilder addTexture and descriptor set bind

* fix(webgpu): mark compute producer passes valid and force-prepare bound descriptor sets

* feat(profiler): add compute dispatch counter

* perf(webgpu): cache compute pipeline states

* refactor(webgpu): simplify descriptor set prepare and dedupe bind group collection

- WebGPUDescriptorSet.prepare(): build the bind group when it was never created,
  so command buffers no longer need a force-prepare branch.
- WebGPUCommandBuffer: extract _collectBindGroups() shared by the draw and
  compute paths; drop the defaultResource bind group fallback since prepare()
  now guarantees a valid bind group.
- executor: guard PreRenderVisitor.dispatch with the COMPUTE_SHADER feature
  (symmetric with PostRenderVisitor.compute) and drop the redundant pass check.

* fix(webgpu): respect storage buffer access type in bind group layout

* fix(types): narrow types to pass tsc  check

* chore(webgpu): clean up redundant assertions and long line in pipeline state

---------

Co-authored-by: VanityNie <vanitynie@qq.com>
2026-09-07 14:36:06 +08:00
zxx43 3b71bf6935 fix particle2d preview error (#326) 2026-09-05 18:58:01 +08:00
J.C 54fd070848 wrong const value passed for webgl2 to op with image 3d (#297) 2026-09-04 15:06:32 +08:00
llsansun 6722aac669 When copying the old buffer value, if the old value is undefined (o… (#321)
* When copying the old buffer value, if the old value is `undefined` (out‑of‑bounds access to an empty array), preserve the default value of `-1` instead of writing `undefined`.

* opt
2026-09-02 18:02:58 +08:00
hyde zhou 68552314c0 bump version to 4.0.0-alpha.32 (#320) 2026-09-01 21:13:19 +08:00
zxx43 550eb15641 add line updateColor function (#317)
* add line setColor function

* fix eslint

* modify setColor to updateColor
2026-08-31 11:56:37 +08:00
Ming c438c2d3f8 fix(rendering): compute render pass merge info in render graph order (#314) 2026-08-29 17:39:20 +08:00
zxx43 f5eaf97ce7 add opacity calculation to Particle System 2D (#307)
* add opacity calculation to Particle System 2D

* modify format
2026-08-25 18:37:08 +08:00
zxx43 69d3d6033a fix message error (#304) 2026-08-24 11:13:30 +08:00
yangchao 469614cf0b fix ios build problem (#292) 2026-08-23 12:01:54 +08:00
Cocos Robot f81094f226 [ci skip][AUTO]: Automated clang-format update: 6c156997c2 (#293) (#301)
Co-authored-by: cocos-robot <cocos-robot@cocos.com>
2026-08-23 11:07:26 +08:00
Ming 825362fac1 fix(webgl): correct buffer-to-texture extent height calculation (#303)
Use regionTexExtentHeight instead of regionTexExtentWidth when calculating copied texture extents to prevent incorrect row and slice strides.

Co-authored-by: vanitynie <vanitynie@qq.com>
2026-08-21 12:27:25 +08:00
ChiaNing 609512f8da fix(ui):keep destroy widgets out of the widget's active list (#302) 2026-08-21 10:04:48 +08:00
troublemaker52025 09b63786f4 fix(legacy): sync instanced buffer batching optimization to native (#293) 2026-08-20 15:56:12 +08:00
MagicXHouse 2b7b438768 Fix: Fixed the issue where custom pipeline profiler were not displaying. (#295) 2026-08-20 11:26:22 +08:00
xubing0906 6b5c8556a2 Fix Builtin reflection probe culling by passing the probe context to … (#186) 2026-08-19 17:25:21 +08:00
昌敦伟 ff436d6a27 fix: balance Texture2D image dependency references (#267) 2026-08-19 16:05:59 +08:00
hyde zhou 09c38ea03f bump version to 4.0.0-alpha.31 (#290) 2026-08-17 17:53:49 +08:00
qiuguohua 926bd5b619 chore(platform): privatize platform; migrate to platform subrepo (#289) 2026-08-17 17:26:19 +08:00
徐兵 e317c04512 fix planar reflections for editor camera previews (#236) 2026-08-17 17:25:14 +08:00
Cocos Robot 140068ddb1 [ci skip][AUTO]: Automated code generating update: 233020bafe (#287) (#288)
Co-authored-by: cocos-robot <cocos-robot@cocos.com>
2026-08-16 18:22:23 +08:00
hyde zhou 80a9d0619e ignore cocos-version.h (#287) 2026-08-16 18:17:09 +08:00
Cocos Robot a01046e391 [ci skip][AUTO]: Automated clang-format update: 25bf4eb07b (#284) (#285)
Co-authored-by: cocos-robot <cocos-robot@cocos.com>
2026-08-16 17:13:20 +08:00
Cocos Robot 2b6ec3b4f0 [ci skip][AUTO]: Automated code generating update: cdd07414a3 (#278) (#284)
Co-authored-by: cocos-robot <cocos-robot@cocos.com>
2026-08-16 17:07:21 +08:00
Cocos Robot 6060f58d1a [ci skip][AUTO]: Automated clang-format update: 3a76374539 (#277) (#278)
Co-authored-by: cocos-robot <cocos-robot@cocos.com>
2026-08-16 17:01:44 +08:00
hyde zhou 18456b6706 try fixing previous clang format ignore (#277) 2026-08-15 23:32:02 +08:00
hyde zhou 62b55a0c48 Revert "fix: exclude spine 4.2 third-party files from clang-format (#273)" (#275)
This reverts commit 01983b75f2.
2026-08-15 20:17:08 +08:00
Copilot 0eac18be1a Fix Clang-Format workflow failure caused by shallow checkout state (#274)
* Initial plan

* Fix Clang-Format workflow shallow fetch failure

Co-authored-by: star-e <13654656+star-e@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: star-e <13654656+star-e@users.noreply.github.com>
2026-08-15 19:50:32 +08:00
Copilot 01983b75f2 fix: exclude spine 4.2 third-party files from clang-format (#273) 2026-08-15 18:34:08 +08:00
jk20012001 2d003cc616 fix punctual lights visibility issue with custom pipeline (#270) (#272) 2026-08-15 15:36:26 +08:00
zxx43 b710cb6e9b fix both null condition (#260)
* fix both null condition

* simplify check condition

* simplify check condition
2026-08-14 17:21:26 +08:00
llsansun f948b5900e perf: optimize instanced buffer batching (#269)
* perf: optimize instanced buffer batching

* perf: reduce instanced buffer optimization code size

* perf: reduce instanced buffer optimization code size

* perf: reduce instanced buffer optimization code size
2026-08-14 16:44:35 +08:00
zxx43 b7883f18ba fix boneIdx check error (#264)
* fix boneIdx check error

* simplify check
2026-08-14 16:41:08 +08:00
troublemaker52025 3ab299035a fix(legacy): Mask component stencil test error for native (#266) 2026-08-14 15:49:57 +08:00
zxx43 c2ab919e9d fix native crash by null material bug (#268) 2026-08-14 15:38:17 +08:00
qiuguohua 5690d1b8a5 fix(google-play): set PROP_MIN_SDK_VERSION to 24 (#262)
play-services-oss-licenses, introduced on Feb 2, 2026, requires minSdkVersion 24.
https://developers.google.com/android/guides/releases
2026-08-11 19:35:31 +08:00
hyde zhou ed0751652b bump version to 4.0.0-alpha.30 (#259) 2026-08-08 20:33:50 +08:00
hyde zhou 97e402c3dc Merge pull request #255 from cocos/v4.0.0-alpha.29
update version, fix libwebp compile err. (#247)
2026-08-08 17:44:37 +08:00
Copilot f378a866cb Fix Clang-Format CI: replace distutils-dependent action with maintained upstream (#257)
* Initial plan

* Fix Clang-Format CI: replace fish9167/clang-format-lint-action@master with DoozyX/clang-format-lint-action@v0.18

Co-authored-by: star-e <13654656+star-e@users.noreply.github.com>

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: star-e <13654656+star-e@users.noreply.github.com>
2026-08-08 17:44:10 +08:00
Copilot 7253ee4a7f Fix ESLint CI job failure on tag push events (#256) 2026-08-08 16:59:07 +08:00
hyde zhou db5462603e Move pal directory to private repository (#191) (#254)
Co-authored-by: qiuguohua <qiuguohua111@126.com>
2026-08-08 16:20:49 +08:00
zxx43 9f0e30acb3 add approx functions (#252) 2026-08-07 18:40:33 +08:00
troublemaker52025 a0a2e97c00 fix(legacy): A2C (Alpha to Coverage) and (antialias or MSAA) are mutually exclusive (#233) 2026-08-07 16:27:27 +08:00
troublemaker52025 90e551b4a1 fix(legacy): the incorrect description of light visibility (#251) 2026-08-07 16:24:00 +08:00
Ming 0a21bb9397 fix(vulkan): fix split barrier events and general barrier submission (#240) 2026-08-07 16:03:46 +08:00
troublemaker52025 2c91155928 fix(legacy): sphere light has not lighting at LDR mode (#243) 2026-08-07 15:20:25 +08:00
llsansun 6f90cec3d4 Merge pull request #245 from zxx43/LogFix
modify success log level from loge to logd
2026-08-05 18:51:56 +08:00
yangchao 4992692780 update version, fix libwebp compile err. (#247) 2026-08-05 16:11:33 +08:00
徐兵 d5f24e6170 Merge pull request #246 from xubing0906/v4.0.0-skybox
fix(rendering): skip environment specular sampling when IBL is disabled in reflection probe fallback
2026-08-05 16:00:31 +08:00
zxx43 e778833d15 modify success log level from loge to logd 2026-08-05 12:05:12 +08:00
hyde zhou c3a8a72f63 bump version to 4.0.0-alpha.29 (#237) 2026-08-02 21:25:47 +08:00
yangchao 2c0e75059f xcode > 14.3 apple silicon use arm64 arch for ios simulation。 (#214) 2026-08-02 17:52:06 +08:00
zxx43 19f4bd5b16 call ClearMaterialCaches when change tint state (#234) 2026-07-31 17:24:28 +08:00
徐兵 085d05928d fix(shader): fix lighting discontinuity at mirrored UV seams (#209) 2026-07-31 17:19:29 +08:00
Tianze-Chen fb4d586629 fix(2d): retain Graphics data while disabled (#230) 2026-07-31 17:03:55 +08:00
troublemaker52025 620d38cf42 Fix(legacy): only DEFAULT layer has lighting (#227) 2026-07-31 16:49:41 +08:00
zxx43 d2713fe00e fix loop duration time (#213) 2026-07-31 16:39:08 +08:00
hyde zhou 3aeb193d42 bump version to 4.0.0-alpha.28 (#226) 2026-07-24 17:30:01 +08:00
Cocos Robot c4e4790ee6 [ci skip][AUTO]: Automated code generating update: 8e77b19f89 (#218) (#219) 2026-07-24 16:49:29 +08:00
troublemaker52025 143af30cf2 feat(legacy): optmize render-additive-light-queue.ts code (#212) 2026-07-21 16:56:11 +08:00
hyde zhou d6ff23fed4 Revert "fix: use PR_TOKEN for create-pull-request fork collab permission (#216)" (#218) 2026-07-21 16:41:03 +08:00
Copilot 84e8d4ebf7 fix: use PR_TOKEN for create-pull-request fork collab permission (#216) 2026-07-21 16:01:42 +08:00
Copilot f2b9936033 fix: replace fish9167/create-pull-request@v3 to resolve token permission error in autogen-code job (#215) 2026-07-21 14:48:19 +08:00
troublemaker52025 129eb437ad fix(legacy): GPU Instancec memory leak in C++ (#211) 2026-07-21 10:56:43 +08:00
hyde zhou c58c893334 bump version to 4.0.0-alpha.27 (#210) 2026-07-20 16:38:33 +08:00
zxx43 ab982aec68 fix index buffer access bug (#205) 2026-07-20 14:14:38 +08:00
徐兵 2d2bbe6731 Use TONE_MAPPING_ACES constant for CC_TONE_MAPPING_TYPE check, skip ACESToneMap in linear mode. (#196) 2026-07-20 14:13:02 +08:00
hyde zhou 187387b03f fix eventWebGLContextLost (#206) 2026-07-20 10:04:57 +08:00
zxx43 661253a521 fix particle trail crash bug (#201) 2026-07-20 09:55:24 +08:00
troublemaker52025 b6d0f02e88 fix(SRP): use lightIdx instead of loop index l in GPU instancing forw… (#198) 2026-07-20 09:52:57 +08:00
troublemaker52025 dd1b155d3a fix(legacy): custom attribute that set format error (#207) 2026-07-20 09:49:10 +08:00
troublemaker52025 df96ee85f3 fix(SRP): crash when native OpenAL is unavailable (#195) 2026-07-15 16:45:36 +08:00
hyde zhou 708a343ce8 bump version to 4.0.0-alpha.26 (#199) 2026-07-13 16:23:49 +08:00
troublemaker52025 393203c2f8 fix(SRP): render-data.ts eslint error (#192) 2026-07-10 15:02:04 +08:00
troublemaker52025 f3d11f017b fix(SRP): A Summary of the Usage Guidelines for 65535 and 65536 (#190) 2026-07-10 14:59:03 +08:00
troublemaker52025 09c201017c fix(standard): spelling errors (#188) 2026-07-08 17:52:23 +08:00
zxx43 ce6107d930 set material parent then set materialInstance to remove error message (#187) 2026-07-08 17:50:44 +08:00
bofeng-song ab8792686b feat(spine): support runtime-selectable spine version for editor/preview (#184) 2026-07-07 14:59:24 +08:00
hyde zhou 44ef76855b bump version to 4.0.0-alpha.25 (#183) 2026-07-06 21:52:51 +08:00
bofeng-song 8878e7aade fix(assets): guard Material/Texture event callbacks against teardown/GC crash (#170) 2026-07-06 20:53:29 +08:00
zxx43 621880a123 use default trail material to fix native particle case crash (#180) 2026-07-06 20:52:48 +08:00
troublemaker52025 2eb268bf9a fix(standard): V8 crash in app shutdown (#178) 2026-07-06 19:09:10 +08:00
troublemaker52025 2e6cc9b127 fix(custom-pipeline): Creates a blit descriptor bug (#169) 2026-07-03 18:25:21 +08:00
hyde zhou 98917ff2a7 Revert "删除多余的构建模板 (#177)" (#179)
This reverts commit dc29d2f8f8.
2026-07-02 18:06:57 +08:00
tangkai dc29d2f8f8 删除多余的构建模板 (#177) 2026-07-02 11:30:59 +08:00
hyde zhou eec2a1693b bump version to 4.0.0-alpha.24 (#175) 2026-06-29 19:14:44 +08:00
hyde zhou 632f9b442f Revert "fix(ci): globally install @cctest/scheduler in Windows test jobs (#173)" (#174)
This reverts commit 8ce19b658e.
2026-06-29 19:07:53 +08:00
Copilot 8ce19b658e fix(ci): globally install @cctest/scheduler in Windows test jobs (#173) 2026-06-29 18:21:05 +08:00
troublemaker52025 07f2c5fb43 fix(custom-pipeline) addLight() func, return byte offset error (#167) 2026-06-26 10:05:22 +08:00
Knox 9b17fd6165 update primitives.fbx.meta (#166) 2026-06-24 14:30:59 +08:00
hyde zhou e2795f9ecd bump version to 4.0.0-alpha.23 (#163) 2026-06-22 17:16:44 +08:00
Leslie Leigh (李的序) 89a412e0d6 supress logs (#154) 2026-06-22 17:11:38 +08:00
qiuguohua aef31099d8 refactor: reorganize cache-manager and asset-manager modules (#159) 2026-06-22 16:02:14 +08:00
bofeng-song 89f8768e57 refine (#144)
(cherry picked from commit 18228e220290fe457e9c05227b32b05cff10a3f8)
2026-06-16 14:06:16 +08:00
bofeng-song 424be5d0b2 Revert "Fix the issue where cli class-registered does not receive messages. (#150)" (#151) 2026-06-16 13:06:16 +08:00
hyde zhou e5183b796a bump version to 4.0.0-alpha.22 (#155) 2026-06-15 16:14:03 +08:00
昌敦伟 32478c1a9c fix(assets): update default cubemap resources (#152) 2026-06-04 09:56:43 +08:00
hyde zhou 74e632a3d6 bump version to 4.0.0-alpha.21 (#153) 2026-06-04 09:55:11 +08:00
orchid-world 26883ba6f4 fix(physics-2d): correct circle collider world position (#142) 2026-06-03 14:29:15 +08:00
orchid-world 055c70f8d2 fix(physics-2d): avoid debug draw crash when toggling flags (#139)
Clear cached debug graphics instead of detaching the debug draw node when
debugDrawFlags is set to None. This keeps the cached node in a valid scene
state and prevents null parent access when debug draw is enabled again.

Add a regression test for toggling Box2D debug draw flags.
2026-06-03 14:28:19 +08:00
bofeng-song 99f6db401c Fix the issue where cli class-registered does not receive messages. (#150) 2026-06-03 14:15:15 +08:00
hyde zhou 9390ee6bc0 Revert "fix codegen (#148)" (#149)
This reverts commit 7f258dac58.
2026-06-02 19:26:13 +08:00
hyde zhou 7f258dac58 fix codegen (#148) 2026-06-02 18:59:58 +08:00
orchid-world 5c99570616 feat(2d): support rounded rect mask radius (#140) 2026-06-02 18:26:55 +08:00
hyde zhou 821928733b bump version to 4.0.0-alpha.20 (#145) 2026-06-01 18:03:01 +08:00
hyde zhou f567861ff6 bump version to 4.0.0-alpha.19 (#143) 2026-05-25 14:33:54 +08:00
hyde zhou a7a20b64ab bump version to 4.0.0-alpha.18 (#137) 2026-05-19 23:40:06 +08:00
hyde zhou 7c75834010 bump version to 4.0.0-alpha.17 (#135) 2026-05-11 23:18:35 +08:00
hyde zhou 8fd985af75 bump version to 4.0.0-alpha.16 (#134) 2026-05-07 15:35:41 +08:00
qiuguohua cc97bc8af4 V4.0.0 fix get window info cache (#123) 2026-05-07 15:16:18 +08:00
tangkai 92124590fe update (#131) 2026-04-29 16:10:42 +08:00
tangkai 822ac6026c update assets.js (#129) 2026-04-29 13:04:48 +08:00
hyde zhou 4a6f83bd6d Revert "refactor platforms (#126)" (#128) 2026-04-28 23:12:10 +08:00
tangkai 04f063eb2b add key value to assets.js (#127) 2026-04-28 23:09:53 +08:00
hyde zhou 910865bd8b refactor platforms (#126) 2026-04-28 18:53:46 +08:00
hyde zhou e384f54ed2 bump version to 4.0.0-alpha.15 (#125) 2026-04-28 16:46:44 +08:00
hyde zhou 5964835c83 bump version to 4.0.0-alpha.14 (#122) 2026-04-22 15:36:07 +08:00
tangkai f4ae16247c overrideClips_experimental error handle (#121) 2026-04-22 15:30:17 +08:00
qiuguohua 4b4a3ca13f Fix the issue where getWindowInfo does not have a cache, which causes lag. (#120) 2026-04-22 15:29:46 +08:00
hyde zhou f1c5d21be6 bump version to 4.0.0-alpha.13 (#119) 2026-04-15 14:09:42 +08:00
bofeng-song da75e89f4a export interface for CLI (#118) 2026-04-15 10:07:46 +08:00
hyde zhou aba27a715d bump version to 4.0.0-alpha.12 (#116) 2026-04-08 16:41:15 +08:00
837 changed files with 5798 additions and 58456 deletions
+8 -2
View File
@@ -20,8 +20,14 @@ if ($env:GITHUB_BASE_REF) {
# Push
$gitHubEvent = Get-Content $env:GITHUB_EVENT_PATH | ConvertFrom-Json
Write-Host "GitHub event: $gitHubEvent"
git fetch origin $gitHubEvent.before --depth=1
$diffFiles = git diff --name-only --diff-filter=$diffFilter $gitHubEvent.before $env:GITHUB_SHA
$beforeSha = $gitHubEvent.before
# On tag creation or initial push, before is all zeros - skip diff in that case
if ($beforeSha -match '^0+$') {
Write-Host "No previous commit (tag creation or initial push). Skipping diff."
return
}
git fetch origin $beforeSha --depth=1
$diffFiles = git diff --name-only --diff-filter=$diffFilter $beforeSha $env:GITHUB_SHA
}
Write-Host "Diff files: $diffFiles"
+4 -8
View File
@@ -18,6 +18,7 @@ jobs:
with:
token: ${{ github.token }}
ref: ${{ github.head_sha }}
fetch-depth: 0
- id: get_change_files
uses: fish9167/file-changes-action@v1.2.3
@@ -25,18 +26,13 @@ jobs:
output: ' '
fileOutput: ' '
- name: Echo change files
run: |
cat $HOME/files.txt
mv $HOME/files.txt ${{github.workspace}}/files.txt
- uses: fish9167/clang-format-lint-action@master
- uses: DoozyX/clang-format-lint-action@v0.18
with:
source: ./native
exclude: ./native/cocos/bindings/auto
exclude: ./native/cocos/bindings/auto ./native/cocos/base/std ./native/cocos/editor-support/spine-wasm ./native/cocos/editor-support/spine ./native/cocos/gi/light-probe/predicates.cpp ./native/cocos/gi/light-probe/tetgen.cpp ./native/cocos/gi/light-probe/tetgen.h ./native/cocos/platform/openharmony/napi ./native/tools ./native/vendor ./native/cocos/cocos-version.h
extensions: 'c,h,hpp,cpp,cxx'
style: file
inplace: True
inplace: true
clangFormatVersion: 12
- name: Create Pull Request
@@ -483,8 +483,8 @@ jobs:
echo "set(CC_USE_GLES3 OFF)" >> build-mac/proj/cfg.cmake
echo "set(CC_USE_METAL ON)" >> build-mac/proj/cfg.cmake
# Test JSVM v8 backend on macOS.
echo "set(USE_SE_V8 OFF)" >> build-mac/proj/cfg.cmake
echo "set(USE_SE_JSVM ON)" >> build-mac/proj/cfg.cmake
echo "set(USE_SE_V8 ON)" >> build-mac/proj/cfg.cmake
echo "set(USE_SE_JSVM OFF)" >> build-mac/proj/cfg.cmake
echo "set(USE_WEBSOCKET_SERVER OFF)" >> build-mac/proj/cfg.cmake
echo "set(CMAKE_CXX_STANDARD_REQUIRED ON)" >> build-mac/proj/cfg.cmake
echo "set(CC_EXECUTABLE_NAME \"\")" >> build-mac/proj/cfg.cmake
@@ -493,7 +493,6 @@ jobs:
RES_DIR=$GITHUB_WORKSPACE/templates/mac/build-mac
cd build-mac
cmake ../ -GXcode -DCMAKE_OSX_ARCHITECTURES=${{ matrix.config.arch }} -DRES_DIR=$RES_DIR -DCOCOS_X_PATH=$NATIVE_ROOT
set +e
cmake --build . --config Release -- -jobs $NUM_OF_CORES -arch ${{ matrix.config.arch }}
echo "Compile MacOSX Release Done!"
@@ -534,7 +533,7 @@ jobs:
echo "set(CC_USE_VULKAN OFF)" >> build-ios/proj/cfg.cmake
echo "set(CC_USE_GLES2 OFF)" >> build-ios/proj/cfg.cmake
echo "set(CC_USE_METAL ON)" >> build-ios/proj/cfg.cmake
echo "set(TARGET_IOS_VERSION 12.0)" >> build-ios/proj/cfg.cmake
echo "set(TARGET_IOS_VERSION 13.0)" >> build-ios/proj/cfg.cmake
echo "set(USE_WEBSOCKET_SERVER OFF)" >> build-ios/proj/cfg.cmake
echo "set(USE_DRAGONBONES OFF)" >> build-ios/proj/cfg.cmake
echo "set(CMAKE_CXX_STANDARD_REQUIRED OFF)" >> build-ios/proj/cfg.cmake
@@ -548,7 +547,6 @@ jobs:
-DCMAKE_OSX_ARCHITECTURES=${{ matrix.config.arch }} \
-DRES_DIR=$RES_DIR \
-DCOCOS_X_PATH=$NATIVE_ROOT
set +e
#cmake --build . --config Debug -- -quiet -jobs $NUM_OF_CORES -allowProvisioningUpdates CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO
cmake --build . --config Debug -- -jobs $NUM_OF_CORES CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO
echo "Compile iOS Done!"
+1
View File
@@ -28,6 +28,7 @@ jobs:
with:
node-version: ${{ matrix.node-version }}
- run: npm ci --ignore-scripts
- run: node scripts/spread-pal.cjs
- run: npm run build:debug-infos
- name: Download external
run: |
+8
View File
@@ -46,3 +46,11 @@ platforms/runtime/platforms/vivo-mini-game/ral.min.js
@types/consts.d.ts
__TS_ENGINE__/
# pal 由 @cocos/engine-pal 在 postinstall 挂载(软链/复制),不入库
/pal
# platforms 源码已抽到 @cocos/engine-platforms;其预打包 adapter 由 postinstall 的
# spread-adapter.cjs 复制到 bin/adapter(/bin 已忽略)。platforms 源码不再入库。
/platforms
+4
View File
@@ -3980,3 +3980,7 @@ Debug bones or slots is invalid in cached mode.
### 16419
Spine version not supported.
### 16420
End time must bigger than start time.
+54 -46
View File
@@ -382,70 +382,70 @@
"test": "context.buildTimeConstants && context.buildTimeConstants.HTML5",
"isVirtualModule": true,
"overrides": {
"pal/minigame": "pal/minigame/non-minigame.ts",
"pal/audio": "pal/audio/web/player.ts",
"pal/system-info": "pal/system-info/web/system-info.ts",
"pal/screen-adapter": "pal/screen-adapter/web/screen-adapter.ts",
"pal/input": "pal/input/web/index.ts",
"pal/env": "pal/env/web/env.ts",
"pal/pacer": "pal/pacer/pacer-web.ts",
"pal/wasm": "pal/wasm/wasm-web.ts"
"pal/minigame": "pal/minigame/non-minigame.js",
"pal/audio": "pal/audio/web/player.js",
"pal/system-info": "pal/system-info/web/system-info.js",
"pal/screen-adapter": "pal/screen-adapter/web/screen-adapter.js",
"pal/input": "pal/input/web/index.js",
"pal/env": "pal/env/web/env.js",
"pal/pacer": "pal/pacer/pacer-web.js",
"pal/wasm": "pal/wasm/wasm-web.js"
}
},
{
"test": "context.buildTimeConstants && context.buildTimeConstants.NATIVE",
"isVirtualModule": true,
"overrides": {
"pal/minigame": "pal/minigame/non-minigame.ts",
"pal/audio": "pal/audio/native/player.ts",
"pal/system-info": "pal/system-info/native/system-info.ts",
"pal/screen-adapter": "pal/screen-adapter/native/screen-adapter.ts",
"pal/input": "pal/input/native/index.ts",
"pal/env": "pal/env/native/env.ts",
"pal/pacer": "pal/pacer/pacer-native.ts",
"pal/wasm": "pal/wasm/wasm-native.ts"
"pal/minigame": "pal/minigame/non-minigame.js",
"pal/audio": "pal/audio/native/player.js",
"pal/system-info": "pal/system-info/native/system-info.js",
"pal/screen-adapter": "pal/screen-adapter/native/screen-adapter.js",
"pal/input": "pal/input/native/index.js",
"pal/env": "pal/env/native/env.js",
"pal/pacer": "pal/pacer/pacer-native.js",
"pal/wasm": "pal/wasm/wasm-native.js"
}
},
{
"test": "context.buildTimeConstants && context.buildTimeConstants.MINIGAME",
"isVirtualModule": true,
"overrides": {
"pal/minigame": "pal/minigame/{{context.platform.toLowerCase()}}.ts",
"pal/audio": "pal/audio/minigame/player.ts",
"pal/system-info": "pal/system-info/minigame/system-info.ts",
"pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.ts",
"pal/input": "pal/input/minigame/index.ts",
"pal/env": "pal/env/minigame/env.ts",
"pal/pacer": "pal/pacer/pacer-minigame.ts",
"pal/wasm": "pal/wasm/wasm-minigame.ts"
"pal/minigame": "pal/minigame/{{context.platform.toLowerCase()}}.js",
"pal/audio": "pal/audio/minigame/player.js",
"pal/system-info": "pal/system-info/minigame/system-info.js",
"pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.js",
"pal/input": "pal/input/minigame/index.js",
"pal/env": "pal/env/minigame/env.js",
"pal/pacer": "pal/pacer/pacer-minigame.js",
"pal/wasm": "pal/wasm/wasm-minigame.js"
}
},
{
"test": "context.buildTimeConstants && context.buildTimeConstants.RUNTIME_BASED",
"isVirtualModule": true,
"overrides": {
"pal/minigame": "pal/minigame/runtime.ts",
"pal/audio": "pal/audio/minigame/player.ts",
"pal/system-info": "pal/system-info/minigame/system-info.ts",
"pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.ts",
"pal/input": "pal/input/minigame/index.ts",
"pal/env": "pal/env/runtime/env.ts",
"pal/pacer": "pal/pacer/pacer-minigame.ts",
"pal/wasm": "pal/wasm/wasm-minigame.ts"
"pal/minigame": "pal/minigame/runtime.js",
"pal/audio": "pal/audio/minigame/player.js",
"pal/system-info": "pal/system-info/minigame/system-info.js",
"pal/screen-adapter": "pal/screen-adapter/minigame/screen-adapter.js",
"pal/input": "pal/input/minigame/index.js",
"pal/env": "pal/env/runtime/env.js",
"pal/pacer": "pal/pacer/pacer-minigame.js",
"pal/wasm": "pal/wasm/wasm-minigame.js"
}
},
{
"test": "context.buildTimeConstants && context.buildTimeConstants.NODEJS",
"isVirtualModule": true,
"overrides": {
"pal/minigame": "pal/minigame/non-minigame.ts",
"pal/audio": "pal/audio/nodejs/player.ts",
"pal/system-info": "pal/system-info/nodejs/system-info.ts",
"pal/screen-adapter": "pal/screen-adapter/nodejs/screen-adapter.ts",
"pal/input": "pal/input/nodejs/index.ts",
"pal/env": "pal/env/nodejs/env.ts",
"pal/pacer": "pal/pacer/pacer-nodejs.ts",
"pal/wasm": "pal/wasm/wasm-nodejs.ts"
"pal/minigame": "pal/minigame/non-minigame.js",
"pal/audio": "pal/audio/nodejs/player.js",
"pal/system-info": "pal/system-info/nodejs/system-info.js",
"pal/screen-adapter": "pal/screen-adapter/nodejs/screen-adapter.js",
"pal/input": "pal/input/nodejs/index.js",
"pal/env": "pal/env/nodejs/env.js",
"pal/pacer": "pal/pacer/pacer-nodejs.js",
"pal/wasm": "pal/wasm/wasm-nodejs.js"
}
},
{
@@ -470,7 +470,15 @@
}
},
{
"test": "context.buildTimeConstants.SPINE_3_8",
"test": "context.buildTimeConstants.SPINE_3_8 && context.buildTimeConstants.SPINE_4_2",
"isVirtualModule": false,
"overrides": {
"cocos/spine/lib/spine-version.ts": "cocos/spine/lib/spine-version-dynamic.ts",
"cocos/spine/lib/spine-instantiate.ts": "cocos/spine/lib/spine-instantiate-dynamic.ts"
}
},
{
"test": "context.buildTimeConstants.SPINE_3_8 && !context.buildTimeConstants.SPINE_4_2",
"isVirtualModule": false,
"overrides": {
"cocos/spine/lib/spine-version.ts": "cocos/spine/lib/spine-version-3.8.ts",
@@ -478,7 +486,7 @@
}
},
{
"test": "context.buildTimeConstants.SPINE_4_2",
"test": "context.buildTimeConstants.SPINE_4_2 && !context.buildTimeConstants.SPINE_3_8",
"isVirtualModule": false,
"overrides": {
"cocos/spine/lib/spine-version.ts": "cocos/spine/lib/spine-version-4.2.ts",
@@ -877,10 +885,10 @@
"cocos/asset/asset-manager/weak-cache.ts",
"cocos/2d/framework/ui-skew-utils.ts",
"cocos/spine/lib/spine-binary.ts",
"pal/input/minigame/gamepad-input.ts",
"pal/input/minigame/handheld-input.ts",
"pal/input/minigame/handle-input.ts",
"pal/input/minigame/hmd-input.ts"
"pal/input/minigame/gamepad-input.js",
"pal/input/minigame/handheld-input.js",
"pal/input/minigame/handle-input.js",
"pal/input/minigame/hmd-input.js"
]
}
}
+1 -1
View File
@@ -115,7 +115,7 @@ export class TextProcessing {
const maxValue = Math.max(outputLayoutData.canvasSize.width, outputLayoutData.canvasSize.height);
const canvasScaleToMaxSizeRatio = MAX_SIZE / maxValue;
this._fontScale *= canvasScaleToMaxSizeRatio;
this._fontScale = Math.max(1, this._fontScale);
this._fontScale = Math.max(0.1, this._fontScale);
}
this._updatePaddingRect(style, outputLayoutData);
+11 -2
View File
@@ -266,6 +266,15 @@ export class Graphics extends UIRenderer {
this._updateMtlForGraphics();
}
protected override get _keepRenderData (): boolean {
// Graphics is a retained-mode renderer: its MeshRenderData is the result of the
// user's previous fill()/stroke() calls. Destroying it here would leave Impl's
// render-data list pointing at cleared geometry, so re-enabling the node on native
// platforms would require the user to draw the paths again. Keep it attached to the
// disabled RenderEntity; clear() and onDestroy() remain the owning release points.
return true;
}
public onDestroy (): void {
this._sceneGetter = null;
if (JSB) {
@@ -637,13 +646,13 @@ export class Graphics extends UIRenderer {
const vertexBuffer = gfxDevice.createBuffer(new BufferInfo(
BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST,
MemoryUsageBit.DEVICE,
65535 * stride,
65536 * stride, // Uint16 can address 65536 vertices (indices 0–65535)
stride,
));
const indexBuffer = gfxDevice.createBuffer(new BufferInfo(
BufferUsageBit.INDEX | BufferUsageBit.TRANSFER_DST,
MemoryUsageBit.DEVICE,
65535 * Uint16Array.BYTES_PER_ELEMENT * 2,
65536 * Uint16Array.BYTES_PER_ELEMENT * 2, // Uint16 can address 65536 vertices (indices 0–65535)
Uint16Array.BYTES_PER_ELEMENT,
));
+56 -4
View File
@@ -64,10 +64,10 @@ function _calculateCircle (center: Vec3, radius: Vec3, segments: number): Vec3[]
*/
export enum MaskType {
/**
* @en Rect mask.
* @en Rect mask, supports rounded corners by setting radius.
*
* @zh
* 使用矩形作为遮罩。
* 使用矩形作为遮罩,可通过 radius 设置圆角。
*/
GRAPHICS_RECT = 0,
@@ -215,6 +215,32 @@ export class Mask extends Component {
this._updateGraphics();
}
/**
* @en
* The radius for rounded corners of rect mask.
*
* @zh
* 矩形遮罩的圆角半径。
*/
@visible(function (this: Mask) {
return this.type === MaskType.GRAPHICS_RECT;
})
@tooltip('i18n:mask.radius')
@range([0, Number.POSITIVE_INFINITY])
get radius (): number {
return this._radius;
}
set radius (value) {
const radius = clamp(value, 0, Number.POSITIVE_INFINITY);
if (this._radius === radius) {
return;
}
this._radius = radius;
this._updateGraphics();
}
/**
* @en
* The mask image.
@@ -289,6 +315,9 @@ export class Mask extends Component {
@serializable
protected _segments = 64;
@serializable
protected _radius = 0;
@serializable
protected _alphaThreshold = 0.1;
@@ -350,7 +379,25 @@ export class Mask extends Component {
testPt.y += ap.y * h;
let result = false;
if (this.type === MaskType.GRAPHICS_RECT || this.type === MaskType.GRAPHICS_STENCIL || this.type === MaskType.SPRITE_STENCIL) {
if (this.type === MaskType.GRAPHICS_RECT) {
result = testPt.x >= 0 && testPt.y >= 0 && testPt.x <= w && testPt.y <= h;
const radius = Math.min(this._radius, w / 2, h / 2);
if (result && radius > 0) {
let dx = 0;
let dy = 0;
if (testPt.x < radius) {
dx = testPt.x - radius;
} else if (testPt.x > w - radius) {
dx = testPt.x - (w - radius);
}
if (testPt.y < radius) {
dy = testPt.y - radius;
} else if (testPt.y > h - radius) {
dy = testPt.y - (h - radius);
}
result = dx * dx + dy * dy <= radius * radius;
}
} else if (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.GRAPHICS_ELLIPSE) {
const rx = w / 2;
@@ -423,7 +470,12 @@ export class Mask extends Component {
const x = -width * ap.x;
const y = -height * ap.y;
if (this._type === MaskType.GRAPHICS_RECT) {
graphics.rect(x, y, width, height);
const radius = Math.min(this._radius, width / 2, height / 2);
if (radius > 0) {
graphics.roundRect(x, y, width, height, radius);
} else {
graphics.rect(x, y, width, height);
}
} 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);
+1 -1
View File
@@ -567,7 +567,7 @@ export class Sprite extends UIRenderer {
if (this.spriteFrame && this.spriteFrame.texture instanceof RenderTexture) {
const rtMatName = `rt-${mat.name}`;
let rtMat = builtinResMgr.get(rtMatName) as Material | null;
if (!rtMat) {
if (!rtMat || !rtMat.passes.length) {
rtMat = new Material(rtMatName);
rtMat.copy(mat, { defines: { SAMPLE_FROM_RT: true } });
builtinResMgr.addAsset(rtMatName, rtMat);
+24 -5
View File
@@ -398,12 +398,23 @@ export class UIRenderer extends Renderer {
this.node.off(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this);
this.node.off(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this);
this.node.off(NodeEventType.PARENT_CHANGED, this._colorDirty, this);
this.destroyRenderData();
if (!this._keepRenderData) {
this.destroyRenderData();
}
uiRendererManager.removeRenderer(this);
this._renderFlag = false;
this._renderEntity.enabled = false;
}
/**
* Whether to keep render data when the component leaves the active hierarchy.
* Retained-mode renderers may override this policy and keep their render data until
* the content is explicitly cleared or the component is destroyed.
*/
protected get _keepRenderData (): boolean {
return false;
}
public onDestroy (): void {
this._renderEntity.setNode(null);
if (this.node._uiProps.uiComp === this) {
@@ -536,7 +547,7 @@ export class UIRenderer extends Renderer {
const mat = this._updateBuiltinMaterial();
this.setSharedMaterial(mat, 0);
if (this.stencilStage === Stage.ENTER_LEVEL || this.stencilStage === Stage.ENTER_LEVEL_INVERTED) {
this.getMaterialInstance(0)!.recompileShaders({ USE_ALPHA_TEST: true });
this.getMaterialInstance(0)?.recompileShaders({ USE_ALPHA_TEST: true });
}
this._updateBlendFunc();
}
@@ -600,16 +611,24 @@ export class UIRenderer extends Renderer {
*/
public _updateBlendFunc (): void {
// todo: Not only Pass[0].target[0]
let target = this.getRenderMaterial(0)!.passes[0].blendState.targets[0];
const renderMat = this.getRenderMaterial(0);
if (!renderMat || !renderMat.passes[0]) {
return;
}
let target = renderMat.passes[0].blendState.targets[0];
this._dstBlendFactorCache = target.blendDst;
this._srcBlendFactorCache = target.blendSrc;
if (this._dstBlendFactorCache !== this._dstBlendFactor || this._srcBlendFactorCache !== this._srcBlendFactor) {
target = this.getMaterialInstance(0)!.passes[0].blendState.targets[0];
const matInstance = this.getMaterialInstance(0);
if (!matInstance || !matInstance.passes[0]) {
return;
}
target = matInstance.passes[0].blendState.targets[0];
target.blend = true;
target.blendDstAlpha = BlendFactor.ONE_MINUS_SRC_ALPHA;
target.blendDst = this._dstBlendFactor;
target.blendSrc = this._srcBlendFactor;
const targetPass = this.getMaterialInstance(0)!.passes[0];
const targetPass = matInstance.passes[0];
targetPass.blendState.setTarget(0, target);
targetPass._updatePassHash();
this._dstBlendFactorCache = this._dstBlendFactor;
+5 -6
View File
@@ -23,7 +23,7 @@
*/
import { JSB } from 'internal:constants';
import { Device, BufferUsageBit, MemoryUsageBit, Attribute, Buffer, BufferInfo, InputAssembler, InputAssemblerInfo, Feature, API } from '../../gfx';
import { Device, BufferUsageBit, MemoryUsageBit, Attribute, Buffer, BufferInfo, InputAssembler, InputAssemblerInfo, Feature } from '../../gfx';
import { getAttributeStride } from './vertex-format';
import { sys, getError, warnID, assertIsTrue } from '../../core';
import { NativeUIMeshBuffer } from './native-2d';
@@ -251,11 +251,10 @@ export class MeshBuffer {
this.floatsPerVertex = getAttributeStride(attrs) >> 2;
var vDataCountLimit = 65536; // 2^16 - 1
const glApi = device.gfxAPI;
if (glApi === API.WEBGPU || glApi === API.WEBGL2 || glApi === API.WEBGL && device.hasFeature(Feature.ELEMENT_INDEX_UINT)) {
vDataCountLimit = 4294967295; // 2^32 - 1
}
// Use the GPU's actual reported capability to determine max addressable vertex count.
// Feature.ELEMENT_INDEX_UINT is set to true in: WebGL2, WebGPU, Vulkan, Metal, GLES3, GLES2+ext.
// vDataCountLimit is a vertex COUNT limit (max index value + 1), not the max index value itself.
const vDataCountLimit = device.hasFeature(Feature.ELEMENT_INDEX_UINT) ? 4294967296 : 65536; // Uint32 or Uint16 can address 2^32 or 2^16 vertices (indices 0–2^32-1 or 0–2^16-1)
assertIsTrue(this._initVDataCount / this._floatsPerVertex < vDataCountLimit, getError(9005));
if (!this.vData || !this.iData) {
+3 -3
View File
@@ -634,7 +634,7 @@ export class MeshRenderData extends BaseRenderData {
const newVBytes = this._byteLength + vertexCount * this.stride;
const newICount = this.indexCount + indexCount;
if (vertexCount + this.vertexCount > 65535) {
if (vertexCount + this.vertexCount > 65536) { // Uint16 can address 65536 vertices (indices 0–65535)
return false;
}
@@ -697,13 +697,13 @@ export class MeshRenderData extends BaseRenderData {
if (this._byteLength > vertexBuffer.size) {
vertexBuffer.resize(this._byteLength);
}
vertexBuffer.update(verticesData);
vertexBuffer.update(verticesData.buffer as ArrayBuffer, this._byteLength);
const indexBytes = indexCount << 1;
if (indexBytes > this._indexBuffer.size) {
this._indexBuffer.resize(indexBytes);
}
this._indexBuffer.update(indicesData);
this._indexBuffer.update(indicesData.buffer as ArrayBuffer, indexBytes);
}
public freeIAPool (): void {
+8 -2
View File
@@ -165,6 +165,10 @@ export class StaticVBAccessor extends BufferAccessor {
errorID(9004, byteLength);
return null;
}
if (vertexCount > 65536) { // Vertex count must less than 65536 for index is uint16 (0 to 65535)
errorID(9004, byteLength);
return null;
}
let buf: MeshBuffer = null!;
let freeList: IFreeEntry[];
let bid = 0;
@@ -176,9 +180,11 @@ export class StaticVBAccessor extends BufferAccessor {
freeList = this._freeLists[i];
// Loop entries
for (let e = 0; e < freeList.length; ++e) {
const freeEntry = freeList[e];
const vertexOffset: number = freeEntry.offset / this.vertexFormatBytes;
// Found suitable free entry
if (freeList[e].length >= byteLength) {
entry = freeList[e];
if (freeEntry.length >= byteLength && vertexOffset + (vertexCount - 1) <= 65535) {
entry = freeEntry;
bid = i;
eid = e;
break;
+1 -1
View File
@@ -508,7 +508,7 @@ export class Mesh extends Asset {
let dstSize = idxView.length;
if (dstStride === 4 && !gfxDevice.hasFeature(Feature.ELEMENT_INDEX_UINT)) {
const vertexCount = this._struct.vertexBundles[prim.vertexBundelIndices[0]].view.count;
if (vertexCount >= 65536) {
if (vertexCount > 65536) { // Uint16 can address 65536 vertices (indices 0–65535)
warnID(10001, vertexCount, 65536);
continue; // Ignore this primitive
} else {
+7 -2
View File
@@ -172,13 +172,18 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
// Fill index buffer.
let indexBuffer: ArrayBuffer | null = null;
let idxCount = 0;
const idxStride = 2;
let idxStride = 2;
let indexFormat = Format.R16UI;
if (geometry.indices) {
const { indices } = geometry;
idxCount = indices.length;
if (indices.some((i) => i > 0xFFFF)) {
idxStride = 4;
indexFormat = Format.R32UI;
}
indexBuffer = new ArrayBuffer(idxStride * idxCount);
const indexBufferView = new DataView(indexBuffer);
writeBuffer(indexBufferView, indices, Format.R16UI);
writeBuffer(indexBufferView, indices, indexFormat);
}
// Create primitive.
+3 -3
View File
@@ -24,7 +24,7 @@
import { CULL_MESHOPT, NATIVE_CODE_BUNDLE_MODE } from 'internal:constants';
import { ensureWasmModuleReady, instantiateWasm } from 'pal/wasm';
import { sys, logID, error } from '../../core';
import { sys, error, debugID } from '../../core';
import { game } from '../../game';
import { NativeCodeBundleMode } from '../../misc/webassembly-support';
@@ -53,7 +53,7 @@ function initDecoderASM (asm_factory: any): Promise<void> {
MeshoptDecoder.decodeGltfBuffer = asm_factory.decodeGltfBuffer;
MeshoptDecoder.useWorkers = asm_factory.useWorkers;
MeshoptDecoder.decodeGltfBufferAsync = asm_factory.decodeGltfBufferAsync;
logID(14202);
debugID(14202);
});
}
@@ -70,7 +70,7 @@ function initDecoderWASM (wasm_factory: any, wasm_url: string): Promise<void> {
MeshoptDecoder.decodeGltfBuffer = wasm_factory.decodeGltfBuffer;
MeshoptDecoder.useWorkers = wasm_factory.useWorkers;
MeshoptDecoder.decodeGltfBufferAsync = wasm_factory.decodeGltfBufferAsync;
logID(14203);
debugID(14203);
});
}
+7
View File
@@ -106,6 +106,13 @@ export class BakedSkinningModel extends MorphModel {
UBOSkinningTexture.SIZE,
));
}
// The animation buffer belongs to the skinning root. Refresh its binding without
// rebuilding the instanced attribute block, which would erase custom attribute values.
for (let i = 0; i < this._subModels.length; i++) {
this._updateLocalDescriptors(i, this._subModels[i].descriptorSet);
}
this.updateInstancedJointTextureInfo();
}
// Override
+10
View File
@@ -142,6 +142,7 @@ export class SkinningModel extends MorphModel {
}
this._bufferIndices = null; this._joints.length = 0;
if (!skeleton || !skinningRoot || !mesh) { return; }
const prevRealTimeTextureMode = this._realTimeTextureMode;
this._realTimeTextureMode = false;
if (UBOSkinning.JOINT_UNIFORM_CAPACITY < skeleton.joints.length) { this._realTimeTextureMode = true; }
this.transform = skinningRoot;
@@ -161,6 +162,15 @@ export class SkinningModel extends MorphModel {
if (!jointMaps) { indices.push(index); buffers.push(0); } else { getRelevantBuffers(indices, buffers, jointMaps, index); }
this._joints.push({ indices, buffers, bound, target, bindpose, transform });
}
// Rebind recreated joint resources without resetting user-provided instanced attributes.
const subModelCount = Math.min(this._subModels.length, this._bufferIndices.length);
if (subModelCount && prevRealTimeTextureMode !== this._realTimeTextureMode) {
this.onMacroPatchesStateChanged();
}
for (let i = 0; i < subModelCount; i++) {
this._updateLocalDescriptors(i, this._subModels[i].descriptorSet);
}
}
/**
@@ -384,10 +384,10 @@ export class ReflectionProbe extends Component {
}
}
}
if (this.probeType === ProbeType.PLANAR && this.sourceCamera) {
if (!EDITOR_NOT_IN_PREVIEW && this.probeType === ProbeType.PLANAR && this.sourceCamera) {
if ((this.sourceCamera.node.hasChangedFlags & TransformBit.TRS)
|| !this._sourceCameraPos.equals(this.sourceCamera.node.getWorldPosition())) {
this._sourceCameraPos = this.sourceCamera.node.getWorldPosition();
this._sourceCameraPos.set(this.sourceCamera.node.getWorldPosition());
this.probe.renderPlanarReflection(this.sourceCamera.camera);
}
}
@@ -177,21 +177,21 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer {
@override
@visible(false)
get mesh (): Mesh | null {
return super.mesh;
return Reflect.get(SkinnedMeshRenderer.prototype, 'mesh', this);
}
set mesh (val) {
super.mesh = val;
Reflect.set(SkinnedMeshRenderer.prototype, 'mesh', val, this);
}
@override
@visible(false)
get skeleton (): Skeleton | null {
return super.skeleton;
return Reflect.get(SkinnedMeshRenderer.prototype, 'skeleton', this);
}
set skeleton (val) {
super.skeleton = val;
Reflect.set(SkinnedMeshRenderer.prototype, 'skeleton', val, this);
}
public onLoad (): void {
@@ -160,7 +160,8 @@ class ClipMotionEval implements MotionEval {
public overrideClips (context: AnimationGraphBindingContext): void {
const { _originalClip: originalClip } = this;
const overriding = context.clipOverrides?.get(originalClip);
const clipOverrides: any = context.clipOverrides;
const overriding: AnimationClip | null = clipOverrides && clipOverrides.get ? clipOverrides.get(originalClip) : null;
if (overriding) {
this._setClip(overriding, context);
}
+3 -2
View File
@@ -76,10 +76,11 @@ simpleTextureProto._onGFXTextureUpdated = function (gfxTexture) {
simpleTextureProto._onAfterAssignImage = function (image) {
if (macro.CLEANUP_IMAGE_CACHE) {
const deps = dependUtil.getDeps(this._uuid);
const index = deps.indexOf(image._uuid);
if (index !== -1) {
let index = deps.indexOf(image._uuid);
while (index !== -1) {
js.array.fastRemoveAt(deps, index);
image.decRef();
index = deps.indexOf(image._uuid);
}
}
};
+4 -2
View File
@@ -194,10 +194,12 @@ export class SimpleTexture extends TextureBase {
if (macro.CLEANUP_IMAGE_CACHE) {
const deps = dependUtil.getDeps(this._uuid);
const index = deps.indexOf(image._uuid);
if (index !== -1) {
let index = deps.indexOf(image._uuid);
while (index !== -1) {
js.array.fastRemoveAt(deps, index);
image.decRef();
// The same UUID may occur more than once; find the next dependency edge.
index = deps.indexOf(image._uuid);
}
}
}
+3 -2
View File
@@ -195,8 +195,9 @@ function define (className, baseClass, options): any {
renderName = 'render_stage';
}
// 增加了 hidden: 开头标识,使它最终不会显示在 Editor inspector 的添加组件列表里
window.EditorExtends && window.EditorExtends.Component.addMenu(cls, `hidden:${renderName}/${className}`, -1);
if (window.EditorExtends) {
window.EditorExtends.Component.addMenu(cls, `hidden:${renderName}/${className}`, -1);
}
}
// Note: `options.ctor` should be the same as `cls` except if
+52
View File
@@ -69,6 +69,58 @@ export function approx (a: number, b: number, maxDiff?: number): boolean {
return mathAbs(a - b) <= maxDiff;
}
/**
* @en Tests whether or not the first argument is approximately greater than or equal to the second
* @zh 测试第一个参数是否近似大于或等于第二个参数
* @param a The first number to test
* @param b The second number to test
* @param maxDiff Maximum difference (default: EPSILON)
* @return True if a is approximately greater than or equal to b, false otherwise
*/
export function approxGE (a: number, b: number, maxDiff?: number): boolean {
maxDiff = maxDiff || EPSILON;
return a >= b - maxDiff;
}
/**
* @en Tests whether or not the first argument is approximately less than or equal to the second
* @zh 测试第一个参数是否近似小于或等于第二个参数
* @param a The first number to test
* @param b The second number to test
* @param maxDiff Maximum difference (default: EPSILON)
* @return True if a is approximately less than or equal to b, false otherwise
*/
export function approxLE (a: number, b: number, maxDiff?: number): boolean {
maxDiff = maxDiff || EPSILON;
return a <= b + maxDiff;
}
/**
* @en Tests whether or not the first argument is approximately greater than the second
* @zh 测试第一个参数是否近似大于第二个参数
* @param a The first number to test
* @param b The second number to test
* @param maxDiff Maximum difference (default: EPSILON)
* @return True if a is approximately greater than b, false otherwise
*/
export function approxGT (a: number, b: number, maxDiff?: number): boolean {
maxDiff = maxDiff || EPSILON;
return a > b + maxDiff;
}
/**
* @en Tests whether or not the first argument is approximately less than the second
* @zh 测试第一个参数是否近似小于第二个参数
* @param a The first number to test
* @param b The second number to test
* @param maxDiff Maximum difference (default: EPSILON)
* @return True if a is approximately less than b, false otherwise
*/
export function approxLT (a: number, b: number, maxDiff?: number): boolean {
maxDiff = maxDiff || EPSILON;
return a < b - maxDiff;
}
/**
* @en Clamps a value between a minimum float and maximum float value.<br/>
* @zh 返回最小浮点数和最大浮点数之间的一个数值。可以使用 clamp 函数将不断变化的数值限制在范围内。
+10
View File
@@ -88,6 +88,14 @@ export abstract class CommandBuffer extends GFXObject {
return this._numTris;
}
/**
* @en Number of compute dispatches currently recorded.
* @zh 计算调度(dispatch)次数。
*/
get numDispatches (): number {
return this._numDispatches;
}
/** @mangle */
protected _queue: Queue | null = null;
/** @mangle */
@@ -95,6 +103,8 @@ export abstract class CommandBuffer extends GFXObject {
/** @mangle */
protected _numDrawCalls = 0;
/** @mangle */
protected _numDispatches = 0;
/** @mangle */
protected _numInstances = 0;
/** @mangle */
protected _numTris = 0;
+10
View File
@@ -127,6 +127,14 @@ export abstract class Device {
return this._numTris;
}
/**
* @en Number of compute dispatches currently recorded.
* @zh 计算调度(dispatch)次数。
*/
get numDispatches (): number {
return this._numDispatches;
}
/**
* @en Total memory size currently allocated.
* @zh 内存状态。
@@ -168,6 +176,8 @@ export abstract class Device {
/** @mangle */
protected _numDrawCalls = 0;
/** @mangle */
protected _numDispatches = 0;
/** @mangle */
protected _numInstances = 0;
/** @mangle */
protected _numTris = 0;
+2 -2
View File
@@ -2702,7 +2702,7 @@ export function WebGLCmdFuncCopyBuffersToTexture (
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
: alignTo(regionTexExtentHeight, blockSizeHeight);
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
@@ -2773,7 +2773,7 @@ export function WebGLCmdFuncCopyBuffersToTexture (
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
: alignTo(regionTexExtentHeight, blockSizeHeight);
stride.width = region.buffStride > 0 ? region.buffStride : extent.width;
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
+7 -7
View File
@@ -2811,7 +2811,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
: alignTo(regionTexExtentHeight, blockSizeHeight);
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
@@ -2883,7 +2883,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
: alignTo(regionTexExtentHeight, blockSizeHeight);
extent.depth = 1;
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
@@ -2965,7 +2965,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
offset.z = regionTexOffset.z;
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
: alignTo(regionTexExtentHeight, blockSizeHeight);
extent.depth = regionTexExtent.depth;
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
@@ -2986,7 +2986,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
if (!isCompressed) {
gl.texSubImage3D(
WebGLConstants.TEXTURE_2D_ARRAY,
WebGLConstants.TEXTURE_3D,
mipLevel,
offset.x,
offset.y,
@@ -3000,7 +3000,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
);
} else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL as number) {
gl.compressedTexSubImage3D(
WebGLConstants.TEXTURE_2D_ARRAY,
WebGLConstants.TEXTURE_3D,
mipLevel,
offset.x,
offset.y,
@@ -3013,7 +3013,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
);
} else { // WEBGL_compressed_texture_etc1
gl.compressedTexImage3D(
WebGLConstants.TEXTURE_2D_ARRAY,
WebGLConstants.TEXTURE_3D,
mipLevel,
gpuTexture.glInternalFmt,
destWidth,
@@ -3043,7 +3043,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
: alignTo(regionTexExtentHeight, blockSizeHeight);
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
+1 -1
View File
@@ -185,7 +185,7 @@ export class WebGL2Swapchain extends Swapchain {
self._canvas = info.windowHandle;
self._webGL2ContextLostHandler = self._onWebGLContextLost.bind(self);
self._canvas.addEventListener(eventWebGLContextLost, self._onWebGLContextLost);
self._canvas.addEventListener(eventWebGLContextLost, self._webGL2ContextLostHandler);
const { instance } = WebGL2DeviceManager;
const { gl, capabilities } = instance;
+89 -28
View File
@@ -40,6 +40,7 @@ import {
TextureBlit,
DescriptorSetInfo,
Format,
DispatchInfo,
} from '../base/define';
import { Framebuffer } from '../base/framebuffer';
import { InputAssembler } from '../base/input-assembler';
@@ -179,6 +180,7 @@ export class WebGPUCommandBuffer extends CommandBuffer {
private _wgpuRenderPass!: WebGPURenderPass;
private _renderPassFuncQueue: ((renPassEncoder: GPURenderPassEncoder) => void)[] = [];
private _computeFuncQueue: ((computePassEncoder: GPUComputePassEncoder) => void)[] = [];
public initialize (info: CommandBufferInfo): boolean {
this._type = info.type;
@@ -222,13 +224,16 @@ export class WebGPUCommandBuffer extends CommandBuffer {
this._curStencilWriteMask = null;
this._curStencilCompareMask = null;
this._numDrawCalls = 0;
this._numDispatches = 0;
this._numInstances = 0;
this._numTris = 0;
this._computeFuncQueue.length = 0;
}
public end (): void {
this._isStateValid = false;
this._isInRenderPass = false;
this._computeFuncQueue.length = 0;
}
public beginRenderPass (
@@ -650,22 +655,20 @@ export class WebGPUCommandBuffer extends CommandBuffer {
this.cmdPackage.cmds.concat(cmdPackage.cmds.array);
this._numDrawCalls += WebGPUCmdBuff._numDrawCalls;
this._numDispatches += WebGPUCmdBuff._numDispatches;
this._numInstances += WebGPUCmdBuff._numInstances;
this._numTris += WebGPUCmdBuff._numTris;
}
}
protected bindStates (): void {
if (!this._curGPUPipelineState) {
return;
}
const gpuPipelineLayout = this._curGPUPipelineState.gpuPipelineLayout as IWebGPUGPUPipelineLayout;
private _prepareDescriptorSets (): void {
const wgpuPipLayout = (currPipelineState?.pipelineLayout as WebGPUPipelineLayout);
const device = WebGPUDeviceManager.instance;
for (let i = 0; i < groupSets.length; i++) {
const currSetIdx = groupSets[i];
const currDesc = descriptorSets[currSetIdx];
if (currDesc && currDesc.gpuDescriptorSet) {
// prepare() builds the bind group if it was never created, or rebuilds it on resource change.
currDesc.prepare();
} else {
const currLayout = wgpuPipLayout.setLayouts[currSetIdx];
@@ -675,23 +678,13 @@ export class WebGPUCommandBuffer extends CommandBuffer {
newDescSet.prepare(true);
}
}
const gpuIA = this._curGPUInputAssembler!;
// only 4x MSAA is supported
gpuIA.samples = samples > 1 ? 4 : 1;
this._curWebGPUPipelineState!.prepare(gpuIA);
// ----------------------------wgpu pipline state-----------------------------
const wgpuPipeline = this._curGPUPipelineState.nativePipeline as GPURenderPipeline;
const pplFunc = (passEncoder: GPURenderPassEncoder): void => {
passEncoder.setPipeline(wgpuPipeline);
};
this._renderPassFuncQueue.push(pplFunc);
if (this._curGPUPipelineState.pipelineState?.depthStencil) {
const stencilRef = this._curGPUPipelineState.stencilRef;
const stencilRefFunc = (passEncoder: GPURenderPassEncoder): void => {
passEncoder.setStencilReference(stencilRef);
};
this._renderPassFuncQueue.push(stencilRefFunc);
}
}
/**
* Collect the bind groups and dynamic offsets for the currently bound descriptor sets.
* Shared by the draw (bindStates) and compute (dispatch) paths.
*/
private _collectBindGroups (): { wgpuBindGroups: GPUBindGroup[]; wgpuDynOffsets: number[][] } {
const currGPUDescSize = groupSets.length;
const wgpuBindGroups = new Array<GPUBindGroup>(currGPUDescSize);
const wgpuDynOffsets = new Array<number[]>(currGPUDescSize);
@@ -703,7 +696,7 @@ export class WebGPUCommandBuffer extends CommandBuffer {
wgpuDynOffsets[currSetIdx] = [...this._curDynamicOffsets[currSetIdx]];
if (!descObj.dynamicOffsetCount) {
wgpuDynOffsets[currSetIdx] = [];
} else if (descObj && descObj.dynamicOffsetCount !== wgpuDynOffsets[currSetIdx].length) {
} else if (descObj.dynamicOffsetCount !== wgpuDynOffsets[currSetIdx].length) {
wgpuDynOffsets[currSetIdx].length = descObj.dynamicOffsetCount;
for (let j = 0; j < descObj.dynamicOffsetCount; j++) {
const currOffset = wgpuDynOffsets[currSetIdx][j];
@@ -719,16 +712,84 @@ export class WebGPUCommandBuffer extends CommandBuffer {
}
}
}
return { wgpuBindGroups, wgpuDynOffsets };
}
public dispatch (info: DispatchInfo): void {
if (!this._curGPUPipelineState) {
return;
}
// Prepare descriptor sets (same logic as bindStates)
this._prepareDescriptorSets();
// Create compute pipeline
this._curWebGPUPipelineState!.prepare(null!);
const computePipeline = this._curGPUPipelineState.nativePipeline as GPUComputePipeline;
// Build bind groups for compute pass
const { wgpuBindGroups, wgpuDynOffsets } = this._collectBindGroups();
const func = (passEncoder: GPUComputePassEncoder): void => {
passEncoder.setPipeline(computePipeline);
const gpuBindGroupSize = wgpuBindGroups.length;
for (let i = 0; i < gpuBindGroupSize; i++) {
passEncoder.setBindGroup(i, wgpuBindGroups[i], wgpuDynOffsets[i]);
}
passEncoder.dispatchWorkgroups(info.groupCountX, info.groupCountY, info.groupCountZ);
};
this._computeFuncQueue.push(func);
++this._numDispatches;
this._isStateValid = false;
}
public submitComputePass (): void {
if (this._computeFuncQueue.length === 0) {
return;
}
const device = WebGPUDeviceManager.instance;
const nativeDevice = device.nativeDevice!;
const cmdEncoder = nativeDevice.createCommandEncoder();
const computePassEncoder = cmdEncoder.beginComputePass();
this._computeFuncQueue.forEach((cb) => {
cb(computePassEncoder);
});
computePassEncoder.end();
nativeDevice.queue.submit([cmdEncoder.finish()]);
this._computeFuncQueue.length = 0;
}
protected bindStates (): void {
if (!this._curGPUPipelineState) {
return;
}
const gpuPipelineLayout = this._curGPUPipelineState.gpuPipelineLayout as IWebGPUGPUPipelineLayout;
this._prepareDescriptorSets();
const gpuIA = this._curGPUInputAssembler!;
// only 4x MSAA is supported
gpuIA.samples = samples > 1 ? 4 : 1;
this._curWebGPUPipelineState!.prepare(gpuIA);
// ----------------------------wgpu pipline state-----------------------------
const wgpuPipeline = this._curGPUPipelineState.nativePipeline as GPURenderPipeline;
const pplFunc = (passEncoder: GPURenderPassEncoder): void => {
passEncoder.setPipeline(wgpuPipeline);
};
this._renderPassFuncQueue.push(pplFunc);
const pipelineDesc = this._curGPUPipelineState.pipelineState;
if (pipelineDesc && 'depthStencil' in pipelineDesc && pipelineDesc.depthStencil) {
const stencilRef = this._curGPUPipelineState.stencilRef;
const stencilRefFunc = (passEncoder: GPURenderPassEncoder): void => {
passEncoder.setStencilReference(stencilRef);
};
this._renderPassFuncQueue.push(stencilRefFunc);
}
const { wgpuBindGroups, wgpuDynOffsets } = this._collectBindGroups();
const bgfunc = (passEncoder: GPURenderPassEncoder): void => {
const gpuBindGroupSize = wgpuBindGroups.length;
for (let i = 0; i < gpuBindGroupSize; i++) {
let currBindGroup = wgpuBindGroups[i];
if (!currBindGroup) {
currBindGroup = (device.defaultResource.descSet as WebGPUDescriptorSet).gpuDescriptorSet.bindGroup;
}
// FIXME: this is a special sentence that 2 in 3 parameters I'm not certain.
passEncoder.setBindGroup(i, currBindGroup, wgpuDynOffsets[i]);
passEncoder.setBindGroup(i, wgpuBindGroups[i], wgpuDynOffsets[i]);
}
};
this._renderPassFuncQueue.push(bgfunc);
+10 -5
View File
@@ -35,6 +35,7 @@ import {
TextureUsageBit,
ShaderStageFlags,
DescriptorType,
MemoryAccessBit,
Color, Rect, Viewport, BufferTextureCopy,
SamplerInfo,
FormatSize,
@@ -1423,11 +1424,15 @@ export function createBindGroupLayoutEntry (currBind: DescriptorSetLayoutBinding
case DescriptorType.STORAGE_BUFFER:
case DescriptorType.DYNAMIC_STORAGE_BUFFER:
entry.buffer = {
type: 'storage',
hasDynamicOffset: type === DescriptorType.DYNAMIC_STORAGE_BUFFER,
minBindingSize: undefined,
};
{
const readOnly = (currBind.access & MemoryAccessBit.READ_ONLY) !== 0
&& (currBind.access & MemoryAccessBit.WRITE_ONLY) === 0;
entry.buffer = {
type: readOnly ? 'read-only-storage' : 'storage',
hasDynamicOffset: type === DescriptorType.DYNAMIC_STORAGE_BUFFER,
minBindingSize: undefined,
};
}
break;
case DescriptorType.SAMPLER_TEXTURE:
+20 -7
View File
@@ -170,9 +170,17 @@ export class WebGPUDescriptorSet extends DescriptorSet {
if (descType & (DescriptorType.DYNAMIC_STORAGE_BUFFER | DescriptorType.DYNAMIC_UNIFORM_BUFFER)) {
this._dynamicOffsets.push(bindIdx);
}
} else if (descType & DESCRIPTOR_SAMPLER_TYPE) {
if ((descType & DescriptorType.SAMPLER) !== DescriptorType.SAMPLER) {
// texture
} else if (descType & (DESCRIPTOR_SAMPLER_TYPE | DescriptorType.STORAGE_IMAGE)) {
const isStorageImage = (descType & DescriptorType.STORAGE_IMAGE) === DescriptorType.STORAGE_IMAGE;
if (isStorageImage) {
// storage texture (compute read/write): bind the texture view, no sampler
let currTex = this._textures[i] as WebGPUTexture;
if (!currTex || (currTex.hasChange && !currTex.gpuTexture)) {
currTex = device.defaultResource.texture;
}
this._bindTextureEntry(binding, currTex);
} else if ((descType & DescriptorType.SAMPLER) !== DescriptorType.SAMPLER) {
// sampled texture
let currTex = this._textures[i] as WebGPUTexture;
// null or destroyed?
if (!currTex || (currTex.hasChange && !currTex.gpuTexture)) {
@@ -185,9 +193,9 @@ export class WebGPUDescriptorSet extends DescriptorSet {
this._bindTextureEntry(binding, currTex);
}
if (!((descType & DescriptorType.STORAGE_IMAGE) === DescriptorType.STORAGE_IMAGE
|| (descType & DescriptorType.INPUT_ATTACHMENT) === DescriptorType.INPUT_ATTACHMENT
|| (descType & DescriptorType.TEXTURE) === DescriptorType.TEXTURE)) {
if (!isStorageImage
&& !((descType & DescriptorType.INPUT_ATTACHMENT) === DescriptorType.INPUT_ATTACHMENT
|| (descType & DescriptorType.TEXTURE) === DescriptorType.TEXTURE)) {
// sampler
const currSampler = (this._samplers[i] || device.defaultResource.sampler) as WebGPUSampler;
this._bindSamplerEntry(binding, currSampler);
@@ -219,7 +227,12 @@ export class WebGPUDescriptorSet extends DescriptorSet {
}
public prepare (force: boolean = false): void {
const breakUpdate = !this._isResourceChange() && !force;
const gpuDescriptorSet = this._gpuDescriptorSet;
if (!gpuDescriptorSet) {
return;
}
// Rebuild when forced, when the bind group has never been built, or when resources changed.
const breakUpdate = gpuDescriptorSet.bindGroup && !this._isResourceChange() && !force;
if (breakUpdate) return;
this._isDirty = true;
this._applyBindGroup();
+19 -1
View File
@@ -53,7 +53,7 @@ import { WebGPUTexture } from './webgpu-texture';
import { DefaultResources, hashCombineNum, hashCombineStr, webGPU, WebGPUDeviceManager } from './define';
import {
Filter, Format,
QueueType, Feature, BufferTextureCopy, Rect, DescriptorSetInfo,
QueueType, Feature, BufferTextureCopy, Rect, Size, DescriptorSetInfo,
BufferInfo, BufferViewInfo, CommandBufferInfo, DeviceInfo,
FramebufferInfo, InputAssemblerInfo, QueueInfo, RenderPassInfo, SamplerInfo,
ShaderInfo, PipelineLayoutInfo, DescriptorSetLayoutInfo, TextureInfo, TextureViewInfo, GeneralBarrierInfo, TextureBarrierInfo,
@@ -552,6 +552,22 @@ export class WebGPUDevice extends Device {
this._caps.max3DTextureSize = limits.maxTextureDimension3D;
this._caps.uboOffsetAlignment = limits.minUniformBufferOffsetAlignment;
// Compute limits are read from the device (not the adapter): no elevated
// compute limits are requested, so these are the values validation enforces.
const deviceLimits = device.limits;
this._caps.maxComputeSharedMemorySize = deviceLimits.maxComputeWorkgroupStorageSize;
this._caps.maxComputeWorkGroupInvocations = deviceLimits.maxComputeInvocationsPerWorkgroup;
this._caps.maxComputeWorkGroupSize = new Size(
deviceLimits.maxComputeWorkgroupSizeX,
deviceLimits.maxComputeWorkgroupSizeY,
deviceLimits.maxComputeWorkgroupSizeZ,
);
this._caps.maxComputeWorkGroupCount = new Size(
deviceLimits.maxComputeWorkgroupsPerDimension,
deviceLimits.maxComputeWorkgroupsPerDimension,
deviceLimits.maxComputeWorkgroupsPerDimension,
);
const features = this._adapter!.features;
// FIXME: require by query
this._multiDrawIndirect = false;
@@ -560,6 +576,7 @@ export class WebGPUDevice extends Device {
this._features[Feature.ELEMENT_INDEX_UINT] = true;
this._features[Feature.INSTANCED_ARRAYS] = true;
this._features[Feature.MULTIPLE_RENDER_TARGETS] = true;
this._features[Feature.COMPUTE_SHADER] = true;
this.initFormatFeatures(features);
this._queue = this.createQueue(new QueueInfo(QueueType.GRAPHICS));
@@ -684,6 +701,7 @@ export class WebGPUDevice extends Device {
public present (): void {
const queue = (this._queue as unknown as WebGPUQueue);
this._numDrawCalls = queue.numDrawCalls;
this._numDispatches = queue.numDispatches;
this._numInstances = queue.numInstances;
this._numTris = queue.numTris;
queue.clear();
+2 -2
View File
@@ -241,8 +241,8 @@ export interface IWebGPUGPUPipelineState {
bs: BlendState;
dynamicStates: DynamicStateFlagBit[];
gpuRenderPass: IWebGPUGPURenderPass | null;
pipelineState: GPURenderPipelineDescriptor | undefined;
nativePipeline: GPUPipelineBase | undefined;
pipelineState: GPURenderPipelineDescriptor | GPUComputePipelineDescriptor | undefined;
nativePipeline: GPURenderPipeline | GPUComputePipeline | undefined;
}
export interface IWebGPUGPUDescriptor {
+161 -118
View File
@@ -26,7 +26,7 @@ import { PipelineState, PipelineStateInfo } from '../base/pipeline-state';
import { IWebGPUGPUInputAssembler, IWebGPUGPUPipelineState } from './webgpu-gpu-objects';
import { WebGPURenderPass } from './webgpu-render-pass';
import { WebGPUShader } from './webgpu-shader';
import { BlendOp, CullMode, DynamicStateFlagBit, Format, FormatInfos, PrimitiveMode, ShaderStageFlagBit } from '../base/define';
import { BlendOp, CullMode, DynamicStateFlagBit, Format, FormatInfos, PipelineBindPoint, PrimitiveMode, ShaderStageFlagBit } from '../base/define';
import { WebGPUPipelineLayout } from './webgpu-pipeline-layout';
import {
GFXFormatToWGPUFormat,
@@ -81,124 +81,156 @@ export class WebGPUPipelineState extends PipelineState {
}
}
// colorstates
const colorAttachments = this._renderPass.colorAttachments;
const colorDescs: GPUColorTargetState[] = [];
const colAttachmentSize = colorAttachments.length;
const pipelineLayoutObj = info.pipelineLayout as WebGPUPipelineLayout;
for (let i = 0; i < colAttachmentSize; i++) {
const colDesc: GPUColorTargetState = {
format: GFXFormatToWGPUFormat(colorAttachments[i].format),
writeMask: WebGPUBlendMask(this._bs.targets[i].blendColorMask),
};
if (this._bs.targets[i].blend) {
colDesc.blend = {
color: {
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDst],
operation: WebGPUBlendOps[this._bs.targets[i].blendEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendEq],
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrc],
},
alpha: {
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDstAlpha],
operation: WebGPUBlendOps[this._bs.targets[i].blendAlphaEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendAlphaEq],
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrcAlpha],
},
};
}
colorDescs.push(colDesc);
}
let vertexStage: GPUProgrammableStage;
let fragmentStage: GPUProgrammableStage;
const shaderStages = (this._shader as WebGPUShader).gpuShader.gpuStages;
const stageSize = shaderStages.length;
for (let i = 0; i < stageSize; i++) {
if (shaderStages[i].type === ShaderStageFlagBit.VERTEX) { vertexStage = shaderStages[i].gpuShader!; }
if (shaderStages[i].type === ShaderStageFlagBit.FRAGMENT) { fragmentStage = shaderStages[i].gpuShader!; }
}
const gpuShader = info.shader as WebGPUShader;
const pipelineLayoutObj = info.pipelineLayout as WebGPUPipelineLayout;
const shaderStages = gpuShader.gpuShader.gpuStages;
const shaderAttrs = gpuShader.attributes;
const attrsSize = shaderAttrs.length;
for (let i = 0; i < attrsSize; i++) {
this._locations.set(shaderAttrs[i].name, shaderAttrs[i].location);
}
const stripTopology = (info.primitive === PrimitiveMode.LINE_STRIP || info.primitive === PrimitiveMode.TRIANGLE_STRIP);
const renderPplDesc: GPURenderPipelineDescriptor = {
layout: pipelineLayoutObj.gpuPipelineLayout!.nativePipelineLayout,
vertex: {
module: vertexStage!.module,
entryPoint: 'main',
buffers: [],
},
primitive: {
topology: WebPUPrimitives[info.primitive],
frontFace: this._rs.isFrontFaceCCW ? 'ccw' : 'cw',
cullMode: this._rs.cullMode === CullMode.NONE ? 'none' : (this._rs.cullMode === CullMode.FRONT) ? 'front' : 'back',
},
fragment: {
module: fragmentStage!.module,
entryPoint: 'main',
targets: colorDescs,
},
};
if (stripTopology) renderPplDesc.primitive!.stripIndexFormat = 'uint16';
// depthstencil states
let stencilRef = 0;
if (this._renderPass.depthStencilAttachment?.format !== Format.UNKNOWN) {
const dssDesc = {} as GPUDepthStencilState;
dssDesc.format = GFXFormatToWGPUFormat(this._renderPass.depthStencilAttachment!.format);
dssDesc.depthWriteEnabled = this._dss.depthWrite;
dssDesc.depthCompare = this._dss.depthTest ? WebGPUCompereFunc[this._dss.depthFunc] : 'always';
let stencilReadMask = 0;
let stencilWriteMask = 0;
if (this._dss.stencilTestFront) {
dssDesc.stencilFront = {
compare: WebGPUCompereFunc[this._dss.stencilFuncFront],
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpFront],
passOp: WebGPUStencilOp[this._dss.stencilPassOpFront],
failOp: WebGPUStencilOp[this._dss.stencilFailOpFront],
};
stencilReadMask |= this._dss.stencilReadMaskFront;
stencilWriteMask |= this._dss.stencilWriteMaskFront;
stencilRef |= this._dss.stencilRefFront;
if (info.bindPoint === PipelineBindPoint.COMPUTE) {
// ---- Compute Pipeline ----
let computeStage: GPUProgrammableStage | undefined;
const stageSize = shaderStages.length;
for (let i = 0; i < stageSize; i++) {
if (shaderStages[i].type === ShaderStageFlagBit.COMPUTE) {
computeStage = shaderStages[i].gpuShader!;
}
}
if (this._dss.stencilTestBack) {
dssDesc.stencilBack = {
compare: WebGPUCompereFunc[this._dss.stencilFuncBack],
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpBack],
passOp: WebGPUStencilOp[this._dss.stencilPassOpBack],
failOp: WebGPUStencilOp[this._dss.stencilFailOpBack],
};
stencilReadMask |= this._dss.stencilReadMaskBack;
stencilWriteMask |= this._dss.stencilWriteMaskBack;
stencilRef |= this._dss.stencilRefBack;
}
dssDesc.stencilReadMask = stencilReadMask;
dssDesc.stencilWriteMask = stencilWriteMask;
dssDesc.depthBias = this._rs.depthBias;
dssDesc.depthBiasSlopeScale = this._rs.depthBiasSlop;
dssDesc.depthBiasClamp = this._rs.depthBiasClamp;
renderPplDesc.depthStencil = dssDesc;
}
this._gpuPipelineState = {
gpuPrimitive: WebPUPrimitives[info.primitive],
gpuShader: gpuShader.gpuShader,
gpuPipelineLayout: pipelineLayoutObj.gpuPipelineLayout,
rs: info.rasterizerState,
dss: info.depthStencilState,
stencilRef,
bs: info.blendState,
gpuRenderPass: (info.renderPass as WebGPURenderPass).gpuRenderPass,
dynamicStates,
pipelineState: renderPplDesc,
nativePipeline: undefined,
};
const computeDesc: GPUComputePipelineDescriptor = {
layout: pipelineLayoutObj.gpuPipelineLayout!.nativePipelineLayout,
compute: computeStage!,
};
this._gpuPipelineState = {
gpuPrimitive: 'triangle-list' as GPUPrimitiveTopology,
gpuShader: gpuShader.gpuShader,
gpuPipelineLayout: pipelineLayoutObj.gpuPipelineLayout,
rs: info.rasterizerState,
dss: info.depthStencilState,
stencilRef: 0,
bs: info.blendState,
gpuRenderPass: null,
dynamicStates,
pipelineState: computeDesc,
nativePipeline: undefined,
};
} else {
// ---- Render Pipeline ----
// colorstates
const colorAttachments = this._renderPass.colorAttachments;
const colorDescs: GPUColorTargetState[] = [];
const colAttachmentSize = colorAttachments.length;
for (let i = 0; i < colAttachmentSize; i++) {
const colDesc: GPUColorTargetState = {
format: GFXFormatToWGPUFormat(colorAttachments[i].format),
writeMask: WebGPUBlendMask(this._bs.targets[i].blendColorMask),
};
if (this._bs.targets[i].blend) {
colDesc.blend = {
color: {
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDst],
operation: WebGPUBlendOps[this._bs.targets[i].blendEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendEq],
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrc],
},
alpha: {
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDstAlpha],
operation: WebGPUBlendOps[
this._bs.targets[i].blendAlphaEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendAlphaEq],
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrcAlpha],
},
};
}
colorDescs.push(colDesc);
}
let vertexStage: GPUProgrammableStage;
let fragmentStage: GPUProgrammableStage;
const stageSize = shaderStages.length;
for (let i = 0; i < stageSize; i++) {
if (shaderStages[i].type === ShaderStageFlagBit.VERTEX) { vertexStage = shaderStages[i].gpuShader!; }
if (shaderStages[i].type === ShaderStageFlagBit.FRAGMENT) { fragmentStage = shaderStages[i].gpuShader!; }
}
const shaderAttrs = gpuShader.attributes;
const attrsSize = shaderAttrs.length;
for (let i = 0; i < attrsSize; i++) {
this._locations.set(shaderAttrs[i].name, shaderAttrs[i].location);
}
const stripTopology = (info.primitive === PrimitiveMode.LINE_STRIP || info.primitive === PrimitiveMode.TRIANGLE_STRIP);
const renderPplDesc: GPURenderPipelineDescriptor = {
layout: pipelineLayoutObj.gpuPipelineLayout!.nativePipelineLayout,
vertex: {
module: vertexStage!.module,
entryPoint: 'main',
buffers: [],
},
primitive: {
topology: WebPUPrimitives[info.primitive],
frontFace: this._rs.isFrontFaceCCW ? 'ccw' : 'cw',
cullMode: this._rs.cullMode === CullMode.NONE ? 'none' : (this._rs.cullMode === CullMode.FRONT) ? 'front' : 'back',
},
fragment: {
module: fragmentStage!.module,
entryPoint: 'main',
targets: colorDescs,
},
};
if (stripTopology) renderPplDesc.primitive!.stripIndexFormat = 'uint16';
// depthstencil states
let stencilRef = 0;
if (this._renderPass.depthStencilAttachment?.format !== Format.UNKNOWN) {
const dssDesc = {} as GPUDepthStencilState;
dssDesc.format = GFXFormatToWGPUFormat(this._renderPass.depthStencilAttachment!.format);
dssDesc.depthWriteEnabled = this._dss.depthWrite;
dssDesc.depthCompare = this._dss.depthTest ? WebGPUCompereFunc[this._dss.depthFunc] : 'always';
let stencilReadMask = 0;
let stencilWriteMask = 0;
if (this._dss.stencilTestFront) {
dssDesc.stencilFront = {
compare: WebGPUCompereFunc[this._dss.stencilFuncFront],
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpFront],
passOp: WebGPUStencilOp[this._dss.stencilPassOpFront],
failOp: WebGPUStencilOp[this._dss.stencilFailOpFront],
};
stencilReadMask |= this._dss.stencilReadMaskFront;
stencilWriteMask |= this._dss.stencilWriteMaskFront;
stencilRef |= this._dss.stencilRefFront;
}
if (this._dss.stencilTestBack) {
dssDesc.stencilBack = {
compare: WebGPUCompereFunc[this._dss.stencilFuncBack],
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpBack],
passOp: WebGPUStencilOp[this._dss.stencilPassOpBack],
failOp: WebGPUStencilOp[this._dss.stencilFailOpBack],
};
stencilReadMask |= this._dss.stencilReadMaskBack;
stencilWriteMask |= this._dss.stencilWriteMaskBack;
stencilRef |= this._dss.stencilRefBack;
}
dssDesc.stencilReadMask = stencilReadMask;
dssDesc.stencilWriteMask = stencilWriteMask;
dssDesc.depthBias = this._rs.depthBias;
dssDesc.depthBiasSlopeScale = this._rs.depthBiasSlop;
dssDesc.depthBiasClamp = this._rs.depthBiasClamp;
renderPplDesc.depthStencil = dssDesc;
}
this._gpuPipelineState = {
gpuPrimitive: WebPUPrimitives[info.primitive],
gpuShader: gpuShader.gpuShader,
gpuPipelineLayout: pipelineLayoutObj.gpuPipelineLayout,
rs: info.rasterizerState,
dss: info.depthStencilState,
stencilRef,
bs: info.blendState,
gpuRenderPass: (info.renderPass as WebGPURenderPass).gpuRenderPass,
dynamicStates,
pipelineState: renderPplDesc,
nativePipeline: undefined,
};
}
}
protected _getShaderLocation (name: string): number | undefined {
@@ -215,9 +247,22 @@ export class WebGPUPipelineState extends PipelineState {
if (this._gpuPipelineState!.nativePipeline && !forceUpdate) {
return;
}
const webgpuDevice = (WebGPUDeviceManager.instance);
const nativeDevice = webgpuDevice.nativeDevice;
const pipelineState = this._gpuPipelineState!.pipelineState!;
// Compute pipeline: no vertex attributes, no multisample
if ('compute' in pipelineState) {
const nativePipeline = nativeDevice?.createComputePipeline(
pipelineState,
);
this._gpuPipelineState!.nativePipeline = nativePipeline;
return;
}
// Render pipeline
const gpuShader = this.shader;
const shaderAttrs = gpuShader.attributes;
const pipelineState = this._gpuPipelineState!.pipelineState!;
const vertexAttrs: GPUVertexBufferLayout[] = [];
const emptyPushAttr: string[] = [];
const streamCount = ia.gpuVertexBuffers.length;
@@ -272,8 +317,6 @@ export class WebGPUPipelineState extends PipelineState {
pipelineState.vertex.buffers = vertexAttrs;
pipelineState.multisample = { count: ia.samples };
const webgpuDevice = (WebGPUDeviceManager.instance);
const nativeDevice = webgpuDevice.nativeDevice;
const nativePipeline = nativeDevice?.createRenderPipeline(pipelineState);
this._gpuPipelineState!.nativePipeline = nativePipeline;
}
+3
View File
@@ -29,6 +29,7 @@ import { QueueInfo } from '../base/define';
export class WebGPUQueue extends Queue {
public numDrawCalls = 0;
public numDispatches = 0;
public numInstances = 0;
public numTris = 0;
@@ -51,6 +52,7 @@ export class WebGPUQueue extends Queue {
for (let i = 0; i < cmdBuffSize; i++) {
const cmdBuff = cmdBuffs[i] as WebGPUCommandBuffer;
this.numDrawCalls += cmdBuff.numDrawCalls;
this.numDispatches += cmdBuff.numDispatches;
this.numInstances += cmdBuff.numInstances;
this.numTris += cmdBuff.numTris;
}
@@ -59,6 +61,7 @@ export class WebGPUQueue extends Queue {
public clear (): void {
this.numDrawCalls = 0;
this.numDispatches = 0;
this.numInstances = 0;
this.numTris = 0;
}
+27 -8
View File
@@ -52,6 +52,7 @@ class Particle {
public pos = new Vec2(0, 0);
public startPos = new Vec2(0, 0);
public color = new Color(0, 0, 0, 255);
public curColor = { r: 0, g: 0, b: 0, a: 255 };
public deltaColor = { r: 0, g: 0, b: 0, a: 255 };
public size = 0;
public deltaSize = 0;
@@ -81,6 +82,8 @@ const pool = new ParticlePool((par: Particle): void => {
par.pos.set(Vec2.ZERO);
par.startPos.set(Vec2.ZERO);
par.color.set(0, 0, 0, 255);
par.curColor.r = par.curColor.g = par.curColor.b = 0;
par.curColor.a = 255;
par.deltaColor.r = par.deltaColor.g = par.deltaColor.b = 0;
par.deltaColor.a = 255;
par.size = 0;
@@ -111,6 +114,7 @@ export class Simulator {
private elapsed = 0;
private emitCounter = 0;
private _worldRotation = 0;
private _parentAlpha = 0.0;
private declare sys: ParticleSystem2D;
constructor (system) {
@@ -169,10 +173,10 @@ export class Simulator {
const endColor = psys.endColor;
const endColorVar = psys.endColorVar;
particle.color.r = sr = clamp(startColor.r + startColorVar.r * (random() - 0.5) * 2, 0, 255);
particle.color.g = sg = clamp(startColor.g + startColorVar.g * (random() - 0.5) * 2, 0, 255);
particle.color.b = sb = clamp(startColor.b + startColorVar.b * (random() - 0.5) * 2, 0, 255);
particle.color.a = sa = clamp(startColor.a + startColorVar.a * (random() - 0.5) * 2, 0, 255);
particle.curColor.r = sr = clamp(startColor.r + startColorVar.r * (random() - 0.5) * 2, 0, 255);
particle.curColor.g = sg = clamp(startColor.g + startColorVar.g * (random() - 0.5) * 2, 0, 255);
particle.curColor.b = sb = clamp(startColor.b + startColorVar.b * (random() - 0.5) * 2, 0, 255);
particle.curColor.a = sa = clamp(startColor.a + startColorVar.a * (random() - 0.5) * 2, 0, 255);
particle.deltaColor.r = (clamp(endColor.r + endColorVar.r * (random() - 0.5) * 2, 0, 255) - sr) / timeToLive;
particle.deltaColor.g = (clamp(endColor.g + endColorVar.g * (random() - 0.5) * 2, 0, 255) - sg) / timeToLive;
particle.deltaColor.b = (clamp(endColor.b + endColorVar.b * (random() - 0.5) * 2, 0, 255) - sb) / timeToLive;
@@ -329,6 +333,14 @@ export class Simulator {
Vec4.toArray(vbuf, _col, offset + 32);
}
private _updateColor (): void {
const selfNode = this.sys.node;
const parentNode = selfNode.parent;
const uiProps = selfNode._uiProps;
const parentOpacity = parentNode ? parentNode._uiProps.opacity : 1.0;
this._parentAlpha = uiProps.localOpacity * parentOpacity;
}
public step (dt: number): void {
const assembler = this.sys.assembler as Particle2DAssembler;
const psys = this.sys;
@@ -379,6 +391,8 @@ export class Simulator {
this.updateUVs();
}
this._updateColor();
// Used to reduce memory allocation / creation within the loop
let particleIdx = 0;
while (particleIdx < particles.length) {
@@ -431,10 +445,15 @@ export class Simulator {
}
// color
particle.color.r += particle.deltaColor.r * dt;
particle.color.g += particle.deltaColor.g * dt;
particle.color.b += particle.deltaColor.b * dt;
particle.color.a += particle.deltaColor.a * dt;
particle.curColor.r += particle.deltaColor.r * dt;
particle.curColor.g += particle.deltaColor.g * dt;
particle.curColor.b += particle.deltaColor.b * dt;
particle.curColor.a += particle.deltaColor.a * dt;
particle.color.r = particle.curColor.r;
particle.color.g = particle.curColor.g;
particle.color.b = particle.curColor.b;
particle.color.a = particle.curColor.a * this._parentAlpha;
// size
particle.size += particle.deltaSize * dt;
+1 -1
View File
@@ -797,7 +797,7 @@ export class ParticleSystem2D extends UIRenderer {
}
private _startPreview (): void {
if (this._preview) {
if (!this._preview) {
this.resetSystem();
}
}
+2 -2
View File
@@ -23,7 +23,7 @@
*/
import { ccclass, type, serializable, editable, range } from 'cc.decorator';
import { repeat } from '../core/math';
import { approxGE, approxLT, repeat } from '../core/math';
import CurveRange from './animator/curve-range';
import type { ParticleSystem } from './particle-system';
@@ -108,7 +108,7 @@ export default class Burst {
let preFrameTime = repeat(psys.time - psys.startDelay.evaluate(0, 1), psys.duration) - dt;
preFrameTime = (preFrameTime > 0.0) ? preFrameTime : 0.0;
const curFrameTime = repeat(psys.time - psys.startDelay.evaluate(0, 1), psys.duration);
if (this._curTime >= preFrameTime && this._curTime < curFrameTime) {
if (approxGE(this._curTime, preFrameTime) && approxLT(this._curTime, curFrameTime)) {
psys.emit(this.count.evaluate(this._curTime / psys.duration, 1), dt - (curFrameTime - this._curTime));
this._curTime += this.repeatInterval;
--this._remainingCount;
+10 -1
View File
@@ -25,7 +25,7 @@
import { ccclass, help, executeInEditMode, menu, tooltip, displayOrder, type, serializable,
range, visible, override, displayName } from 'cc.decorator';
import { Material, Texture2D } from '../asset/assets';
import { Vec3, cclegacy, Vec4, Vec2, CCBoolean } from '../core';
import { Vec3, cclegacy, Vec4, Vec2, CCBoolean, Color } from '../core';
import { LineModel } from './models/line-model';
import { builtinResMgr } from '../asset/asset-manager';
import CurveRange from './animator/curve-range';
@@ -296,6 +296,15 @@ export class Line extends ModelRenderer {
}
}
public updateColor (): void {
if (this._color) {
if (this._models[0]) {
const lineModel = this._models[0] as LineModel;
lineModel.addLineVertexData(this._positions, this._width, this._color);
}
}
}
protected _onMaterialModified (index: number, material: Material | null): void {
super._onMaterialModified(index, material);
const matIns = this.getMaterialInstance(0);
+14 -4
View File
@@ -29,7 +29,8 @@ import { Vec2, Vec3 } from '../core/math';
* @zh 此类生成噪声纹理。
*/
export class ParticleNoise {
private permutation: number[] = [151, 160, 137, 91, 90, 15,
private static readonly DEFAULT_PERMUTATION: readonly number[] = [
151, 160, 137, 91, 90, 15,
131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23,
190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33,
88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166,
@@ -44,9 +45,19 @@ export class ParticleNoise {
138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,
];
private static build512 (src: readonly number[] | number[]): Uint8Array {
const p = new Uint8Array(512);
for (let i = 0; i < 256; i++) { p[256 + i] = p[i] = src[i]; }
return p;
}
private permutation: number[] = ParticleNoise.DEFAULT_PERMUTATION as number[];
private permutation512: Uint8Array = ParticleNoise.build512(ParticleNoise.DEFAULT_PERMUTATION);
constructor (permutation?: number[]) {
if (permutation) {
this.permutation = permutation;
this.permutation = permutation.slice();
this.permutation512 = ParticleNoise.build512(this.permutation);
}
}
@@ -61,8 +72,7 @@ export class ParticleNoise {
* @returns @en Texture pixel generated. @zh 返回生成的噪声纹理值。
*/
public noise (x: number, y: number, z: number, min = 0, max = 1): number {
const p: number[] = new Array(512);
for (let i = 0; i < 256; i++) { p[256 + i] = p[i] = this.permutation[i]; }
const p: Uint8Array = this.permutation512;
const X = Math.floor(x) & 255; // FIND UNIT CUBE THAT
const Y = Math.floor(y) & 255; // CONTAINS POINT.
+11 -9
View File
@@ -42,7 +42,7 @@ import VelocityOvertimeModule from './animator/velocity-overtime';
import Burst from './burst';
import ShapeModule from './emitter/shape-module';
import { ParticleCullingMode, ParticleSpace } from './enum';
import { particleEmitZAxis } from './particle-general-function';
import { isCurveTwoValues, particleEmitZAxis } from './particle-general-function';
import ParticleSystemRenderer from './renderer/particle-system-renderer-data';
import TrailModule from './renderer/trail';
import { ParticleSystemRendererBase } from './renderer/particle-system-renderer-base';
@@ -141,7 +141,7 @@ export class ParticleSystem extends ModelRenderer {
@range([0, Number.POSITIVE_INFINITY])
@displayOrder(10)
@tooltip('i18n:particle_system.startSizeY')
@visible(function (this: ParticleSystem): boolean { return this.startSize3D; })
@visible(function (this: ParticleSystem): boolean { return this.startSize3D; }) // eslint-disable-line func-names, comma-dangle
public startSizeY = new CurveRange();
/**
@@ -153,7 +153,7 @@ export class ParticleSystem extends ModelRenderer {
@range([0, Number.POSITIVE_INFINITY])
@displayOrder(10)
@tooltip('i18n:particle_system.startSizeZ')
@visible(function (this: ParticleSystem): boolean { return this.startSize3D; })
@visible(function (this: ParticleSystem): boolean { return this.startSize3D; }) // eslint-disable-line func-names, comma-dangle
public startSizeZ = new CurveRange();
/**
@@ -184,7 +184,7 @@ export class ParticleSystem extends ModelRenderer {
@radian
@displayOrder(12)
@tooltip('i18n:particle_system.startRotationX')
@visible(function (this: ParticleSystem): boolean { return this.startRotation3D; })
@visible(function (this: ParticleSystem): boolean { return this.startRotation3D; }) // eslint-disable-line func-names, comma-dangle
public startRotationX = new CurveRange();
/**
@@ -196,7 +196,7 @@ export class ParticleSystem extends ModelRenderer {
@radian
@displayOrder(12)
@tooltip('i18n:particle_system.startRotationY')
@visible(function (this: ParticleSystem): boolean { return this.startRotation3D; })
@visible(function (this: ParticleSystem): boolean { return this.startRotation3D; }) // eslint-disable-line func-names, comma-dangle
public startRotationY = new CurveRange();
/**
@@ -233,8 +233,8 @@ export class ParticleSystem extends ModelRenderer {
public startLifetime = new CurveRange();
/**
* @en Particle system duration time.
* @zh 粒子系统运行时间。
* @en Particle system emitter duration time.
* @zh 粒子系统发射器运行时间。
*/
@serializable
@displayOrder(0)
@@ -1455,16 +1455,18 @@ export class ParticleSystem extends ModelRenderer {
if (!self._isEmitting) return;
const randTime = isCurveTwoValues(self.rateOverTime) ? pseudoRandom(randomRangeInt(0, bits.INT_MAX)) : 1;
// emit by rateOverTime
self._emitRateTimeCounter += self.rateOverTime.evaluate(self._time / self.duration, 1)! * dt;
self._emitRateTimeCounter += self.rateOverTime.evaluate(self._time / self.duration, randTime)! * dt;
if (self._emitRateTimeCounter > 1) {
const emitNum = Math.floor(self._emitRateTimeCounter);
self._emitRateTimeCounter -= emitNum;
self.emit(emitNum, dt);
}
const randDist = isCurveTwoValues(self.rateOverDistance) ? pseudoRandom(randomRangeInt(0, bits.INT_MAX)) : 1;
// emit by rateOverDistance
const rateOverDistance = self.rateOverDistance.evaluate(self._time / self.duration, 1)!;
const rateOverDistance = self.rateOverDistance.evaluate(self._time / self.duration, randDist)!;
if (rateOverDistance > 0) {
Vec3.copy(self._oldWPos, self._curWPos);
self.node.getWorldPosition(self._curWPos);
@@ -747,6 +747,12 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas
this._defines[ROTATION_OVER_TIME_MODULE_ENABLE] = enable;
this._defines[INSTANCE_PARTICLE] = this._useInstance;
const matIns: MaterialInstance | null = ps.getMaterialInstance(0);
if (matIns === null || matIns === undefined) {
ps.setSharedMaterial(mat.parent, 0); // set material[0] as material for ui-mesh-renderer to use
ps.setMaterialInstance(mat, 0);
}
mat.recompileShaders(this._defines);
if (this._model) {
this._model.updateMaterial(mat);
@@ -776,6 +782,13 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas
_matInsInfo.subModelIdx = 0;
}
mat = mat || this._defaultTrailMat!;
const matIns: MaterialInstance | null = ps.getMaterialInstance(1);
if (matIns === null || matIns === undefined) {
ps.setSharedMaterial(mat.parent, 1); // set material[1] as trail material for ui-mesh-renderer to use
ps.setMaterialInstance(mat, 1);
}
const texture = mat.getProperty('mainTexture', 0) as Texture2D | null;
if (texture && texture.isAlphaAtlas) {
this._trailDefines[CC_USE_EMBEDDED_ALPHA] = true;
+4 -1
View File
@@ -377,7 +377,10 @@ export default class TrailModule {
if (this.lifeTime.getMax() < 1.0) {
warnID(6036);
}
this._trailNum = Math.ceil(psTime * Math.ceil(this.lifeTime.getMax()) * 60 * (psRate * duration + burstCount));
let pCount: number = psRate * duration; // potential particle count
pCount = ps.prewarm ? pCount * 2 : pCount; // if prewarm we need double space
pCount = pCount > ps.capacity ? ps.capacity : pCount; // max particle count is less/equal than capacity
this._trailNum = Math.ceil(psTime * Math.ceil(this.lifeTime.getMax()) * 60 * (pCount + burstCount));
this._trailSegments = new Pool(
(): TrailSegment => new TrailSegment(10),
Math.ceil(psRate * duration),
+1 -1
View File
@@ -141,7 +141,7 @@ export class b2PhysicsWorld implements IPhysicsWorld {
if (!v) {
if (this._debugGraphics) {
this._debugGraphics.node.parent = null;
this._debugGraphics.clear();
}
}
@@ -34,8 +34,8 @@ export class b2CircleShape extends b2Shape2D implements ICircleShape {
_worldPosition = new Vec2();
get worldPosition (): Vec2 {
const p = (this._shapes[0] as b2jsb.CircleShape).m_p;
return this._worldPosition.set(p.x * PHYSICS_2D_PTM_RATIO, p.y * PHYSICS_2D_PTM_RATIO);
const comp = this.collider as CircleCollider2D;
return Vec2.transformMat4(this._worldPosition, comp.offset, comp.node.worldMatrix);
}
_createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): any[] {
+3 -3
View File
@@ -26,7 +26,7 @@ import { instantiateWasm, ensureWasmModuleReady } from 'pal/wasm';
import { BUILD, LOAD_BOX2D_MANUALLY, NATIVE_CODE_BUNDLE_MODE } from 'internal:constants';
import { game } from '../../game';
import { error, sys, IVec2Like, log } from '../../core';
import { error, sys, IVec2Like, log, debug } from '../../core';
import { NativeCodeBundleMode } from '../../misc/webassembly-support';
// eslint-disable-next-line import/no-mutable-exports
@@ -148,7 +148,7 @@ function initWasm (wasmFactory, wasmUrl: string): Promise<void> {
}).catch((err) => reject(errorMessage(err)));
},
}).then((Instance: any) => {
log('[box2d]:box2d wasm lib loaded.');
debug('[box2d]:box2d wasm lib loaded.');
B2 = Instance;
}).then(resolve).catch((err: any) => reject(errorMessage(err)));
});
@@ -158,7 +158,7 @@ function initAsm (asmFactory): Promise<void> {
return new Promise<void>((resolve, reject) => {
const errorMessage = (err: any): string => `[box2d]: box2d asm lib load failed: ${err}`;
asmFactory().then((instance: any) => {
log('[box2d]:box2d asm lib loaded.');
debug('[box2d]:box2d asm lib loaded.');
B2 = instance;
}).then(resolve).catch((err: any) => reject(errorMessage(err)));
});
+1 -1
View File
@@ -114,7 +114,7 @@ export class B2PhysicsWorld implements IPhysicsWorld {
if (!v) {
if (this._debugGraphics) {
this._debugGraphics.node.parent = null;
this._debugGraphics.clear();
}
}
@@ -37,8 +37,8 @@ export class B2CircleShape extends B2Shape2D implements ICircleShape {
_worldPosition = new Vec2();
get worldPosition (): Vec2 {
const p = B2.CircleShapeGetPosition(this._shapes[0]) as B2.Vec2;
return this._worldPosition.set(p.x * PHYSICS_2D_PTM_RATIO, p.y * PHYSICS_2D_PTM_RATIO);
const comp = this.collider as CircleCollider2D;
return Vec2.transformMat4(this._worldPosition, comp.offset, comp.node.worldMatrix);
}
_createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): number[] { //B2.CircleShape[]
+1 -1
View File
@@ -100,7 +100,7 @@ export class b2PhysicsWorld implements IPhysicsWorld {
if (!v) {
if (this._debugGraphics) {
this._debugGraphics.node.parent = null;
this._debugGraphics.clear();
}
}
@@ -37,8 +37,8 @@ export class b2CircleShape extends b2Shape2D implements ICircleShape {
_worldPosition = new Vec2();
get worldPosition (): Vec2 {
const p = (this._shapes[0] as b2.CircleShape).m_p;
return this._worldPosition.set(p.x * PHYSICS_2D_PTM_RATIO, p.y * PHYSICS_2D_PTM_RATIO);
const comp = this.collider as CircleCollider2D;
return Vec2.transformMat4(this._worldPosition, comp.offset, comp.node.worldMatrix);
}
_createShapes (scaleX: number, scaleY: number, relativePositionX: number, relativePositionY: number): any[] {
@@ -27,7 +27,7 @@ import { EDITOR, DEBUG, TEST, EDITOR_NOT_IN_PREVIEW } from 'internal:constants';
import { IRigidBody2D } from '../spec/i-rigid-body';
import { IBoxShape, ICircleShape, IPolygonShape, IBaseShape } from '../spec/i-physics-shape';
import { IPhysicsWorld } from '../spec/i-physics-world';
import { errorID, log } from '../../core';
import { debug, errorID, log } from '../../core';
import { ECollider2DType, EJoint2DType } from './physics-types';
import { IJoint2D, IDistanceJoint, ISpringJoint, IFixedJoint, IMouseJoint,
IRelativeJoint, ISliderJoint, IWheelJoint, IHingeJoint } from '../spec/i-physics-joint';
@@ -110,7 +110,7 @@ export interface IPhysicsSelector {
}
function register (id: IPhysicsEngineId, wrapper: IPhysicsWrapperObject): void {
if (!EDITOR && !TEST) log(`[PHYSICS2D]: register ${id}.`);
if (!EDITOR && !TEST) debug(`[PHYSICS2D]: register ${id}.`);
selector.backend[id] = wrapper;
if (!selector.physicsWorld || selector.id === id) {
const mutableSelector = selector as Mutable<IPhysicsSelector>;
@@ -124,12 +124,12 @@ function switchTo (id: IPhysicsEngineId): void {
const mutableSelector = selector as Mutable<IPhysicsSelector>;
if (selector.physicsWorld && id !== selector.id && selector.backend[id] != null) {
//selector.physicsWorld.destroy();//todo
if (!TEST) log(`[PHYSICS2D]: switch from ${selector.id} to ${id}.`);
if (!TEST) debug(`[PHYSICS2D]: switch from ${selector.id} to ${id}.`);
mutableSelector.id = id;
mutableSelector.wrapper = selector.backend[id];
mutableSelector.physicsWorld = createPhysicsWorld();
} else {
if (!EDITOR && !TEST) log(`[PHYSICS2D]: using ${mutableSelector.id}.`);
if (!EDITOR && !TEST) debug(`[PHYSICS2D]: using ${mutableSelector.id}.`);
mutableSelector.physicsWorld = createPhysicsWorld();
}
}
+3 -3
View File
@@ -25,7 +25,7 @@
import { ensureWasmModuleReady, instantiateWasm } from 'pal/wasm';
import { BUILD, LOAD_BULLET_MANUALLY, NATIVE_CODE_BUNDLE_MODE } from 'internal:constants';
import { game } from '../../game';
import { error, log, sys } from '../../core';
import { debug, error, sys } from '../../core';
import { NativeCodeBundleMode } from '../../misc/webassembly-support';
import type { BulletCache } from './bullet-cache';
@@ -106,7 +106,7 @@ function initWASM (wasmFactory, wasmUrl: string): Promise<void> {
}).catch((err) => reject(errorMessage(err)));
},
}).then((instance: any) => {
log('[bullet]:bullet wasm lib loaded.');
debug('[bullet]:bullet wasm lib loaded.');
bt = instance as Bullet.instance;
globalThis.Bullet = bt as any;
}).then(resolve).catch((err: any) => reject(errorMessage(err)));
@@ -117,7 +117,7 @@ function initASM (asmFactory): Promise<void> {
if (asmFactory != null) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return asmFactory().then((instance: any) => {
log('[bullet]:bullet asm lib loaded.');
debug('[bullet]:bullet asm lib loaded.');
bt = instance as Bullet.instance;
});
} else {
+5 -5
View File
@@ -35,7 +35,7 @@ import {
import { IPhysicsWorld } from '../spec/i-physics-world';
import { IRigidBody } from '../spec/i-rigid-body';
import { IBoxCharacterController, ICapsuleCharacterController } from '../spec/i-character-controller';
import { errorID, IVec3Like, warn, cclegacy, log } from '../../core';
import { errorID, IVec3Like, warn, cclegacy, debug } from '../../core';
import { EColliderType, EConstraintType, ECharacterControllerType } from './physics-enum';
import { PhysicsMaterial } from '.';
@@ -125,7 +125,7 @@ function updateLegacyMacro (id: string): void {
}
function register (id: IPhysicsEngineId, wrapper: IPhysicsWrapperObject): void {
if (!EDITOR && !TEST) log(`[PHYSICS]: register ${id}.`);
if (!EDITOR && !TEST) debug(`[PHYSICS]: register ${id}.`);
selector.backend[id] = wrapper;
if (!selector.physicsWorld || selector.id === id) {
updateLegacyMacro(id);
@@ -147,13 +147,13 @@ function switchTo (id: IPhysicsEngineId): void {
const mutableSelector = selector as Mutable<IPhysicsSelector>;
if (selector.physicsWorld && id !== selector.id && selector.backend[id] != null) {
selector.physicsWorld.destroy();
if (!TEST) log(`[PHYSICS]: switch from ${selector.id} to ${id}.`);
if (!TEST) debug(`[PHYSICS]: switch from ${selector.id} to ${id}.`);
updateLegacyMacro(id);
mutableSelector.id = id;
mutableSelector.wrapper = selector.backend[id];
mutableSelector.physicsWorld = createPhysicsWorld();
} else {
if (!EDITOR && !TEST) log(`[PHYSICS]: using ${id}.`);
if (!EDITOR && !TEST) debug(`[PHYSICS]: using ${id}.`);
mutableSelector.physicsWorld = createPhysicsWorld();
}
if (worldInitData) {
@@ -185,7 +185,7 @@ export function constructDefaultWorld (data: IWorldInitData): void {
if (!worldInitData) worldInitData = data;
if (!selector.runInEditor) return;
if (!selector.physicsWorld) {
if (!TEST) log(`[PHYSICS]: using ${selector.id}.`);
if (!TEST) debug(`[PHYSICS]: using ${selector.id}.`);
const mutableSelector = selector as Mutable<IPhysicsSelector>;
const world = mutableSelector.physicsWorld = createPhysicsWorld();
world.setGravity(worldInitData.gravity);
+4
View File
@@ -60,6 +60,7 @@ interface IProfilerState {
frame: ICounterOption;
fps: ICounterOption;
draws: ICounterOption;
dispatches: ICounterOption;
instances: ICounterOption;
tricount: ICounterOption;
logic: ICounterOption;
@@ -73,6 +74,7 @@ interface IProfilerState {
const _profileInfo = {
fps: { desc: `Framerate (FPS)`, below: 30, average: _average, isInteger: true },
draws: { desc: 'Draw call', isInteger: true },
dispatches: { desc: 'Dispatch call', isInteger: true },
frame: { desc: 'Frame time (ms)', min: 0, max: 50, average: _average },
instances: { desc: 'Instance Count', isInteger: true },
tricount: { desc: 'Triangle', isInteger: true },
@@ -586,6 +588,8 @@ export class Profiler extends System {
const device = this._device!;
(profilerStats.draws.counter as PerfCounter).value = device.numDrawCalls;
// Native (JSB) devices expose no dispatch stats yet; WebGPU does. Treat missing as 0.
(profilerStats.dispatches.counter as PerfCounter).value = device.numDispatches ?? 0;
(profilerStats.instances.counter as PerfCounter).value = device.numInstances;
(profilerStats.bufferMemory.counter as PerfCounter).value = device.memoryStatus.bufferSize / (1024 * 1024);
(profilerStats.textureMemory.counter as PerfCounter).value = device.memoryStatus.textureSize / (1024 * 1024);
+23 -1
View File
@@ -31,7 +31,7 @@ import { murmurhash2_32_gc, errorID, assertID, cclegacy, warnID } from '../../co
import {
BufferUsageBit, DynamicStateFlagBit, DynamicStateFlags, Feature, GetTypeSize, MemoryUsageBit, PrimitiveMode, Type, Color,
BlendState, BlendTarget, Buffer, BufferInfo, BufferViewInfo, DepthStencilState, DescriptorSet,
DescriptorSetInfo, DescriptorSetLayout, Device, RasterizerState, Sampler, Texture, Shader, PipelineLayout, deviceManager, UniformBlock,
DescriptorSetInfo, DescriptorSetLayout, Device, RasterizerState, Sampler, SampleCount, Texture, Shader, PipelineLayout, deviceManager, UniformBlock,
} from '../../gfx';
import { EffectAsset } from '../../asset/assets/effect-asset';
import { IProgramInfo, programLib } from './program-lib';
@@ -139,6 +139,28 @@ export class Pass {
if (bsInfo.isA2C !== undefined) { bs.isA2C = bsInfo.isA2C; }
if (bsInfo.isIndepend !== undefined) { bs.isIndepend = bsInfo.isIndepend; }
if (bsInfo.blendColor !== undefined) { bs.blendColor = bsInfo.blendColor as Color; }
// A2C (Alpha to Coverage) requires MSAA to be effective.
// Without multiple subsamples, A2C behaves like alpha-test at ~0.5 and should be disabled.
// Disable A2C when neither the pass nor the global framebuffer has MSAA enabled:
// - passWantsMultisample: pass explicitly requests isMultisample
// - globalMsaaEnabled: swapchain has MSAA (native: colorTexture.samples > X1;
// WebGL: antialias from gl.getContextAttributes(), since WebGL
// MSAA is controlled at context level, not texture level)
if (bs.isA2C) {
const gfxDevice = deviceManager.gfxDevice as any;
const gl: WebGL2RenderingContext | WebGLRenderingContext | null = gfxDevice.gl || null;
const ctxAttrs = gl && gl.getContextAttributes();
const antialias: boolean = !!(ctxAttrs && ctxAttrs.antialias);
const passWantsMultisample = (info.rasterizerState && info.rasterizerState.isMultisample === true);
const swapchain = deviceManager.swapchain;
const colorTex = swapchain && swapchain.colorTexture;
const msaaDisabled = (!colorTex || (colorTex && colorTex.samples <= SampleCount.X1))
|| !antialias || !passWantsMultisample;
if (msaaDisabled) {
bs.isA2C = false;
}
}
}
pass._rs.assign(info.rasterizerState as RasterizerState);
pass._dss.assign(info.depthStencilState as DepthStencilState);
+11 -2
View File
@@ -21,12 +21,14 @@
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import { DEBUG } from 'internal:constants';
import { screenAdapter } from 'pal/screen-adapter';
import { Orientation } from '../../../pal/screen-adapter/enum-type';
import {
TextureType, TextureUsageBit, Format, RenderPass, Texture, Framebuffer,
RenderPassInfo, Device, TextureInfo, FramebufferInfo, Swapchain, SurfaceTransform, TextureFlagBit, TextureFlags,
} from '../../gfx';
import { warn } from '../../core/platform/debug';
import { Root } from '../../root';
import { Camera } from '../scene';
@@ -41,7 +43,10 @@ export interface IRenderWindowInfo {
externalFlag?: TextureFlags; // external texture type normal or oes
}
const orientationMap: Record<Orientation, SurfaceTransform> = {
// NOTE: `Orientation` is a flag enum whose composite members (LANDSCAPE, AUTO) are never
// actual runtime orientations, so this map intentionally only covers the physical ones.
// It is therefore typed as Partial rather than a total Record<Orientation, ...>.
const orientationMap: Partial<Record<Orientation, SurfaceTransform>> = {
[Orientation.PORTRAIT]: SurfaceTransform.IDENTITY,
[Orientation.LANDSCAPE_RIGHT]: SurfaceTransform.ROTATE_90,
[Orientation.PORTRAIT_UPSIDE_DOWN]: SurfaceTransform.ROTATE_180,
@@ -253,7 +258,11 @@ export class RenderWindow {
*/
public resize (width: number, height: number): void {
if (this._swapchain) {
this._swapchain.resize(width, height, orientationMap[screenAdapter.orientation]);
const surfaceTransform = orientationMap[screenAdapter.orientation];
if (DEBUG && surfaceTransform === undefined) {
warn(`Unexpected screen orientation: ${screenAdapter.orientation}`);
}
this._swapchain.resize(width, height, surfaceTransform || SurfaceTransform.IDENTITY);
this._width = this._swapchain.width;
this._height = this._swapchain.height;
} else {
+3
View File
@@ -91,6 +91,9 @@ export class PointLight extends Light {
* @en The luminance of the light source in LDR mode.
* @zh LDR 模式下光源的亮度。
*/
get luminanceLDR (): number {
return this._luminanceLDR;
}
set luminanceLDR (value: number) {
this._luminanceLDR = value;
}
+71 -39
View File
@@ -67,11 +67,13 @@ export class ReflectionProbe {
protected readonly _size = v3(1, 1, 1);
/**
* @en Render cubemap's camera
* @zh 渲染cubemap的相机
* @en Camera used for probe rendering (cubemap capture or planar reflection).
* @zh 用于探针渲染的相机(cubemap 采集或平面反射)
*/
private _camera: Camera | null = null;
private _previewCamera: Camera | null = null;
/**
* @en Unique id of probe.
* @zh probe的唯一id
@@ -184,6 +186,9 @@ export class ReflectionProbe {
set visibility (val) {
this._visibility = val;
this._camera!.visibility = this._visibility;
if (this._previewCamera) {
this._previewCamera.visibility = this._visibility;
}
}
/**
@@ -320,6 +325,21 @@ export class ReflectionProbe {
this._needRender = true;
}
/**
* @engineInternal
* @mangle
*/
public renderPreviewPlanarReflection (sourceCamera: Camera): Camera {
if (!this._previewCamera) {
this._createCamera(new Node(`${this.cameraNode.name} Preview Reflection`), true);
}
const previewCamera = this._previewCamera!;
this._syncCameraParams(sourceCamera, previewCamera);
this._transformReflectionCamera(sourceCamera, previewCamera);
this._needRender = true;
return previewCamera;
}
public switchProbeType (type: ProbeType, sourceCamera: Camera | null): void {
if (type === ProbeType.CUBE) {
this._needRender = false;
@@ -357,6 +377,12 @@ export class ReflectionProbe {
this._camera.destroy();
this._camera = null;
}
if (this._previewCamera) {
const cameraNode = this._previewCamera.node;
this._previewCamera.destroy();
this._previewCamera = null;
cameraNode.destroy();
}
for (let i = 0; i < this.bakedCubeTextures.length; i++) {
this.bakedCubeTextures[i].destroy();
}
@@ -410,48 +436,54 @@ export class ReflectionProbe {
return true;
}
private _syncCameraParams (camera: Camera): void {
this.camera.projectionType = camera.projectionType;
this.camera.orthoHeight = camera.orthoHeight;
this.camera.nearClip = camera.nearClip;
this.camera.farClip = camera.farClip;
this.camera.fov = camera.fov;
this.camera.clearFlag = camera.clearFlag;
this.camera.clearColor = camera.clearColor;
this.camera.priority = camera.priority - 1;
this.camera.resize(camera.width, camera.height);
private _syncCameraParams (camera: Camera, targetCamera: Camera = this.camera): void {
targetCamera.projectionType = camera.projectionType;
targetCamera.orthoHeight = camera.orthoHeight;
targetCamera.nearClip = camera.nearClip;
targetCamera.farClip = camera.farClip;
targetCamera.fov = camera.fov;
targetCamera.clearFlag = camera.clearFlag;
targetCamera.clearColor = camera.clearColor;
targetCamera.priority = camera.priority - 1;
targetCamera.resize(camera.width, camera.height);
}
private _createCamera (cameraNode: Node): Camera | null {
private _createCamera (cameraNode: Node, preview = false): Camera | null {
const root = cclegacy.director.root;
if (!this._camera) {
this._camera = root.createCamera();
if (!this._camera) return null;
this._camera.initialize({
let camera = preview ? this._previewCamera : this._camera;
if (!camera) {
camera = root.createCamera();
if (!camera) return null;
camera.initialize({
name: cameraNode.name,
node: cameraNode,
projection: CameraProjection.PERSPECTIVE,
window: EDITOR ? root && root.mainWindow : root && root.tempWindow,
window: preview || EDITOR ? root.mainWindow : root.tempWindow,
priority: 0,
cameraType: CameraType.DEFAULT,
trackingType: TrackingType.NO_TRACKING,
});
if (preview) {
this._previewCamera = camera;
} else {
this._camera = camera;
}
}
this._camera.setViewportInOrientedSpace(new Rect(0, 0, 1, 1));
this._camera.fovAxis = CameraFOVAxis.VERTICAL;
this._camera.fov = toRadian(90);
this._camera.orthoHeight = 10;
this._camera.nearClip = 1;
this._camera.farClip = 1000;
this._camera.clearColor = this._backgroundColor;
this._camera.clearDepth = 1.0;
this._camera.clearStencil = 0.0;
this._camera.clearFlag = this._clearFlag;
this._camera.visibility = this._visibility;
this._camera.aperture = CameraAperture.F16_0;
this._camera.shutter = CameraShutter.D125;
this._camera.iso = CameraISO.ISO100;
return this._camera;
camera.setViewportInOrientedSpace(new Rect(0, 0, 1, 1));
camera.fovAxis = CameraFOVAxis.VERTICAL;
camera.fov = toRadian(90);
camera.orthoHeight = 10;
camera.nearClip = 1;
camera.farClip = 1000;
camera.clearColor = this._backgroundColor;
camera.clearDepth = 1.0;
camera.clearStencil = 0.0;
camera.clearFlag = this._clearFlag;
camera.visibility = this._visibility;
camera.aperture = CameraAperture.F16_0;
camera.shutter = CameraShutter.D125;
camera.iso = CameraISO.ISO100;
return camera;
}
private _resetCameraParams (): void {
@@ -478,10 +510,10 @@ export class ReflectionProbe {
return rt;
}
private _transformReflectionCamera (sourceCamera: Camera): void {
private _transformReflectionCamera (sourceCamera: Camera, targetCamera: Camera = this.camera): void {
const offset = Vec3.dot(this.node.worldPosition, this.node.up);
this._reflect(this._cameraWorldPos, sourceCamera.node.worldPosition, this.node.up, offset);
this.cameraNode.worldPosition = this._cameraWorldPos;
targetCamera.node.worldPosition = this._cameraWorldPos;
Vec3.transformQuat(this._forward, Vec3.FORWARD, sourceCamera.node.worldRotation);
this._reflect(this._forward, this._forward, this.node.up, 0);
@@ -494,14 +526,14 @@ export class ReflectionProbe {
Quat.fromViewUp(this._cameraWorldRotation, this._forward, this._up);
this.cameraNode.worldRotation = this._cameraWorldRotation;
targetCamera.node.worldRotation = this._cameraWorldRotation;
this.camera.update(true);
targetCamera.update(true);
// Transform the plane from world space to reflection camera space use the inverse transpose matrix
const viewSpaceProbe = new Vec4(this.node.up.x, this.node.up.y, this.node.up.z, -Vec3.dot(this.node.up, this.node.worldPosition));
viewSpaceProbe.transformMat4(this.camera.matView.clone().invert().transpose());
this.camera.calculateObliqueMat(viewSpaceProbe);
viewSpaceProbe.transformMat4(targetCamera.matView.clone().invert().transpose());
targetCamera.calculateObliqueMat(viewSpaceProbe);
}
private _reflect (out: Vec3, point: Vec3, normal: Vec3, offset: number): Vec3 {
+3
View File
@@ -102,6 +102,9 @@ export class SphereLight extends Light {
* @en The luminance of the light source in LDR mode
* @zh LDR 模式下光源的亮度
*/
get luminanceLDR (): number {
return this._luminanceLDR;
}
set luminanceLDR (value: number) {
this._luminanceLDR = value;
}
+14 -2
View File
@@ -22,7 +22,6 @@
THE SOFTWARE.
****************************************************************************/
import { Buffer, Framebuffer, Texture, Viewport } from '../../gfx';
import { genHashValue } from './define';
import { VectorGraphColorMap } from './effect';
import { DefaultVisitor, depthFirstSearch, ReferenceGraphView } from './graph';
import { LayoutGraphData } from './layout-graph';
@@ -199,7 +198,6 @@ class PassVisitor implements RenderGraphVisitor {
resourceGraph.visitVertex(this._resVisitor, vertID);
}
}
genHashValue(pass);
}
}
applyID (id: number, resId: number): void {
@@ -233,7 +231,21 @@ class PassVisitor implements RenderGraphVisitor {
compute (value: ComputePass): void {
this._currPass = value;
const rg = context.renderGraph;
if (rg.getValid(this.passID)) {
// Avoid revisiting a valid pass and recursive dependency cycles.
return;
}
rg.setValid(this.passID, true);
// Trace READ dependencies only; WRITE dependencies are produced by this pass.
const resourceGraph = this.context.resourceGraph;
for (const [computeName, cViews] of value.computeViews) {
if (!cViews.length || cViews[0].accessType !== AccessType.READ) continue;
const vertID = resourceGraph.find(computeName);
if (vertID !== 0xFFFFFFFF) {
this._resVisitor.resID = vertID;
resourceGraph.visitVertex(this._resVisitor, vertID);
}
}
}
resolve (value: ResolvePass): void {
// noop
+18 -13
View File
@@ -48,6 +48,7 @@ import {
Device,
deviceManager,
DispatchInfo,
Feature,
Format,
Framebuffer,
FramebufferInfo,
@@ -56,9 +57,7 @@ import {
InputAssemblerInfo,
LoadOp,
MemoryUsageBit,
PipelineBindPoint,
PipelineState,
PipelineStateInfo,
Rect,
RenderPass,
RenderPassInfo,
@@ -615,10 +614,17 @@ class DeviceRenderQueue implements RecordingInterface {
this._devicePass = devicePass;
this._phaseID = cclegacy.rendering.getPhaseID(devicePass.passID, context.renderGraph.getLayout(id));
}
/**
* @en Creates a blit descriptor for the given blit operation.
* @zh 为给定的 blit 操作创建一个 blit 描述符。
* @param blit @en The blit operation to create a descriptor for. @zh 要为其创建描述符的 blit 操作。
*/
createBlitDesc (blit: Blit): void {
if (!this._blitDesc) {
this._blitDesc = new BlitDesc(blit);
}
this._blitDesc.blit = blit;
this._blitDesc.createScreenQuad();
this._blitDesc.createStageDescriptor();
}
@@ -1903,26 +1909,23 @@ class PreRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor {
renderScene.preRecord();
}
dispatch (value: Dispatch): void {
if (!context.device.hasFeature(Feature.COMPUTE_SHADER)) return;
let pso: PipelineState | null = null;
const devicePass = this.currPass as DeviceComputePass;
const pass = value.material?.passes[value.passID];
pass?.update();
const shader = pass?.getShaderVariant();
if (pass !== null && shader !== null) {
const psoInfo = new PipelineStateInfo(
shader,
pass?.pipelineLayout,
);
psoInfo.bindPoint = PipelineBindPoint.COMPUTE;
pso = deviceManager.gfxDevice.createPipelineState(psoInfo);
if (pass && shader) {
pso = PipelineStateManager.getOrCreateComputePipelineState(deviceManager.gfxDevice, pass, shader);
}
const cmdBuff = context.commandBuffer;
if (pso) {
if (pso && pass) {
cmdBuff.bindPipelineState(pso);
const layoutStage = devicePass.renderLayout;
const layoutDesc = layoutStage!.descriptorSet!;
cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, layoutDesc);
cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
}
const gx = value.threadGroupCountX;
@@ -1958,10 +1961,12 @@ class PostRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor
computeSubpass (value: ComputeSubpass): void {
// do nothing
}
resolve (value: ResolvePass): void {
// do nothing
}
compute (value: ComputePass): void {
if (!context.device.hasFeature(Feature.COMPUTE_SHADER)) return;
const cmdBuff = context.commandBuffer;
(cmdBuff as any).submitComputePass();
}
resolve (value: ResolvePass): void {
// do nothing
}
copy (value: CopyPass): void {
+32 -3
View File
@@ -195,10 +195,13 @@ function sceneCulling (
}
models.push(model);
} else if (probe.probeType === ProbeType.CUBE) {
if (!wBounds || !model.bakeToReflectionProbe) {
continue;
}
if (!isVisible(model, visibility)) {
continue;
}
if (wBounds && isIntersectAABB(wBounds, probe.boundingBox!)) {
if (isIntersectAABB(wBounds, probe.boundingBox!)) {
continue;
}
models.push(model);
@@ -475,7 +478,8 @@ export class SceneCulling {
);
// Get or create render queue
const renderQueueID = this.getOrCreateRenderQueue(renderQueueKey, sceneData.flags, sceneData.camera);
const renderCamera = sceneData.light.probe ? sceneData.light.probe.camera : sceneData.camera;
const renderQueueID = this.getOrCreateRenderQueue(renderQueueKey, sceneData.flags, renderCamera);
// add render queue query
const renderQueueQuery = this.cullingPools.renderQueueQueryRecycle.add();
@@ -556,7 +560,11 @@ export class SceneCulling {
private executeSphereLightCulling (light: SphereLight, frustumCullingResult: Array<Model>, lightBoundsCullingResult: Array<Model>): void {
const lightAABB = light.aabb;
const visibility = light.visibility;
for (const model of frustumCullingResult) {
if (!isVisible(model, visibility)) {
continue;
}
const modelBounds = model.worldBounds;
if (!modelBounds || intersect.aabbWithAABB(modelBounds, lightAABB)) {
lightBoundsCullingResult.push(model);
@@ -567,7 +575,11 @@ export class SceneCulling {
private executeSpotLightCulling (light: SpotLight, frustumCullingResult: Array<Model>, lightBoundsCullingResult: Array<Model>): void {
const lightAABB = light.aabb;
const lightFrustum: Frustum = light.frustum;
const visibility = light.visibility;
for (const model of frustumCullingResult) {
if (!isVisible(model, visibility)) {
continue;
}
const modelBounds = model.worldBounds;
if (!modelBounds || (intersect.aabbWithAABB(lightAABB, modelBounds) && intersect.aabbFrustum(modelBounds, lightFrustum))) {
lightBoundsCullingResult.push(model);
@@ -577,7 +589,11 @@ export class SceneCulling {
private executePointLightCulling (light: PointLight, frustumCullingResult: Array<Model>, lightBoundsCullingResult: Array<Model>): void {
const lightAABB = light.aabb;
const visibility = light.visibility;
for (const model of frustumCullingResult) {
if (!isVisible(model, visibility)) {
continue;
}
const modelBounds = model.worldBounds;
if (!modelBounds || intersect.aabbWithAABB(lightAABB, modelBounds)) {
lightBoundsCullingResult.push(model);
@@ -590,8 +606,12 @@ export class SceneCulling {
frustumCullingResult: Array<Model>,
lightBoundsCullingResult: Array<Model>,
): void {
const visibility = light.visibility;
rangedDirLightBoundingBox.transform(light.node!.worldMatrix, null, null, null, lightAABB);
for (const model of frustumCullingResult) {
if (!isVisible(model, visibility)) {
continue;
}
const modelBounds = model.worldBounds;
if (!modelBounds || intersect.aabbWithAABB(lightAABB, modelBounds)) {
lightBoundsCullingResult.push(model);
@@ -817,11 +837,20 @@ export class LightResource {
this.lightIndex.clear();
}
/**
* @en Adds a light to the light buffer and returns its byte offset.
* @zh 将光源添加到光源缓冲区,并返回其字节偏移量。
* @param light @en The light to add. @zh 要添加的光源。
* @param bHDR @en Whether HDR rendering is enabled. @zh 是否启用 HDR 渲染。
* @param exposure @en The camera exposure value. @zh 相机曝光值。
* @param shadowInfo @en The shadow settings, or null if shadows are disabled. @zh 阴影设置,若禁用阴影则为 null。
* @returns @en The byte offset of the light in the light buffer. @zh 光源在光源缓冲区中的字节偏移量。
*/
addLight (light: Light, bHDR: boolean, exposure: number, shadowInfo: Shadows | null): number {
// Already added
const existingLightID = this.lightIndex.get(light);
if (existingLightID !== undefined) {
return existingLightID;
return existingLightID * this.elementSize;
}
if (!this.lightBuffer) {
+28 -8
View File
@@ -258,9 +258,19 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild
addSceneOfCamera (camera: Camera, light: LightInfo, sceneFlags = SceneFlags.NONE, name = 'Camera'): void {
const lightTarget = light.light;
this.addScene(camera, sceneFlags, lightTarget);
const scene = light.probe?.node?.scene?.renderScene || undefined;
this._addScene(camera, sceneFlags, lightTarget, scene, light);
}
addScene (camera: Camera, sceneFlags = SceneFlags.NONE, light: Light | undefined | null = null, scene: RenderScene | undefined = undefined): SceneBuilder {
return this._addScene(camera, sceneFlags, light, scene);
}
private _addScene (
camera: Camera,
sceneFlags: SceneFlags,
light: Light | undefined | null,
scene: RenderScene | undefined,
lightInfo: LightInfo | null = null,
): SceneBuilder {
const sceneData = renderGraphPool.createSceneData(
scene || camera.scene,
camera,
@@ -268,6 +278,9 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild
light && !(sceneFlags & SceneFlags.SHADOW_CASTER) ? CullingFlags.CAMERA_FRUSTUM | CullingFlags.LIGHT_BOUNDS : CullingFlags.CAMERA_FRUSTUM,
light,
);
if (lightInfo) {
sceneData.light.reset(lightInfo.light, lightInfo.level, lightInfo.culledByLight, lightInfo.probe);
}
const renderData = renderGraphPool.createRenderData();
const sceneId = this._renderGraph.addVertex<RenderGraphValue.Scene>(RenderGraphValue.Scene, sceneData, 'Scene', '', renderData, !DEBUG, this._vertID);
if (!(sceneFlags & SceneFlags.NON_BUILTIN)) {
@@ -851,7 +864,11 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild
this._renderGraph.setName(this._vertID, name);
}
addTexture (name: string, slotName: string, sampler: Sampler | null = null): void {
throw new Error('Method not implemented.');
this._addComputeResource(name, AccessType.READ, slotName);
if (sampler) {
const descriptorID = this._lg.attributeIndex.get(slotName)!;
this._data.samplers.set(descriptorID, sampler);
}
}
addStorageBuffer (name: string, accessType: AccessType, slotName: string): void {
this._addComputeResource(name, accessType, slotName);
@@ -1650,13 +1667,16 @@ export class WebPipeline extends WebSetter implements BasicPipeline {
this._compiler = new Compiler(this, this._renderGraph, this._resourceGraph, this._lg);
}
this._compiler.compile(this._renderGraph);
} else {
this._renderGraph.x.forEach((vert) => {
if (vert.t === RenderGraphValue.RasterPass) {
genHashValue(vert.j as RasterPass);
}
});
}
this._renderGraph.x.forEach((vert, v) => {
if (vert.t !== RenderGraphValue.RasterPass) {
return;
}
if (DEBUG && !this._renderGraph!.getValid(v)) {
return;
}
genHashValue(vert.j as RasterPass);
});
}
execute (): void {
@@ -1264,15 +1264,6 @@ export class WebProgramLibrary implements ProgramLibrary {
if (passSet) {
info.setLayouts.push(passSet);
}
const phaseSet = getDescriptorSetLayout(
this.layoutGraph,
subpassOrPassID,
phaseID,
UpdateFrequency.PER_PHASE,
);
if (phaseSet) {
info.setLayouts.push(phaseSet);
}
const batchSet = getProgramDescriptorSetLayout(
device,
lg,
@@ -1293,6 +1284,15 @@ export class WebProgramLibrary implements ProgramLibrary {
if (instanceSet) {
info.setLayouts.push(instanceSet);
}
const phaseSet = getDescriptorSetLayout(
this.layoutGraph,
subpassOrPassID,
phaseID,
UpdateFrequency.PER_PHASE,
);
if (phaseSet) {
info.setLayouts.push(phaseSet);
}
programData.pipelineLayout = device.createPipelineLayout(info);
return programData.pipelineLayout;
}
+88 -48
View File
@@ -28,8 +28,9 @@ import { UNIFORM_LIGHTMAP_TEXTURE_BINDING, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMA
UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, ENABLE_PROBE_BLEND,
IRenderPass,
getPassPool } from './define';
import { BufferUsageBit, MemoryUsageBit, Device, Texture, InputAssembler, InputAssemblerInfo,
import { BufferUsageBit, MemoryUsageBit, Device, InputAssembler, InputAssemblerInfo,
Attribute, Buffer, BufferInfo, CommandBuffer, Shader, DescriptorSet } from '../gfx';
import type { Texture } from '../gfx';
import { RecyclePool } from '../core/memop';
export function instancingCompareFn (l: InstancedBuffer, r: InstancedBuffer): number {
@@ -65,6 +66,7 @@ export class InstancedBuffer {
public sortRender: IRenderPass;
private declare _passPool: RecyclePool<IRenderPass>;
private declare _device: Device;
private readonly _instanceMap = new Map<string, IInstancedItem[]>();
constructor (pass: Pass) {
this._device = pass.device;
this.pass = pass;
@@ -81,6 +83,7 @@ export class InstancedBuffer {
});
this._passPool.reset();
this.instances.length = 0;
this._instanceMap.clear();
}
public merge (subModel: SubModel, passIdx: number, shaderImplant: Shader | null = null): void {
@@ -106,72 +109,109 @@ export class InstancedBuffer {
this.sortRender.hash = hash;
this.sortRender.shaderId = shader.typedID;
this.sortRender.passIdx = passIdx;
for (let i = 0; i < this.instances.length; ++i) {
const instance = this.instances[i];
if (instance.ia.indexBuffer?.objectID !== sourceIA.indexBuffer?.objectID || instance.count >= MAX_CAPACITY) { continue; }
// check same binding
if (instance.lightingMap.objectID !== lightingMap.objectID) {
continue;
const key = `${sourceIA.indexBuffer?.objectID ?? 0}/${lightingMap.objectID}/${useReflectionProbeType}/`
+ `${reflectionProbeCubemap.objectID}/${reflectionProbePlanarMap.objectID}/`
+ `${ENABLE_PROBE_BLEND ? reflectionProbeBlendCubemap!.objectID : 0}/${stride}`;
const mappedInstances = this._instanceMap.get(key);
if (mappedInstances) {
for (let i = 0; i < mappedInstances.length; ++i) {
const instance = mappedInstances[i];
if (instance.count >= MAX_CAPACITY) { continue; }
this._appendInstance(instance, attrs.buffer, shader, descriptorSet);
return;
}
if (instance.useReflectionProbeType !== useReflectionProbeType) {
continue;
}
if (instance.reflectionProbeCubemap.objectID !== reflectionProbeCubemap.objectID) {
continue;
}
if (instance.reflectionProbePlanarMap.objectID !== reflectionProbePlanarMap.objectID) {
continue;
}
if (ENABLE_PROBE_BLEND && instance.reflectionProbeBlendCubemap!.objectID !== reflectionProbeBlendCubemap!.objectID) {
continue;
}
if (instance.stride !== stride) {
// we allow this considering both baked and non-baked
// skinning models may be present in the same buffer
continue;
}
if (instance.count >= instance.capacity) { // resize buffers
instance.capacity <<= 1;
const newSize = instance.stride * instance.capacity;
const oldData = instance.data;
instance.data = new Uint8Array(newSize);
instance.data.set(oldData);
instance.vb.resize(newSize);
}
instance.shader = shader;
instance.descriptorSet = descriptorSet;
instance.data.set(attrs.buffer, instance.stride * instance.count++);
this.hasPendingModels = true;
return;
}
// Create a new instance
this._createInstance(
key,
sourceIA,
attrs.attributes,
attrs.buffer,
stride,
shader,
descriptorSet,
lightingMap,
useReflectionProbeType,
reflectionProbeCubemap,
reflectionProbePlanarMap,
reflectionProbeBlendCubemap,
);
}
private _appendInstance (instance: IInstancedItem, data: Uint8Array, shader: Shader, descriptorSet: DescriptorSet): void {
if (instance.count >= instance.capacity) { // resize buffers
instance.capacity = Math.min(instance.capacity << 1, MAX_CAPACITY);
const newSize = instance.stride * instance.capacity;
const oldData = instance.data;
instance.data = new Uint8Array(newSize);
instance.data.set(oldData);
instance.vb.resize(newSize);
}
instance.shader = shader;
instance.descriptorSet = descriptorSet;
instance.data.set(data, instance.stride * instance.count++);
this.hasPendingModels = true;
}
private _createInstance (
key: string,
sourceIA: InputAssembler,
instancedAttributes: Attribute[],
instanceData: Uint8Array,
stride: number,
shader: Shader,
descriptorSet: DescriptorSet,
lightingMap: Texture,
useReflectionProbeType: number,
reflectionProbeCubemap: Texture,
reflectionProbePlanarMap: Texture,
reflectionProbeBlendCubemap: Texture | null,
): void {
const newSize = stride * INITIAL_CAPACITY;
const vb = this._device.createBuffer(new BufferInfo(
BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST,
MemoryUsageBit.HOST | MemoryUsageBit.DEVICE,
stride * INITIAL_CAPACITY,
newSize,
stride,
));
const data = new Uint8Array(stride * INITIAL_CAPACITY);
const data = new Uint8Array(newSize);
const vertexBuffers = sourceIA.vertexBuffers.slice();
const attributes = sourceIA.attributes.slice();
const indexBuffer = sourceIA.indexBuffer;
for (let i = 0; i < attrs.attributes.length; i++) {
const attr = attrs.attributes[i];
for (let i = 0; i < instancedAttributes.length; i++) {
const attr = instancedAttributes[i];
const newAttr = new Attribute(attr.name, attr.format, attr.isNormalized, vertexBuffers.length, true);
attributes.push(newAttr);
}
data.set(attrs.buffer);
data.set(instanceData);
vertexBuffers.push(vb);
const iaInfo = new InputAssemblerInfo(attributes, vertexBuffers, indexBuffer);
const ia = this._device.createInputAssembler(iaInfo);
// eslint-disable-next-line max-len
this.instances.push({ count: 1, capacity: INITIAL_CAPACITY, vb, data, ia, stride, shader, descriptorSet, lightingMap, reflectionProbeCubemap, reflectionProbePlanarMap, useReflectionProbeType, reflectionProbeBlendCubemap });
const instance = {
count: 1,
capacity: INITIAL_CAPACITY,
vb,
data,
ia,
stride,
shader,
descriptorSet,
lightingMap,
reflectionProbeCubemap,
reflectionProbePlanarMap,
useReflectionProbeType,
reflectionProbeBlendCubemap,
} as IInstancedItem;
this.instances.push(instance);
let mappedInstances = this._instanceMap.get(key);
if (!mappedInstances) {
mappedInstances = [];
this._instanceMap.set(key, mappedInstances);
}
mappedInstances.push(instance);
this.hasPendingModels = true;
}
@@ -180,7 +220,7 @@ export class InstancedBuffer {
const instance = this.instances[i];
if (!instance.count) { continue; }
instance.ia.instanceCount = instance.count;
cmdBuff.updateBuffer(instance.vb, instance.data);
cmdBuff.updateBuffer(instance.vb, instance.data.buffer as ArrayBuffer, instance.count * instance.stride);
}
}
+32 -1
View File
@@ -22,7 +22,7 @@
THE SOFTWARE.
*/
import { Shader, RenderPass, InputAssembler, Device, PipelineState, InputState, PipelineStateInfo } from '../gfx';
import { Shader, RenderPass, InputAssembler, Device, PipelineState, InputState, PipelineStateInfo, PipelineBindPoint } from '../gfx';
import { Pass } from '../render-scene/core/pass';
export class PipelineStateManager {
@@ -30,6 +30,8 @@ export class PipelineStateManager {
private static _PSOHashMap: Map<number, PipelineState> = new Map<number, PipelineState>();
private static _computePSOHashMap: Map<number, PipelineState> = new Map<number, PipelineState>();
// pass is only needed on TS.
static getOrCreatePipelineState (device: Device, pass: Pass, shader: Shader, renderPass: RenderPass, ia: InputAssembler): PipelineState {
const hash1 = pass.hash;
@@ -59,4 +61,33 @@ export class PipelineStateManager {
return pso;
}
/**
* @en Get or create a compute pipeline state.
* A compute pipeline only depends on the shader variant and the pipeline layout,
* both carried by the pass, so the cache key is `pass.hash ^ shader.typedID`,
* mirroring the graphics-side hash mechanism without renderPass/inputState factors.
* @zh 获取或创建计算管线状态。
* 计算管线仅依赖于着色器变体与管线布局(均由 pass 携带),
* 因此缓存键为 `pass.hash ^ shader.typedID`,与图形侧哈希机制一致但不包含 renderPass/顶点布局因子。
*/
static getOrCreateComputePipelineState (device: Device, pass: Pass, shader: Shader): PipelineState {
const hash1 = pass.hash;
const hash2 = shader.typedID;
const newHash = hash1 ^ hash2;
let pso = this._computePSOHashMap.get(newHash);
if (!pso) {
const pipelineLayout = pass.pipelineLayout;
const psoInfo = new PipelineStateInfo(
shader,
pipelineLayout,
);
psoInfo.bindPoint = PipelineBindPoint.COMPUTE;
pso = device.createPipelineState(psoInfo);
this._computePSOHashMap.set(newHash, pso);
}
return pso;
}
}
+2 -5
View File
@@ -29,7 +29,6 @@ import { PipelineStateManager } from './pipeline-state-manager';
import { Model, Camera, SubModel } from '../render-scene/scene';
import { RenderInstancedQueue } from './render-instanced-queue';
import { ShadowType } from '../render-scene/scene/shadows';
import { Layers } from '../scene-graph/layers';
import { PipelineRuntime } from './custom/pipeline';
import { BatchingSchemes, Pass } from '../render-scene/core/pass';
import { getPhaseID } from './pass-phase';
@@ -83,18 +82,16 @@ export class PlanarShadowQueue {
const scene = camera.scene!;
const frustum = camera.frustum;
const shadowVisible = (camera.visibility & Layers.BitMask.DEFAULT) !== 0;
const shadowVisible = camera.visibility !== 0;
if (!scene.mainLight || !shadowVisible) { return; }
const models = scene.models;
const visibility = camera.visibility;
for (let i = 0; i < models.length; i++) {
const model = models[i];
if (scene.isCulledByLod(camera, model)) {
continue;
}
if (model.enabled && model.node && model.castShadow
&& (model.node && ((visibility & model.node.layer) === model.node.layer))) {
if (model.enabled && model.node && model.castShadow) {
this._castModels.push(model);
}
}
@@ -27,7 +27,7 @@ import { IRenderFlowInfo, RenderFlow } from '../render-flow';
import { ReflectionProbeStage } from './reflection-probe-stage';
import { RenderFlowTag } from '../pipeline-serialization';
import { RenderPipeline } from '../render-pipeline';
import { Camera } from '../../render-scene/scene/camera';
import { Camera, CameraUsage } from '../../render-scene/scene/camera';
import { ProbeType, ReflectionProbe } from '../../render-scene/scene/reflection-probe';
import { cclegacy } from '../../core';
@@ -65,7 +65,13 @@ export class ReflectionProbeFlow extends RenderFlow {
const probes = cclegacy.internal.reflectionProbeManager.getProbes() as ReflectionProbe[];
for (let i = 0; i < probes.length; i++) {
if (probes[i].needRender) {
if (EDITOR || probes[i].probeType === ProbeType.PLANAR) {
if (probes[i].probeType === ProbeType.PLANAR) {
let reflectionCamera: Camera | undefined;
if (EDITOR && camera.cameraUsage === CameraUsage.PREVIEW) {
reflectionCamera = probes[i].renderPreviewPlanarReflection(camera);
}
this._renderStage(camera, probes[i], reflectionCamera);
} else if (EDITOR) {
this._renderStage(camera, probes[i]);
}
}
@@ -75,12 +81,12 @@ export class ReflectionProbeFlow extends RenderFlow {
public destroy (): void {
super.destroy();
}
private _renderStage (camera: Camera, probe: ReflectionProbe): void {
private _renderStage (camera: Camera, probe: ReflectionProbe, reflectionCamera?: Camera): void {
for (let i = 0; i < this._stages.length; i++) {
const probeStage = this._stages[i] as ReflectionProbeStage;
if (probe.probeType === ProbeType.PLANAR) {
cclegacy.internal.reflectionProbeManager.updatePlanarMap(probe, null);
probeStage.setUsageInfo(probe, probe.realtimePlanarTexture!.window!.framebuffer);
probeStage.setUsageInfo(probe, probe.realtimePlanarTexture!.window!.framebuffer, reflectionCamera);
probeStage.render(camera);
cclegacy.internal.reflectionProbeManager.updatePlanarMap(probe, probe.realtimePlanarTexture!.getGFXTexture());
} else {
@@ -55,6 +55,7 @@ export class ReflectionProbeStage extends RenderStage {
private _frameBuffer: Framebuffer | null = null;
private _renderArea = new Rect();
private _probe: ReflectionProbe | null = null;
private _reflectionCamera: Camera | null = null;
private _probeRenderQueue!: RenderReflectionProbeQueue;
private _rgbeColor = new Vec3();
@@ -68,9 +69,10 @@ export class ReflectionProbeStage extends RenderStage {
* @param probe
* @param frameBuffer
*/
public setUsageInfo (probe: ReflectionProbe, frameBuffer: Framebuffer): void {
public setUsageInfo (probe: ReflectionProbe, frameBuffer: Framebuffer, reflectionCamera?: Camera): void {
this._probe = probe;
this._frameBuffer = frameBuffer;
this._reflectionCamera = reflectionCamera ?? null;
}
public destroy (): void {
@@ -108,8 +110,9 @@ export class ReflectionProbeStage extends RenderStage {
public render (camera: Camera): void {
const pipeline = this._pipeline;
const cmdBuff = pipeline.commandBuffers[0];
this._probeRenderQueue.gatherRenderObjects(this._probe!, camera, cmdBuff);
pipeline.pipelineUBO.updateCameraUBO(this._probe!.camera);
const probeCamera = this._reflectionCamera ?? this._probe!.camera;
this._probeRenderQueue.gatherRenderObjects(this._probe!, camera, cmdBuff, probeCamera);
pipeline.pipelineUBO.updateCameraUBO(probeCamera);
this._renderArea.x = 0;
this._renderArea.y = 0;
@@ -118,10 +121,10 @@ export class ReflectionProbeStage extends RenderStage {
const renderPass = this._frameBuffer!.renderPass;
if (this._probe!.camera.clearFlag & ClearFlagBit.COLOR) {
this._rgbeColor.x = this._probe!.camera.clearColor.x;
this._rgbeColor.y = this._probe!.camera.clearColor.y;
this._rgbeColor.z = this._probe!.camera.clearColor.z;
if (probeCamera.clearFlag & ClearFlagBit.COLOR) {
this._rgbeColor.x = probeCamera.clearColor.x;
this._rgbeColor.y = probeCamera.clearColor.y;
this._rgbeColor.z = probeCamera.clearColor.z;
const rgbe = packRGBE(this._rgbeColor);
colors[0].x = rgbe.x;
colors[0].y = rgbe.y;
@@ -134,8 +137,8 @@ export class ReflectionProbeStage extends RenderStage {
this._frameBuffer!,
this._renderArea,
colors,
this._probe!.camera.clearDepth,
this._probe!.camera.clearStencil,
probeCamera.clearDepth,
probeCamera.clearStencil,
);
cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
+31 -27
View File
@@ -126,7 +126,7 @@ export class RenderAdditiveLightQueue {
private declare _lightBuffer: Buffer;
private declare _firstLightBufferView: Buffer;
private declare _lightBufferData: Float32Array;
private _instancedQueues: RenderInstancedQueue[] = [];
private _instancedQueues: (RenderInstancedQueue | undefined)[] = [];
private _lightMeterScale = 10000.0;
constructor (pipeline: PipelineRuntime) {
@@ -151,7 +151,9 @@ export class RenderAdditiveLightQueue {
public clear (): void {
this._instancedQueues.forEach((instancedQueue) => {
instancedQueue.clear();
if (instancedQueue) {
instancedQueue.clear();
}
});
this._instancedQueues.length = 0;
@@ -196,7 +198,7 @@ export class RenderAdditiveLightQueue {
this._lightCulling(model, validPunctualLights);
if (!_lightIndices.length && validPunctualLights.length > 0) { continue; }
if (!_lightIndices.length) { continue; }
for (let j = 0; j < subModels.length; j++) {
const lightPassIdx = _lightPassIndices[j];
@@ -219,15 +221,14 @@ export class RenderAdditiveLightQueue {
public gatherLightPasses (camera: Camera, cmdBuff: CommandBuffer, passLayout = 'default'): void {
this.clear();
const validPunctualLights = this._pipeline.pipelineSceneData.validPunctualLights;
if (!validPunctualLights.length) {
this._bindForwardAddLight(validPunctualLights, passLayout);
return;
}
this._updateUBOs(camera, cmdBuff);
this._updateLightDescriptorSet(camera, cmdBuff);
const validPunctualLights = this._pipeline.pipelineSceneData.validPunctualLights;
if (!validPunctualLights.length) { return; }
this._bindForwardAddLight(validPunctualLights, passLayout);
// only for instanced and batched, no light culling applied
for (let l = 0; l < validPunctualLights.length; l++) {
const light = validPunctualLights[l];
@@ -236,17 +237,21 @@ export class RenderAdditiveLightQueue {
}
this._instancedQueues.forEach((instancedQueue) => {
instancedQueue.uploadBuffers(cmdBuff);
if (instancedQueue) {
instancedQueue.uploadBuffers(cmdBuff);
}
});
}
public recordCommandBuffer (device: Device, renderPass: RenderPass, cmdBuff: CommandBuffer): void {
const globalDSManager: GlobalDSManager = this._pipeline.globalDSManager;
for (let j = 0; j < this._instancedQueues.length; ++j) {
const queue = this._instancedQueues[j];
if (!queue) { continue; }
const light = this._instancedLightPassPool.lights[j];
_dynamicOffsets[0] = this._instancedLightPassPool.dynamicOffsets[j];
const descriptorSet = globalDSManager.getOrCreateDescriptorSet(light);
this._instancedQueues[j].recordCommandBuffer(device, renderPass, cmdBuff, descriptorSet, _dynamicOffsets);
queue.recordCommandBuffer(device, renderPass, cmdBuff, descriptorSet, _dynamicOffsets);
}
for (let i = 0; i < this._lightPasses.length; i++) {
@@ -315,14 +320,18 @@ export class RenderAdditiveLightQueue {
const lightIdx = _lightIndices[l];
const light = validPunctualLights[lightIdx];
const visibility = light.visibility;
if (((visibility & model.node.layer) === model.node.layer)) {
if (((visibility & model.node.layer) === model.node.layer)
|| (visibility & model.visFlags)) {
switch (batchingScheme) {
case BatchingSchemes.INSTANCING: {
const buffer = pass.getInstancedBuffer(l);
const buffer = pass.getInstancedBuffer(lightIdx);
buffer.merge(subModel, lightPassIdx);
buffer.dynamicOffsets[0] = this._lightBufferStride;
if (!this._instancedQueues[l]) { this._instancedQueues[l] = new RenderInstancedQueue(); }
this._instancedQueues[l].queue.add(buffer);
buffer.dynamicOffsets[0] = this._lightBufferStride * lightIdx;
if (this._instancedQueues.length <= lightIdx || !this._instancedQueues[lightIdx]) {
this._instancedQueues.length = lightIdx + 1;
this._instancedQueues[lightIdx] = new RenderInstancedQueue();
}
this._instancedQueues[lightIdx]!.queue.add(buffer);
} break;
default:
lp!.lights.push(light);
@@ -370,9 +379,6 @@ export class RenderAdditiveLightQueue {
this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing;
this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = 0.0;
this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0;
// Reserve sphere light shadow interface
Color.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadowEnum.SHADOW_COLOR_OFFSET);
break;
}
case LightType.SPOT: {
@@ -437,8 +443,6 @@ export class RenderAdditiveLightQueue {
this._shadowUBO[UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET + 2] = 1.0 / matShadowProj.m00;
this._shadowUBO[UBOShadowEnum.SHADOW_PROJ_INFO_OFFSET + 3] = 1.0 / matShadowProj.m05;
Color.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadowEnum.SHADOW_COLOR_OFFSET);
// Spot light sampler binding
if (shadowFrameBufferMap.has(light)) {
const texture = shadowFrameBufferMap.get(light)?.colorTextures[0];
@@ -463,15 +467,15 @@ export class RenderAdditiveLightQueue {
this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 1] = packing;
this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 2] = 0.0;
this._shadowUBO[UBOShadowEnum.SHADOW_LIGHT_PACKING_NBIAS_NULL_INFO_OFFSET + 3] = 0.0;
// Reserve point light shadow interface
Color.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadowEnum.SHADOW_COLOR_OFFSET);
break;
}
default:
}
globalDSManager.update();
cmdBuff.updateBuffer(descriptorSet.getBuffer(UBOShadow.BINDING)!, this._shadowUBO);
Color.toArray(this._shadowUBO, shadowInfo.shadowColor, UBOShadowEnum.SHADOW_COLOR_OFFSET);
descriptorSet.update();
cmdBuff.updateBuffer(descriptorSet.getBuffer(UBOShadow.BINDING)!, this._shadowUBO.buffer, this._shadowUBO.byteLength);
}
}
@@ -627,6 +631,6 @@ export class RenderAdditiveLightQueue {
}
}
cmdBuff.updateBuffer(this._lightBuffer, this._lightBufferData);
cmdBuff.updateBuffer(this._lightBuffer, this._lightBufferData.buffer as ArrayBuffer, this._lightBufferData.byteLength);
}
}
@@ -79,13 +79,14 @@ export class RenderReflectionProbeQueue {
public constructor (pipeline: PipelineRuntime) {
this._pipeline = pipeline;
}
public gatherRenderObjects (probe: ReflectionProbe, camera: Camera, cmdBuff: CommandBuffer): void {
public gatherRenderObjects (probe: ReflectionProbe, camera: Camera, cmdBuff: CommandBuffer, reflectionCamera?: Camera): void {
this.clear();
const scene = camera.scene!;
const sceneData = this._pipeline.pipelineSceneData;
const skybox = sceneData.skybox;
const probeCamera = reflectionCamera ?? probe.camera;
if (skybox.enabled && skybox.model && (probe.camera.clearFlag & SkyBoxFlagValue.VALUE)) {
if (skybox.enabled && skybox.model && (probeCamera.clearFlag & SkyBoxFlagValue.VALUE)) {
this.add(skybox.model);
}
@@ -105,7 +106,7 @@ export class RenderReflectionProbeQueue {
if (geometry.intersect.aabbWithAABB(model.worldBounds, probe.boundingBox!)) {
this.add(model);
}
} else if (geometry.intersect.aabbFrustum(model.worldBounds, probe.camera.frustum)) {
} else if (geometry.intersect.aabbFrustum(model.worldBounds, probeCamera.frustum)) {
this.add(model);
}
}
+2 -2
View File
@@ -195,8 +195,8 @@ export function sceneCulling (sceneData: PipelineSceneData, pipelineUBO: Pipelin
csmLayerObjects.push(getRenderObject(model, camera));
}
if (model.node && ((visibility & model.node.layer) === model.node.layer)
|| (visibility & model.visFlags)) {
if ((model.node && ((visibility & model.node.layer) === model.node.layer))
|| (visibility & model.visFlags)) {
// frustum culling
if (model.worldBounds && !geometry.intersect.aabbFrustum(model.worldBounds, camera.frustum)) {
return;
+2 -2
View File
@@ -25,7 +25,7 @@
import { cclegacy } from './core/global-exports';
import { DataPoolManager } from './3d/skeletal-animation/data-pool-manager';
import { Device, deviceManager } from './gfx';
import { settings, Settings, warnID, Pool, macro, log } from './core';
import { settings, Settings, warnID, Pool, macro, log, debug } from './core';
import { PipelineEventProcessor } from './rendering/pipeline-event';
import type { Root as JsbRoot } from './root';
@@ -242,7 +242,7 @@ rootProto.setRenderPipeline = function (customPipeline: boolean) {
if (customPipeline) {
cclegacy.rendering.createCustomPipeline();
ppl = oldSetPipeline.call(this, null);
log(`Using custom pipeline: ${macro.CUSTOM_PIPELINE_NAME}`);
debug(`Using custom pipeline: ${macro.CUSTOM_PIPELINE_NAME}`);
} else {
// pipeline should not be created in C++, ._ctor need to be triggered
if (cclegacy.legacy_rendering) {
+3 -3
View File
@@ -23,7 +23,7 @@
*/
import { USE_XR } from 'internal:constants';
import { Pool, cclegacy, warnID, settings, macro, log, errorID, SettingsCategory } from './core';
import { Pool, cclegacy, warnID, settings, macro, log, errorID, SettingsCategory, debug } from './core';
import { DebugView } from './rendering/debug-view';
import { Camera, CameraType, Light, Model, TrackingType } from './render-scene/scene';
import type { DataPoolManager } from './3d/skeletal-animation/data-pool-manager';
@@ -380,11 +380,11 @@ export class Root {
isCreateDefaultPipeline = true;
this._pipeline = this._customPipeline!;
// Use default _pipelineEvent
log(`Using custom pipeline: ${macro.CUSTOM_PIPELINE_NAME}`);
debug(`Using custom pipeline: ${macro.CUSTOM_PIPELINE_NAME}`);
} else {
const rppl: (PipelineRuntime & IPipelineEvent) = legacy_rendering.createDefaultPipeline();
isCreateDefaultPipeline = true;
log(`Using legacy pipeline`);
debug(`Using legacy pipeline`);
this._classicPipeline = rppl!;
this._pipeline = this._classicPipeline;
+14 -12
View File
@@ -33,16 +33,16 @@ const MAGIC = 0x4E4F4343;
const CHUNK_ALIGN_AS = 8;
export class CCON {
constructor (document: unknown, chunks: Uint8Array[]) {
constructor(document: unknown, chunks: Uint8Array[]) {
this._document = document;
this._chunks = chunks;
}
get document (): unknown {
get document(): unknown {
return this._document;
}
get chunks (): Uint8Array[] {
get chunks(): Uint8Array[] {
return this._chunks;
}
@@ -50,7 +50,7 @@ export class CCON {
private declare _chunks: Uint8Array[];
}
export function encodeCCONBinary (ccon: CCON): Uint8Array {
export function encodeCCONBinary(ccon: CCON): Uint8Array {
const { document, chunks } = ccon;
const jsonBytes = new Uint8Array(notepackEncode(document));
@@ -75,7 +75,7 @@ export function encodeCCONBinary (ccon: CCON): Uint8Array {
headerView.setUint32(8, ccobBuilder.byteLength, true);
return ccobBuilder.get();
function uint32Bytes (value: number): ArrayBufferView {
function uint32Bytes(value: number): ArrayBufferView {
const bytes = new ArrayBuffer(4);
const view = new DataView(bytes);
view.setUint32(0, value, true);
@@ -83,7 +83,7 @@ export function encodeCCONBinary (ccon: CCON): Uint8Array {
}
}
export function decodeCCONBinary (bytes: Uint8Array): CCON {
export function decodeCCONBinary(bytes: Uint8Array): CCON {
if (bytes.length < 16) {
throw new InvalidCCONError(getError(13102));
}
@@ -159,7 +159,7 @@ interface BufferConstructor {
from(buffer: ArrayBuffer, byteOffset?: number, byteLength?: number): Buffer;
}
function decodeJson (data: Uint8Array): string {
function decodeJson(data: Uint8Array): string {
if (typeof TextDecoder !== 'undefined') {
return new TextDecoder().decode(data);
} else if ('Buffer' in globalThis) {
@@ -177,13 +177,13 @@ export class BufferBuilder {
private _viewOrPaddings: (ArrayBufferView | number)[] = [];
private _length = 0;
constructor () {}
constructor() { }
get byteLength (): number {
get byteLength(): number {
return this._length;
}
public alignAs (align: number): number {
public alignAs(align: number): number {
if (align !== 0) {
const remainder = this._length % align;
if (remainder !== 0) {
@@ -196,14 +196,14 @@ export class BufferBuilder {
return 0;
}
public append (view: ArrayBufferView): number {
public append(view: ArrayBufferView): number {
const result = this._length;
this._viewOrPaddings.push(view);
this._length += view.byteLength;
return result;
}
public get (): Uint8Array {
public get(): Uint8Array {
const result = new Uint8Array(this._length);
let counter = 0;
this._viewOrPaddings.forEach((viewOrPadding) => {
@@ -219,4 +219,6 @@ export class BufferBuilder {
}
cclegacy.internal.decodeCCONBinary = decodeCCONBinary;
cclegacy.internal.encodeCCONBinary = encodeCCONBinary;
cclegacy.internal.CCON = CCON;
cclegacy.internal.BufferBuilder = BufferBuilder;
@@ -0,0 +1,90 @@
/*
Copyright (c) 2025 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 documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// Runtime-selectable spine instantiation. Used only when both spine-3.8 and spine-4.2 are compiled into
// the engine (editor/preview): cc.config.json's moduleOverrides then replaces spine-instantiate.ts with
// this file. Unlike the fixed-version files (spine-instantiate-3.8.ts / -4.2.ts), both the 3.8 and 4.2
// external references are kept here (so both wasm/asm binaries are bundled), and the matching one is
// executed at runtime according to the selected version.
// The version comes from the preview boot (game-boot.js / engine-bootstrap.ts), which reads it from
// cocos.config.json before engine init and writes globalThis._CC_SPINE_VERSION.
import { ensureWasmModuleReady } from 'pal/wasm';
import { error } from '../../core';
import { shouldUseWasmModule, initWasm, initAsmJS } from './spine-wasm-utils';
// Import setSpineVersion through the overridden './spine-version' (= spine-version-dynamic) so it is the
// same module instance whose SPINE_VERSION live binding is read by the shared spine-define.ts.
import { setSpineVersion } from './spine-version';
function getSelectedSpineVersion (): string {
const v = (globalThis as any)._CC_SPINE_VERSION;
return v === '4.2' ? '4.2' : '3.8';
}
export function waitForSpineWasmInstantiation (): Promise<void> {
const errorReport = (msg: any): void => { error(msg); };
// The version must be set before wasm instantiation and before spine-define patches prototypes.
const version = getSelectedSpineVersion();
setSpineVersion(version);
return ensureWasmModuleReady().then((): Promise<void> => {
//We should use static code here, import operation will cause file copy to cache folder.
if (version === '4.2') {
if (shouldUseWasmModule()) {
return Promise.all([
import('external:emscripten/spine/4.2/spine.wasm.js'),
import('external:emscripten/spine/4.2/spine.wasm'),
]).then(([
{ default: wasmFactory },
{ default: spineWasmUrl },
]) => initWasm(wasmFactory, spineWasmUrl));
} else {
return Promise.all([
import('external:emscripten/spine/4.2/spine.asm.js'),
import('external:emscripten/spine/4.2/spine.js.mem'),
]).then(([
{ default: asmFactory },
{ default: asmJsMemUrl },
]) => initAsmJS(asmFactory, asmJsMemUrl));
}
} else {
if (shouldUseWasmModule()) {
return Promise.all([
import('external:emscripten/spine/3.8/spine.wasm.js'),
import('external:emscripten/spine/3.8/spine.wasm'),
]).then(([
{ default: wasmFactory },
{ default: spineWasmUrl },
]) => initWasm(wasmFactory, spineWasmUrl));
} else {
return Promise.all([
import('external:emscripten/spine/3.8/spine.asm.js'),
import('external:emscripten/spine/3.8/spine.js.mem'),
]).then(([
{ default: asmFactory },
{ default: asmJsMemUrl },
]) => initAsmJS(asmFactory, asmJsMemUrl));
}
}
}).catch(errorReport);
}
+88
View File
@@ -0,0 +1,88 @@
/*
Copyright (c) 2025 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 documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// Runtime-selectable spine version. Used only when both spine-3.8 and spine-4.2 are compiled into the
// engine (editor/preview): cc.config.json's moduleOverrides then replaces spine-version.ts with this file.
// Unlike the fixed-version files (spine-version-3.8.ts / -4.2.ts), SPINE_VERSION is a mutable `let`
// (a live ES binding), so the shared layer (spine-define.ts / skeleton.ts) reads the runtime value and
// keeps both `SPINE_VERSION === '3.8' / '4.2'` branches instead of tree-shaking to a single one.
// The version is set by spine-instantiate-dynamic.ts before instantiation, sourced from the host-provided
// globalThis._CC_SPINE_VERSION (injected by the preview boot from cocos.config.json).
import { DataInput, SkeletonBinary } from './spine-binary';
import { BUILD } from 'internal:constants';
// Typed as string so comparisons in the shared layer against the other version literal are not flagged by TS.
export let SPINE_VERSION: string = '3.8';
/**
* Sets the current spine version. Must be called before spine wasm instantiation and before spine-define runs.
*/
export function setSpineVersion (version: string): void {
SPINE_VERSION = version === '4.2' ? '4.2' : '3.8';
}
function isVersionCompatible (version: string | null): boolean {
if (!BUILD) {
if (SPINE_VERSION === '3.8') {
if (!version || version === '3.8.75' || !version.startsWith('3.8.')) {
return false;
}
} else {
if (!version || !version.startsWith('4.2.')) {
return false;
}
}
}
return true;
}
/**
* @internal Used only by editor.
*/
export function isBinaryCompatible (buffer: Uint8Array): boolean {
if (!BUILD) {
const input = new DataInput(buffer);
// The binary hash header differs between versions: 3.8 uses one string, 4.2 uses two ints.
if (SPINE_VERSION === '3.8') {
SkeletonBinary.readString(input); // read hash
} else {
SkeletonBinary.readInt(input); // read hash
SkeletonBinary.readInt(input); // read hash
}
const version = SkeletonBinary.readString(input);
return isVersionCompatible(version);
}
return false;
}
/**
* @internal Used only by editor.
*/
export function isJsonCompatible (json: JSON): boolean {
if (!BUILD) {
return isVersionCompatible(json['skeleton']['spine']);
}
return false;
}
+6
View File
@@ -24,6 +24,12 @@
export const SPINE_VERSION = '3.8';
// Placeholder so spine-instantiate-dynamic.ts can import setSpineVersion from './spine-version' and type-check.
// When building the engine with runtime-selectable spine, moduleOverrides replaces this file with
// spine-version-dynamic.ts (the real implementation). In fixed single-version builds (spine-3.8 / spine-4.2)
// spine-instantiate-dynamic is not used, so this no-op is never called.
export function setSpineVersion (version: string): void {}
export function isBinaryCompatible (buffer: Uint8Array): boolean {
return false;
}
+13 -9
View File
@@ -27,7 +27,7 @@ import { Material, Texture2D } from '../asset/assets';
import { error, errorID, logID, warnID } from '../core/platform/debug';
import { Enum, EnumType, ccenum } from '../core/value-types/enum';
import { Node, NodeEventType } from '../scene-graph';
import { CCObjectFlags, Color, RecyclePool, js } from '../core';
import { CCObjectFlags, Color, RecyclePool, js, math } from '../core';
import { SkeletonData } from './skeleton-data';
import type { Graphics } from '../2d/components/graphics';
import { UIRenderer } from '../2d/framework/ui-renderer';
@@ -850,14 +850,12 @@ export class Skeleton extends UIRenderer {
warnID(16410);
}
const skeletonInfo = this._skeletonCache!.getSkeletonInfo(this._skeletonData!);
if (this._skeletonInfo !== skeletonInfo) {
if (this._skeletonInfo !== skeletonInfo || (!this._skeletonInfo && !skeletonInfo)) {
this._destroySkeletonInfo(this._skeletonCache);
if (!skeletonInfo && this._cacheMode === SpineAnimationCacheMode.PRIVATE_CACHE) {
this._animCache = this._skeletonCache!.initAnimationCache(this.skeletonData!.uuid, this._skeletonData!, this._animationName);
}
this._skeletonInfo = this._skeletonCache!.createSkeletonInfo(this._skeletonData!);
}
if (this._skeletonInfo) {
this._skeleton = this._skeletonInfo.skeleton!;
}
} else {
@@ -1589,7 +1587,7 @@ export class Skeleton extends UIRenderer {
const socket = this._sockets[i];
if (socket.path && socket.target) {
const boneIdx = this._cachedSockets.get(socket.path);
if (!boneIdx) {
if (boneIdx == null || boneIdx < 0) {
error(`Skeleton data does not contain path ${socket.path}`);
continue;
}
@@ -1883,10 +1881,16 @@ export class Skeleton extends UIRenderer {
*/
public setTrackCompleteListener (entry: spine.TrackEntry, listener: TrackListener2): void {
const onComplete = (trackEntry: spine.TrackEntry): void => {
const loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd);
listener(trackEntry, loopCount);
// this._instance.setListener(listenerID, spine.EventType.event);
// this._listener!.event = listener;
const animEnd = math.equals(trackEntry.animationEnd, -1.0) ? trackEntry.animation.duration : trackEntry.animationEnd;
const duration = animEnd - trackEntry.animationStart;
if (duration > 0) {
const loopCount = trackEntry.loop ? Math.floor(trackEntry.trackTime / duration) : 1;
listener(trackEntry, loopCount);
// this._instance.setListener(listenerID, spine.EventType.event);
// this._listener!.event = listener;
} else {
warnID(16420);
}
};
TrackEntryListeners.getListeners(entry, this._instance!).complete = onComplete;
}
+5 -3
View File
@@ -1537,6 +1537,7 @@ export class Terrain extends Component {
* @zh 获得地形信息
*/
@type(TerrainInfo)
@visible(false)
public get info (): TerrainInfo {
const ti = new TerrainInfo();
ti.tileSize = this.tileSize;
@@ -1815,11 +1816,11 @@ export class Terrain extends Component {
* @zh 获得纹理层
*/
public getLayer (id: number): TerrainLayer | null {
if (id === -1) {
if (id === -1 || id === undefined) {
return null;
}
return this._layerList[id];
return this._layerList[id] || null;
}
/**
@@ -2584,7 +2585,8 @@ export class Terrain extends Component {
const index1 = j * this.blockCount[0] + i;
for (let l = 0; l < TERRAIN_MAX_BLEND_LAYERS; ++l) {
layerBuffer[index0 * TERRAIN_MAX_BLEND_LAYERS + l] = this._layerBuffer[index1 * TERRAIN_MAX_BLEND_LAYERS + l];
const oldVal = this._layerBuffer[index1 * TERRAIN_MAX_BLEND_LAYERS + l];
layerBuffer[index0 * TERRAIN_MAX_BLEND_LAYERS + l] = oldVal !== undefined ? oldVal : -1;
}
}
}
+4 -4
View File
@@ -878,7 +878,7 @@ export class TiledLayer extends UIRenderer {
const axis = this._staggerAxis;
switch (this._layerOrientation) {
// left top to right dowm
// left top to right down
case Orientation.ORTHO:
col = Math.floor(x / maptw);
row = Math.floor(y / mapth);
@@ -889,7 +889,7 @@ export class TiledLayer extends UIRenderer {
col = Math.floor(x / maptw2);
row = Math.floor(y / mapth2);
break;
// left top to right dowm
// left top to right down
case Orientation.HEX:
if (axis === StaggerAxis.STAGGERAXIS_Y) {
row = Math.floor(y / (mapth - this._diffY1!));
@@ -1017,7 +1017,7 @@ export class TiledLayer extends UIRenderer {
}
switch (layerOrientation) {
// left top to right dowm
// left top to right down
case Orientation.ORTHO:
cullingCol = col;
cullingRow = rows - row - 1;
@@ -1039,7 +1039,7 @@ export class TiledLayer extends UIRenderer {
left = maptw2 * cullingCol;
bottom = mapth2 * cullingRow;
break;
// left top to right dowm
// left top to right down
case Orientation.HEX:
diffX2 = (axis! === StaggerAxis.STAGGERAXIS_Y && row % 2 === 1) ? maptw2 * odd_even! : 0;
diffY2 = (axis! === StaggerAxis.STAGGERAXIS_X && col % 2 === 1) ? mapth2 * -odd_even! : 0;
+54 -7
View File
@@ -93,8 +93,8 @@ enum State {
export enum ButtonEventType {
/**
* @event click
* @param {Event.EventCustom} event
* @param {Button} button - The Button component.
* @param {EventTouch} event - The original touch event, undefined if the click is triggered by XR.
*/
CLICK = 'click',
}
@@ -156,16 +156,16 @@ export enum ButtonEventType {
*
* @example
* ```ts
* import { log, Node } from 'cc';
* import { log } from 'cc';
* // Add an event to the button.
* button.node.on(Node.EventType.TOUCH_START, (event) => {
* log("This is a callback after the trigger event");
* });
* // You could also add a click event
* // Note: In this way, you can't get the touch event info, so use it wisely.
* button.node.on(Node.EventType.CLICK, (button) => {
* //The event is a custom event, you could get the Button component via first argument
* })
* // The callback receives the Button component and the original touch event (if available).
* button.on(Button.EventType.CLICK, (button, event) => {
* log('button clicked');
* });
* ```
*/
@ccclass('cc.Button')
@@ -586,6 +586,53 @@ export class Button extends Component {
super();
}
/**
* @en
* Register a Button event listener on the component. Button events are dispatched by the owner
* node, and this method is a shorthand which forwards the registration to the node, so
* `button.on(...)` and `button.node.on(...)` share the same listener registry.
* @zh
* 在组件上注册 Button 事件监听。Button 的事件由所属节点派发,此方法是 `this.node.on(type, ...)`
* 的便捷封装,`button.on(...)` 与 `button.node.on(...)` 共用同一份监听器。
* @param type @en Event type, e.g. [[ButtonEventType.CLICK]]. @zh 事件类型,如 [[ButtonEventType.CLICK]]。
* @param callback @en The callback, receives the Button component and the original event. @zh 回调函数,参数为 Button 组件与原始事件。
* @param target @en The target to be bound with. @zh 绑定的目标对象。
* @example
* ```ts
* button.on(Button.EventType.CLICK, (button, event) => {
* // clicked
* }, this);
* ```
*/
public on (type: ButtonEventType, callback: (button: Button, event?: EventTouch) => void, target?: unknown): void {
this.node.on(type, callback, target);
}
/**
* @en
* Remove a Button event listener registered via [[on]] or `button.node.on`. To remove a listener,
* the `type`, `callback` and `target` must match the registration.
* @zh
* 移除通过 [[on]] 或 `button.node.on` 注册的 Button 事件监听。`type`、`callback`、`target`
* 需与注册时一致才能正确移除。
*/
public off (type: ButtonEventType, callback?: (button: Button, event?: EventTouch) => void, target?: unknown): void {
this.node.off(type, callback, target);
}
/**
* @en
* Remove all Button event listeners registered with the given target.
* Note: this forwards to `node.targetOff`, so listeners registered by other components
* or by the engine internals on the same node with the same target are removed as well.
* @zh
* 移除指定 target 上注册的所有 Button 事件监听。注意:此方法会转发到 `node.targetOff`,
* 同一节点上其他组件或引擎内部以相同 target 注册的监听也会被一并移除。
*/
public targetOff (target: unknown): void {
this.node.targetOff(target);
}
public __preload (): void {
if (!this.target) {
this.target = this.node;
@@ -892,7 +939,7 @@ export class Button extends Component {
if (this._pressed) {
ComponentEventHandler.emitEvents(this.clickEvents, event);
this.node.emit(ButtonEventType.CLICK, this);
this.node.emit(ButtonEventType.CLICK, this, event);
}
this._pressed = false;
this._updateState();
+1 -1
View File
@@ -204,7 +204,7 @@ function align (node: Node, widget: Widget): void {
// TODO: type is hack, Change to the type actually used (Node or BaseNode) when BaseNode complete
function visitNode (node: any): void {
const widget = node.getComponent(Widget);
if (widget && widget.enabled) {
if (widget && widget.enabled && cclegacy.isValid(widget, true)) {
if (DEV) {
widget._validateTargetInDEV();
}
+3
View File
@@ -852,6 +852,9 @@ export class Widget extends Component {
}
public onDestroy (): void {
// `onDisable` is skipped when the component was never enabled by the scheduler
// (`IsOnEnableCalled` unset), so unregister here as well.
cclegacy._widgetManager?.remove(this);
this._removeParentEvent();
}
@@ -10,7 +10,7 @@ vec3 HDRToLDR(vec3 color)
#endif
{
// linear exposure has already applied to light intensity
#if CC_TONE_MAPPING_TYPE == HDR_TONE_MAPPING_ACES
#if CC_TONE_MAPPING_TYPE == TONE_MAPPING_ACES
color.rgb = ACESToneMap(color.rgb);
#endif
}
@@ -79,8 +79,12 @@ vec4 saturate(vec4 value) { return clamp(value, vec4(0.0), vec4(1.0)); }
#define IS_RANGED_DIRECTIONAL_LIGHT(light_type) equalf_lowp(light_type, LIGHT_TYPE_RANGED_DIRECTIONAL)
// CC_TONE_MAPPING_TYPE Values
#define TONE_MAPPING_ACES 0
#define TONE_MAPPING_LINEAR 1
#ifndef TONE_MAPPING_ACES
#define TONE_MAPPING_ACES 0
#endif
#ifndef TONE_MAPPING_LINEAR
#define TONE_MAPPING_LINEAR 1
#endif
// Material
#define SURFACES_MAX_TRANSMIT_DEPTH_VALUE 999999.0
@@ -81,9 +81,10 @@ vec3 CalculateNormal(vec3 tangent, vec3 binormal)
// return value is un-normalized
vec3 CalculateNormalFromTangentSpace(vec3 normalFromTangentSpace, float normalStrength, vec3 normal, vec3 tangent, float mirrorNormal)
{
// according to the linearly interpolated mirrorNormal value, the binormal length should vary linearly to ensure geometric smoothness. therefore, explicit normalization is unnecessary.
vec3 binormal = CalculateBinormal(normal, tangent, mirrorNormal);
return (normalFromTangentSpace.x * normalStrength) * normalize(tangent) +
(normalFromTangentSpace.y * normalStrength) * normalize(binormal) +
(normalFromTangentSpace.y * normalStrength) * binormal +
normalFromTangentSpace.z * normalize(normal);
}
@@ -7,7 +7,7 @@ vec4 CCFragOutput (vec4 color) {
#if CC_USE_RGBE_OUTPUT
color = packRGBE(color.rgb);
#elif !CC_USE_FLOAT_OUTPUT
#if CC_USE_HDR && CC_TONE_MAPPING_TYPE == HDR_TONE_MAPPING_ACES
#if CC_USE_HDR && CC_TONE_MAPPING_TYPE == TONE_MAPPING_ACES
color.rgb = ACESToneMap(color.rgb);
#endif
color.rgb = LinearToSRGB(color.rgb);
@@ -222,7 +222,9 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {
vec3 R = normalize(reflect(-V, N));
#if CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_CUBE
if(s.reflectionProbeId < 0.0){
env = SampleReflectionProbe(cc_environment, R, s.roughness, cc_ambientGround.w, CC_USE_IBL == IBL_RGBE);
#if CC_USE_IBL
env = SampleReflectionProbe(cc_environment, R, s.roughness, cc_ambientGround.w, CC_USE_IBL == IBL_RGBE);
#endif
}else{
vec3 centerPos, boxHalfSize;
float mipCount;
@@ -247,7 +249,9 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {
env = unpackRGBE(probe);
#elif CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND || CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND_AND_SKYBOX
if (s.reflectionProbeId < 0.0) {
env = SampleReflectionProbe(cc_environment, R, s.roughness, cc_ambientGround.w, CC_USE_IBL == IBL_RGBE);
#if CC_USE_IBL
env = SampleReflectionProbe(cc_environment, R, s.roughness, cc_ambientGround.w, CC_USE_IBL == IBL_RGBE);
#endif
} else {
vec3 centerPos, boxHalfSize;
float mipCount;
@@ -256,7 +260,10 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {
env = SampleReflectionProbe(cc_reflectionProbeCubemap, fixedR.xyz, s.roughness, mipCount, isReflectProbeUsingRGBE(s.reflectionProbeId));
if (s.reflectionProbeBlendId < 0.0) {
vec3 skyBoxEnv = SampleReflectionProbe(cc_environment, R, s.roughness, cc_ambientGround.w, CC_USE_IBL == IBL_RGBE) * lightIntensity;
vec3 skyBoxEnv = vec3(0.0);
#if CC_USE_IBL
skyBoxEnv = SampleReflectionProbe(cc_environment, R, s.roughness, cc_ambientGround.w, CC_USE_IBL == IBL_RGBE) * lightIntensity;
#endif
#if CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND_AND_SKYBOX
//blend with skybox
env = mix(env, skyBoxEnv, s.reflectionProbeBlendFactor);
@@ -99,7 +99,10 @@ vec3 SampleEnvironmentSpecular(samplerCube tex, in LightingIntermediateData ligh
vec4 fixedR = CalculateBoxProjectedDirection(R, worldPos, cubeCenterPos, boxHalfSize);
R = fixedR.xyz;
vec3 envmap = SampleEnvironmentSpecular(cc_environment, lightingData, cc_ambientGround.w).xyz * cc_ambientSky.w;
vec3 envmap = vec3(0.0);
#if CC_USE_IBL
envmap = SampleEnvironmentSpecular(cc_environment, lightingData, cc_ambientGround.w).xyz * cc_ambientSky.w;
#endif
#if CC_SURFACES_LIGHTING_ANISOTROPIC && CC_SURFACES_LIGHTING_ANISOTROPIC_ENVCONVOLUTION_COUNT
envSpec = EnvAnisotropicReflection(tex, fixedR.xyz, roughness, mipCount, lightingData.anisotropyShape, lightingData.V, lightingData.N, lightingData.T, lightingData.B);
#if CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_CUBE
@@ -159,7 +162,9 @@ vec3 CalculateEnvironmentSpecular(in LightingIntermediateData lightingData, floa
#if CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_CUBE
if(FSInput_reflectionProbeId < 0.0){
#if CC_USE_IBL
envSpec = SampleEnvironmentSpecular(cc_environment, lightingData, cc_ambientGround.w);
#endif
}else{
vec3 centerPos, boxHalfSize;
float mipCount;
@@ -181,7 +186,9 @@ vec3 CalculateEnvironmentSpecular(in LightingIntermediateData lightingData, floa
}
#elif CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND || CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND_AND_SKYBOX
if(FSInput_reflectionProbeId < 0.0){
#if CC_USE_IBL
envSpec = SampleEnvironmentSpecular(cc_environment, lightingData, cc_ambientGround.w);
#endif
}else{
vec3 centerPos, boxHalfSize;
float mipCount;
@@ -197,7 +204,10 @@ vec3 CalculateEnvironmentSpecular(in LightingIntermediateData lightingData, floa
if(FSInput_reflectionProbeBlendId < 0.0)
{
vec3 skyBoxEnv = SampleEnvironmentSpecular(cc_environment, lightingData, cc_ambientGround.w).rgb * lightIntensity;
vec3 skyBoxEnv = vec3(0.0);
#if CC_USE_IBL
skyBoxEnv = SampleEnvironmentSpecular(cc_environment, lightingData, cc_ambientGround.w).rgb * lightIntensity;
#endif
#if CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND_AND_SKYBOX
//blend with skybox
envSpec = mix(envSpec, skyBoxEnv, blendFactor);
@@ -145,7 +145,7 @@ void main() {
color = packRGBE(color.rgb); // for reflection-map
#else
color = CCSurfacesDebugDisplayInvalidNumber(color);
#if !CC_USE_FLOAT_OUTPUT || CC_IS_TRANSPARENCY_PASS
#if !CC_USE_FLOAT_OUTPUT
color.rgb = HDRToLDR(color.rgb);
color.rgb = LinearToSRGB(color.rgb);
#endif
Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.4 KiB

After

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.8 KiB

After

Width:  |  Height:  |  Size: 945 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.2 KiB

After

Width:  |  Height:  |  Size: 7.2 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.4 KiB

After

Width:  |  Height:  |  Size: 6.0 KiB

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