diff --git a/cocos/audio/assets/clip.ts b/cocos/audio/assets/clip.ts index 9e48a47068..bf53e0cfa3 100644 --- a/cocos/audio/assets/clip.ts +++ b/cocos/audio/assets/clip.ts @@ -37,9 +37,8 @@ import { AudioPlayerWeb } from './player-web'; export const AudioType = Enum({ WEB_AUDIO: 0, DOM_AUDIO: 1, - MINI_GAME_AUDIO: 2, + JSB_AUDIO: 2, UNKNOWN_AUDIO: 3, - JSB_AUDIO: 4, }); /** diff --git a/cocos/core/3d/framework/batched-skinning-model-component.ts b/cocos/core/3d/framework/batched-skinning-model-component.ts index 7cadd972e1..6de7fbba26 100644 --- a/cocos/core/3d/framework/batched-skinning-model-component.ts +++ b/cocos/core/3d/framework/batched-skinning-model-component.ts @@ -38,7 +38,7 @@ import { GFXFormat, GFXType } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { IGFXAttribute } from '../../gfx/input-assembler'; import { Mat4, Vec2 } from '../../math'; -import { mapBuffer } from '../misc/utils'; +import { mapBuffer } from '../misc/buffer'; import { SkinningModelComponent } from './skinning-model-component'; const repeat = (n: number) => n - Math.floor(n); diff --git a/cocos/core/3d/framework/camera-component.ts b/cocos/core/3d/framework/camera-component.ts index 714c1a5d8e..712a9a7431 100644 --- a/cocos/core/3d/framework/camera-component.ts +++ b/cocos/core/3d/framework/camera-component.ts @@ -28,6 +28,7 @@ */ import { RenderTexture } from '../../assets/render-texture'; +import { UITransformComponent } from '../../components'; import { Component } from '../../components/component'; import { ccclass, executeInEditMode, menu, property } from '../../data/class-decorator'; import { ray } from '../../geom-utils'; @@ -38,9 +39,9 @@ import { CameraDefaultMask } from '../../pipeline/define'; import { Camera } from '../../renderer'; import { SKYBOX_FLAG } from '../../renderer/scene/camera'; import { Root } from '../../root'; -import { Layers, Scene, Node } from '../../scene-graph'; +import { Layers, Node, Scene } from '../../scene-graph'; import { Enum } from '../../value-types'; -import { UITransformComponent } from '../../components'; +import { view } from '../../platform'; const _temp_vec3_1 = new Vec3(); @@ -431,22 +432,37 @@ export class CameraComponent extends Component { return out; } - public convertToUINode(wpos: Vec3, uiNode: Node, out?: Vec3){ + /** + * @zh 3D 节点转 UI 本地节点坐标。 + * 注意:千万不要设置负责做转换的 uiNode 和最终设置位置的 uiNode 是同一个 node,否则可能出现跳动现象。 + * @param wpos 3D 节点事件坐标 + * @param uiNode UI 节点 + * @param out 返回在当前传入的 UI 节点下的偏移量 + * + * @example + * ```typescript + * this.convertToUINode(target.worldPosition, uiNode.parent, out); + * uiNode.position = out; + * ``` + */ + public convertToUINode (wpos: Vec3, uiNode: Node, out?: Vec3){ if (!out) { out = new Vec3(); } + if (!this._camera) { return out; } this.worldToScreen(wpos, _temp_vec3_1); - _temp_vec3_1.x = _temp_vec3_1.x / cc.view.getScaleX(); - _temp_vec3_1.y = _temp_vec3_1.y / cc.view.getScaleY(); const cmp = uiNode.getComponent('cc.UITransformComponent') as UITransformComponent; + const designSize = view.getVisibleSize(); + const xoffset = _temp_vec3_1.x - this._camera!.width * 0.5; + const yoffset = _temp_vec3_1.y - this._camera!.height * 0.5; + _temp_vec3_1.x = xoffset / cc.view.getScaleX() + designSize.width * 0.5; + _temp_vec3_1.y = yoffset / cc.view.getScaleY() + designSize.height * 0.5; - if (!cmp) { - return out; + if (cmp) { + cmp.convertToNodeSpaceAR(_temp_vec3_1, out); } - cmp.convertToNodeSpaceAR(_temp_vec3_1, out); - return out; } diff --git a/cocos/core/3d/framework/model-component.ts b/cocos/core/3d/framework/model-component.ts index 626a69071d..2a7c8f17ab 100644 --- a/cocos/core/3d/framework/model-component.ts +++ b/cocos/core/3d/framework/model-component.ts @@ -177,7 +177,7 @@ export class ModelComponent extends RenderableComponent { } protected _attachToScene () { - if (!this.node.scene && !this._model) { + if (!this.node.scene || !this._model) { return; } const scene = this._getRenderScene(); diff --git a/cocos/core/3d/misc/buffer.ts b/cocos/core/3d/misc/buffer.ts new file mode 100644 index 0000000000..38a8ddec38 --- /dev/null +++ b/cocos/core/3d/misc/buffer.ts @@ -0,0 +1,75 @@ +import { GFXFormat, GFXFormatInfos, GFXFormatType, IGFXFormatInfo } from '../../gfx/define'; + +const isLittleEndian = cc.sys.isLittleEndian; +const _typeMap = { + [GFXFormatType.UNORM]: 'Uint', + [GFXFormatType.SNORM]: 'Int', + [GFXFormatType.UINT]: 'Uint', + [GFXFormatType.INT]: 'Int', + [GFXFormatType.UFLOAT]: 'Float', + [GFXFormatType.FLOAT]: 'Float', + default: 'Uint', +}; +function _getDataViewType (info: IGFXFormatInfo) { + const type = _typeMap[info.type] || _typeMap.default; + const bytes = info.size / info.count * 8; + return type + bytes; +} + + +// default params bahaves just like on an plain, compact Float32Array +export function writeBuffer (target: DataView, data: number[], format: GFXFormat = GFXFormat.R32F, offset: number = 0, stride: number = 0) { + const info = GFXFormatInfos[format]; + if (!stride) { stride = info.size; } + const writer = 'set' + _getDataViewType(info); + const componentBytesLength = info.size / info.count; + const nSeg = Math.floor(data.length / info.count); + + for (let iSeg = 0; iSeg < nSeg; ++iSeg) { + const x = offset + stride * iSeg; + for (let iComponent = 0; iComponent < info.count; ++iComponent) { + const y = x + componentBytesLength * iComponent; + target[writer](y, data[info.count * iSeg + iComponent], isLittleEndian); + } + } +} +export function readBuffer ( + target: DataView, format: GFXFormat = GFXFormat.R32F, offset: number = 0, + length: number = target.byteLength - offset, stride: number = 0, out: number[] = []) { + const info = GFXFormatInfos[format]; + if (!stride) { stride = info.size; } + const reader = 'get' + _getDataViewType(info); + const componentBytesLength = info.size / info.count; + const nSeg = Math.floor(length / stride); + + for (let iSeg = 0; iSeg < nSeg; ++iSeg) { + const x = offset + stride * iSeg; + for (let iComponent = 0; iComponent < info.count; ++iComponent) { + const y = x + componentBytesLength * iComponent; + out[info.count * iSeg + iComponent] = target[reader](y, isLittleEndian); + } + } + return out; +} +export function mapBuffer ( + target: DataView, callback: (cur: number, idx: number, view: DataView) => number, format: GFXFormat = GFXFormat.R32F, + offset: number = 0, length: number = target.byteLength - offset, stride: number = 0, out?: DataView) { + if (!out) { out = new DataView(new ArrayBuffer(target.byteLength)); } + const info = GFXFormatInfos[format]; + if (!stride) { stride = info.size; } + const writer = 'set' + _getDataViewType(info); + const reader = 'get' + _getDataViewType(info); + const componentBytesLength = info.size / info.count; + const nSeg = Math.floor(length / stride); + + for (let iSeg = 0; iSeg < nSeg; ++iSeg) { + const x = offset + stride * iSeg; + for (let iComponent = 0; iComponent < info.count; ++iComponent) { + const y = x + componentBytesLength * iComponent; + const cur = target[reader](y, isLittleEndian); + // iComponent is usually more useful than y + out[writer](y, callback(cur, iComponent, target), isLittleEndian); + } + } + return out; +} \ No newline at end of file diff --git a/cocos/core/3d/misc/create-mesh.ts b/cocos/core/3d/misc/create-mesh.ts new file mode 100644 index 0000000000..34a926bb46 --- /dev/null +++ b/cocos/core/3d/misc/create-mesh.ts @@ -0,0 +1,235 @@ +import { GFXAttributeName, GFXFormat, GFXFormatInfos, GFXPrimitiveMode } from '../../gfx/define'; +import { Mesh } from '../../assets/mesh'; +import { IGFXAttribute } from '../../gfx/input-assembler'; +import { Vec3 } from '../../math'; +import { IGeometry } from '../../primitive/define'; +import { BufferBlob } from './buffer-blob'; +import { writeBuffer } from './buffer'; + +const _defAttrs: IGFXAttribute[] = [ + { name: GFXAttributeName.ATTR_POSITION, format: GFXFormat.RGB32F }, + { name: GFXAttributeName.ATTR_NORMAL, format: GFXFormat.RGB32F }, + { name: GFXAttributeName.ATTR_TEX_COORD, format: GFXFormat.RG32F }, + { name: GFXAttributeName.ATTR_COLOR, format: GFXFormat.RGBA32F }, +]; + +const v3_1 = new Vec3(); +export function createMesh (geometry: IGeometry, out?: Mesh, options?: createMesh.Options) { + options = options || {}; + // Collect attributes and calculate length of result vertex buffer. + const attributes: IGFXAttribute[] = []; + let stride = 0; + const channels: Array<{ offset: number; data: number[]; attribute: IGFXAttribute; }> = []; + let vertCount = 0; + + let attr: IGFXAttribute | null; + + if (geometry.positions.length > 0) { + attr = null; + if (geometry.attributes) { + for (const att of geometry.attributes) { + if (att.name === GFXAttributeName.ATTR_POSITION) { + attr = att; + break; + } + } + } + + if (!attr) { + attr = _defAttrs[0]; + } + + const info = GFXFormatInfos[attr.format]; + attributes.push(attr); + vertCount = Math.max(vertCount, Math.floor(geometry.positions.length / info.count)); + channels.push({ offset: stride, data: geometry.positions, attribute: attr }); + stride += info.size; + } + + if (geometry.normals && geometry.normals.length > 0) { + attr = null; + if (geometry.attributes) { + for (const att of geometry.attributes) { + if (att.name === GFXAttributeName.ATTR_NORMAL) { + attr = att; + break; + } + } + } + + if (!attr) { + attr = _defAttrs[1]; + } + + const info = GFXFormatInfos[attr.format]; + attributes.push(attr); + vertCount = Math.max(vertCount, Math.floor(geometry.normals.length / info.count)); + channels.push({ offset: stride, data: geometry.normals, attribute: attr }); + stride += info.size; + } + + if (geometry.uvs && geometry.uvs.length > 0) { + attr = null; + if (geometry.attributes) { + for (const att of geometry.attributes) { + if (att.name === GFXAttributeName.ATTR_TEX_COORD) { + attr = att; + break; + } + } + } + + if (!attr) { + attr = _defAttrs[2]; + } + + const info = GFXFormatInfos[attr.format]; + attributes.push(attr); + vertCount = Math.max(vertCount, Math.floor(geometry.uvs.length / info.count)); + channels.push({ offset: stride, data: geometry.uvs, attribute: attr }); + stride += info.size; + } + + if (geometry.colors && geometry.colors.length > 0) { + attr = null; + if (geometry.attributes) { + for (const att of geometry.attributes) { + if (att.name === GFXAttributeName.ATTR_COLOR) { + attr = att; + break; + } + } + } + + if (!attr) { + attr = _defAttrs[3]; + } + + const info = GFXFormatInfos[attr.format]; + attributes.push(attr); + vertCount = Math.max(vertCount, Math.floor(geometry.colors.length / info.count)); + channels.push({ offset: stride, data: geometry.colors, attribute: attr }); + stride += info.size; + } + + if (geometry.customAttributes) { + for (const ca of geometry.customAttributes) { + const info = GFXFormatInfos[ca.attr.format]; + attributes.push(ca.attr); + vertCount = Math.max(vertCount, Math.floor(ca.values.length / info.count)); + channels.push({ offset: stride, data: ca.values, attribute: ca.attr }); + stride += info.size; + } + } + + // Use this to generate final merged buffer. + const bufferBlob = new BufferBlob(); + + // Fill vertex buffer. + const vertexBuffer = new ArrayBuffer(vertCount * stride); + const vertexBufferView = new DataView(vertexBuffer); + for (const channel of channels) { + writeBuffer(vertexBufferView, channel.data, channel.attribute.format, channel.offset, stride); + } + bufferBlob.setNextAlignment(0); + const vertexBundle: Mesh.VertexBundle = { + attributes, + view: { + offset: bufferBlob.getLength(), + length: vertexBuffer.byteLength, + count: vertCount, + stride, + }, + }; + bufferBlob.addBuffer(vertexBuffer); + + // Fill index buffer. + let indexBuffer: ArrayBuffer | null = null; + let idxCount = 0; + const idxStride = 2; + if (geometry.indices) { + const { indices } = geometry; + idxCount = indices.length; + indexBuffer = new ArrayBuffer(idxStride * idxCount); + const indexBufferView = new DataView(indexBuffer); + writeBuffer(indexBufferView, indices, GFXFormat.R16UI); + } + + // Create primitive. + const primitive: Mesh.Submesh = { + primitiveMode: geometry.primitiveMode || GFXPrimitiveMode.TRIANGLE_LIST, + vertexBundelIndices: [0], + }; + // geometric info for raycasting + if (primitive.primitiveMode >= GFXPrimitiveMode.TRIANGLE_LIST) { + const geomInfo = Float32Array.from(geometry.positions); + bufferBlob.setNextAlignment(4); + primitive.geometricInfo = { + doubleSided: geometry.doubleSided, + view: { + offset: bufferBlob.getLength(), + length: geomInfo.byteLength, + count: geometry.positions.length / 4, + stride: 4, + }, + }; + bufferBlob.addBuffer(geomInfo.buffer); + } + + if (indexBuffer) { + bufferBlob.setNextAlignment(idxStride); + primitive.indexView = { + offset: bufferBlob.getLength(), + length: indexBuffer.byteLength, + count: idxCount, + stride: idxStride, + }; + bufferBlob.addBuffer(indexBuffer); + } + + let minPosition = geometry.minPos; + if (!minPosition && options.calculateBounds) { + minPosition = Vec3.set(new Vec3(), Infinity, Infinity, Infinity); + for (let iVertex = 0; iVertex < vertCount; ++iVertex) { + Vec3.set(v3_1, geometry.positions[iVertex * 3 + 0], geometry.positions[iVertex * 3 + 1], geometry.positions[iVertex * 3 + 2]); + Vec3.min(minPosition, minPosition, v3_1); + } + } + let maxPosition = geometry.maxPos; + if (!maxPosition && options.calculateBounds) { + maxPosition = Vec3.set(new Vec3(), -Infinity, -Infinity, -Infinity); + for (let iVertex = 0; iVertex < vertCount; ++iVertex) { + Vec3.set(v3_1, geometry.positions[iVertex * 3 + 0], geometry.positions[iVertex * 3 + 1], geometry.positions[iVertex * 3 + 2]); + Vec3.max(maxPosition, maxPosition, v3_1); + } + } + + // Create mesh struct. + const meshStruct: Mesh.Struct = { + vertexBundles: [vertexBundle], + primitives: [primitive], + }; + if (minPosition) { + meshStruct.minPosition = new Vec3(minPosition.x, minPosition.y, minPosition.z); + } + if (maxPosition) { + meshStruct.maxPosition = new Vec3(maxPosition.x, maxPosition.y, maxPosition.z); + } + + // Create mesh. + if (!out) { + out = new Mesh(); + } + out.reset({ + struct: meshStruct, + data: new Uint8Array(bufferBlob.getCombined()), + }); + + return out; +} + +export declare namespace createMesh { + export interface Options { + calculateBounds?: boolean; + } +} \ No newline at end of file diff --git a/cocos/core/3d/misc/ppm.ts b/cocos/core/3d/misc/ppm.ts new file mode 100644 index 0000000000..4bb98e987e --- /dev/null +++ b/cocos/core/3d/misc/ppm.ts @@ -0,0 +1,7 @@ + +/** + * save a color buffer to a PPM file + */ +export function toPPM (buffer: Uint8Array, w: number, h: number) { + return `P3 ${w} ${h} 255\n${buffer.filter((e, i) => i % 4 < 3).toString()}\n`; +} \ No newline at end of file diff --git a/cocos/core/3d/misc/read-mesh.ts b/cocos/core/3d/misc/read-mesh.ts new file mode 100644 index 0000000000..47b36a87ba --- /dev/null +++ b/cocos/core/3d/misc/read-mesh.ts @@ -0,0 +1,32 @@ + +import { GFXAttributeName, GFXFormat, GFXFormatInfos, GFXFormatType, GFXPrimitiveMode, IGFXFormatInfo } from '../../gfx/define'; +import { Mesh } from '../../assets/mesh'; +import { IGeometry } from '../../primitive/define'; +import { readBuffer } from './buffer'; + +enum _keyMap { + positions = GFXAttributeName.ATTR_POSITION, + normals = GFXAttributeName.ATTR_NORMAL, + uvs = GFXAttributeName.ATTR_TEX_COORD, + colors = GFXAttributeName.ATTR_COLOR, +} + +export function readMesh (mesh: Mesh, iPrimitive: number = 0) { + const out: IGeometry = { positions: [] }; + const dataView = new DataView(mesh._nativeAsset); + const struct = mesh.struct; + const primitive = struct.primitives[iPrimitive]; + for (const idx of primitive.vertexBundelIndices) { + const bundle = struct.vertexBundles[idx]; + let offset = bundle.view.offset; + const { length, stride } = bundle.view; + for (const attr of bundle.attributes) { + const name: GFXAttributeName = _keyMap[attr.name]; + if (name) { out[name] = (out[name] || []).concat(readBuffer(dataView, attr.format, offset, length, stride)); } + offset += GFXFormatInfos[attr.format].size; + } + } + const view = primitive.indexView!; + out.indices = readBuffer(dataView, GFXFormat[`R${view.stride * 8}UI`], view.offset, view.length); + return out; +} \ No newline at end of file diff --git a/cocos/core/3d/misc/utils.ts b/cocos/core/3d/misc/utils.ts index d9b1c009bf..b725ec797a 100644 --- a/cocos/core/3d/misc/utils.ts +++ b/cocos/core/3d/misc/utils.ts @@ -1,339 +1,7 @@ -import { GFXAttributeName, GFXFormat, GFXFormatInfos, GFXFormatType, GFXPrimitiveMode, IGFXFormatInfo } from '../../gfx/define'; + export { find } from '../../scene-graph/find'; -import { Mesh } from '../../assets/mesh'; -import { IGFXAttribute } from '../../gfx/input-assembler'; -import { Vec3 } from '../../math'; -import { IGeometry } from '../../primitive/define'; -import { BufferBlob } from './buffer-blob'; - -/** - * save a color buffer to a PPM file - */ -export function toPPM (buffer: Uint8Array, w: number, h: number) { - return `P3 ${w} ${h} 255\n${buffer.filter((e, i) => i % 4 < 3).toString()}\n`; -} - -enum _keyMap { - positions = GFXAttributeName.ATTR_POSITION, - normals = GFXAttributeName.ATTR_NORMAL, - uvs = GFXAttributeName.ATTR_TEX_COORD, - colors = GFXAttributeName.ATTR_COLOR, -} - -const _defAttrs: IGFXAttribute[] = [ - { name: GFXAttributeName.ATTR_POSITION, format: GFXFormat.RGB32F }, - { name: GFXAttributeName.ATTR_NORMAL, format: GFXFormat.RGB32F }, - { name: GFXAttributeName.ATTR_TEX_COORD, format: GFXFormat.RG32F }, - { name: GFXAttributeName.ATTR_COLOR, format: GFXFormat.RGBA32F }, -]; - -export interface ICreateMeshOptions { - calculateBounds?: boolean; -} - -const v3_1 = new Vec3(); -export function createMesh (geometry: IGeometry, out?: Mesh, options?: ICreateMeshOptions) { - options = options || {}; - // Collect attributes and calculate length of result vertex buffer. - const attributes: IGFXAttribute[] = []; - let stride = 0; - const channels: Array<{ offset: number; data: number[]; attribute: IGFXAttribute; }> = []; - let vertCount = 0; - - let attr: IGFXAttribute | null; - - if (geometry.positions.length > 0) { - attr = null; - if (geometry.attributes) { - for (const att of geometry.attributes) { - if (att.name === GFXAttributeName.ATTR_POSITION) { - attr = att; - break; - } - } - } - - if (!attr) { - attr = _defAttrs[0]; - } - - const info = GFXFormatInfos[attr.format]; - attributes.push(attr); - vertCount = Math.max(vertCount, Math.floor(geometry.positions.length / info.count)); - channels.push({ offset: stride, data: geometry.positions, attribute: attr }); - stride += info.size; - } - - if (geometry.normals && geometry.normals.length > 0) { - attr = null; - if (geometry.attributes) { - for (const att of geometry.attributes) { - if (att.name === GFXAttributeName.ATTR_NORMAL) { - attr = att; - break; - } - } - } - - if (!attr) { - attr = _defAttrs[1]; - } - - const info = GFXFormatInfos[attr.format]; - attributes.push(attr); - vertCount = Math.max(vertCount, Math.floor(geometry.normals.length / info.count)); - channels.push({ offset: stride, data: geometry.normals, attribute: attr }); - stride += info.size; - } - - if (geometry.uvs && geometry.uvs.length > 0) { - attr = null; - if (geometry.attributes) { - for (const att of geometry.attributes) { - if (att.name === GFXAttributeName.ATTR_TEX_COORD) { - attr = att; - break; - } - } - } - - if (!attr) { - attr = _defAttrs[2]; - } - - const info = GFXFormatInfos[attr.format]; - attributes.push(attr); - vertCount = Math.max(vertCount, Math.floor(geometry.uvs.length / info.count)); - channels.push({ offset: stride, data: geometry.uvs, attribute: attr }); - stride += info.size; - } - - if (geometry.colors && geometry.colors.length > 0) { - attr = null; - if (geometry.attributes) { - for (const att of geometry.attributes) { - if (att.name === GFXAttributeName.ATTR_COLOR) { - attr = att; - break; - } - } - } - - if (!attr) { - attr = _defAttrs[3]; - } - - const info = GFXFormatInfos[attr.format]; - attributes.push(attr); - vertCount = Math.max(vertCount, Math.floor(geometry.colors.length / info.count)); - channels.push({ offset: stride, data: geometry.colors, attribute: attr }); - stride += info.size; - } - - if (geometry.customAttributes) { - for (const ca of geometry.customAttributes) { - const info = GFXFormatInfos[ca.attr.format]; - attributes.push(ca.attr); - vertCount = Math.max(vertCount, Math.floor(ca.values.length / info.count)); - channels.push({ offset: stride, data: ca.values, attribute: ca.attr }); - stride += info.size; - } - } - - // Use this to generate final merged buffer. - const bufferBlob = new BufferBlob(); - - // Fill vertex buffer. - const vertexBuffer = new ArrayBuffer(vertCount * stride); - const vertexBufferView = new DataView(vertexBuffer); - for (const channel of channels) { - writeBuffer(vertexBufferView, channel.data, channel.attribute.format, channel.offset, stride); - } - bufferBlob.setNextAlignment(0); - const vertexBundle: Mesh.VertexBundle = { - attributes, - view: { - offset: bufferBlob.getLength(), - length: vertexBuffer.byteLength, - count: vertCount, - stride, - }, - }; - bufferBlob.addBuffer(vertexBuffer); - - // Fill index buffer. - let indexBuffer: ArrayBuffer | null = null; - let idxCount = 0; - const idxStride = 2; - if (geometry.indices) { - const { indices } = geometry; - idxCount = indices.length; - indexBuffer = new ArrayBuffer(idxStride * idxCount); - const indexBufferView = new DataView(indexBuffer); - writeBuffer(indexBufferView, indices, GFXFormat.R16UI); - } - - // Create primitive. - const primitive: Mesh.Submesh = { - primitiveMode: geometry.primitiveMode || GFXPrimitiveMode.TRIANGLE_LIST, - vertexBundelIndices: [0], - }; - // geometric info for raycasting - if (primitive.primitiveMode >= GFXPrimitiveMode.TRIANGLE_LIST) { - const geomInfo = Float32Array.from(geometry.positions); - bufferBlob.setNextAlignment(4); - primitive.geometricInfo = { - doubleSided: geometry.doubleSided, - view: { - offset: bufferBlob.getLength(), - length: geomInfo.byteLength, - count: geometry.positions.length / 4, - stride: 4, - }, - }; - bufferBlob.addBuffer(geomInfo.buffer); - } - - if (indexBuffer) { - bufferBlob.setNextAlignment(idxStride); - primitive.indexView = { - offset: bufferBlob.getLength(), - length: indexBuffer.byteLength, - count: idxCount, - stride: idxStride, - }; - bufferBlob.addBuffer(indexBuffer); - } - - let minPosition = geometry.minPos; - if (!minPosition && options.calculateBounds) { - minPosition = Vec3.set(new Vec3(), Infinity, Infinity, Infinity); - for (let iVertex = 0; iVertex < vertCount; ++iVertex) { - Vec3.set(v3_1, geometry.positions[iVertex * 3 + 0], geometry.positions[iVertex * 3 + 1], geometry.positions[iVertex * 3 + 2]); - Vec3.min(minPosition, minPosition, v3_1); - } - } - let maxPosition = geometry.maxPos; - if (!maxPosition && options.calculateBounds) { - maxPosition = Vec3.set(new Vec3(), -Infinity, -Infinity, -Infinity); - for (let iVertex = 0; iVertex < vertCount; ++iVertex) { - Vec3.set(v3_1, geometry.positions[iVertex * 3 + 0], geometry.positions[iVertex * 3 + 1], geometry.positions[iVertex * 3 + 2]); - Vec3.max(maxPosition, maxPosition, v3_1); - } - } - - // Create mesh struct. - const meshStruct: Mesh.Struct = { - vertexBundles: [vertexBundle], - primitives: [primitive], - }; - if (minPosition) { - meshStruct.minPosition = new Vec3(minPosition.x, minPosition.y, minPosition.z); - } - if (maxPosition) { - meshStruct.maxPosition = new Vec3(maxPosition.x, maxPosition.y, maxPosition.z); - } - - // Create mesh. - if (!out) { - out = new Mesh(); - } - out.reset({ - struct: meshStruct, - data: new Uint8Array(bufferBlob.getCombined()), - }); - - return out; -} -export function readMesh (mesh: Mesh, iPrimitive: number = 0) { - const out: IGeometry = { positions: [] }; - const dataView = new DataView(mesh._nativeAsset); - const struct = mesh.struct; - const primitive = struct.primitives[iPrimitive]; - for (const idx of primitive.vertexBundelIndices) { - const bundle = struct.vertexBundles[idx]; - let offset = bundle.view.offset; - const { length, stride } = bundle.view; - for (const attr of bundle.attributes) { - const name: GFXAttributeName = _keyMap[attr.name]; - if (name) { out[name] = (out[name] || []).concat(readBuffer(dataView, attr.format, offset, length, stride)); } - offset += GFXFormatInfos[attr.format].size; - } - } - const view = primitive.indexView!; - out.indices = readBuffer(dataView, GFXFormat[`R${view.stride * 8}UI`], view.offset, view.length); - return out; -} - -const isLittleEndian = cc.sys.isLittleEndian; -const _typeMap = { - [GFXFormatType.UNORM]: 'Uint', - [GFXFormatType.SNORM]: 'Int', - [GFXFormatType.UINT]: 'Uint', - [GFXFormatType.INT]: 'Int', - [GFXFormatType.UFLOAT]: 'Float', - [GFXFormatType.FLOAT]: 'Float', - default: 'Uint', -}; -function _getDataViewType (info: IGFXFormatInfo) { - const type = _typeMap[info.type] || _typeMap.default; - const bytes = info.size / info.count * 8; - return type + bytes; -} -// default params bahaves just like on an plain, compact Float32Array -export function writeBuffer (target: DataView, data: number[], format: GFXFormat = GFXFormat.R32F, offset: number = 0, stride: number = 0) { - const info = GFXFormatInfos[format]; - if (!stride) { stride = info.size; } - const writer = 'set' + _getDataViewType(info); - const componentBytesLength = info.size / info.count; - const nSeg = Math.floor(data.length / info.count); - - for (let iSeg = 0; iSeg < nSeg; ++iSeg) { - const x = offset + stride * iSeg; - for (let iComponent = 0; iComponent < info.count; ++iComponent) { - const y = x + componentBytesLength * iComponent; - target[writer](y, data[info.count * iSeg + iComponent], isLittleEndian); - } - } -} -export function readBuffer ( - target: DataView, format: GFXFormat = GFXFormat.R32F, offset: number = 0, - length: number = target.byteLength - offset, stride: number = 0, out: number[] = []) { - const info = GFXFormatInfos[format]; - if (!stride) { stride = info.size; } - const reader = 'get' + _getDataViewType(info); - const componentBytesLength = info.size / info.count; - const nSeg = Math.floor(length / stride); - - for (let iSeg = 0; iSeg < nSeg; ++iSeg) { - const x = offset + stride * iSeg; - for (let iComponent = 0; iComponent < info.count; ++iComponent) { - const y = x + componentBytesLength * iComponent; - out[info.count * iSeg + iComponent] = target[reader](y, isLittleEndian); - } - } - return out; -} -export function mapBuffer ( - target: DataView, callback: (cur: number, idx: number, view: DataView) => number, format: GFXFormat = GFXFormat.R32F, - offset: number = 0, length: number = target.byteLength - offset, stride: number = 0, out?: DataView) { - if (!out) { out = new DataView(new ArrayBuffer(target.byteLength)); } - const info = GFXFormatInfos[format]; - if (!stride) { stride = info.size; } - const writer = 'set' + _getDataViewType(info); - const reader = 'get' + _getDataViewType(info); - const componentBytesLength = info.size / info.count; - const nSeg = Math.floor(length / stride); - - for (let iSeg = 0; iSeg < nSeg; ++iSeg) { - const x = offset + stride * iSeg; - for (let iComponent = 0; iComponent < info.count; ++iComponent) { - const y = x + componentBytesLength * iComponent; - const cur = target[reader](y, isLittleEndian); - // iComponent is usually more useful than y - out[writer](y, callback(cur, iComponent, target), isLittleEndian); - } - } - return out; -} +export { toPPM } from './ppm'; +export { readMesh } from './read-mesh'; +export { createMesh } from './create-mesh'; +export { readBuffer, writeBuffer, mapBuffer } from './buffer'; \ No newline at end of file diff --git a/cocos/core/animation/animation-component.ts b/cocos/core/animation/animation-component.ts index 59d3523202..95d0af765f 100644 --- a/cocos/core/animation/animation-component.ts +++ b/cocos/core/animation/animation-component.ts @@ -99,7 +99,7 @@ export class AnimationComponent extends Component implements IEventTarget { */ @property({ type: [AnimationClip], - tooltip:'此动画组件的自有动画剪辑', + tooltip: '此动画组件的自有动画剪辑', }) get clips () { return this._clips; @@ -142,7 +142,7 @@ export class AnimationComponent extends Component implements IEventTarget { */ @property({ type: AnimationClip, - tooltip:'默认动画剪辑', + tooltip: '默认动画剪辑', }) get defaultClip () { return this._defaultClip; @@ -169,7 +169,7 @@ export class AnimationComponent extends Component implements IEventTarget { * 是否在动画组件开始运行时自动播放默认动画剪辑。 */ @property({ - tooltip:'是否在动画组件开始运行时自动播放默认动画剪辑', + tooltip: '是否在动画组件开始运行时自动播放默认动画剪辑', }) public playOnLoad = false; diff --git a/cocos/core/animation/animation-state.ts b/cocos/core/animation/animation-state.ts index 17a587e298..50731f1991 100644 --- a/cocos/core/animation/animation-state.ts +++ b/cocos/core/animation/animation-state.ts @@ -33,17 +33,16 @@ import { AnimationBlendState, PropertyBlendState } from './animation-blend-state import { AnimationClip, IRuntimeCurve } from './animation-clip'; import { AnimCurve, RatioSampler } from './animation-curve'; import { additive3D, additiveQuat, BlendFunction } from './blending'; -import { Playable } from './playable'; import { BoundTarget, BufferedTarget } from './bound-target'; +import { Playable } from './playable'; import { WrapMode, WrapModeMask, WrappedInfo } from './types'; -import { warn } from '../platform'; enum PropertySpecialization { NodePosition, NodeScale, NodeRotation, None, -}; +} export class ICurveInstance { public commonTargetIndex?: number; @@ -114,7 +113,7 @@ export class ICurveInstance { return; } let value: any; - if (!lerpRequired) { + if (!this._curve.hasLerp() || !lerpRequired) { value = this._curve.valueAt(index); } else { value = this._curve.valueBetween( @@ -646,18 +645,9 @@ export class AnimationState extends Playable { } public simpleProcess () { - let time = this.time; const duration = this.duration; - - if (time > duration) { - time = time % duration; - if (time === 0) { time = duration; } - } - else if (time < 0) { - time = time % duration; - if (time !== 0) { time += duration; } - } - + let time = this.time % duration; + if (time < 0) { time += duration; } const ratio = time / duration; this._sampleCurves(ratio); @@ -727,14 +717,14 @@ export class AnimationState extends Playable { this.emit('pause', this); } - private _sampleCurves (ratio: number) { + protected _sampleCurves (ratio: number) { // Before we sample, we pull values of common targets. for (let iCommonTarget = 0; iCommonTarget < this._commonTargetStatuses.length; ++iCommonTarget) { const commonTarget = this._commonTargetStatuses[iCommonTarget]; commonTarget.target.pull(); commonTarget.changed = false; } - + for (let iSamplerSharedGroup = 0, szSamplerSharedGroup = this._samplerSharedGroups.length; iSamplerSharedGroup < szSamplerSharedGroup; ++iSamplerSharedGroup) { const samplerSharedGroup = this._samplerSharedGroups[iSamplerSharedGroup]; diff --git a/cocos/core/animation/skeletal-animation-component.ts b/cocos/core/animation/skeletal-animation-component.ts index 3874f30087..46378c3689 100644 --- a/cocos/core/animation/skeletal-animation-component.ts +++ b/cocos/core/animation/skeletal-animation-component.ts @@ -75,12 +75,10 @@ export class SkeletalAnimationComponent extends AnimationComponent { public static Socket = Socket; @property({ type: [Socket] }) - public _sockets: Socket[] = []; + protected _sockets: Socket[] = []; protected _enablePreSample = true; - protected _animMgr: JointsAnimationInfo = null!; - @property({ type: [Socket], tooltip: 'Joint Sockets', @@ -101,31 +99,9 @@ export class SkeletalAnimationComponent extends AnimationComponent { return this._enablePreSample; } - protected _animInfo: IAnimInfo | null = null; - - set frameID (fid: number) { - const info = this._animInfo; - if (!info) { return; } - info.data[1] = fid; - info.dirty = true; - } - get frameID () { - const info = this._animInfo; - return info && info.data[1] || 0; - } - - public onLoad () { - super.onLoad(); - this._animMgr = cc.director.root.dataPoolManager.jointsAnimationInfo; - this._animInfo = this._animMgr.create(this.node.uuid); - } - public onDestroy () { - if (this._animInfo) { - this._animMgr.destroy(this.node.uuid); - this._animInfo = null; - } super.onDestroy(); + cc.director.root.dataPoolManager.jointsAnimationInfo.destroy(this.node.uuid); } public start () { diff --git a/cocos/core/animation/skeletal-animation-data-hub.ts b/cocos/core/animation/skeletal-animation-data-hub.ts index 3288b310fe..95907869ee 100644 --- a/cocos/core/animation/skeletal-animation-data-hub.ts +++ b/cocos/core/animation/skeletal-animation-data-hub.ts @@ -27,12 +27,10 @@ * @category animation */ -import { Mat4, Quat, Vec3 } from '../math'; +import { clamp01, Mat4, Quat, Vec3 } from '../math'; import { DataPoolManager } from '../renderer/data-pool-manager'; -import { getClassName } from '../utils/js'; -import { AnimationClip, IObjectCurveData, IRuntimeCurve } from './animation-clip'; -import { AnimCurve, RatioSampler } from './animation-curve'; -import { ComponentPath, HierarchyPath, isCustomPath, isPropertyPath } from './target-path'; +import { AnimationClip, IObjectCurveData } from './animation-clip'; +import { HierarchyPath, isCustomPath, isPropertyPath } from './target-path'; type CurveData = Vec3 | Quat | Mat4; type ConvertedProps = Record; @@ -42,7 +40,6 @@ interface IPropertyCurve { values: CurveData[]; } interface ISkeletalCurveInfo { - curves: IRuntimeCurve[]; frames: number; sample: number; } @@ -110,26 +107,15 @@ function convertToSkeletalCurves (clip: AnimationClip): IConvertedData { }, }); } - const values: number[] = new Array(frames); const ratios: number[] = new Array(frames); - for (let i = 0; i < frames; i++) { values[i] = i; ratios[i] = i / (frames - 1); } const info: ISkeletalCurveInfo = { frames, sample: clip.sample, - curves: [{ - curve: new AnimCurve({ values, interpolate: false }, (frames - 1) / clip.sample), - modifiers: [ - new HierarchyPath(''), - new ComponentPath(getClassName(cc.SkeletalAnimationComponent)), - 'frameID', - ], - sampler: new RatioSampler(ratios), - }], }; return { info, data }; } function convertToUniformSample (clip: AnimationClip, curve: IPropertyCurve, frames: number) { - const keys = clip.keys[curve.keys]; curve.keys = 0; + const keys = clip.keys[curve.keys]; const values: CurveData[] = []; if (!keys || keys.length === 1) { for (let i = 0; i < frames; i++) { @@ -142,7 +128,7 @@ function convertToUniformSample (clip: AnimationClip, curve: IPropertyCurve, fra if (idx > keys.length - 1) { idx = keys.length - 1; time = keys[idx]; } else if (idx === 0) { idx = 1; } const from = curve.values[idx - 1].clone() as any; - from.lerp(curve.values[idx], (time - keys[idx - 1]) / (keys[idx] - keys[idx - 1])); + from.lerp(curve.values[idx], clamp01((time - keys[idx - 1]) / (keys[idx] - keys[idx - 1]))); values[i] = from; } } diff --git a/cocos/core/animation/skeletal-animation-state.ts b/cocos/core/animation/skeletal-animation-state.ts index 3487fba0ae..f262223114 100644 --- a/cocos/core/animation/skeletal-animation-state.ts +++ b/cocos/core/animation/skeletal-animation-state.ts @@ -29,27 +29,28 @@ import { SkinningModelComponent } from '../3d/framework/skinning-model-component'; import { Mat4 } from '../math'; -import { AnimationClip, IObjectCurveData } from './animation-clip'; -import { AnimCurve } from './animation-curve'; -import { AnimationState, ICurveInstance } from './animation-state'; +import { IAnimInfo, JointsAnimationInfo } from '../renderer/models/skeletal-animation-utils'; +import { Node } from '../scene-graph'; +import { AnimationClip } from './animation-clip'; +import { AnimationState } from './animation-state'; import { Socket } from './skeletal-animation-component'; import { SkelAnimDataHub } from './skeletal-animation-data-hub'; -import { ComponentPath, TargetPath, HierarchyPath } from './target-path'; -import { getPathFromRoot, getWorldTransformUntilRoot } from './transform-utils'; -import { Node } from '../scene-graph'; +import { getWorldTransformUntilRoot } from './transform-utils'; const m4_1 = new Mat4(); +const _defaultCurves = []; // no curves -function isFrameIDCurve (modifiers: TargetPath[]) { - return modifiers.length === 3 && - modifiers[0] instanceof HierarchyPath && - modifiers[1] instanceof ComponentPath && - modifiers[2] === 'frameID'; +interface ISocketData { + target: Node; + frames: Mat4[]; } export class SkeletalAnimationState extends AnimationState { protected _preSample = true; + protected _frames = 1; + protected _animInfo: IAnimInfo | null = null; + protected _sockets: ISocketData[] = []; constructor (clip: AnimationClip, name = '', preSample = true) { super(clip, name); @@ -57,10 +58,13 @@ export class SkeletalAnimationState extends AnimationState { } public initialize (root: Node) { + if (this._curveLoaded) { return; } if (this._preSample) { const info = SkelAnimDataHub.getOrExtract(this.clip).info; - super.initialize(root, info.curves); - this.duration = (info.frames - 1) / info.sample; // last key + super.initialize(root, _defaultCurves); + this._frames = info.frames - 1; + this._animInfo = (cc.director.root.dataPoolManager.jointsAnimationInfo as JointsAnimationInfo).create(root.uuid); + this.duration = this._frames / info.sample; // last key } else { super.initialize(root); } @@ -78,22 +82,21 @@ export class SkeletalAnimationState extends AnimationState { } public rebuildSocketCurves (sockets: Socket[]) { - // TODO: curve reuse perhaps? - // delete previous sockets - if (!this._samplerSharedGroups.length) { return; } - const curves = this._samplerSharedGroups[0].curves; - for (let iCurve = 0; iCurve < curves.length; iCurve++) { - const curveDetail = curves[iCurve].curveDetail; - if (isFrameIDCurve(curveDetail.modifiers)) { - continue; - } else { - curves.splice(iCurve--, 1); - } + this._sockets.length = 0; + for (let i = 0; i < sockets.length; ++i) { + const socket = this._buildSocketData(sockets[i]); + if (socket) { this._sockets.push(socket); } } - // build new ones - for (let iSocket = 0; iSocket < sockets.length; ++iSocket) { - const curve = this._buildSocketData(sockets[iSocket]); - if (curve) { curves.push(curve); } + } + + protected _sampleCurves (ratio: number) { + const info = this._animInfo!; + const curFrame = (ratio * this._frames + 0.5) | 0; + info.data[1] = curFrame; + info.dirty = true; + for (let i = 0; i < this._sockets.length; ++i) { + const { target, frames } = this._sockets[i]; + target.matrix = frames[curFrame]; // ratio guaranteed to be in [0, 1] } } @@ -116,34 +119,17 @@ export class SkeletalAnimationState extends AnimationState { if (idx < 0) { return null; } } // create animation data - const data: IObjectCurveData = { - matrix: { keys: 0, interpolate: false, values: source.worldMatrix.values.map((v) => v.clone()) }, + const socketData: ISocketData = { + target: socket.target, + frames: source.worldMatrix.values.map((v) => v.clone()) as Mat4[], }; - const matrix = data.matrix.values; // apply downstream default pose getWorldTransformUntilRoot(targetNode, animNode, m4_1); - for (let i = 0; i < matrix.length; i++) { - const m = matrix[i]; + for (let i = 0; i < socketData.frames.length; i++) { + const m = socketData.frames[i]; Mat4.multiply(m, m, m4_1); } - if (CC_EDITOR) { // assign back to clip to sync with animation editor - const path = getPathFromRoot(socket.target, root); - const curves = this.clip.curves; - const dstcurve = curves.find((curve) => { - const modifier = curve.modifiers[0]; - return modifier instanceof HierarchyPath && modifier.path === path && curve.modifiers[1] === 'matrix'; - }); - if (dstcurve) { dstcurve.data = data.matrix; } - else { curves.push({ modifiers: [ new HierarchyPath(path), 'matrix' ], data: data.matrix }); } - this.clip.curves = curves; - } - // wrap up - const duration = this.clip.duration; - const hierarchyPath = new HierarchyPath(); - return new ICurveInstance({ - curve: new AnimCurve(data.matrix, duration), - modifiers: [ hierarchyPath, 'matrix' ], - }, socket.target); + return socketData; } } diff --git a/cocos/core/assets/skeleton.ts b/cocos/core/assets/skeleton.ts index 5c0de0d2fc..da65e35d7a 100644 --- a/cocos/core/assets/skeleton.ts +++ b/cocos/core/assets/skeleton.ts @@ -29,23 +29,11 @@ import { ccclass, property } from '../../core/data/class-decorator'; import { CCString } from '../../core/data/utils/attribute'; -import { Mat4, Quat, Vec3 } from '../../core/math'; +import { Mat4 } from '../../core/math'; import { murmurhash2_32_gc } from '../../core/utils/murmurhash2_gc'; -import { aabb } from '../geom-utils'; import { DataPoolManager } from '../renderer/data-pool-manager'; import { Asset } from './asset'; -export interface IBindTRS { - position: Vec3; - rotation: Quat; - scale: Vec3; -} - -const m4_1 = new Mat4(); -const v3_1 = new Vec3(); -const v3_min = new Vec3(); -const v3_max = new Vec3(); - /** * 骨骼资源。 * 骨骼资源记录了每个关节(相对于`SkinningModelComponent.skinningRoot`)的路径以及它的绑定姿势矩阵。 @@ -60,7 +48,6 @@ export class Skeleton extends Asset { private _bindposes: Mat4[] = []; private _hash = 0; - private _bounds = new aabb(); /** * 所有关节的绑定姿势矩阵。该数组的长度始终与 `this.joints` 的长度相同。 @@ -72,8 +59,6 @@ export class Skeleton extends Asset { set bindposes (value) { this._bindposes = value; let str = ''; - Vec3.set(v3_min, Infinity, Infinity, Infinity); - Vec3.set(v3_max, -Infinity, -Infinity, -Infinity); for (let i = 0; i < value.length; i++) { const ibm = value[i]; str += @@ -81,13 +66,8 @@ export class Skeleton extends Asset { ibm.m04.toPrecision(2) + ' ' + ibm.m05.toPrecision(2) + ' ' + ibm.m06.toPrecision(2) + ' ' + ibm.m07.toPrecision(2) + ' ' + ibm.m08.toPrecision(2) + ' ' + ibm.m09.toPrecision(2) + ' ' + ibm.m10.toPrecision(2) + ' ' + ibm.m11.toPrecision(2) + ' ' + ibm.m12.toPrecision(2) + ' ' + ibm.m13.toPrecision(2) + ' ' + ibm.m14.toPrecision(2) + ' ' + ibm.m15.toPrecision(2) + '\n'; - Mat4.invert(m4_1, ibm); - Vec3.set(v3_1, m4_1.m12, m4_1.m13, m4_1.m14); - Vec3.min(v3_min, v3_min, v3_1); - Vec3.max(v3_max, v3_max, v3_1); } this._hash = murmurhash2_32_gc(str, 666); - aabb.fromPoints(this._bounds, v3_min, v3_max); } /** @@ -105,10 +85,6 @@ export class Skeleton extends Asset { return this._hash; } - get bounds () { - return this._bounds; - } - public onLoaded () { this.bindposes = this._bindposes; } diff --git a/cocos/core/assets/texture-util.ts b/cocos/core/assets/texture-util.ts index bb34321535..d630b24469 100644 --- a/cocos/core/assets/texture-util.ts +++ b/cocos/core/assets/texture-util.ts @@ -30,12 +30,12 @@ import { assertID, error } from '../platform/debug'; import { loader } from '../load-pipeline/CCLoader'; -import { LoadCallbackParams } from '../load-pipeline/callback-params'; import { ImageAsset, ImageSource } from './image-asset'; export type LoadImageCallback = ( this: T | undefined, - ...args: LoadCallbackParams + error: Error | null | undefined, + asset?: ImageAsset, ) => void; /** diff --git a/cocos/core/components/ui-coodinate-tracker-component.ts b/cocos/core/components/ui-coodinate-tracker-component.ts index 5e1a228ccd..28f77f4729 100644 --- a/cocos/core/components/ui-coodinate-tracker-component.ts +++ b/cocos/core/components/ui-coodinate-tracker-component.ts @@ -147,6 +147,7 @@ export class UICoordinateTrackerComponent extends Component { protected _viewPos = new Vec3(); protected _canMove = true; protected _lastWpos = new Vec3(); + protected _lastCameraPos = new Vec3(); public onEnable () { this._checkCanMove(); @@ -154,17 +155,18 @@ export class UICoordinateTrackerComponent extends Component { public update () { const wpos = this.node.worldPosition; + const camera = this._camera; // @ts-ignore - if (!this._canMove || !this._camera!._camera || this._lastWpos.equals(wpos)) { + if (!this._canMove || !camera._camera || (this._lastWpos.equals(wpos) && this._lastCameraPos.equals(camera!.node.worldPosition))) { return; } this._lastWpos.set(wpos); - const camera = this._camera!; + this._lastCameraPos.set(camera!.node.worldPosition); // [HACK] // @ts-ignore camera._camera.update(); - convertUtils.WorldNode3DToLocalNodeUI(camera, wpos, this._target!, this._transformPos); + convertUtils.WorldNode3DToLocalNodeUI(camera!, wpos, this._target!, this._transformPos); if (this._useScale) { // @ts-ignore Vec3.transformMat4(this._viewPos, this.node.worldPosition, camera._camera!.matView); diff --git a/cocos/core/data/utils/compact-value-type-array.ts b/cocos/core/data/utils/compact-value-type-array.ts index b6d4de46d4..ab07bdd6fd 100644 --- a/cocos/core/data/utils/compact-value-type-array.ts +++ b/cocos/core/data/utils/compact-value-type-array.ts @@ -1,5 +1,5 @@ import { ccclass, property } from '../class-decorator'; -import { Vec3, Quat, Vec4, Vec2 } from '../../math'; +import { Vec3, Quat, Vec4, Vec2, Mat4 } from '../../math'; export enum StorageUnit { Uint8, Uint16, Uint32, @@ -13,6 +13,7 @@ export enum ElementType { Vec3, Vec4, Quat, + Mat4, } const elementTypeBits = 3; @@ -197,6 +198,15 @@ const BuiltinElementTypeTraits: Record = { return new Quat(storage[index * 4], storage[index * 4 + 1], storage[index * 4 + 2], storage[index * 4 + 3]); } }, + [ElementType.Mat4]: { + requiredUnits: 16, + compress (storage: CompactValueTypeArrayStorage, index: number, value: Mat4) { + Mat4.toArray(storage, value, index * 16); + }, + decompress (storage: CompactValueTypeArrayStorage, index: number) { + return Mat4.fromArray(new Mat4(), storage, index * 16); + }, + }, }; interface CompactValueTypeArrayStorage { diff --git a/cocos/core/game.ts b/cocos/core/game.ts index a948476e97..37f1daeddb 100644 --- a/cocos/core/game.ts +++ b/cocos/core/game.ts @@ -30,9 +30,9 @@ import { EventTarget } from './event/event-target'; import { WebGLGFXDevice } from './gfx/webgl/webgl-device'; import { WebGL2GFXDevice } from './gfx/webgl2/webgl2-device'; -import * as debug from './platform/debug'; -import { SplashScreen } from './splash-image'; import { ForwardPipeline } from './pipeline'; +import * as debug from './platform/debug'; + /** * @en * The current game configuration, including:
@@ -370,8 +370,21 @@ export class Game extends EventTarget { // Pause main loop if (this._intervalId) { window.cancelAnimationFrame(this._intervalId); + this._intervalId = 0; + } + // Because JSB platforms never actually stops the swap chain, + // we draw some more frames here to (try to) make sure swap chain consistency + if (CC_JSB || CC_RUNTIME_BASED) { + let swapbuffers = 3; + const cb = () => { + if (--swapbuffers > 1) { + window.requestAnimationFrame(cb); + } + const root = cc.director.root; + root.frameMove(0); root.device.present(); + }; + window.requestAnimationFrame(cb); } - this._intervalId = 0; } /** @@ -477,7 +490,7 @@ export class Game extends EventTarget { * @param {Object} [target] - The target (this object) to invoke the callback, can be null */ // @ts-ignore - public once (type: string, callback: Function, target: object) { + public once (type: string, callback: Function, target?: object) { // Make sure EVENT_ENGINE_INITED callbacks to be invoked if (this._prepared && type === Game.EVENT_ENGINE_INITED) { callback.call(target); @@ -572,7 +585,6 @@ export class Game extends EventTarget { } const start = () => { - this._prepared = true; this._setAnimFrame(); this._runMainLoop(); @@ -597,9 +609,10 @@ export class Game extends EventTarget { // Log engine version console.log('Cocos Creator 3D v' + cc.ENGINE_VERSION); this.emit(Game.EVENT_ENGINE_INITED); + this._prepared = true; // load renderpipeline - let config = this.config; + const config = this.config; cc.loader.load({ uuid: config.renderPipeline }, (err, asset) => { // failed load renderPipeline if (err || !(asset instanceof cc.RenderPipeline)) { @@ -613,14 +626,11 @@ export class Game extends EventTarget { this._rendererInitialized = true; this.emit(Game.EVENT_RENDERER_INITED); - if (cc.internal.SplashScreen) { - // Start splash screen - cc.internal.SplashScreen.instance.main(this._gfxDevice); - cc.internal.SplashScreen.instance.setOnFinish(cb); - cc.internal.SplashScreen.instance.loadFinish = true; - } - else { - cb && cb(); + if (!CC_EDITOR && !CC_PREVIEW && cc.internal.SplashScreenWebgl) { + cc.internal.SplashScreenWebgl.instance.setOnFinish(cb); + cc.internal.SplashScreenWebgl.instance.loadFinish = true; + } else if (cb) { + cb(); } }); } @@ -665,8 +675,7 @@ export class Game extends EventTarget { private _stTime (callback) { const currTime = new Date().getTime(); const timeToCall = Math.max(0, cc.game._frameTime - (currTime - cc.game._lastTime)); - const id = window.setTimeout(() => { callback(); }, - timeToCall); + const id = window.setTimeout(callback, timeToCall); cc.game._lastTime = currTime + timeToCall; return id; } @@ -675,9 +684,8 @@ export class Game extends EventTarget { } // Run game. private _runMainLoop () { - const self = this; let callback: FrameRequestCallback; - const config = self.config; + const config = this.config; const director = cc.director; let skip: boolean = true; const frameRate = config.frameRate; @@ -685,24 +693,22 @@ export class Game extends EventTarget { debug.setDisplayStats(!!config.showFPS); callback = (time: number) => { - if (!self._paused) { - self._intervalId = window.requestAnimationFrame(callback); - if (!CC_JSB && frameRate === 30) { - skip = !skip; - if (skip) { - return; - } + if (this._paused) { return; } + this._intervalId = window.requestAnimationFrame(callback); + if (!CC_JSB && frameRate === 30) { + skip = !skip; + if (skip) { + return; } - director.mainLoop(time); } + director.mainLoop(time); }; - self._intervalId = window.requestAnimationFrame(callback); - self._paused = false; + this._intervalId = window.requestAnimationFrame(callback); + this._paused = false; } - // @Game loading section - // tslint:disable-next-line: max-line-length + // @Game loading section private _initConfig (config: IGameConfig) { // Configs adjustment if (typeof config.debugMode !== 'number') { @@ -781,62 +787,70 @@ export class Game extends EventTarget { } } - const el = this.config.id; - let width: any; - let height: any; + // TODO: adapter for editor & preview let localCanvas: HTMLCanvasElement; - let localContainer: HTMLElement; + if (CC_EDITOR || CC_PREVIEW) { + const el = this.config.id; + let width: any; + let height: any; + let localContainer: HTMLElement; - if (CC_JSB) { - this.container = localContainer = document.createElement<'div'>('div'); - this.frame = localContainer.parentNode === document.body ? document.documentElement : localContainer.parentNode; - if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { - localCanvas = window.sharedCanvas || wx.getSharedCanvas(); - } - else if (CC_JSB) { - localCanvas = window.__canvas; + if (CC_JSB) { + this.container = localContainer = document.createElement<'div'>('div'); + this.frame = localContainer.parentNode === document.body ? document.documentElement : localContainer.parentNode; + if (cc.sys.browserType === cc.sys.BROWSER_TYPE_WECHAT_GAME_SUB) { + localCanvas = window.sharedCanvas || wx.getSharedCanvas(); + } + else if (CC_JSB) { + localCanvas = window.__canvas; + } + else { + localCanvas = window.canvas; + } + this.canvas = localCanvas; } else { - localCanvas = window.canvas; - } - this.canvas = localCanvas; - } - else { - const element = !el ? null : ((el instanceof HTMLElement) ? el : (document.querySelector(el) || document.querySelector('#' + el))); - if (!element) { - throw new Error(debug.getError(200)); - } - - if (element.tagName === 'CANVAS') { - width = (element as HTMLCanvasElement).width; - height = (element as HTMLCanvasElement).height; - - // it is already a canvas, we wrap it around with a div - this.canvas = localCanvas = (element as HTMLCanvasElement); - this.container = localContainer = document.createElement<'div'>('div'); - if (localCanvas && localCanvas.parentNode) { - localCanvas.parentNode.insertBefore(localContainer, localCanvas); + const element = !el ? null : ((el instanceof HTMLElement) ? el : (document.querySelector(el) || document.querySelector('#' + el))); + if (!element) { + throw new Error(debug.getError(200)); } - } else { - // we must make a new canvas and place into this element - if (element.tagName !== 'DIV') { - debug.warnID(3819); + + if (element.tagName === 'CANVAS') { + width = (element as HTMLCanvasElement).width; + height = (element as HTMLCanvasElement).height; + + // it is already a canvas, we wrap it around with a div + this.canvas = localCanvas = (element as HTMLCanvasElement); + this.container = localContainer = document.createElement<'div'>('div'); + if (localCanvas && localCanvas.parentNode) { + localCanvas.parentNode.insertBefore(localContainer, localCanvas); + } + } else { + // we must make a new canvas and place into this element + if (element.tagName !== 'DIV') { + debug.warnID(3819); + } + width = element.clientWidth; + height = element.clientHeight; + + this.canvas = localCanvas = document.createElement('canvas'); + this.container = localContainer = document.createElement<'div'>('div'); + element.appendChild(localContainer); } - width = element.clientWidth; - height = element.clientHeight; + localContainer.setAttribute('id', 'Cocos3dGameContainer'); + localContainer.appendChild(localCanvas!); + this.frame = (localContainer.parentNode === document.body) ? document.documentElement : localContainer.parentNode; - this.canvas = localCanvas = document.createElement('canvas'); - this.container = localContainer = document.createElement<'div'>('div'); - element.appendChild(localContainer); + addClass(localCanvas!, 'gameCanvas'); + localCanvas.setAttribute('width', width || '480'); + localCanvas.setAttribute('height', height || '320'); + localCanvas.setAttribute('tabindex', '99'); } - localContainer.setAttribute('id', 'Cocos3dGameContainer'); - localContainer.appendChild(localCanvas!); - this.frame = (localContainer.parentNode === document.body) ? document.documentElement : localContainer.parentNode; - - addClass(localCanvas!, 'gameCanvas'); - localCanvas.setAttribute('width', width || '480'); - localCanvas.setAttribute('height', height || '320'); - localCanvas.setAttribute('tabindex', '99'); + } else { + this.canvas = (this.config as any).adapter.canvas; + this.frame = (this.config as any).adapter.frame; + this.container = (this.config as any).adapter.container; + localCanvas = this.canvas as HTMLCanvasElement; } this._determineRenderType(); @@ -845,7 +859,7 @@ export class Game extends EventTarget { if (this.renderType === Game.RENDER_TYPE_WEBGL) { let useWebGL2 = (!!window.WebGL2RenderingContext); - const userAgent = navigator.userAgent.toLowerCase(); + const userAgent = window.navigator.userAgent.toLowerCase(); if (userAgent.indexOf('safari') !== -1) { if (userAgent.indexOf('chrome') === -1) { useWebGL2 = false; diff --git a/cocos/core/geom-utils/intersect.ts b/cocos/core/geom-utils/intersect.ts index bba216818c..15a2fd8c9f 100644 --- a/cocos/core/geom-utils/intersect.ts +++ b/cocos/core/geom-utils/intersect.ts @@ -133,7 +133,7 @@ const ray_aabb = (function () { const tmin = Math.max(Math.max(Math.min(t1, t2), Math.min(t3, t4)), Math.min(t5, t6)); const tmax = Math.min(Math.min(Math.max(t1, t2), Math.max(t3, t4)), Math.max(t5, t6)); if (tmax < 0 || tmin > tmax) { return 0; } - return tmin; + return tmin > 0 ? tmin : tmax; // ray origin inside aabb }; })(); @@ -834,8 +834,8 @@ const obb_capsule = (function () { const v3_2 = new Vec3(); const v3_verts8 = new Array(8); for (let i = 0; i < 8; i++) { v3_verts8[i] = new Vec3(); } - const v3_axis7 = new Array(7); - for (let i = 0; i < 7; i++) { v3_axis7[i] = new Vec3(); } + const v3_axis8 = new Array(8); + for (let i = 0; i < 8; i++) { v3_axis8[i] = new Vec3(); } return function (obb: obb, capsule: capsule) { const h = Vec3.squaredDistance(capsule.ellipseCenter0, capsule.ellipseCenter1); if (h == 0) { @@ -854,25 +854,26 @@ const obb_capsule = (function () { v3_2.z = obb.orientation.m08; getOBBVertices(obb.center, obb.halfExtents, v3_0, v3_1, v3_2, v3_verts8); - const axes = v3_axis7; + const axes = v3_axis8; const a0 = Vec3.copy(axes[0], v3_0); const a1 = Vec3.copy(axes[1], v3_1); const a2 = Vec3.copy(axes[2], v3_2); - const B = Vec3.subtract(axes[3], capsule.ellipseCenter0, capsule.ellipseCenter1); - Vec3.cross(axes[4], a0, B); - Vec3.cross(axes[5], a1, B); - Vec3.cross(axes[6], a2, B); - for (let i = 0; i < 7; ++i) { + const C = Vec3.subtract(axes[3], capsule.center, obb.center); + C.normalize(); + const B = Vec3.subtract(axes[4], capsule.ellipseCenter0, capsule.ellipseCenter1); + B.normalize(); + Vec3.cross(axes[5], a0, B); + Vec3.cross(axes[6], a1, B); + Vec3.cross(axes[7], a2, B); + + for (let i = 0; i < 8; ++i) { const a = getInterval(v3_verts8, axes[i]); const d0 = Vec3.dot(axes[i], capsule.ellipseCenter0); const d1 = Vec3.dot(axes[i], capsule.ellipseCenter1); - const d0_min = d0 - capsule.radius; - const d0_max = d0 + capsule.radius; - const d1_min = d1 - capsule.radius; - const d1_max = d1 + capsule.radius; - const d_max = Math.max(d0_min, d1_min, d0_max, d1_max); - const d_min = Math.min(d0_min, d1_min, d0_max, d1_max); - + const max_d = Math.max(d0, d1); + const min_d = Math.min(d0, d1); + const d_min = min_d - capsule.radius; + const d_max = max_d + capsule.radius; if (d_min > a[1] || a[0] > d_max) { return 0; // Seperating axis found } diff --git a/cocos/core/gfx/input-assembler.ts b/cocos/core/gfx/input-assembler.ts index 12df4cdf45..275f90b51b 100644 --- a/cocos/core/gfx/input-assembler.ts +++ b/cocos/core/gfx/input-assembler.ts @@ -2,7 +2,7 @@ * @category gfx */ -import { writeBuffer } from '../3d/misc/utils'; +import { writeBuffer } from '../3d/misc/buffer'; import { GFXBuffer, GFXBufferSource, IGFXDrawInfo } from './buffer'; import { GFXFormat, GFXFormatInfos, GFXObject, GFXObjectType } from './define'; import { GFXDevice } from './device'; diff --git a/cocos/core/gfx/pipeline-state.ts b/cocos/core/gfx/pipeline-state.ts index e7888a483d..e85d4b0236 100644 --- a/cocos/core/gfx/pipeline-state.ts +++ b/cocos/core/gfx/pipeline-state.ts @@ -69,16 +69,16 @@ export class GFXDepthStencilState { public depthFunc: GFXComparisonFunc = GFXComparisonFunc.LESS; public stencilTestFront: boolean = false; public stencilFuncFront: GFXComparisonFunc = GFXComparisonFunc.ALWAYS; - public stencilReadMaskFront: number = 0xffffffff; - public stencilWriteMaskFront: number = 0xffffffff; + public stencilReadMaskFront: number = -1; + public stencilWriteMaskFront: number = -1; public stencilFailOpFront: GFXStencilOp = GFXStencilOp.KEEP; public stencilZFailOpFront: GFXStencilOp = GFXStencilOp.KEEP; public stencilPassOpFront: GFXStencilOp = GFXStencilOp.KEEP; public stencilRefFront: number = 1; public stencilTestBack: boolean = false; public stencilFuncBack: GFXComparisonFunc = GFXComparisonFunc.ALWAYS; - public stencilReadMaskBack: number = 0xffffffff; - public stencilWriteMaskBack: number = 0xffffffff; + public stencilReadMaskBack: number = -1; + public stencilWriteMaskBack: number = -1; public stencilFailOpBack: GFXStencilOp = GFXStencilOp.KEEP; public stencilZFailOpBack: GFXStencilOp = GFXStencilOp.KEEP; public stencilPassOpBack: GFXStencilOp = GFXStencilOp.KEEP; diff --git a/cocos/core/gfx/webgl/webgl-commands.ts b/cocos/core/gfx/webgl/webgl-commands.ts index bbac63cf84..8e9e302c90 100644 --- a/cocos/core/gfx/webgl/webgl-commands.ts +++ b/cocos/core/gfx/webgl/webgl-commands.ts @@ -1187,8 +1187,13 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web console.error('Shader source dump:', gpuStage.source.replace(/^|\n/g, () => `\n${lineNumber++} `)); console.error(gl.getShaderInfoLog(gpuStage.glShader)); - gl.deleteShader(gpuStage.glShader); - gpuStage.glShader = null; + for (let l = 0; l < gpuShader.gpuStages.length; l++) { + const stage = gpuShader.gpuStages[k]; + if (stage.glShader) { + gl.deleteShader(stage.glShader); + stage.glShader = null; + } + } return; } } @@ -1208,19 +1213,22 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web } gl.linkProgram(gpuShader.glProgram); + + // detach & delete immediately + for (let k = 0; k < gpuShader.gpuStages.length; k++) { + const gpuStage = gpuShader.gpuStages[k]; + if (gpuStage.glShader) { + gl.detachShader(gpuShader.glProgram, gpuStage.glShader); + gl.deleteShader(gpuStage.glShader); + gpuStage.glShader = null; + } + } + if (gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS)) { console.info('Shader \'' + gpuShader.name + '\' compilation succeeded.'); } else { console.error('Failed to link shader \'' + gpuShader.name + '\'.'); console.error(gl.getProgramInfoLog(gpuShader.glProgram)); - - for (let k = 0; k < gpuShader.gpuStages.length; k++) { - const gpuStage = gpuShader.gpuStages[k]; - if (gpuStage.glShader) { - gl.deleteShader(gpuStage.glShader); - gpuStage.glShader = null; - } - } return; } @@ -1426,15 +1434,6 @@ export function WebGLCmdFuncCreateShader (device: WebGLGFXDevice, gpuShader: Web } export function WebGLCmdFuncDestroyShader (device: WebGLGFXDevice, gpuShader: WebGLGPUShader) { - - for (let i = 0; i < gpuShader.gpuStages.length; i++) { - const gpuStage = gpuShader.gpuStages[i]; - if (gpuStage.glShader) { - device.gl.deleteShader(gpuStage.glShader); - gpuStage.glShader = null; - } - } - if (gpuShader.glProgram) { device.gl.deleteProgram(gpuShader.glProgram); gpuShader.glProgram = null; @@ -1613,11 +1612,11 @@ export function WebGLCmdFuncExecuteCmds (device: WebGLGFXDevice, cmdPackage: Web case GFXLoadOp.CLEAR: { if (cmd0.clearFlag & GFXClearFlag.STENCIL) { if (!cache.dss.stencilWriteMaskFront) { - gl.stencilMaskSeparate(gl.FRONT, 0xFFFFFFFF); + gl.stencilMaskSeparate(gl.FRONT, -1); } if (!cache.dss.stencilWriteMaskBack) { - gl.stencilMaskSeparate(gl.BACK, 0xFFFFFFFF); + gl.stencilMaskSeparate(gl.BACK, -1); } gl.clearStencil(cmd0.clearStencil); diff --git a/cocos/core/gfx/webgl/webgl-device.ts b/cocos/core/gfx/webgl/webgl-device.ts index 7a7b84c03f..6b601c9014 100644 --- a/cocos/core/gfx/webgl/webgl-device.ts +++ b/cocos/core/gfx/webgl/webgl-device.ts @@ -1,3 +1,4 @@ +import { macro } from '../../platform'; import sys from '../../platform/sys'; import { GFXBindingLayout, IGFXBindingLayoutInfo } from '../binding-layout'; import { GFXBuffer, IGFXBufferInfo } from '../buffer'; @@ -201,7 +202,7 @@ export class WebGLGFXDevice extends GFXDevice { try { const webGLCtxAttribs: WebGLContextAttributes = { - alpha: false, + alpha: macro.ENABLE_TRANSPARENT_CANVAS, antialias: this._isAntialias, depth: true, stencil: true, @@ -256,6 +257,10 @@ export class WebGLGFXDevice extends GFXDevice { this._depthBits = gl.getParameter(gl.DEPTH_BITS); this._stencilBits = gl.getParameter(gl.STENCIL_BITS); + if (CC_ALIPAY) { + this._depthBits = 24; + } + this._devicePixelRatio = info.devicePixelRatio || 1.0; this._width = this._canvas.width; this._height = this._canvas.height; @@ -313,6 +318,10 @@ export class WebGLGFXDevice extends GFXDevice { this._OES_element_index_uint = this.getExtension('OES_element_index_uint'); this._ANGLE_instanced_arrays = this.getExtension('ANGLE_instanced_arrays'); + if (CC_ALIPAY) { + this._WEBGL_depth_texture = { UNSIGNED_INT_24_8_WEBGL: 0x84FA }; + } + this._features.fill(false); if (this._WEBGL_color_buffer_float) { @@ -382,6 +391,10 @@ export class WebGLGFXDevice extends GFXDevice { } else if ((sys.platform !== sys.WECHAT_GAME || sys.os !== sys.OS_IOS)) { this._useVAO = true; } } + if ((sys.platform === sys.WECHAT_GAME && sys.os === sys.OS_ANDROID)) { + gl.detachShader = () => {}; // Android WeChat may throw errors on detach shader + } + if (this._OES_element_index_uint) { this._features[GFXFeature.ELEMENT_INDEX_UINT] = true; } @@ -714,12 +727,12 @@ export class WebGLGFXDevice extends GFXDevice { gl.depthFunc(gl.LESS); gl.depthRange(0.0, 1.0); - gl.stencilFuncSeparate(gl.FRONT, gl.ALWAYS, 1, 0xffffffff); + gl.stencilFuncSeparate(gl.FRONT, gl.ALWAYS, 1, -1); gl.stencilOpSeparate(gl.FRONT, gl.KEEP, gl.KEEP, gl.KEEP); - gl.stencilMaskSeparate(gl.FRONT, 0xffffffff); - gl.stencilFuncSeparate(gl.BACK, gl.ALWAYS, 1, 0xffffffff); + gl.stencilMaskSeparate(gl.FRONT, -1); + gl.stencilFuncSeparate(gl.BACK, gl.ALWAYS, 1, -1); gl.stencilOpSeparate(gl.BACK, gl.KEEP, gl.KEEP, gl.KEEP); - gl.stencilMaskSeparate(gl.BACK, 0xffffffff); + gl.stencilMaskSeparate(gl.BACK, -1); gl.disable(gl.STENCIL_TEST); diff --git a/cocos/core/gfx/webgl/webgl-texture-view.ts b/cocos/core/gfx/webgl/webgl-texture-view.ts index 7c900baa41..4dffdfac5d 100644 --- a/cocos/core/gfx/webgl/webgl-texture-view.ts +++ b/cocos/core/gfx/webgl/webgl-texture-view.ts @@ -21,7 +21,6 @@ export class WebGLGFXTextureView extends GFXTextureView { this._texture = info.texture; this._type = info.type; this._format = info.format; - this._format = info.format; if (info.baseLevel !== undefined) { this._baseLevel = info.baseLevel; diff --git a/cocos/core/gfx/webgl2/webgl2-commands.ts b/cocos/core/gfx/webgl2/webgl2-commands.ts index a9a3eea632..eaa23af4b4 100644 --- a/cocos/core/gfx/webgl2/webgl2-commands.ts +++ b/cocos/core/gfx/webgl2/webgl2-commands.ts @@ -1415,8 +1415,13 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: W console.error('Shader source dump:', gpuStage.source.replace(/^|\n/g, () => `\n${lineNumber++} `)); console.error(gl.getShaderInfoLog(gpuStage.glShader)); - gl.deleteShader(gpuStage.glShader); - gpuStage.glShader = null; + for (let l = 0; l < gpuShader.gpuStages.length; l++) { + const stage = gpuShader.gpuStages[k]; + if (stage.glShader) { + gl.deleteShader(stage.glShader); + stage.glShader = null; + } + } return; } } @@ -1436,19 +1441,22 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: W } gl.linkProgram(gpuShader.glProgram); + + // detach & delete immediately + for (let k = 0; k < gpuShader.gpuStages.length; k++) { + const gpuStage = gpuShader.gpuStages[k]; + if (gpuStage.glShader) { + gl.detachShader(gpuShader.glProgram, gpuStage.glShader); + gl.deleteShader(gpuStage.glShader); + gpuStage.glShader = null; + } + } + if (gl.getProgramParameter(gpuShader.glProgram, gl.LINK_STATUS)) { console.info('Shader \'' + gpuShader.name + '\' compilation successed.'); } else { console.error('Failed to link shader \'' + gpuShader.name + '\'.'); console.error(gl.getProgramInfoLog(gpuShader.glProgram)); - - for (let k = 0; k < gpuShader.gpuStages.length; k++) { - const gpuStage = gpuShader.gpuStages[k]; - if (gpuStage.glShader) { - gl.deleteShader(gpuStage.glShader); - gpuStage.glShader = null; - } - } return; } @@ -1658,15 +1666,6 @@ export function WebGL2CmdFuncCreateShader (device: WebGL2GFXDevice, gpuShader: W } export function WebGL2CmdFuncDestroyShader (device: WebGL2GFXDevice, gpuShader: WebGL2GPUShader) { - - for (let k = 0; k < gpuShader.gpuStages.length; k++) { - const gpuStage = gpuShader.gpuStages[k]; - if (gpuStage.glShader) { - device.gl.deleteShader(gpuStage.glShader); - gpuStage.glShader = null; - } - } - if (gpuShader.glProgram) { device.gl.deleteProgram(gpuShader.glProgram); gpuShader.glProgram = null; @@ -1846,11 +1845,11 @@ export function WebGL2CmdFuncExecuteCmds (device: WebGL2GFXDevice, cmdPackage: W case GFXLoadOp.CLEAR: { if (cmd0.clearFlag & GFXClearFlag.STENCIL) { if (!cache.dss.stencilWriteMaskFront) { - gl.stencilMaskSeparate(gl.FRONT, 0xFFFFFFFF); + gl.stencilMaskSeparate(gl.FRONT, -1); } if (!cache.dss.stencilWriteMaskBack) { - gl.stencilMaskSeparate(gl.BACK, 0xFFFFFFFF); + gl.stencilMaskSeparate(gl.BACK, -1); } gl.clearStencil(cmd0.clearStencil); diff --git a/cocos/core/gfx/webgl2/webgl2-device.ts b/cocos/core/gfx/webgl2/webgl2-device.ts index 82cea3fff2..3d96936521 100644 --- a/cocos/core/gfx/webgl2/webgl2-device.ts +++ b/cocos/core/gfx/webgl2/webgl2-device.ts @@ -1,3 +1,4 @@ +import { macro } from '../../platform'; import { GFXBindingLayout, IGFXBindingLayoutInfo } from '../binding-layout'; import { GFXBuffer, IGFXBufferInfo } from '../buffer'; import { GFXCommandAllocator, IGFXCommandAllocatorInfo } from '../command-allocator'; @@ -135,7 +136,7 @@ export class WebGL2GFXDevice extends GFXDevice { try { const webGLCtxAttribs: WebGLContextAttributes = { - alpha: false, + alpha: macro.ENABLE_TRANSPARENT_CANVAS, antialias: this._isAntialias, depth: true, stencil: true, @@ -630,12 +631,12 @@ export class WebGL2GFXDevice extends GFXDevice { gl.depthMask(true); gl.depthFunc(gl.LESS); - gl.stencilFuncSeparate(gl.FRONT, gl.ALWAYS, 1, 0xffffffff); + gl.stencilFuncSeparate(gl.FRONT, gl.ALWAYS, 1, -1); gl.stencilOpSeparate(gl.FRONT, gl.KEEP, gl.KEEP, gl.KEEP); - gl.stencilMaskSeparate(gl.FRONT, 0xffffffff); - gl.stencilFuncSeparate(gl.BACK, gl.ALWAYS, 1, 0xffffffff); + gl.stencilMaskSeparate(gl.FRONT, -1); + gl.stencilFuncSeparate(gl.BACK, gl.ALWAYS, 1, -1); gl.stencilOpSeparate(gl.BACK, gl.KEEP, gl.KEEP, gl.KEEP); - gl.stencilMaskSeparate(gl.BACK, 0xffffffff); + gl.stencilMaskSeparate(gl.BACK, -1); gl.disable(gl.STENCIL_TEST); diff --git a/cocos/core/index.ts b/cocos/core/index.ts index ac39a54baf..335655de58 100644 --- a/cocos/core/index.ts +++ b/cocos/core/index.ts @@ -60,4 +60,5 @@ import './primitive'; export * from './utils/profiler/profiler'; import './deprecated'; -import './splash-image'; +// import './splash-image'; +import './splash-screen-webgl'; diff --git a/cocos/core/load-pipeline/CCLoader.ts b/cocos/core/load-pipeline/CCLoader.ts index d96ae11fc7..53fb90cdcb 100644 --- a/cocos/core/load-pipeline/CCLoader.ts +++ b/cocos/core/load-pipeline/CCLoader.ts @@ -391,7 +391,7 @@ export class CCLoader extends Pipeline { if (owner) { const ownerQueue = LoadingItems.getQueue(owner); // Set the root ownerQueue, if no ownerQueue defined in ownerQueue, it's the root - queue._ownerQueue = ownerQueue._ownerQueue || ownerQueue; + queue._ownerQueue = (ownerQueue && ownerQueue._ownerQueue) || ownerQueue; } const accepted = queue.append(_sharedList, owner); _sharedList.length = 0; diff --git a/cocos/core/load-pipeline/callback-params.ts b/cocos/core/load-pipeline/callback-params.ts index c02fab0df4..c86378a349 100644 --- a/cocos/core/load-pipeline/callback-params.ts +++ b/cocos/core/load-pipeline/callback-params.ts @@ -1,13 +1,6 @@ /** * @category loader */ - -type LoadSuccessParams = Parameters<(error: null | undefined, asset: T) => void>; - -type LoadErrorParams = Parameters<(error: Error) => void>; - -export type LoadCallbackParams = LoadSuccessParams | LoadErrorParams; - -export type LoadCompleteCallback = (...args: LoadCallbackParams) => void; +export type LoadCompleteCallback = (error: Error | null | undefined, asset?: T) => void; export type LoadProgressCallback = (completedCount: number, totalCount: number, item: any) => void; diff --git a/cocos/core/pipeline/define.ts b/cocos/core/pipeline/define.ts index 3a02500e36..1f64263e3b 100644 --- a/cocos/core/pipeline/define.ts +++ b/cocos/core/pipeline/define.ts @@ -88,7 +88,6 @@ export enum UniformBinding { UBO_FORWARD_LIGHTS = MAX_BINDING_SUPPORTED - 4, UBO_SKINNING_ANIMATION = MAX_BINDING_SUPPORTED - 5, UBO_SKINNING_TEXTURE = MAX_BINDING_SUPPORTED - 6, - UBO_UI = MAX_BINDING_SUPPORTED - 7, // samplers SAMPLER_JOINTS = MAX_BINDING_SUPPORTED + 1, @@ -96,7 +95,7 @@ export enum UniformBinding { // rooms left for custom bindings // effect importer prepares bindings according to this - CUSTUM_UBO_BINDING_END_POINT = MAX_BINDING_SUPPORTED - 7, + CUSTUM_UBO_BINDING_END_POINT = MAX_BINDING_SUPPORTED - 6, CUSTOM_SAMPLER_BINDING_START_POINT = MAX_BINDING_SUPPORTED + 6, } diff --git a/cocos/core/platform/event-manager/input-manager.ts b/cocos/core/platform/event-manager/input-manager.ts index 7478638fec..321cc92297 100644 --- a/cocos/core/platform/event-manager/input-manager.ts +++ b/cocos/core/platform/event-manager/input-manager.ts @@ -238,8 +238,10 @@ class InputManager { } const docElem = document.documentElement; - const leftOffset = window.pageXOffset - docElem.clientLeft; - const topOffset = window.pageYOffset - docElem.clientTop; + let leftOffset = sys.os === sys.OS_IOS && sys.isBrowser ? window.screenLeft : window.pageXOffset; + leftOffset -= docElem.clientLeft; + let topOffset = sys.os === sys.OS_IOS && sys.isBrowser ? window.screenTop : window.pageYOffset; + topOffset -= docElem.clientTop; if (element.getBoundingClientRect) { const box = element.getBoundingClientRect(); return { @@ -819,7 +821,7 @@ class InputManager { const inputManager = new InputManager(); -game.on(Game.EVENT_ENGINE_INITED, () => { +game.once(Game.EVENT_ENGINE_INITED, () => { // register system events if (!CC_EDITOR && game.config.registerSystemEvent) { inputManager.registerSystemEvent(game.canvas); diff --git a/cocos/core/renderer/models/skeletal-animation-utils.ts b/cocos/core/renderer/models/skeletal-animation-utils.ts index 0e096c31b2..9cb401016b 100644 --- a/cocos/core/renderer/models/skeletal-animation-utils.ts +++ b/cocos/core/renderer/models/skeletal-animation-utils.ts @@ -326,10 +326,10 @@ const ab_1 = new aabb(); export class AnimatedBoundsInfo { private _perJointBoundsPool = new Map>>(); // per Mesh per Skeleton - private _fullClipBoundsPool = new Map>(); // per Skeleton per AnimationClip + private _fullClipBoundsPool = new Map>>(); // per Mesh per Skeleton per AnimationClip public get (mesh: Mesh, skeleton: Skeleton, clip: AnimationClip) { - const list: aabb[] = this._getFullClipBounds(skeleton, clip) || []; + const list: aabb[] = this._getFullClipBounds(mesh, skeleton, clip) || []; if (list.length) { return list; } let perJointBounds = this._getPerJointBounds(mesh, skeleton); if (!perJointBounds) { @@ -361,7 +361,7 @@ export class AnimatedBoundsInfo { const { center, halfExtents } = list[fid]; aabb.fromPoints(list[fid], center, halfExtents); } - this._setFullClipBounds(skeleton, clip, list); + this._setFullClipBounds(mesh, skeleton, clip, list); return list; } @@ -408,23 +408,34 @@ export class AnimatedBoundsInfo { public releaseMesh (mesh: Mesh) { this._perJointBoundsPool.delete(mesh.hash); + this._fullClipBoundsPool.delete(mesh.hash); } public releaseSkeleton (skeleton: Skeleton) { - const it = this._perJointBoundsPool.values(); - let res = it.next(); - while (!res.done) { - res.value.delete(skeleton.hash); - res = it.next(); + const it1 = this._perJointBoundsPool.values(); + let res1 = it1.next(); + while (!res1.done) { + res1.value.delete(skeleton.hash); + res1 = it1.next(); + } + const it2 = this._fullClipBoundsPool.values(); + let res2 = it2.next(); + while (!res2.done) { + res2.value.delete(skeleton.hash); + res2 = it2.next(); } - this._fullClipBoundsPool.delete(skeleton.hash); } public releaseAnimationClip (clip: AnimationClip) { const it = this._fullClipBoundsPool.values(); let res = it.next(); while (!res.done) { - res.value.delete(clip.hash); + const it2 = res.value.values(); + let res2 = it2.next(); + while (!res2.done) { + res2.value.delete(clip.hash); + res2 = it2.next(); + } res = it.next(); } } @@ -434,20 +445,23 @@ export class AnimatedBoundsInfo { return m && m.get(skeleton.hash); } - private _getFullClipBounds (skeleton: Skeleton, clip: AnimationClip) { - const m = this._fullClipBoundsPool.get(skeleton.hash); - return m && m.get(clip.hash); + private _getFullClipBounds (mesh: Mesh, skeleton: Skeleton, clip: AnimationClip) { + const m = this._fullClipBoundsPool.get(mesh.hash); + const s = m && m.get(skeleton.hash); + return s && s.get(clip.hash); } private _setPerJointBounds (mesh: Mesh, skeleton: Skeleton, bounds: Array) { let m = this._perJointBoundsPool.get(mesh.hash); - if (!m) { m = new Map>(); } + if (!m) { m = new Map>(); this._perJointBoundsPool.set(mesh.hash, m); } m.set(skeleton.hash, bounds); } - private _setFullClipBounds (skeleton: Skeleton, clip: AnimationClip, bounds: aabb[]) { - let m = this._fullClipBoundsPool.get(skeleton.hash); - if (!m) { m = new Map(); } - m.set(clip.hash, bounds); + private _setFullClipBounds (mesh: Mesh, skeleton: Skeleton, clip: AnimationClip, bounds: aabb[]) { + let m = this._fullClipBoundsPool.get(mesh.hash); + if (!m) { m = new Map>(); this._fullClipBoundsPool.set(mesh.hash, m); } + let s = m.get(skeleton.hash); + if (!s) { s = new Map(); m.set(skeleton.hash, s); } + s.set(clip.hash, bounds); } } diff --git a/cocos/core/renderer/models/skinning-model.ts b/cocos/core/renderer/models/skinning-model.ts index d4ad54df9d..c4bc0c29ed 100644 --- a/cocos/core/renderer/models/skinning-model.ts +++ b/cocos/core/renderer/models/skinning-model.ts @@ -52,7 +52,7 @@ interface IJointsInfo { export class SkinningModel extends Model { - public uploadedAnim: AnimationClip | null = null; + public uploadedAnim: AnimationClip | null | undefined = undefined; // uninitialized private _jointsMedium: IJointsInfo; private _skeleton: Skeleton | null = null; @@ -75,6 +75,7 @@ export class SkinningModel extends Model { if (this._jointsMedium.buffer) { this._jointsMedium.buffer.destroy(); this._jointsMedium.buffer = null; + this.uploadedAnim = undefined; // uninitialized } } @@ -120,7 +121,7 @@ export class SkinningModel extends Model { } public uploadAnimation (anim: AnimationClip | null) { - if (!this._skeleton || !this._mesh) { return; } + if (!this._skeleton || !this._mesh || this.uploadedAnim === anim) { return; } this.uploadedAnim = anim; const resMgr = this._dataPoolManager; const texture = anim ? resMgr.jointsTexturePool.getJointsTextureWithAnimation(this._skeleton, anim) : @@ -128,7 +129,7 @@ export class SkinningModel extends Model { resMgr.jointsAnimationInfo.switchClip(this._jointsMedium.animInfo!, anim); this._applyJointsTexture(texture); this._jointsMedium.boundsInfo = anim ? resMgr.animatedBoundsInfo.get(this._mesh, this._skeleton, anim) : null; - this._modelBounds = anim ? this._staticModelBounds : null; // don't calc bounds again in Model + this._modelBounds = anim ? null : this._staticModelBounds; // don't calc bounds again in Model } protected _applyJointsTexture (texture: IJointsTextureHandle | null) { diff --git a/cocos/core/renderer/scene/render-scene.ts b/cocos/core/renderer/scene/render-scene.ts index e8075eb40f..32778d79b1 100644 --- a/cocos/core/renderer/scene/render-scene.ts +++ b/cocos/core/renderer/scene/render-scene.ts @@ -4,16 +4,17 @@ import { GFXPrimitiveMode } from '../../gfx/define'; import { Mat4, Vec3 } from '../../math'; import { RecyclePool } from '../../memop'; import { Root } from '../../root'; +import { Node } from '../../scene-graph'; import { Layers } from '../../scene-graph/layers'; +import { SkinningModel } from '../models/skinning-model'; import { Ambient } from './ambient'; -import { Camera, ICameraInfo } from './camera'; +import { Camera } from './camera'; import { DirectionalLight } from './directional-light'; import { Model } from './model'; import { PlanarShadows } from './planar-shadows'; import { Skybox } from './skybox'; import { SphereLight } from './sphere-light'; import { SpotLight } from './spot-light'; -import { Node } from '../../scene-graph'; export interface IRenderSceneInfo { name: string; @@ -301,27 +302,31 @@ export class RenderScene { pool.reset(); for (const m of this._models) { const transform = m.transform; - if (!transform || !m.enabled || m.node.layer & Layers.Enum.IGNORE_RAYCAST || !(m.node.layer & mask) || !m.modelBounds) { continue; } - // transform ray back to model space - Mat4.invert(m4, transform.getWorldMatrix(m4)); - Vec3.transformMat4(modelRay.o, worldRay.o, m4); - Vec3.normalize(modelRay.d, Vec3.transformMat4Normal(modelRay.d, worldRay.d, m4)); + if (!transform || !m.enabled || !(m.node.layer & (mask & ~Layers.Enum.IGNORE_RAYCAST)) || !m.worldBounds) { continue; } // broadphase - const d = intersect.ray_aabb(modelRay, m.modelBounds); - if (d <= 0 || d > distance) { continue; } - for (let i = 0; i < m.subModelNum; ++i) { - const subModel = m.getSubModel(i).subMeshData; - if (subModel && subModel.geometricInfo) { - const { positions: vb, indices: ib, doubleSided: sides } = subModel.geometricInfo; - narrowphase(vb, ib!, subModel.primitiveMode, sides!, distance); - } - if (narrowDis < distance) { - const r = pool.add(); - r.node = m.node; - r.distance = narrowDis * Vec3.multiply(v3, modelRay.d, transform.worldScale).length(); - resultModels[pool.length - 1] = r; + let d = intersect.ray_aabb(worldRay, m.worldBounds); + if (d <= 0 || d >= distance) { continue; } + if (!(m instanceof SkinningModel && m.uploadedAnim)) { + // transform ray back to model space + Mat4.invert(m4, transform.getWorldMatrix(m4)); + Vec3.transformMat4(modelRay.o, worldRay.o, m4); + Vec3.normalize(modelRay.d, Vec3.transformMat4Normal(modelRay.d, worldRay.d, m4)); + d = Infinity; + for (let i = 0; i < m.subModelNum; ++i) { + const subModel = m.getSubModel(i).subMeshData; + if (subModel && subModel.geometricInfo) { + const { positions: vb, indices: ib, doubleSided: sides } = subModel.geometricInfo; + narrowphase(vb, ib!, subModel.primitiveMode, sides!, distance); + d = Math.min(d, narrowDis * Vec3.multiply(v3, modelRay.d, transform.worldScale).length()); + } } } + if (d < distance) { + const r = pool.add(); + r.node = m.node; + r.distance = d; + resultModels[pool.length - 1] = r; + } } resultModels.length = pool.length; return resultModels.length > 0; @@ -350,27 +355,31 @@ export class RenderScene { pool.reset(); const m = model; const transform = m.transform; - if (!transform || !m.enabled || m.node.layer & Layers.Enum.IGNORE_RAYCAST || !(m.node.layer & mask) || !m.modelBounds) { return false; } - // transform ray back to model space - Mat4.invert(m4, transform.getWorldMatrix(m4)); - Vec3.transformMat4(modelRay.o, worldRay.o, m4); - Vec3.normalize(modelRay.d, Vec3.transformMat4Normal(modelRay.d, worldRay.d, m4)); + if (!transform || !m.enabled || !(m.node.layer & (mask & ~Layers.Enum.IGNORE_RAYCAST)) || !m.worldBounds) { return false; } // broadphase - const d = intersect.ray_aabb(modelRay, m.modelBounds); - if (d <= 0 || d > distance) { return false; } - for (let i = 0; i < m.subModelNum; ++i) { - const subModel = m.getSubModel(i).subMeshData; - if (subModel && subModel.geometricInfo) { - const { positions: vb, indices: ib, doubleSided: sides } = subModel.geometricInfo; - narrowphase(vb, ib!, subModel.primitiveMode, sides!, distance); - } - if (narrowDis < distance) { - const r = pool.add(); - r.node = m.node; - r.distance = narrowDis * Vec3.multiply(v3, modelRay.d, transform.worldScale).length(); - resultSingleModel[pool.length - 1] = r; + let d = intersect.ray_aabb(worldRay, m.worldBounds); + if (d <= 0 || d >= distance) { return false; } + if (!(m instanceof SkinningModel && m.uploadedAnim)) { + // transform ray back to model space + Mat4.invert(m4, transform.getWorldMatrix(m4)); + Vec3.transformMat4(modelRay.o, worldRay.o, m4); + Vec3.normalize(modelRay.d, Vec3.transformMat4Normal(modelRay.d, worldRay.d, m4)); + d = Infinity; + for (let i = 0; i < m.subModelNum; ++i) { + const subModel = m.getSubModel(i).subMeshData; + if (subModel && subModel.geometricInfo) { + const { positions: vb, indices: ib, doubleSided: sides } = subModel.geometricInfo; + narrowphase(vb, ib!, subModel.primitiveMode, sides!, distance); + d = Math.min(d, narrowDis * Vec3.multiply(v3, modelRay.d, transform.worldScale).length()); + } } } + if (d < distance) { + const r = pool.add(); + r.node = m.node; + r.distance = d; + resultSingleModel[pool.length - 1] = r; + } resultSingleModel.length = pool.length; return resultSingleModel.length > 0; } @@ -470,7 +479,7 @@ const narrowphase = (vb: Float32Array, ib: IBArray, pm: GFXPrimitiveMode, sides: Vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]); Vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]); const dist = intersect.ray_triangle(modelRay, tri, sides); - if (dist <= 0 || dist > narrowDis) { continue; } + if (dist <= 0 || dist >= narrowDis) { continue; } narrowDis = dist; } } else if (pm === GFXPrimitiveMode.TRIANGLE_STRIP) { @@ -485,7 +494,7 @@ const narrowphase = (vb: Float32Array, ib: IBArray, pm: GFXPrimitiveMode, sides: Vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]); rev = ~rev; const dist = intersect.ray_triangle(modelRay, tri, sides); - if (dist <= 0 || dist > narrowDis) { continue; } + if (dist <= 0 || dist >= narrowDis) { continue; } narrowDis = dist; } } else if (pm === GFXPrimitiveMode.TRIANGLE_FAN) { @@ -498,7 +507,7 @@ const narrowphase = (vb: Float32Array, ib: IBArray, pm: GFXPrimitiveMode, sides: Vec3.set(tri.b, vb[i1], vb[i1 + 1], vb[i1 + 2]); Vec3.set(tri.c, vb[i2], vb[i2 + 1], vb[i2 + 2]); const dist = intersect.ray_triangle(modelRay, tri, sides); - if (dist <= 0 || dist > narrowDis) { continue; } + if (dist <= 0 || dist >= narrowDis) { continue; } narrowDis = dist; } } diff --git a/cocos/core/renderer/ui/stencil-manager.ts b/cocos/core/renderer/ui/stencil-manager.ts index 0bcdaff861..dd91f5ee13 100644 --- a/cocos/core/renderer/ui/stencil-manager.ts +++ b/cocos/core/renderer/ui/stencil-manager.ts @@ -53,8 +53,8 @@ export class StencilManager { private _stencilPattern = { stencilTest: true, func: GFXComparisonFunc.ALWAYS, - stencilMask: 0xffffffff, - writeMask: 0xffffffff, + stencilMask: -1, + writeMask: -1, failOp: GFXStencilOp.KEEP, zFailOp: GFXStencilOp.KEEP, passOp: GFXStencilOp.KEEP, @@ -103,7 +103,7 @@ export class StencilManager { pattern.stencilTest = false; pattern.func = GFXComparisonFunc.ALWAYS; pattern.failOp = GFXStencilOp.KEEP; - pattern.stencilMask = pattern.writeMask = 0xffffffff; + pattern.stencilMask = pattern.writeMask = -1; pattern.ref = 1; } else { pattern.stencilTest = true; diff --git a/cocos/core/renderer/ui/ui.ts b/cocos/core/renderer/ui/ui.ts index 0152737a07..7c3c54ff59 100644 --- a/cocos/core/renderer/ui/ui.ts +++ b/cocos/core/renderer/ui/ui.ts @@ -134,7 +134,6 @@ export class UI { } public destroy () { - this._destroyUIMaterials(); for (const batch of this._batches.array) { batch.destroy(this); @@ -145,13 +144,7 @@ export class UI { } this._meshBuffers.splice(0); - const matIter = this._uiMaterials.values(); - let result = matIter.next(); - while (!result.done) { - const uiMat = result.value; - uiMat.destroy(); - result = matIter.next(); - } + this._destroyUIMaterials(); if (this._cmdBuff) { this._cmdBuff.destroy(); @@ -237,12 +230,17 @@ export class UI { this._screens.splice(idx, 1); if (comp.camera) { - const matHashInter = this._canvasMaterials.get(comp.camera.view.visibility)!.keys(); + const matRecord = this._canvasMaterials.get(comp.camera.view.visibility); + const matHashInter = matRecord!.keys(); let matHash = matHashInter.next(); while (!matHash.done) { this._removeUIMaterial(matHash.value); matHash = matHashInter.next(); } + + if (this._screens.length === 0) { + matRecord!.clear(); + } } let camera: Camera | null; @@ -251,7 +249,11 @@ export class UI { if (camera) { const matRecord = this._canvasMaterials.get(camera.view.visibility)!; camera.view.visibility = Layers.BitMask.UI_2D | (i + 1); - this._canvasMaterials.set(camera.view.visibility, matRecord); + const newMatRecord = this._canvasMaterials.get(camera.view.visibility)!; + newMatRecord.clear(); + matRecord.forEach((value: number, key: number) => { + newMatRecord.set(key, value); + }); } } } diff --git a/cocos/core/root.ts b/cocos/core/root.ts index b97a2f5c95..7220e97615 100644 --- a/cocos/core/root.ts +++ b/cocos/core/root.ts @@ -291,7 +291,7 @@ export class Root { } } - public setRenderPipeline(rppl: RenderPipeline): boolean { + public setRenderPipeline (rppl: RenderPipeline): boolean { this._pipeline = rppl; if (!this._pipeline.activate(this)) { return false; diff --git a/cocos/core/splash-screen-webgl.ts b/cocos/core/splash-screen-webgl.ts new file mode 100644 index 0000000000..1d4c35fc15 --- /dev/null +++ b/cocos/core/splash-screen-webgl.ts @@ -0,0 +1,415 @@ +import { IGFXColor } from "./gfx"; +import { clamp01 } from "./math"; +import { easing } from "./animation"; +import { macro } from "./platform"; + +type SplashEffectType = 'none' | 'Fade-InOut'; + +interface ISplashSetting { + readonly totalTime: number; + readonly base64src: string; + readonly effect: SplashEffectType; + readonly clearColor: IGFXColor; + readonly displayRatio: number; + readonly displayWatermark: boolean; +} + +function createShader (gl: WebGLRenderingContext, type: number, source: string) { + let shader = gl.createShader(type); + if (!shader) { + console.error('create shader error', source); + return; + } + + gl.shaderSource(shader, source); + gl.compileShader(shader); + + let success = gl.getShaderParameter(shader, gl.COMPILE_STATUS); + if (success) { + return shader; + } else { + console.error('compile shader error', shader); + console.log(gl.getShaderInfoLog(shader)); + gl.deleteShader(shader); + } +} + +function createProgram (gl: WebGLRenderingContext, vertexShader: WebGLShader, fragmentShader: WebGLShader) { + let program = gl.createProgram(); + if (!program) { + console.error('create program error'); + return; + } + + gl.attachShader(program, vertexShader); + gl.attachShader(program, fragmentShader); + gl.linkProgram(program); + + let success = gl.getProgramParameter(program, gl.LINK_STATUS); + if (success) { + return program; + } else { + console.error('link program error', success); + console.log(gl.getProgramInfoLog(program)); + gl.deleteProgram(program); + } +} + +const vs = "precision mediump float;attribute vec2 a_position;attribute vec2 a_texCoord;uniform vec2 u_resolution;uniform mat3 u_worldMat;varying vec2 v_texCoord;void main() {vec3 wpos = u_worldMat * vec3(a_position, 1.0);vec2 clipSpace = wpos.xy / u_resolution * 2.0 - 1.0;gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1);v_texCoord = a_texCoord;}"; +const fs = "precision mediump float;uniform float u_alpha;uniform sampler2D u_image;varying vec2 v_texCoord;void main(){gl_FragColor = texture2D(u_image,v_texCoord);gl_FragColor.xyz *= clamp(u_alpha, 0.0, 1.0);}"; + +export class SplashScreenWebgl { + + private gl!: WebGLRenderingContext; + private program!: WebGLProgram; + private vertexShader!: WebGLShader; + private fragmentShader!: WebGLShader; + private positionBuffer!: WebGLBuffer; + private texcoordBuffer!: WebGLBuffer; + private textureLogo!: WebGLTexture; + private textureText!: WebGLTexture; + + private logoImage = new Image(); + private textImage: HTMLCanvasElement = document.createElement('canvas'); + + private vertices = new Float32Array([-1, -1, -1, 1, 1, -1, 1, -1, -1, 1, 1, 1]); + private texcoords = new Float32Array([0, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1]); + private logoMat33 = new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]); + private textMat33 = new Float32Array([1, 0, 0, 0, 1, 0, 0, 0, 1]); + + + private setting!: ISplashSetting; + private callBack: Function | null = null; + private cancelAnimate = false; + private handle = -1; + private startTime = -1; + + private _isStart = false; + private _directCall = false; + private _splashFinish = false; + private _loadFinish = false; + + public set loadFinish (v: boolean) { + this._loadFinish = v; + this._tryToStart(); + } + + private set splashFinish (v: boolean) { + this._splashFinish = v; + this._tryToStart(); + } + + private _tryToStart () { + if (this._splashFinish && this._loadFinish) { + if (this.callBack) { + this.cancelAnimate = true; + cancelAnimationFrame(this.handle); + this.destroy(); + this.callBack(); + } + } + } + + public setOnFinish (cb: Function) { + if ((!this._isStart || this._directCall) && cb) { + delete SplashScreenWebgl._ins; + return cb(); + } + this.callBack = cb; + } + + public main (canvas: HTMLCanvasElement) { + if (window._CCSettings && window._CCSettings.splashScreen) { + this.setting = window._CCSettings.splashScreen; + (this.setting.totalTime as number) = this.setting.totalTime != null ? this.setting.totalTime : 3000; + (this.setting.base64src as string) = this.setting.base64src != null ? this.setting.base64src : ''; + (this.setting.effect as SplashEffectType) = this.setting.effect != null ? this.setting.effect : 'Fade-InOut'; + (this.setting.clearColor as IGFXColor) = this.setting.clearColor != null ? this.setting.clearColor : { r: 0.88, g: 0.88, b: 0.88, a: 1.0 }; + (this.setting.displayRatio as number) = this.setting.displayRatio != null ? this.setting.displayRatio : 0.4; + (this.setting.displayWatermark as boolean) = this.setting.displayWatermark != null ? this.setting.displayWatermark : true; + } else { + this.setting = { + totalTime: 3000, + base64src: '', + effect: 'Fade-InOut', + clearColor: { r: 0.88, g: 0.88, b: 0.88, a: 1.0 }, + displayRatio: 0.4, + displayWatermark: true + }; + } + + if (canvas == null || this.setting.base64src == '' || this.setting.totalTime <= 0) { + if (this.callBack) { this.callBack(); } + this.callBack = null; + (this.setting as any) = null; + this._directCall = true; + return; + } else { + + let useWebGL2 = (!!window.WebGL2RenderingContext); + const userAgent = window.navigator.userAgent.toLowerCase(); + if (userAgent.indexOf('safari') !== -1) { + if (userAgent.indexOf('chrome') === -1) { + useWebGL2 = false; + } + } + const webGLCtxAttribs: WebGLContextAttributes = { + alpha: macro.ENABLE_TRANSPARENT_CANVAS, + antialias: true, + depth: true, + stencil: true, + premultipliedAlpha: true, + preserveDrawingBuffer: false, + powerPreference: 'default', + failIfMajorPerformanceCaveat: false, + }; + + let gl: WebGLRenderingContext | null = null; + let gl2: WebGL2RenderingContext | null = null; + if (useWebGL2 && cc.WebGL2GFXDevice) { + gl2 = canvas.getContext('webgl2', webGLCtxAttribs) as WebGL2RenderingContext; + if (gl2 == null) { + gl = canvas.getContext('webgl', webGLCtxAttribs) as WebGLRenderingContext; + } + } else { + gl = canvas.getContext('webgl', webGLCtxAttribs) as WebGLRenderingContext; + } + + if (gl == null && gl2 == null) { + return console.error("this device does not support webgl"); + } else { + if (gl != null) this.gl = gl; + if (gl2 != null) this.gl = gl2; + } + + const textImage = this.textImage; + textImage.width = 300; + textImage.height = 30; + textImage.style.width = `${textImage.width}`; + textImage.style.height = `${textImage.height}`; + + const ctx = textImage.getContext('2d')!; + ctx.font = `${18}px Arial` + ctx.textBaseline = 'top'; + ctx.textAlign = 'left'; + ctx.fillStyle = '`#424242`'; + ctx.fillText("Powered by Cocos Creator 3D", 30, 8); + + this.logoImage.onload = this.init.bind(this); + this.logoImage.src = this.setting.base64src; + + this._isStart = true; + } + } + + private init () { + this.initMatrix(); + this.initProgram(); + this.initBuffer(); + this.initTexture(); + this.initState(); + + const that = this; + const animate = (time: number) => { + if (this.cancelAnimate) { return; } + that.frame(time); + requestAnimationFrame(animate); + } + this.handle = requestAnimationFrame(animate); + } + + private initMatrix () { + // TODO: hack for cocosPlay cause on landscape canvas value is wrong + if (CC_COCOSPLAY && window._CCSettings.orientation === 'landscape' && this.gl.canvas.width < this.gl.canvas.height ) { + let width = this.gl.canvas.height; + let height = this.gl.canvas.width; + this.gl.canvas.width = width; + this.gl.canvas.height = height; + } + + const screenWidth = this.gl.canvas.width; + const screenHeight = this.gl.canvas.height; + const displayRatio = this.setting.displayRatio; + let logoW = this.logoImage.width / 2; + let logoH = this.logoImage.height / 2; + let textW = this.textImage.width / 2; + let textH = this.textImage.height / 2; + if (screenWidth < screenHeight) { + logoW = screenWidth / 2 * displayRatio; + logoH = logoW / (this.logoImage.width / this.logoImage.height); + textW = screenWidth / 2 * 0.5; + textH = textW / (this.textImage.width / this.textImage.height); + } else { + logoW = screenHeight / 2 * displayRatio; + logoH = logoW / (this.logoImage.width / this.logoImage.height); + textW = screenHeight / 2 * 0.5; + textH = textW / (this.textImage.width / this.textImage.height); + } + + this.logoMat33[0] = logoW; + this.logoMat33[4] = logoH; + this.logoMat33[6] = screenWidth / 2; + this.logoMat33[7] = screenHeight / 2; + + this.textMat33[0] = textW; + this.textMat33[4] = textH; + this.textMat33[6] = screenWidth / 2; + this.textMat33[7] = screenHeight * 0.9; + } + + private initProgram () { + const gl = this.gl; + this.vertexShader = createShader(gl, gl.VERTEX_SHADER, vs)!; + this.fragmentShader = createShader(gl, gl.FRAGMENT_SHADER, fs)!; + this.program = createProgram(gl, this.vertexShader, this.fragmentShader)!; + } + + private initBuffer () { + const gl = this.gl; + gl.useProgram(this.program); + + this.positionBuffer = gl.createBuffer() as WebGLBuffer; + gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.vertices, gl.STATIC_DRAW); + + this.texcoordBuffer = gl.createBuffer() as WebGLBuffer; + gl.bindBuffer(gl.ARRAY_BUFFER, this.texcoordBuffer); + gl.bufferData(gl.ARRAY_BUFFER, this.texcoords, gl.STATIC_DRAW); + + var positionLocation = gl.getAttribLocation(this.program, "a_position"); + gl.enableVertexAttribArray(positionLocation); + gl.bindBuffer(gl.ARRAY_BUFFER, this.positionBuffer); + // Tell the position attribute how to get data out of positionBuffer (ARRAY_BUFFER) + var size = 2; // 2 components per iteration + var type = gl.FLOAT; // the data is 32bit floats + var normalize = false; // don't normalize the data + var stride = 0; // 0 = move forward size * sizeof(type) each iteration to get the next position + var offset = 0; // start at the beginning of the buffer + gl.vertexAttribPointer(positionLocation, size, type, normalize, stride, offset); + + var texcoordLocation = gl.getAttribLocation(this.program, "a_texCoord"); + gl.enableVertexAttribArray(texcoordLocation); + gl.bindBuffer(gl.ARRAY_BUFFER, this.texcoordBuffer); + var size = 2; // 2 components per iteration + var type = gl.FLOAT; // the data is 32bit floats + var normalize = false; // don't normalize the data + var stride = 0; // 0 = move forward size * sizeof(type) each iteration to get the next position + var offset = 0; // start at the beginning of the buffer + gl.vertexAttribPointer(texcoordLocation, size, type, normalize, stride, offset); + } + + private initTexture () { + const gl = this.gl; + + this.textureLogo = gl.createTexture() as WebGLTexture; + gl.bindTexture(gl.TEXTURE_2D, this.textureLogo); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.logoImage); + + this.textureText = gl.createTexture() as WebGLTexture; + gl.bindTexture(gl.TEXTURE_2D, this.textureText); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); + gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); + gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.textImage); + } + + private initState () { + const gl = this.gl; + gl.useProgram(this.program); + + var resolutionLocation = gl.getUniformLocation(this.program, "u_resolution"); + gl.uniform2f(resolutionLocation, gl.canvas.width, gl.canvas.height); + + gl.enable(gl.BLEND); + gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); + } + + private frame (time: number) { + const gl = this.gl; + const program = this.program; + const textureLogo = this.textureLogo; + const textureText = this.textureText; + const clearColor = this.setting.clearColor; + const logoMat33 = this.logoMat33; + const textMat33 = this.textMat33; + + if (this.startTime < 0) { this.startTime = time; } + const elapsedTime = time - this.startTime; + const precent = clamp01(elapsedTime / this.setting.totalTime); + const alpha = easing.cubicOut(precent); + + gl.enable(gl.BLEND); + gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA); + + gl.bindFramebuffer(gl.FRAMEBUFFER, null); + + // TODO: hack for cocosPlay cause on landscape canvas value is wrong + if (CC_COCOSPLAY && window._CCSettings.orientation === 'landscape' && this.gl.canvas.width < this.gl.canvas.height ) { + let width = this.gl.canvas.height; + let height = this.gl.canvas.width; + this.gl.canvas.width = width; + this.gl.canvas.height = height; + } + + gl.viewport(0, 0, gl.canvas.width, gl.canvas.height); + + gl.clearColor(clearColor.r, clearColor.g, clearColor.b, clearColor.a); + gl.depthMask(true); + gl.clearDepth(1); + gl.clearStencil(0); + gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT | gl.STENCIL_BUFFER_BIT); + + gl.useProgram(this.program); + + var resolutionLocation = gl.getUniformLocation(this.program, "u_resolution"); + gl.uniform2f(resolutionLocation, gl.canvas.width, gl.canvas.height); + + let location = gl.getUniformLocation(program, "u_alpha"); + gl.uniform1f(location, alpha); + + location = gl.getUniformLocation(program, "u_worldMat"); + + gl.uniformMatrix3fv(location, false, logoMat33); + gl.bindTexture(gl.TEXTURE_2D, textureLogo); + gl.drawArrays(gl.TRIANGLES, 0, 6); + + if (this.setting.displayWatermark) { + gl.uniformMatrix3fv(location, false, textMat33); + gl.bindTexture(gl.TEXTURE_2D, textureText); + gl.drawArrays(gl.TRIANGLES, 0, 6); + } + + if (elapsedTime > this.setting.totalTime) { + this.splashFinish = true; + } + } + + private destroy () { + delete SplashScreenWebgl._ins; + this.gl.deleteProgram(this.program); + this.gl.deleteShader(this.vertexShader); + this.gl.deleteShader(this.fragmentShader); + this.gl.deleteBuffer(this.positionBuffer); + this.gl.deleteBuffer(this.texcoordBuffer); + this.gl.deleteTexture(this.textureLogo); + this.gl.deleteTexture(this.textureText); + } + + private static _ins: SplashScreenWebgl; + + public static get instance () { + if (SplashScreenWebgl._ins == null) { + SplashScreenWebgl._ins = new SplashScreenWebgl(); + } + return SplashScreenWebgl._ins; + } + + private constructor () { }; +} + +cc.internal.SplashScreenWebgl = SplashScreenWebgl; diff --git a/cocos/core/utils/coordinates-converts-utils.ts b/cocos/core/utils/coordinates-converts-utils.ts index 2579555db1..f4da0793ba 100644 --- a/cocos/core/utils/coordinates-converts-utils.ts +++ b/cocos/core/utils/coordinates-converts-utils.ts @@ -7,6 +7,8 @@ import { Vec3 } from '../math'; import { Node } from '../scene-graph'; import { replaceProperty } from './deprecated'; +const _vec3 = new Vec3(); + /** * @en * Conversion of non-UI nodes to UI Node (Local) Space coordinate system. @@ -24,7 +26,8 @@ export function WorldNode3DToLocalNodeUI (mainCamera: CameraComponent, wpos: Vec } mainCamera.convertToUINode(wpos, uiNode, out); - + const pos = uiNode.position; + out.add(pos); return out; } @@ -60,12 +63,17 @@ const convertUtils = { export { convertUtils }; cc.pipelineUtils = convertUtils; -replaceProperty(cc, 'cc', [ +replaceProperty(cc.pipelineUtils, 'cc.pipelineUtils', [ { - name: 'pipelineUtils', - newName: 'CameraComponent.convertToUINode', - customGetter: () => { - return CameraComponent; + 'name': 'WorldNode3DToLocalNodeUI', + 'newName': 'convertToUINode', + 'targetName': 'cc.CameraComponent.prototype', + 'customFunction': function (...args: any[]) { + const camera = args[0] as CameraComponent; + const out = args[3] || _vec3; + camera.convertToUINode(args[1], args[2], out); + out.add(args[2].position); + return args[3] || out.clone(); }, }, ]); diff --git a/cocos/core/utils/profiler/profiler.ts b/cocos/core/utils/profiler/profiler.ts index a82fc3f703..43ba627749 100644 --- a/cocos/core/utils/profiler/profiler.ts +++ b/cocos/core/utils/profiler/profiler.ts @@ -151,7 +151,7 @@ export class Profiler { this.initDevice(); this.generateCanvas(); this.generateStats(); - cc.game.on(cc.Game.EVENT_ENGINE_INITED, this.generateNode, this); + cc.game.once(cc.Game.EVENT_ENGINE_INITED, this.generateNode, this); if (this._rootNode) { this._rootNode.active = true; diff --git a/cocos/physics/ammo/ammo-shared-body.ts b/cocos/physics/ammo/ammo-shared-body.ts index 6f154ab6ca..8888e1dda7 100644 --- a/cocos/physics/ammo/ammo-shared-body.ts +++ b/cocos/physics/ammo/ammo-shared-body.ts @@ -197,12 +197,14 @@ export class AmmoSharedBody { if (index < 0) { this.ghostStruct.wrappedShapes.push(v); v.setCompound(this.ghostCompoundShape); + this.ghostEnabled = true; } } else { const index = this.bodyStruct.wrappedShapes.indexOf(v); if (index < 0) { this.bodyStruct.wrappedShapes.push(v); v.setCompound(this.bodyCompoundShape); + this.bodyEnabled = true; } } } @@ -213,12 +215,14 @@ export class AmmoSharedBody { if (index >= 0) { this.ghostStruct.wrappedShapes.splice(index, 1); v.setCompound(null); + this.ghostEnabled = false; } } else { const index = this.bodyStruct.wrappedShapes.indexOf(v); if (index >= 0) { this.bodyStruct.wrappedShapes.splice(index, 1); v.setCompound(null); + this.bodyEnabled = false; } } } diff --git a/cocos/physics/ammo/shapes/ammo-shape.ts b/cocos/physics/ammo/shapes/ammo-shape.ts index d1cc815290..97842ad84a 100644 --- a/cocos/physics/ammo/shapes/ammo-shape.ts +++ b/cocos/physics/ammo/shapes/ammo-shape.ts @@ -97,11 +97,6 @@ export class AmmoShape implements IBaseShape { onEnable () { this._isEnabled = true; this._sharedBody.addShape(this, this._isTrigger); - if (this._isTrigger) { - this._sharedBody.ghostEnabled = true; - } else { - this._sharedBody.bodyEnabled = true; - } this.material = this.collider.sharedMaterial!; } @@ -109,11 +104,6 @@ export class AmmoShape implements IBaseShape { onDisable () { this._isEnabled = false; this._sharedBody.removeShape(this, this._isTrigger); - if (this._isTrigger) { - this._sharedBody.ghostEnabled = false; - } else { - this._sharedBody.bodyEnabled = false; - } } onDestroy () { diff --git a/cocos/physics/framework/index.ts b/cocos/physics/framework/index.ts index 3636f79f75..1a1cef2487 100644 --- a/cocos/physics/framework/index.ts +++ b/cocos/physics/framework/index.ts @@ -24,6 +24,8 @@ export { RigidBodyComponent, PhysicMaterial, + + ConstantForce }; cc.PhysicsSystem = PhysicsSystem; diff --git a/cocos/tween/tween.ts b/cocos/tween/tween.ts index 9858a056f7..db409c046d 100644 --- a/cocos/tween/tween.ts +++ b/cocos/tween/tween.ts @@ -19,7 +19,7 @@ import { SetAction } from './set-action'; * @class Tween * @param {Object} [target] * @example - * tweenUtil(this.node) + * tween(this.node) * .to(1, {scale: new Vec3(2, 2, 2), position: new Vec3(5, 5, 5)}) * .call(() => { console.log('This is a callback'); }) * .by(1, {scale: new Vec3(-1, -1, -1), position: new Vec3(-5, -5, -5)}, {easing: 'sineOutIn'}) diff --git a/cocos/ui/components/editbox/edit-box-component.ts b/cocos/ui/components/editbox/edit-box-component.ts index 02576c5372..96db97997f 100644 --- a/cocos/ui/components/editbox/edit-box-component.ts +++ b/cocos/ui/components/editbox/edit-box-component.ts @@ -55,6 +55,13 @@ function capitalize (str: string) { function capitalizeFirstLetter (str: string) { return str.charAt(0).toUpperCase() + str.slice(1); } + +enum EventType { + EDITING_DID_BEGAN = 'editing-did-began', + EDITING_DID_ENDED = 'editing-did-ended', + TEXT_CHANGED = 'text-changed', + EDITING_RETURN = 'editing-return', +} /** * @en * cc.EditBoxComponent is a component for inputing text, you can use it to gather small amounts of text from users. @@ -429,6 +436,7 @@ export class EditBoxComponent extends Component { public static KeyboardReturnType = KeyboardReturnType; public static InputFlag = InputFlag; public static InputMode = InputMode; + public static EventType = EventType; /** * @en * The event handler to be called when EditBox began to edit text. @@ -585,24 +593,24 @@ export class EditBoxComponent extends Component { public _editBoxEditingDidBegan () { ComponentEventHandler.emitEvents(this.editingDidBegan, this); - this.node.emit('editing-did-began', this); + this.node.emit(EventType.EDITING_DID_BEGAN, this); } public _editBoxEditingDidEnded () { ComponentEventHandler.emitEvents(this.editingDidEnded, this); - this.node.emit('editing-did-ended', this); + this.node.emit(EventType.EDITING_DID_ENDED, this); } public _editBoxTextChanged (text: string) { text = this._updateLabelStringStyle(text, true); this.string = text; ComponentEventHandler.emitEvents(this.textChanged, text, this); - this.node.emit('text-changed', this); + this.node.emit(EventType.TEXT_CHANGED, this); } public _editBoxEditingReturn () { ComponentEventHandler.emitEvents(this.editingReturn, this); - this.node.emit('editing-return', this); + this.node.emit(EventType.EDITING_RETURN, this); } public _showLabels () { diff --git a/cocos/ui/components/label-component.ts b/cocos/ui/components/label-component.ts index 8697c62b2d..7df73ac104 100644 --- a/cocos/ui/components/label-component.ts +++ b/cocos/ui/components/label-component.ts @@ -732,19 +732,7 @@ export class LabelComponent extends UIRenderComponent { } protected _flushMaterial () { - const material = this._material; - // Setup blend function for premultiplied ttf label texture - // if (this._texture === this._ttfSpriteFrame) { - // this._srcBlendFactor = macro.BlendFactor.ONE; - // } else { - // this._srcBlendFactor = macro.BlendFactor.SRC_ALPHA; - // } - - if (material) { - material.setProperty('mainTexture', this._texture); - } - - this._updateMaterial(material); + this._updateMaterial(this._material); } protected _applyFontTexture (force: boolean) { diff --git a/cocos/ui/components/page-view-component.ts b/cocos/ui/components/page-view-component.ts index eb4d6d460d..aafdc78afe 100644 --- a/cocos/ui/components/page-view-component.ts +++ b/cocos/ui/components/page-view-component.ts @@ -87,7 +87,7 @@ ccenum(Direction); * @zh 滚动视图事件类型 */ enum EventType { - PAGE_TURING = 'page-turning', + PAGE_TURNING = 'page-turning', } /** @@ -599,7 +599,7 @@ export class PageViewComponent extends ScrollViewComponent { if (this._lastPageIdx === this._curPageIdx) { return; } this._lastPageIdx = this._curPageIdx; ComponentEventHandler.emitEvents(this.pageEvents, this); - this.node.emit(EventType.PAGE_TURING, this); + this.node.emit(EventType.PAGE_TURNING, this); } // 快速滑动 diff --git a/cocos/ui/components/scroll-view-component.ts b/cocos/ui/components/scroll-view-component.ts index 3c951b210f..ac72539711 100644 --- a/cocos/ui/components/scroll-view-component.ts +++ b/cocos/ui/components/scroll-view-component.ts @@ -59,78 +59,6 @@ const getTimeInMilliseconds = () => { return currentTime.getMilliseconds(); }; -// /** -// * @zh -// * 滚动视图事件类型。 -// */ -// enum ScrollViewEventType { -// /** -// * @zh -// * 滚动视图滚动到顶部边界事件。 -// */ -// SCROLL_TO_TOP = 0, -// /** -// * @zh -// * 滚动视图滚动到底部边界事件。 -// */ -// SCROLL_TO_BOTTOM = 1, -// /** -// * @zh -// * 滚动视图滚动到左边界事件。 -// */ -// SCROLL_TO_LEFT = 2, -// /** -// * @zh -// * 滚动视图滚动到右边界事件。 -// */ -// SCROLL_TO_RIGHT = 3, -// /** -// * @zh -// * 滚动视图正在滚动时发出的事件。 -// */ -// SCROLLING = 4, -// /** -// * @zh -// * 滚动视图滚动到顶部边界并且开始回弹时发出的事件。 -// */ -// BOUNCE_TOP = 5, -// /** -// * @zh -// * 滚动视图滚动到底部边界并且开始回弹时发出的事件。 -// */ -// BOUNCE_BOTTOM = 6, -// /** -// * @zh -// * 滚动视图滚动到左边界并且开始回弹时发出的事件。 -// */ -// BOUNCE_LEFT = 7, -// /** -// * @zh -// * 滚动视图滚动到右边界并且开始回弹时发出的事件。 -// */ -// BOUNCE_RIGHT = 8, -// /** -// * @zh -// * 滚动视图滚动结束的时候发出的事件。 -// */ -// SCROLL_ENDED = 9, -// /** -// * @zh -// * 当用户松手的时候会发出一个事件。 -// */ -// TOUCH_UP = 10, -// /** -// * @zh -// * 滚动视图自动滚动快要结束的时候发出的事件。 -// */ -// AUTOSCROLL_ENDED_WITH_THRESHOLD = 11, -// /** -// * @zh -// * 滚动视图滚动开始时发出的事件。 -// */ -// SCROLL_BEGAN = 12, -// } - const eventMap = { 'scroll-to-top': 0, 'scroll-to-bottom': 1, @@ -432,7 +360,7 @@ export class ScrollViewComponent extends ViewGroupComponent { * scrollView.scrollToBottom(0.1); * ``` */ - public scrollToBottom (timeInSecond: number, attenuated: boolean) { + public scrollToBottom (timeInSecond?: number, attenuated = true) { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(0, 0), applyToHorizontal: false, @@ -458,7 +386,7 @@ export class ScrollViewComponent extends ViewGroupComponent { * scrollView.scrollToTop(0.1); * ``` */ - public scrollToTop (timeInSecond: number, attenuated: boolean) { + public scrollToTop (timeInSecond?: number, attenuated = true) { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(0, 1), applyToHorizontal: false, @@ -484,7 +412,7 @@ export class ScrollViewComponent extends ViewGroupComponent { * scrollView.scrollToLeft(0.1); * ``` */ - public scrollToLeft (timeInSecond: number, attenuated: boolean) { + public scrollToLeft (timeInSecond?: number, attenuated = true) { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(0, 0), applyToHorizontal: true, @@ -510,7 +438,7 @@ export class ScrollViewComponent extends ViewGroupComponent { * scrollView.scrollToRight(0.1); * ``` */ - public scrollToRight (timeInSecond: number, attenuated: boolean) { + public scrollToRight (timeInSecond?: number, attenuated = true) { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(1, 0), applyToHorizontal: true, @@ -536,7 +464,7 @@ export class ScrollViewComponent extends ViewGroupComponent { * scrollView.scrollToTopLeft(0.1); * ``` */ - public scrollToTopLeft (timeInSecond, attenuated) { + public scrollToTopLeft (timeInSecond?: number, attenuated = true) { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(0, 1), applyToHorizontal: true, @@ -562,7 +490,7 @@ export class ScrollViewComponent extends ViewGroupComponent { * scrollView.scrollToTopRight(0.1); * ``` */ - public scrollToTopRight (timeInSecond: number, attenuated: boolean) { + public scrollToTopRight (timeInSecond?: number, attenuated = true) { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(1, 1), applyToHorizontal: true, @@ -588,7 +516,7 @@ export class ScrollViewComponent extends ViewGroupComponent { * scrollView.scrollToBottomLeft(0.1); * ``` */ - public scrollToBottomLeft (timeInSecond: number, attenuated: boolean) { + public scrollToBottomLeft (timeInSecond?: number, attenuated = true) { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(0, 0), applyToHorizontal: true, @@ -614,7 +542,7 @@ export class ScrollViewComponent extends ViewGroupComponent { * scrollView.scrollToBottomRight(0.1); * ``` */ - public scrollToBottomRight (timeInSecond: number, attenuated: boolean) { + public scrollToBottomRight (timeInSecond?: number, attenuated = true) { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(1, 0), applyToHorizontal: true, @@ -642,7 +570,7 @@ export class ScrollViewComponent extends ViewGroupComponent { * scrollView.scrollToOffset(new Vec3(maxScrollOffset.x / 2, 0, 0), 0.1); * ``` */ - public scrollToOffset (offset: Vec3, timeInSecond: number, attenuated: boolean) { + public scrollToOffset (offset: Vec3, timeInSecond?: number, attenuated = true) { const maxScrollOffset = this.getMaxScrollOffset(); const anchor = new Vec2(0, 0); @@ -682,8 +610,8 @@ export class ScrollViewComponent extends ViewGroupComponent { * @return - 最大可滚动偏移量。 */ public getMaxScrollOffset () { - const scrollSize = this.node.getContentSize(); - const contentSize = this._content!.getContentSize(); + const scrollSize = this.node._uiProps.uiTransformComp!.contentSize; + const contentSize = this._content!._uiProps.uiTransformComp!.contentSize; let horizontalMaximizeOffset = contentSize.width - scrollSize.width; let verticalMaximizeOffset = contentSize.height - scrollSize.height; horizontalMaximizeOffset = horizontalMaximizeOffset >= 0 ? horizontalMaximizeOffset : 0; @@ -735,7 +663,7 @@ export class ScrollViewComponent extends ViewGroupComponent { * scrollView.scrollTo(new Vec2(1, 0), 0.1); * ``` */ - public scrollTo (anchor: Vec2, timeInSecond: number, attenuated?: boolean) { + public scrollTo (anchor: Vec2, timeInSecond?: number, attenuated?: boolean) { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(anchor), applyToHorizontal: true, @@ -761,7 +689,7 @@ export class ScrollViewComponent extends ViewGroupComponent { * scrollView.scrollToPercentVertical(0.5, 0.1); * ``` */ - public scrollToPercentVertical (percent: number, timeInSecond: number, attenuated?: boolean) { + public scrollToPercentVertical (percent: number, timeInSecond?: number, attenuated?: boolean) { const moveDelta = this._calculateMovePercentDelta({ anchor: new Vec2(0, percent), applyToHorizontal: false, @@ -1011,7 +939,7 @@ export class ScrollViewComponent extends ViewGroupComponent { if (layout && layout.enabledInHierarchy) { layout.updateLayout(); } - const viewSize = this.view!.getContentSize(); + const viewSize = this.view!._uiProps.uiTransformComp!.contentSize; const anchorX = viewSize.width * this.view!.anchorX; const anchorY = viewSize.height * this.view!.anchorY; @@ -1086,8 +1014,8 @@ export class ScrollViewComponent extends ViewGroupComponent { const targetDelta = new Vec3(deltaMove); targetDelta.normalize(); - const contentSize = this._content!.getContentSize(); - const scrollViewSize = this.node.getContentSize(); + const contentSize = this._content!._uiProps.uiTransformComp!.contentSize; + const scrollViewSize = this.node._uiProps.uiTransformComp!.contentSize; const totalMoveWidth = (contentSize.width - scrollViewSize.width); const totalMoveHeight = (contentSize.height - scrollViewSize.height); @@ -1415,8 +1343,8 @@ export class ScrollViewComponent extends ViewGroupComponent { } protected _clampDelta (delta: Vec3) { - const contentSize = this._content!.getContentSize(); - const scrollViewSize = this.node.getContentSize(); + const contentSize = this._content!._uiProps.uiTransformComp!.contentSize; + const scrollViewSize = this.node._uiProps.uiTransformComp!.contentSize; if (contentSize.width < scrollViewSize.width) { delta.x = 0; } @@ -1591,8 +1519,8 @@ export class ScrollViewComponent extends ViewGroupComponent { anchor.clampf(new Vec2(0, 0), new Vec2(1, 1)); - const scrollSize = this.node.getContentSize(); - const contentSize = this._content!.getContentSize(); + const scrollSize = this.node._uiProps.uiTransformComp!.contentSize; + const contentSize = this._content!._uiProps.uiTransformComp!.contentSize; let bottomDelta = this._getContentBottomBoundary() - this._bottomBoundary; bottomDelta = -bottomDelta; @@ -1615,7 +1543,7 @@ export class ScrollViewComponent extends ViewGroupComponent { } protected _moveContentToTopLeft (scrollViewSize: Size) { - const contentSize = this._content!.getContentSize(); + const contentSize = this._content!._uiProps.uiTransformComp!.contentSize; let bottomDelta = this._getContentBottomBoundary() - this._bottomBoundary; bottomDelta = -bottomDelta; diff --git a/package.json b/package.json index 4f03b7ea48..246ff8c6e2 100644 --- a/package.json +++ b/package.json @@ -11,8 +11,8 @@ "scripts": { "server": "http-server . -p 8002 -o http://127.0.0.1:8002/playground/index.html", "build": "npm run build:min && npm run build-declaration", - "build:dev": "node ./rollup/out/build-engine-cli.js --sourcemap --buildmode=universal --platform=HTML5 --physics=cannon --destination=./bin/cocos-3d.dev.js", - "build:min": "node ./rollup/out/build-engine-cli.js --compress --sourcemap --buildmode=universal --platform=HTML5 --physics=cannon --destination=./bin/cocos3d-js.min.js", + "build:dev": "node ./rollup/out/build-engine-cli.js --sourcemap --buildmode=universal --platform=HTML5 --physics=cannon --destination=./bin/dev/cc.js", + "build:min": "node ./rollup/out/build-engine-cli.js --compress --sourcemap --buildmode=universal --platform=HTML5 --physics=cannon --destination=./bin/dev/cc.min.js", "build-declaration": "node ./scripts/generate-declarations/generate-declarations-cli.js", "build-rollup": "tsc --build rollup/tsconfig.json", "postinstall": "npm run build-rollup", @@ -26,14 +26,14 @@ "url": "git+https://github.com/cocos-creator/engine.git" }, "devDependencies": { - "@babel/core": "^7.2.2", - "@babel/plugin-transform-for-of": "^7.4.4", - "@babel/preset-env": "^7.2.0", - "@cocos/babel-preset-cc": "^1.0.0", + "@babel/core": "^7.8.0", + "@babel/plugin-transform-for-of": "^7.8.0", + "@babel/preset-env": "^7.8.2", + "@cocos/babel-preset-cc": "^1.0.3", "@types/fs-extra": "^5.0.4", - "@types/jest": "^24.0.15", + "@types/jest": "^24.0.25", "@types/uglify-js": "^3.0.4", - "@types/yargs": "^12.0.5", + "@types/yargs": "^12.0.14", "@typescript-eslint/eslint-plugin": "^1.13.0", "@typescript-eslint/parser": "^1.13.0", "aliasify": "^2.1.0", @@ -42,10 +42,10 @@ "babelify": "7.3.0", "browserify": "^16.2.3", "chalk": "1.1.0", - "commander": "^2.20.0", + "commander": "^2.20.3", "dat.gui": "^0.7.5", "del": "1.2.0", - "eslint": "^6.1.0", + "eslint": "^6.8.0", "event-stream": "3.3.2", "fire-fs": "0.2.1", "fs-extra": "^7.0.1", @@ -72,19 +72,20 @@ "multipipe": "0.3.0", "persistify": "^1.1.1", "require-dir": "0.3.0", - "rollup": "^1.15.6", + "rollup": "^1.29.0", "rollup-plugin-babel": "^4.1.0-1", "rollup-plugin-commonjs": "10.0.1", "rollup-plugin-json": "^3.1.0", "rollup-plugin-multi-entry": "^2.1.0", "rollup-plugin-node-resolve": "5.2.0", - "rollup-plugin-terser": "^5.1.1", - "rollup-plugin-uglify": "^6.0.2", + "rollup-plugin-progress": "^1.1.1", + "rollup-plugin-terser": "^5.2.0", + "rollup-plugin-uglify": "^6.0.4", "rollup-watch": "^4.3.1", - "spectorjs": "^0.9.10", + "spectorjs": "^0.9.12", "stats.js": "^0.17.0", "tfig": "^1.2.3", - "ts-jest": "^24.0.2", + "ts-jest": "^24.3.0", "typedoc": "^0.14.2", "typedoc-plugin-external-module-name": "github:cocos-creator/typedoc-plugin-external-module-name#master", "typedoc-plugin-internal-external": "github:cocos-creator/typedoc-plugin-internal-external#master", diff --git a/playground/index.html b/playground/index.html index f49f118043..11fd9d83f3 100644 --- a/playground/index.html +++ b/playground/index.html @@ -66,7 +66,7 @@ - + diff --git a/rollup/src/build-engine-cli.ts b/rollup/src/build-engine-cli.ts index c86785da8c..924279359d 100644 --- a/rollup/src/build-engine-cli.ts +++ b/rollup/src/build-engine-cli.ts @@ -23,6 +23,10 @@ yargs.option('flags', { alias: 'f', description: 'Engine flags.', }); +yargs.option('module', { + choices: enumerateModuleOptionReps(), + description: 'Output module format. If not specified, IIFE will be used.', +}); yargs.option('destination', { type: 'string', alias: 'd', @@ -45,6 +49,11 @@ yargs.option('compress', { type: 'boolean', description: 'Whether to compress compiled engine.', }); +yargs.option('progress', { + type: 'boolean', + default: false, + description: 'Whether to show build progress.', +}); yargs.option('watch-files', { type: 'string', description: '(INTERNAL/EXPERIMENTAL) Write built file list as a record with file path as key and mtime as value, into specified file, in JSON format.', @@ -74,8 +83,9 @@ const options: IBuildOptions = { sourcemap: sourceMap, flags, watchFiles: !!watchFiles, + progress: yargs.argv.progress as (boolean | undefined), }; -if (yargs.argv['module']) { +if (yargs.argv.module) { options.moduleFormat = parseModuleOption(yargs.argv['module'] as unknown as string); } if (yargs.argv.buildmode) { diff --git a/rollup/src/build-engine.ts b/rollup/src/build-engine.ts index bf57b3aed8..734af6448e 100644 --- a/rollup/src/build-engine.ts +++ b/rollup/src/build-engine.ts @@ -1,7 +1,6 @@ import { existsSync } from 'fs'; import fs from 'fs-extra'; import { dirname, join, normalize, relative } from 'path'; -import { rollup, ModuleFormat } from 'rollup'; // @ts-ignore import babel from 'rollup-plugin-babel'; // @ts-ignore @@ -21,6 +20,9 @@ import { terser } from 'rollup-plugin-terser'; import babelPresetEnv from '@babel/preset-env'; import babelPresetCc from '@cocos/babel-preset-cc'; import { writeFile, ensureDir } from 'fs-extra'; +import * as rollup from 'rollup'; +// @ts-ignore +import rpProgress from 'rollup-plugin-progress'; interface IBaseOptions { moduleEntries: string[]; @@ -65,6 +67,8 @@ interface IBaseOptions { sourcemapFile?: string; watchFiles?: boolean; + + progress?: boolean; } interface IAdvancedOptions extends IBaseOptions { @@ -154,7 +158,7 @@ async function _internalBuild (options: IAdvancedOptions) { console.log(`Build-engine options: ${JSON.stringify(options, undefined, 2)}`); const doUglify = !!options.compress; - let format: ModuleFormat = 'iife'; + let format: rollup.ModuleFormat = 'iife'; switch (options.moduleFormat) { case ModuleOption.cjs: format = 'cjs'; @@ -167,7 +171,7 @@ async function _internalBuild (options: IAdvancedOptions) { break; } - const rollupPlugins = [ + const rollupPlugins: rollup.Plugin[] = [ multiEntry(), excludes({ @@ -208,37 +212,31 @@ async function _internalBuild (options: IAdvancedOptions) { }), ]; + if (options.progress) { + rollupPlugins.unshift(rpProgress()); + } + /** adapt: reduce_funcs not suitable for ammo.js */ const defines = options.globalDefines as IGlobaldefines; const isReduceFuncs = !defines.CC_PHYSICS_AMMO; - if (format === 'esm') { - rollupPlugins.push(terser({ - compress: { - global_defs: options.globalDefines, - reduce_funcs: isReduceFuncs - }, - mangle: doUglify, - keep_fnames: !doUglify, - output: { - beautify: !doUglify, - }, - sourcemap: !!options.sourcemap, - })); - } else { - rollupPlugins.push(uglify({ - compress: { - global_defs: options.globalDefines, - reduce_funcs: isReduceFuncs - }, - mangle: doUglify, - keep_fnames: !doUglify, - output: { - beautify: !doUglify, - }, - sourcemap: !!options.sourcemap, - })); - } + rollupPlugins.push(terser({ + compress: { + global_defs: options.globalDefines, + reduce_funcs: isReduceFuncs + }, + mangle: doUglify, + keep_fnames: !doUglify, + output: { + beautify: !doUglify, + }, + sourcemap: !!options.sourcemap, + + // https://github.com/rollup/rollup/issues/3315 + // We only do this for CommonJS. + // Especially, we cannot do this for IIFE. + toplevel: format === 'cjs', + })); const outputPath = options.outputPath; const sourcemapFile = options.sourcemapFile || `${options.outputPath}.map`; @@ -253,7 +251,7 @@ async function _internalBuild (options: IAdvancedOptions) { } }); - const rollupBuild = await rollup({ + const rollupBuild = await rollup.rollup({ input: moduleEntries, plugins: rollupPlugins, }); @@ -354,10 +352,11 @@ export enum ModuleOption { esm, cjs, system, + iife, } export function enumerateModuleOptionReps () { - return Object.values(ModuleOption).filter((value) => typeof value === 'string'); + return Object.values(ModuleOption).filter((value) => typeof value === 'string') as Array; } export function parseModuleOption (rep: string) {