diff --git a/cocos/3d/assets/mesh.ts b/cocos/3d/assets/mesh.ts index e91e94b8cc..6b463faeed 100644 --- a/cocos/3d/assets/mesh.ts +++ b/cocos/3d/assets/mesh.ts @@ -291,7 +291,9 @@ export interface IGeometricInfo { } export interface IRenderingSubmesh { - inputAssembler: GFXInputAssembler; + vertexBuffers: GFXBuffer[]; + indexBuffer: GFXBuffer; + attributes: IGFXInputAttribute[]; primitiveMode: GFXPrimitiveMode; geometricInfo?: IGeometricInfo; } @@ -322,12 +324,6 @@ export class RenderingMesh { indexBuffer.destroy(); }); this._indexBuffers.length = 0; - - this._subMeshes.forEach((subMesh) => { - if (subMesh) { - subMesh.inputAssembler.destroy(); - } - }); this._subMeshes.length = 0; } } @@ -429,7 +425,7 @@ export class Mesh extends Asset { */ public getSubMesh (index: number) { const renderingSubmesh = this.renderingMesh ? this.renderingMesh.getSubmesh(index) : null; - return renderingSubmesh ? renderingSubmesh.inputAssembler : null; + return renderingSubmesh; } private _deferredInit () { @@ -493,14 +489,6 @@ export class Mesh extends Asset { const vbReference = primitive.vertexBundelIndices.map( (i) => vertexBuffers[i]); - const inputAssemblerInfo: IGFXInputAssemblerInfo = { - attributes: gfxAttributes, - vertexBuffers: vbReference, - }; - if (indexBuffer) { - inputAssemblerInfo.indexBuffer = indexBuffer; - } - const geomInfo: any = primitive.geometricInfo; if (geomInfo) { geomInfo.indices = ib; @@ -509,9 +497,11 @@ export class Mesh extends Asset { return { primitiveMode: primitive.primitiveMode, - inputAssembler: gfxDevice.createInputAssembler(inputAssemblerInfo), + vertexBuffers: vbReference, + indexBuffer, + attributes: gfxAttributes, geometricInfo: geomInfo, - } as IRenderingSubmesh ; + } as IRenderingSubmesh; }); this._renderingMesh = new RenderingMesh(renderingSubmeshes, vertexBuffers, indexBuffers); diff --git a/cocos/3d/framework/model-component.js b/cocos/3d/framework/model-component.js index edd4e8c5a3..3eda1188bc 100644 --- a/cocos/3d/framework/model-component.js +++ b/cocos/3d/framework/model-component.js @@ -158,9 +158,9 @@ export class ModelComponent extends RenderableComponent { constructor() { super(); /** - * @type {Model[]} + * @type {Model} */ - this._models = []; + this._model = null; } onLoad() { @@ -174,10 +174,7 @@ export class ModelComponent extends RenderableComponent { } onDisable() { - for (let i = 0; i < this._models.length; ++i) { - this._getRenderScene().destroyModel(this._models[i]); - } - this._models.splice(0); + this._getRenderScene().destroyModel(this._model); } onDestroy() { @@ -185,15 +182,15 @@ export class ModelComponent extends RenderableComponent { } _updateModels() { - if (!this.node._scene) return; - let meshCount = this._mesh ? this._mesh.subMeshCount : 0; - - for (let i = 0; i < meshCount; ++i) { - let model = this._createModel(); - model.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); - this._models.push(model); + if (!this.node._scene) { + return; } + let model = this._createModel(); + model.createBoundingShape(this._mesh.minPosition, this._mesh.maxPosition); + this._model = model; + this._model.node = this.node; + this._updateModelParams(); } @@ -203,51 +200,39 @@ export class ModelComponent extends RenderableComponent { _updateModelParams() { this.node._hasChanged = true; - for (let i = 0; i < this._models.length; ++i) { - let model = this._models[i]; + let meshCount = this._mesh ? this._mesh.subMeshCount : 0; + for (let i = 0; i < meshCount; ++i) { let material = this.getSharedMaterial(i); - - model.subMeshData = this._mesh.renderingMesh.getSubmesh(i); - model.node = this.node; - this._updateModelMaterial(model, material); + let subMeshData = this._mesh.renderingMesh.getSubmesh(i); + this._model.setSubModel(i, subMeshData, material); } } _onMaterialModified(idx, material) { - if (idx < this._models.length) { - this._updateModelMaterial(this._models[idx], material); + if (this._model == null) { + return; } + this._model.setSubModelMaterial(idx, material); } _clearMaterials() { - for (let i = 0; i < this._models.length; ++i) { + for (let i = 0; i < this._model.subModelNum; ++i) { this._onMaterialModified(i, null); } } - /** - * - * @param {Model} model - * @param {Material} material - */ - _updateModelMaterial(model, material) { - if (!this.enabled) - return; - model.material = material ? material : this._getBuiltinMaterial(); - } - _updateCastShadow() { if (!this.enabled) return; if (this._shadowCastingMode === ModelShadowCastingMode.Off) { - for (let i = 0; i < this._models.length; ++i) { - let model = this._models[i]; - model._castShadow = false; + for (let i = 0; i < this._model.subModelNum; ++i) { + let subModel = this._model.getSubModel(i); + subModel.castShadow = false; } } else if (this._shadowCastingMode === ModelShadowCastingMode.On) { - for (let i = 0; i < this._models.length; ++i) { - let model = this._models[i]; - model._castShadow = true; + for (let i = 0; i < this._model.subModelNum; ++i) { + let subModel = this._model.getSubModel(i); + subModel.castShadow = true; } } else { console.warn(`ShadowCastingMode ${this._shadowCastingMode} is not supported.`); @@ -257,11 +242,11 @@ export class ModelComponent extends RenderableComponent { _updateReceiveShadow() { if (!this.enabled) return; - for (let i = 0; i < this._models.length; ++i) { - let model = this._models[i]; - if (model._defines['CC_USE_SHADOW_MAP'] != undefined) { - this.getMaterial(i).define('CC_USE_SHADOW_MAP', this._receiveShadows); - } + for (let i = 0; i < this._model.subModelNum; ++i) { + let subModel = this._model.getSubModel(i); + // if (subModel._defines['CC_USE_SHADOW_MAP'] != undefined) { + // this.getMaterial(i).define('CC_USE_SHADOW_MAP', this._receiveShadows); + // } } } diff --git a/cocos/3d/memop/recycle-pool.js b/cocos/3d/memop/recycle-pool.js index 98f8097312..5c975e7d82 100644 --- a/cocos/3d/memop/recycle-pool.js +++ b/cocos/3d/memop/recycle-pool.js @@ -1,57 +1,65 @@ import sort from './timsort'; export default class RecyclePool { - constructor(fn, size) { - this._fn = fn; - this._count = 0; - this._data = new Array(size); + constructor(fn, size) { + this._fn = fn; + this._count = 0; + this._data = new Array(size); + this._objIdx = {}; - for (let i = 0; i < size; ++i) { - this._data[i] = fn(); - } - } - - get length() { - return this._count; - } - - get data() { - return this._data; - } - - reset() { - this._count = 0; - } - - resize(size) { - if (size > this._data.length) { - for (let i = this._data.length; i < size; ++i) { - this._data[i] = this._fn(); - } - } - } - - add() { - if (this._count >= this._data.length) { - this.resize(this._data.length * 2); + for (let i = 0; i < size; ++i) { + this._data[i] = fn(); + this._objIdx[this._data[i]] = i; + } } - return this._data[this._count++]; - } - - remove(idx) { - if (idx >= this._count) { - return; + get length() { + return this._count; } - let last = this._count - 1; - let tmp = this._data[idx]; - this._data[idx] = this._data[last]; - this._data[last] = tmp; - this._count -= 1; - } + get data() { + return this._data; + } - sort(cmp) { - return sort(this._data, 0, this._count, cmp); - } -} \ No newline at end of file + reset() { + this._count = 0; + } + + resize(size) { + if (size > this._data.length) { + for (let i = this._data.length; i < size; ++i) { + this._data[i] = this._fn(); + } + } + } + + add() { + if (this._count >= this._data.length) { + this.resize(this._data.length * 2); + } + + return this._data[this._count++]; + } + + removeAt(idx) { + if (idx >= this._count) { + return; + } + + let last = this._count - 1; + let tmp = this._data[idx]; + this._data[idx] = this._data[last]; + this._data[last] = tmp; + this._objIdx[this._data[idx]] = idx; + this._objIdx[this._data[last]] = last; + this._count -= 1; + } + + remove(obj) { + this.removeAt(this._objIdx[obj]); + } + + sort(cmp) { + return sort(this._data, 0, this._count, cmp); + } +} diff --git a/cocos/pipeline/render-queue.ts b/cocos/pipeline/render-queue.ts index 4fbb36f60b..d51a85a92c 100644 --- a/cocos/pipeline/render-queue.ts +++ b/cocos/pipeline/render-queue.ts @@ -4,12 +4,13 @@ import { GFXCommandBuffer } from '../gfx/command-buffer'; import { Pass } from '../renderer/core/pass'; import { Camera } from '../renderer/scene/camera'; import { Model } from '../renderer/scene/model'; +import { SubModel } from '../renderer/scene/submodel'; export interface IRenderItem { hash: number; depth: number; shaderId: number; - model: Model; + subModel: SubModel; pass: Pass; cmdBuff: GFXCommandBuffer; } @@ -61,30 +62,36 @@ export class RenderQueue { public add (model: Model, camera: Camera) { - const depth = vec3.distance(camera.node.getPosition(), model.node.getPosition()); + let depth = 0; + if (model.node) { + depth = vec3.distance(camera.node.getPosition(), model.node.getPosition()); + } - for (let i = 0; i < model.passes.length; ++i) { - const pass = model.passes[i]; + for (let i = 0; i < model.subModelNum; ++i) { + const subModel = model.getSubModel(i); + for (const pass of subModel.passes) { + // update pass + pass.update(); - // update pass - pass.update(); + const pso = pass.pipelineState; - const pso = pass.pipelineState; + const isTransparent = pso.blendState.targets[0].blend; - const isTransparent = pso.blendState.targets[0].blend; + // TODO: model priority - // TODO: model priority + if (!isTransparent) { + const hash = (0 << 30) | i; - if (!isTransparent) { - const hash = (0 << 30) | i; + this.opaques.push({ + hash, depth, shaderId: pso.shader.id, + subModel, pass, cmdBuff: subModel.commandBuffers[i]}); + } else { + const hash = (1 << 30) | i; - this.opaques.push({hash, depth, shaderId: pso.shader.id, - model, pass, cmdBuff: model.commandBuffers[i]}); - } else { - const hash = (1 << 30) | i; - - this.transparents.push({hash, depth, shaderId: pso.shader.id, - model, pass, cmdBuff: model.commandBuffers[i]}); + this.transparents.push({ + hash, depth, shaderId: pso.shader.id, + subModel, pass, cmdBuff: subModel.commandBuffers[i]}); + } } } } diff --git a/cocos/renderer/core/program-lib.ts b/cocos/renderer/core/program-lib.ts index dbc3bd05a2..0d3852923f 100644 --- a/cocos/renderer/core/program-lib.ts +++ b/cocos/renderer/core/program-lib.ts @@ -8,139 +8,138 @@ import { UBOGlobal, UBOLocal } from '../../pipeline/render-pipeline'; import { IDefineMap } from './effect'; function _generateDefines ( - device: GFXDevice, - defs: IDefineMap, - tDefs: IDefineInfo[], - deps: Record, + device: GFXDevice, + defs: IDefineMap, + tDefs: IDefineInfo[], + deps: Record, ) { - const defines: string[] = []; - for (const { name } of tDefs) { - const d = defs[name]; - let result = (typeof d === 'number') ? d : (d ? 1 : 0); - // fallback if extension dependency not supported - if (result && deps[name] && !device[deps[name]]) { - console.warn(`${deps[name]} not supported on this platform, disabled ${name}`); - result = 0; + const defines: string[] = []; + for (const { name } of tDefs) { + const d = defs[name]; + let result = (typeof d === 'number') ? d : (d ? 1 : 0); + // fallback if extension dependency not supported + if (result && deps[name] && !device[deps[name]]) { + console.warn(`${deps[name]} not supported on this platform, disabled ${name}`); + result = 0; + } + defines.push(`#define ${name} ${result}`); } - defines.push(`#define ${name} ${result}`); - } - return defines.join('\n'); + return defines.join('\n'); } let _shdID = 0; interface IDefineRecord extends IDefineInfo { - _map: (value: any) => number; - _offset: number; + _map: (value: any) => number; + _offset: number; } interface IProgramInfo extends IShaderInfo { - id: number; - defines: IDefineRecord[]; + id: number; + defines: IDefineRecord[]; } export class ProgramLib { - protected _device: GFXDevice; - protected _precision: string; - protected _templates: Record; - protected _cache: Record; + protected _device: GFXDevice; + protected _precision: string; + protected _templates: Record; + protected _cache: Record; - constructor (device: GFXDevice) { - this._device = device; - this._precision = `precision highp float;\n`; - this._templates = {}; - this._cache = {}; - } - - /** - * @example: - * // this object is auto-generated from your actual shaders - * let program = { - * name: 'foobar', - * vert: vertTmpl, - * frag: fragTmpl, - * defines: [ - * { name: 'shadow', type: 'boolean' }, - * { name: 'lightCount', type: 'number', range: [1, 4] } - * ], - * blocks: [{ name: 'Constants', binding: 0, size: 16, members: [{ name: 'color', type: 'vec4' }], defines: [] }], - * dependencies: { 'USE_NORMAL_TEXTURE': 'OES_standard_derivatives' }, - * }; - * programLib.define(program); - */ - public define (prog: IShaderInfo) { - if (this._templates[prog.name]) { return; } - const tmpl = Object.assign({ id: ++_shdID }, prog) as IProgramInfo; - tmpl.vert = this._precision + prog.vert; - tmpl.frag = this._precision + prog.frag; - - // calculate option mask offset - let offset = 0; - for (const def of tmpl.defines) { - let cnt = 1; - if (def.type === 'number') { - const range = def.range || [0, 4]; - cnt = Math.ceil(Math.log2(range[1] - range[0])); - def._map = ((value: number) => (value - range[0]) << def._offset); - } else { // boolean - def._map = ((value: any) => (value ? (1 << def._offset) : 0)); - } - offset += cnt; - def._offset = offset; - } - // store it - this._templates[prog.name] = tmpl; - } - - public getTemplate (name: string) { - return this._templates[name]; - } - - /** - * Does this library has the specified program? - */ - public hasProgram (name: string) { - return this._templates[name] !== undefined; - } - - public getKey (name: string, defines: IDefineMap) { - const tmpl = this._templates[name]; - let key = 0; - for (const tmplDef of tmpl.defines) { - const value = defines[tmplDef.name]; - if (value === undefined || !tmplDef._map) { - continue; - } - key |= tmplDef._map(value); - } - return key << 8 | (tmpl.id & 0xff); - } - - public getGFXShader (name: string, defines: IDefineMap = {}) { - const key = this.getKey(name, defines); - let program = this._cache[key]; - if (program !== undefined) { - return program; + constructor (device: GFXDevice) { + this._device = device; + this._precision = `precision highp float;\n`; + this._templates = {}; + this._cache = {}; } - // get template - const tmpl = this._templates[name]; - const customDef = _generateDefines(this._device, defines, tmpl.defines, tmpl.dependencies) + '\n'; - const vert = customDef + tmpl.vert; - const frag = customDef + tmpl.frag; + /** + * @example: + * // this object is auto-generated from your actual shaders + * let program = { + * name: 'foobar', + * vert: vertTmpl, + * frag: fragTmpl, + * defines: [ + * { name: 'shadow', type: 'boolean' }, + * { name: 'lightCount', type: 'number', range: [1, 4] } + * ], + * blocks: [{ name: 'Constants', binding: 0, size: 16, members: [{ name: 'color', type: 'vec4' }], defines: [] }], + * dependencies: { 'USE_NORMAL_TEXTURE': 'OES_standard_derivatives' }, + * }; + * programLib.define(program); + */ + public define (prog: IShaderInfo) { + if (this._templates[prog.name]) { return; } + const tmpl = Object.assign({ id: ++_shdID }, prog) as IProgramInfo; + tmpl.vert = this._precision + prog.vert; + tmpl.frag = this._precision + prog.frag; + tmpl.blocks = tmpl.blocks.concat(globals, locals); - tmpl.blocks = tmpl.blocks.concat(globals, locals); + // calculate option mask offset + let offset = 0; + for (const def of tmpl.defines) { + let cnt = 1; + if (def.type === 'number') { + const range = def.range || [0, 4]; + cnt = Math.ceil(Math.log2(range[1] - range[0])); + def._map = ((value: number) => (value - range[0]) << def._offset); + } else { // boolean + def._map = ((value: any) => (value ? (1 << def._offset) : 0)); + } + offset += cnt; + def._offset = offset; + } + // store it + this._templates[prog.name] = tmpl; + } - const instanceName = Object.keys(defines).reduce((acc, cur) => defines[cur] ? `${acc}|${cur}` : acc, name); - program = this._device.createShader({ - name: instanceName, - blocks: tmpl.blocks, - samplers: tmpl.samplers, - stages: [ - { type: GFXShaderType.VERTEX, source: vert }, - { type: GFXShaderType.FRAGMENT, source: frag }, - ], - }); - this._cache[key] = program; - return program; - } + public getTemplate (name: string) { + return this._templates[name]; + } + + /** + * Does this library has the specified program? + */ + public hasProgram (name: string) { + return this._templates[name] !== undefined; + } + + public getKey (name: string, defines: IDefineMap) { + const tmpl = this._templates[name]; + let key = 0; + for (const tmplDef of tmpl.defines) { + const value = defines[tmplDef.name]; + if (value === undefined || !tmplDef._map) { + continue; + } + key |= tmplDef._map(value); + } + return key << 8 | (tmpl.id & 0xff); + } + + public getGFXShader (name: string, defines: IDefineMap = {}) { + const key = this.getKey(name, defines); + let program = this._cache[key]; + if (program !== undefined) { + return program; + } + + // get template + const tmpl = this._templates[name]; + const customDef = _generateDefines(this._device, defines, tmpl.defines, tmpl.dependencies) + '\n'; + const vert = customDef + tmpl.vert; + const frag = customDef + tmpl.frag; + + const instanceName = Object.keys(defines).reduce((acc, cur) => defines[cur] ? `${acc}|${cur}` : acc, name); + program = this._device.createShader({ + name: instanceName, + blocks: tmpl.blocks, + samplers: tmpl.samplers, + stages: [ + { type: GFXShaderType.VERTEX, source: vert }, + { type: GFXShaderType.FRAGMENT, source: frag }, + ], + }); + this._cache[key] = program; + return program; + } } const globals = convertToBlockInfo(UBOGlobal.BLOCK); diff --git a/cocos/renderer/scene/model.ts b/cocos/renderer/scene/model.ts index a33c13818f..561631eeb8 100644 --- a/cocos/renderer/scene/model.ts +++ b/cocos/renderer/scene/model.ts @@ -9,14 +9,20 @@ import { GFXCommandBuffer } from '../../gfx/command-buffer'; import { GFXBufferUsageBit, GFXCommandBufferType, GFXMemoryUsageBit } from '../../gfx/define'; import { GFXDevice } from '../../gfx/device'; import { UBOLocal } from '../../pipeline/render-pipeline'; -import { Node } from '../../scene-graph'; import { Effect } from '../core/effect'; import { Pass } from '../core/pass'; import { RenderScene } from './render-scene'; +import { Node } from '../../scene-graph/node'; +import { RecyclePool } from '../../3d/memop'; +import { SubModel } from './submodel'; const _temp_floatx16 = new Float32Array(16); const _temp_mat4 = mat4.create(); +const _subMeshPool = new RecyclePool(() => { + return new SubModel(); +}, 100); + /** * A representation of a model */ @@ -24,25 +30,19 @@ export class Model { protected _device: GFXDevice; protected _type: string; - protected _subMeshObject: IRenderingSubmesh | null; private _scene: RenderScene | null; private _id: number; - private _poolID: number; private _isEnable: boolean; - private _node: Node; - private _effect: Effect | null; - private _defines: Object; - private _dependencies: Object; + private _node: Node | null; private _viewID: number; private _cameraID: number; private _userKey: number; - private _castShadow: boolean; private _worldBounds: aabb; private _modelBounds: aabb; - private _material: Material | null; private _cmdBuffers: GFXCommandBuffer[]; private _uboLocal: UBOLocal; private _localUBO: GFXBuffer | null; + private _subModels: SubModel[]; /** * Setup a default empty model */ @@ -51,22 +51,16 @@ export class Model { this._id = 0; this._type = 'default'; - this._poolID = -1; this._isEnable = true; this._node = null; - this._subMeshObject = null; - this._effect = null; - this._defines = {}; - this._dependencies = {}; this._viewID = -1; this._cameraID = -1; this._userKey = -1; - this._castShadow = false; - this._material = null; this._cmdBuffers = new Array(); this._uboLocal = new UBOLocal(); this._localUBO = null; this._device = cc.director.root.device; + this._subModels = new Array(); } public initialize () { @@ -81,6 +75,13 @@ export class Model { } } + public destroy () { + for (const subModel of this._subModels) { + subModel.destroy(); + _subMeshPool.remove(subModel); + } + } + set scene (scene: RenderScene | null) { this._scene = scene; @@ -97,14 +98,30 @@ export class Model { return this._id; } + get subModelNum (): number { + return this._subModels.length; + } + + public getSubModel (idx: number): SubModel { + return this._subModels[idx]; + } + public _updateTransform () { - if (!this._node._hasChanged || !this._worldBounds) { return; } + if (this._node == null) { + return; + } + if (!this._node._hasChanged || !this._worldBounds) { + return; + } this._node.updateWorldTransformFull(); this._modelBounds.transform(this._node._mat, this._node._pos, this._node._rot, this._node._scale, this._worldBounds); } public updateUBOs () { + if (this._node == null) { + return; + } mat4.array(_temp_floatx16, this._node._mat); this._node._mat.invert(_temp_mat4); this._uboLocal.view.set(_temp_floatx16, UBOLocal.MAT_WORLD_OFFSET); @@ -137,7 +154,7 @@ export class Model { * Get the hosting node of this camera * @returns {Node} the hosting node */ - get node (): Node { + get node (): Node | null { return this._node; } @@ -145,22 +162,10 @@ export class Model { * Set the hosting node of this model * @param {Node} node the hosting node */ - set node (node: Node) { + set node (node: Node | null) { this._node = node; } - /** - * Set the input assembler - * @param {InputAssembler} ia - */ - set subMeshData (sm: IRenderingSubmesh | null) { - this._subMeshObject = sm; - } - - get subMeshData () { - return this._subMeshObject; - } - get worldBounds (): aabb { return this._worldBounds; } @@ -172,59 +177,20 @@ export class Model { return this._viewID; } - /** - * Set the model effect - * @param {?Effect} effect the effect to use - */ - public setEffect (effect: Effect) { - if (effect) { - this._effect = effect; - // this._defines = effect.extractDefines(Object.create(null)); - // this._dependencies = effect.extractDependencies(Object.create(null)); + public setSubModel (idx: number, subMeshData: IRenderingSubmesh, mat: Material) { + if (this._subModels[idx] == null) { + this._subModels[idx] = _subMeshPool.add(); } else { - this._effect = null; - this._defines = Object.create(null); - this._dependencies = Object.create(null); + this._subModels[idx].destroy(); } + this._subModels[idx].initialize(subMeshData, mat, this._localUBO!); } - set material (material: Material) { - this._material = material; - for (let i = 0; i < this._material.passes.length; i++) { - if (this._material.passes[i].primitive !== this._subMeshObject!.primitiveMode) { - cc.error('the model(%d)\'s primitive type doesn\'t match its pass\'s'); - } - this.recordCommandBuffer(i); + public setSubModelMaterial (idx: number, mat: Material) { + if (this._subModels[idx] == null) { + return; } - for (let i = this._cmdBuffers.length - 1; i >= this._material.passes.length; i--) { - const cmdBuff = this._cmdBuffers.pop(); - if (cmdBuff) { - cmdBuff.destroy(); - } - } - } - - private recordCommandBuffer (index: number) { - const pass = this._material!.passes[index]; - if (this._cmdBuffers[index] == null) { - const cmdBufferInfo = { - allocator: this._device.commandAllocator, - type: GFXCommandBufferType.SECONDARY, - }; - this._cmdBuffers[index] = this._device.createCommandBuffer(cmdBufferInfo); - } - - const subMesh = this._subMeshObject!; - - pass.bindingLayout.bindBuffer(UBOLocal.BLOCK.binding, this._localUBO!); - - const cmdBuff = this._cmdBuffers[index]; - cmdBuff.begin(); - cmdBuff.bindPipelineState(pass.pipelineState); - cmdBuff.bindBindingLayout(pass.bindingLayout); - cmdBuff.bindInputAssembler(subMesh.inputAssembler); - cmdBuff.draw(subMesh.inputAssembler); - cmdBuff.end(); + this._subModels[idx].material = mat; } /** @@ -235,14 +201,6 @@ export class Model { this._userKey = key; } - get passes (): Pass[] { - return this._material!.passes; - } - - get commandBuffers (): GFXCommandBuffer[] { - return this._cmdBuffers; - } - get uboLocal (): UBOLocal { return this._uboLocal; } diff --git a/cocos/renderer/scene/render-scene.ts b/cocos/renderer/scene/render-scene.ts index 94b673aabc..33d2265180 100644 --- a/cocos/renderer/scene/render-scene.ts +++ b/cocos/renderer/scene/render-scene.ts @@ -132,13 +132,16 @@ export class RenderScene { public destroyModel (model: Model) { for (let i = 0; i < this._models.length; ++i) { if (this._models[i] === model) { - this._models.splice(i, 1); + this._models.splice(i, 1)[0].destroy(); return; } } } public destroyModels () { + for (const m of this._models) { + m.destroy(); + } this._models = []; } @@ -186,7 +189,7 @@ const m4 = mat4.create(); let distance = Infinity; const tri = triangle.create(); const pool = new RecyclePool(() => { - return { node: null, distance: Infinity }; + return { node: null, distance: Infinity }; }, 8); const results: IRaycastResult[] = []; diff --git a/cocos/renderer/scene/submodel.ts b/cocos/renderer/scene/submodel.ts new file mode 100644 index 0000000000..b893f95aa0 --- /dev/null +++ b/cocos/renderer/scene/submodel.ts @@ -0,0 +1,121 @@ +import { IRenderingSubmesh } from "../../3d/assets/mesh"; +import { GFXDevice } from "../../gfx/device"; +import { Material } from "../../3d/assets/material"; +import { GFXCommandBuffer } from "../../gfx/command-buffer"; +import { aabb } from "../../3d/geom-utils"; +import { Vec3 } from "../../core/value-types"; +import { GFXCommandBufferType } from "../../gfx/define"; +import { GFXBuffer } from "../../gfx/buffer"; +import { UBOLocal } from "../../pipeline/render-pipeline"; +import { Pass } from "../core/pass"; +import { GFXInputAssembler, IGFXInputAssemblerInfo } from "../../gfx/input-assembler"; + +export class SubModel { + protected _subMeshObject: IRenderingSubmesh | null; + private _inputAssembler: GFXInputAssembler | null; + private _material: Material | null; + private _cmdBuffers: GFXCommandBuffer[]; + private _localUBO: GFXBuffer | null; + private _castShadow: boolean; + + constructor () { + this._subMeshObject = null; + this._material = null; + this._cmdBuffers = new Array(); + this._localUBO = null; + this._castShadow = false; + this._inputAssembler = null; + } + + public initialize (subMesh: IRenderingSubmesh, mat: Material, localUBO: GFXBuffer) { + this.localUBO = localUBO; + this.subMeshData = subMesh; + const iaInfo = {} as IGFXInputAssemblerInfo; + iaInfo.attributes = this._subMeshObject!.attributes; + iaInfo.vertexBuffers = this._subMeshObject!.vertexBuffers; + if (this._subMeshObject!.indexBuffer) { + iaInfo.indexBuffer = this._subMeshObject!.indexBuffer; + } + this._inputAssembler = (cc.director.root.device as GFXDevice).createInputAssembler(iaInfo); + + this.material = mat; + } + + public destroy () { + if (this._inputAssembler) { + this._inputAssembler.destroy(); + } + } + + set subMeshData (sm: IRenderingSubmesh) { + this._subMeshObject = sm; + } + + get subMeshData () { + return this._subMeshObject!; + } + + set material (material: Material) { + this._material = material; + if (material == null) { + return; + } + for (let i = 0; i < this._material!.passes.length; i++) { + if (this._material!.passes[i].primitive !== this._subMeshObject!.primitiveMode) { + cc.error('the model(%d)\'s primitive type doesn\'t match its pass\'s'); + } + this.recordCommandBuffer(i); + } + for (let i = this._cmdBuffers.length - 1; i >= this._material!.passes.length; i--) { + const cmdBuff = this._cmdBuffers.pop(); + if (cmdBuff) { + cmdBuff.destroy(); + } + } + } + + set localUBO (val: GFXBuffer) { + this._localUBO = val; + } + + get castShadow (): boolean { + return this._castShadow; + } + + set castShadow (val: boolean) { + this._castShadow = val; + } + + private recordCommandBuffer (index: number) { + const device = cc.director.root.device; + const pass = this._material!.passes[index]; + if (this._cmdBuffers[index] == null) { + const cmdBufferInfo = { + allocator: device.commandAllocator, + type: GFXCommandBufferType.SECONDARY, + }; + this._cmdBuffers[index] = device.createCommandBuffer(cmdBufferInfo); + } + + const localUBO = this._localUBO as GFXBuffer; + const inputAssembler = this._inputAssembler as GFXInputAssembler; + + pass.bindingLayout.bindBuffer(UBOLocal.BLOCK.binding, localUBO); + + const cmdBuff = this._cmdBuffers[index]; + cmdBuff.begin(); + cmdBuff.bindPipelineState(pass.pipelineState); + cmdBuff.bindBindingLayout(pass.bindingLayout); + cmdBuff.bindInputAssembler(inputAssembler); + cmdBuff.draw(inputAssembler); + cmdBuff.end(); + } + + get passes (): Pass[] { + return this._material!.passes; + } + + get commandBuffers (): GFXCommandBuffer[] { + return this._cmdBuffers; + } +}