mirror of
https://github.com/cocos/cocos4.git
synced 2026-11-19 14:52:40 +08:00
Compare commits
18 Commits
v4.0.0-beta.2
...
v4.0.0
| Author | SHA1 | Date | |
|---|---|---|---|
| b01aabdf57 | |||
| 7995924100 | |||
| af2b9e9ed9 | |||
| 229ad74757 | |||
| 5313b86ed1 | |||
| 7fb5ae075b | |||
| 1b0455e10e | |||
| 714bd9d3e2 | |||
| 6ccf1cf9a8 | |||
| 1df519e248 | |||
| aaa3a9168b | |||
| 8e62e7e044 | |||
| 62bd937e7e | |||
| 990e3b09aa | |||
| 111fe1755d | |||
| 4a0dbc977a | |||
| 7037052b40 | |||
| e78ad4d759 |
Vendored
+1
@@ -26,6 +26,7 @@ declare namespace jsb {
|
||||
export function getDeviceOrientation(): number;
|
||||
export function getNetworkType(): number; // TODO: enum type
|
||||
export function getSafeAreaEdge(): NativeSafeAreaEdge;
|
||||
export function setKeepScreenOn(enabled: boolean): void;
|
||||
|
||||
export function setAccelerometerEnabled(isEnabled: boolean);
|
||||
export function setAccelerometerInterval(intervalInSeconds: number);
|
||||
|
||||
@@ -3205,6 +3205,38 @@ request fullscreen is not supported on this platform.
|
||||
|
||||
exit fullscreen is not supported on this platform.
|
||||
|
||||
### 9010
|
||||
|
||||
UIMesh.setMeshData: unsupported vertexStride %d, expected %d (V3F_T2F_C4B) or %d (V3F_T2F_C4B_C4B); data rejected.
|
||||
|
||||
### 9011
|
||||
|
||||
UIMesh.setMeshData: negative counts (vertexCount %d, indexCount %d); data rejected.
|
||||
|
||||
### 9012
|
||||
|
||||
UIMesh.setMeshData: vertexData holds %d bytes, but %d vertices x %d bytes are declared; data rejected.
|
||||
|
||||
### 9013
|
||||
|
||||
UIMesh.setMeshData: indexData is %d bytes at offset %d, but %d Uint16 indices need %d bytes (2-byte aligned view); data rejected.
|
||||
|
||||
### 9014
|
||||
|
||||
UIMesh.setMeshData: indices[%d] = %d is out of range for %d vertices; data rejected.
|
||||
|
||||
### 9015
|
||||
|
||||
UIMesh.setMeshData: segment %d range [%d, %d) is out of bounds for indexCount %d; data rejected.
|
||||
|
||||
### 9016
|
||||
|
||||
UIMesh.setMeshData: %d vertices / %d indices exceed the accessor cap (%d / %d); split the mesh. Data rejected.
|
||||
|
||||
### 9017
|
||||
|
||||
UIMesh: render data allocation failed for %d vertices / %d indices (accessor cap: %d / %d).
|
||||
|
||||
### 9100
|
||||
|
||||
texture size exceeds current device limits %d/%d
|
||||
|
||||
@@ -307,6 +307,9 @@
|
||||
"worker-pool": {
|
||||
"modules": ["worker", "worker-pool"],
|
||||
"dependentModules": ["worker"]
|
||||
},
|
||||
"webassembly": {
|
||||
"modules": ["webassembly"]
|
||||
}
|
||||
},
|
||||
"moduleOverrides": [{
|
||||
|
||||
@@ -48,6 +48,7 @@ const attributes = vfmtPosColor.concat([
|
||||
]);
|
||||
|
||||
const componentPerVertex = getComponentPerVertex(attributes);
|
||||
const alphaOffset = 6; // position.xyz, color.rgba, distance
|
||||
|
||||
const stride = getAttributeStride(attributes);
|
||||
|
||||
@@ -62,10 +63,10 @@ function growCapacity (needed: number, current: number, max: number): number {
|
||||
|
||||
/**
|
||||
* @en
|
||||
* Graphics component.
|
||||
* Graphics component. Fill and stroke alpha are multiplied by the node's cascaded UI opacity at draw time.
|
||||
*
|
||||
* @zh
|
||||
* 自定义图形类。
|
||||
* 自定义图形组件。绘制时,填充和描边的 alpha 会乘以节点的累计 UI 透明度。
|
||||
*/
|
||||
@ccclass('cc.Graphics')
|
||||
@help('i18n:cc.Graphics')
|
||||
@@ -236,6 +237,8 @@ export class Graphics extends UIRenderer {
|
||||
protected _isNeedUploadData = true;
|
||||
|
||||
private _graphicsUseSubMeshes: RenderingSubMesh[] = [];
|
||||
private _uploadedOpacity = 1;
|
||||
private _opacityScratch: Float32Array | null = null;
|
||||
|
||||
//nativeObj
|
||||
protected declare _graphicsNativeProxy: NativeUIModelProxy;
|
||||
@@ -313,6 +316,7 @@ export class Graphics extends UIRenderer {
|
||||
this.impl = null;
|
||||
}
|
||||
|
||||
this._opacityScratch = null;
|
||||
super.onDestroy();
|
||||
}
|
||||
|
||||
@@ -567,6 +571,7 @@ export class Graphics extends UIRenderer {
|
||||
}
|
||||
|
||||
this.impl.clear();
|
||||
this._opacityScratch = null;
|
||||
this._isDrawing = false;
|
||||
if (JSB) {
|
||||
this._graphicsNativeProxy.clear();// need native
|
||||
@@ -676,41 +681,61 @@ export class Graphics extends UIRenderer {
|
||||
}
|
||||
}
|
||||
|
||||
protected _uploadData (): void {
|
||||
const impl = this.impl;
|
||||
if (!impl) {
|
||||
return;
|
||||
}
|
||||
|
||||
const renderDataList = impl && impl.getRenderDataList();
|
||||
if (renderDataList.length <= 0 || !this.model) {
|
||||
protected _uploadData (opacity = this.node._uiProps.opacity): void {
|
||||
if (!this.impl || !this.model) {
|
||||
return;
|
||||
}
|
||||
|
||||
const renderDataList = this.impl.getRenderDataList();
|
||||
const subModelList = this.model.subModels;
|
||||
for (let i = 0; i < renderDataList.length; i++) {
|
||||
const renderData = renderDataList[i];
|
||||
const ia = subModelList[i].inputAssembler;
|
||||
if (renderData.lastFilledVertex === renderData.vertexStart) {
|
||||
continue;
|
||||
const indexCount = renderData.indexStart;
|
||||
const vertexCount = indexCount ? renderData.vertexStart : 0;
|
||||
const newSubModel = i >= subModelList.length;
|
||||
if (newSubModel) {
|
||||
this.activeSubModel(i, vertexCount, indexCount);
|
||||
}
|
||||
const ia = subModelList[i].inputAssembler;
|
||||
const verticesChanged = newSubModel || renderData.lastFilledVertex !== vertexCount;
|
||||
const indicesChanged = newSubModel || renderData.lastFilledIndex !== indexCount;
|
||||
if (verticesChanged || indicesChanged) {
|
||||
this._ensureCapacity(renderData, ia);
|
||||
}
|
||||
if (vertexCount && (verticesChanged || opacity !== this._uploadedOpacity)) {
|
||||
ia.vertexBuffers[0].update(this._getUploadVertices(renderData, vertexCount, opacity));
|
||||
}
|
||||
if (verticesChanged) {
|
||||
ia.vertexCount = vertexCount;
|
||||
renderData.lastFilledVertex = vertexCount;
|
||||
}
|
||||
if (indicesChanged) {
|
||||
if (indexCount) ia.indexBuffer!.update(renderData.iData.subarray(0, indexCount));
|
||||
ia.indexCount = indexCount;
|
||||
renderData.lastFilledIndex = indexCount;
|
||||
}
|
||||
|
||||
// Buffer.update() does not grow the buffer on WebGL, reserve the capacity first.
|
||||
this._ensureCapacity(renderData, ia);
|
||||
|
||||
const vb = new Float32Array(renderData.vData.buffer, 0, renderData.vertexStart * componentPerVertex);
|
||||
ia.vertexBuffers[0].update(vb);
|
||||
ia.vertexCount = renderData.vertexStart;
|
||||
const ib = new Uint16Array(renderData.iData.buffer, 0, renderData.indexStart);
|
||||
ia.indexBuffer!.update(ib);
|
||||
ia.indexCount = renderData.indexStart;
|
||||
renderData.lastFilledVertex = renderData.vertexStart;
|
||||
renderData.lastFilledIndex = renderData.indexStart;
|
||||
}
|
||||
|
||||
this._uploadedOpacity = opacity;
|
||||
this._isNeedUploadData = false;
|
||||
}
|
||||
|
||||
private _getUploadVertices (data: MeshRenderData, vertexCount: number, opacity: number): Float32Array {
|
||||
const raw = new Float32Array(data.vData.buffer, data.vData.byteOffset, vertexCount * componentPerVertex);
|
||||
if (opacity === 1) return raw;
|
||||
|
||||
// Keep the retained paint colors intact so each fade starts from its original alpha.
|
||||
if (!this._opacityScratch || this._opacityScratch.length < raw.length) {
|
||||
this._opacityScratch = new Float32Array(growCapacity(vertexCount, 0, MAX_VERTEX_COUNT) * componentPerVertex);
|
||||
}
|
||||
const output = this._opacityScratch.subarray(0, raw.length);
|
||||
output.set(raw);
|
||||
for (let i = alphaOffset; i < output.length; i += componentPerVertex) {
|
||||
output[i] = raw[i] * opacity;
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Grow only, never shrink: the capacity is reused after clear().
|
||||
*/
|
||||
@@ -733,18 +758,9 @@ export class Graphics extends UIRenderer {
|
||||
}
|
||||
|
||||
protected _render (render: IBatcher): void {
|
||||
if (this._isNeedUploadData) {
|
||||
if (this.impl) {
|
||||
const renderDataList = this.impl.getRenderDataList();
|
||||
const len = this.model!.subModels.length;
|
||||
if (renderDataList.length > len) {
|
||||
for (let i = len; i < renderDataList.length; i++) {
|
||||
const renderData = renderDataList[i];
|
||||
this.activeSubModel(i, renderData.vertexStart, renderData.indexStart);
|
||||
}
|
||||
}
|
||||
}
|
||||
this._uploadData();
|
||||
const opacity = this.node._uiProps.opacity;
|
||||
if (this._isNeedUploadData || this._uploadedOpacity !== opacity) {
|
||||
this._uploadData(opacity);
|
||||
}
|
||||
|
||||
render.commitModel(this, this.model, this.getMaterialInstance(0));
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
export * from './label';
|
||||
export { Sprite } from './sprite';
|
||||
export { UIMeshRenderer } from './ui-mesh-renderer';
|
||||
export * from './ui-mesh';
|
||||
export { LabelOutline } from './label-outline';
|
||||
export { UIStaticBatch } from './ui-static-batch';
|
||||
export { LabelShadow } from './label-shadow';
|
||||
|
||||
@@ -0,0 +1,636 @@
|
||||
/*
|
||||
Copyright (c) 2026
|
||||
Generic 2D mesh data consumer: the plugin feeds pre-baked vertex/index/segment
|
||||
data through setMeshData; this component owns buffer allocation, batching and
|
||||
submission through the 2D batcher, so extensions can render custom meshes
|
||||
without touching engine internals.
|
||||
|
||||
Vertices are ALWAYS node-local; UIMesh owns the node transform:
|
||||
* not batched -- on the GPU, via USE_LOCAL + the per-draw cc-local UBO the
|
||||
batcher already maintains for middleware draws;
|
||||
* batched -- the FULL world matrix baked into the chunk copy on the CPU
|
||||
(a merged batch carries no per-draw matrix), matching the GPU path, z /
|
||||
X-Y rotation included.
|
||||
USE_LOCAL / setUseLocal are derived internally; there is no world-baked
|
||||
input mode.
|
||||
|
||||
Data is FillColorType.VERTEX, so the batcher applies no cascaded opacity:
|
||||
UIMesh folds it into the copied vertices itself, accumulated as Batcher2D.walk
|
||||
does for COLOR data (own color alpha x, per ancestor, UIOpacity localOpacity x
|
||||
that ancestor's color alpha). `premultipliedAlpha` declares the data format:
|
||||
alpha-byte-only vs RGBA + dark RGB fading.
|
||||
|
||||
The batcher resets the shared index tail after every upload (vertex bytes
|
||||
survive), so indices are re-submitted EVERY frame (appendIndexBuffer) and only
|
||||
the vertex refresh is _vertexDirty-gated. A dirty-gated submission would leave
|
||||
a static mesh's draw range aliasing whichever sibling appends after the reset
|
||||
(two UIMeshes in one buffer, one paused: it would draw the other's triangles).
|
||||
*/
|
||||
|
||||
import { JSB } from 'internal:constants';
|
||||
import { ccclass, editable, serializable } from 'cc.decorator';
|
||||
import { errorID } from '../../core';
|
||||
import { Mat4 } from '../../core/math';
|
||||
import { UIRenderer } from '../framework/ui-renderer';
|
||||
import { RenderData } from '../renderer/render-data';
|
||||
import { RenderDrawInfo, RenderDrawInfoType } from '../renderer/render-draw-info';
|
||||
import { StaticVBAccessor } from '../renderer/static-vb-accessor';
|
||||
import type { Batcher2D } from '../renderer/batcher-2d';
|
||||
import { vfmtPosUvColor4B, vfmtPosUvTwoColor4B, getAttributeStride } from '../renderer/vertex-format';
|
||||
import { RenderEntity, RenderEntityType } from '../renderer/render-entity';
|
||||
import { director, DirectorEvent } from '../../game';
|
||||
import { Texture2D } from '../../asset/assets';
|
||||
import { builtinResMgr } from '../../asset/asset-manager';
|
||||
import { BlendFactor } from '../../gfx';
|
||||
import type { MeshBuffer } from '../renderer/mesh-buffer';
|
||||
import type { MaterialInstance } from '../../render-scene';
|
||||
import type { Material } from '../../asset/assets/material';
|
||||
import type { Node } from '../../scene-graph';
|
||||
|
||||
/**
|
||||
* @en A segment of the mesh: a range of indices drawn with one texture+material.
|
||||
* @zh 网格的一个片段:一段索引,用同一纹理+材质绘制。
|
||||
*/
|
||||
export interface UIMeshSegment {
|
||||
indexOffset: number;
|
||||
indexCount: number;
|
||||
texture: Texture2D | null;
|
||||
material: MaterialInstance | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @en Pre-baked mesh data for one frame.
|
||||
* @zh 一帧的预烘焙网格数据。
|
||||
* vertexStride: 24 (single-color V3F_T2F_C4B) or 28 (two-color V3F_T2F_C4B_C4B).
|
||||
*/
|
||||
export interface UIMeshData {
|
||||
vertexCount: number;
|
||||
vertexStride: number;
|
||||
vertexData: Uint8Array;
|
||||
indexCount: number;
|
||||
indexData: Uint8Array;
|
||||
segments: UIMeshSegment[];
|
||||
}
|
||||
|
||||
// Shared static vertex-buffer accessors, keyed by the current Batcher2D: it
|
||||
// destroys every accessor registered with it, so a rebuilt root must never
|
||||
// reuse a cached (destroyed) accessor, and each new one must be registered
|
||||
// with the current batcher or its buffers would never be uploaded or reset.
|
||||
let _accessorBatcher: Batcher2D | null = null;
|
||||
let _sharedAccessor: StaticVBAccessor | null = null;
|
||||
let _sharedTintAccessor: StaticVBAccessor | null = null;
|
||||
|
||||
// Registration keys in the batcher's accessor map (base-36 namespaced, the
|
||||
// same convention as the built-in middleware assemblers — spine/dragon-bones).
|
||||
const UIMESH_ACCESSOR_KEY = Number.parseInt('UIMESH', 36);
|
||||
const UIMESH_TINT_ACCESSOR_KEY = Number.parseInt('UIMESHTINT', 36);
|
||||
|
||||
// The two consumed vertex formats (24 / 28 bytes); strides derived from the
|
||||
// definitions so the byte math always matches the chunk's format.
|
||||
const MESH_STRIDE_BYTES = getAttributeStride(vfmtPosUvColor4B);
|
||||
const MESH_STRIDE_TINT_BYTES = getAttributeStride(vfmtPosUvTwoColor4B);
|
||||
|
||||
/**
|
||||
* @en A generic 2D mesh renderer that consumes pre-baked vertex/index data.
|
||||
* The data provider (e.g. a spine plugin) fills setMeshData every frame; this
|
||||
* component handles buffer allocation, batching and submission.
|
||||
* @zh 通用 2D 网格渲染器,消费预烘焙的顶点/索引数据。数据提供方(如 spine 插件)
|
||||
* 每帧调用 setMeshData,本组件负责缓冲分配、合批与提交。
|
||||
*/
|
||||
@ccclass('cc.UIMesh')
|
||||
export class UIMesh extends UIRenderer {
|
||||
@serializable
|
||||
protected _enableBatch = false;
|
||||
|
||||
/**
|
||||
* @en Whether the incoming color data is premultiplied-alpha. Declares how
|
||||
* cascaded opacity is folded into the vertices (alpha byte only vs
|
||||
* RGBA + dark RGB) and the blend factors of the builtin material.
|
||||
* @zh 输入颜色数据是否为预乘 alpha 格式。决定级联不透明度折算方式
|
||||
* (仅 alpha 字节 vs RGBA + dark RGB)及内置材质混合因子。
|
||||
*/
|
||||
@serializable
|
||||
protected _premultipliedAlpha = false;
|
||||
|
||||
protected _meshData: UIMeshData | null = null;
|
||||
protected _useTint = false;
|
||||
private _drawInfoList: RenderDrawInfo[] = [];
|
||||
|
||||
// Poll cache (see _onBeforeDraw): inputs captured by the last
|
||||
// updateVertexBuffer run; drift means the baked transform / folded opacity
|
||||
// no longer match. The full matrix is tracked — the bake applies all of it.
|
||||
private _pollOpacity = 1;
|
||||
private _pollWorldMatrix = new Mat4();
|
||||
|
||||
// Vertex-staleness latch, consumed by _onBeforeDraw to pick a full refresh
|
||||
// vs an index-only resubmit. Starts dirty so the first frame prepares.
|
||||
private _vertexDirty = true;
|
||||
|
||||
constructor () {
|
||||
super();
|
||||
this._useVertexOpacity = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @en Feeds the pre-baked mesh data for the current frame.
|
||||
* @zh 喂入当前帧的预烘焙网格数据。
|
||||
*/
|
||||
public setMeshData (data: UIMeshData): void {
|
||||
// Reject bad input at the call site; a rejected frame keeps the last
|
||||
// accepted mesh.
|
||||
if (!this._validateMeshData(data)) return;
|
||||
const useTint = data.vertexStride === MESH_STRIDE_TINT_BYTES;
|
||||
if (useTint !== this._useTint) {
|
||||
this.destroyRenderData();
|
||||
this._useTint = useTint;
|
||||
this._flushAssembler();
|
||||
// The builtin fallback material follows the stride (TWO_COLORED).
|
||||
this.updateMaterial();
|
||||
}
|
||||
this._meshData = data;
|
||||
this._vertexDirty = true;
|
||||
}
|
||||
|
||||
private _validateMeshData (data: UIMeshData): boolean {
|
||||
const vc = data.vertexCount;
|
||||
const ic = data.indexCount;
|
||||
if (data.vertexStride !== MESH_STRIDE_BYTES && data.vertexStride !== MESH_STRIDE_TINT_BYTES) {
|
||||
errorID(9010, data.vertexStride, MESH_STRIDE_BYTES, MESH_STRIDE_TINT_BYTES);
|
||||
return false;
|
||||
}
|
||||
if (vc < 0 || ic < 0) {
|
||||
errorID(9011, vc, ic);
|
||||
return false;
|
||||
}
|
||||
// Capacity limits come from the accessor that will serve the data.
|
||||
const accessor = this.ensureAccessor(data.vertexStride === MESH_STRIDE_TINT_BYTES);
|
||||
if (vc > accessor.maxVertexCount || ic > accessor.maxIndexCount) {
|
||||
errorID(9016, vc, ic, accessor.maxVertexCount, accessor.maxIndexCount);
|
||||
return false;
|
||||
}
|
||||
if (!data.vertexData || data.vertexData.byteLength < vc * data.vertexStride) {
|
||||
errorID(9012, data.vertexData ? data.vertexData.byteLength : 0, vc, data.vertexStride);
|
||||
return false;
|
||||
}
|
||||
if (!data.indexData || data.indexData.byteOffset % 2 !== 0 || data.indexData.byteLength < ic * 2) {
|
||||
errorID(
|
||||
9013,
|
||||
data.indexData ? data.indexData.byteLength : 0,
|
||||
data.indexData ? data.indexData.byteOffset : 0,
|
||||
ic,
|
||||
ic * 2,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// Indices are mesh-local; anything >= vertexCount would sample vertices
|
||||
// of other chunks in the shared buffer (silent geometry corruption).
|
||||
const indices = new Uint16Array(data.indexData.buffer, data.indexData.byteOffset, ic);
|
||||
for (let i = 0; i < ic; ++i) {
|
||||
if (indices[i] >= vc) {
|
||||
errorID(9014, i, indices[i], vc);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
for (let i = 0; i < data.segments.length; ++i) {
|
||||
const seg = data.segments[i];
|
||||
if (seg.indexOffset < 0 || seg.indexCount < 0 || seg.indexOffset + seg.indexCount > ic) {
|
||||
errorID(9015, i, seg.indexOffset, seg.indexOffset + seg.indexCount, ic);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @en Whether to enable sprite batching.
|
||||
* @zh 是否启用合批。
|
||||
*/
|
||||
@editable
|
||||
get enableBatch (): boolean { return this._enableBatch; }
|
||||
set enableBatch (value: boolean) {
|
||||
this._enableBatch = value;
|
||||
this._syncTransformMode();
|
||||
this.updateMaterial();
|
||||
}
|
||||
|
||||
/**
|
||||
* @en Whether the input color data is premultiplied-alpha.
|
||||
* @zh 输入颜色数据是否为预乘 alpha 格式。
|
||||
*/
|
||||
@editable
|
||||
get premultipliedAlpha (): boolean { return this._premultipliedAlpha; }
|
||||
set premultipliedAlpha (value: boolean) {
|
||||
this._premultipliedAlpha = value;
|
||||
this.updateMaterial();
|
||||
this._vertexDirty = true;
|
||||
this.onPremultipliedAlphaChanged();
|
||||
}
|
||||
|
||||
/**
|
||||
* Notifies subclasses the declared format changed. The property is owned
|
||||
* here (single source of truth); producers override this to forward it to
|
||||
* their baker instead of redeclaring the field.
|
||||
*/
|
||||
protected onPremultipliedAlphaChanged (): void {}
|
||||
|
||||
public onLoad (): void {
|
||||
super.onLoad();
|
||||
// Deserialization has applied _enableBatch by now; re-derive the
|
||||
// legacy switch state.
|
||||
this._syncTransformMode();
|
||||
}
|
||||
|
||||
/**
|
||||
* useLocal == "vertices are still node-local at submit time". Batched data
|
||||
* is world-baked by updateVertexBuffer before submit, and native
|
||||
* middleware draws only merge when !useLocal — hence !enableBatch.
|
||||
*/
|
||||
private _syncTransformMode (): void {
|
||||
this._renderEntity.setUseLocal(!this._enableBatch);
|
||||
this._vertexDirty = true;
|
||||
}
|
||||
|
||||
protected _updateColor (): void {
|
||||
super._updateColor();
|
||||
// The opacity fold in updateVertexBuffer reads this._color, so a
|
||||
// change must re-prepare. Visibility (color.a 0 <-> !0) is recomputed
|
||||
// fresh by _onBeforeDraw.
|
||||
this._vertexDirty = true;
|
||||
}
|
||||
|
||||
protected _onMaterialModified (idx: number, material: Material | null): void {
|
||||
super._onMaterialModified(idx, material);
|
||||
// Draw infos cache the material reference; a swap must rebuild them.
|
||||
// The base mark only re-syncs visibility (no updateRenderer override
|
||||
// anymore), and the passDirty self-heal path needs an assembler.
|
||||
this._vertexDirty = true;
|
||||
}
|
||||
|
||||
public onEnable (): void {
|
||||
super.onEnable();
|
||||
// BEFORE_DRAW fires between the update and render phases, outside the
|
||||
// director.pause() gate — the render loop still redraws (and resets
|
||||
// shared buffers) while paused, so submission must keep running.
|
||||
if (JSB) director.on(DirectorEvent.BEFORE_DRAW, this._onBeforeDraw, this);
|
||||
}
|
||||
|
||||
public onDisable (): void {
|
||||
if (JSB) director.off(DirectorEvent.BEFORE_DRAW, this._onBeforeDraw, this);
|
||||
super.onDisable();
|
||||
}
|
||||
|
||||
/**
|
||||
* JSB per-frame driver (director BEFORE_DRAW); web is driven by fillBuffers
|
||||
* instead. Three jobs:
|
||||
* * poll — transforms / UIOpacity never mark a middleware renderer, so
|
||||
* compare the live values against the last updateVertexBuffer capture;
|
||||
* * visibility — recomputed fresh (the base class' synchronous
|
||||
* _updateColor recompute is assembler-gated, dead here); an invisible
|
||||
* mesh submits nothing and its draw infos are cleared;
|
||||
* * data — full refresh when the latch is set or the mesh just became
|
||||
* visible again, else the frame-scoped appendIndexBuffer only.
|
||||
*/
|
||||
private _onBeforeDraw (): void {
|
||||
if (!JSB || !this._renderData || !this._meshData) return;
|
||||
if (this._enableBatch && !this.node.worldMatrix.strictEquals(this._pollWorldMatrix)) {
|
||||
this._vertexDirty = true;
|
||||
}
|
||||
if (this._computeCascadedOpacity() !== this._pollOpacity) {
|
||||
this._vertexDirty = true;
|
||||
}
|
||||
const wasRenderable = this._renderFlag;
|
||||
const canRender = this._canRender();
|
||||
this._renderFlag = canRender;
|
||||
this._renderEntity.enabled = canRender;
|
||||
if (!canRender) {
|
||||
if (wasRenderable) this._renderEntity.clearDynamicRenderDrawInfos();
|
||||
return;
|
||||
}
|
||||
if (this._vertexDirty || !wasRenderable) {
|
||||
this._prepareNativeDrawInfos();
|
||||
this._vertexDirty = false;
|
||||
} else {
|
||||
this.appendIndexBuffer();
|
||||
}
|
||||
}
|
||||
|
||||
protected _flushAssembler (): void {
|
||||
if (this._renderData === null) {
|
||||
const accessor = this.ensureAccessor(this._useTint);
|
||||
this._renderData = RenderData.add(this._useTint ? vfmtPosUvTwoColor4B : vfmtPosUvColor4B, accessor);
|
||||
}
|
||||
}
|
||||
|
||||
protected _render (batcher: any): void {
|
||||
const prepared = this._prepareBuffers();
|
||||
if (!prepared || !this._meshData) return;
|
||||
const { meshBuffer, startIndex } = prepared;
|
||||
const data = this._meshData;
|
||||
|
||||
// Segments without their own material fall back to the component
|
||||
// material (the builtin spine effect).
|
||||
for (const seg of data.segments) {
|
||||
const mat = seg.material || this.getRenderMaterial(0);
|
||||
if (seg.texture && mat) {
|
||||
batcher.commitMiddleware(
|
||||
this,
|
||||
meshBuffer,
|
||||
startIndex + seg.indexOffset,
|
||||
seg.indexCount,
|
||||
seg.texture,
|
||||
mat,
|
||||
this._enableBatch,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _prepareBuffers (): { meshBuffer: MeshBuffer, startIndex: number } | null {
|
||||
// Full refresh: the dirty-gated vertex half + the frame-scoped index
|
||||
// half. Shared by the web walk (_render) and _prepareNativeDrawInfos.
|
||||
if (!this.updateVertexBuffer()) return null;
|
||||
return this.appendIndexBuffer();
|
||||
}
|
||||
|
||||
/**
|
||||
* Vertex half of a refresh: grow the chunk, copy this frame's bytes, bake
|
||||
* the world matrix when batching, fold cascaded opacity, capture the poll
|
||||
* inputs. The expensive half — callers gate it (native: dirty only; web:
|
||||
* every frame). Returns whether the chunk holds this frame's vertices.
|
||||
*/
|
||||
protected updateVertexBuffer (): boolean {
|
||||
if (!this._renderData || !this._meshData) return false;
|
||||
const data = this._meshData;
|
||||
const rd = this._renderData;
|
||||
const vc = data.vertexCount;
|
||||
const ic = data.indexCount;
|
||||
if (vc < 1 || ic < 1) return false;
|
||||
const vLength = vc * data.vertexStride;
|
||||
|
||||
// ~10% head room, clamped to the accessor's per-chunk caps — an
|
||||
// unclamped reserve would permanently fail data that fits (30000 ->
|
||||
// 33000 requested > 32767). Per-frame counts live on the render data;
|
||||
// the reserve lives on the chunk.
|
||||
if (!rd.chunk || rd.chunk.vb.byteLength < vLength || rd.chunk.indexCount < ic) {
|
||||
rd.resize(
|
||||
Math.min(Math.ceil(vc * 1.1), rd.accessor.maxVertexCount),
|
||||
Math.min(Math.ceil(ic * 1.1), rd.accessor.maxIndexCount),
|
||||
);
|
||||
if (!rd.chunk) {
|
||||
errorID(9017, vc, ic, rd.accessor.maxVertexCount, rd.accessor.maxIndexCount);
|
||||
return false;
|
||||
}
|
||||
rd.updateSize(vc, ic);
|
||||
} else if (rd.vertexCount !== vc || rd.indexCount !== ic) {
|
||||
rd.updateSize(vc, ic);
|
||||
}
|
||||
if (!rd.chunk) return false;
|
||||
// Copy into the chunk's view of the shared vData.
|
||||
const vbuf = rd.chunk.vb;
|
||||
const vU8 = new Uint8Array(vbuf.buffer, vbuf.byteOffset, vLength);
|
||||
vU8.set(data.vertexData.subarray(0, vLength));
|
||||
|
||||
// Batched: a merged batch carries no per-draw matrix, so bake the
|
||||
// world transform into the chunk copy (the incoming vertexData may be
|
||||
// a worker-shared view — never touch it).
|
||||
if (this._enableBatch) {
|
||||
this._bakeWorldTransform(vbuf, vLength, data.vertexStride);
|
||||
}
|
||||
|
||||
// Cascaded opacity: VERTEX-type data gets no engine-side fade, UIMesh
|
||||
// applies it while copying (see the opacity contract in the header).
|
||||
const opacity = this._computeCascadedOpacity();
|
||||
if (opacity < 0.9999) {
|
||||
this._applyOpacity(vU8, vc, data.vertexStride, opacity);
|
||||
}
|
||||
|
||||
// Capture the poll inputs (compared in _onBeforeDraw).
|
||||
this._pollOpacity = opacity;
|
||||
if (this._enableBatch) {
|
||||
this._pollWorldMatrix.set(this.node.worldMatrix);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Index half: offset by the chunk's vertexOffset, append into the shared
|
||||
* index buffer, refresh the draw-info offsets. Must run EVERY frame for
|
||||
* every participating mesh — the batcher resets the index tail after each
|
||||
* upload while draw infos keep absolute offsets, so a mesh that skipped
|
||||
* would alias whichever sibling appends first (see the header contract).
|
||||
* Runs exactly once per frame (native pump / web fillBuffers);
|
||||
* commitMiddleware reads meshBuffer.iData.
|
||||
*/
|
||||
protected appendIndexBuffer (): { meshBuffer: MeshBuffer, startIndex: number } | null {
|
||||
const data = this._meshData;
|
||||
const rd = this._renderData;
|
||||
if (!rd || !rd.chunk || !data || data.vertexCount < 1 || data.indexCount < 1) {
|
||||
return null;
|
||||
}
|
||||
const meshBuffer = rd.getMeshBuffer()!;
|
||||
// The native batcher resets indexOffset through shared memory after
|
||||
// uploading — sync the JS-side cache before appending.
|
||||
if (JSB) meshBuffer.indexOffset = meshBuffer.sharedBuffer[2];
|
||||
const startIndex = meshBuffer.indexOffset;
|
||||
const ic = data.indexCount;
|
||||
const chunkOffset = rd.chunk.vertexOffset;
|
||||
const offsetIndices = new Uint16Array(ic);
|
||||
new Uint8Array(offsetIndices.buffer).set(data.indexData.subarray(0, ic * 2));
|
||||
for (let i = 0; i < ic; i++) offsetIndices[i] += chunkOffset;
|
||||
rd.chunk.vertexAccessor.appendIndices(rd.chunk.bufferId, offsetIndices);
|
||||
rd.chunk.vertexAccessor.getMeshBuffer(rd.chunk.bufferId).setDirty();
|
||||
|
||||
// Static frames never re-run _prepareNativeDrawInfos — keep the cached
|
||||
// draw infos' offsets in step (segment mapping mirrors it).
|
||||
this._refreshDrawInfoOffsets(startIndex);
|
||||
return { meshBuffer, startIndex };
|
||||
}
|
||||
|
||||
private _refreshDrawInfoOffsets (startIndex: number): void {
|
||||
const data = this._meshData;
|
||||
if (!data || this._drawInfoList.length === 0) return;
|
||||
let drawIndex = 0;
|
||||
for (const seg of data.segments) {
|
||||
const mat = seg.material || this.getRenderMaterial(0);
|
||||
if (!seg.texture || !mat) continue;
|
||||
const drawInfo = this._drawInfoList[drawIndex++];
|
||||
if (drawInfo) drawInfo.setIndexOffset(startIndex + seg.indexOffset);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Bakes the FULL world matrix into the chunk copy's positions — exactly
|
||||
* what the USE_LOCAL GPU path applies (pos = cc_matWorld * pos), z and
|
||||
* X/Y-rotation included, so batched and unbatched renders agree. Identity
|
||||
* is skipped.
|
||||
*/
|
||||
private _bakeWorldTransform (vbuf: Float32Array, byteLength: number, stride: number): void {
|
||||
const m = this.node.worldMatrix;
|
||||
const m00 = m.m00; const m01 = m.m01; const m02 = m.m02;
|
||||
const m04 = m.m04; const m05 = m.m05; const m06 = m.m06;
|
||||
const m08 = m.m08; const m09 = m.m09; const m10 = m.m10;
|
||||
const m12 = m.m12; const m13 = m.m13; const m14 = m.m14;
|
||||
if (m00 === 1 && m01 === 0 && m02 === 0
|
||||
&& m04 === 0 && m05 === 1 && m06 === 0
|
||||
&& m08 === 0 && m09 === 0 && m10 === 1
|
||||
&& m12 === 0 && m13 === 0 && m14 === 0) return;
|
||||
const floats = new Float32Array(vbuf.buffer, vbuf.byteOffset, byteLength >> 2);
|
||||
const strideF = stride >> 2;
|
||||
const vertexCount = byteLength / stride;
|
||||
for (let i = 0; i < vertexCount; i++) {
|
||||
const o = i * strideF;
|
||||
const x = floats[o];
|
||||
const y = floats[o + 1];
|
||||
const z = floats[o + 2];
|
||||
floats[o] = m00 * x + m04 * y + m08 * z + m12;
|
||||
floats[o + 1] = m01 * x + m05 * y + m09 * z + m13;
|
||||
floats[o + 2] = m02 * x + m06 * y + m10 * z + m14;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cascaded opacity as Batcher2D.walk accumulates it for COLOR data: own
|
||||
* color alpha x, per ancestor, localOpacity x that ancestor's color alpha.
|
||||
*/
|
||||
private _computeCascadedOpacity (): number {
|
||||
let opacity = this._color.a / 255;
|
||||
for (let node: Node | null = this.node; node; node = node.parent) {
|
||||
opacity *= node._uiProps.localOpacity;
|
||||
if (node !== this.node) {
|
||||
const ancestor = node._uiProps.uiComp as UIRenderer | null;
|
||||
if (ancestor && ancestor.color) opacity *= ancestor.color.a / 255;
|
||||
}
|
||||
}
|
||||
return opacity;
|
||||
}
|
||||
|
||||
/**
|
||||
* Folds opacity into the copied vertices. Light color sits at bytes
|
||||
* 20..23 (pos*3f + uv*2f), dark at 24..27 for two-color. Straight data
|
||||
* fades via the alpha byte only; PMA data scales light RGBA + dark RGB
|
||||
* (dark alpha is the sentinel, not a fade channel).
|
||||
*/
|
||||
private _applyOpacity (vU8: Uint8Array, vc: number, stride: number, opacity: number): void {
|
||||
const pma = this._premultipliedAlpha;
|
||||
const darkRGB = (pma && stride === MESH_STRIDE_TINT_BYTES) ? 3 : 0;
|
||||
for (let i = 0; i < vc; i++) {
|
||||
const o = i * stride + 20;
|
||||
if (pma) {
|
||||
vU8[o] = (vU8[o] * opacity + 0.5) | 0;
|
||||
vU8[o + 1] = (vU8[o + 1] * opacity + 0.5) | 0;
|
||||
vU8[o + 2] = (vU8[o + 2] * opacity + 0.5) | 0;
|
||||
}
|
||||
vU8[o + 3] = (vU8[o + 3] * opacity + 0.5) | 0;
|
||||
for (let j = 0; j < darkRGB; j++) {
|
||||
vU8[o + 4 + j] = (vU8[o + 4 + j] * opacity + 0.5) | 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private _prepareNativeDrawInfos (): void {
|
||||
this._renderEntity.clearDynamicRenderDrawInfos();
|
||||
// Vertex refresh + this frame's index submission; a null return means
|
||||
// there is nothing drawable this frame.
|
||||
const prepared = this._prepareBuffers();
|
||||
const data = this._meshData;
|
||||
const rd = this._renderData;
|
||||
if (!prepared || !data || !rd?.chunk) return;
|
||||
|
||||
const { startIndex } = prepared;
|
||||
let drawIndex = 0;
|
||||
for (const seg of data.segments) {
|
||||
const mat = seg.material || this.getRenderMaterial(0);
|
||||
if (!seg.texture || !mat) continue;
|
||||
let drawInfo = this._drawInfoList[drawIndex];
|
||||
if (!drawInfo) {
|
||||
drawInfo = new RenderDrawInfo();
|
||||
drawInfo.setDrawInfoType(RenderDrawInfoType.MIDDLEWARE);
|
||||
this._drawInfoList[drawIndex] = drawInfo;
|
||||
}
|
||||
drawInfo.setAccAndBuffer(rd.accessor.id, rd.chunk.bufferId);
|
||||
drawInfo.setIndexOffset(startIndex + seg.indexOffset);
|
||||
drawInfo.setIBCount(seg.indexCount);
|
||||
drawInfo.setTexture(seg.texture.getGFXTexture());
|
||||
drawInfo.setSampler(seg.texture.getGFXSampler());
|
||||
drawInfo.setMaterial(mat);
|
||||
this._renderEntity.setDynamicRenderDrawInfo(drawInfo, drawIndex);
|
||||
drawIndex++;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The spine effect (default-spine-material): ui-sprite-material has no
|
||||
* USE_LOCAL variant — node-local input through it would render stuck at
|
||||
* the origin.
|
||||
*/
|
||||
protected _updateBuiltinMaterial (): Material {
|
||||
return builtinResMgr.get<Material>('default-spine-material');
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the builtin material instance in step with the declared vertex
|
||||
* space / data format: USE_LOCAL for the GPU take-over mode, TWO_COLORED
|
||||
* for two-color data, and blend factors matching the alpha format.
|
||||
*/
|
||||
public updateMaterial (): void {
|
||||
// Align the legacy blend-factor fields first so _updateBlendFunc
|
||||
// (inside super) never fights the explicit patching below.
|
||||
this._srcBlendFactor = this._premultipliedAlpha ? BlendFactor.ONE : BlendFactor.SRC_ALPHA;
|
||||
this._dstBlendFactor = BlendFactor.ONE_MINUS_SRC_ALPHA;
|
||||
super.updateMaterial();
|
||||
if (this._customMaterial) return; // custom materials are the user's contract
|
||||
const inst = this.getMaterialInstance(0);
|
||||
if (!inst) return;
|
||||
inst.recompileShaders({
|
||||
USE_LOCAL: !this._enableBatch,
|
||||
TWO_COLORED: this._useTint,
|
||||
});
|
||||
// Straight data: src_alpha / 1-src_alpha (the effect default);
|
||||
// premultiplied data: ONE / 1-src_alpha, color and alpha channels.
|
||||
const src = this._premultipliedAlpha ? BlendFactor.ONE : BlendFactor.SRC_ALPHA;
|
||||
const pass = inst.passes[0];
|
||||
const target = pass.blendState.targets[0];
|
||||
target.blend = true;
|
||||
target.blendSrc = src;
|
||||
target.blendSrcAlpha = src;
|
||||
target.blendDst = BlendFactor.ONE_MINUS_SRC_ALPHA;
|
||||
target.blendDstAlpha = BlendFactor.ONE_MINUS_SRC_ALPHA;
|
||||
pass.blendState.setTarget(0, target);
|
||||
pass._updatePassHash();
|
||||
}
|
||||
|
||||
protected createRenderEntity (): RenderEntity {
|
||||
const entity = new RenderEntity(RenderEntityType.DYNAMIC);
|
||||
// useLocal is re-derived in _syncTransformMode once deserialization
|
||||
// has run.
|
||||
entity.setUseLocal(!this._enableBatch);
|
||||
return entity;
|
||||
}
|
||||
|
||||
private ensureAccessor (useTint: boolean): StaticVBAccessor {
|
||||
const batcher = director.root!.batcher2D;
|
||||
// The previous batcher destroyed its accessors — invalidate the cache.
|
||||
if (_accessorBatcher !== batcher) {
|
||||
_accessorBatcher = batcher;
|
||||
_sharedAccessor = null;
|
||||
_sharedTintAccessor = null;
|
||||
}
|
||||
let accessor = useTint ? _sharedTintAccessor : _sharedAccessor;
|
||||
if (!accessor) {
|
||||
const device = director.root!.device;
|
||||
// Copy the format: the accessor empties its attributes array on
|
||||
// destroy, and the vfmt* constants are shared module-level state.
|
||||
const attributes = (useTint ? vfmtPosUvTwoColor4B : vfmtPosUvColor4B).slice();
|
||||
// 32767: the spine middleware assembler's per-chunk cap
|
||||
// (cocos/spine/assembler/simple.ts), half the Uint16 index space.
|
||||
accessor = new StaticVBAccessor(device, attributes, 32767);
|
||||
batcher.registerBufferAccessor(useTint ? UIMESH_TINT_ACCESSOR_KEY : UIMESH_ACCESSOR_KEY, accessor);
|
||||
if (useTint) {
|
||||
_sharedTintAccessor = accessor;
|
||||
} else {
|
||||
_sharedAccessor = accessor;
|
||||
}
|
||||
}
|
||||
return accessor;
|
||||
}
|
||||
}
|
||||
@@ -29,7 +29,7 @@ import { EDITOR_NOT_IN_PREVIEW } from 'internal:constants';
|
||||
import { Camera, CameraEvent } from '../../misc/camera-component';
|
||||
import { Widget } from '../../ui/widget';
|
||||
import { Vec3, screen, Enum, cclegacy, visibleRect } from '../../core';
|
||||
import { view } from '../../ui/view';
|
||||
import { toUISpace, view } from '../../ui/view';
|
||||
import { RenderRoot2D } from './render-root-2d';
|
||||
|
||||
const _worldPos = new Vec3();
|
||||
@@ -226,7 +226,7 @@ export class Canvas extends RenderRoot2D {
|
||||
this._cameraComponent.orthoHeight = visibleRect.height / 2;
|
||||
} else {
|
||||
const size = screen.windowSize;
|
||||
this._cameraComponent.orthoHeight = size.height / view.getScaleY() / 2;
|
||||
this._cameraComponent.orthoHeight = toUISpace(size.height, view.getRatioY()) / 2;
|
||||
}
|
||||
|
||||
this.node.getWorldPosition(_worldPos);
|
||||
|
||||
@@ -85,6 +85,12 @@ export class StaticVBAccessor extends BufferAccessor {
|
||||
private _id = 0;
|
||||
get id (): number { return this._id; }
|
||||
|
||||
/** Per-chunk capacity; allocateChunk refuses requests above these. */
|
||||
get maxVertexCount (): number { return this._vCount; }
|
||||
|
||||
/** Per-chunk index capacity; allocateChunk refuses requests above these. */
|
||||
get maxIndexCount (): number { return this._iCount; }
|
||||
|
||||
public constructor (device: Device, attributes: Attribute[], vCount?: number, iCount?: number) {
|
||||
super(device, attributes);
|
||||
this._vCount = vCount || Math.floor(macro.BATCHER2D_MEM_INCREMENT * 1024 / this._vertexFormatBytes);
|
||||
|
||||
@@ -45,6 +45,12 @@ export function quoteFontFamily (name: string): CssFontFamily {
|
||||
return `${result}"` as CssFontFamily;
|
||||
}
|
||||
|
||||
/** A simple generated alias is already a CSS identifier and cannot be a reserved family keyword. */
|
||||
export function serializeFontFamily (name: string): CssFontFamily {
|
||||
// Some Canvas implementations only recognize the bare alias registered by the font loader.
|
||||
return /^[A-Za-z_][A-Za-z0-9_-]*_LABEL$/.test(name) ? name as CssFontFamily : quoteFontFamily(name);
|
||||
}
|
||||
|
||||
interface FontFamilySource {
|
||||
readonly useSystemFont: boolean;
|
||||
readonly fontFamily: string;
|
||||
@@ -56,7 +62,7 @@ export function getCanvasFontFamily (source: FontFamilySource): CssFontFamily {
|
||||
const system = source.useSystemFont;
|
||||
const value = system ? source.fontFamily : source.font?._nativeAsset;
|
||||
const name = typeof value === 'string' && value ? value : DEFAULT_FONT_FAMILY;
|
||||
return system ? name as CssFontFamily : quoteFontFamily(name);
|
||||
return system ? name as CssFontFamily : serializeFontFamily(name);
|
||||
}
|
||||
|
||||
/** Family is already serialized: changing size or style must never quote it again. */
|
||||
|
||||
@@ -23,7 +23,7 @@
|
||||
*/
|
||||
|
||||
import { warnID } from '../../core';
|
||||
import { buildFontDesc, quoteFontFamily } from './font-family';
|
||||
import { buildFontDesc, serializeFontFamily } from './font-family';
|
||||
import downloader from '../../asset/asset-manager/downloader';
|
||||
import factory from '../../asset/asset-manager/factory';
|
||||
import { TTFFont } from '../assets/ttf-font';
|
||||
@@ -169,7 +169,7 @@ export function loadFont (url: string, options: Record<string, any>, onComplete:
|
||||
}
|
||||
|
||||
// Default width reference to test whether new font is loaded correctly
|
||||
const familyCss = quoteFontFamily(fontFamilyName);
|
||||
const familyCss = serializeFontFamily(fontFamilyName);
|
||||
const fontDesc = buildFontDesc(40, familyCss);
|
||||
|
||||
// Setup font face style
|
||||
|
||||
@@ -26,6 +26,8 @@
|
||||
*/
|
||||
|
||||
import { screenAdapter, IScreenOptions } from 'pal/screen-adapter';
|
||||
import { systemInfo } from 'pal/system-info';
|
||||
import { OS } from '../../../pal/system-info/enum-type';
|
||||
import { legacyCC } from '../global-exports';
|
||||
import { Size } from '../math';
|
||||
import { settings, SettingsCategory } from '../settings';
|
||||
@@ -101,6 +103,18 @@ export class Screen {
|
||||
return screenAdapter.devicePixelRatio;
|
||||
}
|
||||
|
||||
/**
|
||||
* @en Controls whether the screen stays on while the app is in the foreground.
|
||||
* Supported on native Android and iOS. Has no effect on other platforms.
|
||||
* @zh 控制应用在前台时是否保持屏幕常亮。仅在 Android 和 iOS 原生平台生效。
|
||||
* @param enabled @en Pass true to keep the screen on or false to restore normal screen timeout. @zh 传入 true 开启常亮,传入 false 恢复系统的自动熄屏行为。
|
||||
*/
|
||||
public setKeepScreenOn (enabled: boolean): void {
|
||||
if (systemInfo.isNative && (systemInfo.os === OS.ANDROID || systemInfo.os === OS.IOS)) {
|
||||
jsb.device.setKeepScreenOn(enabled);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @en Get and set the size of current window in physical pixels.
|
||||
* NOTE:
|
||||
|
||||
@@ -69,6 +69,7 @@ const CC_USE_EMBEDDED_ALPHA = 'CC_USE_EMBEDDED_ALPHA';
|
||||
|
||||
const CC_RENDER_MODE = 'CC_RENDER_MODE';
|
||||
const ROTATION_OVER_TIME_MODULE_ENABLE = 'ROTATION_OVER_TIME_MODULE_ENABLE';
|
||||
const USE_NORMAL_MAP = 'USE_NORMAL_MAP';
|
||||
const INSTANCE_PARTICLE = 'CC_INSTANCE_PARTICLE';
|
||||
const RENDER_MODE_BILLBOARD = 0;
|
||||
const RENDER_MODE_STRETCHED_BILLBOARD = 1;
|
||||
@@ -402,9 +403,11 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas
|
||||
}
|
||||
ps.node.getWorldMatrix(_tempWorldTrans);
|
||||
const mat: Material | null = ps.getMaterialInstance(0) || this._defaultMat;
|
||||
const pass = mat!.passes[0];
|
||||
this.doUpdateScale(pass);
|
||||
this.doUpdateRotation(pass);
|
||||
const pass = mat?.passes[0];
|
||||
if (pass) {
|
||||
this.doUpdateScale(pass);
|
||||
this.doUpdateRotation(pass);
|
||||
}
|
||||
|
||||
this._updateList.forEach((value: IParticleModule, key: string): void => {
|
||||
// TODO(cjh): Bug here? _updateList is a Map, the old code uses `this._updateList['some_key'] = some_value;`
|
||||
@@ -695,7 +698,8 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas
|
||||
this._renderInfo!.mainTexture = shareMaterial.getProperty('mainTexture', 0) as Texture2D;
|
||||
}
|
||||
|
||||
if (ps.sharedMaterial == null && this._defaultMat == null) {
|
||||
// Renderer can destroy the cached instance when replacing a preview material.
|
||||
if (ps.sharedMaterial == null && (!this._defaultMat || !this._defaultMat.passes.length)) {
|
||||
_matInsInfo.parent = builtinResMgr.get<Material>('default-particle-material');
|
||||
_matInsInfo.owner = this._particleSystem;
|
||||
_matInsInfo.subModelIdx = 0;
|
||||
@@ -708,6 +712,11 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas
|
||||
}
|
||||
}
|
||||
const mat: Material = ps.getMaterialInstance(0) || this._defaultMat!;
|
||||
// A custom material may still have an invalid or unavailable effect.
|
||||
if (!mat || !mat.passes.length) {
|
||||
warn('Particle material has no render passes. Check its effect import and selected technique.');
|
||||
return;
|
||||
}
|
||||
if (ps.simulationSpace === ParticleSpace.World) {
|
||||
this._defines[CC_USE_WORLD_SPACE] = true;
|
||||
} else {
|
||||
@@ -754,6 +763,10 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas
|
||||
const roationModule = this._particleSystem._rotationOvertimeModule;
|
||||
enable = roationModule ? roationModule.enable : false;
|
||||
this._defines[ROTATION_OVER_TIME_MODULE_ENABLE] = enable;
|
||||
// Explicitly clear the override when the material omits the disabled macro.
|
||||
const materialDefines = (shareMaterial || mat.parent || mat).passes[0]?.defines;
|
||||
this._defines[USE_NORMAL_MAP] = !!materialDefines?.[USE_NORMAL_MAP];
|
||||
|
||||
this._defines[INSTANCE_PARTICLE] = this._useInstance;
|
||||
|
||||
const matIns: MaterialInstance | null = ps.getMaterialInstance(0);
|
||||
@@ -781,7 +794,7 @@ export default class ParticleSystemRendererCPU extends ParticleSystemRendererBas
|
||||
this._trailDefines[CC_USE_WORLD_SPACE] = false;
|
||||
}
|
||||
let mat: Material | null = ps.getMaterialInstance(1);
|
||||
if (mat === null && this._defaultTrailMat === null) {
|
||||
if (mat === null && (!this._defaultTrailMat || !this._defaultTrailMat.passes.length)) {
|
||||
_matInsInfo.parent = builtinResMgr.get<Material>('default-trail-material');
|
||||
_matInsInfo.owner = this._particleSystem;
|
||||
_matInsInfo.subModelIdx = 1;
|
||||
|
||||
@@ -61,6 +61,7 @@ const RENDER_MODE_MESH = 4;
|
||||
|
||||
const COLOR_OVER_TIME_MODULE_ENABLE = 'COLOR_OVER_TIME_MODULE_ENABLE';
|
||||
const ROTATION_OVER_TIME_MODULE_ENABLE = 'ROTATION_OVER_TIME_MODULE_ENABLE';
|
||||
const USE_NORMAL_MAP = 'USE_NORMAL_MAP';
|
||||
const SIZE_OVER_TIME_MODULE_ENABLE = 'SIZE_OVER_TIME_MODULE_ENABLE';
|
||||
const VELOCITY_OVER_TIME_MODULE_ENABLE = 'VELOCITY_OVER_TIME_MODULE_ENABLE';
|
||||
const FORCE_OVER_TIME_MODULE_ENABLE = 'FORCE_OVER_TIME_MODULE_ENABLE';
|
||||
@@ -229,7 +230,7 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas
|
||||
this.initShaderUniform(mat);
|
||||
mat.recompileShaders(this._defines);
|
||||
if (this._model) {
|
||||
this._model.setSubModelMaterial(0, mat);
|
||||
this._model.updateMaterial(mat);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -372,6 +373,9 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas
|
||||
}
|
||||
|
||||
const pass = mat.passes[0];
|
||||
if (!pass) {
|
||||
return;
|
||||
}
|
||||
_tempVec4.x = this._particleSystem.time;
|
||||
_tempVec4.y = dt;
|
||||
pass.setUniform(this._uTimeHandle, _tempVec4);
|
||||
@@ -384,6 +388,13 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas
|
||||
|
||||
public initShaderUniform (mat: Material): void {
|
||||
const pass = mat.passes[0];
|
||||
if (!pass) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Explicitly clear the override when the material omits the disabled macro.
|
||||
const materialDefines = (this._particleSystem?.sharedMaterial || mat.parent || mat).passes[0]?.defines;
|
||||
this._defines[USE_NORMAL_MAP] = !!materialDefines?.[USE_NORMAL_MAP];
|
||||
|
||||
this._uTimeHandle = pass.getHandle('u_timeDelta');
|
||||
this._uRotHandle = pass.getHandle('u_worldRot');
|
||||
@@ -606,7 +617,8 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas
|
||||
this._renderInfo!.mainTexture = shareMaterial.getProperty('mainTexture', 0) as Texture2D;
|
||||
}
|
||||
|
||||
if (ps.sharedMaterial == null && this._defaultMat == null) {
|
||||
// Recreate the fallback if its passes have been destroyed.
|
||||
if (ps.sharedMaterial == null && (!this._defaultMat || !this._defaultMat.passes.length)) {
|
||||
_matInsInfo.parent = builtinResMgr.get<Material>('default-particle-gpu-material');
|
||||
_matInsInfo.owner = ps;
|
||||
_matInsInfo.subModelIdx = 0;
|
||||
@@ -619,6 +631,11 @@ export default class ParticleSystemRendererGPU extends ParticleSystemRendererBas
|
||||
}
|
||||
}
|
||||
const mat: Material | null = ps.getMaterialInstance(0) || this._defaultMat!;
|
||||
// A custom material may still have an invalid or unavailable effect.
|
||||
if (!mat || !mat.passes.length) {
|
||||
warn('Particle material has no render passes. Check its effect import and selected technique.');
|
||||
return;
|
||||
}
|
||||
|
||||
ps.node.getWorldMatrix(_tempWorldTrans);
|
||||
|
||||
|
||||
@@ -102,7 +102,7 @@ class TrailSegment {
|
||||
}
|
||||
if (this.start === -1) {
|
||||
this.start = 0;
|
||||
this.end = 1;
|
||||
this.end = 1 % this.trailElements.length;
|
||||
return this.trailElements[0];
|
||||
}
|
||||
if (this.start === this.end) {
|
||||
@@ -128,20 +128,25 @@ class TrailSegment {
|
||||
p: Particle,
|
||||
dt: number,
|
||||
): void {
|
||||
const end = this.start >= this.end ? this.end + this.trailElements.length : this.end;
|
||||
for (let i = this.start; i < end; i++) {
|
||||
if (this.start === -1) return;
|
||||
const count = this.count();
|
||||
const start = this.start;
|
||||
let removed = 0;
|
||||
for (let i = start; i < start + count; i++) {
|
||||
if (f(target, this.trailElements[i % this.trailElements.length], p, dt)) {
|
||||
this.start++;
|
||||
this.start %= this.trailElements.length;
|
||||
removed++;
|
||||
}
|
||||
}
|
||||
if (this.start === end) {
|
||||
if (removed === count) {
|
||||
this.start = -1;
|
||||
this.end = -1;
|
||||
}
|
||||
}
|
||||
|
||||
public count (): number {
|
||||
if (this.start === -1) return 0;
|
||||
if (this.start < this.end) {
|
||||
return this.end - this.start;
|
||||
} else {
|
||||
@@ -182,7 +187,11 @@ export default class TrailModule {
|
||||
}
|
||||
if (val && !this._enable) {
|
||||
this._enable = val;
|
||||
if (this._particleSystem!.processor) this._particleSystem!.processor.updateTrailMaterial();
|
||||
if (this._particleSystem?.processor) this._particleSystem.processor.updateTrailMaterial();
|
||||
}
|
||||
if (!this._particleSystem) {
|
||||
this._enable = val;
|
||||
return;
|
||||
}
|
||||
if (val && !this._trailModel) {
|
||||
this._createModel();
|
||||
@@ -397,7 +406,7 @@ export default class TrailModule {
|
||||
}
|
||||
|
||||
public onDisable (): void {
|
||||
this._particleTrail.clear();
|
||||
this.clear();
|
||||
this._detachFromScene();
|
||||
}
|
||||
|
||||
@@ -423,6 +432,7 @@ export default class TrailModule {
|
||||
}
|
||||
|
||||
public destroy (): void {
|
||||
this.clear();
|
||||
this.destroySubMeshData();
|
||||
if (this._trailModel) {
|
||||
director.root!.destroyModel(this._trailModel);
|
||||
@@ -441,17 +451,14 @@ export default class TrailModule {
|
||||
}
|
||||
|
||||
public clear (): void {
|
||||
if (this.enable) {
|
||||
const trailIter = this._particleTrail.values();
|
||||
let trail = trailIter.next();
|
||||
while (!trail.done) {
|
||||
trail.value.clear();
|
||||
trail = trailIter.next();
|
||||
}
|
||||
this._particleTrail.clear();
|
||||
this.updateRenderData();
|
||||
if (this._trailModel) this._trailModel.enabled = false;
|
||||
for (const trail of this._particleTrail.values()) {
|
||||
trail.clear();
|
||||
this._trailSegments?.free(trail);
|
||||
}
|
||||
this._particleTrail.clear();
|
||||
this.vbOffset = 0;
|
||||
this.ibOffset = 0;
|
||||
if (this._trailModel) this._trailModel.enabled = false;
|
||||
}
|
||||
|
||||
public updateMaterial (): void {
|
||||
@@ -505,7 +512,7 @@ export default class TrailModule {
|
||||
}
|
||||
if (lastSeg) {
|
||||
trail.iterateElement(this, this._updateTrailElement, p, scaledDt);
|
||||
if (Vec3.squaredDistance(lastSeg.position, _temp_vec3) < this._minSquaredDistance) {
|
||||
if (trail.count() > 0 && Vec3.squaredDistance(lastSeg.position, _temp_vec3) < this._minSquaredDistance) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
@@ -516,6 +523,8 @@ export default class TrailModule {
|
||||
|
||||
Vec3.copy(lastSeg.position, _temp_vec3);
|
||||
lastSeg.lifetime = 0;
|
||||
lastSeg.direction = 0;
|
||||
lastSeg.velocity.set(0, 0, 0);
|
||||
if (this.widthFromParticle) {
|
||||
lastSeg.width = p.size.x * this.widthRatio.evaluate(0, 1)!;
|
||||
} else {
|
||||
@@ -526,6 +535,7 @@ export default class TrailModule {
|
||||
if (trailNum === 2) {
|
||||
const lastSecondTrail = trail.getElement(trail.end - 2)!;
|
||||
Vec3.subtract(lastSecondTrail.velocity, lastSeg.position, lastSecondTrail.position);
|
||||
Vec3.normalize(lastSecondTrail.velocity, lastSecondTrail.velocity);
|
||||
} else if (trailNum > 2) {
|
||||
const lastSecondTrail = trail.getElement(trail.end - 2)!;
|
||||
const lastThirdTrail = trail.getElement(trail.end - 3)!;
|
||||
@@ -557,14 +567,28 @@ export default class TrailModule {
|
||||
public updateRenderData (): void {
|
||||
this.vbOffset = 0;
|
||||
this.ibOffset = 0;
|
||||
for (const p of this._particleTrail.keys()) {
|
||||
const trailSeg = this._particleTrail.get(p)!;
|
||||
let vertexCount = 0;
|
||||
for (const trail of this._particleTrail.values()) {
|
||||
if (trail.count() > 0) vertexCount += (trail.count() + 1) * 2;
|
||||
}
|
||||
// Initialization preallocates the estimated capacity; grow only if that estimate is exceeded.
|
||||
if (vertexCount > this._iaVertCount) {
|
||||
if (!this._ensureBufferCapacity(Math.min(vertexCount, 65536))) {
|
||||
// Do not upload or draw with a partially resized pair of GPU buffers.
|
||||
this.updateIA(0);
|
||||
if (this._trailModel) this._trailModel.enabled = false;
|
||||
return;
|
||||
}
|
||||
}
|
||||
for (const [p, trailSeg] of this._particleTrail) {
|
||||
if (trailSeg.start === -1) {
|
||||
continue;
|
||||
}
|
||||
const indexOffset = this.vbOffset * 4 / this._vertSize;
|
||||
const end = trailSeg.start >= trailSeg.end ? trailSeg.end + trailSeg.trailElements.length : trailSeg.end;
|
||||
const trailNum = end - trailSeg.start;
|
||||
// Uint16 indices cannot address vertices beyond this limit.
|
||||
if (indexOffset + (trailNum + 1) * 2 > 65536) continue;
|
||||
// const lastSegRatio = vec3.distance(trailSeg.getTailElement()!.position, p.position) / this._minParticleDistance;
|
||||
const textCoordSeg = 1 / (trailNum /* - 1 + lastSegRatio */);
|
||||
const startSegEle = trailSeg.trailElements[trailSeg.start];
|
||||
@@ -656,11 +680,13 @@ export default class TrailModule {
|
||||
const subModels = this._trailModel && this._trailModel.subModels;
|
||||
if (subModels && subModels.length > 0) {
|
||||
const subModel = subModels[0];
|
||||
subModel.inputAssembler.vertexBuffers[0].update(this._vbF32!);
|
||||
subModel.inputAssembler.indexBuffer!.update(this._iBuffer!);
|
||||
if (count > 0) {
|
||||
subModel.inputAssembler.vertexBuffers[0].update(this._vbF32!, this.vbOffset * 4);
|
||||
subModel.inputAssembler.indexBuffer!.update(this._iBuffer!, count * Uint16Array.BYTES_PER_ELEMENT);
|
||||
}
|
||||
subModel.inputAssembler.firstIndex = 0;
|
||||
subModel.inputAssembler.indexCount = count;
|
||||
subModel.inputAssembler.vertexCount = this._iaVertCount;
|
||||
subModel.inputAssembler.vertexCount = this.vbOffset * 4 / this._vertSize;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -676,8 +702,31 @@ export default class TrailModule {
|
||||
this._trailModel = (cclegacy.director.root as Root).createModel(scene.Model);
|
||||
}
|
||||
|
||||
private _ensureBufferCapacity (vertexCount: number): boolean {
|
||||
if (vertexCount <= this._iaVertCount) return true;
|
||||
if (!this._subMeshData) return false;
|
||||
const capacity = Math.min(65536, Math.max(vertexCount, this._iaVertCount * 2));
|
||||
const vertexBytes = capacity * this._vertSize;
|
||||
const indexBytes = capacity * 3 * Uint16Array.BYTES_PER_ELEMENT;
|
||||
const vertexBuffer = this._subMeshData.vertexBuffers[0];
|
||||
const indexBuffer = this._subMeshData.indexBuffer!;
|
||||
if (vertexBuffer.size < vertexBytes) vertexBuffer.resize(vertexBytes);
|
||||
if (indexBuffer.size < indexBytes) indexBuffer.resize(indexBytes);
|
||||
if (vertexBuffer.size < vertexBytes || indexBuffer.size < indexBytes) return false;
|
||||
|
||||
// Commit CPU storage and capacity only after both GPU allocations succeed.
|
||||
const buffer = new ArrayBuffer(vertexBytes);
|
||||
this._vbF32 = new Float32Array(buffer);
|
||||
this._vbUint32 = new Uint32Array(buffer);
|
||||
this._iBuffer = new Uint16Array(capacity * 3);
|
||||
this._iaVertCount = capacity;
|
||||
this._iaIndexCount = this._iBuffer.length;
|
||||
return true;
|
||||
}
|
||||
|
||||
private rebuild (): void {
|
||||
const self = this;
|
||||
// Preserve the full estimate from onInit instead of relying on runtime buffer growth.
|
||||
const device: Device = director.root!.device;
|
||||
const vertexBuffer = device.createBuffer(new BufferInfo(
|
||||
BufferUsageBit.VERTEX | BufferUsageBit.TRANSFER_DST,
|
||||
@@ -715,6 +764,7 @@ export default class TrailModule {
|
||||
|
||||
private _updateTrailElement (module: TrailModule, trailEle: ITrailElement, p: Particle, dt: number): boolean {
|
||||
trailEle.lifetime += dt;
|
||||
if (module._trailLifetime <= 0 || trailEle.lifetime > module._trailLifetime) return true;
|
||||
if (module.colorFromParticle) {
|
||||
trailEle.color.set(p.color);
|
||||
trailEle.color.multiply(module.colorOvertime.evaluate(1.0 - p.remainingLifetime / p.startLifetime, 1));
|
||||
|
||||
+130
-141
@@ -26,7 +26,6 @@
|
||||
import { BufferInfo, Buffer, BufferUsageBit, ClearFlagBit, Color, DescriptorSet, LoadOp,
|
||||
Format, Rect, Sampler, StoreOp, Texture, Viewport, MemoryUsageBit,
|
||||
UniformBlock,
|
||||
Device,
|
||||
} from '../../gfx';
|
||||
import { ReflectionProbe } from '../../render-scene/scene/reflection-probe';
|
||||
import { Camera, SkyBoxFlagValue } from '../../render-scene/scene/camera';
|
||||
@@ -446,58 +445,109 @@ export function getDescBindingFromName (bindingName: string): number {
|
||||
return -1;
|
||||
}
|
||||
|
||||
const uploadedUniforms = new WeakMap<Buffer, Float32Array>();
|
||||
function isUniformChanged (cached: Float32Array, values: number[]): boolean {
|
||||
return cached.length !== values.length || values.some((v, i) => !Object.is(Math.fround(v), cached[i]));
|
||||
}
|
||||
|
||||
class DescBuffManager {
|
||||
private buffers: Buffer[] = [];
|
||||
private currBuffIdx: number = 0;
|
||||
private device: Device;
|
||||
public currUniform: Float32Array;
|
||||
private _root;
|
||||
private currUniform: Float32Array;
|
||||
private lastUploadedBuffer: Buffer | null = null;
|
||||
constructor (bufferSize: number, numBuffers: number = 2) {
|
||||
const root = this._root = cclegacy.director.root;
|
||||
const device = root.device;
|
||||
this.device = device;
|
||||
const root = cclegacy.director.root;
|
||||
const device = (root.pipeline as WebPipeline)?.device || root.device;
|
||||
const { buffers } = this;
|
||||
const bufferInfo = new BufferInfo(
|
||||
BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST,
|
||||
MemoryUsageBit.HOST | MemoryUsageBit.DEVICE,
|
||||
bufferSize,
|
||||
bufferSize,
|
||||
);
|
||||
this.currUniform = new Float32Array(bufferSize / 4);
|
||||
for (let i = 0; i < numBuffers; i++) {
|
||||
const bufferInfo: BufferInfo = new BufferInfo(
|
||||
BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST,
|
||||
MemoryUsageBit.HOST | MemoryUsageBit.DEVICE,
|
||||
bufferSize,
|
||||
bufferSize,
|
||||
);
|
||||
this.buffers.push(this.device.createBuffer(bufferInfo));
|
||||
buffers.push(device.createBuffer(bufferInfo));
|
||||
}
|
||||
}
|
||||
getCurrentBuffer (): Buffer {
|
||||
const { director } = cclegacy;
|
||||
this.currBuffIdx = director.getTotalFrames() % this.buffers.length;
|
||||
return this.buffers[this.currBuffIdx];
|
||||
updateBuffer (binding: number, descriptorSet: DescriptorSet, values: number[]): void {
|
||||
const { buffers, currUniform } = this;
|
||||
let lastBuf = this.lastUploadedBuffer;
|
||||
if (!lastBuf || isUniformChanged(currUniform, values)) {
|
||||
if (lastBuf) {
|
||||
uploadedUniforms.delete(lastBuf);
|
||||
}
|
||||
lastBuf = buffers[this.currBuffIdx];
|
||||
this.currBuffIdx = (this.currBuffIdx + 1) % buffers.length;
|
||||
currUniform.set(values);
|
||||
lastBuf.update(currUniform);
|
||||
uploadedUniforms.set(lastBuf, currUniform);
|
||||
this.lastUploadedBuffer = lastBuf;
|
||||
}
|
||||
descriptorSet.bindBuffer(binding, lastBuf);
|
||||
}
|
||||
updateData (vals: number[]): void {
|
||||
this.currUniform.set(vals);
|
||||
}
|
||||
updateBuffer (bindId: number, setData: DescriptorSetData): void {
|
||||
const descriptorSet = setData.descriptorSet!;
|
||||
const buffer = this.getCurrentBuffer();
|
||||
buffer.update(this.currUniform);
|
||||
bindGlobalDesc(descriptorSet, bindId, buffer);
|
||||
destroy (): void {
|
||||
const { buffers } = this;
|
||||
for (const buffer of buffers) {
|
||||
uploadedUniforms.delete(buffer);
|
||||
buffer.destroy();
|
||||
}
|
||||
buffers.length = 0;
|
||||
this.lastUploadedBuffer = null;
|
||||
}
|
||||
}
|
||||
|
||||
const buffsMap: Map<string, DescBuffManager> = new Map();
|
||||
const currBindBuffs: Map<string, number> = new Map();
|
||||
interface ConstantBlockInfo {
|
||||
offset: number;
|
||||
buffer: number[];
|
||||
blockId: number;
|
||||
}
|
||||
|
||||
const layouts: Map<string, DescriptorSetData> = new Map();
|
||||
export function getDescriptorSetDataFromLayout (layoutName: string): DescriptorSetData | undefined {
|
||||
interface LayoutUBOCache {
|
||||
descriptorSetData: DescriptorSetData;
|
||||
uniformBlockMap: Map<number, number[]>;
|
||||
constantBlockMap: Map<number, ConstantBlockInfo>;
|
||||
}
|
||||
|
||||
const pipelineCaches = new WeakMap<WebPipeline, { buffsMap: Map<string, DescBuffManager>; layouts: Map<string, LayoutUBOCache> }>();
|
||||
const pendingBlocks: Map<number, number[]> = new Map();
|
||||
|
||||
function getUBOCache (webPip: WebPipeline): { buffsMap: Map<string, DescBuffManager>; layouts: Map<string, LayoutUBOCache> } {
|
||||
let cache = pipelineCaches.get(webPip);
|
||||
if (!cache) {
|
||||
cache = { buffsMap: new Map(), layouts: new Map() };
|
||||
pipelineCaches.set(webPip, cache);
|
||||
}
|
||||
return cache;
|
||||
}
|
||||
|
||||
export function destroyUBOCache (webPip: WebPipeline): void {
|
||||
const cache = pipelineCaches.get(webPip);
|
||||
if (!cache) { return; }
|
||||
for (const manager of cache.buffsMap.values()) {
|
||||
manager.destroy();
|
||||
}
|
||||
pipelineCaches.delete(webPip);
|
||||
}
|
||||
|
||||
function getLayoutUBOCache (layoutName: string): LayoutUBOCache | undefined {
|
||||
const webPip = cclegacy.director.root.pipeline as WebPipeline;
|
||||
const { layouts } = getUBOCache(webPip);
|
||||
const descLayout = layouts.get(layoutName);
|
||||
if (descLayout) {
|
||||
return descLayout;
|
||||
}
|
||||
const webPip = cclegacy.director.root.pipeline as WebPipeline;
|
||||
const stageId = webPip.layoutGraph.locateChild(webPip.layoutGraph.N, layoutName);
|
||||
const layout = webPip.layoutGraph.getLayout(stageId);
|
||||
const layoutData = layout.getSet(UpdateFrequency.PER_PASS);
|
||||
layouts.set(layoutName, layoutData!);
|
||||
return layoutData;
|
||||
const lg = webPip.layoutGraph;
|
||||
const stageId = lg.locateChild(lg.N, layoutName);
|
||||
const layoutData = lg.getLayout(stageId).getSet(UpdateFrequency.PER_PASS);
|
||||
if (!layoutData) { return undefined; }
|
||||
const cache: LayoutUBOCache = { descriptorSetData: layoutData, uniformBlockMap: new Map(), constantBlockMap: new Map() };
|
||||
layouts.set(layoutName, cache);
|
||||
return cache;
|
||||
}
|
||||
|
||||
export function getDescriptorSetDataFromLayout (layoutName: string): DescriptorSetData | undefined {
|
||||
return getLayoutUBOCache(layoutName)?.descriptorSetData;
|
||||
}
|
||||
|
||||
export function getDescriptorSetDataFromLayoutId (id: number): DescriptorSetData | undefined {
|
||||
@@ -507,147 +557,74 @@ export function getDescriptorSetDataFromLayoutId (id: number): DescriptorSetData
|
||||
return layoutData;
|
||||
}
|
||||
|
||||
export function updateGlobalDescBinding (data: RenderData, sceneId: number, idxRD: number, layoutName = 'default'): void {
|
||||
updatePerPassUBO(layoutName, sceneId, idxRD, data);
|
||||
}
|
||||
|
||||
function getUniformBlock (block: string, layoutName: string): UniformBlock | undefined {
|
||||
const webPip = cclegacy.director.root.pipeline as WebPipeline;
|
||||
const lg = webPip.layoutGraph;
|
||||
const nodeId = lg.locateChild(0xFFFFFFFF, layoutName);
|
||||
const ppl = lg.getLayout(nodeId);
|
||||
const layout = ppl.getSet(UpdateFrequency.PER_PASS)!.descriptorSetLayoutData;
|
||||
const nameID: number = lg.attributeIndex.get(block)!;
|
||||
return layout.uniformBlocks.get(nameID);
|
||||
}
|
||||
|
||||
function getUniformOffset (uniform: string, block: string, layout: string): number {
|
||||
const uniformBlock = getUniformBlock(block, layout);
|
||||
if (!uniformBlock) return -1;
|
||||
function getUniformOffset (uniform: string, uniformBlock: UniformBlock): number {
|
||||
let offset = 0;
|
||||
for (const currUniform of uniformBlock.members) {
|
||||
const currCount = getUBOTypeCount(currUniform.type);
|
||||
if (currUniform.name === uniform) {
|
||||
return offset;
|
||||
}
|
||||
offset += currCount * currUniform.count;
|
||||
offset += getUBOTypeCount(currUniform.type) * currUniform.count;
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
const uniformBlockMap: Map<string, number[]> = new Map();
|
||||
class ConstantBlockInfo {
|
||||
offset: number = -1;
|
||||
buffer: number[] = [];
|
||||
blockId: number = -1;
|
||||
}
|
||||
const constantBlockMap: Map<number, ConstantBlockInfo> = new Map();
|
||||
function copyToConstantBuffer (target: number[], val: number[], offset: number): boolean {
|
||||
let isImparity = false;
|
||||
if (offset < 0 || offset > target.length) {
|
||||
return isImparity;
|
||||
}
|
||||
const length = Math.min(val.length, target.length - offset);
|
||||
|
||||
for (let i = 0; i < length; i++) {
|
||||
if (target[offset + i] !== val[i]) {
|
||||
target[offset + i] = val[i];
|
||||
isImparity = true;
|
||||
}
|
||||
}
|
||||
return isImparity;
|
||||
}
|
||||
|
||||
function addConstantBuffer (block: string, layout: string): number[] | null {
|
||||
let buffers = uniformBlockMap.get(block);
|
||||
function addConstantBuffer (blockId: number, currBlock: UniformBlock, uniformBlockMap: Map<number, number[]>): number[] {
|
||||
let buffers = uniformBlockMap.get(blockId);
|
||||
if (buffers) {
|
||||
return buffers;
|
||||
}
|
||||
buffers = [];
|
||||
const webPip = cclegacy.director.root.pipeline as WebPipeline;
|
||||
const lg = webPip.layoutGraph;
|
||||
let currCount = 0;
|
||||
const currBlock = getUniformBlock(block, layout);
|
||||
if (!currBlock) return null;
|
||||
for (const uniform of currBlock.members) {
|
||||
currCount += getUBOTypeCount(uniform.type) * uniform.count;
|
||||
}
|
||||
buffers.length = currCount;
|
||||
buffers.fill(0);
|
||||
uniformBlockMap.set(block, buffers);
|
||||
buffers = new Array<number>(currCount).fill(0);
|
||||
uniformBlockMap.set(blockId, buffers);
|
||||
return buffers;
|
||||
}
|
||||
|
||||
function updateGlobalDescBuffer (descKey: string, vals: number[]): void {
|
||||
let currDescBuff = buffsMap.get(descKey);
|
||||
if (!currDescBuff) {
|
||||
buffsMap.set(descKey, new DescBuffManager(vals.length * 4, 2));
|
||||
currDescBuff = buffsMap.get(descKey);
|
||||
function updateConstantBlock ({ buffer, blockId, offset }: ConstantBlockInfo, data: number[]): void {
|
||||
const length = Math.min(data.length, buffer.length - offset);
|
||||
for (let i = 0; i < length; ++i) {
|
||||
buffer[offset + i] = data[i];
|
||||
}
|
||||
currDescBuff!.updateData(vals);
|
||||
pendingBlocks.set(blockId, buffer);
|
||||
}
|
||||
|
||||
function updateConstantBlock (
|
||||
constantBuff: ConstantBlockInfo,
|
||||
data: number[],
|
||||
descriptorSetData: DescriptorSetData,
|
||||
sceneId: number,
|
||||
idxRD: number,
|
||||
): void {
|
||||
const blockId = constantBuff.blockId;
|
||||
const buffer = constantBuff.buffer;
|
||||
const isImparity = copyToConstantBuffer(buffer, data, constantBuff.offset);
|
||||
const bindId = getDescBinding(blockId, descriptorSetData);
|
||||
const desc = descriptorSetData.descriptorSet!;
|
||||
if (isImparity || !desc.getBuffer(bindId) && bindId !== -1) {
|
||||
const descKey = `${blockId}${bindId}${idxRD}${sceneId}`;
|
||||
currBindBuffs.set(descKey, bindId);
|
||||
updateGlobalDescBuffer(descKey, buffer);
|
||||
}
|
||||
}
|
||||
|
||||
function updateDefaultConstantBlock (blockId: number, sceneId: number, idxRD: number, vals: number[], setData: DescriptorSetData): void {
|
||||
const bindId = getDescBinding(blockId, setData);
|
||||
if (bindId === -1) { return; }
|
||||
const descKey = `${blockId}${bindId}${idxRD}${sceneId}`;
|
||||
currBindBuffs.set(descKey, bindId);
|
||||
updateGlobalDescBuffer(descKey, vals);
|
||||
}
|
||||
|
||||
export function updatePerPassUBO (layout: string, sceneId: number, idxRD: number, user: RenderData): void {
|
||||
export function updateGlobalDescBinding (user: RenderData, sceneId: number, layout = 'default'): void {
|
||||
const { constants, samplers, textures, buffers } = user;
|
||||
const webPip = cclegacy.director.root.pipeline as WebPipeline;
|
||||
const { buffsMap } = getUBOCache(webPip);
|
||||
const lg = webPip.layoutGraph;
|
||||
const descriptorSetData = getDescriptorSetDataFromLayout(layout)!;
|
||||
currBindBuffs.clear();
|
||||
const { descriptorSetData, uniformBlockMap, constantBlockMap } = getLayoutUBOCache(layout)!;
|
||||
const descriptorSet = descriptorSetData.descriptorSet!;
|
||||
const uniformBlocks = descriptorSetData.descriptorSetLayoutData.uniformBlocks;
|
||||
pendingBlocks.clear();
|
||||
for (const [key, data] of constants) {
|
||||
let constantBlock = constantBlockMap.get(key);
|
||||
if (!constantBlock) {
|
||||
const currMemKey = Array.from(lg.constantIndex).find(([_, v]) => v === key)![0];
|
||||
for (const [block, blockId] of lg.attributeIndex) {
|
||||
const constantBuff = addConstantBuffer(block, layout);
|
||||
if (!constantBuff) continue;
|
||||
const offset = getUniformOffset(currMemKey, block, layout);
|
||||
for (const [blockId, uniformBlock] of uniformBlocks) {
|
||||
const constantBuff = addConstantBuffer(blockId, uniformBlock, uniformBlockMap);
|
||||
const offset = getUniformOffset(currMemKey, uniformBlock);
|
||||
// not found
|
||||
if (offset === -1) {
|
||||
// Although the current uniformMem does not belong to the current uniform block,
|
||||
// it does not mean that it should not be bound to the corresponding descriptor.
|
||||
updateDefaultConstantBlock(blockId, sceneId, idxRD, constantBuff, descriptorSetData);
|
||||
const binding = getDescBinding(blockId, descriptorSetData);
|
||||
if (binding !== -1 && !descriptorSet.getBuffer(binding)) {
|
||||
pendingBlocks.set(blockId, constantBuff);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
constantBlockMap.set(key, new ConstantBlockInfo());
|
||||
constantBlock = constantBlockMap.get(key)!;
|
||||
constantBlock.buffer = constantBuff;
|
||||
constantBlock.blockId = blockId;
|
||||
constantBlock.offset = offset;
|
||||
updateConstantBlock(constantBlock, data, descriptorSetData, sceneId, idxRD);
|
||||
constantBlock = { buffer: constantBuff, blockId, offset };
|
||||
constantBlockMap.set(key, constantBlock);
|
||||
updateConstantBlock(constantBlock, data);
|
||||
}
|
||||
} else {
|
||||
updateConstantBlock(constantBlock, data, descriptorSetData, sceneId, idxRD);
|
||||
updateConstantBlock(constantBlock, data);
|
||||
}
|
||||
}
|
||||
|
||||
const descriptorSet = descriptorSetData.descriptorSet!;
|
||||
for (const [key, value] of textures) {
|
||||
const bindId = getDescBinding(key, descriptorSetData);
|
||||
if (bindId === -1) { continue; }
|
||||
@@ -666,15 +643,27 @@ export function updatePerPassUBO (layout: string, sceneId: number, idxRD: number
|
||||
bindGlobalDesc(descriptorSet, bindId, value);
|
||||
}
|
||||
}
|
||||
for (const [key, value] of currBindBuffs) {
|
||||
const buffManager = buffsMap.get(key)!;
|
||||
buffManager.updateBuffer(value, descriptorSetData);
|
||||
for (const [blockId, values] of pendingBlocks) {
|
||||
const binding = getDescBinding(blockId, descriptorSetData);
|
||||
if (binding === -1) { continue; }
|
||||
const boundBuffer = descriptorSet.getBuffer(binding);
|
||||
const boundValues = boundBuffer ? uploadedUniforms.get(boundBuffer) : undefined;
|
||||
if (boundValues && !isUniformChanged(boundValues, values)) {
|
||||
continue;
|
||||
}
|
||||
const key = `${layout}:${blockId}:${sceneId}`;
|
||||
let manager = buffsMap.get(key);
|
||||
if (!manager) {
|
||||
manager = new DescBuffManager(values.length * 4);
|
||||
buffsMap.set(key, manager);
|
||||
}
|
||||
manager.updateBuffer(binding, descriptorSet, values);
|
||||
}
|
||||
for (const [key, value] of buffers) {
|
||||
const bindId = getDescBinding(key, descriptorSetData);
|
||||
if (bindId === -1) { continue; }
|
||||
const buffer = descriptorSet.getBuffer(bindId);
|
||||
if (!buffer) {
|
||||
if (buffer !== value) {
|
||||
bindGlobalDesc(descriptorSet, bindId, value);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -103,7 +103,6 @@ import {
|
||||
RasterPass,
|
||||
RasterSubpass,
|
||||
RaytracePass,
|
||||
RenderData,
|
||||
RenderGraph,
|
||||
RenderGraphValue,
|
||||
RenderGraphVisitor,
|
||||
@@ -773,7 +772,6 @@ class DeviceRenderPass implements RecordingInterface {
|
||||
protected _layoutName: string;
|
||||
protected _viewport: Viewport | null = null;
|
||||
private _layout: RenderPassLayoutInfo | null = null;
|
||||
private _idxOfRenderData: number = 0;
|
||||
|
||||
private _traversalResolves (callback: (resolvePair: ResolvePair) => void): void {
|
||||
const subpassGraph = this._rasterPass.subpassGraph;
|
||||
@@ -899,7 +897,6 @@ class DeviceRenderPass implements RecordingInterface {
|
||||
);
|
||||
}
|
||||
get passMergeInfo (): RenderPassMergeInfo { return rpMergeInfos.get(this._rasterPass)!; }
|
||||
get indexOfRD (): number { return this._idxOfRenderData; }
|
||||
get rasterID (): number { return this._rasterID; }
|
||||
get layoutName (): string { return this._layoutName; }
|
||||
get passID (): number { return this._passID; }
|
||||
@@ -911,9 +908,6 @@ class DeviceRenderPass implements RecordingInterface {
|
||||
get clearStencil (): number { return this._clearStencil; }
|
||||
get deviceQueues (): Map<number, DeviceRenderQueue> { return this._deviceQueues; }
|
||||
get viewport (): Viewport | null { return this._viewport; }
|
||||
addIdxOfRD (): void {
|
||||
this._idxOfRenderData++;
|
||||
}
|
||||
visitResource (resName: string): void {
|
||||
const resourceGraph = context.resourceGraph;
|
||||
const vertId = resourceGraph.vertex(resName);
|
||||
@@ -1038,7 +1032,6 @@ class DeviceRenderPass implements RecordingInterface {
|
||||
this._layoutName = context.renderGraph.getLayout(id);
|
||||
this._passID = cclegacy.rendering.getPassID(this._layoutName);
|
||||
this._deviceQueues.clear();
|
||||
this._idxOfRenderData = 0;
|
||||
let framebuffer: Framebuffer | null = null;
|
||||
const colTextures: Texture[] = [];
|
||||
const currFramebuffer = this._framebuffer;
|
||||
@@ -1172,8 +1165,9 @@ class DeviceComputePass implements RecordingInterface {
|
||||
for (const queue of this._deviceQueues) {
|
||||
queue.record();
|
||||
}
|
||||
const renderData = context.renderGraph.getData(this._computeInfo.id);
|
||||
updateGlobalDescBinding(renderData, -1, 0, context.renderGraph.getLayout(this._computeInfo.id));
|
||||
const rg = context.renderGraph;
|
||||
const passId = this._computeInfo.id;
|
||||
updateGlobalDescBinding(rg.getData(passId), -1, rg.getLayout(passId));
|
||||
}
|
||||
|
||||
resetResource (id: number, pass: ComputePass): void {
|
||||
@@ -1309,32 +1303,26 @@ class DeviceRenderScene implements RecordingInterface {
|
||||
recordCommand(context.commandBuffer, this._renderPass, pass, blitDesc.stageDesc!, shader, screenIa);
|
||||
}
|
||||
|
||||
protected _updateGlobal (data: RenderData, sceneId: number): void {
|
||||
const devicePass = this._currentQueue.devicePass;
|
||||
devicePass.addIdxOfRD();
|
||||
updateGlobalDescBinding(data, sceneId, devicePass.indexOfRD, context.renderGraph.getLayout(devicePass.rasterID));
|
||||
}
|
||||
|
||||
protected _updateRenderData (): void {
|
||||
if (this._currentQueue.isUpdateUBO) return;
|
||||
const devicePass = this._currentQueue.devicePass;
|
||||
const queue = this._currentQueue;
|
||||
if (queue.isUpdateUBO) return;
|
||||
const devicePass = queue.devicePass;
|
||||
const rg = context.renderGraph;
|
||||
const rasterId = devicePass.rasterID;
|
||||
const passRenderData = context.renderGraph.getData(rasterId);
|
||||
const layout = rg.getLayout(rasterId);
|
||||
const sceneId = this.sceneID;
|
||||
// global
|
||||
this._updateGlobal(context.renderGraph.globalRenderData, sceneId);
|
||||
updateGlobalDescBinding(rg.globalRenderData, sceneId, layout);
|
||||
// pass
|
||||
this._updateGlobal(passRenderData, sceneId);
|
||||
updateGlobalDescBinding(rg.getData(rasterId), sceneId, layout);
|
||||
// queue
|
||||
const queueId = this._currentQueue.queueId;
|
||||
const queueRenderData = context.renderGraph.getData(queueId)!;
|
||||
this._updateGlobal(queueRenderData, sceneId);
|
||||
updateGlobalDescBinding(rg.getData(queue.queueId)!, sceneId, layout);
|
||||
// scene
|
||||
const sceneRenderData = context.renderGraph.getData(sceneId)!;
|
||||
if (sceneRenderData) this._updateGlobal(sceneRenderData, sceneId);
|
||||
const sceneRenderData = rg.getData(sceneId);
|
||||
if (sceneRenderData) updateGlobalDescBinding(sceneRenderData, sceneId, layout);
|
||||
devicePass.processRenderLayout();
|
||||
context.passDescriptorSet?.update();
|
||||
this._currentQueue.isUpdateUBO = true;
|
||||
queue.isUpdateUBO = true;
|
||||
}
|
||||
|
||||
private _applyViewport (): void {
|
||||
|
||||
@@ -58,6 +58,7 @@ export enum ResourceResidency {
|
||||
PERSISTENT,
|
||||
EXTERNAL,
|
||||
BACKBUFFER,
|
||||
CUSTOM,
|
||||
}
|
||||
|
||||
export enum QueueHint {
|
||||
|
||||
@@ -45,7 +45,7 @@ import { GeometryRenderer } from '../geometry-renderer';
|
||||
import { Material } from '../../asset/assets';
|
||||
import { decideProfilerCamera } from '../pipeline-funcs';
|
||||
import { DebugViewCompositeType } from '../debug-view';
|
||||
import { buildReflectionProbePass, genHashValue, resetPassMGState } from './define';
|
||||
import { buildReflectionProbePass, destroyUBOCache, genHashValue, resetPassMGState } from './define';
|
||||
import { createGfxDescriptorSetsAndPipelines } from './layout-graph-utils';
|
||||
import { Root } from '../../root';
|
||||
import { Scene } from '../../scene-graph';
|
||||
@@ -1360,6 +1360,7 @@ export class WebPipeline extends WebSetter implements BasicPipeline {
|
||||
return true;
|
||||
}
|
||||
public destroy (): boolean {
|
||||
destroyUBOCache(this);
|
||||
this._pipelineSceneData?.destroy();
|
||||
return true;
|
||||
}
|
||||
@@ -1624,7 +1625,7 @@ export class WebPipeline extends WebSetter implements BasicPipeline {
|
||||
addShadingRateTexture (name: string, width: number, height: number, residency = ResourceResidency.MANAGED): number {
|
||||
const resID = this._resourceGraph.find(name);
|
||||
if (resID !== 0xFFFFFFFF) {
|
||||
this.addShadingRateTexture(name, width, height);
|
||||
this.updateShadingRateTexture(name, width, height);
|
||||
return resID;
|
||||
}
|
||||
const desc = new ResourceDesc();
|
||||
|
||||
@@ -28,7 +28,7 @@ import { NodeEventType } from './node-event';
|
||||
import { CCObjectFlags } from '../core/data/object';
|
||||
import { NodeUIProperties } from './node-ui-properties';
|
||||
import { MobilityMode, NodeSpace, TransformBit } from './node-enum';
|
||||
import { IVec2Like, Mat4, Quat, Vec3 } from '../core/math';
|
||||
import { EPSILON, IVec2Like, Mat4, Quat, toDegree, Vec3 } from '../core/math';
|
||||
import { Layers } from './layers';
|
||||
import { editorExtrasTag, SerializationContext, SerializationOutput, serializeTag } from '../core/data';
|
||||
import { _tempFloatArray, fillMat4WithTempFloatArray } from './utils.jsb';
|
||||
@@ -692,6 +692,14 @@ nodeProto.setPosition = function setPosition(val: Readonly<Vec3> | number, y?: n
|
||||
this._setPosition();
|
||||
};
|
||||
|
||||
nodeProto.getAngle2D = function getAngle2D(): number {
|
||||
const { x, y, z, w } = this._lrot;
|
||||
if (Math.abs(x) < EPSILON && Math.abs(y) < EPSILON) {
|
||||
return toDegree(Math.atan2(2 * w * z, 1 - 2 * z * z));
|
||||
}
|
||||
return this.eulerAngles.z;
|
||||
};
|
||||
|
||||
nodeProto.getRotation = function getRotation(out?: Quat): Quat {
|
||||
const lrot = this._lrot;
|
||||
if (out) {
|
||||
|
||||
@@ -29,7 +29,7 @@ import { NodeUIProperties } from './node-ui-properties';
|
||||
import { cclegacy } from '../core/global-exports';
|
||||
import { nodePolyfill } from './node-dev';
|
||||
import { ISchedulable } from '../core/scheduler';
|
||||
import { approx, EPSILON, Mat3, mat4, Mat4, quat, Quat, v3, Vec3 } from '../core/math';
|
||||
import { approx, EPSILON, Mat3, mat4, Mat4, quat, Quat, toDegree, v3, Vec3 } from '../core/math';
|
||||
import { MobilityMode, NodeSpace, TransformBit } from './node-enum';
|
||||
import { CustomSerializable, editorExtrasTag, SerializationContext, SerializationOutput, serializeTag } from '../core/data';
|
||||
import { errorID, warnID, error, log, getError } from '../core/platform/debug';
|
||||
@@ -59,6 +59,7 @@ const ACTIVE_ON = 1 << 1;
|
||||
|
||||
const idGenerator = new js.IDGenerator('Node');
|
||||
|
||||
/* eslint-disable-next-line max-len */
|
||||
function getConstructor<T> (typeOrClassName: string | Constructor<T> | AbstractedConstructor<T>): Constructor<T> | AbstractedConstructor<T> | null | undefined {
|
||||
if (!typeOrClassName) {
|
||||
errorID(3804);
|
||||
@@ -316,6 +317,7 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable {
|
||||
return null;
|
||||
}
|
||||
|
||||
/* eslint-disable-next-line max-len */
|
||||
protected static _findComponents<T extends Component> (node: Node, constructor: Constructor<T> | AbstractedConstructor<T>, components: Component[]): void {
|
||||
const cls = constructor;
|
||||
const comps = node._components;
|
||||
@@ -1847,6 +1849,22 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @en Gets the signed local Z rotation in degrees for 2D nodes, in [-180, 180].
|
||||
* Full turns are not preserved. For non-planar rotations, returns the Euler Z component.
|
||||
* @zh 获取二维节点的本地 Z 轴有符号旋转角度,范围为 [-180, 180],不保留累计圈数。
|
||||
* 非平面旋转返回欧拉角的 Z 分量。
|
||||
*/
|
||||
public getAngle2D (): number {
|
||||
// YZX Euler decomposition folds Z into [-90, 90]. For a 2D rotation,
|
||||
// extract the signed angle directly, without changing the 3D Euler cache.
|
||||
const { x, y, z, w } = this._lrot;
|
||||
if (Math.abs(x) < EPSILON && Math.abs(y) < EPSILON) {
|
||||
return toDegree(Math.atan2(2 * w * z, 1 - 2 * z * z));
|
||||
}
|
||||
return this.eulerAngles.z;
|
||||
}
|
||||
|
||||
/**
|
||||
* @en Rotation in world coordinate system, represented by a quaternion
|
||||
* @zh 世界坐标系下的旋转,用四元数表示
|
||||
@@ -2801,9 +2819,18 @@ export class Node extends CCObject implements ISchedulable, CustomSerializable {
|
||||
Mat3.multiplyMat4(m3_1, m3_1, m4_2);
|
||||
|
||||
const localScale = self._lscale;
|
||||
localScale.x = Vec3.set(v3_a, m3_1.m00, m3_1.m01, m3_1.m02).length();
|
||||
localScale.y = Vec3.set(v3_a, m3_1.m03, m3_1.m04, m3_1.m05).length();
|
||||
localScale.z = Vec3.set(v3_a, m3_1.m06, m3_1.m07, m3_1.m08).length();
|
||||
// Restore the requested signs. For negative X, the parent may already supply a reflection.
|
||||
const parentScale = parent._scale;
|
||||
const parentSign = (parentScale.x < 0 ? -1 : 1) * (parentScale.y < 0 ? -1 : 1) * (parentScale.z < 0 ? -1 : 1);
|
||||
const localScaleX = Vec3.set(v3_a, m3_1.m00, m3_1.m01, m3_1.m02).length() * (worldScale.x < 0 ? -parentSign : 1);
|
||||
const localScaleY = Vec3.set(v3_a, m3_1.m03, m3_1.m04, m3_1.m05).length() * (worldScale.y < 0 ? -1 : 1);
|
||||
const localScaleZ = Vec3.set(v3_a, m3_1.m06, m3_1.m07, m3_1.m08).length() * (worldScale.z < 0 ? -1 : 1);
|
||||
if ((localScale.x < 0) !== (localScaleX < 0)
|
||||
|| (localScale.y < 0) !== (localScaleY < 0)
|
||||
|| (localScale.z < 0) !== (localScaleZ < 0)) {
|
||||
rotationFlag = TransformBit.ROTATION;
|
||||
}
|
||||
Vec3.set(localScale, localScaleX, localScaleY, localScaleZ);
|
||||
if (localScale.x === 0 || localScale.y === 0 || localScale.z === 0) {
|
||||
rotationFlag = TransformBit.ROTATION;
|
||||
}
|
||||
|
||||
+107
-45
@@ -56,6 +56,28 @@ import type { Game } from '../game';
|
||||
|
||||
const localWinSize = size();
|
||||
|
||||
/**
|
||||
* A pair of equal lengths measured in the two coordinate spaces:
|
||||
* `pixels` device pixels cover the same distance as `units` UI units, so `scale = pixels / units`.
|
||||
* Converting between the spaces with those two lengths directly avoids the extra rounding of
|
||||
* `pixels / scale`, which is off by one ULP in the common case
|
||||
* (e.g. `1532 / (1532 / 1920) === 1919.9999999999998`).
|
||||
*/
|
||||
export interface ScaleRatio {
|
||||
/** A length in device pixels (the container). */
|
||||
readonly pixels: number;
|
||||
/** The same length in UI units (the design resolution). */
|
||||
readonly units: number;
|
||||
}
|
||||
|
||||
export function toUISpace (value: number, ratio: ScaleRatio): number {
|
||||
return (value * ratio.units) / ratio.pixels;
|
||||
}
|
||||
|
||||
export function toPixelSpace (value: number, ratio: ScaleRatio): number {
|
||||
return (value * ratio.pixels) / ratio.units;
|
||||
}
|
||||
|
||||
const orientationMap = {
|
||||
[macro.ORIENTATION_AUTO]: Orientation.AUTO,
|
||||
[macro.ORIENTATION_LANDSCAPE]: Orientation.LANDSCAPE,
|
||||
@@ -69,8 +91,8 @@ export class View extends Eventify(System) {
|
||||
*/
|
||||
public _designResolutionSize: Size = size(0, 0); // resolution size, it is the size appropriate for the app resources.
|
||||
|
||||
private _scaleX: number = 1;
|
||||
private _scaleY: number = 1;
|
||||
private _ratioX: ScaleRatio = { pixels: 1, units: 1 };
|
||||
private _ratioY: ScaleRatio = { pixels: 1, units: 1 };
|
||||
private _viewportRect: Rect = rect(); // Viewport is the container's rect related to content's coordinates in pixel
|
||||
private _visibleRect: Rect = rect(); // The visible rect in content's coordinate in point
|
||||
private _autoFullScreen: boolean = false; // Auto full screen disabled by default
|
||||
@@ -352,8 +374,8 @@ export class View extends Eventify(System) {
|
||||
*/
|
||||
public getVisibleSizeInPixel (): Size {
|
||||
return new Size(
|
||||
this._visibleRect.width * this._scaleX,
|
||||
this._visibleRect.height * this._scaleY,
|
||||
toPixelSpace(this._visibleRect.width, this._ratioX),
|
||||
toPixelSpace(this._visibleRect.height, this._ratioY),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -371,8 +393,8 @@ export class View extends Eventify(System) {
|
||||
*/
|
||||
public getVisibleOriginInPixel (): Vec2 {
|
||||
return new Vec2(
|
||||
this._visibleRect.x * this._scaleX,
|
||||
this._visibleRect.y * this._scaleY,
|
||||
toPixelSpace(this._visibleRect.x, this._ratioX),
|
||||
toPixelSpace(this._visibleRect.y, this._ratioY),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -451,9 +473,9 @@ export class View extends Eventify(System) {
|
||||
|
||||
const result = policy.apply(this, this._designResolutionSize);
|
||||
|
||||
if (result.scale && result.scale.length === 2) {
|
||||
this._scaleX = result.scale[0];
|
||||
this._scaleY = result.scale[1];
|
||||
if (result.ratioX && result.ratioY) {
|
||||
this._ratioX = result.ratioX;
|
||||
this._ratioY = result.ratioY;
|
||||
}
|
||||
|
||||
if (result.viewport) {
|
||||
@@ -468,8 +490,8 @@ export class View extends Eventify(System) {
|
||||
|
||||
vb.x = 0;
|
||||
vb.y = 0;
|
||||
vb.width = rv.width / this._scaleX;
|
||||
vb.height = rv.height / this._scaleY;
|
||||
vb.width = toUISpace(rv.width, this._ratioX);
|
||||
vb.height = toUISpace(rv.height, this._ratioY);
|
||||
}
|
||||
|
||||
policy.postApply(this);
|
||||
@@ -534,7 +556,7 @@ export class View extends Eventify(System) {
|
||||
* @zh 返回横轴的缩放比,这个缩放比是将画布像素分辨率放到设计分辨率的比例。
|
||||
*/
|
||||
public getScaleX (): number {
|
||||
return this._scaleX;
|
||||
return this._ratioX.pixels / this._ratioX.units;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -542,7 +564,31 @@ export class View extends Eventify(System) {
|
||||
* @zh 返回纵轴的缩放比,这个缩放比是将画布像素分辨率缩放到设计分辨率的比例。
|
||||
*/
|
||||
public getScaleY (): number {
|
||||
return this._scaleY;
|
||||
return this._ratioY.pixels / this._ratioY.units;
|
||||
}
|
||||
|
||||
/**
|
||||
* @en Returns the exact ratio behind `getScaleX()`, use it with `toUISpace()` / `toPixelSpace()`
|
||||
* to convert lengths without the rounding error of `pixels / getScaleX()`.
|
||||
* @zh 返回 `getScaleX()` 背后的精确比例,配合 `toUISpace()` / `toPixelSpace()` 换算长度,
|
||||
* 以避免 `像素 / getScaleX()` 带来的舍入误差。
|
||||
* @engineInternal
|
||||
* @mangle
|
||||
*/
|
||||
public getRatioX (): ScaleRatio {
|
||||
return this._ratioX;
|
||||
}
|
||||
|
||||
/**
|
||||
* @en Returns the exact ratio behind `getScaleY()`, use it with `toUISpace()` / `toPixelSpace()`
|
||||
* to convert lengths without the rounding error of `pixels / getScaleY()`.
|
||||
* @zh 返回 `getScaleY()` 背后的精确比例,配合 `toUISpace()` / `toPixelSpace()` 换算长度,
|
||||
* 以避免 `像素 / getScaleY()` 带来的舍入误差。
|
||||
* @engineInternal
|
||||
* @mangle
|
||||
*/
|
||||
public getRatioY (): ScaleRatio {
|
||||
return this._ratioY;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -579,14 +625,15 @@ export class View extends Eventify(System) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert location in Cocos screen coordinate to location in UI space
|
||||
* @en Converts a length from device pixels to UI units, preferring the exact scale ratio.
|
||||
* @zh 将像素长度换算为 UI 单位长度,优先使用精确比例。
|
||||
* @engineInternal
|
||||
* @mangle
|
||||
*/
|
||||
public _convertToUISpace (point: Vec2): void {
|
||||
const viewport = this._viewportRect;
|
||||
point.x = (point.x - viewport.x) / this._scaleX;
|
||||
point.y = (point.y - viewport.y) / this._scaleY;
|
||||
point.x = toUISpace(point.x - viewport.x, this._ratioX);
|
||||
point.y = toUISpace(point.y - viewport.y, this._ratioY);
|
||||
}
|
||||
|
||||
private _updateAdaptResult (width: number, height: number, windowId?: number): void {
|
||||
@@ -617,8 +664,9 @@ export class View extends Eventify(System) {
|
||||
*/
|
||||
|
||||
interface AdaptResult {
|
||||
scale: number[];
|
||||
viewport?: null | Rect;
|
||||
ratioX: ScaleRatio;
|
||||
ratioY: ScaleRatio;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -699,8 +747,9 @@ class ContentStrategy {
|
||||
public name = 'ContentStrategy';
|
||||
|
||||
private _result: AdaptResult = {
|
||||
scale: [1, 1],
|
||||
viewport: null,
|
||||
ratioX: { pixels: 1, units: 1 },
|
||||
ratioY: { pixels: 1, units: 1 },
|
||||
};
|
||||
protected _strategy = ResolutionPolicy.UNKNOWN;
|
||||
|
||||
@@ -722,13 +771,13 @@ class ContentStrategy {
|
||||
|
||||
/**
|
||||
* @en Function to apply this strategy
|
||||
* The return value is {scale: [scaleX, scaleY], viewport: {new Rect}},
|
||||
* The return value is {ratioX, ratioY, viewport: {new Rect}},
|
||||
* The target view can then apply these value to itself, it's preferred not to modify directly its private variables
|
||||
* @zh 调用策略方法
|
||||
* @return The result scale and viewport rect
|
||||
* @return The exact ratios and the viewport rect
|
||||
*/
|
||||
public apply (_view: View, designedResolution: Size): AdaptResult {
|
||||
return { scale: [1, 1] };
|
||||
return this._result;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -743,7 +792,14 @@ class ContentStrategy {
|
||||
/**
|
||||
* @deprecated since v3.5.0, this is an engine private interface that will be removed in the future.
|
||||
*/
|
||||
public _buildResult (containerW: number, containerH: number, contentW: number, contentH: number, scaleX: number, scaleY: number): AdaptResult {
|
||||
public _buildResult (
|
||||
containerW: number,
|
||||
containerH: number,
|
||||
contentW: number,
|
||||
contentH: number,
|
||||
ratioX: ScaleRatio,
|
||||
ratioY: ScaleRatio,
|
||||
): AdaptResult {
|
||||
// Makes content fit better the canvas
|
||||
if (Math.abs(containerW - contentW) < 2) {
|
||||
contentW = containerW;
|
||||
@@ -760,8 +816,9 @@ class ContentStrategy {
|
||||
);
|
||||
|
||||
const result = this._result;
|
||||
result.scale = [scaleX, scaleY];
|
||||
result.viewport = viewport;
|
||||
result.ratioX = ratioX;
|
||||
result.ratioY = ratioY;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
@@ -819,10 +876,15 @@ class ExactFit extends ContentStrategy {
|
||||
const windowSize = screen.windowSize;
|
||||
const containerW = windowSize.width;
|
||||
const containerH = windowSize.height;
|
||||
const scaleX = containerW / designedResolution.width;
|
||||
const scaleY = containerH / designedResolution.height;
|
||||
|
||||
return this._buildResult(containerW, containerH, containerW, containerH, scaleX, scaleY);
|
||||
return this._buildResult(
|
||||
containerW,
|
||||
containerH,
|
||||
containerW,
|
||||
containerH,
|
||||
{ pixels: containerW, units: designedResolution.width },
|
||||
{ pixels: containerH, units: designedResolution.height },
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -842,21 +904,21 @@ class ShowAll extends ContentStrategy {
|
||||
const designH = designedResolution.height;
|
||||
const scaleX = containerW / designW;
|
||||
const scaleY = containerH / designH;
|
||||
let scale = 0;
|
||||
let contentW: number;
|
||||
let contentH: number;
|
||||
|
||||
let ratio: ScaleRatio;
|
||||
if (scaleX < scaleY) {
|
||||
scale = scaleX;
|
||||
ratio = { pixels: containerW, units: designW };
|
||||
contentW = containerW;
|
||||
contentH = designH * scale;
|
||||
contentH = toPixelSpace(designH, ratio);
|
||||
} else {
|
||||
scale = scaleY;
|
||||
contentW = designW * scale;
|
||||
ratio = { pixels: containerH, units: designH };
|
||||
contentW = toPixelSpace(designW, ratio);
|
||||
contentH = containerH;
|
||||
}
|
||||
|
||||
return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
|
||||
return this._buildResult(containerW, containerH, contentW, contentH, ratio, ratio);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -868,7 +930,7 @@ class NoBorder extends ContentStrategy {
|
||||
this._strategy = ResolutionPolicy.NO_BORDER;
|
||||
}
|
||||
|
||||
public apply (_view, designedResolution): AdaptResult {
|
||||
public apply (_view: View, designedResolution: Size): AdaptResult {
|
||||
const windowSize = screen.windowSize;
|
||||
const containerW = windowSize.width;
|
||||
const containerH = windowSize.height;
|
||||
@@ -876,21 +938,21 @@ class NoBorder extends ContentStrategy {
|
||||
const designH = designedResolution.height;
|
||||
const scaleX = containerW / designW;
|
||||
const scaleY = containerH / designH;
|
||||
let scale: number;
|
||||
let contentW: number;
|
||||
let contentH: number;
|
||||
|
||||
let ratio: ScaleRatio;
|
||||
if (scaleX < scaleY) {
|
||||
scale = scaleY;
|
||||
contentW = designW * scale;
|
||||
ratio = { pixels: containerH, units: designH };
|
||||
contentW = toPixelSpace(designW, ratio);
|
||||
contentH = containerH;
|
||||
} else {
|
||||
scale = scaleX;
|
||||
ratio = { pixels: containerW, units: designW };
|
||||
contentW = containerW;
|
||||
contentH = designH * scale;
|
||||
contentH = toPixelSpace(designH, ratio);
|
||||
}
|
||||
|
||||
return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
|
||||
return this._buildResult(containerW, containerH, contentW, contentH, ratio, ratio);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -907,11 +969,11 @@ class FixedHeight extends ContentStrategy {
|
||||
const containerW = windowSize.width;
|
||||
const containerH = windowSize.height;
|
||||
const designH = designedResolution.height;
|
||||
const scale = containerH / designH;
|
||||
const contentW = containerW;
|
||||
const contentH = containerH;
|
||||
const ratio: ScaleRatio = { pixels: containerH, units: designH };
|
||||
|
||||
return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
|
||||
return this._buildResult(containerW, containerH, contentW, contentH, ratio, ratio);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -928,11 +990,11 @@ class FixedWidth extends ContentStrategy {
|
||||
const containerW = windowSize.width;
|
||||
const containerH = windowSize.height;
|
||||
const designW = designedResolution.width;
|
||||
const scale = containerW / designW;
|
||||
const contentW = containerW;
|
||||
const contentH = containerH;
|
||||
const ratio: ScaleRatio = { pixels: containerW, units: designW };
|
||||
|
||||
return this._buildResult(containerW, containerH, contentW, contentH, scale, scale);
|
||||
return this._buildResult(containerW, containerH, contentW, contentH, ratio, ratio);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1026,12 +1088,12 @@ export class ResolutionPolicy {
|
||||
|
||||
/**
|
||||
* @en Function to apply this resolution policy
|
||||
* The return value is {scale: [scaleX, scaleY], viewport: {new Rect}},
|
||||
* The return value is {ratioX, ratioY, viewport: {new Rect}},
|
||||
* The target view can then apply these value to itself, it's preferred not to modify directly its private variables
|
||||
* @zh 调用策略方法
|
||||
* @param _view - The target view
|
||||
* @param designedResolution - The user defined design resolution
|
||||
* @return An object contains the scale X/Y values and the viewport rect
|
||||
* @return An object contains the exact ratios and the viewport rect
|
||||
*/
|
||||
public apply (_view: View, designedResolution: Size): AdaptResult {
|
||||
this._containerStrategy.apply(_view, designedResolution);
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
#pragma define-meta USE_NORMAL_MAP default(false)
|
||||
#pragma define-meta CC_RENDER_MODE range([0, 4])
|
||||
#pragma define RENDER_MODE_BILLBOARD 0
|
||||
#pragma define RENDER_MODE_STRETCHED_BILLBOARD 1
|
||||
@@ -19,6 +20,13 @@ uniform Constants {
|
||||
out mediump vec2 uv;
|
||||
out mediump vec4 color;
|
||||
|
||||
#if USE_NORMAL_MAP
|
||||
out highp vec3 particlePositionWS;
|
||||
#if CC_RENDER_MODE == RENDER_MODE_MESH
|
||||
out highp vec3 particleNormalWS;
|
||||
#endif
|
||||
#endif
|
||||
|
||||
void computeVertPos (inout vec4 pos, vec2 vertOffset, vec4 q, vec3 s
|
||||
#if CC_RENDER_MODE == RENDER_MODE_BILLBOARD || CC_RENDER_MODE == RENDER_MODE_VERTICAL_BILLBOARD
|
||||
, mat4 viewInv
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
#pragma define-meta USE_NORMAL_MAP default(false)
|
||||
// Both stages must declare the range: Mesh uses 4, beyond the inferred [0, 3].
|
||||
#pragma define-meta CC_RENDER_MODE range([0, 4])
|
||||
#pragma extension([GL_OES_standard_derivatives, __VERSION__ < 300])
|
||||
|
||||
#include <builtin/uniforms/cc-global>
|
||||
|
||||
#if USE_NORMAL_MAP
|
||||
in highp vec3 particlePositionWS;
|
||||
#if CC_RENDER_MODE == 4
|
||||
in highp vec3 particleNormalWS;
|
||||
#endif
|
||||
|
||||
uniform sampler2D normalMap;
|
||||
uniform ParticleNormalConstants {
|
||||
vec4 particleNormalParams;
|
||||
};
|
||||
|
||||
vec4 ApplyParticleNormalLighting (vec4 col, vec2 texCoord) {
|
||||
// Derive the tangent frame from the animated UVs and final world position.
|
||||
// This also handles billboard rotation and meshes without tangent attributes.
|
||||
highp vec3 dpdx = dFdx(particlePositionWS);
|
||||
highp vec3 dpdy = dFdy(particlePositionWS);
|
||||
highp vec2 duvdx = dFdx(texCoord);
|
||||
highp vec2 duvdy = dFdy(texCoord);
|
||||
#if CC_RENDER_MODE == 4
|
||||
highp vec3 n = normalize(particleNormalWS);
|
||||
n *= gl_FrontFacing ? 1.0 : -1.0;
|
||||
#else
|
||||
highp vec3 n = normalize(cross(dpdx, dpdy));
|
||||
// Keep the two-sided billboard's surface normal facing the viewer.
|
||||
n *= dot(n, cc_cameraPos.xyz - particlePositionWS) < 0.0 ? -1.0 : 1.0;
|
||||
#endif
|
||||
highp vec3 perpendicularY = cross(dpdy, n);
|
||||
highp vec3 perpendicularX = cross(n, dpdx);
|
||||
highp vec3 tangent = perpendicularY * duvdx.x + perpendicularX * duvdy.x;
|
||||
highp vec3 bitangent = perpendicularY * duvdx.y + perpendicularX * duvdy.y;
|
||||
highp float frameLength = max(dot(tangent, tangent), dot(bitangent, bitangent));
|
||||
highp float inverseLength = inversesqrt(max(frameLength, 1e-20));
|
||||
vec3 mappedNormal = texture(normalMap, texCoord).xyz * 2.0 - 1.0;
|
||||
mappedNormal.xy *= particleNormalParams.x;
|
||||
highp vec3 perturbedNormal = (tangent * mappedNormal.x + bitangent * mappedNormal.y) * inverseLength + n * mappedNormal.z;
|
||||
n = dot(perturbedNormal, perturbedNormal) > 1e-12 ? normalize(perturbedNormal) : n;
|
||||
|
||||
vec3 lighting = mix(cc_ambientGround.rgb, cc_ambientSky.rgb, n.y * 0.5 + 0.5) * cc_ambientSky.w;
|
||||
#if !CC_DISABLE_DIRECTIONAL_LIGHT
|
||||
lighting += cc_mainLitColor.rgb * cc_mainLitColor.w * max(dot(n, -cc_mainLitDir.xyz), 0.0);
|
||||
#endif
|
||||
col.rgb *= lighting;
|
||||
return col;
|
||||
}
|
||||
#else
|
||||
vec4 ApplyParticleNormalLighting (vec4 col, vec2 texCoord) {
|
||||
return col;
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,9 @@
|
||||
{
|
||||
"ver": "1.0.7",
|
||||
"importer": "effect-header",
|
||||
"imported": true,
|
||||
"uuid": "46b14ea9-3215-41c5-97d6-65254854762e",
|
||||
"files": [],
|
||||
"subMetas": {},
|
||||
"userData": {}
|
||||
}
|
||||
@@ -365,6 +365,14 @@ vec4 gpvs_main () {
|
||||
color *= a_color1;
|
||||
#endif
|
||||
|
||||
#if USE_NORMAL_MAP
|
||||
particlePositionWS = pos.xyz;
|
||||
#if CC_RENDER_MODE == RENDER_MODE_MESH
|
||||
// Inverse-transpose of particle rotation and scale, including mirrored scale.
|
||||
highp vec3 safeScale = mix(vec3(-1.0), vec3(1.0), step(vec3(0.0), compScale)) * max(abs(compScale), vec3(0.000001));
|
||||
particleNormalWS = mat3(xformNoScale) * (a_normal / safeScale);
|
||||
#endif
|
||||
#endif
|
||||
pos = cc_matViewProj * pos;
|
||||
|
||||
float frameIndex = 0.;
|
||||
|
||||
@@ -108,6 +108,14 @@ vec4 lpvs_main () {
|
||||
uv = computeUV(a_texCoord4.w, a_texCoord.xy, frameTile_velLenScale.xy) * mainTiling_Offset.xy + mainTiling_Offset.zw;
|
||||
#endif
|
||||
|
||||
#if USE_NORMAL_MAP
|
||||
particlePositionWS = pos.xyz;
|
||||
#if CC_RENDER_MODE == RENDER_MODE_MESH
|
||||
// Inverse-transpose of particle rotation and scale, including mirrored scale.
|
||||
highp vec3 safeScale = mix(vec3(-1.0), vec3(1.0), step(vec3(0.0), compScale)) * max(abs(compScale), vec3(0.000001));
|
||||
particleNormalWS = mat3(xformNoScale) * (a_normal / safeScale);
|
||||
#endif
|
||||
#endif
|
||||
pos = cc_matViewProj * pos;
|
||||
|
||||
return pos;
|
||||
|
||||
@@ -26,6 +26,8 @@ CCEffect %{
|
||||
r1: &r1 { cullMode: none }
|
||||
p1: &p1
|
||||
mainTexture: { value: grey }
|
||||
normalMap: { value: normal, editor: { parent: USE_NORMAL_MAP } }
|
||||
normalStrength: { value: 1.0, target: particleNormalParams.x, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 5], step: 0.01 } }
|
||||
mainTiling_Offset: { value: [1, 1, 0, 0] }
|
||||
p2: &p2
|
||||
<<: *p1
|
||||
@@ -119,6 +121,8 @@ CCProgram tinted-fs %{
|
||||
in vec2 uv;
|
||||
in vec4 color;
|
||||
|
||||
#include <builtin/internal/particle-normal>
|
||||
|
||||
uniform sampler2D mainTexture;
|
||||
|
||||
uniform FragConstants {
|
||||
@@ -127,14 +131,14 @@ CCProgram tinted-fs %{
|
||||
|
||||
vec4 add () {
|
||||
vec4 col = 2.0 * color * tintColor * CCSampleWithAlphaSeparated(mainTexture, uv);
|
||||
return CCFragOutput(col);
|
||||
return CCFragOutput(ApplyParticleNormalLighting(col, uv));
|
||||
}
|
||||
|
||||
vec4 multiply () {
|
||||
vec4 col;
|
||||
vec4 texColor = CCSampleWithAlphaSeparated(mainTexture, uv);
|
||||
col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);
|
||||
return CCFragOutput(col);
|
||||
return CCFragOutput(ApplyParticleNormalLighting(col, uv));
|
||||
}
|
||||
}%
|
||||
|
||||
@@ -146,16 +150,18 @@ CCProgram no-tint-fs %{
|
||||
in vec2 uv;
|
||||
in vec4 color;
|
||||
|
||||
#include <builtin/internal/particle-normal>
|
||||
|
||||
uniform sampler2D mainTexture;
|
||||
|
||||
vec4 addSmooth () {
|
||||
vec4 col = color * CCSampleWithAlphaSeparated(mainTexture, uv);
|
||||
col.rgb *= col.a;
|
||||
return CCFragOutput(col);
|
||||
return CCFragOutput(ApplyParticleNormalLighting(col, uv));
|
||||
}
|
||||
|
||||
vec4 premultiplied () {
|
||||
vec4 col = color * CCSampleWithAlphaSeparated(mainTexture, uv) * color.a;
|
||||
return CCFragOutput(col);
|
||||
return CCFragOutput(ApplyParticleNormalLighting(col, uv));
|
||||
}
|
||||
}%
|
||||
|
||||
@@ -26,6 +26,8 @@ CCEffect %{
|
||||
r1: &r1 { cullMode: none }
|
||||
p1: &p1
|
||||
mainTexture: { value: grey }
|
||||
normalMap: { value: normal, editor: { parent: USE_NORMAL_MAP } }
|
||||
normalStrength: { value: 1.0, target: particleNormalParams.x, editor: { parent: USE_NORMAL_MAP, slide: true, range: [0, 5], step: 0.01 } }
|
||||
mainTiling_Offset: { value: [1, 1, 0, 0] }
|
||||
p2: &p2
|
||||
<<: *p1
|
||||
@@ -119,6 +121,8 @@ CCProgram tinted-fs %{
|
||||
in vec2 uv;
|
||||
in vec4 color;
|
||||
|
||||
#include <builtin/internal/particle-normal>
|
||||
|
||||
uniform sampler2D mainTexture;
|
||||
uniform FragConstants {
|
||||
vec4 tintColor;
|
||||
@@ -126,14 +130,14 @@ CCProgram tinted-fs %{
|
||||
|
||||
vec4 add () {
|
||||
vec4 col = 2.0 * color * tintColor * CCSampleWithAlphaSeparated(mainTexture, uv);
|
||||
return CCFragOutput(col);
|
||||
return CCFragOutput(ApplyParticleNormalLighting(col, uv));
|
||||
}
|
||||
|
||||
vec4 multiply () {
|
||||
vec4 col;
|
||||
vec4 texColor = CCSampleWithAlphaSeparated(mainTexture, uv);
|
||||
col.rgb = tintColor.rgb * texColor.rgb * color.rgb * vec3(2.0);
|
||||
return CCFragOutput(col);
|
||||
return CCFragOutput(ApplyParticleNormalLighting(col, uv));
|
||||
}
|
||||
}%
|
||||
|
||||
@@ -145,16 +149,18 @@ CCProgram no-tint-fs %{
|
||||
in vec2 uv;
|
||||
in vec4 color;
|
||||
|
||||
#include <builtin/internal/particle-normal>
|
||||
|
||||
uniform sampler2D mainTexture;
|
||||
|
||||
vec4 addSmooth () {
|
||||
vec4 col = color * CCSampleWithAlphaSeparated(mainTexture, uv);
|
||||
col.rgb *= col.a;
|
||||
return CCFragOutput(col);
|
||||
return CCFragOutput(ApplyParticleNormalLighting(col, uv));
|
||||
}
|
||||
|
||||
vec4 premultiplied () {
|
||||
vec4 col = color * CCSampleWithAlphaSeparated(mainTexture, uv) * color.a;
|
||||
return CCFragOutput(col);
|
||||
return CCFragOutput(ApplyParticleNormalLighting(col, uv));
|
||||
}
|
||||
}%
|
||||
|
||||
@@ -412,7 +412,7 @@
|
||||
"spine-3.8": {
|
||||
"enginePlugin": true,
|
||||
"cmakeConfig": "USE_SPINE_3_8",
|
||||
"default": true,
|
||||
"default": false,
|
||||
"isNativeModule": true,
|
||||
"label": "i18n:ENGINE.features.spine_38.label",
|
||||
"description": "i18n:ENGINE.features.spine_38.description",
|
||||
@@ -504,6 +504,13 @@
|
||||
"description": "i18n:ENGINE.features.xr.description",
|
||||
"enginePlugin": false,
|
||||
"envCondition": "$NATIVE || $HTML5"
|
||||
},
|
||||
"webassembly": {
|
||||
"default": true,
|
||||
"required": true,
|
||||
"label": "WebAssembly",
|
||||
"description": "Export the engine's cross-platform WebAssembly loading interface as cc.wasm, so that extensions and game scripts can load their own .wasm files. 以 cc.wasm 导出引擎的跨平台 WebAssembly 加载接口,供扩展与游戏脚本加载自己的 .wasm 文件。",
|
||||
"enginePlugin": true
|
||||
}
|
||||
},
|
||||
"categories": {
|
||||
|
||||
@@ -42,7 +42,7 @@ function formatValue(value) {
|
||||
}
|
||||
|
||||
const imageExt = ['.png', '.jpg', '.jpeg', '.webp', '.gif'];
|
||||
const pageAttr = ['name', 'size', 'format', 'filter', 'repeat', 'pma'];
|
||||
const pageAttr = ['name', 'size', 'format', 'filter', 'repeat', 'scale', 'pma'];
|
||||
|
||||
class ParseAtlasFile {
|
||||
constructor() { }
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
/*
|
||||
Copyright (c) 2026 Xiamen Yaji Software Co., Ltd.
|
||||
|
||||
https://www.cocos.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is furnished
|
||||
to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
import { instantiateWasm, fetchBuffer, fetchUrl, ensureWasmModuleReady } from 'pal/wasm';
|
||||
|
||||
/**
|
||||
* @en
|
||||
* The engine's packaged cross-platform WebAssembly interface (pal/wasm).
|
||||
*
|
||||
* Re-exported under the public `cc.wasm` namespace so extension/game code can
|
||||
* load its own `.wasm` files through the same platform-adaptive path the engine
|
||||
* uses internally for box2d / physx / spine / webgpu:
|
||||
*
|
||||
* - web: fetch the `.wasm` bytes, then `WebAssembly.instantiate`;
|
||||
* - mini-game: resolve the path into `cocos-js/` and delegate to the platform's
|
||||
* `CCWebAssembly.instantiate` (which accepts a file path, never
|
||||
* raw bytes — this is why embedded-base64 wasm fails there);
|
||||
* - native: read the file from `src/cocos-js/` via `fileUtils`.
|
||||
*
|
||||
* The `wasmUrl` argument is a bare file name (e.g. `'foo.wasm'`) whose file is
|
||||
* expected to land in the build output's `cocos-js/` directory.
|
||||
* @zh
|
||||
* 引擎封装好的跨平台 WebAssembly 接口(pal/wasm),通过 `cc.wasm` 命名空间公开,
|
||||
* 供扩展/游戏代码用与引擎内部一致的路径加载自己的 `.wasm`。
|
||||
*/
|
||||
export const wasm = {
|
||||
instantiateWasm,
|
||||
fetchBuffer,
|
||||
fetchUrl,
|
||||
ensureWasmModuleReady,
|
||||
};
|
||||
@@ -36,14 +36,76 @@ constexpr uint32_t MAX_VERTEX_COUNT = 65536;
|
||||
constexpr uint32_t INDICES_PER_VERTEX = 3;
|
||||
constexpr uint32_t MAX_INDEX_COUNT = MAX_VERTEX_COUNT * INDICES_PER_VERTEX;
|
||||
|
||||
// Graphics vertex layout: position.xyz, color.rgba, distance.
|
||||
constexpr uint32_t FLOATS_PER_VERTEX = 8;
|
||||
constexpr uint32_t VERTEX_STRIDE = FLOATS_PER_VERTEX * sizeof(float);
|
||||
constexpr uint32_t ALPHA_OFFSET = 6;
|
||||
|
||||
inline uint32_t growCapacity(uint32_t needed, uint32_t current, uint32_t maxCap) {
|
||||
uint32_t cap = current > 1U ? current : 1U;
|
||||
while (cap < needed) {
|
||||
while (cap < needed && cap < maxCap) {
|
||||
cap *= 2;
|
||||
}
|
||||
return cap < maxCap ? cap : maxCap;
|
||||
}
|
||||
|
||||
class GraphicsModel final : public scene::Model {
|
||||
public:
|
||||
void resizeGeometry(size_t size) {
|
||||
_geometry.resize(size);
|
||||
_lastOpacity = -1.F;
|
||||
}
|
||||
|
||||
void setVertices(size_t index, const float* source, uint32_t count) {
|
||||
auto& chunk = _geometry[index];
|
||||
chunk.paintAlpha.clear();
|
||||
if (count) {
|
||||
// JS can replace its arrays after updateRenderer and before the native UI walk.
|
||||
chunk.vertices.assign(source, source + count * FLOATS_PER_VERTEX);
|
||||
} else {
|
||||
chunk.vertices.clear();
|
||||
}
|
||||
}
|
||||
|
||||
void updateUBOs(uint32_t stamp) override {
|
||||
const auto* node = getNode();
|
||||
if (node && node->_getFinalOpacity() != _lastOpacity) {
|
||||
// The UI walk resolves this node's opacity immediately before submitting the model.
|
||||
const float opacity = node->_getFinalOpacity();
|
||||
for (size_t i = 0; i < _geometry.size(); ++i) {
|
||||
auto& chunk = _geometry[i];
|
||||
if (chunk.vertices.empty()) continue;
|
||||
if (opacity != 1.F && chunk.paintAlpha.empty()) {
|
||||
chunk.paintAlpha.resize(chunk.vertices.size() / FLOATS_PER_VERTEX);
|
||||
for (size_t v = 0; v < chunk.paintAlpha.size(); ++v) {
|
||||
chunk.paintAlpha[v] = chunk.vertices[v * FLOATS_PER_VERTEX + ALPHA_OFFSET];
|
||||
}
|
||||
}
|
||||
for (size_t v = 0; v < chunk.paintAlpha.size(); ++v) {
|
||||
chunk.vertices[v * FLOATS_PER_VERTEX + ALPHA_OFFSET] = chunk.paintAlpha[v] * opacity;
|
||||
}
|
||||
auto* vb = getSubModels()[i]->getInputAssembler()->getVertexBuffers().front();
|
||||
vb->update(chunk.vertices.data(), static_cast<uint32_t>(chunk.vertices.size() * sizeof(float)));
|
||||
}
|
||||
_lastOpacity = opacity;
|
||||
}
|
||||
scene::Model::updateUBOs(stamp);
|
||||
}
|
||||
|
||||
void destroy() override {
|
||||
_geometry.clear();
|
||||
scene::Model::destroy();
|
||||
}
|
||||
|
||||
private:
|
||||
struct Chunk {
|
||||
ccstd::vector<float> vertices;
|
||||
ccstd::vector<float> paintAlpha;
|
||||
};
|
||||
ccstd::vector<Chunk> _geometry;
|
||||
float _lastOpacity{-1.F};
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
UIModelProxy::UIModelProxy() {
|
||||
@@ -55,7 +117,7 @@ UIModelProxy::~UIModelProxy() {
|
||||
}
|
||||
|
||||
void UIModelProxy::initModel(Node* node) {
|
||||
_model = Root::getInstance()->createModel<scene::Model>();
|
||||
_model = Root::getInstance()->createModel<GraphicsModel>();
|
||||
_model->setNode(node);
|
||||
_model->setTransform(node);
|
||||
_node = node;
|
||||
@@ -81,8 +143,8 @@ void UIModelProxy::activeSubModels() {
|
||||
auto* vertexBuffer = _device->createBuffer({
|
||||
gfx::BufferUsageBit::VERTEX | gfx::BufferUsageBit::TRANSFER_DST,
|
||||
gfx::MemoryUsageBit::DEVICE,
|
||||
vertexCapacity * _stride,
|
||||
_stride,
|
||||
vertexCapacity * VERTEX_STRIDE,
|
||||
VERTEX_STRIDE,
|
||||
});
|
||||
auto* indexBuffer = _device->createBuffer({
|
||||
gfx::BufferUsageBit::INDEX | gfx::BufferUsageBit::TRANSFER_DST,
|
||||
@@ -104,27 +166,33 @@ void UIModelProxy::activeSubModels() {
|
||||
}
|
||||
|
||||
void UIModelProxy::uploadData() {
|
||||
if (!_model) return;
|
||||
auto* entity = static_cast<RenderEntity*>(_node->getUserData());
|
||||
const auto& drawInfos = entity->getDynamicRenderDrawInfos();
|
||||
const auto& subModelList = _model->getSubModels();
|
||||
for (size_t i = 0; i < drawInfos.size(); i++) {
|
||||
auto* drawInfo = drawInfos[i];
|
||||
auto* model = static_cast<GraphicsModel*>(_model.get());
|
||||
model->resizeGeometry(subModelList.size());
|
||||
for (size_t i = 0; i < subModelList.size(); i++) {
|
||||
auto* drawInfo = i < drawInfos.size() ? drawInfos[i] : nullptr;
|
||||
auto* ia = subModelList.at(i)->getInputAssembler();
|
||||
const uint32_t vertexCount = drawInfo->getVertexOffset();
|
||||
const uint32_t indexCount = drawInfo->getIndexOffset();
|
||||
if (vertexCount == 0 || indexCount == 0) continue;
|
||||
|
||||
gfx::BufferList vBuffers = ia->getVertexBuffers();
|
||||
if (!vBuffers.empty()) {
|
||||
gfx::Buffer* vBuffer = vBuffers[0];
|
||||
const uint32_t neededVBytes = vertexCount * _stride;
|
||||
if (neededVBytes > vBuffer->getSize()) {
|
||||
const uint32_t capacity = growCapacity(vertexCount, vBuffer->getSize() / _stride, MAX_VERTEX_COUNT);
|
||||
vBuffer->resize(capacity * _stride);
|
||||
}
|
||||
// pass the valid size explicitly, update(ptr) uploads the whole capacity
|
||||
vBuffer->update(drawInfo->getVDataBuffer(), neededVBytes); // vdata
|
||||
const uint32_t vertexCount = drawInfo ? drawInfo->getVertexOffset() : 0U;
|
||||
const uint32_t indexCount = drawInfo ? drawInfo->getIndexOffset() : 0U;
|
||||
const auto& vBuffers = ia->getVertexBuffers();
|
||||
if (!vertexCount || !indexCount || vBuffers.empty() || vertexCount > MAX_VERTEX_COUNT || indexCount > MAX_INDEX_COUNT ||
|
||||
!drawInfo->getVDataBuffer() || !drawInfo->getIDataBuffer()) {
|
||||
model->setVertices(i, nullptr, 0);
|
||||
ia->setVertexCount(0);
|
||||
ia->setIndexCount(0);
|
||||
continue;
|
||||
}
|
||||
|
||||
gfx::Buffer* vBuffer = vBuffers[0];
|
||||
const uint32_t neededVBytes = vertexCount * VERTEX_STRIDE;
|
||||
if (neededVBytes > vBuffer->getSize()) {
|
||||
const uint32_t capacity = growCapacity(vertexCount, vBuffer->getSize() / VERTEX_STRIDE, MAX_VERTEX_COUNT);
|
||||
vBuffer->resize(capacity * VERTEX_STRIDE);
|
||||
}
|
||||
model->setVertices(i, drawInfo->getVDataBuffer(), vertexCount);
|
||||
ia->setVertexCount(vertexCount); // count
|
||||
|
||||
gfx::Buffer* iBuffer = ia->getIndexBuffer();
|
||||
@@ -139,7 +207,7 @@ void UIModelProxy::uploadData() {
|
||||
// drawInfo->setModel(_model); // hack, render by model
|
||||
}
|
||||
|
||||
if (!drawInfos.empty()) {
|
||||
if (!drawInfos.empty() && drawInfos[0]) {
|
||||
drawInfos[0]->setModel(_model);
|
||||
}
|
||||
}
|
||||
@@ -163,6 +231,7 @@ void UIModelProxy::clear() {
|
||||
if (_model == nullptr) {
|
||||
return;
|
||||
}
|
||||
static_cast<GraphicsModel*>(_model.get())->resizeGeometry(0);
|
||||
const auto& subModels = _model->getSubModels();
|
||||
for (const auto& subModel : subModels) {
|
||||
auto* ia = subModel->getInputAssembler();
|
||||
|
||||
@@ -56,7 +56,6 @@ private:
|
||||
ccstd::vector<scene::Model*> _models{};
|
||||
|
||||
gfx::Device* _device{nullptr};
|
||||
uint32_t _stride{32};
|
||||
ccstd::vector<gfx::Attribute> _attributes{
|
||||
gfx::Attribute{gfx::ATTR_NAME_POSITION, gfx::Format::RGB32F},
|
||||
gfx::Attribute{gfx::ATTR_NAME_COLOR, gfx::Format::RGBA32F},
|
||||
|
||||
@@ -42,7 +42,7 @@ ValueArrayPool::ValueArrayPool() {
|
||||
}
|
||||
|
||||
ValueArray &ValueArrayPool::get(uint32_t argc, bool &outNeedDelete) {
|
||||
if (SE_UNLIKELY(_depth >= _pools.size())) {
|
||||
if (SE_UNLIKELY(argc > MAX_ARGS || _depth >= _pools.size())) {
|
||||
outNeedDelete = true;
|
||||
auto *ret = ccnew ValueArray();
|
||||
ret->resize(argc);
|
||||
@@ -50,7 +50,6 @@ ValueArray &ValueArrayPool::get(uint32_t argc, bool &outNeedDelete) {
|
||||
}
|
||||
|
||||
outNeedDelete = false;
|
||||
CC_ASSERT_LE(argc, MAX_ARGS);
|
||||
auto &ret = _pools[_depth][argc];
|
||||
CC_ASSERT(ret.size() == argc);
|
||||
return ret;
|
||||
|
||||
@@ -432,6 +432,14 @@ ccstd::unordered_map<uint32_t, ccstd::string> debugInfos = {
|
||||
{ 9007, "Since v3.6, Because mask changes the inheritance relationship, you can directly manipulate the rendering components under the same node to complete the operation." },
|
||||
{ 9008, "request fullscreen is not supported on this platform." },
|
||||
{ 9009, "exit fullscreen is not supported on this platform." },
|
||||
{ 9010, "UIMesh.setMeshData: unsupported vertexStride %d, expected %d (V3F_T2F_C4B) or %d (V3F_T2F_C4B_C4B); data rejected." },
|
||||
{ 9011, "UIMesh.setMeshData: negative counts (vertexCount %d, indexCount %d); data rejected." },
|
||||
{ 9012, "UIMesh.setMeshData: vertexData holds %d bytes, but %d vertices x %d bytes are declared; data rejected." },
|
||||
{ 9013, "UIMesh.setMeshData: indexData is %d bytes at offset %d, but %d Uint16 indices need %d bytes (2-byte aligned view); data rejected." },
|
||||
{ 9014, "UIMesh.setMeshData: indices[%d] = %d is out of range for %d vertices; data rejected." },
|
||||
{ 9015, "UIMesh.setMeshData: segment %d range [%d, %d) is out of bounds for indexCount %d; data rejected." },
|
||||
{ 9016, "UIMesh.setMeshData: %d vertices / %d indices exceed the accessor cap (%d / %d); split the mesh. Data rejected." },
|
||||
{ 9017, "UIMesh: render data allocation failed for %d vertices / %d indices (accessor cap: %d / %d)." },
|
||||
{ 9100, "texture size exceeds current device limits %d/%d" },
|
||||
{ 9101, "The length of the TypedArrayBuffer must be an integer." },
|
||||
{ 9201, "Cannot access game frame or container." },
|
||||
|
||||
@@ -684,7 +684,12 @@ const Quaternion &Node::getWorldRotation() const { // NOLINT(misc-no-recursion)
|
||||
void Node::setWorldScale(float x, float y, float z) {
|
||||
bool forceUpdate = _parent != nullptr && (_transformFlags & static_cast<uint32_t>(TransformBit::SCALE)) != static_cast<uint32_t>(TransformBit::NONE);
|
||||
|
||||
if (!forceUpdate && _worldScale.approxEquals({x, y, z})) {
|
||||
// World-scale decomposition can hide local mirror signs. Preserve the same-value no-op for nonnegative targets.
|
||||
const bool parentedNonnegativeTarget = _parent != nullptr && x >= 0.F && y >= 0.F && z >= 0.F;
|
||||
if (!forceUpdate && (_parent == nullptr || (y >= 0.F && z >= 0.F)) &&
|
||||
_worldScale.approxEquals({x, y, z}) &&
|
||||
(_worldScale.x < 0.F) == (x < 0.F) &&
|
||||
(parentedNonnegativeTarget || ((_localScale.y < 0.F) == (y < 0.F) && (_localScale.z < 0.F) == (z < 0.F)))) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -738,10 +743,22 @@ void Node::setWorldScale(float x, float y, float z) {
|
||||
// remove rotation part of the local matrix
|
||||
Mat3::multiply(localRotInv, localRS, &localRS);
|
||||
|
||||
// extract scaling part from local matrix
|
||||
_localScale.x = Vec3{localRS.m[0], localRS.m[1], localRS.m[2]}.length();
|
||||
_localScale.y = Vec3{localRS.m[3], localRS.m[4], localRS.m[5]}.length();
|
||||
_localScale.z = Vec3{localRS.m[6], localRS.m[7], localRS.m[8]}.length();
|
||||
// Restore the requested signs after extracting the scale magnitudes.
|
||||
// A negative X request accounts for parent reflection. A nonnegative X keeps
|
||||
// the original positive local X behavior.
|
||||
const Vec3 &parentScale = _parent->_worldScale;
|
||||
const float parentSign = (parentScale.x < 0.F ? -1.F : 1.F) *
|
||||
(parentScale.y < 0.F ? -1.F : 1.F) *
|
||||
(parentScale.z < 0.F ? -1.F : 1.F);
|
||||
const float localScaleX = Vec3{localRS.m[0], localRS.m[1], localRS.m[2]}.length() * (_worldScale.x < 0.F ? -parentSign : 1.F);
|
||||
const float localScaleY = Vec3{localRS.m[3], localRS.m[4], localRS.m[5]}.length() * (_worldScale.y < 0.F ? -1.F : 1.F);
|
||||
const float localScaleZ = Vec3{localRS.m[6], localRS.m[7], localRS.m[8]}.length() * (_worldScale.z < 0.F ? -1.F : 1.F);
|
||||
if ((_localScale.x < 0.F) != (localScaleX < 0.F) ||
|
||||
(_localScale.y < 0.F) != (localScaleY < 0.F) ||
|
||||
(_localScale.z < 0.F) != (localScaleZ < 0.F)) {
|
||||
rotationFlag = TransformBit::ROTATION;
|
||||
}
|
||||
_localScale.set(localScaleX, localScaleY, localScaleZ);
|
||||
|
||||
if (_localScale.x == 0 || _localScale.y == 0 || _localScale.z == 0) {
|
||||
rotationFlag = TransformBit::ROTATION;
|
||||
|
||||
@@ -24,6 +24,8 @@
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <cmath>
|
||||
|
||||
#include "base/Ptr.h"
|
||||
#include "base/std/any.h"
|
||||
#include "bindings/utils/BindingUtils.h"
|
||||
@@ -35,6 +37,7 @@
|
||||
#include "core/scene-graph/NodeEnum.h"
|
||||
#include "math/Mat3.h"
|
||||
#include "math/Mat4.h"
|
||||
#include "math/Math.h"
|
||||
#include "math/Quaternion.h"
|
||||
#include "math/Vec3.h"
|
||||
#include "math/Vec4.h"
|
||||
@@ -434,6 +437,16 @@ public:
|
||||
return getEulerAngles().z;
|
||||
}
|
||||
|
||||
// Signed local 2D angle in degrees, normalized to [-180, 180].
|
||||
inline float getAngle2D() const {
|
||||
// Keep 2D angles independent of the folded Z in YZX Euler decomposition.
|
||||
const auto &q = _localRotation;
|
||||
if (std::abs(q.x) < 1e-6F && std::abs(q.y) < 1e-6F) {
|
||||
return std::atan2(2.F * q.w * q.z, 1.F - 2.F * q.z * q.z) * math::RAD_TO_DEG;
|
||||
}
|
||||
return getEulerAngles().z;
|
||||
}
|
||||
|
||||
inline Vec3 getForward() const {
|
||||
Vec3 forward{0, 0, -1};
|
||||
forward.transformQuat(getWorldRotation());
|
||||
|
||||
@@ -28,13 +28,15 @@
|
||||
* ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! =========================
|
||||
*/
|
||||
// NOLINTBEGIN(misc-include-cleaner)
|
||||
#include "cocos/renderer/pipeline/custom/LayoutGraphSerialization.h"
|
||||
// clang-format off
|
||||
#include "cocos/renderer/pipeline/custom/ArchiveTypes.h"
|
||||
#include "cocos/renderer/pipeline/custom/LayoutGraphGraphs.h"
|
||||
#include "cocos/renderer/pipeline/custom/LayoutGraphSerialization.h"
|
||||
#include "cocos/renderer/pipeline/custom/LayoutGraphTypes.h"
|
||||
#include "cocos/renderer/pipeline/custom/RenderCommonSerialization.h"
|
||||
#include "cocos/renderer/pipeline/custom/details/Range.h"
|
||||
#include "cocos/renderer/pipeline/custom/details/SerializationUtils.h"
|
||||
// clang-format on
|
||||
|
||||
namespace cc {
|
||||
|
||||
|
||||
@@ -71,6 +71,7 @@ inline const char* getName(ResourceResidency e) noexcept {
|
||||
case ResourceResidency::PERSISTENT: return "PERSISTENT";
|
||||
case ResourceResidency::EXTERNAL: return "EXTERNAL";
|
||||
case ResourceResidency::BACKBUFFER: return "BACKBUFFER";
|
||||
case ResourceResidency::CUSTOM: return "CUSTOM";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
@@ -28,10 +28,12 @@
|
||||
* ========================= !DO NOT CHANGE THE FOLLOWING SECTION MANUALLY! =========================
|
||||
*/
|
||||
// NOLINTBEGIN(misc-include-cleaner)
|
||||
#include "cocos/renderer/pipeline/custom/RenderCommonSerialization.h"
|
||||
// clang-format off
|
||||
#include "cocos/renderer/pipeline/custom/ArchiveTypes.h"
|
||||
#include "cocos/renderer/pipeline/custom/RenderCommonSerialization.h"
|
||||
#include "cocos/renderer/pipeline/custom/RenderCommonTypes.h"
|
||||
#include "cocos/renderer/pipeline/custom/details/SerializationUtils.h"
|
||||
// clang-format on
|
||||
|
||||
namespace cc {
|
||||
|
||||
|
||||
@@ -83,6 +83,7 @@ enum class ResourceResidency : uint8_t {
|
||||
PERSISTENT,
|
||||
EXTERNAL,
|
||||
BACKBUFFER,
|
||||
CUSTOM,
|
||||
};
|
||||
|
||||
enum class QueueHint : uint8_t {
|
||||
|
||||
@@ -216,4 +216,174 @@ TEST(NodeTest, setWorldScale0yz_and_rotation) {
|
||||
0, 0, 0, 1)));
|
||||
}
|
||||
|
||||
TEST(NodeTest, angleAfterQuaternionWriteback) {
|
||||
cc::IntrusivePtr<cc::Node> node(new Node());
|
||||
for (const float angle : {-179.F, -120.F, -91.F, -90.F, 90.F, 91.F, 120.F, 179.F}) {
|
||||
const float halfAngle = angle * math::DEG_TO_RAD * 0.5F;
|
||||
const Quaternion rotation(0.F, 0.F, std::sin(halfAngle), std::cos(halfAngle));
|
||||
node->setRotation(rotation);
|
||||
EXPECT_NEAR(node->getAngle2D(), angle, 1e-4F);
|
||||
const Vec3 euler = node->getEulerAngles();
|
||||
EXPECT_NEAR(node->getAngle2D(), angle, 1e-4F);
|
||||
EXPECT_TRUE(node->getEulerAngles().approxEquals(euler));
|
||||
node->setRotation(Quaternion(-rotation.x, -rotation.y, -rotation.z, -rotation.w));
|
||||
EXPECT_NEAR(node->getAngle2D(), angle, 1e-4F);
|
||||
}
|
||||
node->setAngle(720.F);
|
||||
EXPECT_FLOAT_EQ(node->getAngle(), 720.F);
|
||||
EXPECT_NEAR(node->getAngle2D(), 0.F, 1e-4F);
|
||||
const float halfAngle = 60.F * math::DEG_TO_RAD;
|
||||
node->setRotation(Quaternion(0.F, 0.F, std::sin(halfAngle), std::cos(halfAngle)));
|
||||
EXPECT_NEAR(node->getAngle2D(), 120.F, 1e-4F);
|
||||
EXPECT_NEAR(node->getAngle(), 60.F, 1e-4F);
|
||||
EXPECT_NEAR(node->getAngle2D(), 120.F, 1e-4F);
|
||||
}
|
||||
|
||||
TEST(NodeTest, setWorldScaleSignedTargetsAreIdempotent) {
|
||||
for (int signs = 0; signs < 8; ++signs) {
|
||||
cc::IntrusivePtr<cc::Node> parent(new Node());
|
||||
cc::IntrusivePtr<cc::Node> child(new Node());
|
||||
child->setParent(parent);
|
||||
const Vec3 target((signs & 1) ? -2.F : 2.F,
|
||||
(signs & 2) ? -3.F : 3.F,
|
||||
(signs & 4) ? -4.F : 4.F);
|
||||
child->setWorldScale(target);
|
||||
Mat4 expected;
|
||||
Mat4::fromRTS(Quaternion::identity(), Vec3::ZERO, target, &expected);
|
||||
EXPECT_TRUE(child->getScale().approxEquals(target));
|
||||
EXPECT_TRUE(child->getWorldMatrix().approxEquals(expected));
|
||||
child->setWorldScale(target);
|
||||
EXPECT_TRUE(child->getScale().approxEquals(target));
|
||||
EXPECT_TRUE(child->getWorldMatrix().approxEquals(expected));
|
||||
}
|
||||
}
|
||||
|
||||
TEST(NodeTest, setWorldScaleWithSignedParent) {
|
||||
for (int signs = 0; signs < 8; ++signs) {
|
||||
cc::IntrusivePtr<cc::Node> parent(new Node());
|
||||
const float signX = (signs & 1) ? -1.F : 1.F;
|
||||
const float signY = (signs & 2) ? -1.F : 1.F;
|
||||
const float signZ = (signs & 4) ? -1.F : 1.F;
|
||||
parent->setScale(2.F * signX, 3.F * signY, 4.F * signZ);
|
||||
cc::IntrusivePtr<cc::Node> child(new Node());
|
||||
child->setParent(parent);
|
||||
child->setWorldScale(-6.F, 9.F, 8.F);
|
||||
const Vec3 expectedLocal(-3.F * signX * signY * signZ, 3.F, 2.F);
|
||||
EXPECT_TRUE(child->getScale().approxEquals(expectedLocal));
|
||||
EXPECT_TRUE(child->getWorldScale().approxEquals(Vec3(-6.F, 9.F, 8.F)));
|
||||
Mat4 expected;
|
||||
Mat4::fromRTS(Quaternion::identity(), Vec3::ZERO,
|
||||
Vec3(-6.F * signY * signZ, 9.F * signY, 8.F * signZ), &expected);
|
||||
EXPECT_TRUE(child->getWorldMatrix().approxEquals(expected));
|
||||
child->setWorldScale(-6.F, 9.F, 8.F);
|
||||
EXPECT_TRUE(child->getScale().approxEquals(expectedLocal));
|
||||
EXPECT_TRUE(child->getWorldMatrix().approxEquals(expected));
|
||||
|
||||
child->setWorldScale(6.F, 9.F, 8.F);
|
||||
EXPECT_TRUE(child->getScale().approxEquals(Vec3(3.F, 3.F, 2.F)));
|
||||
EXPECT_TRUE(child->getWorldScale().approxEquals(Vec3(6.F * signX * signY * signZ, 9.F, 8.F)));
|
||||
Mat4::fromRTS(Quaternion::identity(), Vec3::ZERO,
|
||||
Vec3(6.F * signX, 9.F * signY, 8.F * signZ), &expected);
|
||||
EXPECT_TRUE(child->getWorldMatrix().approxEquals(expected));
|
||||
}
|
||||
}
|
||||
|
||||
TEST(NodeTest, setWorldScaleSignsDoNotDependOnPreviousLocalScale) {
|
||||
cc::IntrusivePtr<cc::Node> parent(new Node());
|
||||
cc::IntrusivePtr<cc::Node> child(new Node());
|
||||
child->setParent(parent);
|
||||
child->setScale(-1.F, -1.F, -1.F);
|
||||
child->getWorldMatrix();
|
||||
child->setWorldScale(2.F, -3.F, 4.F);
|
||||
EXPECT_TRUE(child->getScale().approxEquals(Vec3(2.F, -3.F, 4.F)));
|
||||
const Mat4 firstMatrix = child->getWorldMatrix();
|
||||
child->setWorldScale(2.F, -3.F, 4.F);
|
||||
EXPECT_TRUE(child->getScale().approxEquals(Vec3(2.F, -3.F, 4.F)));
|
||||
EXPECT_TRUE(child->getWorldMatrix().approxEquals(firstMatrix));
|
||||
child->setWorldScale(2.F, 3.F, 4.F);
|
||||
EXPECT_TRUE(child->getScale().approxEquals(Vec3(2.F, 3.F, 4.F)));
|
||||
}
|
||||
|
||||
TEST(NodeTest, setWorldScaleChangesMirrorAxisWhenWorldScaleMatches) {
|
||||
cc::IntrusivePtr<cc::Node> parent(new Node());
|
||||
cc::IntrusivePtr<cc::Node> child(new Node());
|
||||
child->setParent(parent);
|
||||
child->setWorldScale(2.F, -3.F, 4.F);
|
||||
EXPECT_TRUE(child->getWorldScale().approxEquals(Vec3(-2.F, 3.F, 4.F)));
|
||||
Mat4 expected;
|
||||
Mat4::fromRTS(Quaternion::identity(), Vec3::ZERO, Vec3(2.F, -3.F, 4.F), &expected);
|
||||
EXPECT_TRUE(child->getWorldMatrix().approxEquals(expected));
|
||||
|
||||
child->setWorldScale(-2.F, 3.F, 4.F);
|
||||
EXPECT_TRUE(child->getScale().approxEquals(Vec3(-2.F, 3.F, 4.F)));
|
||||
Mat4::fromRTS(Quaternion::identity(), Vec3::ZERO, Vec3(-2.F, 3.F, 4.F), &expected);
|
||||
EXPECT_TRUE(child->getWorldMatrix().approxEquals(expected));
|
||||
child->setWorldScale(-2.F, 3.F, 4.F);
|
||||
EXPECT_TRUE(child->getWorldMatrix().approxEquals(expected));
|
||||
|
||||
child->setScale(2.F, -3.F, -4.F);
|
||||
EXPECT_TRUE(child->getWorldScale().approxEquals(Vec3(2.F, 3.F, 4.F)));
|
||||
const Mat4 matrixBefore = child->getWorldMatrix();
|
||||
child->setWorldScale(2.F, 3.F, 4.F);
|
||||
EXPECT_TRUE(child->getScale().approxEquals(Vec3(2.F, -3.F, -4.F)));
|
||||
EXPECT_TRUE(child->getWorldMatrix().approxEquals(matrixBefore));
|
||||
}
|
||||
|
||||
TEST(NodeTest, setWorldScaleChangesXWithTinyNegativeY) {
|
||||
cc::IntrusivePtr<cc::Node> parent(new Node());
|
||||
cc::IntrusivePtr<cc::Node> child(new Node());
|
||||
child->setParent(parent);
|
||||
child->setScale(2.F, -1e-7F, 4.F);
|
||||
EXPECT_FLOAT_EQ(child->getWorldMatrix().m[0], 2.F);
|
||||
child->setWorldScale(-2.F, -1e-7F, 4.F);
|
||||
EXPECT_FLOAT_EQ(child->getWorldMatrix().m[0], -2.F);
|
||||
}
|
||||
|
||||
TEST(NodeTest, setWorldScalePreservesTinyXSignChange) {
|
||||
cc::IntrusivePtr<cc::Node> parent(new Node());
|
||||
cc::IntrusivePtr<cc::Node> child(new Node());
|
||||
child->setParent(parent);
|
||||
child->setScale(1e-7F, 1.F, 1.F);
|
||||
child->getWorldScale();
|
||||
child->setWorldScale(-1e-7F, 1.F, 1.F);
|
||||
EXPECT_TRUE(child->getScale().x < 0.F);
|
||||
EXPECT_TRUE(child->getWorldScale().x < 0.F);
|
||||
EXPECT_TRUE(child->getWorldMatrix().m[0] < 0.F);
|
||||
child->setWorldScale(1e-7F, 1.F, 1.F);
|
||||
EXPECT_TRUE(child->getScale().x > 0.F);
|
||||
EXPECT_TRUE(child->getWorldScale().x > 0.F);
|
||||
EXPECT_TRUE(child->getWorldMatrix().m[0] > 0.F);
|
||||
}
|
||||
|
||||
TEST(NodeTest, setWorldScalePreservesLocalRotationWithSignedTargets) {
|
||||
cc::IntrusivePtr<cc::Node> parent(new Node());
|
||||
parent->setScale(2.F, 2.F, 2.F);
|
||||
cc::IntrusivePtr<cc::Node> child(new Node());
|
||||
child->setParent(parent);
|
||||
child->setRotationFromEuler(10.F, 30.F, 25.F);
|
||||
const Quaternion localRotation = child->getRotation();
|
||||
child->setScale(-1.F, -1.F, 1.F);
|
||||
child->getWorldMatrix();
|
||||
child->setWorldScale(-2.F, -3.F, 4.F);
|
||||
EXPECT_TRUE(child->getRotation().approxEquals(localRotation));
|
||||
Mat4 expected;
|
||||
Mat4::fromRTS(localRotation, Vec3::ZERO, Vec3(-2.F, -3.F, 4.F), &expected);
|
||||
EXPECT_TRUE(child->getWorldMatrix().approxEquals(expected));
|
||||
child->setWorldScale(-2.F, -3.F, 4.F);
|
||||
EXPECT_TRUE(child->getRotation().approxEquals(localRotation));
|
||||
EXPECT_TRUE(child->getWorldMatrix().approxEquals(expected));
|
||||
}
|
||||
|
||||
TEST(NodeTest, setWorldScaleSignChangeRefreshesWorldRotation) {
|
||||
cc::IntrusivePtr<cc::Node> parent(new Node());
|
||||
cc::IntrusivePtr<cc::Node> child(new Node());
|
||||
child->setParent(parent);
|
||||
child->setScale(1.F, -1.F, 1.F);
|
||||
const Quaternion before = child->getWorldRotation();
|
||||
EXPECT_FALSE(before.approxEquals(Quaternion::identity()));
|
||||
child->setWorldScale(-2.F, 3.F, 4.F);
|
||||
EXPECT_TRUE(child->getRotation().approxEquals(Quaternion::identity()));
|
||||
EXPECT_TRUE(child->getWorldRotation().approxEquals(Quaternion::identity()));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
@@ -43,6 +43,19 @@ set(USE_DEBUG_RENDERER OFF)
|
||||
include(${cocosdir}/CMakeLists.txt)
|
||||
include(${cocosdir}/tools/simulator/libsimulator/CMakeLists.txt)
|
||||
|
||||
# Native plugin discovery, same mechanism as native builds. Opt-in: pass
|
||||
# -DSIMULATOR_PLUGIN_SCAN_DIRS="<dir>[;<dir>]" with directories to scan for
|
||||
# cc_plugin.json. Unset (default) keeps the stock plugin-less simulator.
|
||||
set(SIMULATOR_PLUGIN_SCAN_DIRS "" CACHE STRING
|
||||
"Directories scanned for cc_plugin.json native plugins")
|
||||
set(COCOS_X_PATH ${cocosdir})
|
||||
if(SIMULATOR_PLUGIN_SCAN_DIRS)
|
||||
set(CC_PROJECT_DIR ${CMAKE_BINARY_DIR}/plugin-scan)
|
||||
set(CC_PLUGIN_PATH ${SIMULATOR_PLUGIN_SCAN_DIRS})
|
||||
file(MAKE_DIRECTORY ${CC_PROJECT_DIR})
|
||||
cc_common_before_target(${APP_NAME})
|
||||
endif()
|
||||
|
||||
|
||||
|
||||
if(MACOSX)
|
||||
@@ -153,6 +166,11 @@ else()
|
||||
endif()
|
||||
|
||||
target_link_libraries(${LIB_NAME} ${ENGINE_NAME} simulator)
|
||||
# Plain signature, matching the call above: mixing keyword/plain forms for one
|
||||
# target is a hard CMake error.
|
||||
if(TARGET plugin_registry)
|
||||
target_link_libraries(${LIB_NAME} plugin_registry)
|
||||
endif()
|
||||
target_include_directories(${LIB_NAME} PRIVATE
|
||||
Classes
|
||||
)
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
#include "Game.h"
|
||||
#include "cocos/application/ApplicationManager.h"
|
||||
#include "cocos/bindings/jswrapper/SeApi.h"
|
||||
#include "cocos/plugins/Plugins.h"
|
||||
#include "cocos/bindings/manual/jsb_classtype.h"
|
||||
#include "cocos/bindings/manual/jsb_global.h"
|
||||
#include "cocos/bindings/manual/jsb_module_register.h"
|
||||
@@ -56,6 +57,8 @@ Game::~Game() {
|
||||
int Game::init() {
|
||||
|
||||
cc::pipeline::GlobalDSManager::setDescriptorSetLayout();
|
||||
// Mirrors BaseGame::init(): register native plugins before any script runs.
|
||||
cc_load_all_plugins();
|
||||
SimulatorApp::getInstance()->init();
|
||||
std::call_once(_windowCreateFlag, [&]() {
|
||||
cc::ISystemWindowInfo info;
|
||||
|
||||
@@ -30,6 +30,11 @@
|
||||
/* protobuf config.h for MSVC. On other platforms, this is generated
|
||||
* automatically by autoheader / autoconf / configure. */
|
||||
|
||||
/* VS 18 (MSVC >= 1950) removed the legacy <hash_map>/<hash_set> headers.
|
||||
* Leave the HAVE_* flags undefined there so stubs/hash.h takes its built-in
|
||||
* MISSING_HASH fallback (std::map / std::set based). */
|
||||
#if !(defined(_MSC_VER) && _MSC_VER >= 1950)
|
||||
|
||||
/* the location of <hash_map> */
|
||||
#define HASH_MAP_H <hash_map>
|
||||
|
||||
@@ -53,6 +58,8 @@
|
||||
/* define if the compiler has hash_set */
|
||||
#define HAVE_HASH_SET 1
|
||||
|
||||
#endif // MSVC >= 1950
|
||||
|
||||
/* define if you want to use zlib. See readme.txt for additional
|
||||
* requirements. */
|
||||
// #define HAVE_ZLIB 1
|
||||
|
||||
@@ -78,9 +78,15 @@ async function bundleRuntimeAdapter () {
|
||||
const platforms = getPlatformsFromPath(platformsPath);
|
||||
console.log(green(`\nBundling runtime platform adapters, including: ${platforms}`));
|
||||
for (const platform of platforms) {
|
||||
const engineEntry = normalizePath(ps.join(engineRoot, `platforms/runtime/platforms/${platform}/engine/index.js`));
|
||||
// Some platform dirs may be incomplete in a checkout (missing engine files);
|
||||
// skip them instead of crashing the adapter build.
|
||||
if (!fs.existsSync(engineEntry)) {
|
||||
console.log(`skip platform: ${platform} (missing ${engineEntry})`);
|
||||
continue;
|
||||
}
|
||||
console.log(`handle platform: ${green(platform)}`);
|
||||
// bundle engine-adapter.js
|
||||
const engineEntry = normalizePath(ps.join(engineRoot, `platforms/runtime/platforms/${platform}/engine/index.js`));
|
||||
const engineOutput = normalizePath(ps.join(engineRoot, `bin/adapter/runtime/${platform}/engine-adapter.js`));
|
||||
await bundle(engineEntry, engineOutput, true);
|
||||
}
|
||||
|
||||
@@ -60,14 +60,19 @@ endfunction()
|
||||
|
||||
|
||||
function(cc_gen_plugin_cmake_hook)
|
||||
set(project_root_dir ${CC_PROJECT_DIR}/../../..)
|
||||
set(load_plugin_cmake ${CC_PROJECT_DIR}/Pre-AutoLoadPlulgins.cmake)
|
||||
message(STATUS "Try generating ${load_plugin_cmake}")
|
||||
file(REMOVE ${load_plugin_cmake})
|
||||
list(APPEND CC_PLUGIN_PATH
|
||||
${project_root_dir}/native
|
||||
${project_root_dir}/extensions
|
||||
)
|
||||
# Scan roots default to the native-build project layout; callers that host
|
||||
# the scan elsewhere (e.g. the Simulator, pointed at an arbitrary
|
||||
# extensions tree) may pre-set CC_PLUGIN_PATH with their own roots.
|
||||
if(NOT DEFINED CC_PLUGIN_PATH)
|
||||
set(project_root_dir ${CC_PROJECT_DIR}/../../..)
|
||||
list(APPEND CC_PLUGIN_PATH
|
||||
${project_root_dir}/native
|
||||
${project_root_dir}/extensions
|
||||
)
|
||||
endif()
|
||||
set(plugin_args_info ${CMAKE_CURRENT_BINARY_DIR}/plugin_dirs.txt)
|
||||
file(WRITE ${plugin_args_info} "# directories for searching native plugins\n")
|
||||
foreach(dir ${CC_PLUGIN_PATH})
|
||||
|
||||
@@ -0,0 +1,179 @@
|
||||
import { Mat4, Quat, Vec3 } from '../../cocos/core/math';
|
||||
import { Node, TransformBit } from '../../cocos/scene-graph';
|
||||
import type { UISkew } from '../../cocos/2d/framework/ui-skew';
|
||||
import { captureWarnIDs } from '../utils/log-capture';
|
||||
|
||||
function expectVec3 (actual: Readonly<Vec3>, expected: Readonly<Vec3>): void {
|
||||
expect(actual.x).toBeCloseTo(expected.x, 8);
|
||||
expect(actual.y).toBeCloseTo(expected.y, 8);
|
||||
expect(actual.z).toBeCloseTo(expected.z, 8);
|
||||
}
|
||||
|
||||
function signedScale (signs: number, x: number, y: number, z: number): Vec3 {
|
||||
return new Vec3(signs & 1 ? -x : x, signs & 2 ? -y : y, signs & 4 ? -z : z);
|
||||
}
|
||||
|
||||
describe('Node.setWorldScale signed scale', () => {
|
||||
test('accepts negative input on every axis and preserves the requested mirror in the matrix', () => {
|
||||
const parent = new Node();
|
||||
const child = new Node();
|
||||
child.parent = parent;
|
||||
const warnings = captureWarnIDs();
|
||||
for (let signs = 0; signs < 8; ++signs) {
|
||||
const target = signedScale(signs, 2, 3, 4);
|
||||
child.setWorldScale(target);
|
||||
expectVec3(child.scale, target);
|
||||
expectVec3(new Vec3(child.worldMatrix.m00, child.worldMatrix.m05, child.worldMatrix.m10), target);
|
||||
const expectedWorld = new Vec3(target.x * target.y * target.z < 0 ? -2 : 2, 3, 4);
|
||||
expectVec3(child.worldScale, expectedWorld);
|
||||
const matrix = child.worldMatrix.clone();
|
||||
child.setWorldScale(target.x, target.y, target.z);
|
||||
expect(child.worldMatrix.equals(matrix)).toBe(true);
|
||||
}
|
||||
expect(warnings.captured).toEqual([]);
|
||||
});
|
||||
|
||||
test('preserves a negative X sign even when its magnitude is below the native equality tolerance', () => {
|
||||
const parent = new Node();
|
||||
const child = new Node();
|
||||
child.parent = parent;
|
||||
child.setScale(1e-7, 1, 1);
|
||||
child.getWorldScale();
|
||||
child.setWorldScale(-1e-7, 1, 1);
|
||||
expect(child.scale.x).toBeLessThan(0);
|
||||
expect(child.worldMatrix.m00).toBeLessThan(0);
|
||||
});
|
||||
|
||||
test('changes the requested mirror axis even when canonical world-scale readback is identical', () => {
|
||||
const parent = new Node();
|
||||
const child = new Node();
|
||||
child.parent = parent;
|
||||
child.setWorldScale(2, -3, 4);
|
||||
expectVec3(child.worldScale, new Vec3(-2, 3, 4));
|
||||
child.setWorldScale(-2, 3, 4);
|
||||
expectVec3(child.worldScale, new Vec3(-2, 3, 4));
|
||||
expectVec3(new Vec3(child.worldMatrix.m00, child.worldMatrix.m05, child.worldMatrix.m10), new Vec3(-2, 3, 4));
|
||||
child.setScale(2, -3, -4);
|
||||
child.getWorldScale();
|
||||
child.setWorldScale(2, 3, 4);
|
||||
expectVec3(child.scale, new Vec3(2, 3, 4));
|
||||
});
|
||||
|
||||
test('restores requested signs independently of old local signs with orientation-preserving parents', () => {
|
||||
for (const parentSigns of [0, 3, 5, 6]) {
|
||||
for (let localSigns = 0; localSigns < 8; ++localSigns) {
|
||||
for (let targetSigns = 0; targetSigns < 8; ++targetSigns) {
|
||||
const parent = new Node();
|
||||
parent.setScale(signedScale(parentSigns, 2, 3, 4));
|
||||
parent.setRotationFromEuler(10, 25, 40);
|
||||
const child = new Node();
|
||||
child.parent = parent;
|
||||
child.setRotationFromEuler(20, 35, 15);
|
||||
child.setScale(signedScale(localSigns, 1, 2, 3));
|
||||
const rotation = child.rotation.clone();
|
||||
const target = signedScale(targetSigns, 2, 3, 4);
|
||||
child.setWorldScale(target);
|
||||
const expectedWorld = new Vec3(target.x * target.y * target.z < 0 ? -2 : 2, 3, 4);
|
||||
expectVec3(child.worldScale, expectedWorld);
|
||||
expect(child.rotation.equals(rotation)).toBe(true);
|
||||
expect(child.scale.y < 0).toBe(target.y < 0);
|
||||
expect(child.scale.z < 0).toBe(target.z < 0);
|
||||
expect(child.scale.x < 0).toBe(target.x < 0);
|
||||
const matrix = child.worldMatrix.clone();
|
||||
child.setWorldScale(target);
|
||||
expect(child.worldMatrix.equals(matrix)).toBe(true);
|
||||
expectVec3(child.worldScale, expectedWorld);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('preserves inherited reflections for positive scale and for an already negative world X', () => {
|
||||
const cases = [
|
||||
{ parentScale: new Vec3(-1, 1, 1), expected: new Vec3(-2, 3, 4) },
|
||||
{ parentScale: new Vec3(1, -1, 1), expected: new Vec3(2, -3, 4) },
|
||||
{ parentScale: new Vec3(1, 1, -1), expected: new Vec3(2, 3, -4) },
|
||||
];
|
||||
for (const { parentScale, expected } of cases) {
|
||||
const parent = new Node();
|
||||
parent.setScale(parentScale);
|
||||
const child = new Node();
|
||||
child.parent = parent;
|
||||
child.setWorldScale(2, 3, 4);
|
||||
expectVec3(new Vec3(child.worldMatrix.m00, child.worldMatrix.m05, child.worldMatrix.m10), expected);
|
||||
expectVec3(child.worldScale, new Vec3(-2, 3, 4));
|
||||
const matrix = child.worldMatrix.clone();
|
||||
child.setWorldScale(-2, 3, 4);
|
||||
expect(child.worldMatrix.equals(matrix)).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
test('applies negative Y and Z independently while inheriting the parent X reflection', () => {
|
||||
const parent = new Node();
|
||||
parent.setScale(-1, 1, 1);
|
||||
const child = new Node();
|
||||
child.parent = parent;
|
||||
child.setWorldScale(2, -3, -4);
|
||||
expectVec3(child.scale, new Vec3(2, -3, -4));
|
||||
expectVec3(new Vec3(child.worldMatrix.m00, child.worldMatrix.m05, child.worldMatrix.m10), new Vec3(-2, -3, -4));
|
||||
const matrix = child.worldMatrix.clone();
|
||||
child.setWorldScale(2, -3, -4);
|
||||
expect(child.worldMatrix.equals(matrix)).toBe(true);
|
||||
});
|
||||
|
||||
test('recomputes world rotation caches when the local mirror signs change', () => {
|
||||
const parent = new Node();
|
||||
const child = new Node();
|
||||
child.parent = parent;
|
||||
const grandchild = new Node();
|
||||
grandchild.parent = child;
|
||||
grandchild.setRotationFromEuler(20, 35, 15);
|
||||
child.getWorldRotation();
|
||||
grandchild.getWorldRotation();
|
||||
child.setWorldScale(2, -3, 4);
|
||||
const expected = new Quat();
|
||||
Mat4.toSRT(child.worldMatrix, expected, null, null);
|
||||
expect(child.worldRotation.equals(expected)).toBe(true);
|
||||
Mat4.toSRT(grandchild.worldMatrix, expected, null, null);
|
||||
expect(grandchild.worldRotation.equals(expected)).toBe(true);
|
||||
});
|
||||
|
||||
test('keeps the existing zero-scale recovery path while restoring negative signs', () => {
|
||||
const parent = new Node();
|
||||
parent.setScale(2, 2, 2);
|
||||
const child = new Node();
|
||||
child.parent = parent;
|
||||
child.setRotationFromEuler(10, 20, 30);
|
||||
const rotation = child.rotation.clone();
|
||||
child.setWorldScale(0, 0, 0);
|
||||
child.getWorldMatrix();
|
||||
child.setWorldScale(-2, -3, 4);
|
||||
expectVec3(child.scale, new Vec3(-1, -1.5, 2));
|
||||
expectVec3(child.worldScale, new Vec3(2, 3, 4));
|
||||
expect(child.rotation.equals(rotation)).toBe(true);
|
||||
const matrix = child.worldMatrix.clone();
|
||||
child.setWorldScale(-2, -3, 4);
|
||||
expect(child.worldMatrix.equals(matrix)).toBe(true);
|
||||
});
|
||||
|
||||
test('uses parent reflection signs without counting the UISkew component reflection', () => {
|
||||
const root = new Node();
|
||||
const parent = new Node();
|
||||
parent.parent = root;
|
||||
parent.setScale(2, 3, 4);
|
||||
const child = new Node();
|
||||
child.parent = parent;
|
||||
// The UISkew lifecycle is stubbed; matrix composition and decomposition run normally.
|
||||
parent._uiProps._uiSkewComp = { x: 180, y: 0, rotational: true, isSkewEnabled: () => true } as UISkew;
|
||||
Node._incSkewCompCount();
|
||||
try {
|
||||
parent.invalidateChildren(TransformBit.SKEW);
|
||||
child.setWorldScale(-2, 3, 4);
|
||||
expectVec3(child.scale, new Vec3(-1, 1, 1));
|
||||
expectVec3(child.worldScale, new Vec3(-2, 3, 4));
|
||||
} finally {
|
||||
parent._uiProps._uiSkewComp = null;
|
||||
Node._decSkewCompCount();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"constantOverrides": {
|
||||
"USE_UI_SKEW": true
|
||||
}
|
||||
}
|
||||
@@ -666,6 +666,50 @@ describe(`Node`, () => {
|
||||
))).toBeTruthy();
|
||||
});
|
||||
|
||||
test.each([-179, -120, -91, -90, 90, 91, 120, 179])('2D angle after quaternion writeback: %s', (angle) => {
|
||||
const node = new Node();
|
||||
const rotation = Quat.fromAngleZ(new Quat(), angle);
|
||||
node.setRotation(rotation);
|
||||
expect(node.getAngle2D()).toBeCloseTo(angle);
|
||||
// Reading the 3D Euler cache first must not change the 2D angle.
|
||||
const euler = node.eulerAngles.clone();
|
||||
expect(node.getAngle2D()).toBeCloseTo(angle);
|
||||
expect(Vec3.equals(node.eulerAngles, euler)).toBe(true);
|
||||
node.setRotation(new Quat(-rotation.x, -rotation.y, -rotation.z, -rotation.w));
|
||||
expect(node.getAngle2D()).toBeCloseTo(angle);
|
||||
});
|
||||
|
||||
test('angle keeps legacy Euler results independently of getAngle2D', () => {
|
||||
const node = new Node();
|
||||
node.setRotation(Quat.fromAngleZ(new Quat(), 120));
|
||||
expect(node.getAngle2D()).toBeCloseTo(120);
|
||||
expect(node.angle).toBeCloseTo(60);
|
||||
expect(node.getAngle2D()).toBeCloseTo(120);
|
||||
expect(node.angle).toBeCloseTo(60);
|
||||
});
|
||||
|
||||
test('getAngle2D stays local under a rotated parent', () => {
|
||||
const parent = new Node();
|
||||
const node = new Node();
|
||||
parent.addChild(node);
|
||||
parent.angle = 30;
|
||||
node.setWorldRotationFromEuler(0, 0, 150);
|
||||
expect(node.getAngle2D()).toBeCloseTo(120);
|
||||
});
|
||||
|
||||
test('angle preserves explicit full turns and 3D Euler behavior', () => {
|
||||
const node = new Node();
|
||||
node.angle = 720;
|
||||
expect(node.angle).toBe(720);
|
||||
expect(node.getAngle2D()).toBeCloseTo(0);
|
||||
const rotation = Quat.fromEuler(new Quat(), 30, 40, 120);
|
||||
node.setRotation(rotation);
|
||||
const euler = Quat.toEuler(new Vec3(), rotation);
|
||||
expect(node.angle).toBeCloseTo(euler.z);
|
||||
expect(node.getAngle2D()).toBeCloseTo(euler.z);
|
||||
expect(node.eulerAngles).toEqual(euler);
|
||||
});
|
||||
|
||||
test ('angle', ()=> {
|
||||
let node = new Node();
|
||||
|
||||
|
||||
@@ -11,6 +11,37 @@ export default function (parent: Node, _steps = 0) {
|
||||
if (physics2d.selector.id === 'builtin')
|
||||
return;
|
||||
|
||||
// Regression: physics writeback must not fold getAngle2D() at +/-90 degrees.
|
||||
for (const type of [physics2d.ERigidBody2DType.Dynamic, physics2d.ERigidBody2DType.Kinematic]) {
|
||||
for (const enabled of [true, false]) {
|
||||
const node = new Node('AngleRegression');
|
||||
parent.addChild(node);
|
||||
const body = node.addComponent(physics2d.RigidBody2D);
|
||||
body.type = type;
|
||||
body.gravityScale = 0;
|
||||
body.enabled = enabled;
|
||||
const dt = physics2d.PhysicsSystem2D.instance.fixedTimeStep;
|
||||
for (const angle of [-179, -120, -91, 91, 120, 179]) {
|
||||
node.angle = angle;
|
||||
director.tick(dt);
|
||||
expect(node.getAngle2D()).toBeCloseTo(angle, 3);
|
||||
expect(Math.abs(Quat.dot(node.worldRotation, Quat.fromAngleZ(new Quat(), angle)))).toBeCloseTo(1);
|
||||
}
|
||||
// Exercise read/modify/write across both 90 degrees and full turns.
|
||||
for (const delta of [10, -10]) {
|
||||
node.angle = 0;
|
||||
for (let step = 1; step <= 40; ++step) {
|
||||
node.angle = node.getAngle2D() + delta;
|
||||
director.tick(dt);
|
||||
const expected = Quat.fromAngleZ(new Quat(), step * delta);
|
||||
expect(Math.abs(Quat.dot(node.worldRotation, expected))).toBeCloseTo(1);
|
||||
}
|
||||
}
|
||||
node.destroy();
|
||||
director.tick(dt);
|
||||
}
|
||||
}
|
||||
|
||||
// basic api
|
||||
{
|
||||
const nodeRigidBody = new Node('RigidBody');
|
||||
@@ -191,4 +222,4 @@ export default function (parent: Node, _steps = 0) {
|
||||
director.tick(0.2);//make sure is destroyed
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,466 @@
|
||||
import { cclegacy, Vec4 } from '../../cocos/core';
|
||||
import {
|
||||
Buffer,
|
||||
BufferInfo,
|
||||
BufferUsageBit,
|
||||
BufferViewInfo,
|
||||
Color,
|
||||
DescriptorType,
|
||||
Format,
|
||||
LoadOp,
|
||||
MemoryUsageBit,
|
||||
Rect,
|
||||
ShaderStageFlagBit,
|
||||
StoreOp,
|
||||
Type,
|
||||
Uniform,
|
||||
UniformBlock,
|
||||
} from '../../cocos/gfx';
|
||||
import { Executor } from '../../cocos/rendering/custom/executor';
|
||||
import {
|
||||
DescriptorBlockData,
|
||||
DescriptorData,
|
||||
DescriptorSetData,
|
||||
DescriptorSetLayoutData,
|
||||
DescriptorTypeOrder,
|
||||
LayoutGraphData,
|
||||
LayoutGraphDataValue,
|
||||
PipelineLayoutData,
|
||||
RenderPhaseData,
|
||||
RenderStageData,
|
||||
} from '../../cocos/rendering/custom/layout-graph';
|
||||
import { QueueHint, ResourceResidency, UpdateFrequency } from '../../cocos/rendering/custom/types';
|
||||
import { WebPipeline } from '../../cocos/rendering/custom/web-pipeline';
|
||||
|
||||
interface TrackedUBOStats {
|
||||
liveBytes: number;
|
||||
bufferWords: Map<Buffer, Uint32Array>;
|
||||
restore: () => void;
|
||||
}
|
||||
|
||||
function trackUniformBuffers (): TrackedUBOStats {
|
||||
const device = cclegacy.director.root.device;
|
||||
const origCreateBuffer = device.createBuffer.bind(device);
|
||||
const bufferSizes = new Map<Buffer, number>();
|
||||
const bufferWords = new Map<Buffer, Uint32Array>();
|
||||
const stats: TrackedUBOStats = {
|
||||
liveBytes: 0,
|
||||
bufferWords,
|
||||
restore: (): void => {},
|
||||
};
|
||||
|
||||
const spy = jest.spyOn(device, 'createBuffer').mockImplementation((info: BufferInfo | BufferViewInfo): Buffer => {
|
||||
const buf = origCreateBuffer(info as any);
|
||||
if (!('buffer' in info) && (info.usage & BufferUsageBit.UNIFORM)) {
|
||||
const byteSize = info.size;
|
||||
bufferSizes.set(buf, byteSize);
|
||||
bufferWords.set(buf, new Uint32Array(byteSize / 4));
|
||||
stats.liveBytes += byteSize;
|
||||
|
||||
const origUpdate = buf.update.bind(buf);
|
||||
jest.spyOn(buf, 'update').mockImplementation((data: BufferSource, size?: number): void => {
|
||||
const view = ArrayBuffer.isView(data)
|
||||
? new Uint8Array(data.buffer, data.byteOffset, size ?? data.byteLength)
|
||||
: new Uint8Array(data, 0, size ?? data.byteLength);
|
||||
const dst = new Uint8Array(bufferWords.get(buf)!.buffer);
|
||||
dst.set(view.subarray(0, dst.byteLength));
|
||||
origUpdate(data, size);
|
||||
});
|
||||
|
||||
const origDestroy = buf.destroy.bind(buf);
|
||||
jest.spyOn(buf, 'destroy').mockImplementation((): void => {
|
||||
const trackedSize = bufferSizes.get(buf);
|
||||
if (trackedSize !== undefined) {
|
||||
stats.liveBytes -= trackedSize;
|
||||
bufferSizes.delete(buf);
|
||||
bufferWords.delete(buf);
|
||||
}
|
||||
origDestroy();
|
||||
});
|
||||
}
|
||||
return buf;
|
||||
});
|
||||
|
||||
stats.restore = (): void => {
|
||||
spy.mockRestore();
|
||||
};
|
||||
return stats;
|
||||
}
|
||||
|
||||
function addStageWithUBOs (
|
||||
lg: LayoutGraphData,
|
||||
stageName: string,
|
||||
blocks: Array<{ blockId: number; binding: number; blockName: string; members: Uniform[] }>,
|
||||
): number {
|
||||
const stageLayout = new PipelineLayoutData();
|
||||
const layoutData = new DescriptorSetLayoutData();
|
||||
const descBlock = new DescriptorBlockData(
|
||||
DescriptorTypeOrder.UNIFORM_BUFFER,
|
||||
ShaderStageFlagBit.ALL,
|
||||
blocks.length,
|
||||
);
|
||||
descBlock.offset = 0;
|
||||
for (const b of blocks) {
|
||||
descBlock.descriptors.push(new DescriptorData(b.blockId, Type.UNKNOWN, 1));
|
||||
layoutData.uniformBlocks.set(b.blockId, new UniformBlock(UpdateFrequency.PER_PASS, b.binding, b.blockName, b.members, 1));
|
||||
layoutData.bindingMap.set(b.blockId, b.binding);
|
||||
}
|
||||
layoutData.descriptorBlocks.push(descBlock);
|
||||
|
||||
const setData = new DescriptorSetData(layoutData);
|
||||
stageLayout.getSets().set(UpdateFrequency.PER_PASS, setData);
|
||||
|
||||
const stageId = lg.addVertex<LayoutGraphDataValue.RenderStage>(
|
||||
LayoutGraphDataValue.RenderStage,
|
||||
new RenderStageData(),
|
||||
stageName,
|
||||
UpdateFrequency.PER_PASS,
|
||||
stageLayout,
|
||||
);
|
||||
lg.addVertex<LayoutGraphDataValue.RenderPhase>(
|
||||
LayoutGraphDataValue.RenderPhase,
|
||||
new RenderPhaseData(),
|
||||
'default',
|
||||
UpdateFrequency.PER_PHASE,
|
||||
new PipelineLayoutData(),
|
||||
stageId,
|
||||
);
|
||||
return stageId;
|
||||
}
|
||||
|
||||
function createUBOTestPipeline (twoVec4 = false, includeGlobalInCustomStages = true, suffix = ''): {
|
||||
ppl: WebPipeline;
|
||||
stageA: string;
|
||||
stageB: string;
|
||||
cleanup: () => void;
|
||||
getBoundBuffer: (layoutName: string, binding?: number) => Buffer;
|
||||
} {
|
||||
const lg = new LayoutGraphData();
|
||||
const constantNames = ['cc_time', 'cc_screenSize', 'cc_nativeSize', 'cc_debug_view_mode', 'bugParam', 'bugExtra'];
|
||||
constantNames.forEach((name, idx) => {
|
||||
lg.constantIndex.set(name, idx);
|
||||
});
|
||||
const blockNames = ['CCGlobal', 'BugUBO'];
|
||||
blockNames.forEach((name, idx) => {
|
||||
lg.attributeIndex.set(name, idx);
|
||||
});
|
||||
|
||||
const globalMembers = [
|
||||
new Uniform('cc_time', Type.FLOAT4, 1),
|
||||
new Uniform('cc_screenSize', Type.FLOAT4, 1),
|
||||
new Uniform('cc_nativeSize', Type.FLOAT4, 1),
|
||||
new Uniform('cc_debug_view_mode', Type.FLOAT4, 1),
|
||||
];
|
||||
const bugMembers = twoVec4
|
||||
? [new Uniform('bugParam', Type.FLOAT4, 1), new Uniform('bugExtra', Type.FLOAT4, 1)]
|
||||
: [new Uniform('bugParam', Type.FLOAT4, 1)];
|
||||
|
||||
const bugBinding = includeGlobalInCustomStages ? 1 : 0;
|
||||
const customBlocks = includeGlobalInCustomStages
|
||||
? [
|
||||
{ blockId: 0, binding: 0, blockName: 'CCGlobal', members: globalMembers },
|
||||
{ blockId: 1, binding: bugBinding, blockName: 'BugUBO', members: bugMembers },
|
||||
]
|
||||
: [
|
||||
{ blockId: 1, binding: bugBinding, blockName: 'BugUBO', members: bugMembers },
|
||||
];
|
||||
|
||||
const stageA = `ubo-bug-a${suffix}`;
|
||||
const stageB = `ubo-bug-b${suffix}`;
|
||||
|
||||
const defaultStage = addStageWithUBOs(lg, 'default', [
|
||||
{ blockId: 0, binding: 0, blockName: 'CCGlobal', members: globalMembers },
|
||||
]);
|
||||
addStageWithUBOs(lg, stageA, customBlocks);
|
||||
addStageWithUBOs(lg, stageB, customBlocks);
|
||||
|
||||
const ppl = new WebPipeline(lg);
|
||||
jest.spyOn(ppl as any, '_compileMaterial').mockImplementation(() => {});
|
||||
ppl.activate(null!);
|
||||
// Ensure EmptyDescriptorSetLayout has descriptorType / bindingIndices populated like WebGL2DescriptorSetLayout
|
||||
for (const v of lg.v()) {
|
||||
const set = lg.getLayout(v).getSet(UpdateFrequency.PER_PASS);
|
||||
if (set?.descriptorSetLayout) {
|
||||
const dsl = set.descriptorSetLayout;
|
||||
for (let i = 0; i < dsl.bindings.length; ++i) {
|
||||
dsl.bindings[i].descriptorType = DescriptorType.UNIFORM_BUFFER;
|
||||
const b = dsl.bindings[i].binding;
|
||||
dsl.bindingIndices[b] = i;
|
||||
dsl.descriptorIndices[b] = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
(ppl as any)._width = 64;
|
||||
(ppl as any)._height = 64;
|
||||
|
||||
const prevPipeline = cclegacy.director.root.pipeline;
|
||||
const prevRendering = cclegacy.rendering;
|
||||
cclegacy.director.root._pipeline = ppl;
|
||||
cclegacy.rendering = {
|
||||
getPassID: (name?: string): number => lg.locateChild(lg.N, name || 'default'),
|
||||
getPhaseID: (): number => defaultStage + 1,
|
||||
};
|
||||
|
||||
ppl.addRenderTarget('Temp0', Format.RGBA8, 64, 64, ResourceResidency.PERSISTENT);
|
||||
ppl.addRenderTarget('Color0', Format.RGBA8, 64, 64, ResourceResidency.PERSISTENT);
|
||||
|
||||
return {
|
||||
ppl,
|
||||
stageA,
|
||||
stageB,
|
||||
getBoundBuffer: (layoutName: string, binding = bugBinding): Buffer => {
|
||||
const stageId = lg.locateChild(lg.N, layoutName);
|
||||
const set = lg.getLayout(stageId).getSet(UpdateFrequency.PER_PASS)!;
|
||||
return set.descriptorSet!.getBuffer(binding);
|
||||
},
|
||||
cleanup: (): void => {
|
||||
cclegacy.director.root._pipeline = prevPipeline;
|
||||
cclegacy.rendering = prevRendering;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('Custom pipeline per-pass UBO upload', () => {
|
||||
test('uploads identical uniform values to both passes across 16 alternating frames after default layout warmup', () => {
|
||||
const tracker = trackUniformBuffers();
|
||||
const { ppl, stageA, stageB, cleanup, getBoundBuffer } = createUBOTestPipeline(false, true, '-1');
|
||||
const dummyCam = { viewport: new Rect(0, 0, 1, 1) } as any;
|
||||
const executor = new Executor(ppl, ppl.device, ppl.resourceGraph, ppl.layoutGraph, 64, 64);
|
||||
|
||||
try {
|
||||
// Warm-up default layout frame
|
||||
ppl.beginSetup();
|
||||
const warmPass = ppl.addRenderPass(64, 64, 'default');
|
||||
warmPass.addRenderTarget('Color0', LoadOp.CLEAR, StoreOp.STORE, new Color(0, 0, 0, 1));
|
||||
warmPass.addQueue(QueueHint.NONE).addDraw3D(dummyCam, []);
|
||||
ppl.endSetup();
|
||||
ppl.compile();
|
||||
executor.execute(ppl.renderGraph!);
|
||||
ppl.endFrame();
|
||||
|
||||
const val = new Vec4();
|
||||
for (let frame = 0; frame < 16; ++frame) {
|
||||
const input = frame & 1;
|
||||
val.set(input, 0, 0, 0);
|
||||
|
||||
ppl.beginSetup();
|
||||
const passA = ppl.addRenderPass(64, 64, stageA);
|
||||
passA.addRenderTarget('Temp0', LoadOp.DISCARD, StoreOp.STORE);
|
||||
passA.setVec4('bugParam', val);
|
||||
passA.addQueue(QueueHint.NONE).addDraw3D(dummyCam, []);
|
||||
|
||||
const passB = ppl.addRenderPass(64, 64, stageB);
|
||||
passB.addRenderTarget('Color0', LoadOp.DISCARD, StoreOp.STORE);
|
||||
passB.setVec4('bugParam', val);
|
||||
passB.addQueue(QueueHint.NONE).addDraw3D(dummyCam, []);
|
||||
ppl.endSetup();
|
||||
ppl.compile();
|
||||
|
||||
executor.execute(ppl.renderGraph!);
|
||||
|
||||
const wordsA = tracker.bufferWords.get(getBoundBuffer(stageA))!;
|
||||
const wordsB = tracker.bufferWords.get(getBoundBuffer(stageB))!;
|
||||
const expectedWord = input === 1 ? 0x3f800000 : 0x00000000;
|
||||
expect(wordsA[0]).toBe(expectedWord);
|
||||
expect(wordsB[0]).toBe(expectedWord);
|
||||
ppl.endFrame();
|
||||
}
|
||||
} finally {
|
||||
executor.release();
|
||||
ppl.destroy();
|
||||
cleanup();
|
||||
tracker.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('preserves IEEE-754 negative zero sign bit (0x80000000 vs 0x00000000) across alternating frames', () => {
|
||||
const tracker = trackUniformBuffers();
|
||||
const { ppl, stageA, stageB, cleanup, getBoundBuffer } = createUBOTestPipeline(false, true, '-2');
|
||||
const dummyCam = { viewport: new Rect(0, 0, 1, 1) } as any;
|
||||
const executor = new Executor(ppl, ppl.device, ppl.resourceGraph, ppl.layoutGraph, 64, 64);
|
||||
|
||||
try {
|
||||
const valA = new Vec4(1, 0, 0, 0);
|
||||
const valB = new Vec4(0, 0, 0, 0);
|
||||
const observedWordsB: number[] = [];
|
||||
|
||||
for (let frame = 0; frame < 8; ++frame) {
|
||||
valB.x = (frame & 1) === 0 ? +0 : -0;
|
||||
|
||||
ppl.beginSetup();
|
||||
const passA = ppl.addRenderPass(64, 64, stageA);
|
||||
passA.addRenderTarget('Temp0', LoadOp.DISCARD, StoreOp.STORE);
|
||||
passA.setVec4('bugParam', valA);
|
||||
passA.addQueue(QueueHint.NONE).addDraw3D(dummyCam, []);
|
||||
|
||||
const passB = ppl.addRenderPass(64, 64, stageB);
|
||||
passB.addRenderTarget('Color0', LoadOp.DISCARD, StoreOp.STORE);
|
||||
passB.setVec4('bugParam', valB);
|
||||
passB.addQueue(QueueHint.NONE).addDraw3D(dummyCam, []);
|
||||
ppl.endSetup();
|
||||
ppl.compile();
|
||||
|
||||
executor.execute(ppl.renderGraph!);
|
||||
const wordsB = tracker.bufferWords.get(getBoundBuffer(stageB))!;
|
||||
observedWordsB.push(wordsB[0]);
|
||||
ppl.endFrame();
|
||||
}
|
||||
|
||||
expect(observedWordsB).toEqual([
|
||||
0x00000000,
|
||||
0x80000000,
|
||||
0x00000000,
|
||||
0x80000000,
|
||||
0x00000000,
|
||||
0x80000000,
|
||||
0x00000000,
|
||||
0x80000000,
|
||||
]);
|
||||
} finally {
|
||||
executor.release();
|
||||
ppl.destroy();
|
||||
cleanup();
|
||||
tracker.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('allows queue.setBuffer to override parent pass UBO binding across frames', () => {
|
||||
const tracker = trackUniformBuffers();
|
||||
const { ppl, stageA, cleanup, getBoundBuffer } = createUBOTestPipeline(false, true, '-3');
|
||||
const dummyCam = { viewport: new Rect(0, 0, 1, 1) } as any;
|
||||
const executor = new Executor(ppl, ppl.device, ppl.resourceGraph, ppl.layoutGraph, 64, 64);
|
||||
|
||||
const extBuffer = ppl.device.createBuffer(new BufferInfo(
|
||||
BufferUsageBit.UNIFORM | BufferUsageBit.TRANSFER_DST,
|
||||
MemoryUsageBit.HOST | MemoryUsageBit.DEVICE,
|
||||
16,
|
||||
16,
|
||||
));
|
||||
extBuffer.update(new Float32Array([1.0, 0.5, 0.0, 0.0]));
|
||||
|
||||
try {
|
||||
for (let frame = 0; frame < 4; ++frame) {
|
||||
ppl.beginSetup();
|
||||
const pass = ppl.addRenderPass(64, 64, stageA);
|
||||
pass.addRenderTarget('Color0', LoadOp.CLEAR, StoreOp.STORE);
|
||||
if (frame >= 1) {
|
||||
pass.setVec4('bugParam', new Vec4(0, 0, 0, 0));
|
||||
}
|
||||
const queue = pass.addQueue(QueueHint.NONE);
|
||||
queue.setBuffer('BugUBO', extBuffer);
|
||||
queue.addDraw3D(dummyCam, []);
|
||||
ppl.endSetup();
|
||||
ppl.compile();
|
||||
|
||||
executor.execute(ppl.renderGraph!);
|
||||
const bound = getBoundBuffer(stageA);
|
||||
expect(bound).toBe(extBuffer);
|
||||
const words = tracker.bufferWords.get(bound)!;
|
||||
expect(words[0]).toBe(0x3f800000); // 1.0
|
||||
expect(words[1]).toBe(0x3f000000); // 0.5
|
||||
ppl.endFrame();
|
||||
}
|
||||
} finally {
|
||||
executor.release();
|
||||
ppl.destroy();
|
||||
expect(tracker.bufferWords.has(extBuffer)).toBe(true);
|
||||
extBuffer.destroy();
|
||||
cleanup();
|
||||
tracker.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('isolates partial UBO member updates across layouts while preserving pass-to-queue inheritance', () => {
|
||||
const tracker = trackUniformBuffers();
|
||||
const { ppl, stageA, stageB, cleanup, getBoundBuffer } = createUBOTestPipeline(true, true, '-5');
|
||||
const dummyCam = { viewport: new Rect(0, 0, 1, 1) } as any;
|
||||
const executor = new Executor(ppl, ppl.device, ppl.resourceGraph, ppl.layoutGraph, 64, 64);
|
||||
|
||||
try {
|
||||
for (let frame = 0; frame < 4; ++frame) {
|
||||
ppl.beginSetup();
|
||||
// Pass A (stageA): only sets bugParam (fieldX = 0); bugExtra (fieldY) must stay 0 across all frames
|
||||
const passA = ppl.addRenderPass(64, 64, stageA);
|
||||
passA.addRenderTarget('Temp0', LoadOp.DISCARD, StoreOp.STORE);
|
||||
passA.setVec4('bugParam', new Vec4(0, 0, 0, 0));
|
||||
passA.addQueue(QueueHint.NONE).addDraw3D(dummyCam, []);
|
||||
|
||||
// Pass B (stageB): pass sets bugParam = 0.5, queue sets bugExtra = 1.0 (inherits bugParam = 0.5)
|
||||
const passB = ppl.addRenderPass(64, 64, stageB);
|
||||
passB.addRenderTarget('Color0', LoadOp.DISCARD, StoreOp.STORE);
|
||||
passB.setVec4('bugParam', new Vec4(0.5, 0, 0, 0));
|
||||
const queueB = passB.addQueue(QueueHint.NONE);
|
||||
queueB.setVec4('bugExtra', new Vec4(1.0, 0, 0, 0));
|
||||
queueB.addDraw3D(dummyCam, []);
|
||||
ppl.endSetup();
|
||||
ppl.compile();
|
||||
|
||||
executor.execute(ppl.renderGraph!);
|
||||
|
||||
const wordsA = tracker.bufferWords.get(getBoundBuffer(stageA))!;
|
||||
const wordsB = tracker.bufferWords.get(getBoundBuffer(stageB))!;
|
||||
// Pass A: bugParam.x = 0, bugExtra.x = 0 (not polluted by Pass B's bugExtra = 1.0)
|
||||
expect(wordsA[0]).toBe(0x00000000);
|
||||
expect(wordsA[4]).toBe(0x00000000);
|
||||
// Pass B: queue inherited bugParam.x = 0.5 (0x3f000000) and applied bugExtra.x = 1.0 (0x3f800000)
|
||||
expect(wordsB[0]).toBe(0x3f000000);
|
||||
expect(wordsB[4]).toBe(0x3f800000);
|
||||
ppl.endFrame();
|
||||
}
|
||||
} finally {
|
||||
executor.release();
|
||||
ppl.destroy();
|
||||
cleanup();
|
||||
tracker.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('reuses bound GPU buffer across 128 queues writing identical 32-byte UBO and frees buffers on pipeline.destroy()', () => {
|
||||
const tracker = trackUniformBuffers();
|
||||
const { ppl, stageA, cleanup } = createUBOTestPipeline(true, false, '-4');
|
||||
const dummyCam = { viewport: new Rect(0, 0, 1, 1) } as any;
|
||||
const executor = new Executor(ppl, ppl.device, ppl.resourceGraph, ppl.layoutGraph, 64, 64);
|
||||
const baselineBytes = tracker.liveBytes;
|
||||
|
||||
const runFrameWithQueues = (queueCount: number, distinctPerQueue = false): void => {
|
||||
ppl.beginSetup();
|
||||
const pass = ppl.addRenderPass(64, 64, stageA);
|
||||
pass.addRenderTarget('Color0', LoadOp.CLEAR, StoreOp.STORE);
|
||||
for (let i = 0; i < queueCount; ++i) {
|
||||
const q = pass.addQueue(QueueHint.NONE);
|
||||
q.setVec4('bugParam', new Vec4(distinctPerQueue ? i : 1, 2, 3, 4));
|
||||
q.setVec4('bugExtra', new Vec4(5, 6, 7, 8));
|
||||
q.addDraw3D(dummyCam, []);
|
||||
}
|
||||
ppl.endSetup();
|
||||
ppl.compile();
|
||||
executor.execute(ppl.renderGraph!);
|
||||
ppl.endFrame();
|
||||
};
|
||||
|
||||
try {
|
||||
// 1 queue writing 32-byte UBO -> 1 DescBuffManager = 2 * 32 = 64 bytes
|
||||
runFrameWithQueues(1, false);
|
||||
expect(tracker.liveBytes - baselineBytes).toBe(64);
|
||||
|
||||
// 128 queues writing the SAME 32-byte UBO -> 0 extra bytes (NOT +8128 bytes)
|
||||
runFrameWithQueues(128, false);
|
||||
expect(tracker.liveBytes - baselineBytes).toBe(64);
|
||||
|
||||
// Recover to 1 queue -> still 64 bytes
|
||||
runFrameWithQueues(1, false);
|
||||
expect(tracker.liveBytes - baselineBytes).toBe(64);
|
||||
|
||||
// Even if 128 temporary queues write DISTINCT 32-byte UBOs, pipeline.destroy() frees all buffers
|
||||
runFrameWithQueues(128, true);
|
||||
expect(tracker.liveBytes - baselineBytes).toBe(64 + 8128);
|
||||
|
||||
// Destroying pipeline frees all UBO GPU buffers
|
||||
ppl.destroy();
|
||||
expect(tracker.liveBytes - baselineBytes).toBe(0);
|
||||
} finally {
|
||||
cleanup();
|
||||
tracker.restore();
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { buildFontDesc, CssFontFamily, getCanvasFontFamily, quoteFontFamily } from '../../cocos/2d/utils/font-family';
|
||||
import { buildFontDesc, CssFontFamily, getCanvasFontFamily, quoteFontFamily, serializeFontFamily } from '../../cocos/2d/utils/font-family';
|
||||
import { TTFFont } from '../../cocos/2d/assets/ttf-font';
|
||||
import type { Label } from '../../cocos/2d/components/label';
|
||||
import { TTFUtils } from '../../cocos/2d/assembler/label/ttfUtils';
|
||||
@@ -57,13 +57,13 @@ describe('font family serialization', () => {
|
||||
const descriptions = rawAliases.map((rawAlias) => {
|
||||
const source = { useSystemFont: false, fontFamily: 'Arial', font: { _nativeAsset: rawAlias } };
|
||||
// A migrated manual caller uses the original registered alias, not its old ctx.font text.
|
||||
const migrated = buildFontDesc(40, quoteFontFamily(rawAlias));
|
||||
const migrated = buildFontDesc(40, serializeFontFamily(rawAlias));
|
||||
expect(migrated).toBe(buildFontDesc(40, getCanvasFontFamily(source)));
|
||||
expect(source.font._nativeAsset).toBe(rawAlias);
|
||||
return migrated;
|
||||
});
|
||||
expect(descriptions).toEqual([
|
||||
'40px "Example_LABEL"',
|
||||
'40px Example_LABEL',
|
||||
'40px "\\"Example_LABEL\\""',
|
||||
'40px "\\"My Font_LABEL\\""',
|
||||
]);
|
||||
@@ -84,15 +84,25 @@ describe('Label font consumers', () => {
|
||||
}
|
||||
}
|
||||
|
||||
test('TTF and CHAR resolve the same raw asset without modifying it', () => {
|
||||
test.each([
|
||||
['KenneyPixel_LABEL', 'KenneyPixel_LABEL'],
|
||||
['AlibabaPuHuiTi-3-105-Heavy_LABEL', 'AlibabaPuHuiTi-3-105-Heavy_LABEL'],
|
||||
['sans-serif_LABEL', 'sans-serif_LABEL'],
|
||||
['中文字体_LABEL', '"中文字体_LABEL"'],
|
||||
['阿里普惠体-Heavy_LABEL', '"阿里普惠体-Heavy_LABEL"'],
|
||||
['Alibaba PuHuiTi 3.0 105 Heavy', '"Alibaba PuHuiTi 3.0 105 Heavy"'],
|
||||
['3Font_LABEL', '"3Font_LABEL"'],
|
||||
['Font.3_LABEL', '"Font.3_LABEL"'],
|
||||
['A,B_LABEL', '"A,B_LABEL"'],
|
||||
])('TTF and CHAR select the family for %p without modifying the asset', (raw, expected) => {
|
||||
const font = new TTFFont();
|
||||
font._nativeAsset = 'Alibaba PuHuiTi 3.0 105 Heavy';
|
||||
font._nativeAsset = raw;
|
||||
const label = { font, useSystemFont: false, fontFamily: 'Arial' } as unknown as Label;
|
||||
const ttf = new TTFUtils();
|
||||
const char = new ExposedLetterFont();
|
||||
expect(ttf._updateFontFamily(label)).toBe('"Alibaba PuHuiTi 3.0 105 Heavy"');
|
||||
expect(ttf._updateFontFamily(label)).toBe(expected);
|
||||
expect(char.familyFor(label)).toBe(ttf._updateFontFamily(label));
|
||||
expect(font._nativeAsset).toBe('Alibaba PuHuiTi 3.0 105 Heavy');
|
||||
expect(font._nativeAsset).toBe(raw);
|
||||
});
|
||||
|
||||
test('Web EditBox applies a custom family as CSS and preserves system lists', () => {
|
||||
|
||||
@@ -1,4 +1,9 @@
|
||||
import { TTFFont } from '../../cocos/2d/assets/ttf-font';
|
||||
import { TTFUtils } from '../../cocos/2d/assembler/label/ttfUtils';
|
||||
import type { Label } from '../../cocos/2d/components/label';
|
||||
import { buildFontDesc } from '../../cocos/2d/utils/font-family';
|
||||
import { getFontFamily, loadFont } from '../../cocos/2d/utils/font-loader';
|
||||
import factory from '../../cocos/asset/asset-manager/factory';
|
||||
|
||||
test.each([
|
||||
['fonts/Alibaba PuHuiTi 3.0.ttf', 'Alibaba PuHuiTi 3.0_LABEL'],
|
||||
@@ -8,7 +13,14 @@ test.each([
|
||||
expect(getFontFamily(url)).toBe(expected);
|
||||
});
|
||||
|
||||
test('Web registration and FontFaceSet loading share one CSS family and return a raw alias', async () => {
|
||||
test.each([
|
||||
// URL, raw asset alias, expected CSS family for registration and drawing.
|
||||
['fonts/Web Family 3.0.ttf', 'Web Family 3.0_LABEL', '"Web Family 3.0_LABEL"'],
|
||||
['fonts/KenneyPixel.ttf', 'KenneyPixel_LABEL', 'KenneyPixel_LABEL'],
|
||||
['fonts/sans-serif.ttf', 'sans-serif_LABEL', 'sans-serif_LABEL'],
|
||||
['fonts/My Font.ttf', 'My Font_LABEL', '"My Font_LABEL"'],
|
||||
['fonts/中文字体.ttf', '中文字体_LABEL', '"中文字体_LABEL"'],
|
||||
])('Web registration, font loading and the TTF Label descriptor agree for %s', async (url, alias, familyCss) => {
|
||||
jest.useFakeTimers();
|
||||
const faceDescriptor = Object.getOwnPropertyDescriptor(window, 'FontFace');
|
||||
const fontsDescriptor = Object.getOwnPropertyDescriptor(document, 'fonts');
|
||||
@@ -28,23 +40,30 @@ test('Web registration and FontFaceSet loading share one CSS family and return a
|
||||
}) as typeof document.createElement);
|
||||
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
loadFont('fonts/Web Family 3.0.ttf', {}, (error, family) => {
|
||||
const font = await new Promise<TTFFont>((resolve, reject) => {
|
||||
loadFont(url, {}, (error, family) => {
|
||||
if (error) {
|
||||
reject(error);
|
||||
return;
|
||||
}
|
||||
callback(family);
|
||||
resolve();
|
||||
factory.create(url, family, '.ttf', { cacheAsset: false }, (err, asset) => {
|
||||
if (err) reject(err);
|
||||
else if (asset instanceof TTFFont) resolve(asset);
|
||||
else reject(new Error('Expected the font factory to return a TTFFont'));
|
||||
});
|
||||
});
|
||||
});
|
||||
const style = nodes.find((node) => node.tagName === 'STYLE')!;
|
||||
const preload = nodes.find((node) => node.tagName === 'DIV')!;
|
||||
expect(style.textContent).toBe('@font-face { font-family:"Web Family 3.0_LABEL"; src:url("fonts/Web Family 3.0.ttf");}');
|
||||
expect(preload.style.fontFamily).toBe('"Web Family 3.0_LABEL"');
|
||||
expect(load).toHaveBeenCalledWith('40px "Web Family 3.0_LABEL"');
|
||||
expect(style.textContent).toBe(`@font-face { font-family:${familyCss}; src:url("${url}");}`);
|
||||
expect(preload.style.fontFamily).toBe(familyCss);
|
||||
expect(load).toHaveBeenCalledWith(`40px ${familyCss}`);
|
||||
expect(callback).toHaveBeenCalledTimes(1);
|
||||
expect(callback).toHaveBeenCalledWith('Web Family 3.0_LABEL');
|
||||
expect(callback).toHaveBeenCalledWith(alias);
|
||||
expect(font._nativeAsset).toBe(alias);
|
||||
const label: Pick<Label, 'font' | 'useSystemFont' | 'fontFamily'> = { font, useSystemFont: false, fontFamily: 'Arial' };
|
||||
expect(buildFontDesc(40, new TTFUtils()._updateFontFamily(label as Label))).toBe(`40px ${familyCss}`);
|
||||
expect(jest.getTimerCount()).toBe(0);
|
||||
} finally {
|
||||
create.mockRestore();
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
import { Canvas, UIOpacity } from '../../cocos/2d';
|
||||
import { Batcher2D } from '../../cocos/2d/renderer/batcher-2d';
|
||||
import { Color } from '../../cocos/core';
|
||||
import type { Buffer } from '../../cocos/gfx';
|
||||
import { EmptyBuffer } from '../../cocos/gfx/empty/empty-buffer';
|
||||
import { Camera, Node, Scene, director, game } from '../../exports/base';
|
||||
import { Graphics } from '../../exports/graphics';
|
||||
|
||||
// Graphics uploads position.xyz, color.rgba, and distance for each vertex.
|
||||
const vertexStride = 8;
|
||||
const alphaOffset = 6;
|
||||
|
||||
function vertices (graphics: Graphics, block = 0): Float32Array {
|
||||
const data = graphics.impl!.getRenderDataList()[block];
|
||||
return data.vData.slice(0, data.vertexStart * vertexStride);
|
||||
}
|
||||
|
||||
function recordUploads () {
|
||||
const writes = new Map<Buffer, (Float32Array | Uint16Array)[]>();
|
||||
const update = EmptyBuffer.prototype.update;
|
||||
jest.spyOn(EmptyBuffer.prototype, 'update').mockImplementation(function (this: EmptyBuffer, data, size) {
|
||||
if (data instanceof Float32Array || data instanceof Uint16Array) {
|
||||
const calls = writes.get(this) ?? [];
|
||||
// The next upload can reuse the source array, including for another block in this frame.
|
||||
calls.push(data.slice(0, size === undefined ? data.length : size / data.BYTES_PER_ELEMENT));
|
||||
writes.set(this, calls);
|
||||
}
|
||||
update.call(this, data, size);
|
||||
});
|
||||
return writes;
|
||||
}
|
||||
|
||||
function expectUpload (writes: ReturnType<typeof recordUploads>, graphics: Graphics, block: number,
|
||||
raw: Float32Array, opacity: number, geometryChanged: boolean): void {
|
||||
const input = graphics.model!.subModels[block].inputAssembler;
|
||||
const expected = raw.slice();
|
||||
for (let i = alphaOffset; i < expected.length; i += vertexStride) {
|
||||
expected[i] = raw[i] * opacity;
|
||||
}
|
||||
expect(writes.get(input.vertexBuffers[0])).toEqual([expected]);
|
||||
const data = graphics.impl!.getRenderDataList()[block];
|
||||
expect(writes.get(input.indexBuffer!)).toEqual(geometryChanged ? [data.iData.slice(0, data.indexStart)] : undefined);
|
||||
expect(vertices(graphics, block)).toEqual(raw);
|
||||
}
|
||||
|
||||
describe('Graphics cascaded opacity', () => {
|
||||
let batcher: Batcher2D;
|
||||
let previousBatcher: Batcher2D | null;
|
||||
let parentOpacity: UIOpacity;
|
||||
let graphics: Graphics;
|
||||
const root = () => director.root as unknown as { _batcher: Batcher2D | null };
|
||||
|
||||
beforeEach(() => {
|
||||
const scene = new Scene('Graphics opacity');
|
||||
director.runSceneImmediate(scene);
|
||||
previousBatcher = root()._batcher;
|
||||
batcher = new Batcher2D(director.root!);
|
||||
root()._batcher = batcher;
|
||||
batcher.initialize();
|
||||
const canvasNode = new Node('Canvas');
|
||||
scene.addChild(canvasNode);
|
||||
const canvas = canvasNode.addComponent(Canvas);
|
||||
const camera = new Node('Camera');
|
||||
canvasNode.addChild(camera);
|
||||
canvas.cameraComponent = camera.addComponent(Camera);
|
||||
const group = new Node('Fade group');
|
||||
canvasNode.addChild(group);
|
||||
parentOpacity = group.addComponent(UIOpacity);
|
||||
const node = new Node('Graphics');
|
||||
group.addChild(node);
|
||||
graphics = node.addComponent(Graphics);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
director.runSceneImmediate(new Scene('Cleanup'));
|
||||
batcher.destroy();
|
||||
root()._batcher = previousBatcher;
|
||||
});
|
||||
|
||||
test('fades retained fills and strokes from their own alpha and restores them without redrawing', () => {
|
||||
graphics.fillColor = new Color(255, 0, 0, 64);
|
||||
graphics.fillRect(0, 0, 16, 16);
|
||||
graphics.strokeColor = new Color(0, 255, 0, 192);
|
||||
graphics.moveTo(20, 0);
|
||||
graphics.lineTo(20, 16);
|
||||
graphics.stroke();
|
||||
// Place a second fill in a separate draw buffer to verify both uploads on a fade.
|
||||
graphics.impl!.requestRenderData();
|
||||
graphics.impl!.dataOffset = 1;
|
||||
graphics.fillRect(32, 0, 8, 8);
|
||||
const raw = [vertices(graphics), vertices(graphics, 1)];
|
||||
const alpha = raw[0].filter((_, i) => i % vertexStride === alphaOffset);
|
||||
expect(alpha).toContain(Math.fround(64 / 255));
|
||||
expect(alpha).toContain(Math.fround(192 / 255));
|
||||
const writes = recordUploads();
|
||||
game.step();
|
||||
raw.forEach((original, block) => expectUpload(writes, graphics, block, original, 1, true));
|
||||
for (const value of [128, 64]) {
|
||||
writes.clear();
|
||||
parentOpacity.opacity = value;
|
||||
game.step();
|
||||
raw.forEach((original, block) => expectUpload(writes, graphics, block, original, value / 255, false));
|
||||
}
|
||||
|
||||
writes.clear();
|
||||
game.step();
|
||||
for (const sub of graphics.model!.subModels) {
|
||||
expect(writes.has(sub.inputAssembler.vertexBuffers[0])).toBe(false);
|
||||
expect(writes.has(sub.inputAssembler.indexBuffer!)).toBe(false);
|
||||
}
|
||||
const commits = jest.spyOn(batcher, 'commitModel');
|
||||
parentOpacity.opacity = 0;
|
||||
game.step();
|
||||
expect(commits).not.toHaveBeenCalled();
|
||||
|
||||
writes.clear();
|
||||
parentOpacity.opacity = 255;
|
||||
game.step();
|
||||
expect(commits).toHaveBeenCalledTimes(1);
|
||||
raw.forEach((original, block) => expectUpload(writes, graphics, block, original, 1, false));
|
||||
});
|
||||
|
||||
test('applies current opacity when appending paint or replacing paint of the same size while hidden', () => {
|
||||
parentOpacity.opacity = 128;
|
||||
graphics.fillColor = new Color(10, 50, 150, 192);
|
||||
graphics.fillRect(0, 0, 8, 8);
|
||||
const writes = recordUploads();
|
||||
const first = vertices(graphics);
|
||||
game.step();
|
||||
expectUpload(writes, graphics, 0, first, 128 / 255, true);
|
||||
|
||||
writes.clear();
|
||||
graphics.fillColor = new Color(180, 20, 5, 64);
|
||||
graphics.fillRect(10, 0, 8, 8);
|
||||
const appended = vertices(graphics);
|
||||
game.step();
|
||||
expectUpload(writes, graphics, 0, appended, 128 / 255, true);
|
||||
|
||||
parentOpacity.opacity = 0;
|
||||
graphics.clear();
|
||||
graphics.fillColor = new Color(20, 220, 10, 48);
|
||||
graphics.fillRect(32, 0, 8, 8);
|
||||
graphics.fillRect(42, 0, 8, 8);
|
||||
const replacement = vertices(graphics);
|
||||
expect(replacement.length).toBe(appended.length);
|
||||
expect(replacement).not.toEqual(appended);
|
||||
game.step();
|
||||
writes.clear();
|
||||
parentOpacity.opacity = 128;
|
||||
game.step();
|
||||
expectUpload(writes, graphics, 0, replacement, 128 / 255, true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,438 @@
|
||||
import { UIMesh, UIMeshData } from '../../cocos/2d/components/ui-mesh';
|
||||
import { UITransform } from '../../cocos/2d';
|
||||
import { UIOpacity } from '../../cocos/2d/components/ui-opacity';
|
||||
import { Node } from '../../cocos/scene-graph/node';
|
||||
import { Scene, director } from '../../exports/base';
|
||||
import { Batcher2D } from '../../cocos/2d/renderer/batcher-2d';
|
||||
import { vfmtPosUvColor4B, vfmtPosUvTwoColor4B } from '../../cocos/2d/renderer/vertex-format';
|
||||
import { Vec3 } from '../../cocos/core/math/vec3';
|
||||
import { captureErrorIDs } from '../utils/log-capture';
|
||||
|
||||
// Mirrors sprite.test.ts: a headless batcher so UIMesh can create its shared
|
||||
// StaticVBAccessor and allocate chunks from it.
|
||||
// @ts-expect-error
|
||||
director.root!._batcher = new Batcher2D(director.root!);
|
||||
const scene = new Scene('uimesh-test');
|
||||
director.runSceneImmediate(scene);
|
||||
|
||||
const ACCESSOR_VERTEX_COUNT = 32767;
|
||||
|
||||
function createUIMesh (parent: Node = scene): { mesh: UIMesh, anyMesh: any, node: Node } {
|
||||
const node = new Node('mesh');
|
||||
node.addComponent(UITransform);
|
||||
parent.addChild(node);
|
||||
const mesh = node.addComponent(UIMesh);
|
||||
return { mesh, anyMesh: mesh as any, node };
|
||||
}
|
||||
|
||||
function makeMeshData (vc: number, stride = 24): UIMeshData {
|
||||
const quadCount = Math.floor(vc / 4);
|
||||
const ic = quadCount * 6;
|
||||
const vertexData = new Uint8Array(vc * stride);
|
||||
const indices = new Uint16Array(ic);
|
||||
for (let q = 0; q < quadCount; ++q) {
|
||||
const v = q * 4;
|
||||
const o = q * 6;
|
||||
indices[o] = v; indices[o + 1] = v + 1; indices[o + 2] = v + 2;
|
||||
indices[o + 3] = v + 2; indices[o + 4] = v + 1; indices[o + 5] = v + 3;
|
||||
}
|
||||
return {
|
||||
vertexCount: vc,
|
||||
vertexStride: stride,
|
||||
vertexData,
|
||||
indexCount: ic,
|
||||
indexData: new Uint8Array(indices.buffer),
|
||||
segments: [{ indexOffset: 0, indexCount: ic, texture: null, material: null }],
|
||||
};
|
||||
}
|
||||
|
||||
describe('UIMesh: accessor capacity', () => {
|
||||
test('30000 vertices render — the 10% reserve is clamped to the accessor cap', () => {
|
||||
const { mesh, anyMesh } = createUIMesh();
|
||||
const data = makeMeshData(30000); // fits, but ceil(30000 * 1.1) > 32767
|
||||
mesh.setMeshData(data);
|
||||
expect(anyMesh._meshData).toBe(data);
|
||||
expect(anyMesh._prepareBuffers()).not.toBeNull();
|
||||
const rd = anyMesh._renderData;
|
||||
// Actual counts are tracked; the reserve lives in the chunk.
|
||||
expect(rd.vertexCount).toBe(30000);
|
||||
expect(rd.indexCount).toBe(data.indexCount);
|
||||
expect(rd.chunk).toBeTruthy();
|
||||
expect(rd.chunk.vb.byteLength).toBe(ACCESSOR_VERTEX_COUNT * 24);
|
||||
});
|
||||
|
||||
test('32767 vertices (exact accessor cap) render', () => {
|
||||
const { mesh, anyMesh } = createUIMesh();
|
||||
mesh.setMeshData(makeMeshData(32767));
|
||||
expect(anyMesh._prepareBuffers()).not.toBeNull();
|
||||
const rd = anyMesh._renderData;
|
||||
expect(rd.vertexCount).toBe(32767);
|
||||
expect(rd.chunk.vb.byteLength).toBe(ACCESSOR_VERTEX_COUNT * 24);
|
||||
});
|
||||
|
||||
test('data beyond the accessor cap is rejected with an error', () => {
|
||||
const { mesh, anyMesh } = createUIMesh();
|
||||
const watcher = captureErrorIDs();
|
||||
mesh.setMeshData(makeMeshData(32768));
|
||||
expect(watcher.captured).toHaveLength(1);
|
||||
expect(watcher.captured[0]).toEqual([9016, 32768, 49152, 32767, 131068]);
|
||||
watcher.clear();
|
||||
expect(anyMesh._meshData).toBeNull(); // rejected frame stores nothing
|
||||
});
|
||||
|
||||
test('growth within the reserve does not reallocate the chunk', () => {
|
||||
const { mesh, anyMesh } = createUIMesh();
|
||||
mesh.setMeshData(makeMeshData(100));
|
||||
expect(anyMesh._prepareBuffers()).not.toBeNull();
|
||||
const chunk = anyMesh._renderData.chunk;
|
||||
mesh.setMeshData(makeMeshData(105)); // within the ~10% head room
|
||||
expect(anyMesh._prepareBuffers()).not.toBeNull();
|
||||
expect(anyMesh._renderData.chunk).toBe(chunk);
|
||||
expect(anyMesh._renderData.vertexCount).toBe(105);
|
||||
});
|
||||
});
|
||||
|
||||
describe('UIMesh: setMeshData boundary validation', () => {
|
||||
let mesh: UIMesh;
|
||||
let anyMesh: any;
|
||||
let watcher: ReturnType<typeof captureErrorIDs>;
|
||||
|
||||
beforeEach(() => {
|
||||
({ mesh, anyMesh } = createUIMesh());
|
||||
watcher = captureErrorIDs();
|
||||
});
|
||||
|
||||
// The watcher must be empty by test end (log-capture afterEach enforces it):
|
||||
// every test asserts its single errorID call and clears it. Entries are the
|
||||
// raw errorID arguments — [id, ...params]; the texts live in DebugInfos.json.
|
||||
afterEach(() => {
|
||||
watcher.clear();
|
||||
});
|
||||
|
||||
test('rejects unsupported vertex stride', () => {
|
||||
mesh.setMeshData(makeMeshData(8, 32));
|
||||
expect(watcher.captured).toHaveLength(1);
|
||||
expect(watcher.captured[0]).toEqual([9010, 32, 24, 28]);
|
||||
expect(anyMesh._meshData).toBeNull();
|
||||
});
|
||||
|
||||
test('rejects vertexData shorter than vertexCount * stride', () => {
|
||||
const data = makeMeshData(8);
|
||||
data.vertexData = data.vertexData.slice(0, data.vertexData.byteLength - 1);
|
||||
mesh.setMeshData(data);
|
||||
expect(watcher.captured).toHaveLength(1);
|
||||
expect(watcher.captured[0]).toEqual([9012, 191, 8, 24]);
|
||||
expect(anyMesh._meshData).toBeNull();
|
||||
});
|
||||
|
||||
test('rejects indexData shorter than indexCount * 2', () => {
|
||||
const data = makeMeshData(8);
|
||||
data.indexData = data.indexData.slice(0, data.indexData.byteLength - 2);
|
||||
mesh.setMeshData(data);
|
||||
expect(watcher.captured).toHaveLength(1);
|
||||
expect(watcher.captured[0]).toEqual([9013, 22, 0, 12, 24]);
|
||||
expect(anyMesh._meshData).toBeNull();
|
||||
});
|
||||
|
||||
test('rejects indices out of vertex range', () => {
|
||||
const data = makeMeshData(8);
|
||||
const indices = new Uint16Array(data.indexData.buffer, data.indexData.byteOffset, data.indexCount);
|
||||
indices[0] = data.vertexCount; // one past the last vertex
|
||||
mesh.setMeshData(data);
|
||||
expect(watcher.captured).toHaveLength(1);
|
||||
expect(watcher.captured[0]).toEqual([9014, 0, 8, 8]);
|
||||
expect(anyMesh._meshData).toBeNull();
|
||||
});
|
||||
|
||||
test('rejects segment ranges beyond indexCount', () => {
|
||||
const data = makeMeshData(8);
|
||||
data.segments = [{ indexOffset: 0, indexCount: data.indexCount + 1, texture: null, material: null }];
|
||||
mesh.setMeshData(data);
|
||||
expect(watcher.captured).toHaveLength(1);
|
||||
expect(watcher.captured[0]).toEqual([9015, 0, 0, 13, 12]);
|
||||
expect(anyMesh._meshData).toBeNull();
|
||||
});
|
||||
|
||||
test('a rejected frame keeps the last accepted mesh', () => {
|
||||
const good = makeMeshData(8);
|
||||
mesh.setMeshData(good);
|
||||
mesh.setMeshData(makeMeshData(32768)); // over cap, rejected
|
||||
expect(watcher.captured).toHaveLength(1);
|
||||
expect(watcher.captured[0]).toEqual([9016, 32768, 49152, 32767, 131068]);
|
||||
expect(anyMesh._meshData).toBe(good);
|
||||
});
|
||||
});
|
||||
|
||||
describe('UIMesh: accessor lifetime follows the batcher', () => {
|
||||
test('a rebuilt root/batcher never reuses a destroyed accessor (single- and two-color)', () => {
|
||||
const UIMESH_KEY = Number.parseInt('UIMESH', 36);
|
||||
const UIMESH_TINT_KEY = Number.parseInt('UIMESHTINT', 36);
|
||||
|
||||
// First root: a UIMesh creates its accessors and registers them with
|
||||
// the current batcher.
|
||||
const first = createUIMesh();
|
||||
first.mesh.setMeshData(makeMeshData(8));
|
||||
expect(first.anyMesh._prepareBuffers()).not.toBeNull();
|
||||
const oldAccessor = first.anyMesh._renderData.accessor;
|
||||
const oldMap: Map<number, any> = (director.root!.batcher2D as any)._bufferAccessors;
|
||||
expect(oldMap.get(UIMESH_KEY)).toBe(oldAccessor); // registered with its batcher
|
||||
|
||||
// Root.destroy(): the batcher destroys every accessor it owns, is
|
||||
// dropped, and a rebuilt root creates a fresh batcher with an empty map
|
||||
// — all within the same JS context.
|
||||
const root: any = director.root!;
|
||||
const oldBatcher: Batcher2D = root.batcher2D;
|
||||
oldBatcher.destroy();
|
||||
expect(oldMap.size).toBe(0); // accessors released with the batcher
|
||||
expect((oldAccessor as any)._buffers.length).toBe(0); // buffers gone
|
||||
root._batcher = new Batcher2D(root);
|
||||
|
||||
// UIMesh components under the new root must resolve fresh accessors
|
||||
// from the new batcher. A batcher-keyed cache that forgot to invalidate
|
||||
// would hand back the destroyed accessor and skip registration,
|
||||
// breaking upload/reset.
|
||||
const second = createUIMesh();
|
||||
second.mesh.setMeshData(makeMeshData(8));
|
||||
expect(second.anyMesh._prepareBuffers()).not.toBeNull();
|
||||
const newAccessor = second.anyMesh._renderData.accessor;
|
||||
expect(newAccessor).not.toBe(oldAccessor);
|
||||
expect((newAccessor as any)._buffers.length).toBeGreaterThan(0);
|
||||
|
||||
const newMap: Map<number, any> = (director.root!.batcher2D as any)._bufferAccessors;
|
||||
expect(newMap.get(UIMESH_KEY)).toBe(newAccessor); // registered with the new batcher
|
||||
|
||||
// Two-color branch: same guarantee for the tint accessor.
|
||||
const tinted = createUIMesh();
|
||||
tinted.mesh.setMeshData(makeMeshData(8, 28));
|
||||
expect(tinted.anyMesh._prepareBuffers()).not.toBeNull();
|
||||
const newTintAccessor = tinted.anyMesh._renderData.accessor;
|
||||
expect(newTintAccessor).not.toBe(oldAccessor);
|
||||
expect(newMap.get(UIMESH_TINT_KEY)).toBe(newTintAccessor);
|
||||
|
||||
// The accessors hold copies of the vertex formats: destroying them with
|
||||
// the old batcher must not empty the shared module-level constants.
|
||||
expect(vfmtPosUvColor4B).toHaveLength(3);
|
||||
expect(vfmtPosUvTwoColor4B).toHaveLength(4);
|
||||
});
|
||||
});
|
||||
|
||||
// A drawable segment: a texture is what makes _prepareNativeDrawInfos create a
|
||||
// draw info (segments without texture are skipped). Only getGFXTexture /
|
||||
// getGFXSampler are called headless.
|
||||
const fakeTexture = (): any => ({ getGFXTexture: () => ({}), getGFXSampler: () => ({}) });
|
||||
|
||||
function makeDrawnData (vc: number): UIMeshData {
|
||||
const data = makeMeshData(vc);
|
||||
data.segments = [{ indexOffset: 0, indexCount: data.indexCount, texture: fakeTexture(), material: {} as any }];
|
||||
return data;
|
||||
}
|
||||
|
||||
describe('UIMesh: per-frame index submission (native cross-frame)', () => {
|
||||
// The native batcher resets every mesh buffer's index tail after upload
|
||||
// (indexOffset = 0, synchronized through shared memory) while only dirty
|
||||
// renderers re-prepare. jest runs with JSB = false, so these tests drive
|
||||
// the JSB pump's two submit paths directly: appendIndexBuffer (static
|
||||
// frame) and _prepareNativeDrawInfos (dirty frame) -- each runs exactly
|
||||
// once per frame. The helper below performs the post-upload reset.
|
||||
const nextFrame = (buf: any): void => {
|
||||
buf.indexOffset = 0; // the post-upload index-tail reset
|
||||
};
|
||||
|
||||
test('a paused mesh keeps drawing its own triangles while a sibling updates', () => {
|
||||
const a = createUIMesh();
|
||||
const b = createUIMesh();
|
||||
a.mesh.setMeshData(makeDrawnData(4)); // ic = 6
|
||||
b.mesh.setMeshData(makeDrawnData(4));
|
||||
|
||||
// Frame 1: both dirty -> both run the native draw-info refresh.
|
||||
a.anyMesh._prepareNativeDrawInfos();
|
||||
b.anyMesh._prepareNativeDrawInfos();
|
||||
const buf = a.anyMesh._renderData.getMeshBuffer();
|
||||
expect(b.anyMesh._renderData.getMeshBuffer()).toBe(buf); // one shared buffer
|
||||
const offsetA = a.anyMesh._renderData.chunk.vertexOffset;
|
||||
const offsetB = b.anyMesh._renderData.chunk.vertexOffset;
|
||||
expect(offsetB).toBeGreaterThan(offsetA);
|
||||
const quadOf = (o: number): Uint16Array => new Uint16Array([o, o + 1, o + 2, o + 2, o + 1, o + 3]);
|
||||
const startA = a.anyMesh._drawInfoList[0]._indexOffset;
|
||||
const startB = b.anyMesh._drawInfoList[0]._indexOffset;
|
||||
expect(startB - startA).toBe(6); // B appended right after A
|
||||
expect(buf.iData.slice(startA, startA + 6)).toEqual(quadOf(offsetA));
|
||||
expect(buf.iData.slice(startB, startB + 6)).toEqual(quadOf(offsetB));
|
||||
|
||||
// Frame 2: A paused (no setMeshData), B advancing.
|
||||
nextFrame(buf);
|
||||
b.mesh.setMeshData(makeDrawnData(4)); // B's producer, update phase
|
||||
a.anyMesh.appendIndexBuffer(); // A's pump: static, index-only resubmit
|
||||
b.anyMesh._prepareNativeDrawInfos(); // B's pump: dirty, full refresh
|
||||
|
||||
// A's cached draw info still points at a range holding A's OWN indices.
|
||||
// Without the per-frame resubmit, B would append at the reset offset 0
|
||||
// and A (start 0, never refreshed) would draw B's vertices.
|
||||
expect(a.anyMesh._drawInfoList[0]._indexOffset).toBe(0);
|
||||
expect(b.anyMesh._drawInfoList[0]._indexOffset).toBe(6);
|
||||
expect(buf.iData.slice(0, 6)).toEqual(quadOf(offsetA));
|
||||
expect(buf.iData.slice(6, 12)).toEqual(quadOf(offsetB));
|
||||
expect(buf.indexOffset).toBe(12); // one append per mesh — the pump is the single driver
|
||||
});
|
||||
|
||||
test('each frame appends once; re-feeding the same object resubmits', () => {
|
||||
const { mesh, anyMesh } = createUIMesh();
|
||||
const data = makeMeshData(4);
|
||||
mesh.setMeshData(data);
|
||||
expect(anyMesh._prepareBuffers()).not.toBeNull(); // establishes the chunk
|
||||
const buf = anyMesh._renderData.getMeshBuffer();
|
||||
const offset = anyMesh._renderData.chunk.vertexOffset;
|
||||
const quadOf = (o: number): Uint16Array => new Uint16Array([o, o + 1, o + 2, o + 2, o + 1, o + 3]);
|
||||
|
||||
nextFrame(buf);
|
||||
anyMesh.appendIndexBuffer(); // the pump's static-frame path
|
||||
expect(buf.indexOffset).toBe(6);
|
||||
expect(buf.iData.slice(0, 6)).toEqual(quadOf(offset));
|
||||
|
||||
nextFrame(buf);
|
||||
mesh.setMeshData(data); // SAME object, mutated in place by the producer
|
||||
anyMesh.appendIndexBuffer();
|
||||
expect(buf.indexOffset).toBe(6); // setMeshData latched a refresh; fresh append at the reset tail
|
||||
expect(buf.iData.slice(0, 6)).toEqual(quadOf(offset));
|
||||
});
|
||||
});
|
||||
|
||||
describe('UIMesh: batched bake applies the full world matrix', () => {
|
||||
const writePositions = (data: UIMeshData, locals: Vec3[]): void => {
|
||||
const floats = new Float32Array(data.vertexData.buffer, data.vertexData.byteOffset, data.vertexData.byteLength >> 2);
|
||||
locals.forEach((v, i) => {
|
||||
floats[i * 6] = v.x; floats[i * 6 + 1] = v.y; floats[i * 6 + 2] = v.z;
|
||||
});
|
||||
};
|
||||
const chunkPosition = (anyMesh: any, i: number): Vec3 => {
|
||||
const vb = anyMesh._renderData.chunk.vb; // stride 24 = 6 floats
|
||||
return new Vec3(vb[i * 6], vb[i * 6 + 1], vb[i * 6 + 2]);
|
||||
};
|
||||
|
||||
test('a parent Z translation reaches the batched vertices: local (1,2,3) + z+10 -> (1,2,13)', () => {
|
||||
const parent = new Node('parent');
|
||||
parent.addComponent(UITransform);
|
||||
scene.addChild(parent);
|
||||
parent.setPosition(0, 0, 10);
|
||||
const { mesh, anyMesh } = createUIMesh(parent); // node itself stays identity
|
||||
|
||||
const data = makeMeshData(4);
|
||||
writePositions(data, [new Vec3(1, 2, 3), new Vec3(-1, 2, 3), new Vec3(1, -2, -3), new Vec3(-1, -2, -3)]);
|
||||
anyMesh._enableBatch = true; // direct: the public setter also recompiles materials
|
||||
mesh.setMeshData(data);
|
||||
expect(anyMesh._prepareBuffers()).not.toBeNull();
|
||||
|
||||
// The old 2D-only bake kept z at 3; the GPU path (pos = cc_matWorld * pos)
|
||||
// produces 13, and so must the baked chunk.
|
||||
const got = chunkPosition(anyMesh, 0);
|
||||
expect(got.x).toBeCloseTo(1, 6);
|
||||
expect(got.y).toBeCloseTo(2, 6);
|
||||
expect(got.z).toBeCloseTo(13, 6);
|
||||
});
|
||||
|
||||
test('batched chunk equals the full world matrix applied to the unbatched chunk (toggle consistency)', () => {
|
||||
const parent = new Node('parent');
|
||||
parent.addComponent(UITransform);
|
||||
scene.addChild(parent);
|
||||
parent.setPosition(1, 2, 10);
|
||||
parent.setRotationFromEuler(30, 0, 0); // X-axis rotation
|
||||
const { mesh, anyMesh, node } = createUIMesh(parent);
|
||||
node.setPosition(0.5, -0.25, 2);
|
||||
node.setRotationFromEuler(0, 45, 0); // Y-axis rotation
|
||||
|
||||
const locals = [new Vec3(1, 2, 3), new Vec3(-4, 5, -6), new Vec3(7, -8, 9), new Vec3(-10, -11, -12)];
|
||||
const data = makeMeshData(4);
|
||||
writePositions(data, locals);
|
||||
|
||||
// Unbatched: the chunk stays node-local (the GPU applies cc_matWorld).
|
||||
anyMesh._enableBatch = false;
|
||||
mesh.setMeshData(data);
|
||||
expect(anyMesh._prepareBuffers()).not.toBeNull();
|
||||
const localChunk = [0, 1, 2, 3].map((i) => chunkPosition(anyMesh, i));
|
||||
|
||||
// Batched: the chunk holds the world matrix baked on the CPU. What the
|
||||
// GPU would compute for the unbatched data and what the batched data
|
||||
// carries must agree component by component, z and X/Y rotation included.
|
||||
anyMesh._enableBatch = true;
|
||||
expect(anyMesh._prepareBuffers()).not.toBeNull();
|
||||
const wm = node.worldMatrix;
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const expected = new Vec3();
|
||||
Vec3.transformMat4(expected, localChunk[i], wm);
|
||||
const got = chunkPosition(anyMesh, i);
|
||||
expect(got.x).toBeCloseTo(expected.x, 5);
|
||||
expect(got.y).toBeCloseTo(expected.y, 5);
|
||||
expect(got.z).toBeCloseTo(expected.z, 5);
|
||||
}
|
||||
|
||||
// The JSB staleness poll must track the full matrix the bake consumes:
|
||||
// a paused mesh that moves in Z or rotates in X/Y still has to re-bake.
|
||||
// The capture after a batched prepare is exactly what _onBeforeDraw
|
||||
// compares against on the next frame.
|
||||
expect(Math.abs(wm.m02)).toBeGreaterThan(0.5); // the rotations are live
|
||||
expect(anyMesh._pollWorldMatrix.strictEquals(wm)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('UIMesh: cascaded opacity includes ancestor renderer color.a', () => {
|
||||
const makeParentWithRenderer = (alpha: number): { parent: Node, parentMesh: any } => {
|
||||
const parent = new Node('parent');
|
||||
parent.addComponent(UITransform);
|
||||
scene.addChild(parent);
|
||||
const parentMesh = parent.addComponent(UIMesh) as any;
|
||||
parentMesh._color.a = alpha; // direct write: the setter drags color-update machinery in
|
||||
return { parent, parentMesh };
|
||||
};
|
||||
|
||||
test('a parent renderer at color.a 128 fades the child to ~0.502', () => {
|
||||
const { parent } = makeParentWithRenderer(128);
|
||||
const { anyMesh } = createUIMesh(parent);
|
||||
// Own alpha 255 x parent level (UIOpacity 1 x renderer 128/255). The old
|
||||
// computation stopped at localOpacity and returned 1 here.
|
||||
expect(anyMesh._computeCascadedOpacity()).toBeCloseTo(128 / 255, 6);
|
||||
});
|
||||
|
||||
test('UIOpacity localOpacity and renderer alpha accumulate at every ancestor level', () => {
|
||||
const grand = new Node('grand');
|
||||
grand.addComponent(UITransform);
|
||||
scene.addChild(grand);
|
||||
grand.addComponent(UIOpacity).opacity = 204; // localOpacity 0.8
|
||||
const parent = new Node('parent');
|
||||
parent.addComponent(UITransform);
|
||||
grand.addChild(parent);
|
||||
const parentMesh = parent.addComponent(UIMesh) as any;
|
||||
parentMesh._color.a = 128;
|
||||
parent.addComponent(UIOpacity).opacity = 128; // localOpacity 128/255
|
||||
const { anyMesh } = createUIMesh(parent);
|
||||
|
||||
expect(anyMesh._computeCascadedOpacity()).toBeCloseTo((204 / 255) * (128 / 255) * (128 / 255), 6);
|
||||
});
|
||||
|
||||
test('a paused mesh picks up ancestor color.a changes (the JSB poll input)', () => {
|
||||
const { parent, parentMesh } = makeParentWithRenderer(128);
|
||||
const { mesh, anyMesh } = createUIMesh(parent);
|
||||
const data = makeMeshData(4);
|
||||
// vfmtPosUvColor4B: pos 12B + uv 8B puts the color attribute at bytes
|
||||
// 20..23 of the 24-byte vertex — alpha lives at 23.
|
||||
for (let i = 0; i < 4; i++) data.vertexData[i * 24 + 23] = 255; // opaque alpha bytes
|
||||
mesh.setMeshData(data);
|
||||
expect(anyMesh._prepareBuffers()).not.toBeNull();
|
||||
expect(anyMesh._pollOpacity).toBeCloseTo(128 / 255, 6); // captured by the last active frame
|
||||
|
||||
// The ancestor fades while this mesh is paused: no engine event marks a
|
||||
// middleware renderer dirty -- the update() poll compares exactly this
|
||||
// value and re-marks on drift.
|
||||
parentMesh._color.a = 64;
|
||||
expect(anyMesh._computeCascadedOpacity()).not.toBe(anyMesh._pollOpacity);
|
||||
|
||||
// The refresh the poll triggers re-folds the new opacity into the
|
||||
// copied vertices' alpha bytes.
|
||||
expect(anyMesh._prepareBuffers()).not.toBeNull();
|
||||
expect(anyMesh._pollOpacity).toBeCloseTo(64 / 255, 6);
|
||||
const vb = anyMesh._renderData.chunk.vb;
|
||||
const bytes = new Uint8Array(vb.buffer, vb.byteOffset, 4 * 24);
|
||||
for (let i = 0; i < 4; i++) {
|
||||
expect(bytes[i * 24 + 23]).toBe(64); // 255 * (64 / 255)
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
import { screen, Size } from '../../cocos/core';
|
||||
import { UITransform } from '../../cocos/2d/framework/ui-transform';
|
||||
import { Canvas } from '../../cocos/2d/framework/canvas';
|
||||
import { Batcher2D } from '../../cocos/2d/renderer/batcher-2d';
|
||||
import { Camera } from '../../cocos/misc/camera-component';
|
||||
import { Node } from '../../cocos/scene-graph/node';
|
||||
import { Scene } from '../../cocos/scene-graph/scene';
|
||||
import { director } from '../../cocos/game/director';
|
||||
import { ResolutionPolicy, toPixelSpace, toUISpace, view } from '../../cocos/ui/view';
|
||||
import { Widget } from '../../cocos/ui/widget';
|
||||
import { widgetManager } from '../../cocos/ui/widget-manager';
|
||||
|
||||
const DESIGN_W = 1080;
|
||||
const DESIGN_H = 1920;
|
||||
|
||||
function mockWindowSize (width: number, height: number): void {
|
||||
jest.spyOn(screen, 'windowSize', 'get').mockReturnValue(new Size(width, height));
|
||||
}
|
||||
|
||||
function initBatcher (): void {
|
||||
// @ts-expect-error the batcher is required by Canvas.onEnable in the headless test environment
|
||||
director.root!._batcher = new Batcher2D(director.root!);
|
||||
}
|
||||
|
||||
function createSceneCanvas (name: string): { node: Node; canvas: Canvas; camera: Camera } {
|
||||
const scene = new Scene(name);
|
||||
director.runSceneImmediate(scene);
|
||||
|
||||
const node = new Node('Canvas');
|
||||
scene.addChild(node);
|
||||
node.addComponent(UITransform);
|
||||
const canvas = node.addComponent(Canvas) as Canvas;
|
||||
|
||||
const camNode = new Node('UICamera');
|
||||
camNode.parent = node;
|
||||
const camera = camNode.addComponent(Camera) as Camera;
|
||||
canvas.cameraComponent = camera;
|
||||
(canvas as unknown as { _onResizeCamera(): void })._onResizeCamera();
|
||||
|
||||
return { node, canvas, camera };
|
||||
}
|
||||
|
||||
afterEach(() => {
|
||||
jest.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe('scale ratio keeps UI lengths exact', () => {
|
||||
test('FIXED_HEIGHT: the fitted axis equals the design size instead of 1919.9999999999998', () => {
|
||||
mockWindowSize(1532, 1532); // the viewport from the packaged-editor report
|
||||
view.setDesignResolutionSize(DESIGN_W, DESIGN_H, ResolutionPolicy.FIXED_HEIGHT);
|
||||
|
||||
const visible = view.getVisibleSize();
|
||||
expect(visible.height).toBe(1920);
|
||||
expect(visible.width).toBe(1920); // adapted axis, exactly representable
|
||||
|
||||
const pixel = view.getVisibleSizeInPixel();
|
||||
expect(pixel.width).toBe(1532); // the round trip back to pixels stays exact
|
||||
expect(pixel.height).toBe(1532);
|
||||
|
||||
// the rounded scale is untouched, it is only no longer used for the conversion
|
||||
expect(view.getScaleY()).toBe(1532 / 1920);
|
||||
});
|
||||
|
||||
test('FIXED_HEIGHT: the canvas camera keeps 960 instead of 959.9999999999999', () => {
|
||||
mockWindowSize(1532, 1532);
|
||||
view.setDesignResolutionSize(DESIGN_W, DESIGN_H, ResolutionPolicy.FIXED_HEIGHT);
|
||||
initBatcher();
|
||||
|
||||
const { camera } = createSceneCanvas('ratio-camera-fixed-height');
|
||||
expect(camera.orthoHeight).toBe(960);
|
||||
});
|
||||
|
||||
test('FIXED_WIDTH: both axes are exact', () => {
|
||||
mockWindowSize(1024, 768);
|
||||
view.setDesignResolutionSize(DESIGN_W, DESIGN_H, ResolutionPolicy.FIXED_WIDTH);
|
||||
initBatcher();
|
||||
|
||||
const visible = view.getVisibleSize();
|
||||
expect(visible.width).toBe(1080);
|
||||
expect(visible.height).toBe(810);
|
||||
|
||||
const { camera } = createSceneCanvas('ratio-camera-fixed-width');
|
||||
expect(camera.orthoHeight).toBe(405);
|
||||
});
|
||||
|
||||
test('SHOW_ALL: the visible size equals the design resolution', () => {
|
||||
mockWindowSize(1024, 768);
|
||||
view.setDesignResolutionSize(DESIGN_W, DESIGN_H, ResolutionPolicy.SHOW_ALL);
|
||||
|
||||
const visible = view.getVisibleSize();
|
||||
expect(visible.width).toBe(1080);
|
||||
expect(visible.height).toBe(1920);
|
||||
});
|
||||
|
||||
test('EXACT_FIT: the visible size equals the design resolution', () => {
|
||||
mockWindowSize(1024, 768);
|
||||
view.setDesignResolutionSize(DESIGN_W, DESIGN_H, ResolutionPolicy.EXACT_FIT);
|
||||
|
||||
const visible = view.getVisibleSize();
|
||||
expect(visible.width).toBe(1080);
|
||||
expect(visible.height).toBe(1920);
|
||||
});
|
||||
|
||||
test('NO_BORDER: the visible size equals the design resolution while the content is cropped', () => {
|
||||
mockWindowSize(1024, 3840);
|
||||
view.setDesignResolutionSize(DESIGN_W, DESIGN_H, ResolutionPolicy.NO_BORDER);
|
||||
|
||||
const visible = view.getVisibleSize();
|
||||
expect(visible.width).toBe(1080);
|
||||
expect(visible.height).toBe(1920);
|
||||
});
|
||||
|
||||
test('the reported ratio converts lengths in both directions without error', () => {
|
||||
mockWindowSize(1532, 1532);
|
||||
view.setDesignResolutionSize(DESIGN_W, DESIGN_H, ResolutionPolicy.FIXED_HEIGHT);
|
||||
|
||||
const ratio = view.getRatioY();
|
||||
expect(ratio.pixels).toBe(1532);
|
||||
expect(ratio.units).toBe(1920);
|
||||
expect(toUISpace(1532, ratio)).toBe(1920);
|
||||
expect(toPixelSpace(1920, ratio)).toBe(1532);
|
||||
});
|
||||
|
||||
test('EXACT_FIT: the derived scale factors stay bit-identical to the policy scale', () => {
|
||||
mockWindowSize(1024, 768);
|
||||
view.setDesignResolutionSize(DESIGN_W, DESIGN_H, ResolutionPolicy.EXACT_FIT);
|
||||
|
||||
// The scale is no longer stored, it is derived from the exact ratio on demand.
|
||||
expect(view.getScaleX()).toBe(1024 / 1080);
|
||||
expect(view.getScaleY()).toBe(768 / 1920);
|
||||
});
|
||||
|
||||
test('setting the same resolution twice is idempotent', () => {
|
||||
mockWindowSize(1532, 1532);
|
||||
view.setDesignResolutionSize(DESIGN_W, DESIGN_H, ResolutionPolicy.FIXED_HEIGHT);
|
||||
const first = { visible: view.getVisibleSize(), scale: view.getScaleY() };
|
||||
|
||||
view.setDesignResolutionSize(DESIGN_W, DESIGN_H, ResolutionPolicy.FIXED_HEIGHT);
|
||||
expect(view.getVisibleSize().width).toBe(first.visible.width);
|
||||
expect(view.getVisibleSize().height).toBe(first.visible.height);
|
||||
expect(view.getScaleY()).toBe(first.scale);
|
||||
});
|
||||
|
||||
test('a root widget gets the exact canvas size and position', () => {
|
||||
mockWindowSize(1532, 1532);
|
||||
view.setDesignResolutionSize(DESIGN_W, DESIGN_H, ResolutionPolicy.FIXED_HEIGHT);
|
||||
initBatcher();
|
||||
|
||||
const scene = new Scene('ratio-widget');
|
||||
director.runSceneImmediate(scene);
|
||||
|
||||
const node = new Node('Canvas');
|
||||
scene.addChild(node);
|
||||
node.addComponent(UITransform);
|
||||
node.addComponent(Canvas);
|
||||
|
||||
const widget = node.addComponent(Widget) as Widget;
|
||||
widget.isAlignLeft = true;
|
||||
widget.isAlignRight = true;
|
||||
widget.isAlignTop = true;
|
||||
widget.isAlignBottom = true;
|
||||
widget.left = 0;
|
||||
widget.right = 0;
|
||||
widget.top = 0;
|
||||
widget.bottom = 0;
|
||||
widgetManager.updateAlignment(node);
|
||||
|
||||
const trans = node.getComponent(UITransform) as UITransform;
|
||||
expect(trans.width).toBe(1920);
|
||||
expect(trans.height).toBe(1920);
|
||||
expect(node.position.x).toBe(960);
|
||||
expect(node.position.y).toBe(960);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user