Compare commits

..

1 Commits

Author SHA1 Message Date
qiuguohua a855400c93 Move pal directory to private repository (#191) 2026-07-24 17:37:45 +08:00
361 changed files with 3826 additions and 4864 deletions
+2 -8
View File
@@ -20,14 +20,8 @@ if ($env:GITHUB_BASE_REF) {
# Push
$gitHubEvent = Get-Content $env:GITHUB_EVENT_PATH | ConvertFrom-Json
Write-Host "GitHub event: $gitHubEvent"
$beforeSha = $gitHubEvent.before
# On tag creation or initial push, before is all zeros - skip diff in that case
if ($beforeSha -match '^0+$') {
Write-Host "No previous commit (tag creation or initial push). Skipping diff."
return
}
git fetch origin $beforeSha --depth=1
$diffFiles = git diff --name-only --diff-filter=$diffFilter $beforeSha $env:GITHUB_SHA
git fetch origin $gitHubEvent.before --depth=1
$diffFiles = git diff --name-only --diff-filter=$diffFilter $gitHubEvent.before $env:GITHUB_SHA
}
Write-Host "Diff files: $diffFiles"
+8 -4
View File
@@ -18,7 +18,6 @@ jobs:
with:
token: ${{ github.token }}
ref: ${{ github.head_sha }}
fetch-depth: 0
- id: get_change_files
uses: fish9167/file-changes-action@v1.2.3
@@ -26,13 +25,18 @@ jobs:
output: ' '
fileOutput: ' '
- uses: DoozyX/clang-format-lint-action@v0.18
- name: Echo change files
run: |
cat $HOME/files.txt
mv $HOME/files.txt ${{github.workspace}}/files.txt
- uses: fish9167/clang-format-lint-action@master
with:
source: ./native
exclude: ./native/cocos/bindings/auto ./native/cocos/base/std ./native/cocos/editor-support/spine-wasm ./native/cocos/editor-support/spine ./native/cocos/gi/light-probe/predicates.cpp ./native/cocos/gi/light-probe/tetgen.cpp ./native/cocos/gi/light-probe/tetgen.h ./native/cocos/platform/openharmony/napi ./native/tools ./native/vendor ./native/cocos/cocos-version.h
exclude: ./native/cocos/bindings/auto
extensions: 'c,h,hpp,cpp,cxx'
style: file
inplace: true
inplace: True
clangFormatVersion: 12
- name: Create Pull Request
@@ -483,8 +483,8 @@ jobs:
echo "set(CC_USE_GLES3 OFF)" >> build-mac/proj/cfg.cmake
echo "set(CC_USE_METAL ON)" >> build-mac/proj/cfg.cmake
# Test JSVM v8 backend on macOS.
echo "set(USE_SE_V8 ON)" >> build-mac/proj/cfg.cmake
echo "set(USE_SE_JSVM OFF)" >> build-mac/proj/cfg.cmake
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_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,6 +493,7 @@ 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!"
@@ -533,7 +534,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 13.0)" >> build-ios/proj/cfg.cmake
echo "set(TARGET_IOS_VERSION 12.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
@@ -547,6 +548,7 @@ 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!"
-4
View File
@@ -3980,7 +3980,3 @@ Debug bones or slots is invalid in cached mode.
### 16419
Spine version not supported.
### 16420
End time must bigger than start time.
+1 -1
View File
@@ -115,7 +115,7 @@ export class TextProcessing {
const maxValue = Math.max(outputLayoutData.canvasSize.width, outputLayoutData.canvasSize.height);
const canvasScaleToMaxSizeRatio = MAX_SIZE / maxValue;
this._fontScale *= canvasScaleToMaxSizeRatio;
this._fontScale = Math.max(0.1, this._fontScale);
this._fontScale = Math.max(1, this._fontScale);
}
this._updatePaddingRect(style, outputLayoutData);
-9
View File
@@ -266,15 +266,6 @@ 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) {
+1 -12
View File
@@ -398,23 +398,12 @@ 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);
if (!this._keepRenderData) {
this.destroyRenderData();
}
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) {
+2 -7
View File
@@ -172,18 +172,13 @@ export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMe
// Fill index buffer.
let indexBuffer: ArrayBuffer | null = null;
let idxCount = 0;
let idxStride = 2;
let indexFormat = Format.R16UI;
const idxStride = 2;
if (geometry.indices) {
const { indices } = geometry;
idxCount = indices.length;
if (indices.some((i) => i > 0xFFFF)) {
idxStride = 4;
indexFormat = Format.R32UI;
}
indexBuffer = new ArrayBuffer(idxStride * idxCount);
const indexBufferView = new DataView(indexBuffer);
writeBuffer(indexBufferView, indices, indexFormat);
writeBuffer(indexBufferView, indices, Format.R16UI);
}
// Create primitive.
-7
View File
@@ -106,13 +106,6 @@ export class BakedSkinningModel extends MorphModel {
UBOSkinningTexture.SIZE,
));
}
// The animation buffer belongs to the skinning root. Refresh its binding without
// rebuilding the instanced attribute block, which would erase custom attribute values.
for (let i = 0; i < this._subModels.length; i++) {
this._updateLocalDescriptors(i, this._subModels[i].descriptorSet);
}
this.updateInstancedJointTextureInfo();
}
// Override
-10
View File
@@ -142,7 +142,6 @@ export class SkinningModel extends MorphModel {
}
this._bufferIndices = null; this._joints.length = 0;
if (!skeleton || !skinningRoot || !mesh) { return; }
const prevRealTimeTextureMode = this._realTimeTextureMode;
this._realTimeTextureMode = false;
if (UBOSkinning.JOINT_UNIFORM_CAPACITY < skeleton.joints.length) { this._realTimeTextureMode = true; }
this.transform = skinningRoot;
@@ -162,15 +161,6 @@ export class SkinningModel extends MorphModel {
if (!jointMaps) { indices.push(index); buffers.push(0); } else { getRelevantBuffers(indices, buffers, jointMaps, index); }
this._joints.push({ indices, buffers, bound, target, bindpose, transform });
}
// Rebind recreated joint resources without resetting user-provided instanced attributes.
const subModelCount = Math.min(this._subModels.length, this._bufferIndices.length);
if (subModelCount && prevRealTimeTextureMode !== this._realTimeTextureMode) {
this.onMacroPatchesStateChanged();
}
for (let i = 0; i < subModelCount; i++) {
this._updateLocalDescriptors(i, this._subModels[i].descriptorSet);
}
}
/**
@@ -384,10 +384,10 @@ export class ReflectionProbe extends Component {
}
}
}
if (!EDITOR_NOT_IN_PREVIEW && this.probeType === ProbeType.PLANAR && this.sourceCamera) {
if (this.probeType === ProbeType.PLANAR && this.sourceCamera) {
if ((this.sourceCamera.node.hasChangedFlags & TransformBit.TRS)
|| !this._sourceCameraPos.equals(this.sourceCamera.node.getWorldPosition())) {
this._sourceCameraPos.set(this.sourceCamera.node.getWorldPosition());
this._sourceCameraPos = this.sourceCamera.node.getWorldPosition();
this.probe.renderPlanarReflection(this.sourceCamera.camera);
}
}
@@ -177,21 +177,21 @@ export class SkinnedMeshBatchRenderer extends SkinnedMeshRenderer {
@override
@visible(false)
get mesh (): Mesh | null {
return Reflect.get(SkinnedMeshRenderer.prototype, 'mesh', this);
return super.mesh;
}
set mesh (val) {
Reflect.set(SkinnedMeshRenderer.prototype, 'mesh', val, this);
super.mesh = val;
}
@override
@visible(false)
get skeleton (): Skeleton | null {
return Reflect.get(SkinnedMeshRenderer.prototype, 'skeleton', this);
return super.skeleton;
}
set skeleton (val) {
Reflect.set(SkinnedMeshRenderer.prototype, 'skeleton', val, this);
super.skeleton = val;
}
public onLoad (): void {
+2 -3
View File
@@ -76,11 +76,10 @@ simpleTextureProto._onGFXTextureUpdated = function (gfxTexture) {
simpleTextureProto._onAfterAssignImage = function (image) {
if (macro.CLEANUP_IMAGE_CACHE) {
const deps = dependUtil.getDeps(this._uuid);
let index = deps.indexOf(image._uuid);
while (index !== -1) {
const index = deps.indexOf(image._uuid);
if (index !== -1) {
js.array.fastRemoveAt(deps, index);
image.decRef();
index = deps.indexOf(image._uuid);
}
}
};
+2 -4
View File
@@ -194,12 +194,10 @@ export class SimpleTexture extends TextureBase {
if (macro.CLEANUP_IMAGE_CACHE) {
const deps = dependUtil.getDeps(this._uuid);
let index = deps.indexOf(image._uuid);
while (index !== -1) {
const index = deps.indexOf(image._uuid);
if (index !== -1) {
js.array.fastRemoveAt(deps, index);
image.decRef();
// The same UUID may occur more than once; find the next dependency edge.
index = deps.indexOf(image._uuid);
}
}
}
-52
View File
@@ -69,58 +69,6 @@ export function approx (a: number, b: number, maxDiff?: number): boolean {
return mathAbs(a - b) <= maxDiff;
}
/**
* @en Tests whether or not the first argument is approximately greater than or equal to the second
* @zh 测试第一个参数是否近似大于或等于第二个参数
* @param a The first number to test
* @param b The second number to test
* @param maxDiff Maximum difference (default: EPSILON)
* @return True if a is approximately greater than or equal to b, false otherwise
*/
export function approxGE (a: number, b: number, maxDiff?: number): boolean {
maxDiff = maxDiff || EPSILON;
return a >= b - maxDiff;
}
/**
* @en Tests whether or not the first argument is approximately less than or equal to the second
* @zh 测试第一个参数是否近似小于或等于第二个参数
* @param a The first number to test
* @param b The second number to test
* @param maxDiff Maximum difference (default: EPSILON)
* @return True if a is approximately less than or equal to b, false otherwise
*/
export function approxLE (a: number, b: number, maxDiff?: number): boolean {
maxDiff = maxDiff || EPSILON;
return a <= b + maxDiff;
}
/**
* @en Tests whether or not the first argument is approximately greater than the second
* @zh 测试第一个参数是否近似大于第二个参数
* @param a The first number to test
* @param b The second number to test
* @param maxDiff Maximum difference (default: EPSILON)
* @return True if a is approximately greater than b, false otherwise
*/
export function approxGT (a: number, b: number, maxDiff?: number): boolean {
maxDiff = maxDiff || EPSILON;
return a > b + maxDiff;
}
/**
* @en Tests whether or not the first argument is approximately less than the second
* @zh 测试第一个参数是否近似小于第二个参数
* @param a The first number to test
* @param b The second number to test
* @param maxDiff Maximum difference (default: EPSILON)
* @return True if a is approximately less than b, false otherwise
*/
export function approxLT (a: number, b: number, maxDiff?: number): boolean {
maxDiff = maxDiff || EPSILON;
return a < b - maxDiff;
}
/**
* @en Clamps a value between a minimum float and maximum float value.<br/>
* @zh 返回最小浮点数和最大浮点数之间的一个数值。可以使用 clamp 函数将不断变化的数值限制在范围内。
-10
View File
@@ -88,14 +88,6 @@ export abstract class CommandBuffer extends GFXObject {
return this._numTris;
}
/**
* @en Number of compute dispatches currently recorded.
* @zh 计算调度(dispatch)次数。
*/
get numDispatches (): number {
return this._numDispatches;
}
/** @mangle */
protected _queue: Queue | null = null;
/** @mangle */
@@ -103,8 +95,6 @@ export abstract class CommandBuffer extends GFXObject {
/** @mangle */
protected _numDrawCalls = 0;
/** @mangle */
protected _numDispatches = 0;
/** @mangle */
protected _numInstances = 0;
/** @mangle */
protected _numTris = 0;
-10
View File
@@ -127,14 +127,6 @@ export abstract class Device {
return this._numTris;
}
/**
* @en Number of compute dispatches currently recorded.
* @zh 计算调度(dispatch)次数。
*/
get numDispatches (): number {
return this._numDispatches;
}
/**
* @en Total memory size currently allocated.
* @zh 内存状态。
@@ -176,8 +168,6 @@ export abstract class Device {
/** @mangle */
protected _numDrawCalls = 0;
/** @mangle */
protected _numDispatches = 0;
/** @mangle */
protected _numInstances = 0;
/** @mangle */
protected _numTris = 0;
+2 -2
View File
@@ -2702,7 +2702,7 @@ export function WebGLCmdFuncCopyBuffersToTexture (
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
: alignTo(regionTexExtentHeight, blockSizeHeight);
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
@@ -2773,7 +2773,7 @@ export function WebGLCmdFuncCopyBuffersToTexture (
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
: alignTo(regionTexExtentHeight, blockSizeHeight);
stride.width = region.buffStride > 0 ? region.buffStride : extent.width;
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
+7 -7
View File
@@ -2811,7 +2811,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
: alignTo(regionTexExtentHeight, blockSizeHeight);
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
@@ -2883,7 +2883,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
: alignTo(regionTexExtentHeight, blockSizeHeight);
extent.depth = 1;
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
@@ -2965,7 +2965,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
offset.z = regionTexOffset.z;
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
: alignTo(regionTexExtentHeight, blockSizeHeight);
extent.depth = regionTexExtent.depth;
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
@@ -2986,7 +2986,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
if (!isCompressed) {
gl.texSubImage3D(
WebGLConstants.TEXTURE_3D,
WebGLConstants.TEXTURE_2D_ARRAY,
mipLevel,
offset.x,
offset.y,
@@ -3000,7 +3000,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
);
} else if (gpuTexture.glInternalFmt !== WebGL2EXT.COMPRESSED_RGB_ETC1_WEBGL as number) {
gl.compressedTexSubImage3D(
WebGLConstants.TEXTURE_3D,
WebGLConstants.TEXTURE_2D_ARRAY,
mipLevel,
offset.x,
offset.y,
@@ -3013,7 +3013,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
);
} else { // WEBGL_compressed_texture_etc1
gl.compressedTexImage3D(
WebGLConstants.TEXTURE_3D,
WebGLConstants.TEXTURE_2D_ARRAY,
mipLevel,
gpuTexture.glInternalFmt,
destWidth,
@@ -3043,7 +3043,7 @@ export function WebGL2CmdFuncCopyBuffersToTexture (
offset.x = regionTexOffset.x === 0 ? 0 : alignTo(regionTexOffset.x, blockSizeWidth);
offset.y = regionTexOffset.y === 0 ? 0 : alignTo(regionTexOffset.y, blockSizeHeight);
extent.width = regionTexExtentWidth < blockSizeWidth ? regionTexExtentWidth : alignTo(regionTexExtentWidth, blockSizeWidth);
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentHeight
extent.height = regionTexExtentHeight < blockSizeHeight ? regionTexExtentWidth
: alignTo(regionTexExtentHeight, blockSizeHeight);
stride.width = regionBuffStride > 0 ? regionBuffStride : extent.width;
stride.height = region.buffTexHeight > 0 ? region.buffTexHeight : extent.height;
+28 -89
View File
@@ -40,7 +40,6 @@ import {
TextureBlit,
DescriptorSetInfo,
Format,
DispatchInfo,
} from '../base/define';
import { Framebuffer } from '../base/framebuffer';
import { InputAssembler } from '../base/input-assembler';
@@ -180,7 +179,6 @@ export class WebGPUCommandBuffer extends CommandBuffer {
private _wgpuRenderPass!: WebGPURenderPass;
private _renderPassFuncQueue: ((renPassEncoder: GPURenderPassEncoder) => void)[] = [];
private _computeFuncQueue: ((computePassEncoder: GPUComputePassEncoder) => void)[] = [];
public initialize (info: CommandBufferInfo): boolean {
this._type = info.type;
@@ -224,16 +222,13 @@ export class WebGPUCommandBuffer extends CommandBuffer {
this._curStencilWriteMask = null;
this._curStencilCompareMask = null;
this._numDrawCalls = 0;
this._numDispatches = 0;
this._numInstances = 0;
this._numTris = 0;
this._computeFuncQueue.length = 0;
}
public end (): void {
this._isStateValid = false;
this._isInRenderPass = false;
this._computeFuncQueue.length = 0;
}
public beginRenderPass (
@@ -655,20 +650,22 @@ export class WebGPUCommandBuffer extends CommandBuffer {
this.cmdPackage.cmds.concat(cmdPackage.cmds.array);
this._numDrawCalls += WebGPUCmdBuff._numDrawCalls;
this._numDispatches += WebGPUCmdBuff._numDispatches;
this._numInstances += WebGPUCmdBuff._numInstances;
this._numTris += WebGPUCmdBuff._numTris;
}
}
private _prepareDescriptorSets (): void {
protected bindStates (): void {
if (!this._curGPUPipelineState) {
return;
}
const gpuPipelineLayout = this._curGPUPipelineState.gpuPipelineLayout as IWebGPUGPUPipelineLayout;
const wgpuPipLayout = (currPipelineState?.pipelineLayout as WebGPUPipelineLayout);
const device = WebGPUDeviceManager.instance;
for (let i = 0; i < groupSets.length; i++) {
const currSetIdx = groupSets[i];
const currDesc = descriptorSets[currSetIdx];
if (currDesc && currDesc.gpuDescriptorSet) {
// prepare() builds the bind group if it was never created, or rebuilds it on resource change.
currDesc.prepare();
} else {
const currLayout = wgpuPipLayout.setLayouts[currSetIdx];
@@ -678,13 +675,23 @@ export class WebGPUCommandBuffer extends CommandBuffer {
newDescSet.prepare(true);
}
}
}
/**
* Collect the bind groups and dynamic offsets for the currently bound descriptor sets.
* Shared by the draw (bindStates) and compute (dispatch) paths.
*/
private _collectBindGroups (): { wgpuBindGroups: GPUBindGroup[]; wgpuDynOffsets: number[][] } {
const gpuIA = this._curGPUInputAssembler!;
// only 4x MSAA is supported
gpuIA.samples = samples > 1 ? 4 : 1;
this._curWebGPUPipelineState!.prepare(gpuIA);
// ----------------------------wgpu pipline state-----------------------------
const wgpuPipeline = this._curGPUPipelineState.nativePipeline as GPURenderPipeline;
const pplFunc = (passEncoder: GPURenderPassEncoder): void => {
passEncoder.setPipeline(wgpuPipeline);
};
this._renderPassFuncQueue.push(pplFunc);
if (this._curGPUPipelineState.pipelineState?.depthStencil) {
const stencilRef = this._curGPUPipelineState.stencilRef;
const stencilRefFunc = (passEncoder: GPURenderPassEncoder): void => {
passEncoder.setStencilReference(stencilRef);
};
this._renderPassFuncQueue.push(stencilRefFunc);
}
const currGPUDescSize = groupSets.length;
const wgpuBindGroups = new Array<GPUBindGroup>(currGPUDescSize);
const wgpuDynOffsets = new Array<number[]>(currGPUDescSize);
@@ -696,7 +703,7 @@ export class WebGPUCommandBuffer extends CommandBuffer {
wgpuDynOffsets[currSetIdx] = [...this._curDynamicOffsets[currSetIdx]];
if (!descObj.dynamicOffsetCount) {
wgpuDynOffsets[currSetIdx] = [];
} else if (descObj.dynamicOffsetCount !== wgpuDynOffsets[currSetIdx].length) {
} else if (descObj && descObj.dynamicOffsetCount !== wgpuDynOffsets[currSetIdx].length) {
wgpuDynOffsets[currSetIdx].length = descObj.dynamicOffsetCount;
for (let j = 0; j < descObj.dynamicOffsetCount; j++) {
const currOffset = wgpuDynOffsets[currSetIdx][j];
@@ -712,84 +719,16 @@ export class WebGPUCommandBuffer extends CommandBuffer {
}
}
}
return { wgpuBindGroups, wgpuDynOffsets };
}
public dispatch (info: DispatchInfo): void {
if (!this._curGPUPipelineState) {
return;
}
// Prepare descriptor sets (same logic as bindStates)
this._prepareDescriptorSets();
// Create compute pipeline
this._curWebGPUPipelineState!.prepare(null!);
const computePipeline = this._curGPUPipelineState.nativePipeline as GPUComputePipeline;
// Build bind groups for compute pass
const { wgpuBindGroups, wgpuDynOffsets } = this._collectBindGroups();
const func = (passEncoder: GPUComputePassEncoder): void => {
passEncoder.setPipeline(computePipeline);
const gpuBindGroupSize = wgpuBindGroups.length;
for (let i = 0; i < gpuBindGroupSize; i++) {
passEncoder.setBindGroup(i, wgpuBindGroups[i], wgpuDynOffsets[i]);
}
passEncoder.dispatchWorkgroups(info.groupCountX, info.groupCountY, info.groupCountZ);
};
this._computeFuncQueue.push(func);
++this._numDispatches;
this._isStateValid = false;
}
public submitComputePass (): void {
if (this._computeFuncQueue.length === 0) {
return;
}
const device = WebGPUDeviceManager.instance;
const nativeDevice = device.nativeDevice!;
const cmdEncoder = nativeDevice.createCommandEncoder();
const computePassEncoder = cmdEncoder.beginComputePass();
this._computeFuncQueue.forEach((cb) => {
cb(computePassEncoder);
});
computePassEncoder.end();
nativeDevice.queue.submit([cmdEncoder.finish()]);
this._computeFuncQueue.length = 0;
}
protected bindStates (): void {
if (!this._curGPUPipelineState) {
return;
}
const gpuPipelineLayout = this._curGPUPipelineState.gpuPipelineLayout as IWebGPUGPUPipelineLayout;
this._prepareDescriptorSets();
const gpuIA = this._curGPUInputAssembler!;
// only 4x MSAA is supported
gpuIA.samples = samples > 1 ? 4 : 1;
this._curWebGPUPipelineState!.prepare(gpuIA);
// ----------------------------wgpu pipline state-----------------------------
const wgpuPipeline = this._curGPUPipelineState.nativePipeline as GPURenderPipeline;
const pplFunc = (passEncoder: GPURenderPassEncoder): void => {
passEncoder.setPipeline(wgpuPipeline);
};
this._renderPassFuncQueue.push(pplFunc);
const pipelineDesc = this._curGPUPipelineState.pipelineState;
if (pipelineDesc && 'depthStencil' in pipelineDesc && pipelineDesc.depthStencil) {
const stencilRef = this._curGPUPipelineState.stencilRef;
const stencilRefFunc = (passEncoder: GPURenderPassEncoder): void => {
passEncoder.setStencilReference(stencilRef);
};
this._renderPassFuncQueue.push(stencilRefFunc);
}
const { wgpuBindGroups, wgpuDynOffsets } = this._collectBindGroups();
const bgfunc = (passEncoder: GPURenderPassEncoder): void => {
const gpuBindGroupSize = wgpuBindGroups.length;
for (let i = 0; i < gpuBindGroupSize; i++) {
let currBindGroup = wgpuBindGroups[i];
if (!currBindGroup) {
currBindGroup = (device.defaultResource.descSet as WebGPUDescriptorSet).gpuDescriptorSet.bindGroup;
}
// FIXME: this is a special sentence that 2 in 3 parameters I'm not certain.
passEncoder.setBindGroup(i, wgpuBindGroups[i], wgpuDynOffsets[i]);
passEncoder.setBindGroup(i, currBindGroup, wgpuDynOffsets[i]);
}
};
this._renderPassFuncQueue.push(bgfunc);
+5 -10
View File
@@ -35,7 +35,6 @@ import {
TextureUsageBit,
ShaderStageFlags,
DescriptorType,
MemoryAccessBit,
Color, Rect, Viewport, BufferTextureCopy,
SamplerInfo,
FormatSize,
@@ -1424,15 +1423,11 @@ export function createBindGroupLayoutEntry (currBind: DescriptorSetLayoutBinding
case DescriptorType.STORAGE_BUFFER:
case DescriptorType.DYNAMIC_STORAGE_BUFFER:
{
const readOnly = (currBind.access & MemoryAccessBit.READ_ONLY) !== 0
&& (currBind.access & MemoryAccessBit.WRITE_ONLY) === 0;
entry.buffer = {
type: readOnly ? 'read-only-storage' : 'storage',
hasDynamicOffset: type === DescriptorType.DYNAMIC_STORAGE_BUFFER,
minBindingSize: undefined,
};
}
entry.buffer = {
type: 'storage',
hasDynamicOffset: type === DescriptorType.DYNAMIC_STORAGE_BUFFER,
minBindingSize: undefined,
};
break;
case DescriptorType.SAMPLER_TEXTURE:
+7 -20
View File
@@ -170,17 +170,9 @@ export class WebGPUDescriptorSet extends DescriptorSet {
if (descType & (DescriptorType.DYNAMIC_STORAGE_BUFFER | DescriptorType.DYNAMIC_UNIFORM_BUFFER)) {
this._dynamicOffsets.push(bindIdx);
}
} else if (descType & (DESCRIPTOR_SAMPLER_TYPE | DescriptorType.STORAGE_IMAGE)) {
const isStorageImage = (descType & DescriptorType.STORAGE_IMAGE) === DescriptorType.STORAGE_IMAGE;
if (isStorageImage) {
// storage texture (compute read/write): bind the texture view, no sampler
let currTex = this._textures[i] as WebGPUTexture;
if (!currTex || (currTex.hasChange && !currTex.gpuTexture)) {
currTex = device.defaultResource.texture;
}
this._bindTextureEntry(binding, currTex);
} else if ((descType & DescriptorType.SAMPLER) !== DescriptorType.SAMPLER) {
// sampled texture
} else if (descType & DESCRIPTOR_SAMPLER_TYPE) {
if ((descType & DescriptorType.SAMPLER) !== DescriptorType.SAMPLER) {
// texture
let currTex = this._textures[i] as WebGPUTexture;
// null or destroyed?
if (!currTex || (currTex.hasChange && !currTex.gpuTexture)) {
@@ -193,9 +185,9 @@ export class WebGPUDescriptorSet extends DescriptorSet {
this._bindTextureEntry(binding, currTex);
}
if (!isStorageImage
&& !((descType & DescriptorType.INPUT_ATTACHMENT) === DescriptorType.INPUT_ATTACHMENT
|| (descType & DescriptorType.TEXTURE) === DescriptorType.TEXTURE)) {
if (!((descType & DescriptorType.STORAGE_IMAGE) === DescriptorType.STORAGE_IMAGE
|| (descType & DescriptorType.INPUT_ATTACHMENT) === DescriptorType.INPUT_ATTACHMENT
|| (descType & DescriptorType.TEXTURE) === DescriptorType.TEXTURE)) {
// sampler
const currSampler = (this._samplers[i] || device.defaultResource.sampler) as WebGPUSampler;
this._bindSamplerEntry(binding, currSampler);
@@ -227,12 +219,7 @@ export class WebGPUDescriptorSet extends DescriptorSet {
}
public prepare (force: boolean = false): void {
const gpuDescriptorSet = this._gpuDescriptorSet;
if (!gpuDescriptorSet) {
return;
}
// Rebuild when forced, when the bind group has never been built, or when resources changed.
const breakUpdate = gpuDescriptorSet.bindGroup && !this._isResourceChange() && !force;
const breakUpdate = !this._isResourceChange() && !force;
if (breakUpdate) return;
this._isDirty = true;
this._applyBindGroup();
+1 -19
View File
@@ -53,7 +53,7 @@ import { WebGPUTexture } from './webgpu-texture';
import { DefaultResources, hashCombineNum, hashCombineStr, webGPU, WebGPUDeviceManager } from './define';
import {
Filter, Format,
QueueType, Feature, BufferTextureCopy, Rect, Size, DescriptorSetInfo,
QueueType, Feature, BufferTextureCopy, Rect, DescriptorSetInfo,
BufferInfo, BufferViewInfo, CommandBufferInfo, DeviceInfo,
FramebufferInfo, InputAssemblerInfo, QueueInfo, RenderPassInfo, SamplerInfo,
ShaderInfo, PipelineLayoutInfo, DescriptorSetLayoutInfo, TextureInfo, TextureViewInfo, GeneralBarrierInfo, TextureBarrierInfo,
@@ -552,22 +552,6 @@ export class WebGPUDevice extends Device {
this._caps.max3DTextureSize = limits.maxTextureDimension3D;
this._caps.uboOffsetAlignment = limits.minUniformBufferOffsetAlignment;
// Compute limits are read from the device (not the adapter): no elevated
// compute limits are requested, so these are the values validation enforces.
const deviceLimits = device.limits;
this._caps.maxComputeSharedMemorySize = deviceLimits.maxComputeWorkgroupStorageSize;
this._caps.maxComputeWorkGroupInvocations = deviceLimits.maxComputeInvocationsPerWorkgroup;
this._caps.maxComputeWorkGroupSize = new Size(
deviceLimits.maxComputeWorkgroupSizeX,
deviceLimits.maxComputeWorkgroupSizeY,
deviceLimits.maxComputeWorkgroupSizeZ,
);
this._caps.maxComputeWorkGroupCount = new Size(
deviceLimits.maxComputeWorkgroupsPerDimension,
deviceLimits.maxComputeWorkgroupsPerDimension,
deviceLimits.maxComputeWorkgroupsPerDimension,
);
const features = this._adapter!.features;
// FIXME: require by query
this._multiDrawIndirect = false;
@@ -576,7 +560,6 @@ export class WebGPUDevice extends Device {
this._features[Feature.ELEMENT_INDEX_UINT] = true;
this._features[Feature.INSTANCED_ARRAYS] = true;
this._features[Feature.MULTIPLE_RENDER_TARGETS] = true;
this._features[Feature.COMPUTE_SHADER] = true;
this.initFormatFeatures(features);
this._queue = this.createQueue(new QueueInfo(QueueType.GRAPHICS));
@@ -701,7 +684,6 @@ export class WebGPUDevice extends Device {
public present (): void {
const queue = (this._queue as unknown as WebGPUQueue);
this._numDrawCalls = queue.numDrawCalls;
this._numDispatches = queue.numDispatches;
this._numInstances = queue.numInstances;
this._numTris = queue.numTris;
queue.clear();
+2 -2
View File
@@ -241,8 +241,8 @@ export interface IWebGPUGPUPipelineState {
bs: BlendState;
dynamicStates: DynamicStateFlagBit[];
gpuRenderPass: IWebGPUGPURenderPass | null;
pipelineState: GPURenderPipelineDescriptor | GPUComputePipelineDescriptor | undefined;
nativePipeline: GPURenderPipeline | GPUComputePipeline | undefined;
pipelineState: GPURenderPipelineDescriptor | undefined;
nativePipeline: GPUPipelineBase | undefined;
}
export interface IWebGPUGPUDescriptor {
+117 -160
View File
@@ -26,7 +26,7 @@ import { PipelineState, PipelineStateInfo } from '../base/pipeline-state';
import { IWebGPUGPUInputAssembler, IWebGPUGPUPipelineState } from './webgpu-gpu-objects';
import { WebGPURenderPass } from './webgpu-render-pass';
import { WebGPUShader } from './webgpu-shader';
import { BlendOp, CullMode, DynamicStateFlagBit, Format, FormatInfos, PipelineBindPoint, PrimitiveMode, ShaderStageFlagBit } from '../base/define';
import { BlendOp, CullMode, DynamicStateFlagBit, Format, FormatInfos, PrimitiveMode, ShaderStageFlagBit } from '../base/define';
import { WebGPUPipelineLayout } from './webgpu-pipeline-layout';
import {
GFXFormatToWGPUFormat,
@@ -81,156 +81,124 @@ export class WebGPUPipelineState extends PipelineState {
}
}
const gpuShader = info.shader as WebGPUShader;
// colorstates
const colorAttachments = this._renderPass.colorAttachments;
const colorDescs: GPUColorTargetState[] = [];
const colAttachmentSize = colorAttachments.length;
const pipelineLayoutObj = info.pipelineLayout as WebGPUPipelineLayout;
const shaderStages = gpuShader.gpuShader.gpuStages;
if (info.bindPoint === PipelineBindPoint.COMPUTE) {
// ---- Compute Pipeline ----
let computeStage: GPUProgrammableStage | undefined;
const stageSize = shaderStages.length;
for (let i = 0; i < stageSize; i++) {
if (shaderStages[i].type === ShaderStageFlagBit.COMPUTE) {
computeStage = shaderStages[i].gpuShader!;
}
}
const computeDesc: GPUComputePipelineDescriptor = {
layout: pipelineLayoutObj.gpuPipelineLayout!.nativePipelineLayout,
compute: computeStage!,
for (let i = 0; i < colAttachmentSize; i++) {
const colDesc: GPUColorTargetState = {
format: GFXFormatToWGPUFormat(colorAttachments[i].format),
writeMask: WebGPUBlendMask(this._bs.targets[i].blendColorMask),
};
this._gpuPipelineState = {
gpuPrimitive: 'triangle-list' as GPUPrimitiveTopology,
gpuShader: gpuShader.gpuShader,
gpuPipelineLayout: pipelineLayoutObj.gpuPipelineLayout,
rs: info.rasterizerState,
dss: info.depthStencilState,
stencilRef: 0,
bs: info.blendState,
gpuRenderPass: null,
dynamicStates,
pipelineState: computeDesc,
nativePipeline: undefined,
};
} else {
// ---- Render Pipeline ----
// colorstates
const colorAttachments = this._renderPass.colorAttachments;
const colorDescs: GPUColorTargetState[] = [];
const colAttachmentSize = colorAttachments.length;
for (let i = 0; i < colAttachmentSize; i++) {
const colDesc: GPUColorTargetState = {
format: GFXFormatToWGPUFormat(colorAttachments[i].format),
writeMask: WebGPUBlendMask(this._bs.targets[i].blendColorMask),
if (this._bs.targets[i].blend) {
colDesc.blend = {
color: {
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDst],
operation: WebGPUBlendOps[this._bs.targets[i].blendEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendEq],
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrc],
},
alpha: {
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDstAlpha],
operation: WebGPUBlendOps[this._bs.targets[i].blendAlphaEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendAlphaEq],
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrcAlpha],
},
};
if (this._bs.targets[i].blend) {
colDesc.blend = {
color: {
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDst],
operation: WebGPUBlendOps[this._bs.targets[i].blendEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendEq],
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrc],
},
alpha: {
dstFactor: WebGPUBlendFactors[this._bs.targets[i].blendDstAlpha],
operation: WebGPUBlendOps[
this._bs.targets[i].blendAlphaEq === BlendOp.MAX ? BlendOp.ADD : this._bs.targets[i].blendAlphaEq],
srcFactor: WebGPUBlendFactors[this._bs.targets[i].blendSrcAlpha],
},
};
}
colorDescs.push(colDesc);
}
let vertexStage: GPUProgrammableStage;
let fragmentStage: GPUProgrammableStage;
const stageSize = shaderStages.length;
for (let i = 0; i < stageSize; i++) {
if (shaderStages[i].type === ShaderStageFlagBit.VERTEX) { vertexStage = shaderStages[i].gpuShader!; }
if (shaderStages[i].type === ShaderStageFlagBit.FRAGMENT) { fragmentStage = shaderStages[i].gpuShader!; }
}
const shaderAttrs = gpuShader.attributes;
const attrsSize = shaderAttrs.length;
for (let i = 0; i < attrsSize; i++) {
this._locations.set(shaderAttrs[i].name, shaderAttrs[i].location);
}
const stripTopology = (info.primitive === PrimitiveMode.LINE_STRIP || info.primitive === PrimitiveMode.TRIANGLE_STRIP);
const renderPplDesc: GPURenderPipelineDescriptor = {
layout: pipelineLayoutObj.gpuPipelineLayout!.nativePipelineLayout,
vertex: {
module: vertexStage!.module,
entryPoint: 'main',
buffers: [],
},
primitive: {
topology: WebPUPrimitives[info.primitive],
frontFace: this._rs.isFrontFaceCCW ? 'ccw' : 'cw',
cullMode: this._rs.cullMode === CullMode.NONE ? 'none' : (this._rs.cullMode === CullMode.FRONT) ? 'front' : 'back',
},
fragment: {
module: fragmentStage!.module,
entryPoint: 'main',
targets: colorDescs,
},
};
if (stripTopology) renderPplDesc.primitive!.stripIndexFormat = 'uint16';
// depthstencil states
let stencilRef = 0;
if (this._renderPass.depthStencilAttachment?.format !== Format.UNKNOWN) {
const dssDesc = {} as GPUDepthStencilState;
dssDesc.format = GFXFormatToWGPUFormat(this._renderPass.depthStencilAttachment!.format);
dssDesc.depthWriteEnabled = this._dss.depthWrite;
dssDesc.depthCompare = this._dss.depthTest ? WebGPUCompereFunc[this._dss.depthFunc] : 'always';
let stencilReadMask = 0;
let stencilWriteMask = 0;
if (this._dss.stencilTestFront) {
dssDesc.stencilFront = {
compare: WebGPUCompereFunc[this._dss.stencilFuncFront],
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpFront],
passOp: WebGPUStencilOp[this._dss.stencilPassOpFront],
failOp: WebGPUStencilOp[this._dss.stencilFailOpFront],
};
stencilReadMask |= this._dss.stencilReadMaskFront;
stencilWriteMask |= this._dss.stencilWriteMaskFront;
stencilRef |= this._dss.stencilRefFront;
}
if (this._dss.stencilTestBack) {
dssDesc.stencilBack = {
compare: WebGPUCompereFunc[this._dss.stencilFuncBack],
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpBack],
passOp: WebGPUStencilOp[this._dss.stencilPassOpBack],
failOp: WebGPUStencilOp[this._dss.stencilFailOpBack],
};
stencilReadMask |= this._dss.stencilReadMaskBack;
stencilWriteMask |= this._dss.stencilWriteMaskBack;
stencilRef |= this._dss.stencilRefBack;
}
dssDesc.stencilReadMask = stencilReadMask;
dssDesc.stencilWriteMask = stencilWriteMask;
dssDesc.depthBias = this._rs.depthBias;
dssDesc.depthBiasSlopeScale = this._rs.depthBiasSlop;
dssDesc.depthBiasClamp = this._rs.depthBiasClamp;
renderPplDesc.depthStencil = dssDesc;
}
this._gpuPipelineState = {
gpuPrimitive: WebPUPrimitives[info.primitive],
gpuShader: gpuShader.gpuShader,
gpuPipelineLayout: pipelineLayoutObj.gpuPipelineLayout,
rs: info.rasterizerState,
dss: info.depthStencilState,
stencilRef,
bs: info.blendState,
gpuRenderPass: (info.renderPass as WebGPURenderPass).gpuRenderPass,
dynamicStates,
pipelineState: renderPplDesc,
nativePipeline: undefined,
};
colorDescs.push(colDesc);
}
let vertexStage: GPUProgrammableStage;
let fragmentStage: GPUProgrammableStage;
const shaderStages = (this._shader as WebGPUShader).gpuShader.gpuStages;
const stageSize = shaderStages.length;
for (let i = 0; i < stageSize; i++) {
if (shaderStages[i].type === ShaderStageFlagBit.VERTEX) { vertexStage = shaderStages[i].gpuShader!; }
if (shaderStages[i].type === ShaderStageFlagBit.FRAGMENT) { fragmentStage = shaderStages[i].gpuShader!; }
}
const gpuShader = info.shader as WebGPUShader;
const shaderAttrs = gpuShader.attributes;
const attrsSize = shaderAttrs.length;
for (let i = 0; i < attrsSize; i++) {
this._locations.set(shaderAttrs[i].name, shaderAttrs[i].location);
}
const stripTopology = (info.primitive === PrimitiveMode.LINE_STRIP || info.primitive === PrimitiveMode.TRIANGLE_STRIP);
const renderPplDesc: GPURenderPipelineDescriptor = {
layout: pipelineLayoutObj.gpuPipelineLayout!.nativePipelineLayout,
vertex: {
module: vertexStage!.module,
entryPoint: 'main',
buffers: [],
},
primitive: {
topology: WebPUPrimitives[info.primitive],
frontFace: this._rs.isFrontFaceCCW ? 'ccw' : 'cw',
cullMode: this._rs.cullMode === CullMode.NONE ? 'none' : (this._rs.cullMode === CullMode.FRONT) ? 'front' : 'back',
},
fragment: {
module: fragmentStage!.module,
entryPoint: 'main',
targets: colorDescs,
},
};
if (stripTopology) renderPplDesc.primitive!.stripIndexFormat = 'uint16';
// depthstencil states
let stencilRef = 0;
if (this._renderPass.depthStencilAttachment?.format !== Format.UNKNOWN) {
const dssDesc = {} as GPUDepthStencilState;
dssDesc.format = GFXFormatToWGPUFormat(this._renderPass.depthStencilAttachment!.format);
dssDesc.depthWriteEnabled = this._dss.depthWrite;
dssDesc.depthCompare = this._dss.depthTest ? WebGPUCompereFunc[this._dss.depthFunc] : 'always';
let stencilReadMask = 0;
let stencilWriteMask = 0;
if (this._dss.stencilTestFront) {
dssDesc.stencilFront = {
compare: WebGPUCompereFunc[this._dss.stencilFuncFront],
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpFront],
passOp: WebGPUStencilOp[this._dss.stencilPassOpFront],
failOp: WebGPUStencilOp[this._dss.stencilFailOpFront],
};
stencilReadMask |= this._dss.stencilReadMaskFront;
stencilWriteMask |= this._dss.stencilWriteMaskFront;
stencilRef |= this._dss.stencilRefFront;
}
if (this._dss.stencilTestBack) {
dssDesc.stencilBack = {
compare: WebGPUCompereFunc[this._dss.stencilFuncBack],
depthFailOp: WebGPUStencilOp[this._dss.stencilZFailOpBack],
passOp: WebGPUStencilOp[this._dss.stencilPassOpBack],
failOp: WebGPUStencilOp[this._dss.stencilFailOpBack],
};
stencilReadMask |= this._dss.stencilReadMaskBack;
stencilWriteMask |= this._dss.stencilWriteMaskBack;
stencilRef |= this._dss.stencilRefBack;
}
dssDesc.stencilReadMask = stencilReadMask;
dssDesc.stencilWriteMask = stencilWriteMask;
dssDesc.depthBias = this._rs.depthBias;
dssDesc.depthBiasSlopeScale = this._rs.depthBiasSlop;
dssDesc.depthBiasClamp = this._rs.depthBiasClamp;
renderPplDesc.depthStencil = dssDesc;
}
this._gpuPipelineState = {
gpuPrimitive: WebPUPrimitives[info.primitive],
gpuShader: gpuShader.gpuShader,
gpuPipelineLayout: pipelineLayoutObj.gpuPipelineLayout,
rs: info.rasterizerState,
dss: info.depthStencilState,
stencilRef,
bs: info.blendState,
gpuRenderPass: (info.renderPass as WebGPURenderPass).gpuRenderPass,
dynamicStates,
pipelineState: renderPplDesc,
nativePipeline: undefined,
};
}
protected _getShaderLocation (name: string): number | undefined {
@@ -247,22 +215,9 @@ export class WebGPUPipelineState extends PipelineState {
if (this._gpuPipelineState!.nativePipeline && !forceUpdate) {
return;
}
const webgpuDevice = (WebGPUDeviceManager.instance);
const nativeDevice = webgpuDevice.nativeDevice;
const pipelineState = this._gpuPipelineState!.pipelineState!;
// Compute pipeline: no vertex attributes, no multisample
if ('compute' in pipelineState) {
const nativePipeline = nativeDevice?.createComputePipeline(
pipelineState,
);
this._gpuPipelineState!.nativePipeline = nativePipeline;
return;
}
// Render pipeline
const gpuShader = this.shader;
const shaderAttrs = gpuShader.attributes;
const pipelineState = this._gpuPipelineState!.pipelineState!;
const vertexAttrs: GPUVertexBufferLayout[] = [];
const emptyPushAttr: string[] = [];
const streamCount = ia.gpuVertexBuffers.length;
@@ -317,6 +272,8 @@ export class WebGPUPipelineState extends PipelineState {
pipelineState.vertex.buffers = vertexAttrs;
pipelineState.multisample = { count: ia.samples };
const webgpuDevice = (WebGPUDeviceManager.instance);
const nativeDevice = webgpuDevice.nativeDevice;
const nativePipeline = nativeDevice?.createRenderPipeline(pipelineState);
this._gpuPipelineState!.nativePipeline = nativePipeline;
}
-3
View File
@@ -29,7 +29,6 @@ import { QueueInfo } from '../base/define';
export class WebGPUQueue extends Queue {
public numDrawCalls = 0;
public numDispatches = 0;
public numInstances = 0;
public numTris = 0;
@@ -52,7 +51,6 @@ export class WebGPUQueue extends Queue {
for (let i = 0; i < cmdBuffSize; i++) {
const cmdBuff = cmdBuffs[i] as WebGPUCommandBuffer;
this.numDrawCalls += cmdBuff.numDrawCalls;
this.numDispatches += cmdBuff.numDispatches;
this.numInstances += cmdBuff.numInstances;
this.numTris += cmdBuff.numTris;
}
@@ -61,7 +59,6 @@ export class WebGPUQueue extends Queue {
public clear (): void {
this.numDrawCalls = 0;
this.numDispatches = 0;
this.numInstances = 0;
this.numTris = 0;
}
+8 -27
View File
@@ -52,7 +52,6 @@ class Particle {
public pos = new Vec2(0, 0);
public startPos = new Vec2(0, 0);
public color = new Color(0, 0, 0, 255);
public curColor = { r: 0, g: 0, b: 0, a: 255 };
public deltaColor = { r: 0, g: 0, b: 0, a: 255 };
public size = 0;
public deltaSize = 0;
@@ -82,8 +81,6 @@ const pool = new ParticlePool((par: Particle): void => {
par.pos.set(Vec2.ZERO);
par.startPos.set(Vec2.ZERO);
par.color.set(0, 0, 0, 255);
par.curColor.r = par.curColor.g = par.curColor.b = 0;
par.curColor.a = 255;
par.deltaColor.r = par.deltaColor.g = par.deltaColor.b = 0;
par.deltaColor.a = 255;
par.size = 0;
@@ -114,7 +111,6 @@ export class Simulator {
private elapsed = 0;
private emitCounter = 0;
private _worldRotation = 0;
private _parentAlpha = 0.0;
private declare sys: ParticleSystem2D;
constructor (system) {
@@ -173,10 +169,10 @@ export class Simulator {
const endColor = psys.endColor;
const endColorVar = psys.endColorVar;
particle.curColor.r = sr = clamp(startColor.r + startColorVar.r * (random() - 0.5) * 2, 0, 255);
particle.curColor.g = sg = clamp(startColor.g + startColorVar.g * (random() - 0.5) * 2, 0, 255);
particle.curColor.b = sb = clamp(startColor.b + startColorVar.b * (random() - 0.5) * 2, 0, 255);
particle.curColor.a = sa = clamp(startColor.a + startColorVar.a * (random() - 0.5) * 2, 0, 255);
particle.color.r = sr = clamp(startColor.r + startColorVar.r * (random() - 0.5) * 2, 0, 255);
particle.color.g = sg = clamp(startColor.g + startColorVar.g * (random() - 0.5) * 2, 0, 255);
particle.color.b = sb = clamp(startColor.b + startColorVar.b * (random() - 0.5) * 2, 0, 255);
particle.color.a = sa = clamp(startColor.a + startColorVar.a * (random() - 0.5) * 2, 0, 255);
particle.deltaColor.r = (clamp(endColor.r + endColorVar.r * (random() - 0.5) * 2, 0, 255) - sr) / timeToLive;
particle.deltaColor.g = (clamp(endColor.g + endColorVar.g * (random() - 0.5) * 2, 0, 255) - sg) / timeToLive;
particle.deltaColor.b = (clamp(endColor.b + endColorVar.b * (random() - 0.5) * 2, 0, 255) - sb) / timeToLive;
@@ -333,14 +329,6 @@ export class Simulator {
Vec4.toArray(vbuf, _col, offset + 32);
}
private _updateColor (): void {
const selfNode = this.sys.node;
const parentNode = selfNode.parent;
const uiProps = selfNode._uiProps;
const parentOpacity = parentNode ? parentNode._uiProps.opacity : 1.0;
this._parentAlpha = uiProps.localOpacity * parentOpacity;
}
public step (dt: number): void {
const assembler = this.sys.assembler as Particle2DAssembler;
const psys = this.sys;
@@ -391,8 +379,6 @@ export class Simulator {
this.updateUVs();
}
this._updateColor();
// Used to reduce memory allocation / creation within the loop
let particleIdx = 0;
while (particleIdx < particles.length) {
@@ -445,15 +431,10 @@ export class Simulator {
}
// color
particle.curColor.r += particle.deltaColor.r * dt;
particle.curColor.g += particle.deltaColor.g * dt;
particle.curColor.b += particle.deltaColor.b * dt;
particle.curColor.a += particle.deltaColor.a * dt;
particle.color.r = particle.curColor.r;
particle.color.g = particle.curColor.g;
particle.color.b = particle.curColor.b;
particle.color.a = particle.curColor.a * this._parentAlpha;
particle.color.r += particle.deltaColor.r * dt;
particle.color.g += particle.deltaColor.g * dt;
particle.color.b += particle.deltaColor.b * dt;
particle.color.a += particle.deltaColor.a * dt;
// size
particle.size += particle.deltaSize * dt;
+1 -1
View File
@@ -797,7 +797,7 @@ export class ParticleSystem2D extends UIRenderer {
}
private _startPreview (): void {
if (!this._preview) {
if (this._preview) {
this.resetSystem();
}
}
+2 -2
View File
@@ -23,7 +23,7 @@
*/
import { ccclass, type, serializable, editable, range } from 'cc.decorator';
import { approxGE, approxLT, repeat } from '../core/math';
import { repeat } from '../core/math';
import CurveRange from './animator/curve-range';
import type { ParticleSystem } from './particle-system';
@@ -108,7 +108,7 @@ export default class Burst {
let preFrameTime = repeat(psys.time - psys.startDelay.evaluate(0, 1), psys.duration) - dt;
preFrameTime = (preFrameTime > 0.0) ? preFrameTime : 0.0;
const curFrameTime = repeat(psys.time - psys.startDelay.evaluate(0, 1), psys.duration);
if (approxGE(this._curTime, preFrameTime) && approxLT(this._curTime, curFrameTime)) {
if (this._curTime >= preFrameTime && this._curTime < curFrameTime) {
psys.emit(this.count.evaluate(this._curTime / psys.duration, 1), dt - (curFrameTime - this._curTime));
this._curTime += this.repeatInterval;
--this._remainingCount;
+1 -10
View File
@@ -25,7 +25,7 @@
import { ccclass, help, executeInEditMode, menu, tooltip, displayOrder, type, serializable,
range, visible, override, displayName } from 'cc.decorator';
import { Material, Texture2D } from '../asset/assets';
import { Vec3, cclegacy, Vec4, Vec2, CCBoolean, Color } from '../core';
import { Vec3, cclegacy, Vec4, Vec2, CCBoolean } from '../core';
import { LineModel } from './models/line-model';
import { builtinResMgr } from '../asset/asset-manager';
import CurveRange from './animator/curve-range';
@@ -296,15 +296,6 @@ export class Line extends ModelRenderer {
}
}
public updateColor (): void {
if (this._color) {
if (this._models[0]) {
const lineModel = this._models[0] as LineModel;
lineModel.addLineVertexData(this._positions, this._width, this._color);
}
}
}
protected _onMaterialModified (index: number, material: Material | null): void {
super._onMaterialModified(index, material);
const matIns = this.getMaterialInstance(0);
+4 -14
View File
@@ -29,8 +29,7 @@ import { Vec2, Vec3 } from '../core/math';
* @zh 此类生成噪声纹理。
*/
export class ParticleNoise {
private static readonly DEFAULT_PERMUTATION: readonly number[] = [
151, 160, 137, 91, 90, 15,
private permutation: number[] = [151, 160, 137, 91, 90, 15,
131, 13, 201, 95, 96, 53, 194, 233, 7, 225, 140, 36, 103, 30, 69, 142, 8, 99, 37, 240, 21, 10, 23,
190, 6, 148, 247, 120, 234, 75, 0, 26, 197, 62, 94, 252, 219, 203, 117, 35, 11, 32, 57, 177, 33,
88, 237, 149, 56, 87, 174, 20, 125, 136, 171, 168, 68, 175, 74, 165, 71, 134, 139, 48, 27, 166,
@@ -45,19 +44,9 @@ export class ParticleNoise {
138, 236, 205, 93, 222, 114, 67, 29, 24, 72, 243, 141, 128, 195, 78, 66, 215, 61, 156, 180,
];
private static build512 (src: readonly number[] | number[]): Uint8Array {
const p = new Uint8Array(512);
for (let i = 0; i < 256; i++) { p[256 + i] = p[i] = src[i]; }
return p;
}
private permutation: number[] = ParticleNoise.DEFAULT_PERMUTATION as number[];
private permutation512: Uint8Array = ParticleNoise.build512(ParticleNoise.DEFAULT_PERMUTATION);
constructor (permutation?: number[]) {
if (permutation) {
this.permutation = permutation.slice();
this.permutation512 = ParticleNoise.build512(this.permutation);
this.permutation = permutation;
}
}
@@ -72,7 +61,8 @@ export class ParticleNoise {
* @returns @en Texture pixel generated. @zh 返回生成的噪声纹理值。
*/
public noise (x: number, y: number, z: number, min = 0, max = 1): number {
const p: Uint8Array = this.permutation512;
const p: number[] = new Array(512);
for (let i = 0; i < 256; i++) { p[256 + i] = p[i] = this.permutation[i]; }
const X = Math.floor(x) & 255; // FIND UNIT CUBE THAT
const Y = Math.floor(y) & 255; // CONTAINS POINT.
+7 -9
View File
@@ -42,7 +42,7 @@ import VelocityOvertimeModule from './animator/velocity-overtime';
import Burst from './burst';
import ShapeModule from './emitter/shape-module';
import { ParticleCullingMode, ParticleSpace } from './enum';
import { isCurveTwoValues, particleEmitZAxis } from './particle-general-function';
import { particleEmitZAxis } from './particle-general-function';
import ParticleSystemRenderer from './renderer/particle-system-renderer-data';
import TrailModule from './renderer/trail';
import { ParticleSystemRendererBase } from './renderer/particle-system-renderer-base';
@@ -141,7 +141,7 @@ export class ParticleSystem extends ModelRenderer {
@range([0, Number.POSITIVE_INFINITY])
@displayOrder(10)
@tooltip('i18n:particle_system.startSizeY')
@visible(function (this: ParticleSystem): boolean { return this.startSize3D; }) // eslint-disable-line func-names, comma-dangle
@visible(function (this: ParticleSystem): boolean { return this.startSize3D; })
public startSizeY = new CurveRange();
/**
@@ -153,7 +153,7 @@ export class ParticleSystem extends ModelRenderer {
@range([0, Number.POSITIVE_INFINITY])
@displayOrder(10)
@tooltip('i18n:particle_system.startSizeZ')
@visible(function (this: ParticleSystem): boolean { return this.startSize3D; }) // eslint-disable-line func-names, comma-dangle
@visible(function (this: ParticleSystem): boolean { return this.startSize3D; })
public startSizeZ = new CurveRange();
/**
@@ -184,7 +184,7 @@ export class ParticleSystem extends ModelRenderer {
@radian
@displayOrder(12)
@tooltip('i18n:particle_system.startRotationX')
@visible(function (this: ParticleSystem): boolean { return this.startRotation3D; }) // eslint-disable-line func-names, comma-dangle
@visible(function (this: ParticleSystem): boolean { return this.startRotation3D; })
public startRotationX = new CurveRange();
/**
@@ -196,7 +196,7 @@ export class ParticleSystem extends ModelRenderer {
@radian
@displayOrder(12)
@tooltip('i18n:particle_system.startRotationY')
@visible(function (this: ParticleSystem): boolean { return this.startRotation3D; }) // eslint-disable-line func-names, comma-dangle
@visible(function (this: ParticleSystem): boolean { return this.startRotation3D; })
public startRotationY = new CurveRange();
/**
@@ -1455,18 +1455,16 @@ export class ParticleSystem extends ModelRenderer {
if (!self._isEmitting) return;
const randTime = isCurveTwoValues(self.rateOverTime) ? pseudoRandom(randomRangeInt(0, bits.INT_MAX)) : 1;
// emit by rateOverTime
self._emitRateTimeCounter += self.rateOverTime.evaluate(self._time / self.duration, randTime)! * dt;
self._emitRateTimeCounter += self.rateOverTime.evaluate(self._time / self.duration, 1)! * dt;
if (self._emitRateTimeCounter > 1) {
const emitNum = Math.floor(self._emitRateTimeCounter);
self._emitRateTimeCounter -= emitNum;
self.emit(emitNum, dt);
}
const randDist = isCurveTwoValues(self.rateOverDistance) ? pseudoRandom(randomRangeInt(0, bits.INT_MAX)) : 1;
// emit by rateOverDistance
const rateOverDistance = self.rateOverDistance.evaluate(self._time / self.duration, randDist)!;
const rateOverDistance = self.rateOverDistance.evaluate(self._time / self.duration, 1)!;
if (rateOverDistance > 0) {
Vec3.copy(self._oldWPos, self._curWPos);
self.node.getWorldPosition(self._curWPos);
@@ -747,12 +747,6 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas
this._defines[ROTATION_OVER_TIME_MODULE_ENABLE] = enable;
this._defines[INSTANCE_PARTICLE] = this._useInstance;
const matIns: MaterialInstance | null = ps.getMaterialInstance(0);
if (matIns === null || matIns === undefined) {
ps.setSharedMaterial(mat.parent, 0); // set material[0] as material for ui-mesh-renderer to use
ps.setMaterialInstance(mat, 0);
}
mat.recompileShaders(this._defines);
if (this._model) {
this._model.updateMaterial(mat);
-4
View File
@@ -60,7 +60,6 @@ interface IProfilerState {
frame: ICounterOption;
fps: ICounterOption;
draws: ICounterOption;
dispatches: ICounterOption;
instances: ICounterOption;
tricount: ICounterOption;
logic: ICounterOption;
@@ -74,7 +73,6 @@ interface IProfilerState {
const _profileInfo = {
fps: { desc: `Framerate (FPS)`, below: 30, average: _average, isInteger: true },
draws: { desc: 'Draw call', isInteger: true },
dispatches: { desc: 'Dispatch call', isInteger: true },
frame: { desc: 'Frame time (ms)', min: 0, max: 50, average: _average },
instances: { desc: 'Instance Count', isInteger: true },
tricount: { desc: 'Triangle', isInteger: true },
@@ -588,8 +586,6 @@ export class Profiler extends System {
const device = this._device!;
(profilerStats.draws.counter as PerfCounter).value = device.numDrawCalls;
// Native (JSB) devices expose no dispatch stats yet; WebGPU does. Treat missing as 0.
(profilerStats.dispatches.counter as PerfCounter).value = device.numDispatches ?? 0;
(profilerStats.instances.counter as PerfCounter).value = device.numInstances;
(profilerStats.bufferMemory.counter as PerfCounter).value = device.memoryStatus.bufferSize / (1024 * 1024);
(profilerStats.textureMemory.counter as PerfCounter).value = device.memoryStatus.textureSize / (1024 * 1024);
+1 -23
View File
@@ -31,7 +31,7 @@ import { murmurhash2_32_gc, errorID, assertID, cclegacy, warnID } from '../../co
import {
BufferUsageBit, DynamicStateFlagBit, DynamicStateFlags, Feature, GetTypeSize, MemoryUsageBit, PrimitiveMode, Type, Color,
BlendState, BlendTarget, Buffer, BufferInfo, BufferViewInfo, DepthStencilState, DescriptorSet,
DescriptorSetInfo, DescriptorSetLayout, Device, RasterizerState, Sampler, SampleCount, Texture, Shader, PipelineLayout, deviceManager, UniformBlock,
DescriptorSetInfo, DescriptorSetLayout, Device, RasterizerState, Sampler, Texture, Shader, PipelineLayout, deviceManager, UniformBlock,
} from '../../gfx';
import { EffectAsset } from '../../asset/assets/effect-asset';
import { IProgramInfo, programLib } from './program-lib';
@@ -139,28 +139,6 @@ export class Pass {
if (bsInfo.isA2C !== undefined) { bs.isA2C = bsInfo.isA2C; }
if (bsInfo.isIndepend !== undefined) { bs.isIndepend = bsInfo.isIndepend; }
if (bsInfo.blendColor !== undefined) { bs.blendColor = bsInfo.blendColor as Color; }
// A2C (Alpha to Coverage) requires MSAA to be effective.
// Without multiple subsamples, A2C behaves like alpha-test at ~0.5 and should be disabled.
// Disable A2C when neither the pass nor the global framebuffer has MSAA enabled:
// - passWantsMultisample: pass explicitly requests isMultisample
// - globalMsaaEnabled: swapchain has MSAA (native: colorTexture.samples > X1;
// WebGL: antialias from gl.getContextAttributes(), since WebGL
// MSAA is controlled at context level, not texture level)
if (bs.isA2C) {
const gfxDevice = deviceManager.gfxDevice as any;
const gl: WebGL2RenderingContext | WebGLRenderingContext | null = gfxDevice.gl || null;
const ctxAttrs = gl && gl.getContextAttributes();
const antialias: boolean = !!(ctxAttrs && ctxAttrs.antialias);
const passWantsMultisample = (info.rasterizerState && info.rasterizerState.isMultisample === true);
const swapchain = deviceManager.swapchain;
const colorTex = swapchain && swapchain.colorTexture;
const msaaDisabled = (!colorTex || (colorTex && colorTex.samples <= SampleCount.X1))
|| !antialias || !passWantsMultisample;
if (msaaDisabled) {
bs.isA2C = false;
}
}
}
pass._rs.assign(info.rasterizerState as RasterizerState);
pass._dss.assign(info.depthStencilState as DepthStencilState);
-3
View File
@@ -91,9 +91,6 @@ export class PointLight extends Light {
* @en The luminance of the light source in LDR mode.
* @zh LDR 模式下光源的亮度。
*/
get luminanceLDR (): number {
return this._luminanceLDR;
}
set luminanceLDR (value: number) {
this._luminanceLDR = value;
}
+39 -71
View File
@@ -67,13 +67,11 @@ export class ReflectionProbe {
protected readonly _size = v3(1, 1, 1);
/**
* @en Camera used for probe rendering (cubemap capture or planar reflection).
* @zh 用于探针渲染的相机(cubemap 采集或平面反射)
* @en Render cubemap's camera
* @zh 渲染cubemap的相机
*/
private _camera: Camera | null = null;
private _previewCamera: Camera | null = null;
/**
* @en Unique id of probe.
* @zh probe的唯一id
@@ -186,9 +184,6 @@ export class ReflectionProbe {
set visibility (val) {
this._visibility = val;
this._camera!.visibility = this._visibility;
if (this._previewCamera) {
this._previewCamera.visibility = this._visibility;
}
}
/**
@@ -325,21 +320,6 @@ export class ReflectionProbe {
this._needRender = true;
}
/**
* @engineInternal
* @mangle
*/
public renderPreviewPlanarReflection (sourceCamera: Camera): Camera {
if (!this._previewCamera) {
this._createCamera(new Node(`${this.cameraNode.name} Preview Reflection`), true);
}
const previewCamera = this._previewCamera!;
this._syncCameraParams(sourceCamera, previewCamera);
this._transformReflectionCamera(sourceCamera, previewCamera);
this._needRender = true;
return previewCamera;
}
public switchProbeType (type: ProbeType, sourceCamera: Camera | null): void {
if (type === ProbeType.CUBE) {
this._needRender = false;
@@ -377,12 +357,6 @@ export class ReflectionProbe {
this._camera.destroy();
this._camera = null;
}
if (this._previewCamera) {
const cameraNode = this._previewCamera.node;
this._previewCamera.destroy();
this._previewCamera = null;
cameraNode.destroy();
}
for (let i = 0; i < this.bakedCubeTextures.length; i++) {
this.bakedCubeTextures[i].destroy();
}
@@ -436,54 +410,48 @@ export class ReflectionProbe {
return true;
}
private _syncCameraParams (camera: Camera, targetCamera: Camera = this.camera): void {
targetCamera.projectionType = camera.projectionType;
targetCamera.orthoHeight = camera.orthoHeight;
targetCamera.nearClip = camera.nearClip;
targetCamera.farClip = camera.farClip;
targetCamera.fov = camera.fov;
targetCamera.clearFlag = camera.clearFlag;
targetCamera.clearColor = camera.clearColor;
targetCamera.priority = camera.priority - 1;
targetCamera.resize(camera.width, camera.height);
private _syncCameraParams (camera: Camera): void {
this.camera.projectionType = camera.projectionType;
this.camera.orthoHeight = camera.orthoHeight;
this.camera.nearClip = camera.nearClip;
this.camera.farClip = camera.farClip;
this.camera.fov = camera.fov;
this.camera.clearFlag = camera.clearFlag;
this.camera.clearColor = camera.clearColor;
this.camera.priority = camera.priority - 1;
this.camera.resize(camera.width, camera.height);
}
private _createCamera (cameraNode: Node, preview = false): Camera | null {
private _createCamera (cameraNode: Node): Camera | null {
const root = cclegacy.director.root;
let camera = preview ? this._previewCamera : this._camera;
if (!camera) {
camera = root.createCamera();
if (!camera) return null;
camera.initialize({
if (!this._camera) {
this._camera = root.createCamera();
if (!this._camera) return null;
this._camera.initialize({
name: cameraNode.name,
node: cameraNode,
projection: CameraProjection.PERSPECTIVE,
window: preview || EDITOR ? root.mainWindow : root.tempWindow,
window: EDITOR ? root && root.mainWindow : root && root.tempWindow,
priority: 0,
cameraType: CameraType.DEFAULT,
trackingType: TrackingType.NO_TRACKING,
});
if (preview) {
this._previewCamera = camera;
} else {
this._camera = camera;
}
}
camera.setViewportInOrientedSpace(new Rect(0, 0, 1, 1));
camera.fovAxis = CameraFOVAxis.VERTICAL;
camera.fov = toRadian(90);
camera.orthoHeight = 10;
camera.nearClip = 1;
camera.farClip = 1000;
camera.clearColor = this._backgroundColor;
camera.clearDepth = 1.0;
camera.clearStencil = 0.0;
camera.clearFlag = this._clearFlag;
camera.visibility = this._visibility;
camera.aperture = CameraAperture.F16_0;
camera.shutter = CameraShutter.D125;
camera.iso = CameraISO.ISO100;
return camera;
this._camera.setViewportInOrientedSpace(new Rect(0, 0, 1, 1));
this._camera.fovAxis = CameraFOVAxis.VERTICAL;
this._camera.fov = toRadian(90);
this._camera.orthoHeight = 10;
this._camera.nearClip = 1;
this._camera.farClip = 1000;
this._camera.clearColor = this._backgroundColor;
this._camera.clearDepth = 1.0;
this._camera.clearStencil = 0.0;
this._camera.clearFlag = this._clearFlag;
this._camera.visibility = this._visibility;
this._camera.aperture = CameraAperture.F16_0;
this._camera.shutter = CameraShutter.D125;
this._camera.iso = CameraISO.ISO100;
return this._camera;
}
private _resetCameraParams (): void {
@@ -510,10 +478,10 @@ export class ReflectionProbe {
return rt;
}
private _transformReflectionCamera (sourceCamera: Camera, targetCamera: Camera = this.camera): void {
private _transformReflectionCamera (sourceCamera: Camera): void {
const offset = Vec3.dot(this.node.worldPosition, this.node.up);
this._reflect(this._cameraWorldPos, sourceCamera.node.worldPosition, this.node.up, offset);
targetCamera.node.worldPosition = this._cameraWorldPos;
this.cameraNode.worldPosition = this._cameraWorldPos;
Vec3.transformQuat(this._forward, Vec3.FORWARD, sourceCamera.node.worldRotation);
this._reflect(this._forward, this._forward, this.node.up, 0);
@@ -526,14 +494,14 @@ export class ReflectionProbe {
Quat.fromViewUp(this._cameraWorldRotation, this._forward, this._up);
targetCamera.node.worldRotation = this._cameraWorldRotation;
this.cameraNode.worldRotation = this._cameraWorldRotation;
targetCamera.update(true);
this.camera.update(true);
// Transform the plane from world space to reflection camera space use the inverse transpose matrix
const viewSpaceProbe = new Vec4(this.node.up.x, this.node.up.y, this.node.up.z, -Vec3.dot(this.node.up, this.node.worldPosition));
viewSpaceProbe.transformMat4(targetCamera.matView.clone().invert().transpose());
targetCamera.calculateObliqueMat(viewSpaceProbe);
viewSpaceProbe.transformMat4(this.camera.matView.clone().invert().transpose());
this.camera.calculateObliqueMat(viewSpaceProbe);
}
private _reflect (out: Vec3, point: Vec3, normal: Vec3, offset: number): Vec3 {
-3
View File
@@ -102,9 +102,6 @@ export class SphereLight extends Light {
* @en The luminance of the light source in LDR mode
* @zh LDR 模式下光源的亮度
*/
get luminanceLDR (): number {
return this._luminanceLDR;
}
set luminanceLDR (value: number) {
this._luminanceLDR = value;
}
+2 -14
View File
@@ -22,6 +22,7 @@
THE SOFTWARE.
****************************************************************************/
import { Buffer, Framebuffer, Texture, Viewport } from '../../gfx';
import { genHashValue } from './define';
import { VectorGraphColorMap } from './effect';
import { DefaultVisitor, depthFirstSearch, ReferenceGraphView } from './graph';
import { LayoutGraphData } from './layout-graph';
@@ -198,6 +199,7 @@ class PassVisitor implements RenderGraphVisitor {
resourceGraph.visitVertex(this._resVisitor, vertID);
}
}
genHashValue(pass);
}
}
applyID (id: number, resId: number): void {
@@ -231,21 +233,7 @@ class PassVisitor implements RenderGraphVisitor {
compute (value: ComputePass): void {
this._currPass = value;
const rg = context.renderGraph;
if (rg.getValid(this.passID)) {
// Avoid revisiting a valid pass and recursive dependency cycles.
return;
}
rg.setValid(this.passID, true);
// Trace READ dependencies only; WRITE dependencies are produced by this pass.
const resourceGraph = this.context.resourceGraph;
for (const [computeName, cViews] of value.computeViews) {
if (!cViews.length || cViews[0].accessType !== AccessType.READ) continue;
const vertID = resourceGraph.find(computeName);
if (vertID !== 0xFFFFFFFF) {
this._resVisitor.resID = vertID;
resourceGraph.visitVertex(this._resVisitor, vertID);
}
}
}
resolve (value: ResolvePass): void {
// noop
+13 -11
View File
@@ -48,7 +48,6 @@ import {
Device,
deviceManager,
DispatchInfo,
Feature,
Format,
Framebuffer,
FramebufferInfo,
@@ -57,7 +56,9 @@ import {
InputAssemblerInfo,
LoadOp,
MemoryUsageBit,
PipelineBindPoint,
PipelineState,
PipelineStateInfo,
Rect,
RenderPass,
RenderPassInfo,
@@ -1909,23 +1910,26 @@ class PreRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor {
renderScene.preRecord();
}
dispatch (value: Dispatch): void {
if (!context.device.hasFeature(Feature.COMPUTE_SHADER)) return;
let pso: PipelineState | null = null;
const devicePass = this.currPass as DeviceComputePass;
const pass = value.material?.passes[value.passID];
pass?.update();
const shader = pass?.getShaderVariant();
if (pass && shader) {
pso = PipelineStateManager.getOrCreateComputePipelineState(deviceManager.gfxDevice, pass, shader);
if (pass !== null && shader !== null) {
const psoInfo = new PipelineStateInfo(
shader,
pass?.pipelineLayout,
);
psoInfo.bindPoint = PipelineBindPoint.COMPUTE;
pso = deviceManager.gfxDevice.createPipelineState(psoInfo);
}
const cmdBuff = context.commandBuffer;
if (pso && pass) {
if (pso) {
cmdBuff.bindPipelineState(pso);
const layoutStage = devicePass.renderLayout;
const layoutDesc = layoutStage!.descriptorSet!;
cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, layoutDesc);
cmdBuff.bindDescriptorSet(SetIndex.MATERIAL, pass.descriptorSet);
}
const gx = value.threadGroupCountX;
@@ -1961,14 +1965,12 @@ class PostRenderVisitor extends BaseRenderVisitor implements RenderGraphVisitor
computeSubpass (value: ComputeSubpass): void {
// do nothing
}
compute (value: ComputePass): void {
if (!context.device.hasFeature(Feature.COMPUTE_SHADER)) return;
const cmdBuff = context.commandBuffer;
(cmdBuff as any).submitComputePass();
}
resolve (value: ResolvePass): void {
// do nothing
}
compute (value: ComputePass): void {
// do nothing
}
copy (value: CopyPass): void {
// do nothing
}
+2 -22
View File
@@ -195,13 +195,10 @@ function sceneCulling (
}
models.push(model);
} else if (probe.probeType === ProbeType.CUBE) {
if (!wBounds || !model.bakeToReflectionProbe) {
continue;
}
if (!isVisible(model, visibility)) {
continue;
}
if (isIntersectAABB(wBounds, probe.boundingBox!)) {
if (wBounds && isIntersectAABB(wBounds, probe.boundingBox!)) {
continue;
}
models.push(model);
@@ -478,8 +475,7 @@ export class SceneCulling {
);
// Get or create render queue
const renderCamera = sceneData.light.probe ? sceneData.light.probe.camera : sceneData.camera;
const renderQueueID = this.getOrCreateRenderQueue(renderQueueKey, sceneData.flags, renderCamera);
const renderQueueID = this.getOrCreateRenderQueue(renderQueueKey, sceneData.flags, sceneData.camera);
// add render queue query
const renderQueueQuery = this.cullingPools.renderQueueQueryRecycle.add();
@@ -560,11 +556,7 @@ export class SceneCulling {
private executeSphereLightCulling (light: SphereLight, frustumCullingResult: Array<Model>, lightBoundsCullingResult: Array<Model>): void {
const lightAABB = light.aabb;
const visibility = light.visibility;
for (const model of frustumCullingResult) {
if (!isVisible(model, visibility)) {
continue;
}
const modelBounds = model.worldBounds;
if (!modelBounds || intersect.aabbWithAABB(modelBounds, lightAABB)) {
lightBoundsCullingResult.push(model);
@@ -575,11 +567,7 @@ export class SceneCulling {
private executeSpotLightCulling (light: SpotLight, frustumCullingResult: Array<Model>, lightBoundsCullingResult: Array<Model>): void {
const lightAABB = light.aabb;
const lightFrustum: Frustum = light.frustum;
const visibility = light.visibility;
for (const model of frustumCullingResult) {
if (!isVisible(model, visibility)) {
continue;
}
const modelBounds = model.worldBounds;
if (!modelBounds || (intersect.aabbWithAABB(lightAABB, modelBounds) && intersect.aabbFrustum(modelBounds, lightFrustum))) {
lightBoundsCullingResult.push(model);
@@ -589,11 +577,7 @@ export class SceneCulling {
private executePointLightCulling (light: PointLight, frustumCullingResult: Array<Model>, lightBoundsCullingResult: Array<Model>): void {
const lightAABB = light.aabb;
const visibility = light.visibility;
for (const model of frustumCullingResult) {
if (!isVisible(model, visibility)) {
continue;
}
const modelBounds = model.worldBounds;
if (!modelBounds || intersect.aabbWithAABB(lightAABB, modelBounds)) {
lightBoundsCullingResult.push(model);
@@ -606,12 +590,8 @@ export class SceneCulling {
frustumCullingResult: Array<Model>,
lightBoundsCullingResult: Array<Model>,
): void {
const visibility = light.visibility;
rangedDirLightBoundingBox.transform(light.node!.worldMatrix, null, null, null, lightAABB);
for (const model of frustumCullingResult) {
if (!isVisible(model, visibility)) {
continue;
}
const modelBounds = model.worldBounds;
if (!modelBounds || intersect.aabbWithAABB(lightAABB, modelBounds)) {
lightBoundsCullingResult.push(model);
+8 -28
View File
@@ -258,19 +258,9 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild
addSceneOfCamera (camera: Camera, light: LightInfo, sceneFlags = SceneFlags.NONE, name = 'Camera'): void {
const lightTarget = light.light;
const scene = light.probe?.node?.scene?.renderScene || undefined;
this._addScene(camera, sceneFlags, lightTarget, scene, light);
this.addScene(camera, sceneFlags, lightTarget);
}
addScene (camera: Camera, sceneFlags = SceneFlags.NONE, light: Light | undefined | null = null, scene: RenderScene | undefined = undefined): SceneBuilder {
return this._addScene(camera, sceneFlags, light, scene);
}
private _addScene (
camera: Camera,
sceneFlags: SceneFlags,
light: Light | undefined | null,
scene: RenderScene | undefined,
lightInfo: LightInfo | null = null,
): SceneBuilder {
const sceneData = renderGraphPool.createSceneData(
scene || camera.scene,
camera,
@@ -278,9 +268,6 @@ export class WebRenderQueueBuilder extends WebSetter implements RenderQueueBuild
light && !(sceneFlags & SceneFlags.SHADOW_CASTER) ? CullingFlags.CAMERA_FRUSTUM | CullingFlags.LIGHT_BOUNDS : CullingFlags.CAMERA_FRUSTUM,
light,
);
if (lightInfo) {
sceneData.light.reset(lightInfo.light, lightInfo.level, lightInfo.culledByLight, lightInfo.probe);
}
const renderData = renderGraphPool.createRenderData();
const sceneId = this._renderGraph.addVertex<RenderGraphValue.Scene>(RenderGraphValue.Scene, sceneData, 'Scene', '', renderData, !DEBUG, this._vertID);
if (!(sceneFlags & SceneFlags.NON_BUILTIN)) {
@@ -864,11 +851,7 @@ export class WebComputePassBuilder extends WebSetter implements ComputePassBuild
this._renderGraph.setName(this._vertID, name);
}
addTexture (name: string, slotName: string, sampler: Sampler | null = null): void {
this._addComputeResource(name, AccessType.READ, slotName);
if (sampler) {
const descriptorID = this._lg.attributeIndex.get(slotName)!;
this._data.samplers.set(descriptorID, sampler);
}
throw new Error('Method not implemented.');
}
addStorageBuffer (name: string, accessType: AccessType, slotName: string): void {
this._addComputeResource(name, accessType, slotName);
@@ -1667,16 +1650,13 @@ export class WebPipeline extends WebSetter implements BasicPipeline {
this._compiler = new Compiler(this, this._renderGraph, this._resourceGraph, this._lg);
}
this._compiler.compile(this._renderGraph);
} else {
this._renderGraph.x.forEach((vert) => {
if (vert.t === RenderGraphValue.RasterPass) {
genHashValue(vert.j as RasterPass);
}
});
}
this._renderGraph.x.forEach((vert, v) => {
if (vert.t !== RenderGraphValue.RasterPass) {
return;
}
if (DEBUG && !this._renderGraph!.getValid(v)) {
return;
}
genHashValue(vert.j as RasterPass);
});
}
execute (): void {
@@ -1264,6 +1264,15 @@ export class WebProgramLibrary implements ProgramLibrary {
if (passSet) {
info.setLayouts.push(passSet);
}
const phaseSet = getDescriptorSetLayout(
this.layoutGraph,
subpassOrPassID,
phaseID,
UpdateFrequency.PER_PHASE,
);
if (phaseSet) {
info.setLayouts.push(phaseSet);
}
const batchSet = getProgramDescriptorSetLayout(
device,
lg,
@@ -1284,15 +1293,6 @@ export class WebProgramLibrary implements ProgramLibrary {
if (instanceSet) {
info.setLayouts.push(instanceSet);
}
const phaseSet = getDescriptorSetLayout(
this.layoutGraph,
subpassOrPassID,
phaseID,
UpdateFrequency.PER_PHASE,
);
if (phaseSet) {
info.setLayouts.push(phaseSet);
}
programData.pipelineLayout = device.createPipelineLayout(info);
return programData.pipelineLayout;
}
+48 -88
View File
@@ -28,9 +28,8 @@ import { UNIFORM_LIGHTMAP_TEXTURE_BINDING, UNIFORM_REFLECTION_PROBE_BLEND_CUBEMA
UNIFORM_REFLECTION_PROBE_TEXTURE_BINDING, ENABLE_PROBE_BLEND,
IRenderPass,
getPassPool } from './define';
import { BufferUsageBit, MemoryUsageBit, Device, InputAssembler, InputAssemblerInfo,
import { BufferUsageBit, MemoryUsageBit, Device, Texture, InputAssembler, InputAssemblerInfo,
Attribute, Buffer, BufferInfo, CommandBuffer, Shader, DescriptorSet } from '../gfx';
import type { Texture } from '../gfx';
import { RecyclePool } from '../core/memop';
export function instancingCompareFn (l: InstancedBuffer, r: InstancedBuffer): number {
@@ -66,7 +65,6 @@ export class InstancedBuffer {
public sortRender: IRenderPass;
private declare _passPool: RecyclePool<IRenderPass>;
private declare _device: Device;
private readonly _instanceMap = new Map<string, IInstancedItem[]>();
constructor (pass: Pass) {
this._device = pass.device;
this.pass = pass;
@@ -83,7 +81,6 @@ export class InstancedBuffer {
});
this._passPool.reset();
this.instances.length = 0;
this._instanceMap.clear();
}
public merge (subModel: SubModel, passIdx: number, shaderImplant: Shader | null = null): void {
@@ -109,109 +106,72 @@ export class InstancedBuffer {
this.sortRender.hash = hash;
this.sortRender.shaderId = shader.typedID;
this.sortRender.passIdx = passIdx;
for (let i = 0; i < this.instances.length; ++i) {
const instance = this.instances[i];
if (instance.ia.indexBuffer?.objectID !== sourceIA.indexBuffer?.objectID || instance.count >= MAX_CAPACITY) { continue; }
const key = `${sourceIA.indexBuffer?.objectID ?? 0}/${lightingMap.objectID}/${useReflectionProbeType}/`
+ `${reflectionProbeCubemap.objectID}/${reflectionProbePlanarMap.objectID}/`
+ `${ENABLE_PROBE_BLEND ? reflectionProbeBlendCubemap!.objectID : 0}/${stride}`;
const mappedInstances = this._instanceMap.get(key);
if (mappedInstances) {
for (let i = 0; i < mappedInstances.length; ++i) {
const instance = mappedInstances[i];
if (instance.count >= MAX_CAPACITY) { continue; }
this._appendInstance(instance, attrs.buffer, shader, descriptorSet);
return;
// check same binding
if (instance.lightingMap.objectID !== lightingMap.objectID) {
continue;
}
if (instance.useReflectionProbeType !== useReflectionProbeType) {
continue;
}
if (instance.reflectionProbeCubemap.objectID !== reflectionProbeCubemap.objectID) {
continue;
}
if (instance.reflectionProbePlanarMap.objectID !== reflectionProbePlanarMap.objectID) {
continue;
}
if (ENABLE_PROBE_BLEND && instance.reflectionProbeBlendCubemap!.objectID !== reflectionProbeBlendCubemap!.objectID) {
continue;
}
if (instance.stride !== stride) {
// we allow this considering both baked and non-baked
// skinning models may be present in the same buffer
continue;
}
if (instance.count >= instance.capacity) { // resize buffers
instance.capacity <<= 1;
const newSize = instance.stride * instance.capacity;
const oldData = instance.data;
instance.data = new Uint8Array(newSize);
instance.data.set(oldData);
instance.vb.resize(newSize);
}
instance.shader = shader;
instance.descriptorSet = descriptorSet;
instance.data.set(attrs.buffer, instance.stride * instance.count++);
this.hasPendingModels = true;
return;
}
this._createInstance(
key,
sourceIA,
attrs.attributes,
attrs.buffer,
stride,
shader,
descriptorSet,
lightingMap,
useReflectionProbeType,
reflectionProbeCubemap,
reflectionProbePlanarMap,
reflectionProbeBlendCubemap,
);
}
private _appendInstance (instance: IInstancedItem, data: Uint8Array, shader: Shader, descriptorSet: DescriptorSet): void {
if (instance.count >= instance.capacity) { // resize buffers
instance.capacity = Math.min(instance.capacity << 1, MAX_CAPACITY);
const newSize = instance.stride * instance.capacity;
const oldData = instance.data;
instance.data = new Uint8Array(newSize);
instance.data.set(oldData);
instance.vb.resize(newSize);
}
instance.shader = shader;
instance.descriptorSet = descriptorSet;
instance.data.set(data, instance.stride * instance.count++);
this.hasPendingModels = true;
}
private _createInstance (
key: string,
sourceIA: InputAssembler,
instancedAttributes: Attribute[],
instanceData: Uint8Array,
stride: number,
shader: Shader,
descriptorSet: DescriptorSet,
lightingMap: Texture,
useReflectionProbeType: number,
reflectionProbeCubemap: Texture,
reflectionProbePlanarMap: Texture,
reflectionProbeBlendCubemap: Texture | null,
): void {
const newSize = stride * INITIAL_CAPACITY;
// Create a new instance
const vb = this._device.createBuffer(new BufferInfo(
BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST,
MemoryUsageBit.HOST | MemoryUsageBit.DEVICE,
newSize,
stride * INITIAL_CAPACITY,
stride,
));
const data = new Uint8Array(newSize);
const data = new Uint8Array(stride * INITIAL_CAPACITY);
const vertexBuffers = sourceIA.vertexBuffers.slice();
const attributes = sourceIA.attributes.slice();
const indexBuffer = sourceIA.indexBuffer;
for (let i = 0; i < instancedAttributes.length; i++) {
const attr = instancedAttributes[i];
for (let i = 0; i < attrs.attributes.length; i++) {
const attr = attrs.attributes[i];
const newAttr = new Attribute(attr.name, attr.format, attr.isNormalized, vertexBuffers.length, true);
attributes.push(newAttr);
}
data.set(instanceData);
data.set(attrs.buffer);
vertexBuffers.push(vb);
const iaInfo = new InputAssemblerInfo(attributes, vertexBuffers, indexBuffer);
const ia = this._device.createInputAssembler(iaInfo);
const instance = {
count: 1,
capacity: INITIAL_CAPACITY,
vb,
data,
ia,
stride,
shader,
descriptorSet,
lightingMap,
reflectionProbeCubemap,
reflectionProbePlanarMap,
useReflectionProbeType,
reflectionProbeBlendCubemap,
} as IInstancedItem;
this.instances.push(instance);
let mappedInstances = this._instanceMap.get(key);
if (!mappedInstances) {
mappedInstances = [];
this._instanceMap.set(key, mappedInstances);
}
mappedInstances.push(instance);
// eslint-disable-next-line max-len
this.instances.push({ count: 1, capacity: INITIAL_CAPACITY, vb, data, ia, stride, shader, descriptorSet, lightingMap, reflectionProbeCubemap, reflectionProbePlanarMap, useReflectionProbeType, reflectionProbeBlendCubemap });
this.hasPendingModels = true;
}
@@ -220,7 +180,7 @@ export class InstancedBuffer {
const instance = this.instances[i];
if (!instance.count) { continue; }
instance.ia.instanceCount = instance.count;
cmdBuff.updateBuffer(instance.vb, instance.data.buffer as ArrayBuffer, instance.count * instance.stride);
cmdBuff.updateBuffer(instance.vb, instance.data);
}
}
+1 -32
View File
@@ -22,7 +22,7 @@
THE SOFTWARE.
*/
import { Shader, RenderPass, InputAssembler, Device, PipelineState, InputState, PipelineStateInfo, PipelineBindPoint } from '../gfx';
import { Shader, RenderPass, InputAssembler, Device, PipelineState, InputState, PipelineStateInfo } from '../gfx';
import { Pass } from '../render-scene/core/pass';
export class PipelineStateManager {
@@ -30,8 +30,6 @@ export class PipelineStateManager {
private static _PSOHashMap: Map<number, PipelineState> = new Map<number, PipelineState>();
private static _computePSOHashMap: Map<number, PipelineState> = new Map<number, PipelineState>();
// pass is only needed on TS.
static getOrCreatePipelineState (device: Device, pass: Pass, shader: Shader, renderPass: RenderPass, ia: InputAssembler): PipelineState {
const hash1 = pass.hash;
@@ -61,33 +59,4 @@ export class PipelineStateManager {
return pso;
}
/**
* @en Get or create a compute pipeline state.
* A compute pipeline only depends on the shader variant and the pipeline layout,
* both carried by the pass, so the cache key is `pass.hash ^ shader.typedID`,
* mirroring the graphics-side hash mechanism without renderPass/inputState factors.
* @zh 获取或创建计算管线状态。
* 计算管线仅依赖于着色器变体与管线布局(均由 pass 携带),
* 因此缓存键为 `pass.hash ^ shader.typedID`,与图形侧哈希机制一致但不包含 renderPass/顶点布局因子。
*/
static getOrCreateComputePipelineState (device: Device, pass: Pass, shader: Shader): PipelineState {
const hash1 = pass.hash;
const hash2 = shader.typedID;
const newHash = hash1 ^ hash2;
let pso = this._computePSOHashMap.get(newHash);
if (!pso) {
const pipelineLayout = pass.pipelineLayout;
const psoInfo = new PipelineStateInfo(
shader,
pipelineLayout,
);
psoInfo.bindPoint = PipelineBindPoint.COMPUTE;
pso = device.createPipelineState(psoInfo);
this._computePSOHashMap.set(newHash, pso);
}
return pso;
}
}
+5 -2
View File
@@ -29,6 +29,7 @@ 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';
@@ -82,16 +83,18 @@ export class PlanarShadowQueue {
const scene = camera.scene!;
const frustum = camera.frustum;
const shadowVisible = camera.visibility !== 0;
const shadowVisible = (camera.visibility & Layers.BitMask.DEFAULT) !== 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) {
if (model.enabled && model.node && model.castShadow
&& (model.node && ((visibility & model.node.layer) === model.node.layer))) {
this._castModels.push(model);
}
}
@@ -27,7 +27,7 @@ import { IRenderFlowInfo, RenderFlow } from '../render-flow';
import { ReflectionProbeStage } from './reflection-probe-stage';
import { RenderFlowTag } from '../pipeline-serialization';
import { RenderPipeline } from '../render-pipeline';
import { Camera, CameraUsage } from '../../render-scene/scene/camera';
import { Camera } from '../../render-scene/scene/camera';
import { ProbeType, ReflectionProbe } from '../../render-scene/scene/reflection-probe';
import { cclegacy } from '../../core';
@@ -65,13 +65,7 @@ export class ReflectionProbeFlow extends RenderFlow {
const probes = cclegacy.internal.reflectionProbeManager.getProbes() as ReflectionProbe[];
for (let i = 0; i < probes.length; i++) {
if (probes[i].needRender) {
if (probes[i].probeType === ProbeType.PLANAR) {
let reflectionCamera: Camera | undefined;
if (EDITOR && camera.cameraUsage === CameraUsage.PREVIEW) {
reflectionCamera = probes[i].renderPreviewPlanarReflection(camera);
}
this._renderStage(camera, probes[i], reflectionCamera);
} else if (EDITOR) {
if (EDITOR || probes[i].probeType === ProbeType.PLANAR) {
this._renderStage(camera, probes[i]);
}
}
@@ -81,12 +75,12 @@ export class ReflectionProbeFlow extends RenderFlow {
public destroy (): void {
super.destroy();
}
private _renderStage (camera: Camera, probe: ReflectionProbe, reflectionCamera?: Camera): void {
private _renderStage (camera: Camera, probe: ReflectionProbe): void {
for (let i = 0; i < this._stages.length; i++) {
const probeStage = this._stages[i] as ReflectionProbeStage;
if (probe.probeType === ProbeType.PLANAR) {
cclegacy.internal.reflectionProbeManager.updatePlanarMap(probe, null);
probeStage.setUsageInfo(probe, probe.realtimePlanarTexture!.window!.framebuffer, reflectionCamera);
probeStage.setUsageInfo(probe, probe.realtimePlanarTexture!.window!.framebuffer);
probeStage.render(camera);
cclegacy.internal.reflectionProbeManager.updatePlanarMap(probe, probe.realtimePlanarTexture!.getGFXTexture());
} else {
@@ -55,7 +55,6 @@ export class ReflectionProbeStage extends RenderStage {
private _frameBuffer: Framebuffer | null = null;
private _renderArea = new Rect();
private _probe: ReflectionProbe | null = null;
private _reflectionCamera: Camera | null = null;
private _probeRenderQueue!: RenderReflectionProbeQueue;
private _rgbeColor = new Vec3();
@@ -69,10 +68,9 @@ export class ReflectionProbeStage extends RenderStage {
* @param probe
* @param frameBuffer
*/
public setUsageInfo (probe: ReflectionProbe, frameBuffer: Framebuffer, reflectionCamera?: Camera): void {
public setUsageInfo (probe: ReflectionProbe, frameBuffer: Framebuffer): void {
this._probe = probe;
this._frameBuffer = frameBuffer;
this._reflectionCamera = reflectionCamera ?? null;
}
public destroy (): void {
@@ -110,9 +108,8 @@ export class ReflectionProbeStage extends RenderStage {
public render (camera: Camera): void {
const pipeline = this._pipeline;
const cmdBuff = pipeline.commandBuffers[0];
const probeCamera = this._reflectionCamera ?? this._probe!.camera;
this._probeRenderQueue.gatherRenderObjects(this._probe!, camera, cmdBuff, probeCamera);
pipeline.pipelineUBO.updateCameraUBO(probeCamera);
this._probeRenderQueue.gatherRenderObjects(this._probe!, camera, cmdBuff);
pipeline.pipelineUBO.updateCameraUBO(this._probe!.camera);
this._renderArea.x = 0;
this._renderArea.y = 0;
@@ -121,10 +118,10 @@ export class ReflectionProbeStage extends RenderStage {
const renderPass = this._frameBuffer!.renderPass;
if (probeCamera.clearFlag & ClearFlagBit.COLOR) {
this._rgbeColor.x = probeCamera.clearColor.x;
this._rgbeColor.y = probeCamera.clearColor.y;
this._rgbeColor.z = probeCamera.clearColor.z;
if (this._probe!.camera.clearFlag & ClearFlagBit.COLOR) {
this._rgbeColor.x = this._probe!.camera.clearColor.x;
this._rgbeColor.y = this._probe!.camera.clearColor.y;
this._rgbeColor.z = this._probe!.camera.clearColor.z;
const rgbe = packRGBE(this._rgbeColor);
colors[0].x = rgbe.x;
colors[0].y = rgbe.y;
@@ -137,8 +134,8 @@ export class ReflectionProbeStage extends RenderStage {
this._frameBuffer!,
this._renderArea,
colors,
probeCamera.clearDepth,
probeCamera.clearStencil,
this._probe!.camera.clearDepth,
this._probe!.camera.clearStencil,
);
cmdBuff.bindDescriptorSet(SetIndex.GLOBAL, pipeline.descriptorSet);
@@ -320,8 +320,7 @@ export class RenderAdditiveLightQueue {
const lightIdx = _lightIndices[l];
const light = validPunctualLights[lightIdx];
const visibility = light.visibility;
if (((visibility & model.node.layer) === model.node.layer)
|| (visibility & model.visFlags)) {
if (((visibility & model.node.layer) === model.node.layer)) {
switch (batchingScheme) {
case BatchingSchemes.INSTANCING: {
const buffer = pass.getInstancedBuffer(lightIdx);
@@ -79,14 +79,13 @@ export class RenderReflectionProbeQueue {
public constructor (pipeline: PipelineRuntime) {
this._pipeline = pipeline;
}
public gatherRenderObjects (probe: ReflectionProbe, camera: Camera, cmdBuff: CommandBuffer, reflectionCamera?: Camera): void {
public gatherRenderObjects (probe: ReflectionProbe, camera: Camera, cmdBuff: CommandBuffer): void {
this.clear();
const scene = camera.scene!;
const sceneData = this._pipeline.pipelineSceneData;
const skybox = sceneData.skybox;
const probeCamera = reflectionCamera ?? probe.camera;
if (skybox.enabled && skybox.model && (probeCamera.clearFlag & SkyBoxFlagValue.VALUE)) {
if (skybox.enabled && skybox.model && (probe.camera.clearFlag & SkyBoxFlagValue.VALUE)) {
this.add(skybox.model);
}
@@ -106,7 +105,7 @@ export class RenderReflectionProbeQueue {
if (geometry.intersect.aabbWithAABB(model.worldBounds, probe.boundingBox!)) {
this.add(model);
}
} else if (geometry.intersect.aabbFrustum(model.worldBounds, probeCamera.frustum)) {
} else if (geometry.intersect.aabbFrustum(model.worldBounds, probe.camera.frustum)) {
this.add(model);
}
}
+2 -2
View File
@@ -195,8 +195,8 @@ export function sceneCulling (sceneData: PipelineSceneData, pipelineUBO: Pipelin
csmLayerObjects.push(getRenderObject(model, camera));
}
if ((model.node && ((visibility & model.node.layer) === model.node.layer))
|| (visibility & model.visFlags)) {
if (model.node && ((visibility & model.node.layer) === model.node.layer)
|| (visibility & model.visFlags)) {
// frustum culling
if (model.worldBounds && !geometry.intersect.aabbFrustum(model.worldBounds, camera.frustum)) {
return;
+9 -13
View File
@@ -27,7 +27,7 @@ import { Material, Texture2D } from '../asset/assets';
import { error, errorID, logID, warnID } from '../core/platform/debug';
import { Enum, EnumType, ccenum } from '../core/value-types/enum';
import { Node, NodeEventType } from '../scene-graph';
import { CCObjectFlags, Color, RecyclePool, js, math } from '../core';
import { CCObjectFlags, Color, RecyclePool, js } from '../core';
import { SkeletonData } from './skeleton-data';
import type { Graphics } from '../2d/components/graphics';
import { UIRenderer } from '../2d/framework/ui-renderer';
@@ -850,12 +850,14 @@ export class Skeleton extends UIRenderer {
warnID(16410);
}
const skeletonInfo = this._skeletonCache!.getSkeletonInfo(this._skeletonData!);
if (this._skeletonInfo !== skeletonInfo || (!this._skeletonInfo && !skeletonInfo)) {
if (this._skeletonInfo !== skeletonInfo) {
this._destroySkeletonInfo(this._skeletonCache);
if (!skeletonInfo && this._cacheMode === SpineAnimationCacheMode.PRIVATE_CACHE) {
this._animCache = this._skeletonCache!.initAnimationCache(this.skeletonData!.uuid, this._skeletonData!, this._animationName);
}
this._skeletonInfo = this._skeletonCache!.createSkeletonInfo(this._skeletonData!);
}
if (this._skeletonInfo) {
this._skeleton = this._skeletonInfo.skeleton!;
}
} else {
@@ -1587,7 +1589,7 @@ export class Skeleton extends UIRenderer {
const socket = this._sockets[i];
if (socket.path && socket.target) {
const boneIdx = this._cachedSockets.get(socket.path);
if (boneIdx == null || boneIdx < 0) {
if (!boneIdx) {
error(`Skeleton data does not contain path ${socket.path}`);
continue;
}
@@ -1881,16 +1883,10 @@ export class Skeleton extends UIRenderer {
*/
public setTrackCompleteListener (entry: spine.TrackEntry, listener: TrackListener2): void {
const onComplete = (trackEntry: spine.TrackEntry): void => {
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);
}
const loopCount = Math.floor(trackEntry.trackTime / trackEntry.animationEnd);
listener(trackEntry, loopCount);
// this._instance.setListener(listenerID, spine.EventType.event);
// this._listener!.event = listener;
};
TrackEntryListeners.getListeners(entry, this._instance!).complete = onComplete;
}
+3 -5
View File
@@ -1537,7 +1537,6 @@ export class Terrain extends Component {
* @zh 获得地形信息
*/
@type(TerrainInfo)
@visible(false)
public get info (): TerrainInfo {
const ti = new TerrainInfo();
ti.tileSize = this.tileSize;
@@ -1816,11 +1815,11 @@ export class Terrain extends Component {
* @zh 获得纹理层
*/
public getLayer (id: number): TerrainLayer | null {
if (id === -1 || id === undefined) {
if (id === -1) {
return null;
}
return this._layerList[id] || null;
return this._layerList[id];
}
/**
@@ -2585,8 +2584,7 @@ export class Terrain extends Component {
const index1 = j * this.blockCount[0] + i;
for (let l = 0; l < TERRAIN_MAX_BLEND_LAYERS; ++l) {
const oldVal = this._layerBuffer[index1 * TERRAIN_MAX_BLEND_LAYERS + l];
layerBuffer[index0 * TERRAIN_MAX_BLEND_LAYERS + l] = oldVal !== undefined ? oldVal : -1;
layerBuffer[index0 * TERRAIN_MAX_BLEND_LAYERS + l] = this._layerBuffer[index1 * TERRAIN_MAX_BLEND_LAYERS + l];
}
}
}
+7 -54
View File
@@ -93,8 +93,8 @@ enum State {
export enum ButtonEventType {
/**
* @event click
* @param {Event.EventCustom} event
* @param {Button} button - The Button component.
* @param {EventTouch} event - The original touch event, undefined if the click is triggered by XR.
*/
CLICK = 'click',
}
@@ -156,16 +156,16 @@ export enum ButtonEventType {
*
* @example
* ```ts
* import { log } from 'cc';
* import { log, Node } from 'cc';
* // Add an event to the button.
* button.node.on(Node.EventType.TOUCH_START, (event) => {
* log("This is a callback after the trigger event");
* });
* // You could also add a click event
* // The callback receives the Button component and the original touch event (if available).
* button.on(Button.EventType.CLICK, (button, event) => {
* log('button clicked');
* });
* // Note: In this way, you can't get the touch event info, so use it wisely.
* button.node.on(Node.EventType.CLICK, (button) => {
* //The event is a custom event, you could get the Button component via first argument
* })
* ```
*/
@ccclass('cc.Button')
@@ -586,53 +586,6 @@ export class Button extends Component {
super();
}
/**
* @en
* Register a Button event listener on the component. Button events are dispatched by the owner
* node, and this method is a shorthand which forwards the registration to the node, so
* `button.on(...)` and `button.node.on(...)` share the same listener registry.
* @zh
* 在组件上注册 Button 事件监听。Button 的事件由所属节点派发,此方法是 `this.node.on(type, ...)`
* 的便捷封装,`button.on(...)` 与 `button.node.on(...)` 共用同一份监听器。
* @param type @en Event type, e.g. [[ButtonEventType.CLICK]]. @zh 事件类型,如 [[ButtonEventType.CLICK]]。
* @param callback @en The callback, receives the Button component and the original event. @zh 回调函数,参数为 Button 组件与原始事件。
* @param target @en The target to be bound with. @zh 绑定的目标对象。
* @example
* ```ts
* button.on(Button.EventType.CLICK, (button, event) => {
* // clicked
* }, this);
* ```
*/
public on (type: ButtonEventType, callback: (button: Button, event?: EventTouch) => void, target?: unknown): void {
this.node.on(type, callback, target);
}
/**
* @en
* Remove a Button event listener registered via [[on]] or `button.node.on`. To remove a listener,
* the `type`, `callback` and `target` must match the registration.
* @zh
* 移除通过 [[on]] 或 `button.node.on` 注册的 Button 事件监听。`type`、`callback`、`target`
* 需与注册时一致才能正确移除。
*/
public off (type: ButtonEventType, callback?: (button: Button, event?: EventTouch) => void, target?: unknown): void {
this.node.off(type, callback, target);
}
/**
* @en
* Remove all Button event listeners registered with the given target.
* Note: this forwards to `node.targetOff`, so listeners registered by other components
* or by the engine internals on the same node with the same target are removed as well.
* @zh
* 移除指定 target 上注册的所有 Button 事件监听。注意:此方法会转发到 `node.targetOff`,
* 同一节点上其他组件或引擎内部以相同 target 注册的监听也会被一并移除。
*/
public targetOff (target: unknown): void {
this.node.targetOff(target);
}
public __preload (): void {
if (!this.target) {
this.target = this.node;
@@ -939,7 +892,7 @@ export class Button extends Component {
if (this._pressed) {
ComponentEventHandler.emitEvents(this.clickEvents, event);
this.node.emit(ButtonEventType.CLICK, this, event);
this.node.emit(ButtonEventType.CLICK, this);
}
this._pressed = false;
this._updateState();
+1 -1
View File
@@ -204,7 +204,7 @@ function align (node: Node, widget: Widget): void {
// TODO: type is hack, Change to the type actually used (Node or BaseNode) when BaseNode complete
function visitNode (node: any): void {
const widget = node.getComponent(Widget);
if (widget && widget.enabled && cclegacy.isValid(widget, true)) {
if (widget && widget.enabled) {
if (DEV) {
widget._validateTargetInDEV();
}
-3
View File
@@ -852,9 +852,6 @@ export class Widget extends Component {
}
public onDestroy (): void {
// `onDisable` is skipped when the component was never enabled by the scheduler
// (`IsOnEnableCalled` unset), so unregister here as well.
cclegacy._widgetManager?.remove(this);
this._removeParentEvent();
}
@@ -81,10 +81,9 @@ 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) * binormal +
(normalFromTangentSpace.y * normalStrength) * normalize(binormal) +
normalFromTangentSpace.z * normalize(normal);
}
@@ -222,9 +222,7 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {
vec3 R = normalize(reflect(-V, N));
#if CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_CUBE
if(s.reflectionProbeId < 0.0){
#if CC_USE_IBL
env = SampleReflectionProbe(cc_environment, R, s.roughness, cc_ambientGround.w, CC_USE_IBL == IBL_RGBE);
#endif
env = SampleReflectionProbe(cc_environment, R, s.roughness, cc_ambientGround.w, CC_USE_IBL == IBL_RGBE);
}else{
vec3 centerPos, boxHalfSize;
float mipCount;
@@ -249,9 +247,7 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {
env = unpackRGBE(probe);
#elif CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND || CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND_AND_SKYBOX
if (s.reflectionProbeId < 0.0) {
#if CC_USE_IBL
env = SampleReflectionProbe(cc_environment, R, s.roughness, cc_ambientGround.w, CC_USE_IBL == IBL_RGBE);
#endif
env = SampleReflectionProbe(cc_environment, R, s.roughness, cc_ambientGround.w, CC_USE_IBL == IBL_RGBE);
} else {
vec3 centerPos, boxHalfSize;
float mipCount;
@@ -260,10 +256,7 @@ vec4 CCStandardShadingBase (StandardSurface s, vec4 shadowPos) {
env = SampleReflectionProbe(cc_reflectionProbeCubemap, fixedR.xyz, s.roughness, mipCount, isReflectProbeUsingRGBE(s.reflectionProbeId));
if (s.reflectionProbeBlendId < 0.0) {
vec3 skyBoxEnv = vec3(0.0);
#if CC_USE_IBL
skyBoxEnv = SampleReflectionProbe(cc_environment, R, s.roughness, cc_ambientGround.w, CC_USE_IBL == IBL_RGBE) * lightIntensity;
#endif
vec3 skyBoxEnv = SampleReflectionProbe(cc_environment, R, s.roughness, cc_ambientGround.w, CC_USE_IBL == IBL_RGBE) * lightIntensity;
#if CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND_AND_SKYBOX
//blend with skybox
env = mix(env, skyBoxEnv, s.reflectionProbeBlendFactor);
@@ -99,10 +99,7 @@ vec3 SampleEnvironmentSpecular(samplerCube tex, in LightingIntermediateData ligh
vec4 fixedR = CalculateBoxProjectedDirection(R, worldPos, cubeCenterPos, boxHalfSize);
R = fixedR.xyz;
vec3 envmap = vec3(0.0);
#if CC_USE_IBL
envmap = SampleEnvironmentSpecular(cc_environment, lightingData, cc_ambientGround.w).xyz * cc_ambientSky.w;
#endif
vec3 envmap = SampleEnvironmentSpecular(cc_environment, lightingData, cc_ambientGround.w).xyz * cc_ambientSky.w;
#if CC_SURFACES_LIGHTING_ANISOTROPIC && CC_SURFACES_LIGHTING_ANISOTROPIC_ENVCONVOLUTION_COUNT
envSpec = EnvAnisotropicReflection(tex, fixedR.xyz, roughness, mipCount, lightingData.anisotropyShape, lightingData.V, lightingData.N, lightingData.T, lightingData.B);
#if CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_CUBE
@@ -162,9 +159,7 @@ vec3 CalculateEnvironmentSpecular(in LightingIntermediateData lightingData, floa
#if CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_CUBE
if(FSInput_reflectionProbeId < 0.0){
#if CC_USE_IBL
envSpec = SampleEnvironmentSpecular(cc_environment, lightingData, cc_ambientGround.w);
#endif
}else{
vec3 centerPos, boxHalfSize;
float mipCount;
@@ -186,9 +181,7 @@ vec3 CalculateEnvironmentSpecular(in LightingIntermediateData lightingData, floa
}
#elif CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND || CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND_AND_SKYBOX
if(FSInput_reflectionProbeId < 0.0){
#if CC_USE_IBL
envSpec = SampleEnvironmentSpecular(cc_environment, lightingData, cc_ambientGround.w);
#endif
}else{
vec3 centerPos, boxHalfSize;
float mipCount;
@@ -204,10 +197,7 @@ vec3 CalculateEnvironmentSpecular(in LightingIntermediateData lightingData, floa
if(FSInput_reflectionProbeBlendId < 0.0)
{
vec3 skyBoxEnv = vec3(0.0);
#if CC_USE_IBL
skyBoxEnv = SampleEnvironmentSpecular(cc_environment, lightingData, cc_ambientGround.w).rgb * lightIntensity;
#endif
vec3 skyBoxEnv = SampleEnvironmentSpecular(cc_environment, lightingData, cc_ambientGround.w).rgb * lightIntensity;
#if CC_USE_REFLECTION_PROBE == REFLECTION_PROBE_TYPE_BLEND_AND_SKYBOX
//blend with skybox
envSpec = mix(envSpec, skyBoxEnv, blendFactor);
@@ -145,7 +145,7 @@ void main() {
color = packRGBE(color.rgb); // for reflection-map
#else
color = CCSurfacesDebugDisplayInvalidNumber(color);
#if !CC_USE_FLOAT_OUTPUT
#if !CC_USE_FLOAT_OUTPUT || CC_IS_TRANSPARENCY_PASS
color.rgb = HDRToLDR(color.rgb);
color.rgb = LinearToSRGB(color.rgb);
#endif
@@ -434,8 +434,7 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
// Reflection Probe
cameraConfigs.enablePlanarReflectionProbe = cameraConfigs.isMainGameWindow
|| camera.cameraUsage === CameraUsage.SCENE_VIEW
|| camera.cameraUsage === CameraUsage.GAME_VIEW
|| camera.cameraUsage === CameraUsage.PREVIEW;
|| camera.cameraUsage === CameraUsage.GAME_VIEW;
// MSAA
cameraConfigs.enableMSAA = cameraConfigs.settings.msaa.enabled
@@ -552,7 +551,7 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
ppl, camera, pplConfigs.mobileMaxSpotLightShadowMaps);
}
this._tryAddReflectionProbePasses(ppl, cameraConfigs, id, mainLight, camera.scene, camera);
this._tryAddReflectionProbePasses(ppl, cameraConfigs, id, mainLight, camera.scene);
if (cameraConfigs.remainingPasses > 0 || cameraConfigs.enableShadingScale) {
context.colorName = cameraConfigs.enableShadingScale
@@ -631,7 +630,6 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
id: number,
mainLight: renderer.scene.DirectionalLight | null,
scene: renderer.RenderScene | null,
sourceCamera: renderer.scene.Camera,
): void {
const reflectionProbeManager = cclegacy.internal.reflectionProbeManager as ReflectionProbeManager | undefined;
if (!reflectionProbeManager) {
@@ -653,10 +651,6 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
if (!cameraConfigs.enablePlanarReflectionProbe) {
continue;
}
let reflectionCamera = probe.camera;
if (EDITOR && sourceCamera.cameraUsage === CameraUsage.PREVIEW) {
reflectionCamera = probe.renderPreviewPlanarReflection(sourceCamera);
}
const window: renderer.RenderWindow = probe.realtimePlanarTexture!.window!;
const colorName = `PlanarProbeRT${probeID}`;
const depthStencilName = `PlanarProbeDS${probeID}`;
@@ -669,8 +663,8 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
// Rendering
const probePass = ppl.addRenderPass(width, height, 'default');
probePass.name = `PlanarReflectionProbe${probeID}`;
this._buildReflectionProbePass(probePass, cameraConfigs, id, reflectionCamera, probe,
colorName, depthStencilName, mainLight);
this._buildReflectionProbePass(probePass, cameraConfigs, id, probe.camera,
colorName, depthStencilName, mainLight, scene);
} else if (EDITOR) {
for (let faceIdx = 0; faceIdx < probe.bakedCubeTextures.length; faceIdx++) {
probe.updateCameraDir(faceIdx);
@@ -686,8 +680,8 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
// Rendering
const probePass = ppl.addRenderPass(width, height, 'default');
probePass.name = `CubeProbe${probeID}${faceIdx}`;
this._buildReflectionProbePass(probePass, cameraConfigs, id, probe.camera, probe,
colorName, depthStencilName, mainLight);
this._buildReflectionProbePass(probePass, cameraConfigs, id, probe.camera,
colorName, depthStencilName, mainLight, scene);
}
probe.needRender = false;
}
@@ -702,10 +696,10 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
cameraConfigs: Readonly<CameraConfigs & ForwardPassConfigs>,
id: number,
camera: renderer.scene.Camera,
probe: renderer.scene.ReflectionProbe,
colorName: string,
depthStencilName: string,
mainLight: renderer.scene.DirectionalLight | null,
scene: renderer.RenderScene | null = null,
): void {
const QueueHint = rendering.QueueHint;
const SceneFlags = rendering.SceneFlags;
@@ -749,11 +743,11 @@ export class BuiltinForwardPassBuilder implements rendering.PipelinePassBuilder
// TODO(zhouzhenglong): Separate OPAQUE and MASK queue
// add opaque and mask queue
const lightInfo = new rendering.LightInfo(mainLight || null, 0, false, probe);
pass.addQueue(QueueHint.NONE, 'reflect-map') // Currently we put OPAQUE and MASK into one queue, so QueueHint is NONE
.addSceneOfCamera(camera,
lightInfo,
SceneFlags.OPAQUE | SceneFlags.MASK | SceneFlags.REFLECTION_PROBE);
.addScene(camera,
SceneFlags.OPAQUE | SceneFlags.MASK | SceneFlags.REFLECTION_PROBE,
mainLight || undefined,
scene ? scene : undefined);
}
private _addForwardRadiancePasses(
ppl: rendering.BasicPipeline,
+1 -1
View File
@@ -298,7 +298,7 @@ module.exports = link(mixin({
illuminance: 'Illuminance of the light',
luminous_power: 'Luminous power of the light',
luminance: 'Luminance of the light',
visibility: 'Visibility mask, declaring a set of node layers that will be visible in the current light source',
visibility: 'Visibility mask, declaring a set of node layers that will be visible to this valid punctual Light(Does not work with directional light)',
term: 'The photometric term currently being used',
size: 'Size of the light',
range: 'Range of the light',
+1 -1
View File
@@ -288,7 +288,7 @@ module.exports = link(mixin({
illuminance: '光源强度',
luminous_flux: '光通量',
luminance: '光亮度',
visibility: '可见性掩码,声明在当前光源中可见的节点层级集合',
visibility: '可见性掩码,声明在当前精确光源中可见的节点层级集合(对方向光不生效)',
term: '当前使用的光度学计量单位',
size: '光源大小',
range: '光源范围',
-7
View File
@@ -1,12 +1,5 @@
# ignore third_party code from clang-format checks
./cocos/bindings/auto/*
./cocos/base/std/**
./cocos/cocos-version.h
./cocos/editor-support/spine-wasm/**
./cocos/editor-support/spine/**
./cocos/gi/light-probe/predicates.cpp
./cocos/gi/light-probe/tetgen.cpp
./cocos/gi/light-probe/tetgen.h
./cocos/platform/openharmony/napi/**
./tools/**
./vendor/**
+4 -9
View File
@@ -3725,14 +3725,9 @@ 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 "${_CC_ENGINE_ARCHS}"
OSX_ARCHITECTURES "arm64;x86_64"
ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/archives
)
if(MACOSX)
@@ -3744,9 +3739,9 @@ if(APPLE)
)
elseif(IOS)
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.")
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.")
target_link_options(${ENGINE_NAME} PUBLIC -Wl,-ld_classic)
endif()
+1 -1
View File
@@ -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 -Wno-nontrivial-memcall")
set(WERROR_FLAGS " ${WERROR_FLAGS} -Wno-deprecated-declarations -Wno-deprecated-builtins -Wno-unqualified-std-cast-call")
elseif(LINUX)
set(WERROR_FLAGS " ${WERROR_FLAGS} -Wno-nullability-completeness -Wno-deprecated-declarations")
elseif(ANDROID)
+27 -29
View File
@@ -40,16 +40,16 @@ int32_t sorting2DCount{0};
CC_FORCE_INLINE void fillIndexBuffers(RenderDrawInfo* drawInfo) { // NOLINT(readability-convert-member-functions-to-static)
uint16_t* ib = drawInfo->getIDataBuffer();
UIMeshBuffer* buffer = drawInfo->getMeshBuffer();
uint32_t indexOffset = buffer->getIndexOffset();
uint16_t* indexb = drawInfo->getIbBuffer();
uint32_t indexCount = drawInfo->getIbCount();
memcpy(&ib[indexOffset], indexb, indexCount * sizeof(uint16_t));
indexOffset += indexCount;
buffer->setIndexOffset(indexOffset);
}
@@ -83,7 +83,7 @@ CC_FORCE_INLINE void fillColor(RenderEntity* entity, RenderDrawInfo* drawInfo) {
uint32_t size = drawInfo->getVbCount() * stride;
float* vbBuffer = drawInfo->getVbBuffer();
Color temp = entity->getColor();
uint32_t offset = 0;
for (int i = 0; i < size; i += stride) {
offset = i + 5;
@@ -91,9 +91,9 @@ CC_FORCE_INLINE void fillColor(RenderEntity* entity, RenderDrawInfo* drawInfo) {
// Spine set 'UIRenderer._useVertexOpacity = true', it uses RGBA32 (4 bytes) color and fills color in Skeleton._updateColor and spine/simple.ts assembler.
// So for Spine rendering, it will never go here to fill color.
vbBuffer[offset] = static_cast<float>(temp.r) / 255.0F;
vbBuffer[offset + 1] = static_cast<float>(temp.g) / 255.0F;
vbBuffer[offset + 2] = static_cast<float>(temp.b) / 255.0F;
vbBuffer[offset + 3] = entity->getOpacity();
vbBuffer[offset+1] = static_cast<float>(temp.g) / 255.0F;
vbBuffer[offset+2] = static_cast<float>(temp.b) / 255.0F;
vbBuffer[offset+3] = entity->getOpacity();
}
}
@@ -110,7 +110,7 @@ Batcher2d::Batcher2d(Root* root)
_root = root;
_device = _root->getDevice();
_stencilManager = StencilManager::getInstance();
_recordedRendererInfoQueue.reserve(100);
}
@@ -138,7 +138,7 @@ Batcher2d::~Batcher2d() { // NOLINT
_maskAttributes.clear();
}
ccstd::vector<RecordedRendererInfo>& Batcher2d::getRecordedRendererInfoQueue() {
ccstd::vector<RecordedRendererInfo> &Batcher2d::getRecordedRendererInfoQueue() {
return _recordedRendererInfoQueue;
}
@@ -170,11 +170,11 @@ void Batcher2d::fillBuffersAndMergeBatches() {
for (auto* rootNode : _rootNodeArr) {
// _batches will add by generateBatch
walk(rootNode, 1, false);
if (ENABLE_SORTING_2D && sorting2DCount > 0) {
flushRecordedUIRenderers();
}
generateBatch(_currEntity, _currDrawInfo);
auto* scene = rootNode->getScene()->getRenderScene();
@@ -186,7 +186,7 @@ void Batcher2d::fillBuffersAndMergeBatches() {
}
}
void Batcher2d::handleUIRenderer(RenderEntity* entity) { // NOLINT(misc-no-recursion)
void Batcher2d::handleUIRenderer(RenderEntity *entity) { // NOLINT(misc-no-recursion)
uint32_t size = entity->getRenderDrawInfosSize();
for (uint32_t i = 0; i < size; i++) {
auto* drawInfo = entity->getRenderDrawInfoAt(i);
@@ -195,25 +195,25 @@ void Batcher2d::handleUIRenderer(RenderEntity* entity) { // NOLINT(misc-no-recur
entity->setVBColorDirty(false);
}
int32_t Batcher2d::recordUIRenderer(RenderEntity* entity) {
int32_t Batcher2d::recordUIRenderer(RenderEntity *entity) {
if (!ENABLE_SORTING_2D) return -1;
auto& queue = getRecordedRendererInfoQueue();
auto& info = queue.emplace_back();
auto &queue = getRecordedRendererInfoQueue();
auto &info = queue.emplace_back();
info.renderEntity = entity;
return static_cast<int32_t>(queue.size() - 1);
}
void Batcher2d::flushRecordedUIRenderers() { // NOLINT(misc-no-recursion)
if (!ENABLE_SORTING_2D) return;
auto& queue = getRecordedRendererInfoQueue();
auto &queue = getRecordedRendererInfoQueue();
if (queue.empty()) return;
std::stable_sort(queue.begin(), queue.end(), [](const auto& a, const auto& b) {
std::stable_sort(queue.begin(), queue.end(), [](const auto &a, const auto &b){
return a.renderEntity->getPriority() < b.renderEntity->getPriority();
});
for (const auto& info : queue) {
auto* entity = info.renderEntity;
for (const auto &info : queue) {
auto *entity = info.renderEntity;
if (entity) {
handleUIRenderer(entity);
}
@@ -227,13 +227,13 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { /
}
bool breakWalk = false;
auto* entity = static_cast<RenderEntity*>(node->getUserData());
const bool isCurrentColorDirty = node->_isColorDirty() || parentColorDirty;
const float localOpacity = node->_getLocalOpacity();
// Keep the same logic as which in batcher-2d.ts
const float finalOpacity = parentOpacity * localOpacity * (entity ? entity->getColorAlpha() : 1.F);
node->_setFinalOpacity(finalOpacity);
const bool visible = math::isNotEqualF(finalOpacity, 0);
if (entity) {
@@ -244,7 +244,7 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { /
entity->setOpacity(finalOpacity);
entity->setVBColorDirty(true);
}
if (ENABLE_SORTING_2D && sorting2DCount > 0) {
if (entity->getIsMask()) {
flushRecordedUIRenderers();
@@ -257,7 +257,7 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { /
handleUIRenderer(entity);
}
}
if (entity->getRenderEntityType() == RenderEntityType::CROSSED) {
breakWalk = true;
}
@@ -271,7 +271,7 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { /
walk(child, thisOpacity, isCurrentColorDirty);
}
}
if (isCurrentColorDirty) {
node->_setColorDirty(false);
}
@@ -283,7 +283,7 @@ void Batcher2d::walk(Node* node, float parentOpacity, bool parentColorDirty) { /
flushRecordedUIRenderers();
}
}
if (visible && _stencilManager->getMaskStackSize() > 0) {
handlePostRender(entity);
}
@@ -521,7 +521,7 @@ void Batcher2d::generateBatch(RenderEntity* entity, RenderDrawInfo* drawInfo) {
curdrawBatch->setFirstIndex(indexOffset);
curdrawBatch->setIndexCount(indexCount);
curdrawBatch->fillPass(_currMaterial, depthStencil, dssHash);
const auto& passes = curdrawBatch->getPasses();
const auto &passes = curdrawBatch->getPasses();
if (!passes.empty()) {
const auto& pass = passes.at(0);
if (entity->getUseLocal()) {
@@ -695,8 +695,6 @@ void Batcher2d::reset() {
_currSampler = nullptr;
// stencilManager
_stencilManager->setMaskStackSize(0);
_stencilManager->setStencilStage(static_cast<uint32_t>(StencilStage::DISABLED));
}
void Batcher2d::insertMaskBatch(RenderEntity* entity) {
+7 -7
View File
@@ -41,13 +41,13 @@ using UIMeshBufferArray = ccstd::vector<UIMeshBuffer*>;
using UIMeshBufferMap = ccstd::unordered_map<uint16_t, UIMeshBufferArray>;
struct RecordedRendererInfo {
RenderEntity* renderEntity{nullptr};
RenderEntity *renderEntity{nullptr};
};
class Batcher2d final {
public:
static void setSorting2DCount(int32_t v);
Batcher2d();
explicit Batcher2d(Root* root);
~Batcher2d();
@@ -87,10 +87,10 @@ private:
void createClearModel();
gfx::DescriptorSet* getDescriptorSet(gfx::Texture* texture, gfx::Sampler* sampler, const gfx::DescriptorSetLayout* dsLayout);
ccstd::vector<RecordedRendererInfo>& getRecordedRendererInfoQueue();
void handleUIRenderer(RenderEntity* entity);
int32_t recordUIRenderer(RenderEntity* entity);
ccstd::vector<RecordedRendererInfo> &getRecordedRendererInfoQueue();
void handleUIRenderer(RenderEntity *entity);
int32_t recordUIRenderer(RenderEntity *entity);
void flushRecordedUIRenderers();
StencilManager* _stencilManager{nullptr};
@@ -103,7 +103,7 @@ private:
// manage memory manually
ccstd::vector<scene::DrawBatch2D*> _batches;
memop::Pool<scene::DrawBatch2D> _drawBatchPool;
ccstd::vector<RecordedRendererInfo> _recordedRendererInfoQueue;
// weak reference
+5 -5
View File
@@ -24,8 +24,8 @@
#pragma once
#include "2d/renderer/UIMeshBuffer.h"
#include "base/Macros.h"
#include "base/Ptr.h"
#include "base/Macros.h"
#include "base/TypeDef.h"
#include "bindings/utils/BindingUtils.h"
#include "core/ArrayBuffer.h"
@@ -115,7 +115,7 @@ public:
inline void setIsMeshBuffer(bool isMeshBuffer) {
_drawInfoAttrs._isMeshBuffer = isMeshBuffer ? 1 : 0;
}
inline bool isVertexPositionInWorld() const {
return _drawInfoAttrs._isVertexPositionInWorld != 0;
}
@@ -262,9 +262,9 @@ private:
struct DrawInfoAttrs {
RenderDrawInfoType _drawInfoType{RenderDrawInfoType::COMP};
bool _vertDirty{false};
uint8_t _isMeshBuffer : 1;
uint8_t _isVertexPositionInWorld : 1;
uint8_t _padding : 6;
uint8_t _isMeshBuffer: 1;
uint8_t _isVertexPositionInWorld: 1;
uint8_t _padding: 6;
uint8_t _stride{0};
uint16_t _bufferId{0};
uint16_t _accId{0};
+2 -2
View File
@@ -33,11 +33,11 @@ RenderEntity::RenderEntity(RenderEntityType type) : _renderEntityType(type) {
} else {
ccnew_placement(&_dynamicDrawInfos) ccstd::vector<RenderDrawInfo*>();
}
_entityAttrLayout.enabledIndex = 0;
_entityAttrLayout.useLocal = 0;
_entityAttrLayout.paddings = 0;
_entitySharedBufferActor.initialize(&_entityAttrLayout, sizeof(EntityAttrLayout));
}
+9 -9
View File
@@ -49,7 +49,7 @@ enum class MaskMode : uint8_t {
MASK_NODE_INVERTED
};
enum class FillColorType : uint8_t {
enum class FillColorType: uint8_t {
COLOR = 0,
VERTEX,
};
@@ -62,9 +62,9 @@ struct EntityAttrLayout {
uint8_t colorA{255};
uint8_t maskMode{0};
FillColorType fillColorType{FillColorType::COLOR};
uint8_t enabledIndex : 1;
uint8_t useLocal : 1;
uint8_t paddings : 6;
uint8_t enabledIndex: 1;
uint8_t useLocal: 1;
uint8_t paddings: 6;
uint8_t paddings2{0};
};
@@ -99,7 +99,7 @@ public:
inline void setUseLocal(bool useLocal) {
_entityAttrLayout.useLocal = useLocal;
}
inline FillColorType getFillColorType() const { return _entityAttrLayout.fillColorType; }
inline Node* getNode() const { return _node; }
@@ -142,7 +142,7 @@ public:
inline RenderDrawInfo* getRenderDrawInfoAt(uint32_t index) {
return _renderEntityType == RenderEntityType::STATIC ? &(_staticDrawInfos[index]) : _dynamicDrawInfos[index];
}
inline uint32_t getPriority() const { return _entityAttrLayout.priority; }
private:
@@ -152,7 +152,7 @@ private:
// weak reference
Node* _renderTransform{nullptr};
bindings::NativeMemorySharedToScriptActor _entitySharedBufferActor;
union {
@@ -160,13 +160,13 @@ private:
ccstd::vector<RenderDrawInfo*> _dynamicDrawInfos;
};
EntityAttrLayout _entityAttrLayout;
StencilStage _stencilStage{StencilStage::DISABLED};
RenderEntityType _renderEntityType{RenderEntityType::STATIC};
uint8_t _staticDrawInfoSize{0};
bool _vbColorDirty{true};
uint8_t _paddings[1];
float _opacity{1.0F};
};
+3 -3
View File
@@ -23,12 +23,12 @@
****************************************************************************/
#pragma once
#include "base/Macros.h"
#include "base/Ptr.h"
#include "base/Macros.h"
#include "base/TypeDef.h"
#include "renderer/gfx-base/GFXBuffer.h"
#include "renderer/gfx-base/GFXDef-common.h"
#include "renderer/gfx-base/GFXInputAssembler.h"
#include "renderer/gfx-base/GFXDef-common.h"
#include "renderer/gfx-base/GFXBuffer.h"
namespace cc {
+4 -4
View File
@@ -58,13 +58,13 @@ void UIModelProxy::activeSubModels() {
auto* vertexBuffer = _device->createBuffer({
gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST,
gfx::MemoryUsageBit::DEVICE,
65536 * _stride, // Uint16 can address 65536 vertices (indices 0–65535)
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,
65536 * sizeof(uint16_t) * 2, // Uint16 can address 65536 vertices (indices 0–65535)
65536 * sizeof(uint16_t) * 2, // Uint16 can address 65536 vertices (indices 0–65535)
sizeof(uint16_t),
});
gfx::BufferList vbReference;
@@ -133,8 +133,8 @@ void UIModelProxy::clear() {
return;
}
const auto& subModels = _model->getSubModels();
for (const auto& subModel : subModels) {
auto* ia = subModel->getInputAssembler();
for (const auto &subModel : subModels) {
auto *ia = subModel->getInputAssembler();
ia->setVertexCount(0);
ia->setIndexCount(0);
}
+2 -2
View File
@@ -531,14 +531,14 @@ void Mesh::initialize() {
uint32_t vertexCount = _struct.vertexBundles[prim.vertexBundelIndices[0]].view.count;
#if CC_OPTIMIZE_MESH_DATA
if (vertexCount <= 65536) { // Uint16 can address 65536 vertices (indices 0–65535)
dstStride >>= 1; // Reduce to short.
dstStride >>= 1; // Reduce to short.
dstSize >>= 1;
} else if (!gfxDevice->hasFeature(gfx::Feature::ELEMENT_INDEX_UINT)) {
continue; // Ignore this primitive
}
#else
if (!gfxDevice->hasFeature(gfx::Feature::ELEMENT_INDEX_UINT)) {
if (vertexCount > 65536) { // Uint16 can address 65536 vertices (indices 0–65535)
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;
}
+3 -12
View File
@@ -222,22 +222,13 @@ Mesh::ICreateInfo MeshUtils::createMeshInfo(const IGeometry &geometry, const ccs
// Fill index buffer.
ArrayBuffer::Ptr indexBuffer;
uint32_t idxCount = 0;
uint32_t idxStride = 2;
gfx::Format indexFormat = gfx::Format::R16UI;
const uint32_t idxStride = 2;
if (geometry.indices.has_value()) {
const ccstd::vector<uint32_t> &indices = geometry.indices.value();
uint32_t maxIndex = 0;
for (uint32_t idx : indices) {
maxIndex = std::max(maxIndex, idx);
}
if (maxIndex > std::numeric_limits<uint16_t>::max()) {
idxStride = 4;
indexFormat = gfx::Format::R32UI;
}
idxCount = static_cast<uint32_t>(indices.size());
indexBuffer = ccnew ArrayBuffer(idxStride * idxCount);
DataView indexBufferView(indexBuffer);
writeBuffer(indexBufferView, indices, indexFormat);
writeBuffer(indexBufferView, indices, gfx::Format::R16UI);
}
// Create primitive.
@@ -319,7 +310,7 @@ Mesh::ICreateInfo MeshUtils::createDynamicMeshInfo(const IDynamicGeometry &geome
if (aOptions.has_value()) {
options = aOptions.value();
}
gfx::AttributeList attributes;
uint32_t stream = 0U;
@@ -86,12 +86,6 @@ void BakedSkinningModel::bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Me
pipeline::UBOSkinning::size,
});
}
// JSB synchronizes the new root's animation buffer before calling bindSkeleton.
for (index_t i = 0; i < _subModels.size(); ++i) {
updateLocalDescriptors(i, _subModels[i]->getDescriptorSet());
}
updateInstancedJointTextureInfo();
}
void BakedSkinningModel::updateTransform(uint32_t stamp) {
-12
View File
@@ -23,8 +23,6 @@
****************************************************************************/
#include "3d/models/SkinningModel.h"
#include <algorithm>
#include <utility>
#include "3d/assets/Mesh.h"
@@ -82,7 +80,6 @@ void SkinningModel::bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Mesh *m
_joints.clear();
if (!skeleton || !skinningRoot || !mesh) return;
const bool prevRealTimeTextureMode = _realTimeTextureMode;
auto jointCount = static_cast<uint32_t>(skeleton->getJoints().size());
_realTimeTextureMode = pipeline::SkinningJointCapacity::jointUniformCapacity < jointCount;
setTransform(skinningRoot);
@@ -116,15 +113,6 @@ void SkinningModel::bindSkeleton(Skeleton *skeleton, Node *skinningRoot, Mesh *m
jointInfo.indices = std::move(indices);
_joints.emplace_back(std::move(jointInfo));
}
// Rebind recreated resources without resetting custom instanced attributes.
const auto subModelCount = std::min(_subModels.size(), _bufferIndices.size());
if (subModelCount && prevRealTimeTextureMode != _realTimeTextureMode) {
onMacroPatchesStateChanged();
}
for (index_t i = 0; i < subModelCount; ++i) {
updateLocalDescriptors(i, _subModels[i]->getDescriptorSet());
}
}
void SkinningModel::updateTransform(uint32_t stamp) {
@@ -25,8 +25,8 @@
#define LOG_TAG "AudioDecoderSLES"
#include "audio/android/AudioDecoderSLES.h"
#include "base/Macros.h"
#include "audio/android/AudioDecoderSLES.h"
#include "platform/FileUtils.h"
#include <mutex>
+52 -54
View File
@@ -29,15 +29,14 @@
#include <unistd.h>
// for native asset manager
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <android/log.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <android/log.h>
#endif
#include <sys/types.h>
#include <mutex>
#include <thread>
#include <utility>
#include "application/ApplicationManager.h"
#include "audio/include/AudioEngine.h"
@@ -46,11 +45,11 @@
#include "base/UTF8.h"
#include "base/memory/Memory.h"
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include "platform/android/FileUtils-android.h"
#include "platform/java/jni/JniHelper.h"
#include "platform/java/jni/JniImp.h"
#include "platform/android/FileUtils-android.h"
#include "platform/java/jni/JniHelper.h"
#include "platform/java/jni/JniImp.h"
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include "cocos/platform/openharmony/FileUtils-OpenHarmony.h"
#include "cocos/platform/openharmony/FileUtils-OpenHarmony.h"
#endif
#include "audio/android/AudioDecoder.h"
@@ -69,20 +68,20 @@ namespace {
AudioEngineImpl *gAudioImpl = nullptr;
int outputSampleRate = 44100;
#if CC_PLATFORM == CC_PLATFORM_ANDROID
int bufferSizeInFrames = 192;
int bufferSizeInFrames = 192;
#endif
void getAudioInfo() {
#if CC_PLATFORM == CC_PLATFORM_ANDROID
JNIEnv *env = JniHelper::getEnv();
jclass audioSystem = env->FindClass("android/media/AudioSystem");
jmethodID method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputSamplingRate", "()I");
outputSampleRate = env->CallStaticIntMethod(audioSystem, method);
method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputFrameCount", "()I");
bufferSizeInFrames = env->CallStaticIntMethod(audioSystem, method);
JNIEnv * env = JniHelper::getEnv();
jclass audioSystem = env->FindClass("android/media/AudioSystem");
jmethodID method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputSamplingRate", "()I");
outputSampleRate = env->CallStaticIntMethod(audioSystem, method);
method = env->GetStaticMethodID(audioSystem, "getPrimaryOutputFrameCount", "()I");
bufferSizeInFrames = env->CallStaticIntMethod(audioSystem, method);
#else
// In openharmony, setting to 48K does not cause audio delays
outputSampleRate = 48000;
outputSampleRate = 48000;
#endif
}
} // namespace
@@ -124,8 +123,8 @@ static int fdGetter(const ccstd::string &url, off_t *start, off_t *length) {
AAsset_close(asset);
}
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
FileUtilsOpenHarmony *fileUtils = dynamic_cast<FileUtilsOpenHarmony *>(FileUtils::getInstance());
if (fileUtils) {
FileUtilsOpenHarmony* fileUtils = dynamic_cast<FileUtilsOpenHarmony*>(FileUtils::getInstance());
if(fileUtils) {
RawFileDescriptor64 descriptor;
fileUtils->getRawFileDescriptor(url, descriptor);
fd = descriptor.fd;
@@ -190,27 +189,27 @@ bool AudioEngineImpl::init() {
CC_LOG_ERROR("get the engine interface fail");
break;
}
#if CC_PLATFORM == CC_PLATFORM_ANDROID
// create output mix
const SLInterfaceID outputMixIIDs[] = {};
const SLboolean outputMixReqs[] = {};
result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs);
if (SL_RESULT_SUCCESS != result) {
CC_LOG_ERROR("create output mix fail");
break;
}
#if CC_PLATFORM == CC_PLATFORM_ANDROID
// create output mix
const SLInterfaceID outputMixIIDs[] = {};
const SLboolean outputMixReqs[] = {};
result = (*_engineEngine)->CreateOutputMix(_engineEngine, &_outputMixObject, 0, outputMixIIDs, outputMixReqs);
if (SL_RESULT_SUCCESS != result) {
CC_LOG_ERROR("create output mix fail");
break;
}
// realize the output mix
result = (*_outputMixObject)->Realize(_outputMixObject, SL_BOOLEAN_FALSE);
if (SL_RESULT_SUCCESS != result) {
CC_LOG_ERROR("realize the output mix fail");
break;
}
// realize the output mix
result = (*_outputMixObject)->Realize(_outputMixObject, SL_BOOLEAN_FALSE);
if (SL_RESULT_SUCCESS != result) {
CC_LOG_ERROR("realize the output mix fail");
break;
}
_audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, _outputMixObject, outputSampleRate, bufferSizeInFrames, fdGetter, &gCallerThreadUtils);
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
_audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, outputSampleRate, fdGetter, &gCallerThreadUtils);
#endif
_audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, _outputMixObject, outputSampleRate, bufferSizeInFrames, fdGetter, &gCallerThreadUtils);
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
_audioPlayerProvider = ccnew AudioPlayerProvider(_engineEngine, outputSampleRate, fdGetter, &gCallerThreadUtils);
#endif
ret = true;
} while (false);
@@ -228,14 +227,14 @@ int AudioEngineImpl::play2d(const ccstd::string &filePath, bool loop, float volu
auto audioId = AudioEngine::INVALID_AUDIO_ID;
do {
#if CC_PLATFORM == CC_PLATFORM_ANDROID
if (_engineEngine == nullptr || _audioPlayerProvider == nullptr) {
break;
}
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
if (_audioPlayerProvider == nullptr)
break;
#endif
#if CC_PLATFORM == CC_PLATFORM_ANDROID
if (_engineEngine == nullptr || _audioPlayerProvider == nullptr) {
break;
}
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
if (_audioPlayerProvider == nullptr)
break;
#endif
auto fullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
@@ -266,11 +265,10 @@ int AudioEngineImpl::play2d(const ccstd::string &filePath, bool loop, float volu
auto iter = _callbackMap.find(id);
if (iter != _callbackMap.end()) {
auto callback = std::move(iter->second);
_callbackMap.erase(iter);
if (state == IAudioPlayer::State::OVER) {
callback(id, filePath);
iter->second(id, filePath);
}
_callbackMap.erase(iter);
}
});
@@ -445,12 +443,12 @@ PCMHeader AudioEngineImpl::getPCMHeader(const char *url) {
CC_LOG_DEBUG("file %s pcm data already cached", url);
return header;
}
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#if CC_PLATFORM == CC_PLATFORM_ANDROID
AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(_engineEngine, fileFullPath, bufferSizeInFrames, outputSampleRate, fdGetter);
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(
_engineEngine, fileFullPath, _audioPlayerProvider->getBufferSizeInFrames(), outputSampleRate, fdGetter);
#endif
#endif
if (decoder == nullptr) {
CC_LOG_DEBUG("decode %s failed, the file formate might not support", url);
return header;
@@ -484,12 +482,12 @@ ccstd::vector<uint8_t> AudioEngineImpl::getOriginalPCMBuffer(const char *url, ui
if (_audioPlayerProvider->getPcmData(url, data)) {
CC_LOG_DEBUG("file %s pcm data already cached", url);
} else {
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#if CC_PLATFORM == CC_PLATFORM_ANDROID
AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(_engineEngine, fileFullPath, bufferSizeInFrames, outputSampleRate, fdGetter);
#else
#else
AudioDecoder *decoder = AudioDecoderProvider::createAudioDecoder(
_engineEngine, fileFullPath, _audioPlayerProvider->getBufferSizeInFrames(), outputSampleRate, fdGetter);
#endif
#endif
if (decoder == nullptr) {
CC_LOG_DEBUG("decode %s failed, the file formate might not support", url);
return pcmData;
+2 -2
View File
@@ -26,9 +26,9 @@
#include <SLES/OpenSLES.h>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <SLES/OpenSLES_Android.h>
#include <SLES/OpenSLES_Android.h>
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include <SLES/OpenSLES_Platform.h>
#include <SLES/OpenSLES_Platform.h>
#endif
#include <functional>
#include "audio/include/AudioDef.h"
+18 -18
View File
@@ -17,9 +17,9 @@
#pragma once
#include <pthread.h>
#include <sys/types.h>
#include <cstdint>
#include <sys/types.h>
#include <pthread.h>
#include "audio/android/AudioBufferProvider.h"
#include "audio/android/AudioResamplerPublic.h"
@@ -160,7 +160,7 @@ private:
struct track_t;
typedef void (*hook_t)(track_t *t, int32_t *output, size_t numOutFrames, int32_t *temp, int32_t *aux); //NOLINT(modernize-use-using)
static const int BLOCKSIZE = 16; // 4 cache lines
static const int BLOCKSIZE = 16; // 4 cache lines
struct track_t {
uint32_t needs;
@@ -288,19 +288,19 @@ private:
};
// bitmask of allocated track names, where bit 0 corresponds to TRACK0 etc.
uint32_t mTrackNames; // NOLINT(readability-identifier-naming)
uint32_t mTrackNames;// NOLINT(readability-identifier-naming)
// bitmask of configured track names; ~0 if maxNumTracks == MAX_NUM_TRACKS,
// but will have fewer bits set if maxNumTracks < MAX_NUM_TRACKS
const uint32_t mConfiguredNames; // NOLINT(readability-identifier-naming)
const uint32_t mConfiguredNames;// NOLINT(readability-identifier-naming)
const uint32_t mSampleRate; // NOLINT(readability-identifier-naming)
const uint32_t mSampleRate;// NOLINT(readability-identifier-naming)
//cjh NBLog::Writer mDummyLog;
public:
//cjh void setLog(NBLog::Writer* log);
private:
state_t mState __attribute__((aligned(32))); // NOLINT(readability-identifier-naming)
state_t mState __attribute__((aligned(32)));// NOLINT(readability-identifier-naming)
// Call after changing either the enabled status of a track, or parameters of an enabled track.
// OK to call more often than that, but unnecessary.
@@ -309,19 +309,19 @@ private:
bool setChannelMasks(int name,
audio_channel_mask_t trackChannelMask, audio_channel_mask_t mixerChannelMask);
static void track__genericResample(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__nop(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__16BitsStereo(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__16BitsMono(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__genericResample(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__nop(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__16BitsStereo(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__16BitsMono(track_t *t, int32_t *out, size_t numFrames, int32_t *temp, int32_t *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void volumeRampStereo(track_t *t, int32_t *out, size_t frameCount, int32_t *temp, int32_t *aux);
static void volumeStereo(track_t *t, int32_t *out, size_t frameCount, int32_t *temp,
int32_t *aux);
static void process__validate(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__nop(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__genericNoResampling(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__genericResampling(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__OneTrack16BitsStereoNoResampling(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__validate(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__nop(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__genericNoResampling(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__genericResampling(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process__OneTrack16BitsStereoNoResampling(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static int64_t calculateOutputPTS(const track_t &t, int64_t basePTS,
int outputFrameIndex);
@@ -347,11 +347,11 @@ private:
// multi-format process hooks
template <int MIXTYPE, typename TO, typename TI, typename TA>
static void process_NoResampleOneTrack(state_t *state, int64_t pts); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void process_NoResampleOneTrack(state_t *state, int64_t pts);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
// multi-format track hooks
template <int MIXTYPE, typename TO, typename TI, typename TA>
static void track__Resample(track_t *t, TO *out, size_t frameCount, TO *temp __unused, TA *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static void track__Resample(track_t *t, TO *out, size_t frameCount, TO *temp __unused, TA *aux);// NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
template <int MIXTYPE, typename TO, typename TI, typename TA>
static void track__NoResample(track_t *t, TO *out, size_t frameCount, TO *temp __unused, TA *aux); // NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
@@ -33,8 +33,8 @@
#include "base/std/container/vector.h"
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
// for openharmony platform, buffer size is 4458 in normal latency mode, 240 in fast latency mode
#define MAX_AUDIO_BUFFER_SIZE 4458
// for openharmony platform, buffer size is 4458 in normal latency mode, 240 in fast latency mode
#define MAX_AUDIO_BUFFER_SIZE 4458
#endif
namespace cc {
@@ -42,14 +42,14 @@
#include "base/ThreadPool.h"
#include "base/memory/Memory.h"
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <sys/system_properties.h>
#include "audio/android/PcmAudioService.h"
#include "audio/android/UrlAudioPlayer.h"
#include <sys/system_properties.h>
#include "audio/android/UrlAudioPlayer.h"
#include "audio/android/PcmAudioService.h"
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include "audio/openharmony/PcmAudioService.h"
#include "audio/openharmony/UrlAudioPlayer.h"
#include "cocos/platform/FileUtils.h"
#include "cocos/platform/openharmony/FileUtils-OpenHarmony.h"
#include "cocos/platform/FileUtils.h"
#include "cocos/platform/openharmony/FileUtils-OpenHarmony.h"
#include "audio/openharmony/UrlAudioPlayer.h"
#include "audio/openharmony/PcmAudioService.h"
#endif
#include <algorithm> // for std::find_if
#include <cstdlib>
@@ -107,9 +107,12 @@ AudioPlayerProvider::AudioPlayerProvider(SLEngineItf engineItf, SLObjectItf outp
}
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
AudioPlayerProvider::AudioPlayerProvider(SLEngineItf engineItf, int deviceSampleRate,
const FdGetterCallback &fdGetterCallback,
const FdGetterCallback &fdGetterCallback,
ICallerThreadUtils *callerThreadUtils)
: _engineItf(engineItf), _deviceSampleRate(deviceSampleRate), _fdGetterCallback(fdGetterCallback), _callerThreadUtils(callerThreadUtils), _pcmAudioService(nullptr), _mixController(nullptr), _threadPool(LegacyThreadPool::newCachedThreadPool(1, 8, 5, 2, 2)) {
: _engineItf(engineItf), _deviceSampleRate(deviceSampleRate), _fdGetterCallback(fdGetterCallback),
_callerThreadUtils(callerThreadUtils), _pcmAudioService(nullptr),
_mixController(nullptr), _threadPool(LegacyThreadPool::newCachedThreadPool(1, 8, 5, 2, 2))
{
_mixController = ccnew AudioMixerController(_deviceSampleRate, 2);
_pcmAudioService = ccnew PcmAudioService();
_pcmAudioService->init(_mixController, 2, deviceSampleRate, &_bufferSizeInFrames);
@@ -361,13 +364,13 @@ AudioPlayerProvider::AudioFileInfo AudioPlayerProvider::getFileInfo(
fileSize = length;
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
RawFileDescriptor64 descriptor;
FileUtilsOpenHarmony *fileUtils = static_cast<FileUtilsOpenHarmony *>(FileUtils::getInstance());
if (!fileUtils) {
FileUtilsOpenHarmony* fileUtils = static_cast<FileUtilsOpenHarmony*>(FileUtils::getInstance());
if(!fileUtils) {
return info;
}
FileUtils::Status status = fileUtils->getRawFileDescriptor(audioFilePath, descriptor);
if (status != FileUtils::Status::OK || descriptor.fd <= 0) {
if(status != FileUtils::Status::OK || descriptor.fd<= 0) {
ALOGE("Failed to open file descriptor for %s", audioFilePath.c_str());
return info;
}
@@ -409,9 +412,9 @@ bool AudioPlayerProvider::isSmallFile(const AudioFileInfo &info) { //NOLINT(read
extension = audioFileInfo.url.substr(pos);
}
auto *iter = std::find_if(std::begin(gAudioFileIndicator), std::end(gAudioFileIndicator),
[&extension](const AudioFileIndicator &judge) -> bool {
return judge.extension == extension;
});
[&extension](const AudioFileIndicator &judge) -> bool {
return judge.extension == extension;
});
if (iter != std::end(gAudioFileIndicator)) {
// ALOGV("isSmallFile: found: %s: ", iter->extension.c_str());
@@ -469,18 +472,19 @@ UrlAudioPlayer *AudioPlayerProvider::createUrlAudioPlayer(
}
#if CC_PLATFORM == CC_PLATFORM_ANDROID
SLuint32 locatorType = info.assetFd->getFd() > 0 ? SL_DATALOCATOR_ANDROIDFD : SL_DATALOCATOR_URI;
auto *urlPlayer = new (std::nothrow) UrlAudioPlayer(_engineItf, _outputMixObject, _callerThreadUtils);
bool ret = urlPlayer->prepare(info.url, locatorType, info.assetFd, info.start, info.length);
auto *urlPlayer = new (std::nothrow) UrlAudioPlayer(_engineItf, _outputMixObject, _callerThreadUtils);
bool ret = urlPlayer->prepare(info.url, locatorType, info.assetFd, info.start, info.length);
if (!ret) {
SL_SAFE_DELETE(urlPlayer);
}
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
auto urlPlayer = new (std::nothrow) UrlAudioPlayer(_callerThreadUtils);
bool ret = urlPlayer->prepare(info.url, info.assetFd, info.start, info.length);
if (!ret) {
if (urlPlayer != nullptr) {
if (!ret)
{
if (urlPlayer != nullptr) {
delete urlPlayer;
urlPlayer = nullptr;
urlPlayer = nullptr;
}
}
#endif
+18 -17
View File
@@ -18,9 +18,9 @@
#include <cstdint>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <android/log.h>
#include <sys/system_properties.h>
#include <sys/types.h>
#include <android/log.h>
#include <sys/system_properties.h>
#include <sys/types.h>
#endif
#include "audio/android/AudioBufferProvider.h"
@@ -108,20 +108,21 @@ protected:
int64_t calculateOutputPTS(int outputFrameIndex);
const int32_t mChannelCount; // NOLINT(readability-identifier-naming)
const int32_t mSampleRate; // NOLINT(readability-identifier-naming)
int32_t mInSampleRate; // NOLINT(readability-identifier-naming)
AudioBufferProvider::Buffer mBuffer; // NOLINT(readability-identifier-naming)
const int32_t mChannelCount;// NOLINT(readability-identifier-naming)
const int32_t mSampleRate;// NOLINT(readability-identifier-naming)
int32_t mInSampleRate;// NOLINT(readability-identifier-naming)
AudioBufferProvider::Buffer mBuffer;// NOLINT(readability-identifier-naming)
union {
int16_t mVolume[2]; // NOLINT(readability-identifier-naming)
uint32_t mVolumeRL; // NOLINT(readability-identifier-naming)
int16_t mVolume[2];// NOLINT(readability-identifier-naming)
uint32_t mVolumeRL;// NOLINT(readability-identifier-naming)
};
int16_t mTargetVolume[2]; // NOLINT(readability-identifier-naming)
size_t mInputIndex; // NOLINT(readability-identifier-naming)
int32_t mPhaseIncrement; // NOLINT(readability-identifier-naming)
uint32_t mPhaseFraction; // NOLINT(readability-identifier-naming)
uint64_t mLocalTimeFreq; // NOLINT(readability-identifier-naming)
int64_t mPTS; // NOLINT(readability-identifier-naming)
int16_t mTargetVolume[2];// NOLINT(readability-identifier-naming)
size_t mInputIndex;// NOLINT(readability-identifier-naming)
int32_t mPhaseIncrement;// NOLINT(readability-identifier-naming)
uint32_t mPhaseFraction;// NOLINT(readability-identifier-naming)
uint64_t mLocalTimeFreq;// NOLINT(readability-identifier-naming)
int64_t mPTS;// NOLINT(readability-identifier-naming)
// returns the inFrameCount required to generate outFrameCount frames.
//
@@ -154,7 +155,7 @@ protected:
return (static_cast<size_t>(outFrameCount) * mInSampleRate + (mSampleRate - 1)) / mSampleRate;
}
inline float clampFloatVol(float volume) { //NOLINT(readability-identifier-naming, readability-convert-member-functions-to-static)
inline float clampFloatVol(float volume) {//NOLINT(readability-identifier-naming, readability-convert-member-functions-to-static)
float ret = 0.0F;
if (volume > UNITY_GAIN_FLOAT) {
ret = UNITY_GAIN_FLOAT;
@@ -165,7 +166,7 @@ protected:
}
private:
const src_quality mQuality; // NOLINT(readability-identifier-naming)
const src_quality mQuality;// NOLINT(readability-identifier-naming)
// Return 'true' if the quality level is supported without explicit request
static bool qualityIsSupported(src_quality quality);
@@ -19,8 +19,8 @@
#include <stdint.h>
#include <sys/types.h>
#include "audio/android/AudioBufferProvider.h"
#include "audio/android/AudioResampler.h"
#include "audio/android/AudioBufferProvider.h"
namespace cc {
// ----------------------------------------------------------------------------
+2 -2
View File
@@ -29,9 +29,9 @@
#include <SLES/OpenSLES.h>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <SLES/OpenSLES_Android.h>
#include <SLES/OpenSLES_Android.h>
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include <SLES/OpenSLES_Platform.h>
#include <SLES/OpenSLES_Platform.h>
#endif
#include <functional>
+19 -19
View File
@@ -25,28 +25,28 @@
#define LOG_TAG "PcmAudioService"
#include "base/Macros.h"
#include "audio/android/PcmAudioService.h"
#include "audio/android/AudioMixerController.h"
#include "audio/android/utils/Compat.h"
#include "base/Macros.h"
namespace cc {
static ccstd::vector<char> __silenceData; //NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
static ccstd::vector<char> __silenceData;//NOLINT(bugprone-reserved-identifier, readability-identifier-naming)
#define AUDIO_PLAYER_BUFFER_COUNT (2)
class SLPcmAudioPlayerCallbackProxy {
public:
#if CC_PLATFORM == CC_PLATFORM_ANDROID
static void samplePlayerCallback(CCSLBufferQueueItf bq, void *context){
static void samplePlayerCallback(CCSLBufferQueueItf bq, void *context) {
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
static void samplePlayerCallback(CCSLBufferQueueItf bq, void *context, SLuint32 size) {
#endif
auto *thiz = reinterpret_cast<PcmAudioService *>(context);
thiz->bqFetchBufferCallback(bq);
}
}; // namespace cc
thiz->bqFetchBufferCallback(bq);
}
};
PcmAudioService::PcmAudioService(SLEngineItf engineItf, SLObjectItf outputMixObject)
: _engineItf(engineItf), _outputMixObj(outputMixObject), _playObj(nullptr), _playItf(nullptr), _volumeItf(nullptr), _bufferQueueItf(nullptr), _numChannels(-1), _sampleRate(-1), _bufferSizeInBytes(0), _controller(nullptr) {
@@ -59,12 +59,12 @@ PcmAudioService::~PcmAudioService() {
}
bool PcmAudioService::enqueue() {
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
// We need to call this interface in openharmony, otherwise there will be noise
SLuint8 *buffer = nullptr;
SLuint32 size = 0;
(*_bufferQueueItf)->GetBuffer(_bufferQueueItf, &buffer, &size);
#endif
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
// We need to call this interface in openharmony, otherwise there will be noise
SLuint8 *buffer = nullptr;
SLuint32 size = 0;
(*_bufferQueueItf)->GetBuffer(_bufferQueueItf, &buffer, &size);
#endif
if (_controller->hasPlayingTacks()) {
if (_controller->isPaused()) {
SLresult r = (*_bufferQueueItf)->Enqueue(_bufferQueueItf, __silenceData.data(), __silenceData.size());
@@ -141,7 +141,7 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in
SLresult r;
r = (*_engineItf)->CreateAudioPlayer(_engineItf, &_playObj, &source, &sink, sizeof(ids) / sizeof(ids[0]), ids, req); //NOLINT(bugprone-sizeof-expression)
r = (*_engineItf)->CreateAudioPlayer(_engineItf, &_playObj, &source, &sink, sizeof(ids) / sizeof(ids[0]), ids, req);//NOLINT(bugprone-sizeof-expression)
SL_RETURN_VAL_IF_FAILED(r, false, "CreateAudioPlayer failed");
r = (*_playObj)->Realize(_playObj, SL_BOOLEAN_FALSE);
@@ -162,12 +162,12 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in
if (__silenceData.empty()) {
__silenceData.resize(_numChannels * _bufferSizeInBytes, 0x00);
}
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
// We need to call this interface in openharmony, otherwise there will be noise
SLuint8 *buffer = nullptr;
SLuint32 size = 0;
(*_bufferQueueItf)->GetBuffer(_bufferQueueItf, &buffer, &size);
#endif
#if CC_PLATFORM == CC_PLATFORM_OPENHARMONY
// We need to call this interface in openharmony, otherwise there will be noise
SLuint8 *buffer = nullptr;
SLuint32 size = 0;
(*_bufferQueueItf)->GetBuffer(_bufferQueueItf, &buffer, &size);
#endif
r = (*_bufferQueueItf)->Enqueue(_bufferQueueItf, __silenceData.data(), __silenceData.size());
SL_RETURN_VAL_IF_FAILED(r, false, "_bufferQueueItf Enqueue failed");
@@ -26,17 +26,17 @@
#define LOG_TAG "UrlAudioPlayer"
#include "audio/android/UrlAudioPlayer.h"
#include <algorithm> // for std::find
#include <cmath>
#include "audio/android/ICallerThreadUtils.h"
#include "base/Macros.h"
#include "base/std/container/vector.h"
#include "base/Macros.h"
#include <cmath>
#include <algorithm> // for std::find
namespace {
std::mutex __playerContainerMutex; //NOLINT(bugprone-reserved-identifier,readability-identifier-naming)
ccstd::vector<cc::UrlAudioPlayer *> __playerContainer; //NOLINT(bugprone-reserved-identifier,readability-identifier-naming)
std::once_flag __onceFlag; //NOLINT(bugprone-reserved-identifier,readability-identifier-naming)
std::mutex __playerContainerMutex;//NOLINT(bugprone-reserved-identifier,readability-identifier-naming)
ccstd::vector<cc::UrlAudioPlayer *> __playerContainer;//NOLINT(bugprone-reserved-identifier,readability-identifier-naming)
std::once_flag __onceFlag;//NOLINT(bugprone-reserved-identifier,readability-identifier-naming)
} // namespace
@@ -216,7 +216,7 @@ float UrlAudioPlayer::getDuration() const {
if (duration == SL_TIME_UNKNOWN) {
return -1.0F;
} else { // NOLINT(readability-else-after-return)
} else {// NOLINT(readability-else-after-return)
const_cast<UrlAudioPlayer *>(this)->_duration = duration / 1000.0F;
if (_duration <= 0) {
+3 -3
View File
@@ -22,10 +22,10 @@
#include <strings.h>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <sys/cdefs.h>
#include <sys/cdefs.h>
#endif
#ifdef __cplusplus
#ifdef __cplusplus
extern "C" {
#endif
@@ -41,7 +41,7 @@ static inline int popcountll(unsigned long long x) {
return __builtin_popcountll(x);
}
#ifdef __cplusplus
#ifdef __cplusplus
}
#endif
+36 -35
View File
@@ -34,10 +34,10 @@
#include <time.h>
#include <unistd.h>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <android/log.h>
#include <android/log.h>
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include <hilog/log.h>
#define LOG_VERBOSE LOG_INFO
#include <hilog/log.h>
#define LOG_VERBOSE LOG_INFO
#endif
#ifdef __cplusplus
@@ -90,11 +90,11 @@ extern "C" {
* Simplified macro to send a verbose log message using the current LOG_TAG.
*/
#ifndef ALOGV
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define __ALOGV(...) ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define __ALOGV(...) ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__))
#endif
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define __ALOGV(...) ((void)ALOG(LOG_VERBOSE, LOG_TAG, __VA_ARGS__))
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define __ALOGV(...) ((void)ALOG(LOG_INFO, LOG_TAG, __VA_ARGS__))
#endif
#if LOG_NDEBUG
#define ALOGV(...) \
do { \
@@ -413,23 +413,23 @@ extern "C" {
* is -inverted- from the normal assert() semantics.
*/
#ifndef LOG_ALWAYS_FATAL_IF
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define LOG_ALWAYS_FATAL_IF(cond, ...) \
((__predict_false(cond)) \
? ((void)android_printAssert(#cond, LOG_TAG, ##__VA_ARGS__)) \
: (void)0)
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define LOG_ALWAYS_FATAL_IF(cond, ...) ((void)0)
#endif
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define LOG_ALWAYS_FATAL_IF(cond, ...) \
((__predict_false(cond)) \
? ((void)android_printAssert(#cond, LOG_TAG, ##__VA_ARGS__)) \
: (void)0)
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define LOG_ALWAYS_FATAL_IF(cond, ...) ((void)0 )
#endif
#endif
#ifndef LOG_ALWAYS_FATAL
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define LOG_ALWAYS_FATAL(...) \
(((void)android_printAssert(NULL, LOG_TAG, ##__VA_ARGS__)))
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define LOG_ALWAYS_FATAL(...) ((void)OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#endif
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define LOG_ALWAYS_FATAL(...) \
(((void)android_printAssert(NULL, LOG_TAG, ##__VA_ARGS__)))
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define LOG_ALWAYS_FATAL(...) ((void) OH_LOG_Print(LOG_APP, LOG_ERROR, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#endif
#endif
/*
@@ -476,25 +476,26 @@ extern "C" {
* The second argument may be NULL or "" to indicate the "global" tag.
*/
#ifndef ALOG
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define ALOG(priority, tag, ...) \
LOG_PRI(ANDROID_##priority, tag, __VA_ARGS__)
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define ALOG(priority, tag, ...) \
LOG_PRI(priority, tag, __VA_ARGS__)
#endif
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define ALOG(priority, tag, ...) \
LOG_PRI(ANDROID_##priority, tag, __VA_ARGS__)
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define ALOG(priority, tag, ...) \
LOG_PRI(priority, tag, __VA_ARGS__)
#endif
#endif
/*
* Log macro that allows you to specify a number for the priority.
*/
#ifndef LOG_PRI
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define LOG_PRI(priority, tag, ...) \
android_printLog(priority, tag, __VA_ARGS__)
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define LOG_PRI(priority, tag, ...) ((void)OH_LOG_Print(LOG_APP, priority, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#endif
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#define LOG_PRI(priority, tag, ...) \
android_printLog(priority, tag, __VA_ARGS__)
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#define LOG_PRI(priority, tag, ...) ((void) OH_LOG_Print(LOG_APP, priority, LOG_DOMAIN, "HMG_LOG", __VA_ARGS__))
#endif
#endif
/*
+9 -8
View File
@@ -17,15 +17,16 @@
#ifndef COCOS_LIB_UTILS_COMPAT_H
#define COCOS_LIB_UTILS_COMPAT_H
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
#include <unistd.h>
#include <unistd.h>
#include <SLES/OpenSLES.h>
#include <SLES/OpenSLES_Android.h>
#elif CC_PLATFORM == CC_PLATFORM_WINDOWS
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
#include <SLES/OpenSLES_OpenHarmony.h>
#include <SLES/OpenSLES_Platform.h>
#include <SLES/OpenSLES_OpenHarmony.h>
#include <SLES/OpenSLES_Platform.h>
#endif
#if defined(__APPLE__)
@@ -96,11 +97,11 @@ static inline ssize_t pwrite64(int fd, const void *buf, size_t nbytes, off64_t o
#if CC_PLATFORM == CC_PLATFORM_ANDROID
typedef SLAndroidSimpleBufferQueueItf CCSLBufferQueueItf;
#define CC_SL_IDD_BUFFER_QUEUE SL_IID_ANDROIDSIMPLEBUFFERQUEUE
#define CC_SL_IDD_BUFFER_QUEUE SL_IID_ANDROIDSIMPLEBUFFERQUEUE
#elif CC_PLATFORM == CC_PLATFORM_OPENHARMONY
typedef SLOHBufferQueueItf CCSLBufferQueueItf;
#define CC_SL_IDD_BUFFER_QUEUE SL_IID_OH_BUFFERQUEUE
#define __unused
#define CC_SL_IDD_BUFFER_QUEUE SL_IID_OH_BUFFERQUEUE
#define __unused
#endif
#endif /* COCOS_LIB_UTILS_COMPAT_H */
+1 -1
View File
@@ -17,8 +17,8 @@
#ifndef COCOS_ERRORS_H
#define COCOS_ERRORS_H
#include <errno.h>
#include <sys/types.h>
#include <errno.h>
namespace cc {
+5 -10
View File
@@ -27,10 +27,8 @@
#import <OpenAL/al.h>
#include <atomic>
#include <functional>
#include <memory>
#include <mutex>
#include <functional>
#include "base/std/container/string.h"
#include "audio/apple/AudioMacros.h"
@@ -42,7 +40,6 @@
namespace cc {
class AudioEngineImpl;
class AudioPlayer;
class Scheduler;
class AudioCache {
public:
@@ -99,15 +96,13 @@ protected:
std::mutex _readDataTaskMutex;
std::atomic<State> _state{State::INITIAL};
State _state{State::INITIAL};
// Assigned before the read task is submitted; workers must not look up the current application.
std::weak_ptr<Scheduler> _scheduler;
std::shared_ptr<std::atomic_bool> _isDestroyed;
std::shared_ptr<bool> _isDestroyed;
ccstd::string _fileFullPath;
unsigned int _id;
std::atomic_bool _isLoadingFinished{false};
std::atomic_bool _isSkipReadDataTask{false};
bool _isLoadingFinished{false};
bool _isSkipReadDataTask{false};
friend class AudioEngineImpl;
friend class AudioPlayer;
+14 -22
View File
@@ -31,6 +31,7 @@
#import <Foundation/Foundation.h>
#import <OpenAL/alc.h>
#include <thread>
#include "application/ApplicationManager.h"
#include "base/Scheduler.h"
#include "base/memory/Memory.h"
@@ -84,7 +85,7 @@ unsigned int __idIndex = 0;
using namespace cc;
AudioCache::AudioCache()
: _isDestroyed(std::make_shared<std::atomic_bool>(false)), _id(++__idIndex){
: _isDestroyed(std::make_shared<bool>(false)), _id(++__idIndex){
ALOGVV("AudioCache() %p, id=%u", this, _id);
for (int i = 0; i < QUEUEBUFFER_NUM; ++i) {
_queBuffers[i] = nullptr;
@@ -113,7 +114,7 @@ AudioCache::~AudioCache() {
_alBufferId = INVALID_AL_BUFFER_ID;
}
} else {
ALOGW("AudioCache (%p), id=%u, buffer isn't ready, state=%d", this, _id, static_cast<int>(_state.load()));
ALOGW("AudioCache (%p), id=%u, buffer isn't ready, state=%d", this, _id, _state);
}
if (_queBufferFrames > 0) {
@@ -266,6 +267,7 @@ void AudioCache::readDataTask(unsigned int selfId) {
invokingPlayCallbacks();
invokingLoadCallbacks();
_isLoadingFinished = true;
if (_state != State::READY) {
_state = State::FAILED;
if (_alBufferId != INVALID_AL_BUFFER_ID && alIsBuffer(_alBufferId)) {
@@ -275,13 +277,12 @@ void AudioCache::readDataTask(unsigned int selfId) {
}
}
_isLoadingFinished = true;
_readDataTaskMutex.unlock();
}
void AudioCache::addPlayCallback(const std::function<void()> &callback) {
std::lock_guard<std::mutex> lk(_playCallbackMutex);
switch (_state.load()) {
switch (_state) {
case State::INITIAL:
case State::LOADING:
_playCallbacks.push_back(callback);
@@ -295,7 +296,7 @@ void AudioCache::addPlayCallback(const std::function<void()> &callback) {
break;
default:
ALOGE("Invalid state: %d", static_cast<int>(_state.load()));
ALOGE("Invalid state: %d", _state);
break;
}
}
@@ -311,7 +312,7 @@ void AudioCache::invokingPlayCallbacks() {
}
void AudioCache::addLoadCallback(const std::function<void(bool)> &callback) {
switch (_state.load()) {
switch (_state) {
case State::INITIAL:
case State::LOADING:
_loadCallbacks.push_back(callback);
@@ -325,7 +326,7 @@ void AudioCache::addLoadCallback(const std::function<void(bool)> &callback) {
break;
default:
ALOGE("Invalid state: %d", static_cast<int>(_state.load()));
ALOGE("Invalid state: %d", _state);
break;
}
}
@@ -336,27 +337,18 @@ void AudioCache::invokingLoadCallbacks() {
return;
}
auto scheduler = _scheduler.lock();
if (!scheduler) {
return;
}
auto isDestroyed = _isDestroyed;
const bool isReady = _state.load() == State::READY;
scheduler->performFunctionInCocosThread([this, isDestroyed, isReady]() {
auto scheduler = CC_CURRENT_ENGINE()->getScheduler();
scheduler->performFunctionInCocosThread([&, isDestroyed]() {
if (*isDestroyed) {
ALOGV("invokingLoadCallbacks perform in cocos thread, AudioCache (%p) was destroyed!", this);
return;
}
// A callback may uncache this file or end the audio engine. Do not access the
// cache again after invoking user code, and cancel any remaining callbacks.
auto callbacks = std::move(_loadCallbacks);
for (auto &&cb : callbacks) {
if (*isDestroyed) {
break;
}
cb(isReady);
for (auto &&cb : _loadCallbacks) {
cb(_state == State::READY);
}
_loadCallbacks.clear();
});
}
@@ -167,13 +167,6 @@ AudioEngineImpl::~AudioEngineImpl() {
sche->unschedule("AudioEngine", this);
}
// AudioEngine::end() has joined the worker pool before deleting this backend.
// Queued tasks are discarded by the pool, so their caches will never receive
// a read/skip notification from a worker. Unblock those cache destructors.
for (auto &entry : _audioCaches) {
entry.second.setSkipReadDataTask(true);
}
if (s_ALContext) {
alDeleteSources(MAX_AUDIOINSTANCES, _alSources);
@@ -293,7 +286,6 @@ AudioCache *AudioEngineImpl::preload(const ccstd::string &filePath, std::functio
auto it = _audioCaches.find(filePath);
if (it == _audioCaches.end()) {
audioCache = &_audioCaches[filePath];
audioCache->_scheduler = _scheduler;
audioCache->_fileFullPath = FileUtils::getInstance()->fullPathForFilename(filePath);
unsigned int cacheId = audioCache->_id;
auto isCacheDestroyed = audioCache->_isDestroyed;
@@ -19,7 +19,7 @@
#include <stdint.h>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <sys/cdefs.h>
#include <sys/cdefs.h>
#endif
#include "audio/android/audio.h"
@@ -25,7 +25,7 @@
#include <stdio.h>
#include <stdlib.h>
#if CC_PLATFORM == CC_PLATFORM_ANDROID
#include <sys/cdefs.h>
#include <sys/cdefs.h>
#endif
/* The memcpy_* conversion routines are designed to work in-place on same dst as src
@@ -28,7 +28,6 @@
#include <cstdlib>
#include <cstring>
#include <mutex>
#include <utility>
#include "audio/common/decoder/AudioDecoder.h"
#include "base/Log.h"
#include "base/Utils.h"
@@ -179,7 +178,7 @@ bool AudioEngineImpl::init() {
alcMakeContextCurrent(sALContext);
std::fill(std::begin(_alSources), std::end(_alSources), 0);
std::fill(std::begin(_alSources), std::end(_alSources), 0);
alGenSources(MAX_AUDIOINSTANCES, _alSources);
auto alError = alGetError();
@@ -501,7 +500,6 @@ void AudioEngineImpl::setFinishCallback(int audioID, const std::function<void(in
}
void AudioEngineImpl::update(float /*dt*/) {
ccstd::vector<std::function<void()>> finishCallbacks;
ALint sourceState;
int audioID;
AudioPlayer *player;
@@ -536,9 +534,7 @@ void AudioEngineImpl::update(float /*dt*/) {
_threadMutex.unlock();
if (player->_finishCallbak) {
finishCallbacks.emplace_back([callback = std::move(player->_finishCallbak), audioID, filePath]() {
callback(audioID, filePath);
});
player->_finishCallbak(audioID, filePath); //IDEA: callback will delay 50ms
}
delete player;
_alSourceUsed[alSource] = false;
@@ -553,12 +549,6 @@ void AudioEngineImpl::update(float /*dt*/) {
sche->unschedule("AudioEngine", this);
}
}
// Callbacks may play/stop audio or destroy the engine. Finish all access to
// player state before invoking them, and keep the callbacks in local storage.
for (const auto &callback : finishCallbacks) {
callback();
}
}
void AudioEngineImpl::uncache(const ccstd::string &filePath) {
@@ -26,9 +26,9 @@ THE SOFTWARE.
#define LOG_TAG "PcmAudioService"
#include "audio/openharmony/PcmAudioService.h"
#include <deviceinfo.h>
#include "audio/android/AudioMixerController.h"
#include "audio/android/cutils/log.h"
#include <deviceinfo.h>
namespace cc {
@@ -106,10 +106,10 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in
OH_AudioRenderer_Callbacks callbacks;
static int sdkApi = OH_GetSdkApiVersion();
if (sdkApi >= 21) {
if(sdkApi >= 21) {
callbacks.OH_AudioRenderer_OnWriteData = nullptr;
} else {
callbacks.OH_AudioRenderer_OnWriteData = reinterpret_cast<int32_t (*)(OH_AudioRenderer *, void *, void *, int32_t)>(AudioRendererOnWriteData);
callbacks.OH_AudioRenderer_OnWriteData = reinterpret_cast<int32_t (*)(OH_AudioRenderer*,void* ,void* ,int32_t)>(AudioRendererOnWriteData);
}
callbacks.OH_AudioRenderer_OnInterruptEvent = AudioRendererOnInterrupt;
callbacks.OH_AudioRenderer_OnError = nullptr;
@@ -118,9 +118,9 @@ bool PcmAudioService::init(AudioMixerController *controller, int numChannels, in
if (ret != AUDIOSTREAM_SUCCESS) {
return false;
}
if (sdkApi >= 21) {
ret = OH_AudioStreamBuilder_SetRendererWriteDataCallback(_builder, AudioRendererOnWriteData, this);
if(sdkApi >= 21) {
ret = OH_AudioStreamBuilder_SetRendererWriteDataCallback(_builder, AudioRendererOnWriteData, this);
if (ret != AUDIOSTREAM_SUCCESS) {
return false;
}
@@ -26,8 +26,8 @@ THE SOFTWARE.
#define LOG_TAG "UrlAudioPlayer"
#include "audio/openharmony/UrlAudioPlayer.h"
#include <algorithm> // for std::find
#include <map>
#include <algorithm> // for std::find
#include "audio/android/ICallerThreadUtils.h"
#include "audio/android/cutils/log.h"
#include "cocos/application/ApplicationManager.h"

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