UNPKG

playcanvas

Version:

PlayCanvas WebGL game engine

255 lines (252 loc) 11.3 kB
import { Debug } from '../core/debug.js'; import { RefCountedObject } from '../core/ref-counted-object.js'; import { Vec3 } from '../core/math/vec3.js'; import { FloatPacking } from '../core/math/float-packing.js'; import { BoundingBox } from '../core/shape/bounding-box.js'; import { PIXELFORMAT_RGBA16F, FILTER_NEAREST, ADDRESS_CLAMP_TO_EDGE, PIXELFORMAT_RGBA32F, PIXELFORMAT_RGBA16U, isIntegerPixelFormat, PIXELFORMAT_RGB32F, SEMANTIC_ATTR15, TYPE_UINT32 } from '../platform/graphics/constants.js'; import { Texture } from '../platform/graphics/texture.js'; import { VertexBuffer } from '../platform/graphics/vertex-buffer.js'; import { VertexFormat } from '../platform/graphics/vertex-format.js'; /** * @import { GraphicsDevice } from '../platform/graphics/graphics-device.js' * @import { MorphTarget } from './morph-target.js' */ /** * Contains a list of {@link MorphTarget}s, a combined delta AABB and some associated data. * * @category Graphics */ class Morph extends RefCountedObject { get aabb() { // lazy evaluation, which allows us to skip this completely if customAABB is used if (!this._aabb) { // calculate min and max expansion size // Note: This represents average case, where most morph targets expand the mesh within the same area. It does not // represent the stacked worst case scenario where all morphs could be enabled at the same time, as this can result // in a very large aabb. In cases like this, the users should specify customAabb for Model/Render component. var min = new Vec3(); var max = new Vec3(); for(var i = 0; i < this._targets.length; i++){ var targetAabb = this._targets[i].aabb; min.min(targetAabb.getMin()); max.max(targetAabb.getMax()); } this._aabb = new BoundingBox(); this._aabb.setMinMax(min, max); } return this._aabb; } get morphPositions() { return this._morphPositions; } get morphNormals() { return this._morphNormals; } _init() { // texture based morphing this._initTextureBased(); // finalize init for(var i = 0; i < this._targets.length; i++){ this._targets[i]._postInit(); } } _findSparseSet(deltaArrays, ids, usedDataIndices) { var freeIndex = 1; // reserve slot 0 for zero delta var dataCount = deltaArrays[0].length; for(var v = 0; v < dataCount; v += 3){ // find if vertex is morphed by any target var vertexUsed = false; for(var i = 0; i < deltaArrays.length; i++){ var data = deltaArrays[i]; // if non-zero delta if (data[v] !== 0 || data[v + 1] !== 0 || data[v + 2] !== 0) { vertexUsed = true; break; } } if (vertexUsed) { ids.push(freeIndex); usedDataIndices.push(v / 3); freeIndex++; } else { // non morphed vertices would be all mapped to pixel 0 of texture ids.push(0); } } return freeIndex; } _initTextureBased() { // collect all source delta arrays to find sparse set of vertices var deltaArrays = [], deltaInfos = []; for(var i = 0; i < this._targets.length; i++){ var target = this._targets[i]; if (target.options.deltaPositions) { deltaArrays.push(target.options.deltaPositions); deltaInfos.push({ target: target, name: 'texturePositions' }); } if (target.options.deltaNormals) { deltaArrays.push(target.options.deltaNormals); deltaInfos.push({ target: target, name: 'textureNormals' }); } } // find sparse set for all target deltas into usedDataIndices and build vertex id buffer var ids = [], usedDataIndices = []; var freeIndex = this._findSparseSet(deltaArrays, ids, usedDataIndices); // texture size for freeIndex pixels - roughly square var maxTextureSize = this.device.maxTextureSize; var morphTextureWidth = Math.ceil(Math.sqrt(freeIndex)); morphTextureWidth = Math.min(morphTextureWidth, maxTextureSize); var morphTextureHeight = Math.ceil(freeIndex / morphTextureWidth); // if data cannot fit into max size texture, fail this set up if (morphTextureHeight > maxTextureSize) { return false; } this.morphTextureWidth = morphTextureWidth; this.morphTextureHeight = morphTextureHeight; // texture format based vars var halfFloat = false; var numComponents = 3; // RGB32 is used var float2Half = FloatPacking.float2Half; if (this._textureFormat === PIXELFORMAT_RGBA16F) { halfFloat = true; numComponents = 4; // RGBA16 is used, RGB16 does not work } // create textures var textures = []; for(var i1 = 0; i1 < deltaArrays.length; i1++){ textures.push(this._createTexture('MorphTarget', this._textureFormat)); } // build texture for each delta array, all textures are the same size for(var i2 = 0; i2 < deltaArrays.length; i2++){ var data = deltaArrays[i2]; var texture = textures[i2]; var textureData = texture.lock(); // copy full arrays into sparse arrays and convert format (skip 0th pixel - used by non-morphed vertices) if (halfFloat) { for(var v = 0; v < usedDataIndices.length; v++){ var index = usedDataIndices[v] * 3; var dstIndex = v * numComponents + numComponents; textureData[dstIndex] = float2Half(data[index]); textureData[dstIndex + 1] = float2Half(data[index + 1]); textureData[dstIndex + 2] = float2Half(data[index + 2]); } } else { for(var v1 = 0; v1 < usedDataIndices.length; v1++){ var index1 = usedDataIndices[v1] * 3; var dstIndex1 = v1 * numComponents + numComponents; textureData[dstIndex1] = data[index1]; textureData[dstIndex1 + 1] = data[index1 + 1]; textureData[dstIndex1 + 2] = data[index1 + 2]; } } // assign texture to target texture.unlock(); var target1 = deltaInfos[i2].target; target1._setTexture(deltaInfos[i2].name, texture); } // create vertex stream with vertex_id used to map vertex to texture var formatDesc = [ { semantic: SEMANTIC_ATTR15, components: 1, type: TYPE_UINT32, asInt: true } ]; this.vertexBufferIds = new VertexBuffer(this.device, new VertexFormat(this.device, formatDesc, ids.length), ids.length, { data: new Uint32Array(ids) }); return true; } /** * Frees video memory allocated by this object. */ destroy() { var _this_vertexBufferIds; (_this_vertexBufferIds = this.vertexBufferIds) == null ? undefined : _this_vertexBufferIds.destroy(); this.vertexBufferIds = null; for(var i = 0; i < this._targets.length; i++){ this._targets[i].destroy(); } this._targets.length = 0; } /** * Gets the array of morph targets. * * @type {MorphTarget[]} */ get targets() { return this._targets; } _updateMorphFlags() { // find out if this morph needs to morph positions and normals this._morphPositions = false; this._morphNormals = false; for(var i = 0; i < this._targets.length; i++){ var target = this._targets[i]; if (target.morphPositions) { this._morphPositions = true; } if (target.morphNormals) { this._morphNormals = true; } } } /** * Creates texture. Used to create both source morph target data, as well as render target used * to morph these into, positions and normals. * * @param {string} name - The name of the texture. * @param {number} format - The format of the texture. * @returns {Texture} The created texture. * @private */ _createTexture(name, format) { return new Texture(this.device, { width: this.morphTextureWidth, height: this.morphTextureHeight, format: format, cubemap: false, mipmaps: false, minFilter: FILTER_NEAREST, magFilter: FILTER_NEAREST, addressU: ADDRESS_CLAMP_TO_EDGE, addressV: ADDRESS_CLAMP_TO_EDGE, name: name }); } /** * Create a new Morph instance. * * @param {MorphTarget[]} targets - A list of morph targets. * @param {GraphicsDevice} graphicsDevice - The graphics device used to manage this morph target. * @param {object} [options] - Object for passing optional arguments. * @param {boolean} [options.preferHighPrecision] - True if high precision storage should be * preferred. This is faster to create and allows higher precision, but takes more memory and * might be slower to render. Defaults to false. */ constructor(targets, graphicsDevice, { preferHighPrecision = false } = {}){ super(); Debug.assert(graphicsDevice, 'Morph constructor takes a GraphicsDevice as a parameter, and it was not provided.'); this.device = graphicsDevice; this.preferHighPrecision = preferHighPrecision; // validation Debug.assert(targets.every((target)=>!target.used), 'A specified target has already been used to create a Morph, use its clone instead.'); this._targets = targets.slice(); // default to texture based morphing if available var device = this.device; // renderable format var renderableHalf = device.textureHalfFloatRenderable ? PIXELFORMAT_RGBA16F : undefined; var renderableFloat = device.textureFloatRenderable ? PIXELFORMAT_RGBA32F : undefined; this._renderTextureFormat = this.preferHighPrecision ? renderableFloat != null ? renderableFloat : renderableHalf : renderableHalf != null ? renderableHalf : renderableFloat; var _this__renderTextureFormat; // fallback to more limited int format this._renderTextureFormat = (_this__renderTextureFormat = this._renderTextureFormat) != null ? _this__renderTextureFormat : PIXELFORMAT_RGBA16U; this.intRenderFormat = isIntegerPixelFormat(this._renderTextureFormat); // source texture format - both are always supported this._textureFormat = this.preferHighPrecision ? PIXELFORMAT_RGB32F : PIXELFORMAT_RGBA16F; this._init(); this._updateMorphFlags(); } } export { Morph };