Merge pull request #9752 from holycanvas/v3.5.0-sync

sync 3.4.0
This commit is contained in:
minggo
2021-12-03 10:28:51 +08:00
committed by GitHub
81 changed files with 1600 additions and 323 deletions
+1
View File
@@ -30,6 +30,7 @@ jobs:
- name: rebase HEAD branch
working-directory: ./engine
run: |
git checkout .
git remote add HEAD_REPO https://github.com/${{ github.event.pull_request.head.repo.full_name }}.git
git pull --rebase HEAD_REPO ${{ github.head_ref }}
+9
View File
@@ -621,6 +621,7 @@ Invalid index in MultiplexLayer switchTo message
cc.Layer.addLayer(): layer should be non-null
### 2104
Layer collision. The name of layer (%s) is collided with the name or value of some layer
### 2200
@@ -1703,6 +1704,10 @@ Cannot change hierarchy while activating or deactivating the parent.
addComponent: Cannot add any component to the scene.
### 3823
The enabled component (id: %s, name: %s) doesn't have a valid node
### 3900
Invalid clip to add
@@ -3172,3 +3177,7 @@ Graph update has been interrupted since too many transitions(greater than %s) oc
### 14100
Pool.destroy no longer take a function as parameter, Please specify destruct function in the construction of Pool instead
### 14200
Batcher2D.commitComp could not be used for components without render data, please use commitPlainComp instead
+8 -1
View File
@@ -34,7 +34,7 @@ import { Color, Rect } from '../../../core/math';
import { IBatcher } from '../../renderer/i-batcher';
import { Label } from '../../components/label';
import { IAssembler } from '../../renderer/base';
import { fillMeshVertices3D } from '../utils';
import { fillMeshVertices3D, updateCachedVertices } from '../utils';
import { bmfontUtils } from './bmfontUtils';
const tempColor = new Color(255, 255, 255, 255);
@@ -55,6 +55,13 @@ export const bmfont: IAssembler = {
fillMeshVertices3D(node, renderer, comp.renderData!, tempColor);
},
fillCacheBuffer (comp: Label) {
const node = comp.node;
tempColor.set(comp.color);
tempColor.a = node._uiProps.opacity * 255;
updateCachedVertices(node, comp.renderData!, tempColor);
},
appendQuad (comp: Label, spriteFrame: SpriteFrame, rect: Rect, rotated: boolean, x: number, y: number, scale: number) {
const renderData = comp.renderData;
if (!renderData) {
+11 -1
View File
@@ -31,7 +31,7 @@
import { addon } from '../../../core/utils/js';
import { IBatcher } from '../../renderer/i-batcher';
import { Label } from '../../components/label';
import { fillMeshVertices3D } from '../utils';
import { fillMeshVertices3D, updateCachedVertices } from '../utils';
import { bmfont } from './bmfont';
import { letterFont } from './letter-font';
import { Color } from '../../../core/math/color';
@@ -57,6 +57,16 @@ export const letter = {
fillMeshVertices3D(node, renderer, comp.renderData, WHITE);
},
fillCacheBuffer (comp: Label) {
if (!comp.renderData) {
return;
}
const node = comp.node;
WHITE.a = node._uiProps.opacity * 255;
updateCachedVertices(node, comp.renderData, WHITE);
},
appendQuad: bmfont.appendQuad,
};
+46
View File
@@ -79,6 +79,8 @@ export const ttf: IAssembler = {
vertexOffset = 0;
}
renderData.cacheBuffer = buffer;
renderData.bufferOffset = vertexOffset;
// buffer data may be reallocated, need get reference after request.
const vBuf = buffer.vData!;
const iBuf = buffer.iData!;
@@ -124,6 +126,50 @@ export const ttf: IAssembler = {
iBuf[indicesOffset++] = vertexId + 3;
},
fillCacheBuffer (comp: Label) {
const renderData = comp.renderData!;
const dataList: IRenderData[] = renderData.data;
const node = comp.node;
const buffer = renderData.cacheBuffer!;
const vertexOffset = renderData.bufferOffset;
const vBuf = buffer.vData!;
const vData = renderData.vData!;
const data0 = dataList[0];
const data3 = dataList[3];
/* */
node.updateWorldTransform();
// @ts-expect-error private property access
const pos = node._pos; const rot = node._rot; const scale = node._scale;
const ax = data0.x * scale.x; const bx = data3.x * scale.x;
const ay = data0.y * scale.y; const by = data3.y * scale.y;
const qx = rot.x; const qy = rot.y; const qz = rot.z; const qw = rot.w;
const qxy = qx * qy; const qzw = qz * qw;
const qxy2 = qx * qx - qy * qy;
const qzw2 = qw * qw - qz * qz;
const cx1 = qzw2 + qxy2;
const cx2 = (qxy - qzw) * 2;
const cy1 = qzw2 - qxy2;
const cy2 = (qxy + qzw) * 2;
const x = pos.x; const y = pos.y;
// left bottom
vData[0] = cx1 * ax + cx2 * ay + x;
vData[1] = cy1 * ay + cy2 * ax + y;
// right bottom
vData[9] = cx1 * bx + cx2 * ay + x;
vData[10] = cy1 * ay + cy2 * bx + y;
// left top
vData[18] = cx1 * ax + cx2 * by + x;
vData[19] = cy1 * by + cy2 * ax + y;
// right top
vData[27] = cx1 * bx + cx2 * by + x;
vData[28] = cy1 * by + cy2 * bx + y;
vBuf.set(vData, vertexOffset);
buffer.setDirty();
},
updateVertexData (comp: Label) {
const renderData = comp.renderData;
if (!renderData) {
+1 -3
View File
@@ -352,9 +352,7 @@ export const ttfUtils = {
_texture.rect = new Rect(0, 0, _canvas.width, _canvas.height);
_texture._calculateUV();
}
if (comp.renderData) {
comp.renderData.textureDirty = true;
}
comp.setTextureDirty();
if (legacyCC.director.root && legacyCC.director.root.batcher2D) {
legacyCC.director.root.batcher2D._releaseDescriptorSetCache(tex.getHash());
}
+29
View File
@@ -34,6 +34,7 @@ import { Mask, MaskType } from '../../components/mask';
import { IAssembler, IAssemblerManager } from '../../renderer/base';
import { StencilManager } from '../../renderer/stencil-manager';
import { simple } from '../sprite';
import { legacyCC } from '../../../core/global-exports';
const _stencilManager = StencilManager.sharedManager!;
@@ -53,6 +54,17 @@ function applyAreaMask (mask: Mask, renderer: IBatcher) {
}
}
function updateMaskForCacheBuffer (mask: Mask, renderer: IBatcher) {
_stencilManager.enterLevel(mask);
if (mask.type === MaskType.IMAGE_STENCIL) {
simple.fillCacheBuffer(mask);
const mat = mask.graphics!.getMaterialInstance(0)!;
renderer.forceMergeBatches(mat, mask.spriteFrame, mask.graphics!);
} else {
mask.graphics!.updateAssembler(renderer);
}
}
export const maskAssembler: IAssembler = {
createData (mask: Mask) {
const renderData = mask.requestRenderData();
@@ -82,12 +94,29 @@ export const maskAssembler: IAssembler = {
_stencilManager.enableMask();
}
},
fillCacheBuffer (mask: Mask) {
if (mask.type !== MaskType.IMAGE_STENCIL || mask.spriteFrame) {
const renderer = legacyCC.director.root!.batcher2D;
_stencilManager.pushMask(mask);
renderer.finishMergeBatches();
applyClearMask(mask, renderer);
updateMaskForCacheBuffer(mask, renderer);
_stencilManager.enableMask();
}
},
};
export const maskEndAssembler: IAssembler = {
fillBuffers (mask: Mask, ui: IBatcher) {
_stencilManager.exitMask();
},
fillCacheBuffer (mask: Mask) {
_stencilManager.exitMask();
},
};
const StartAssembler: IAssemblerManager = {
+11 -1
View File
@@ -33,7 +33,7 @@ import { IRenderData, RenderData } from '../../renderer/render-data';
import { IBatcher } from '../../renderer/i-batcher';
import { Sprite } from '../../components';
import { IAssembler } from '../../renderer/base';
import { fillVerticesWithoutCalc3D } from '../utils';
import { fillVerticesWithoutCalc3D, updateCachedVerticesWithoutCalc3D } from '../utils';
import { errorID } from '../../../core/platform/debug';
import { dynamicAtlasManager } from '../../utils/dynamic-atlas/atlas-manager';
@@ -266,6 +266,16 @@ export const barFilled: IAssembler = {
fillVerticesWithoutCalc3D(node, renderer, sprite.renderData!, tempColor);
},
fillCacheBuffer (sprite: Sprite) {
if (sprite.node.hasChangedFlags) {
this.updateWorldVertexData(sprite);
}
const node = sprite.node;
tempColor.set(sprite.color);
tempColor.a = node._uiProps.opacity * 255;
updateCachedVerticesWithoutCalc3D(node, sprite.renderData!, tempColor);
},
updateColor (sprite: Sprite) {
},
};
+9 -1
View File
@@ -34,7 +34,7 @@ import { IRenderData, RenderData } from '../../renderer/render-data';
import { IBatcher } from '../../renderer/i-batcher';
import { Sprite } from '../../components';
import { IAssembler } from '../../renderer/base';
import { fillVertices3D } from '../utils';
import { fillVertices3D, updateCachedVertices } from '../utils';
import { dynamicAtlasManager } from '../../utils/dynamic-atlas/atlas-manager';
const PI_2 = Math.PI * 2;
@@ -372,6 +372,14 @@ export const radialFilled: IAssembler = {
fillVertices3D(node, renderer, renderData, tempColor);
},
fillCacheBuffer (comp: Sprite) {
const node = comp.node;
const renderData: RenderData = comp.renderData!;
tempColor.set(comp.color);
tempColor.a = node._uiProps.opacity * 255;
updateCachedVertices(node, renderData, tempColor);
},
updateColor (sprite: Sprite) {
},
};
+19
View File
@@ -186,6 +186,9 @@ export const simple: IAssembler = {
const iBuf = buffer.iData!;
vBuf.set(vData, vertexOffset);
const renderData = sprite.renderData!;
renderData.cacheBuffer = buffer;
renderData.bufferOffset = vertexOffset;
const index0 = vertexId; const index1 = vertexId + 1;
const index2 = vertexId + 2; const index3 = vertexId + 3;
@@ -199,6 +202,22 @@ export const simple: IAssembler = {
iBuf[indicesOffset++] = index3;
},
fillCacheBuffer (sprite: Sprite) {
if (sprite === null) {
return;
}
const renderData = sprite.renderData!;
const vData = renderData.vData!;
if (sprite.node.hasChangedFlags) {
this.updateWorldVerts(sprite, vData);
}
const meshBuffer = renderData.cacheBuffer!;
const vBuf = meshBuffer.vData!;
vBuf.set(vData, renderData.bufferOffset);
meshBuffer.setDirty();
},
updateVertexData (sprite: Sprite) {
const renderData: RenderData | null = sprite.renderData;
if (!renderData) {
+32
View File
@@ -145,6 +145,9 @@ export const sliced: IAssembler = {
vertexId = 0;
}
renderData!.cacheBuffer = buffer;
renderData!.bufferOffset = vertexOffset;
// buffer data may be realloc, need get reference after request.
const vBuf: Float32Array|null = buffer.vData;
// const uintbuf = buffer._uintVData,
@@ -177,6 +180,35 @@ export const sliced: IAssembler = {
}
},
fillCacheBuffer (sprite: Sprite) {
if (sprite === null) {
return;
}
if (sprite.node.hasChangedFlags) {
this.updateWorldVertexData(sprite);
}
const renderData = sprite.renderData!;
const dataList: IRenderData[] = renderData.data;
const uvSliced: IUV[] = sprite.spriteFrame!.uvSliced;
const meshBuffer = renderData.cacheBuffer!;
const vBuf: Float32Array|null = meshBuffer.vData;
let vertexOffset = renderData.bufferOffset;
for (let i = 4; i < 20; ++i) {
const vert = dataList[i];
const uvs = uvSliced[i - 4];
vBuf![vertexOffset++] = vert.x;
vBuf![vertexOffset++] = vert.y;
vBuf![vertexOffset++] = vert.z;
vBuf![vertexOffset++] = uvs.u;
vBuf![vertexOffset++] = uvs.v;
Color.toArray(vBuf!, dataList[i].color, vertexOffset);
vertexOffset += 4;
// uintbuf[vertexOffset++] = color;
}
meshBuffer.setDirty();
},
updateWorldVertexData (sprite: Sprite) {
const node = sprite.node;
const dataList: IRenderData[] = sprite.renderData!.data;
+154
View File
@@ -145,6 +145,9 @@ export const tiled: IAssembler = {
const matrix = node.worldMatrix;
renderData.cacheBuffer = buffer;
renderData.bufferOffset = vertexOffset;
const datalist = renderData.data;
this.fillVertices(vBuf, vertexOffset, matrix, row, col, datalist);
@@ -270,6 +273,157 @@ export const tiled: IAssembler = {
}
},
fillCacheBuffer (sprite: Sprite) {
const node = sprite.node;
const uiTrans = sprite.node._uiProps.uiTransformComp!;
const contentWidth = Math.abs(uiTrans.width);
const contentHeight = Math.abs(uiTrans.height);
const renderData = sprite.renderData!;
// buffer
const buffer = renderData.cacheBuffer;
// buffer data may be realloc, need get reference after request.
let vertexOffset = renderData.bufferOffset;
buffer!.setDirty();
const vBuf = buffer!.vData!;
const frame = sprite.spriteFrame!;
const rotated = frame.isRotated();
const uv = frame.uv;
const uvSliced: IUV[] = sprite.spriteFrame!.uvSliced;
const rect = frame.getRect();
const leftWidth = frame.insetLeft;
const rightWidth = frame.insetRight;
const centerWidth = rect.width - leftWidth - rightWidth;
const topHeight = frame.insetTop;
const bottomHeight = frame.insetBottom;
const centerHeight = rect.height - topHeight - bottomHeight;
let sizableWidth = contentWidth - leftWidth - rightWidth;
let sizableHeight = contentHeight - topHeight - bottomHeight;
sizableWidth = sizableWidth > 0 ? sizableWidth : 0;
sizableHeight = sizableHeight > 0 ? sizableHeight : 0;
const hRepeat = centerWidth === 0 ? sizableWidth : sizableWidth / centerWidth;
const vRepeat = centerHeight === 0 ? sizableHeight : sizableHeight / centerHeight;
const row = Math.ceil(vRepeat + 2);
const col = Math.ceil(hRepeat + 2);
const matrix = node.worldMatrix;
const datalist = renderData.data;
this.fillVertices(vBuf, vertexOffset, matrix, row, col, datalist);
const offset = _perVertexLength;
const offset1 = offset; const offset2 = offset * 2; const offset3 = offset * 3; const offset4 = offset * 4;
let coefU = 0; let coefV = 0;
const tempXVerts :any = [];
const tempYVerts :any = [];
for (let yIndex = 0, yLength = row; yIndex < yLength; ++yIndex) {
if (sizableHeight > centerHeight) {
if (sizableHeight >= yIndex * centerHeight) {
coefV = 1;
} else {
coefV = vRepeat % 1;
}
} else {
coefV = vRepeat;
}
for (let xIndex = 0, xLength = col; xIndex < xLength; ++xIndex) {
if (sizableWidth > centerWidth) {
if (sizableWidth >= xIndex * centerWidth) {
coefU = 1;
} else {
coefU = hRepeat % 1;
}
} else {
coefU = hRepeat;
}
const vertexOffsetU = vertexOffset + 3;
const vertexOffsetV = vertexOffsetU + 1;
// UV
if (rotated) {
if (yIndex === 0) {
tempXVerts[0] = uvSliced[0].u;
tempXVerts[1] = uvSliced[0].u;
tempXVerts[2] = uvSliced[4].u + (uvSliced[8].u - uvSliced[4].u) * coefV;
} else if (yIndex < (row - 1)) {
tempXVerts[0] = uvSliced[4].u;
tempXVerts[1] = uvSliced[4].u;
tempXVerts[2] = uvSliced[4].u + (uvSliced[8].u - uvSliced[4].u) * coefV;
} else if (yIndex === (row - 1)) {
tempXVerts[0] = uvSliced[8].u;
tempXVerts[1] = uvSliced[8].u;
tempXVerts[2] = uvSliced[12].u;
}
if (xIndex === 0) {
tempYVerts[0] = uvSliced[0].v;
tempYVerts[1] = uvSliced[1].v + (uvSliced[2].v - uvSliced[1].v) * coefU;
tempYVerts[2] = uvSliced[0].v;
} else if (xIndex < (col - 1)) {
tempYVerts[0] = uvSliced[1].v;
tempYVerts[1] = uvSliced[1].v + (uvSliced[2].v - uvSliced[1].v) * coefU;
tempYVerts[2] = uvSliced[1].v;
} else if (xIndex === (col - 1)) {
tempYVerts[0] = uvSliced[2].v;
tempYVerts[1] = uvSliced[3].v;
tempYVerts[2] = uvSliced[2].v;
}
tempXVerts[3] = tempXVerts[2];
tempYVerts[3] = tempYVerts[1];
} else {
if (xIndex === 0) {
tempXVerts[0] = uvSliced[0].u;
tempXVerts[1] = uvSliced[1].u + (uvSliced[2].u - uvSliced[1].u) * coefU;
tempXVerts[2] = uv[0];
} else if (xIndex < (col - 1)) {
tempXVerts[0] = uvSliced[1].u;
tempXVerts[1] = uvSliced[1].u + (uvSliced[2].u - uvSliced[1].u) * coefU;
tempXVerts[2] = uvSliced[1].u;
} else if (xIndex === (col - 1)) {
tempXVerts[0] = uvSliced[2].u;
tempXVerts[1] = uvSliced[3].u;
tempXVerts[2] = uvSliced[2].u;
}
if (yIndex === 0) {
tempYVerts[0] = uvSliced[0].v;
tempYVerts[1] = uvSliced[0].v;
tempYVerts[2] = uvSliced[4].v + (uvSliced[8].v - uvSliced[4].v) * coefV;
} else if (yIndex < (row - 1)) {
tempYVerts[0] = uvSliced[4].v;
tempYVerts[1] = uvSliced[4].v;
tempYVerts[2] = uvSliced[4].v + (uvSliced[8].v - uvSliced[4].v) * coefV;
} else if (yIndex === (row - 1)) {
tempYVerts[0] = uvSliced[8].v;
tempYVerts[1] = uvSliced[8].v;
tempYVerts[2] = uvSliced[12].v;
}
tempXVerts[3] = tempXVerts[1];
tempYVerts[3] = tempYVerts[2];
}
// lb
vBuf[vertexOffsetU] = tempXVerts[0];
vBuf[vertexOffsetV] = tempYVerts[0];
// rb
vBuf[vertexOffsetU + offset1] = tempXVerts[1];
vBuf[vertexOffsetV + offset1] = tempYVerts[1];
// lt
vBuf[vertexOffsetU + offset2] = tempXVerts[2];
vBuf[vertexOffsetV + offset2] = tempYVerts[2];
// rt
vBuf[vertexOffsetU + offset3] = tempXVerts[3];
vBuf[vertexOffsetV + offset3] = tempYVerts[3];
// color
// Hack: the color is same
Color.toArray(vBuf, datalist[0].color, vertexOffsetV + 1);
Color.toArray(vBuf, datalist[0].color, vertexOffsetV + offset1 + 1);
Color.toArray(vBuf, datalist[0].color, vertexOffsetV + offset2 + 1);
Color.toArray(vBuf, datalist[0].color, vertexOffsetV + offset3 + 1);
vertexOffset += offset4;
}
}
},
fillVertices (vBuf: Float32Array, vertexOffset: number, matrix: Mat4, row: number, col: number, dataList: IRenderData[]) {
let x = 0; let x1 = 0; let y = 0; let y1 = 0;
for (let yIndex = 0, yLength = row; yIndex < yLength; ++yIndex) {
+52
View File
@@ -52,6 +52,8 @@ export function fillVertices3D (node: Node, renderer: IBatcher, renderData: Rend
vertexId = 0;
}
renderData.cacheBuffer = buffer;
renderData.bufferOffset = vertexOffset;
// buffer data may be realloc, need get reference after request.
const vBuf = buffer.vData!;
@@ -77,6 +79,31 @@ export function fillVertices3D (node: Node, renderer: IBatcher, renderData: Rend
}
}
export function updateCachedVertices (node: Node, renderData: RenderData, color: Color) {
const dataList = renderData.data;
const buffer = renderData.cacheBuffer!;
let vertexOffset = renderData.bufferOffset;
const vertexCount = renderData.vertexCount;
const vBuf = buffer.vData!;
node.getWorldMatrix(_worldMatrix);
for (let i = 0; i < vertexCount; i++) {
const vert = dataList[i];
Vec3.set(vec3_temp, vert.x, vert.y, 0);
Vec3.transformMat4(vec3_temp, vec3_temp, _worldMatrix);
vBuf[vertexOffset++] = vec3_temp.x;
vBuf[vertexOffset++] = vec3_temp.y;
vBuf[vertexOffset++] = vec3_temp.z;
vBuf[vertexOffset++] = vert.u;
vBuf[vertexOffset++] = vert.v;
Color.toArray(vBuf, color, vertexOffset);
vertexOffset += 4;
}
buffer.setDirty();
}
export function fillMeshVertices3D (node: Node, renderer: IBatcher, renderData: RenderData, color: Color) {
const dataList = renderData.data;
let buffer = renderer.acquireBufferBatch()!;
@@ -94,6 +121,8 @@ export function fillMeshVertices3D (node: Node, renderer: IBatcher, renderData:
vertexId = 0;
}
renderData.cacheBuffer = buffer;
renderData.bufferOffset = vertexOffset;
// buffer data may be realloc, need get reference after request.
const vBuf = buffer.vData!;
const iBuf = buffer.iData!;
@@ -142,6 +171,8 @@ export function fillVerticesWithoutCalc3D (node: Node, renderer: IBatcher, rende
vertexId = 0;
}
renderData.cacheBuffer = buffer;
renderData.bufferOffset = vertexOffset;
// buffer data may be realloc, need get reference after request.
const vBuf = buffer.vData!;
@@ -165,3 +196,24 @@ export function fillVerticesWithoutCalc3D (node: Node, renderer: IBatcher, rende
iBuf![indicesOffset++] = vertexId + 3;
iBuf![indicesOffset++] = vertexId + 2;
}
export function updateCachedVerticesWithoutCalc3D (node: Node, renderData: RenderData, color: Color) {
const dataList = renderData.data;
const buffer = renderData.cacheBuffer!;
let vertexOffset = renderData.bufferOffset;
const vertexCount = renderData.vertexCount;
const vBuf = buffer.vData!;
for (let i = 0; i < vertexCount; i++) {
const vert = dataList[i];
vBuf[vertexOffset++] = vert.x;
vBuf[vertexOffset++] = vert.y;
vBuf[vertexOffset++] = vert.z;
vBuf[vertexOffset++] = vert.u;
vBuf[vertexOffset++] = vert.v;
Color.toArray(vBuf, color, vertexOffset);
vertexOffset += 4;
}
buffer.setDirty();
}
+2
View File
@@ -546,6 +546,7 @@ export class Graphics extends Renderable2D {
this._isDrawing = true;
this._isNeedUploadData = true;
director.root!.batcher2D._reloadBatch();
(this._assembler as IAssembler).stroke!(this);
}
@@ -563,6 +564,7 @@ export class Graphics extends Renderable2D {
this._isDrawing = true;
this._isNeedUploadData = true;
director.root!.batcher2D._reloadBatch();
(this._assembler as IAssembler).fill!(this);
}
+7 -3
View File
@@ -40,6 +40,7 @@ import { CanvasPool, ISharedLabelData, LetterRenderTexture } from '../assembler/
import { InstanceMaterialType, Renderable2D } from '../framework/renderable-2d';
import { TextureBase } from '../../core/assets/texture-base';
import { PixelFormat } from '../../core/assets/asset-enum';
import { director } from '../../core/director';
/**
* @en Enum for horizontal text alignment.
@@ -765,6 +766,11 @@ export class Label extends Renderable2D {
}
}
public markForUpdateRenderData (enable = true) {
super.markForUpdateRenderData(enable);
director.root!.batcher2D._reloadBatch();
}
protected _render (render: IBatcher) {
render.commitComp(this, this._texture, this._assembler!, null);
}
@@ -820,9 +826,7 @@ export class Label extends Renderable2D {
const spriteFrame = font.spriteFrame;
if (spriteFrame && spriteFrame.texture) {
this._texture = spriteFrame;
if (this.renderData) {
this.renderData.textureDirty = true;
}
this.setTextureDirty();
this.changeMaterialForDefine();
if (this._assembler) {
this._assembler.updateRenderData(this);
+3 -2
View File
@@ -378,6 +378,7 @@ export class Mask extends Renderable2D {
super.updateMaterial();
this._updateGraphics();
this._renderFlag = this._canRender();
director.root!.batcher2D._reloadBatch();
}
public onDisable () {
@@ -438,7 +439,7 @@ export class Mask extends Renderable2D {
}
protected _render (render: IBatcher) {
render.commitComp(this, null, this._assembler!, null);
render.commitPlainComp(this, null, this._assembler!, null);
}
protected _postRender (render: IBatcher) {
@@ -446,7 +447,7 @@ export class Mask extends Renderable2D {
return;
}
render.commitComp(this, null, this._postAssembler, null);
render.commitPlainComp(this, null, this._postAssembler, null);
}
protected _nodeStateChange (type: TransformBit) {
+10 -1
View File
@@ -273,6 +273,7 @@ export class Sprite extends Renderable2D {
if (this._type !== value) {
this._type = value;
this._flushAssembler();
director.root!.batcher2D._reloadBatch();
}
}
@@ -575,6 +576,14 @@ export class Sprite extends Renderable2D {
this.spriteFrame = sprite;
}
public markForUpdateRenderData (enable = true) {
super.markForUpdateRenderData(enable);
// cause these type may change vertex count
if (this._type === SpriteType.TILED || (this._type === SpriteType.FILLED && this._fillType === FillType.RADIAL)) {
director.root!.batcher2D._reloadBatch();
}
}
public changeMaterialForDefine () {
let texture;
const lastInstanceMaterialType = this._instanceMaterialType;
@@ -728,7 +737,7 @@ export class Sprite extends Renderable2D {
textureChanged = true;
}
if (textureChanged) {
if (this._renderData) this._renderData.textureDirty = true;
this.setTextureDirty();
this.changeMaterialForDefine();
}
this._applySpriteSize();
+38 -10
View File
@@ -170,7 +170,7 @@ export class Renderable2D extends RenderableComponent {
if (this._renderData) {
this._renderData.material = this._customMaterial;
this.markForUpdateRenderData();
this._renderData.passDirty = true;
this.setPassDirty();
}
this._blendHash = -1; // a flag to check merge
if (UI_GPU_DRIVEN) {
@@ -257,6 +257,8 @@ export class Renderable2D extends RenderableComponent {
protected _renderData: RenderData | null = null;
protected _renderDataFlag = true;
protected _renderFlag = true;
protected _renderFlagCache = true;
public _renderDataDirty = true;
// 特殊渲染节点,给一些不在节点树上的组件做依赖渲染(例如 mask 组件内置两个 graphics 来渲染)
protected _delegateSrc: Node | null = null;
protected _instanceMaterialType = -1;
@@ -298,18 +300,25 @@ export class Renderable2D extends RenderableComponent {
this.node.on(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this);
this.updateMaterial();
this._renderFlag = this._canRender();
this._renderFlagCache = this._renderFlag;
director.root!.batcher2D._reloadBatch();
}
// For Redo, Undo
public onRestore () {
this.updateMaterial();
this._renderFlag = this._canRender();
this._renderFlagCache = this._renderFlag;
director.root!.batcher2D._reloadBatch();
}
public onDisable () {
this.node.off(NodeEventType.ANCHOR_CHANGED, this._nodeStateChange, this);
this.node.off(NodeEventType.SIZE_CHANGED, this._nodeStateChange, this);
this.getRenderMaterial(0)!.off('setProperty', this._onPropertyChange);
this._renderFlag = false;
this._renderFlagCache = this._renderFlag;
director.root!.batcher2D._reloadBatch();
}
public onDestroy () {
@@ -345,6 +354,10 @@ export class Renderable2D extends RenderableComponent {
} else if (!enable) {
this._renderDataFlag = enable;
}
if (this._renderFlag !== this._renderFlagCache) {
director.root!.batcher2D._reloadBatch();
this._renderFlagCache = this._renderFlag;
}
}
/**
@@ -409,6 +422,7 @@ export class Renderable2D extends RenderableComponent {
if (this._renderDataFlag) {
this._assembler!.updateRenderData!(this);
this._renderDataFlag = false;
this._renderDataDirty = true;
}
}
@@ -416,8 +430,7 @@ export class Renderable2D extends RenderableComponent {
return this.isValid
&& this.getMaterial(0) !== null
&& this.enabled
&& (this._delegateSrc ? this._delegateSrc.activeInHierarchy : this.enabledInHierarchy)
&& this.node._uiProps.opacity > 0;
&& (this._delegateSrc ? this._delegateSrc.activeInHierarchy : this.enabledInHierarchy);
}
protected _postCanRender () {}
@@ -425,17 +438,15 @@ export class Renderable2D extends RenderableComponent {
protected _updateColor () {
if (UI_GPU_DRIVEN && this._canDrawByFourVertex) {
if (this._colorDirty) {
this._renderFlag = this._canRender();
this._colorDirty = false;
}
return;
}
// Need update rendFlag when opacity changes from 0 to !0
if (this._colorDirty && this._assembler && this._assembler.updateColor) {
this._assembler.updateColor(this);
// Need update rendFlag when opacity changes from 0 to !0 or 0 to !0
this._renderFlag = this._canRender();
this._colorDirty = false;
this._renderDataDirty = true;
}
}
@@ -455,9 +466,7 @@ export class Renderable2D extends RenderableComponent {
target.blendDstAlpha = BlendFactor.ONE_MINUS_SRC_ALPHA;
target.blendDst = this._dstBlendFactor;
target.blendSrc = this._srcBlendFactor;
if (this.renderData) {
this.renderData.passDirty = true;
}
this.setPassDirty();
}
this.updateBlendHash();
}
@@ -482,11 +491,17 @@ export class Renderable2D extends RenderableComponent {
}
protected _onMaterialModified (idx: number, material: Material | null) {
if (this._customMaterial) {
this._customMaterial.off('setProperty', this._onPropertyChange);
}
if (this._renderData) {
this.markForUpdateRenderData();
this._renderData.passDirty = true;
this.setPassDirty();
}
super._onMaterialModified(idx, material);
if (this._customMaterial) {
this.getRenderMaterial(0)!.on('setProperty', this._onPropertyChange);
}
}
// macro.UI_GPU_DRIVEN
@@ -521,16 +536,29 @@ export class Renderable2D extends RenderableComponent {
protected _flushAssembler? (): void;
public setNodeDirty () {
director.root!.batcher2D._reloadBatch();
if (this.renderData) {
this.renderData.nodeDirty = true;
}
}
public setTextureDirty () {
director.root!.batcher2D._reloadBatch();
if (this.renderData) {
this.renderData.textureDirty = true;
}
}
public setPassDirty () {
director.root!.batcher2D._reloadBatch();
if (this.renderData) {
this.renderData.passDirty = true;
}
}
protected _onPropertyChange () {
director.root!.batcher2D._reloadBatch();
}
}
legacyCC.internal.Renderable2D = Renderable2D;
+84 -33
View File
@@ -26,7 +26,7 @@
* @packageDocumentation
* @hidden
*/
import { JSB } from 'internal:constants';
import { DEBUG, JSB } from 'internal:constants';
import { Camera, Model } from 'cocos/core/renderer/scene';
import { UIStaticBatch } from '../components';
import { Material } from '../../core/assets/material';
@@ -49,6 +49,7 @@ import { TextureBase } from '../../core/assets/texture-base';
import { sys } from '../../core/platform/sys';
import { Mat4 } from '../../core/math';
import { IBatcher } from './i-batcher';
import { warnID } from '../../core';
const _dsInfo = new DescriptorSetInfo(null!);
const m4_1 = new Mat4();
@@ -151,12 +152,13 @@ export class Batcher2D implements IBatcher {
private _currTransform: Node | null = null;
private _currTextureHash = 0;
private _currSamplerHash = 0;
private _currBlendTargetHash = 0;
private _currLayer = 0;
private _currDepthStencilStateStage: any | null = null;
private _currIsStatic = false;
private _currHash = 0;
private _reloadBatchDirty: boolean;
// DescriptorSet Cache Map
private _descriptorSetCache = new DescriptorSetCache();
@@ -164,6 +166,7 @@ export class Batcher2D implements IBatcher {
this.device = _root.device;
this._batches = new CachedArray(64);
this._drawBatchPool = new Pool(() => new DrawBatch2D(), 128, (obj) => obj.destroy(this));
this._reloadBatchDirty = true;
}
public initialize () {
@@ -244,6 +247,15 @@ export class Batcher2D implements IBatcher {
public update () {
const screens = this._screens;
for (let i = 0; i < screens.length; ++i) {
const screen = screens[i].node;
if (screen.hasChildTreeUpdated()) {
this._reloadBatch();
}
}
if (this._reloadBatchDirty) {
this.resetWithReload();
}
for (let i = 0; i < screens.length; ++i) {
const screen = screens[i];
if (!screen.enabledInHierarchy) {
@@ -279,7 +291,6 @@ export class Batcher2D implements IBatcher {
buffers.forEach((value, key) => {
value.forEach((bb) => {
bb.uploadBuffers();
bb.reset();
});
});
@@ -292,10 +303,35 @@ export class Batcher2D implements IBatcher {
});
this._descriptorSetCache.update();
// upload
this._reloadBatchDirty = false;
}
}
public reset () {
this._currHash = 0;
this._currLayer = 0;
this._currMaterial = this._emptyMaterial;
this._currTexture = null;
this._currSampler = null;
this._currComponent = null;
this._currTransform = null;
this._currScene = null;
this._currMeshBuffer = null;
StencilManager.sharedManager!.reset();
this._descriptorSetCache.reset();
}
private resetWithReload () {
if (this._batches.length > 0) {
const buffers = this._meshBuffers;
buffers.forEach((value, key) => {
value.forEach((bb) => {
bb.reset();
});
});
}
for (let i = 0; i < this._batches.length; ++i) {
const batch = this._batches.array[i];
if (batch.isStatic) {
@@ -307,19 +343,8 @@ export class Batcher2D implements IBatcher {
this._drawBatchPool.free(batch);
}
this._currHash = 0;
this._currLayer = 0;
this._currMaterial = this._emptyMaterial;
this._currTexture = null;
this._currSampler = null;
this._currComponent = null;
this._currTransform = null;
this._currScene = null;
this._currMeshBuffer = null;
this._meshBufferUseCount.clear();
this._batches.clear();
StencilManager.sharedManager!.reset();
this._descriptorSetCache.reset();
}
/**
@@ -337,27 +362,28 @@ export class Batcher2D implements IBatcher {
* @param assembler - 当前组件渲染数据组装器。
*/
public commitComp (comp: Renderable2D, frame: TextureBase | SpriteFrame | null, assembler: any, transform: Node | null) {
const renderComp = comp;
const renderData = comp.renderData;
let dataHash = 0;
let mat;
if (renderData) {
dataHash = renderData.dataHash;
mat = renderData.material;
if (DEBUG) {
if (!comp.renderData) {
this.commitPlainComp(comp, frame, assembler, transform);
warnID(14200);
}
}
renderComp.stencilStage = StencilManager.sharedManager!.stage;
const depthStencilStateStage = renderComp.stencilStage;
if (this._reloadBatchDirty) {
const renderComp = comp;
const renderData = comp.renderData!;
const dataHash = renderData.dataHash;
const mat = renderData.material;
renderComp.stencilStage = StencilManager.sharedManager!.stage;
const depthStencilStateStage = renderComp.stencilStage;
if (this._currHash !== dataHash || dataHash === 0 || this._currMaterial !== mat
if (this._currHash !== dataHash || this._currMaterial !== mat
|| this._currDepthStencilStateStage !== depthStencilStateStage) {
this.autoMergeBatches(this._currComponent!);
if (renderData) {
this.autoMergeBatches(this._currComponent!);
this._currHash = renderData.dataHash;
this._currScene = renderData.renderScene;
this._currComponent = renderComp;
this._currTransform = transform;
this._currMaterial = renderData.material!;
this._currBlendTargetHash = renderData.blendHash;
this._currDepthStencilStateStage = depthStencilStateStage;
this._currLayer = renderData.layer;
const frame = renderData.frame;
@@ -372,14 +398,32 @@ export class Batcher2D implements IBatcher {
this._currTextureHash = 0;
this._currSamplerHash = 0;
}
} else {
// for Mask & spine
}
assembler.fillBuffers(renderComp, this);
} else if (comp.node.hasChangedFlags || comp._renderDataDirty) {
assembler.fillCacheBuffer(comp, this);
comp._renderDataDirty = false;
}
}
public commitPlainComp (comp: Renderable2D, frame: TextureBase | SpriteFrame | null, assembler: any, transform: Node | null) {
if (this._reloadBatchDirty) {
const renderComp = comp;
const dataHash = 0;
let mat;
renderComp.stencilStage = StencilManager.sharedManager!.stage;
const depthStencilStateStage = renderComp.stencilStage;
if (this._currHash !== dataHash || this._currMaterial !== mat
|| this._currDepthStencilStateStage !== depthStencilStateStage) {
this.autoMergeBatches(this._currComponent!);
// for Mask & middleware & Particle2D
this._currHash = dataHash;
this._currScene = renderComp._getRenderScene();
this._currComponent = renderComp;
this._currTransform = transform;
this._currMaterial = renderComp.getRenderMaterial(0)!;
this._currBlendTargetHash = renderComp.blendHash;
this._currDepthStencilStateStage = depthStencilStateStage;
this._currLayer = renderComp.node.layer;
if (frame) {
@@ -394,10 +438,11 @@ export class Batcher2D implements IBatcher {
this._currSamplerHash = 0;
}
}
}
if (assembler) {
assembler.fillBuffers(renderComp, this);
} else if (comp.node.hasChangedFlags || comp._renderDataDirty) {
assembler.fillCacheBuffer(comp, this);
comp._renderDataDirty = false;
}
}
@@ -415,6 +460,9 @@ export class Batcher2D implements IBatcher {
* @param mat - 提交渲染的材质。
*/
public commitModel (comp: UIComponent | Renderable2D, model: Model | null, mat: Material | null) {
if (!this._reloadBatchDirty) {
return;
}
// if the last comp is spriteComp, previous comps should be batched.
if (this._currMaterial !== this._emptyMaterial) {
this.autoMergeBatches(this._currComponent!);
@@ -595,7 +643,6 @@ export class Batcher2D implements IBatcher {
}
public walk (node: Node, level = 0) {
const len = node.children.length;
this._preProcess(node);
if (len > 0 && !node._static) {
@@ -691,6 +738,10 @@ export class Batcher2D implements IBatcher {
private _releaseDescriptorSetCache (textureHash: number) {
this._descriptorSetCache.releaseDescriptorSetCache(textureHash);
}
public _reloadBatch () {
this._reloadBatchDirty = true;
}
}
class LocalDescriptorSet {
+2
View File
@@ -37,6 +37,7 @@ export interface IBatcher {
reset ();
commitComp (comp: Renderable2D, frame: TextureBase | SpriteFrame | null, assembler: any, transform: Node | null);
commitPlainComp (comp: Renderable2D, frame: TextureBase | SpriteFrame | null, assembler: any, transform: Node | null);
commitModel (comp: UIComponent | Renderable2D, model: Model | null, mat: Material | null);
commitStaticBatch (comp: UIStaticBatch);
@@ -46,4 +47,5 @@ export interface IBatcher {
flushMaterial (mat: Material);
walk (node: Node, level?: number);
_reloadBatch ();
}
+4
View File
@@ -115,6 +115,10 @@ export class MeshBuffer extends ScalableContainer {
// ----------
}
public setDirty () {
this._dirty = true;
}
public request (vertexCount = 4, indicesCount = 6) {
this.lastByteOffset = this.byteOffset;
const byteOffset = this.byteOffset + vertexCount * this._vertexFormatBytes;
+12 -1
View File
@@ -28,6 +28,7 @@
* @hidden
*/
import { MeshBuffer } from '..';
import { Material } from '../../core/assets/material';
import { TextureBase } from '../../core/assets/texture-base';
import { Color } from '../../core/math';
@@ -36,6 +37,7 @@ import { RenderScene } from '../../core/renderer/scene';
import { murmurhash2_32_gc } from '../../core/utils/murmurhash2_gc';
import { SpriteFrame } from '../assets/sprite-frame';
import { Renderable2D } from '../framework/renderable-2d';
import { DrawBatch2D } from './draw-batch';
export interface IRenderData {
x: number;
@@ -119,6 +121,9 @@ export class RenderData extends BaseRenderData {
public hashDirty = true;
public dataHash = 0;
public cacheBuffer: MeshBuffer | null = null;
public bufferOffset = 0;
public updateNode (comp: Renderable2D) {
this.renderScene = comp.node.scene ? comp._getRenderScene() : null;
this.layer = comp.node.layer;
@@ -156,7 +161,10 @@ export class RenderData extends BaseRenderData {
if (this.nodeDirty) {
this.renderScene = comp.node.scene ? comp._getRenderScene() : null;
this.layer = comp.node.layer;
this.nodeDirty = false;
// Hack for updateRenderData when node not add to scene
if (this.renderScene !== null) {
this.nodeDirty = false;
}
this.hashDirty = true;
}
if (this.textureDirty) {
@@ -229,6 +237,9 @@ export class MeshRenderData extends BaseRenderData {
public lastFilledIndices = 0;
public lastFilledVertex = 0;
public cacheBuffer: MeshBuffer | null = null;
public bufferOffset = 0;
private _formatByte:number;
constructor (vertexFloatCnt = 9) {
+4 -4
View File
@@ -287,6 +287,10 @@ export class Mesh extends Asset {
super();
}
public onLoaded () {
this.initialize();
}
public initialize () {
if (this._initialized) {
return;
@@ -1012,10 +1016,6 @@ export class Mesh extends Asset {
data: globalEmptyMeshBuffer,
});
}
public validate () {
return this.renderingSubMeshes.length > 0 && this.data.byteLength > 0;
}
}
legacyCC.Mesh = Mesh;
+2 -2
View File
@@ -146,7 +146,7 @@ export class BakedSkinningModel extends MorphModel {
}
private _applyNativeJointMedium () {
if (JSB) {
if (JSB && this._nativeObj) {
const boundsInfo: NativeAABB[] = [];
if (this._jointsMedium.boundsInfo) {
this._jointsMedium.boundsInfo.forEach((bound: AABB) => {
@@ -154,7 +154,7 @@ export class BakedSkinningModel extends MorphModel {
});
}
const animInfoKey = 'nativeDirty';
(this._nativeObj! as NativeBakedSkinningModel).setJointMedium(!!this.uploadedAnim, {
(this._nativeObj as NativeBakedSkinningModel).setJointMedium(!!this.uploadedAnim, {
boundsInfo,
jointTextureInfo: this._jointsMedium.jointTextureInfo.buffer,
animInfo: {
@@ -31,12 +31,24 @@ export class AnimationController extends Component {
this._graphEval?.update(deltaTime);
}
public getVariables () {
const { _graphEval: graphEval } = this;
assertIsNonNullable(graphEval);
return graphEval.getVariables();
}
public setValue (name: string, value: Value) {
const { _graphEval: graphEval } = this;
assertIsNonNullable(graphEval);
graphEval.setValue(name, value);
}
public getValue (name: string) {
const { _graphEval: graphEval } = this;
assertIsNonNullable(graphEval);
return graphEval.getValue(name);
}
public getCurrentStateStatus (layer: number) {
const { _graphEval: graphEval } = this;
assertIsNonNullable(graphEval);
@@ -65,6 +65,10 @@ export class AnimationGraphEval {
graphDebugGroupEnd();
}
public getVariables (): Iterable<Readonly<[string, Readonly<{ type: VariableType }>]>> {
return Object.entries(this._varInstances);
}
public getCurrentStateStatus (layer: number): Readonly<MotionStateStatus> | null {
return this._layerEvaluations[layer].getCurrentStateStatus();
}
@@ -9,6 +9,7 @@ import type { MotionStateStatus } from './animation-controller';
export type { AnimationGraphRunTime } from './animation-graph';
export { AnimationController } from './animation-controller';
export type { ClipStatus, TransitionStatus, MotionStateStatus } from './animation-controller';
export { VariableType } from './parametric';
export { StateMachineComponent } from './state-machine-component';
/**
+1
View File
@@ -306,6 +306,7 @@ export class Material extends Asset {
if (!success) {
console.warn(`illegal property name: ${name}.`);
}
this.emit('setProperty');
}
/**
+7 -2
View File
@@ -40,7 +40,7 @@ import { Rect } from '../math';
import * as RF from '../data/utils/requiring-frame';
import { Node } from '../scene-graph';
import { legacyCC } from '../global-exports';
import { errorID, warnID, assertID } from '../platform/debug';
import { errorID, warnID, assertID, error } from '../platform/debug';
import { CompPrefabInfo } from '../utils/prefab/prefab-info';
const idGenerator = new IDGenerator('Comp');
@@ -70,7 +70,12 @@ class Component extends CCObject {
if (trimLeft >= 0) {
className = className.slice(trimLeft + 1);
}
return `${this.node.name}<${className}>`;
if (this.node) {
return `${this.node.name}<${className}>`;
} else {
return className;
}
}
set name (value) {
this._name = value;
+14 -1
View File
@@ -35,7 +35,7 @@ import { _getClassById } from '../utils/js';
import { BUILTIN_CLASSID_RE } from '../utils/misc';
import { Component } from './component';
import { legacyCC } from '../global-exports';
import { warnID } from '../platform/debug';
import { warnID, error } from '../platform/debug';
/**
* @en
@@ -85,3 +85,16 @@ export default class MissingScript extends Component {
}
legacyCC._MissingScript = MissingScript;
// DEBUG: Check MissingScript class for issue 9878
// import { error } from '../platform/debug';
try {
const props = MissingScript.__values__;
if (props.length === 0 || props[props.length - 1] !== '_$erialized') {
error(`The '_$erialized' prop in MissingScript is missing. Please contact jare.`);
error(` Error props: ['${props}']`);
// props.push('_$erialized');
}
} catch (e) {
error(`Error when checking MissingScript 5, ${e}`);
}
+30
View File
@@ -654,6 +654,36 @@ class _Deserializer {
deserialize = klass.__deserialize__ as CompiledDeserializeFn;
} else {
deserialize = compileDeserialize(this, klass);
// DEBUG: Check MissingScript data for issue 9878
try {
if (klass === MissingScript) {
const props: string[] = klass.__values__;
if (props.length === 0 || props[props.length - 1] !== '_$erialized') {
error(`The '_$erialized' prop of MissingScript is missing. Will force the raw data to be save.`);
error(` Error props: ['${props}']. Please contact jare.`);
// props.push('_$erialized');
}
const rawDeserialize: CompiledDeserializeFn = deserialize;
deserialize = function (deserializer: _Deserializer,
object: Record<string, unknown>,
deserialized: Record<string, unknown>,
constructor: AnyFunction) {
try {
if (!JSON.parse(JSON.stringify(deserialized._$erialized))) {
error(`Unable to load previously serialized data. ${JSON.stringify(deserialized)}`);
}
} catch (e) {
error(`Error when checking MissingScript 7, ${e}`);
}
rawDeserialize(deserializer, object, deserialized, constructor);
};
}
} catch (e) {
error(`Error when checking MissingScript 6, ${e}`);
}
js.value(klass, '__deserialize__', deserialize, true);
}
deserialize(this, obj, serialized, klass);
+13 -4
View File
@@ -440,10 +440,19 @@ export class Game extends EventTarget {
}
/**
* @en Pause the game main loop. This will pause:<br>
* game logic execution, rendering process, event manager, background music and all audio effects.<br>
* This is different with `director.pause` which only pause the game logic execution.<br>
* @zh 暂停游戏主循环。包含:游戏逻辑,渲染,事件处理,背景音乐和所有音效。这点和只暂停游戏逻辑的 `director.pause` 不同。
* @en Pause the game main loop. This will pause:
* - game logic execution
* - rendering process
* - input event dispatching (excluding Web and Minigame platforms)
*
* This is different with `director.pause()` which only pause the game logic execution.
*
* @zh 暂停游戏主循环。包含:
* - 游戏逻辑
* - 渲染
* - 输入事件派发(Web 和小游戏平台除外)
*
* 这点和只暂停游戏逻辑的 `director.pause()` 不同。
*/
public pause () {
if (this._paused) { return; }
+2 -3
View File
@@ -97,12 +97,11 @@ export class BloomStage extends RenderStage {
public render (camera: Camera) {
const pipeline = this._pipeline;
pipeline.generateBloomRenderData();
if (!camera.window?.swapchain && !pipeline.macros.CC_PIPELINE_TYPE) {
return;
}
if (!pipeline.bloomEnabled || camera.scene!.batches.length > 0) return;
pipeline.generateBloomRenderData();
if (!pipeline.bloomEnabled || pipeline.pipelineSceneData.renderObjects.length === 0) return;
if (this._bloomUBO.length === 0) {
const passNumber = MAX_BLOOM_FILTER_PASS_NUM * 2 + 2;
+1 -1
View File
@@ -154,9 +154,9 @@ export class ForwardStage extends RenderStage {
}
this._renderQueues.forEach(renderQueueSortFunc);
pipeline.pipelineUBO.updateShadowUBO(camera);
const cmdBuff = pipeline.commandBuffers[0];
pipeline.pipelineUBO.updateShadowUBO(camera);
this._instancedQueue.uploadBuffers(cmdBuff);
this._batchedQueue.uploadBuffers(cmdBuff);
+1 -1
View File
@@ -400,8 +400,8 @@ export class PipelineUBO {
if (mainLight && shadowFrameBufferMap.has(mainLight)) {
ds.bindTexture(UNIFORM_SHADOWMAP_BINDING, shadowFrameBufferMap.get(mainLight)!.colorTextures[0]!);
}
ds.update();
PipelineUBO.updateShadowUBOView(this._pipeline, this._shadowUBO, camera);
ds.update();
cmdBuffer[0].updateBuffer(ds.getBuffer(UBOShadow.BINDING), this._shadowUBO);
}
@@ -55,8 +55,6 @@ export class PlanarShadowQueue {
this._castModels.length = 0;
if (!shadows.enabled || shadows.type !== ShadowType.Planar) { return; }
pipelineUBO.updateShadowUBO(camera);
const scene = camera.scene!;
const frustum = camera.frustum;
const shadowVisible = (camera.visibility & Layers.BitMask.DEFAULT) !== 0;
@@ -191,6 +191,11 @@ export class RenderAdditiveLightQueue {
if (lightPassIdx < 0) { continue; }
const subModel = subModels[j];
const pass = subModel.passes[lightPassIdx];
// object has translucent base pass, prohibiting forward-add pass for multi light sources lighting
const isTransparent = subModel.passes[0].blendState.targets[0].blend;
if (isTransparent) {
continue;
}
subModel.descriptorSet.bindBuffer(UBOForwardLight.BINDING, this._firstLightBufferView);
subModel.descriptorSet.update();
@@ -97,8 +97,6 @@ export class RenderShadowMapBatchedQueue {
const dirShadowObjects = pipelineSceneData.dirShadowObjects;
const castShadowObjects = pipelineSceneData.castShadowObjects;
if (light && shadowInfo.enabled && shadowInfo.type === ShadowType.ShadowMap) {
this._pipeline.pipelineUBO.updateShadowUBOLight(globalDS, light);
switch (light.type) {
case LightType.DIRECTIONAL:
for (let i = 0; i < dirShadowObjects.length; i++) {
@@ -104,6 +104,7 @@ export class ShadowStage extends RenderStage {
const cmdBuff = pipeline.commandBuffers[0];
if (!this._light || !this._shadowFrameBuffer) { return; }
this._pipeline.pipelineUBO.updateShadowUBOLight(descriptorSet, this._light);
this._additiveShadowQueue.gatherLightPasses(descriptorSet, camera, this._light, cmdBuff);
const vp = camera.viewport;
+8 -8
View File
@@ -52,10 +52,10 @@ export type MaterialProperty = number | Vec2 | Vec3 | Vec4 | Color | Mat3 | Mat4
export const type2reader = {
[Type.UNKNOWN]: (a: Float32Array, v: number, idx = 0): void => console.warn('illegal uniform handle'),
[Type.INT]: (a: Float32Array, v: number, idx = 0): number => a[idx],
[Type.INT2]: (a: Float32Array, v: IVec2Like, idx = 0): IVec2Like => Vec2.fromArray(v, a, idx),
[Type.INT3]: (a: Float32Array, v: IVec3Like, idx = 0): IVec3Like => Vec3.fromArray(v, a, idx),
[Type.INT4]: (a: Float32Array, v: IVec4Like, idx = 0): IVec4Like => Vec4.fromArray(v, a, idx),
[Type.INT]: (a: Int32Array, v: number, idx = 0): number => a[idx],
[Type.INT2]: (a: Int32Array, v: IVec2Like, idx = 0): IVec2Like => Vec2.fromArray(v, a, idx),
[Type.INT3]: (a: Int32Array, v: IVec3Like, idx = 0): IVec3Like => Vec3.fromArray(v, a, idx),
[Type.INT4]: (a: Int32Array, v: IVec4Like, idx = 0): IVec4Like => Vec4.fromArray(v, a, idx),
[Type.FLOAT]: (a: Float32Array, v: number, idx = 0): number => a[idx],
[Type.FLOAT2]: (a: Float32Array, v: IVec2Like, idx = 0): IVec2Like => Vec2.fromArray(v, a, idx),
[Type.FLOAT3]: (a: Float32Array, v: IVec3Like, idx = 0): IVec3Like => Vec3.fromArray(v, a, idx),
@@ -66,10 +66,10 @@ export const type2reader = {
export const type2writer = {
[Type.UNKNOWN]: (a: Float32Array, v: number, idx = 0): void => console.warn('illegal uniform handle'),
[Type.INT]: (a: Float32Array, v: number, idx = 0): number => a[idx] = v,
[Type.INT2]: (a: Float32Array, v: IVec2Like, idx = 0): Float32Array => Vec2.toArray(a, v, idx),
[Type.INT3]: (a: Float32Array, v: IVec3Like, idx = 0): Float32Array => Vec3.toArray(a, v, idx),
[Type.INT4]: (a: Float32Array, v: IVec4Like, idx = 0): Float32Array => Vec4.toArray(a, v, idx),
[Type.INT]: (a: Int32Array, v: number, idx = 0): number => a[idx] = v,
[Type.INT2]: (a: Int32Array, v: IVec2Like, idx = 0): Int32Array => Vec2.toArray(a, v, idx),
[Type.INT3]: (a: Int32Array, v: IVec3Like, idx = 0): Int32Array => Vec3.toArray(a, v, idx),
[Type.INT4]: (a: Int32Array, v: IVec4Like, idx = 0): Int32Array => Vec4.toArray(a, v, idx),
[Type.FLOAT]: (a: Float32Array, v: number, idx = 0): number => a[idx] = v,
[Type.FLOAT2]: (a: Float32Array, v: IVec2Like, idx = 0): Float32Array => Vec2.toArray(a, v, idx),
[Type.FLOAT3]: (a: Float32Array, v: IVec3Like, idx = 0): Float32Array => Vec3.toArray(a, v, idx),
+13 -5
View File
@@ -176,6 +176,7 @@ export class Pass {
protected _dynamics: IPassDynamics = {};
protected _propertyHandleMap: Record<string, number> = {};
protected _rootBlock: ArrayBuffer | null = null;
protected _blocksInt: Int32Array[] = [];
protected _blocks: Float32Array[] = [];
protected _shaderInfo: IProgramInfo = null!;
protected _defines: MacroRecord = {};
@@ -278,7 +279,7 @@ export class Pass {
const binding = Pass.getBindingFromHandle(handle);
const type = Pass.getTypeFromHandle(handle);
const ofs = Pass.getOffsetFromHandle(handle);
const block = this._blocks[binding];
const block = this._getBlockView(type, binding);
type2writer[type](block, value, ofs);
this._setRootBufferDirty(true);
}
@@ -293,7 +294,7 @@ export class Pass {
const binding = Pass.getBindingFromHandle(handle);
const type = Pass.getTypeFromHandle(handle);
const ofs = Pass.getOffsetFromHandle(handle);
const block = this._blocks[binding];
const block = this._getBlockView(type, binding);
return type2reader[type](block, out, ofs) as T;
}
@@ -307,7 +308,7 @@ export class Pass {
const binding = Pass.getBindingFromHandle(handle);
const type = Pass.getTypeFromHandle(handle);
const stride = GetTypeSize(type) >> 2;
const block = this._blocks[binding];
const block = this._getBlockView(type, binding);
let ofs = Pass.getOffsetFromHandle(handle);
for (let i = 0; i < value.length; i++, ofs += stride) {
if (value[i] === null) { continue; }
@@ -462,7 +463,7 @@ export class Pass {
const binding = Pass.getBindingFromHandle(handle);
const ofs = Pass.getOffsetFromHandle(handle);
const count = Pass.getCountFromHandle(handle);
const block = this._blocks[binding];
const block = this._getBlockView(type, binding);
const info = this._properties[name];
const givenDefault = info && info.value;
const value = (givenDefault || getDefaultFromType(type)) as number[];
@@ -499,10 +500,10 @@ export class Pass {
public resetUBOs (): void {
for (let i = 0; i < this._shaderInfo.blocks.length; i++) {
const u = this._shaderInfo.blocks[i];
const block = this._blocks[u.binding];
let ofs = 0;
for (let j = 0; j < u.members.length; j++) {
const cur = u.members[j];
const block = this._getBlockView(cur.type, u.binding);
const info = this._properties[cur.name];
const givenDefault = info && info.value;
const value = (givenDefault || getDefaultFromType(cur.type)) as number[];
@@ -695,6 +696,7 @@ export class Pass {
// guarantees these bindings to be consecutive, starting from 0 and non-array-typed
this._blocks[binding] = new Float32Array(this._rootBlock!, _bufferViewInfo.offset,
size / Float32Array.BYTES_PER_ELEMENT);
this._blocksInt[binding] = new Int32Array(this._blocks[binding].buffer);
this._descriptorSet.bindBuffer(binding, bufferView);
}
// store handles
@@ -745,6 +747,10 @@ export class Pass {
}
}
private _getBlockView (type: Type, binding: number) {
return type < Type.FLOAT ? this._blocksInt[binding] : this._blocks[binding];
}
private _setPipelineLayout (pipelineLayout: PipelineLayout) {
this._pipelineLayout = pipelineLayout;
if (JSB) {
@@ -771,6 +777,7 @@ export class Pass {
this._properties = target._properties;
this._blocks = target._blocks;
this._blocksInt = target._blocksInt;
this._dynamics = target._dynamics;
this._shader = target._shader;
@@ -792,6 +799,7 @@ export class Pass {
// data
get dynamics (): IPassDynamics { return this._dynamics; }
get blocks (): Float32Array[] { return this._blocks; }
get blocksInt (): Int32Array[] { return this._blocksInt; }
get rootBufferDirty (): boolean { return this._rootBufferDirty; }
// states
get priority (): RenderPriority { return this._priority; }
+3
View File
@@ -98,6 +98,9 @@ export class Light {
set baked (val) {
this._baked = val;
if (JSB) {
this._nativeObj!.setBaked(val);
}
}
set color (color: Vec3) {
@@ -103,6 +103,7 @@ export const NativeLight: Constructor<{
setUseColorTemperature (enable: boolean): void;
setColorTemperatureRGB (color: Vec3): void;
setNode (n: Node): void;
setBaked (baked: boolean): void;
}> = null!;
export type NativeLight = InstanceType<typeof NativeLight>;
+1 -1
View File
@@ -366,7 +366,7 @@ export class RenderScene {
}
private _createNativeObject () {
if (JSB) {
if (JSB && !this._nativeObj) {
this._nativeObj = new NativeRenderScene();
}
}
+25 -2
View File
@@ -334,6 +334,8 @@ export class BaseNode extends CCObject implements ISchedulable {
// record scene's id when set this node as persist node
public _originalSceneId = '';
private _childTreeVersion = 0;
/**
* Set `_scene` field of this node.
* The derived `Scene` overrides this method to behavior differently.
@@ -440,6 +442,7 @@ export class BaseNode extends CCObject implements ISchedulable {
}
oldParent._children.splice(removeAt, 1);
oldParent._updateSiblingIndex();
oldParent._updateChildTreeVersion();
if (oldParent.emit) {
oldParent.emit(NodeEventType.CHILD_REMOVED, this);
}
@@ -452,6 +455,7 @@ export class BaseNode extends CCObject implements ISchedulable {
}
newParent._children.push(this);
this._siblingIndex = newParent._children.length - 1;
newParent._updateChildTreeVersion();
if (newParent.emit) {
newParent.emit(NodeEventType.CHILD_ADDED, this);
}
@@ -1241,10 +1245,15 @@ export class BaseNode extends CCObject implements ISchedulable {
}
public _updateSiblingIndex () {
let siblingChanged = false;
for (let i = 0; i < this._children.length; ++i) {
this._children[i]._siblingIndex = i;
const child = this._children[i];
if (child._siblingIndex !== i) {
child._siblingIndex = i;
siblingChanged = true;
}
}
if (siblingChanged) { this._updateChildTreeVersion(); }
this.emit(NodeEventType.SIBLING_ORDER_CHANGED);
}
@@ -1364,6 +1373,7 @@ export class BaseNode extends CCObject implements ISchedulable {
if (parent.emit) {
parent.emit(NodeEventType.CHILD_REMOVED, this);
}
parent._updateChildTreeVersion();
}
}
@@ -1391,6 +1401,19 @@ export class BaseNode extends CCObject implements ISchedulable {
return destroyByParent;
}
private _updateChildTreeVersion () {
let cur: BaseNode | null = this as BaseNode;
const totalFrames = legacyCC.director.getTotalFrames();
while (cur && cur._childTreeVersion !== totalFrames) {
cur._childTreeVersion = totalFrames;
cur = cur._parent;
}
}
public hasChildTreeUpdated () {
return this._childTreeVersion === legacyCC.director.getTotalFrames();
}
protected _onSiblingIndexChanged? (siblingIndex: number): void;
/**
+10 -2
View File
@@ -28,14 +28,16 @@
* @module scene-graph
*/
import { EDITOR, DEV, TEST, SUPPORT_JIT } from 'internal:constants';
import { EDITOR, DEV, TEST, SUPPORT_JIT, DEBUG } from 'internal:constants';
import { CCObject, isValid } from '../data/object';
import { array, Pool } from '../utils/js';
import { tryCatchFunctor_EDITOR } from '../utils/misc';
import { invokeOnEnable, createInvokeImpl, createInvokeImplJit, OneOffInvoker, LifeCycleInvoker } from './component-scheduler';
import { legacyCC } from '../global-exports';
import { assert, errorID } from '../platform/debug';
import { assert, errorID, error, getError } from '../platform/debug';
import { NodeEventType } from './node-event';
import { assertIsTrue } from '../data/utils/asserts';
import { Component } from '..';
const MAX_POOL_SIZE = 4;
@@ -243,6 +245,9 @@ export default class NodeActivator {
}
}
if (comp._enabled) {
if (DEBUG) {
assertIsTrue(comp.node, getError(3823, comp.uuid, comp.name));
}
const deactivatedOnLoading = !comp.node._activeInHierarchy;
if (deactivatedOnLoading) {
return;
@@ -377,6 +382,9 @@ if (EDITOR) {
}
}
if (comp._enabled) {
if (DEBUG) {
assertIsTrue(comp.node, getError(3823, comp.uuid, comp.name));
}
const deactivatedOnLoading = !comp.node._activeInHierarchy;
if (deactivatedOnLoading) {
return;
@@ -32,6 +32,7 @@ import { UIComponent } from '../../2d/framework/ui-component';
import { Renderable2D } from '../../2d/framework/renderable-2d';
import { UITransform } from '../../2d/framework/ui-transform';
import { warnID } from '../platform/debug';
import { legacyCC } from '../global-exports';
/**
* @en Node's UI properties abstraction
@@ -105,6 +106,8 @@ export class NodeUIProperties {
* @zh 为结点树的透明度状态设置脏标签
*/
public static markOpacityTree (node, isDirty = true) {
// cause label opacity change need reload
legacyCC.director.root!.batcher2D._reloadBatch();
node._uiProps.opacityDirty = isDirty;
for (let i = 0, l = node.children.length; i < l; i++) {
const c = node.children[i];
+7 -2
View File
@@ -7,7 +7,7 @@ import { EDITOR } from 'internal:constants';
import { Armature, Bone, EventObject } from '@cocos/dragonbones-js';
import { ccclass, executeInEditMode, help, menu } from '../core/data/class-decorator';
import { Renderable2D } from '../2d/framework/renderable-2d';
import { Node, CCClass, Color, Enum, ccenum, errorID, Texture2D, js, CCObject } from '../core';
import { Node, CCClass, Color, Enum, ccenum, errorID, Texture2D, js, CCObject, director } from '../core';
import { EventTarget } from '../core/event';
import { BlendFactor } from '../core/gfx';
import { displayName, editable, override, serializable, tooltip, type, visible } from '../core/data/decorators';
@@ -569,7 +569,7 @@ export class ArmatureDisplay extends Renderable2D {
this.material = m.renderData.material;
}
if (m.texture) {
ui.commitComp(this, m.texture, this._assembler, null);
ui.commitPlainComp(this, m.texture, this._assembler, null);
}
this.material = mat;
}
@@ -1303,6 +1303,11 @@ export class ArmatureDisplay extends Renderable2D {
}
}
}
public markForUpdateRenderData (enable = true) {
super.markForUpdateRenderData(enable);
director.root!.batcher2D._reloadBatch();
}
}
legacyCC.internal.ArmatureDisplay = ArmatureDisplay;
+37
View File
@@ -154,6 +154,9 @@ export const simple: IAssembler = {
const srcVIdx = renderData.vertexStart;
const srcIBuf = renderData.iData;
renderData.cacheBuffer = buffer;
renderData.bufferOffset = floatOffset;
// copy all vertexData
vBuf.set(srcVBuf.slice(srcVIdx, srcVIdx + renderData.vertexCount * STRIDE_FLOAT), floatOffset);
if (!comp._enableBatch) {
@@ -172,6 +175,40 @@ export const simple: IAssembler = {
iBuf[i + indicesOffset] = srcIBuf[i + srcIOffset] + vertexOffset;
}
},
fillCacheBuffer (comp: ArmatureDisplay) {
if (!comp || comp.meshRenderDataArray.length === 0) return;
const dataArray = comp.meshRenderDataArray;
const node = comp.node;
// 当前渲染的数据
const data = dataArray[comp._meshRenderDataArrayIdx];
const renderData = data.renderData;
const buffer = renderData.cacheBuffer!;
const floatOffset = renderData.bufferOffset;
const vBuf = buffer.vData!;
const matrix = node.worldMatrix;
const srcVBuf = renderData.vData;
const srcVIdx = renderData.vertexStart;
// copy all vertexData
vBuf.set(srcVBuf.slice(srcVIdx, srcVIdx + renderData.vertexCount * STRIDE_FLOAT), floatOffset);
if (!comp._enableBatch) {
for (let i = 0; i < renderData.vertexCount; i++) {
const pOffset = floatOffset + i * STRIDE_FLOAT;
_vec3u_temp.set(vBuf[pOffset], vBuf[pOffset + 1], vBuf[pOffset + 2]);
_vec3u_temp.transformMat4(matrix);
vBuf[pOffset] = _vec3u_temp.x;
vBuf[pOffset + 1] = _vec3u_temp.y;
vBuf[pOffset + 2] = _vec3u_temp.z;
}
}
buffer.setDirty();
},
};
function realTimeTraverse (armature: Armature, parentMat: Mat4|undefined, parentOpacity: number) {
@@ -33,7 +33,7 @@ import { IAssembler, IAssemblerManager } from '../2d/renderer/base';
import { MotionStreak } from './motion-streak-2d';
import { Vec2, Color } from '../core/math';
import { IBatcher } from '../2d/renderer/i-batcher';
import { Texture2D } from '../core';
import { director, Texture2D } from '../core';
import { RenderData } from '../2d/renderer/render-data';
const _tangent = new Vec2();
@@ -183,6 +183,7 @@ export const MotionStreakAssembler: IAssembler = {
renderData.vertexCount = verticesCount;
renderData.indicesCount = indicesCount;
director.root!.batcher2D._reloadBatch();
},
updateRenderDataCache (comp: MotionStreak, renderData: RenderData) {
@@ -226,6 +227,9 @@ export const MotionStreakAssembler: IAssembler = {
const vertexCount = renderData.vertexCount;
const indicesCount = renderData.indicesCount;
renderData.cacheBuffer = buffer;
renderData.bufferOffset = vertexOffset;
for (let i = 0; i < vertexCount; i++) {
const vert = dataList[i];
vBuf[vertexOffset++] = vert.x;
@@ -248,6 +252,30 @@ export const MotionStreakAssembler: IAssembler = {
iBuf[indicesOffset++] = start + 3;
}
},
fillCacheBuffer (comp: MotionStreak) {
const renderData = comp.renderData!;
const dataList = renderData.data;
const buffer = renderData.cacheBuffer!;
let vertexOffset = renderData.bufferOffset;
// buffer data may be reallocated, need get reference after request.
const vBuf = buffer.vData!;
const vertexCount = renderData.vertexCount;
for (let i = 0; i < vertexCount; i++) {
const vert = dataList[i];
vBuf[vertexOffset++] = vert.x;
vBuf[vertexOffset++] = vert.y;
vBuf[vertexOffset++] = vert.z;
vBuf[vertexOffset++] = vert.u;
vBuf[vertexOffset++] = vert.v;
Color.toArray(vBuf, vert.color, vertexOffset);
vertexOffset += 4;
}
buffer.setDirty();
},
};
export const MotionStreakAssemblerManager: IAssemblerManager = {
@@ -34,6 +34,7 @@ import { clampf, degreesToRadians, radiansToDegrees } from '../core/utils/misc';
import { vfmtPosUvColor, getComponentPerVertex } from '../2d/renderer/vertex-format';
import { PositionType, EmitterMode, START_SIZE_EQUAL_TO_END_SIZE, START_RADIUS_EQUAL_TO_END_RADIUS } from './define';
import { ParticleSystem2D } from './particle-system-2d';
import { director } from '../core';
const ZERO_VEC2 = new Vec2(0, 0);
const _pos = new Vec2();
@@ -470,6 +471,8 @@ export class Simulator {
this.finished = true;
psys._finishedSimulation();
}
director.root!.batcher2D._reloadBatch();
}
requestData (vertexCount: number, indicesCount: number) {
@@ -71,6 +71,9 @@ export const ParticleAssembler: IAssembler = {
const vData = renderData.vData;
const iData = renderData.iData as number[];
renderData.cacheBuffer = buffer;
renderData.bufferOffset = vertexOffset;
const vLen = renderData.vertexCount * 9;
for (let i = 0; i < vLen; i++) {
vBuf[vertexOffset++] = vData[i];
@@ -81,6 +84,30 @@ export const ParticleAssembler: IAssembler = {
iBuf[indicesOffset++] = iData[i] + vertexId;
}
},
fillCacheBuffer (comp: ParticleSystem2D) {
if (comp === null) {
return;
}
const renderData = comp._simulator.renderData;
if (renderData.vertexCount === 0 || renderData.indicesCount === 0) {
return;
}
const buffer = renderData.cacheBuffer!;
let vertexOffset = renderData.bufferOffset;
// buffer data may be realloc, need get reference after request.
const vBuf = buffer.vData!;
const vData = renderData.vData;
const vLen = renderData.vertexCount * 9;
for (let i = 0; i < vLen; i++) {
vBuf[vertexOffset++] = vData[i];
}
buffer.setDirty();
},
};
export const ParticleSystem2DAssembler: IAssemblerManager = {
+3 -3
View File
@@ -1169,11 +1169,11 @@ export class ParticleSystem2D extends Renderable2D {
protected _render (render: IBatcher) {
if (this._positionType === PositionType.RELATIVE) {
render.commitComp(this, this._renderSpriteFrame, this._assembler!, this.node.parent);
render.commitPlainComp(this, this._renderSpriteFrame, this._assembler!, this.node.parent);
} else if (this.positionType === PositionType.GROUPED) {
render.commitComp(this, this._renderSpriteFrame, this._assembler!, this.node);
render.commitPlainComp(this, this._renderSpriteFrame, this._assembler!, this.node);
} else {
render.commitComp(this, this._renderSpriteFrame, this._assembler!, null);
render.commitPlainComp(this, this._renderSpriteFrame, this._assembler!, null);
}
}
}
+62 -40
View File
@@ -29,7 +29,7 @@
*/
// eslint-disable-next-line import/no-extraneous-dependencies
import bulletModule from '@cocos/bullet';
import bulletModule, { bulletType } from '@cocos/bullet';
import { WECHAT } from 'internal:constants';
import { physics } from '../../../exports/physics-framework';
import { pageSize, pageCount, importFunc } from './bullet-env';
@@ -52,45 +52,67 @@ globalThis.Bullet = bt;
bt.BODY_CACHE_NAME = 'body';
export function waitForAmmoInstantiation (dirRoot: string) {
if (typeof bulletModule === 'string') {
console.info('[Physics][Bullet]: Using wasm Bullet libs.');
const infoReport = (msg: any) => { console.info(msg); };
const errorReport = (msg: any) => { console.error(msg); };
const memory = new WebAssembly.Memory({ initial: pageCount });
const importObject = {
cc: importFunc,
wasi_snapshot_preview1: { fd_close: infoReport, fd_seek: infoReport, fd_write: infoReport },
env: { memory },
};
return new Promise<void>((resolve, reject) => {
function instantiateWasm (buff: any) {
WebAssembly.instantiate(buff, importObject).then((results) => {
const btInstance = results.instance.exports as unknown as Bullet.instance;
Object.assign(bt, btInstance);
resolve();
}, errorReport);
// refer https://stackoverflow.com/questions/47879864/how-can-i-check-if-a-browser-supports-webassembly
const supported = (() => {
try {
if (typeof WebAssembly === 'object'
&& typeof WebAssembly.instantiate === 'function') {
const module = new WebAssembly.Module(new Uint8Array([0x0, 0x61, 0x73, 0x6d, 0x01, 0x00, 0x00, 0x00]));
if (module instanceof WebAssembly.Module) {
return new WebAssembly.Instance(module) instanceof WebAssembly.Instance;
}
}
if (WECHAT) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
const wasmFilePath = `${dirRoot}${bulletModule}` as any;
instantiateWasm(wasmFilePath);
} else {
fetch(bulletModule as any).then((response) => {
response.arrayBuffer().then((buff) => {
instantiateWasm(buff);
} catch (e) {
return false;
}
return false;
})();
return Promise.resolve().then(() => {
if (bulletType === 'fallback') {
return (bulletModule as any)(supported) as string | typeof bulletModule;
}
return bulletLibs as string | typeof bulletModule;
}).then((module) => {
if (typeof module === 'string') {
console.info('[Physics][Bullet]: Using wasm Bullet libs.');
const infoReport = (msg: any) => { console.info(msg); };
const errorReport = (msg: any) => { console.error(msg); };
const memory = new WebAssembly.Memory({ initial: pageCount });
const importObject = {
cc: importFunc,
wasi_snapshot_preview1: { fd_close: infoReport, fd_seek: infoReport, fd_write: infoReport },
env: { memory },
};
return new Promise<void>((resolve, reject) => {
function instantiateWasm (buff: any) {
WebAssembly.instantiate(buff, importObject).then((results) => {
const btInstance = results.instance.exports as unknown as Bullet.instance;
Object.assign(bt, btInstance);
resolve();
}, errorReport);
}, errorReport);
}
});
} else {
console.info('[Physics][Bullet]: Using asmjs Bullet libs.');
const env: any = importFunc;
const wasmMemory: any = {};
wasmMemory.buffer = new ArrayBuffer(pageSize * pageCount);
env.memory = wasmMemory;
const btInstance = bulletLibs(env, wasmMemory);
Object.assign(bt, btInstance);
return new Promise<void>((resolve, reject) => { resolve(); });
}
}
if (WECHAT) {
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
const wasmFilePath = `${dirRoot}${module}` as any;
instantiateWasm(wasmFilePath);
} else {
fetch(module).then((response) => {
response.arrayBuffer().then((buff) => {
instantiateWasm(buff);
}, errorReport);
}, errorReport);
}
});
} else {
console.info('[Physics][Bullet]: Using asmjs Bullet libs.');
const env: any = importFunc;
const wasmMemory: any = {};
wasmMemory.buffer = new ArrayBuffer(pageSize * pageCount);
env.memory = wasmMemory;
const btInstance = module(env, wasmMemory);
Object.assign(bt, btInstance);
return new Promise<void>((resolve, reject) => { resolve(); });
}
});
}
+37 -1
View File
@@ -177,7 +177,7 @@ export const simple: IAssembler = {
},
fillBuffers (comp: Skeleton, renderer: IBatcher) {
if (!comp || !comp.meshRenderDataArray) return;
if (!comp || !comp.meshRenderDataArray || comp.meshRenderDataArray.length < 1) return;
_comp = comp;
const dataArray = comp.meshRenderDataArray;
const node = comp.node;
@@ -207,6 +207,9 @@ export const simple: IAssembler = {
const srcVIdx = renderData.vertexStart;
const srcIBuf = renderData.iData;
renderData.cacheBuffer = buffer;
renderData.bufferOffset = floatOffset;
// copy all vertexData
const strideFloat = renderData.floatStride;
vBuf.set(srcVBuf.subarray(srcVIdx, srcVIdx + renderData.vertexCount * strideFloat), floatOffset);
@@ -224,6 +227,39 @@ export const simple: IAssembler = {
iBuf[i + indicesOffset] = srcIBuf[i + srcIOffset] + vertexOffset;
}
},
fillCacheBuffer (comp: Skeleton) {
if (!comp || !comp.meshRenderDataArray || comp.meshRenderDataArray.length < 1) return;
_comp = comp;
const dataArray = comp.meshRenderDataArray;
const node = comp.node;
// 当前渲染的数据
const data = dataArray[comp._meshRenderDataArrayIdx];
const renderData = data.renderData;
const buffer = renderData.cacheBuffer!;
const floatOffset = renderData.bufferOffset;
const vBuf = buffer.vData!;
const matrix = node.worldMatrix;
const srcVBuf = renderData.vData;
const srcVIdx = renderData.vertexStart;
// copy all vertexData
const strideFloat = renderData.floatStride;
vBuf.set(srcVBuf.subarray(srcVIdx, srcVIdx + renderData.vertexCount * strideFloat), floatOffset);
for (let i = 0; i < renderData.vertexCount; i++) {
const pOffset = floatOffset + i * strideFloat;
_vec3u_temp.set(vBuf[pOffset], vBuf[pOffset + 1], vBuf[pOffset + 2]);
_vec3u_temp.transformMat4(matrix);
vBuf[pOffset] = _vec3u_temp.x;
vBuf[pOffset + 1] = _vec3u_temp.y;
vBuf[pOffset + 2] = _vec3u_temp.z;
}
buffer.setDirty();
},
};
function updateComponentRenderData (comp: Skeleton, ui: IBatcher) {
+7 -2
View File
@@ -10,7 +10,7 @@ import SkeletonCache, { AnimationCache, AnimationFrame } from './skeleton-cache'
import { AttachUtil } from './attach-util';
import { ccclass, executeInEditMode, help, menu } from '../core/data/class-decorator';
import { Renderable2D } from '../2d/framework/renderable-2d';
import { Node, CCClass, CCObject, Color, Enum, Material, Texture2D, builtinResMgr, ccenum, errorID, logID, warn } from '../core';
import { Node, CCClass, CCObject, Color, Enum, Material, Texture2D, builtinResMgr, ccenum, errorID, logID, warn, director } from '../core';
import { displayName, displayOrder, editable, override, serializable, tooltip, type, visible } from '../core/data/decorators';
import { SkeletonData } from './skeleton-data';
import { VertexEffectDelegate } from './vertex-effect-delegate';
@@ -1372,7 +1372,7 @@ export class Skeleton extends Renderable2D {
this.material = m.renderData.material;
}
if (m.texture) {
ui.commitComp(this, m.texture, this._assembler, null);
ui.commitPlainComp(this, m.texture, this._assembler, null);
}
this.material = mat;
}
@@ -1665,6 +1665,11 @@ export class Skeleton extends Renderable2D {
}
this._materialCache = {};
}
public markForUpdateRenderData (enable = true) {
super.markForUpdateRenderData(enable);
director.root!.batcher2D._reloadBatch();
}
}
legacyCC.internal.SpineSkeleton = Skeleton;
+34
View File
@@ -172,6 +172,9 @@ export const simple: IAssembler = {
const srcVBuf = renderData.vData;
const srcVIdx = renderData.vertexStart;
renderData.cacheBuffer = buffer;
renderData.bufferOffset = vertexOffset;
// copy all vertexData
vBuf.set(srcVBuf.slice(srcVIdx, srcVIdx + renderData.vertexCount * 9), vertexOffset);
for (let i = 0; i < renderData.vertexCount; i++) {
@@ -195,6 +198,37 @@ export const simple: IAssembler = {
vertexId += 4;
}
},
fillCacheBuffer (layer: TiledLayer) {
if (!layer || !layer.meshRenderDataArray) return;
const dataArray = layer.meshRenderDataArray;
const node = layer.node;
const data = dataArray[layer._meshRenderDataArrayIdx] as TiledMeshData;
const renderData = data.renderData;
const buffer = renderData.cacheBuffer!;
const vertexOffset = renderData.bufferOffset;
const vBuf = buffer.vData!;
const matrix = node.worldMatrix;
const srcVBuf = renderData.vData;
const srcVIdx = renderData.vertexStart;
// copy all vertexData
vBuf.set(srcVBuf.slice(srcVIdx, srcVIdx + renderData.vertexCount * 9), vertexOffset);
for (let i = 0; i < renderData.vertexCount; i++) {
const pOffset = vertexOffset + i * 9;
_vec3u_temp.set(vBuf[pOffset], vBuf[pOffset + 1], vBuf[pOffset + 2]);
_vec3u_temp.transformMat4(matrix);
vBuf[pOffset] = _vec3u_temp.x;
vBuf[pOffset + 1] = _vec3u_temp.y;
vBuf[pOffset + 2] = _vec3u_temp.z;
}
buffer.setDirty();
},
};
/*
+6 -1
View File
@@ -1447,10 +1447,15 @@ export class TiledLayer extends Renderable2D {
});
} else if ((m as TiledMeshData).texture) {
// NOTE: 由于 commitComp 只支持单张纹理, 故分多次提交
ui.commitComp(this, (m as TiledMeshData).texture, this._assembler, null);
ui.commitPlainComp(this, (m as TiledMeshData).texture, this._assembler, null);
}
}
this.node._static = true;
}
}
public markForUpdateRenderData (enable = true) {
super.markForUpdateRenderData(enable);
director.root!.batcher2D._reloadBatch();
}
}
+38
View File
@@ -0,0 +1,38 @@
/*
Copyright (c) 2020 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* @packageDocumentation
* @hidden
*/
import { replaceProperty } from '../core/utils/x-deprecated';
import { VideoPlayer } from './video-player';
replaceProperty(VideoPlayer.prototype, 'VideoPlayer.prototype', [
{
name: 'onPasued',
newName: 'onPaused',
},
]);
+38
View File
@@ -0,0 +1,38 @@
/*
Copyright (c) 2020 Xiamen Yaji Software Co., Ltd.
https://www.cocos.com/
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
/**
* @packageDocumentation
* @hidden
*/
import './video-downloader';
import { VideoClip } from './assets/video-clip';
import { VideoPlayer } from './video-player';
import './deprecated';
export { VideoClip };
export { VideoPlayer };
+2 -2
View File
@@ -389,7 +389,7 @@ export class VideoPlayer extends Component {
this._impl.componentEventList.set(EventType.META_LOADED, this.onMetaLoaded.bind(this));
this._impl.componentEventList.set(EventType.READY_TO_PLAY, this.onReadyToPlay.bind(this));
this._impl.componentEventList.set(EventType.PLAYING, this.onPlaying.bind(this));
this._impl.componentEventList.set(EventType.PAUSED, this.onPasued.bind(this));
this._impl.componentEventList.set(EventType.PAUSED, this.onPaused.bind(this));
this._impl.componentEventList.set(EventType.STOPPED, this.onStopped.bind(this));
this._impl.componentEventList.set(EventType.COMPLETED, this.onCompleted.bind(this));
this._impl.componentEventList.set(EventType.ERROR, this.onError.bind(this));
@@ -439,7 +439,7 @@ export class VideoPlayer extends Component {
this.node.emit(EventType.PLAYING, this);
}
public onPasued () {
public onPaused () {
ComponentEventHandler.emitEvents(this.videoPlayerEvent, this, EventType.PAUSED);
this.node.emit(EventType.PAUSED, this);
}
+24 -24
View File
@@ -70,17 +70,17 @@ export class WebViewImplWeb extends WebViewImpl {
}
public createWebView () {
const warpper = document.createElement('div');
this._warpper = warpper;
warpper.id = 'webview-wrapper';
warpper.style['-webkit-overflow'] = 'auto';
warpper.style['-webkit-overflow-scrolling'] = 'touch';
warpper.style.position = 'absolute';
warpper.style.bottom = '0px';
warpper.style.left = '0px';
warpper.style.transformOrigin = '0px 100% 0px';
warpper.style['-webkit-transform-origin'] = '0px 100% 0px';
game.container!.appendChild(warpper);
const wrapper = document.createElement('div');
this._wrapper = wrapper;
wrapper.id = 'webview-wrapper';
wrapper.style['-webkit-overflow'] = 'auto';
wrapper.style['-webkit-overflow-scrolling'] = 'touch';
wrapper.style.position = 'absolute';
wrapper.style.bottom = '0px';
wrapper.style.left = '0px';
wrapper.style.transformOrigin = '0px 100% 0px';
wrapper.style['-webkit-transform-origin'] = '0px 100% 0px';
game.container!.appendChild(wrapper);
const webview = document.createElement('iframe');
this._webview = webview;
@@ -88,27 +88,27 @@ export class WebViewImplWeb extends WebViewImpl {
webview.style.border = 'none';
webview.style.width = '100%';
webview.style.height = '100%';
warpper.appendChild(webview);
wrapper.appendChild(webview);
this._bindDomEvent();
}
public removeWebView () {
const warpper = this._warpper;
if (contains(game.container, warpper)) {
game.container!.removeChild(warpper);
const wrapper = this._wrapper;
if (contains(game.container, wrapper)) {
game.container!.removeChild(wrapper);
}
this.reset();
}
public enable () {
if (this._warpper) {
this._warpper.style.visibility = 'visible';
if (this._wrapper) {
this._wrapper.style.visibility = 'visible';
}
}
public disable () {
if (this._warpper) {
this._warpper.style.visibility = 'hidden';
if (this._wrapper) {
this._wrapper.style.visibility = 'hidden';
}
}
@@ -135,7 +135,7 @@ export class WebViewImplWeb extends WebViewImpl {
}
public syncMatrix () {
if (!this._warpper || !this._uiTrans || !this._component || this._warpper.style.visibility === 'hidden') return;
if (!this._wrapper || !this._uiTrans || !this._component || this._wrapper.style.visibility === 'hidden') return;
const camera = this.UICamera;
if (!camera) {
@@ -176,8 +176,8 @@ export class WebViewImplWeb extends WebViewImpl {
const c = _mat4_temp.m04;
const sy = _mat4_temp.m05 * scaleY;
this._warpper.style.width = `${width}px`;
this._warpper.style.height = `${height}px`;
this._wrapper.style.width = `${width}px`;
this._wrapper.style.height = `${height}px`;
const w = this._w * scaleX;
const h = this._h * scaleY;
@@ -190,8 +190,8 @@ export class WebViewImplWeb extends WebViewImpl {
const ty = _mat4_temp.m13 * scaleY - appy + offsetY;
const matrix = `matrix(${sx},${-b},${-c},${sy},${tx},${-ty})`;
this._warpper.style.transform = matrix;
this._warpper.style['-webkit-transform'] = matrix;
this._wrapper.style.transform = matrix;
this._wrapper.style['-webkit-transform'] = matrix;
this._forceUpdate = false;
}
}
+3 -3
View File
@@ -38,7 +38,7 @@ import { Node } from '../core/scene-graph';
export abstract class WebViewImpl {
protected _componentEventList: Map<EventType, (...args: any[any]) => void> = new Map();
protected _state = EventType.NONE;
protected _warpper: any; // Fix iframe display problem in ios.
protected _wrapper: any; // Fix iframe display problem in ios.
protected _webview: HTMLIFrameElement | null = null;
protected _loaded = false;
@@ -66,7 +66,7 @@ export abstract class WebViewImpl {
}
public reset () {
this._warpper = null;
this._wrapper = null;
this._webview = null;
this._loaded = false;
this._w = 0;
@@ -110,7 +110,7 @@ export abstract class WebViewImpl {
public destroy () {
this.removeWebView();
this._warpper = null;
this._wrapper = null;
this._webview = null;
this._loaded = false;
this._component = null;
+1 -1
View File
@@ -325,7 +325,7 @@ module.exports = {
'illegal-inspector-url': "Inspector's URL is not valid",
},
animationGraph: {
edit: 'Edit in the Animation Graph panel',
edit: 'Edit',
},
multipleWarning: 'Multi-select editing of this type of asset is not supported',
},
+1 -1
View File
@@ -316,7 +316,7 @@ module.exports = {
'illegal-inspector-url': "Inspector的路径不合法",
},
animationGraph: {
edit: '打开动画图面板进行编辑',
edit: '编辑',
},
multipleWarning: '不支持此类型资源的多选编辑',
},
+30 -8
View File
@@ -427,11 +427,11 @@ const Elements = {
line.appendChild(name);
const time = document.createElement('div');
time.setAttribute('class', 'time');
time.innerHTML = panel.animationTimeShowType === 'time' ? subAnim.from.toFixed(2) : Math.round(subAnim.from * panel.rawClipInfo.fps);
time.innerHTML = panel.animationTimeShowType === 'time' ? subAnim.from.toFixed(2) : Math.round(subAnim.from * (subAnim.fps || panel.rawClipInfo.fps));
line.appendChild(time);
const timeEnd = document.createElement('div');
timeEnd.setAttribute('class', 'time end');
timeEnd.innerHTML = panel.animationTimeShowType === 'time' ? subAnim.to.toFixed(2) : Math.round(subAnim.to * panel.rawClipInfo.fps);
timeEnd.innerHTML = panel.animationTimeShowType === 'time' ? subAnim.to.toFixed(2) : Math.round(subAnim.to * (subAnim.fps || panel.rawClipInfo.fps));
line.appendChild(timeEnd);
});
@@ -818,12 +818,17 @@ exports.methods = {
panel.$.clipFrames.innerText = maxFrames;
panel.$.clipFPS.value = fps;
panel.$.clipFrom.setAttribute('max', endFrames);
panel.$.clipFrom.value = startFrames;
// TODO: hack for bug at 3d-tasks#10113. Because the new value would be limited in min and max, should firstly remove min and max.
panel.$.clipFrom.max = null;
panel.$.clipTo.min = null;
panel.$.clipTo.max = null;
panel.$.clipFrom.value = startFrames;
panel.$.clipFrom.setAttribute('max', endFrames);
panel.$.clipTo.value = endFrames;
panel.$.clipTo.setAttribute('min', startFrames);
panel.$.clipTo.setAttribute('max', maxFrames);
panel.$.clipTo.value = endFrames;
panel.$.wrapMode.value = panel.currentClipInfo.wrapMode;
panel.$.speed.value = panel.currentClipInfo.speed || 1;
@@ -1049,15 +1054,32 @@ exports.methods = {
onWrapModeChange(event) {
const panel = this;
panel.animationInfos[panel.rawClipIndex].splits[panel.splitClipIndex].wrapMode = Number(event.target.value);
const wrapMode = Number(event.target.value);
panel.animationInfos[panel.rawClipIndex].splits[panel.splitClipIndex].wrapMode = wrapMode;
Editor.Message.request(
'scene',
'execute-model-preview-animation-operation',
'setClipConfig',
{
wrapMode,
}
);
Elements.editor.update.call(panel);
panel.dispatch('change');
},
onSpeedChange(event) {
const panel = this;
panel.animationInfos[panel.rawClipIndex].splits[panel.splitClipIndex].speed = Number(event.target.value);
const speed = Number(event.target.value);
panel.animationInfos[panel.rawClipIndex].splits[panel.splitClipIndex].speed = speed;
Editor.Message.request(
'scene',
'execute-model-preview-animation-operation',
'setClipConfig',
{
speed,
}
);
Elements.editor.update.call(panel);
panel.dispatch('change');
+11
View File
@@ -742,6 +742,17 @@ exports.methods = {
clipInfo.from,
clipInfo.to,
);
await Editor.Message.request(
'scene',
'execute-model-preview-animation-operation',
'setClipConfig',
{
wrapMode: clipInfo.userData.wrapMode,
speed: clipInfo.userData.speed,
}
);
await this.stopAnimation();
}
},
+1 -5
View File
@@ -26,8 +26,4 @@
/**
* @hidden
*/
export { VideoClip } from '../cocos/video/assets/video-clip';
import '../cocos/video/video-downloader';
export { VideoPlayer } from '../cocos/video/video-player';
export * from '../cocos/video';
+2 -2
View File
@@ -312,7 +312,7 @@ let VideoPlayer = cc.Class({
if (!CC_EDITOR) {
impl.setEventListener(EventType.PLAYING, this.onPlaying.bind(this));
impl.setEventListener(EventType.PAUSED, this.onPasued.bind(this));
impl.setEventListener(EventType.PAUSED, this.onPaused.bind(this));
impl.setEventListener(EventType.STOPPED, this.onStopped.bind(this));
impl.setEventListener(EventType.COMPLETED, this.onCompleted.bind(this));
impl.setEventListener(EventType.META_LOADED, this.onMetaLoaded.bind(this));
@@ -373,7 +373,7 @@ let VideoPlayer = cc.Class({
this.node.emit('playing', this);
},
onPasued () {
onPaused () {
cc.Component.EventHandler.emitEvents(this.videoPlayerEvent, this, EventType.PAUSED);
this.node.emit('paused', this);
},
+3
View File
@@ -15,6 +15,9 @@ module.exports = {
// - @cocos/dragonbones-js
'node_modules/(?!(@cocos/dragonbones-js)/)',
],
setupFilesAfterEnv: [
"./tests/setup-after-env.ts",
],
setupFiles: [
'./tests/init.ts',
],
+280 -118
View File
File diff suppressed because it is too large Load Diff
+3 -2
View File
@@ -30,7 +30,7 @@
"@babel/core": "^7.13.10",
"@babel/preset-env": "7.8.7",
"@cocos/babel-preset-cc": "2.2.0",
"@cocos/build-engine": "4.2.18",
"@cocos/build-engine": "4.2.19",
"@cocos/typedoc-plugin-internal-external": "^1.0.1",
"@cocos/typedoc-plugin-localization": "^1.0.0",
"@types/fs-extra": "^5.0.4",
@@ -50,6 +50,7 @@
"gulp": "^4.0.2",
"http-server": "^0.12.3",
"jest": "^26.6.3",
"jest-extended": "^1.1.0",
"jest-matcher-deep-close-to": "^2.0.1",
"path": "^0.12.7",
"pngjs": "^6.0.0",
@@ -64,7 +65,7 @@
},
"dependencies": {
"@cocos/box2d": "1.0.1",
"@cocos/bullet": "1.0.0",
"@cocos/bullet": "1.0.2",
"@cocos/cannon": "1.2.8",
"@cocos/dragonbones-js": "^1.0.1",
"@cocos/physx": "1.0.7"
@@ -92,7 +92,9 @@ class ScreenAdapter extends EventTarget {
public get safeAreaEdge (): SafeAreaEdge {
const minigameSafeArea = minigame.getSafeArea();
const windowSize = this.windowSize;
const dpr = this.devicePixelRatio;
// NOTE: safe area info on vivo platform is in physical pixel.
// No need to multiply with DPR.
const dpr = VIVO ? 1 : this.devicePixelRatio;
let topEdge = minigameSafeArea.top * dpr;
let bottomEdge = windowSize.height - minigameSafeArea.bottom * dpr;
let leftEdge = minigameSafeArea.left * dpr;
-1
View File
@@ -285,7 +285,6 @@ class ScreenAdapter extends EventTarget {
this.orientation = orientationMap[options.configOrientation];
this._exactFitScreen = options.exactFitScreen;
this._resizeFrame();
this._cbToUpdateFrameBuffer();
}
public requestFullScreen (): Promise<void> {
+1 -1
View File
@@ -794,7 +794,7 @@ const cacheManager = require('./jsb-cache-manager');
middleware.resetIndicesStart = false;
}
ui.commitComp(this, realTexture, this._assembler, null);
ui.commitPlainComp(this, realTexture, this._assembler, null);
this.material = mat;
}
}
@@ -886,7 +886,7 @@ const cacheManager = require('./jsb-cache-manager');
middleware.resetIndicesStart = false;
}
ui.commitComp(this, realTexture, this._assembler, null);
ui.commitPlainComp(this, realTexture, this._assembler, null);
this.material = mat;
}
}
+19 -3
View File
@@ -517,14 +517,30 @@ async function doBuild ({
const bulletAsmJsModule = await nodeResolveAsync('@cocos/bullet/bullet.cocos.js');
const wasmBinaryPath = ps.join(bulletAsmJsModule, '..', 'bullet.wasm.wasm');
if (ammoJsWasm === true || ammoJsWasm === 'fallback') {
rpVirtualOptions['@cocos/bullet'] = `
if (ammoJsWasm === true) {
rpVirtualOptions['@cocos/bullet'] = `
import wasmBinaryURL from '${pathToAssetRefURL(wasmBinaryPath)}';
export const bulletType = 'wasm';
export default wasmBinaryURL;
`;
} else if (ammoJsWasm === 'fallback') {
rpVirtualOptions['@cocos/bullet'] = `
export async function initialize(isWasm) {
let ammo;
if (isWasm) {
ammo = await import('${pathToAssetRefURL(wasmBinaryPath)}');
} else {
rpVirtualOptions['@cocos/bullet'] = `
ammo = await import('${filePathToModuleRequest(bulletAsmJsModule)}');
}
return ammo.default;
}
export const bulletType = 'fallback';
export default initialize;
`;
} else {
rpVirtualOptions['@cocos/bullet'] = `
import Bullet from '${filePathToModuleRequest(bulletAsmJsModule)}';
export const bulletType = 'asmjs';
export default Bullet;
`;
}
+45
View File
@@ -21,6 +21,7 @@ import { BinaryCondition, UnaryCondition, TriggerCondition } from '../../cocos/c
import { AnimationController } from '../../cocos/core/animation/marionette/animation-controller';
import { StateMachineComponent } from '../../cocos/core/animation/marionette/state-machine-component';
import { VectorTrack } from '../../cocos/core/animation/animation';
import 'jest-extended';
describe('NewGen Anim', () => {
const demoGraphs = __getDemoGraphs();
@@ -1870,6 +1871,50 @@ describe('NewGen Anim', () => {
describe('Property binding', () => {
});
test(`Runtime variable manipulation`, () => {
const animationGraph = new AnimationGraph();
animationGraph.addVariable('i0', VariableType.INTEGER, 0);
animationGraph.addVariable('i1', VariableType.INTEGER, 2);
animationGraph.addVariable('f0', VariableType.FLOAT, 0.0);
animationGraph.addVariable('f1', VariableType.FLOAT, 3.14);
animationGraph.addVariable('b0', VariableType.BOOLEAN, true);
animationGraph.addVariable('b1', VariableType.BOOLEAN, false);
animationGraph.addVariable('t0', VariableType.TRIGGER, true);
animationGraph.addVariable('t1', VariableType.TRIGGER, false);
const node = new Node();
const { newGenAnim: controller } = createAnimationGraphEval2(animationGraph, node);
expect(Array.from(controller.getVariables()).map(
([name, { type }]) => [name, type, controller.getValue(name)] as const)).toIncludeAllMembers([
['i0', VariableType.INTEGER, 0],
['i1', VariableType.INTEGER, 2],
['f0', VariableType.FLOAT, 0.0],
['f1', VariableType.FLOAT, 3.14],
['b0', VariableType.BOOLEAN, true],
['b1', VariableType.BOOLEAN, false],
['t0', VariableType.TRIGGER, true],
['t1', VariableType.TRIGGER, false],
]);
controller.setValue('i0', 3);
controller.setValue('i1', 4);
controller.setValue('f0', 1.0);
controller.setValue('f1', 6.28);
controller.setValue('b0', false);
controller.setValue('b1', true);
controller.setValue('t0', false);
controller.setValue('t1', true);
expect(Array.from(controller.getVariables()).map(
([name, { type }]) => [name, type, controller.getValue(name)] as const)).toIncludeAllMembers([
['i0', VariableType.INTEGER, 3],
['i1', VariableType.INTEGER, 4],
['f0', VariableType.FLOAT, 1.0],
['f1', VariableType.FLOAT, 6.28],
['b0', VariableType.BOOLEAN, false],
['b1', VariableType.BOOLEAN, true],
['t0', VariableType.TRIGGER, false],
['t1', VariableType.TRIGGER, true],
]);
});
});
function createEmptyClipMotion (duration: number, name = '') {
+6 -2
View File
@@ -1,14 +1,18 @@
import { SpriteFrame } from "../../cocos/2d/assets/sprite-frame";
import { Sprite } from "../../cocos/2d/components/sprite";
import { Batcher2D } from "../../cocos/2d/renderer/batcher-2d";
import { assetManager, loader } from "../../cocos/core/asset-manager";
import releaseManager from "../../cocos/core/asset-manager/release-manager";
import { Texture2D } from "../../cocos/core/assets/texture-2d";
import { isValid } from "../../cocos/core/data/object";
import { director } from "../../cocos/core/director";
import { Scene, Node } from "../../cocos/core/scene-graph";
director.root!._batcher = new Batcher2D(director.root);
describe('releaseManager', () => {
const libPath = './tests/fixtures/library';
const libPath = './tests/fixtures/library';
assetManager.init({importBase: libPath, nativeBase: libPath});
test('reference', function () {
@@ -182,7 +186,7 @@ describe('releaseManager', () => {
assetManager.dependUtil._depends.add('DDD', {deps: ['AAA']});
// @ts-ignore
releaseManager._free(texA);
expect(assetManager.assets.count).toBe(0);
assetManager.releaseAll();
});
+127 -1
View File
@@ -1,8 +1,11 @@
import { Node, Scene } from "../../cocos/core/scene-graph"
import { Vec3 } from "../../cocos/core/math"
import { BaseNode, director } from "../../cocos/core";
import { CCObject, director, game } from "../../cocos/core";
import { NodeEventType } from "../../cocos/core/scene-graph/node-event";
import { NodeUIProperties } from "../../cocos/core/scene-graph/node-ui-properties";
import { Batcher2D } from "../../cocos/2d/renderer/batcher-2d";
director.root!._batcher = new Batcher2D(director.root);
describe(`Node`, () => {
test('mark-opacity-tree',() => {
@@ -135,4 +138,127 @@ describe(`Node`, () => {
node.active = true;
expect(node.active).toBe(true);
});
test('hierarchy-changed', () => {
const scene = new Scene('');
director.runSceneImmediate(scene);
const node = new Node();
const childNode = new Node();
node.addChild(childNode);
expect(node.hasChildTreeUpdated()).toBeTruthy();
game.step();
expect(node.hasChildTreeUpdated()).toBeFalsy();
// scene -|
// |-node-|
// |-childNode
// insert node, scene will be notify
scene.addChild(node);
expect(node.hasChildTreeUpdated()).toBeFalsy();
expect(childNode.hasChildTreeUpdated()).toBeFalsy();
expect(scene.hasChildTreeUpdated()).toBeTruthy();
game.step();
const node1 = new Node();
// scene -|
// |- node -|
// |-childNode
// |- node1
// insert node1, scene will be notify
scene.addChild(node1);
expect(node1.hasChildTreeUpdated()).toBeFalsy();
expect(node.hasChildTreeUpdated()).toBeFalsy();
expect(scene.hasChildTreeUpdated()).toBeTruthy();
game.step();
// scene -|
// |- node1
// |- node -|
// |-childNode
// change node sibling index, scene will be notify
node.setSiblingIndex(1);
expect(node1.hasChildTreeUpdated()).toBeFalsy();
expect(node.hasChildTreeUpdated()).toBeFalsy();
expect(scene.hasChildTreeUpdated()).toBeTruthy();
game.step();
const childNode2 = new Node();
// scene -|
// |- node1
// |- node -|
// |-childNode
// |-childNode2
// insert childNode2, node and scene will be notify
node.addChild(childNode2);
expect(node.hasChildTreeUpdated()).toBeTruthy();
expect(node1.hasChildTreeUpdated()).toBeFalsy();
expect(scene.hasChildTreeUpdated()).toBeTruthy();
game.step();
// scene -|
// |- node1
// |- node -|
// |-childNode2
// |-childNode
// change childNode2 sibling, node and scene will be notify
childNode2.setSiblingIndex(0);
expect(node.hasChildTreeUpdated()).toBeTruthy();
expect(node1.hasChildTreeUpdated()).toBeFalsy();
expect(scene.hasChildTreeUpdated()).toBeTruthy();
expect(childNode2.hasChildTreeUpdated()).toBeFalsy();
expect(childNode.hasChildTreeUpdated()).toBeFalsy();
game.step();
const childNode3 = new Node();
// scene -|
// |- node1
// |- node -|
// |-childNode2
// |-childNode
// |-childNode3
// insert childNode3, node and scene will be notify
node.addChild(childNode3);
expect(node.hasChildTreeUpdated()).toBeTruthy();
expect(node1.hasChildTreeUpdated()).toBeFalsy();
expect(scene.hasChildTreeUpdated()).toBeTruthy();
expect(childNode2.hasChildTreeUpdated()).toBeFalsy();
expect(childNode.hasChildTreeUpdated()).toBeFalsy();
expect(childNode3.hasChildTreeUpdated()).toBeFalsy();
game.step();
// scene -|
// |- node1
// |- node -|
// |-childNode2
// |-childNode
// remove childNode3, node and scene will be notify
childNode3.removeFromParent();
expect(node.hasChildTreeUpdated()).toBeTruthy();
expect(node1.hasChildTreeUpdated()).toBeFalsy();
expect(scene.hasChildTreeUpdated()).toBeTruthy();
expect(childNode2.hasChildTreeUpdated()).toBeFalsy();
expect(childNode.hasChildTreeUpdated()).toBeFalsy();
expect(childNode3.hasChildTreeUpdated()).toBeFalsy();
game.step();
// scene -|
// |- node1
// |- node -|
// |-childNode
// destroy childNode2, node and scene will be notify
childNode2.destroy();
CCObject._deferredDestroy();
expect(node.hasChildTreeUpdated()).toBeTruthy();
expect(node1.hasChildTreeUpdated()).toBeFalsy();
expect(scene.hasChildTreeUpdated()).toBeTruthy();
expect(childNode.hasChildTreeUpdated()).toBeFalsy();
});
});
+3
View File
@@ -0,0 +1,3 @@
// @ts-ignore
import * as matchers from 'jest-extended';
expect.extend(matchers);