From f274ff4cf9c2642e9d2a238dddc89a21f8be8624 Mon Sep 17 00:00:00 2001 From: Leslie Date: Mon, 14 Jan 2019 16:29:42 +0800 Subject: [PATCH 1/3] createMesh now create serializable mesh asset --- cocos/3d/assets/mesh.ts | 154 +++++++++++++-------- cocos/3d/misc/utils.ts | 247 ++++++++++++++++++++++++++++++++-- cocos/3d/primitive/box.ts | 2 +- cocos/3d/primitive/defines.ts | 5 + playground/simple.html | 2 +- 5 files changed, 343 insertions(+), 67 deletions(-) diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index d2fb82746b..983230fa12 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -32,7 +32,7 @@ import { Vec3 } from '../../core/value-types'; import { GFXBuffer } from '../../gfx/buffer'; import { GFXBufferUsageBit, GFXFormat, GFXMemoryUsageBit, GFXPrimitiveMode } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; -import { GFXInputAssembler, IGFXInputAttribute } from '../../gfx/input-assembler'; +import { GFXInputAssembler, IGFXInputAssemblerInfo, IGFXInputAttribute } from '../../gfx/input-assembler'; import { IBufferRange } from './utils/buffer-range'; export enum AttributeBaseType { @@ -247,15 +247,17 @@ export interface IPrimitive { */ vertexBundelIndices: number[]; - /** - * The indices data range of this primitive. - */ - indices: IBufferRange; + indices?: { + /** + * The indices data range of this primitive. + */ + range: IBufferRange; - /** - * The type of this primitive's indices. - */ - indexUnit: IndexUnit; + /** + * The type of this primitive's indices. + */ + indexUnit: IndexUnit; + }; /** * This primitive's topology. @@ -263,6 +265,31 @@ export interface IPrimitive { topology: Topology; } +/** + * Describes a mesh. + */ +export interface IMeshStruct { + /** + * The vertex bundles that this mesh owns. + */ + vertexBundles: IVertexBundle[]; + + /** + * The primitives that this mesh owns. + */ + primitives: IPrimitive[]; + + /** + * The min position of this mesh's vertices. + */ + minPosition: Vec3; + + /** + * The max position of this mesh's vertices. + */ + maxPosition: Vec3; +} + export interface IRenderingSubmesh { inputAssembler: GFXInputAssembler; primitiveMode: GFXPrimitiveMode; @@ -327,41 +354,29 @@ export class Mesh extends Asset { /** * Min position of this mesh. + * @deprecated Use this.struct.minPosition instead. */ get minPosition () { - return this._minPosition; + return this.struct.minPosition; } /** * Max position of this mesh. + * @deprecated Use this.struct.maxPosition instead. */ get maxPosition () { - return this._maxPosition; + return this.struct.maxPosition; } - /** - * The vertex bundles that this mesh owns. - */ - @property - public _vertexBundles: IVertexBundle[] = []; + get struct () { + return this._struct; + } - /** - * The primitives that this mesh owns. - */ - @property - public _primitives: IPrimitive[] = []; + get data () { + return this._data; + } - /** - * The min position of this mesh's vertices. - */ - @property(Vec3) - public _minPosition: Vec3 = new Vec3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE); - - /** - * The max position of this mesh's vertices. - */ - @property(Vec3) - public _maxPosition: Vec3 = new Vec3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE); + private _struct: IMeshStruct; private _data: Uint8Array | null = null; @@ -371,20 +386,34 @@ export class Mesh extends Asset { constructor () { super(); + + this._struct = { + vertexBundles: [], + primitives: [], + minPosition: new Vec3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE), + maxPosition: new Vec3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE), + }; } /** - * Destory this mesh and immediately release its video memory. + * Destory this mesh and immediately release its GPU resources. */ public destroy () { - if (this._renderingMesh) { - this._renderingMesh.destroy(); - this._renderingMesh = null; - this._initialized = false; - } + this._tryDestroyRenderingMesh(); return super.destroy(); } + /** + * Assigns new mesh struct to this. + * @param struct The new mesh's struct. + * @param data The new mesh's data. + */ + public assign (struct: IMeshStruct, data: Uint8Array) { + this._struct = struct; + this._data = data; + this._tryDestroyRenderingMesh(); + } + /** * Gets the rendering mesh. */ @@ -423,24 +452,29 @@ export class Mesh extends Asset { const indexBuffers: GFXBuffer[] = []; - const renderingSubmeshes = this._primitives.map((primitive) => { + const renderingSubmeshes = this._struct.primitives.map((primitive) => { if (primitive.vertexBundelIndices.length === 0) { return null; } - const indexBuffer = gfxDevice.createBuffer({ - usage: GFXBufferUsageBit.INDEX, - memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, - size: primitive.indices.length, - stride: getIndexUnitStride(primitive.indexUnit), - }); - indexBuffers.push(indexBuffer); + let indexBuffer: GFXBuffer | null = null; + if (primitive.indices) { + const indices = primitive.indices; - indexBuffer.update(buffer, primitive.indices.offset, primitive.indices.length); + indexBuffer = gfxDevice.createBuffer({ + usage: GFXBufferUsageBit.INDEX, + memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, + size: indices.range.length, + stride: getIndexUnitStride(indices.indexUnit), + }); + indexBuffers.push(indexBuffer); + + indexBuffer.update(new Uint8Array(buffer, indices.range.offset), 0, indices.range.length); + } const gfxAttributes: IGFXInputAttribute[] = []; primitive.vertexBundelIndices.forEach((iVertexBundle) => { - const vertexBundle = this._vertexBundles[iVertexBundle]; + const vertexBundle = this._struct.vertexBundles[iVertexBundle]; vertexBundle.attributes.forEach((attribute) => { const gfxAttribute: IGFXInputAttribute = { name: attribute.name, @@ -457,13 +491,17 @@ export class Mesh extends Asset { const referedVertexBuffers = primitive.vertexBundelIndices.map( (i) => vertexBuffers[i]); + const inputAssemblerInfo: IGFXInputAssemblerInfo = { + attributes: gfxAttributes, + vertexBuffers: referedVertexBuffers, + }; + if (indexBuffer) { + inputAssemblerInfo.indexBuffer = indexBuffer; + } + return { primitiveMode: toGFXTopology(primitive.topology), - inputAssembler: gfxDevice.createInputAssembler({ - attributes: gfxAttributes, - vertexBuffers: referedVertexBuffers, - indexBuffer, - }), + inputAssembler: gfxDevice.createInputAssembler(inputAssemblerInfo), } as IRenderingSubmesh ; }); @@ -471,7 +509,7 @@ export class Mesh extends Asset { } private _createVertexBuffers (gfxDevice: GFXDevice, data: ArrayBuffer): GFXBuffer[] { - return this._vertexBundles.map((vertexBundle) => { + return this._struct.vertexBundles.map((vertexBundle) => { const vertexBuffer = gfxDevice.createBuffer({ usage: GFXBufferUsageBit.VERTEX, memUsage: GFXMemoryUsageBit.HOST | GFXMemoryUsageBit.DEVICE, @@ -482,5 +520,13 @@ export class Mesh extends Asset { return vertexBuffer; }); } + + private _tryDestroyRenderingMesh () { + if (this._renderingMesh) { + this._renderingMesh.destroy(); + this._renderingMesh = null; + this._initialized = false; + } + } } cc.Mesh = Mesh; diff --git a/cocos/3d/misc/utils.ts b/cocos/3d/misc/utils.ts index 46c82198a9..073dd1abe9 100644 --- a/cocos/3d/misc/utils.ts +++ b/cocos/3d/misc/utils.ts @@ -1,9 +1,11 @@ -import { GFXPrimitiveMode } from '../../gfx/define'; -import * as renderer from '../../renderer'; +import { GFXAttributeName, GFXPrimitiveMode } from '../../gfx/define'; export { default as find } from '../../scene-graph/find'; import Texture2D from '../../assets/texture-2d'; import { Filter, PixelFormat, WrapMode } from '../../assets/texture-base'; -import { Mesh, RenderingMesh } from '../assets/mesh'; +import { Vec3 } from '../../core/value-types'; +import { AttributeBaseType, AttributeType, + IMeshStruct, IndexUnit, IPrimitive, IVertexAttribute, IVertexBundle, Mesh, Topology } from '../assets/mesh'; +import { IGeometry } from '../primitive/defines'; /** * @@ -37,15 +39,95 @@ export function createJointsTexture (skinning: { joints: any[]; }) { return texture; } -export function createMesh (context, data) { - const ia = renderer.createIA(context, data); - const meshAsset = new Mesh(); - const primitiveMode = data.primitiveMode === undefined ? GFXPrimitiveMode.TRIANGLE_LIST : data.primitiveMode; - meshAsset._renderingMesh = new RenderingMesh([{ inputAssembler: ia, primitiveMode }], [], []); - meshAsset._minPosition = data.minPos; - meshAsset._maxPosition = data.maxPos; +export function createMesh (geometry: IGeometry) { + // Collect attributes and calculate length of result vertex buffer. + const attributes: IVertexAttribute[] = []; + let stride = 0; + const channels: Array<{ offset: number; data: number[]; attribute: IVertexAttribute; }> = []; + let verticesCount = 0; + const copyAttribute = (attribute: IVertexAttribute) => Object.assign({}, attribute); + const addAttribute = (attribute: IVertexAttribute, data: number[]) => { + const componentCount = _getComponentCount(attribute); + const componentBytesLength = _getComponentByteLength(attribute); + const bytesLength = componentBytesLength * componentCount; + attributes.push(attribute); + channels.push({ offset: stride, data, attribute }); + stride += bytesLength; + verticesCount = Math.max(verticesCount, Math.floor(data.length / componentCount)); + }; + addAttribute(copyAttribute(predefinedAttributes.positions), geometry.positions); + if (geometry.normals) { + addAttribute(copyAttribute(predefinedAttributes.normals), geometry.normals); + } + if (geometry.uvs) { + addAttribute(copyAttribute(predefinedAttributes.uvs), geometry.uvs); + } + if (geometry.colors) { + addAttribute(copyAttribute(predefinedAttributes.colors), geometry.colors); + } - return meshAsset; + // Use this to generate final merged buffer. + const bufferBlob = new BufferBlob(); + + // Fill vertex buffer. + const vertexBuffer = new ArrayBuffer(verticesCount * stride); + const vertexBufferView = new DataView(vertexBuffer); + for (const channel of channels) { + _writeVertices(vertexBufferView, channel.offset, stride, channel.attribute, channel.data); + } + const vertexBundle: IVertexBundle = { + verticesCount, + attributes, + data: { + offset: bufferBlob.getLength(), + length: vertexBuffer.byteLength, + }, + }; + bufferBlob.addBuffer(vertexBuffer); + + // Fill index buffer. + let indexBuffer: ArrayBuffer | null = null; + const targetIndexUnit = IndexUnit.UINT16; + if (geometry.indices) { + const { indices } = geometry; + const indexUnitBytesLength = 2; + indexBuffer = new ArrayBuffer(indexUnitBytesLength * indices.length); + const indexBufferView = new DataView(indexBuffer); + const writer = _getIndicesWriter(indexBufferView, targetIndexUnit); + for (let i = 0; i < indices.length; ++i) { + writer(indexUnitBytesLength * i, indices[i]); + } + } + + // Create primitive. + const primitive: IPrimitive = { + topology: _getTopology(geometry.primitiveMode), + vertexBundelIndices: [0], + }; + if (indexBuffer) { + primitive.indices = { + indexUnit: targetIndexUnit, + range: { + offset: bufferBlob.getLength(), + length: indexBuffer.byteLength, + }, + }; + bufferBlob.addBuffer(indexBuffer); + } + + // Create mesh struct. + const meshStruct: IMeshStruct = { + vertexBundles: [vertexBundle], + primitives: [primitive], + minPosition: new Vec3(geometry.minPos.x, geometry.minPos.y, geometry.minPos.z), + maxPosition: new Vec3(geometry.maxPos.x, geometry.maxPos.y, geometry.maxPos.z), + }; + + // Create mesh. + const mesh = new Mesh(); + mesh.assign(meshStruct, new Uint8Array(bufferBlob.getCombined())); + + return mesh; } /** @@ -54,3 +136,146 @@ export function createMesh (context, data) { export function toPPM (buffer: Uint8Array, w: number, h: number) { return `P3 ${w} ${h} 255\n${buffer.filter((e, i) => i % 4 < 3).toString()}\n`; } + +const predefinedAttributes = { + positions: { + name: GFXAttributeName.ATTR_POSITION, + baseType: AttributeBaseType.FLOAT32, + type: AttributeType.VEC3, + normalize: false, + }, + normals: { + name: GFXAttributeName.ATTR_NORMAL, + baseType: AttributeBaseType.FLOAT32, + type: AttributeType.VEC3, + normalize: false, + }, + uvs: { + name: GFXAttributeName.ATTR_TEX_COORD, + baseType: AttributeBaseType.FLOAT32, + type: AttributeType.VEC2, + normalize: false, + }, + colors: { + name: GFXAttributeName.ATTR_COLOR, + baseType: AttributeBaseType.FLOAT32, + type: AttributeType.VEC4, + normalize: false, + }, +}; + +class BufferBlob { + private _arrayBuffers: ArrayBuffer[] = []; + private _length = 0; + + public addBuffer (arrayBuffer: ArrayBuffer) { + const result = this._length; + this._arrayBuffers.push(arrayBuffer); + this._length += arrayBuffer.byteLength; + return result; + } + + public getLength () { + return this._length; + } + + public getCombined () { + let length = 0; + this._arrayBuffers.forEach((arrayBuffer) => length += arrayBuffer.byteLength); + const result = new Uint8Array(length); + let counter = 0; + this._arrayBuffers.forEach((arrayBuffer) => { + result.set(new Uint8Array(arrayBuffer), counter); + counter += arrayBuffer.byteLength; + }); + return result.buffer; + } +} + +function _getTopology (primitiveMode: GFXPrimitiveMode) { + switch (primitiveMode) { + case GFXPrimitiveMode.POINT_LIST: + return Topology.POINT_LIST; + case GFXPrimitiveMode.LINE_LIST: + return Topology.LINE_LIST; + case GFXPrimitiveMode.TRIANGLE_LIST: + return Topology.TRIANGLE_LIST; + } + return Topology.POINT_LIST; +} + +function _writeVertices ( + target: DataView, offset: number, stride: number, attribute: IVertexAttribute, data: number[]) { + const writer = _getVerticesWriter(target, attribute.baseType); + const componentCount = _getComponentCount(attribute); + const componentBytesLength = _getComponentByteLength(attribute); + const nVertices = Math.floor(data.length / componentCount); + + for (let iVertex = 0; iVertex < nVertices; ++iVertex) { + const x = offset + stride * iVertex; + for (let iComponent = 0; iComponent < componentCount; ++iComponent) { + const y = x + componentBytesLength * iComponent; + writer(y, data[componentCount * iVertex + iComponent]); + } + } +} + +function _getComponentByteLength (vertexAttribute: IVertexAttribute) { + switch (vertexAttribute.baseType) { + case AttributeBaseType.INT8: + case AttributeBaseType.UINT8: + return 1; + case AttributeBaseType.INT16: + case AttributeBaseType.UINT16: + return 2; + case AttributeBaseType.INT32: + case AttributeBaseType.UINT32: + case AttributeBaseType.FLOAT32: + return 4; + } + return 1; +} + +function _getComponentCount (vertexAttribute: IVertexAttribute) { + switch (vertexAttribute.type) { + case AttributeType.SCALAR: return 1; + case AttributeType.VEC2: return 2; + case AttributeType.VEC3: return 3; + case AttributeType.VEC4: return 4; + } + return 1; +} + +function _getVerticesWriter (dataView: DataView, baseType: AttributeBaseType) { + switch (baseType) { + case AttributeBaseType.INT8: + return (offset: number, value: number) => dataView.setInt8(offset, value); + case AttributeBaseType.UINT8: + return (offset: number, value: number) => dataView.setUint8(offset, value); + case AttributeBaseType.INT16: + return (offset: number, value: number) => dataView.setInt16(offset, value, isLittleEndian); + case AttributeBaseType.UINT16: + return (offset: number, value: number) => dataView.setUint16(offset, value, isLittleEndian); + case AttributeBaseType.INT32: + return (offset: number, value: number) => dataView.setInt32(offset, value, isLittleEndian); + case AttributeBaseType.UINT32: + return (offset: number, value: number) => dataView.setUint32(offset, value, isLittleEndian); + case AttributeBaseType.FLOAT32: + return (offset: number, value: number) => dataView.setFloat32(offset, value, isLittleEndian); + } + return (offset: number, value: number) => dataView.setUint8(offset, value); +} + +function _getIndicesWriter (dataView: DataView, indexUnit: IndexUnit) { + switch (indexUnit) { + case IndexUnit.UINT8: + return (offset: number, value: number) => dataView.setUint8(offset, value); + case IndexUnit.UINT16: + return (offset: number, value: number) => dataView.setUint16(offset, value, isLittleEndian); + case IndexUnit.UINT32: + return (offset: number, value: number) => dataView.setUint32(offset, value, isLittleEndian); + } + return (offset: number, value: number) => dataView.setUint8(offset, value); +} + +const isLittleEndian = true; diff --git a/cocos/3d/primitive/box.ts b/cocos/3d/primitive/box.ts index 19e604581f..574e2da293 100644 --- a/cocos/3d/primitive/box.ts +++ b/cocos/3d/primitive/box.ts @@ -37,7 +37,7 @@ interface IBoxOptions extends IGeometryOptions { /** * This function generates a box with specified extents and centered at origin, - * but may emplaced through `center` option). + * but may be repositioned through `center` option). * @param options Options. */ export default function box (options?: IBoxOptions): IGeometry { diff --git a/cocos/3d/primitive/defines.ts b/cocos/3d/primitive/defines.ts index d6b6f43e20..fbb6b0c2e0 100644 --- a/cocos/3d/primitive/defines.ts +++ b/cocos/3d/primitive/defines.ts @@ -55,4 +55,9 @@ export interface IGeometry { * Texture coordinates. */ uvs?: number[]; + + /** + * Vertex colors. + */ + colors?: number[]; } diff --git a/playground/simple.html b/playground/simple.html index b2e57b0d8f..62dd098689 100644 --- a/playground/simple.html +++ b/playground/simple.html @@ -63,7 +63,7 @@ modelNode.parent = scene; const modelCom = modelNode.addComponent('cc.ModelComponent'); modelCom.material = material; - modelCom.mesh = cc.utils.createMesh(cc.game._renderContext, cc.primitives.box()); + modelCom.mesh = cc.utils.createMesh(cc.primitives.box()); modelNode.setRotationFromEuler(45, 45, 45); cc.director.runSceneImmediate(scene); From b6ecf7ee5dd7a511c022568d376fcf08a650cb1a Mon Sep 17 00:00:00 2001 From: Leslie Date: Mon, 14 Jan 2019 17:05:21 +0800 Subject: [PATCH 2/3] get endianness dynamically --- cocos/3d/misc/utils.ts | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/cocos/3d/misc/utils.ts b/cocos/3d/misc/utils.ts index 073dd1abe9..09db9ade47 100644 --- a/cocos/3d/misc/utils.ts +++ b/cocos/3d/misc/utils.ts @@ -278,4 +278,9 @@ function _getIndicesWriter (dataView: DataView, indexUnit: IndexUnit) { return (offset: number, value: number) => dataView.setUint8(offset, value); } -const isLittleEndian = true; +const isLittleEndian = (() => { + const buffer = new ArrayBuffer(2); + new DataView(buffer).setInt16(0, 256, true); + // Int16Array uses the platform's endianness. + return new Int16Array(buffer)[0] === 256; +})(); From d24aeb1550eb8c839f1cec94739d79a89f9cea7f Mon Sep 17 00:00:00 2001 From: Leslie Date: Mon, 14 Jan 2019 17:21:07 +0800 Subject: [PATCH 3/3] add @property --- cocos/3d/assets/mesh.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index 983230fa12..1091f0f01a 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -376,6 +376,7 @@ export class Mesh extends Asset { return this._data; } + @property private _struct: IMeshStruct; private _data: Uint8Array | null = null;