babylon.mesh.ts 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289
  1. module BABYLON {
  2. export class _InstancesBatch {
  3. public mustReturn = false;
  4. public visibleInstances = new Array<Array<InstancedMesh>>();
  5. public renderSelf = new Array<boolean>();
  6. }
  7. export class Mesh extends AbstractMesh implements IGetSetVerticesData {
  8. // Members
  9. public delayLoadState = Engine.DELAYLOADSTATE_NONE;
  10. public instances = new Array<InstancedMesh>();
  11. public delayLoadingFile: string;
  12. public _binaryInfo: any;
  13. private _LODLevels = new Array<Internals.MeshLODLevel>();
  14. // Private
  15. public _geometry: Geometry;
  16. private _onBeforeRenderCallbacks = new Array<() => void>();
  17. private _onAfterRenderCallbacks = new Array<() => void>();
  18. public _delayInfo; //ANY
  19. public _delayLoadingFunction: (any, Mesh) => void;
  20. public _visibleInstances: any = {};
  21. private _renderIdForInstances = new Array<number>();
  22. private _batchCache = new _InstancesBatch();
  23. private _worldMatricesInstancesBuffer: WebGLBuffer;
  24. private _worldMatricesInstancesArray: Float32Array;
  25. private _instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  26. public _shouldGenerateFlatShading: boolean;
  27. private _preActivateId: number;
  28. /**
  29. * @constructor
  30. * @param {string} name - The value used by scene.getMeshByName() to do a lookup.
  31. * @param {Scene} scene - The scene to add this mesh to.
  32. * @param {Node} parent - The parent of this mesh, if it has one
  33. * @param {Mesh} source - An optional Mesh from which geometry is shared, cloned.
  34. * @param {boolean} doNotCloneChildren - When cloning, skip cloning child meshes of source, default False.
  35. * When false, achieved by calling a clone(), also passing False.
  36. * This will make creation of children, recursive.
  37. */
  38. constructor(name: string, scene: Scene, parent: Node = null, source?: Mesh, doNotCloneChildren?: boolean) {
  39. super(name, scene);
  40. if (source) {
  41. // Geometry
  42. if (source._geometry) {
  43. source._geometry.applyToMesh(this);
  44. }
  45. // Deep copy
  46. Tools.DeepCopy(source, this, ["name", "material", "skeleton"], []);
  47. // Material
  48. this.material = source.material;
  49. if (!doNotCloneChildren) {
  50. // Children
  51. for (var index = 0; index < scene.meshes.length; index++) {
  52. var mesh = scene.meshes[index];
  53. if (mesh.parent === source) {
  54. // doNotCloneChildren is always going to be False
  55. var newChild = mesh.clone(name + "." + mesh.name, this, doNotCloneChildren);
  56. }
  57. }
  58. }
  59. // Particles
  60. for (index = 0; index < scene.particleSystems.length; index++) {
  61. var system = scene.particleSystems[index];
  62. if (system.emitter === source) {
  63. system.clone(system.name, this);
  64. }
  65. }
  66. this.computeWorldMatrix(true);
  67. }
  68. // Parent
  69. if (parent !== null) {
  70. this.parent = parent;
  71. }
  72. }
  73. // Methods
  74. public get hasLODLevels(): boolean {
  75. return this._LODLevels.length > 0;
  76. }
  77. private _sortLODLevels(): void {
  78. this._LODLevels.sort((a, b) => {
  79. if (a.distance < b.distance) {
  80. return 1;
  81. }
  82. if (a.distance > b.distance) {
  83. return -1;
  84. }
  85. return 0;
  86. });
  87. }
  88. /**
  89. * Add a mesh as LOD level triggered at the given distance.
  90. * @param {number} distance - the distance from the center of the object to show this level
  91. * @param {BABYLON.Mesh} mesh - the mesh to be added as LOD level
  92. * @return {BABYLON.Mesh} this mesh (for chaining)
  93. */
  94. public addLODLevel(distance: number, mesh: Mesh): Mesh {
  95. if (mesh && mesh._masterMesh) {
  96. Tools.Warn("You cannot use a mesh as LOD level twice");
  97. return this;
  98. }
  99. var level = new Internals.MeshLODLevel(distance, mesh);
  100. this._LODLevels.push(level);
  101. if (mesh) {
  102. mesh._masterMesh = this;
  103. }
  104. this._sortLODLevels();
  105. return this;
  106. }
  107. /**
  108. * Remove a mesh from the LOD array
  109. * @param {BABYLON.Mesh} mesh - the mesh to be removed.
  110. * @return {BABYLON.Mesh} this mesh (for chaining)
  111. */
  112. public removeLODLevel(mesh: Mesh): Mesh {
  113. for (var index = 0; index < this._LODLevels.length; index++) {
  114. if (this._LODLevels[index].mesh === mesh) {
  115. this._LODLevels.splice(index, 1);
  116. if (mesh) {
  117. mesh._masterMesh = null;
  118. }
  119. }
  120. }
  121. this._sortLODLevels();
  122. return this;
  123. }
  124. public getLOD(camera: Camera, boundingSphere?: BoundingSphere): AbstractMesh {
  125. if (!this._LODLevels || this._LODLevels.length === 0) {
  126. return this;
  127. }
  128. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.position).length();
  129. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  130. return this;
  131. }
  132. for (var index = 0; index < this._LODLevels.length; index++) {
  133. var level = this._LODLevels[index];
  134. if (level.distance < distanceToCamera) {
  135. if (level.mesh) {
  136. level.mesh._preActivate();
  137. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  138. }
  139. return level.mesh;
  140. }
  141. }
  142. return this;
  143. }
  144. public get geometry(): Geometry {
  145. return this._geometry;
  146. }
  147. public getTotalVertices(): number {
  148. if (!this._geometry) {
  149. return 0;
  150. }
  151. return this._geometry.getTotalVertices();
  152. }
  153. public getVerticesData(kind: string): number[] {
  154. if (!this._geometry) {
  155. return null;
  156. }
  157. return this._geometry.getVerticesData(kind);
  158. }
  159. public getVertexBuffer(kind): VertexBuffer {
  160. if (!this._geometry) {
  161. return undefined;
  162. }
  163. return this._geometry.getVertexBuffer(kind);
  164. }
  165. public isVerticesDataPresent(kind: string): boolean {
  166. if (!this._geometry) {
  167. if (this._delayInfo) {
  168. return this._delayInfo.indexOf(kind) !== -1;
  169. }
  170. return false;
  171. }
  172. return this._geometry.isVerticesDataPresent(kind);
  173. }
  174. public getVerticesDataKinds(): string[] {
  175. if (!this._geometry) {
  176. var result = [];
  177. if (this._delayInfo) {
  178. for (var kind in this._delayInfo) {
  179. result.push(kind);
  180. }
  181. }
  182. return result;
  183. }
  184. return this._geometry.getVerticesDataKinds();
  185. }
  186. public getTotalIndices(): number {
  187. if (!this._geometry) {
  188. return 0;
  189. }
  190. return this._geometry.getTotalIndices();
  191. }
  192. public getIndices(): number[] {
  193. if (!this._geometry) {
  194. return [];
  195. }
  196. return this._geometry.getIndices();
  197. }
  198. public get isBlocked(): boolean {
  199. return this._masterMesh !== null && this._masterMesh !== undefined;
  200. }
  201. public isReady(): boolean {
  202. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  203. return false;
  204. }
  205. return super.isReady();
  206. }
  207. public isDisposed(): boolean {
  208. return this._isDisposed;
  209. }
  210. // Methods
  211. public _preActivate(): void {
  212. var sceneRenderId = this.getScene().getRenderId();
  213. if (this._preActivateId == sceneRenderId) {
  214. return;
  215. }
  216. this._preActivateId = sceneRenderId;
  217. this._visibleInstances = null;
  218. }
  219. public _registerInstanceForRenderId(instance: InstancedMesh, renderId: number) {
  220. if (!this._visibleInstances) {
  221. this._visibleInstances = {};
  222. this._visibleInstances.defaultRenderId = renderId;
  223. this._visibleInstances.selfDefaultRenderId = this._renderId;
  224. }
  225. if (!this._visibleInstances[renderId]) {
  226. this._visibleInstances[renderId] = new Array<InstancedMesh>();
  227. }
  228. this._visibleInstances[renderId].push(instance);
  229. }
  230. public refreshBoundingInfo(): void {
  231. var data = this.getVerticesData(VertexBuffer.PositionKind);
  232. if (data) {
  233. var extend = Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  234. this._boundingInfo = new BoundingInfo(extend.minimum, extend.maximum);
  235. }
  236. if (this.subMeshes) {
  237. for (var index = 0; index < this.subMeshes.length; index++) {
  238. this.subMeshes[index].refreshBoundingInfo();
  239. }
  240. }
  241. this._updateBoundingInfo();
  242. }
  243. public _createGlobalSubMesh(): SubMesh {
  244. var totalVertices = this.getTotalVertices();
  245. if (!totalVertices || !this.getIndices()) {
  246. return null;
  247. }
  248. this.releaseSubMeshes();
  249. return new SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  250. }
  251. public subdivide(count: number): void {
  252. if (count < 1) {
  253. return;
  254. }
  255. var totalIndices = this.getTotalIndices();
  256. var subdivisionSize = (totalIndices / count) | 0;
  257. var offset = 0;
  258. // Ensure that subdivisionSize is a multiple of 3
  259. while (subdivisionSize % 3 != 0) {
  260. subdivisionSize++;
  261. }
  262. this.releaseSubMeshes();
  263. for (var index = 0; index < count; index++) {
  264. if (offset >= totalIndices) {
  265. break;
  266. }
  267. SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  268. offset += subdivisionSize;
  269. }
  270. this.synchronizeInstances();
  271. }
  272. public setVerticesData(kind: any, data: any, updatable?: boolean, stride?: number): void {
  273. if (kind instanceof Array) {
  274. var temp = data;
  275. data = kind;
  276. kind = temp;
  277. Tools.Warn("Deprecated usage of setVerticesData detected (since v1.12). Current signature is setVerticesData(kind, data, updatable).");
  278. }
  279. if (!this._geometry) {
  280. var vertexData = new VertexData();
  281. vertexData.set(data, kind);
  282. var scene = this.getScene();
  283. new Geometry(Geometry.RandomId(), scene, vertexData, updatable, this);
  284. }
  285. else {
  286. this._geometry.setVerticesData(kind, data, updatable, stride);
  287. }
  288. }
  289. public updateVerticesData(kind: string, data: number[], updateExtends?: boolean, makeItUnique?: boolean): void {
  290. if (!this._geometry) {
  291. return;
  292. }
  293. if (!makeItUnique) {
  294. this._geometry.updateVerticesData(kind, data, updateExtends);
  295. }
  296. else {
  297. this.makeGeometryUnique();
  298. this.updateVerticesData(kind, data, updateExtends, false);
  299. }
  300. }
  301. public updateVerticesDataDirectly(kind: string, data: Float32Array, offset?: number, makeItUnique?: boolean): void {
  302. if (!this._geometry) {
  303. return;
  304. }
  305. if (!makeItUnique) {
  306. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  307. }
  308. else {
  309. this.makeGeometryUnique();
  310. this.updateVerticesDataDirectly(kind, data, offset, false);
  311. }
  312. }
  313. public makeGeometryUnique() {
  314. if (!this._geometry) {
  315. return;
  316. }
  317. var geometry = this._geometry.copy(Geometry.RandomId());
  318. geometry.applyToMesh(this);
  319. }
  320. public setIndices(indices: number[], totalVertices?: number): void {
  321. if (!this._geometry) {
  322. var vertexData = new VertexData();
  323. vertexData.indices = indices;
  324. var scene = this.getScene();
  325. new Geometry(Geometry.RandomId(), scene, vertexData, false, this);
  326. }
  327. else {
  328. this._geometry.setIndices(indices, totalVertices);
  329. }
  330. }
  331. public _bind(subMesh: SubMesh, effect: Effect, fillMode: number): void {
  332. var engine = this.getScene().getEngine();
  333. // Wireframe
  334. var indexToBind;
  335. switch (fillMode) {
  336. case Material.PointFillMode:
  337. indexToBind = null;
  338. break;
  339. case Material.WireFrameFillMode:
  340. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  341. break;
  342. default:
  343. case Material.TriangleFillMode:
  344. indexToBind = this._geometry.getIndexBuffer();
  345. break;
  346. }
  347. // VBOs
  348. engine.bindMultiBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  349. }
  350. public _draw(subMesh: SubMesh, fillMode: number, instancesCount?: number): void {
  351. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  352. return;
  353. }
  354. var engine = this.getScene().getEngine();
  355. // Draw order
  356. switch (fillMode) {
  357. case Material.PointFillMode:
  358. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  359. break;
  360. case Material.WireFrameFillMode:
  361. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  362. break;
  363. default:
  364. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  365. }
  366. }
  367. public registerBeforeRender(func: () => void): void {
  368. this._onBeforeRenderCallbacks.push(func);
  369. }
  370. public unregisterBeforeRender(func: () => void): void {
  371. var index = this._onBeforeRenderCallbacks.indexOf(func);
  372. if (index > -1) {
  373. this._onBeforeRenderCallbacks.splice(index, 1);
  374. }
  375. }
  376. public registerAfterRender(func: () => void): void {
  377. this._onAfterRenderCallbacks.push(func);
  378. }
  379. public unregisterAfterRender(func: () => void): void {
  380. var index = this._onAfterRenderCallbacks.indexOf(func);
  381. if (index > -1) {
  382. this._onAfterRenderCallbacks.splice(index, 1);
  383. }
  384. }
  385. public _getInstancesRenderList(subMeshId: number): _InstancesBatch {
  386. var scene = this.getScene();
  387. this._batchCache.mustReturn = false;
  388. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  389. this._batchCache.visibleInstances[subMeshId] = null;
  390. if (this._visibleInstances) {
  391. var currentRenderId = scene.getRenderId();
  392. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  393. var selfRenderId = this._renderId;
  394. if (!this._batchCache.visibleInstances[subMeshId] && this._visibleInstances.defaultRenderId) {
  395. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[this._visibleInstances.defaultRenderId];
  396. currentRenderId = Math.max(this._visibleInstances.defaultRenderId, currentRenderId);
  397. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  398. }
  399. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  400. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  401. this._batchCache.mustReturn = true;
  402. return this._batchCache;
  403. }
  404. if (currentRenderId !== selfRenderId) {
  405. this._batchCache.renderSelf[subMeshId] = false;
  406. }
  407. }
  408. this._renderIdForInstances[subMeshId] = currentRenderId;
  409. }
  410. return this._batchCache;
  411. }
  412. public _renderWithInstances(subMesh: SubMesh, fillMode: number, batch: _InstancesBatch, effect: Effect, engine: Engine): void {
  413. var visibleInstances = batch.visibleInstances[subMesh._id];
  414. var matricesCount = visibleInstances.length + 1;
  415. var bufferSize = matricesCount * 16 * 4;
  416. while (this._instancesBufferSize < bufferSize) {
  417. this._instancesBufferSize *= 2;
  418. }
  419. if (!this._worldMatricesInstancesBuffer || this._worldMatricesInstancesBuffer.capacity < this._instancesBufferSize) {
  420. if (this._worldMatricesInstancesBuffer) {
  421. engine.deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  422. }
  423. this._worldMatricesInstancesBuffer = engine.createInstancesBuffer(this._instancesBufferSize);
  424. this._worldMatricesInstancesArray = new Float32Array(this._instancesBufferSize / 4);
  425. }
  426. var offset = 0;
  427. var instancesCount = 0;
  428. var world = this.getWorldMatrix();
  429. if (batch.renderSelf[subMesh._id]) {
  430. world.copyToArray(this._worldMatricesInstancesArray, offset);
  431. offset += 16;
  432. instancesCount++;
  433. }
  434. if (visibleInstances) {
  435. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  436. var instance = visibleInstances[instanceIndex];
  437. instance.getWorldMatrix().copyToArray(this._worldMatricesInstancesArray, offset);
  438. offset += 16;
  439. instancesCount++;
  440. }
  441. }
  442. var offsetLocation0 = effect.getAttributeLocationByName("world0");
  443. var offsetLocation1 = effect.getAttributeLocationByName("world1");
  444. var offsetLocation2 = effect.getAttributeLocationByName("world2");
  445. var offsetLocation3 = effect.getAttributeLocationByName("world3");
  446. var offsetLocations = [offsetLocation0, offsetLocation1, offsetLocation2, offsetLocation3];
  447. engine.updateAndBindInstancesBuffer(this._worldMatricesInstancesBuffer, this._worldMatricesInstancesArray, offsetLocations);
  448. this._draw(subMesh, fillMode, instancesCount);
  449. engine.unBindInstancesBuffer(this._worldMatricesInstancesBuffer, offsetLocations);
  450. }
  451. public render(subMesh: SubMesh): void {
  452. var scene = this.getScene();
  453. // Managing instances
  454. var batch = this._getInstancesRenderList(subMesh._id);
  455. if (batch.mustReturn) {
  456. return;
  457. }
  458. // Checking geometry state
  459. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  460. return;
  461. }
  462. for (var callbackIndex = 0; callbackIndex < this._onBeforeRenderCallbacks.length; callbackIndex++) {
  463. this._onBeforeRenderCallbacks[callbackIndex]();
  464. }
  465. var engine = scene.getEngine();
  466. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  467. // Material
  468. var effectiveMaterial = subMesh.getMaterial();
  469. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  470. return;
  471. }
  472. // Outline - step 1
  473. var savedDepthWrite = engine.getDepthWrite();
  474. if (this.renderOutline) {
  475. engine.setDepthWrite(false);
  476. scene.getOutlineRenderer().render(subMesh, batch);
  477. engine.setDepthWrite(savedDepthWrite);
  478. }
  479. effectiveMaterial._preBind();
  480. var effect = effectiveMaterial.getEffect();
  481. // Bind
  482. var fillMode = scene.forcePointsCloud ? Material.PointFillMode : (scene.forceWireframe ? Material.WireFrameFillMode : effectiveMaterial.fillMode);
  483. this._bind(subMesh, effect, fillMode);
  484. var world = this.getWorldMatrix();
  485. effectiveMaterial.bind(world, this);
  486. // Instances rendering
  487. if (hardwareInstancedRendering) {
  488. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  489. } else {
  490. if (batch.renderSelf[subMesh._id]) {
  491. // Draw
  492. this._draw(subMesh, fillMode);
  493. }
  494. if (batch.visibleInstances[subMesh._id]) {
  495. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  496. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  497. // World
  498. world = instance.getWorldMatrix();
  499. effectiveMaterial.bindOnlyWorldMatrix(world);
  500. // Draw
  501. this._draw(subMesh, fillMode);
  502. }
  503. }
  504. }
  505. // Unbind
  506. effectiveMaterial.unbind();
  507. // Outline - step 2
  508. if (this.renderOutline && savedDepthWrite) {
  509. engine.setDepthWrite(true);
  510. engine.setColorWrite(false);
  511. scene.getOutlineRenderer().render(subMesh, batch);
  512. engine.setColorWrite(true);
  513. }
  514. // Overlay
  515. if (this.renderOverlay) {
  516. var currentMode = engine.getAlphaMode();
  517. engine.setAlphaMode(Engine.ALPHA_COMBINE);
  518. scene.getOutlineRenderer().render(subMesh, batch, true);
  519. engine.setAlphaMode(currentMode);
  520. }
  521. for (callbackIndex = 0; callbackIndex < this._onAfterRenderCallbacks.length; callbackIndex++) {
  522. this._onAfterRenderCallbacks[callbackIndex]();
  523. }
  524. }
  525. public getEmittedParticleSystems(): ParticleSystem[] {
  526. var results = new Array<ParticleSystem>();
  527. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  528. var particleSystem = this.getScene().particleSystems[index];
  529. if (particleSystem.emitter === this) {
  530. results.push(particleSystem);
  531. }
  532. }
  533. return results;
  534. }
  535. public getHierarchyEmittedParticleSystems(): ParticleSystem[] {
  536. var results = new Array<ParticleSystem>();
  537. var descendants = this.getDescendants();
  538. descendants.push(this);
  539. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  540. var particleSystem = this.getScene().particleSystems[index];
  541. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  542. results.push(particleSystem);
  543. }
  544. }
  545. return results;
  546. }
  547. public getChildren(): Node[] {
  548. var results = [];
  549. for (var index = 0; index < this.getScene().meshes.length; index++) {
  550. var mesh = this.getScene().meshes[index];
  551. if (mesh.parent == this) {
  552. results.push(mesh);
  553. }
  554. }
  555. return results;
  556. }
  557. public _checkDelayState(): void {
  558. var that = this;
  559. var scene = this.getScene();
  560. if (this._geometry) {
  561. this._geometry.load(scene);
  562. }
  563. else if (that.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  564. that.delayLoadState = Engine.DELAYLOADSTATE_LOADING;
  565. scene._addPendingData(that);
  566. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1) ? true : false;
  567. Tools.LoadFile(this.delayLoadingFile, data => {
  568. if (data instanceof ArrayBuffer) {
  569. this._delayLoadingFunction(data, this);
  570. }
  571. else {
  572. this._delayLoadingFunction(JSON.parse(data), this);
  573. }
  574. this.delayLoadState = Engine.DELAYLOADSTATE_LOADED;
  575. scene._removePendingData(this);
  576. },() => { }, scene.database, getBinaryData);
  577. }
  578. }
  579. public isInFrustum(frustumPlanes: Plane[]): boolean {
  580. if (this.delayLoadState === Engine.DELAYLOADSTATE_LOADING) {
  581. return false;
  582. }
  583. if (!super.isInFrustum(frustumPlanes)) {
  584. return false;
  585. }
  586. this._checkDelayState();
  587. return true;
  588. }
  589. public setMaterialByID(id: string): void {
  590. var materials = this.getScene().materials;
  591. for (var index = 0; index < materials.length; index++) {
  592. if (materials[index].id == id) {
  593. this.material = materials[index];
  594. return;
  595. }
  596. }
  597. // Multi
  598. var multiMaterials = this.getScene().multiMaterials;
  599. for (index = 0; index < multiMaterials.length; index++) {
  600. if (multiMaterials[index].id == id) {
  601. this.material = multiMaterials[index];
  602. return;
  603. }
  604. }
  605. }
  606. public getAnimatables(): IAnimatable[] {
  607. var results = [];
  608. if (this.material) {
  609. results.push(this.material);
  610. }
  611. if (this.skeleton) {
  612. results.push(this.skeleton);
  613. }
  614. return results;
  615. }
  616. // Geometry
  617. public bakeTransformIntoVertices(transform: Matrix): void {
  618. // Position
  619. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)) {
  620. return;
  621. }
  622. this._resetPointsArrayCache();
  623. var data = this.getVerticesData(VertexBuffer.PositionKind);
  624. var temp = [];
  625. for (var index = 0; index < data.length; index += 3) {
  626. Vector3.TransformCoordinates(Vector3.FromArray(data, index), transform).toArray(temp, index);
  627. }
  628. this.setVerticesData(VertexBuffer.PositionKind, temp, this.getVertexBuffer(VertexBuffer.PositionKind).isUpdatable());
  629. // Normals
  630. if (!this.isVerticesDataPresent(VertexBuffer.NormalKind)) {
  631. return;
  632. }
  633. data = this.getVerticesData(VertexBuffer.NormalKind);
  634. for (index = 0; index < data.length; index += 3) {
  635. Vector3.TransformNormal(Vector3.FromArray(data, index), transform).toArray(temp, index);
  636. }
  637. this.setVerticesData(VertexBuffer.NormalKind, temp, this.getVertexBuffer(VertexBuffer.NormalKind).isUpdatable());
  638. }
  639. // Cache
  640. public _resetPointsArrayCache(): void {
  641. this._positions = null;
  642. }
  643. public _generatePointsArray(): boolean {
  644. if (this._positions)
  645. return true;
  646. this._positions = [];
  647. var data = this.getVerticesData(VertexBuffer.PositionKind);
  648. if (!data) {
  649. return false;
  650. }
  651. for (var index = 0; index < data.length; index += 3) {
  652. this._positions.push(Vector3.FromArray(data, index));
  653. }
  654. return true;
  655. }
  656. // Clone
  657. public clone(name: string, newParent?: Node, doNotCloneChildren?: boolean): Mesh {
  658. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  659. }
  660. // Dispose
  661. public dispose(doNotRecurse?: boolean): void {
  662. if (this._geometry) {
  663. this._geometry.releaseForMesh(this, true);
  664. }
  665. // Instances
  666. if (this._worldMatricesInstancesBuffer) {
  667. this.getEngine().deleteInstancesBuffer(this._worldMatricesInstancesBuffer);
  668. this._worldMatricesInstancesBuffer = null;
  669. }
  670. while (this.instances.length) {
  671. this.instances[0].dispose();
  672. }
  673. super.dispose(doNotRecurse);
  674. }
  675. // Geometric tools
  676. public applyDisplacementMap(url: string, minHeight: number, maxHeight: number, onSuccess?: (mesh: Mesh) => void): void {
  677. var scene = this.getScene();
  678. var onload = img => {
  679. // Getting height map data
  680. var canvas = document.createElement("canvas");
  681. var context = canvas.getContext("2d");
  682. var heightMapWidth = img.width;
  683. var heightMapHeight = img.height;
  684. canvas.width = heightMapWidth;
  685. canvas.height = heightMapHeight;
  686. context.drawImage(img, 0, 0);
  687. // Create VertexData from map data
  688. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  689. this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  690. //execute success callback, if set
  691. if (onSuccess) {
  692. onSuccess(this);
  693. }
  694. };
  695. Tools.LoadImage(url, onload,() => { }, scene.database);
  696. }
  697. public applyDisplacementMapFromBuffer(buffer: Uint8Array, heightMapWidth: number, heightMapHeight: number, minHeight: number, maxHeight: number): void {
  698. if (!this.isVerticesDataPresent(VertexBuffer.PositionKind)
  699. || !this.isVerticesDataPresent(VertexBuffer.NormalKind)
  700. || !this.isVerticesDataPresent(VertexBuffer.UVKind)) {
  701. Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  702. return;
  703. }
  704. var positions = this.getVerticesData(VertexBuffer.PositionKind);
  705. var normals = this.getVerticesData(VertexBuffer.NormalKind);
  706. var uvs = this.getVerticesData(VertexBuffer.UVKind);
  707. var position = Vector3.Zero();
  708. var normal = Vector3.Zero();
  709. var uv = Vector2.Zero();
  710. for (var index = 0; index < positions.length; index += 3) {
  711. Vector3.FromArrayToRef(positions, index, position);
  712. Vector3.FromArrayToRef(normals, index, normal);
  713. Vector2.FromArrayToRef(uvs,(index / 3) * 2, uv);
  714. // Compute height
  715. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  716. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  717. var pos = (u + v * heightMapWidth) * 4;
  718. var r = buffer[pos] / 255.0;
  719. var g = buffer[pos + 1] / 255.0;
  720. var b = buffer[pos + 2] / 255.0;
  721. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  722. normal.normalize();
  723. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  724. position = position.add(normal);
  725. position.toArray(positions, index);
  726. }
  727. VertexData.ComputeNormals(positions, this.getIndices(), normals);
  728. this.updateVerticesData(VertexBuffer.PositionKind, positions);
  729. this.updateVerticesData(VertexBuffer.NormalKind, normals);
  730. }
  731. public convertToFlatShadedMesh(): void {
  732. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  733. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  734. var kinds = this.getVerticesDataKinds();
  735. var vbs = [];
  736. var data = [];
  737. var newdata = [];
  738. var updatableNormals = false;
  739. for (var kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  740. var kind = kinds[kindIndex];
  741. var vertexBuffer = this.getVertexBuffer(kind);
  742. if (kind === VertexBuffer.NormalKind) {
  743. updatableNormals = vertexBuffer.isUpdatable();
  744. kinds.splice(kindIndex, 1);
  745. kindIndex--;
  746. continue;
  747. }
  748. vbs[kind] = vertexBuffer;
  749. data[kind] = vbs[kind].getData();
  750. newdata[kind] = [];
  751. }
  752. // Save previous submeshes
  753. var previousSubmeshes = this.subMeshes.slice(0);
  754. var indices = this.getIndices();
  755. var totalIndices = this.getTotalIndices();
  756. // Generating unique vertices per face
  757. for (var index = 0; index < totalIndices; index++) {
  758. var vertexIndex = indices[index];
  759. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  760. kind = kinds[kindIndex];
  761. var stride = vbs[kind].getStrideSize();
  762. for (var offset = 0; offset < stride; offset++) {
  763. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  764. }
  765. }
  766. }
  767. // Updating faces & normal
  768. var normals = [];
  769. var positions = newdata[VertexBuffer.PositionKind];
  770. for (index = 0; index < totalIndices; index += 3) {
  771. indices[index] = index;
  772. indices[index + 1] = index + 1;
  773. indices[index + 2] = index + 2;
  774. var p1 = Vector3.FromArray(positions, index * 3);
  775. var p2 = Vector3.FromArray(positions,(index + 1) * 3);
  776. var p3 = Vector3.FromArray(positions,(index + 2) * 3);
  777. var p1p2 = p1.subtract(p2);
  778. var p3p2 = p3.subtract(p2);
  779. var normal = Vector3.Normalize(Vector3.Cross(p1p2, p3p2));
  780. // Store same normals for every vertex
  781. for (var localIndex = 0; localIndex < 3; localIndex++) {
  782. normals.push(normal.x);
  783. normals.push(normal.y);
  784. normals.push(normal.z);
  785. }
  786. }
  787. this.setIndices(indices);
  788. this.setVerticesData(VertexBuffer.NormalKind, normals, updatableNormals);
  789. // Updating vertex buffers
  790. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  791. kind = kinds[kindIndex];
  792. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  793. }
  794. // Updating submeshes
  795. this.releaseSubMeshes();
  796. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  797. var previousOne = previousSubmeshes[submeshIndex];
  798. var subMesh = new SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  799. }
  800. this.synchronizeInstances();
  801. }
  802. // Instances
  803. public createInstance(name: string): InstancedMesh {
  804. return new InstancedMesh(name, this);
  805. }
  806. public synchronizeInstances(): void {
  807. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  808. var instance = this.instances[instanceIndex];
  809. instance._syncSubMeshes();
  810. }
  811. }
  812. /**
  813. * Simplify the mesh according to the given array of settings.
  814. * Function will return immediately and will simplify async.
  815. * @param settings a collection of simplification settings.
  816. * @param parallelProcessing should all levels calculate parallel or one after the other.
  817. * @param type the type of simplification to run.
  818. * successCallback optional success callback to be called after the simplification finished processing all settings.
  819. */
  820. public simplify(settings: Array<ISimplificationSettings>, parallelProcessing: boolean = true, type: SimplificationType = SimplificationType.QUADRATIC, successCallback?: () => void) {
  821. var getSimplifier = (): ISimplifier => {
  822. switch (type) {
  823. case SimplificationType.QUADRATIC:
  824. default:
  825. return new QuadraticErrorSimplification(this);
  826. }
  827. }
  828. if (parallelProcessing) {
  829. //parallel simplifier
  830. settings.forEach((setting) => {
  831. var simplifier = getSimplifier();
  832. simplifier.simplify(setting,(newMesh) => {
  833. this.addLODLevel(setting.distance, newMesh);
  834. //check if it is the last
  835. if (setting.quality == settings[settings.length - 1].quality && successCallback) {
  836. //all done, run the success callback.
  837. successCallback();
  838. }
  839. });
  840. });
  841. } else {
  842. //single simplifier.
  843. var simplifier = getSimplifier();
  844. var runDecimation = (setting: ISimplificationSettings, callback: () => void) => {
  845. simplifier.simplify(setting,(newMesh) => {
  846. this.addLODLevel(setting.distance, newMesh);
  847. //run the next quality level
  848. callback();
  849. });
  850. }
  851. AsyncLoop.Run(settings.length,(loop: AsyncLoop) => {
  852. runDecimation(settings[loop.index],() => {
  853. loop.executeNext();
  854. });
  855. },() => {
  856. //execution ended, run the success callback.
  857. if (successCallback) {
  858. successCallback();
  859. }
  860. });
  861. }
  862. }
  863. // Statics
  864. public static CreateBox(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
  865. var box = new Mesh(name, scene);
  866. var vertexData = VertexData.CreateBox(size);
  867. vertexData.applyToMesh(box, updatable);
  868. return box;
  869. }
  870. public static CreateSphere(name: string, segments: number, diameter: number, scene: Scene, updatable?: boolean): Mesh {
  871. var sphere = new Mesh(name, scene);
  872. var vertexData = VertexData.CreateSphere(segments, diameter);
  873. vertexData.applyToMesh(sphere, updatable);
  874. return sphere;
  875. }
  876. // Cylinder and cone (Code inspired by SharpDX.org)
  877. public static CreateCylinder(name: string, height: number, diameterTop: number, diameterBottom: number, tessellation: number, subdivisions: any, scene: Scene, updatable?: any): Mesh {
  878. // subdivisions is a new parameter, we need to support old signature
  879. if (scene === undefined || !(scene instanceof Scene)) {
  880. if (scene !== undefined) {
  881. updatable = scene;
  882. }
  883. scene = <Scene>subdivisions;
  884. subdivisions = 1;
  885. }
  886. var cylinder = new Mesh(name, scene);
  887. var vertexData = VertexData.CreateCylinder(height, diameterTop, diameterBottom, tessellation, subdivisions);
  888. vertexData.applyToMesh(cylinder, updatable);
  889. return cylinder;
  890. }
  891. // Torus (Code from SharpDX.org)
  892. public static CreateTorus(name: string, diameter: number, thickness: number, tessellation: number, scene: Scene, updatable?: boolean): Mesh {
  893. var torus = new Mesh(name, scene);
  894. var vertexData = VertexData.CreateTorus(diameter, thickness, tessellation);
  895. vertexData.applyToMesh(torus, updatable);
  896. return torus;
  897. }
  898. public static CreateTorusKnot(name: string, radius: number, tube: number, radialSegments: number, tubularSegments: number, p: number, q: number, scene: Scene, updatable?: boolean): Mesh {
  899. var torusKnot = new Mesh(name, scene);
  900. var vertexData = VertexData.CreateTorusKnot(radius, tube, radialSegments, tubularSegments, p, q);
  901. vertexData.applyToMesh(torusKnot, updatable);
  902. return torusKnot;
  903. }
  904. // Lines
  905. public static CreateLines(name: string, points: Vector3[], scene: Scene, updatable?: boolean): LinesMesh {
  906. var lines = new LinesMesh(name, scene, updatable);
  907. var vertexData = VertexData.CreateLines(points);
  908. vertexData.applyToMesh(lines, updatable);
  909. return lines;
  910. }
  911. // Plane & ground
  912. public static CreatePlane(name: string, size: number, scene: Scene, updatable?: boolean): Mesh {
  913. var plane = new Mesh(name, scene);
  914. var vertexData = VertexData.CreatePlane(size);
  915. vertexData.applyToMesh(plane, updatable);
  916. return plane;
  917. }
  918. public static CreateGround(name: string, width: number, height: number, subdivisions: number, scene: Scene, updatable?: boolean): Mesh {
  919. var ground = new GroundMesh(name, scene);
  920. ground._setReady(false);
  921. ground._subdivisions = subdivisions;
  922. var vertexData = VertexData.CreateGround(width, height, subdivisions);
  923. vertexData.applyToMesh(ground, updatable);
  924. ground._setReady(true);
  925. return ground;
  926. }
  927. public static CreateTiledGround(name: string, xmin: number, zmin: number, xmax: number, zmax: number, subdivisions: { w: number; h: number; }, precision: { w: number; h: number; }, scene: Scene, updatable?: boolean): Mesh {
  928. var tiledGround = new Mesh(name, scene);
  929. var vertexData = VertexData.CreateTiledGround(xmin, zmin, xmax, zmax, subdivisions, precision);
  930. vertexData.applyToMesh(tiledGround, updatable);
  931. return tiledGround;
  932. }
  933. public static CreateGroundFromHeightMap(name: string, url: string, width: number, height: number, subdivisions: number, minHeight: number, maxHeight: number, scene: Scene, updatable?: boolean, onReady?:(mesh: GroundMesh) => void): GroundMesh {
  934. var ground = new GroundMesh(name, scene);
  935. ground._subdivisions = subdivisions;
  936. ground._setReady(false);
  937. var onload = img => {
  938. // Getting height map data
  939. var canvas = document.createElement("canvas");
  940. var context = canvas.getContext("2d");
  941. var heightMapWidth = img.width;
  942. var heightMapHeight = img.height;
  943. canvas.width = heightMapWidth;
  944. canvas.height = heightMapHeight;
  945. context.drawImage(img, 0, 0);
  946. // Create VertexData from map data
  947. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  948. var vertexData = VertexData.CreateGroundFromHeightMap(width, height, subdivisions, minHeight, maxHeight, buffer, heightMapWidth, heightMapHeight);
  949. vertexData.applyToMesh(ground, updatable);
  950. ground._setReady(true);
  951. //execute ready callback, if set
  952. if (onReady) {
  953. onReady(ground);
  954. }
  955. };
  956. Tools.LoadImage(url, onload,() => { }, scene.database);
  957. return ground;
  958. }
  959. // Tools
  960. public static MinMax(meshes: AbstractMesh[]): { min: Vector3; max: Vector3 } {
  961. var minVector = null;
  962. var maxVector = null;
  963. for (var i in meshes) {
  964. var mesh = meshes[i];
  965. var boundingBox = mesh.getBoundingInfo().boundingBox;
  966. if (!minVector) {
  967. minVector = boundingBox.minimumWorld;
  968. maxVector = boundingBox.maximumWorld;
  969. continue;
  970. }
  971. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  972. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  973. }
  974. return {
  975. min: minVector,
  976. max: maxVector
  977. };
  978. }
  979. public static Center(meshesOrMinMaxVector): Vector3 {
  980. var minMaxVector = meshesOrMinMaxVector.min !== undefined ? meshesOrMinMaxVector : Mesh.MinMax(meshesOrMinMaxVector);
  981. return Vector3.Center(minMaxVector.min, minMaxVector.max);
  982. }
  983. public static MergeMeshes(meshes: Array<Mesh>, disposeSource = true, allow32BitsIndices?: boolean): Mesh {
  984. var source = meshes[0];
  985. var material = source.material;
  986. var scene = source.getScene();
  987. if (!allow32BitsIndices) {
  988. var totalVertices = 0;
  989. // Counting vertices
  990. for (var index = 0; index < meshes.length; index++) {
  991. totalVertices += meshes[index].getTotalVertices();
  992. if (totalVertices > 65536) {
  993. Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  994. return null;
  995. }
  996. }
  997. }
  998. // Merge
  999. var vertexData = VertexData.ExtractFromMesh(source);
  1000. vertexData.transform(source.getWorldMatrix());
  1001. for (index = 1; index < meshes.length; index++) {
  1002. var otherVertexData = VertexData.ExtractFromMesh(meshes[index]);
  1003. otherVertexData.transform(meshes[index].getWorldMatrix());
  1004. vertexData.merge(otherVertexData);
  1005. }
  1006. var newMesh = new Mesh(source.name + "_merged", scene);
  1007. vertexData.applyToMesh(newMesh);
  1008. // Setting properties
  1009. newMesh.material = material;
  1010. newMesh.checkCollisions = source.checkCollisions;
  1011. // Cleaning
  1012. if (disposeSource) {
  1013. for (index = 0; index < meshes.length; index++) {
  1014. meshes[index].dispose();
  1015. }
  1016. }
  1017. return newMesh;
  1018. }
  1019. }
  1020. }