12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148 |
- var __extends = this.__extends || function (d, b) {
- for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
- function __() { this.constructor = d; }
- __.prototype = b.prototype;
- d.prototype = new __();
- };
- var BABYLON;
- (function (BABYLON) {
- var _InstancesBatch = (function () {
- function _InstancesBatch() {
- this.mustReturn = false;
- this.visibleInstances = new Array();
- this.renderSelf = new Array();
- }
- return _InstancesBatch;
- })();
- BABYLON._InstancesBatch = _InstancesBatch;
- var Mesh = (function (_super) {
- __extends(Mesh, _super);
- function Mesh(name, scene) {
- _super.call(this, name, scene);
- // Members
- this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
- this.instances = new Array();
- this._LODLevels = new Array();
- this._onBeforeRenderCallbacks = new Array();
- this._onAfterRenderCallbacks = new Array();
- this._visibleInstances = {};
- this._renderIdForInstances = new Array();
- this._batchCache = new _InstancesBatch();
- this._instancesBufferSize = 32 * 16 * 4;
- }
- Object.defineProperty(Mesh.prototype, "hasLODLevels", {
- // Methods
- get: function () {
- return this._LODLevels.length > 0;
- },
- enumerable: true,
- configurable: true
- });
- Mesh.prototype._sortLODLevels = function () {
- this._LODLevels.sort(function (a, b) {
- if (a.distance < b.distance) {
- return 1;
- }
- if (a.distance > b.distance) {
- return -1;
- }
- return 0;
- });
- };
- Mesh.prototype.addLODLevel = function (distance, mesh) {
- if (mesh && mesh._masterMesh) {
- BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
- return this;
- }
- var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
- this._LODLevels.push(level);
- if (mesh) {
- mesh._masterMesh = this;
- }
- this._sortLODLevels();
- return this;
- };
- Mesh.prototype.removeLODLevel = function (mesh) {
- for (var index = 0; index < this._LODLevels.length; index++) {
- if (this._LODLevels[index].mesh === mesh) {
- this._LODLevels.splice(index, 1);
- if (mesh) {
- mesh._masterMesh = null;
- }
- }
- }
- this._sortLODLevels();
- return this;
- };
- Mesh.prototype.getLOD = function (camera, boundingSphere) {
- if (!this._LODLevels || this._LODLevels.length === 0) {
- return this;
- }
- var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
- if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
- return this;
- }
- for (var index = 0; index < this._LODLevels.length; index++) {
- var level = this._LODLevels[index];
- if (level.distance < distanceToCamera) {
- if (level.mesh) {
- level.mesh._preActivate();
- level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
- }
- return level.mesh;
- }
- }
- return this;
- };
- Object.defineProperty(Mesh.prototype, "geometry", {
- get: function () {
- return this._geometry;
- },
- enumerable: true,
- configurable: true
- });
- Mesh.prototype.getTotalVertices = function () {
- if (!this._geometry) {
- return 0;
- }
- return this._geometry.getTotalVertices();
- };
- Mesh.prototype.getVerticesData = function (kind) {
- if (!this._geometry) {
- return null;
- }
- return this._geometry.getVerticesData(kind);
- };
- Mesh.prototype.getVertexBuffer = function (kind) {
- if (!this._geometry) {
- return undefined;
- }
- return this._geometry.getVertexBuffer(kind);
- };
- Mesh.prototype.isVerticesDataPresent = function (kind) {
- if (!this._geometry) {
- if (this._delayInfo) {
- return this._delayInfo.indexOf(kind) !== -1;
- }
- return false;
- }
- return this._geometry.isVerticesDataPresent(kind);
- };
- Mesh.prototype.getVerticesDataKinds = function () {
- if (!this._geometry) {
- var result = [];
- if (this._delayInfo) {
- for (var kind in this._delayInfo) {
- result.push(kind);
- }
- }
- return result;
- }
- return this._geometry.getVerticesDataKinds();
- };
- Mesh.prototype.getTotalIndices = function () {
- if (!this._geometry) {
- return 0;
- }
- return this._geometry.getTotalIndices();
- };
- Mesh.prototype.getIndices = function () {
- if (!this._geometry) {
- return [];
- }
- return this._geometry.getIndices();
- };
- Object.defineProperty(Mesh.prototype, "isBlocked", {
- get: function () {
- return this._masterMesh !== null && this._masterMesh !== undefined;
- },
- enumerable: true,
- configurable: true
- });
- Mesh.prototype.isReady = function () {
- if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
- return false;
- }
- return _super.prototype.isReady.call(this);
- };
- Mesh.prototype.isDisposed = function () {
- return this._isDisposed;
- };
- // Methods
- Mesh.prototype._preActivate = function () {
- var sceneRenderId = this.getScene().getRenderId();
- if (this._preActivateId == sceneRenderId) {
- return;
- }
- this._preActivateId = sceneRenderId;
- this._visibleInstances = null;
- };
- Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
- if (!this._visibleInstances) {
- this._visibleInstances = {};
- this._visibleInstances.defaultRenderId = renderId;
- this._visibleInstances.selfDefaultRenderId = this._renderId;
- }
- if (!this._visibleInstances[renderId]) {
- this._visibleInstances[renderId] = new Array();
- }
- this._visibleInstances[renderId].push(instance);
- };
- Mesh.prototype.refreshBoundingInfo = function () {
- var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- if (data) {
- var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
- this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
- }
- if (this.subMeshes) {
- for (var index = 0; index < this.subMeshes.length; index++) {
- this.subMeshes[index].refreshBoundingInfo();
- }
- }
- this._updateBoundingInfo();
- };
- Mesh.prototype._createGlobalSubMesh = function () {
- var totalVertices = this.getTotalVertices();
- if (!totalVertices || !this.getIndices()) {
- return null;
- }
- this.releaseSubMeshes();
- return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
- };
- Mesh.prototype.subdivide = function (count) {
- if (count < 1) {
- return;
- }
- var totalIndices = this.getTotalIndices();
- var subdivisionSize = (totalIndices / count) | 0;
- var offset = 0;
- while (subdivisionSize % 3 != 0) {
- subdivisionSize++;
- }
- this.releaseSubMeshes();
- for (var index = 0; index < count; index++) {
- if (offset >= totalIndices) {
- break;
- }
- BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
- offset += subdivisionSize;
- }
- this.synchronizeInstances();
- };
- Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
- if (kind instanceof Array) {
- var temp = data;
- data = kind;
- kind = temp;
- BABYLON.Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
- }
- if (!this._geometry) {
- var vertexData = new BABYLON.VertexData();
- vertexData.set(data, kind);
- var scene = this.getScene();
- new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
- } else {
- this._geometry.setVerticesData(kind, data, updatable, stride);
- }
- };
- Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
- if (!this._geometry) {
- return;
- }
- if (!makeItUnique) {
- this._geometry.updateVerticesData(kind, data, updateExtends);
- } else {
- this.makeGeometryUnique();
- this.updateVerticesData(kind, data, updateExtends, false);
- }
- };
- Mesh.prototype.updateVerticesDataDirectly = function (kind, data, makeItUnique) {
- if (!this._geometry) {
- return;
- }
- if (!makeItUnique) {
- this._geometry.updateVerticesDataDirectly(kind, data);
- } else {
- this.makeGeometryUnique();
- this.updateVerticesDataDirectly(kind, data, false);
- }
- };
- Mesh.prototype.makeGeometryUnique = function () {
- if (!this._geometry) {
- return;
- }
- var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
- geometry.applyToMesh(this);
- };
- Mesh.prototype.setIndices = function (indices) {
- if (!this._geometry) {
- var vertexData = new BABYLON.VertexData();
- vertexData.indices = indices;
- var scene = this.getScene();
- new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
- } else {
- this._geometry.setIndices(indices);
- }
- };
- Mesh.prototype._bind = function (subMesh, effect, fillMode) {
- var engine = this.getScene().getEngine();
- // Wireframe
- var indexToBind;
- switch (fillMode) {
- case BABYLON.Material.PointFillMode:
- indexToBind = null;
- break;
- case BABYLON.Material.WireFrameFillMode:
- indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
- break;
- default:
- case BABYLON.Material.TriangleFillMode:
- indexToBind = this._geometry.getIndexBuffer();
- break;
- }
- // VBOs
- engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
- };
- Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
- if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
- return;
- }
- var engine = this.getScene().getEngine();
- switch (fillMode) {
- case BABYLON.Material.PointFillMode:
- engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
- break;
- case BABYLON.Material.WireFrameFillMode:
- engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
- break;
- default:
- engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
- }
- };
- Mesh.prototype.registerBeforeRender = function (func) {
- this._onBeforeRenderCallbacks.push(func);
- };
- Mesh.prototype.unregisterBeforeRender = function (func) {
- var index = this._onBeforeRenderCallbacks.indexOf(func);
- if (index > -1) {
- this._onBeforeRenderCallbacks.splice(index, 1);
- }
- };
- Mesh.prototype.registerAfterRender = function (func) {
- this._onAfterRenderCallbacks.push(func);
- };
- Mesh.prototype.unregisterAfterRender = function (func) {
- var index = this._onAfterRenderCallbacks.indexOf(func);
- if (index > -1) {
- this._onAfterRenderCallbacks.splice(index, 1);
- }
- };
- Mesh.prototype._getInstancesRenderList = function (subMeshId) {
- var scene = this.getScene();
- this._batchCache.mustReturn = false;
- this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
- this._batchCache.visibleInstances[subMeshId] = null;
- if (this._visibleInstances) {
- var currentRenderId = scene.getRenderId();
- this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
- var selfRenderId = this._renderId;
- if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
- this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
- currentRenderId = this._visibleInstances.defaultRenderId;
- selfRenderId = this._visibleInstances.selfDefaultRenderId;
- }
- if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
- if (this._renderIdForInstances[subMeshId] === currentRenderId) {
- this._batchCache.mustReturn = true;
- return this._batchCache;
- }
- if (currentRenderId !== selfRenderId) {
- this._batchCache.renderSelf[subMeshId] = false;
- }
- }
- this._renderIdForInstances[subMeshId] = currentRenderId;
- }
- return this._batchCache;
- };
- Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
- var visibleInstances = batch.visibleInstances[subMesh._id];
- var matricesCount = visibleInstances.length + 1;
- var bufferSize = matricesCount * 16 * 4;
- while (this._instancesBufferSize < bufferSize) {
- this._instancesBufferSize *= 2;
- }
- if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
- if (this._worldMatricesInstancesBuffer) {
- engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
- }
- this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
- this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
- }
- var offset = 0;
- var instancesCount = 0;
- var world = this.getWorldMatrix();
- if (batch.renderSelf[subMesh._id]) {
- world.copyToArray(this._worldMatricesInstancesArray, offset);
- offset += 16;
- instancesCount++;
- }
- if (visibleInstances) {
- for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
- var instance = visibleInstances[instanceIndex];
- instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
- offset += 16;
- instancesCount++;
- }
- }
- var offsetLocation0 = effect.getAttributeLocationByName("world0");
- var offsetLocation1 = effect.getAttributeLocationByName("world1");
- var offsetLocation2 = effect.getAttributeLocationByName("world2");
- var offsetLocation3 = effect.getAttributeLocationByName("world3");
- var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
- engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
- this._draw(subMesh, fillMode, instancesCount);
- engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
- };
- Mesh.prototype.render = function (subMesh) {
- var scene = this.getScene();
- // Managing instances
- var batch = this._getInstancesRenderList(subMesh._id);
- if (batch.mustReturn) {
- return;
- }
- // Checking geometry state
- if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
- return;
- }
- for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
- this._onBeforeRenderCallbacks[callbackIndex]();
- }
- var engine = scene.getEngine();
- var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
- // Material
- var effectiveMaterial = subMesh.getMaterial();
- if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
- return;
- }
- // Outline - step 1
- var savedDepthWrite = engine.getDepthWrite();
- if (this.renderOutline) {
- engine.setDepthWrite(false);
- scene.getOutlineRenderer().render(subMesh, batch);
- engine.setDepthWrite(savedDepthWrite);
- }
- effectiveMaterial._preBind();
- var effect = effectiveMaterial.getEffect();
- // Bind
- var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
- this._bind(subMesh, effect, fillMode);
- var world = this.getWorldMatrix();
- effectiveMaterial.bind(world, this);
- // Instances rendering
- if (hardwareInstancedRendering) {
- this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
- } else {
- if (batch.renderSelf[subMesh._id]) {
- // Draw
- this._draw(subMesh, fillMode);
- }
- if (batch.visibleInstances[subMesh._id]) {
- for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
- var instance = batch.visibleInstances[subMesh._id][instanceIndex];
- // World
- world = instance.getWorldMatrix();
- effectiveMaterial.bindOnlyWorldMatrix(world);
- // Draw
- this._draw(subMesh, fillMode);
- }
- }
- }
- // Unbind
- effectiveMaterial.unbind();
- // Outline - step 2
- if (this.renderOutline && savedDepthWrite) {
- engine.setDepthWrite(true);
- engine.setColorWrite(false);
- scene.getOutlineRenderer().render(subMesh, batch);
- engine.setColorWrite(true);
- }
- // Overlay
- if (this.renderOverlay) {
- var currentMode = engine.getAlphaMode();
- engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
- scene.getOutlineRenderer().render(subMesh, batch, true);
- engine.setAlphaMode(currentMode);
- }
- for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
- this._onAfterRenderCallbacks[callbackIndex]();
- }
- };
- Mesh.prototype.getEmittedParticleSystems = function () {
- var results = new Array();
- for (var index = 0; index < this.getScene().particleSystems.length; index++) {
- var particleSystem = this.getScene().particleSystems[index];
- if (particleSystem.emitter === this) {
- results.push(particleSystem);
- }
- }
- return results;
- };
- Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
- var results = new Array();
- var descendants = this.getDescendants();
- descendants.push(this);
- for (var index = 0; index < this.getScene().particleSystems.length; index++) {
- var particleSystem = this.getScene().particleSystems[index];
- if (descendants.indexOf(particleSystem.emitter) !== -1) {
- results.push(particleSystem);
- }
- }
- return results;
- };
- Mesh.prototype.getChildren = function () {
- var results = [];
- for (var index = 0; index < this.getScene().meshes.length; index++) {
- var mesh = this.getScene().meshes[index];
- if (mesh.parent == this) {
- results.push(mesh);
- }
- }
- return results;
- };
- Mesh.prototype._checkDelayState = function () {
- var _this = this;
- var that = this;
- var scene = this.getScene();
- if (this._geometry) {
- this._geometry.load(scene);
- } else if (that.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
- that.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
- scene._addPendingData(that);
- var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
- BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
- if (data instanceof ArrayBuffer) {
- _this._delayLoadingFunction(data, _this);
- } else {
- _this._delayLoadingFunction(JSON.parse(data), _this);
- }
- _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
- scene._removePendingData(_this);
- }, function () {
- }, scene.database, getBinaryData);
- }
- };
- Mesh.prototype.isInFrustum = function (frustumPlanes) {
- if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
- return false;
- }
- if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
- return false;
- }
- this._checkDelayState();
- return true;
- };
- Mesh.prototype.setMaterialByID = function (id) {
- var materials = this.getScene().materials;
- for (var index = 0; index < materials.length; index++) {
- if (materials[index].id == id) {
- this.material = materials[index];
- return;
- }
- }
- // Multi
- var multiMaterials = this.getScene().multiMaterials;
- for (index = 0; index < multiMaterials.length; index++) {
- if (multiMaterials[index].id == id) {
- this.material = multiMaterials[index];
- return;
- }
- }
- };
- Mesh.prototype.getAnimatables = function () {
- var results = [];
- if (this.material) {
- results.push(this.material);
- }
- if (this.skeleton) {
- results.push(this.skeleton);
- }
- return results;
- };
- // Geometry
- Mesh.prototype.bakeTransformIntoVertices = function (transform) {
- // Position
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
- return;
- }
- this._resetPointsArrayCache();
- var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var temp = [];
- for (var index = 0; index < data.length; index += 3) {
- BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
- }
- this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
- // Normals
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
- return;
- }
- data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- for (index = 0; index < data.length; index += 3) {
- BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
- }
- this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
- };
- // Cache
- Mesh.prototype._resetPointsArrayCache = function () {
- this._positions = null;
- };
- Mesh.prototype._generatePointsArray = function () {
- if (this._positions)
- return true;
- this._positions = [];
- var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- if (!data) {
- return false;
- }
- for (var index = 0; index < data.length; index += 3) {
- this._positions.push(BABYLON.Vector3.FromArray(data, index));
- }
- return true;
- };
- // Clone
- Mesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
- var result = new BABYLON.Mesh(name, this.getScene());
- // Geometry
- this._geometry.applyToMesh(result);
- // Deep copy
- BABYLON.Tools.DeepCopy(this, result, ["name", "material", "skeleton"], []);
- // Material
- result.material = this.material;
- // Parent
- if (newParent) {
- result.parent = newParent;
- }
- if (!doNotCloneChildren) {
- for (var index = 0; index < this.getScene().meshes.length; index++) {
- var mesh = this.getScene().meshes[index];
- if (mesh.parent == this) {
- mesh.clone(mesh.name, result);
- }
- }
- }
- for (index = 0; index < this.getScene().particleSystems.length; index++) {
- var system = this.getScene().particleSystems[index];
- if (system.emitter == this) {
- system.clone(system.name, result);
- }
- }
- result.computeWorldMatrix(true);
- return result;
- };
- // Dispose
- Mesh.prototype.dispose = function (doNotRecurse) {
- if (this._geometry) {
- this._geometry.releaseForMesh(this, true);
- }
- // Instances
- if (this._worldMatricesInstancesBuffer) {
- this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
- this._worldMatricesInstancesBuffer = null;
- }
- while (this.instances.length) {
- this.instances[0].dispose();
- }
- _super.prototype.dispose.call(this, doNotRecurse);
- };
- // Geometric tools
- Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight) {
- var _this = this;
- var scene = this.getScene();
- var onload = function (img) {
- // Getting height map data
- var canvas = document.createElement("canvas");
- var context = canvas.getContext("2d");
- var heightMapWidth = img.width;
- var heightMapHeight = img.height;
- canvas.width = heightMapWidth;
- canvas.height = heightMapHeight;
- context.drawImage(img, 0, 0);
- // Create VertexData from map data
- var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
- _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
- };
- BABYLON.Tools.LoadImage(url, onload, function () {
- }, scene.database);
- };
- Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
- if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
- BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
- return;
- }
- var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
- var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
- var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
- var position = BABYLON.Vector3.Zero();
- var normal = BABYLON.Vector3.Zero();
- var uv = BABYLON.Vector2.Zero();
- for (var index = 0; index < positions.length; index += 3) {
- BABYLON.Vector3.FromArrayToRef(positions, index, position);
- BABYLON.Vector3.FromArrayToRef(normals, index, normal);
- BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
- // Compute height
- var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
- var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
- var pos = (u + v * heightMapWidth) * 4;
- var r = buffer[pos] / 255.0;
- var g = buffer[pos + 1] / 255.0;
- var b = buffer[pos + 2] / 255.0;
- var gradient = r * 0.3 + g * 0.59 + b * 0.11;
- normal.normalize();
- normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
- position = position.add(normal);
- position.toArray(positions, index);
- }
- BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
- this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
- this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
- };
- Mesh.prototype.convertToFlatShadedMesh = function () {
- /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
- /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
- var kinds = this.getVerticesDataKinds();
- var vbs = [];
- var data = [];
- var newdata = [];
- var updatableNormals = false;
- for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- var kind = kinds[kindIndex];
- var vertexBuffer = this.getVertexBuffer(kind);
- if (kind === BABYLON.VertexBuffer.NormalKind) {
- updatableNormals = vertexBuffer.isUpdatable();
- kinds.splice(kindIndex, 1);
- kindIndex--;
- continue;
- }
- vbs[kind] = vertexBuffer;
- data[kind] = vbs[kind].getData();
- newdata[kind] = [];
- }
- // Save previous submeshes
- var previousSubmeshes = this.subMeshes.slice(0);
- var indices = this.getIndices();
- var totalIndices = this.getTotalIndices();
- for (index = 0; index < totalIndices; index++) {
- var vertexIndex = indices[index];
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- var stride = vbs[kind].getStrideSize();
- for (var offset = 0; offset < stride; offset++) {
- newdata[kind].push(data[kind][vertexIndex * stride + offset]);
- }
- }
- }
- // Updating faces & normal
- var normals = [];
- var positions = newdata[BABYLON.VertexBuffer.PositionKind];
- for (var index = 0; index < totalIndices; index += 3) {
- indices[index] = index;
- indices[index + 1] = index + 1;
- indices[index + 2] = index + 2;
- var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
- var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
- var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
- var p1p2 = p1.subtract(p2);
- var p3p2 = p3.subtract(p2);
- var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
- for (var localIndex = 0; localIndex < 3; localIndex++) {
- normals.push(normal.x);
- normals.push(normal.y);
- normals.push(normal.z);
- }
- }
- this.setIndices(indices);
- this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
- for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
- kind = kinds[kindIndex];
- this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
- }
- // Updating submeshes
- this.releaseSubMeshes();
- for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
- var previousOne = previousSubmeshes[submeshIndex];
- var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
- }
- this.synchronizeInstances();
- };
- // Instances
- Mesh.prototype.createInstance = function (name) {
- return new BABYLON.InstancedMesh(name, this);
- };
- Mesh.prototype.synchronizeInstances = function () {
- for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
- var instance = this.instances[instanceIndex];
- instance._syncSubMeshes();
- }
- };
- // Statics
- Mesh.CreateBox = function (name, size, scene, updatable) {
- var box = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateBox(size);
- vertexData.applyToMesh(box, updatable);
- return box;
- };
- Mesh.CreateSphere = function (name, segments, diameter, scene, updatable) {
- var sphere = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateSphere(segments, diameter);
- vertexData.applyToMesh(sphere, updatable);
- return sphere;
- };
- // Cylinder and cone (Code inspired by SharpDX.org)
- Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable) {
- // subdivisions is a new parameter, we need to support old signature
- if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
- if (scene !== undefined) {
- updatable = scene;
- }
- scene = subdivisions;
- subdivisions = 1;
- }
- var cylinder = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
- vertexData.applyToMesh(cylinder, updatable);
- return cylinder;
- };
- // Torus (Code from SharpDX.org)
- Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable) {
- var torus = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateTorus(diameter, thickness, tessellation);
- vertexData.applyToMesh(torus, updatable);
- return torus;
- };
- Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable) {
- var torusKnot = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
- vertexData.applyToMesh(torusKnot, updatable);
- return torusKnot;
- };
- // Lines
- Mesh.CreateLines = function (name, points, scene, updatable) {
- var lines = new BABYLON.LinesMesh(name, scene, updatable);
- var vertexData = BABYLON.VertexData.CreateLines(points);
- vertexData.applyToMesh(lines, updatable);
- return lines;
- };
- // Plane & ground
- Mesh.CreatePlane = function (name, size, scene, updatable) {
- var plane = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreatePlane(size);
- vertexData.applyToMesh(plane, updatable);
- return plane;
- };
- Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
- var ground = new BABYLON.GroundMesh(name, scene);
- ground._setReady(false);
- ground._subdivisions = subdivisions;
- var vertexData = BABYLON.VertexData.CreateGround(width, height, subdivisions);
- vertexData.applyToMesh(ground, updatable);
- ground._setReady(true);
- return ground;
- };
- Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
- var tiledGround = new BABYLON.Mesh(name, scene);
- var vertexData = BABYLON.VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
- vertexData.applyToMesh(tiledGround, updatable);
- return tiledGround;
- };
- Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable) {
- var ground = new BABYLON.GroundMesh(name, scene);
- ground._subdivisions = subdivisions;
- ground._setReady(false);
- var onload = function (img) {
- // Getting height map data
- var canvas = document.createElement("canvas");
- var context = canvas.getContext("2d");
- var heightMapWidth = img.width;
- var heightMapHeight = img.height;
- canvas.width = heightMapWidth;
- canvas.height = heightMapHeight;
- context.drawImage(img, 0, 0);
- // Create VertexData from map data
- var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
- var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
- vertexData.applyToMesh(ground, updatable);
- ground._setReady(true);
- };
- BABYLON.Tools.LoadImage(url, onload, function () {
- }, scene.database);
- return ground;
- };
- // Tools
- Mesh.MinMax = function (meshes) {
- var minVector = null;
- var maxVector = null;
- for (var i in meshes) {
- var mesh = meshes[i];
- var boundingBox = mesh.getBoundingInfo().boundingBox;
- if (!minVector) {
- minVector = boundingBox.minimumWorld;
- maxVector = boundingBox.maximumWorld;
- continue;
- }
- minVector.MinimizeInPlace(boundingBox.minimumWorld);
- maxVector.MaximizeInPlace(boundingBox.maximumWorld);
- }
- return {
- min: minVector,
- max: maxVector
- };
- };
- Mesh.Center = function (meshesOrMinMaxVector) {
- var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
- return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
- };
- return Mesh;
- })(BABYLON.AbstractMesh);
- BABYLON.Mesh = Mesh;
- })(BABYLON || (BABYLON = {}));
- //# sourceMappingURL=babylon.mesh.js.map
|