Merge pull request #42 from shrinktofit/create-mesh

createMesh now create serializable mesh asset
This commit is contained in:
Weiliang Wang
2019-01-14 17:32:31 +08:00
committed by GitHub
5 changed files with 350 additions and 68 deletions
+102 -55
View File
@@ -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,30 @@ 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;
}
get struct () {
return this._struct;
}
get data () {
return this._data;
}
/**
* The vertex bundles that this mesh owns.
*/
@property
public _vertexBundles: IVertexBundle[] = [];
/**
* The primitives that this mesh owns.
*/
@property
public _primitives: IPrimitive[] = [];
/**
* 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 +387,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 +453,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 +492,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 +510,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 +521,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;
+241 -11
View File
@@ -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,151 @@ 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 = (() => {
const buffer = new ArrayBuffer(2);
new DataView(buffer).setInt16(0, 256, true);
// Int16Array uses the platform's endianness.
return new Int16Array(buffer)[0] === 256;
})();
+1 -1
View File
@@ -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 {
+5
View File
@@ -55,4 +55,9 @@ export interface IGeometry {
* Texture coordinates.
*/
uvs?: number[];
/**
* Vertex colors.
*/
colors?: number[];
}
+1 -1
View File
@@ -63,7 +63,7 @@
modelNode.parent = scene;
const modelCom = modelNode.addComponent('cc.ModelComponent');
modelCom.material = material;
modelCom.mesh = cc.utils.createMesh(cc.game._gfxDevice, cc.primitives.box());
modelCom.mesh = cc.utils.createMesh(cc.primitives.box());
modelNode.setRotationFromEuler(45, 45, 45);
cc.director.runSceneImmediate(scene);