Compare commits
88 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 4992692780 | |||
| c3a8a72f63 | |||
| 2c0e75059f | |||
| 19f4bd5b16 | |||
| 085d05928d | |||
| fb4d586629 | |||
| 620d38cf42 | |||
| d2713fe00e | |||
| 3aeb193d42 | |||
| c4e4790ee6 | |||
| 143af30cf2 | |||
| d6ff23fed4 | |||
| 84e8d4ebf7 | |||
| f2b9936033 | |||
| 129eb437ad | |||
| c58c893334 | |||
| ab982aec68 | |||
| 2d2bbe6731 | |||
| 187387b03f | |||
| 661253a521 | |||
| b6d0f02e88 | |||
| dd1b155d3a | |||
| df96ee85f3 | |||
| 708a343ce8 | |||
| 393203c2f8 | |||
| f3d11f017b | |||
| 09c201017c | |||
| ce6107d930 | |||
| ab8792686b | |||
| 44ef76855b | |||
| 8878e7aade | |||
| 621880a123 | |||
| 2eb268bf9a | |||
| 2e6cc9b127 | |||
| 98917ff2a7 | |||
| dc29d2f8f8 | |||
| eec2a1693b | |||
| 632f9b442f | |||
| 8ce19b658e | |||
| 07f2c5fb43 | |||
| 9b17fd6165 | |||
| e2795f9ecd | |||
| 89a412e0d6 | |||
| aef31099d8 | |||
| 89f8768e57 | |||
| 424be5d0b2 | |||
| e5183b796a | |||
| 32478c1a9c | |||
| 74e632a3d6 | |||
| 26883ba6f4 | |||
| 055c70f8d2 | |||
| 99f6db401c | |||
| 9390ee6bc0 | |||
| 7f258dac58 | |||
| 5c99570616 | |||
| 821928733b | |||
| f567861ff6 | |||
| a7a20b64ab | |||
| 7c75834010 | |||
| 8fd985af75 | |||
| cc97bc8af4 | |||
| 92124590fe | |||
| 822ac6026c | |||
| 4a6f83bd6d | |||
| 04f063eb2b | |||
| 910865bd8b | |||
| e384f54ed2 | |||
| 5964835c83 | |||
| f4ae16247c | |||
| 4b4a3ca13f | |||
| f1c5d21be6 | |||
| da75e89f4a | |||
| aba27a715d | |||
| 62c1eb58c3 | |||
| 5b09978eb1 | |||
| 1b8da1df9b | |||
| ea6ff53aad | |||
| b7ba9f76bb | |||
| ab670c4f99 | |||
| ba0a042ef5 | |||
| 8aa41cc3e7 | |||
| db7666f821 | |||
| 37abbf226a | |||
| c890b69a9e | |||
| 5f4f091c3e | |||
| 1519043126 | |||
| b7e83d3460 | |||
| a64e164e82 |
@@ -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!"
|
||||
|
||||
@@ -3980,3 +3980,7 @@ Debug bones or slots is invalid in cached mode.
|
||||
### 16419
|
||||
|
||||
Spine version not supported.
|
||||
|
||||
### 16420
|
||||
|
||||
Start time must bigger than end time.
|
||||
|
||||
@@ -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",
|
||||
@@ -659,6 +667,13 @@
|
||||
"ccGlobal": true,
|
||||
"internal": false
|
||||
},
|
||||
"SUDV2": {
|
||||
"comment": "Running in the sud v2's quick game.",
|
||||
"type": "boolean",
|
||||
"value": false,
|
||||
"ccGlobal": true,
|
||||
"internal": false
|
||||
},
|
||||
"NODEJS": {
|
||||
"comment": "Running in the Node.js environment.",
|
||||
"type": "boolean",
|
||||
@@ -738,7 +753,7 @@
|
||||
"RUNTIME_BASED": {
|
||||
"comment": "Running in runtime based environment.",
|
||||
"type": "boolean",
|
||||
"value": "$OPPO || $VIVO || $HUAWEI || $MIGU || $HONOR || $COCOS_RUNTIME || $SUD",
|
||||
"value": "$OPPO || $VIVO || $HUAWEI || $MIGU || $HONOR || $COCOS_RUNTIME || $SUD || $SUDV2",
|
||||
"ccGlobal": true,
|
||||
"internal": false
|
||||
},
|
||||
|
||||
@@ -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,
|
||||
));
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -776,6 +776,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;
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
Copyright (c) 2024 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.
|
||||
*/
|
||||
import { PhysicsContact, b2ContactExtends } from './physics-contact';
|
||||
|
||||
const contactMap = new Map<b2ContactExtends, PhysicsContact>();
|
||||
const pools: PhysicsContact[] = [];
|
||||
|
||||
export class PhysicsContactManager {
|
||||
static get (b2contact: b2ContactExtends): PhysicsContact {
|
||||
let c = pools.pop();
|
||||
if (!c) {
|
||||
c = new PhysicsContact();
|
||||
}
|
||||
c.init(b2contact);
|
||||
contactMap.set(b2contact, c);
|
||||
return c;
|
||||
}
|
||||
|
||||
static find (b2contact: b2ContactExtends): PhysicsContact | null {
|
||||
return contactMap.get(b2contact) ?? null;
|
||||
}
|
||||
|
||||
static put (b2contact: b2ContactExtends): void {
|
||||
const c = contactMap.get(b2contact);
|
||||
if (!c) return;
|
||||
pools.push(c);
|
||||
c.reset();
|
||||
contactMap.delete(b2contact);
|
||||
}
|
||||
|
||||
static clear (): void {
|
||||
contactMap.clear();
|
||||
pools.length = 0;
|
||||
}
|
||||
}
|
||||
@@ -31,8 +31,6 @@ export type b2ContactExtends = b2jsb.Contact & {
|
||||
m_userData: any
|
||||
}
|
||||
|
||||
const pools: PhysicsContact[] = [];
|
||||
|
||||
// temp world manifold
|
||||
const pointCache = [new Vec2(), new Vec2()];
|
||||
|
||||
@@ -74,25 +72,6 @@ const impulse: IPhysics2DImpulse = {
|
||||
};
|
||||
|
||||
export class PhysicsContact implements IPhysics2DContact {
|
||||
static get (b2contact: b2ContactExtends): PhysicsContact {
|
||||
let c = pools.pop();
|
||||
|
||||
if (!c) {
|
||||
c = new PhysicsContact();
|
||||
}
|
||||
|
||||
c.init(b2contact);
|
||||
return c;
|
||||
}
|
||||
|
||||
static put (b2contact: b2ContactExtends): void {
|
||||
const c: PhysicsContact = b2contact.m_userData as PhysicsContact;
|
||||
if (!c) return;
|
||||
|
||||
pools.push(c);
|
||||
c.reset();
|
||||
}
|
||||
|
||||
colliderA: Collider2D | null = null;
|
||||
colliderB: Collider2D | null = null;
|
||||
|
||||
@@ -108,16 +87,13 @@ export class PhysicsContact implements IPhysics2DContact {
|
||||
}
|
||||
|
||||
init (b2contact: b2ContactExtends): void {
|
||||
this._b2contact = b2contact;
|
||||
this.colliderA = (b2contact.GetFixtureA().m_userData as b2Shape2D).collider;
|
||||
this.colliderB = (b2contact.GetFixtureB().m_userData as b2Shape2D).collider;
|
||||
this.disabled = false;
|
||||
this.disabledOnce = false;
|
||||
this._impulse = null!;
|
||||
|
||||
this._inverted = false;
|
||||
|
||||
this._b2contact = b2contact;
|
||||
b2contact.m_userData = this;
|
||||
}
|
||||
|
||||
reset (): void {
|
||||
@@ -130,7 +106,6 @@ export class PhysicsContact implements IPhysics2DContact {
|
||||
this.disabled = false;
|
||||
this._impulse = null!;
|
||||
|
||||
this._b2contact.m_userData = null;
|
||||
this._b2contact = null!;
|
||||
}
|
||||
|
||||
|
||||
@@ -36,6 +36,7 @@ import { PhysicsContactListener } from './platform/physics-contact-listener';
|
||||
import { PhysicsAABBQueryCallback } from './platform/physics-aabb-query-callback';
|
||||
import { PhysicsRayCastCallback } from './platform/physics-ray-cast-callback';
|
||||
import { PhysicsContact, b2ContactExtends } from './physics-contact';
|
||||
import { PhysicsContactManager } from './physics-contact-manager';
|
||||
import { Contact2DType, Collider2D, RaycastResult2D } from '../framework';
|
||||
import { b2Shape2D } from './shapes/shape-2d';
|
||||
import { PhysicsDebugDraw } from './platform/physics-debug-draw';
|
||||
@@ -140,7 +141,7 @@ export class b2PhysicsWorld implements IPhysicsWorld {
|
||||
|
||||
if (!v) {
|
||||
if (this._debugGraphics) {
|
||||
this._debugGraphics.node.parent = null;
|
||||
this._debugGraphics.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -444,22 +445,22 @@ export class b2PhysicsWorld implements IPhysicsWorld {
|
||||
}
|
||||
|
||||
_onBeginContact (b2contact: b2ContactExtends): void {
|
||||
const c = PhysicsContact.get(b2contact);
|
||||
const c = PhysicsContactManager.get(b2contact);
|
||||
c.emit(Contact2DType.BEGIN_CONTACT);
|
||||
}
|
||||
|
||||
_onEndContact (b2contact: b2ContactExtends): void {
|
||||
const c = b2contact.m_userData as PhysicsContact;
|
||||
const c = PhysicsContactManager.find(b2contact);
|
||||
if (!c) {
|
||||
return;
|
||||
}
|
||||
c.emit(Contact2DType.END_CONTACT);
|
||||
|
||||
PhysicsContact.put(b2contact);
|
||||
PhysicsContactManager.put(b2contact);
|
||||
}
|
||||
|
||||
_onPreSolve (b2contact: b2ContactExtends): void {
|
||||
const c = b2contact.m_userData as PhysicsContact;
|
||||
const c = PhysicsContactManager.find(b2contact);
|
||||
if (!c) {
|
||||
return;
|
||||
}
|
||||
@@ -468,7 +469,7 @@ export class b2PhysicsWorld implements IPhysicsWorld {
|
||||
}
|
||||
|
||||
_onPostSolve (b2contact: b2ContactExtends, impulse: b2jsb.ContactImpulse): void {
|
||||
const c: PhysicsContact = b2contact.m_userData as PhysicsContact;
|
||||
const c = PhysicsContactManager.find(b2contact);
|
||||
if (!c) {
|
||||
return;
|
||||
}
|
||||
@@ -478,4 +479,7 @@ export class b2PhysicsWorld implements IPhysicsWorld {
|
||||
c.emit(Contact2DType.POST_SOLVE);
|
||||
c._setImpulse(null);
|
||||
}
|
||||
clearContacts (): void {
|
||||
PhysicsContactManager.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[] {
|
||||
|
||||
@@ -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)));
|
||||
});
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/*
|
||||
Copyright (c) 2024 Xiamen Yaji Software Co., Ltd.
|
||||
https://www.cocos.com/
|
||||
*/
|
||||
import { B2ObjectType, getTSObjectFromWASMObjectPtr } from './instantiated';
|
||||
import { PhysicsContact } from './physics-contact';
|
||||
|
||||
const pools: PhysicsContact[] = [];
|
||||
|
||||
export class PhysicsContactManager {
|
||||
static get (b2contact: number): PhysicsContact {
|
||||
let c = pools.pop();
|
||||
if (!c) {
|
||||
c = new PhysicsContact();
|
||||
}
|
||||
c.init(b2contact);
|
||||
return c;
|
||||
}
|
||||
static find (b2contact: number): PhysicsContact | null {
|
||||
return getTSObjectFromWASMObjectPtr<PhysicsContact>(B2ObjectType.Contact, b2contact);
|
||||
}
|
||||
|
||||
static put (b2contact: number): void {
|
||||
const c = getTSObjectFromWASMObjectPtr<PhysicsContact>(B2ObjectType.Contact, b2contact);
|
||||
if (!c) return;
|
||||
|
||||
pools.push(c);
|
||||
c.reset();
|
||||
}
|
||||
|
||||
static clear (): void {
|
||||
pools.length = 0;
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ import { Collider2D, Contact2DType, PhysicsSystem2D } from '../framework';
|
||||
import { B2Shape2D } from './shapes/shape-2d';
|
||||
import { IPhysics2DContact, IPhysics2DImpulse, IPhysics2DManifoldPoint, IPhysics2DWorldManifold } from '../spec/i-physics-contact';
|
||||
|
||||
const pools: PhysicsContact[] = [];
|
||||
/* pools moved to PhysicsContactManager */
|
||||
|
||||
// temp world manifold
|
||||
const pointCache = [new Vec2(), new Vec2()];
|
||||
@@ -62,24 +62,7 @@ const impulse: IPhysics2DImpulse = {
|
||||
|
||||
/** @mangle */
|
||||
export class PhysicsContact implements IPhysics2DContact {
|
||||
static get (b2contact: number): PhysicsContact {
|
||||
let c = pools.pop();
|
||||
|
||||
if (!c) {
|
||||
c = new PhysicsContact();
|
||||
}
|
||||
|
||||
c.init(b2contact);
|
||||
return c;
|
||||
}
|
||||
|
||||
static put (b2contact: number): void {
|
||||
const c = getTSObjectFromWASMObjectPtr<PhysicsContact>(B2ObjectType.Contact, b2contact);
|
||||
if (!c) return;
|
||||
|
||||
pools.push(c);
|
||||
c.reset();
|
||||
}
|
||||
/* static get/put/clear moved to PhysicsContactManager */
|
||||
|
||||
colliderA: Collider2D | null = null;
|
||||
colliderB: Collider2D | null = null;
|
||||
|
||||
@@ -35,7 +35,7 @@ import { B2RigidBody2D } from './rigid-body';
|
||||
import { PhysicsContactListener } from './platform/physics-contact-listener';
|
||||
import { PhysicsAABBQueryCallback } from './platform/physics-aabb-query-callback';
|
||||
import { PhysicsRayCastCallback } from './platform/physics-ray-cast-callback';
|
||||
import { PhysicsContact } from './physics-contact';
|
||||
import { PhysicsContactManager } from './physics-contact-manager';
|
||||
import { Contact2DType, Collider2D, RaycastResult2D } from '../framework';
|
||||
import { B2Shape2D } from './shapes/shape-2d';
|
||||
import { PhysicsDebugDraw } from './platform/physics-debug-draw';
|
||||
@@ -82,6 +82,16 @@ export class B2PhysicsWorld implements IPhysicsWorld {
|
||||
PhysicsContactListener._PreSolve = this._onPreSolve;
|
||||
PhysicsContactListener._PostSolve = this._onPostSolve;
|
||||
this._contactListener = B2.ContactListener.implement(PhysicsContactListener.callback);
|
||||
const orgRegisterContactFixture = this._contactListener.registerContactFixture.bind(this._contactListener);
|
||||
this._contactListener.registerContactFixture = (contactFixture: number): void => {
|
||||
PhysicsContactListener.registerContactFixture(contactFixture);
|
||||
orgRegisterContactFixture(contactFixture);
|
||||
};
|
||||
const orgUnregisterContactFixture = this._contactListener.unregisterContactFixture.bind(this._contactListener);
|
||||
this._contactListener.unregisterContactFixture = (contactFixture: number): void => {
|
||||
PhysicsContactListener.unregisterContactFixture(contactFixture);
|
||||
orgUnregisterContactFixture(contactFixture);
|
||||
};
|
||||
this._world.SetContactListener(this._contactListener);
|
||||
|
||||
this._aabbQueryCallback = B2.QueryCallback.implement(PhysicsAABBQueryCallback.callback);
|
||||
@@ -104,7 +114,7 @@ export class B2PhysicsWorld implements IPhysicsWorld {
|
||||
|
||||
if (!v) {
|
||||
if (this._debugGraphics) {
|
||||
this._debugGraphics.node.parent = null;
|
||||
this._debugGraphics.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -427,22 +437,22 @@ export class B2PhysicsWorld implements IPhysicsWorld {
|
||||
}
|
||||
|
||||
_onBeginContact (b2contact: number): void {
|
||||
const c = PhysicsContact.get(b2contact);
|
||||
const c = PhysicsContactManager.get(b2contact);
|
||||
c.emit(Contact2DType.BEGIN_CONTACT);
|
||||
}
|
||||
|
||||
_onEndContact (b2contact: number): void {
|
||||
const c = getTSObjectFromWASMObjectPtr<PhysicsContact>(B2ObjectType.Contact, b2contact);
|
||||
const c = PhysicsContactManager.find(b2contact);
|
||||
if (!c) {
|
||||
return;
|
||||
}
|
||||
c.emit(Contact2DType.END_CONTACT);
|
||||
|
||||
PhysicsContact.put(b2contact);
|
||||
PhysicsContactManager.put(b2contact);
|
||||
}
|
||||
|
||||
_onPreSolve (b2contact: number): void {
|
||||
const c = getTSObjectFromWASMObjectPtr<PhysicsContact>(B2ObjectType.Contact, b2contact);
|
||||
const c = PhysicsContactManager.find(b2contact);
|
||||
if (!c) {
|
||||
return;
|
||||
}
|
||||
@@ -451,7 +461,7 @@ export class B2PhysicsWorld implements IPhysicsWorld {
|
||||
}
|
||||
|
||||
_onPostSolve (b2contact: number, impulse: number): void {
|
||||
const c = getTSObjectFromWASMObjectPtr<PhysicsContact>(B2ObjectType.Contact, b2contact);
|
||||
const c = PhysicsContactManager.find(b2contact);
|
||||
if (!c) {
|
||||
return;
|
||||
}
|
||||
@@ -461,4 +471,8 @@ export class B2PhysicsWorld implements IPhysicsWorld {
|
||||
c.emit(Contact2DType.POST_SOLVE);
|
||||
c._setImpulse(0);
|
||||
}
|
||||
|
||||
clearContacts (): void {
|
||||
PhysicsContactManager.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,37 +22,56 @@
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { B2 } from '../instantiated';
|
||||
|
||||
type BeginContactCallback = (contact: number) => void;
|
||||
type EndContactCallback = (contact: number) => void;
|
||||
type PreSolveCallback = (contact: number, oldManifold: number) => void;
|
||||
type PostSolveCallback = (contact: number, impulse: number) => void;
|
||||
|
||||
export class PhysicsContactListener {
|
||||
static _contactFixtures: Set<number> = new Set<number>();
|
||||
static _BeginContact: BeginContactCallback | null = null;
|
||||
static _EndContact: EndContactCallback | null = null;
|
||||
static _PreSolve: PreSolveCallback | null = null;
|
||||
static _PostSolve: PostSolveCallback | null = null;
|
||||
static _shouldReportContacts: Set<number> = new Set<number>();
|
||||
|
||||
static BeginContact (contact: number): void {
|
||||
if (this._BeginContact) {
|
||||
if (!this._BeginContact) return;
|
||||
const fixtureA = B2.ContactGetFixtureA(contact) as number;
|
||||
const fixtureB = B2.ContactGetFixtureB(contact) as number;
|
||||
const fixtures = this._contactFixtures;
|
||||
this._shouldReportContacts.delete(contact);
|
||||
|
||||
if (fixtures.has(fixtureA) || fixtures.has(fixtureB)) {
|
||||
this._shouldReportContacts.add(contact);
|
||||
this._BeginContact(contact);
|
||||
}
|
||||
}
|
||||
|
||||
static EndContact (contact: number): void {
|
||||
if (this._EndContact) {
|
||||
if (this._EndContact && this._shouldReportContacts.has(contact)) {
|
||||
this._shouldReportContacts.delete(contact);
|
||||
this._EndContact(contact);
|
||||
}
|
||||
}
|
||||
|
||||
static PreSolve (contact: number, oldManifold: number): void {
|
||||
if (this._PreSolve) {
|
||||
if (this._PreSolve && this._shouldReportContacts.has(contact)) {
|
||||
this._PreSolve(contact, oldManifold);
|
||||
}
|
||||
}
|
||||
static registerContactFixture (fixture: number): void {
|
||||
this._contactFixtures.add(fixture);
|
||||
}
|
||||
|
||||
static unregisterContactFixture (fixture: number): void {
|
||||
this._contactFixtures.delete(fixture);
|
||||
}
|
||||
|
||||
static PostSolve (contact: number, impulse: number): void {
|
||||
if (this._PostSolve) {
|
||||
if (this._PostSolve && this._shouldReportContacts.has(contact)) {
|
||||
this._PostSolve(contact, impulse);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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[]
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
Copyright (c) 2024 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.
|
||||
*/
|
||||
import { PhysicsContact, b2ContactExtends } from './physics-contact';
|
||||
|
||||
const contactMap = new Map<b2ContactExtends, PhysicsContact>();
|
||||
const pools: PhysicsContact[] = [];
|
||||
|
||||
export class PhysicsContactManager {
|
||||
static get (b2contact: b2ContactExtends): PhysicsContact {
|
||||
let c = pools.pop();
|
||||
if (!c) {
|
||||
c = new PhysicsContact();
|
||||
}
|
||||
c.init(b2contact);
|
||||
contactMap.set(b2contact, c);
|
||||
return c;
|
||||
}
|
||||
|
||||
static find (b2contact: b2ContactExtends): PhysicsContact | null {
|
||||
return contactMap.get(b2contact) ?? null;
|
||||
}
|
||||
|
||||
static put (b2contact: b2ContactExtends): void {
|
||||
const c = contactMap.get(b2contact);
|
||||
if (!c) return;
|
||||
pools.push(c);
|
||||
c.reset();
|
||||
contactMap.delete(b2contact);
|
||||
}
|
||||
|
||||
static clear (): void {
|
||||
contactMap.clear();
|
||||
pools.length = 0;
|
||||
}
|
||||
}
|
||||
@@ -33,8 +33,6 @@ export type b2ContactExtends = b2.Contact & {
|
||||
m_userData: any;
|
||||
}
|
||||
|
||||
const pools: PhysicsContact[] = [];
|
||||
|
||||
// temp world manifold
|
||||
const pointCache = [new Vec2(), new Vec2()];
|
||||
|
||||
@@ -68,25 +66,6 @@ const impulse: IPhysics2DImpulse = {
|
||||
|
||||
/** @mangle */
|
||||
export class PhysicsContact implements IPhysics2DContact {
|
||||
static get (b2contact: b2ContactExtends): PhysicsContact {
|
||||
let c = pools.pop();
|
||||
|
||||
if (!c) {
|
||||
c = new PhysicsContact();
|
||||
}
|
||||
|
||||
c.init(b2contact);
|
||||
return c;
|
||||
}
|
||||
|
||||
static put (b2contact: b2ContactExtends): void {
|
||||
const c: PhysicsContact = b2contact.m_userData as PhysicsContact;
|
||||
if (!c) return;
|
||||
|
||||
pools.push(c);
|
||||
c.reset();
|
||||
}
|
||||
|
||||
colliderA: Collider2D | null = null;
|
||||
colliderB: Collider2D | null = null;
|
||||
|
||||
@@ -111,7 +90,6 @@ export class PhysicsContact implements IPhysics2DContact {
|
||||
this._inverted = false;
|
||||
|
||||
this._b2contact = b2contact;
|
||||
b2contact.m_userData = this;
|
||||
}
|
||||
|
||||
reset (): void {
|
||||
@@ -124,7 +102,6 @@ export class PhysicsContact implements IPhysics2DContact {
|
||||
this.disabled = false;
|
||||
this._impulse = null;
|
||||
|
||||
this._b2contact!.m_userData = null;
|
||||
this._b2contact = null;
|
||||
}
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ import { PhysicsDebugDraw } from './platform/physics-debug-draw';
|
||||
import { Node, find, Layers } from '../../scene-graph';
|
||||
import { director } from '../../game';
|
||||
import type { Graphics } from '../../2d/components/graphics';
|
||||
import { PhysicsContactManager } from './physics-contact-manager';
|
||||
|
||||
const tempVec3 = new Vec3();
|
||||
const tempVec2_1 = new Vec2();
|
||||
@@ -99,7 +100,7 @@ export class b2PhysicsWorld implements IPhysicsWorld {
|
||||
|
||||
if (!v) {
|
||||
if (this._debugGraphics) {
|
||||
this._debugGraphics.node.parent = null;
|
||||
this._debugGraphics.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -414,22 +415,22 @@ export class b2PhysicsWorld implements IPhysicsWorld {
|
||||
}
|
||||
|
||||
_onBeginContact (b2contact: b2ContactExtends): void {
|
||||
const c = PhysicsContact.get(b2contact);
|
||||
const c = PhysicsContactManager.get(b2contact);
|
||||
c.emit(Contact2DType.BEGIN_CONTACT);
|
||||
}
|
||||
|
||||
_onEndContact (b2contact: b2ContactExtends): void {
|
||||
const c = b2contact.m_userData as PhysicsContact;
|
||||
const c = PhysicsContactManager.find(b2contact);
|
||||
if (!c) {
|
||||
return;
|
||||
}
|
||||
c.emit(Contact2DType.END_CONTACT);
|
||||
|
||||
PhysicsContact.put(b2contact);
|
||||
PhysicsContactManager.put(b2contact);
|
||||
}
|
||||
|
||||
_onPreSolve (b2contact: b2ContactExtends): void {
|
||||
const c = b2contact.m_userData as PhysicsContact;
|
||||
const c = PhysicsContactManager.find(b2contact);
|
||||
if (!c) {
|
||||
return;
|
||||
}
|
||||
@@ -438,7 +439,7 @@ export class b2PhysicsWorld implements IPhysicsWorld {
|
||||
}
|
||||
|
||||
_onPostSolve (b2contact: b2ContactExtends, impulse: b2.ContactImpulse): void {
|
||||
const c: PhysicsContact = b2contact.m_userData as PhysicsContact;
|
||||
const c = PhysicsContactManager.find(b2contact);
|
||||
if (!c) {
|
||||
return;
|
||||
}
|
||||
@@ -448,4 +449,7 @@ export class b2PhysicsWorld implements IPhysicsWorld {
|
||||
c.emit(Contact2DType.POST_SOLVE);
|
||||
c._setImpulse(null);
|
||||
}
|
||||
clearContacts (): void {
|
||||
PhysicsContactManager.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[] {
|
||||
|
||||
@@ -285,4 +285,6 @@ export class BuiltinPhysicsWorld implements IPhysicsWorld {
|
||||
raycast (p1: IVec2Like, p2: IVec2Like, type: ERaycast2DType): RaycastResult2D[] {
|
||||
return [];
|
||||
}
|
||||
clearContacts (): void {
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -165,6 +165,7 @@ const ENTIRE_WORLD: IPhysicsWorld = {
|
||||
testPoint: FUNC,
|
||||
testAABB: FUNC,
|
||||
drawDebug: FUNC,
|
||||
clearContacts: FUNC,
|
||||
};
|
||||
|
||||
export function checkPhysicsModule (obj: any): boolean {
|
||||
|
||||
@@ -381,8 +381,12 @@ export class PhysicsSystem2D extends Eventify(System) {
|
||||
static constructAndRegister (): void {
|
||||
director.registerSystem(PhysicsSystem2D.ID, PhysicsSystem2D.instance, SystemPriority.LOW);
|
||||
}
|
||||
clearContacts (): void {
|
||||
this.physicsWorld.clearContacts();
|
||||
}
|
||||
}
|
||||
|
||||
if (!BUILD || !LOAD_BOX2D_MANUALLY) {
|
||||
director.once(DirectorEvent.INIT, (): void => { PhysicsSystem2D.constructAndRegister(); });
|
||||
director.once(DirectorEvent.RESET, (): void => { PhysicsSystem2D.instance.clearContacts(); });
|
||||
}
|
||||
|
||||
@@ -38,4 +38,5 @@ export interface IPhysicsWorld {
|
||||
testPoint (p: Vec2): readonly Collider2D[];
|
||||
testAABB (rect: Rect): readonly Collider2D[];
|
||||
drawDebug (): void;
|
||||
clearContacts (): void;
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -615,10 +615,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();
|
||||
}
|
||||
|
||||
@@ -817,11 +817,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) {
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -42,6 +42,24 @@ declare namespace spine {
|
||||
delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
class SPVectorPhysicsConstraintPtr {
|
||||
size(): number;
|
||||
get(index: number): PhysicsConstraint;
|
||||
delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
class SPVectorPhysicsConstraintDataPtr {
|
||||
size(): number;
|
||||
get(index: number): PhysicsConstraintData;
|
||||
delete();
|
||||
}
|
||||
|
||||
class Animation {
|
||||
constructor(name: string, timelines: Array<Timeline>, duration: number);
|
||||
duration: number;
|
||||
@@ -708,6 +726,10 @@ declare namespace spine {
|
||||
ikConstraints: Array<IkConstraint>;
|
||||
transformConstraints: Array<TransformConstraint>;
|
||||
pathConstraints: Array<PathConstraint>;
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
physicsConstraints: Array<PhysicsConstraint>;
|
||||
_updateCache: Updatable[];
|
||||
skin: Skin;
|
||||
color: Color;
|
||||
@@ -735,8 +757,24 @@ declare namespace spine {
|
||||
findIkConstraint(constraintName: string): IkConstraint;
|
||||
findTransformConstraint(constraintName: string): TransformConstraint;
|
||||
findPathConstraint(constraintName: string): PathConstraint;
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
findPhysicsConstraint(constraintName: string): PhysicsConstraint;
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
getPhysicsConstraints(): SPVectorPhysicsConstraintPtr;
|
||||
//getBounds(offset: Vector2, size: Vector2, temp?: Array<number>): void;
|
||||
update(delta: number): void;
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
updateWorldTransform(physics: Physics): void;
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
updateWorldTransform(physics: Physics, parent: Bone): void;
|
||||
}
|
||||
class SkeletonBinary {
|
||||
static AttachmentTypeValues: number[];
|
||||
@@ -812,6 +850,10 @@ declare namespace spine {
|
||||
ikConstraints: IkConstraintData[];
|
||||
transformConstraints: TransformConstraintData[];
|
||||
pathConstraints: PathConstraintData[];
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
physicsConstraints: PhysicsConstraintData[];
|
||||
x: number;
|
||||
y: number;
|
||||
width: number;
|
||||
@@ -835,6 +877,14 @@ declare namespace spine {
|
||||
findTransformConstraint(constraintName: string): TransformConstraintData;
|
||||
findPathConstraint(constraintName: string): PathConstraintData;
|
||||
findPathConstraintIndex(pathConstraintName: string): number;
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
findPhysicsConstraint(constraintName: string): PhysicsConstraintData;
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
getPhysicsConstraints(): SPVectorPhysicsConstraintDataPtr;
|
||||
}
|
||||
class SkeletonJson {
|
||||
attachmentLoader: AttachmentLoader;
|
||||
@@ -1005,6 +1055,82 @@ declare namespace spine {
|
||||
local: boolean;
|
||||
constructor(name: string);
|
||||
}
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
enum Physics {
|
||||
none = 0,
|
||||
reset = 1,
|
||||
update = 2,
|
||||
pose = 3
|
||||
}
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
class PhysicsConstraint implements Updatable {
|
||||
data: PhysicsConstraintData;
|
||||
bone: Bone;
|
||||
inertia: number;
|
||||
strength: number;
|
||||
damping: number;
|
||||
massInverse: number;
|
||||
wind: number;
|
||||
gravity: number;
|
||||
mix: number;
|
||||
_reset: boolean;
|
||||
ux: number;
|
||||
uy: number;
|
||||
cx: number;
|
||||
cy: number;
|
||||
tx: number;
|
||||
ty: number;
|
||||
xOffset: number;
|
||||
xVelocity: number;
|
||||
yOffset: number;
|
||||
yVelocity: number;
|
||||
rotateOffset: number;
|
||||
rotateVelocity: number;
|
||||
scaleOffset: number;
|
||||
scaleVelocity: number;
|
||||
remaining: number;
|
||||
lastTime: number;
|
||||
active: boolean;
|
||||
constructor(data: PhysicsConstraintData, skeleton: Skeleton);
|
||||
isActive(): boolean;
|
||||
reset(): void;
|
||||
setToSetupPose(): void;
|
||||
update(): void;
|
||||
translate(x: number, y: number): void;
|
||||
rotate(x: number, y: number, degrees: number): void;
|
||||
}
|
||||
/**
|
||||
* @version 4.2
|
||||
*/
|
||||
class PhysicsConstraintData extends ConstraintData {
|
||||
bone: BoneData;
|
||||
x: number;
|
||||
y: number;
|
||||
rotate: number;
|
||||
scaleX: number;
|
||||
shearX: number;
|
||||
limit: number;
|
||||
step: number;
|
||||
inertia: number;
|
||||
strength: number;
|
||||
damping: number;
|
||||
massInverse: number;
|
||||
wind: number;
|
||||
gravity: number;
|
||||
mix: number;
|
||||
inertiaGlobal: boolean;
|
||||
strengthGlobal: boolean;
|
||||
dampingGlobal: boolean;
|
||||
massGlobal: boolean;
|
||||
windGlobal: boolean;
|
||||
gravityGlobal: boolean;
|
||||
mixGlobal: boolean;
|
||||
constructor(name: string);
|
||||
}
|
||||
class Triangulator {
|
||||
private convexPolygons;
|
||||
private convexPolygonsIndices;
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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';
|
||||
@@ -1883,10 +1883,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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
Before Width: | Height: | Size: 8.4 KiB After Width: | Height: | Size: 6.8 KiB |
|
Before Width: | Height: | Size: 8.8 KiB After Width: | Height: | Size: 945 B |
|
Before Width: | Height: | Size: 9.4 KiB After Width: | Height: | Size: 5.2 KiB |
|
Before Width: | Height: | Size: 9.2 KiB After Width: | Height: | Size: 7.2 KiB |
|
Before Width: | Height: | Size: 9.4 KiB After Width: | Height: | Size: 6.0 KiB |
|
Before Width: | Height: | Size: 9.2 KiB After Width: | Height: | Size: 4.5 KiB |
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"ver": "1.2.0",
|
||||
"importer": "directory",
|
||||
"imported": true,
|
||||
"uuid": "6ef37a33-5db9-4231-9855-f72b8428f6fa",
|
||||
"files": [],
|
||||
"subMetas": {},
|
||||
"userData": {}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"ver": "1.0.4",
|
||||
"importer": "texture-cube",
|
||||
"imported": true,
|
||||
"uuid": "a4063d6c-c46e-482a-bf84-99eb9fbb2789",
|
||||
"files": [
|
||||
".json"
|
||||
],
|
||||
"subMetas": {},
|
||||
"userData": {
|
||||
"wrapModeS": "repeat",
|
||||
"wrapModeT": "repeat",
|
||||
"minfilter": "linear",
|
||||
"magfilter": "linear",
|
||||
"mipfilter": "none",
|
||||
"anisotropy": 0,
|
||||
"isRGBE": false
|
||||
}
|
||||
}
|
||||
@@ -70,7 +70,9 @@ CCProgram smaa-edge-fs %{
|
||||
vec3 ToLDR(vec3 color) {
|
||||
#if CC_USE_HDR
|
||||
color *= cc_exposure.x * FP_SCALE_INV;
|
||||
color = ACESToneMap(color);
|
||||
#if CC_TONE_MAPPING_TYPE == TONE_MAPPING_ACES
|
||||
color = ACESToneMap(color);
|
||||
#endif
|
||||
color = LinearToSRGB(color);
|
||||
#endif
|
||||
return color;
|
||||
|
||||
@@ -55,7 +55,9 @@ CCProgram tonemap-fs %{
|
||||
vec3 ToLDR(vec3 color) {
|
||||
#if CC_USE_HDR
|
||||
color *= cc_exposure.x * FP_SCALE_INV;
|
||||
color = ACESToneMap(color);
|
||||
#if CC_TONE_MAPPING_TYPE == TONE_MAPPING_ACES
|
||||
color = ACESToneMap(color);
|
||||
#endif
|
||||
color = LinearToSRGB(color);
|
||||
#endif
|
||||
return color;
|
||||
|
||||
@@ -244,6 +244,20 @@
|
||||
"faceCount": 0.1
|
||||
}
|
||||
]
|
||||
},
|
||||
"legacyFbxImporter": false,
|
||||
"allowMeshDataAccess": true,
|
||||
"addVertexColor": false,
|
||||
"generateLightmapUVNode": false,
|
||||
"meshOptimizer": {
|
||||
"enable": false,
|
||||
"algorithm": "simplify",
|
||||
"simplifyOptions": {
|
||||
"targetRatio": 1,
|
||||
"enableSmartLink": true,
|
||||
"agressiveness": 7,
|
||||
"maxIterationCount": 100
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,6 +38,11 @@ module.exports = {
|
||||
newCubeMap: 'CubeMap',
|
||||
newRenderTexture: 'Render Texture',
|
||||
newScene: 'Scene',
|
||||
newScene:{
|
||||
'2d': '2D Scene',
|
||||
'3d': '3D Scene',
|
||||
quality: 'High Quality Scene',
|
||||
},
|
||||
newPrefab: 'Node Prefab',
|
||||
newMaterial: 'Material',
|
||||
newPhysicsMaterial: 'Physics Material',
|
||||
|
||||
@@ -779,6 +779,7 @@ module.exports = link(mixin({
|
||||
},
|
||||
mask: {
|
||||
type: 'The mask type',
|
||||
radius: 'The radius for rounded corners of rect mask',
|
||||
spriteFrame: 'The mask image',
|
||||
inverted: 'The Reverse mask (Not supported Canvas Mode)',
|
||||
alphaThreshold:
|
||||
|
||||
@@ -37,6 +37,11 @@ module.exports = {
|
||||
newTypeScript: '脚本 (TypeScript)',
|
||||
newCubeMap: '立方体贴图',
|
||||
newScene: '场景',
|
||||
newScene:{
|
||||
'2d': '2D 场景',
|
||||
'3d': '3D 场景',
|
||||
quality: '高质量场景',
|
||||
},
|
||||
newPrefab: '预制 (Prefab)',
|
||||
newRenderTexture: '渲染纹理 (Render Texture)',
|
||||
newMaterial: '材质',
|
||||
|
||||
@@ -760,6 +760,7 @@ module.exports = link(mixin({
|
||||
},
|
||||
mask: {
|
||||
type: '遮罩类型',
|
||||
radius: '矩形遮罩的圆角半径',
|
||||
spriteFrame: '遮罩所需要的贴图',
|
||||
inverted: '反向遮罩(不支持 Canvas 模式)',
|
||||
alphaThreshold: 'Alpha 阈值,只有当模板的像素的 Alpha 大于 Alpha Threshold 时,才会绘制内容(不支持 Canvas 模式)',
|
||||
|
||||
@@ -3725,9 +3725,14 @@ if(APPLE)
|
||||
"$(inherited)"
|
||||
${CC_EXTERNAL_LIBS}
|
||||
)
|
||||
if(CMAKE_OSX_ARCHITECTURES)
|
||||
set(_CC_ENGINE_ARCHS "${CMAKE_OSX_ARCHITECTURES}")
|
||||
else()
|
||||
set(_CC_ENGINE_ARCHS "arm64;x86_64")
|
||||
endif()
|
||||
set_target_properties(${ENGINE_NAME} PROPERTIES
|
||||
XCODE_ATTRIBUTE_ONLY_ACTIVE_ARCH "YES"
|
||||
OSX_ARCHITECTURES "arm64;x86_64"
|
||||
OSX_ARCHITECTURES "${_CC_ENGINE_ARCHS}"
|
||||
ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/archives
|
||||
)
|
||||
if(MACOSX)
|
||||
@@ -3739,9 +3744,9 @@ if(APPLE)
|
||||
)
|
||||
elseif(IOS)
|
||||
|
||||
if("${XCODE_VERSION}" VERSION_GREATER_EQUAL "15.0")
|
||||
# For Xcode 15 and newer, add extra link flags to fix crash in __cxx_global_var_init.
|
||||
message(STATUS "Using Xcode 15 or newer, adding extra link flags: -Wl,-ld_classic.")
|
||||
if("${XCODE_VERSION}" VERSION_GREATER_EQUAL "15.0" AND "${XCODE_VERSION}" VERSION_LESS "15.1")
|
||||
# Xcode 15.0 new linker crashes on weak symbols (114813650), fixed in 15.1.
|
||||
message(STATUS "Xcode ${XCODE_VERSION}: adding -Wl,-ld_classic to work around weak symbol crash.")
|
||||
target_link_options(${ENGINE_NAME} PUBLIC -Wl,-ld_classic)
|
||||
endif()
|
||||
|
||||
|
||||
@@ -126,7 +126,7 @@ if("$ENV{COCOS_ENGINE_DEV}" EQUAL "1")
|
||||
set(WERROR_FLAGS "-Werror -Werror=return-type") # -Wshorten-64-to-32 -Werror=return-type
|
||||
|
||||
if(APPLE)
|
||||
set(WERROR_FLAGS " ${WERROR_FLAGS} -Wno-deprecated-declarations -Wno-deprecated-builtins -Wno-unqualified-std-cast-call")
|
||||
set(WERROR_FLAGS " ${WERROR_FLAGS} -Wno-deprecated-declarations -Wno-deprecated-builtins -Wno-unqualified-std-cast-call -Wno-nontrivial-memcall")
|
||||
elseif(LINUX)
|
||||
set(WERROR_FLAGS " ${WERROR_FLAGS} -Wno-nullability-completeness -Wno-deprecated-declarations")
|
||||
elseif(ANDROID)
|
||||
|
||||
@@ -58,13 +58,13 @@ void UIModelProxy::activeSubModels() {
|
||||
auto* vertexBuffer = _device->createBuffer({
|
||||
gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST,
|
||||
gfx::MemoryUsageBit::DEVICE,
|
||||
65535 * _stride,
|
||||
65536 * _stride, // Uint16 can address 65536 vertices (indices 0–65535)
|
||||
_stride,
|
||||
});
|
||||
auto* indexBuffer = _device->createBuffer({
|
||||
gfx::BufferUsageBit::INDEX | gfx::BufferUsageBit::TRANSFER_DST,
|
||||
gfx::MemoryUsageBit::DEVICE,
|
||||
65535 * sizeof(uint16_t) * 2,
|
||||
65536 * sizeof(uint16_t) * 2, // Uint16 can address 65536 vertices (indices 0–65535)
|
||||
sizeof(uint16_t),
|
||||
});
|
||||
gfx::BufferList vbReference;
|
||||
|
||||
@@ -530,7 +530,7 @@ void Mesh::initialize() {
|
||||
if (dstStride == 4) {
|
||||
uint32_t vertexCount = _struct.vertexBundles[prim.vertexBundelIndices[0]].view.count;
|
||||
#if CC_OPTIMIZE_MESH_DATA
|
||||
if (vertexCount < 65536) {
|
||||
if (vertexCount <= 65536) { // Uint16 can address 65536 vertices (indices 0–65535)
|
||||
dstStride >>= 1; // Reduce to short.
|
||||
dstSize >>= 1;
|
||||
} else if (!gfxDevice->hasFeature(gfx::Feature::ELEMENT_INDEX_UINT)) {
|
||||
@@ -538,7 +538,7 @@ void Mesh::initialize() {
|
||||
}
|
||||
#else
|
||||
if (!gfxDevice->hasFeature(gfx::Feature::ELEMENT_INDEX_UINT)) {
|
||||
if (vertexCount >= 65536) {
|
||||
if (vertexCount > 65536) { // Uint16 can address 65536 vertices (indices 0–65535)
|
||||
CC_LOG_WARNING("Device does not support UINT element index type and vertexCount (%u) is larger than ushort", vertexCount);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -185,7 +185,11 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ccs
|
||||
|
||||
if (geometry.customAttributes.has_value()) {
|
||||
for (const auto &ca : geometry.customAttributes.value()) {
|
||||
const auto &info = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(attr->format)];
|
||||
if (ca.values.empty()) {
|
||||
CC_LOG_WARNING("Custom attribute %s has no values, skipped.", ca.attr.name.c_str());
|
||||
continue;
|
||||
}
|
||||
const auto &info = gfx::GFX_FORMAT_INFOS[static_cast<uint32_t>(ca.attr.format)];
|
||||
attributes.emplace_back(ca.attr);
|
||||
vertCount = std::max(vertCount, static_cast<uint32_t>(std::floor(ca.values.size() / info.count)));
|
||||
channels.emplace_back(Channel{stride, ca.values, ca.attr});
|
||||
|
||||
@@ -68,6 +68,9 @@ unsigned int AudioEngine::sMaxInstances = MAX_AUDIOINSTANCES;
|
||||
AudioEngine::ProfileHelper *AudioEngine::sDefaultProfileHelper = nullptr;
|
||||
ccstd::unordered_map<int, AudioEngine::AudioInfo> AudioEngine::sAudioIDInfoMap;
|
||||
AudioEngineImpl *AudioEngine::sAudioEngineImpl = nullptr;
|
||||
// Decoder-only fallback instance, defined here to keep AudioDecoderManager
|
||||
// initialization separate from OpenAL initialization.
|
||||
AudioEngineImpl *AudioEngine::sDecoderImpl = nullptr;
|
||||
|
||||
float AudioEngine::sVolumeFactor = 1.0F;
|
||||
events::EnterBackground::Listener AudioEngine::sOnPauseListenerID;
|
||||
@@ -156,6 +159,9 @@ void AudioEngine::end() {
|
||||
delete sAudioEngineImpl;
|
||||
sAudioEngineImpl = nullptr;
|
||||
|
||||
delete sDecoderImpl;
|
||||
sDecoderImpl = nullptr;
|
||||
|
||||
delete sDefaultProfileHelper;
|
||||
sDefaultProfileHelper = nullptr;
|
||||
|
||||
@@ -587,12 +593,48 @@ bool AudioEngine::isEnabled() {
|
||||
return sIsEnabled;
|
||||
}
|
||||
|
||||
PCMHeader AudioEngine::getPCMHeader(const char *url) {
|
||||
lazyInit();
|
||||
return sAudioEngineImpl->getPCMHeader(url);
|
||||
AudioEngineImpl *AudioEngine::getDecoderImpl() {
|
||||
if (AudioEngine::sAudioEngineImpl != nullptr) {
|
||||
return AudioEngine::sAudioEngineImpl;
|
||||
}
|
||||
// Try full init first; if it succeeds we get OpenAL + decoder.
|
||||
AudioEngine::lazyInit();
|
||||
if (AudioEngine::sAudioEngineImpl != nullptr) {
|
||||
return AudioEngine::sAudioEngineImpl;
|
||||
}
|
||||
// On oalsoft platforms, PCM decoding via AudioDecoderManager works
|
||||
// independently of OpenAL — create a decoder-only fallback instance.
|
||||
// On Android/OpenHarmony and Apple, AudioEngineImpl::getPCMHeader/
|
||||
// getOriginalPCMBuffer dereferences _audioPlayerProvider/_engineEngine
|
||||
// which are only set up by init(). Returning nullptr here lets callers
|
||||
// fail gracefully instead of crashing.
|
||||
#if CC_PLATFORM == CC_PLATFORM_WINDOWS || CC_PLATFORM == CC_PLATFORM_OHOS || \
|
||||
CC_PLATFORM == CC_PLATFORM_LINUX || CC_PLATFORM == CC_PLATFORM_QNX
|
||||
if (AudioEngine::sDecoderImpl == nullptr) {
|
||||
AudioEngine::sDecoderImpl = ccnew AudioEngineImpl();
|
||||
AudioEngineImpl::initDecoder();
|
||||
}
|
||||
return AudioEngine::sDecoderImpl;
|
||||
#else
|
||||
return nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
PCMHeader AudioEngine::getPCMHeader(const char *url) {
|
||||
AudioEngineImpl *impl = AudioEngine::getDecoderImpl();
|
||||
if (impl == nullptr) {
|
||||
CC_LOG_WARNING("AudioEngine::getPCMHeader: audio engine unavailable, url: %s", url);
|
||||
return {};
|
||||
}
|
||||
return impl->getPCMHeader(url);
|
||||
}
|
||||
|
||||
ccstd::vector<uint8_t> AudioEngine::getOriginalPCMBuffer(const char *url, uint32_t channelID) {
|
||||
lazyInit();
|
||||
return sAudioEngineImpl->getOriginalPCMBuffer(url, channelID);
|
||||
AudioEngineImpl *impl = AudioEngine::getDecoderImpl();
|
||||
if (impl == nullptr) {
|
||||
CC_LOG_WARNING("AudioEngine::getOriginalPCMBuffer: audio engine unavailable, url: %s", url);
|
||||
return {};
|
||||
}
|
||||
return impl->getOriginalPCMBuffer(url, channelID);
|
||||
}
|
||||
} // namespace cc
|
||||
|
||||
@@ -426,6 +426,12 @@ void AudioEngineImpl::onResume() {
|
||||
}
|
||||
}
|
||||
|
||||
bool AudioEngineImpl::initDecoder() {
|
||||
// On Android the decoder infrastructure is set up by init().
|
||||
// This method exists so AudioEngine.cpp compiles uniformly across all platforms.
|
||||
return true;
|
||||
}
|
||||
|
||||
PCMHeader AudioEngineImpl::getPCMHeader(const char *url) {
|
||||
PCMHeader header{};
|
||||
ccstd::string fileFullPath = FileUtils::getInstance()->fullPathForFilename(url);
|
||||
|
||||
@@ -55,6 +55,7 @@ public:
|
||||
~AudioEngineImpl() override;
|
||||
|
||||
bool init();
|
||||
static bool initDecoder();
|
||||
int play2d(const ccstd::string &filePath, bool loop, float volume);
|
||||
void setVolume(int audioID, float volume);
|
||||
void setLoop(int audioID, bool loop);
|
||||
|
||||
@@ -43,6 +43,7 @@ public:
|
||||
~AudioEngineImpl();
|
||||
|
||||
bool init();
|
||||
static bool initDecoder();
|
||||
int play2d(const ccstd::string &fileFullPath, bool loop, float volume);
|
||||
void setVolume(int audioID, float volume);
|
||||
void setLoop(int audioID, bool loop);
|
||||
|
||||
@@ -632,6 +632,12 @@ bool AudioEngineImpl::checkAudioIdValid(int audioID) {
|
||||
return _audioPlayers.find(audioID) != _audioPlayers.end();
|
||||
}
|
||||
|
||||
bool AudioEngineImpl::initDecoder() {
|
||||
// On Apple the decoder infrastructure is set up by init().
|
||||
// This method exists so AudioEngine.cpp compiles uniformly across all platforms.
|
||||
return true;
|
||||
}
|
||||
|
||||
PCMHeader AudioEngineImpl::getPCMHeader(const char *url){
|
||||
PCMHeader header {};
|
||||
auto itr = _audioCaches.find(url);
|
||||
|
||||
@@ -339,6 +339,19 @@ protected:
|
||||
static void pauseAll(ccstd::vector<int> *pausedAudioIDs);
|
||||
static void resumeAll(ccstd::vector<int> *pausedAudioIDs);
|
||||
|
||||
/**
|
||||
* @brief Get Audio Decoder
|
||||
*
|
||||
* Strategy:
|
||||
* 1. If the full impl (with OpenAL) is already alive, reuse it (cache + decoder both available).
|
||||
* 2. If OpenAL init has not been attempted yet, try lazyInit() so that a successful OpenAL
|
||||
* environment still gets the full impl (keeps _audioCaches coherent with play2d).
|
||||
* 3. Only fall back to the decoder-only sDecoderImpl when lazyInit() has failed
|
||||
* (alcOpenDevice returned null, headless / OHOS / CI environments).
|
||||
* @return The impl instance to use for PCM decoding.
|
||||
*/
|
||||
static AudioEngineImpl *getDecoderImpl();
|
||||
|
||||
struct ProfileHelper {
|
||||
AudioProfile profile;
|
||||
|
||||
@@ -382,6 +395,10 @@ protected:
|
||||
static ProfileHelper *sDefaultProfileHelper;
|
||||
|
||||
static AudioEngineImpl *sAudioEngineImpl;
|
||||
// Decoder-only fallback instance used when OpenAL is unavailable.
|
||||
// getPCMHeader / getOriginalPCMBuffer do not depend on OpenAL and use this
|
||||
// instance directly instead of going through lazyInit().
|
||||
static AudioEngineImpl *sDecoderImpl;
|
||||
|
||||
class AudioEngineThreadPool;
|
||||
static AudioEngineThreadPool *sThreadPool;
|
||||
|
||||
@@ -62,7 +62,7 @@
|
||||
// log, CC_LOG_DEBUG aren't threadsafe, since we uses sub threads for parsing pcm data, threadsafe log output
|
||||
// is needed. Define the following macros (ALOGV, ALOGD, ALOGI, ALOGW, ALOGE) for threadsafe log output.
|
||||
|
||||
//IDEA: Move _winLog, winLog to a separated file
|
||||
// IDEA: Move _winLog, winLog to a separate file
|
||||
static void _winLog(const char *format, va_list args) {
|
||||
static const int MAX_LOG_LENGTH = 16 * 1024;
|
||||
int bufferSize = MAX_LOG_LENGTH;
|
||||
@@ -153,31 +153,50 @@ AudioEngineImpl::~AudioEngineImpl() {
|
||||
AudioDecoderManager::destroy();
|
||||
}
|
||||
|
||||
bool AudioEngineImpl::initDecoder() {
|
||||
return AudioDecoderManager::init();
|
||||
}
|
||||
|
||||
bool AudioEngineImpl::init() {
|
||||
bool ret = false;
|
||||
do {
|
||||
sALDevice = alcOpenDevice(nullptr);
|
||||
|
||||
if (sALDevice) {
|
||||
alGetError();
|
||||
sALContext = alcCreateContext(sALDevice, nullptr);
|
||||
alcMakeContextCurrent(sALContext);
|
||||
|
||||
alGenSources(MAX_AUDIOINSTANCES, _alSources);
|
||||
auto alError = alGetError();
|
||||
if (alError != AL_NO_ERROR) {
|
||||
CC_LOG_ERROR("%s:generating sources failed! error = %x\n", __FUNCTION__, alError);
|
||||
break;
|
||||
}
|
||||
|
||||
for (unsigned int src : _alSources) {
|
||||
_alSourceUsed[src] = false;
|
||||
}
|
||||
|
||||
_scheduler = CC_CURRENT_ENGINE()->getScheduler();
|
||||
ret = AudioDecoderManager::init();
|
||||
CC_LOG_DEBUG("OpenAL was initialized successfully!");
|
||||
if (sALDevice == nullptr) {
|
||||
// alcGetError(nullptr) is valid when no device is open
|
||||
ALCenum alcErr = alcGetError(nullptr);
|
||||
CC_LOG_ERROR("%s: alcOpenDevice failed, ALC error = 0x%x", __FUNCTION__, alcErr);
|
||||
break;
|
||||
}
|
||||
|
||||
alGetError();
|
||||
sALContext = alcCreateContext(sALDevice, nullptr);
|
||||
if (sALContext == nullptr) {
|
||||
ALCenum alcErr = alcGetError(sALDevice);
|
||||
CC_LOG_ERROR("%s: alcCreateContext failed, ALC error = 0x%x", __FUNCTION__, alcErr);
|
||||
break;
|
||||
}
|
||||
|
||||
alcMakeContextCurrent(sALContext);
|
||||
|
||||
std::fill(std::begin(_alSources), std::end(_alSources), 0);
|
||||
|
||||
alGenSources(MAX_AUDIOINSTANCES, _alSources);
|
||||
auto alError = alGetError();
|
||||
if (alError != AL_NO_ERROR) {
|
||||
CC_LOG_ERROR("%s:generating sources failed! error = %x\n", __FUNCTION__, alError);
|
||||
alcMakeContextCurrent(nullptr);
|
||||
alcDestroyContext(sALContext);
|
||||
sALContext = nullptr;
|
||||
break;
|
||||
}
|
||||
|
||||
for (unsigned int src : _alSources) {
|
||||
_alSourceUsed[src] = false;
|
||||
}
|
||||
|
||||
_scheduler = CC_CURRENT_ENGINE()->getScheduler();
|
||||
ret = initDecoder();
|
||||
CC_LOG_DEBUG("OpenAL was initialized successfully!");
|
||||
} while (false);
|
||||
|
||||
return ret;
|
||||
@@ -264,7 +283,7 @@ int AudioEngineImpl::play2d(const ccstd::string &filePath, bool loop, float volu
|
||||
}
|
||||
|
||||
void AudioEngineImpl::play2dImpl(AudioCache *cache, int audioID) {
|
||||
//Note: It may bn in sub thread or main thread :(
|
||||
// Note: It may be in sub thread or main thread :(
|
||||
if (!*cache->_isDestroyed && cache->_state == AudioCache::State::READY) {
|
||||
_threadMutex.lock();
|
||||
auto playerIt = _audioPlayers.find(audioID);
|
||||
|
||||
@@ -45,6 +45,9 @@ public:
|
||||
~AudioEngineImpl() override;
|
||||
|
||||
bool init();
|
||||
// Initialize only the PCM decoder subsystem (AudioDecoderManager).
|
||||
// Does not require an OpenAL device. Safe to call when init() failed.
|
||||
static bool initDecoder();
|
||||
int play2d(const ccstd::string &filePath, bool loop, float volume);
|
||||
void setVolume(int audioID, float volume);
|
||||
void setLoop(int audioID, bool loop);
|
||||
|
||||
@@ -70,20 +70,37 @@ static bool js_assets_SimpleTexture_registerListeners(se::State &s) // NOLINT(re
|
||||
{
|
||||
auto *cobj = SE_THIS_OBJECT<cc::SimpleTexture>(s);
|
||||
SE_PRECONDITION2(cobj, false, "Invalid Native Object");
|
||||
auto *thisObj = s.thisObject();
|
||||
|
||||
cobj->on<cc::SimpleTexture::TextureUpdated>([thisObj](cc::SimpleTexture * /*emitter*/, cc::gfx::Texture *texture) {
|
||||
// NOTE: resolve the live JS wrapper from the native pointer at emit time instead of capturing
|
||||
// `s.thisObject()`. A native texture can outlive its JS wrapper (e.g. builtin textures kept alive
|
||||
// by builtinResMgr), so a captured raw se::Object* would dangle and a later event would call into a
|
||||
// dead object. Skip when no live wrapper exists. See registerPassesUpdatedListener below for details.
|
||||
cobj->on<cc::SimpleTexture::TextureUpdated>([](cc::SimpleTexture *emitter, cc::gfx::Texture *texture) {
|
||||
auto *se = se::ScriptEngine::getInstance();
|
||||
if (se == nullptr || !se->isValid() || se->isInCleanup() || se->isGarbageCollecting()) {
|
||||
return;
|
||||
}
|
||||
se::AutoHandleScope hs;
|
||||
se::Value arg0;
|
||||
nativevalue_to_se(texture, arg0, nullptr);
|
||||
se::ScriptEngine::getInstance()->callFunction(thisObj, "_onGFXTextureUpdated", 1, &arg0);
|
||||
se::Object *jsObject = se::NativePtrToObjectMap::findFirst(emitter);
|
||||
if (jsObject != nullptr) {
|
||||
se::Value arg0;
|
||||
nativevalue_to_se(texture, arg0, nullptr);
|
||||
se->callFunction(jsObject, "_onGFXTextureUpdated", 1, &arg0);
|
||||
}
|
||||
});
|
||||
|
||||
cobj->on<cc::SimpleTexture::AfterAssignImage>([thisObj](cc::SimpleTexture * /*emitter*/, cc::ImageAsset *image) {
|
||||
cobj->on<cc::SimpleTexture::AfterAssignImage>([](cc::SimpleTexture *emitter, cc::ImageAsset *image) {
|
||||
auto *se = se::ScriptEngine::getInstance();
|
||||
if (se == nullptr || !se->isValid() || se->isInCleanup() || se->isGarbageCollecting()) {
|
||||
return;
|
||||
}
|
||||
se::AutoHandleScope hs;
|
||||
se::Value arg0;
|
||||
nativevalue_to_se(image, arg0, nullptr);
|
||||
se::ScriptEngine::getInstance()->callFunction(thisObj, "_onAfterAssignImage", 1, &arg0);
|
||||
se::Object *jsObject = se::NativePtrToObjectMap::findFirst(emitter);
|
||||
if (jsObject != nullptr) {
|
||||
se::Value arg0;
|
||||
nativevalue_to_se(image, arg0, nullptr);
|
||||
se->callFunction(jsObject, "_onAfterAssignImage", 1, &arg0);
|
||||
}
|
||||
});
|
||||
|
||||
return true;
|
||||
@@ -94,12 +111,20 @@ static bool js_assets_TextureBase_registerGFXSamplerUpdatedListener(se::State &s
|
||||
{
|
||||
auto *cobj = SE_THIS_OBJECT<cc::TextureBase>(s);
|
||||
SE_PRECONDITION2(cobj, false, "Invalid Native Object");
|
||||
auto *thisObj = s.thisObject();
|
||||
cobj->on<cc::TextureBase::SamplerUpdated>([thisObj](cc::TextureBase * /*emitter*/, cc::gfx::Sampler *sampler) {
|
||||
// Resolve the live JS wrapper at emit time (see SimpleTexture/Material listeners above) so the
|
||||
// callback never targets a wrapper that has already been GC'd while the native object lives on.
|
||||
cobj->on<cc::TextureBase::SamplerUpdated>([](cc::TextureBase *emitter, cc::gfx::Sampler *sampler) {
|
||||
auto *se = se::ScriptEngine::getInstance();
|
||||
if (se == nullptr || !se->isValid() || se->isInCleanup() || se->isGarbageCollecting()) {
|
||||
return;
|
||||
}
|
||||
se::AutoHandleScope hs;
|
||||
se::Value arg0;
|
||||
nativevalue_to_se(sampler, arg0, nullptr);
|
||||
se::ScriptEngine::getInstance()->callFunction(thisObj, "_onGFXSamplerUpdated", 1, &arg0);
|
||||
se::Object *jsObject = se::NativePtrToObjectMap::findFirst(emitter);
|
||||
if (jsObject != nullptr) {
|
||||
se::Value arg0;
|
||||
nativevalue_to_se(sampler, arg0, nullptr);
|
||||
se->callFunction(jsObject, "_onGFXSamplerUpdated", 1, &arg0);
|
||||
}
|
||||
});
|
||||
|
||||
return true;
|
||||
@@ -110,10 +135,31 @@ static bool js_assets_Material_registerPassesUpdatedListener(se::State &s) // NO
|
||||
{
|
||||
auto *cobj = SE_THIS_OBJECT<cc::Material>(s);
|
||||
SE_PRECONDITION2(cobj, false, "Invalid Native Object");
|
||||
auto *thisObj = s.thisObject();
|
||||
cobj->on<cc::Material::PassesUpdated>([thisObj](cc::Material * /*emitter*/) {
|
||||
// NOTE: Do NOT capture the JS wrapper (`s.thisObject()`) here. A native Material can outlive
|
||||
// its JS wrapper -- e.g. builtin "rt-*" materials are kept alive by builtinResMgr's IntrusivePtr
|
||||
// while their JS wrapper is GC'd after the owning sprite is destroyed. A captured raw se::Object*
|
||||
// would then dangle, and a later PassesUpdated (emitted from Material::update()/doDestroy()) would
|
||||
// invoke `_onPassesUpdated` on a dead object, producing:
|
||||
// [SE_ERROR] _onPassesUpdated is not a function: undefined
|
||||
// Instead resolve the *current* live JS wrapper from the native pointer at emit time, and skip
|
||||
// when none exists (a freshly recreated wrapper syncs passes lazily via its `passes` getter).
|
||||
//
|
||||
// The engine-state guard below is also mandatory: PassesUpdated can be emitted from
|
||||
// Material::update()/copy()/doDestroy() while the script engine is being torn down (editor
|
||||
// engine restart / scene reload) or while a GC is in progress. In those windows `findFirst`
|
||||
// may still return an se::Object whose V8 persistent now points at a freed object, and calling
|
||||
// into it crashes inside ObjectWrap::handle() (`Local<Object>::New` on a dangling handle).
|
||||
// Never touch JS during cleanup or GC -- see native/cocos/bindings/docs/JSB2.0-learning.
|
||||
cobj->on<cc::Material::PassesUpdated>([](cc::Material *emitter) {
|
||||
auto *se = se::ScriptEngine::getInstance();
|
||||
if (se == nullptr || !se->isValid() || se->isInCleanup() || se->isGarbageCollecting()) {
|
||||
return;
|
||||
}
|
||||
se::AutoHandleScope hs;
|
||||
se::ScriptEngine::getInstance()->callFunction(thisObj, "_onPassesUpdated", 0, nullptr);
|
||||
se::Object *jsObject = se::NativePtrToObjectMap::findFirst(emitter);
|
||||
if (jsObject != nullptr) {
|
||||
se->callFunction(jsObject, "_onPassesUpdated", 0, nullptr);
|
||||
}
|
||||
});
|
||||
|
||||
return true;
|
||||
|
||||
@@ -146,10 +146,19 @@ bool jsb_register_all_modules() {
|
||||
se::ScriptEngine *se = se::ScriptEngine::getInstance();
|
||||
|
||||
se->addBeforeCleanupHook([se]() {
|
||||
#if (CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS)
|
||||
// REMOVED: se->garbageCollect()
|
||||
// Reason: Calling GC before Object::cleanup() causes MarkCompact to traverse
|
||||
// live JSTypedArrays whose external BackingStore data has already been freed
|
||||
// by AudioEngine::end(). The safe GC in ScriptEngine::cleanup() (step 5,
|
||||
// after Object::cleanup() releases all persistent handles) is sufficient.
|
||||
cc::DeferredReleasePool::clear();
|
||||
#else
|
||||
se->garbageCollect();
|
||||
cc::DeferredReleasePool::clear();
|
||||
se->garbageCollect();
|
||||
cc::DeferredReleasePool::clear();
|
||||
#endif // (CC_PLATFORM == CC_PLATFORM_IOS || CC_PLATFORM == CC_PLATFORM_MACOS || CC_PLATFORM == CC_PLATFORM_ANDROID || CC_PLATFORM == CC_PLATFORM_OHOS)
|
||||
});
|
||||
|
||||
se->addRegisterCallback(jsb_register_global_variables);
|
||||
|
||||
@@ -699,7 +699,7 @@ static bool js_Model_setInstancedAttribute(se::State &s) // NOLINT(readability-i
|
||||
value[i] = dataVal.toFloat();
|
||||
}
|
||||
|
||||
cobj->setInstancedAttribute(name, value);
|
||||
cobj->setInstancedAttribute(name, std::move(value));
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
/****************************************************************************
|
||||
Copyright (c) 2022-2025 Xiamen Yaji Software Co., Ltd.
|
||||
Copyright (c) 2022-2026 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
http://www.cocos.com
|
||||
|
||||
@@ -23,11 +23,11 @@ THE SOFTWARE.
|
||||
****************************************************************************/
|
||||
#pragma once
|
||||
|
||||
#define COCOS_MAJOR_VERSION 3
|
||||
#define COCOS_MINJOR_VERSION 8
|
||||
#define COCOS_PATCH_VERSION 8
|
||||
#define COCOS_VERSION_STRING "3.8.8"
|
||||
#define COCOS_MAJOR_VERSION 4
|
||||
#define COCOS_MINJOR_VERSION 0
|
||||
#define COCOS_PATCH_VERSION 0
|
||||
#define COCOS_VERSION_STRING "4.0.0"
|
||||
#define COCOS_VERSION_DEFINED 1
|
||||
#define COCOS_VERSION 30808
|
||||
#define COCOS_VERSION 40000
|
||||
|
||||
// #define COCOS_PRE_RELEASE "release"
|
||||
// #define COCOS_PRE_RELEASE "alpha"
|
||||
|
||||
@@ -623,6 +623,7 @@ ccstd::unordered_map<uint32_t, ccstd::string> debugInfos = {
|
||||
{ 16417, "'clearTrack' interface can not be invoked in cached mode." },
|
||||
{ 16418, "Debug bones or slots is invalid in cached mode." },
|
||||
{ 16419, "Spine version not supported." },
|
||||
{ 16420, "Start time must bigger than end time." },
|
||||
|
||||
};
|
||||
}//namespace cc
|
||||
|
||||
@@ -55,7 +55,18 @@ MeshBuffer *MiddlewareManager::getMeshBuffer(int format) {
|
||||
}
|
||||
|
||||
void MiddlewareManager::updateOperateCache() {
|
||||
for (const auto &op : _operateCacheQueue) {
|
||||
if (_operateCacheQueue.empty()) return;
|
||||
|
||||
ccstd::vector<IMiddleware*> seen;
|
||||
ccstd::vector<std::pair<IMiddleware*, bool>> finalOperations;
|
||||
for (auto it = _operateCacheQueue.rbegin(); it != _operateCacheQueue.rend(); ++it) {
|
||||
if (std::find(seen.begin(), seen.end(), it->first) == seen.end()) {
|
||||
seen.push_back(it->first);
|
||||
finalOperations.emplace_back(it->first, it->second);
|
||||
}
|
||||
}
|
||||
|
||||
for (const auto &op : finalOperations) {
|
||||
IMiddleware *editor = op.first;
|
||||
bool isAddOperation = op.second;
|
||||
|
||||
@@ -88,12 +99,19 @@ void MiddlewareManager::update(float dt) {
|
||||
}
|
||||
|
||||
void MiddlewareManager::render(float dt) {
|
||||
// Object._deferredDestroy is called after component update in Director.tick and before emitting BEFORE_DRAW event in which MiddlewareManager::render is invoked,
|
||||
// so the native object may be released here and it needs to be erased from _updateList.
|
||||
for (auto &iter : _operateCacheQueue) {
|
||||
auto it = std::find(_updateList.begin(), _updateList.end(), iter.first);
|
||||
if (!iter.second && it != _updateList.end()) {
|
||||
_updateList.erase(it);
|
||||
ccstd::vector<IMiddleware*> skipRenderList;
|
||||
if (!_operateCacheQueue.empty()) {
|
||||
ccstd::vector<IMiddleware*> seen;
|
||||
// Object._deferredDestroy is called after component update in Director.tick and before emitting BEFORE_DRAW event in which MiddlewareManager::render is invoked,
|
||||
// so the native object may be released here.
|
||||
// We shouldn't execute editor->render(dt) if it's already removed in _operateCacheQueue.
|
||||
for (auto it = _operateCacheQueue.rbegin(); it != _operateCacheQueue.rend(); ++it) {
|
||||
if (std::find(seen.begin(), seen.end(), it->first) == seen.end()) {
|
||||
seen.push_back(it->first);
|
||||
if (!it->second) {
|
||||
skipRenderList.push_back(it->first);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -106,6 +124,9 @@ void MiddlewareManager::render(float dt) {
|
||||
|
||||
for (size_t i = 0, len = _updateList.size(); i < len; ++i) {
|
||||
auto *editor = _updateList[i];
|
||||
if (!skipRenderList.empty() && std::find(skipRenderList.begin(), skipRenderList.end(), editor) != skipRenderList.end()) {
|
||||
continue;
|
||||
}
|
||||
editor->render(dt);
|
||||
}
|
||||
|
||||
|
||||
@@ -1033,6 +1033,7 @@ bool SkeletonRenderer::setAttachment(const std::string &slotName, const char *at
|
||||
|
||||
void SkeletonRenderer::setUseTint(bool enabled) {
|
||||
_useTint = enabled;
|
||||
_needClearMaterialCaches = true;
|
||||
}
|
||||
|
||||
#if CC_USE_SPINE_3_8
|
||||
|
||||
@@ -33,6 +33,7 @@ using SPVectorIkConstraintPtr = Vector<IkConstraint*>;
|
||||
using SPVectorIkConstraintDataPtr = Vector<IkConstraintData*>;
|
||||
using SPVectorTransformConstraintPtr = Vector<TransformConstraint*>;
|
||||
using SPVectorPathConstraintPtr = Vector<PathConstraint*>;
|
||||
using SPVectorPhysicsConstraintPtr = Vector<PhysicsConstraint*>;
|
||||
using SPVectorTimelinePtr = Vector<Timeline*>;
|
||||
using SPVectorTrackEntryPtr = Vector<TrackEntry*>;
|
||||
using SPVectorUpdatablePtr = Vector<Updatable*>;
|
||||
@@ -207,6 +208,8 @@ DEFINE_ALLOW_RAW_POINTER(TrackEntry)
|
||||
DEFINE_ALLOW_RAW_POINTER(IkConstraintData)
|
||||
DEFINE_ALLOW_RAW_POINTER(PathConstraintData)
|
||||
DEFINE_ALLOW_RAW_POINTER(TransformConstraintData)
|
||||
DEFINE_ALLOW_RAW_POINTER(PhysicsConstraintData)
|
||||
DEFINE_ALLOW_RAW_POINTER(PhysicsConstraint)
|
||||
DEFINE_ALLOW_RAW_POINTER(SPVectorUnsignedShort)
|
||||
DEFINE_ALLOW_RAW_POINTER(SPVectorFloat)
|
||||
DEFINE_ALLOW_RAW_POINTER(SPVectorEventPtr)
|
||||
@@ -516,7 +519,7 @@ EMSCRIPTEN_BINDINGS(spine) {
|
||||
REGISTER_SPINE_ENUM(TextureFilter);
|
||||
REGISTER_SPINE_ENUM(TextureWrap);
|
||||
REGISTER_SPINE_ENUM(AttachmentType);
|
||||
|
||||
REGISTER_SPINE_ENUM(Physics);
|
||||
|
||||
REGISTER_SPINE_VECTOR(SPVectorDebugShape, false);
|
||||
|
||||
@@ -544,7 +547,9 @@ EMSCRIPTEN_BINDINGS(spine) {
|
||||
REGISTER_SPINE_VECTOR(SPVectorIkConstraintDataPtr, false);
|
||||
REGISTER_SPINE_VECTOR(SPVectorTransformConstraintPtr, false);
|
||||
REGISTER_SPINE_VECTOR(SPVectorPathConstraintPtr, false);
|
||||
REGISTER_SPINE_VECTOR(SPVectorTimelinePtr, true); // .set used in Animation constructor
|
||||
REGISTER_SPINE_VECTOR(SPVectorTimelinePtr, true); // .set used in Animation constructor
|
||||
REGISTER_SPINE_VECTOR(SPVectorPhysicsConstraintDataPtr, false);
|
||||
REGISTER_SPINE_VECTOR(SPVectorPhysicsConstraintPtr, false);
|
||||
REGISTER_SPINE_VECTOR(SPVectorTrackEntryPtr, false);
|
||||
REGISTER_SPINE_VECTOR(SPVectorUpdatablePtr, false);
|
||||
REGISTER_SPINE_VECTOR(SPVectorSkinEntryPtr, false);
|
||||
@@ -879,6 +884,64 @@ EMSCRIPTEN_BINDINGS(spine) {
|
||||
.property("mixScaleY", &TransformConstraint::getMixScaleY)
|
||||
.property("mixShearY", &TransformConstraint::getMixShearY);
|
||||
|
||||
class_<PhysicsConstraintData, base<ConstraintData>>("PhysicsConstraintData")
|
||||
.constructor<const String &>()
|
||||
.property("bone", &PhysicsConstraintData::getBone)
|
||||
.property("x", &PhysicsConstraintData::getX, &PhysicsConstraintData::setX)
|
||||
.property("y", &PhysicsConstraintData::getY, &PhysicsConstraintData::setY)
|
||||
.property("rotate", &PhysicsConstraintData::getRotate, &PhysicsConstraintData::setRotate)
|
||||
.property("scaleX", &PhysicsConstraintData::getScaleX, &PhysicsConstraintData::setScaleX)
|
||||
.property("shearX", &PhysicsConstraintData::getShearX, &PhysicsConstraintData::setShearX)
|
||||
.property("limit", &PhysicsConstraintData::getLimit, &PhysicsConstraintData::setLimit)
|
||||
.property("step", &PhysicsConstraintData::getStep, &PhysicsConstraintData::setStep)
|
||||
.property("inertia", &PhysicsConstraintData::getInertia, &PhysicsConstraintData::setInertia)
|
||||
.property("strength", &PhysicsConstraintData::getStrength, &PhysicsConstraintData::setStrength)
|
||||
.property("damping", &PhysicsConstraintData::getDamping, &PhysicsConstraintData::setDamping)
|
||||
.property("massInverse", &PhysicsConstraintData::getMassInverse, &PhysicsConstraintData::setMassInverse)
|
||||
.property("wind", &PhysicsConstraintData::getWind, &PhysicsConstraintData::setWind)
|
||||
.property("gravity", &PhysicsConstraintData::getGravity, &PhysicsConstraintData::setGravity)
|
||||
.property("mix", &PhysicsConstraintData::getMix, &PhysicsConstraintData::setMix)
|
||||
.property("inertiaGlobal", &PhysicsConstraintData::isInertiaGlobal, &PhysicsConstraintData::setInertiaGlobal)
|
||||
.property("strengthGlobal", &PhysicsConstraintData::isStrengthGlobal, &PhysicsConstraintData::setStrengthGlobal)
|
||||
.property("dampingGlobal", &PhysicsConstraintData::isDampingGlobal, &PhysicsConstraintData::setDampingGlobal)
|
||||
.property("massGlobal", &PhysicsConstraintData::isMassGlobal, &PhysicsConstraintData::setMassGlobal)
|
||||
.property("windGlobal", &PhysicsConstraintData::isWindGlobal, &PhysicsConstraintData::setWindGlobal)
|
||||
.property("gravityGlobal", &PhysicsConstraintData::isGravityGlobal, &PhysicsConstraintData::setGravityGlobal)
|
||||
.property("mixGlobal", &PhysicsConstraintData::isMixGlobal, &PhysicsConstraintData::setMixGlobal);
|
||||
|
||||
class_<PhysicsConstraint, base<Updatable>>("PhysicsConstraint")
|
||||
.constructor<PhysicsConstraintData &, Skeleton &>()
|
||||
.property("data", GETTER_RVAL_TO_PTR(PhysicsConstraint, getData, PhysicsConstraintData*))
|
||||
.property("bone", &PhysicsConstraint::getBone, &PhysicsConstraint::setBone)
|
||||
.property("inertia", &PhysicsConstraint::getInertia, &PhysicsConstraint::setInertia)
|
||||
.property("strength", &PhysicsConstraint::getStrength, &PhysicsConstraint::setStrength)
|
||||
.property("damping", &PhysicsConstraint::getDamping, &PhysicsConstraint::setDamping)
|
||||
.property("massInverse", &PhysicsConstraint::getMassInverse, &PhysicsConstraint::setMassInverse)
|
||||
.property("wind", &PhysicsConstraint::getWind, &PhysicsConstraint::setWind)
|
||||
.property("gravity", &PhysicsConstraint::getGravity, &PhysicsConstraint::setGravity)
|
||||
.property("mix", &PhysicsConstraint::getMix, &PhysicsConstraint::setMix)
|
||||
.property("_reset", &PhysicsConstraint::getReset, &PhysicsConstraint::setReset)
|
||||
.property("ux", &PhysicsConstraint::getUx, &PhysicsConstraint::setUx)
|
||||
.property("uy", &PhysicsConstraint::getUy, &PhysicsConstraint::setUy)
|
||||
.property("cx", &PhysicsConstraint::getCx, &PhysicsConstraint::setCx)
|
||||
.property("cy", &PhysicsConstraint::getCy, &PhysicsConstraint::setCy)
|
||||
.property("tx", &PhysicsConstraint::getTx, &PhysicsConstraint::setTx)
|
||||
.property("ty", &PhysicsConstraint::getTy, &PhysicsConstraint::setTy)
|
||||
.property("xOffset", &PhysicsConstraint::getXOffset, &PhysicsConstraint::setXOffset)
|
||||
.property("xVelocity", &PhysicsConstraint::getXVelocity, &PhysicsConstraint::setXVelocity)
|
||||
.property("yOffset", &PhysicsConstraint::getYOffset, &PhysicsConstraint::setYOffset)
|
||||
.property("yVelocity", &PhysicsConstraint::getYVelocity, &PhysicsConstraint::setYVelocity)
|
||||
.property("rotateOffset", &PhysicsConstraint::getRotateOffset, &PhysicsConstraint::setRotateOffset)
|
||||
.property("rotateVelocity", &PhysicsConstraint::getRotateVelocity, &PhysicsConstraint::setRotateVelocity)
|
||||
.property("scaleOffset", &PhysicsConstraint::getScaleOffset, &PhysicsConstraint::setScaleOffset)
|
||||
.property("scaleVelocity", &PhysicsConstraint::getScaleVelocity, &PhysicsConstraint::setScaleVelocity)
|
||||
.property("remaining", &PhysicsConstraint::getRemaining, &PhysicsConstraint::setRemaining)
|
||||
.property("lastTime", &PhysicsConstraint::getLastTime, &PhysicsConstraint::setLastTime)
|
||||
.function("reset", &PhysicsConstraint::reset)
|
||||
.function("setToSetupPose", &PhysicsConstraint::setToSetupPose)
|
||||
.function("translate", &PhysicsConstraint::translate)
|
||||
.function("rotate", &PhysicsConstraint::rotate);
|
||||
|
||||
class_<Bone, base<Updatable>>("Bone")
|
||||
.constructor<BoneData &, Skeleton &, Bone *>()
|
||||
.property("data", GETTER_RVAL_TO_PTR(Bone, getData, BoneData*))
|
||||
@@ -1058,7 +1121,7 @@ EMSCRIPTEN_BINDINGS(spine) {
|
||||
.function("findAnimation", &SkeletonData::findAnimation, allow_raw_pointers())
|
||||
.function("findIkConstraint", &SkeletonData::findIkConstraint, allow_raw_pointers())
|
||||
.function("findTransformConstraint", &SkeletonData::findTransformConstraint, allow_raw_pointers())
|
||||
.function("findPhysicsConstraint", &SkeletonData::findPathConstraint, allow_raw_pointers())
|
||||
.function("findPhysicsConstraint", &SkeletonData::findPhysicsConstraint, allow_raw_pointers())
|
||||
.function("findPathConstraint", &SkeletonData::findPathConstraint, allow_raw_pointers());
|
||||
|
||||
class_<Animation>("Animation")
|
||||
@@ -1295,6 +1358,8 @@ EMSCRIPTEN_BINDINGS(spine) {
|
||||
return &obj.getTransformConstraints(); }), allow_raw_pointer<SPVectorTransformConstraintPtr>())
|
||||
.function("getPathConstraints", optional_override([](Skeleton &obj){
|
||||
return &obj.getPathConstraints(); }), allow_raw_pointer<SPVectorPathConstraintPtr>())
|
||||
.function("getPhysicsConstraints", optional_override([](Skeleton &obj){
|
||||
return &obj.getPhysicsConstraints(); }), allow_raw_pointer<SPVectorPhysicsConstraintPtr>())
|
||||
.function("getUpdateCacheList", optional_override([](Skeleton &obj){
|
||||
return &obj.getUpdateCacheList(); }), allow_raw_pointer<SPVectorUpdatablePtr>())
|
||||
.property("skin", &Skeleton::_skin)
|
||||
@@ -1322,6 +1387,7 @@ EMSCRIPTEN_BINDINGS(spine) {
|
||||
.function("findIkConstraint", &Skeleton::findIkConstraint, allow_raw_pointers())
|
||||
.function("findTransformConstraint", &Skeleton::findTransformConstraint, allow_raw_pointers())
|
||||
.function("findPathConstraint", &Skeleton::findPathConstraint, allow_raw_pointers())
|
||||
.function("findPhysicsConstraint", &Skeleton::findPhysicsConstraint, allow_raw_pointers())
|
||||
//.function("getBounds", optional_override([](Skeleton &obj, &outX, ) {}), allow_raw_pointers())
|
||||
.function("update", &Skeleton::update);
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
#import <Foundation/Foundation.h>
|
||||
#include "application/ApplicationManager.h"
|
||||
#include "base/memory/Memory.h"
|
||||
#include "base/std/container/queue.h"
|
||||
#include "base/std/container/list.h"
|
||||
#include "base/UTF8.h"
|
||||
#include "network/Downloader.h"
|
||||
#include "platform/FileUtils.h"
|
||||
@@ -54,7 +54,8 @@
|
||||
@interface DownloaderAppleImpl : NSObject <NSURLSessionDataDelegate, NSURLSessionDownloadDelegate> {
|
||||
const cc::network::DownloaderApple *_outer;
|
||||
cc::network::DownloaderHints _hints;
|
||||
ccstd::queue<NSURLSessionTask *> _taskQueue;
|
||||
ccstd::list<NSURLSessionTask *> _waitingList;
|
||||
int _runningCount;
|
||||
}
|
||||
@property (nonatomic, strong) NSURLSession *downloadSession;
|
||||
@property (nonatomic, strong) NSMutableDictionary *taskDict; // ocTask: DownloadTaskWrapper
|
||||
@@ -203,6 +204,7 @@ void DownloaderApple::abort(const std::unique_ptr<IDownloadTask> &task) {
|
||||
_hints = hints;
|
||||
// create task dictionary
|
||||
self.taskDict = [NSMutableDictionary dictionary];
|
||||
_runningCount = 0;
|
||||
|
||||
#if CC_PLATFORM == CC_PLATFORM_IOS
|
||||
// create backgroundSession for iOS to support background download
|
||||
@@ -264,11 +266,11 @@ void DownloaderApple::abort(const std::unique_ptr<IDownloadTask> &task) {
|
||||
[self.taskDict setObject:taskWrapper forKey:ocTask];
|
||||
[taskWrapper release];
|
||||
|
||||
if (_taskQueue.size() < _hints.countOfMaxProcessingTasks) {
|
||||
if (_runningCount < _hints.countOfMaxProcessingTasks) {
|
||||
[ocTask resume];
|
||||
_taskQueue.push(nil);
|
||||
_runningCount++;
|
||||
} else {
|
||||
_taskQueue.push(ocTask);
|
||||
_waitingList.push_back(ocTask);
|
||||
}
|
||||
return ocTask;
|
||||
};
|
||||
@@ -315,11 +317,11 @@ void DownloaderApple::abort(const std::unique_ptr<IDownloadTask> &task) {
|
||||
[self.taskDict setObject:taskWrapper forKey:ocTask];
|
||||
[taskWrapper release];
|
||||
|
||||
if (_taskQueue.size() < _hints.countOfMaxProcessingTasks) {
|
||||
if (_runningCount < _hints.countOfMaxProcessingTasks) {
|
||||
[ocTask resume];
|
||||
_taskQueue.push(nil);
|
||||
_runningCount++;
|
||||
} else {
|
||||
_taskQueue.push(ocTask);
|
||||
_waitingList.push_back(ocTask);
|
||||
}
|
||||
return ocTask;
|
||||
};
|
||||
@@ -390,8 +392,8 @@ void DownloaderApple::abort(const std::unique_ptr<IDownloadTask> &task) {
|
||||
}
|
||||
_outer = nullptr;
|
||||
|
||||
while (!_taskQueue.empty())
|
||||
_taskQueue.pop();
|
||||
_waitingList.clear();
|
||||
_runningCount = 0;
|
||||
|
||||
[self.downloadSession invalidateAndCancel];
|
||||
[self release];
|
||||
@@ -518,12 +520,18 @@ void DownloaderApple::abort(const std::unique_ptr<IDownloadTask> &task) {
|
||||
}
|
||||
[self.taskDict removeObjectForKey:task];
|
||||
|
||||
while (!_taskQueue.empty() && _taskQueue.front() == nil) {
|
||||
_taskQueue.pop();
|
||||
auto it = std::find(_waitingList.begin(), _waitingList.end(), task);
|
||||
if (it != _waitingList.end()) {
|
||||
_waitingList.erase(it);
|
||||
} else {
|
||||
_runningCount--;
|
||||
}
|
||||
if (!_taskQueue.empty()) {
|
||||
[_taskQueue.front() resume];
|
||||
_taskQueue.pop();
|
||||
|
||||
if (_runningCount < _hints.countOfMaxProcessingTasks && !_waitingList.empty()) {
|
||||
NSURLSessionTask *nextTask = _waitingList.front();
|
||||
_waitingList.pop_front();
|
||||
[nextTask resume];
|
||||
_runningCount++;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -134,7 +134,6 @@ void HttpClient::networkThread() {
|
||||
|
||||
// Worker thread
|
||||
void HttpClient::networkThreadAlone(HttpRequest *request, HttpResponse *response) {
|
||||
increaseThreadCount();
|
||||
|
||||
char responseMessage[RESPONSE_BUFFER_SIZE] = {0};
|
||||
processResponse(response, responseMessage);
|
||||
@@ -431,6 +430,7 @@ void HttpClient::sendImmediate(HttpRequest *request) {
|
||||
HttpResponse *response = ccnew HttpResponse(request);
|
||||
response->addRef(); // NOTE: RefCounted object's reference count is changed to 0 now. so needs to addRef after ccnew.
|
||||
|
||||
increaseThreadCount();
|
||||
gThreadPool->pushTask([this, request, response](int /*tid*/) { HttpClient::networkThreadAlone(request, response); });
|
||||
}
|
||||
|
||||
@@ -552,6 +552,11 @@ void HttpClient::increaseThreadCount() {
|
||||
|
||||
void HttpClient::decreaseThreadCountAndMayDeleteThis() {
|
||||
bool needDeleteThis = false;
|
||||
// if _threadCount is 0, it means that this HttpClient object is not used anymore.
|
||||
// so return.
|
||||
if (_threadCount == 0) {
|
||||
return;
|
||||
}
|
||||
_threadCountMutex.lock();
|
||||
--_threadCount;
|
||||
if (0 == _threadCount) {
|
||||
|
||||
@@ -178,6 +178,11 @@ long FileUtilsOpenHarmony::getFileSize(const std::string &filepath) {
|
||||
if (fullPath.empty()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if(fullPath[0] == '/') {
|
||||
return FileUtils::getFileSize(fullPath);
|
||||
}
|
||||
|
||||
if (nullptr == _nativeResourceManager) {
|
||||
CC_LOG_ERROR("nativeResourceManager is nullptr");
|
||||
return 0;
|
||||
@@ -201,11 +206,11 @@ bool FileUtilsOpenHarmony::isFileExistInternal(const std::string &strFilePath) c
|
||||
return false;
|
||||
}
|
||||
|
||||
if (strFilePath[0] != '/') {
|
||||
if (strFilePath[0] != '/') {
|
||||
const char *s = strFilePath.c_str();
|
||||
// Found "@assets/" at the beginning of the path and we don't want it
|
||||
if (strFilePath.find(ASSETS_FOLDER_NAME) == 0) s += strlen(ASSETS_FOLDER_NAME);
|
||||
|
||||
|
||||
if (nullptr == _nativeResourceManager) {
|
||||
CC_LOG_ERROR("nativeResourceManager is nullptr");
|
||||
return false;
|
||||
@@ -217,7 +222,7 @@ bool FileUtilsOpenHarmony::isFileExistInternal(const std::string &strFilePath) c
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
FILE *fp = fopen(strFilePath.c_str(), "r");
|
||||
if (fp) {
|
||||
fclose(fp);
|
||||
|
||||
@@ -59,7 +59,7 @@ void PlanarShadowQueue::gatherShadowPasses(scene::Camera *camera, gfx::CommandBu
|
||||
}
|
||||
|
||||
const auto *scene = camera->getScene();
|
||||
const bool shadowVisible = camera->getVisibility() & static_cast<uint32_t>(LayerList::DEFAULT);
|
||||
const bool shadowVisible = camera->getVisibility() != 0;
|
||||
if (!scene->getMainLight() || !shadowVisible) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -68,6 +68,7 @@ RenderAdditiveLightQueue::RenderAdditiveLightQueue(RenderPipeline *pipeline) : _
|
||||
void RenderAdditiveLightQueue::recordCommandBuffer(gfx::Device *device, scene::Camera *camera, gfx::RenderPass *renderPass, gfx::CommandBuffer *cmdBuffer) {
|
||||
const uint32_t offset = _pipeline->getPipelineUBO()->getCurrentCameraUBOOffset();
|
||||
for (uint32_t i = 0; i < _instancedQueues.size(); ++i) {
|
||||
if (!this->_instancedQueues[i]) { continue; }
|
||||
const auto *light = _instancedLightPass.lights[i];
|
||||
_dynamicOffsets[0] = _instancedLightPass.dynamicOffsets[i];
|
||||
auto *globalDescriptorSet = _pipeline->getGlobalDSManager()->getOrCreateDescriptorSet(light);
|
||||
@@ -109,13 +110,12 @@ void RenderAdditiveLightQueue::gatherLightPasses(const scene::Camera *camera, gf
|
||||
|
||||
clear();
|
||||
|
||||
_validPunctualLights = _pipeline->getPipelineSceneData()->getValidPunctualLights();
|
||||
|
||||
if (_validPunctualLights.empty()) return;
|
||||
|
||||
updateUBOs(camera, cmdBuffer);
|
||||
updateLightDescriptorSet(camera, cmdBuffer);
|
||||
|
||||
_validPunctualLights = _pipeline->getPipelineSceneData()->getValidPunctualLights();
|
||||
if (_validPunctualLights.empty()) return;
|
||||
|
||||
const auto &renderObjects = _pipeline->getPipelineSceneData()->getRenderObjects();
|
||||
for (const auto &renderObject : renderObjects) {
|
||||
const auto *const model = renderObject.model;
|
||||
@@ -154,20 +154,19 @@ void RenderAdditiveLightQueue::gatherLightPasses(const scene::Camera *camera, gf
|
||||
_instancedLightPass.dynamicOffsets.emplace_back(_lightBufferStride * l);
|
||||
}
|
||||
for (const auto &instancedQueue : _instancedQueues) {
|
||||
instancedQueue->uploadBuffers(cmdBuffer);
|
||||
if (instancedQueue) {
|
||||
instancedQueue->uploadBuffers(cmdBuffer);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void RenderAdditiveLightQueue::clear() {
|
||||
for (const auto &instancedQueue : _instancedQueues) {
|
||||
instancedQueue->clear();
|
||||
if (instancedQueue) {
|
||||
instancedQueue->clear();
|
||||
}
|
||||
}
|
||||
_instancedQueues.clear();
|
||||
|
||||
for (auto lightPass : _lightPasses) {
|
||||
lightPass.dynamicOffsets.clear();
|
||||
lightPass.lights.clear();
|
||||
}
|
||||
_lightPasses.clear();
|
||||
|
||||
_instancedLightPass.dynamicOffsets.clear();
|
||||
@@ -209,16 +208,18 @@ void RenderAdditiveLightQueue::addRenderQueue(scene::SubModel *subModel, const s
|
||||
const auto lightIdx = _lightIndices[i];
|
||||
const auto *light = _validPunctualLights[lightIdx];
|
||||
const auto visibility = light->getVisibility();
|
||||
if ((visibility & model->getNode()->getLayer()) == model->getNode()->getLayer()) {
|
||||
if (((visibility & model->getNode()->getLayer()) == model->getNode()->getLayer()) ||
|
||||
(visibility & static_cast<uint32_t>(model->getVisFlags()))) {
|
||||
switch (batchingScheme) {
|
||||
case scene::BatchingSchemes::INSTANCING: {
|
||||
auto *buffer = pass->getInstancedBuffer(i);
|
||||
auto *buffer = pass->getInstancedBuffer(lightIdx);
|
||||
buffer->merge(subModel, lightPassIdx);
|
||||
buffer->setDynamicOffset(0, _lightBufferStride);
|
||||
if (i >= _instancedQueues.size()) {
|
||||
_instancedQueues.emplace_back(ccnew RenderInstancedQueue());
|
||||
buffer->setDynamicOffset(0, _lightBufferStride * lightIdx);
|
||||
if (_instancedQueues.size() <= lightIdx || !_instancedQueues[lightIdx]) {
|
||||
_instancedQueues.resize(lightIdx + 1);
|
||||
_instancedQueues[lightIdx] = ccnew RenderInstancedQueue();
|
||||
}
|
||||
_instancedQueues[i]->add(buffer);
|
||||
_instancedQueues[lightIdx]->add(buffer);
|
||||
} break;
|
||||
case scene::BatchingSchemes::NONE: {
|
||||
lightPass.lights.emplace_back(light);
|
||||
@@ -243,6 +244,7 @@ void RenderAdditiveLightQueue::updateUBOs(const scene::Camera *camera, gfx::Comm
|
||||
|
||||
size_t offset = 0;
|
||||
if (validLightCount > _lightBufferCount) {
|
||||
_firstLightBufferView->destroy();
|
||||
_lightBufferCount = nextPow2(static_cast<uint32_t>(validLightCount));
|
||||
_lightBuffer->resize(utils::toUint(_lightBufferStride * _lightBufferCount));
|
||||
_lightBufferData.resize(static_cast<size_t>(_lightBufferElementCount) * _lightBufferCount);
|
||||
@@ -432,7 +434,7 @@ void RenderAdditiveLightQueue::updateLightDescriptorSet(const scene::Camera *cam
|
||||
memcpy(_shadowUBO.data() + UBOShadow::MAT_LIGHT_VIEW_PROJ_OFFSET, matShadowViewProj.m, sizeof(matShadowViewProj));
|
||||
|
||||
// shadow info
|
||||
float shadowNFLSInfos[4] = {0.1F, spotLight->getRange(), 0.0F, 0.0F};
|
||||
float shadowNFLSInfos[4] = {0.01F, spotLight->getRange(), 0.0F, 0.0F};
|
||||
memcpy(_shadowUBO.data() + UBOShadow::SHADOW_NEAR_FAR_LINEAR_SATURATION_INFO_OFFSET, &shadowNFLSInfos, sizeof(shadowNFLSInfos));
|
||||
|
||||
const auto &shadowSize = shadowInfo->getSize();
|
||||
@@ -491,15 +493,17 @@ bool RenderAdditiveLightQueue::getLightPassIndex(const scene::Model *model, ccst
|
||||
bool hasValidLightPass = false;
|
||||
|
||||
for (const auto &subModel : model->getSubModels()) {
|
||||
int lightPassIndex = 0;
|
||||
int lightPassIndex = -1; // use -1 to indicate no valid light pass found
|
||||
int k = 0;
|
||||
for (const auto &pass : *(subModel->getPasses())) {
|
||||
if (pass->getPhase() == _phaseID) {
|
||||
lightPassIndex = k;
|
||||
hasValidLightPass = true;
|
||||
break;
|
||||
}
|
||||
++lightPassIndex;
|
||||
++k;
|
||||
}
|
||||
lightPassIndices->push_back(lightPassIndex);
|
||||
lightPassIndices->push_back(static_cast<uint32_t>(lightPassIndex));
|
||||
}
|
||||
|
||||
return hasValidLightPass;
|
||||
@@ -517,7 +521,7 @@ void RenderAdditiveLightQueue::lightCulling(const scene::Model *model) {
|
||||
isCulled = cullSpotLight(static_cast<const scene::SpotLight *>(light), model);
|
||||
break;
|
||||
case scene::LightType::POINT:
|
||||
isCulled = cullSphereLight(static_cast<const scene::SphereLight *>(light), model);
|
||||
isCulled = cullPointLight(static_cast<const scene::PointLight *>(light), model);
|
||||
break;
|
||||
case scene::LightType::RANGED_DIRECTIONAL:
|
||||
isCulled = cullRangedDirLight(static_cast<const scene::RangedDirectionalLight *>(light), model);
|
||||
|
||||
@@ -753,7 +753,7 @@ uint32_t LightResource::addLight(
|
||||
// already added
|
||||
auto iter = lightIndex.find(light);
|
||||
if (iter != lightIndex.end()) {
|
||||
return iter->second;
|
||||
return iter->second * elementSize;
|
||||
}
|
||||
|
||||
// resize buffer
|
||||
|
||||
@@ -3,6 +3,6 @@
|
||||
"type": "github",
|
||||
"owner": "cocos",
|
||||
"name": "cocos-engine-external",
|
||||
"checkout": "v4.0.0-3"
|
||||
"checkout": "v4.0.0-7"
|
||||
}
|
||||
}
|
||||